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
backend/abcd.py
rohitner/SCT2018
1
6622351
<gh_stars>1-10 import matplotlib as mpl; import matplotlib.pyplot as plt; import numpy as np; from pandas import read_csv; import gzip; import StringIO; import sys; def parse_header_of_csv(csv_str): # Isolate the headline columns: headline = csv_str[:csv_str.index('\n')]; columns = headline.split(','); # The first column should be timestamp: assert columns[0] == 'timestamp'; # The last column should be label_source: assert columns[-1] == 'label_source'; # Search for the column of the first label: for (ci,col) in enumerate(columns): if col.startswith('label:'): first_label_ind = ci; break; pass; # Feature columns come after timestamp and before the labels: feature_names = columns[1:first_label_ind]; # Then come the labels, till the one-before-last column: label_names = columns[first_label_ind:-1]; for (li,label) in enumerate(label_names): # In the CSV the label names appear with prefix 'label:', but we don't need it after reading the data: assert label.startswith('label:'); label_names[li] = label.replace('label:',''); pass; return (feature_names,label_names); def parse_body_of_csv(csv_str,n_features): # Read the entire CSV body into a single numeric matrix: full_table = np.loadtxt(StringIO.StringIO(csv_str),delimiter=',',skiprows=1); # Timestamp is the primary key for the records (examples): timestamps = full_table[:,0].astype(int); # Read the sensor features: X = full_table[:,1:(n_features+1)]; # Read the binary label values, and the 'missing label' indicators: trinary_labels_mat = full_table[:,(n_features+1):-1]; # This should have values of either 0., 1. or NaN #print trinary_labels_mat, "labels" M = np.isnan(trinary_labels_mat); # M is the missing label matrix #print M, 'm' Y = np.where(M,0,trinary_labels_mat) ; # Y is the label matrix #print Y, 'Y' return (X,Y,M,timestamps); ''' Read the data (precomputed sensor-features and labels) for a user. This function assumes the user's data file is present. ''' def read_user_data(uuid): user_data_file = 'data/%s.features_labels.csv.gz' % uuid; # Read the entire csv file of the user: with gzip.open(user_data_file,'rb') as fid: csv_str = fid.read(); pass; (feature_names,label_names) = parse_header_of_csv(csv_str); n_features = len(feature_names); (X,Y,M,timestamps) = parse_body_of_csv(csv_str,n_features); return (X,Y,M,timestamps,feature_names,label_names); def figure__pie_chart(Y,label_names,labels_to_display,title_str,ax): portion_of_time = np.mean(Y,axis=0); portions_to_display = [portion_of_time[label_names.index(label)] for label in labels_to_display]; pretty_labels_to_display = [get_label_pretty_name(label) for label in labels_to_display]; ax.pie(portions_to_display,labels=pretty_labels_to_display,autopct='%.2f%%'); ax.axis('equal'); plt.title(title_str); return; def get_label_pretty_name(label): if label == 'FIX_walking': return 'Walking'; if label == 'FIX_running': return 'Running'; if label == 'LOC_main_workplace': return 'At main workplace'; if label == 'OR_indoors': return 'Indoors'; if label == 'OR_outside': return 'Outside'; if label == 'LOC_home': return 'At home'; if label == 'FIX_restaurant': return 'At a restaurant'; if label == 'OR_exercise': return 'OR_exerciseise'; if label == 'LOC_beach': return 'At the beach'; if label == 'OR_standing': return 'Standing'; if label == 'WATCHING_TV': return 'Watching TV' if label.endswith('_'): label = label[:-1] + ')'; pass; label = label.replace('__',' (').replace('_',' '); label = label[0] + label[1:].lower(); label = label.replace('i m','I\'m'); return label;
import matplotlib as mpl; import matplotlib.pyplot as plt; import numpy as np; from pandas import read_csv; import gzip; import StringIO; import sys; def parse_header_of_csv(csv_str): # Isolate the headline columns: headline = csv_str[:csv_str.index('\n')]; columns = headline.split(','); # The first column should be timestamp: assert columns[0] == 'timestamp'; # The last column should be label_source: assert columns[-1] == 'label_source'; # Search for the column of the first label: for (ci,col) in enumerate(columns): if col.startswith('label:'): first_label_ind = ci; break; pass; # Feature columns come after timestamp and before the labels: feature_names = columns[1:first_label_ind]; # Then come the labels, till the one-before-last column: label_names = columns[first_label_ind:-1]; for (li,label) in enumerate(label_names): # In the CSV the label names appear with prefix 'label:', but we don't need it after reading the data: assert label.startswith('label:'); label_names[li] = label.replace('label:',''); pass; return (feature_names,label_names); def parse_body_of_csv(csv_str,n_features): # Read the entire CSV body into a single numeric matrix: full_table = np.loadtxt(StringIO.StringIO(csv_str),delimiter=',',skiprows=1); # Timestamp is the primary key for the records (examples): timestamps = full_table[:,0].astype(int); # Read the sensor features: X = full_table[:,1:(n_features+1)]; # Read the binary label values, and the 'missing label' indicators: trinary_labels_mat = full_table[:,(n_features+1):-1]; # This should have values of either 0., 1. or NaN #print trinary_labels_mat, "labels" M = np.isnan(trinary_labels_mat); # M is the missing label matrix #print M, 'm' Y = np.where(M,0,trinary_labels_mat) ; # Y is the label matrix #print Y, 'Y' return (X,Y,M,timestamps); ''' Read the data (precomputed sensor-features and labels) for a user. This function assumes the user's data file is present. ''' def read_user_data(uuid): user_data_file = 'data/%s.features_labels.csv.gz' % uuid; # Read the entire csv file of the user: with gzip.open(user_data_file,'rb') as fid: csv_str = fid.read(); pass; (feature_names,label_names) = parse_header_of_csv(csv_str); n_features = len(feature_names); (X,Y,M,timestamps) = parse_body_of_csv(csv_str,n_features); return (X,Y,M,timestamps,feature_names,label_names); def figure__pie_chart(Y,label_names,labels_to_display,title_str,ax): portion_of_time = np.mean(Y,axis=0); portions_to_display = [portion_of_time[label_names.index(label)] for label in labels_to_display]; pretty_labels_to_display = [get_label_pretty_name(label) for label in labels_to_display]; ax.pie(portions_to_display,labels=pretty_labels_to_display,autopct='%.2f%%'); ax.axis('equal'); plt.title(title_str); return; def get_label_pretty_name(label): if label == 'FIX_walking': return 'Walking'; if label == 'FIX_running': return 'Running'; if label == 'LOC_main_workplace': return 'At main workplace'; if label == 'OR_indoors': return 'Indoors'; if label == 'OR_outside': return 'Outside'; if label == 'LOC_home': return 'At home'; if label == 'FIX_restaurant': return 'At a restaurant'; if label == 'OR_exercise': return 'OR_exerciseise'; if label == 'LOC_beach': return 'At the beach'; if label == 'OR_standing': return 'Standing'; if label == 'WATCHING_TV': return 'Watching TV' if label.endswith('_'): label = label[:-1] + ')'; pass; label = label.replace('__',' (').replace('_',' '); label = label[0] + label[1:].lower(); label = label.replace('i m','I\'m'); return label;
en
0.770948
# Isolate the headline columns: # The first column should be timestamp: # The last column should be label_source: # Search for the column of the first label: # Feature columns come after timestamp and before the labels: # Then come the labels, till the one-before-last column: # In the CSV the label names appear with prefix 'label:', but we don't need it after reading the data: # Read the entire CSV body into a single numeric matrix: # Timestamp is the primary key for the records (examples): # Read the sensor features: # Read the binary label values, and the 'missing label' indicators: # This should have values of either 0., 1. or NaN #print trinary_labels_mat, "labels" # M is the missing label matrix #print M, 'm' # Y is the label matrix #print Y, 'Y' Read the data (precomputed sensor-features and labels) for a user. This function assumes the user's data file is present. # Read the entire csv file of the user:
3.136169
3
label_studio/tests/data_manager_test.py
mengzaiqiao/label-studio
2
6622352
import pytest # label_studio from label_studio import blueprint as server from label_studio.tests.base import goc_project @pytest.fixture(autouse=True) def default_project(monkeypatch): """ apply patch for label_studio.server.project_get_or_create() for all tests. """ monkeypatch.setattr(server, 'project_get_or_create', goc_project) def project_init_source(): project = goc_project() ids = range(0, 16) values = [{'data': {'image': '123', 'text': '123' + str(i)}, 'id': i} for i in range(0, 16)] project.source_storage.remove_all() project.source_storage.set_many(ids, values) return project def project_init_target(): project = goc_project() ids = range(0, 16) project.target_storage.remove_all() for i in ids: value = { 'id': i, 'data': {'image': '123', 'text': '123'}, 'completions': [{'id': 1001 + i}] } project.target_storage.set(i, value) return project class TestColumns: """ Table Columns """ def test_import_page(self, test_client, captured_templates): response = test_client.get('/api/project/columns') assert response.status_code == 200 class TestTabs: """ Table Tabs """ def test_tabs(self, test_client, captured_templates): response = test_client.get('/api/project/tabs') assert response.status_code == 200 def test_selected_items(self, test_client, captured_templates): project_init_source() # post response = test_client.post('/api/project/tabs/1/selected-items', json={"all": False, "included": [1, 2, 3]}) assert response.status_code == 201 # get response = test_client.get('/api/project/tabs/1/selected-items') assert response.status_code == 200 assert response.json == {'all': False, 'included': [1, 2, 3]} # patch response = test_client.patch('/api/project/tabs/1/selected-items', json={"all": False, "included": [4, 5]}) assert response.status_code == 201 response = test_client.get('/api/project/tabs/1/selected-items') assert response.status_code == 200 assert response.json == {'all': False, 'included': [1, 2, 3, 4, 5]} # delete response = test_client.delete('/api/project/tabs/1/selected-items', json={"all": False, "included": [3]}) assert response.status_code == 204 response = test_client.get('/api/project/tabs/1/selected-items') assert response.status_code == 200 assert response.json == {'all': False, 'included': [1, 2, 4, 5]} # check TAB has selectedItems response = test_client.get('/api/project/tabs/1/') assert response.status_code == 200 assert response.json['selectedItems'] == {'all': False, 'included': [1, 2, 4, 5]} # select all response = test_client.post('/api/project/tabs/1/selected-items', json={'all': True, 'excluded': []}) assert response.status_code == 201 response = test_client.get('/api/project/tabs/1/selected-items') assert response.status_code == 200 assert response.json == {'all': True, 'excluded': []} # delete all response = test_client.delete('/api/project/tabs/1/selected-items', json={'all': True, 'excluded': []}) assert response.status_code == 204 response = test_client.get('/api/project/tabs/1/selected-items') assert response.status_code == 200 assert response.json == {'all': True, 'excluded': []} def test_selected_items_excluded(self, test_client, captured_templates): project_init_source() # post response = test_client.post('/api/project/tabs/1/selected-items', json={"all": True, "excluded": [1, 2, 3]}) assert response.status_code == 201 # get response = test_client.get('/api/project/tabs/1/selected-items') assert response.status_code == 200 assert response.json == {'all': True, 'excluded': [1, 2, 3]} # patch response = test_client.patch('/api/project/tabs/1/selected-items', json={"all": True, "excluded": [1, 2]}) assert response.status_code == 201 response = test_client.get('/api/project/tabs/1/selected-items') assert response.status_code == 200 assert response.json == {'all': True, 'excluded': [1, 2, 3]} # delete response = test_client.delete('/api/project/tabs/1/selected-items', json={"all": True, "excluded": [4, 5]}) assert response.status_code == 204 response = test_client.get('/api/project/tabs/1/selected-items') assert response.status_code == 200 assert response.json == {'all': True, 'excluded': [1, 2, 3]} class TestActions: def test_get_actions(self, test_client, captured_templates): # GET: check action list response = test_client.get('/api/project/actions') assert response.status_code == 200 assert response.json == [ { "dialog": { "text": "You are going to delete selected tasks. Please, confirm your action.", "type": "confirm" }, "id": "delete_tasks", "order": 100, "permissions": "project.can_delete_tasks", "title": "Delete tasks" }, { "dialog": { "text": "You are going to delete all completions from selected tasks. Please, confirm your action.", "type": "confirm" }, "id": "delete_tasks_completions", "order": 101, "permissions": "project.can_manage_completions", "title": "Delete completions" } ] @staticmethod def action_tasks_delete(test_client, captured_templates, key): """ Remove tasks by ids """ project = project_init_source() # POST: delete 3 tasks before_task_ids = set(project.source_storage.ids()) data = {'all': key == 'excluded', key: [4, 5, 6]} response = test_client.post('/api/project/tabs/1/selected-items', json=data) assert response.status_code == 201 response = test_client.post('/api/project/tabs/1/actions?id=delete_tasks') assert response.status_code == 200 after_task_ids = set(project.source_storage.ids()) return before_task_ids, after_task_ids, set(data[key]) def test_action_tasks_delete_included(self, test_client, captured_templates): before, after, result = self.action_tasks_delete(test_client, captured_templates, 'included') assert before - result == after, 'Tasks after deletion are incorrect' def test_action_tasks_delete_excluded(self, test_client, captured_templates): before, after, result = self.action_tasks_delete(test_client, captured_templates, 'excluded') assert result == after, 'Tasks after deletion are incorrect' def test_action_tasks_completions_delete(self, test_client, captured_templates): """ Remove all completions for task ids """ project = project_init_target() """# POST: delete 3 tasks before_ids = set(project.target_storage.ids()) items = [4, 5, 6] response = test_client.post('/api/project/tabs/1/selected-items', json=items) assert response.status_code == 201 response = test_client.post('/api/project/tabs/1/actions?id=delete_tasks_completions') assert response.status_code == 200 after_ids = set(project.source_storage.ids()) assert before_ids - set(items) == after_ids, 'Completions after deletion are incorrect'""" class TestTasksAndAnnotations: """ Test tasks on tabs """ def test_tasks(self, test_client, captured_templates): project = project_init_source() project.target_storage.remove_all() data = { 'filters': { 'conjunction': 'and', 'items': [{ 'filter': 'filters:tasks:id', 'operator': 'in', 'value': {'min': 2, 'max': 5}, 'type': 'Number' }, { 'filter': 'filters:tasks:data.text', 'operator': 'contains', 'value': '123', 'type': 'String' }] } } response = test_client.get('/api/tasks', json=data) assert response.status_code == 200 assert response.json == { 'tasks': [{'cancelled_completions': 0, 'completed_at': None, 'completions_results': '', 'data': {'image': '123', 'text': '1232'}, 'id': 2, 'total_completions': 0, 'total_predictions': 0, 'predictions_results': ''}, {'cancelled_completions': 0, 'completed_at': None, 'completions_results': '', 'data': {'image': '123', 'text': '1233'}, 'id': 3, 'total_completions': 0, 'total_predictions': 0, 'predictions_results': ''}, {'cancelled_completions': 0, 'completed_at': None, 'completions_results': '', 'data': {'image': '123', 'text': '1234'}, 'id': 4, 'total_completions': 0, 'total_predictions': 0, 'predictions_results': ''}, {'cancelled_completions': 0, 'completed_at': None, 'completions_results': '', 'data': {'image': '123', 'text': '1235'}, 'id': 5, 'total_completions': 0, 'total_predictions': 0, 'predictions_results': ''}], 'total': 4, 'total_completions': 0, 'total_predictions': 0} def test_annotations(self, test_client, captured_templates): response = test_client.get('/api/project/tabs/1/annotations') assert response.status_code == 200
import pytest # label_studio from label_studio import blueprint as server from label_studio.tests.base import goc_project @pytest.fixture(autouse=True) def default_project(monkeypatch): """ apply patch for label_studio.server.project_get_or_create() for all tests. """ monkeypatch.setattr(server, 'project_get_or_create', goc_project) def project_init_source(): project = goc_project() ids = range(0, 16) values = [{'data': {'image': '123', 'text': '123' + str(i)}, 'id': i} for i in range(0, 16)] project.source_storage.remove_all() project.source_storage.set_many(ids, values) return project def project_init_target(): project = goc_project() ids = range(0, 16) project.target_storage.remove_all() for i in ids: value = { 'id': i, 'data': {'image': '123', 'text': '123'}, 'completions': [{'id': 1001 + i}] } project.target_storage.set(i, value) return project class TestColumns: """ Table Columns """ def test_import_page(self, test_client, captured_templates): response = test_client.get('/api/project/columns') assert response.status_code == 200 class TestTabs: """ Table Tabs """ def test_tabs(self, test_client, captured_templates): response = test_client.get('/api/project/tabs') assert response.status_code == 200 def test_selected_items(self, test_client, captured_templates): project_init_source() # post response = test_client.post('/api/project/tabs/1/selected-items', json={"all": False, "included": [1, 2, 3]}) assert response.status_code == 201 # get response = test_client.get('/api/project/tabs/1/selected-items') assert response.status_code == 200 assert response.json == {'all': False, 'included': [1, 2, 3]} # patch response = test_client.patch('/api/project/tabs/1/selected-items', json={"all": False, "included": [4, 5]}) assert response.status_code == 201 response = test_client.get('/api/project/tabs/1/selected-items') assert response.status_code == 200 assert response.json == {'all': False, 'included': [1, 2, 3, 4, 5]} # delete response = test_client.delete('/api/project/tabs/1/selected-items', json={"all": False, "included": [3]}) assert response.status_code == 204 response = test_client.get('/api/project/tabs/1/selected-items') assert response.status_code == 200 assert response.json == {'all': False, 'included': [1, 2, 4, 5]} # check TAB has selectedItems response = test_client.get('/api/project/tabs/1/') assert response.status_code == 200 assert response.json['selectedItems'] == {'all': False, 'included': [1, 2, 4, 5]} # select all response = test_client.post('/api/project/tabs/1/selected-items', json={'all': True, 'excluded': []}) assert response.status_code == 201 response = test_client.get('/api/project/tabs/1/selected-items') assert response.status_code == 200 assert response.json == {'all': True, 'excluded': []} # delete all response = test_client.delete('/api/project/tabs/1/selected-items', json={'all': True, 'excluded': []}) assert response.status_code == 204 response = test_client.get('/api/project/tabs/1/selected-items') assert response.status_code == 200 assert response.json == {'all': True, 'excluded': []} def test_selected_items_excluded(self, test_client, captured_templates): project_init_source() # post response = test_client.post('/api/project/tabs/1/selected-items', json={"all": True, "excluded": [1, 2, 3]}) assert response.status_code == 201 # get response = test_client.get('/api/project/tabs/1/selected-items') assert response.status_code == 200 assert response.json == {'all': True, 'excluded': [1, 2, 3]} # patch response = test_client.patch('/api/project/tabs/1/selected-items', json={"all": True, "excluded": [1, 2]}) assert response.status_code == 201 response = test_client.get('/api/project/tabs/1/selected-items') assert response.status_code == 200 assert response.json == {'all': True, 'excluded': [1, 2, 3]} # delete response = test_client.delete('/api/project/tabs/1/selected-items', json={"all": True, "excluded": [4, 5]}) assert response.status_code == 204 response = test_client.get('/api/project/tabs/1/selected-items') assert response.status_code == 200 assert response.json == {'all': True, 'excluded': [1, 2, 3]} class TestActions: def test_get_actions(self, test_client, captured_templates): # GET: check action list response = test_client.get('/api/project/actions') assert response.status_code == 200 assert response.json == [ { "dialog": { "text": "You are going to delete selected tasks. Please, confirm your action.", "type": "confirm" }, "id": "delete_tasks", "order": 100, "permissions": "project.can_delete_tasks", "title": "Delete tasks" }, { "dialog": { "text": "You are going to delete all completions from selected tasks. Please, confirm your action.", "type": "confirm" }, "id": "delete_tasks_completions", "order": 101, "permissions": "project.can_manage_completions", "title": "Delete completions" } ] @staticmethod def action_tasks_delete(test_client, captured_templates, key): """ Remove tasks by ids """ project = project_init_source() # POST: delete 3 tasks before_task_ids = set(project.source_storage.ids()) data = {'all': key == 'excluded', key: [4, 5, 6]} response = test_client.post('/api/project/tabs/1/selected-items', json=data) assert response.status_code == 201 response = test_client.post('/api/project/tabs/1/actions?id=delete_tasks') assert response.status_code == 200 after_task_ids = set(project.source_storage.ids()) return before_task_ids, after_task_ids, set(data[key]) def test_action_tasks_delete_included(self, test_client, captured_templates): before, after, result = self.action_tasks_delete(test_client, captured_templates, 'included') assert before - result == after, 'Tasks after deletion are incorrect' def test_action_tasks_delete_excluded(self, test_client, captured_templates): before, after, result = self.action_tasks_delete(test_client, captured_templates, 'excluded') assert result == after, 'Tasks after deletion are incorrect' def test_action_tasks_completions_delete(self, test_client, captured_templates): """ Remove all completions for task ids """ project = project_init_target() """# POST: delete 3 tasks before_ids = set(project.target_storage.ids()) items = [4, 5, 6] response = test_client.post('/api/project/tabs/1/selected-items', json=items) assert response.status_code == 201 response = test_client.post('/api/project/tabs/1/actions?id=delete_tasks_completions') assert response.status_code == 200 after_ids = set(project.source_storage.ids()) assert before_ids - set(items) == after_ids, 'Completions after deletion are incorrect'""" class TestTasksAndAnnotations: """ Test tasks on tabs """ def test_tasks(self, test_client, captured_templates): project = project_init_source() project.target_storage.remove_all() data = { 'filters': { 'conjunction': 'and', 'items': [{ 'filter': 'filters:tasks:id', 'operator': 'in', 'value': {'min': 2, 'max': 5}, 'type': 'Number' }, { 'filter': 'filters:tasks:data.text', 'operator': 'contains', 'value': '123', 'type': 'String' }] } } response = test_client.get('/api/tasks', json=data) assert response.status_code == 200 assert response.json == { 'tasks': [{'cancelled_completions': 0, 'completed_at': None, 'completions_results': '', 'data': {'image': '123', 'text': '1232'}, 'id': 2, 'total_completions': 0, 'total_predictions': 0, 'predictions_results': ''}, {'cancelled_completions': 0, 'completed_at': None, 'completions_results': '', 'data': {'image': '123', 'text': '1233'}, 'id': 3, 'total_completions': 0, 'total_predictions': 0, 'predictions_results': ''}, {'cancelled_completions': 0, 'completed_at': None, 'completions_results': '', 'data': {'image': '123', 'text': '1234'}, 'id': 4, 'total_completions': 0, 'total_predictions': 0, 'predictions_results': ''}, {'cancelled_completions': 0, 'completed_at': None, 'completions_results': '', 'data': {'image': '123', 'text': '1235'}, 'id': 5, 'total_completions': 0, 'total_predictions': 0, 'predictions_results': ''}], 'total': 4, 'total_completions': 0, 'total_predictions': 0} def test_annotations(self, test_client, captured_templates): response = test_client.get('/api/project/tabs/1/annotations') assert response.status_code == 200
en
0.739474
# label_studio apply patch for label_studio.server.project_get_or_create() for all tests. Table Columns Table Tabs # post # get # patch # delete # check TAB has selectedItems # select all # delete all # post # get # patch # delete # GET: check action list Remove tasks by ids # POST: delete 3 tasks Remove all completions for task ids # POST: delete 3 tasks before_ids = set(project.target_storage.ids()) items = [4, 5, 6] response = test_client.post('/api/project/tabs/1/selected-items', json=items) assert response.status_code == 201 response = test_client.post('/api/project/tabs/1/actions?id=delete_tasks_completions') assert response.status_code == 200 after_ids = set(project.source_storage.ids()) assert before_ids - set(items) == after_ids, 'Completions after deletion are incorrect' Test tasks on tabs
2.053941
2
sei_py/base/exception.py
xh4zr/sei_py
1
6622353
<gh_stars>1-10 class SeiException(Exception): def __init__(self, message, errors): super(SeiException, self).__init__(message) self.errors = errors
class SeiException(Exception): def __init__(self, message, errors): super(SeiException, self).__init__(message) self.errors = errors
none
1
2.314523
2
game_pkg/stories.py
DejunJackson/Madlibs
0
6622354
<gh_stars>0 """This Module holds all the possible stories and queries to collect those stories""" import random def story_one(words): if words == {}: body_part = input("Name a body part. \n") adjective = input("Name an adjective. \n") place = input("Name a city. \n") adjective2 = input("Name another adjective. \n") place2 = input("Name a state. \n") female_celebrity = input("Name a female celebrity \n") body_part3 = input("Name another body part. \n") male_celebrity = input("Name a male celebrity. \n") body_part2 = input("Name another body part. \n") adjective3 = input("Name another adjective. \n") body_part4 = input("Name another body part. \n") organ = input("Name an organ. \n") words.update(adjective=adjective, adjective2=adjective2, adjective3=adjective3, place=place, place2=place2, female_celebrity=female_celebrity, male_celebrity=male_celebrity, body_part=body_part, body_part2=body_part2, body_part3=body_part3, body_part4=body_part4, organ=organ) return words else: return (f"\nOnce upon a time, at a place called {words['place']}, there was " + f"a {words['adjective']} princess named {words['female_celebrity']}.\nHer kingdom " + f"was huge, but her {words['body_part']} was bigger.\nShe was beautiful " + f"from her {words['body_part2']} to her {words['organ']}.\nOne day she saw a {words['adjective2']} " + f"prince named {words['male_celebrity']}.\nHe had a {words['adjective3']} face. As soon as " + f"his {words['body_part3']} touched her {words['body_part4']} they fell in love.\nThey " + f"got married in {words['place2']} the following day.\n") def story_two(words): if words == {}: adjective = input("Name an adjective. \n") plural_noun = input("Name a plural noun. \n") ing_verb = input("Name a verb ending in -ing. \n") plural_noun2 = input("Name a plural noun. \n") female_celebrity_name = input("Name a female celebrity. \n") person = input("Name a person in the game. \n") silly_word = input("Name a silly word. \n") verb = input("Name a verb. \n") food = input("Name a the plural word of a food. \n") noun = input("Name a noun. \n") adjective2 = input("Name an adjective. \n") adjective3 = input("Name an adjective. \n") shoe = input("Name a type of shoe. \n") something_alive = input("Name something alive. \n") noun2 = input("Name a noun. \n") ing_verb2 = input("Name a verb ending in -ing. \n") noun3 = input("Name a noun. \n") silly_word2 = input("Name a silly word. \n") words.update(adjective=adjective, plural_noun=plural_noun, ing_verb=ing_verb, plural_noun2=plural_noun2, female_celebrity_name=female_celebrity_name, person=person, silly_word=silly_word, verb=verb, food=food, noun=noun, adjective2=adjective2, adjective3=adjective3, shoe=shoe, something_alive=something_alive, noun2=noun2, ing_verb2=ing_verb2, noun3=noun3, silly_word2=silly_word2) return words else: return (f"\nOne of the most {words['adjective']} things about graduating is that my " + f"{words['plural_noun']} are {words['ing_verb']} a huge party.\nI decided to have a backyard " + f"barbeque for all of my family and {words['plural_noun2']}.\nI've invited my best friends {words['female_celebrity_name']}, {words['person']}, " + f"and of course my teacher, Ms. {words['silly_word']}.\nMy dad is going to {words['verb']} hamburgers and {words['food']} on his shiny new {words['noun']}.\n" + f"He always thinks his {words['food']} tastes really {words['adjective2']}, but I think they taste like {words['adjective3']} {words['shoe']}.\n" + f"My mom is going to make her famous {words['something_alive']} salad, which is my favorite {words['noun2']}.\nMom said after we finish {words['ing_verb2']}, " + f"we can go swimming in our new {words['noun3']} {words['silly_word2']}.\n") # Selects random stories to play for each game story = random.choice([story_one, story_two])
"""This Module holds all the possible stories and queries to collect those stories""" import random def story_one(words): if words == {}: body_part = input("Name a body part. \n") adjective = input("Name an adjective. \n") place = input("Name a city. \n") adjective2 = input("Name another adjective. \n") place2 = input("Name a state. \n") female_celebrity = input("Name a female celebrity \n") body_part3 = input("Name another body part. \n") male_celebrity = input("Name a male celebrity. \n") body_part2 = input("Name another body part. \n") adjective3 = input("Name another adjective. \n") body_part4 = input("Name another body part. \n") organ = input("Name an organ. \n") words.update(adjective=adjective, adjective2=adjective2, adjective3=adjective3, place=place, place2=place2, female_celebrity=female_celebrity, male_celebrity=male_celebrity, body_part=body_part, body_part2=body_part2, body_part3=body_part3, body_part4=body_part4, organ=organ) return words else: return (f"\nOnce upon a time, at a place called {words['place']}, there was " + f"a {words['adjective']} princess named {words['female_celebrity']}.\nHer kingdom " + f"was huge, but her {words['body_part']} was bigger.\nShe was beautiful " + f"from her {words['body_part2']} to her {words['organ']}.\nOne day she saw a {words['adjective2']} " + f"prince named {words['male_celebrity']}.\nHe had a {words['adjective3']} face. As soon as " + f"his {words['body_part3']} touched her {words['body_part4']} they fell in love.\nThey " + f"got married in {words['place2']} the following day.\n") def story_two(words): if words == {}: adjective = input("Name an adjective. \n") plural_noun = input("Name a plural noun. \n") ing_verb = input("Name a verb ending in -ing. \n") plural_noun2 = input("Name a plural noun. \n") female_celebrity_name = input("Name a female celebrity. \n") person = input("Name a person in the game. \n") silly_word = input("Name a silly word. \n") verb = input("Name a verb. \n") food = input("Name a the plural word of a food. \n") noun = input("Name a noun. \n") adjective2 = input("Name an adjective. \n") adjective3 = input("Name an adjective. \n") shoe = input("Name a type of shoe. \n") something_alive = input("Name something alive. \n") noun2 = input("Name a noun. \n") ing_verb2 = input("Name a verb ending in -ing. \n") noun3 = input("Name a noun. \n") silly_word2 = input("Name a silly word. \n") words.update(adjective=adjective, plural_noun=plural_noun, ing_verb=ing_verb, plural_noun2=plural_noun2, female_celebrity_name=female_celebrity_name, person=person, silly_word=silly_word, verb=verb, food=food, noun=noun, adjective2=adjective2, adjective3=adjective3, shoe=shoe, something_alive=something_alive, noun2=noun2, ing_verb2=ing_verb2, noun3=noun3, silly_word2=silly_word2) return words else: return (f"\nOne of the most {words['adjective']} things about graduating is that my " + f"{words['plural_noun']} are {words['ing_verb']} a huge party.\nI decided to have a backyard " + f"barbeque for all of my family and {words['plural_noun2']}.\nI've invited my best friends {words['female_celebrity_name']}, {words['person']}, " + f"and of course my teacher, Ms. {words['silly_word']}.\nMy dad is going to {words['verb']} hamburgers and {words['food']} on his shiny new {words['noun']}.\n" + f"He always thinks his {words['food']} tastes really {words['adjective2']}, but I think they taste like {words['adjective3']} {words['shoe']}.\n" + f"My mom is going to make her famous {words['something_alive']} salad, which is my favorite {words['noun2']}.\nMom said after we finish {words['ing_verb2']}, " + f"we can go swimming in our new {words['noun3']} {words['silly_word2']}.\n") # Selects random stories to play for each game story = random.choice([story_one, story_two])
en
0.901965
This Module holds all the possible stories and queries to collect those stories # Selects random stories to play for each game
3.738256
4
mainpg/models.py
mohitdmak/Community-Page
3
6622355
from django.db import models from django.contrib.auth.models import User from django.db.models.fields.related import ForeignKey from django.utils import timezone from django.urls import reverse from PIL import Image from allauth.socialaccount.models import SocialAccount class Question(models.Model): subject = models.CharField(max_length = 200) desc = models.TextField() time = models.DateTimeField(default = timezone.now) author = models.ForeignKey(User, on_delete = models.CASCADE, related_name = "Question") likes = models.IntegerField() dislikes = models.IntegerField() def __str__(self): return self.subject def get_absolute_url(self): return reverse('home') class Answers(models.Model): ans = models.TextField() author = models.ForeignKey(User,on_delete=models.CASCADE, related_name='ansrs') time = models.DateTimeField(default=timezone.now) of = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='allans') class Like(models.Model): ofQ = models.ForeignKey(Question, on_delete = models.CASCADE, related_name = 'liked') byU = models.ForeignKey(User, on_delete = models.CASCADE, related_name = 'saved') def __str__(self): return str(self.byU.id) class DisLike(models.Model): ofQ = models.ForeignKey(Question, on_delete = models.CASCADE, related_name = 'disliked') byU = models.ForeignKey(User, on_delete = models.CASCADE, related_name = 'dissaved') def __str__(self): return str(self.byU.id) class Profile(models.Model): usr = models.OneToOneField(SocialAccount, on_delete = models.CASCADE, related_name = 'profile') Name = models.CharField(max_length = 100) Contact_Email = models.EmailField() dp = models.ImageField(default = 'default.png',upload_to = 'profilepics') Bio = models.TextField() originaldp = models.CharField(max_length = 9999, default="") Twitter_Handle = models.CharField(max_length=100, default="") Instagram_Handle = models.CharField(max_length=100, default="") Github_Handle = models.CharField(max_length=100, default="") Linkedin_Handle = models.CharField(max_length=100, default="") def save(self,*args,**kwargs): super().save(*args,**kwargs) img=Image.open(self.dp.path) if img.height>160 or img.width>110: output_size=(110,160) img.thumbnail(output_size) img.save(self.dp.path) class FollowList(models.Model): usrtf = models.ForeignKey(SocialAccount,related_name='yuser',on_delete=models.CASCADE) followings = models.ManyToManyField(SocialAccount,related_name='followings') def __str__(self): return str(self.usrtf)
from django.db import models from django.contrib.auth.models import User from django.db.models.fields.related import ForeignKey from django.utils import timezone from django.urls import reverse from PIL import Image from allauth.socialaccount.models import SocialAccount class Question(models.Model): subject = models.CharField(max_length = 200) desc = models.TextField() time = models.DateTimeField(default = timezone.now) author = models.ForeignKey(User, on_delete = models.CASCADE, related_name = "Question") likes = models.IntegerField() dislikes = models.IntegerField() def __str__(self): return self.subject def get_absolute_url(self): return reverse('home') class Answers(models.Model): ans = models.TextField() author = models.ForeignKey(User,on_delete=models.CASCADE, related_name='ansrs') time = models.DateTimeField(default=timezone.now) of = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='allans') class Like(models.Model): ofQ = models.ForeignKey(Question, on_delete = models.CASCADE, related_name = 'liked') byU = models.ForeignKey(User, on_delete = models.CASCADE, related_name = 'saved') def __str__(self): return str(self.byU.id) class DisLike(models.Model): ofQ = models.ForeignKey(Question, on_delete = models.CASCADE, related_name = 'disliked') byU = models.ForeignKey(User, on_delete = models.CASCADE, related_name = 'dissaved') def __str__(self): return str(self.byU.id) class Profile(models.Model): usr = models.OneToOneField(SocialAccount, on_delete = models.CASCADE, related_name = 'profile') Name = models.CharField(max_length = 100) Contact_Email = models.EmailField() dp = models.ImageField(default = 'default.png',upload_to = 'profilepics') Bio = models.TextField() originaldp = models.CharField(max_length = 9999, default="") Twitter_Handle = models.CharField(max_length=100, default="") Instagram_Handle = models.CharField(max_length=100, default="") Github_Handle = models.CharField(max_length=100, default="") Linkedin_Handle = models.CharField(max_length=100, default="") def save(self,*args,**kwargs): super().save(*args,**kwargs) img=Image.open(self.dp.path) if img.height>160 or img.width>110: output_size=(110,160) img.thumbnail(output_size) img.save(self.dp.path) class FollowList(models.Model): usrtf = models.ForeignKey(SocialAccount,related_name='yuser',on_delete=models.CASCADE) followings = models.ManyToManyField(SocialAccount,related_name='followings') def __str__(self): return str(self.usrtf)
none
1
2.16069
2
tests/utils/test_pluggable_interface.py
Purg/SMQTK
1
6622356
import os import pytest # noinspection PyUnresolvedReferences from six.moves import mock from smqtk.utils.plugin import Pluggable, NotUsableError THIS_DIR = os.path.abspath(os.path.dirname(__file__)) class DummyImpl (Pluggable): TEST_USABLE = True @classmethod def is_usable(cls): return cls.TEST_USABLE class DummyImplSub (DummyImpl): pass ############################################################################### # Tests @mock.patch.object(DummyImpl, 'TEST_USABLE', new_callable=mock.PropertyMock) def test_construct_when_usable(m_TEST_USABLE): # Construction should happen without incident m_TEST_USABLE.return_value = True DummyImpl() @mock.patch.object(DummyImpl, 'TEST_USABLE', new_callable=mock.PropertyMock) def test_construct_when_not_usable(m_TEST_USABLE): # Should raise NotUsableError exception on construction. m_TEST_USABLE.return_value = False with pytest.raises(NotUsableError): DummyImpl() def test_get_impls_expected_defaults(): """ Test that the correct package and containing module directory is correct for the dummy plugin. """ mock_return_value = 'mock return' with mock.patch('smqtk.utils.plugin.get_plugins') as m_get_plugins: m_get_plugins.return_value = mock_return_value assert DummyImpl.get_impls() == mock_return_value m_get_plugins.assert_called_once_with(DummyImpl, 'SMQTK_PLUGIN_PATH', 'SMQTK_PLUGIN_CLASS', # Default ``warn`` value warn=True, # Default ``reload_modules`` value reload_modules=False) def test_get_impls_do_reload(): """ Test passing change to ``reload_modules`` argument. """ mock_return_value = 'mock return' with mock.patch('smqtk.utils.plugin.get_plugins') as m_get_plugins: m_get_plugins.return_value = mock_return_value assert DummyImpl.get_impls(reload_modules=True) == mock_return_value m_get_plugins.assert_called_once_with(DummyImpl, 'SMQTK_PLUGIN_PATH', 'SMQTK_PLUGIN_CLASS', warn=True, reload_modules=True) @mock.patch.object(DummyImpl, 'PLUGIN_HELPER_VAR', new_callable=mock.PropertyMock) @mock.patch.object(DummyImpl, 'PLUGIN_ENV_VAR', new_callable=mock.PropertyMock) def test_get_impls_change_vars(m_env_var_prop, m_helper_var_prop): """ Test that changes to env/helper vars propagates to call to underlying ``get_plugins`` functional call. """ expected_return_value = 'mock return' expected_env_var = m_env_var_prop.return_value = "new test env var" expected_helper_var = m_helper_var_prop.return_value = "new test helper var" with mock.patch('smqtk.utils.plugin.get_plugins') as m_get_plugins: m_get_plugins.return_value = expected_return_value assert DummyImpl.get_impls() == expected_return_value m_get_plugins.assert_called_once_with(DummyImpl, expected_env_var, expected_helper_var, warn=True, reload_modules=False) # Make sure there is not something in the environment to mess with this test. @mock.patch.dict(os.environ, {DummyImpl.PLUGIN_ENV_VAR: ""}) def test_get_impls_implemented_classes(): """ DESIGN TEST: Test that a leaf class (i.e. full implementation of an abstract base class) still returns something when the ``get_impls`` class method is called, just that its empty. If there are sub-classes to a fully implemented class, then its discovered sub-classes should be returned. """ expected = {DummyImplSub} assert DummyImpl.get_impls() == expected expected = set() assert DummyImplSub.get_impls() == expected
import os import pytest # noinspection PyUnresolvedReferences from six.moves import mock from smqtk.utils.plugin import Pluggable, NotUsableError THIS_DIR = os.path.abspath(os.path.dirname(__file__)) class DummyImpl (Pluggable): TEST_USABLE = True @classmethod def is_usable(cls): return cls.TEST_USABLE class DummyImplSub (DummyImpl): pass ############################################################################### # Tests @mock.patch.object(DummyImpl, 'TEST_USABLE', new_callable=mock.PropertyMock) def test_construct_when_usable(m_TEST_USABLE): # Construction should happen without incident m_TEST_USABLE.return_value = True DummyImpl() @mock.patch.object(DummyImpl, 'TEST_USABLE', new_callable=mock.PropertyMock) def test_construct_when_not_usable(m_TEST_USABLE): # Should raise NotUsableError exception on construction. m_TEST_USABLE.return_value = False with pytest.raises(NotUsableError): DummyImpl() def test_get_impls_expected_defaults(): """ Test that the correct package and containing module directory is correct for the dummy plugin. """ mock_return_value = 'mock return' with mock.patch('smqtk.utils.plugin.get_plugins') as m_get_plugins: m_get_plugins.return_value = mock_return_value assert DummyImpl.get_impls() == mock_return_value m_get_plugins.assert_called_once_with(DummyImpl, 'SMQTK_PLUGIN_PATH', 'SMQTK_PLUGIN_CLASS', # Default ``warn`` value warn=True, # Default ``reload_modules`` value reload_modules=False) def test_get_impls_do_reload(): """ Test passing change to ``reload_modules`` argument. """ mock_return_value = 'mock return' with mock.patch('smqtk.utils.plugin.get_plugins') as m_get_plugins: m_get_plugins.return_value = mock_return_value assert DummyImpl.get_impls(reload_modules=True) == mock_return_value m_get_plugins.assert_called_once_with(DummyImpl, 'SMQTK_PLUGIN_PATH', 'SMQTK_PLUGIN_CLASS', warn=True, reload_modules=True) @mock.patch.object(DummyImpl, 'PLUGIN_HELPER_VAR', new_callable=mock.PropertyMock) @mock.patch.object(DummyImpl, 'PLUGIN_ENV_VAR', new_callable=mock.PropertyMock) def test_get_impls_change_vars(m_env_var_prop, m_helper_var_prop): """ Test that changes to env/helper vars propagates to call to underlying ``get_plugins`` functional call. """ expected_return_value = 'mock return' expected_env_var = m_env_var_prop.return_value = "new test env var" expected_helper_var = m_helper_var_prop.return_value = "new test helper var" with mock.patch('smqtk.utils.plugin.get_plugins') as m_get_plugins: m_get_plugins.return_value = expected_return_value assert DummyImpl.get_impls() == expected_return_value m_get_plugins.assert_called_once_with(DummyImpl, expected_env_var, expected_helper_var, warn=True, reload_modules=False) # Make sure there is not something in the environment to mess with this test. @mock.patch.dict(os.environ, {DummyImpl.PLUGIN_ENV_VAR: ""}) def test_get_impls_implemented_classes(): """ DESIGN TEST: Test that a leaf class (i.e. full implementation of an abstract base class) still returns something when the ``get_impls`` class method is called, just that its empty. If there are sub-classes to a fully implemented class, then its discovered sub-classes should be returned. """ expected = {DummyImplSub} assert DummyImpl.get_impls() == expected expected = set() assert DummyImplSub.get_impls() == expected
en
0.762151
# noinspection PyUnresolvedReferences ############################################################################### # Tests # Construction should happen without incident # Should raise NotUsableError exception on construction. Test that the correct package and containing module directory is correct for the dummy plugin. # Default ``warn`` value # Default ``reload_modules`` value Test passing change to ``reload_modules`` argument. Test that changes to env/helper vars propagates to call to underlying ``get_plugins`` functional call. # Make sure there is not something in the environment to mess with this test. DESIGN TEST: Test that a leaf class (i.e. full implementation of an abstract base class) still returns something when the ``get_impls`` class method is called, just that its empty. If there are sub-classes to a fully implemented class, then its discovered sub-classes should be returned.
1.995495
2
tenant_faq/urls.py
smegurus/smegurus-django
1
6622357
<reponame>smegurus/smegurus-django from django.conf.urls import include, url from tenant_faq import views urlpatterns = ( url(r'^faq$', views.faq_page, name='tenant_faq'), )
from django.conf.urls import include, url from tenant_faq import views urlpatterns = ( url(r'^faq$', views.faq_page, name='tenant_faq'), )
none
1
1.620103
2
api/nhlapi/graphql/definitions/player.py
rosszm/hashmarks
0
6622358
import strawberry from enum import Enum from nhlapi.graphql.definitions.team import Team from nhlapi.clients.stats import StatsClient @strawberry.type class Location: """ Represents a city location. """ city: str state_province: str country: str @strawberry.enum class Handedness(Enum): RIGHT = "R" LEFT = "L" @strawberry.type class Position: """ Represents a position in the game of hockey. """ code: str name: str type: str abbreviation: str @classmethod def from_dict(cls, pos_dict: dict): return cls( code = pos_dict.get("code"), name = pos_dict.get("name"), type = pos_dict.get("type"), abbreviation = pos_dict.get("abbreviation"), ) @strawberry.type class Player: """ Represents an NHL Player. """ id: int first_name: str last_name: str number: str | None active: bool age: int birth_date: str birth_location: Location nationality: str height: str weight: int rookie: bool handedness: Handedness roster_status: bool position: Position team_id: strawberry.Private[int | None] @strawberry.field def name(self) -> str: """ The full name of the player. """ return self.first_name + " " + self.last_name @strawberry.field def team(self) -> Team | None: """ The current team of the player. """ if self.team_id: return Team.from_dict(StatsClient.get_team(self.team_id)) @classmethod def from_dict(cls, player_dict: dict): """ Creates a new player from a dictionary representation. Args: dict: the dictionary representation of the player. The dict keys are expected to be camel case. """ currentTeam: dict | None = player_dict.get("currentTeam") team_id: int | None = None if currentTeam: team_id = currentTeam.get("id") return cls( id = player_dict.get("id"), first_name = player_dict.get("firstName"), last_name = player_dict.get("lastName"), number = player_dict.get("primaryNumber"), active = player_dict.get("active"), position = Position.from_dict(player_dict.get("primaryPosition")), age = player_dict.get("currentAge"), birth_date = player_dict.get("birthDate"), birth_location = Location( city = player_dict.get("birthCity"), state_province = player_dict.get("birthStateProvince"), country = player_dict.get("birthCountry"), ), nationality = player_dict.get("nationality"), height = player_dict.get("height"), weight = player_dict.get("weight"), rookie = player_dict.get("rookie"), handedness = player_dict.get("shootsCatches"), roster_status = player_dict.get("rosterStatus"), team_id = team_id )
import strawberry from enum import Enum from nhlapi.graphql.definitions.team import Team from nhlapi.clients.stats import StatsClient @strawberry.type class Location: """ Represents a city location. """ city: str state_province: str country: str @strawberry.enum class Handedness(Enum): RIGHT = "R" LEFT = "L" @strawberry.type class Position: """ Represents a position in the game of hockey. """ code: str name: str type: str abbreviation: str @classmethod def from_dict(cls, pos_dict: dict): return cls( code = pos_dict.get("code"), name = pos_dict.get("name"), type = pos_dict.get("type"), abbreviation = pos_dict.get("abbreviation"), ) @strawberry.type class Player: """ Represents an NHL Player. """ id: int first_name: str last_name: str number: str | None active: bool age: int birth_date: str birth_location: Location nationality: str height: str weight: int rookie: bool handedness: Handedness roster_status: bool position: Position team_id: strawberry.Private[int | None] @strawberry.field def name(self) -> str: """ The full name of the player. """ return self.first_name + " " + self.last_name @strawberry.field def team(self) -> Team | None: """ The current team of the player. """ if self.team_id: return Team.from_dict(StatsClient.get_team(self.team_id)) @classmethod def from_dict(cls, player_dict: dict): """ Creates a new player from a dictionary representation. Args: dict: the dictionary representation of the player. The dict keys are expected to be camel case. """ currentTeam: dict | None = player_dict.get("currentTeam") team_id: int | None = None if currentTeam: team_id = currentTeam.get("id") return cls( id = player_dict.get("id"), first_name = player_dict.get("firstName"), last_name = player_dict.get("lastName"), number = player_dict.get("primaryNumber"), active = player_dict.get("active"), position = Position.from_dict(player_dict.get("primaryPosition")), age = player_dict.get("currentAge"), birth_date = player_dict.get("birthDate"), birth_location = Location( city = player_dict.get("birthCity"), state_province = player_dict.get("birthStateProvince"), country = player_dict.get("birthCountry"), ), nationality = player_dict.get("nationality"), height = player_dict.get("height"), weight = player_dict.get("weight"), rookie = player_dict.get("rookie"), handedness = player_dict.get("shootsCatches"), roster_status = player_dict.get("rosterStatus"), team_id = team_id )
en
0.915042
Represents a city location. Represents a position in the game of hockey. Represents an NHL Player. The full name of the player. The current team of the player. Creates a new player from a dictionary representation. Args: dict: the dictionary representation of the player. The dict keys are expected to be camel case.
3.007812
3
aiida/orm/calculation/job/quantumespresso/pw.py
BIGDATA2015-AIIDA-EXTENSION/query_engine
0
6622359
# -*- coding: utf-8 -*- """ Plugin to create a Quantum Espresso pw.x file. """ # TODO: COPY OUTDIR FROM PREVIOUS CALCULATION! Should be an input node of type # RemoteData (or maybe subclass it?). # TODO: tests! # TODO: DOC + implementation of SETTINGS # TODO: preexec, postexec # TODO: Check that no further parameters are passed in SETTINGS # TODO: many cards missing: check and implement # e.g.: ['CONSTRAINTS', 'OCCUPATIONS'] # TODO: implement pre... and post... hooks to add arbitrary strings before # and after a namelist, and a 'final_string' (all optional); useful # for development when new cards are needed # TODO: all a lot of logger.debug stuff import os from aiida.orm.calculation.job import JobCalculation from aiida.orm.calculation.job.quantumespresso import BasePwCpInputGenerator from aiida.common.utils import classproperty from aiida.orm.data.array.kpoints import KpointsData __copyright__ = u"Copyright (c), 2015, ECOLE POLYTECHNIQUE FEDERALE DE LAUSANNE (Theory and Simulation of Materials (THEOS) and National Centre for Computational Design and Discovery of Novel Materials (NCCR MARVEL)), Switzerland and ROBERT BOSCH LLC, USA. All rights reserved." __license__ = "MIT license, see LICENSE.txt file" __version__ = "0.4.0" __contributors__ = "<NAME>, <NAME>" class PwCalculation(BasePwCpInputGenerator, JobCalculation): """ Main DFT code (PWscf, pw.x) of the Quantum ESPRESSO distribution. For more information, refer to http://www.quantum-espresso.org/ """ # false due to PWscf bug, could be set to true on versions >= 5.1.0 _default_symlink_usage = False def _init_internal_params(self): super(PwCalculation, self)._init_internal_params() self._DATAFILE_XML = os.path.join(BasePwCpInputGenerator._OUTPUT_SUBFOLDER, '{}.save'.format(BasePwCpInputGenerator._PREFIX), BasePwCpInputGenerator._DATAFILE_XML_BASENAME) # Default PW output parser provided by AiiDA self._default_parser = 'quantumespresso.basicpw' self._automatic_namelists = { 'scf': ['CONTROL', 'SYSTEM', 'ELECTRONS'], 'nscf': ['CONTROL', 'SYSTEM', 'ELECTRONS'], 'bands': ['CONTROL', 'SYSTEM', 'ELECTRONS'], 'relax': ['CONTROL', 'SYSTEM', 'ELECTRONS', 'IONS'], 'md': ['CONTROL', 'SYSTEM', 'ELECTRONS', 'IONS'], 'vc-md': ['CONTROL', 'SYSTEM', 'ELECTRONS', 'IONS', 'CELL'], 'vc-relax': ['CONTROL', 'SYSTEM', 'ELECTRONS', 'IONS', 'CELL'], } # Keywords that cannot be set self._blocked_keywords = [('CONTROL', 'pseudo_dir'), # set later ('CONTROL', 'outdir'), # set later ('CONTROL', 'prefix'), # set later ('SYSTEM', 'ibrav'), # set later ('SYSTEM', 'celldm'), ('SYSTEM', 'nat'), # set later ('SYSTEM', 'ntyp'), # set later ('SYSTEM', 'a'), ('SYSTEM', 'b'), ('SYSTEM', 'c'), ('SYSTEM', 'cosab'), ('SYSTEM', 'cosac'), ('SYSTEM', 'cosbc'), ] self._use_kpoints = True # Default input and output files self._DEFAULT_INPUT_FILE = 'aiida.in' self._DEFAULT_OUTPUT_FILE = 'aiida.out' @classproperty def _use_methods(cls): """ Extend the parent _use_methods with further keys. """ retdict = JobCalculation._use_methods retdict.update(BasePwCpInputGenerator._baseclass_use_methods) retdict['kpoints'] = { 'valid_types': KpointsData, 'additional_parameter': None, 'linkname': 'kpoints', 'docstring': "Use the node defining the kpoint sampling to use", } return retdict
# -*- coding: utf-8 -*- """ Plugin to create a Quantum Espresso pw.x file. """ # TODO: COPY OUTDIR FROM PREVIOUS CALCULATION! Should be an input node of type # RemoteData (or maybe subclass it?). # TODO: tests! # TODO: DOC + implementation of SETTINGS # TODO: preexec, postexec # TODO: Check that no further parameters are passed in SETTINGS # TODO: many cards missing: check and implement # e.g.: ['CONSTRAINTS', 'OCCUPATIONS'] # TODO: implement pre... and post... hooks to add arbitrary strings before # and after a namelist, and a 'final_string' (all optional); useful # for development when new cards are needed # TODO: all a lot of logger.debug stuff import os from aiida.orm.calculation.job import JobCalculation from aiida.orm.calculation.job.quantumespresso import BasePwCpInputGenerator from aiida.common.utils import classproperty from aiida.orm.data.array.kpoints import KpointsData __copyright__ = u"Copyright (c), 2015, ECOLE POLYTECHNIQUE FEDERALE DE LAUSANNE (Theory and Simulation of Materials (THEOS) and National Centre for Computational Design and Discovery of Novel Materials (NCCR MARVEL)), Switzerland and ROBERT BOSCH LLC, USA. All rights reserved." __license__ = "MIT license, see LICENSE.txt file" __version__ = "0.4.0" __contributors__ = "<NAME>, <NAME>" class PwCalculation(BasePwCpInputGenerator, JobCalculation): """ Main DFT code (PWscf, pw.x) of the Quantum ESPRESSO distribution. For more information, refer to http://www.quantum-espresso.org/ """ # false due to PWscf bug, could be set to true on versions >= 5.1.0 _default_symlink_usage = False def _init_internal_params(self): super(PwCalculation, self)._init_internal_params() self._DATAFILE_XML = os.path.join(BasePwCpInputGenerator._OUTPUT_SUBFOLDER, '{}.save'.format(BasePwCpInputGenerator._PREFIX), BasePwCpInputGenerator._DATAFILE_XML_BASENAME) # Default PW output parser provided by AiiDA self._default_parser = 'quantumespresso.basicpw' self._automatic_namelists = { 'scf': ['CONTROL', 'SYSTEM', 'ELECTRONS'], 'nscf': ['CONTROL', 'SYSTEM', 'ELECTRONS'], 'bands': ['CONTROL', 'SYSTEM', 'ELECTRONS'], 'relax': ['CONTROL', 'SYSTEM', 'ELECTRONS', 'IONS'], 'md': ['CONTROL', 'SYSTEM', 'ELECTRONS', 'IONS'], 'vc-md': ['CONTROL', 'SYSTEM', 'ELECTRONS', 'IONS', 'CELL'], 'vc-relax': ['CONTROL', 'SYSTEM', 'ELECTRONS', 'IONS', 'CELL'], } # Keywords that cannot be set self._blocked_keywords = [('CONTROL', 'pseudo_dir'), # set later ('CONTROL', 'outdir'), # set later ('CONTROL', 'prefix'), # set later ('SYSTEM', 'ibrav'), # set later ('SYSTEM', 'celldm'), ('SYSTEM', 'nat'), # set later ('SYSTEM', 'ntyp'), # set later ('SYSTEM', 'a'), ('SYSTEM', 'b'), ('SYSTEM', 'c'), ('SYSTEM', 'cosab'), ('SYSTEM', 'cosac'), ('SYSTEM', 'cosbc'), ] self._use_kpoints = True # Default input and output files self._DEFAULT_INPUT_FILE = 'aiida.in' self._DEFAULT_OUTPUT_FILE = 'aiida.out' @classproperty def _use_methods(cls): """ Extend the parent _use_methods with further keys. """ retdict = JobCalculation._use_methods retdict.update(BasePwCpInputGenerator._baseclass_use_methods) retdict['kpoints'] = { 'valid_types': KpointsData, 'additional_parameter': None, 'linkname': 'kpoints', 'docstring': "Use the node defining the kpoint sampling to use", } return retdict
en
0.739929
# -*- coding: utf-8 -*- Plugin to create a Quantum Espresso pw.x file. # TODO: COPY OUTDIR FROM PREVIOUS CALCULATION! Should be an input node of type # RemoteData (or maybe subclass it?). # TODO: tests! # TODO: DOC + implementation of SETTINGS # TODO: preexec, postexec # TODO: Check that no further parameters are passed in SETTINGS # TODO: many cards missing: check and implement # e.g.: ['CONSTRAINTS', 'OCCUPATIONS'] # TODO: implement pre... and post... hooks to add arbitrary strings before # and after a namelist, and a 'final_string' (all optional); useful # for development when new cards are needed # TODO: all a lot of logger.debug stuff Main DFT code (PWscf, pw.x) of the Quantum ESPRESSO distribution. For more information, refer to http://www.quantum-espresso.org/ # false due to PWscf bug, could be set to true on versions >= 5.1.0 # Default PW output parser provided by AiiDA # Keywords that cannot be set # set later # set later # set later # set later # set later # set later # Default input and output files Extend the parent _use_methods with further keys.
1.87324
2
contrib/scripts/test_false_positives.py
electrumsv/libcuckoofilter
0
6622360
<filename>contrib/scripts/test_false_positives.py """ .... false positives .... maximum entries, added entries, minimum, maximum, average 16000, 2000, 231, 301, 262.8 16000, 4000, 470, 601, 535.4 16000, 8000, 1005, 1161, 1075.9 16000, 16000, 2021, 2270, 2139.1 32000, 2000, 53, 88, 67.0 32000, 4000, 106, 159, 134.7 32000, 8000, 225, 313, 268.2 32000, 16000, 503, 602, 542.0 32000, 32000, 997, 1148, 1069.4 62914, 2000, 47, 101, 68.8 62914, 4000, 104, 161, 132.6 62914, 8000, 233, 315, 270.5 62914, 16000, 488, 598, 538.3 62914, 32000, 989, 1141, 1063.8 62914, 62914, 1869, 2063, 1971.1 ... 65536 * 0.96 62915, 2000, 10, 26, 16.8 62915, 4000, 20, 46, 33.5 62915, 8000, 47, 92, 67.1 62915, 16000, 102, 156, 134.8 62915, 32000, 225, 307, 269.5 62915, 62915, 463, 584, 530.4 64000, 2000, 9, 30, 17.0 64000, 4000, 18, 46, 33.4 64000, 8000, 46, 83, 65.9 64000, 16000, 109, 163, 134.2 64000, 32000, 234, 303, 267.7 64000, 64000, 478, 598, 533.8 125829, 2000, 7, 31, 16.6 125829, 4000, 20, 52, 34.0 125829, 8000, 47, 83, 67.7 125829, 16000, 102, 164, 134.4 125829, 32000, 218, 322, 270.0 125829, 64000, 478, 597, 535.5 125829, 125829, 901, 1051, 985.2 ... (65536 << 1) * 0.96 125830, 2000, 0, 9, 4.5 125830, 4000, 2, 15, 8.8 125830, 8000, 4, 27, 17.1 125830, 16000, 18, 46, 31.7 125830, 32000, 44, 86, 66.5 125830, 64000, 105, 166, 132.8 125830, 125830, 228, 299, 261.5 128000, 2000, 1, 12, 4.6 128000, 4000, 3, 15, 8.6 128000, 8000, 9, 26, 17.4 128000, 16000, 21, 45, 33.4 128000, 32000, 45, 93, 67.1 128000, 64000, 103, 166, 135.5 128000, 128000, 235, 310, 268.9 251658, 2000, 0, 9, 4.2 251658, 4000, 1, 19, 8.1 251658, 8000, 9, 34, 17.1 251658, 16000, 16, 52, 33.0 251658, 32000, 49, 86, 66.2 251658, 64000, 104, 174, 135.4 251658, 128000, 228, 324, 266.8 251658, 251658, 441, 538, 494.2 ... (65536 << 2) * 0.96 251659, 2000, 0, 6, 2.1 251659, 4000, 1, 9, 4.1 251659, 8000, 2, 18, 8.4 251659, 16000, 8, 31, 17.1 251659, 32000, 19, 47, 33.1 251659, 64000, 47, 91, 67.6 251659, 128000, 105, 161, 134.8 251659, 251659, 224, 306, 263.2 256000, 2000, 0, 5, 1.8 256000, 4000, 1, 11, 4.3 256000, 8000, 1, 15, 8.5 256000, 16000, 8, 32, 17.6 256000, 32000, 21, 48, 33.4 256000, 64000, 49, 92, 67.3 256000, 128000, 106, 163, 134.7 256000, 256000, 229, 316, 266.2 512000, 2000, 0, 4, 1.1 512000, 4000, 0, 6, 1.9 512000, 8000, 0, 11, 4.2 512000, 16000, 2, 16, 8.4 512000, 32000, 9, 29, 16.7 512000, 64000, 22, 51, 33.1 512000, 128000, 46, 83, 65.7 512000, 256000, 100, 156, 133.7 512000, 512000, 240, 303, 268.9 """ from collections import defaultdict import os import bsvcuckoo LOOKUP_COUNT = 1000000 ITERATIONS = 100 MAX_KICK_COUNT = 10 with open("test.csv", "w") as f: print("maximum entries, added entries, minimum, maximum, average", file=f) maximum_entries = 251658 while maximum_entries <= 251659: false_positive_map: dict[int, list[int]] = defaultdict(list) for i in range(ITERATIONS): print(f"{i}, ", end="", flush=True) filter = bsvcuckoo.CuckooFilter(maximum_entries, MAX_KICK_COUNT, 1644963952) addition_count = 2000 last_addition_count = 0 while addition_count <= maximum_entries: for i in range(last_addition_count, addition_count): k = os.urandom(32) filter.add(k) false_positives = 0 for j in range(LOOKUP_COUNT): k = os.urandom(32) if filter.contains(k) == 0: false_positives += 1 false_positive_map[addition_count].append(false_positives) last_addition_count = addition_count addition_count *= 2 if last_addition_count < maximum_entries and addition_count > maximum_entries: addition_count = maximum_entries print() for addition_count, false_positive_counts in false_positive_map.items(): print(f"{maximum_entries:15}, {addition_count:13}, {min(false_positive_counts):7}, " f"{max(false_positive_counts):7}, {sum(false_positive_counts)/ITERATIONS:7.1f}", file=f) maximum_entries += 1
<filename>contrib/scripts/test_false_positives.py """ .... false positives .... maximum entries, added entries, minimum, maximum, average 16000, 2000, 231, 301, 262.8 16000, 4000, 470, 601, 535.4 16000, 8000, 1005, 1161, 1075.9 16000, 16000, 2021, 2270, 2139.1 32000, 2000, 53, 88, 67.0 32000, 4000, 106, 159, 134.7 32000, 8000, 225, 313, 268.2 32000, 16000, 503, 602, 542.0 32000, 32000, 997, 1148, 1069.4 62914, 2000, 47, 101, 68.8 62914, 4000, 104, 161, 132.6 62914, 8000, 233, 315, 270.5 62914, 16000, 488, 598, 538.3 62914, 32000, 989, 1141, 1063.8 62914, 62914, 1869, 2063, 1971.1 ... 65536 * 0.96 62915, 2000, 10, 26, 16.8 62915, 4000, 20, 46, 33.5 62915, 8000, 47, 92, 67.1 62915, 16000, 102, 156, 134.8 62915, 32000, 225, 307, 269.5 62915, 62915, 463, 584, 530.4 64000, 2000, 9, 30, 17.0 64000, 4000, 18, 46, 33.4 64000, 8000, 46, 83, 65.9 64000, 16000, 109, 163, 134.2 64000, 32000, 234, 303, 267.7 64000, 64000, 478, 598, 533.8 125829, 2000, 7, 31, 16.6 125829, 4000, 20, 52, 34.0 125829, 8000, 47, 83, 67.7 125829, 16000, 102, 164, 134.4 125829, 32000, 218, 322, 270.0 125829, 64000, 478, 597, 535.5 125829, 125829, 901, 1051, 985.2 ... (65536 << 1) * 0.96 125830, 2000, 0, 9, 4.5 125830, 4000, 2, 15, 8.8 125830, 8000, 4, 27, 17.1 125830, 16000, 18, 46, 31.7 125830, 32000, 44, 86, 66.5 125830, 64000, 105, 166, 132.8 125830, 125830, 228, 299, 261.5 128000, 2000, 1, 12, 4.6 128000, 4000, 3, 15, 8.6 128000, 8000, 9, 26, 17.4 128000, 16000, 21, 45, 33.4 128000, 32000, 45, 93, 67.1 128000, 64000, 103, 166, 135.5 128000, 128000, 235, 310, 268.9 251658, 2000, 0, 9, 4.2 251658, 4000, 1, 19, 8.1 251658, 8000, 9, 34, 17.1 251658, 16000, 16, 52, 33.0 251658, 32000, 49, 86, 66.2 251658, 64000, 104, 174, 135.4 251658, 128000, 228, 324, 266.8 251658, 251658, 441, 538, 494.2 ... (65536 << 2) * 0.96 251659, 2000, 0, 6, 2.1 251659, 4000, 1, 9, 4.1 251659, 8000, 2, 18, 8.4 251659, 16000, 8, 31, 17.1 251659, 32000, 19, 47, 33.1 251659, 64000, 47, 91, 67.6 251659, 128000, 105, 161, 134.8 251659, 251659, 224, 306, 263.2 256000, 2000, 0, 5, 1.8 256000, 4000, 1, 11, 4.3 256000, 8000, 1, 15, 8.5 256000, 16000, 8, 32, 17.6 256000, 32000, 21, 48, 33.4 256000, 64000, 49, 92, 67.3 256000, 128000, 106, 163, 134.7 256000, 256000, 229, 316, 266.2 512000, 2000, 0, 4, 1.1 512000, 4000, 0, 6, 1.9 512000, 8000, 0, 11, 4.2 512000, 16000, 2, 16, 8.4 512000, 32000, 9, 29, 16.7 512000, 64000, 22, 51, 33.1 512000, 128000, 46, 83, 65.7 512000, 256000, 100, 156, 133.7 512000, 512000, 240, 303, 268.9 """ from collections import defaultdict import os import bsvcuckoo LOOKUP_COUNT = 1000000 ITERATIONS = 100 MAX_KICK_COUNT = 10 with open("test.csv", "w") as f: print("maximum entries, added entries, minimum, maximum, average", file=f) maximum_entries = 251658 while maximum_entries <= 251659: false_positive_map: dict[int, list[int]] = defaultdict(list) for i in range(ITERATIONS): print(f"{i}, ", end="", flush=True) filter = bsvcuckoo.CuckooFilter(maximum_entries, MAX_KICK_COUNT, 1644963952) addition_count = 2000 last_addition_count = 0 while addition_count <= maximum_entries: for i in range(last_addition_count, addition_count): k = os.urandom(32) filter.add(k) false_positives = 0 for j in range(LOOKUP_COUNT): k = os.urandom(32) if filter.contains(k) == 0: false_positives += 1 false_positive_map[addition_count].append(false_positives) last_addition_count = addition_count addition_count *= 2 if last_addition_count < maximum_entries and addition_count > maximum_entries: addition_count = maximum_entries print() for addition_count, false_positive_counts in false_positive_map.items(): print(f"{maximum_entries:15}, {addition_count:13}, {min(false_positive_counts):7}, " f"{max(false_positive_counts):7}, {sum(false_positive_counts)/ITERATIONS:7.1f}", file=f) maximum_entries += 1
en
0.357069
.... false positives .... maximum entries, added entries, minimum, maximum, average 16000, 2000, 231, 301, 262.8 16000, 4000, 470, 601, 535.4 16000, 8000, 1005, 1161, 1075.9 16000, 16000, 2021, 2270, 2139.1 32000, 2000, 53, 88, 67.0 32000, 4000, 106, 159, 134.7 32000, 8000, 225, 313, 268.2 32000, 16000, 503, 602, 542.0 32000, 32000, 997, 1148, 1069.4 62914, 2000, 47, 101, 68.8 62914, 4000, 104, 161, 132.6 62914, 8000, 233, 315, 270.5 62914, 16000, 488, 598, 538.3 62914, 32000, 989, 1141, 1063.8 62914, 62914, 1869, 2063, 1971.1 ... 65536 * 0.96 62915, 2000, 10, 26, 16.8 62915, 4000, 20, 46, 33.5 62915, 8000, 47, 92, 67.1 62915, 16000, 102, 156, 134.8 62915, 32000, 225, 307, 269.5 62915, 62915, 463, 584, 530.4 64000, 2000, 9, 30, 17.0 64000, 4000, 18, 46, 33.4 64000, 8000, 46, 83, 65.9 64000, 16000, 109, 163, 134.2 64000, 32000, 234, 303, 267.7 64000, 64000, 478, 598, 533.8 125829, 2000, 7, 31, 16.6 125829, 4000, 20, 52, 34.0 125829, 8000, 47, 83, 67.7 125829, 16000, 102, 164, 134.4 125829, 32000, 218, 322, 270.0 125829, 64000, 478, 597, 535.5 125829, 125829, 901, 1051, 985.2 ... (65536 << 1) * 0.96 125830, 2000, 0, 9, 4.5 125830, 4000, 2, 15, 8.8 125830, 8000, 4, 27, 17.1 125830, 16000, 18, 46, 31.7 125830, 32000, 44, 86, 66.5 125830, 64000, 105, 166, 132.8 125830, 125830, 228, 299, 261.5 128000, 2000, 1, 12, 4.6 128000, 4000, 3, 15, 8.6 128000, 8000, 9, 26, 17.4 128000, 16000, 21, 45, 33.4 128000, 32000, 45, 93, 67.1 128000, 64000, 103, 166, 135.5 128000, 128000, 235, 310, 268.9 251658, 2000, 0, 9, 4.2 251658, 4000, 1, 19, 8.1 251658, 8000, 9, 34, 17.1 251658, 16000, 16, 52, 33.0 251658, 32000, 49, 86, 66.2 251658, 64000, 104, 174, 135.4 251658, 128000, 228, 324, 266.8 251658, 251658, 441, 538, 494.2 ... (65536 << 2) * 0.96 251659, 2000, 0, 6, 2.1 251659, 4000, 1, 9, 4.1 251659, 8000, 2, 18, 8.4 251659, 16000, 8, 31, 17.1 251659, 32000, 19, 47, 33.1 251659, 64000, 47, 91, 67.6 251659, 128000, 105, 161, 134.8 251659, 251659, 224, 306, 263.2 256000, 2000, 0, 5, 1.8 256000, 4000, 1, 11, 4.3 256000, 8000, 1, 15, 8.5 256000, 16000, 8, 32, 17.6 256000, 32000, 21, 48, 33.4 256000, 64000, 49, 92, 67.3 256000, 128000, 106, 163, 134.7 256000, 256000, 229, 316, 266.2 512000, 2000, 0, 4, 1.1 512000, 4000, 0, 6, 1.9 512000, 8000, 0, 11, 4.2 512000, 16000, 2, 16, 8.4 512000, 32000, 9, 29, 16.7 512000, 64000, 22, 51, 33.1 512000, 128000, 46, 83, 65.7 512000, 256000, 100, 156, 133.7 512000, 512000, 240, 303, 268.9
1.60849
2
postprocessing/plot_aggregate_data.py
mvousden/psap
0
6622361
<gh_stars>0 #!/usr/bin/env python3 # Postprocessing for data aggregated from many individual annealing # procedures. The input CSV file should have these headings: # # - Problem Size: String # - Synchronisation: String # - Number of Compute Workers: Degree of parallelism (int64). # - Runtime: Execution time in units of your choice - it's all # normalised (int64). # - Reliable Fitness Rate: Fraction of fitness computations that are # reliable (float64). import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd import sys matplotlib.rc("axes", linewidth=1) matplotlib.rc("figure", figsize=(2.7, 2.7)) matplotlib.rc("font", family="serif", size=7) matplotlib.rc("legend", frameon=False) matplotlib.rc("xtick.major", width=1) matplotlib.rc("ytick.major", width=1) # Load data if len(sys.argv) < 2: fPath = "aggregate_data.csv" else: fPath = sys.argv[1] df = pd.read_csv(fPath).sort_values(by="Number of Compute Workers") # Draw speedup data for the small and large problems separately for problem in ["Small", "Large"]: figure, axes = plt.subplots() for synchronisation in df["Synchronisation"].unique(): subFrame = df[(df["Synchronisation"] == synchronisation) & (df["Problem Size"] == problem)] serialTime = subFrame[subFrame["Number of Compute Workers"] == 0]\ ["Runtime"].values[0] # Points (the 1: slice removes n=0) axes.plot(subFrame["Number of Compute Workers"][1:], serialTime / subFrame["Runtime"][1:], "k." if synchronisation == "Asynchronous" else "k1", label=synchronisation + " Annealer") # Draw linear speedup line maxHoriz = df["Number of Compute Workers"].max() # axes.plot([1, maxHoriz], [1, maxHoriz], alpha=0.2, color="k", # linestyle="--") # Other stuff for speedup graph axisBuffer = 1 axes.set_xlim(1 - axisBuffer, maxHoriz + axisBuffer) axes.set_ylim(0, 10) axes.set_xlabel("Number of Compute Workers") if problem == "Large": axes.set_ylabel("Serial-Relative Speedup ($t_0/t_n$)") axes.spines["top"].set_visible(False) axes.spines["right"].set_visible(False) axes.xaxis.set_ticks_position("bottom") axes.yaxis.set_ticks_position("left") labels = [2**power for power in [0, 4, 5, 6]] axes.xaxis.set_ticks(labels) axes.xaxis.set_ticklabels(["1", "16", "32", "64"]) axes.yaxis.set_ticks([0, 1, 2, 4, 6, 8, 10]) axes.set_title("Runtime Scaling ({} Problem)".format(problem)) if problem == "Large": plt.legend(handletextpad=0) figure.tight_layout() figure.savefig("speedup_{}.pdf".format(problem.lower())) plt.close() # Collision rate data from MC experiments (sorry): nw = [1] + list(range(2, 65, 2)) smallProbs = np.array([0.0, 0.00982, 0.03159, .052128957420851586, .07211, .09074, .10806135509159268, .126707465850683, .14564, .16300695944324453, .18095, .1951965764108307, .21164306855451565, .23096918677890865, .2489701647736362, .262997400519896, .27977, .29164833846522975, .30478561715062796, .3198488241881299, .33376, .3472230555388892, .36214654241491023, .3766249350025999, .3889855246321177, .40163, .4124520230289461, .42360611151107913, .43787993920972645, .44990504747626187, .4605278944211158, .4697418154910705, .48380518234165065]) * 100 largeProbs = np.array([0.0, 0.00514, 0.01649, 0.025369492610147797, 0.03539, 0.04631, 0.05629549636029118, 0.06436871262574749, 0.0755, 0.08567314614830814, 0.09602, 0.10628724553053634, 0.11447084233261338, 0.12224310651656635, 0.13309870420732683, 0.14034193161367725, 0.15084, 0.16032510896948854, 0.16655667546596273, 0.1750919852823548, 0.18523, 0.19281614367712646, 0.1977462704475463, 0.20977160913563458, 0.21718050223928342, 0.22727, 0.23267831440908365, 0.24246060315174786, 0.24979003359462487, 0.2554022988505747, 0.2640071985602879, 0.2722736635801852, 0.2778510876519514]) * 100 # Draw fitness collision rate data figure, axes = plt.subplots() for problemSize in df["Problem Size"].unique(): subFrame = df[(df["Synchronisation"] == "Asynchronous") & (df["Problem Size"] == problemSize) & (df["Number of Compute Workers"] != 0)] # Points axes.plot(subFrame["Number of Compute Workers"], (1 - subFrame["Reliable Fitness Rate"]) * \ (100 if problemSize == "Large" else 85), "kx" if problemSize == "Large" else "k+", label=problemSize + " Problem") # Draw model data. axes.plot(nw, smallProbs, "k--", alpha=0.5, label="Monte Carlo") axes.plot(nw, largeProbs, "k--", alpha=0.5) # Other stuff for fitness collision rate graph horizAxisBuffer = 1 axes.set_xlim(1 - horizAxisBuffer, maxHoriz + horizAxisBuffer) axes.set_ylim(-1.3, 50) axes.set_xlabel("Number of Compute Workers") axes.set_ylabel("Collision Rate (percentage of\nunreliable fitness " "calculations)") axes.spines["top"].set_visible(False) axes.spines["right"].set_visible(False) axes.xaxis.set_ticks_position("bottom") axes.yaxis.set_ticks_position("left") axes.xaxis.set_ticks([2**power for power in [0, 4, 5, 6]]) axes.xaxis.set_ticklabels(["1", "16", "32", "64"]) axes.yaxis.set_ticks([0, 10, 20, 30, 40, 50]) axes.set_title("Asynchronous Annealing Collision Rate") plt.legend(handletextpad=0) figure.tight_layout() figure.savefig("collision_rate.pdf")
#!/usr/bin/env python3 # Postprocessing for data aggregated from many individual annealing # procedures. The input CSV file should have these headings: # # - Problem Size: String # - Synchronisation: String # - Number of Compute Workers: Degree of parallelism (int64). # - Runtime: Execution time in units of your choice - it's all # normalised (int64). # - Reliable Fitness Rate: Fraction of fitness computations that are # reliable (float64). import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd import sys matplotlib.rc("axes", linewidth=1) matplotlib.rc("figure", figsize=(2.7, 2.7)) matplotlib.rc("font", family="serif", size=7) matplotlib.rc("legend", frameon=False) matplotlib.rc("xtick.major", width=1) matplotlib.rc("ytick.major", width=1) # Load data if len(sys.argv) < 2: fPath = "aggregate_data.csv" else: fPath = sys.argv[1] df = pd.read_csv(fPath).sort_values(by="Number of Compute Workers") # Draw speedup data for the small and large problems separately for problem in ["Small", "Large"]: figure, axes = plt.subplots() for synchronisation in df["Synchronisation"].unique(): subFrame = df[(df["Synchronisation"] == synchronisation) & (df["Problem Size"] == problem)] serialTime = subFrame[subFrame["Number of Compute Workers"] == 0]\ ["Runtime"].values[0] # Points (the 1: slice removes n=0) axes.plot(subFrame["Number of Compute Workers"][1:], serialTime / subFrame["Runtime"][1:], "k." if synchronisation == "Asynchronous" else "k1", label=synchronisation + " Annealer") # Draw linear speedup line maxHoriz = df["Number of Compute Workers"].max() # axes.plot([1, maxHoriz], [1, maxHoriz], alpha=0.2, color="k", # linestyle="--") # Other stuff for speedup graph axisBuffer = 1 axes.set_xlim(1 - axisBuffer, maxHoriz + axisBuffer) axes.set_ylim(0, 10) axes.set_xlabel("Number of Compute Workers") if problem == "Large": axes.set_ylabel("Serial-Relative Speedup ($t_0/t_n$)") axes.spines["top"].set_visible(False) axes.spines["right"].set_visible(False) axes.xaxis.set_ticks_position("bottom") axes.yaxis.set_ticks_position("left") labels = [2**power for power in [0, 4, 5, 6]] axes.xaxis.set_ticks(labels) axes.xaxis.set_ticklabels(["1", "16", "32", "64"]) axes.yaxis.set_ticks([0, 1, 2, 4, 6, 8, 10]) axes.set_title("Runtime Scaling ({} Problem)".format(problem)) if problem == "Large": plt.legend(handletextpad=0) figure.tight_layout() figure.savefig("speedup_{}.pdf".format(problem.lower())) plt.close() # Collision rate data from MC experiments (sorry): nw = [1] + list(range(2, 65, 2)) smallProbs = np.array([0.0, 0.00982, 0.03159, .052128957420851586, .07211, .09074, .10806135509159268, .126707465850683, .14564, .16300695944324453, .18095, .1951965764108307, .21164306855451565, .23096918677890865, .2489701647736362, .262997400519896, .27977, .29164833846522975, .30478561715062796, .3198488241881299, .33376, .3472230555388892, .36214654241491023, .3766249350025999, .3889855246321177, .40163, .4124520230289461, .42360611151107913, .43787993920972645, .44990504747626187, .4605278944211158, .4697418154910705, .48380518234165065]) * 100 largeProbs = np.array([0.0, 0.00514, 0.01649, 0.025369492610147797, 0.03539, 0.04631, 0.05629549636029118, 0.06436871262574749, 0.0755, 0.08567314614830814, 0.09602, 0.10628724553053634, 0.11447084233261338, 0.12224310651656635, 0.13309870420732683, 0.14034193161367725, 0.15084, 0.16032510896948854, 0.16655667546596273, 0.1750919852823548, 0.18523, 0.19281614367712646, 0.1977462704475463, 0.20977160913563458, 0.21718050223928342, 0.22727, 0.23267831440908365, 0.24246060315174786, 0.24979003359462487, 0.2554022988505747, 0.2640071985602879, 0.2722736635801852, 0.2778510876519514]) * 100 # Draw fitness collision rate data figure, axes = plt.subplots() for problemSize in df["Problem Size"].unique(): subFrame = df[(df["Synchronisation"] == "Asynchronous") & (df["Problem Size"] == problemSize) & (df["Number of Compute Workers"] != 0)] # Points axes.plot(subFrame["Number of Compute Workers"], (1 - subFrame["Reliable Fitness Rate"]) * \ (100 if problemSize == "Large" else 85), "kx" if problemSize == "Large" else "k+", label=problemSize + " Problem") # Draw model data. axes.plot(nw, smallProbs, "k--", alpha=0.5, label="Monte Carlo") axes.plot(nw, largeProbs, "k--", alpha=0.5) # Other stuff for fitness collision rate graph horizAxisBuffer = 1 axes.set_xlim(1 - horizAxisBuffer, maxHoriz + horizAxisBuffer) axes.set_ylim(-1.3, 50) axes.set_xlabel("Number of Compute Workers") axes.set_ylabel("Collision Rate (percentage of\nunreliable fitness " "calculations)") axes.spines["top"].set_visible(False) axes.spines["right"].set_visible(False) axes.xaxis.set_ticks_position("bottom") axes.yaxis.set_ticks_position("left") axes.xaxis.set_ticks([2**power for power in [0, 4, 5, 6]]) axes.xaxis.set_ticklabels(["1", "16", "32", "64"]) axes.yaxis.set_ticks([0, 10, 20, 30, 40, 50]) axes.set_title("Asynchronous Annealing Collision Rate") plt.legend(handletextpad=0) figure.tight_layout() figure.savefig("collision_rate.pdf")
en
0.786793
#!/usr/bin/env python3 # Postprocessing for data aggregated from many individual annealing # procedures. The input CSV file should have these headings: # # - Problem Size: String # - Synchronisation: String # - Number of Compute Workers: Degree of parallelism (int64). # - Runtime: Execution time in units of your choice - it's all # normalised (int64). # - Reliable Fitness Rate: Fraction of fitness computations that are # reliable (float64). # Load data # Draw speedup data for the small and large problems separately # Points (the 1: slice removes n=0) # Draw linear speedup line # axes.plot([1, maxHoriz], [1, maxHoriz], alpha=0.2, color="k", # linestyle="--") # Other stuff for speedup graph # Collision rate data from MC experiments (sorry): # Draw fitness collision rate data # Points # Draw model data. # Other stuff for fitness collision rate graph
3.068261
3
topi/python/topi/cuda/rcnn/__init__.py
mingwayzhang/tvm
48
6622362
<reponame>mingwayzhang/tvm # pylint: disable=wildcard-import """Faster R-CNN and Mask R-CNN operators""" from .proposal import *
# pylint: disable=wildcard-import """Faster R-CNN and Mask R-CNN operators""" from .proposal import *
en
0.709287
# pylint: disable=wildcard-import Faster R-CNN and Mask R-CNN operators
1.09825
1
examples/logo.py
luzpaz/cqparts
69
6622363
<filename>examples/logo.py """ This example makes the cqparts logo """ from cqparts import Assembly class CQPartsLogo(Assembly): # TODO pass
<filename>examples/logo.py """ This example makes the cqparts logo """ from cqparts import Assembly class CQPartsLogo(Assembly): # TODO pass
en
0.727675
This example makes the cqparts logo # TODO
1.271478
1
Python/Bit--Manipulation/toggle_kth_bit.py
Khushboo85277/NeoAlgo
897
6622364
<filename>Python/Bit--Manipulation/toggle_kth_bit.py # Python program to toggle the k-th bit of a number. def toggle(num, k): return (num ^ (1 << (k-1))) if __name__ == '__main__': print("Enter the number: ", end="") n = int(input()) print("Enter the value of k(where you need to toggle the k'th bit): ", end="") b = int(input()) res = toggle(n, b) print("The given number, after toggling the k-th bit is {}".format(res)) """ Time Complexity: O(1) Space Complexity: O(1) SAMPLE INPUT AND OUTPUT SAMPLE 1 Enter the number: 24 Enter the value of k(where you need to toggle the k'th bit): 3 The given number, after toggling the k-th bit is 28. SAMPLE 2 Enter the number: 33 Enter the value of k(where you need to toggle the k'th bit): 12 The given number, after toggling the k-th bit is 2081. """
<filename>Python/Bit--Manipulation/toggle_kth_bit.py # Python program to toggle the k-th bit of a number. def toggle(num, k): return (num ^ (1 << (k-1))) if __name__ == '__main__': print("Enter the number: ", end="") n = int(input()) print("Enter the value of k(where you need to toggle the k'th bit): ", end="") b = int(input()) res = toggle(n, b) print("The given number, after toggling the k-th bit is {}".format(res)) """ Time Complexity: O(1) Space Complexity: O(1) SAMPLE INPUT AND OUTPUT SAMPLE 1 Enter the number: 24 Enter the value of k(where you need to toggle the k'th bit): 3 The given number, after toggling the k-th bit is 28. SAMPLE 2 Enter the number: 33 Enter the value of k(where you need to toggle the k'th bit): 12 The given number, after toggling the k-th bit is 2081. """
en
0.711806
# Python program to toggle the k-th bit of a number. Time Complexity: O(1) Space Complexity: O(1) SAMPLE INPUT AND OUTPUT SAMPLE 1 Enter the number: 24 Enter the value of k(where you need to toggle the k'th bit): 3 The given number, after toggling the k-th bit is 28. SAMPLE 2 Enter the number: 33 Enter the value of k(where you need to toggle the k'th bit): 12 The given number, after toggling the k-th bit is 2081.
4.441402
4
fastlab/routers/__init__.py
tezignlab/fastweb
14
6622365
from .health import HealthRouter __all__ = ['HealthRouter']
from .health import HealthRouter __all__ = ['HealthRouter']
none
1
1.124519
1
RAFT/raft/omdao_raft.py
ptrbortolotti/WEIS
26
6622366
import openmdao.api as om import raft import numpy as np ndim = 3 ndof = 6 class RAFT_OMDAO(om.ExplicitComponent): """ RAFT OpenMDAO Wrapper API """ def initialize(self): self.options.declare('modeling_options') self.options.declare('turbine_options') self.options.declare('mooring_options') self.options.declare('member_options') def setup(self): # unpack options modeling_opt = self.options['modeling_options'] nfreq = modeling_opt['nfreq'] turbine_opt = self.options['turbine_options'] turbine_npts = turbine_opt['npts'] members_opt = self.options['member_options'] nmembers = members_opt['nmembers'] member_npts = members_opt['npts'] member_npts_lfill = members_opt['npts_lfill'] member_npts_rho_fill = members_opt['npts_rho_fill'] member_ncaps = members_opt['ncaps'] member_nreps = members_opt['nreps'] member_shape = members_opt['shape'] member_scalar_t = members_opt['scalar_thicknesses'] member_scalar_d = members_opt['scalar_diameters'] member_scalar_coeff = members_opt['scalar_coefficients'] mooring_opt = self.options['mooring_options'] nlines = mooring_opt['nlines'] nline_types = mooring_opt['nline_types'] nconnections = mooring_opt['nconnections'] # frequency domain self.add_input('frequency_range', val=np.zeros(nfreq), units='Hz', desc='Frequency range to compute response over') # turbine inputs self.add_input('turbine_mRNA', val=0.0, units='kg', desc='RNA mass') self.add_input('turbine_IxRNA', val=0.0, units='kg*m**2', desc='RNA moment of inertia about local x axis') self.add_input('turbine_IrRNA', val=0.0, units='kg*m**2', desc='RNA moment of inertia about local y or z axes') self.add_input('turbine_xCG_RNA', val=0.0, units='m', desc='x location of RNA center of mass') self.add_input('turbine_hHub', val=0.0, units='m', desc='Hub height above water line') self.add_input('turbine_Fthrust', val=0.0, units='N', desc='Temporary thrust force to use') self.add_input('turbine_yaw_stiffness', val=0.0, units='N*m', desc='Additional yaw stiffness to apply if not modeling crowfoot in the mooring system') # tower inputs self.add_input('turbine_tower_rA', val=np.zeros(ndim), units='m', desc='End A coordinates') self.add_input('turbine_tower_rB', val=np.zeros(ndim), units='m', desc='End B coordinates') self.add_input('turbine_tower_gamma', val=0.0, units='deg', desc='Twist angle about z-axis') self.add_input('turbine_tower_stations', val=np.zeros(turbine_npts), desc='Location of stations along axis, will be normalized along rA to rB') if turbine_opt['scalar_diameters']: self.add_input('turbine_tower_d', val=0.0, units='m', desc='Diameters if circular or side lengths if rectangular') else: if turbine_opt['shape'] == 'circ' or 'square': self.add_input('turbine_tower_d', val=np.zeros(turbine_npts), units='m', desc='Diameters if circular or side lengths if rectangular') elif turbine_opt['shape'] == 'rect': self.add_input('turbine_tower_d', val=np.zeros(2 * turbine_npts), units='m', desc='Diameters if circular or side lengths if rectangular') if turbine_opt['scalar_thicknesses']: self.add_input('turbine_tower_t', val=0.0, units='m', desc='Wall thicknesses at station locations') else: self.add_input('turbine_tower_t', val=np.zeros(turbine_npts), units='m', desc='Wall thicknesses at station locations') if turbine_opt['scalar_coefficients']: self.add_input('turbine_tower_Cd', val=0.0, desc='Transverse drag coefficient') self.add_input('turbine_tower_Ca', val=0.0, desc='Transverse added mass coefficient') self.add_input('turbine_tower_CdEnd', val=0.0, desc='End axial drag coefficient') self.add_input('turbine_tower_CaEnd', val=0.0, desc='End axial added mass coefficient') else: self.add_input('turbine_tower_Cd', val=np.zeros(turbine_npts), desc='Transverse drag coefficient') self.add_input('turbine_tower_Ca', val=np.zeros(turbine_npts), desc='Transverse added mass coefficient') self.add_input('turbine_tower_CdEnd', val=np.zeros(turbine_npts), desc='End axial drag coefficient') self.add_input('turbine_tower_CaEnd', val=np.zeros(turbine_npts), desc='End axial added mass coefficient') self.add_input('turbine_tower_rho_shell', val=0.0, units='kg/m**3', desc='Material density') # member inputs for i in range(1, nmembers + 1): mnpts = member_npts[i - 1] mnpts_lfill = member_npts_lfill[i - 1] mncaps = member_ncaps[i - 1] mnreps = member_nreps[i - 1] mshape = member_shape[i - 1] scalar_t = member_scalar_t[i - 1] scalar_d = member_scalar_d[i - 1] scalar_coeff = member_scalar_coeff[i - 1] m_name = f'platform_member{i}_' self.add_input(m_name+'heading', val=np.zeros(mnreps), units='deg', desc='Heading rotation of column about z axis (for repeated members)') self.add_input(m_name+'rA', val=np.zeros(ndim), units='m', desc='End A coordinates') self.add_input(m_name+'rB', val=np.zeros(ndim), units='m', desc='End B coordinates') self.add_input(m_name+'gamma', val=0.0, units='deg', desc='Twist angle about the member z axis') # ADD THIS AS AN OPTION IN WEIS self.add_discrete_input(m_name+'potMod', val=False, desc='Whether to model the member with potential flow') self.add_input(m_name+'stations', val=np.zeros(mnpts), desc='Location of stations along axis, will be normalized from end A to B') # updated version to better handle 'diameters' between circular and rectangular members if mshape == 'circ' or mshape == 'square': if scalar_d: self.add_input(m_name+'d', val=0.0, units='m', desc='Constant diameter of the whole member') else: self.add_input(m_name+'d', val=np.zeros(mnpts), units='m', desc='Diameters at each station along the member') elif mshape == 'rect': if scalar_d: self.add_input(m_name+'d', val=[0.0, 0.0], units='m', desc='Constant side lengths of the whole member') else: self.add_input(m_name+'d', val=np.zeros([mnpts,2]), units='m', desc='Side lengths at each station along the member') ''' original version of handling diameters if scalar_d: self.add_input(m_name+'d', val=0.0, units='m', desc='Diameters if circular, side lengths if rectangular') else: if mshape == 'circ' or 'square': self.add_input(m_name+'d', val=np.zeros(mnpts), units='m', desc='Diameters if circular, side lengths if rectangular') elif mshape == 'rect': self.add_input(m_name+'d', val=np.zeros(2 * mnpts), units='m', desc='Diameters if circular, side lengths if rectangular') ''' if scalar_t: self.add_input(m_name+'t', val=0.0, units='m', desc='Wall thicknesses') else: self.add_input(m_name+'t', val=np.zeros(mnpts), units='m', desc='Wall thicknesses') if scalar_coeff: self.add_input(m_name+'Cd', val=0.0, desc='Transverse drag coefficient') self.add_input(m_name+'Ca', val=0.0, desc='Transverse added mass coefficient') self.add_input(m_name+'CdEnd', val=0.0, desc='End axial drag coefficient') self.add_input(m_name+'CaEnd', val=0.0, desc='End axial added mass coefficient') else: self.add_input(m_name+'Cd', val=np.zeros(mnpts), desc='Transverse drag coefficient') self.add_input(m_name+'Ca', val=np.zeros(mnpts), desc='Transverse added mass coefficient') self.add_input(m_name+'CdEnd', val=np.zeros(mnpts), desc='End axial drag coefficient') self.add_input(m_name+'CaEnd', val=np.zeros(mnpts), desc='End axial added mass coefficient') self.add_input(m_name+'rho_shell', val=0.0, units='kg/m**3', desc='Material density') # optional self.add_input(m_name+'l_fill', val=np.zeros(mnpts_lfill), units='m', desc='Fill heights of ballast in each section') self.add_input(m_name+'rho_fill', val=np.zeros(mnpts_lfill), units='kg/m**3', desc='Material density of ballast in each section') self.add_input(m_name+'cap_stations', val=np.zeros(mncaps), desc='Location along member of any inner structures (same scaling as stations') self.add_input(m_name+'cap_t', val=np.zeros(mncaps), units='m', desc='Thickness of any internal structures') self.add_input(m_name+'cap_d_in', val=np.zeros(mncaps), units='m', desc='Inner diameter of internal structures') self.add_input(m_name+'ring_spacing', val=0.0, desc='Spacing of internal structures placed based on spacing. Dimension is same as used in stations') self.add_input(m_name+'ring_t', val=0.0, units='m', desc='Effective thickness of any internal structures placed based on spacing') self.add_input(m_name+'ring_h', val=0.0, units='m', desc='Effective web height of internal structures placed based on spacing') # mooring inputs self.add_input('mooring_water_depth', val=0.0, units='m', desc='Uniform water depth') # connection points for i in range(1, nconnections + 1): pt_name = f'mooring_point{i}_' self.add_discrete_input(pt_name+'name', val=f'line{i}', desc='Mooring point identifier') self.add_discrete_input(pt_name+'type', val='fixed', desc='Mooring connection type') self.add_input(pt_name+'location', val=np.zeros(ndim), units='m', desc='Coordinates of mooring connection') # lines for i in range(1, nlines + 1): pt_name = f'mooring_line{i}_' self.add_discrete_input(pt_name+'endA', val='default', desc='End A coordinates') self.add_discrete_input(pt_name+'endB', val='default', desc='End B coordinates') self.add_discrete_input(pt_name+'type', val='mooring_line_type1', desc='Mooring line type') self.add_input(pt_name+'length', val=0.0, units='m', desc='Length of line') # line types for i in range(1, nline_types + 1): lt_name = f'mooring_line_type{i}_' self.add_discrete_input(lt_name+'name', val='default', desc='Name of line type') self.add_input(lt_name+'diameter', val=0.0, units='m', desc='Diameter of mooring line type') self.add_input(lt_name+'mass_density', val=0.0, units='kg/m**3', desc='Mass density of line type') self.add_input(lt_name+'stiffness', val=0.0, desc='Stiffness of line type') self.add_input(lt_name+'breaking_load', val=0.0, desc='Breaking load of line type') self.add_input(lt_name+'cost', val=0.0, units='USD', desc='Cost of mooring line type') self.add_input(lt_name+'transverse_added_mass', val=0.0, desc='Transverse added mass') self.add_input(lt_name+'tangential_added_mass', val=0.0, desc='Tangential added mass') self.add_input(lt_name+'transverse_drag', val=0.0, desc='Transverse drag') self.add_input(lt_name+'tangential_drag', val=0.0, desc='Tangential drag') # outputs # properties nballast = np.sum(member_npts_rho_fill) self.add_output('properties_tower mass', units='kg', desc='Tower mass') self.add_output('properties_tower CG', val=np.zeros(ndim), units='m', desc='Tower center of gravity') self.add_output('properties_substructure mass', val=0.0, units='kg', desc='Substructure mass') self.add_output('properties_substructure CG', val=np.zeros(ndim), units='m', desc='Substructure center of gravity') self.add_output('properties_shell mass', val=0.0, units='kg', desc='Shell mass') self.add_output('properties_ballast mass', val=np.zeros(nballast), units='m', desc='Ballast mass') self.add_output('properties_ballast densities', val=np.zeros(nballast), units='kg', desc='Ballast densities') self.add_output('properties_total mass', val=0.0, units='kg', desc='Total mass of system') self.add_output('properties_total CG', val=np.zeros(ndim), units='m', desc='Total system center of gravity') self.add_output('properties_roll inertia at subCG', val=np.zeros(ndim), units='kg*m**2', desc='Roll inertia sub CG') self.add_output('properties_pitch inertia at subCG', val=np.zeros(ndim), units='kg*m**2', desc='Pitch inertia sub CG') self.add_output('properties_yaw inertia at subCG', val=np.zeros(ndim), units='kg*m**2', desc='Yaw inertia sub CG') self.add_output('properties_Buoyancy (pgV)', val=0.0, units='N', desc='Buoyancy (pgV)') self.add_output('properties_Center of Buoyancy', val=np.zeros(ndim), units='m', desc='Center of buoyancy') self.add_output('properties_C stiffness matrix', val=np.zeros((ndof,ndof)), units='Pa', desc='C stiffness matrix') self.add_output('properties_F_lines0', val=np.zeros(nconnections), units='N', desc='Mean mooring force') self.add_output('properties_C_lines0', val=np.zeros((ndof,ndof)), units='Pa', desc='Mooring stiffness') self.add_output('properties_M support structure', val=np.zeros((ndof,ndof)), units='kg', desc='Mass matrix for platform') self.add_output('properties_A support structure', val=np.zeros((ndof,ndof)), desc='Added mass matrix for platform') self.add_output('properties_C support structure', val=np.zeros((ndof,ndof)), units='Pa', desc='Stiffness matrix for platform') # response self.add_output('response_frequencies', val=np.zeros(nfreq), units='Hz', desc='Response frequencies') self.add_output('response_wave elevation', val=np.zeros(nfreq), units='m', desc='Wave elevation') self.add_output('response_surge RAO', val=np.zeros(nfreq), units='m', desc='Surge RAO') self.add_output('response_sway RAO', val=np.zeros(nfreq), units='m', desc='Sway RAO') self.add_output('response_heave RAO', val=np.zeros(nfreq), units='m', desc='Heave RAO') self.add_output('response_pitch RAO', val=np.zeros(nfreq), units='m', desc='Pitch RAO') self.add_output('response_roll RAO', val=np.zeros(nfreq), units='m', desc='Roll RAO') self.add_output('response_yaw RAO', val=np.zeros(nfreq), units='m', desc='Yaw RAO') self.add_output('response_nacelle acceleration', val=np.zeros(nfreq), units='m/s**2', desc='Nacelle acceleration') def compute(self, inputs, outputs, discrete_inputs, discrete_outputs): turbine_opt = self.options['turbine_options'] mooring_opt = self.options['mooring_options'] members_opt = self.options['member_options'] modeling_opt = self.options['modeling_options'] #turbine_npts = turbine_opt['npts'] nmembers = members_opt['nmembers'] member_npts = members_opt['npts'] member_npts_lfill = members_opt['npts_lfill'] #member_npts_rho_fill = members_opt['npts_rho_fill'] member_ncaps = members_opt['ncaps'] member_nreps = members_opt['nreps'] member_shapes = members_opt['shape'] member_scalar_t = members_opt['scalar_thicknesses'] member_scalar_d = members_opt['scalar_diameters'] member_scalar_coeff = members_opt['scalar_coefficients'] nlines = mooring_opt['nlines'] nline_types = mooring_opt['nline_types'] nconnections = mooring_opt['nconnections'] # set up design design = {} design['type'] = ['input dictionary for RAFT'] design['name'] = ['spiderfloat'] design['comments'] = ['none'] design['potModMaster'] = int(modeling_opt['potModMaster']) design['XiStart'] = float(modeling_opt['XiStart']) design['nIter'] = int(modeling_opt['nIter']) design['dlsMax'] = float(modeling_opt['dlsMax']) # TODO: these float conversions are messy design['turbine'] = {} design['turbine']['mRNA'] = float(inputs['turbine_mRNA']) design['turbine']['IxRNA'] = float(inputs['turbine_IxRNA']) design['turbine']['IrRNA'] = float(inputs['turbine_IrRNA']) design['turbine']['xCG_RNA'] = float(inputs['turbine_xCG_RNA']) design['turbine']['hHub'] = float(inputs['turbine_hHub']) design['turbine']['Fthrust'] = float(inputs['turbine_Fthrust']) design['turbine']['yaw_stiffness'] = float(inputs['turbine_yaw_stiffness']) design['turbine']['tower'] = {} design['turbine']['tower']['name'] = 'tower' design['turbine']['tower']['type'] = 1 design['turbine']['tower']['rA'] = inputs['turbine_tower_rA'] design['turbine']['tower']['rB'] = inputs['turbine_tower_rB'] design['turbine']['tower']['shape'] = turbine_opt['shape'] design['turbine']['tower']['gamma'] = inputs['turbine_tower_gamma'] design['turbine']['tower']['stations'] = inputs['turbine_tower_stations'] if turbine_opt['scalar_diameters']: design['turbine']['tower']['d'] = float(inputs['turbine_tower_d']) else: design['turbine']['tower']['d'] = inputs['turbine_tower_d'] if turbine_opt['scalar_thicknesses']: design['turbine']['tower']['t'] = float(inputs['turbine_tower_t']) else: design['turbine']['tower']['t'] = inputs['turbine_tower_t'] if turbine_opt['scalar_coefficients']: design['turbine']['tower']['Cd'] = float(inputs['turbine_tower_Cd']) design['turbine']['tower']['Ca'] = float(inputs['turbine_tower_Ca']) design['turbine']['tower']['CdEnd'] = float(inputs['turbine_tower_CdEnd']) design['turbine']['tower']['CaEnd'] = float(inputs['turbine_tower_CaEnd']) else: design['turbine']['tower']['Cd'] = inputs['turbine_tower_Cd'] design['turbine']['tower']['Ca'] = inputs['turbine_tower_Ca'] design['turbine']['tower']['CdEnd'] = inputs['turbine_tower_CdEnd'] design['turbine']['tower']['CaEnd'] = inputs['turbine_tower_CaEnd'] design['turbine']['tower']['rho_shell'] = float(inputs['turbine_tower_rho_shell']) design['platform'] = {} design['platform']['members'] = [dict() for i in range(nmembers)] for i in range(nmembers): m_name = f'platform_member{i+1}_' m_shape = member_shapes[i] mnpts_lfill = member_npts_lfill[i] mncaps = member_ncaps[i] mnreps = member_nreps[i] mnpts = member_npts[i] design['platform']['members'][i]['name'] = m_name design['platform']['members'][i]['type'] = i + 2 design['platform']['members'][i]['rA'] = inputs[m_name+'rA'] design['platform']['members'][i]['rB'] = inputs[m_name+'rB'] design['platform']['members'][i]['shape'] = m_shape design['platform']['members'][i]['gamma'] = float(inputs[m_name+'gamma']) design['platform']['members'][i]['potMod'] = discrete_inputs[m_name+'potMod'] design['platform']['members'][i]['stations'] = inputs[m_name+'stations'] # updated version to better handle 'diameters' between circular and rectangular members if m_shape == 'circ' or m_shape == 'square': if member_scalar_d[i]: design['platform']['members'][i]['d'] = [float(inputs[m_name+'d'])]*mnpts else: design['platform']['members'][i]['d'] = inputs[m_name+'d'] elif m_shape == 'rect': if member_scalar_d[i]: design['platform']['members'][i]['d'] = [inputs[m_name+'d']]*mnpts else: design['platform']['members'][i]['d'] = inputs[m_name+'d'] ''' original version of handling diameters if member_scalar_d[i]: design['platform']['members'][i]['d'] = float(inputs[m_name+'d']) else: design['platform']['members'][i]['d'] = inputs[m_name+'d'] ''' if member_scalar_t[i]: design['platform']['members'][i]['t'] = float(inputs[m_name+'t']) else: design['platform']['members'][i]['t'] = inputs[m_name+'t'] if member_scalar_coeff[i]: design['platform']['members'][i]['Cd'] = float(inputs[m_name+'Cd']) design['platform']['members'][i]['Ca'] = float(inputs[m_name+'Ca']) design['platform']['members'][i]['CdEnd'] = float(inputs[m_name+'CdEnd']) design['platform']['members'][i]['CaEnd'] = float(inputs[m_name+'CaEnd']) else: design['platform']['members'][i]['Cd'] = inputs[m_name+'Cd'] design['platform']['members'][i]['Ca'] = inputs[m_name+'Ca'] design['platform']['members'][i]['CdEnd'] = inputs[m_name+'CdEnd'] design['platform']['members'][i]['CaEnd'] = inputs[m_name+'CaEnd'] design['platform']['members'][i]['rho_shell'] = float(inputs[m_name+'rho_shell']) if mnreps > 0: design['platform']['members'][i]['heading'] = inputs[m_name+'heading'] if mnpts_lfill > 0: design['platform']['members'][i]['l_fill'] = inputs[m_name+'l_fill'] design['platform']['members'][i]['rho_fill'] = inputs[m_name+'rho_fill'] if ( (mncaps > 0) or (inputs[m_name+'ring_spacing'] > 0) ): # Member discretization s_grid = inputs[m_name+'stations'] s_height = s_grid[-1] - s_grid[0] # Get locations of internal structures based on spacing ring_spacing = inputs[m_name+'ring_spacing'] n_stiff = 0 if ring_spacing == 0.0 else int(np.floor(s_height / ring_spacing)) s_ring = (np.arange(1, n_stiff + 0.1) - 0.5) * (ring_spacing / s_height) #d_ring = np.interp(s_ring, s_grid, inputs[m_name+'d']) d_ring = np.interp(s_ring, s_grid, design['platform']['members'][i]['d']) # Combine internal structures based on spacing and defined positions s_cap = np.r_[s_ring, inputs[m_name+'cap_stations']] t_cap = np.r_[inputs[m_name+'ring_t']*np.ones(n_stiff), inputs[m_name+'cap_t']] di_cap = np.r_[d_ring-2*inputs[m_name+'ring_h'], inputs[m_name+'cap_d_in']] # Store vectors in sorted order isort = np.argsort(s_cap) design['platform']['members'][i]['cap_stations'] = s_cap[isort] design['platform']['members'][i]['cap_t'] = t_cap[isort] design['platform']['members'][i]['cap_d_in'] = di_cap[isort] design['mooring'] = {} design['mooring']['water_depth'] = inputs['mooring_water_depth'] design['mooring']['points'] = [dict() for i in range(nconnections)] for i in range(0, nconnections): pt_name = f'mooring_point{i+1}_' design['mooring']['points'][i]['name'] = discrete_inputs[pt_name+'name'] design['mooring']['points'][i]['type'] = discrete_inputs[pt_name+'type'] design['mooring']['points'][i]['location'] = inputs[pt_name+'location'] design['mooring']['lines'] = [dict() for i in range(nlines)] for i in range(0, nlines): ml_name = f'mooring_line{i+1}_' design['mooring']['lines'][i]['name'] = f'line{i+1}' design['mooring']['lines'][i]['endA'] = discrete_inputs[ml_name+'endA'] design['mooring']['lines'][i]['endB'] = discrete_inputs[ml_name+'endB'] design['mooring']['lines'][i]['type'] = discrete_inputs[ml_name+'type'] design['mooring']['lines'][i]['length'] = inputs[ml_name+'length'] design['mooring']['line_types'] = [dict() for i in range(nline_types)] for i in range(0, nline_types): lt_name = f'mooring_line_type{i+1}_' design['mooring']['line_types'][i]['name'] = discrete_inputs[lt_name+'name'] design['mooring']['line_types'][i]['diameter'] = float(inputs[lt_name+'diameter']) design['mooring']['line_types'][i]['mass_density'] = float(inputs[lt_name+'mass_density']) design['mooring']['line_types'][i]['stiffness'] = float(inputs[lt_name+'stiffness']) design['mooring']['line_types'][i]['breaking_load'] = float(inputs[lt_name+'breaking_load']) design['mooring']['line_types'][i]['cost'] = float(inputs[lt_name+'cost']) design['mooring']['line_types'][i]['transverse_added_mass'] = float(inputs[lt_name+'transverse_added_mass']) design['mooring']['line_types'][i]['tangential_added_mass'] = float(inputs[lt_name+'tangential_added_mass']) design['mooring']['line_types'][i]['transverse_drag'] = float(inputs[lt_name+'transverse_drag']) design['mooring']['line_types'][i]['tangential_drag'] = float(inputs[lt_name+'tangential_drag']) # grab the depth depth = float(design['mooring']['water_depth']) # set up frequency range for computing response over w = inputs['frequency_range'] # create and run the model model = raft.Model(design, w=w, depth=depth) model.setEnv(spectrum="unit") model.calcSystemProps() model.solveEigen() model.calcMooringAndOffsets() model.solveDynamics() results = model.calcOutputs() outs = self.list_outputs(values=False, out_stream=None) for i in range(len(outs)): if outs[i][0].startswith('properties_'): name = outs[i][0].split('properties_')[1] outputs['properties_'+name] = results['properties'][name] elif outs[i][0].startswith('response_'): name = outs[i][0].split('response_')[1] if np.iscomplex(results['response'][name]).any(): outputs['response_'+name] = np.abs(results['response'][name]) else: outputs['response_'+name] = results['response'][name]
import openmdao.api as om import raft import numpy as np ndim = 3 ndof = 6 class RAFT_OMDAO(om.ExplicitComponent): """ RAFT OpenMDAO Wrapper API """ def initialize(self): self.options.declare('modeling_options') self.options.declare('turbine_options') self.options.declare('mooring_options') self.options.declare('member_options') def setup(self): # unpack options modeling_opt = self.options['modeling_options'] nfreq = modeling_opt['nfreq'] turbine_opt = self.options['turbine_options'] turbine_npts = turbine_opt['npts'] members_opt = self.options['member_options'] nmembers = members_opt['nmembers'] member_npts = members_opt['npts'] member_npts_lfill = members_opt['npts_lfill'] member_npts_rho_fill = members_opt['npts_rho_fill'] member_ncaps = members_opt['ncaps'] member_nreps = members_opt['nreps'] member_shape = members_opt['shape'] member_scalar_t = members_opt['scalar_thicknesses'] member_scalar_d = members_opt['scalar_diameters'] member_scalar_coeff = members_opt['scalar_coefficients'] mooring_opt = self.options['mooring_options'] nlines = mooring_opt['nlines'] nline_types = mooring_opt['nline_types'] nconnections = mooring_opt['nconnections'] # frequency domain self.add_input('frequency_range', val=np.zeros(nfreq), units='Hz', desc='Frequency range to compute response over') # turbine inputs self.add_input('turbine_mRNA', val=0.0, units='kg', desc='RNA mass') self.add_input('turbine_IxRNA', val=0.0, units='kg*m**2', desc='RNA moment of inertia about local x axis') self.add_input('turbine_IrRNA', val=0.0, units='kg*m**2', desc='RNA moment of inertia about local y or z axes') self.add_input('turbine_xCG_RNA', val=0.0, units='m', desc='x location of RNA center of mass') self.add_input('turbine_hHub', val=0.0, units='m', desc='Hub height above water line') self.add_input('turbine_Fthrust', val=0.0, units='N', desc='Temporary thrust force to use') self.add_input('turbine_yaw_stiffness', val=0.0, units='N*m', desc='Additional yaw stiffness to apply if not modeling crowfoot in the mooring system') # tower inputs self.add_input('turbine_tower_rA', val=np.zeros(ndim), units='m', desc='End A coordinates') self.add_input('turbine_tower_rB', val=np.zeros(ndim), units='m', desc='End B coordinates') self.add_input('turbine_tower_gamma', val=0.0, units='deg', desc='Twist angle about z-axis') self.add_input('turbine_tower_stations', val=np.zeros(turbine_npts), desc='Location of stations along axis, will be normalized along rA to rB') if turbine_opt['scalar_diameters']: self.add_input('turbine_tower_d', val=0.0, units='m', desc='Diameters if circular or side lengths if rectangular') else: if turbine_opt['shape'] == 'circ' or 'square': self.add_input('turbine_tower_d', val=np.zeros(turbine_npts), units='m', desc='Diameters if circular or side lengths if rectangular') elif turbine_opt['shape'] == 'rect': self.add_input('turbine_tower_d', val=np.zeros(2 * turbine_npts), units='m', desc='Diameters if circular or side lengths if rectangular') if turbine_opt['scalar_thicknesses']: self.add_input('turbine_tower_t', val=0.0, units='m', desc='Wall thicknesses at station locations') else: self.add_input('turbine_tower_t', val=np.zeros(turbine_npts), units='m', desc='Wall thicknesses at station locations') if turbine_opt['scalar_coefficients']: self.add_input('turbine_tower_Cd', val=0.0, desc='Transverse drag coefficient') self.add_input('turbine_tower_Ca', val=0.0, desc='Transverse added mass coefficient') self.add_input('turbine_tower_CdEnd', val=0.0, desc='End axial drag coefficient') self.add_input('turbine_tower_CaEnd', val=0.0, desc='End axial added mass coefficient') else: self.add_input('turbine_tower_Cd', val=np.zeros(turbine_npts), desc='Transverse drag coefficient') self.add_input('turbine_tower_Ca', val=np.zeros(turbine_npts), desc='Transverse added mass coefficient') self.add_input('turbine_tower_CdEnd', val=np.zeros(turbine_npts), desc='End axial drag coefficient') self.add_input('turbine_tower_CaEnd', val=np.zeros(turbine_npts), desc='End axial added mass coefficient') self.add_input('turbine_tower_rho_shell', val=0.0, units='kg/m**3', desc='Material density') # member inputs for i in range(1, nmembers + 1): mnpts = member_npts[i - 1] mnpts_lfill = member_npts_lfill[i - 1] mncaps = member_ncaps[i - 1] mnreps = member_nreps[i - 1] mshape = member_shape[i - 1] scalar_t = member_scalar_t[i - 1] scalar_d = member_scalar_d[i - 1] scalar_coeff = member_scalar_coeff[i - 1] m_name = f'platform_member{i}_' self.add_input(m_name+'heading', val=np.zeros(mnreps), units='deg', desc='Heading rotation of column about z axis (for repeated members)') self.add_input(m_name+'rA', val=np.zeros(ndim), units='m', desc='End A coordinates') self.add_input(m_name+'rB', val=np.zeros(ndim), units='m', desc='End B coordinates') self.add_input(m_name+'gamma', val=0.0, units='deg', desc='Twist angle about the member z axis') # ADD THIS AS AN OPTION IN WEIS self.add_discrete_input(m_name+'potMod', val=False, desc='Whether to model the member with potential flow') self.add_input(m_name+'stations', val=np.zeros(mnpts), desc='Location of stations along axis, will be normalized from end A to B') # updated version to better handle 'diameters' between circular and rectangular members if mshape == 'circ' or mshape == 'square': if scalar_d: self.add_input(m_name+'d', val=0.0, units='m', desc='Constant diameter of the whole member') else: self.add_input(m_name+'d', val=np.zeros(mnpts), units='m', desc='Diameters at each station along the member') elif mshape == 'rect': if scalar_d: self.add_input(m_name+'d', val=[0.0, 0.0], units='m', desc='Constant side lengths of the whole member') else: self.add_input(m_name+'d', val=np.zeros([mnpts,2]), units='m', desc='Side lengths at each station along the member') ''' original version of handling diameters if scalar_d: self.add_input(m_name+'d', val=0.0, units='m', desc='Diameters if circular, side lengths if rectangular') else: if mshape == 'circ' or 'square': self.add_input(m_name+'d', val=np.zeros(mnpts), units='m', desc='Diameters if circular, side lengths if rectangular') elif mshape == 'rect': self.add_input(m_name+'d', val=np.zeros(2 * mnpts), units='m', desc='Diameters if circular, side lengths if rectangular') ''' if scalar_t: self.add_input(m_name+'t', val=0.0, units='m', desc='Wall thicknesses') else: self.add_input(m_name+'t', val=np.zeros(mnpts), units='m', desc='Wall thicknesses') if scalar_coeff: self.add_input(m_name+'Cd', val=0.0, desc='Transverse drag coefficient') self.add_input(m_name+'Ca', val=0.0, desc='Transverse added mass coefficient') self.add_input(m_name+'CdEnd', val=0.0, desc='End axial drag coefficient') self.add_input(m_name+'CaEnd', val=0.0, desc='End axial added mass coefficient') else: self.add_input(m_name+'Cd', val=np.zeros(mnpts), desc='Transverse drag coefficient') self.add_input(m_name+'Ca', val=np.zeros(mnpts), desc='Transverse added mass coefficient') self.add_input(m_name+'CdEnd', val=np.zeros(mnpts), desc='End axial drag coefficient') self.add_input(m_name+'CaEnd', val=np.zeros(mnpts), desc='End axial added mass coefficient') self.add_input(m_name+'rho_shell', val=0.0, units='kg/m**3', desc='Material density') # optional self.add_input(m_name+'l_fill', val=np.zeros(mnpts_lfill), units='m', desc='Fill heights of ballast in each section') self.add_input(m_name+'rho_fill', val=np.zeros(mnpts_lfill), units='kg/m**3', desc='Material density of ballast in each section') self.add_input(m_name+'cap_stations', val=np.zeros(mncaps), desc='Location along member of any inner structures (same scaling as stations') self.add_input(m_name+'cap_t', val=np.zeros(mncaps), units='m', desc='Thickness of any internal structures') self.add_input(m_name+'cap_d_in', val=np.zeros(mncaps), units='m', desc='Inner diameter of internal structures') self.add_input(m_name+'ring_spacing', val=0.0, desc='Spacing of internal structures placed based on spacing. Dimension is same as used in stations') self.add_input(m_name+'ring_t', val=0.0, units='m', desc='Effective thickness of any internal structures placed based on spacing') self.add_input(m_name+'ring_h', val=0.0, units='m', desc='Effective web height of internal structures placed based on spacing') # mooring inputs self.add_input('mooring_water_depth', val=0.0, units='m', desc='Uniform water depth') # connection points for i in range(1, nconnections + 1): pt_name = f'mooring_point{i}_' self.add_discrete_input(pt_name+'name', val=f'line{i}', desc='Mooring point identifier') self.add_discrete_input(pt_name+'type', val='fixed', desc='Mooring connection type') self.add_input(pt_name+'location', val=np.zeros(ndim), units='m', desc='Coordinates of mooring connection') # lines for i in range(1, nlines + 1): pt_name = f'mooring_line{i}_' self.add_discrete_input(pt_name+'endA', val='default', desc='End A coordinates') self.add_discrete_input(pt_name+'endB', val='default', desc='End B coordinates') self.add_discrete_input(pt_name+'type', val='mooring_line_type1', desc='Mooring line type') self.add_input(pt_name+'length', val=0.0, units='m', desc='Length of line') # line types for i in range(1, nline_types + 1): lt_name = f'mooring_line_type{i}_' self.add_discrete_input(lt_name+'name', val='default', desc='Name of line type') self.add_input(lt_name+'diameter', val=0.0, units='m', desc='Diameter of mooring line type') self.add_input(lt_name+'mass_density', val=0.0, units='kg/m**3', desc='Mass density of line type') self.add_input(lt_name+'stiffness', val=0.0, desc='Stiffness of line type') self.add_input(lt_name+'breaking_load', val=0.0, desc='Breaking load of line type') self.add_input(lt_name+'cost', val=0.0, units='USD', desc='Cost of mooring line type') self.add_input(lt_name+'transverse_added_mass', val=0.0, desc='Transverse added mass') self.add_input(lt_name+'tangential_added_mass', val=0.0, desc='Tangential added mass') self.add_input(lt_name+'transverse_drag', val=0.0, desc='Transverse drag') self.add_input(lt_name+'tangential_drag', val=0.0, desc='Tangential drag') # outputs # properties nballast = np.sum(member_npts_rho_fill) self.add_output('properties_tower mass', units='kg', desc='Tower mass') self.add_output('properties_tower CG', val=np.zeros(ndim), units='m', desc='Tower center of gravity') self.add_output('properties_substructure mass', val=0.0, units='kg', desc='Substructure mass') self.add_output('properties_substructure CG', val=np.zeros(ndim), units='m', desc='Substructure center of gravity') self.add_output('properties_shell mass', val=0.0, units='kg', desc='Shell mass') self.add_output('properties_ballast mass', val=np.zeros(nballast), units='m', desc='Ballast mass') self.add_output('properties_ballast densities', val=np.zeros(nballast), units='kg', desc='Ballast densities') self.add_output('properties_total mass', val=0.0, units='kg', desc='Total mass of system') self.add_output('properties_total CG', val=np.zeros(ndim), units='m', desc='Total system center of gravity') self.add_output('properties_roll inertia at subCG', val=np.zeros(ndim), units='kg*m**2', desc='Roll inertia sub CG') self.add_output('properties_pitch inertia at subCG', val=np.zeros(ndim), units='kg*m**2', desc='Pitch inertia sub CG') self.add_output('properties_yaw inertia at subCG', val=np.zeros(ndim), units='kg*m**2', desc='Yaw inertia sub CG') self.add_output('properties_Buoyancy (pgV)', val=0.0, units='N', desc='Buoyancy (pgV)') self.add_output('properties_Center of Buoyancy', val=np.zeros(ndim), units='m', desc='Center of buoyancy') self.add_output('properties_C stiffness matrix', val=np.zeros((ndof,ndof)), units='Pa', desc='C stiffness matrix') self.add_output('properties_F_lines0', val=np.zeros(nconnections), units='N', desc='Mean mooring force') self.add_output('properties_C_lines0', val=np.zeros((ndof,ndof)), units='Pa', desc='Mooring stiffness') self.add_output('properties_M support structure', val=np.zeros((ndof,ndof)), units='kg', desc='Mass matrix for platform') self.add_output('properties_A support structure', val=np.zeros((ndof,ndof)), desc='Added mass matrix for platform') self.add_output('properties_C support structure', val=np.zeros((ndof,ndof)), units='Pa', desc='Stiffness matrix for platform') # response self.add_output('response_frequencies', val=np.zeros(nfreq), units='Hz', desc='Response frequencies') self.add_output('response_wave elevation', val=np.zeros(nfreq), units='m', desc='Wave elevation') self.add_output('response_surge RAO', val=np.zeros(nfreq), units='m', desc='Surge RAO') self.add_output('response_sway RAO', val=np.zeros(nfreq), units='m', desc='Sway RAO') self.add_output('response_heave RAO', val=np.zeros(nfreq), units='m', desc='Heave RAO') self.add_output('response_pitch RAO', val=np.zeros(nfreq), units='m', desc='Pitch RAO') self.add_output('response_roll RAO', val=np.zeros(nfreq), units='m', desc='Roll RAO') self.add_output('response_yaw RAO', val=np.zeros(nfreq), units='m', desc='Yaw RAO') self.add_output('response_nacelle acceleration', val=np.zeros(nfreq), units='m/s**2', desc='Nacelle acceleration') def compute(self, inputs, outputs, discrete_inputs, discrete_outputs): turbine_opt = self.options['turbine_options'] mooring_opt = self.options['mooring_options'] members_opt = self.options['member_options'] modeling_opt = self.options['modeling_options'] #turbine_npts = turbine_opt['npts'] nmembers = members_opt['nmembers'] member_npts = members_opt['npts'] member_npts_lfill = members_opt['npts_lfill'] #member_npts_rho_fill = members_opt['npts_rho_fill'] member_ncaps = members_opt['ncaps'] member_nreps = members_opt['nreps'] member_shapes = members_opt['shape'] member_scalar_t = members_opt['scalar_thicknesses'] member_scalar_d = members_opt['scalar_diameters'] member_scalar_coeff = members_opt['scalar_coefficients'] nlines = mooring_opt['nlines'] nline_types = mooring_opt['nline_types'] nconnections = mooring_opt['nconnections'] # set up design design = {} design['type'] = ['input dictionary for RAFT'] design['name'] = ['spiderfloat'] design['comments'] = ['none'] design['potModMaster'] = int(modeling_opt['potModMaster']) design['XiStart'] = float(modeling_opt['XiStart']) design['nIter'] = int(modeling_opt['nIter']) design['dlsMax'] = float(modeling_opt['dlsMax']) # TODO: these float conversions are messy design['turbine'] = {} design['turbine']['mRNA'] = float(inputs['turbine_mRNA']) design['turbine']['IxRNA'] = float(inputs['turbine_IxRNA']) design['turbine']['IrRNA'] = float(inputs['turbine_IrRNA']) design['turbine']['xCG_RNA'] = float(inputs['turbine_xCG_RNA']) design['turbine']['hHub'] = float(inputs['turbine_hHub']) design['turbine']['Fthrust'] = float(inputs['turbine_Fthrust']) design['turbine']['yaw_stiffness'] = float(inputs['turbine_yaw_stiffness']) design['turbine']['tower'] = {} design['turbine']['tower']['name'] = 'tower' design['turbine']['tower']['type'] = 1 design['turbine']['tower']['rA'] = inputs['turbine_tower_rA'] design['turbine']['tower']['rB'] = inputs['turbine_tower_rB'] design['turbine']['tower']['shape'] = turbine_opt['shape'] design['turbine']['tower']['gamma'] = inputs['turbine_tower_gamma'] design['turbine']['tower']['stations'] = inputs['turbine_tower_stations'] if turbine_opt['scalar_diameters']: design['turbine']['tower']['d'] = float(inputs['turbine_tower_d']) else: design['turbine']['tower']['d'] = inputs['turbine_tower_d'] if turbine_opt['scalar_thicknesses']: design['turbine']['tower']['t'] = float(inputs['turbine_tower_t']) else: design['turbine']['tower']['t'] = inputs['turbine_tower_t'] if turbine_opt['scalar_coefficients']: design['turbine']['tower']['Cd'] = float(inputs['turbine_tower_Cd']) design['turbine']['tower']['Ca'] = float(inputs['turbine_tower_Ca']) design['turbine']['tower']['CdEnd'] = float(inputs['turbine_tower_CdEnd']) design['turbine']['tower']['CaEnd'] = float(inputs['turbine_tower_CaEnd']) else: design['turbine']['tower']['Cd'] = inputs['turbine_tower_Cd'] design['turbine']['tower']['Ca'] = inputs['turbine_tower_Ca'] design['turbine']['tower']['CdEnd'] = inputs['turbine_tower_CdEnd'] design['turbine']['tower']['CaEnd'] = inputs['turbine_tower_CaEnd'] design['turbine']['tower']['rho_shell'] = float(inputs['turbine_tower_rho_shell']) design['platform'] = {} design['platform']['members'] = [dict() for i in range(nmembers)] for i in range(nmembers): m_name = f'platform_member{i+1}_' m_shape = member_shapes[i] mnpts_lfill = member_npts_lfill[i] mncaps = member_ncaps[i] mnreps = member_nreps[i] mnpts = member_npts[i] design['platform']['members'][i]['name'] = m_name design['platform']['members'][i]['type'] = i + 2 design['platform']['members'][i]['rA'] = inputs[m_name+'rA'] design['platform']['members'][i]['rB'] = inputs[m_name+'rB'] design['platform']['members'][i]['shape'] = m_shape design['platform']['members'][i]['gamma'] = float(inputs[m_name+'gamma']) design['platform']['members'][i]['potMod'] = discrete_inputs[m_name+'potMod'] design['platform']['members'][i]['stations'] = inputs[m_name+'stations'] # updated version to better handle 'diameters' between circular and rectangular members if m_shape == 'circ' or m_shape == 'square': if member_scalar_d[i]: design['platform']['members'][i]['d'] = [float(inputs[m_name+'d'])]*mnpts else: design['platform']['members'][i]['d'] = inputs[m_name+'d'] elif m_shape == 'rect': if member_scalar_d[i]: design['platform']['members'][i]['d'] = [inputs[m_name+'d']]*mnpts else: design['platform']['members'][i]['d'] = inputs[m_name+'d'] ''' original version of handling diameters if member_scalar_d[i]: design['platform']['members'][i]['d'] = float(inputs[m_name+'d']) else: design['platform']['members'][i]['d'] = inputs[m_name+'d'] ''' if member_scalar_t[i]: design['platform']['members'][i]['t'] = float(inputs[m_name+'t']) else: design['platform']['members'][i]['t'] = inputs[m_name+'t'] if member_scalar_coeff[i]: design['platform']['members'][i]['Cd'] = float(inputs[m_name+'Cd']) design['platform']['members'][i]['Ca'] = float(inputs[m_name+'Ca']) design['platform']['members'][i]['CdEnd'] = float(inputs[m_name+'CdEnd']) design['platform']['members'][i]['CaEnd'] = float(inputs[m_name+'CaEnd']) else: design['platform']['members'][i]['Cd'] = inputs[m_name+'Cd'] design['platform']['members'][i]['Ca'] = inputs[m_name+'Ca'] design['platform']['members'][i]['CdEnd'] = inputs[m_name+'CdEnd'] design['platform']['members'][i]['CaEnd'] = inputs[m_name+'CaEnd'] design['platform']['members'][i]['rho_shell'] = float(inputs[m_name+'rho_shell']) if mnreps > 0: design['platform']['members'][i]['heading'] = inputs[m_name+'heading'] if mnpts_lfill > 0: design['platform']['members'][i]['l_fill'] = inputs[m_name+'l_fill'] design['platform']['members'][i]['rho_fill'] = inputs[m_name+'rho_fill'] if ( (mncaps > 0) or (inputs[m_name+'ring_spacing'] > 0) ): # Member discretization s_grid = inputs[m_name+'stations'] s_height = s_grid[-1] - s_grid[0] # Get locations of internal structures based on spacing ring_spacing = inputs[m_name+'ring_spacing'] n_stiff = 0 if ring_spacing == 0.0 else int(np.floor(s_height / ring_spacing)) s_ring = (np.arange(1, n_stiff + 0.1) - 0.5) * (ring_spacing / s_height) #d_ring = np.interp(s_ring, s_grid, inputs[m_name+'d']) d_ring = np.interp(s_ring, s_grid, design['platform']['members'][i]['d']) # Combine internal structures based on spacing and defined positions s_cap = np.r_[s_ring, inputs[m_name+'cap_stations']] t_cap = np.r_[inputs[m_name+'ring_t']*np.ones(n_stiff), inputs[m_name+'cap_t']] di_cap = np.r_[d_ring-2*inputs[m_name+'ring_h'], inputs[m_name+'cap_d_in']] # Store vectors in sorted order isort = np.argsort(s_cap) design['platform']['members'][i]['cap_stations'] = s_cap[isort] design['platform']['members'][i]['cap_t'] = t_cap[isort] design['platform']['members'][i]['cap_d_in'] = di_cap[isort] design['mooring'] = {} design['mooring']['water_depth'] = inputs['mooring_water_depth'] design['mooring']['points'] = [dict() for i in range(nconnections)] for i in range(0, nconnections): pt_name = f'mooring_point{i+1}_' design['mooring']['points'][i]['name'] = discrete_inputs[pt_name+'name'] design['mooring']['points'][i]['type'] = discrete_inputs[pt_name+'type'] design['mooring']['points'][i]['location'] = inputs[pt_name+'location'] design['mooring']['lines'] = [dict() for i in range(nlines)] for i in range(0, nlines): ml_name = f'mooring_line{i+1}_' design['mooring']['lines'][i]['name'] = f'line{i+1}' design['mooring']['lines'][i]['endA'] = discrete_inputs[ml_name+'endA'] design['mooring']['lines'][i]['endB'] = discrete_inputs[ml_name+'endB'] design['mooring']['lines'][i]['type'] = discrete_inputs[ml_name+'type'] design['mooring']['lines'][i]['length'] = inputs[ml_name+'length'] design['mooring']['line_types'] = [dict() for i in range(nline_types)] for i in range(0, nline_types): lt_name = f'mooring_line_type{i+1}_' design['mooring']['line_types'][i]['name'] = discrete_inputs[lt_name+'name'] design['mooring']['line_types'][i]['diameter'] = float(inputs[lt_name+'diameter']) design['mooring']['line_types'][i]['mass_density'] = float(inputs[lt_name+'mass_density']) design['mooring']['line_types'][i]['stiffness'] = float(inputs[lt_name+'stiffness']) design['mooring']['line_types'][i]['breaking_load'] = float(inputs[lt_name+'breaking_load']) design['mooring']['line_types'][i]['cost'] = float(inputs[lt_name+'cost']) design['mooring']['line_types'][i]['transverse_added_mass'] = float(inputs[lt_name+'transverse_added_mass']) design['mooring']['line_types'][i]['tangential_added_mass'] = float(inputs[lt_name+'tangential_added_mass']) design['mooring']['line_types'][i]['transverse_drag'] = float(inputs[lt_name+'transverse_drag']) design['mooring']['line_types'][i]['tangential_drag'] = float(inputs[lt_name+'tangential_drag']) # grab the depth depth = float(design['mooring']['water_depth']) # set up frequency range for computing response over w = inputs['frequency_range'] # create and run the model model = raft.Model(design, w=w, depth=depth) model.setEnv(spectrum="unit") model.calcSystemProps() model.solveEigen() model.calcMooringAndOffsets() model.solveDynamics() results = model.calcOutputs() outs = self.list_outputs(values=False, out_stream=None) for i in range(len(outs)): if outs[i][0].startswith('properties_'): name = outs[i][0].split('properties_')[1] outputs['properties_'+name] = results['properties'][name] elif outs[i][0].startswith('response_'): name = outs[i][0].split('response_')[1] if np.iscomplex(results['response'][name]).any(): outputs['response_'+name] = np.abs(results['response'][name]) else: outputs['response_'+name] = results['response'][name]
en
0.630849
RAFT OpenMDAO Wrapper API # unpack options # frequency domain # turbine inputs # tower inputs # member inputs # ADD THIS AS AN OPTION IN WEIS # updated version to better handle 'diameters' between circular and rectangular members original version of handling diameters if scalar_d: self.add_input(m_name+'d', val=0.0, units='m', desc='Diameters if circular, side lengths if rectangular') else: if mshape == 'circ' or 'square': self.add_input(m_name+'d', val=np.zeros(mnpts), units='m', desc='Diameters if circular, side lengths if rectangular') elif mshape == 'rect': self.add_input(m_name+'d', val=np.zeros(2 * mnpts), units='m', desc='Diameters if circular, side lengths if rectangular') # optional # mooring inputs # connection points # lines # line types # outputs # properties # response #turbine_npts = turbine_opt['npts'] #member_npts_rho_fill = members_opt['npts_rho_fill'] # set up design # TODO: these float conversions are messy # updated version to better handle 'diameters' between circular and rectangular members original version of handling diameters if member_scalar_d[i]: design['platform']['members'][i]['d'] = float(inputs[m_name+'d']) else: design['platform']['members'][i]['d'] = inputs[m_name+'d'] # Member discretization # Get locations of internal structures based on spacing #d_ring = np.interp(s_ring, s_grid, inputs[m_name+'d']) # Combine internal structures based on spacing and defined positions # Store vectors in sorted order # grab the depth # set up frequency range for computing response over # create and run the model
2.484585
2
cogs/commands/misc/subnews.py
DiscordGIR/Bloo
34
6622367
<reponame>DiscordGIR/Bloo import discord from discord.commands import slash_command from discord.ext import commands import traceback from data.services.guild_service import guild_service from utils.config import cfg from utils.logger import logger from utils.context import BlooContext, PromptData from utils.permissions.checks import PermissionsFailure, submod_or_admin_and_up from utils.permissions.slash_perms import slash_perms from utils.views.prompt import GenericDescriptionModal class SubNews(commands.Cog): def __init__(self, bot): self.bot = bot @submod_or_admin_and_up() @slash_command(guild_ids=[cfg.guild_id], description="Post a new subreddit news post", permissions=slash_perms.submod_or_admin_and_up()) async def subnews(self, ctx: BlooContext, image: discord.Option(discord.Attachment, required=False, description="Image to show in embed")): """Posts a new subreddit news post Example usage ------------- /subnews """ db_guild = guild_service.get_guild() channel = ctx.guild.get_channel(db_guild.channel_subnews) if not channel: raise commands.BadArgument("A subreddit news channel was not found. Contact Slim.") subnews = ctx.guild.get_role(db_guild.role_sub_news) if not subnews: raise commands.BadArgument("A subbredit news role was not found. Conact Slim") modal = GenericDescriptionModal(author=ctx.author, title=f"New sub news post") await ctx.interaction.response.send_modal(modal) await modal.wait() description = modal.value if not description: await ctx.send_warning("Cancelled adding meme.") return body = f"{subnews.mention} New Subreddit news post!\n\n{description}" if image is not None: # ensure the attached file is an image _type = image.content_type if _type not in ["image/png", "image/jpeg", "image/gif", "image/webp"]: raise commands.BadArgument("Attached file was not an image.") f = await image.to_file() else: f = None await channel.send(content=body, file=f) await ctx.send_success("Posted subreddit news post!", delete_after=5, followup=True) @subnews.error async def info_error(self, ctx: BlooContext, error): if isinstance(error, discord.ApplicationCommandInvokeError): error = error.original if (isinstance(error, commands.MissingRequiredArgument) or isinstance(error, PermissionsFailure) or isinstance(error, commands.BadArgument) or isinstance(error, commands.BadUnionArgument) or isinstance(error, commands.MissingPermissions) or isinstance(error, commands.BotMissingPermissions) or isinstance(error, commands.MaxConcurrencyReached) or isinstance(error, commands.NoPrivateMessage)): await ctx.send_error(error) else: await ctx.send_error("A fatal error occured. Tell <@109705860275539968> about this.") logger.error(traceback.format_exc()) def setup(bot): bot.add_cog(SubNews(bot))
import discord from discord.commands import slash_command from discord.ext import commands import traceback from data.services.guild_service import guild_service from utils.config import cfg from utils.logger import logger from utils.context import BlooContext, PromptData from utils.permissions.checks import PermissionsFailure, submod_or_admin_and_up from utils.permissions.slash_perms import slash_perms from utils.views.prompt import GenericDescriptionModal class SubNews(commands.Cog): def __init__(self, bot): self.bot = bot @submod_or_admin_and_up() @slash_command(guild_ids=[cfg.guild_id], description="Post a new subreddit news post", permissions=slash_perms.submod_or_admin_and_up()) async def subnews(self, ctx: BlooContext, image: discord.Option(discord.Attachment, required=False, description="Image to show in embed")): """Posts a new subreddit news post Example usage ------------- /subnews """ db_guild = guild_service.get_guild() channel = ctx.guild.get_channel(db_guild.channel_subnews) if not channel: raise commands.BadArgument("A subreddit news channel was not found. Contact Slim.") subnews = ctx.guild.get_role(db_guild.role_sub_news) if not subnews: raise commands.BadArgument("A subbredit news role was not found. Conact Slim") modal = GenericDescriptionModal(author=ctx.author, title=f"New sub news post") await ctx.interaction.response.send_modal(modal) await modal.wait() description = modal.value if not description: await ctx.send_warning("Cancelled adding meme.") return body = f"{subnews.mention} New Subreddit news post!\n\n{description}" if image is not None: # ensure the attached file is an image _type = image.content_type if _type not in ["image/png", "image/jpeg", "image/gif", "image/webp"]: raise commands.BadArgument("Attached file was not an image.") f = await image.to_file() else: f = None await channel.send(content=body, file=f) await ctx.send_success("Posted subreddit news post!", delete_after=5, followup=True) @subnews.error async def info_error(self, ctx: BlooContext, error): if isinstance(error, discord.ApplicationCommandInvokeError): error = error.original if (isinstance(error, commands.MissingRequiredArgument) or isinstance(error, PermissionsFailure) or isinstance(error, commands.BadArgument) or isinstance(error, commands.BadUnionArgument) or isinstance(error, commands.MissingPermissions) or isinstance(error, commands.BotMissingPermissions) or isinstance(error, commands.MaxConcurrencyReached) or isinstance(error, commands.NoPrivateMessage)): await ctx.send_error(error) else: await ctx.send_error("A fatal error occured. Tell <@109705860275539968> about this.") logger.error(traceback.format_exc()) def setup(bot): bot.add_cog(SubNews(bot))
en
0.786572
Posts a new subreddit news post Example usage ------------- /subnews # ensure the attached file is an image
2.436906
2
week1/main.py
GalsenDev221/python.weekly
5
6622368
<filename>week1/main.py # author @daoodaba975 # GalsenDev n = int(input("Entrez le nombre pour lequel afficher le tableau de multiplication:")) for i in range(1, 11): print(n, "*", i, "=", n*i)
<filename>week1/main.py # author @daoodaba975 # GalsenDev n = int(input("Entrez le nombre pour lequel afficher le tableau de multiplication:")) for i in range(1, 11): print(n, "*", i, "=", n*i)
en
0.468605
# author @daoodaba975 # GalsenDev
3.761944
4
tests/test_comment.py
EugeneZnm/BLOG-IT
0
6622369
import unittest from app.models import Comments class CommentsModelTest(unittest.TestCase): def setUp(self): self.new_comment = Comments(comment='interesting article') # test instantiation of comment def test_instance(self): self.assertEqual(self.new_comment.comment, 'interesting article') # test comment saving def test_save_comment(self): self.new_comment.save_comment() self.assertTrue(len(Comments.query.all()) > 0) # test getting comment by id def test_get_comment_by_id(self): self.new_comment.save_comment() got_comment = Comments.get_comment(1) self.assertTrue(len(got_comment) > 0) # test comment deletion def test_delete_comment(self): self.new_comment.delete_comment() self.assertTrue(len(Comments.query.id()) > 0)
import unittest from app.models import Comments class CommentsModelTest(unittest.TestCase): def setUp(self): self.new_comment = Comments(comment='interesting article') # test instantiation of comment def test_instance(self): self.assertEqual(self.new_comment.comment, 'interesting article') # test comment saving def test_save_comment(self): self.new_comment.save_comment() self.assertTrue(len(Comments.query.all()) > 0) # test getting comment by id def test_get_comment_by_id(self): self.new_comment.save_comment() got_comment = Comments.get_comment(1) self.assertTrue(len(got_comment) > 0) # test comment deletion def test_delete_comment(self): self.new_comment.delete_comment() self.assertTrue(len(Comments.query.id()) > 0)
en
0.738595
# test instantiation of comment # test comment saving # test getting comment by id # test comment deletion
3.382008
3
src/setup.py
AchWoDu/msfs-parking-brake-toggler
1
6622370
<filename>src/setup.py # Konfigurieren und auf shell aufrufen: python setup.py py2exe from distutils.core import setup import py2exe setup(console=['main.py'])
<filename>src/setup.py # Konfigurieren und auf shell aufrufen: python setup.py py2exe from distutils.core import setup import py2exe setup(console=['main.py'])
de
0.979531
# Konfigurieren und auf shell aufrufen: python setup.py py2exe
1.330258
1
livechat/tests/test_agent_rtm_client.py
livechat/lc-sdk-python
5
6622371
<reponame>livechat/lc-sdk-python ''' Tests for Agent RTM client. ''' # pylint: disable=E1120,W0621,C0103 import pytest from livechat.agent.rtm.client import AgentRTM def test_get_client_with_non_existing_version(): ''' Test if ValueError raised for non-existing version. ''' with pytest.raises(ValueError) as exception: AgentRTM.get_client(version='2.9') assert str(exception.value) == 'Provided version does not exist.' def test_get_client(): ''' Test if created client opens and closes socket in default url. ''' client = AgentRTM.get_client() client.open_connection() opened_state = client.ws.keep_running client_url = client.ws.url client.close_connection() closed_state = client.ws.keep_running assert client_url == 'wss://api.livechatinc.com/v3.3/agent/rtm/ws', 'Incorrect WS address.' assert opened_state is True, 'Client did not open socket.' assert closed_state is False, 'Client did not close socket.' def test_client_logs_in_with_token(): ''' Test if created client can send request. ''' client = AgentRTM.get_client() client.open_connection() response = client.login(token='Bearer 10386012') client.close_connection() assert response['response']['payload'] == { 'error': { 'type': 'authentication', 'message': 'Invalid access token' } }, 'Request was not sent.' def test_client_logs_in_with_payload(): ''' Test if created client can send request. ''' client = AgentRTM.get_client() client.open_connection() response = client.login(payload={ 'customer_push_level': 'online', 'token': 'Bearer 10386012' }) client.close_connection() assert response['response']['payload'] == { 'error': { 'type': 'authentication', 'message': 'Invalid access token' } }, 'Request was not sent.'
''' Tests for Agent RTM client. ''' # pylint: disable=E1120,W0621,C0103 import pytest from livechat.agent.rtm.client import AgentRTM def test_get_client_with_non_existing_version(): ''' Test if ValueError raised for non-existing version. ''' with pytest.raises(ValueError) as exception: AgentRTM.get_client(version='2.9') assert str(exception.value) == 'Provided version does not exist.' def test_get_client(): ''' Test if created client opens and closes socket in default url. ''' client = AgentRTM.get_client() client.open_connection() opened_state = client.ws.keep_running client_url = client.ws.url client.close_connection() closed_state = client.ws.keep_running assert client_url == 'wss://api.livechatinc.com/v3.3/agent/rtm/ws', 'Incorrect WS address.' assert opened_state is True, 'Client did not open socket.' assert closed_state is False, 'Client did not close socket.' def test_client_logs_in_with_token(): ''' Test if created client can send request. ''' client = AgentRTM.get_client() client.open_connection() response = client.login(token='Bearer 10386012') client.close_connection() assert response['response']['payload'] == { 'error': { 'type': 'authentication', 'message': 'Invalid access token' } }, 'Request was not sent.' def test_client_logs_in_with_payload(): ''' Test if created client can send request. ''' client = AgentRTM.get_client() client.open_connection() response = client.login(payload={ 'customer_push_level': 'online', 'token': 'Bearer 10386012' }) client.close_connection() assert response['response']['payload'] == { 'error': { 'type': 'authentication', 'message': 'Invalid access token' } }, 'Request was not sent.'
en
0.755082
Tests for Agent RTM client. # pylint: disable=E1120,W0621,C0103 Test if ValueError raised for non-existing version. Test if created client opens and closes socket in default url. Test if created client can send request. Test if created client can send request.
2.3156
2
install_list.py
dgabbe/rconfig
2
6622372
<reponame>dgabbe/rconfig<filename>install_list.py # For rprofile.site. scripts = [ [".Renviron", "dot-Renviron"], ["Rprofile.site", "Rprofile.site"] ]
# For rprofile.site. scripts = [ [".Renviron", "dot-Renviron"], ["Rprofile.site", "Rprofile.site"] ]
hr
0.103399
# For rprofile.site.
1.172802
1
test_find_path.py
SanjoSolutions/planing
0
6622373
<gh_stars>0 import unittest from find_path import find_path class TestFindPath(unittest.TestCase): def test_find_path(self): space = ( (1, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 2) ) from_position = determine_from_position(space) to_position = determine_to_position(space) path = find_path(space, from_position, to_position) self.assertEqual( ( (1, 0), (2, 0), (3, 0), (3, 1), (3, 2) ), path ) def test_find_path_with_obstacle(self): space = ( (1, 0, 3, 0), (0, 0, 0, 0), (0, 0, 0, 2) ) from_position = determine_from_position(space) to_position = determine_to_position(space) path = find_path(space, from_position, to_position) self.assertEqual( ( (1, 0), (1, 1), (2, 1), (3, 1), (3, 2) ), path ) def test_find_path_with_obstacles(self): space = ( (1, 0, 3, 0), (0, 0, 3, 0), (0, 3, 0, 0), (0, 0, 0, 2) ) from_position = determine_from_position(space) to_position = determine_to_position(space) path = find_path(space, from_position, to_position) self.assertEqual( ( (0, 1), (0, 2), (0, 3), (1, 3), (2, 3), (3, 3) ), path ) def test_find_path_going_up(self): space = ( (2,), (1,) ) from_position = determine_from_position(space) to_position = determine_to_position(space) path = find_path(space, from_position, to_position) self.assertEqual( ( (0, 0), ), path ) def test_find_path_going_left(self): space = ( (2, 1), ) from_position = determine_from_position(space) to_position = determine_to_position(space) path = find_path(space, from_position, to_position) self.assertEqual( ( (0, 0), ), path ) def test_find_path_zero_paths(self): space = ( (1, 3, 2), ) from_position = determine_from_position(space) to_position = determine_to_position(space) path = find_path(space, from_position, to_position) self.assertEqual( None, path ) def determine_from_position(space): return find_value(space, 1) def determine_to_position(space): return find_value(space, 2) def find_value(space, value): for y in range(len(space)): for x in range(len(space[0])): if space[y][x] == value: return (x, y) return None if __name__ == '__main__': unittest.main()
import unittest from find_path import find_path class TestFindPath(unittest.TestCase): def test_find_path(self): space = ( (1, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 2) ) from_position = determine_from_position(space) to_position = determine_to_position(space) path = find_path(space, from_position, to_position) self.assertEqual( ( (1, 0), (2, 0), (3, 0), (3, 1), (3, 2) ), path ) def test_find_path_with_obstacle(self): space = ( (1, 0, 3, 0), (0, 0, 0, 0), (0, 0, 0, 2) ) from_position = determine_from_position(space) to_position = determine_to_position(space) path = find_path(space, from_position, to_position) self.assertEqual( ( (1, 0), (1, 1), (2, 1), (3, 1), (3, 2) ), path ) def test_find_path_with_obstacles(self): space = ( (1, 0, 3, 0), (0, 0, 3, 0), (0, 3, 0, 0), (0, 0, 0, 2) ) from_position = determine_from_position(space) to_position = determine_to_position(space) path = find_path(space, from_position, to_position) self.assertEqual( ( (0, 1), (0, 2), (0, 3), (1, 3), (2, 3), (3, 3) ), path ) def test_find_path_going_up(self): space = ( (2,), (1,) ) from_position = determine_from_position(space) to_position = determine_to_position(space) path = find_path(space, from_position, to_position) self.assertEqual( ( (0, 0), ), path ) def test_find_path_going_left(self): space = ( (2, 1), ) from_position = determine_from_position(space) to_position = determine_to_position(space) path = find_path(space, from_position, to_position) self.assertEqual( ( (0, 0), ), path ) def test_find_path_zero_paths(self): space = ( (1, 3, 2), ) from_position = determine_from_position(space) to_position = determine_to_position(space) path = find_path(space, from_position, to_position) self.assertEqual( None, path ) def determine_from_position(space): return find_value(space, 1) def determine_to_position(space): return find_value(space, 2) def find_value(space, value): for y in range(len(space)): for x in range(len(space[0])): if space[y][x] == value: return (x, y) return None if __name__ == '__main__': unittest.main()
none
1
3.671081
4
maxatac/utilities/training_tools.py
tacazares/maxATAC
5
6622374
import random import sys from os import path import tensorflow as tf import numpy as np import pandas as pd from Bio.Seq import Seq import threading import pybedtools import os import glob from maxatac.architectures.dcnn import get_dilated_cnn from maxatac.utilities.constants import BP_RESOLUTION, BATCH_SIZE, CHR_POOL_SIZE, INPUT_LENGTH, INPUT_CHANNELS, \ BP_ORDER, TRAIN_SCALE_SIGNAL, BLACKLISTED_REGIONS, DEFAULT_CHROM_SIZES from maxatac.utilities.genome_tools import load_bigwig, load_2bit, get_one_hot_encoded, build_chrom_sizes_dict from maxatac.utilities.system_tools import get_dir, remove_tags, replace_extension class MaxATACModel(object): """ This object will organize the input model parameters and initialize the maxATAC model The methods are: __get_interpretation_attributes: This will import the interpretation inputs if interpretation module is being used. __get_model: This will get the correct architecture and parameters based on the user input """ def __init__(self, arch, seed, output_directory, prefix, threads, meta_path, weights, dense=False, target_scale_factor=TRAIN_SCALE_SIGNAL, output_activation="sigmoid", interpret=False, interpret_cell_type="" ): """ Initialize the maxATAC model with the input parameters and architecture :param arch: Neural network architecture to use: DCNN, resNet, UNet, multi-modal :param seed: Random seed to use :param output_directory: Path to output directory :param prefix: Prefix to use for filename :param threads: Number of threads to use :param meta_path: Path to the meta file associated with the run :param output_activation: The activation function to use in the output layer :param dense: Whether to use a dense layer on output :param weights: Input weights to use for model :param interpret: Boolean for whether this is training or interpretation """ self.arch = arch self.seed = seed self.output_directory = get_dir(output_directory) self.model_filename = prefix + "_{epoch}" + ".h5" self.results_location = path.join(self.output_directory, self.model_filename) self.log_location = replace_extension(remove_tags(self.results_location, "_{epoch}"), ".csv") self.tensor_board_log_dir = get_dir(path.join(self.output_directory, "tensorboard")) self.threads = threads self.training_history = "" self.meta_path = meta_path self.output_activation = output_activation self.dense = dense self.weights = weights self.target_scale_factor = target_scale_factor # Set the random seed for the model random.seed(seed) # Import meta txt as dataframe self.meta_dataframe = pd.read_csv(self.meta_path, sep='\t', header=0, index_col=None) # Find the unique number of cell types in the meta file self.cell_types = self.meta_dataframe["Cell_Line"].unique().tolist() self.train_tf = self.meta_dataframe["TF"].unique()[0] self.nn_model = self.__get_model() if interpret: assert (interpret_cell_type is not None, "Set the interpretation cell type argument") self.interpret_cell_type = interpret_cell_type self.__get_interpretation_attributes() def __get_interpretation_attributes(self): self.interpret_location = get_dir(path.join(self.output_directory, 'interpret')) self.metacluster_patterns_location = get_dir(path.join(self.interpret_location, 'metacluster_patterns')) self.meme_query_pattern_location = get_dir(path.join(self.interpret_location, 'meme_query')) self.interpret_model_file = path.join(self.interpret_location, 'tmp.model') def __get_model(self): # Get the neural network model based on the specified model architecture if self.arch == "DCNN_V2": return get_dilated_cnn(output_activation=self.output_activation, target_scale_factor=self.target_scale_factor, dense_b=self.dense, weights=self.weights ) else: sys.exit("Model Architecture not specified correctly. Please check") def DataGenerator( sequence, meta_table, roi_pool, cell_type_list, rand_ratio, chroms, bp_resolution=BP_RESOLUTION, target_scale_factor=1, batch_size=BATCH_SIZE, shuffle_cell_type=False, rev_comp_train=False ): """ Initiate a data generator that will yield a batch of examples for training. This generator will mix samples from a pool of random regions and a pool of regions of interest based on the user defined ratio. The examples will be returned as a list of numpy arrays. _________________ Workflow Overview 1) Create the random regions pool 2) Create the roi generator 3) Create the random regions generator 4) Combine the roi and random regions batches according to the rand_ratio value :param sequence: The input 2bit DNA sequence :param meta_table: The run meta table with locations to ATAC and ChIP-seq data :param roi_pool: The pool of regions to use centered on peaks :param cell_type_list: The training cell lines to use :param rand_ratio: The number of random examples to use per batch :param chroms: The training chromosomes :param bp_resolution: The resolution of the predictions to use :param batch_size: The number of examples to use per batch of training :param shuffle_cell_type: Shuffle the ROI cell type labels if True :param rev_comp_train: use the reverse complement to train :return A generator that will yield a batch with number of examples equal to batch size """ # Calculate the number of ROIs to use based on the total batch size and proportion of random regions to use n_roi = round(batch_size * (1. - rand_ratio)) # Calculate number of random regions to use each batch n_rand = round(batch_size - n_roi) if n_rand > 0: # Generate the training random regions pool train_random_regions_pool = RandomRegionsPool(chroms=build_chrom_sizes_dict(chroms, DEFAULT_CHROM_SIZES), chrom_pool_size=CHR_POOL_SIZE, region_length=INPUT_LENGTH, preferences=False # can be None ) # Initialize the random regions generator rand_gen = create_random_batch(sequence=sequence, meta_table=meta_table, cell_type_list=cell_type_list, n_rand=n_rand, regions_pool=train_random_regions_pool, bp_resolution=bp_resolution, target_scale_factor=target_scale_factor, rev_comp_train=rev_comp_train ) # Initialize the ROI generator roi_gen = create_roi_batch(sequence=sequence, meta_table=meta_table, roi_pool=roi_pool, n_roi=n_roi, cell_type_list=cell_type_list, bp_resolution=bp_resolution, target_scale_factor=target_scale_factor, shuffle_cell_type=shuffle_cell_type, rev_comp_train=rev_comp_train ) while True: # roi_batch.shape = (n_samples, 1024, 6) if 0. < rand_ratio < 1.: roi_input_batch, roi_target_batch = next(roi_gen) rand_input_batch, rand_target_batch = next(rand_gen) inputs_batch = np.concatenate((roi_input_batch, rand_input_batch), axis=0) targets_batch = np.concatenate((roi_target_batch, rand_target_batch), axis=0) elif rand_ratio == 1.: rand_input_batch, rand_target_batch = next(rand_gen) inputs_batch = rand_input_batch targets_batch = rand_target_batch else: roi_input_batch, roi_target_batch = next(roi_gen) inputs_batch = roi_input_batch targets_batch = roi_target_batch yield inputs_batch, targets_batch # change to yield def get_input_matrix(signal_stream, sequence_stream, chromosome, start, # end - start = cols end, rows=INPUT_CHANNELS, cols=INPUT_LENGTH, bp_order=BP_ORDER, use_complement=False, reverse_matrix=False ): """ Get a matrix of values from the corresponding genomic position. You can supply whether you want to use the complement sequence. You can also choose whether you want to reverse the whole matrix. :param rows: Number of rows == channels :param cols: Number of cols == region length :param signal_stream: Signal bigwig stream :param sequence_stream: 2bit DNA sequence stream :param bp_order: BP order :param chromosome: chromosome :param start: start :param end: end :param use_complement: use complement strand for training :param reverse_matrix: reverse the input matrix :return: a matrix (rows x cols) of values from the input bigwig files """ input_matrix = np.zeros((rows, cols)) for n, bp in enumerate(bp_order): # Get the sequence from the interval of interest target_sequence = Seq(sequence_stream.sequence(chromosome, start, end)) if use_complement: # Get the complement of the sequence target_sequence = target_sequence.complement() # Get the one hot encoded sequence input_matrix[n, :] = get_one_hot_encoded(target_sequence, bp) signal_array = np.array(signal_stream.values(chromosome, start, end)) input_matrix[4, :] = signal_array # If reverse_matrix then reverse the matrix. This changes the left to right orientation. if reverse_matrix: input_matrix = input_matrix[::-1] return input_matrix.T def create_roi_batch(sequence, meta_table, roi_pool, n_roi, cell_type_list, bp_resolution=1, target_scale_factor=1, shuffle_cell_type=False, rev_comp_train=False ): """ Create a batch of examples from regions of interest. The batch size is defined by n_roi. This code will randomly generate a batch of examples based on an input meta file that defines the paths to training data. The cell_type_list is used to randomly select the cell type that the training signal is drawn from. :param sequence: The input 2bit DNA sequence :param meta_table: The meta file that contains the paths to signal and peak files :param roi_pool: The pool of regions that we want to sample from :param n_roi: The number of regions that go into each batch :param cell_type_list: A list of unique training cell types :param bp_resolution: The resolution of the output bins. i.e. 32 bp :param shuffle_cell_type: Whether to shuffle cell types during training :param rev_comp_train: use reverse complement for training :return: np.array(inputs_batch), np.array(targets_batch) """ while True: # Create empty lists that will hold the signal tracks inputs_batch, targets_batch = [], [] # Get the shape of the ROI pool roi_size = roi_pool.shape[0] # Randomly select n regions from the pool curr_batch_idxs = random.sample(range(roi_size), n_roi) # Extract the signal for every sample for row_idx in curr_batch_idxs: roi_row = roi_pool.iloc[row_idx, :] # If shuffle_cell_type the cell type will be randomly chosen if shuffle_cell_type: cell_line = random.choice(cell_type_list) else: cell_line = roi_row['Cell_Line'] # Get the paths for the cell type of interest. meta_row = meta_table[(meta_table['Cell_Line'] == cell_line)] meta_row = meta_row.reset_index(drop=True) # Rename some variables. This just helps clean up code downstream chrom_name = roi_row['Chr'] start = int(roi_row['Start']) end = int(roi_row['Stop']) signal = meta_row.loc[0, 'ATAC_Signal_File'] binding = meta_row.loc[0, 'Binding_File'] # Choose whether to use the reverse complement of the region if rev_comp_train: rev_comp = random.choice([True, False]) else: rev_comp = False with \ load_2bit(sequence) as sequence_stream, \ load_bigwig(signal) as signal_stream, \ load_bigwig(binding) as binding_stream: # Get the input matrix of values and one-hot encoded sequence input_matrix = get_input_matrix(signal_stream=signal_stream, sequence_stream=sequence_stream, chromosome=chrom_name, start=start, end=end, use_complement=rev_comp, reverse_matrix=rev_comp ) # Append the sample to the inputs batch. inputs_batch.append(input_matrix) # Some bigwig files do not have signal for some chromosomes because they do not have peaks # in those regions # Our workaround for issue#42 is to provide a zero matrix for that position try: # Get the target matrix target_vector = np.array(binding_stream.values(chrom_name, start, end)).T except: # TODO change length of array target_vector = np.zeros(1024) # change nan to numbers target_vector = np.nan_to_num(target_vector, 0.0) # If reverse compliment, reverse the matrix if rev_comp: target_vector = target_vector[::-1] # get the number of 32 bp bins across the input sequence n_bins = int(target_vector.shape[0] / bp_resolution) # Split the data up into 32 x 32 bp bins. split_targets = np.array(np.split(target_vector, n_bins, axis=0)) # TODO we might want to test what happens if we change the bin_sums = np.sum(split_targets, axis=1) bin_vector = np.where(bin_sums > 0.5 * bp_resolution, 1.0, 0.0) # Append the sample to the target batch targets_batch.append(bin_vector) yield np.array(inputs_batch), np.array(targets_batch) # change to yield def create_random_batch( sequence, meta_table, cell_type_list, n_rand, regions_pool, bp_resolution=1, target_scale_factor=1, rev_comp_train=False ): """ This function will create a batch of examples that are randomly generated. This batch of data is created the same as the roi batches. """ while True: inputs_batch, targets_batch = [], [] for idx in range(n_rand): cell_line = random.choice(cell_type_list) # Randomly select a cell line chrom_name, seq_start, seq_end = regions_pool.get_region() # returns random region (chrom_name, start, end) meta_row = meta_table[(meta_table['Cell_Line'] == cell_line)] # get meta row for selected cell line meta_row = meta_row.reset_index(drop=True) signal = meta_row.loc[0, 'ATAC_Signal_File'] binding = meta_row.loc[0, 'Binding_File'] with \ load_2bit(sequence) as sequence_stream, \ load_bigwig(signal) as signal_stream, \ load_bigwig(binding) as binding_stream: if rev_comp_train: rev_comp = random.choice([True, False]) else: rev_comp = False input_matrix = get_input_matrix(signal_stream=signal_stream, sequence_stream=sequence_stream, chromosome=chrom_name, start=seq_start, end=seq_end, use_complement=rev_comp, reverse_matrix=rev_comp ) inputs_batch.append(input_matrix) try: # Get the target matrix target_vector = np.array(binding_stream.values(chrom_name, start, end)).T except: # TODO change length of array target_vector = np.zeros(1024) target_vector = np.nan_to_num(target_vector, 0.0) if rev_comp: target_vector = target_vector[::-1] n_bins = int(target_vector.shape[0] / bp_resolution) split_targets = np.array(np.split(target_vector, n_bins, axis=0)) bin_sums = np.sum(split_targets, axis=1) bin_vector = np.where(bin_sums > 0.5 * bp_resolution, 1.0, 0.0) targets_batch.append(bin_vector) yield np.array(inputs_batch), np.array(targets_batch) # change to yield class RandomRegionsPool: """ Generate a pool of random genomic regions """ def __init__( self, chroms, # in a form of {"chr1": {"length": 249250621, "region": [0, 249250621]}}, "region" is ignored chrom_pool_size, region_length, preferences=None # bigBed file with ranges to limit random regions selection ): self.chroms = chroms self.chrom_pool_size = chrom_pool_size self.region_length = region_length self.preferences = preferences # self.preference_pool = self.__get_preference_pool() # should be run before self.__get_chrom_pool() self.preference_pool = False self.chrom_pool = self.__get_chrom_pool() # self.chrom_pool_size is updated to ensure compatibility between HG19 and HG38 self.chrom_pool_size = min(chrom_pool_size, len(self.chrom_pool)) self.__idx = 0 def get_region(self): if self.__idx == self.chrom_pool_size: random.shuffle(self.chrom_pool) self.__idx = 0 chrom_name, chrom_length = self.chrom_pool[self.__idx] self.__idx += 1 if self.preference_pool: preference = random.sample(self.preference_pool[chrom_name], 1)[0] start = round(random.randint(preference[0], preference[1] - self.region_length)) else: start = round(random.randint(0, chrom_length - self.region_length)) end = start + self.region_length return chrom_name, start, end def __get_preference_pool(self): preference_pool = {} if self.preferences is not None: with load_bigwig(self.preferences) as input_stream: for chrom_name, chrom_data in self.chroms.items(): for entry in input_stream.entries(chrom_name, 0, chrom_data["length"], withString=False): if entry[1] - entry[0] < self.region_length: continue preference_pool.setdefault(chrom_name, []).append(list(entry[0:2])) return preference_pool def __get_chrom_pool(self): """ TODO: rewrite to produce exactly the same number of items as chrom_pool_size regardless of length(chroms) and chrom_pool_size """ sum_lengths = sum(self.chroms.values()) frequencies = { chrom_name: round(chrom_length / sum_lengths * self.chrom_pool_size) for chrom_name, chrom_length in self.chroms.items() } labels = [] for k, v in frequencies.items(): labels += [(k, self.chroms[k])] * v random.shuffle(labels) return labels class ROIPool(object): """ Import genomic regions of interest for training """ def __init__(self, chroms, roi_file_path, meta_file, prefix, output_directory, shuffle, tag ): """ :param chroms: Chromosomes to limit the analysis to :param roi_file_path: User provided ROI file path :param meta_file: path to meta file :param prefix: Prefix for saving output file :param output_directory: Output directory to save files to :param shuffle: Whether to shuffle the input ROI file :param tag: Tag to use for writing the file. """ self.chroms = chroms self.roi_file_path = roi_file_path self.meta_file = meta_file self.prefix = prefix self.output_directory = output_directory self.tag = tag # If an ROI path is provided import it as the ROI pool if self.roi_file_path: self.ROI_pool = self.__import_roi_pool__(shuffle=shuffle) # Import the data from the meta file. else: regions = GenomicRegions(meta_path=self.meta_file, region_length=1024, chromosomes=self.chroms, chromosome_sizes_dictionary=build_chrom_sizes_dict(self.chroms, DEFAULT_CHROM_SIZES), blacklist=BLACKLISTED_REGIONS) regions.write_data(self.prefix, output_dir=self.output_directory, set_tag=tag) self.ROI_pool = regions.combined_pool def __import_roi_pool__(self, shuffle=False): """ Import the ROI file containing the regions of interest. This file is similar to a bed file, but with a header The roi DF is read in from a TSV file that is formatted similarly as a BED file with a header. The following columns are required: Chr | Start | Stop | ROI_Type | Cell_Line The chroms list is used to filter the ROI df to make sure that only training chromosomes are included. :param shuffle: Whether to shuffle the dataframe upon import :return: A pool of regions to use for training or validation """ roi_df = pd.read_csv(self.roi_file_path, sep="\t", header=0, index_col=None) roi_df = roi_df[roi_df['Chr'].isin(self.chroms)] if shuffle: roi_df = roi_df.sample(frac=1) return roi_df class SeqDataGenerator(tf.keras.utils.Sequence): # ‘Generates data for Keras’ def __init__(self, batches, generator): # ‘Initialization’ self.batches = batches self.generator = generator def __len__(self): # ‘Denotes the number of batches per epoch’ return self.batches def __getitem__(self, index): # ‘Generate one batch of data’ # Generate indexes of the batch # Generate data return next(self.generator) def model_selection(training_history, output_dir): """ This function will take the training history and output the best model based on the dice coefficient value. """ # Create a dataframe from the history object df = pd.DataFrame(training_history.history) epoch = df['val_dice_coef'].idxmax() + 1 # Get the realpath to the best model out = pd.DataFrame([glob.glob(output_dir + "/*" + str(epoch) + ".h5")], columns=['Best_Model_Path']) # Write the location of the best model to a file out.to_csv(output_dir + "/" + "best_epoch.txt", sep='\t', index=None, header=None) return epoch class GenomicRegions(object): """ This class will generate a pool of examples based on regions of interest defined by ATAC-seq and ChIP-seq peaks. """ def __init__(self, meta_path, chromosomes, chromosome_sizes_dictionary, blacklist, region_length ): """ When the object is initialized it will import all of the peaks in the meta files and parse them into training and validation regions of interest. These will be output in the form of TSV formatted file similar to a BED file. :param meta_path: Path to the meta file :param chromosomes: List of chromosomes to use :param chromosome_sizes_dictionary: A dictionary of chromosome sizes :param blacklist: The blacklist file of BED regions to exclude :param region_length: Length of the input regions """ self.meta_path = meta_path self.chromosome_sizes_dictionary = chromosome_sizes_dictionary self.chromosomes = chromosomes self.blacklist = blacklist self.region_length = region_length # Import meta txt as dataframe self.meta_dataframe = pd.read_csv(self.meta_path, sep='\t', header=0, index_col=None) # Select Training Cell lines self.meta_dataframe = self.meta_dataframe[self.meta_dataframe["Train_Test_Label"] == 'Train'] # Get a dictionary of {Cell Types: Peak Paths} self.atac_dictionary = pd.Series(self.meta_dataframe.ATAC_Peaks.values, index=self.meta_dataframe.Cell_Line).to_dict() self.chip_dictionary = pd.Series(self.meta_dataframe.CHIP_Peaks.values, index=self.meta_dataframe.Cell_Line).to_dict() # You must generate the ROI pool before you can get the final shape self.atac_roi_pool = self.__get_roi_pool(self.atac_dictionary, "ATAC", ) self.chip_roi_pool = self.__get_roi_pool(self.chip_dictionary, "CHIP") self.combined_pool = pd.concat([self.atac_roi_pool, self.chip_roi_pool]) self.atac_roi_size = self.atac_roi_pool.shape[0] self.chip_roi_size = self.chip_roi_pool.shape[0] def __get_roi_pool(self, dictionary, roi_type_tag): """ Build a pool of regions of interest from BED files. :param dictionary: A dictionary of Cell Types and their associated BED files :param roi_type_tag: Tag used to name the type of ROI being generated. IE Chip or ATAC :return: A dataframe of BED regions that are formatted for maxATAC training. """ bed_list = [] for roi_cell_tag, bed_file in dictionary.items(): bed_list.append(self.__import_bed(bed_file, ROI_type_tag=roi_type_tag, ROI_cell_tag=roi_cell_tag)) return pd.concat(bed_list) def write_data(self, prefix="ROI_pool", output_dir="./ROI", set_tag="training"): """ Write the ROI dataframe to a tsv and a bed for for ATAC, CHIP, and combined ROIs :param set_tag: Tag for training or validation :param prefix: Prefix for filenames to use :param output_dir: Directory to output the bed and tsv files :return: Write BED and TSV versions of the ROI data """ output_directory = get_dir(output_dir) combined_BED_filename = os.path.join(output_directory, prefix + "_" + set_tag + "_ROI.bed.gz") stats_filename = os.path.join(output_directory, prefix + "_" + set_tag + "_ROI_stats") total_regions_stats_filename = os.path.join(output_directory, prefix + "_" + set_tag + "_ROI_totalregions_stats") self.combined_pool.to_csv(combined_BED_filename, sep="\t", index=False, header=False) group_ms = self.combined_pool.groupby(["Chr", "Cell_Line", "ROI_Type"], as_index=False).size() len_ms = self.combined_pool.shape[0] group_ms.to_csv(stats_filename, sep="\t", index=False) file = open(total_regions_stats_filename, "a") file.write('Total number of regions found for ' + set_tag + ' are: {0}\n'.format(len_ms)) file.close() def get_regions_list(self, n_roi): """ Generate a batch of regions of interest from the input ChIP-seq and ATAC-seq peaks :param n_roi: Number of regions to generate per batch :return: A batch of training examples centered on regions of interest """ random_roi_pool = self.combined_pool.sample(n=n_roi, replace=True, random_state=1) return random_roi_pool.to_numpy().tolist() def __import_bed(self, bed_file, ROI_type_tag, ROI_cell_tag): """ Import a BED file and format the regions to be compatible with our maxATAC models :param bed_file: Input BED file to format :param ROI_type_tag: Tag to use in the description column :param ROI_cell_tag: Tag to use in the description column :return: A dataframe of BED regions compatible with our model """ # Import dataframe df = pd.read_csv(bed_file, sep="\t", usecols=[0, 1, 2], header=None, names=["Chr", "Start", "Stop"], low_memory=False) # Make sure the chromosomes in the ROI file frame are in the target chromosome list df = df[df["Chr"].isin(self.chromosomes)] # Find the length of the regions df["length"] = df["Stop"] - df["Start"] # Find the center of each peak. # We might want to use bedtools to window the regions of interest around the peak. df["center"] = np.floor(df["Start"] + (df["length"] / 2)).apply(int) # The start of the interval will be the center minus 1/2 the desired region length. df["Start"] = np.floor(df["center"] - (self.region_length / 2)).apply(int) # the end of the interval will be the center plus 1/2 the desired region length df["Stop"] = np.floor(df["center"] + (self.region_length / 2)).apply(int) # The chromosome end is defined as the chromosome length df["END"] = df["Chr"].map(self.chromosome_sizes_dictionary) # Make sure the stop is less than the end df = df[df["Stop"].apply(int) < df["END"].apply(int)] # Make sure the start is greater than the chromosome start of 0 df = df[df["Start"].apply(int) > 0] # Select for the first three columns to clean up df = df[["Chr", "Start", "Stop"]] # Import the dataframe as a pybedtools object so we can remove the blacklist BED_df_bedtool = pybedtools.BedTool.from_dataframe(df) # Import the blacklist as a pybedtools object blacklist_bedtool = pybedtools.BedTool(self.blacklist) # Find the intervals that do not intersect blacklisted regions. blacklisted_df = BED_df_bedtool.intersect(blacklist_bedtool, v=True) # Convert the pybedtools object to a pandas dataframe. df = blacklisted_df.to_dataframe() # Rename the columns df.columns = ["Chr", "Start", "Stop"] df["ROI_Type"] = ROI_type_tag df["Cell_Line"] = ROI_cell_tag return df
import random import sys from os import path import tensorflow as tf import numpy as np import pandas as pd from Bio.Seq import Seq import threading import pybedtools import os import glob from maxatac.architectures.dcnn import get_dilated_cnn from maxatac.utilities.constants import BP_RESOLUTION, BATCH_SIZE, CHR_POOL_SIZE, INPUT_LENGTH, INPUT_CHANNELS, \ BP_ORDER, TRAIN_SCALE_SIGNAL, BLACKLISTED_REGIONS, DEFAULT_CHROM_SIZES from maxatac.utilities.genome_tools import load_bigwig, load_2bit, get_one_hot_encoded, build_chrom_sizes_dict from maxatac.utilities.system_tools import get_dir, remove_tags, replace_extension class MaxATACModel(object): """ This object will organize the input model parameters and initialize the maxATAC model The methods are: __get_interpretation_attributes: This will import the interpretation inputs if interpretation module is being used. __get_model: This will get the correct architecture and parameters based on the user input """ def __init__(self, arch, seed, output_directory, prefix, threads, meta_path, weights, dense=False, target_scale_factor=TRAIN_SCALE_SIGNAL, output_activation="sigmoid", interpret=False, interpret_cell_type="" ): """ Initialize the maxATAC model with the input parameters and architecture :param arch: Neural network architecture to use: DCNN, resNet, UNet, multi-modal :param seed: Random seed to use :param output_directory: Path to output directory :param prefix: Prefix to use for filename :param threads: Number of threads to use :param meta_path: Path to the meta file associated with the run :param output_activation: The activation function to use in the output layer :param dense: Whether to use a dense layer on output :param weights: Input weights to use for model :param interpret: Boolean for whether this is training or interpretation """ self.arch = arch self.seed = seed self.output_directory = get_dir(output_directory) self.model_filename = prefix + "_{epoch}" + ".h5" self.results_location = path.join(self.output_directory, self.model_filename) self.log_location = replace_extension(remove_tags(self.results_location, "_{epoch}"), ".csv") self.tensor_board_log_dir = get_dir(path.join(self.output_directory, "tensorboard")) self.threads = threads self.training_history = "" self.meta_path = meta_path self.output_activation = output_activation self.dense = dense self.weights = weights self.target_scale_factor = target_scale_factor # Set the random seed for the model random.seed(seed) # Import meta txt as dataframe self.meta_dataframe = pd.read_csv(self.meta_path, sep='\t', header=0, index_col=None) # Find the unique number of cell types in the meta file self.cell_types = self.meta_dataframe["Cell_Line"].unique().tolist() self.train_tf = self.meta_dataframe["TF"].unique()[0] self.nn_model = self.__get_model() if interpret: assert (interpret_cell_type is not None, "Set the interpretation cell type argument") self.interpret_cell_type = interpret_cell_type self.__get_interpretation_attributes() def __get_interpretation_attributes(self): self.interpret_location = get_dir(path.join(self.output_directory, 'interpret')) self.metacluster_patterns_location = get_dir(path.join(self.interpret_location, 'metacluster_patterns')) self.meme_query_pattern_location = get_dir(path.join(self.interpret_location, 'meme_query')) self.interpret_model_file = path.join(self.interpret_location, 'tmp.model') def __get_model(self): # Get the neural network model based on the specified model architecture if self.arch == "DCNN_V2": return get_dilated_cnn(output_activation=self.output_activation, target_scale_factor=self.target_scale_factor, dense_b=self.dense, weights=self.weights ) else: sys.exit("Model Architecture not specified correctly. Please check") def DataGenerator( sequence, meta_table, roi_pool, cell_type_list, rand_ratio, chroms, bp_resolution=BP_RESOLUTION, target_scale_factor=1, batch_size=BATCH_SIZE, shuffle_cell_type=False, rev_comp_train=False ): """ Initiate a data generator that will yield a batch of examples for training. This generator will mix samples from a pool of random regions and a pool of regions of interest based on the user defined ratio. The examples will be returned as a list of numpy arrays. _________________ Workflow Overview 1) Create the random regions pool 2) Create the roi generator 3) Create the random regions generator 4) Combine the roi and random regions batches according to the rand_ratio value :param sequence: The input 2bit DNA sequence :param meta_table: The run meta table with locations to ATAC and ChIP-seq data :param roi_pool: The pool of regions to use centered on peaks :param cell_type_list: The training cell lines to use :param rand_ratio: The number of random examples to use per batch :param chroms: The training chromosomes :param bp_resolution: The resolution of the predictions to use :param batch_size: The number of examples to use per batch of training :param shuffle_cell_type: Shuffle the ROI cell type labels if True :param rev_comp_train: use the reverse complement to train :return A generator that will yield a batch with number of examples equal to batch size """ # Calculate the number of ROIs to use based on the total batch size and proportion of random regions to use n_roi = round(batch_size * (1. - rand_ratio)) # Calculate number of random regions to use each batch n_rand = round(batch_size - n_roi) if n_rand > 0: # Generate the training random regions pool train_random_regions_pool = RandomRegionsPool(chroms=build_chrom_sizes_dict(chroms, DEFAULT_CHROM_SIZES), chrom_pool_size=CHR_POOL_SIZE, region_length=INPUT_LENGTH, preferences=False # can be None ) # Initialize the random regions generator rand_gen = create_random_batch(sequence=sequence, meta_table=meta_table, cell_type_list=cell_type_list, n_rand=n_rand, regions_pool=train_random_regions_pool, bp_resolution=bp_resolution, target_scale_factor=target_scale_factor, rev_comp_train=rev_comp_train ) # Initialize the ROI generator roi_gen = create_roi_batch(sequence=sequence, meta_table=meta_table, roi_pool=roi_pool, n_roi=n_roi, cell_type_list=cell_type_list, bp_resolution=bp_resolution, target_scale_factor=target_scale_factor, shuffle_cell_type=shuffle_cell_type, rev_comp_train=rev_comp_train ) while True: # roi_batch.shape = (n_samples, 1024, 6) if 0. < rand_ratio < 1.: roi_input_batch, roi_target_batch = next(roi_gen) rand_input_batch, rand_target_batch = next(rand_gen) inputs_batch = np.concatenate((roi_input_batch, rand_input_batch), axis=0) targets_batch = np.concatenate((roi_target_batch, rand_target_batch), axis=0) elif rand_ratio == 1.: rand_input_batch, rand_target_batch = next(rand_gen) inputs_batch = rand_input_batch targets_batch = rand_target_batch else: roi_input_batch, roi_target_batch = next(roi_gen) inputs_batch = roi_input_batch targets_batch = roi_target_batch yield inputs_batch, targets_batch # change to yield def get_input_matrix(signal_stream, sequence_stream, chromosome, start, # end - start = cols end, rows=INPUT_CHANNELS, cols=INPUT_LENGTH, bp_order=BP_ORDER, use_complement=False, reverse_matrix=False ): """ Get a matrix of values from the corresponding genomic position. You can supply whether you want to use the complement sequence. You can also choose whether you want to reverse the whole matrix. :param rows: Number of rows == channels :param cols: Number of cols == region length :param signal_stream: Signal bigwig stream :param sequence_stream: 2bit DNA sequence stream :param bp_order: BP order :param chromosome: chromosome :param start: start :param end: end :param use_complement: use complement strand for training :param reverse_matrix: reverse the input matrix :return: a matrix (rows x cols) of values from the input bigwig files """ input_matrix = np.zeros((rows, cols)) for n, bp in enumerate(bp_order): # Get the sequence from the interval of interest target_sequence = Seq(sequence_stream.sequence(chromosome, start, end)) if use_complement: # Get the complement of the sequence target_sequence = target_sequence.complement() # Get the one hot encoded sequence input_matrix[n, :] = get_one_hot_encoded(target_sequence, bp) signal_array = np.array(signal_stream.values(chromosome, start, end)) input_matrix[4, :] = signal_array # If reverse_matrix then reverse the matrix. This changes the left to right orientation. if reverse_matrix: input_matrix = input_matrix[::-1] return input_matrix.T def create_roi_batch(sequence, meta_table, roi_pool, n_roi, cell_type_list, bp_resolution=1, target_scale_factor=1, shuffle_cell_type=False, rev_comp_train=False ): """ Create a batch of examples from regions of interest. The batch size is defined by n_roi. This code will randomly generate a batch of examples based on an input meta file that defines the paths to training data. The cell_type_list is used to randomly select the cell type that the training signal is drawn from. :param sequence: The input 2bit DNA sequence :param meta_table: The meta file that contains the paths to signal and peak files :param roi_pool: The pool of regions that we want to sample from :param n_roi: The number of regions that go into each batch :param cell_type_list: A list of unique training cell types :param bp_resolution: The resolution of the output bins. i.e. 32 bp :param shuffle_cell_type: Whether to shuffle cell types during training :param rev_comp_train: use reverse complement for training :return: np.array(inputs_batch), np.array(targets_batch) """ while True: # Create empty lists that will hold the signal tracks inputs_batch, targets_batch = [], [] # Get the shape of the ROI pool roi_size = roi_pool.shape[0] # Randomly select n regions from the pool curr_batch_idxs = random.sample(range(roi_size), n_roi) # Extract the signal for every sample for row_idx in curr_batch_idxs: roi_row = roi_pool.iloc[row_idx, :] # If shuffle_cell_type the cell type will be randomly chosen if shuffle_cell_type: cell_line = random.choice(cell_type_list) else: cell_line = roi_row['Cell_Line'] # Get the paths for the cell type of interest. meta_row = meta_table[(meta_table['Cell_Line'] == cell_line)] meta_row = meta_row.reset_index(drop=True) # Rename some variables. This just helps clean up code downstream chrom_name = roi_row['Chr'] start = int(roi_row['Start']) end = int(roi_row['Stop']) signal = meta_row.loc[0, 'ATAC_Signal_File'] binding = meta_row.loc[0, 'Binding_File'] # Choose whether to use the reverse complement of the region if rev_comp_train: rev_comp = random.choice([True, False]) else: rev_comp = False with \ load_2bit(sequence) as sequence_stream, \ load_bigwig(signal) as signal_stream, \ load_bigwig(binding) as binding_stream: # Get the input matrix of values and one-hot encoded sequence input_matrix = get_input_matrix(signal_stream=signal_stream, sequence_stream=sequence_stream, chromosome=chrom_name, start=start, end=end, use_complement=rev_comp, reverse_matrix=rev_comp ) # Append the sample to the inputs batch. inputs_batch.append(input_matrix) # Some bigwig files do not have signal for some chromosomes because they do not have peaks # in those regions # Our workaround for issue#42 is to provide a zero matrix for that position try: # Get the target matrix target_vector = np.array(binding_stream.values(chrom_name, start, end)).T except: # TODO change length of array target_vector = np.zeros(1024) # change nan to numbers target_vector = np.nan_to_num(target_vector, 0.0) # If reverse compliment, reverse the matrix if rev_comp: target_vector = target_vector[::-1] # get the number of 32 bp bins across the input sequence n_bins = int(target_vector.shape[0] / bp_resolution) # Split the data up into 32 x 32 bp bins. split_targets = np.array(np.split(target_vector, n_bins, axis=0)) # TODO we might want to test what happens if we change the bin_sums = np.sum(split_targets, axis=1) bin_vector = np.where(bin_sums > 0.5 * bp_resolution, 1.0, 0.0) # Append the sample to the target batch targets_batch.append(bin_vector) yield np.array(inputs_batch), np.array(targets_batch) # change to yield def create_random_batch( sequence, meta_table, cell_type_list, n_rand, regions_pool, bp_resolution=1, target_scale_factor=1, rev_comp_train=False ): """ This function will create a batch of examples that are randomly generated. This batch of data is created the same as the roi batches. """ while True: inputs_batch, targets_batch = [], [] for idx in range(n_rand): cell_line = random.choice(cell_type_list) # Randomly select a cell line chrom_name, seq_start, seq_end = regions_pool.get_region() # returns random region (chrom_name, start, end) meta_row = meta_table[(meta_table['Cell_Line'] == cell_line)] # get meta row for selected cell line meta_row = meta_row.reset_index(drop=True) signal = meta_row.loc[0, 'ATAC_Signal_File'] binding = meta_row.loc[0, 'Binding_File'] with \ load_2bit(sequence) as sequence_stream, \ load_bigwig(signal) as signal_stream, \ load_bigwig(binding) as binding_stream: if rev_comp_train: rev_comp = random.choice([True, False]) else: rev_comp = False input_matrix = get_input_matrix(signal_stream=signal_stream, sequence_stream=sequence_stream, chromosome=chrom_name, start=seq_start, end=seq_end, use_complement=rev_comp, reverse_matrix=rev_comp ) inputs_batch.append(input_matrix) try: # Get the target matrix target_vector = np.array(binding_stream.values(chrom_name, start, end)).T except: # TODO change length of array target_vector = np.zeros(1024) target_vector = np.nan_to_num(target_vector, 0.0) if rev_comp: target_vector = target_vector[::-1] n_bins = int(target_vector.shape[0] / bp_resolution) split_targets = np.array(np.split(target_vector, n_bins, axis=0)) bin_sums = np.sum(split_targets, axis=1) bin_vector = np.where(bin_sums > 0.5 * bp_resolution, 1.0, 0.0) targets_batch.append(bin_vector) yield np.array(inputs_batch), np.array(targets_batch) # change to yield class RandomRegionsPool: """ Generate a pool of random genomic regions """ def __init__( self, chroms, # in a form of {"chr1": {"length": 249250621, "region": [0, 249250621]}}, "region" is ignored chrom_pool_size, region_length, preferences=None # bigBed file with ranges to limit random regions selection ): self.chroms = chroms self.chrom_pool_size = chrom_pool_size self.region_length = region_length self.preferences = preferences # self.preference_pool = self.__get_preference_pool() # should be run before self.__get_chrom_pool() self.preference_pool = False self.chrom_pool = self.__get_chrom_pool() # self.chrom_pool_size is updated to ensure compatibility between HG19 and HG38 self.chrom_pool_size = min(chrom_pool_size, len(self.chrom_pool)) self.__idx = 0 def get_region(self): if self.__idx == self.chrom_pool_size: random.shuffle(self.chrom_pool) self.__idx = 0 chrom_name, chrom_length = self.chrom_pool[self.__idx] self.__idx += 1 if self.preference_pool: preference = random.sample(self.preference_pool[chrom_name], 1)[0] start = round(random.randint(preference[0], preference[1] - self.region_length)) else: start = round(random.randint(0, chrom_length - self.region_length)) end = start + self.region_length return chrom_name, start, end def __get_preference_pool(self): preference_pool = {} if self.preferences is not None: with load_bigwig(self.preferences) as input_stream: for chrom_name, chrom_data in self.chroms.items(): for entry in input_stream.entries(chrom_name, 0, chrom_data["length"], withString=False): if entry[1] - entry[0] < self.region_length: continue preference_pool.setdefault(chrom_name, []).append(list(entry[0:2])) return preference_pool def __get_chrom_pool(self): """ TODO: rewrite to produce exactly the same number of items as chrom_pool_size regardless of length(chroms) and chrom_pool_size """ sum_lengths = sum(self.chroms.values()) frequencies = { chrom_name: round(chrom_length / sum_lengths * self.chrom_pool_size) for chrom_name, chrom_length in self.chroms.items() } labels = [] for k, v in frequencies.items(): labels += [(k, self.chroms[k])] * v random.shuffle(labels) return labels class ROIPool(object): """ Import genomic regions of interest for training """ def __init__(self, chroms, roi_file_path, meta_file, prefix, output_directory, shuffle, tag ): """ :param chroms: Chromosomes to limit the analysis to :param roi_file_path: User provided ROI file path :param meta_file: path to meta file :param prefix: Prefix for saving output file :param output_directory: Output directory to save files to :param shuffle: Whether to shuffle the input ROI file :param tag: Tag to use for writing the file. """ self.chroms = chroms self.roi_file_path = roi_file_path self.meta_file = meta_file self.prefix = prefix self.output_directory = output_directory self.tag = tag # If an ROI path is provided import it as the ROI pool if self.roi_file_path: self.ROI_pool = self.__import_roi_pool__(shuffle=shuffle) # Import the data from the meta file. else: regions = GenomicRegions(meta_path=self.meta_file, region_length=1024, chromosomes=self.chroms, chromosome_sizes_dictionary=build_chrom_sizes_dict(self.chroms, DEFAULT_CHROM_SIZES), blacklist=BLACKLISTED_REGIONS) regions.write_data(self.prefix, output_dir=self.output_directory, set_tag=tag) self.ROI_pool = regions.combined_pool def __import_roi_pool__(self, shuffle=False): """ Import the ROI file containing the regions of interest. This file is similar to a bed file, but with a header The roi DF is read in from a TSV file that is formatted similarly as a BED file with a header. The following columns are required: Chr | Start | Stop | ROI_Type | Cell_Line The chroms list is used to filter the ROI df to make sure that only training chromosomes are included. :param shuffle: Whether to shuffle the dataframe upon import :return: A pool of regions to use for training or validation """ roi_df = pd.read_csv(self.roi_file_path, sep="\t", header=0, index_col=None) roi_df = roi_df[roi_df['Chr'].isin(self.chroms)] if shuffle: roi_df = roi_df.sample(frac=1) return roi_df class SeqDataGenerator(tf.keras.utils.Sequence): # ‘Generates data for Keras’ def __init__(self, batches, generator): # ‘Initialization’ self.batches = batches self.generator = generator def __len__(self): # ‘Denotes the number of batches per epoch’ return self.batches def __getitem__(self, index): # ‘Generate one batch of data’ # Generate indexes of the batch # Generate data return next(self.generator) def model_selection(training_history, output_dir): """ This function will take the training history and output the best model based on the dice coefficient value. """ # Create a dataframe from the history object df = pd.DataFrame(training_history.history) epoch = df['val_dice_coef'].idxmax() + 1 # Get the realpath to the best model out = pd.DataFrame([glob.glob(output_dir + "/*" + str(epoch) + ".h5")], columns=['Best_Model_Path']) # Write the location of the best model to a file out.to_csv(output_dir + "/" + "best_epoch.txt", sep='\t', index=None, header=None) return epoch class GenomicRegions(object): """ This class will generate a pool of examples based on regions of interest defined by ATAC-seq and ChIP-seq peaks. """ def __init__(self, meta_path, chromosomes, chromosome_sizes_dictionary, blacklist, region_length ): """ When the object is initialized it will import all of the peaks in the meta files and parse them into training and validation regions of interest. These will be output in the form of TSV formatted file similar to a BED file. :param meta_path: Path to the meta file :param chromosomes: List of chromosomes to use :param chromosome_sizes_dictionary: A dictionary of chromosome sizes :param blacklist: The blacklist file of BED regions to exclude :param region_length: Length of the input regions """ self.meta_path = meta_path self.chromosome_sizes_dictionary = chromosome_sizes_dictionary self.chromosomes = chromosomes self.blacklist = blacklist self.region_length = region_length # Import meta txt as dataframe self.meta_dataframe = pd.read_csv(self.meta_path, sep='\t', header=0, index_col=None) # Select Training Cell lines self.meta_dataframe = self.meta_dataframe[self.meta_dataframe["Train_Test_Label"] == 'Train'] # Get a dictionary of {Cell Types: Peak Paths} self.atac_dictionary = pd.Series(self.meta_dataframe.ATAC_Peaks.values, index=self.meta_dataframe.Cell_Line).to_dict() self.chip_dictionary = pd.Series(self.meta_dataframe.CHIP_Peaks.values, index=self.meta_dataframe.Cell_Line).to_dict() # You must generate the ROI pool before you can get the final shape self.atac_roi_pool = self.__get_roi_pool(self.atac_dictionary, "ATAC", ) self.chip_roi_pool = self.__get_roi_pool(self.chip_dictionary, "CHIP") self.combined_pool = pd.concat([self.atac_roi_pool, self.chip_roi_pool]) self.atac_roi_size = self.atac_roi_pool.shape[0] self.chip_roi_size = self.chip_roi_pool.shape[0] def __get_roi_pool(self, dictionary, roi_type_tag): """ Build a pool of regions of interest from BED files. :param dictionary: A dictionary of Cell Types and their associated BED files :param roi_type_tag: Tag used to name the type of ROI being generated. IE Chip or ATAC :return: A dataframe of BED regions that are formatted for maxATAC training. """ bed_list = [] for roi_cell_tag, bed_file in dictionary.items(): bed_list.append(self.__import_bed(bed_file, ROI_type_tag=roi_type_tag, ROI_cell_tag=roi_cell_tag)) return pd.concat(bed_list) def write_data(self, prefix="ROI_pool", output_dir="./ROI", set_tag="training"): """ Write the ROI dataframe to a tsv and a bed for for ATAC, CHIP, and combined ROIs :param set_tag: Tag for training or validation :param prefix: Prefix for filenames to use :param output_dir: Directory to output the bed and tsv files :return: Write BED and TSV versions of the ROI data """ output_directory = get_dir(output_dir) combined_BED_filename = os.path.join(output_directory, prefix + "_" + set_tag + "_ROI.bed.gz") stats_filename = os.path.join(output_directory, prefix + "_" + set_tag + "_ROI_stats") total_regions_stats_filename = os.path.join(output_directory, prefix + "_" + set_tag + "_ROI_totalregions_stats") self.combined_pool.to_csv(combined_BED_filename, sep="\t", index=False, header=False) group_ms = self.combined_pool.groupby(["Chr", "Cell_Line", "ROI_Type"], as_index=False).size() len_ms = self.combined_pool.shape[0] group_ms.to_csv(stats_filename, sep="\t", index=False) file = open(total_regions_stats_filename, "a") file.write('Total number of regions found for ' + set_tag + ' are: {0}\n'.format(len_ms)) file.close() def get_regions_list(self, n_roi): """ Generate a batch of regions of interest from the input ChIP-seq and ATAC-seq peaks :param n_roi: Number of regions to generate per batch :return: A batch of training examples centered on regions of interest """ random_roi_pool = self.combined_pool.sample(n=n_roi, replace=True, random_state=1) return random_roi_pool.to_numpy().tolist() def __import_bed(self, bed_file, ROI_type_tag, ROI_cell_tag): """ Import a BED file and format the regions to be compatible with our maxATAC models :param bed_file: Input BED file to format :param ROI_type_tag: Tag to use in the description column :param ROI_cell_tag: Tag to use in the description column :return: A dataframe of BED regions compatible with our model """ # Import dataframe df = pd.read_csv(bed_file, sep="\t", usecols=[0, 1, 2], header=None, names=["Chr", "Start", "Stop"], low_memory=False) # Make sure the chromosomes in the ROI file frame are in the target chromosome list df = df[df["Chr"].isin(self.chromosomes)] # Find the length of the regions df["length"] = df["Stop"] - df["Start"] # Find the center of each peak. # We might want to use bedtools to window the regions of interest around the peak. df["center"] = np.floor(df["Start"] + (df["length"] / 2)).apply(int) # The start of the interval will be the center minus 1/2 the desired region length. df["Start"] = np.floor(df["center"] - (self.region_length / 2)).apply(int) # the end of the interval will be the center plus 1/2 the desired region length df["Stop"] = np.floor(df["center"] + (self.region_length / 2)).apply(int) # The chromosome end is defined as the chromosome length df["END"] = df["Chr"].map(self.chromosome_sizes_dictionary) # Make sure the stop is less than the end df = df[df["Stop"].apply(int) < df["END"].apply(int)] # Make sure the start is greater than the chromosome start of 0 df = df[df["Start"].apply(int) > 0] # Select for the first three columns to clean up df = df[["Chr", "Start", "Stop"]] # Import the dataframe as a pybedtools object so we can remove the blacklist BED_df_bedtool = pybedtools.BedTool.from_dataframe(df) # Import the blacklist as a pybedtools object blacklist_bedtool = pybedtools.BedTool(self.blacklist) # Find the intervals that do not intersect blacklisted regions. blacklisted_df = BED_df_bedtool.intersect(blacklist_bedtool, v=True) # Convert the pybedtools object to a pandas dataframe. df = blacklisted_df.to_dataframe() # Rename the columns df.columns = ["Chr", "Start", "Stop"] df["ROI_Type"] = ROI_type_tag df["Cell_Line"] = ROI_cell_tag return df
en
0.782198
This object will organize the input model parameters and initialize the maxATAC model The methods are: __get_interpretation_attributes: This will import the interpretation inputs if interpretation module is being used. __get_model: This will get the correct architecture and parameters based on the user input Initialize the maxATAC model with the input parameters and architecture :param arch: Neural network architecture to use: DCNN, resNet, UNet, multi-modal :param seed: Random seed to use :param output_directory: Path to output directory :param prefix: Prefix to use for filename :param threads: Number of threads to use :param meta_path: Path to the meta file associated with the run :param output_activation: The activation function to use in the output layer :param dense: Whether to use a dense layer on output :param weights: Input weights to use for model :param interpret: Boolean for whether this is training or interpretation # Set the random seed for the model # Import meta txt as dataframe # Find the unique number of cell types in the meta file # Get the neural network model based on the specified model architecture Initiate a data generator that will yield a batch of examples for training. This generator will mix samples from a pool of random regions and a pool of regions of interest based on the user defined ratio. The examples will be returned as a list of numpy arrays. _________________ Workflow Overview 1) Create the random regions pool 2) Create the roi generator 3) Create the random regions generator 4) Combine the roi and random regions batches according to the rand_ratio value :param sequence: The input 2bit DNA sequence :param meta_table: The run meta table with locations to ATAC and ChIP-seq data :param roi_pool: The pool of regions to use centered on peaks :param cell_type_list: The training cell lines to use :param rand_ratio: The number of random examples to use per batch :param chroms: The training chromosomes :param bp_resolution: The resolution of the predictions to use :param batch_size: The number of examples to use per batch of training :param shuffle_cell_type: Shuffle the ROI cell type labels if True :param rev_comp_train: use the reverse complement to train :return A generator that will yield a batch with number of examples equal to batch size # Calculate the number of ROIs to use based on the total batch size and proportion of random regions to use # Calculate number of random regions to use each batch # Generate the training random regions pool # can be None # Initialize the random regions generator # Initialize the ROI generator # roi_batch.shape = (n_samples, 1024, 6) # change to yield # end - start = cols Get a matrix of values from the corresponding genomic position. You can supply whether you want to use the complement sequence. You can also choose whether you want to reverse the whole matrix. :param rows: Number of rows == channels :param cols: Number of cols == region length :param signal_stream: Signal bigwig stream :param sequence_stream: 2bit DNA sequence stream :param bp_order: BP order :param chromosome: chromosome :param start: start :param end: end :param use_complement: use complement strand for training :param reverse_matrix: reverse the input matrix :return: a matrix (rows x cols) of values from the input bigwig files # Get the sequence from the interval of interest # Get the complement of the sequence # Get the one hot encoded sequence # If reverse_matrix then reverse the matrix. This changes the left to right orientation. Create a batch of examples from regions of interest. The batch size is defined by n_roi. This code will randomly generate a batch of examples based on an input meta file that defines the paths to training data. The cell_type_list is used to randomly select the cell type that the training signal is drawn from. :param sequence: The input 2bit DNA sequence :param meta_table: The meta file that contains the paths to signal and peak files :param roi_pool: The pool of regions that we want to sample from :param n_roi: The number of regions that go into each batch :param cell_type_list: A list of unique training cell types :param bp_resolution: The resolution of the output bins. i.e. 32 bp :param shuffle_cell_type: Whether to shuffle cell types during training :param rev_comp_train: use reverse complement for training :return: np.array(inputs_batch), np.array(targets_batch) # Create empty lists that will hold the signal tracks # Get the shape of the ROI pool # Randomly select n regions from the pool # Extract the signal for every sample # If shuffle_cell_type the cell type will be randomly chosen # Get the paths for the cell type of interest. # Rename some variables. This just helps clean up code downstream # Choose whether to use the reverse complement of the region # Get the input matrix of values and one-hot encoded sequence # Append the sample to the inputs batch. # Some bigwig files do not have signal for some chromosomes because they do not have peaks # in those regions # Our workaround for issue#42 is to provide a zero matrix for that position # Get the target matrix # TODO change length of array # change nan to numbers # If reverse compliment, reverse the matrix # get the number of 32 bp bins across the input sequence # Split the data up into 32 x 32 bp bins. # TODO we might want to test what happens if we change the # Append the sample to the target batch # change to yield This function will create a batch of examples that are randomly generated. This batch of data is created the same as the roi batches. # Randomly select a cell line # returns random region (chrom_name, start, end) # get meta row for selected cell line # Get the target matrix # TODO change length of array # change to yield Generate a pool of random genomic regions # in a form of {"chr1": {"length": 249250621, "region": [0, 249250621]}}, "region" is ignored # bigBed file with ranges to limit random regions selection # self.preference_pool = self.__get_preference_pool() # should be run before self.__get_chrom_pool() # self.chrom_pool_size is updated to ensure compatibility between HG19 and HG38 TODO: rewrite to produce exactly the same number of items as chrom_pool_size regardless of length(chroms) and chrom_pool_size Import genomic regions of interest for training :param chroms: Chromosomes to limit the analysis to :param roi_file_path: User provided ROI file path :param meta_file: path to meta file :param prefix: Prefix for saving output file :param output_directory: Output directory to save files to :param shuffle: Whether to shuffle the input ROI file :param tag: Tag to use for writing the file. # If an ROI path is provided import it as the ROI pool # Import the data from the meta file. Import the ROI file containing the regions of interest. This file is similar to a bed file, but with a header The roi DF is read in from a TSV file that is formatted similarly as a BED file with a header. The following columns are required: Chr | Start | Stop | ROI_Type | Cell_Line The chroms list is used to filter the ROI df to make sure that only training chromosomes are included. :param shuffle: Whether to shuffle the dataframe upon import :return: A pool of regions to use for training or validation # ‘Generates data for Keras’ # ‘Initialization’ # ‘Denotes the number of batches per epoch’ # ‘Generate one batch of data’ # Generate indexes of the batch # Generate data This function will take the training history and output the best model based on the dice coefficient value. # Create a dataframe from the history object # Get the realpath to the best model # Write the location of the best model to a file This class will generate a pool of examples based on regions of interest defined by ATAC-seq and ChIP-seq peaks. When the object is initialized it will import all of the peaks in the meta files and parse them into training and validation regions of interest. These will be output in the form of TSV formatted file similar to a BED file. :param meta_path: Path to the meta file :param chromosomes: List of chromosomes to use :param chromosome_sizes_dictionary: A dictionary of chromosome sizes :param blacklist: The blacklist file of BED regions to exclude :param region_length: Length of the input regions # Import meta txt as dataframe # Select Training Cell lines # Get a dictionary of {Cell Types: Peak Paths} # You must generate the ROI pool before you can get the final shape Build a pool of regions of interest from BED files. :param dictionary: A dictionary of Cell Types and their associated BED files :param roi_type_tag: Tag used to name the type of ROI being generated. IE Chip or ATAC :return: A dataframe of BED regions that are formatted for maxATAC training. Write the ROI dataframe to a tsv and a bed for for ATAC, CHIP, and combined ROIs :param set_tag: Tag for training or validation :param prefix: Prefix for filenames to use :param output_dir: Directory to output the bed and tsv files :return: Write BED and TSV versions of the ROI data Generate a batch of regions of interest from the input ChIP-seq and ATAC-seq peaks :param n_roi: Number of regions to generate per batch :return: A batch of training examples centered on regions of interest Import a BED file and format the regions to be compatible with our maxATAC models :param bed_file: Input BED file to format :param ROI_type_tag: Tag to use in the description column :param ROI_cell_tag: Tag to use in the description column :return: A dataframe of BED regions compatible with our model # Import dataframe # Make sure the chromosomes in the ROI file frame are in the target chromosome list # Find the length of the regions # Find the center of each peak. # We might want to use bedtools to window the regions of interest around the peak. # The start of the interval will be the center minus 1/2 the desired region length. # the end of the interval will be the center plus 1/2 the desired region length # The chromosome end is defined as the chromosome length # Make sure the stop is less than the end # Make sure the start is greater than the chromosome start of 0 # Select for the first three columns to clean up # Import the dataframe as a pybedtools object so we can remove the blacklist # Import the blacklist as a pybedtools object # Find the intervals that do not intersect blacklisted regions. # Convert the pybedtools object to a pandas dataframe. # Rename the columns
2.135128
2
teraserver/python/opentera/db/models/TeraSite.py
introlab/opentera
10
6622375
from opentera.db.Base import db, BaseModel from flask_sqlalchemy import event class TeraSite(db.Model, BaseModel): __tablename__ = 't_sites' id_site = db.Column(db.Integer, db.Sequence('id_site_sequence'), primary_key=True, autoincrement=True) site_name = db.Column(db.String, nullable=False, unique=True) # site_devices = db.relationship("TeraDeviceSite") site_projects = db.relationship("TeraProject", cascade="delete", passive_deletes=True) def to_json(self, ignore_fields=None, minimal=False): if ignore_fields is None: ignore_fields = [] ignore_fields.extend(['site_projects']) return super().to_json(ignore_fields=ignore_fields) def to_json_create_event(self): return self.to_json(minimal=True) def to_json_update_event(self): return self.to_json(minimal=True) def to_json_delete_event(self): # Minimal information, delete can not be filtered return {'id_site': self.id_site} @staticmethod def create_defaults(test=False): base_site = TeraSite() base_site.site_name = 'Default Site' TeraSite.insert(base_site) if test: base_site = TeraSite() base_site.site_name = 'Top Secret Site' TeraSite.insert(base_site) @staticmethod def get_site_by_sitename(sitename): return TeraSite.query.filter_by(site_name=sitename).first() @staticmethod def get_site_by_id(site_id: int): return TeraSite.query.filter_by(id_site=site_id).first() @staticmethod def query_data(filter_args): if isinstance(filter_args, tuple): return TeraSite.query.filter_by(*filter_args).all() if isinstance(filter_args, dict): return TeraSite.query.filter_by(**filter_args).all() return None @classmethod def delete(cls, id_todel): super().delete(id_todel) # from opentera.db.models.TeraSession import TeraSession # TeraSession.delete_orphaned_sessions() @classmethod def insert(cls, site): # Creates admin and user roles for that site super().insert(site) from opentera.db.models.TeraServiceRole import TeraServiceRole from opentera.db.models.TeraService import TeraService opentera_service_id = TeraService.get_openteraserver_service().id_service access_role = TeraServiceRole() access_role.id_service = opentera_service_id access_role.id_site = site.id_site access_role.service_role_name = 'admin' db.session.add(access_role) access_role = TeraServiceRole() access_role.id_service = opentera_service_id access_role.id_site = site.id_site access_role.service_role_name = 'user' db.session.add(access_role) db.session.commit() # # @event.listens_for(TeraSite, 'after_insert') # def site_inserted(mapper, connection, target): # # By default, creates user and admin roles after a site has been added # from opentera.db.models.TeraServiceRole import TeraServiceRole # from opentera.db.models.TeraService import TeraService # # access_role = TeraServiceRole() # access_role.id_service = Globals.opentera_service_id # access_role.id_site = target.id_site # access_role.service_role_name = 'admin' # db.session.add(access_role) # # access_role = TeraServiceRole() # access_role.id_service = Globals.opentera_service_id # access_role.id_site = target.id_site # access_role.service_role_name = 'user' # db.session.add(access_role)
from opentera.db.Base import db, BaseModel from flask_sqlalchemy import event class TeraSite(db.Model, BaseModel): __tablename__ = 't_sites' id_site = db.Column(db.Integer, db.Sequence('id_site_sequence'), primary_key=True, autoincrement=True) site_name = db.Column(db.String, nullable=False, unique=True) # site_devices = db.relationship("TeraDeviceSite") site_projects = db.relationship("TeraProject", cascade="delete", passive_deletes=True) def to_json(self, ignore_fields=None, minimal=False): if ignore_fields is None: ignore_fields = [] ignore_fields.extend(['site_projects']) return super().to_json(ignore_fields=ignore_fields) def to_json_create_event(self): return self.to_json(minimal=True) def to_json_update_event(self): return self.to_json(minimal=True) def to_json_delete_event(self): # Minimal information, delete can not be filtered return {'id_site': self.id_site} @staticmethod def create_defaults(test=False): base_site = TeraSite() base_site.site_name = 'Default Site' TeraSite.insert(base_site) if test: base_site = TeraSite() base_site.site_name = 'Top Secret Site' TeraSite.insert(base_site) @staticmethod def get_site_by_sitename(sitename): return TeraSite.query.filter_by(site_name=sitename).first() @staticmethod def get_site_by_id(site_id: int): return TeraSite.query.filter_by(id_site=site_id).first() @staticmethod def query_data(filter_args): if isinstance(filter_args, tuple): return TeraSite.query.filter_by(*filter_args).all() if isinstance(filter_args, dict): return TeraSite.query.filter_by(**filter_args).all() return None @classmethod def delete(cls, id_todel): super().delete(id_todel) # from opentera.db.models.TeraSession import TeraSession # TeraSession.delete_orphaned_sessions() @classmethod def insert(cls, site): # Creates admin and user roles for that site super().insert(site) from opentera.db.models.TeraServiceRole import TeraServiceRole from opentera.db.models.TeraService import TeraService opentera_service_id = TeraService.get_openteraserver_service().id_service access_role = TeraServiceRole() access_role.id_service = opentera_service_id access_role.id_site = site.id_site access_role.service_role_name = 'admin' db.session.add(access_role) access_role = TeraServiceRole() access_role.id_service = opentera_service_id access_role.id_site = site.id_site access_role.service_role_name = 'user' db.session.add(access_role) db.session.commit() # # @event.listens_for(TeraSite, 'after_insert') # def site_inserted(mapper, connection, target): # # By default, creates user and admin roles after a site has been added # from opentera.db.models.TeraServiceRole import TeraServiceRole # from opentera.db.models.TeraService import TeraService # # access_role = TeraServiceRole() # access_role.id_service = Globals.opentera_service_id # access_role.id_site = target.id_site # access_role.service_role_name = 'admin' # db.session.add(access_role) # # access_role = TeraServiceRole() # access_role.id_service = Globals.opentera_service_id # access_role.id_site = target.id_site # access_role.service_role_name = 'user' # db.session.add(access_role)
en
0.58679
# site_devices = db.relationship("TeraDeviceSite") # Minimal information, delete can not be filtered # from opentera.db.models.TeraSession import TeraSession # TeraSession.delete_orphaned_sessions() # Creates admin and user roles for that site # # @event.listens_for(TeraSite, 'after_insert') # def site_inserted(mapper, connection, target): # # By default, creates user and admin roles after a site has been added # from opentera.db.models.TeraServiceRole import TeraServiceRole # from opentera.db.models.TeraService import TeraService # # access_role = TeraServiceRole() # access_role.id_service = Globals.opentera_service_id # access_role.id_site = target.id_site # access_role.service_role_name = 'admin' # db.session.add(access_role) # # access_role = TeraServiceRole() # access_role.id_service = Globals.opentera_service_id # access_role.id_site = target.id_site # access_role.service_role_name = 'user' # db.session.add(access_role)
2.158138
2
apps/pep8.py
deeplook/streamlit-helpers
0
6622376
<reponame>deeplook/streamlit-helpers import autopep8 import streamlit as st from pygments import highlight from pygments.lexers import PythonLexer from pygments.formatters import HtmlFormatter from .generic import Tool class Pep8(Tool): name = "PEP-8" description = """ Reformat Python source code to follow [PEP-8](https://www.python.org/dev/peps/pep-0008/) style guide. """ def __init__(self): self.text = "" def make_examples(self): return { "Example 1": '''\ def example1(): ####This is a long comment. This should be wrapped to fit within 72 characters. some_tuple=( 1,2, 3,'a' ); some_variable={'long':'Long code lines should be wrapped within 79 characters.', 'other':[math.pi, 100,200,300,9876543210,'This is a long string that goes on'], 'more':{'inner':'This whole logical line should be wrapped.',some_tuple:[1, 20,300,40000,500000000,60000000000000000]}} return (some_tuple, some_variable) ''', } def make_config(self): max_line_length = st.number_input("Max. line length", min_value=40, max_value=120, value=72) aggressive = st.number_input("Aggressive level", min_value=0, value=0) st.session_state.config = dict( max_line_length=max_line_length, aggressive=aggressive ) def make_output(self): options = st.session_state.config # pep8_code = st.text(autopep8.fix_code(self.text, options=options)) style = HtmlFormatter().get_style_defs('.highlight') st.markdown(f"<style>\n{style}\n</style>", unsafe_allow_html=True) st.markdown(highlight(autopep8.fix_code(self.text, options=options), PythonLexer(), HtmlFormatter()), unsafe_allow_html=True)
import autopep8 import streamlit as st from pygments import highlight from pygments.lexers import PythonLexer from pygments.formatters import HtmlFormatter from .generic import Tool class Pep8(Tool): name = "PEP-8" description = """ Reformat Python source code to follow [PEP-8](https://www.python.org/dev/peps/pep-0008/) style guide. """ def __init__(self): self.text = "" def make_examples(self): return { "Example 1": '''\ def example1(): ####This is a long comment. This should be wrapped to fit within 72 characters. some_tuple=( 1,2, 3,'a' ); some_variable={'long':'Long code lines should be wrapped within 79 characters.', 'other':[math.pi, 100,200,300,9876543210,'This is a long string that goes on'], 'more':{'inner':'This whole logical line should be wrapped.',some_tuple:[1, 20,300,40000,500000000,60000000000000000]}} return (some_tuple, some_variable) ''', } def make_config(self): max_line_length = st.number_input("Max. line length", min_value=40, max_value=120, value=72) aggressive = st.number_input("Aggressive level", min_value=0, value=0) st.session_state.config = dict( max_line_length=max_line_length, aggressive=aggressive ) def make_output(self): options = st.session_state.config # pep8_code = st.text(autopep8.fix_code(self.text, options=options)) style = HtmlFormatter().get_style_defs('.highlight') st.markdown(f"<style>\n{style}\n</style>", unsafe_allow_html=True) st.markdown(highlight(autopep8.fix_code(self.text, options=options), PythonLexer(), HtmlFormatter()), unsafe_allow_html=True)
en
0.576235
Reformat Python source code to follow [PEP-8](https://www.python.org/dev/peps/pep-0008/) style guide. \ def example1(): ####This is a long comment. This should be wrapped to fit within 72 characters. some_tuple=( 1,2, 3,'a' ); some_variable={'long':'Long code lines should be wrapped within 79 characters.', 'other':[math.pi, 100,200,300,9876543210,'This is a long string that goes on'], 'more':{'inner':'This whole logical line should be wrapped.',some_tuple:[1, 20,300,40000,500000000,60000000000000000]}} return (some_tuple, some_variable) # pep8_code = st.text(autopep8.fix_code(self.text, options=options))
3.015788
3
robots/migrations/0001_initial.py
zerolab/wagtail-robots
13
6622377
<filename>robots/migrations/0001_initial.py # -*- coding: utf-8 -*- # Generated by Django 1.11.10 on 2018-02-27 05:02 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import modelcluster.fields class Migration(migrations.Migration): initial = True dependencies = [ ('wagtailcore', '0040_page_draft_title'), ] operations = [ migrations.CreateModel( name='AllowedUrl', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('pattern', models.CharField(help_text="Case-sensitive. A missing trailing slash does also match to files which start with the name of the pattern, e.g., '/admin' matches /admin.html too. Some major search engines allow an asterisk (*) as a wildcard and a dollar sign ($) to match the end of the URL, e.g., '/*.jpg$'.", max_length=255, verbose_name='pattern')), ], options={ 'abstract': False, 'verbose_name': 'url', 'verbose_name_plural': 'urls', }, ), migrations.CreateModel( name='DisallowedUrl', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('pattern', models.CharField(help_text="Case-sensitive. A missing trailing slash does also match to files which start with the name of the pattern, e.g., '/admin' matches /admin.html too. Some major search engines allow an asterisk (*) as a wildcard and a dollar sign ($) to match the end of the URL, e.g., '/*.jpg$'.", max_length=255, verbose_name='pattern')), ], options={ 'abstract': False, 'verbose_name': 'url', 'verbose_name_plural': 'urls', }, ), migrations.CreateModel( name='Rule', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('robot', models.CharField(help_text="This should be a user agent string like 'Googlebot'. Enter an asterisk (*) for all user agents. For a full list look at the <a target=_blank href='http://www.robotstxt.org/db.html'> database of Web Robots</a>.", max_length=255, verbose_name='robot')), ('crawl_delay', models.DecimalField(blank=True, decimal_places=1, help_text="Between 0.1 and 99.0. This field is supported by some search engines and defines the delay between successive crawler accesses in seconds. If the crawler rate is a problem for your server, you can set the delay up to 5 or 10 or a comfortable value for your server, but it's suggested to start with small values (0.5-1), and increase as needed to an acceptable value for your server. Larger delay values add more delay between successive crawl accesses and decrease the maximum crawl rate to your web server.", max_digits=3, null=True, verbose_name='crawl delay')), ('sites', models.ManyToManyField(blank=True, help_text='The sites which these rules apply to. If none selected, will apply to all sites. CTRL+Click to deselect.', related_name='sites', to='wagtailcore.Site', verbose_name='sites')), ], options={ 'verbose_name': 'robots.txt rule', 'verbose_name_plural': 'robots.txt rules', }, ), migrations.AddField( model_name='disallowedurl', name='rule', field=modelcluster.fields.ParentalKey(on_delete=django.db.models.deletion.CASCADE, related_name='disallowed', to='robots.Rule'), ), migrations.AddField( model_name='allowedurl', name='rule', field=modelcluster.fields.ParentalKey(on_delete=django.db.models.deletion.CASCADE, related_name='allowed', to='robots.Rule'), ), ]
<filename>robots/migrations/0001_initial.py # -*- coding: utf-8 -*- # Generated by Django 1.11.10 on 2018-02-27 05:02 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import modelcluster.fields class Migration(migrations.Migration): initial = True dependencies = [ ('wagtailcore', '0040_page_draft_title'), ] operations = [ migrations.CreateModel( name='AllowedUrl', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('pattern', models.CharField(help_text="Case-sensitive. A missing trailing slash does also match to files which start with the name of the pattern, e.g., '/admin' matches /admin.html too. Some major search engines allow an asterisk (*) as a wildcard and a dollar sign ($) to match the end of the URL, e.g., '/*.jpg$'.", max_length=255, verbose_name='pattern')), ], options={ 'abstract': False, 'verbose_name': 'url', 'verbose_name_plural': 'urls', }, ), migrations.CreateModel( name='DisallowedUrl', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('pattern', models.CharField(help_text="Case-sensitive. A missing trailing slash does also match to files which start with the name of the pattern, e.g., '/admin' matches /admin.html too. Some major search engines allow an asterisk (*) as a wildcard and a dollar sign ($) to match the end of the URL, e.g., '/*.jpg$'.", max_length=255, verbose_name='pattern')), ], options={ 'abstract': False, 'verbose_name': 'url', 'verbose_name_plural': 'urls', }, ), migrations.CreateModel( name='Rule', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('robot', models.CharField(help_text="This should be a user agent string like 'Googlebot'. Enter an asterisk (*) for all user agents. For a full list look at the <a target=_blank href='http://www.robotstxt.org/db.html'> database of Web Robots</a>.", max_length=255, verbose_name='robot')), ('crawl_delay', models.DecimalField(blank=True, decimal_places=1, help_text="Between 0.1 and 99.0. This field is supported by some search engines and defines the delay between successive crawler accesses in seconds. If the crawler rate is a problem for your server, you can set the delay up to 5 or 10 or a comfortable value for your server, but it's suggested to start with small values (0.5-1), and increase as needed to an acceptable value for your server. Larger delay values add more delay between successive crawl accesses and decrease the maximum crawl rate to your web server.", max_digits=3, null=True, verbose_name='crawl delay')), ('sites', models.ManyToManyField(blank=True, help_text='The sites which these rules apply to. If none selected, will apply to all sites. CTRL+Click to deselect.', related_name='sites', to='wagtailcore.Site', verbose_name='sites')), ], options={ 'verbose_name': 'robots.txt rule', 'verbose_name_plural': 'robots.txt rules', }, ), migrations.AddField( model_name='disallowedurl', name='rule', field=modelcluster.fields.ParentalKey(on_delete=django.db.models.deletion.CASCADE, related_name='disallowed', to='robots.Rule'), ), migrations.AddField( model_name='allowedurl', name='rule', field=modelcluster.fields.ParentalKey(on_delete=django.db.models.deletion.CASCADE, related_name='allowed', to='robots.Rule'), ), ]
en
0.714768
# -*- coding: utf-8 -*- # Generated by Django 1.11.10 on 2018-02-27 05:02
1.859028
2
baekjoon/2587.py
jiyeoun/PS
0
6622378
<reponame>jiyeoun/PS a=int(input()) b=int(input()) c=int(input()) d=int(input()) e=int(input()) print((a+b+c+d+e)//5) list=[a,b,c,d,e] list.sort() print(list[2])
a=int(input()) b=int(input()) c=int(input()) d=int(input()) e=int(input()) print((a+b+c+d+e)//5) list=[a,b,c,d,e] list.sort() print(list[2])
none
1
3.40285
3
legal_advice_builder/__init__.py
prototypefund/django-legal-advice-builder
4
6622379
__title__ = 'Django Legal Advice Builder' __version__ = '0.0.1' __author__ = '<NAME>' __email__ = '<EMAIL>' __license__ = 'Apache-2.0' VERSION = __version__
__title__ = 'Django Legal Advice Builder' __version__ = '0.0.1' __author__ = '<NAME>' __email__ = '<EMAIL>' __license__ = 'Apache-2.0' VERSION = __version__
none
1
1.00451
1
src/recommendation.py
acs6610987/CredibleWeb
0
6622380
<filename>src/recommendation.py import webapp2 from basichandler import BasicHandler from google.appengine.ext.db import stats import random import logging from data_models import URLStorage import urllib import recommendAlg class RandomRMDHandler(BasicHandler): def get(self): # m_stat = stats.KindStat.gql('WHERE kind_name = :1', 'URLStorage').get() # li = [random.randint(1, m_stat.count) for i in range(10)] # query = URLStorage.gql('WHERE index IN :1', li) # recommendations = [item for item in query] recommendations = recommendAlg.randomAlg() self.render('boredRMD.html', recommendations = recommendations) class UserRMDHandler(BasicHandler): def get(self): # m_stat = stats.KindStat.gql('WHERE kind_name = :1', 'URLStorage').get() # n = random.randint(1, m_stat.count) # recommendation = URLStorage.gql('WHERE index = :1', n).get() recommendation = recommendAlg.randomAlg(1)[0] self.redirect('/evaluate?url='+urllib.quote(recommendation.url)) class BoredRmdHandler(BasicHandler): def get(self): bored_rmds = recommendAlg.boredRecommend(self.user.user_id) self.render('bored_rmd.html', bored_rmds = bored_rmds) class HelpRmdHandler(BasicHandler): def get(self): sparse_rmds = recommendAlg.sparseRecommend(self.user.user_id) diff_rmds = recommendAlg.diffRecommend(self.user.user_id) self.render('help_rmd.html', sparse_rmds = sparse_rmds, diff_rmds = diff_rmds) app = webapp2.WSGIApplication([('/randomRMD', RandomRMDHandler), ('/userRMD', UserRMDHandler), ('/bored_rmd', BoredRmdHandler), ('/help_rmd', HelpRmdHandler)], debug = True)
<filename>src/recommendation.py import webapp2 from basichandler import BasicHandler from google.appengine.ext.db import stats import random import logging from data_models import URLStorage import urllib import recommendAlg class RandomRMDHandler(BasicHandler): def get(self): # m_stat = stats.KindStat.gql('WHERE kind_name = :1', 'URLStorage').get() # li = [random.randint(1, m_stat.count) for i in range(10)] # query = URLStorage.gql('WHERE index IN :1', li) # recommendations = [item for item in query] recommendations = recommendAlg.randomAlg() self.render('boredRMD.html', recommendations = recommendations) class UserRMDHandler(BasicHandler): def get(self): # m_stat = stats.KindStat.gql('WHERE kind_name = :1', 'URLStorage').get() # n = random.randint(1, m_stat.count) # recommendation = URLStorage.gql('WHERE index = :1', n).get() recommendation = recommendAlg.randomAlg(1)[0] self.redirect('/evaluate?url='+urllib.quote(recommendation.url)) class BoredRmdHandler(BasicHandler): def get(self): bored_rmds = recommendAlg.boredRecommend(self.user.user_id) self.render('bored_rmd.html', bored_rmds = bored_rmds) class HelpRmdHandler(BasicHandler): def get(self): sparse_rmds = recommendAlg.sparseRecommend(self.user.user_id) diff_rmds = recommendAlg.diffRecommend(self.user.user_id) self.render('help_rmd.html', sparse_rmds = sparse_rmds, diff_rmds = diff_rmds) app = webapp2.WSGIApplication([('/randomRMD', RandomRMDHandler), ('/userRMD', UserRMDHandler), ('/bored_rmd', BoredRmdHandler), ('/help_rmd', HelpRmdHandler)], debug = True)
en
0.302979
# m_stat = stats.KindStat.gql('WHERE kind_name = :1', 'URLStorage').get() # li = [random.randint(1, m_stat.count) for i in range(10)] # query = URLStorage.gql('WHERE index IN :1', li) # recommendations = [item for item in query] # m_stat = stats.KindStat.gql('WHERE kind_name = :1', 'URLStorage').get() # n = random.randint(1, m_stat.count) # recommendation = URLStorage.gql('WHERE index = :1', n).get()
2.45385
2
scripts/misc/detect_s2_partial_scenes.py
caitlinadams/deafrica-scripts
3
6622381
<filename>scripts/misc/detect_s2_partial_scenes.py """ Generate a report on scenes in deafrica-sentinel-2 bucket which have incomplete data E.g command: python generate_report.py "s3://deafrica-sentinel-2-inventory/deafrica-sentinel-2/deafrica-sentinel-2-inventory/2020-11-24T00-00Z/manifest.json" africa_account report.txt """ import json from pathlib import Path import boto3 import click import pandas as pd from tqdm import tqdm MANIFEST_SUFFIX = "manifest.json" SRC_BUCKET_NAME = "deafrica-sentinel-2" INVENTORY_BUCKET_NAME = "s3://deafrica-sentinel-2-inventory/" @click.command() @click.argument("manifest-file") @click.argument("output-filepath") def generate_report(manifest_file, output_filepath): """ Compare Sentinel-2 buckets in US and Africa and detect differences A report containing missing keys will be written to output folder """ s3 = boto3.client("s3", region_name="af-south-1") manifest_file = manifest_file def read_manifest(): bucket, key = manifest_file.replace("s3://", "").split("/", 1) s3_clientobj = s3.get_object(Bucket=bucket, Key=key) return json.loads(s3_clientobj["Body"].read().decode("utf-8")) manifest = read_manifest() df = pd.Series() for obj in tqdm(manifest["files"]): bucket = "deafrica-sentinel-2-inventory" gzip_obj = s3.get_object(Bucket=bucket, Key=obj["key"]) inventory_df = pd.read_csv( gzip_obj["Body"], names=["bucket", "key", "size", "time"], compression="gzip", header=None, ) # second column is the object key inventory_df["key"] = inventory_df["key"].map(lambda a: Path(a).parent) count = inventory_df.groupby("key").count()["size"] partial_inventory = count[count != 18] df = df.append(partial_inventory) # aggregate across files df = df.groupby(df.index).sum() df = df[df != 18] print(f"{len(df)} partial scenes found in {SRC_BUCKET_NAME}") output_file = open(output_filepath, "w") df.index = [ "s3://sentinel-cogs/" + str(x) + "/" + x.name + ".json" for x in df.index ] df.index = df.index.astype(str) output_file.write("\n".join(df.index)) if __name__ == "__main__": generate_report()
<filename>scripts/misc/detect_s2_partial_scenes.py """ Generate a report on scenes in deafrica-sentinel-2 bucket which have incomplete data E.g command: python generate_report.py "s3://deafrica-sentinel-2-inventory/deafrica-sentinel-2/deafrica-sentinel-2-inventory/2020-11-24T00-00Z/manifest.json" africa_account report.txt """ import json from pathlib import Path import boto3 import click import pandas as pd from tqdm import tqdm MANIFEST_SUFFIX = "manifest.json" SRC_BUCKET_NAME = "deafrica-sentinel-2" INVENTORY_BUCKET_NAME = "s3://deafrica-sentinel-2-inventory/" @click.command() @click.argument("manifest-file") @click.argument("output-filepath") def generate_report(manifest_file, output_filepath): """ Compare Sentinel-2 buckets in US and Africa and detect differences A report containing missing keys will be written to output folder """ s3 = boto3.client("s3", region_name="af-south-1") manifest_file = manifest_file def read_manifest(): bucket, key = manifest_file.replace("s3://", "").split("/", 1) s3_clientobj = s3.get_object(Bucket=bucket, Key=key) return json.loads(s3_clientobj["Body"].read().decode("utf-8")) manifest = read_manifest() df = pd.Series() for obj in tqdm(manifest["files"]): bucket = "deafrica-sentinel-2-inventory" gzip_obj = s3.get_object(Bucket=bucket, Key=obj["key"]) inventory_df = pd.read_csv( gzip_obj["Body"], names=["bucket", "key", "size", "time"], compression="gzip", header=None, ) # second column is the object key inventory_df["key"] = inventory_df["key"].map(lambda a: Path(a).parent) count = inventory_df.groupby("key").count()["size"] partial_inventory = count[count != 18] df = df.append(partial_inventory) # aggregate across files df = df.groupby(df.index).sum() df = df[df != 18] print(f"{len(df)} partial scenes found in {SRC_BUCKET_NAME}") output_file = open(output_filepath, "w") df.index = [ "s3://sentinel-cogs/" + str(x) + "/" + x.name + ".json" for x in df.index ] df.index = df.index.astype(str) output_file.write("\n".join(df.index)) if __name__ == "__main__": generate_report()
en
0.757641
Generate a report on scenes in deafrica-sentinel-2 bucket which have incomplete data E.g command: python generate_report.py "s3://deafrica-sentinel-2-inventory/deafrica-sentinel-2/deafrica-sentinel-2-inventory/2020-11-24T00-00Z/manifest.json" africa_account report.txt Compare Sentinel-2 buckets in US and Africa and detect differences A report containing missing keys will be written to output folder # second column is the object key # aggregate across files
3.016829
3
more/content_security/core.py
morepath/more.content_security
1
6622382
import base64 import os from morepath import App from morepath.request import Request from more.content_security.policy import ContentSecurityPolicy # see https://csp.withgoogle.com/docs/faq.html#generating-nonces NONCE_LENGTH = 16 def random_nonce(): return base64.b64encode(os.urandom(NONCE_LENGTH)).decode("utf-8") class ContentSecurityRequest(Request): @property def content_security_policy(self): """Provides access to a request-local version of the content security policy. This policy may be modified without having any effect on the default security policy. """ if not hasattr(self, "_content_security_policy"): self._content_security_policy = ( self.app.settings.content_security_policy.default.copy() ) return self._content_security_policy @content_security_policy.setter def content_security_policy(self, policy): self._content_security_policy = policy def content_security_policy_nonce(self, target): """Generates a nonce that's random once per request, adds it to either 'style-src' or 'script-src' and returns its value. This can be used to whitelist inline scripts/styles with nonces. This way, inline scripts/styles may be used without having to allow all of them in one swoop. """ assert target in ("script", "style") policy = self.content_security_policy nonce = self.content_security_policy_nonce_value directive = f"{target}_src" getattr(policy, directive).add(f"'nonce-{nonce}'") return nonce @property def content_security_policy_nonce_value(self): """Returns the request-bound content security nonce. It is secure to keep this once per request. It is only dangerous to use nonces over more than one request. We use one per request as it ensure that our content security policy header doesn't get bloated if there are a lot of inline scripts/styles. """ if not hasattr(self, "_nonce_value"): self._nonce_value = random_nonce() return self._nonce_value class ContentSecurityApp(App): request_class = ContentSecurityRequest @ContentSecurityApp.setting("content_security_policy", "default") def default_policy(): return ContentSecurityPolicy() @ContentSecurityApp.setting("content_security_policy", "apply_policy") def default_policy_apply_factory(): def apply_policy(policy, request, response): policy.apply(response) return apply_policy @ContentSecurityApp.tween_factory() def content_security_policy_tween_factory(app, handler): policy_settings = app.settings.content_security_policy def content_security_policy_tween(request): response = handler(request) if hasattr(request, "_content_security_policy"): # a custom security policy is used policy = request._content_security_policy else: # the default policy is used policy = policy_settings.default policy_settings.apply_policy(policy, request, response) return response return content_security_policy_tween
import base64 import os from morepath import App from morepath.request import Request from more.content_security.policy import ContentSecurityPolicy # see https://csp.withgoogle.com/docs/faq.html#generating-nonces NONCE_LENGTH = 16 def random_nonce(): return base64.b64encode(os.urandom(NONCE_LENGTH)).decode("utf-8") class ContentSecurityRequest(Request): @property def content_security_policy(self): """Provides access to a request-local version of the content security policy. This policy may be modified without having any effect on the default security policy. """ if not hasattr(self, "_content_security_policy"): self._content_security_policy = ( self.app.settings.content_security_policy.default.copy() ) return self._content_security_policy @content_security_policy.setter def content_security_policy(self, policy): self._content_security_policy = policy def content_security_policy_nonce(self, target): """Generates a nonce that's random once per request, adds it to either 'style-src' or 'script-src' and returns its value. This can be used to whitelist inline scripts/styles with nonces. This way, inline scripts/styles may be used without having to allow all of them in one swoop. """ assert target in ("script", "style") policy = self.content_security_policy nonce = self.content_security_policy_nonce_value directive = f"{target}_src" getattr(policy, directive).add(f"'nonce-{nonce}'") return nonce @property def content_security_policy_nonce_value(self): """Returns the request-bound content security nonce. It is secure to keep this once per request. It is only dangerous to use nonces over more than one request. We use one per request as it ensure that our content security policy header doesn't get bloated if there are a lot of inline scripts/styles. """ if not hasattr(self, "_nonce_value"): self._nonce_value = random_nonce() return self._nonce_value class ContentSecurityApp(App): request_class = ContentSecurityRequest @ContentSecurityApp.setting("content_security_policy", "default") def default_policy(): return ContentSecurityPolicy() @ContentSecurityApp.setting("content_security_policy", "apply_policy") def default_policy_apply_factory(): def apply_policy(policy, request, response): policy.apply(response) return apply_policy @ContentSecurityApp.tween_factory() def content_security_policy_tween_factory(app, handler): policy_settings = app.settings.content_security_policy def content_security_policy_tween(request): response = handler(request) if hasattr(request, "_content_security_policy"): # a custom security policy is used policy = request._content_security_policy else: # the default policy is used policy = policy_settings.default policy_settings.apply_policy(policy, request, response) return response return content_security_policy_tween
en
0.856597
# see https://csp.withgoogle.com/docs/faq.html#generating-nonces Provides access to a request-local version of the content security policy. This policy may be modified without having any effect on the default security policy. Generates a nonce that's random once per request, adds it to either 'style-src' or 'script-src' and returns its value. This can be used to whitelist inline scripts/styles with nonces. This way, inline scripts/styles may be used without having to allow all of them in one swoop. Returns the request-bound content security nonce. It is secure to keep this once per request. It is only dangerous to use nonces over more than one request. We use one per request as it ensure that our content security policy header doesn't get bloated if there are a lot of inline scripts/styles. # a custom security policy is used # the default policy is used
2.411345
2
algo/linear_regression.py
byscut/exercise
0
6622383
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2022/4/25 2:45 下午 # @File : linear_regression.py # @author : Akaya # @Software: PyCharm # linear_regression : import matplotlib.pyplot as plt from scipy import stats x = [5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6] y = [99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86] slope, intercept, r, p, std_err = stats.linregress(x, y) def myfunc(x): return slope * x + intercept mymodel = list(map(myfunc, x)) plt.scatter(x, y) plt.plot(x, mymodel) plt.show()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2022/4/25 2:45 下午 # @File : linear_regression.py # @author : Akaya # @Software: PyCharm # linear_regression : import matplotlib.pyplot as plt from scipy import stats x = [5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6] y = [99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86] slope, intercept, r, p, std_err = stats.linregress(x, y) def myfunc(x): return slope * x + intercept mymodel = list(map(myfunc, x)) plt.scatter(x, y) plt.plot(x, mymodel) plt.show()
zh
0.171739
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2022/4/25 2:45 下午 # @File : linear_regression.py # @author : Akaya # @Software: PyCharm # linear_regression :
3.496309
3
openfl/component/aggregation_functions/geometric_median.py
walteriviera/openfl
0
6622384
<gh_stars>0 # Copyright (C) 2020-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 """Geometric median module.""" from .interface import AggregationFunctionInterface import numpy as np from .weighted_average import weighted_average def _geometric_median_objective(median, tensors, weights): """Compute geometric median objective.""" return sum([w * _l2dist(median, x) for w, x in zip(weights, tensors)]) def geometric_median(tensors, weights, maxiter=4, eps=1e-5, ftol=1e-6): """Compute geometric median of tensors with weights using Weiszfeld's Algorithm.""" weights = np.asarray(weights) / sum(weights) median = weighted_average(tensors, weights) num_oracle_calls = 1 obj_val = _geometric_median_objective(median, tensors, weights) for _ in range(maxiter): prev_obj_val = obj_val weights = np.asarray([w / max(eps, _l2dist(median, x)) for w, x in zip(weights, tensors)]) weights = weights / weights.sum() median = weighted_average(tensors, weights) num_oracle_calls += 1 obj_val = _geometric_median_objective(median, tensors, weights) if abs(prev_obj_val - obj_val) < ftol * obj_val: break return median def _l2dist(p1, p2): """L2 distance between p1, p2, each of which is a list of nd-arrays.""" if p1.ndim != p2.ndim: raise RuntimeError('Tensor shapes should be equal') if p1.ndim < 2: return _l2dist(*[np.expand_dims(x, axis=0) for x in [p1, p2]]) return np.linalg.norm([np.linalg.norm(x1 - x2) for x1, x2 in zip(p1, p2)]) class GeometricMedian(AggregationFunctionInterface): """Geometric median aggregation.""" def call(self, local_tensors, *_) -> np.ndarray: """Aggregate tensors. Args: agg_tensor_dict: Dict of (collaborator name, tensor) pairs to aggregate. weights: array of floats representing data partition (sum up to 1) db_iterator: iterator over history of all tensors. Columns: ['tensor_name', 'round', 'tags', 'nparray'] tensor_name: name of the tensor fl_round: round number tags: tuple of tags for this tensor """ tensors, weights = zip(*[(x.tensor, x.weight) for x in local_tensors]) tensors, weights = np.array(tensors), np.array(weights) return geometric_median(tensors, weights)
# Copyright (C) 2020-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 """Geometric median module.""" from .interface import AggregationFunctionInterface import numpy as np from .weighted_average import weighted_average def _geometric_median_objective(median, tensors, weights): """Compute geometric median objective.""" return sum([w * _l2dist(median, x) for w, x in zip(weights, tensors)]) def geometric_median(tensors, weights, maxiter=4, eps=1e-5, ftol=1e-6): """Compute geometric median of tensors with weights using Weiszfeld's Algorithm.""" weights = np.asarray(weights) / sum(weights) median = weighted_average(tensors, weights) num_oracle_calls = 1 obj_val = _geometric_median_objective(median, tensors, weights) for _ in range(maxiter): prev_obj_val = obj_val weights = np.asarray([w / max(eps, _l2dist(median, x)) for w, x in zip(weights, tensors)]) weights = weights / weights.sum() median = weighted_average(tensors, weights) num_oracle_calls += 1 obj_val = _geometric_median_objective(median, tensors, weights) if abs(prev_obj_val - obj_val) < ftol * obj_val: break return median def _l2dist(p1, p2): """L2 distance between p1, p2, each of which is a list of nd-arrays.""" if p1.ndim != p2.ndim: raise RuntimeError('Tensor shapes should be equal') if p1.ndim < 2: return _l2dist(*[np.expand_dims(x, axis=0) for x in [p1, p2]]) return np.linalg.norm([np.linalg.norm(x1 - x2) for x1, x2 in zip(p1, p2)]) class GeometricMedian(AggregationFunctionInterface): """Geometric median aggregation.""" def call(self, local_tensors, *_) -> np.ndarray: """Aggregate tensors. Args: agg_tensor_dict: Dict of (collaborator name, tensor) pairs to aggregate. weights: array of floats representing data partition (sum up to 1) db_iterator: iterator over history of all tensors. Columns: ['tensor_name', 'round', 'tags', 'nparray'] tensor_name: name of the tensor fl_round: round number tags: tuple of tags for this tensor """ tensors, weights = zip(*[(x.tensor, x.weight) for x in local_tensors]) tensors, weights = np.array(tensors), np.array(weights) return geometric_median(tensors, weights)
en
0.704767
# Copyright (C) 2020-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 Geometric median module. Compute geometric median objective. Compute geometric median of tensors with weights using Weiszfeld's Algorithm. L2 distance between p1, p2, each of which is a list of nd-arrays. Geometric median aggregation. Aggregate tensors. Args: agg_tensor_dict: Dict of (collaborator name, tensor) pairs to aggregate. weights: array of floats representing data partition (sum up to 1) db_iterator: iterator over history of all tensors. Columns: ['tensor_name', 'round', 'tags', 'nparray'] tensor_name: name of the tensor fl_round: round number tags: tuple of tags for this tensor
2.372564
2
SDT.py
Suhail-Athar/Python
3
6622385
import os def sdt(): g = int (input("""What would you like to calculate: Press 1 for Speed Press 2 for Distance Press 3 for Time -- """)) if g == 1: d = int (input('Enter the Distance: ')) t = int (input('Enter the Time: ')) S = d/t print ('The Speed is: ',S) elif g == 2: s = int (input('Enter the Speed: ')) d = int (input('Enter the Distance: ')) T = d/s print ('The time required is: ',T) elif g == 3: s = int (input('Enter the Speed: ')) t = int (input('Enter the Time: ')) D = s * t print ('The distance travelled is: ',D) else: print ('Sorry, Try again') sdt() print ('----------------------------') result=input("Would you like to calculate again? [y/n] > ") if result=='y': os.system('python "C:/Users/DEV-OPS/python/SDT.py"') else: print("Terminating the program...")
import os def sdt(): g = int (input("""What would you like to calculate: Press 1 for Speed Press 2 for Distance Press 3 for Time -- """)) if g == 1: d = int (input('Enter the Distance: ')) t = int (input('Enter the Time: ')) S = d/t print ('The Speed is: ',S) elif g == 2: s = int (input('Enter the Speed: ')) d = int (input('Enter the Distance: ')) T = d/s print ('The time required is: ',T) elif g == 3: s = int (input('Enter the Speed: ')) t = int (input('Enter the Time: ')) D = s * t print ('The distance travelled is: ',D) else: print ('Sorry, Try again') sdt() print ('----------------------------') result=input("Would you like to calculate again? [y/n] > ") if result=='y': os.system('python "C:/Users/DEV-OPS/python/SDT.py"') else: print("Terminating the program...")
en
0.923023
What would you like to calculate: Press 1 for Speed Press 2 for Distance Press 3 for Time --
4.085284
4
GIDI/Test/activeReactions/activeReactions.py
Mathnerd314/gidiplus
0
6622386
#! /usr/bin/env python # <<BEGIN-copyright>> # Copyright 2019, Lawrence Livermore National Security, LLC. # See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: MIT # <<END-copyright>> from __future__ import print_function from argparse import ArgumentParser description = """Compares three output files from activeReactions. The first must be the output from running activeReactions with no -r options and no --invert option. The second and third must be run with the same -r options but one must also have the --invert option and the other must not.""" parser = ArgumentParser( description = description ) parser.add_argument( 'label', help = 'A string to print out if an error is found that indicates the test code.' ) parser.add_argument( 'file1', type = open, help = 'An output file from "activeReactions" with no "-r" option and no "--invert" option.' ) parser.add_argument( 'file2', type = open, help = 'An output file from "activeReactions" some "-r" options.' ) parser.add_argument( 'file3', type = open, help = 'An output file from "activeReactions" the same "-r" options the the prior argument but not the same "--invert" option.' ) args = parser.parse_args( ) def getData( file ) : lines = file.readlines( ) file.close( ) keys = [] data = {} for lineNumber, line in enumerate( lines ) : if( '::' in line ) : key, values = line.split( "::" ) key = key.strip( ) if( key == "" ) : key = priorKey if( key not in keys ) : keys.append( key ) if( key not in data ) : data[key] = [] data[key].append( list( map( float, values.split( ) ) ) ) else : priorKey = line.strip( ) return( keys, data ) keys1, file1 = getData( args.file1 ) dummy, file2 = getData( args.file2 ) dummy, file3 = getData( args.file3 ) for key in keys1 : data1 = file1[key] if( key not in file2 ) : data2 = len( data1 ) * [ [] ] else : data2 = file2[key] if( key not in file3 ) : data3 = len( data1 ) * [ [] ] else : data3 = file3[key] for i1, values1 in enumerate( data1 ) : values2 = data2[i1] values3 = data3[i1] if( len( values2 ) == 0 ) : values2 = len( values1 ) * [ 0.0 ] if( len( values3 ) == 0 ) : values3 = len( values1 ) * [ 0.0 ] for i2, value in enumerate( values1 ) : sum_2_3 = values2[i2] + values3[i2] diff = value - sum_2_3 ratio = diff if( value != 0.0 ) : ratio /= value if( abs( ratio ) > 1e-8 ) : print( ' Bad sum for data "%s" at index %s: %18.9e %18.9e %18.9e %10.2e %9.1e' % ( key, i2, value, values2[i2], values3[i2], diff, ratio ) )
#! /usr/bin/env python # <<BEGIN-copyright>> # Copyright 2019, Lawrence Livermore National Security, LLC. # See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: MIT # <<END-copyright>> from __future__ import print_function from argparse import ArgumentParser description = """Compares three output files from activeReactions. The first must be the output from running activeReactions with no -r options and no --invert option. The second and third must be run with the same -r options but one must also have the --invert option and the other must not.""" parser = ArgumentParser( description = description ) parser.add_argument( 'label', help = 'A string to print out if an error is found that indicates the test code.' ) parser.add_argument( 'file1', type = open, help = 'An output file from "activeReactions" with no "-r" option and no "--invert" option.' ) parser.add_argument( 'file2', type = open, help = 'An output file from "activeReactions" some "-r" options.' ) parser.add_argument( 'file3', type = open, help = 'An output file from "activeReactions" the same "-r" options the the prior argument but not the same "--invert" option.' ) args = parser.parse_args( ) def getData( file ) : lines = file.readlines( ) file.close( ) keys = [] data = {} for lineNumber, line in enumerate( lines ) : if( '::' in line ) : key, values = line.split( "::" ) key = key.strip( ) if( key == "" ) : key = priorKey if( key not in keys ) : keys.append( key ) if( key not in data ) : data[key] = [] data[key].append( list( map( float, values.split( ) ) ) ) else : priorKey = line.strip( ) return( keys, data ) keys1, file1 = getData( args.file1 ) dummy, file2 = getData( args.file2 ) dummy, file3 = getData( args.file3 ) for key in keys1 : data1 = file1[key] if( key not in file2 ) : data2 = len( data1 ) * [ [] ] else : data2 = file2[key] if( key not in file3 ) : data3 = len( data1 ) * [ [] ] else : data3 = file3[key] for i1, values1 in enumerate( data1 ) : values2 = data2[i1] values3 = data3[i1] if( len( values2 ) == 0 ) : values2 = len( values1 ) * [ 0.0 ] if( len( values3 ) == 0 ) : values3 = len( values1 ) * [ 0.0 ] for i2, value in enumerate( values1 ) : sum_2_3 = values2[i2] + values3[i2] diff = value - sum_2_3 ratio = diff if( value != 0.0 ) : ratio /= value if( abs( ratio ) > 1e-8 ) : print( ' Bad sum for data "%s" at index %s: %18.9e %18.9e %18.9e %10.2e %9.1e' % ( key, i2, value, values2[i2], values3[i2], diff, ratio ) )
en
0.734228
#! /usr/bin/env python # <<BEGIN-copyright>> # Copyright 2019, Lawrence Livermore National Security, LLC. # See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: MIT # <<END-copyright>> Compares three output files from activeReactions. The first must be the output from running activeReactions with no -r options and no --invert option. The second and third must be run with the same -r options but one must also have the --invert option and the other must not.
2.895972
3
bin/flaskserver.py
phplaboratory/madcore-ai
0
6622387
from flask import Flask, request, send_from_directory app = Flask(__name__, root_path='/opt/www') @app.route('/<path:path>') def send_static(path): return send_from_directory('', path) if __name__ == '__main__': app.run(host="0.0.0.0", port=int("11180"), debug=True)
from flask import Flask, request, send_from_directory app = Flask(__name__, root_path='/opt/www') @app.route('/<path:path>') def send_static(path): return send_from_directory('', path) if __name__ == '__main__': app.run(host="0.0.0.0", port=int("11180"), debug=True)
none
1
2.510664
3
week5/Task3.py
mcv-m6-video/mcv-m6-2018-team1
0
6622388
from utils import * def task3(): pass
from utils import * def task3(): pass
none
1
0.884672
1
test/db/test_dbing.py
reputage/bluepea
0
6622389
from __future__ import generator_stop import os import stat import tempfile import shutil import binascii import base64 import datetime from collections import OrderedDict as ODict try: import simplejson as json except ImportError: import json import libnacl from ioflo.aid import timing import pytest from pytest import approx from bluepea.bluepeaing import SEPARATOR from bluepea.help.helping import (keyToKey64u, setupTmpBaseDir, cleanupTmpBaseDir, makeSignedAgentReg, makeSignedThingReg) from bluepea.db import dbing from bluepea.prime import priming from bluepea.keep import keeping def test_setupDbEnv(): """ """ print("Testing Setup DB Env") baseDirPath = setupTmpBaseDir() assert baseDirPath.startswith("/tmp/bluepea") assert baseDirPath.endswith("test") dbDirPath = os.path.join(baseDirPath, "bluepea/db") os.makedirs(dbDirPath) assert os.path.exists(dbDirPath) env = dbing.setupDbEnv(baseDirPath=dbDirPath) assert env.path() == dbDirPath assert dbing.gDbDirPath == dbDirPath assert dbing.gDbEnv is env data = ODict() dbCore = dbing.gDbEnv.open_db(b'core') # open named sub db named 'core' within env with dbing.gDbEnv.begin(db=dbCore, write=True) as txn: # txn is a Transaction object data["name"] = "<NAME>" data["city"] = "Alta" datab = json.dumps(data, indent=2).encode("utf-8") txn.put(b'person0', datab) # keys and values are bytes d0b = txn.get(b'person0') assert d0b == datab data["name"] = "<NAME>" data["city"] = "Snowbird" datab = json.dumps(data, indent=2).encode("utf-8") txn.put(b'person1', datab) # keys and values are bytes d1b = txn.get(b'person1') assert d1b == datab d0b = txn.get(b'person0') # re-fetch person0 assert d0b != datab data = json.loads(d0b.decode('utf-8'), object_pairs_hook=ODict) assert data['name'] == "<NAME>" assert data['city'] == "Alta" cleanupTmpBaseDir(dbDirPath) assert not os.path.exists(dbDirPath) print("Done Test") def test_putSigned_getSelfSigned(): """ Test putSigned and getSelfSigned """ print("Testing putSigned and getSelfSigned") dbEnv = dbing.setupTestDbEnv() # Create self signed resource # random seed used to generate private signing key #seed = libnacl.randombytes(libnacl.crypto_sign_SEEDBYTES) seed = (b'PTi\x15\xd5\xd3`\xf1u\x15}^r\x9bfH\x02l\xc6\x1b\x1d\x1c\x0b9\xd7{\xc0_' b'\xf2K\x93`') # creates signing/verification key pair vk, sk = libnacl.crypto_sign_seed_keypair(seed) dt = datetime.datetime(2000, 1, 1, tzinfo=datetime.timezone.utc) stamp = timing.iso8601(dt, aware=True) assert stamp == "2000-01-01T00:00:00+00:00" sig, ser = makeSignedAgentReg(vk, sk, changed=stamp) assert len(sig) == 88 assert sig == ('AeYbsHot0pmdWAcgTo5sD8iAuSQAfnH5U6wiIGpVNJQQoYKBYrPP' 'xAoIc1i5SHCIDS8KFFgf8i0tDq8XGizaCg==') assert len(ser) == 291 assert SEPARATOR not in ser # separator assert ser == ( '{\n' ' "did": "did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=",\n' ' "signer": "did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=#0",\n' ' "changed": "2000-01-01T00:00:00+00:00",\n' ' "keys": [\n' ' {\n' ' "key": "Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=",\n' ' "kind": "EdDSA"\n' ' }\n' ' ]\n' '}') dat = json.loads(ser, object_pairs_hook=ODict) did = dat['did'] assert did == "did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=" dbing.putSigned(key=did, ser=ser, sig=sig, clobber=False) gdat, gser, gsig = dbing.getSelfSigned(did) assert gdat == dat assert gser == ser assert gsig == sig cleanupTmpBaseDir(dbEnv.path()) print("Done Test") def test_putSigned_getSigned(): """ Test putSigned and getSigned """ print("Testing putSigned and getSigned") dbEnv = dbing.setupTestDbEnv() # Create self signed resource # random seed used to generate private signing key #seed = libnacl.randombytes(libnacl.crypto_sign_SEEDBYTES) seed = (b'PTi\x15\xd5\xd3`\xf1u\x15}^r\x9bfH\x02l\xc6\x1b\x1d\x1c\x0b9\xd7{\xc0_' b'\xf2K\x93`') # creates signing/verification key pair svk, ssk = libnacl.crypto_sign_seed_keypair(seed) dt = datetime.datetime(2000, 1, 1, tzinfo=datetime.timezone.utc) stamp = timing.iso8601(dt, aware=True) assert stamp == "2000-01-01T00:00:00+00:00" issuant = ODict(kind="dns", issuer="generic.com", registered=stamp, validationURL="https://generic.com/indigo") issuants = [issuant] # list of issuants of hid name spaces ssig, sser = makeSignedAgentReg(svk, ssk, changed=stamp, issuants=issuants) assert len(ssig) == 88 assert ssig == ('Fgn0uNoZ4OqJrqiKv03HotWztrrM2ZPapf-977nZEtlpk6JPywuFFem6f4UZOZkNcvAbfUalwAr29nkX5P6ADg==') assert len(sser) == 477 assert SEPARATOR not in sser # separator assert sser == ( '{\n' ' "did": "did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=",\n' ' "signer": "did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=#0",\n' ' "changed": "2000-01-01T00:00:00+00:00",\n' ' "keys": [\n' ' {\n' ' "key": "Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=",\n' ' "kind": "EdDSA"\n' ' }\n' ' ],\n' ' "issuants": [\n' ' {\n' ' "kind": "dns",\n' ' "issuer": "generic.com",\n' ' "registered": "2000-01-01T00:00:00+00:00",\n' ' "validationURL": "https://generic.com/indigo"\n' ' }\n' ' ]\n' '}') sdat = json.loads(sser, object_pairs_hook=ODict) sdid = sdat['did'] assert sdid == "did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=" dbing.putSigned(key=sdid, ser=sser, sig=ssig, clobber=False) # creates signing/verification key pair thing DID #seed = libnacl.randombytes(libnacl.crypto_sign_SEEDBYTES) seed = (b'\xba^\xe4\xdd\x81\xeb\x8b\xfa\xb1k\xe2\xfd6~^\x86tC\x9c\xa7\xe3\x1d2\x9d' b'P\xdd&R <\x97\x01') dvk, dsk = libnacl.crypto_sign_seed_keypair(seed) assert dvk == (b'\xe0\x90\x8c\xf1\xd2V\xc3\xf3\xb9\xee\xf38\x90\x0bS\xb7L\x96\xa9(' b'\x01\xbb\x08\x87\xa5X\x1d\xe7\x90b\xa0#') assert dsk == (b'\xba^\xe4\xdd\x81\xeb\x8b\xfa\xb1k\xe2\xfd6~^\x86tC\x9c\xa7\xe3\x1d2\x9d' b'P\xdd&R <\x97\x01\xe0\x90\x8c\xf1\xd2V\xc3\xf3\xb9\xee\xf38\x90\x0bS\xb7' b'L\x96\xa9(\x01\xbb\x08\x87\xa5X\x1d\xe7\x90b\xa0#') signer = sdat['signer'] assert signer == 'did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=#0' hid = "hid:dns:generic.com#02" data = ODict(keywords=["Canon", "EOS Rebel T6", "251440"], message="If found please return.") dsig, tsig, tser = makeSignedThingReg(dvk, dsk, ssk, signer, changed=stamp, hid=hid, data=data) assert tser == ( '{\n' ' "did": "did:igo:4JCM8dJWw_O57vM4kAtTt0yWqSgBuwiHpVgd55BioCM=",\n' ' "hid": "hid:dns:generic.com#02",\n' ' "signer": "did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=#0",\n' ' "changed": "2000-01-01T00:00:00+00:00",\n' ' "data": {\n' ' "keywords": [\n' ' "Canon",\n' ' "EOS Rebel T6",\n' ' "251440"\n' ' ],\n' ' "message": "If found please return."\n' ' }\n' '}') assert dsig == ('kWZwPfepoAV9zyt9B9vPlPNGeb_POHlP9LL3H-PH71WWZzVJT1Ce' '64IKj1GmOXkNo2JaXrnIpQyfm2vynn7mCg==') assert tsig == ('RtlBu9sZgqhfc0QbGe7IHqwsHOARrGNjy4BKJG7gNfNP4GfKDQ8F' 'Gdjyv-EzN1OIHYlnMBFB2Kf05KZAj-g2Cg==') tdat = json.loads(tser, object_pairs_hook=ODict) tdid = tdat['did'] assert tdid == "did:igo:4JCM8dJWw_O57vM4kAtTt0yWqSgBuwiHpVgd55BioCM=" dbing.putSigned(key=tdid, ser=tser, sig=tsig, clobber=False) gdat, gser, gsig = dbing.getSigned(tdid) assert gdat == tdat assert gser == tser assert gsig == tsig dbing.putHid(hid, tdid) # verify hid table entry dbHid2Did = dbEnv.open_db(b'hid2did') # open named sub db named 'hid2did' within env with dbEnv.begin(db=dbHid2Did) as txn: # txn is a Transaction object tdidb = txn.get(hid.encode("utf-8")) # keys are bytes assert tdidb.decode("utf-8") == tdid cleanupTmpBaseDir(dbEnv.path()) print("Done Test") def test_exists(): """ """ print("Testing exits in DB Env") dbEnv = dbing.setupTestDbEnv() data = ODict() data["name"] = "<NAME>" data["city"] = "Alta" datab = json.dumps(data, indent=2).encode("utf-8") dbCore = dbing.gDbEnv.open_db(b'core') # open named sub db named 'core' within env with dbing.gDbEnv.begin(db=dbCore, write=True) as txn: # txn is a Transaction object txn.put(b'person0', datab) # keys and values are bytes d0b = txn.get(b'person0') assert d0b == datab result = dbing.exists(key="person0") assert result is True result = dbing.exists(key="person1") assert result is False cleanupTmpBaseDir(dbEnv.path()) print("Done Test") def test_getEntities(): """ Test get all entities Agents and Things in db getEntities(dbn='core', env=None) """ print("Testing getEntities in DB Env") priming.setupTest() dbEnv = dbing.gDbEnv keeper = keeping.gKeeper kdid = keeper.did agents, things = dbing.setupTestDbAgentsThings() agents['sam'] = (kdid, keeper.verkey, keeper.sigkey) # sam the server entities = dbing.getEntities() assert len(entities) == 6 assert entities == [ODict([('did', 'did:igo:3syVH2woCpOvPF0SD9Z0bu_OxNe2ZgxKjTQ961LlMnA='), ('kind', 'agent')]), ODict([('did', 'did:igo:4JCM8dJWw_O57vM4kAtTt0yWqSgBuwiHpVgd55BioCM='), ('kind', 'thing')]), ODict([('did', 'did:igo:QBRKvLW1CnVDIgznfet3rpad-wZBL4qGASVpGRsE2uU='), ('kind', 'agent')]), ODict([('did', 'did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE='), ('kind', 'agent')]), ODict([('did', 'did:igo:Xq5YqaL6L48pf0fu7IUhL0JRaU2_RxFP0AL43wYn148='), ('kind', 'agent')]), ODict([('did', 'did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY='), ('kind', 'agent')])] cleanupTmpBaseDir(dbEnv.path()) print("Done Test") def test_getAgents(): """ Test get all Agents in db getEntities(dbn='core', env=None) """ print("Testing getAgents in DB Env") priming.setupTest() dbEnv = dbing.gDbEnv keeper = keeping.gKeeper kdid = keeper.did agents, things = dbing.setupTestDbAgentsThings() agents['sam'] = (kdid, keeper.verkey, keeper.sigkey) # sam the server entries = dbing.getAgents() assert len(entries) == 5 assert entries == ['did:igo:3syVH2woCpOvPF0SD9Z0bu_OxNe2ZgxKjTQ961LlMnA=', 'did:igo:QBRKvLW1CnVDIgznfet3rpad-wZBL4qGASVpGRsE2uU=', 'did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=', 'did:igo:Xq5YqaL6L48pf0fu7IUhL0JRaU2_RxFP0AL43wYn148=', 'did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY='] entries = dbing.getAgents(issuer=True) assert len(entries) == 3 assert entries == ['did:igo:3syVH2woCpOvPF0SD9Z0bu_OxNe2ZgxKjTQ961LlMnA=', 'did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=', 'did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY='] cleanupTmpBaseDir(dbEnv.path()) print("Done Test") def test_getThings(): """ Test get all Things in db getEntities(dbn='core', env=None) """ print("Testing getThings in DB Env") priming.setupTest() dbEnv = dbing.gDbEnv keeper = keeping.gKeeper kdid = keeper.did agents, things = dbing.setupTestDbAgentsThings() agents['sam'] = (kdid, keeper.verkey, keeper.sigkey) # sam the server entries = dbing.getThings() assert len(entries) == 1 assert entries == ['did:igo:4JCM8dJWw_O57vM4kAtTt0yWqSgBuwiHpVgd55BioCM='] did = dbing.getHid(key="hid:dns:localhost#02") assert did == entries[0] cleanupTmpBaseDir(dbEnv.path()) print("Done Test") def test_getDrops(): """ Test get essage drop entries in core database for a given did getDrops(did, dbn='core', env=None) """ print("Testing getDrops in DB Env") priming.setupTest() dbEnv = dbing.gDbEnv keeper = keeping.gKeeper kdid = keeper.did agents, things = dbing.setupTestDbAgentsThings() agents['sam'] = (kdid, keeper.verkey, keeper.sigkey) # sam the server for did, vk, sk in agents.values(): dat, ser, sig = dbing.getSelfSigned(did) assert dat is not None assert dat['did'] == did for did, vk, sk in things.values(): dat, ser, sig = dbing.getSigned(did) assert dat is not None assert dat['did'] == did annDid, annVk, annSk = agents['ann'] ivyDid, ivyVk, ivySk = agents['ivy'] thingDid, thingVk, thingSk = things['cam'] assert annDid == "did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=" assert ivyDid == "did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY=" # test empty inbox for ivy messages = dbing.getDrops(ivyDid) assert not messages # test empty inbox for ann messages = dbing.getDrops(annDid) assert not messages # create message from Ann to Ivy dt = datetime.datetime(2000, 1, 3, tzinfo=datetime.timezone.utc) changed = timing.iso8601(dt, aware=True) assert changed == "2000-01-03T00:00:00+00:00" stamp = dt.timestamp() # make time.time value #muid = timing.tuuid(stamp=stamp, prefix="m") muid = "m_00035d2976e6a000_26ace93" assert muid == "m_00035d2976e6a000_26ace93" signer = "{}#0".format(annDid) assert signer == "did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=#0" msg = ODict() msg['uid'] = muid msg['kind'] = "found" msg['signer'] = signer msg['date'] = changed msg['to'] = ivyDid msg['from'] = annDid msg['thing'] = thingDid msg['subject'] = "Lose something?" msg['content'] = "Look what I found" mser = json.dumps(msg, indent=2) msig = keyToKey64u(libnacl.crypto_sign(mser.encode("utf-8"), annSk)[:libnacl.crypto_sign_BYTES]) assert msig == "07u1OcQI8FUeWPqeiga3A9k4MPJGSFmC4vShiJNpv2Rke9ssnW7aLx857HC5ZaJ973WSKkLAwPzkl399d01HBA==" # Build key for message from (to, from, uid) (did, sdid, muid) key = "{}/drop/{}/{}".format(ivyDid, annDid, muid) assert key == ('did:<KEY> '/drop' '/did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=' '/m_00035d2976e6a000_26ace93') # save message to database error if duplicate dbing.putSigned(key=key, ser=mser, sig=msig, clobber=False) # no clobber so error #test get inbox for Ivy messages = dbing.getDrops(ivyDid) assert messages assert len(messages) == 1 assert messages[0]['uid'] == muid assert messages[0]['from'] == annDid # create another message from Ann to Ivy dt = datetime.datetime(2000, 1, 4, tzinfo=datetime.timezone.utc) changed = timing.iso8601(dt, aware=True) assert changed == "2000-01-04T00:00:00+00:00" stamp = dt.timestamp() # make time.time value #muid = timing.tuuid(stamp=stamp, prefix="m") muid = "m_00035d3d94be0000_15aabb5" assert muid == "m_00035d3d94be0000_15aabb5" signer = "{}#0".format(annDid) assert signer == "did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=#0" msg = ODict() msg['uid'] = muid msg['kind'] = "found" msg['signer'] = signer msg['date'] = changed msg['to'] = ivyDid msg['from'] = annDid msg['thing'] = thingDid msg['subject'] = "Lose something?" msg['content'] = "Look what I found again" mser = json.dumps(msg, indent=2) msig = keyToKey64u(libnacl.crypto_sign(mser.encode("utf-8"), annSk)[:libnacl.crypto_sign_BYTES]) assert msig == "<KEY> # Build key for message from (to, from, uid) (did, sdid, muid) key = "{}/drop/{}/{}".format(ivyDid, annDid, muid) assert key == ('<KEY> '/drop' '/did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=' '/m_00035d3d94be0000_15aabb5') # save message to database error if duplicate dbing.putSigned(key=key, ser=mser, sig=msig, clobber=False) # no clobber so error #test get inbox for Ivy messages = dbing.getDrops(ivyDid) assert messages assert len(messages) == 2 assert messages[1]['uid'] == muid assert messages[1]['from'] == annDid # create message from Ivy to Ann dt = datetime.datetime(2000, 1, 4, tzinfo=datetime.timezone.utc) changed = timing.iso8601(dt, aware=True) assert changed == "2000-01-04T00:00:00+00:00" stamp = dt.timestamp() # make time.time value #muid = timing.tuuid(stamp=stamp, prefix="m") muid = "m_00035d3d94be0000_15aabb5" # use duplicate muid to test no collision assert muid == "m_00035d3d94be0000_15aabb5" signer = "{}#0".format(ivyDid) assert signer == "did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY=#0" msg = ODict() msg['uid'] = muid msg['kind'] = "found" msg['signer'] = signer msg['date'] = changed msg['to'] = annDid msg['from'] = ivyDid msg['thing'] = thingDid msg['subject'] = "Lose something?" msg['content'] = "I am so happy your found it." mser = json.dumps(msg, indent=2) msig = keyToKey64u(libnacl.crypto_sign(mser.encode("utf-8"), annSk)[:libnacl.crypto_sign_BYTES]) assert msig == "<KEY> # Build key for message from (to, from, uid) (did, sdid, muid) key = "{}/drop/{}/{}".format(annDid, ivyDid, muid) assert key == ('did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=' '/drop' '/did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY=' '/m_00035d3d94be0000_15aabb5') # save message to database error if duplicate dbing.putSigned(key=key, ser=mser, sig=msig, clobber=False) # no clobber so error #test get inbox for Ann messages = dbing.getDrops(annDid) assert messages assert len(messages) == 1 assert messages[0]['uid'] == muid assert messages[0]['from'] == ivyDid #test get inbox for Ivy to make sure still works messages = dbing.getDrops(ivyDid) assert messages assert len(messages) == 2 for message in messages: assert message['from'] == annDid cleanupTmpBaseDir(dbEnv.path()) print("Done Test") def test_putOfferExpire(): """ Test put entry in did2offer database putOfferExpire(expire, did, ouid, dbn="did2offer", env=None) """ print("Testing putOfferExpire in DB Env") dbEnv = dbing.setupTestDbEnv() dt = datetime.datetime(2000, 1, 1, minute=30, tzinfo=datetime.timezone.utc) #stamp = dt.timestamp() # make time.time value #ouid = timing.tuuid(stamp=stamp, prefix="o") ouid = "o_00035d2976e6a000_26ace93" did = "did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY=" expire = timing.iso8601(dt=dt, aware=True) assert expire == "2000-01-01T00:30:00+00:00" result = dbing.putDidOfferExpire(did, ouid, expire) assert result # verify in database assert dbing.exists(did, dbn='did2offer', dup=True) == True # read from database subDb = dbing.gDbEnv.open_db(b"did2offer", dupsort=True) # open named sub db named dbn within env with dbing.gDbEnv.begin(db=subDb) as txn: # txn is a Transaction object rsrcb = txn.get(did.encode("utf-8")) rsrc = rsrcb.decode("utf-8") assert rsrc == ( '{\n' ' "offer": ' '"did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY=/offer/o_00035d2976e6a000_26ace93",\n' ' "expire": "2000-01-01T00:30:00+00:00"\n' '}') dat = json.loads(rsrc, object_pairs_hook=ODict) offer = "{}/offer/{}".format(did, ouid) assert offer == "did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY=/offer/o_00035d2976e6a000_26ace93" assert dat["offer"] == offer assert dat["expire"] == expire # write another one td = datetime.timedelta(seconds=360) expire1 = timing.iso8601(dt=dt+td, aware=True) assert expire1 == "2000-01-01T00:36:00+00:00" result = dbing.putDidOfferExpire(did, ouid, expire1) assert result == { 'offer': 'did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY=/offer/o_00035d2976e6a000_26ace93', 'expire': '2000-01-01T00:36:00+00:00', } # read from database entries = [] subDb = dbing.gDbEnv.open_db(b"did2offer", dupsort=True) # open named sub db named dbn within env with dbing.gDbEnv.begin(db=subDb) as txn: # txn is a Transaction object with txn.cursor() as cursor: if cursor.set_key(did.encode("utf-8")): entries = [json.loads(value.decode("utf-8"), object_pairs_hook=ODict) for value in cursor.iternext_dup()] assert len(entries) == 2 assert entries[0]["expire"] == expire assert entries[0]["offer"] == offer assert entries[1]["expire"] == expire1 assert entries[1]["offer"] == offer cleanupTmpBaseDir(dbEnv.path()) print("Done Test") def test_getOfferExpires(): """ Test get entries in did2offer database getOfferExpires(did, lastOnly=True, dbn='did2offer', env=None) """ print("Testing getOfferExpires in DB Env") dbEnv = dbing.setupTestDbEnv() dt = datetime.datetime(2000, 1, 1, minute=30, tzinfo=datetime.timezone.utc) #stamp = dt.timestamp() # make time.time value #ouid = timing.tuuid(stamp=stamp, prefix="o") ouid = "o_00035d2976e6a000_26ace93" did = "did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY=" expire = timing.iso8601(dt=dt, aware=True) assert expire == "2000-01-01T00:30:00+00:00" offer = "{}/offer/{}".format(did, ouid) assert offer == "did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY=/offer/o_00035d2976e6a000_26ace93" # no offer expire entries yet entries = dbing.getOfferExpires(did, lastOnly=False) assert entries == [] # write entry result = dbing.putDidOfferExpire(did, ouid, expire) assert result == { 'offer': 'did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY=/offer/o_00035d2976e6a000_26ace93', 'expire': '2000-01-01T00:30:00+00:00' } # write another one td = datetime.timedelta(seconds=360) expire1 = timing.iso8601(dt=dt+td, aware=True) assert expire1 == "2000-01-01T00:36:00+00:00" result = dbing.putDidOfferExpire(did, ouid, expire1) assert result == { 'offer': 'did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY=/offer/o_00035d2976e6a000_26ace93', 'expire': '2000-01-01T00:36:00+00:00' } entries = dbing.getOfferExpires(did, lastOnly=False) assert len(entries) == 2 assert entries[0]["expire"] == expire assert entries[0]["offer"] == offer assert entries[1]["expire"] == expire1 assert entries[1]["offer"] == offer entries = dbing.getOfferExpires(did) # lastOnly=True assert len(entries) == 1 assert entries[0]["expire"] == expire1 assert entries[0]["offer"] == offer cleanupTmpBaseDir(dbEnv.path()) print("Done Test") def test_putGetDeleteAnon(): """ Test putAnonMsg(key, data, dbn="anon", env=None) getAnonMsgs(key, dbn='anon', env=None) deleteAnonMsgs(key, dbn='anon', env=None) where key is ephemeral ID 16 byte hex data is anon data The key for the entry is just the uid uid is up 32 bytes if anon ephemeral ID in base64 url safe content is message up to 256 bytes if location string in base 64 url safe date is iso8601 datetime This is augmented with server time stamp and stored in database { create: 1501774813367861, # creation in server time microseconds since epoch expire: 1501818013367861, # expiration in server time microseconds since epoch anon: { uid: "AQIDBAoLDA0=", # base64 url safe of 8 byte eid content: "EjRWeBI0Vng=", # base64 url safe of 8 byte location date: "2000-01-01T00:36:00+00:00", # ISO-8601 creation date of anon gateway time } } """ print("Testing put get delete Track in DB Env") dbEnv = dbing.setupTestDbEnv() dt = datetime.datetime(2000, 1, 1, minute=30, tzinfo=datetime.timezone.utc) #stamp = dt.timestamp() # make time.time value #create = timing.iso8601(dt=dt, aware=True) #assert create == '2000-01-01T00:30:00+00:00' create = int(dt.timestamp() * 1000000) assert create == 946686600000000 #td = datetime.timedelta(seconds=360) #expire = timing.iso8601(dt=dt+td, aware=True) #assert expire == '2000-01-01T00:36:00+00:00' expire = create + (360 * 1000000) assert expire == 946686960000000 # local time td = datetime.timedelta(seconds=5) date = timing.iso8601(dt=dt+td, aware=True) assert date == '2000-01-01T00:30:05+00:00' uid = "AQIDBAoLDA0=" content = "EjRWeBI0Vng=" anon = ODict() anon['uid'] = uid anon['content'] = content anon['date'] = date assert anon == { "uid": "AQIDBAoLDA0=", "content": "EjRWeBI0Vng=", "date": "2000-01-01T00:30:05+00:00", } data = ODict() data['create'] = create data['expire'] = expire data['anon'] = anon assert data == { "create": 946686600000000, "expire": 946686960000000, "anon": { "uid": "AQIDBAoLDA0=", "content": "EjRWeBI0Vng=", "date": "2000-01-01T00:30:05+00:00" } } # write entry result = dbing.putAnonMsg(key=uid, data=data) assert result # read entries entries = dbing.getAnonMsgs(key=uid) assert len(entries) == 1 assert entries[0] == data anon2 = anon.copy() anon2['content'] = "ABRWeBI0VAA=" data2 = ODict() data2['create'] = create + 1 data2['expire'] = expire + 1 data2['anon'] = anon2 result = dbing.putAnonMsg(key=uid, data=data2) assert result # read entries entries = dbing.getAnonMsgs(key=uid) assert len(entries) == 2 assert entries[0] == data assert entries[1] == data2 uid2 = "BBIDBAoLCCC=" anon3 = anon.copy() anon3["uid"] = uid2 data3 = ODict() data3['create'] = create data3['expire'] = expire data3['anon'] = anon3 result = dbing.putAnonMsg(key=uid2, data=data3) assert result # read entries entries = dbing.getAnonMsgs(key=uid2) assert len(entries) == 1 assert entries[0] == data3 # remove entries at uid result = dbing.deleteAnonMsgs(key=uid) assert result # read deleted entries entries = dbing.getAnonMsgs(key=uid) assert not entries cleanupTmpBaseDir(dbEnv.path()) print("Done Test") def test_getAllAnonUids(): """ Test getAllAnonUids(dbn="anon", env=None) Gets list of Anon Uids no dups The key for the entry is just the uid uid is up 32 bytes if anon ephemeral ID in base64 url safe """ print("Testing put get delete Track in DB Env") dbEnv = dbing.setupTestDbEnv() dt = datetime.datetime(2000, 1, 1, minute=30, tzinfo=datetime.timezone.utc) #stamp = dt.timestamp() # make time.time value #create = timing.iso8601(dt=dt, aware=True) #assert create == '2000-01-01T00:30:00+00:00' create = int(dt.timestamp() * 1000000) assert create == 946686600000000 #td = datetime.timedelta(seconds=360) #expire = timing.iso8601(dt=dt+td, aware=True) #assert expire == '2000-01-01T00:36:00+00:00' expire = create + (360 * 1000000) assert expire == 946686960000000 # local time td = datetime.timedelta(seconds=5) date = timing.iso8601(dt=dt+td, aware=True) assert date == '2000-01-01T00:30:05+00:00' uid1 = "AQIDBAoLDA0=" content = "EjRWeBI0Vng=" anon1 = ODict() anon1['uid'] = uid1 anon1['content'] = content anon1['date'] = date assert anon1 == { "uid": "AQIDBAoLDA0=", "content": "EjRWeBI0Vng=", "date": "2000-01-01T00:30:05+00:00", } data1 = ODict() data1['create'] = create data1['expire'] = expire data1['anon'] = anon1 assert data1 == { "create": 946686600000000, "expire": 946686960000000, "anon": { "uid": "AQIDBAoLDA0=", "content": "EjRWeBI0Vng=", "date": "2000-01-01T00:30:05+00:00" } } # write entry result = dbing.putAnonMsg(key=uid1, data=data1) assert result anon2 = anon1.copy() anon2['content'] = "ABRWeBI0VAA=" data2 = ODict() data2['create'] = create + 1 data2['expire'] = expire + 1 data2['anon'] = anon2 result = dbing.putAnonMsg(key=uid1, data=data2) assert result uid2 = "BBIDBAoLCCC=" anon3 = anon1.copy() anon3["uid"] = uid2 data3 = ODict() data3['create'] = create data3['expire'] = expire data3['anon'] = anon3 result = dbing.putAnonMsg(key=uid2, data=data3) assert result anon4 = anon1.copy() anon4["uid"] = uid2 data4 = ODict() data4['create'] = create data4['expire'] = expire data4['anon'] = anon4 result = dbing.putAnonMsg(key=uid2, data=data4) assert result entries = dbing.getAllAnonUids() assert len(entries) == 2 assert uid1 in entries assert uid2 in entries cleanupTmpBaseDir(dbEnv.path()) print("Done Test") def test_expireUid(): """ Test putExpireUid(expire, uid, dbn="expire2uid", env=None) getExpireUid(key, dbn='expire2uid', env=None) deleteExpireUid(key, dbn='expire2uid', env=None) where key is timestamp in int microseconds since epoch data is anon uid """ print("Testing put get delete expire UID in DB Env") dbEnv = dbing.setupTestDbEnv() dt = datetime.datetime(2000, 1, 3, minute=30, tzinfo=datetime.timezone.utc) expire = int(dt.timestamp() * 1000000) assert expire == 946859400000000 td = datetime.timedelta(seconds=360) expire1 = expire + int(360 * 1000000) assert expire1 == 946859760000000 uid = "00000000000=" uid1 = "11111111111=" uid2 = "22222222222=" # write entry result = dbing.putExpireUid(key=expire, uid=uid) assert result # read entries entries = dbing.getExpireUid(key=expire) assert len(entries) == 1 assert entries[0] == uid result = dbing.putExpireUid(key=expire, uid=uid1) assert result result = dbing.putExpireUid(key=expire, uid=uid2) assert result # read entries entries = dbing.getExpireUid(key=expire) assert len(entries) == 3 assert entries[0] == uid assert entries[1] == uid1 assert entries[2] == uid2 # write entry result = dbing.putExpireUid(key=expire1, uid=uid) assert result entries = dbing.getExpireUid(key=expire1) assert len(entries) == 1 assert entries[0] == uid # remove entries at expire result = dbing.deleteExpireUid(key=expire) assert result # read deleted entries entries = dbing.getExpireUid(key=expire) assert not entries cleanupTmpBaseDir(dbEnv.path()) print("Done Test") def test_popExpired(): """ Test popExpired(key, dbn='expire2uid', env=None) where key is timestamp in int microseconds since epoch """ print("Testing put get delete expire UID in DB Env") dbEnv = dbing.setupTestDbEnv() dt = datetime.datetime(2000, 1, 3, minute=30, tzinfo=datetime.timezone.utc) expire0 = int(dt.timestamp() * 1000000) assert expire0 == 946859400000000 expire1 = expire0 + int(360 * 1000000) assert expire1 == 946859760000000 uid0 = "00000000000=" uid1 = "11111111111=" uid2 = "22222222222=" uid3 = "33333333333=" uid4 = "44444444444=" uid5 = "55555555555=" # write entries at expire result = dbing.putExpireUid(key=expire0, uid=uid0) assert result result = dbing.putExpireUid(key=expire0, uid=uid1) assert result result = dbing.putExpireUid(key=expire0, uid=uid2) assert result # read entries entries = dbing.getExpireUid(key=expire0) assert len(entries) == 3 assert entries[0] == uid0 assert entries[1] == uid1 assert entries[2] == uid2 # write entries result = dbing.putExpireUid(key=expire1, uid=uid3) assert result result = dbing.putExpireUid(key=expire1, uid=uid4) assert result result = dbing.putExpireUid(key=expire1, uid=uid5) assert result entries = dbing.getExpireUid(key=expire1) assert len(entries) == 3 assert entries[0] == uid3 assert entries[1] == uid4 assert entries[2] == uid5 # gets the earliest at expire0 before expire1 entries = dbing.popExpired(key=expire1) assert len(entries) == 3 assert entries[0] == uid0 assert entries[1] == uid1 assert entries[2] == uid2 # attempt to read deleted entries at expire0 entries = dbing.getExpireUid(key=expire0) assert not entries # gets the later at expire1 since expire0 has been deleted entries = dbing.popExpired(key=expire1) assert len(entries) == 3 assert entries[0] == uid3 assert entries[1] == uid4 assert entries[2] == uid5 # attempt to read deleted entries at expire1 entries = dbing.getExpireUid(key=expire1) assert not entries cleanupTmpBaseDir(dbEnv.path()) print("Done Test") def test_clearStaleAnons(): """ Test clearStaleAnonMsgs(key, adbn='anon', edbn='expire2uid', env=None) where key is timestamp in int microseconds since epoch """ print("Testing Clear Stale Anon Msg in DB Env") dbEnv = dbing.setupTestDbEnv() dt = datetime.datetime(2000, 1, 3, minute=30, tzinfo=datetime.timezone.utc) # local time td = datetime.timedelta(seconds=5) date = timing.iso8601(dt=dt+td, aware=True) assert date == '2000-01-03T00:30:05+00:00' content = "12341234123=" create0 = int(dt.timestamp() * 1000000) expire0 = create0 + int(360 * 1000000) create1 = create0 + int(10 * 1000000) expire1 = create1 + int(360 * 1000000) uids0 = ["00000000000=", "10000000000=", "20000000000="] for uid in uids0: anon = ODict() anon['uid'] = uid anon['content'] = content anon['date'] = date data = ODict() data['create'] = create0 data['expire'] = expire0 data['track'] = anon # write entry result = dbing.putAnonMsg(key=uid, data=data) assert result result = dbing.putExpireUid(key=expire0, uid=uid) assert result # read entries for uid in uids0: entries = dbing.getAnonMsgs(key=uid) assert entries entries = dbing.getExpireUid(key=expire0) assert len(entries) == 3 uids1 = ["30000000000=", "40000000000=", "50000000000="] for uid in uids1: anon = ODict() anon['uid'] = uid anon['content'] = content anon['date'] = date data = ODict() data['create'] = create1 data['expire'] = expire1 data['anon'] = anon # write entry result = dbing.putAnonMsg(key=uid, data=data) assert result result = dbing.putExpireUid(key=expire1, uid=uid) assert result # read entries for uid in uids1: entries = dbing.getAnonMsgs(key=uid) assert entries entries = dbing.getExpireUid(key=expire0) assert len(entries) == 3 expire = expire0 - 1 # none expired result = dbing.clearStaleAnonMsgs(key=expire) assert not result expire = expire1 # all expired result = dbing.clearStaleAnonMsgs(key=expire) assert result # verify databases are empty uids = uids0 + uids1 for uid in uids: entries = dbing.getAnonMsgs(key=uid) assert not entries expires = [expire0, expire1] for expire in expires: entries = dbing.getExpireUid(key=expire) assert not entries cleanupTmpBaseDir(dbEnv.path()) print("Done Test") def test_preloadTestDbs(): """ Test preloadTestDbs """ print("Testing staging dbs") priming.setupTest() dbEnv = dbing.gDbEnv dbing.preloadTestDbs() agents = dbing.getAgents() assert agents == ['did:igo:3syVH2woCpOvPF0SD9Z0bu_OxNe2ZgxKjTQ961LlMnA=', 'did:igo:QBRKvLW1CnVDIgznfet3rpad-wZBL4qGASVpGRsE2uU=', 'did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=', 'did:igo:Xq5YqaL6L48pf0fu7IUhL0JRaU2_RxFP0AL43wYn148=', 'did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY='] things = dbing.getThings() assert things == ['did:igo:4JCM8dJWw_O57vM4kAtTt0yWqSgBuwiHpVgd55BioCM='] did = dbing.getHid(key="hid:dns:localhost#02") assert did == things[0] #test get inbox for Ivy messages = dbing.getDrops("did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY=") assert len(messages) == 2 assert messages[0]['from'] == "did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=" #test get inbox for Ann messages = dbing.getDrops("did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=") assert len(messages) == 1 assert messages[0]['from'] == "did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY=" entries = dbing.getOfferExpires('did:igo:4JCM8dJWw_O57vM4kAtTt0yWqSgBuwiHpVgd55BioCM=', lastOnly=False) assert len(entries) == 2 dat, ser, sig = dbing.getSigned(entries[0]["offer"]) assert dat["uid"] == 'o_00035d2976e6a000_26ace93' auids = dbing.getAllAnonUids() assert auids == ['AQIDBAoLDA0=', 'BBIDBAoLCCC='] anons = dbing.getAnonMsgs(key=auids[0]) assert len(anons) == 3 anons = dbing.getAnonMsgs(key=auids[1]) assert len(anons) == 1 cleanupTmpBaseDir(dbEnv.path()) print("Done Test")
from __future__ import generator_stop import os import stat import tempfile import shutil import binascii import base64 import datetime from collections import OrderedDict as ODict try: import simplejson as json except ImportError: import json import libnacl from ioflo.aid import timing import pytest from pytest import approx from bluepea.bluepeaing import SEPARATOR from bluepea.help.helping import (keyToKey64u, setupTmpBaseDir, cleanupTmpBaseDir, makeSignedAgentReg, makeSignedThingReg) from bluepea.db import dbing from bluepea.prime import priming from bluepea.keep import keeping def test_setupDbEnv(): """ """ print("Testing Setup DB Env") baseDirPath = setupTmpBaseDir() assert baseDirPath.startswith("/tmp/bluepea") assert baseDirPath.endswith("test") dbDirPath = os.path.join(baseDirPath, "bluepea/db") os.makedirs(dbDirPath) assert os.path.exists(dbDirPath) env = dbing.setupDbEnv(baseDirPath=dbDirPath) assert env.path() == dbDirPath assert dbing.gDbDirPath == dbDirPath assert dbing.gDbEnv is env data = ODict() dbCore = dbing.gDbEnv.open_db(b'core') # open named sub db named 'core' within env with dbing.gDbEnv.begin(db=dbCore, write=True) as txn: # txn is a Transaction object data["name"] = "<NAME>" data["city"] = "Alta" datab = json.dumps(data, indent=2).encode("utf-8") txn.put(b'person0', datab) # keys and values are bytes d0b = txn.get(b'person0') assert d0b == datab data["name"] = "<NAME>" data["city"] = "Snowbird" datab = json.dumps(data, indent=2).encode("utf-8") txn.put(b'person1', datab) # keys and values are bytes d1b = txn.get(b'person1') assert d1b == datab d0b = txn.get(b'person0') # re-fetch person0 assert d0b != datab data = json.loads(d0b.decode('utf-8'), object_pairs_hook=ODict) assert data['name'] == "<NAME>" assert data['city'] == "Alta" cleanupTmpBaseDir(dbDirPath) assert not os.path.exists(dbDirPath) print("Done Test") def test_putSigned_getSelfSigned(): """ Test putSigned and getSelfSigned """ print("Testing putSigned and getSelfSigned") dbEnv = dbing.setupTestDbEnv() # Create self signed resource # random seed used to generate private signing key #seed = libnacl.randombytes(libnacl.crypto_sign_SEEDBYTES) seed = (b'PTi\x15\xd5\xd3`\xf1u\x15}^r\x9bfH\x02l\xc6\x1b\x1d\x1c\x0b9\xd7{\xc0_' b'\xf2K\x93`') # creates signing/verification key pair vk, sk = libnacl.crypto_sign_seed_keypair(seed) dt = datetime.datetime(2000, 1, 1, tzinfo=datetime.timezone.utc) stamp = timing.iso8601(dt, aware=True) assert stamp == "2000-01-01T00:00:00+00:00" sig, ser = makeSignedAgentReg(vk, sk, changed=stamp) assert len(sig) == 88 assert sig == ('AeYbsHot0pmdWAcgTo5sD8iAuSQAfnH5U6wiIGpVNJQQoYKBYrPP' 'xAoIc1i5SHCIDS8KFFgf8i0tDq8XGizaCg==') assert len(ser) == 291 assert SEPARATOR not in ser # separator assert ser == ( '{\n' ' "did": "did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=",\n' ' "signer": "did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=#0",\n' ' "changed": "2000-01-01T00:00:00+00:00",\n' ' "keys": [\n' ' {\n' ' "key": "Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=",\n' ' "kind": "EdDSA"\n' ' }\n' ' ]\n' '}') dat = json.loads(ser, object_pairs_hook=ODict) did = dat['did'] assert did == "did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=" dbing.putSigned(key=did, ser=ser, sig=sig, clobber=False) gdat, gser, gsig = dbing.getSelfSigned(did) assert gdat == dat assert gser == ser assert gsig == sig cleanupTmpBaseDir(dbEnv.path()) print("Done Test") def test_putSigned_getSigned(): """ Test putSigned and getSigned """ print("Testing putSigned and getSigned") dbEnv = dbing.setupTestDbEnv() # Create self signed resource # random seed used to generate private signing key #seed = libnacl.randombytes(libnacl.crypto_sign_SEEDBYTES) seed = (b'PTi\x15\xd5\xd3`\xf1u\x15}^r\x9bfH\x02l\xc6\x1b\x1d\x1c\x0b9\xd7{\xc0_' b'\xf2K\x93`') # creates signing/verification key pair svk, ssk = libnacl.crypto_sign_seed_keypair(seed) dt = datetime.datetime(2000, 1, 1, tzinfo=datetime.timezone.utc) stamp = timing.iso8601(dt, aware=True) assert stamp == "2000-01-01T00:00:00+00:00" issuant = ODict(kind="dns", issuer="generic.com", registered=stamp, validationURL="https://generic.com/indigo") issuants = [issuant] # list of issuants of hid name spaces ssig, sser = makeSignedAgentReg(svk, ssk, changed=stamp, issuants=issuants) assert len(ssig) == 88 assert ssig == ('Fgn0uNoZ4OqJrqiKv03HotWztrrM2ZPapf-977nZEtlpk6JPywuFFem6f4UZOZkNcvAbfUalwAr29nkX5P6ADg==') assert len(sser) == 477 assert SEPARATOR not in sser # separator assert sser == ( '{\n' ' "did": "did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=",\n' ' "signer": "did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=#0",\n' ' "changed": "2000-01-01T00:00:00+00:00",\n' ' "keys": [\n' ' {\n' ' "key": "Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=",\n' ' "kind": "EdDSA"\n' ' }\n' ' ],\n' ' "issuants": [\n' ' {\n' ' "kind": "dns",\n' ' "issuer": "generic.com",\n' ' "registered": "2000-01-01T00:00:00+00:00",\n' ' "validationURL": "https://generic.com/indigo"\n' ' }\n' ' ]\n' '}') sdat = json.loads(sser, object_pairs_hook=ODict) sdid = sdat['did'] assert sdid == "did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=" dbing.putSigned(key=sdid, ser=sser, sig=ssig, clobber=False) # creates signing/verification key pair thing DID #seed = libnacl.randombytes(libnacl.crypto_sign_SEEDBYTES) seed = (b'\xba^\xe4\xdd\x81\xeb\x8b\xfa\xb1k\xe2\xfd6~^\x86tC\x9c\xa7\xe3\x1d2\x9d' b'P\xdd&R <\x97\x01') dvk, dsk = libnacl.crypto_sign_seed_keypair(seed) assert dvk == (b'\xe0\x90\x8c\xf1\xd2V\xc3\xf3\xb9\xee\xf38\x90\x0bS\xb7L\x96\xa9(' b'\x01\xbb\x08\x87\xa5X\x1d\xe7\x90b\xa0#') assert dsk == (b'\xba^\xe4\xdd\x81\xeb\x8b\xfa\xb1k\xe2\xfd6~^\x86tC\x9c\xa7\xe3\x1d2\x9d' b'P\xdd&R <\x97\x01\xe0\x90\x8c\xf1\xd2V\xc3\xf3\xb9\xee\xf38\x90\x0bS\xb7' b'L\x96\xa9(\x01\xbb\x08\x87\xa5X\x1d\xe7\x90b\xa0#') signer = sdat['signer'] assert signer == 'did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=#0' hid = "hid:dns:generic.com#02" data = ODict(keywords=["Canon", "EOS Rebel T6", "251440"], message="If found please return.") dsig, tsig, tser = makeSignedThingReg(dvk, dsk, ssk, signer, changed=stamp, hid=hid, data=data) assert tser == ( '{\n' ' "did": "did:igo:4JCM8dJWw_O57vM4kAtTt0yWqSgBuwiHpVgd55BioCM=",\n' ' "hid": "hid:dns:generic.com#02",\n' ' "signer": "did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=#0",\n' ' "changed": "2000-01-01T00:00:00+00:00",\n' ' "data": {\n' ' "keywords": [\n' ' "Canon",\n' ' "EOS Rebel T6",\n' ' "251440"\n' ' ],\n' ' "message": "If found please return."\n' ' }\n' '}') assert dsig == ('kWZwPfepoAV9zyt9B9vPlPNGeb_POHlP9LL3H-PH71WWZzVJT1Ce' '64IKj1GmOXkNo2JaXrnIpQyfm2vynn7mCg==') assert tsig == ('RtlBu9sZgqhfc0QbGe7IHqwsHOARrGNjy4BKJG7gNfNP4GfKDQ8F' 'Gdjyv-EzN1OIHYlnMBFB2Kf05KZAj-g2Cg==') tdat = json.loads(tser, object_pairs_hook=ODict) tdid = tdat['did'] assert tdid == "did:igo:4JCM8dJWw_O57vM4kAtTt0yWqSgBuwiHpVgd55BioCM=" dbing.putSigned(key=tdid, ser=tser, sig=tsig, clobber=False) gdat, gser, gsig = dbing.getSigned(tdid) assert gdat == tdat assert gser == tser assert gsig == tsig dbing.putHid(hid, tdid) # verify hid table entry dbHid2Did = dbEnv.open_db(b'hid2did') # open named sub db named 'hid2did' within env with dbEnv.begin(db=dbHid2Did) as txn: # txn is a Transaction object tdidb = txn.get(hid.encode("utf-8")) # keys are bytes assert tdidb.decode("utf-8") == tdid cleanupTmpBaseDir(dbEnv.path()) print("Done Test") def test_exists(): """ """ print("Testing exits in DB Env") dbEnv = dbing.setupTestDbEnv() data = ODict() data["name"] = "<NAME>" data["city"] = "Alta" datab = json.dumps(data, indent=2).encode("utf-8") dbCore = dbing.gDbEnv.open_db(b'core') # open named sub db named 'core' within env with dbing.gDbEnv.begin(db=dbCore, write=True) as txn: # txn is a Transaction object txn.put(b'person0', datab) # keys and values are bytes d0b = txn.get(b'person0') assert d0b == datab result = dbing.exists(key="person0") assert result is True result = dbing.exists(key="person1") assert result is False cleanupTmpBaseDir(dbEnv.path()) print("Done Test") def test_getEntities(): """ Test get all entities Agents and Things in db getEntities(dbn='core', env=None) """ print("Testing getEntities in DB Env") priming.setupTest() dbEnv = dbing.gDbEnv keeper = keeping.gKeeper kdid = keeper.did agents, things = dbing.setupTestDbAgentsThings() agents['sam'] = (kdid, keeper.verkey, keeper.sigkey) # sam the server entities = dbing.getEntities() assert len(entities) == 6 assert entities == [ODict([('did', 'did:igo:3syVH2woCpOvPF0SD9Z0bu_OxNe2ZgxKjTQ961LlMnA='), ('kind', 'agent')]), ODict([('did', 'did:igo:4JCM8dJWw_O57vM4kAtTt0yWqSgBuwiHpVgd55BioCM='), ('kind', 'thing')]), ODict([('did', 'did:igo:QBRKvLW1CnVDIgznfet3rpad-wZBL4qGASVpGRsE2uU='), ('kind', 'agent')]), ODict([('did', 'did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE='), ('kind', 'agent')]), ODict([('did', 'did:igo:Xq5YqaL6L48pf0fu7IUhL0JRaU2_RxFP0AL43wYn148='), ('kind', 'agent')]), ODict([('did', 'did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY='), ('kind', 'agent')])] cleanupTmpBaseDir(dbEnv.path()) print("Done Test") def test_getAgents(): """ Test get all Agents in db getEntities(dbn='core', env=None) """ print("Testing getAgents in DB Env") priming.setupTest() dbEnv = dbing.gDbEnv keeper = keeping.gKeeper kdid = keeper.did agents, things = dbing.setupTestDbAgentsThings() agents['sam'] = (kdid, keeper.verkey, keeper.sigkey) # sam the server entries = dbing.getAgents() assert len(entries) == 5 assert entries == ['did:igo:3syVH2woCpOvPF0SD9Z0bu_OxNe2ZgxKjTQ961LlMnA=', 'did:igo:QBRKvLW1CnVDIgznfet3rpad-wZBL4qGASVpGRsE2uU=', 'did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=', 'did:igo:Xq5YqaL6L48pf0fu7IUhL0JRaU2_RxFP0AL43wYn148=', 'did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY='] entries = dbing.getAgents(issuer=True) assert len(entries) == 3 assert entries == ['did:igo:3syVH2woCpOvPF0SD9Z0bu_OxNe2ZgxKjTQ961LlMnA=', 'did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=', 'did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY='] cleanupTmpBaseDir(dbEnv.path()) print("Done Test") def test_getThings(): """ Test get all Things in db getEntities(dbn='core', env=None) """ print("Testing getThings in DB Env") priming.setupTest() dbEnv = dbing.gDbEnv keeper = keeping.gKeeper kdid = keeper.did agents, things = dbing.setupTestDbAgentsThings() agents['sam'] = (kdid, keeper.verkey, keeper.sigkey) # sam the server entries = dbing.getThings() assert len(entries) == 1 assert entries == ['did:igo:4JCM8dJWw_O57vM4kAtTt0yWqSgBuwiHpVgd55BioCM='] did = dbing.getHid(key="hid:dns:localhost#02") assert did == entries[0] cleanupTmpBaseDir(dbEnv.path()) print("Done Test") def test_getDrops(): """ Test get essage drop entries in core database for a given did getDrops(did, dbn='core', env=None) """ print("Testing getDrops in DB Env") priming.setupTest() dbEnv = dbing.gDbEnv keeper = keeping.gKeeper kdid = keeper.did agents, things = dbing.setupTestDbAgentsThings() agents['sam'] = (kdid, keeper.verkey, keeper.sigkey) # sam the server for did, vk, sk in agents.values(): dat, ser, sig = dbing.getSelfSigned(did) assert dat is not None assert dat['did'] == did for did, vk, sk in things.values(): dat, ser, sig = dbing.getSigned(did) assert dat is not None assert dat['did'] == did annDid, annVk, annSk = agents['ann'] ivyDid, ivyVk, ivySk = agents['ivy'] thingDid, thingVk, thingSk = things['cam'] assert annDid == "did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=" assert ivyDid == "did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY=" # test empty inbox for ivy messages = dbing.getDrops(ivyDid) assert not messages # test empty inbox for ann messages = dbing.getDrops(annDid) assert not messages # create message from Ann to Ivy dt = datetime.datetime(2000, 1, 3, tzinfo=datetime.timezone.utc) changed = timing.iso8601(dt, aware=True) assert changed == "2000-01-03T00:00:00+00:00" stamp = dt.timestamp() # make time.time value #muid = timing.tuuid(stamp=stamp, prefix="m") muid = "m_00035d2976e6a000_26ace93" assert muid == "m_00035d2976e6a000_26ace93" signer = "{}#0".format(annDid) assert signer == "did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=#0" msg = ODict() msg['uid'] = muid msg['kind'] = "found" msg['signer'] = signer msg['date'] = changed msg['to'] = ivyDid msg['from'] = annDid msg['thing'] = thingDid msg['subject'] = "Lose something?" msg['content'] = "Look what I found" mser = json.dumps(msg, indent=2) msig = keyToKey64u(libnacl.crypto_sign(mser.encode("utf-8"), annSk)[:libnacl.crypto_sign_BYTES]) assert msig == "07u1OcQI8FUeWPqeiga3A9k4MPJGSFmC4vShiJNpv2Rke9ssnW7aLx857HC5ZaJ973WSKkLAwPzkl399d01HBA==" # Build key for message from (to, from, uid) (did, sdid, muid) key = "{}/drop/{}/{}".format(ivyDid, annDid, muid) assert key == ('did:<KEY> '/drop' '/did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=' '/m_00035d2976e6a000_26ace93') # save message to database error if duplicate dbing.putSigned(key=key, ser=mser, sig=msig, clobber=False) # no clobber so error #test get inbox for Ivy messages = dbing.getDrops(ivyDid) assert messages assert len(messages) == 1 assert messages[0]['uid'] == muid assert messages[0]['from'] == annDid # create another message from Ann to Ivy dt = datetime.datetime(2000, 1, 4, tzinfo=datetime.timezone.utc) changed = timing.iso8601(dt, aware=True) assert changed == "2000-01-04T00:00:00+00:00" stamp = dt.timestamp() # make time.time value #muid = timing.tuuid(stamp=stamp, prefix="m") muid = "m_00035d3d94be0000_15aabb5" assert muid == "m_00035d3d94be0000_15aabb5" signer = "{}#0".format(annDid) assert signer == "did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=#0" msg = ODict() msg['uid'] = muid msg['kind'] = "found" msg['signer'] = signer msg['date'] = changed msg['to'] = ivyDid msg['from'] = annDid msg['thing'] = thingDid msg['subject'] = "Lose something?" msg['content'] = "Look what I found again" mser = json.dumps(msg, indent=2) msig = keyToKey64u(libnacl.crypto_sign(mser.encode("utf-8"), annSk)[:libnacl.crypto_sign_BYTES]) assert msig == "<KEY> # Build key for message from (to, from, uid) (did, sdid, muid) key = "{}/drop/{}/{}".format(ivyDid, annDid, muid) assert key == ('<KEY> '/drop' '/did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=' '/m_00035d3d94be0000_15aabb5') # save message to database error if duplicate dbing.putSigned(key=key, ser=mser, sig=msig, clobber=False) # no clobber so error #test get inbox for Ivy messages = dbing.getDrops(ivyDid) assert messages assert len(messages) == 2 assert messages[1]['uid'] == muid assert messages[1]['from'] == annDid # create message from Ivy to Ann dt = datetime.datetime(2000, 1, 4, tzinfo=datetime.timezone.utc) changed = timing.iso8601(dt, aware=True) assert changed == "2000-01-04T00:00:00+00:00" stamp = dt.timestamp() # make time.time value #muid = timing.tuuid(stamp=stamp, prefix="m") muid = "m_00035d3d94be0000_15aabb5" # use duplicate muid to test no collision assert muid == "m_00035d3d94be0000_15aabb5" signer = "{}#0".format(ivyDid) assert signer == "did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY=#0" msg = ODict() msg['uid'] = muid msg['kind'] = "found" msg['signer'] = signer msg['date'] = changed msg['to'] = annDid msg['from'] = ivyDid msg['thing'] = thingDid msg['subject'] = "Lose something?" msg['content'] = "I am so happy your found it." mser = json.dumps(msg, indent=2) msig = keyToKey64u(libnacl.crypto_sign(mser.encode("utf-8"), annSk)[:libnacl.crypto_sign_BYTES]) assert msig == "<KEY> # Build key for message from (to, from, uid) (did, sdid, muid) key = "{}/drop/{}/{}".format(annDid, ivyDid, muid) assert key == ('did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=' '/drop' '/did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY=' '/m_00035d3d94be0000_15aabb5') # save message to database error if duplicate dbing.putSigned(key=key, ser=mser, sig=msig, clobber=False) # no clobber so error #test get inbox for Ann messages = dbing.getDrops(annDid) assert messages assert len(messages) == 1 assert messages[0]['uid'] == muid assert messages[0]['from'] == ivyDid #test get inbox for Ivy to make sure still works messages = dbing.getDrops(ivyDid) assert messages assert len(messages) == 2 for message in messages: assert message['from'] == annDid cleanupTmpBaseDir(dbEnv.path()) print("Done Test") def test_putOfferExpire(): """ Test put entry in did2offer database putOfferExpire(expire, did, ouid, dbn="did2offer", env=None) """ print("Testing putOfferExpire in DB Env") dbEnv = dbing.setupTestDbEnv() dt = datetime.datetime(2000, 1, 1, minute=30, tzinfo=datetime.timezone.utc) #stamp = dt.timestamp() # make time.time value #ouid = timing.tuuid(stamp=stamp, prefix="o") ouid = "o_00035d2976e6a000_26ace93" did = "did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY=" expire = timing.iso8601(dt=dt, aware=True) assert expire == "2000-01-01T00:30:00+00:00" result = dbing.putDidOfferExpire(did, ouid, expire) assert result # verify in database assert dbing.exists(did, dbn='did2offer', dup=True) == True # read from database subDb = dbing.gDbEnv.open_db(b"did2offer", dupsort=True) # open named sub db named dbn within env with dbing.gDbEnv.begin(db=subDb) as txn: # txn is a Transaction object rsrcb = txn.get(did.encode("utf-8")) rsrc = rsrcb.decode("utf-8") assert rsrc == ( '{\n' ' "offer": ' '"did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY=/offer/o_00035d2976e6a000_26ace93",\n' ' "expire": "2000-01-01T00:30:00+00:00"\n' '}') dat = json.loads(rsrc, object_pairs_hook=ODict) offer = "{}/offer/{}".format(did, ouid) assert offer == "did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY=/offer/o_00035d2976e6a000_26ace93" assert dat["offer"] == offer assert dat["expire"] == expire # write another one td = datetime.timedelta(seconds=360) expire1 = timing.iso8601(dt=dt+td, aware=True) assert expire1 == "2000-01-01T00:36:00+00:00" result = dbing.putDidOfferExpire(did, ouid, expire1) assert result == { 'offer': 'did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY=/offer/o_00035d2976e6a000_26ace93', 'expire': '2000-01-01T00:36:00+00:00', } # read from database entries = [] subDb = dbing.gDbEnv.open_db(b"did2offer", dupsort=True) # open named sub db named dbn within env with dbing.gDbEnv.begin(db=subDb) as txn: # txn is a Transaction object with txn.cursor() as cursor: if cursor.set_key(did.encode("utf-8")): entries = [json.loads(value.decode("utf-8"), object_pairs_hook=ODict) for value in cursor.iternext_dup()] assert len(entries) == 2 assert entries[0]["expire"] == expire assert entries[0]["offer"] == offer assert entries[1]["expire"] == expire1 assert entries[1]["offer"] == offer cleanupTmpBaseDir(dbEnv.path()) print("Done Test") def test_getOfferExpires(): """ Test get entries in did2offer database getOfferExpires(did, lastOnly=True, dbn='did2offer', env=None) """ print("Testing getOfferExpires in DB Env") dbEnv = dbing.setupTestDbEnv() dt = datetime.datetime(2000, 1, 1, minute=30, tzinfo=datetime.timezone.utc) #stamp = dt.timestamp() # make time.time value #ouid = timing.tuuid(stamp=stamp, prefix="o") ouid = "o_00035d2976e6a000_26ace93" did = "did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY=" expire = timing.iso8601(dt=dt, aware=True) assert expire == "2000-01-01T00:30:00+00:00" offer = "{}/offer/{}".format(did, ouid) assert offer == "did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY=/offer/o_00035d2976e6a000_26ace93" # no offer expire entries yet entries = dbing.getOfferExpires(did, lastOnly=False) assert entries == [] # write entry result = dbing.putDidOfferExpire(did, ouid, expire) assert result == { 'offer': 'did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY=/offer/o_00035d2976e6a000_26ace93', 'expire': '2000-01-01T00:30:00+00:00' } # write another one td = datetime.timedelta(seconds=360) expire1 = timing.iso8601(dt=dt+td, aware=True) assert expire1 == "2000-01-01T00:36:00+00:00" result = dbing.putDidOfferExpire(did, ouid, expire1) assert result == { 'offer': 'did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY=/offer/o_00035d2976e6a000_26ace93', 'expire': '2000-01-01T00:36:00+00:00' } entries = dbing.getOfferExpires(did, lastOnly=False) assert len(entries) == 2 assert entries[0]["expire"] == expire assert entries[0]["offer"] == offer assert entries[1]["expire"] == expire1 assert entries[1]["offer"] == offer entries = dbing.getOfferExpires(did) # lastOnly=True assert len(entries) == 1 assert entries[0]["expire"] == expire1 assert entries[0]["offer"] == offer cleanupTmpBaseDir(dbEnv.path()) print("Done Test") def test_putGetDeleteAnon(): """ Test putAnonMsg(key, data, dbn="anon", env=None) getAnonMsgs(key, dbn='anon', env=None) deleteAnonMsgs(key, dbn='anon', env=None) where key is ephemeral ID 16 byte hex data is anon data The key for the entry is just the uid uid is up 32 bytes if anon ephemeral ID in base64 url safe content is message up to 256 bytes if location string in base 64 url safe date is iso8601 datetime This is augmented with server time stamp and stored in database { create: 1501774813367861, # creation in server time microseconds since epoch expire: 1501818013367861, # expiration in server time microseconds since epoch anon: { uid: "AQIDBAoLDA0=", # base64 url safe of 8 byte eid content: "EjRWeBI0Vng=", # base64 url safe of 8 byte location date: "2000-01-01T00:36:00+00:00", # ISO-8601 creation date of anon gateway time } } """ print("Testing put get delete Track in DB Env") dbEnv = dbing.setupTestDbEnv() dt = datetime.datetime(2000, 1, 1, minute=30, tzinfo=datetime.timezone.utc) #stamp = dt.timestamp() # make time.time value #create = timing.iso8601(dt=dt, aware=True) #assert create == '2000-01-01T00:30:00+00:00' create = int(dt.timestamp() * 1000000) assert create == 946686600000000 #td = datetime.timedelta(seconds=360) #expire = timing.iso8601(dt=dt+td, aware=True) #assert expire == '2000-01-01T00:36:00+00:00' expire = create + (360 * 1000000) assert expire == 946686960000000 # local time td = datetime.timedelta(seconds=5) date = timing.iso8601(dt=dt+td, aware=True) assert date == '2000-01-01T00:30:05+00:00' uid = "AQIDBAoLDA0=" content = "EjRWeBI0Vng=" anon = ODict() anon['uid'] = uid anon['content'] = content anon['date'] = date assert anon == { "uid": "AQIDBAoLDA0=", "content": "EjRWeBI0Vng=", "date": "2000-01-01T00:30:05+00:00", } data = ODict() data['create'] = create data['expire'] = expire data['anon'] = anon assert data == { "create": 946686600000000, "expire": 946686960000000, "anon": { "uid": "AQIDBAoLDA0=", "content": "EjRWeBI0Vng=", "date": "2000-01-01T00:30:05+00:00" } } # write entry result = dbing.putAnonMsg(key=uid, data=data) assert result # read entries entries = dbing.getAnonMsgs(key=uid) assert len(entries) == 1 assert entries[0] == data anon2 = anon.copy() anon2['content'] = "ABRWeBI0VAA=" data2 = ODict() data2['create'] = create + 1 data2['expire'] = expire + 1 data2['anon'] = anon2 result = dbing.putAnonMsg(key=uid, data=data2) assert result # read entries entries = dbing.getAnonMsgs(key=uid) assert len(entries) == 2 assert entries[0] == data assert entries[1] == data2 uid2 = "BBIDBAoLCCC=" anon3 = anon.copy() anon3["uid"] = uid2 data3 = ODict() data3['create'] = create data3['expire'] = expire data3['anon'] = anon3 result = dbing.putAnonMsg(key=uid2, data=data3) assert result # read entries entries = dbing.getAnonMsgs(key=uid2) assert len(entries) == 1 assert entries[0] == data3 # remove entries at uid result = dbing.deleteAnonMsgs(key=uid) assert result # read deleted entries entries = dbing.getAnonMsgs(key=uid) assert not entries cleanupTmpBaseDir(dbEnv.path()) print("Done Test") def test_getAllAnonUids(): """ Test getAllAnonUids(dbn="anon", env=None) Gets list of Anon Uids no dups The key for the entry is just the uid uid is up 32 bytes if anon ephemeral ID in base64 url safe """ print("Testing put get delete Track in DB Env") dbEnv = dbing.setupTestDbEnv() dt = datetime.datetime(2000, 1, 1, minute=30, tzinfo=datetime.timezone.utc) #stamp = dt.timestamp() # make time.time value #create = timing.iso8601(dt=dt, aware=True) #assert create == '2000-01-01T00:30:00+00:00' create = int(dt.timestamp() * 1000000) assert create == 946686600000000 #td = datetime.timedelta(seconds=360) #expire = timing.iso8601(dt=dt+td, aware=True) #assert expire == '2000-01-01T00:36:00+00:00' expire = create + (360 * 1000000) assert expire == 946686960000000 # local time td = datetime.timedelta(seconds=5) date = timing.iso8601(dt=dt+td, aware=True) assert date == '2000-01-01T00:30:05+00:00' uid1 = "AQIDBAoLDA0=" content = "EjRWeBI0Vng=" anon1 = ODict() anon1['uid'] = uid1 anon1['content'] = content anon1['date'] = date assert anon1 == { "uid": "AQIDBAoLDA0=", "content": "EjRWeBI0Vng=", "date": "2000-01-01T00:30:05+00:00", } data1 = ODict() data1['create'] = create data1['expire'] = expire data1['anon'] = anon1 assert data1 == { "create": 946686600000000, "expire": 946686960000000, "anon": { "uid": "AQIDBAoLDA0=", "content": "EjRWeBI0Vng=", "date": "2000-01-01T00:30:05+00:00" } } # write entry result = dbing.putAnonMsg(key=uid1, data=data1) assert result anon2 = anon1.copy() anon2['content'] = "ABRWeBI0VAA=" data2 = ODict() data2['create'] = create + 1 data2['expire'] = expire + 1 data2['anon'] = anon2 result = dbing.putAnonMsg(key=uid1, data=data2) assert result uid2 = "BBIDBAoLCCC=" anon3 = anon1.copy() anon3["uid"] = uid2 data3 = ODict() data3['create'] = create data3['expire'] = expire data3['anon'] = anon3 result = dbing.putAnonMsg(key=uid2, data=data3) assert result anon4 = anon1.copy() anon4["uid"] = uid2 data4 = ODict() data4['create'] = create data4['expire'] = expire data4['anon'] = anon4 result = dbing.putAnonMsg(key=uid2, data=data4) assert result entries = dbing.getAllAnonUids() assert len(entries) == 2 assert uid1 in entries assert uid2 in entries cleanupTmpBaseDir(dbEnv.path()) print("Done Test") def test_expireUid(): """ Test putExpireUid(expire, uid, dbn="expire2uid", env=None) getExpireUid(key, dbn='expire2uid', env=None) deleteExpireUid(key, dbn='expire2uid', env=None) where key is timestamp in int microseconds since epoch data is anon uid """ print("Testing put get delete expire UID in DB Env") dbEnv = dbing.setupTestDbEnv() dt = datetime.datetime(2000, 1, 3, minute=30, tzinfo=datetime.timezone.utc) expire = int(dt.timestamp() * 1000000) assert expire == 946859400000000 td = datetime.timedelta(seconds=360) expire1 = expire + int(360 * 1000000) assert expire1 == 946859760000000 uid = "00000000000=" uid1 = "11111111111=" uid2 = "22222222222=" # write entry result = dbing.putExpireUid(key=expire, uid=uid) assert result # read entries entries = dbing.getExpireUid(key=expire) assert len(entries) == 1 assert entries[0] == uid result = dbing.putExpireUid(key=expire, uid=uid1) assert result result = dbing.putExpireUid(key=expire, uid=uid2) assert result # read entries entries = dbing.getExpireUid(key=expire) assert len(entries) == 3 assert entries[0] == uid assert entries[1] == uid1 assert entries[2] == uid2 # write entry result = dbing.putExpireUid(key=expire1, uid=uid) assert result entries = dbing.getExpireUid(key=expire1) assert len(entries) == 1 assert entries[0] == uid # remove entries at expire result = dbing.deleteExpireUid(key=expire) assert result # read deleted entries entries = dbing.getExpireUid(key=expire) assert not entries cleanupTmpBaseDir(dbEnv.path()) print("Done Test") def test_popExpired(): """ Test popExpired(key, dbn='expire2uid', env=None) where key is timestamp in int microseconds since epoch """ print("Testing put get delete expire UID in DB Env") dbEnv = dbing.setupTestDbEnv() dt = datetime.datetime(2000, 1, 3, minute=30, tzinfo=datetime.timezone.utc) expire0 = int(dt.timestamp() * 1000000) assert expire0 == 946859400000000 expire1 = expire0 + int(360 * 1000000) assert expire1 == 946859760000000 uid0 = "00000000000=" uid1 = "11111111111=" uid2 = "22222222222=" uid3 = "33333333333=" uid4 = "44444444444=" uid5 = "55555555555=" # write entries at expire result = dbing.putExpireUid(key=expire0, uid=uid0) assert result result = dbing.putExpireUid(key=expire0, uid=uid1) assert result result = dbing.putExpireUid(key=expire0, uid=uid2) assert result # read entries entries = dbing.getExpireUid(key=expire0) assert len(entries) == 3 assert entries[0] == uid0 assert entries[1] == uid1 assert entries[2] == uid2 # write entries result = dbing.putExpireUid(key=expire1, uid=uid3) assert result result = dbing.putExpireUid(key=expire1, uid=uid4) assert result result = dbing.putExpireUid(key=expire1, uid=uid5) assert result entries = dbing.getExpireUid(key=expire1) assert len(entries) == 3 assert entries[0] == uid3 assert entries[1] == uid4 assert entries[2] == uid5 # gets the earliest at expire0 before expire1 entries = dbing.popExpired(key=expire1) assert len(entries) == 3 assert entries[0] == uid0 assert entries[1] == uid1 assert entries[2] == uid2 # attempt to read deleted entries at expire0 entries = dbing.getExpireUid(key=expire0) assert not entries # gets the later at expire1 since expire0 has been deleted entries = dbing.popExpired(key=expire1) assert len(entries) == 3 assert entries[0] == uid3 assert entries[1] == uid4 assert entries[2] == uid5 # attempt to read deleted entries at expire1 entries = dbing.getExpireUid(key=expire1) assert not entries cleanupTmpBaseDir(dbEnv.path()) print("Done Test") def test_clearStaleAnons(): """ Test clearStaleAnonMsgs(key, adbn='anon', edbn='expire2uid', env=None) where key is timestamp in int microseconds since epoch """ print("Testing Clear Stale Anon Msg in DB Env") dbEnv = dbing.setupTestDbEnv() dt = datetime.datetime(2000, 1, 3, minute=30, tzinfo=datetime.timezone.utc) # local time td = datetime.timedelta(seconds=5) date = timing.iso8601(dt=dt+td, aware=True) assert date == '2000-01-03T00:30:05+00:00' content = "12341234123=" create0 = int(dt.timestamp() * 1000000) expire0 = create0 + int(360 * 1000000) create1 = create0 + int(10 * 1000000) expire1 = create1 + int(360 * 1000000) uids0 = ["00000000000=", "10000000000=", "20000000000="] for uid in uids0: anon = ODict() anon['uid'] = uid anon['content'] = content anon['date'] = date data = ODict() data['create'] = create0 data['expire'] = expire0 data['track'] = anon # write entry result = dbing.putAnonMsg(key=uid, data=data) assert result result = dbing.putExpireUid(key=expire0, uid=uid) assert result # read entries for uid in uids0: entries = dbing.getAnonMsgs(key=uid) assert entries entries = dbing.getExpireUid(key=expire0) assert len(entries) == 3 uids1 = ["30000000000=", "40000000000=", "50000000000="] for uid in uids1: anon = ODict() anon['uid'] = uid anon['content'] = content anon['date'] = date data = ODict() data['create'] = create1 data['expire'] = expire1 data['anon'] = anon # write entry result = dbing.putAnonMsg(key=uid, data=data) assert result result = dbing.putExpireUid(key=expire1, uid=uid) assert result # read entries for uid in uids1: entries = dbing.getAnonMsgs(key=uid) assert entries entries = dbing.getExpireUid(key=expire0) assert len(entries) == 3 expire = expire0 - 1 # none expired result = dbing.clearStaleAnonMsgs(key=expire) assert not result expire = expire1 # all expired result = dbing.clearStaleAnonMsgs(key=expire) assert result # verify databases are empty uids = uids0 + uids1 for uid in uids: entries = dbing.getAnonMsgs(key=uid) assert not entries expires = [expire0, expire1] for expire in expires: entries = dbing.getExpireUid(key=expire) assert not entries cleanupTmpBaseDir(dbEnv.path()) print("Done Test") def test_preloadTestDbs(): """ Test preloadTestDbs """ print("Testing staging dbs") priming.setupTest() dbEnv = dbing.gDbEnv dbing.preloadTestDbs() agents = dbing.getAgents() assert agents == ['did:igo:3syVH2woCpOvPF0SD9Z0bu_OxNe2ZgxKjTQ961LlMnA=', 'did:igo:QBRKvLW1CnVDIgznfet3rpad-wZBL4qGASVpGRsE2uU=', 'did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=', 'did:igo:Xq5YqaL6L48pf0fu7IUhL0JRaU2_RxFP0AL43wYn148=', 'did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY='] things = dbing.getThings() assert things == ['did:igo:4JCM8dJWw_O57vM4kAtTt0yWqSgBuwiHpVgd55BioCM='] did = dbing.getHid(key="hid:dns:localhost#02") assert did == things[0] #test get inbox for Ivy messages = dbing.getDrops("did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY=") assert len(messages) == 2 assert messages[0]['from'] == "did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=" #test get inbox for Ann messages = dbing.getDrops("did:igo:Qt27fThWoNZsa88VrTkep6H-4HA8tr54sHON1vWl6FE=") assert len(messages) == 1 assert messages[0]['from'] == "did:igo:dZ74MLZXD-1QHoa73w9pQ9GroAvxqFi2RTZWlkC0raY=" entries = dbing.getOfferExpires('did:igo:4JCM8dJWw_O57vM4kAtTt0yWqSgBuwiHpVgd55BioCM=', lastOnly=False) assert len(entries) == 2 dat, ser, sig = dbing.getSigned(entries[0]["offer"]) assert dat["uid"] == 'o_00035d2976e6a000_26ace93' auids = dbing.getAllAnonUids() assert auids == ['AQIDBAoLDA0=', 'BBIDBAoLCCC='] anons = dbing.getAnonMsgs(key=auids[0]) assert len(anons) == 3 anons = dbing.getAnonMsgs(key=auids[1]) assert len(anons) == 1 cleanupTmpBaseDir(dbEnv.path()) print("Done Test")
en
0.667945
# open named sub db named 'core' within env # txn is a Transaction object # keys and values are bytes # keys and values are bytes # re-fetch person0 Test putSigned and getSelfSigned # Create self signed resource # random seed used to generate private signing key #seed = libnacl.randombytes(libnacl.crypto_sign_SEEDBYTES) # creates signing/verification key pair # separator #0",\n' Test putSigned and getSigned # Create self signed resource # random seed used to generate private signing key #seed = libnacl.randombytes(libnacl.crypto_sign_SEEDBYTES) # creates signing/verification key pair # list of issuants of hid name spaces # separator #0",\n' # creates signing/verification key pair thing DID #seed = libnacl.randombytes(libnacl.crypto_sign_SEEDBYTES) #') #') #0' #02" #02",\n' #0",\n' # verify hid table entry # open named sub db named 'hid2did' within env # txn is a Transaction object # keys are bytes # open named sub db named 'core' within env # txn is a Transaction object # keys and values are bytes Test get all entities Agents and Things in db getEntities(dbn='core', env=None) # sam the server Test get all Agents in db getEntities(dbn='core', env=None) # sam the server Test get all Things in db getEntities(dbn='core', env=None) # sam the server #02") Test get essage drop entries in core database for a given did getDrops(did, dbn='core', env=None) # sam the server # test empty inbox for ivy # test empty inbox for ann # create message from Ann to Ivy # make time.time value #muid = timing.tuuid(stamp=stamp, prefix="m") #0".format(annDid) #0" # Build key for message from (to, from, uid) (did, sdid, muid) # save message to database error if duplicate # no clobber so error #test get inbox for Ivy # create another message from Ann to Ivy # make time.time value #muid = timing.tuuid(stamp=stamp, prefix="m") #0".format(annDid) #0" # Build key for message from (to, from, uid) (did, sdid, muid) # save message to database error if duplicate # no clobber so error #test get inbox for Ivy # create message from Ivy to Ann # make time.time value #muid = timing.tuuid(stamp=stamp, prefix="m") # use duplicate muid to test no collision #0".format(ivyDid) #0" # Build key for message from (to, from, uid) (did, sdid, muid) # save message to database error if duplicate # no clobber so error #test get inbox for Ann #test get inbox for Ivy to make sure still works Test put entry in did2offer database putOfferExpire(expire, did, ouid, dbn="did2offer", env=None) #stamp = dt.timestamp() # make time.time value #ouid = timing.tuuid(stamp=stamp, prefix="o") # verify in database # read from database # open named sub db named dbn within env # txn is a Transaction object # write another one # read from database # open named sub db named dbn within env # txn is a Transaction object Test get entries in did2offer database getOfferExpires(did, lastOnly=True, dbn='did2offer', env=None) #stamp = dt.timestamp() # make time.time value #ouid = timing.tuuid(stamp=stamp, prefix="o") # no offer expire entries yet # write entry # write another one # lastOnly=True Test putAnonMsg(key, data, dbn="anon", env=None) getAnonMsgs(key, dbn='anon', env=None) deleteAnonMsgs(key, dbn='anon', env=None) where key is ephemeral ID 16 byte hex data is anon data The key for the entry is just the uid uid is up 32 bytes if anon ephemeral ID in base64 url safe content is message up to 256 bytes if location string in base 64 url safe date is iso8601 datetime This is augmented with server time stamp and stored in database { create: 1501774813367861, # creation in server time microseconds since epoch expire: 1501818013367861, # expiration in server time microseconds since epoch anon: { uid: "AQIDBAoLDA0=", # base64 url safe of 8 byte eid content: "EjRWeBI0Vng=", # base64 url safe of 8 byte location date: "2000-01-01T00:36:00+00:00", # ISO-8601 creation date of anon gateway time } } #stamp = dt.timestamp() # make time.time value #create = timing.iso8601(dt=dt, aware=True) #assert create == '2000-01-01T00:30:00+00:00' #td = datetime.timedelta(seconds=360) #expire = timing.iso8601(dt=dt+td, aware=True) #assert expire == '2000-01-01T00:36:00+00:00' # local time # write entry # read entries # read entries # read entries # remove entries at uid # read deleted entries Test getAllAnonUids(dbn="anon", env=None) Gets list of Anon Uids no dups The key for the entry is just the uid uid is up 32 bytes if anon ephemeral ID in base64 url safe #stamp = dt.timestamp() # make time.time value #create = timing.iso8601(dt=dt, aware=True) #assert create == '2000-01-01T00:30:00+00:00' #td = datetime.timedelta(seconds=360) #expire = timing.iso8601(dt=dt+td, aware=True) #assert expire == '2000-01-01T00:36:00+00:00' # local time # write entry Test putExpireUid(expire, uid, dbn="expire2uid", env=None) getExpireUid(key, dbn='expire2uid', env=None) deleteExpireUid(key, dbn='expire2uid', env=None) where key is timestamp in int microseconds since epoch data is anon uid # write entry # read entries # read entries # write entry # remove entries at expire # read deleted entries Test popExpired(key, dbn='expire2uid', env=None) where key is timestamp in int microseconds since epoch # write entries at expire # read entries # write entries # gets the earliest at expire0 before expire1 # attempt to read deleted entries at expire0 # gets the later at expire1 since expire0 has been deleted # attempt to read deleted entries at expire1 Test clearStaleAnonMsgs(key, adbn='anon', edbn='expire2uid', env=None) where key is timestamp in int microseconds since epoch # local time # write entry # read entries # write entry # read entries # none expired # all expired # verify databases are empty Test preloadTestDbs #02") #test get inbox for Ivy #test get inbox for Ann
1.891338
2
App/pages/data_table.py
ericbdaniels/ddh-qaqc
0
6622390
<reponame>ericbdaniels/ddh-qaqc<gh_stars>0 import dash_bootstrap_components as dbc import pandas as pd from app import db_connection from utils.misc import load_table def table_view(table_name): df = pd.read_sql(f"SELECT * from {table_name}", db_connection) table = load_table(df) return dbc.Container([table], fluid=True)
import dash_bootstrap_components as dbc import pandas as pd from app import db_connection from utils.misc import load_table def table_view(table_name): df = pd.read_sql(f"SELECT * from {table_name}", db_connection) table = load_table(df) return dbc.Container([table], fluid=True)
none
1
2.28471
2
main.py
aleehub/WallpapersWideSpider
0
6622391
from wallpaper import main from categories import getCategoriesList if __name__ == '__main__': # 爬取开始页数 a = 1 # 爬取截止页数 b = 6 header = { "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36\ (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36", 'Cookie': '_ga=GA1.2.1761384977.1568614064; _gid=GA1.2.409143292.1568614064; __gads=ID=b8f347fe9629b571:T=1568614066:S=ALNI_MZf1DuAq9mGzSvHv-vXE_t6_hgnWw; PHPSESSID=16bd3ec1907411f342a53005b6134d07; ae74935a9f5bd890e996f9ae0c7fe805=q5vS1ldKBFw%3D5bsJAoCRxp0%3D5JiQfeVePKY%3Dl4t%2FkEo5S%2Bc%3Daa0wj%2BrGoS4%3DlopdREWA8%2B4%3DquA2PukvyvY%3DQT%2B7MWP5KJ0%3D' } index_url = 'http://wallpaperswide.com' index_href_list, index_name_list = getCategoriesList(index_url, header) index_info_list = [] for i in range(len(index_href_list)): new_href = index_url+index_href_list[i] index_info_list.append((index_name_list[i], new_href)) print(index_info_list) main(a, b, header, index_info_list)
from wallpaper import main from categories import getCategoriesList if __name__ == '__main__': # 爬取开始页数 a = 1 # 爬取截止页数 b = 6 header = { "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36\ (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36", 'Cookie': '_ga=GA1.2.1761384977.1568614064; _gid=GA1.2.409143292.1568614064; __gads=ID=b8f347fe9629b571:T=1568614066:S=ALNI_MZf1DuAq9mGzSvHv-vXE_t6_hgnWw; PHPSESSID=16bd3ec1907411f342a53005b6134d07; ae74935a9f5bd890e996f9ae0c7fe805=q5vS1ldKBFw%3D5bsJAoCRxp0%3D5JiQfeVePKY%3Dl4t%2FkEo5S%2Bc%3Daa0wj%2BrGoS4%3DlopdREWA8%2B4%3DquA2PukvyvY%3DQT%2B7MWP5KJ0%3D' } index_url = 'http://wallpaperswide.com' index_href_list, index_name_list = getCategoriesList(index_url, header) index_info_list = [] for i in range(len(index_href_list)): new_href = index_url+index_href_list[i] index_info_list.append((index_name_list[i], new_href)) print(index_info_list) main(a, b, header, index_info_list)
zh
0.532717
# 爬取开始页数 # 爬取截止页数
2.313176
2
sendfile_osm_oauth_protector/__init__.py
geofabrik/osm-internal-auth
2
6622392
# flake8: noqa: F841 from .authentication_state import AuthenticationState from .config import Config from .key_manager import KeyManager from .oauth_data_cookie import OAuthDataCookie
# flake8: noqa: F841 from .authentication_state import AuthenticationState from .config import Config from .key_manager import KeyManager from .oauth_data_cookie import OAuthDataCookie
it
0.184389
# flake8: noqa: F841
1.11428
1
thingscoop/classifier.py
nishgaddam/thingscoop
1
6622393
import cPickle import caffe import cv2 import glob import logging import numpy import os class ImageClassifier(object): def __init__(self, model, gpu_mode=False): self.model = model kwargs = {} if self.model.get("image_dims"): kwargs['image_dims'] = tuple(self.model.get("image_dims")) if self.model.get("channel_swap"): kwargs['channel_swap'] = tuple(self.model.get("channel_swap")) if self.model.get("raw_scale"): kwargs['raw_scale'] = float(self.model.get("raw_scale")) if self.model.get("mean"): kwargs['mean'] = numpy.array(self.model.get("mean")) self.net = caffe.Classifier( model.deploy_path(), model.model_path(), **kwargs ) self.confidence_threshold = 0.1 if gpu_mode: caffe.set_mode_gpu() else: caffe.set_mode_cpu() self.labels = numpy.array(model.labels()) if self.model.bet_path(): self.bet = cPickle.load(open(self.model.bet_path())) self.bet['words'] = map(lambda w: w.replace(' ', '_'), self.bet['words']) else: self.bet = None self.net.forward() def classify_image(self, filename): image = caffe.io.load_image(open(filename)) scores = self.net.predict([image], oversample=True).flatten() if self.bet: expected_infogain = numpy.dot(self.bet['probmat'], scores[self.bet['idmapping']]) expected_infogain *= self.bet['infogain'] infogain_sort = expected_infogain.argsort()[::-1] results = [ (self.bet['words'][v], float(expected_infogain[v])) for v in infogain_sort if expected_infogain[v] > self.confidence_threshold ] else: indices = (-scores).argsort() predictions = self.labels[indices] results = [ (p, float(scores[i])) for i, p in zip(indices, predictions) if scores[i] > self.confidence_threshold ] return results
import cPickle import caffe import cv2 import glob import logging import numpy import os class ImageClassifier(object): def __init__(self, model, gpu_mode=False): self.model = model kwargs = {} if self.model.get("image_dims"): kwargs['image_dims'] = tuple(self.model.get("image_dims")) if self.model.get("channel_swap"): kwargs['channel_swap'] = tuple(self.model.get("channel_swap")) if self.model.get("raw_scale"): kwargs['raw_scale'] = float(self.model.get("raw_scale")) if self.model.get("mean"): kwargs['mean'] = numpy.array(self.model.get("mean")) self.net = caffe.Classifier( model.deploy_path(), model.model_path(), **kwargs ) self.confidence_threshold = 0.1 if gpu_mode: caffe.set_mode_gpu() else: caffe.set_mode_cpu() self.labels = numpy.array(model.labels()) if self.model.bet_path(): self.bet = cPickle.load(open(self.model.bet_path())) self.bet['words'] = map(lambda w: w.replace(' ', '_'), self.bet['words']) else: self.bet = None self.net.forward() def classify_image(self, filename): image = caffe.io.load_image(open(filename)) scores = self.net.predict([image], oversample=True).flatten() if self.bet: expected_infogain = numpy.dot(self.bet['probmat'], scores[self.bet['idmapping']]) expected_infogain *= self.bet['infogain'] infogain_sort = expected_infogain.argsort()[::-1] results = [ (self.bet['words'][v], float(expected_infogain[v])) for v in infogain_sort if expected_infogain[v] > self.confidence_threshold ] else: indices = (-scores).argsort() predictions = self.labels[indices] results = [ (p, float(scores[i])) for i, p in zip(indices, predictions) if scores[i] > self.confidence_threshold ] return results
none
1
2.255943
2
server.py
mcarval4/chat_socket
0
6622394
<reponame>mcarval4/chat_socket<gh_stars>0 import re import Pyro4 # Administração de servidor de chat. # Trata logins, logouts, canais e apelidos, @Pyro4.expose @Pyro4.behavior(instance_mode="single") class ChatBox(object): def __init__(self): self.channels = {} # canais registrados {canal --> (apelido, client callback) lista} self.nicks = [] # todos apelidos registrados def getChannels(self): return list(self.channels.keys()) def getNicks(self): self.nicks # Função para criar um novo canal ou apelido def join(self, channel, nick, callback): if not channel or not nick: raise ValueError("canal ou apelido inválido") if nick in self.nicks: raise ValueError('esse apelido já está em uso') if channel not in self.channels: print('CRIANDO UM NOVO CANAL %s' % channel) self.channels[channel] = [] self.channels[channel].append((nick, callback)) self.nicks.append(nick) print("%s ENTROU %s" % (nick, channel)) self.publish(channel, 'SERVIDOR', '** ' + nick + ' entrou **') return [nick for (nick, c) in self.channels[channel]] # retorna todos os apelidos do canal # Função para saída do usuário e para limpar a lista com os usuários que saíram def leave(self, channel, nick): if channel not in self.channels: print('CANAL DESCONHECIDO IGNORADO %s' % channel) return for (n, c) in self.channels[channel]: if n == nick: self.channels[channel].remove((n, c)) break self.publish(channel, 'SERVIDOR', '** ' + nick + ' saiu **') if len(self.channels[channel]) < 1: del self.channels[channel] print('CANAL REMOVIDO %s' % channel) self.nicks.remove(nick) print("%s SAIU %s" % (nick, channel)) # Função para publicar as mensagens e remover canais ociosos def publish(self, channel, nick, msg): if channel not in self.channels: print('CANAL DESCONHECIDO IGNORADO %s' % channel) return match = re.match("^\#(\w+)\s(.+)", msg) for (n, c) in self.channels[channel][:]: # print(self.channels[channel][1]) # print(getNicks()) print("n -> %s\n c -> %s" % (n, c)) try: if match == None: c.message(nick, msg) # oneway call elif match.group(1) == n: print("Tentando mandar msg privada de {} para {}".format(nick, n)) m = "Privado de {}: {}".format(nick, match.group(2)) c.message(nick, m) # oneway call except Pyro4.errors.ConnectionClosedError: # queda de conexão, remove o listener se ainda houver # checa a existência porque outra thread por ter finalizado. if (n, c) in self.channels[channel]: self.channels[channel].remove((n, c)) print('Dead listener removidos %s %s' % (n, c)) # Função para enviar as mensagens privadas para os usuários def private_publish(self, nick, msg): if nick not in self.nicks: print('USUÁRIO DESCONHECIDO IGNORADO %s' % nick) return for (n, c) in self.nicks[nick][:]: try: c_split = c.split() print(c_split[6][:57]) uri_string = c_split[6][:57] c.pv_message(nick, msg, uri_string) except Pyro4.errors.ConnectionClosedError: if (n, c) in self.nicks[nick]: self.nicks[nick].remove((n, c)) print('Dead listener removidos %s %s' % (n, c)) Pyro4.Daemon.serveSimple( { ChatBox: "chatbox" }, ns=True )
import re import Pyro4 # Administração de servidor de chat. # Trata logins, logouts, canais e apelidos, @Pyro4.expose @Pyro4.behavior(instance_mode="single") class ChatBox(object): def __init__(self): self.channels = {} # canais registrados {canal --> (apelido, client callback) lista} self.nicks = [] # todos apelidos registrados def getChannels(self): return list(self.channels.keys()) def getNicks(self): self.nicks # Função para criar um novo canal ou apelido def join(self, channel, nick, callback): if not channel or not nick: raise ValueError("canal ou apelido inválido") if nick in self.nicks: raise ValueError('esse apelido já está em uso') if channel not in self.channels: print('CRIANDO UM NOVO CANAL %s' % channel) self.channels[channel] = [] self.channels[channel].append((nick, callback)) self.nicks.append(nick) print("%s ENTROU %s" % (nick, channel)) self.publish(channel, 'SERVIDOR', '** ' + nick + ' entrou **') return [nick for (nick, c) in self.channels[channel]] # retorna todos os apelidos do canal # Função para saída do usuário e para limpar a lista com os usuários que saíram def leave(self, channel, nick): if channel not in self.channels: print('CANAL DESCONHECIDO IGNORADO %s' % channel) return for (n, c) in self.channels[channel]: if n == nick: self.channels[channel].remove((n, c)) break self.publish(channel, 'SERVIDOR', '** ' + nick + ' saiu **') if len(self.channels[channel]) < 1: del self.channels[channel] print('CANAL REMOVIDO %s' % channel) self.nicks.remove(nick) print("%s SAIU %s" % (nick, channel)) # Função para publicar as mensagens e remover canais ociosos def publish(self, channel, nick, msg): if channel not in self.channels: print('CANAL DESCONHECIDO IGNORADO %s' % channel) return match = re.match("^\#(\w+)\s(.+)", msg) for (n, c) in self.channels[channel][:]: # print(self.channels[channel][1]) # print(getNicks()) print("n -> %s\n c -> %s" % (n, c)) try: if match == None: c.message(nick, msg) # oneway call elif match.group(1) == n: print("Tentando mandar msg privada de {} para {}".format(nick, n)) m = "Privado de {}: {}".format(nick, match.group(2)) c.message(nick, m) # oneway call except Pyro4.errors.ConnectionClosedError: # queda de conexão, remove o listener se ainda houver # checa a existência porque outra thread por ter finalizado. if (n, c) in self.channels[channel]: self.channels[channel].remove((n, c)) print('Dead listener removidos %s %s' % (n, c)) # Função para enviar as mensagens privadas para os usuários def private_publish(self, nick, msg): if nick not in self.nicks: print('USUÁRIO DESCONHECIDO IGNORADO %s' % nick) return for (n, c) in self.nicks[nick][:]: try: c_split = c.split() print(c_split[6][:57]) uri_string = c_split[6][:57] c.pv_message(nick, msg, uri_string) except Pyro4.errors.ConnectionClosedError: if (n, c) in self.nicks[nick]: self.nicks[nick].remove((n, c)) print('Dead listener removidos %s %s' % (n, c)) Pyro4.Daemon.serveSimple( { ChatBox: "chatbox" }, ns=True )
pt
0.923334
# Administração de servidor de chat. # Trata logins, logouts, canais e apelidos, # canais registrados {canal --> (apelido, client callback) lista} # todos apelidos registrados # Função para criar um novo canal ou apelido # retorna todos os apelidos do canal # Função para saída do usuário e para limpar a lista com os usuários que saíram # Função para publicar as mensagens e remover canais ociosos #(\w+)\s(.+)", msg) # print(self.channels[channel][1]) # print(getNicks()) # oneway call # oneway call # queda de conexão, remove o listener se ainda houver # checa a existência porque outra thread por ter finalizado. # Função para enviar as mensagens privadas para os usuários
2.974843
3
journey11/src/interface/agent.py
parrisma/AI-intuition
0
6622395
<gh_stars>0 import threading from copy import deepcopy from abc import abstractmethod from pubsub import pub from typing import List from journey11.src.interface.notification import Notification from journey11.src.interface.srcsink import SrcSink from journey11.src.interface.tasknotification import TaskNotification from journey11.src.interface.worknotificationdo import WorkNotificationDo from journey11.src.interface.taskconsumptionpolicy import TaskConsumptionPolicy from journey11.src.interface.worknotificationfinalise import WorkNotificationFinalise from journey11.src.interface.worknotificationinitiate import WorkNotificationInitiate from journey11.src.interface.capability import Capability from journey11.src.interface.srcsinkping import SrcSinkPing from journey11.src.interface.srcsinkpingnotification import SrcSinkPingNotification from journey11.src.lib.notificationhandler import NotificationHandler from journey11.src.lib.purevirtual import purevirtual from journey11.src.lib.state import State from journey11.src.lib.uniquetopic import UniqueTopic from journey11.src.main.simple.simplecapability import SimpleCapability from journey11.src.lib.capabilityregister import CapabilityRegister from journey11.src.lib.addressbook import AddressBook class Agent(SrcSink): WORK_TIMER = float(.25) WORK_TIMER_MAX = float(30) PRS_TIMER = float(.25) PRD_TIMER_MAX = float(60) WORK_INIT_TIMER = float(.25) WORK_INIT_TIMER_MAX = float(180) AGENT_TOPIC_PREFIX = "agent" def __init__(self, agent_name: str): """ Register all notification handlers & activities. """ self._address_book = AddressBook() self._lock = threading.RLock() self._subscribed_topics = list() super().__init__() self._work_timer = Agent.WORK_TIMER self._timer = None self._task_consumption_policy = None self._handler = NotificationHandler(object_to_be_handler_for=self, throw_unhandled=False) self._handler.register_handler(self._do_notification, TaskNotification) self._handler.register_handler(self._do_work, WorkNotificationDo) self._handler.register_handler(self._do_work_finalise, WorkNotificationFinalise) self._handler.register_handler(self._do_work_initiate, WorkNotificationInitiate) self._handler.register_handler(self._do_srcsink_ping, SrcSinkPing) self._handler.register_handler(self._do_srcsink_ping_notification, SrcSinkPingNotification) self._handler.register_activity(handler_for_activity=self._activity_check_work_to_do, activity_interval=self._work_timer, activity_name="{}-activity-work-to-do".format(agent_name)) self._handler.register_activity(handler_for_activity=self._activity_manage_presence, activity_interval=Agent.PRS_TIMER, activity_name="{}-activity-manage-presence".format(agent_name)) self._handler.register_activity(handler_for_activity=self._activity_initiate_work, activity_interval=Agent.WORK_INIT_TIMER, activity_name="{}-activity-work-init".format(agent_name)) self._unique_topic = self._create_topic_and_subscriptions() self._capabilities = self._get_capabilities() return def __del__(self): """ Shut down """ self._handler.activity_state(paused=True) with self._lock: sub_list = deepcopy(self._subscribed_topics) for topic in sub_list: pub.unsubscribe(self, topic) return def __call__(self, notification: Notification): """ Handle notification requests :param notification: The notification to be passed to the handler """ if isinstance(notification, Notification): self._handler.call_handler(notification) else: raise ValueError("{} is an un supported notification type for Agent}".format(type(notification).__name__)) return def _create_topic_and_subscriptions(self) -> str: """ Create the unique topic for the agent that it will listen on for work (task) deliveries that it has requested from the task-pool """ topics = list() unique_topic = UniqueTopic().topic(Agent.AGENT_TOPIC_PREFIX) topics.append(unique_topic) for topic in self._work_topics(): topics.append(topic) self.add_subscription_topics(topics=topics) for topic in topics: # do potentially high latency subscriptions outside of the lock. pub.subscribe(self, topic) return unique_topic def add_subscription_topics(self, topics: List[str]) -> None: """ Add the given list of topics to the list of topics agent is subscribed to """ with self._lock: for topic in topics: if topic not in self._subscribed_topics: self._subscribed_topics.append(topic) return @staticmethod def _get_capabilities() -> List[Capability]: """ The capabilities of this Agent :return: List of Capabilities """ return [SimpleCapability(capability_name=str(CapabilityRegister.AGENT))] @abstractmethod @purevirtual def _do_notification(self, task_notification: TaskNotification): """ callback to Notify agent of a task that needs attention. The agent can optionally grab the task from the task pool and work on it or ignore it. :param task_notification: The notification event for task requiring attention """ pass @abstractmethod @purevirtual def _do_work(self, work_notification: WorkNotificationDo) -> None: """ Process any out standing tasks associated with the agent. """ pass @abstractmethod @purevirtual def _do_work_initiate(self, work_notification: WorkNotificationInitiate) -> None: """ Handle the initiation the given work item from this agent """ pass @abstractmethod @purevirtual def _do_work_finalise(self, work_notification_finalise: WorkNotificationFinalise) -> None: """ Take receipt of the given completed work item that was initiated from this agent and do any final processing. """ pass @abstractmethod @purevirtual def work_initiate(self, work_notification: WorkNotificationDo) -> None: """ Initiate the given work item with the agent as the owner of the work. """ pass @abstractmethod @purevirtual def _activity_check_work_to_do(self, current_activity_interval: float) -> float: """ Are there any tasks associated with the Agent that need working on ? of so schedule them by calling work execute handler. :param current_activity_interval: The current delay in seconds before activity is re-triggered. :return: The new delay in seconds before the activity is re-triggered. """ pass @purevirtual @abstractmethod def _activity_manage_presence(self, current_activity_interval: float) -> float: """ Ensure that we are known on the ether & our address book has the name of at least one local pool in it. :param current_activity_interval: The current delay in seconds before activity is re-triggered. :return: The new delay in seconds before the activity is re-triggered. """ pass @purevirtual @abstractmethod def _activity_initiate_work(self, current_activity_interval: float) -> float: """ If the agent is a source (origin) of work then this activity will create and inject the new tasks. Zero or more tasks may be created depending on the specific task creation policy. :param current_activity_interval: The current delay in seconds before activity is re-triggered. :return: The new delay in seconds before the activity is re-triggered. """ pass @purevirtual @abstractmethod def _work_topics(self) -> List[str]: """ The list of topics to subscribe to based on the Work Topics (status transitions) supported by the agent. """ pass @property def task_consumption_policy(self) -> TaskConsumptionPolicy: """ Get the policy that the agent uses to decide to process (or not) the task based on tasks meta data :return: The consumption policy """ return self._task_consumption_policy @task_consumption_policy.setter def task_consumption_policy(self, p: TaskConsumptionPolicy) -> None: """ Set the policy that the agent uses to decide to process (or not) the task based on tasks meta data """ self._task_consumption_policy = p @abstractmethod @purevirtual def reset(self) -> None: """ Return the Actor to the same state at which it was constructed """ pass # ----- P R O P E R T I E S ----- @property @abstractmethod @purevirtual def name(self) -> str: """ The unique name of the Agent :return: The Agent name """ pass @property @abstractmethod @purevirtual def capacity(self) -> int: """ The current work capacity of the actor. :return: Current work capacity as int """ pass @property @abstractmethod @purevirtual def from_state(self) -> State: """ The state the actor expects to receive tasks in :return: from state """ pass @abstractmethod @purevirtual @property def to_state(self) -> State: """ The state the actor will process tasks into :return: to state """ pass @abstractmethod @purevirtual @property def failure_rate(self) -> float: """ The rate at which completed tasks fail. :return: Failure state of the actor """ pass @property def work_interval(self) -> float: """ The wait period between doing work. :return: Wait interval between work timer events in seconds """ return self._work_timer @property def capabilities(self) -> List[Capability]: """ The collection of capabilities of the SrcSink :return: The collection of capabilities """ return self._capabilities def get_addressbook(self) -> List[SrcSink]: """ The list of srcsinks known to the Ether :return: srcsinks """ return self._address_book.get() def _update_addressbook(self, srcsink: SrcSink) -> None: """ Update the given src_sink in the collection of registered srcsinks. If src_sink is not in the collection add it with a current time stamp. :param srcsink: The src_sink to update / add. """ self._address_book.update(srcsink) return
import threading from copy import deepcopy from abc import abstractmethod from pubsub import pub from typing import List from journey11.src.interface.notification import Notification from journey11.src.interface.srcsink import SrcSink from journey11.src.interface.tasknotification import TaskNotification from journey11.src.interface.worknotificationdo import WorkNotificationDo from journey11.src.interface.taskconsumptionpolicy import TaskConsumptionPolicy from journey11.src.interface.worknotificationfinalise import WorkNotificationFinalise from journey11.src.interface.worknotificationinitiate import WorkNotificationInitiate from journey11.src.interface.capability import Capability from journey11.src.interface.srcsinkping import SrcSinkPing from journey11.src.interface.srcsinkpingnotification import SrcSinkPingNotification from journey11.src.lib.notificationhandler import NotificationHandler from journey11.src.lib.purevirtual import purevirtual from journey11.src.lib.state import State from journey11.src.lib.uniquetopic import UniqueTopic from journey11.src.main.simple.simplecapability import SimpleCapability from journey11.src.lib.capabilityregister import CapabilityRegister from journey11.src.lib.addressbook import AddressBook class Agent(SrcSink): WORK_TIMER = float(.25) WORK_TIMER_MAX = float(30) PRS_TIMER = float(.25) PRD_TIMER_MAX = float(60) WORK_INIT_TIMER = float(.25) WORK_INIT_TIMER_MAX = float(180) AGENT_TOPIC_PREFIX = "agent" def __init__(self, agent_name: str): """ Register all notification handlers & activities. """ self._address_book = AddressBook() self._lock = threading.RLock() self._subscribed_topics = list() super().__init__() self._work_timer = Agent.WORK_TIMER self._timer = None self._task_consumption_policy = None self._handler = NotificationHandler(object_to_be_handler_for=self, throw_unhandled=False) self._handler.register_handler(self._do_notification, TaskNotification) self._handler.register_handler(self._do_work, WorkNotificationDo) self._handler.register_handler(self._do_work_finalise, WorkNotificationFinalise) self._handler.register_handler(self._do_work_initiate, WorkNotificationInitiate) self._handler.register_handler(self._do_srcsink_ping, SrcSinkPing) self._handler.register_handler(self._do_srcsink_ping_notification, SrcSinkPingNotification) self._handler.register_activity(handler_for_activity=self._activity_check_work_to_do, activity_interval=self._work_timer, activity_name="{}-activity-work-to-do".format(agent_name)) self._handler.register_activity(handler_for_activity=self._activity_manage_presence, activity_interval=Agent.PRS_TIMER, activity_name="{}-activity-manage-presence".format(agent_name)) self._handler.register_activity(handler_for_activity=self._activity_initiate_work, activity_interval=Agent.WORK_INIT_TIMER, activity_name="{}-activity-work-init".format(agent_name)) self._unique_topic = self._create_topic_and_subscriptions() self._capabilities = self._get_capabilities() return def __del__(self): """ Shut down """ self._handler.activity_state(paused=True) with self._lock: sub_list = deepcopy(self._subscribed_topics) for topic in sub_list: pub.unsubscribe(self, topic) return def __call__(self, notification: Notification): """ Handle notification requests :param notification: The notification to be passed to the handler """ if isinstance(notification, Notification): self._handler.call_handler(notification) else: raise ValueError("{} is an un supported notification type for Agent}".format(type(notification).__name__)) return def _create_topic_and_subscriptions(self) -> str: """ Create the unique topic for the agent that it will listen on for work (task) deliveries that it has requested from the task-pool """ topics = list() unique_topic = UniqueTopic().topic(Agent.AGENT_TOPIC_PREFIX) topics.append(unique_topic) for topic in self._work_topics(): topics.append(topic) self.add_subscription_topics(topics=topics) for topic in topics: # do potentially high latency subscriptions outside of the lock. pub.subscribe(self, topic) return unique_topic def add_subscription_topics(self, topics: List[str]) -> None: """ Add the given list of topics to the list of topics agent is subscribed to """ with self._lock: for topic in topics: if topic not in self._subscribed_topics: self._subscribed_topics.append(topic) return @staticmethod def _get_capabilities() -> List[Capability]: """ The capabilities of this Agent :return: List of Capabilities """ return [SimpleCapability(capability_name=str(CapabilityRegister.AGENT))] @abstractmethod @purevirtual def _do_notification(self, task_notification: TaskNotification): """ callback to Notify agent of a task that needs attention. The agent can optionally grab the task from the task pool and work on it or ignore it. :param task_notification: The notification event for task requiring attention """ pass @abstractmethod @purevirtual def _do_work(self, work_notification: WorkNotificationDo) -> None: """ Process any out standing tasks associated with the agent. """ pass @abstractmethod @purevirtual def _do_work_initiate(self, work_notification: WorkNotificationInitiate) -> None: """ Handle the initiation the given work item from this agent """ pass @abstractmethod @purevirtual def _do_work_finalise(self, work_notification_finalise: WorkNotificationFinalise) -> None: """ Take receipt of the given completed work item that was initiated from this agent and do any final processing. """ pass @abstractmethod @purevirtual def work_initiate(self, work_notification: WorkNotificationDo) -> None: """ Initiate the given work item with the agent as the owner of the work. """ pass @abstractmethod @purevirtual def _activity_check_work_to_do(self, current_activity_interval: float) -> float: """ Are there any tasks associated with the Agent that need working on ? of so schedule them by calling work execute handler. :param current_activity_interval: The current delay in seconds before activity is re-triggered. :return: The new delay in seconds before the activity is re-triggered. """ pass @purevirtual @abstractmethod def _activity_manage_presence(self, current_activity_interval: float) -> float: """ Ensure that we are known on the ether & our address book has the name of at least one local pool in it. :param current_activity_interval: The current delay in seconds before activity is re-triggered. :return: The new delay in seconds before the activity is re-triggered. """ pass @purevirtual @abstractmethod def _activity_initiate_work(self, current_activity_interval: float) -> float: """ If the agent is a source (origin) of work then this activity will create and inject the new tasks. Zero or more tasks may be created depending on the specific task creation policy. :param current_activity_interval: The current delay in seconds before activity is re-triggered. :return: The new delay in seconds before the activity is re-triggered. """ pass @purevirtual @abstractmethod def _work_topics(self) -> List[str]: """ The list of topics to subscribe to based on the Work Topics (status transitions) supported by the agent. """ pass @property def task_consumption_policy(self) -> TaskConsumptionPolicy: """ Get the policy that the agent uses to decide to process (or not) the task based on tasks meta data :return: The consumption policy """ return self._task_consumption_policy @task_consumption_policy.setter def task_consumption_policy(self, p: TaskConsumptionPolicy) -> None: """ Set the policy that the agent uses to decide to process (or not) the task based on tasks meta data """ self._task_consumption_policy = p @abstractmethod @purevirtual def reset(self) -> None: """ Return the Actor to the same state at which it was constructed """ pass # ----- P R O P E R T I E S ----- @property @abstractmethod @purevirtual def name(self) -> str: """ The unique name of the Agent :return: The Agent name """ pass @property @abstractmethod @purevirtual def capacity(self) -> int: """ The current work capacity of the actor. :return: Current work capacity as int """ pass @property @abstractmethod @purevirtual def from_state(self) -> State: """ The state the actor expects to receive tasks in :return: from state """ pass @abstractmethod @purevirtual @property def to_state(self) -> State: """ The state the actor will process tasks into :return: to state """ pass @abstractmethod @purevirtual @property def failure_rate(self) -> float: """ The rate at which completed tasks fail. :return: Failure state of the actor """ pass @property def work_interval(self) -> float: """ The wait period between doing work. :return: Wait interval between work timer events in seconds """ return self._work_timer @property def capabilities(self) -> List[Capability]: """ The collection of capabilities of the SrcSink :return: The collection of capabilities """ return self._capabilities def get_addressbook(self) -> List[SrcSink]: """ The list of srcsinks known to the Ether :return: srcsinks """ return self._address_book.get() def _update_addressbook(self, srcsink: SrcSink) -> None: """ Update the given src_sink in the collection of registered srcsinks. If src_sink is not in the collection add it with a current time stamp. :param srcsink: The src_sink to update / add. """ self._address_book.update(srcsink) return
en
0.921735
Register all notification handlers & activities. Shut down Handle notification requests :param notification: The notification to be passed to the handler Create the unique topic for the agent that it will listen on for work (task) deliveries that it has requested from the task-pool # do potentially high latency subscriptions outside of the lock. Add the given list of topics to the list of topics agent is subscribed to The capabilities of this Agent :return: List of Capabilities callback to Notify agent of a task that needs attention. The agent can optionally grab the task from the task pool and work on it or ignore it. :param task_notification: The notification event for task requiring attention Process any out standing tasks associated with the agent. Handle the initiation the given work item from this agent Take receipt of the given completed work item that was initiated from this agent and do any final processing. Initiate the given work item with the agent as the owner of the work. Are there any tasks associated with the Agent that need working on ? of so schedule them by calling work execute handler. :param current_activity_interval: The current delay in seconds before activity is re-triggered. :return: The new delay in seconds before the activity is re-triggered. Ensure that we are known on the ether & our address book has the name of at least one local pool in it. :param current_activity_interval: The current delay in seconds before activity is re-triggered. :return: The new delay in seconds before the activity is re-triggered. If the agent is a source (origin) of work then this activity will create and inject the new tasks. Zero or more tasks may be created depending on the specific task creation policy. :param current_activity_interval: The current delay in seconds before activity is re-triggered. :return: The new delay in seconds before the activity is re-triggered. The list of topics to subscribe to based on the Work Topics (status transitions) supported by the agent. Get the policy that the agent uses to decide to process (or not) the task based on tasks meta data :return: The consumption policy Set the policy that the agent uses to decide to process (or not) the task based on tasks meta data Return the Actor to the same state at which it was constructed # ----- P R O P E R T I E S ----- The unique name of the Agent :return: The Agent name The current work capacity of the actor. :return: Current work capacity as int The state the actor expects to receive tasks in :return: from state The state the actor will process tasks into :return: to state The rate at which completed tasks fail. :return: Failure state of the actor The wait period between doing work. :return: Wait interval between work timer events in seconds The collection of capabilities of the SrcSink :return: The collection of capabilities The list of srcsinks known to the Ether :return: srcsinks Update the given src_sink in the collection of registered srcsinks. If src_sink is not in the collection add it with a current time stamp. :param srcsink: The src_sink to update / add.
1.95329
2
src/diffbank/constants.py
adam-coogan/diffbank
6
6622396
<reponame>adam-coogan/diffbank<gh_stars>1-10 """ Various constants. ``diffbank`` uses SI units throughout. """ MSUN = 1.98855e30 # kg """Solar mass""" G = 6.674e-11 # m^3 / kg / s^2 """Newton's gravitational constant""" C = 299792458.0 # m / s """Speed of light"""
""" Various constants. ``diffbank`` uses SI units throughout. """ MSUN = 1.98855e30 # kg """Solar mass""" G = 6.674e-11 # m^3 / kg / s^2 """Newton's gravitational constant""" C = 299792458.0 # m / s """Speed of light"""
en
0.730888
Various constants. ``diffbank`` uses SI units throughout. # kg Solar mass # m^3 / kg / s^2 Newton's gravitational constant # m / s Speed of light
1.517907
2
doc/argument_rotation.py
ilopata1/matplotlib-scalebar
92
6622397
import numpy as np import matplotlib.pyplot as plt import matplotlib.cbook as cbook from matplotlib_scalebar.scalebar import ScaleBar with cbook.get_sample_data("s1045.ima.gz") as dfile: im = np.frombuffer(dfile.read(), np.uint16).reshape((256, 256)) fig, ax = plt.subplots() ax.axis("off") ax.imshow(im, cmap="gray") scalebar = ScaleBar( 0.08, "cm", length_fraction=0.25, rotation="vertical", scale_loc="right", border_pad=1, pad=0.5, ) ax.add_artist(scalebar) fig.savefig("argument_rotation.png", dpi=60, bbox_inches="tight")
import numpy as np import matplotlib.pyplot as plt import matplotlib.cbook as cbook from matplotlib_scalebar.scalebar import ScaleBar with cbook.get_sample_data("s1045.ima.gz") as dfile: im = np.frombuffer(dfile.read(), np.uint16).reshape((256, 256)) fig, ax = plt.subplots() ax.axis("off") ax.imshow(im, cmap="gray") scalebar = ScaleBar( 0.08, "cm", length_fraction=0.25, rotation="vertical", scale_loc="right", border_pad=1, pad=0.5, ) ax.add_artist(scalebar) fig.savefig("argument_rotation.png", dpi=60, bbox_inches="tight")
none
1
2.634942
3
hockey_scraper/json_schedule.py
alex-gable/Hockey-Scraper
0
6622398
<filename>hockey_scraper/json_schedule.py """ This module contains functions to scrape the json schedule for any games or date range """ import json import time import datetime import hockey_scraper.shared as shared def get_schedule(date_from, date_to): """ Scrapes games in date range Ex: https://statsapi.web.nhl.com/api/v1/schedule?startDate=2010-10-03&endDate=2011-06-20 :param date_from: scrape from this date :param date_to: scrape until this date :return: raw json of schedule of date range """ page_info = { "url": 'https://statsapi.web.nhl.com/api/v1/schedule?startDate={a}&endDate={b}'.format(a=date_from, b=date_to), "name": date_from + "_" + date_to, "type": "json_schedule", "season": shared.get_season(date_from), } return json.loads(shared.get_file(page_info)) def get_current_season(): """ Get Season based on today's date :return: season -> ex: 2016 for 2016-2017 season """ year = str(datetime.date.today().year) date = time.strptime(str(datetime.date.today()), "%Y-%m-%d") if date > time.strptime('-'.join([year, '01-01']), "%Y-%m-%d"): if date < time.strptime('-'.join([year, '07-01']), "%Y-%m-%d"): return str(int(year)-1) else: return year else: if date > time.strptime('-'.join([year, '07-01']), "%Y-%m-%d"): return year else: return str(int(year)-1) def get_dates(games): """ Given a list game_ids it returns the dates for each game :param games: list with game_id's ex: 2016020001 :return: list with game_id and corresponding date for all games """ games.sort() year_from = str(games[0])[:4] year_to = str(games[len(games)-1])[:4] date_from = '-'.join([year_from, '9', '1']) # Earliest games in sample # If the last game is part of the ongoing season then only request the schedule until that day...we get strange # errors if we don't do it like this if year_to == get_current_season(): date_to = '-'.join([str(datetime.date.today().year), str(datetime.date.today().month), str(datetime.date.today().day)]) else: date_to = '-'.join([str(int(year_to) + 1), '7', '1']) # Newest game in sample schedule = scrape_schedule(date_from, date_to, preseason=True) games_list = [] for game in schedule: if game[0] in games: games_list.extend([game]) return games_list def scrape_schedule(date_from, date_to, preseason=False): """ Calls getSchedule and scrapes the raw schedule JSON :param date_from: scrape from this date :param date_to: scrape until this date :param preseason: Boolean indicating whether include preseason games (default if False) :return: list with all the game id's """ schedule = [] schedule_json = get_schedule(date_from, date_to) for day in schedule_json['dates']: for game in day['games']: if game['status']['detailedState'] == 'Final': if int(str(game['gamePk'])[5:]) >= 20000 or preseason: schedule.append([game['gamePk'], day['date']]) return schedule
<filename>hockey_scraper/json_schedule.py """ This module contains functions to scrape the json schedule for any games or date range """ import json import time import datetime import hockey_scraper.shared as shared def get_schedule(date_from, date_to): """ Scrapes games in date range Ex: https://statsapi.web.nhl.com/api/v1/schedule?startDate=2010-10-03&endDate=2011-06-20 :param date_from: scrape from this date :param date_to: scrape until this date :return: raw json of schedule of date range """ page_info = { "url": 'https://statsapi.web.nhl.com/api/v1/schedule?startDate={a}&endDate={b}'.format(a=date_from, b=date_to), "name": date_from + "_" + date_to, "type": "json_schedule", "season": shared.get_season(date_from), } return json.loads(shared.get_file(page_info)) def get_current_season(): """ Get Season based on today's date :return: season -> ex: 2016 for 2016-2017 season """ year = str(datetime.date.today().year) date = time.strptime(str(datetime.date.today()), "%Y-%m-%d") if date > time.strptime('-'.join([year, '01-01']), "%Y-%m-%d"): if date < time.strptime('-'.join([year, '07-01']), "%Y-%m-%d"): return str(int(year)-1) else: return year else: if date > time.strptime('-'.join([year, '07-01']), "%Y-%m-%d"): return year else: return str(int(year)-1) def get_dates(games): """ Given a list game_ids it returns the dates for each game :param games: list with game_id's ex: 2016020001 :return: list with game_id and corresponding date for all games """ games.sort() year_from = str(games[0])[:4] year_to = str(games[len(games)-1])[:4] date_from = '-'.join([year_from, '9', '1']) # Earliest games in sample # If the last game is part of the ongoing season then only request the schedule until that day...we get strange # errors if we don't do it like this if year_to == get_current_season(): date_to = '-'.join([str(datetime.date.today().year), str(datetime.date.today().month), str(datetime.date.today().day)]) else: date_to = '-'.join([str(int(year_to) + 1), '7', '1']) # Newest game in sample schedule = scrape_schedule(date_from, date_to, preseason=True) games_list = [] for game in schedule: if game[0] in games: games_list.extend([game]) return games_list def scrape_schedule(date_from, date_to, preseason=False): """ Calls getSchedule and scrapes the raw schedule JSON :param date_from: scrape from this date :param date_to: scrape until this date :param preseason: Boolean indicating whether include preseason games (default if False) :return: list with all the game id's """ schedule = [] schedule_json = get_schedule(date_from, date_to) for day in schedule_json['dates']: for game in day['games']: if game['status']['detailedState'] == 'Final': if int(str(game['gamePk'])[5:]) >= 20000 or preseason: schedule.append([game['gamePk'], day['date']]) return schedule
en
0.770102
This module contains functions to scrape the json schedule for any games or date range Scrapes games in date range Ex: https://statsapi.web.nhl.com/api/v1/schedule?startDate=2010-10-03&endDate=2011-06-20 :param date_from: scrape from this date :param date_to: scrape until this date :return: raw json of schedule of date range Get Season based on today's date :return: season -> ex: 2016 for 2016-2017 season Given a list game_ids it returns the dates for each game :param games: list with game_id's ex: 2016020001 :return: list with game_id and corresponding date for all games # Earliest games in sample # If the last game is part of the ongoing season then only request the schedule until that day...we get strange # errors if we don't do it like this # Newest game in sample Calls getSchedule and scrapes the raw schedule JSON :param date_from: scrape from this date :param date_to: scrape until this date :param preseason: Boolean indicating whether include preseason games (default if False) :return: list with all the game id's
3.74132
4
pystanley/tests/mockup.py
claudiomattera/pystanley
0
6622399
# Copyright <NAME> 2019. # Copyright Center for Energy Informatics 2018. # Distributed under the MIT License. # See accompanying file License.txt, or online at # https://opensource.org/licenses/MIT import typing from pystanley.types import JsonType from pystanley.transport import TransportInterface class DummyTransportInterface(TransportInterface): """docstring for DummyTransportInterface""" def __init__( self, result: typing.Text, ) -> None: super(DummyTransportInterface, self).__init__() self.result = result async def post_data( self, data: JsonType, ) -> None: self.received_post_data = data async def fetch( self, params: typing.Dict[typing.Text, typing.Text] ) -> typing.Text: self.received_fetch_params = params return self.result
# Copyright <NAME> 2019. # Copyright Center for Energy Informatics 2018. # Distributed under the MIT License. # See accompanying file License.txt, or online at # https://opensource.org/licenses/MIT import typing from pystanley.types import JsonType from pystanley.transport import TransportInterface class DummyTransportInterface(TransportInterface): """docstring for DummyTransportInterface""" def __init__( self, result: typing.Text, ) -> None: super(DummyTransportInterface, self).__init__() self.result = result async def post_data( self, data: JsonType, ) -> None: self.received_post_data = data async def fetch( self, params: typing.Dict[typing.Text, typing.Text] ) -> typing.Text: self.received_fetch_params = params return self.result
en
0.710537
# Copyright <NAME> 2019. # Copyright Center for Energy Informatics 2018. # Distributed under the MIT License. # See accompanying file License.txt, or online at # https://opensource.org/licenses/MIT docstring for DummyTransportInterface
2.158598
2
cibyl/outputs/cli/ci/system/impls/jobs/serialized.py
rhos-infra/cibyl
3
6622400
""" # Copyright 2022 Red Hat # # 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 json from abc import ABC from overrides import overrides from cibyl.cli.query import QueryType from cibyl.outputs.cli.ci.system.impls.base.serialized import \ SerializedBaseSystemPrinter class SerializedJobsSystemPrinter(SerializedBaseSystemPrinter, ABC): """Base printer for all machine-readable printers dedicated to output Jenkins systems. """ @overrides def print_system(self, system): # Build on top of the base answer result = self._load(super().print_system(system)) if self.query != QueryType.NONE: result['jobs'] = [] for job in system.jobs.values(): result['jobs'].append(self._load(self.print_job(job))) return self._dump(result) def print_job(self, job): """ :param job: The job. :type job: :class:`cibyl.models.ci.base.job.Job` :return: Textual representation of the provided model. :rtype: str """ result = { 'name': job.name.value } if self.query in (QueryType.FEATURES_JOBS, QueryType.FEATURES): return self._dump(result) if self.query >= QueryType.BUILDS: result['builds'] = [] for build in job.builds.values(): result['builds'].append(self._load(self.print_build(build))) return self._dump(result) def print_build(self, build): """ :param build: The build. :type build: :class:`cibyl.models.ci.base.build.Build` :return: Textual representation of the provided model. :rtype: str """ result = { 'uuid': build.build_id.value, 'status': build.status.value, 'duration': build.duration.value, 'tests': [], 'stages': [] } for test in build.tests.values(): result['tests'].append(self._load(self.print_test(test))) for stage in build.stages: result['stages'].append(self._load(self.print_stage(stage))) return self._dump(result) def print_test(self, test): """ :param test: The test. :type test: :class:`cibyl.models.ci.base.test.Test` :return: Textual representation of the provided model. :rtype: str """ result = { 'name': test.name.value, 'result': test.result.value, 'class_name': test.class_name.value, 'duration': test.duration.value } return self._dump(result) def print_stage(self, stage): """ :param stage: The stage. :type stage: :class:`cibyl.models.ci.base.stage.Stage` :return: Textual representation of the provided model. :rtype: str """ result = { 'name': stage.name.value, 'status': stage.status.value, 'duration': stage.duration.value } return self._dump(result) class JSONJobsSystemPrinter(SerializedJobsSystemPrinter): """Printer that will output Jenkins systems in JSON format. """ def __init__(self, query=QueryType.NONE, verbosity=0, indentation=4): """Constructor. See parent for more information. :param indentation: Number of spaces indenting each level of the JSON output. :type indentation: int """ super().__init__( load_function=self._from_json, dump_function=self._to_json, query=query, verbosity=verbosity ) self._indentation = indentation @property def indentation(self): """ :return: Number of spaces preceding every level of the JSON output. :rtype: int """ return self._indentation def _from_json(self, obj): return json.loads(obj) def _to_json(self, obj): return json.dumps(obj, indent=self._indentation)
""" # Copyright 2022 Red Hat # # 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 json from abc import ABC from overrides import overrides from cibyl.cli.query import QueryType from cibyl.outputs.cli.ci.system.impls.base.serialized import \ SerializedBaseSystemPrinter class SerializedJobsSystemPrinter(SerializedBaseSystemPrinter, ABC): """Base printer for all machine-readable printers dedicated to output Jenkins systems. """ @overrides def print_system(self, system): # Build on top of the base answer result = self._load(super().print_system(system)) if self.query != QueryType.NONE: result['jobs'] = [] for job in system.jobs.values(): result['jobs'].append(self._load(self.print_job(job))) return self._dump(result) def print_job(self, job): """ :param job: The job. :type job: :class:`cibyl.models.ci.base.job.Job` :return: Textual representation of the provided model. :rtype: str """ result = { 'name': job.name.value } if self.query in (QueryType.FEATURES_JOBS, QueryType.FEATURES): return self._dump(result) if self.query >= QueryType.BUILDS: result['builds'] = [] for build in job.builds.values(): result['builds'].append(self._load(self.print_build(build))) return self._dump(result) def print_build(self, build): """ :param build: The build. :type build: :class:`cibyl.models.ci.base.build.Build` :return: Textual representation of the provided model. :rtype: str """ result = { 'uuid': build.build_id.value, 'status': build.status.value, 'duration': build.duration.value, 'tests': [], 'stages': [] } for test in build.tests.values(): result['tests'].append(self._load(self.print_test(test))) for stage in build.stages: result['stages'].append(self._load(self.print_stage(stage))) return self._dump(result) def print_test(self, test): """ :param test: The test. :type test: :class:`cibyl.models.ci.base.test.Test` :return: Textual representation of the provided model. :rtype: str """ result = { 'name': test.name.value, 'result': test.result.value, 'class_name': test.class_name.value, 'duration': test.duration.value } return self._dump(result) def print_stage(self, stage): """ :param stage: The stage. :type stage: :class:`cibyl.models.ci.base.stage.Stage` :return: Textual representation of the provided model. :rtype: str """ result = { 'name': stage.name.value, 'status': stage.status.value, 'duration': stage.duration.value } return self._dump(result) class JSONJobsSystemPrinter(SerializedJobsSystemPrinter): """Printer that will output Jenkins systems in JSON format. """ def __init__(self, query=QueryType.NONE, verbosity=0, indentation=4): """Constructor. See parent for more information. :param indentation: Number of spaces indenting each level of the JSON output. :type indentation: int """ super().__init__( load_function=self._from_json, dump_function=self._to_json, query=query, verbosity=verbosity ) self._indentation = indentation @property def indentation(self): """ :return: Number of spaces preceding every level of the JSON output. :rtype: int """ return self._indentation def _from_json(self, obj): return json.loads(obj) def _to_json(self, obj): return json.dumps(obj, indent=self._indentation)
en
0.701971
# Copyright 2022 Red Hat # # 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. Base printer for all machine-readable printers dedicated to output Jenkins systems. # Build on top of the base answer :param job: The job. :type job: :class:`cibyl.models.ci.base.job.Job` :return: Textual representation of the provided model. :rtype: str :param build: The build. :type build: :class:`cibyl.models.ci.base.build.Build` :return: Textual representation of the provided model. :rtype: str :param test: The test. :type test: :class:`cibyl.models.ci.base.test.Test` :return: Textual representation of the provided model. :rtype: str :param stage: The stage. :type stage: :class:`cibyl.models.ci.base.stage.Stage` :return: Textual representation of the provided model. :rtype: str Printer that will output Jenkins systems in JSON format. Constructor. See parent for more information. :param indentation: Number of spaces indenting each level of the JSON output. :type indentation: int :return: Number of spaces preceding every level of the JSON output. :rtype: int
2.177378
2
setup.py
socialwifi/flask-oauthres
4
6622401
<filename>setup.py import pathlib import pkg_resources from setuptools import setup from setuptools import find_packages with pathlib.Path('base_requirements.txt').open() as requirements_txt: install_requires = [ str(requirement) for requirement in pkg_resources.parse_requirements(requirements_txt) ] setup( name='Flask-OAuthRes', version='0.3.1.dev0', description="OAuth Resource for Flask", author='Social WiFi', author_email='<EMAIL>', url='https://github.com/socialwifi/flask-oauthres', packages=find_packages(exclude=['tests', 'example']), install_requires=install_requires, setup_requires=['pytest-runner'], tests_require=['pytest'], license='BSD', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved', 'License :: OSI Approved :: BSD License', 'Operating System :: MacOS', 'Operating System :: POSIX', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
<filename>setup.py import pathlib import pkg_resources from setuptools import setup from setuptools import find_packages with pathlib.Path('base_requirements.txt').open() as requirements_txt: install_requires = [ str(requirement) for requirement in pkg_resources.parse_requirements(requirements_txt) ] setup( name='Flask-OAuthRes', version='0.3.1.dev0', description="OAuth Resource for Flask", author='Social WiFi', author_email='<EMAIL>', url='https://github.com/socialwifi/flask-oauthres', packages=find_packages(exclude=['tests', 'example']), install_requires=install_requires, setup_requires=['pytest-runner'], tests_require=['pytest'], license='BSD', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved', 'License :: OSI Approved :: BSD License', 'Operating System :: MacOS', 'Operating System :: POSIX', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
none
1
1.755714
2
content/Displayer.py
FrancoisGoualard/Lunar_Landscape_Detection
0
6622402
<reponame>FrancoisGoualard/Lunar_Landscape_Detection<gh_stars>0 import csv import numpy import matplotlib.patches as patches import matplotlib.pyplot as plt from PIL import Image from config import DATAPATH class Displayer: project_dir = DATAPATH def __init__(self, bounding_boxes=[], fileNumber=""): self.bounding_boxes_list = bounding_boxes self.file = fileNumber def __get_bounding_boxes(self, file): with open(f"{self.project_dir}bounding_boxes.csv") as bounding_boxes_csv: reader = csv.reader(bounding_boxes_csv, delimiter=',') next(bounding_boxes_csv) # Skip the header for row in reader: if int(row[0]) == int(file): self.bounding_boxes_list.append(row[1:5]) if int(row[0]) > int(file): break def display_image_and_boxes(self, image, title=""): fig, ax = plt.subplots(1) ax.axis('off') ax.set_title(title) ax.imshow(numpy.array(Image.open(image))) for bounding_box in self.bounding_boxes_list: bounding_box = list(map(float, bounding_box)) rect = patches.Rectangle((bounding_box[0] - 0.5, bounding_box[1] - 0.5), bounding_box[2], bounding_box[3], linewidth=2, edgecolor='w', facecolor='none') ax.add_patch(rect) plt.show() def display_image(self, image, title=""): fig, ax = plt.subplots(1) ax.axis('off') ax.set_title(title) ax.imshow(image) plt.show() def clean(self): plt.close('all') def run_without_image(self): self.file = input('Number of the image? -- or EXIT : \n') while self.file != "EXIT": self.__get_bounding_boxes(self.file) zeros = '0' * (4 - len(self.file)) image = f"{self.project_dir}images/ground/ground{zeros}{self.file}.png" self.display_image_and_boxes(image, f"image number {self.file}") self.file = input('Number of the image? -- or EXIT')
import csv import numpy import matplotlib.patches as patches import matplotlib.pyplot as plt from PIL import Image from config import DATAPATH class Displayer: project_dir = DATAPATH def __init__(self, bounding_boxes=[], fileNumber=""): self.bounding_boxes_list = bounding_boxes self.file = fileNumber def __get_bounding_boxes(self, file): with open(f"{self.project_dir}bounding_boxes.csv") as bounding_boxes_csv: reader = csv.reader(bounding_boxes_csv, delimiter=',') next(bounding_boxes_csv) # Skip the header for row in reader: if int(row[0]) == int(file): self.bounding_boxes_list.append(row[1:5]) if int(row[0]) > int(file): break def display_image_and_boxes(self, image, title=""): fig, ax = plt.subplots(1) ax.axis('off') ax.set_title(title) ax.imshow(numpy.array(Image.open(image))) for bounding_box in self.bounding_boxes_list: bounding_box = list(map(float, bounding_box)) rect = patches.Rectangle((bounding_box[0] - 0.5, bounding_box[1] - 0.5), bounding_box[2], bounding_box[3], linewidth=2, edgecolor='w', facecolor='none') ax.add_patch(rect) plt.show() def display_image(self, image, title=""): fig, ax = plt.subplots(1) ax.axis('off') ax.set_title(title) ax.imshow(image) plt.show() def clean(self): plt.close('all') def run_without_image(self): self.file = input('Number of the image? -- or EXIT : \n') while self.file != "EXIT": self.__get_bounding_boxes(self.file) zeros = '0' * (4 - len(self.file)) image = f"{self.project_dir}images/ground/ground{zeros}{self.file}.png" self.display_image_and_boxes(image, f"image number {self.file}") self.file = input('Number of the image? -- or EXIT')
en
0.316937
# Skip the header
2.781812
3
designate-8.0.0/designate/tests/unit/test_mdns/test_handler.py
scottwedge/OpenStack-Stein
0
6622403
<gh_stars>0 # Copyright 2014 Rackspace Inc. # # Author: <NAME> <<EMAIL>> # # 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 unittest from mock import Mock from oslo_log import log as logging import dns from designate import exceptions from designate import objects from designate.mdns import handler LOG = logging.getLogger(__name__) class TestRequestHandlerCall(unittest.TestCase): """ Unit test to assert the dispatching based on the request operation. """ def setUp(self): self.storage = Mock() self.tg = Mock() self.handler = handler.RequestHandler(self.storage, self.tg) # Use a simple handlers that doesn't require a real request self.handler._handle_query_error = Mock(return_value='Error') self.handler._handle_axfr = Mock(return_value=['AXFR']) self.handler._handle_record_query = Mock(return_value=['Record Query']) self.handler._handle_notify = Mock(return_value=['Notify']) def assert_error(self, request, error_type): self.handler._handle_query_error.assert_called_with( request, error_type ) def test_central_api_property(self): self.handler._central_api = 'foo' assert self.handler.central_api == 'foo' def test___call___unhandled_opcodes(self): unhandled_codes = [ dns.opcode.STATUS, dns.opcode.IQUERY, dns.opcode.UPDATE, ] request = Mock() for code in unhandled_codes: request.opcode.return_value = code # return an error assert list(self.handler(request)) == ['Error'] self.assert_error(request, dns.rcode.REFUSED) def test___call__query_error_with_more_than_one_question(self): request = Mock() request.opcode.return_value = dns.opcode.QUERY request.question = [Mock(), Mock()] assert list(self.handler(request)) == ['Error'] self.assert_error(request, dns.rcode.REFUSED) def test___call__query_error_with_data_claas_not_in(self): request = Mock() request.opcode.return_value = dns.opcode.QUERY request.question = [Mock(rdclass=dns.rdataclass.ANY)] assert list(self.handler(request)) == ['Error'] self.assert_error(request, dns.rcode.REFUSED) def test___call__axfr(self): request = Mock() request.opcode.return_value = dns.opcode.QUERY request.question = [ Mock(rdclass=dns.rdataclass.IN, rdtype=dns.rdatatype.AXFR) ] assert list(self.handler(request)) == ['AXFR'] def test___call__ixfr(self): request = Mock() request.opcode.return_value = dns.opcode.QUERY request.question = [ Mock(rdclass=dns.rdataclass.IN, rdtype=dns.rdatatype.IXFR) ] assert list(self.handler(request)) == ['AXFR'] def test___call__record_query(self): request = Mock() request.opcode.return_value = dns.opcode.QUERY request.question = [ Mock(rdclass=dns.rdataclass.IN, rdtype=dns.rdatatype.A) ] assert list(self.handler(request)) == ['Record Query'] def test___call__notify(self): request = Mock() request.opcode.return_value = dns.opcode.NOTIFY assert list(self.handler(request)) == ['Notify'] def test__convert_to_rrset_no_records(self): zone = objects.Zone.from_dict({'ttl': 1234}) recordset = objects.RecordSet( name='www.example.org.', type='A', records=objects.RecordList(objects=[ ]) ) r_rrset = self.handler._convert_to_rrset(zone, recordset) self.assertIsNone(r_rrset) def test__convert_to_rrset(self): zone = objects.Zone.from_dict({'ttl': 1234}) recordset = objects.RecordSet( name='www.example.org.', type='A', records=objects.RecordList(objects=[ objects.Record(data='192.0.2.1'), objects.Record(data='192.0.2.2'), ]) ) r_rrset = self.handler._convert_to_rrset(zone, recordset) self.assertEqual(2, len(r_rrset)) class HandleRecordQueryTest(unittest.TestCase): def setUp(self): self.storage = Mock() self.tg = Mock() self.handler = handler.RequestHandler(self.storage, self.tg) def test__handle_record_query_empty_recordlist(self): # bug #1550441 self.storage.find_recordset.return_value = objects.RecordSet( name='www.example.org.', type='A', records=objects.RecordList(objects=[ ]) ) request = dns.message.make_query('www.example.org.', dns.rdatatype.A) request.environ = dict(context='ctx') response_gen = self.handler._handle_record_query(request) for r in response_gen: # This was raising an exception due to bug #1550441 out = r.to_wire(max_size=65535) self.assertEqual(33, len(out)) def test__handle_record_query_zone_not_found(self): self.storage.find_recordset.return_value = objects.RecordSet( name='www.example.org.', type='A', records=objects.RecordList(objects=[ objects.Record(data='192.0.2.2'), ]) ) self.storage.find_zone.side_effect = exceptions.ZoneNotFound request = dns.message.make_query('www.example.org.', dns.rdatatype.A) request.environ = dict(context='ctx') response = tuple(self.handler._handle_record_query(request)) self.assertEqual(1, len(response)) self.assertEqual(dns.rcode.REFUSED, response[0].rcode()) def test__handle_record_query_forbidden(self): self.storage.find_recordset.return_value = objects.RecordSet( name='www.example.org.', type='A', records=objects.RecordList(objects=[ objects.Record(data='192.0.2.2'), ]) ) self.storage.find_zone.side_effect = exceptions.Forbidden request = dns.message.make_query('www.example.org.', dns.rdatatype.A) request.environ = dict(context='ctx') response = tuple(self.handler._handle_record_query(request)) self.assertEqual(1, len(response)) self.assertEqual(dns.rcode.REFUSED, response[0].rcode()) def test__handle_record_query_find_recordsed_forbidden(self): self.storage.find_recordset.side_effect = exceptions.Forbidden request = dns.message.make_query('www.example.org.', dns.rdatatype.A) request.environ = dict(context='ctx') response = tuple(self.handler._handle_record_query(request)) self.assertEqual(1, len(response)) self.assertEqual(dns.rcode.REFUSED, response[0].rcode()) def test__handle_record_query_find_recordsed_not_found(self): self.storage.find_recordset.side_effect = exceptions.NotFound request = dns.message.make_query('www.example.org.', dns.rdatatype.A) request.environ = dict(context='ctx') response = tuple(self.handler._handle_record_query(request)) self.assertEqual(1, len(response)) self.assertEqual(dns.rcode.REFUSED, response[0].rcode())
# Copyright 2014 Rackspace Inc. # # Author: <NAME> <<EMAIL>> # # 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 unittest from mock import Mock from oslo_log import log as logging import dns from designate import exceptions from designate import objects from designate.mdns import handler LOG = logging.getLogger(__name__) class TestRequestHandlerCall(unittest.TestCase): """ Unit test to assert the dispatching based on the request operation. """ def setUp(self): self.storage = Mock() self.tg = Mock() self.handler = handler.RequestHandler(self.storage, self.tg) # Use a simple handlers that doesn't require a real request self.handler._handle_query_error = Mock(return_value='Error') self.handler._handle_axfr = Mock(return_value=['AXFR']) self.handler._handle_record_query = Mock(return_value=['Record Query']) self.handler._handle_notify = Mock(return_value=['Notify']) def assert_error(self, request, error_type): self.handler._handle_query_error.assert_called_with( request, error_type ) def test_central_api_property(self): self.handler._central_api = 'foo' assert self.handler.central_api == 'foo' def test___call___unhandled_opcodes(self): unhandled_codes = [ dns.opcode.STATUS, dns.opcode.IQUERY, dns.opcode.UPDATE, ] request = Mock() for code in unhandled_codes: request.opcode.return_value = code # return an error assert list(self.handler(request)) == ['Error'] self.assert_error(request, dns.rcode.REFUSED) def test___call__query_error_with_more_than_one_question(self): request = Mock() request.opcode.return_value = dns.opcode.QUERY request.question = [Mock(), Mock()] assert list(self.handler(request)) == ['Error'] self.assert_error(request, dns.rcode.REFUSED) def test___call__query_error_with_data_claas_not_in(self): request = Mock() request.opcode.return_value = dns.opcode.QUERY request.question = [Mock(rdclass=dns.rdataclass.ANY)] assert list(self.handler(request)) == ['Error'] self.assert_error(request, dns.rcode.REFUSED) def test___call__axfr(self): request = Mock() request.opcode.return_value = dns.opcode.QUERY request.question = [ Mock(rdclass=dns.rdataclass.IN, rdtype=dns.rdatatype.AXFR) ] assert list(self.handler(request)) == ['AXFR'] def test___call__ixfr(self): request = Mock() request.opcode.return_value = dns.opcode.QUERY request.question = [ Mock(rdclass=dns.rdataclass.IN, rdtype=dns.rdatatype.IXFR) ] assert list(self.handler(request)) == ['AXFR'] def test___call__record_query(self): request = Mock() request.opcode.return_value = dns.opcode.QUERY request.question = [ Mock(rdclass=dns.rdataclass.IN, rdtype=dns.rdatatype.A) ] assert list(self.handler(request)) == ['Record Query'] def test___call__notify(self): request = Mock() request.opcode.return_value = dns.opcode.NOTIFY assert list(self.handler(request)) == ['Notify'] def test__convert_to_rrset_no_records(self): zone = objects.Zone.from_dict({'ttl': 1234}) recordset = objects.RecordSet( name='www.example.org.', type='A', records=objects.RecordList(objects=[ ]) ) r_rrset = self.handler._convert_to_rrset(zone, recordset) self.assertIsNone(r_rrset) def test__convert_to_rrset(self): zone = objects.Zone.from_dict({'ttl': 1234}) recordset = objects.RecordSet( name='www.example.org.', type='A', records=objects.RecordList(objects=[ objects.Record(data='192.0.2.1'), objects.Record(data='192.0.2.2'), ]) ) r_rrset = self.handler._convert_to_rrset(zone, recordset) self.assertEqual(2, len(r_rrset)) class HandleRecordQueryTest(unittest.TestCase): def setUp(self): self.storage = Mock() self.tg = Mock() self.handler = handler.RequestHandler(self.storage, self.tg) def test__handle_record_query_empty_recordlist(self): # bug #1550441 self.storage.find_recordset.return_value = objects.RecordSet( name='www.example.org.', type='A', records=objects.RecordList(objects=[ ]) ) request = dns.message.make_query('www.example.org.', dns.rdatatype.A) request.environ = dict(context='ctx') response_gen = self.handler._handle_record_query(request) for r in response_gen: # This was raising an exception due to bug #1550441 out = r.to_wire(max_size=65535) self.assertEqual(33, len(out)) def test__handle_record_query_zone_not_found(self): self.storage.find_recordset.return_value = objects.RecordSet( name='www.example.org.', type='A', records=objects.RecordList(objects=[ objects.Record(data='192.0.2.2'), ]) ) self.storage.find_zone.side_effect = exceptions.ZoneNotFound request = dns.message.make_query('www.example.org.', dns.rdatatype.A) request.environ = dict(context='ctx') response = tuple(self.handler._handle_record_query(request)) self.assertEqual(1, len(response)) self.assertEqual(dns.rcode.REFUSED, response[0].rcode()) def test__handle_record_query_forbidden(self): self.storage.find_recordset.return_value = objects.RecordSet( name='www.example.org.', type='A', records=objects.RecordList(objects=[ objects.Record(data='192.0.2.2'), ]) ) self.storage.find_zone.side_effect = exceptions.Forbidden request = dns.message.make_query('www.example.org.', dns.rdatatype.A) request.environ = dict(context='ctx') response = tuple(self.handler._handle_record_query(request)) self.assertEqual(1, len(response)) self.assertEqual(dns.rcode.REFUSED, response[0].rcode()) def test__handle_record_query_find_recordsed_forbidden(self): self.storage.find_recordset.side_effect = exceptions.Forbidden request = dns.message.make_query('www.example.org.', dns.rdatatype.A) request.environ = dict(context='ctx') response = tuple(self.handler._handle_record_query(request)) self.assertEqual(1, len(response)) self.assertEqual(dns.rcode.REFUSED, response[0].rcode()) def test__handle_record_query_find_recordsed_not_found(self): self.storage.find_recordset.side_effect = exceptions.NotFound request = dns.message.make_query('www.example.org.', dns.rdatatype.A) request.environ = dict(context='ctx') response = tuple(self.handler._handle_record_query(request)) self.assertEqual(1, len(response)) self.assertEqual(dns.rcode.REFUSED, response[0].rcode())
en
0.859784
# Copyright 2014 Rackspace Inc. # # Author: <NAME> <<EMAIL>> # # 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. Unit test to assert the dispatching based on the request operation. # Use a simple handlers that doesn't require a real request # return an error # bug #1550441 # This was raising an exception due to bug #1550441
2.147662
2
atuproot/ReaderComposite.py
shane-breeze/atuproot
0
6622404
from alphatwirl.loop import ReaderComposite class CustomReaderComposite(ReaderComposite): def merge(self, other): if not hasattr(other, "readers"): return super(CustomReaderComposite, self).merge(other)
from alphatwirl.loop import ReaderComposite class CustomReaderComposite(ReaderComposite): def merge(self, other): if not hasattr(other, "readers"): return super(CustomReaderComposite, self).merge(other)
none
1
2.336106
2
ichnaea/taskapp/tests.py
mikiec84/ichnaea
348
6622405
from inspect import getmembers from celery import signals from ichnaea.taskapp.task import BaseTask class TestBeat(object): def test_tasks(self, celery, tmpdir): filename = str(tmpdir / "celerybeat-schedule") beat_app = celery.Beat() beat = beat_app.Service(app=celery, schedule_filename=filename) signals.beat_init.send(sender=beat) # Parses the schedule as a side-effect scheduler = beat.get_scheduler() registered_tasks = set(scheduler._store["entries"].keys()) # Import tasks after beat startup, to ensure beat_init correctly loads # configured Celery imports. from ichnaea.data import tasks all_tasks = set( [m[1].shortname() for m in getmembers(tasks) if isinstance(m[1], BaseTask)] ) assert all_tasks - registered_tasks == set( [ "data.update_blue", "data.update_cell", "data.update_wifi", "data.update_datamap", "data.cleanup_datamap", "data.cell_export_diff", "data.cell_export_full", "data.export_reports", "data.sentry_test", ] ) assert registered_tasks - all_tasks == set( [ "data.cleanup_datamap_ne", "data.cleanup_datamap_nw", "data.cleanup_datamap_se", "data.cleanup_datamap_sw", "data.update_blue_0", "data.update_blue_1", "data.update_blue_2", "data.update_blue_3", "data.update_blue_4", "data.update_blue_5", "data.update_blue_6", "data.update_blue_7", "data.update_blue_8", "data.update_blue_9", "data.update_blue_a", "data.update_blue_b", "data.update_blue_c", "data.update_blue_d", "data.update_blue_e", "data.update_blue_f", "data.update_cell_gsm", "data.update_cell_lte", "data.update_cell_wcdma", "data.update_datamap_ne", "data.update_datamap_nw", "data.update_datamap_se", "data.update_datamap_sw", "data.update_wifi_0", "data.update_wifi_1", "data.update_wifi_2", "data.update_wifi_3", "data.update_wifi_4", "data.update_wifi_5", "data.update_wifi_6", "data.update_wifi_7", "data.update_wifi_8", "data.update_wifi_9", "data.update_wifi_a", "data.update_wifi_b", "data.update_wifi_c", "data.update_wifi_d", "data.update_wifi_e", "data.update_wifi_f", ] ) for i in range(16): assert "data.update_blue_%x" % i in registered_tasks for name in ("gsm", "wcdma", "lte"): assert "data.update_cell_" + name in registered_tasks for i in range(16): assert "data.update_wifi_%x" % i in registered_tasks class TestWorkerConfig(object): def test_config(self, celery): assert celery.conf["task_always_eager"] assert "redis" in celery.conf["result_backend"]
from inspect import getmembers from celery import signals from ichnaea.taskapp.task import BaseTask class TestBeat(object): def test_tasks(self, celery, tmpdir): filename = str(tmpdir / "celerybeat-schedule") beat_app = celery.Beat() beat = beat_app.Service(app=celery, schedule_filename=filename) signals.beat_init.send(sender=beat) # Parses the schedule as a side-effect scheduler = beat.get_scheduler() registered_tasks = set(scheduler._store["entries"].keys()) # Import tasks after beat startup, to ensure beat_init correctly loads # configured Celery imports. from ichnaea.data import tasks all_tasks = set( [m[1].shortname() for m in getmembers(tasks) if isinstance(m[1], BaseTask)] ) assert all_tasks - registered_tasks == set( [ "data.update_blue", "data.update_cell", "data.update_wifi", "data.update_datamap", "data.cleanup_datamap", "data.cell_export_diff", "data.cell_export_full", "data.export_reports", "data.sentry_test", ] ) assert registered_tasks - all_tasks == set( [ "data.cleanup_datamap_ne", "data.cleanup_datamap_nw", "data.cleanup_datamap_se", "data.cleanup_datamap_sw", "data.update_blue_0", "data.update_blue_1", "data.update_blue_2", "data.update_blue_3", "data.update_blue_4", "data.update_blue_5", "data.update_blue_6", "data.update_blue_7", "data.update_blue_8", "data.update_blue_9", "data.update_blue_a", "data.update_blue_b", "data.update_blue_c", "data.update_blue_d", "data.update_blue_e", "data.update_blue_f", "data.update_cell_gsm", "data.update_cell_lte", "data.update_cell_wcdma", "data.update_datamap_ne", "data.update_datamap_nw", "data.update_datamap_se", "data.update_datamap_sw", "data.update_wifi_0", "data.update_wifi_1", "data.update_wifi_2", "data.update_wifi_3", "data.update_wifi_4", "data.update_wifi_5", "data.update_wifi_6", "data.update_wifi_7", "data.update_wifi_8", "data.update_wifi_9", "data.update_wifi_a", "data.update_wifi_b", "data.update_wifi_c", "data.update_wifi_d", "data.update_wifi_e", "data.update_wifi_f", ] ) for i in range(16): assert "data.update_blue_%x" % i in registered_tasks for name in ("gsm", "wcdma", "lte"): assert "data.update_cell_" + name in registered_tasks for i in range(16): assert "data.update_wifi_%x" % i in registered_tasks class TestWorkerConfig(object): def test_config(self, celery): assert celery.conf["task_always_eager"] assert "redis" in celery.conf["result_backend"]
en
0.810397
# Parses the schedule as a side-effect # Import tasks after beat startup, to ensure beat_init correctly loads # configured Celery imports.
1.996508
2
demo/demo-logging.py
Duplexes/py_console
13
6622406
<reponame>Duplexes/py_console from pyco import print_message, user_input, logging from pyco.color import Fore logging.clear_log() logging.enable_message_logging = True logging.log("Log file gets created automatically", "[Prefix]") print_message("Error messages logged by default", "[ERROR]") logging.log("Log entry without a prefix") logging.enable_input_logging = True user_input("Input logging enabled: ") logging.set_log_level(logging.Levels.ALL) print_message("Log level set to 'ALL'", "[Prefix]") print_message(Fore.BRIGHT_CYAN + "Escape codes in messages are automatically removed.", Fore.BRIGHT_MAGENTA + "Colorized Prefix:")
from pyco import print_message, user_input, logging from pyco.color import Fore logging.clear_log() logging.enable_message_logging = True logging.log("Log file gets created automatically", "[Prefix]") print_message("Error messages logged by default", "[ERROR]") logging.log("Log entry without a prefix") logging.enable_input_logging = True user_input("Input logging enabled: ") logging.set_log_level(logging.Levels.ALL) print_message("Log level set to 'ALL'", "[Prefix]") print_message(Fore.BRIGHT_CYAN + "Escape codes in messages are automatically removed.", Fore.BRIGHT_MAGENTA + "Colorized Prefix:")
none
1
2.540855
3
vv_core_inference/make_yukarin_sosoa_forwarder.py
Hiroshiba/vv_core_inference
12
6622407
<gh_stars>10-100 from pathlib import Path from typing import List, Optional import math import numpy import torch import yaml from espnet_pytorch_library.tacotron2.decoder import Postnet from torch import Tensor, nn from torch.nn.utils.rnn import pad_sequence from yukarin_sosoa.config import Config from yukarin_sosoa.network.predictor import Predictor, create_predictor from vv_core_inference.utility import remove_weight_norm, to_tensor class RelPositionalEncoding(torch.nn.Module): """Variant of espnet_pytorch_library/transformer/embedding.py#RelPositionalEncoding copyright 2019 <NAME> apache 2.0 (http://www.apache.org/licenses/license-2.0) """ def __init__(self, d_model, dropout_rate, max_len=5000): """Construct an PositionalEncoding object.""" super().__init__() assert d_model % 2 == 0 self.d_model = d_model self.xscale = math.sqrt(self.d_model) self.dropout = torch.nn.Dropout(p=dropout_rate) def forward(self, x: torch.Tensor): """Add positional encoding. Args: x (torch.Tensor): Input tensor (batch, time, `*`). Returns: torch.Tensor: Encoded tensor (batch, time, `*`). """ # Suppose `i` means to the position of query vecotr and `j` means the # position of key vector. We use position relative positions when keys # are to the left (i>j) and negative relative positions otherwise (i<j). pe_positive = torch.zeros(x.size(1), self.d_model//2, 2) pe_negative = torch.zeros(x.size(1), self.d_model//2, 2) position = torch.arange(0, x.size(1), dtype=torch.float32).unsqueeze(1) div_term = torch.exp( torch.arange(0, self.d_model, 2, dtype=torch.float32) * -(math.log(10000.0) / self.d_model) ) pe_positive[:, :, 0] = torch.sin(position * div_term) pe_positive[:, :, 1] = torch.cos(position * div_term) pe_negative[:, :, 0] = torch.sin(-1 * position * div_term) pe_negative[:, :, 1] = torch.cos(-1 * position * div_term) pe_positive = pe_positive.view(x.size(1), self.d_model) pe_negative = pe_negative.view(x.size(1), self.d_model) # Reserve the order of positive indices and concat both positive and # negative indices. This is used to support the shifting trick # as in https://arxiv.org/abs/1901.02860 pe_positive = torch.flip(pe_positive, [0]).unsqueeze(0) pe_negative = pe_negative[1:].unsqueeze(0) pe = torch.cat([pe_positive, pe_negative], dim=1) x = x * self.xscale pos_emb = pe[ :, pe.size(1) // 2 - x.size(1) + 1 : pe.size(1) // 2 + x.size(1), ] return self.dropout(x), self.dropout(pos_emb) def make_pad_mask(lengths: Tensor): bs = lengths.shape[0] maxlen = lengths.max() seq_range = torch.arange(0, maxlen, dtype=torch.int64, device=lengths.device) seq_range_expand = seq_range.unsqueeze(0).expand(bs, maxlen) seq_length_expand = lengths.unsqueeze(-1) mask = seq_range_expand >= seq_length_expand return mask def make_non_pad_mask(lengths: Tensor): return ~make_pad_mask(lengths) class WrapperPostnet(nn.Module): def __init__(self, net: Postnet): super().__init__() self.postnet = net.postnet def forward(self, xs): for net in self.postnet: xs = net(xs) return xs class WrapperYukarinSosoa(nn.Module): def __init__(self, predictor: Predictor): super().__init__() self.speaker_embedder = predictor.speaker_embedder self.pre = predictor.pre self.encoder = predictor.encoder self.post = predictor.post self.postnet = WrapperPostnet(predictor.postnet) @torch.no_grad() def forward( self, f0: Tensor, phoneme: Tensor, speaker_id: Tensor, ): f0 = f0.unsqueeze(0) phoneme = phoneme.unsqueeze(0) h = torch.cat((f0, phoneme), dim=2) # (batch_size, length, ?) speaker_id = self.speaker_embedder(speaker_id) speaker_id = speaker_id.unsqueeze(dim=1) # (batch_size, 1, ?) speaker_feature = speaker_id.expand( speaker_id.shape[0], h.shape[1], speaker_id.shape[2] ) # (batch_size, length, ?) h = torch.cat((h, speaker_feature), dim=2) # (batch_size, length, ?) h = self.pre(h) mask = torch.ones_like(f0).squeeze() h, _ = self.encoder(h, mask) output1 = self.post(h) output2 = output1 + self.postnet(output1.transpose(1, 2)).transpose(1, 2) return output2[0] def make_yukarin_sosoa_wrapper(yukarin_sosoa_model_dir: Path, device) -> nn.Module: with yukarin_sosoa_model_dir.joinpath("config.yaml").open() as f: config = Config.from_dict(yaml.safe_load(f)) predictor = create_predictor(config.network) pe = predictor.encoder.embed[-1] predictor.encoder.embed[-1] = RelPositionalEncoding(pe.d_model, pe.dropout.p) # Use my dynamic positional encoding version state_dict = torch.load( yukarin_sosoa_model_dir.joinpath("model.pth"), map_location=device ) predictor.load_state_dict(state_dict) predictor.eval().to(device) predictor.apply(remove_weight_norm) print("yukarin_sosoa loaded!") return WrapperYukarinSosoa(predictor) def make_yukarin_sosoa_forwarder(yukarin_sosoa_model_dir: Path, device): yukarin_sosoa_forwarder = make_yukarin_sosoa_wrapper(yukarin_sosoa_model_dir, device) def _dispatcher( f0: Tensor, phoneme: Tensor, speaker_id: Optional[numpy.ndarray] = None, ): if speaker_id is not None: speaker_id = to_tensor(speaker_id, device=device) return yukarin_sosoa_forwarder(f0, phoneme, speaker_id) return _dispatcher
from pathlib import Path from typing import List, Optional import math import numpy import torch import yaml from espnet_pytorch_library.tacotron2.decoder import Postnet from torch import Tensor, nn from torch.nn.utils.rnn import pad_sequence from yukarin_sosoa.config import Config from yukarin_sosoa.network.predictor import Predictor, create_predictor from vv_core_inference.utility import remove_weight_norm, to_tensor class RelPositionalEncoding(torch.nn.Module): """Variant of espnet_pytorch_library/transformer/embedding.py#RelPositionalEncoding copyright 2019 <NAME> apache 2.0 (http://www.apache.org/licenses/license-2.0) """ def __init__(self, d_model, dropout_rate, max_len=5000): """Construct an PositionalEncoding object.""" super().__init__() assert d_model % 2 == 0 self.d_model = d_model self.xscale = math.sqrt(self.d_model) self.dropout = torch.nn.Dropout(p=dropout_rate) def forward(self, x: torch.Tensor): """Add positional encoding. Args: x (torch.Tensor): Input tensor (batch, time, `*`). Returns: torch.Tensor: Encoded tensor (batch, time, `*`). """ # Suppose `i` means to the position of query vecotr and `j` means the # position of key vector. We use position relative positions when keys # are to the left (i>j) and negative relative positions otherwise (i<j). pe_positive = torch.zeros(x.size(1), self.d_model//2, 2) pe_negative = torch.zeros(x.size(1), self.d_model//2, 2) position = torch.arange(0, x.size(1), dtype=torch.float32).unsqueeze(1) div_term = torch.exp( torch.arange(0, self.d_model, 2, dtype=torch.float32) * -(math.log(10000.0) / self.d_model) ) pe_positive[:, :, 0] = torch.sin(position * div_term) pe_positive[:, :, 1] = torch.cos(position * div_term) pe_negative[:, :, 0] = torch.sin(-1 * position * div_term) pe_negative[:, :, 1] = torch.cos(-1 * position * div_term) pe_positive = pe_positive.view(x.size(1), self.d_model) pe_negative = pe_negative.view(x.size(1), self.d_model) # Reserve the order of positive indices and concat both positive and # negative indices. This is used to support the shifting trick # as in https://arxiv.org/abs/1901.02860 pe_positive = torch.flip(pe_positive, [0]).unsqueeze(0) pe_negative = pe_negative[1:].unsqueeze(0) pe = torch.cat([pe_positive, pe_negative], dim=1) x = x * self.xscale pos_emb = pe[ :, pe.size(1) // 2 - x.size(1) + 1 : pe.size(1) // 2 + x.size(1), ] return self.dropout(x), self.dropout(pos_emb) def make_pad_mask(lengths: Tensor): bs = lengths.shape[0] maxlen = lengths.max() seq_range = torch.arange(0, maxlen, dtype=torch.int64, device=lengths.device) seq_range_expand = seq_range.unsqueeze(0).expand(bs, maxlen) seq_length_expand = lengths.unsqueeze(-1) mask = seq_range_expand >= seq_length_expand return mask def make_non_pad_mask(lengths: Tensor): return ~make_pad_mask(lengths) class WrapperPostnet(nn.Module): def __init__(self, net: Postnet): super().__init__() self.postnet = net.postnet def forward(self, xs): for net in self.postnet: xs = net(xs) return xs class WrapperYukarinSosoa(nn.Module): def __init__(self, predictor: Predictor): super().__init__() self.speaker_embedder = predictor.speaker_embedder self.pre = predictor.pre self.encoder = predictor.encoder self.post = predictor.post self.postnet = WrapperPostnet(predictor.postnet) @torch.no_grad() def forward( self, f0: Tensor, phoneme: Tensor, speaker_id: Tensor, ): f0 = f0.unsqueeze(0) phoneme = phoneme.unsqueeze(0) h = torch.cat((f0, phoneme), dim=2) # (batch_size, length, ?) speaker_id = self.speaker_embedder(speaker_id) speaker_id = speaker_id.unsqueeze(dim=1) # (batch_size, 1, ?) speaker_feature = speaker_id.expand( speaker_id.shape[0], h.shape[1], speaker_id.shape[2] ) # (batch_size, length, ?) h = torch.cat((h, speaker_feature), dim=2) # (batch_size, length, ?) h = self.pre(h) mask = torch.ones_like(f0).squeeze() h, _ = self.encoder(h, mask) output1 = self.post(h) output2 = output1 + self.postnet(output1.transpose(1, 2)).transpose(1, 2) return output2[0] def make_yukarin_sosoa_wrapper(yukarin_sosoa_model_dir: Path, device) -> nn.Module: with yukarin_sosoa_model_dir.joinpath("config.yaml").open() as f: config = Config.from_dict(yaml.safe_load(f)) predictor = create_predictor(config.network) pe = predictor.encoder.embed[-1] predictor.encoder.embed[-1] = RelPositionalEncoding(pe.d_model, pe.dropout.p) # Use my dynamic positional encoding version state_dict = torch.load( yukarin_sosoa_model_dir.joinpath("model.pth"), map_location=device ) predictor.load_state_dict(state_dict) predictor.eval().to(device) predictor.apply(remove_weight_norm) print("yukarin_sosoa loaded!") return WrapperYukarinSosoa(predictor) def make_yukarin_sosoa_forwarder(yukarin_sosoa_model_dir: Path, device): yukarin_sosoa_forwarder = make_yukarin_sosoa_wrapper(yukarin_sosoa_model_dir, device) def _dispatcher( f0: Tensor, phoneme: Tensor, speaker_id: Optional[numpy.ndarray] = None, ): if speaker_id is not None: speaker_id = to_tensor(speaker_id, device=device) return yukarin_sosoa_forwarder(f0, phoneme, speaker_id) return _dispatcher
en
0.752003
Variant of espnet_pytorch_library/transformer/embedding.py#RelPositionalEncoding copyright 2019 <NAME> apache 2.0 (http://www.apache.org/licenses/license-2.0) Construct an PositionalEncoding object. Add positional encoding. Args: x (torch.Tensor): Input tensor (batch, time, `*`). Returns: torch.Tensor: Encoded tensor (batch, time, `*`). # Suppose `i` means to the position of query vecotr and `j` means the # position of key vector. We use position relative positions when keys # are to the left (i>j) and negative relative positions otherwise (i<j). # Reserve the order of positive indices and concat both positive and # negative indices. This is used to support the shifting trick # as in https://arxiv.org/abs/1901.02860 # (batch_size, length, ?) # (batch_size, 1, ?) # (batch_size, length, ?) # (batch_size, length, ?) # Use my dynamic positional encoding version
2.387067
2
src/multipleInstanceLearning/generateSimilarityMatrices.py
UMCUGenetics/svMIL
0
6622408
""" The goal of this script is to generate the similarity matrices for MIL The similarity matrices are pre-generated for the CV type that these will be used for. There is: - leave-one-chromosome-out CV - leave-one-patient-out CV - leave-bags-out CV - the similarity matrix on the whole dataset (used for feature importance) If we do feature elimination, we have similarity matrices for each feature output these as well. """ import sys import os import numpy as np import pickle as pkl import random random.seed(785) np.random.seed(785) import matplotlib matplotlib.use('Agg') path = sys.argv[7] sys.path.insert(1, path) import settings featureElimination = sys.argv[2] leaveOnePatientOut = sys.argv[3] #make the similarity matrices for each left out patient leaveOneChromosomeOut = sys.argv[4] #1 chromosome at a time in the test set leaveBagsOut = sys.argv[5] #random bags in each CV fold fullDataset = sys.argv[6] #generate sim matrix for the whole dataset. svTypes = ['DEL', 'DUP', 'INV', 'ITX'] #svTypes = ['ALL'] outDir = sys.argv[1] finalOutDir = outDir + '/multipleInstanceLearning/similarityMatrices/' if not os.path.exists(finalOutDir): os.makedirs(finalOutDir) if featureElimination == "True": featureEliminationOutDir = finalOutDir + '/featureSelection' if not os.path.exists(featureEliminationOutDir): os.makedirs(featureEliminationOutDir) if leaveOnePatientOut == 'True': leaveOnePatientOutDir = finalOutDir + '/leaveOnePatientOut' if not os.path.exists(leaveOnePatientOutDir): os.makedirs(leaveOnePatientOutDir) if leaveOneChromosomeOut == 'True': leaveOneChromosomeOutDir = finalOutDir + '/leaveOneChromosomeOut' if not os.path.exists(leaveOneChromosomeOutDir): os.makedirs(leaveOneChromosomeOutDir) if leaveBagsOut == 'True': leaveBagsOutDir = finalOutDir + '/leaveBagsOut' if not os.path.exists(leaveBagsOutDir): os.makedirs(leaveBagsOutDir) #input the normalized bags with open(outDir + '/linkedSVGenePairs/normalizedBags.pkl', 'rb') as handle: bagDict = pkl.load(handle) #get the information for the bag labels degPairs = np.loadtxt(outDir + '/tadDisruptionsZScores/zScores.txt', dtype='object') #labels print(degPairs) print("initial number of bags: ", len(bagDict)) print('initial deg pairs: ', degPairs.shape[0]) mutDir = outDir + '/patientGeneMutationPairs/' cnvPatientsAmp = np.load(mutDir + 'cnvPatientsAmp.npy', allow_pickle=True, encoding='latin1').item() svPatientsDup = np.load(mutDir + 'svPatientsDup.npy', allow_pickle=True, encoding='latin1').item() svGenePairs = np.loadtxt(outDir + '/linkedSVGenePairs/nonCoding_geneSVPairs.txt_', dtype='object') splitSVGenePairs = [] for pair in svGenePairs: splitPair = pair[0].split('_') splitSVGenePairs.append(splitPair[0] + '_' + splitPair[7] + '_' + splitPair[12]) def getSimilarityMatrix(bags, instances, reverseBagMap): """ function to get the similarity matrix. This is mainly used to make the sim matrix for the training set. To make the test set sim matrix, use the function below. bags (numpy array): all bags that we use for this matrix instances (numpy array): all instances in the bags reverseBagMap (dictionary): bag index as key, instance indices as values. Used to find out which instances are in which bag. """ bagIndices = np.arange(bags.shape[0]) similarityMatrix = np.zeros([bags.shape[0], instances.shape[0]]) for bagInd in range(0, bags.shape[0]): #Get the indices of the instances that are in this bag instanceIndices = reverseBagMap[bagInd] instanceSubset = instances[instanceIndices,:] #get the average of all instances in this bag instanceAvg = np.mean(instanceSubset, axis=0) #compute distance to all other instances from this bag average distance = np.abs(instanceAvg - instances) #sum the distances to get 1 similarity score summedDistance = np.sum(distance,axis=1) similarityMatrix[bagInd,:] = summedDistance return similarityMatrix def getSimilarityMatrixTest(testBags, trainInstances, labels): """ function to get the similarity matrix specific for the test case. The instances that we map the distance to are the provided train instances. testBags (numpy array): all test bags that we use for this matrix trainInstances (numpy array): all instances in the bags of the training data, we compute distance to these instances from the test bags labels (list): obsolete. """ similarityMatrix = np.zeros([testBags.shape[0], trainInstances.shape[0]]) #print(similarityMatrix.shape) for bagInd in range(0, testBags.shape[0]): #print(labels[bagInd]) #get the average of all instances in this test patient bag testInstances = testBags[bagInd] instanceAvg = np.mean(testInstances, axis=0) #compute distance to all other instances from this bag average distance = np.abs(instanceAvg - trainInstances) #sum the distances to get 1 similarity score summedDistance = np.sum(distance,axis=1) #print(summedDistance) similarityMatrix[bagInd,:] = summedDistance return similarityMatrix #Generate the similarity matrices for the SV types for svType in svTypes: bagLabels = [] positiveBagPairNames = [] negativeBagPairNames = [] positiveInstanceLabels = [] positiveBags = [] negativeBags = [] #for each SV-gene pair, get the instances for pair in bagDict: #check if the SV type matches our selection splitPair = pair.split("_") shortPair = splitPair[7] + '_' + splitPair[0] if svType != '' and svType != 'ALL': if splitPair[12] != svType: continue #get the label of the bag by checking if it exists in degPairs, some pairs do not have a z-score because the gene is excluded due to mutations. if shortPair in degPairs[:,0]: #get the z-score of the pair. degPairInfo = degPairs[degPairs[:,0] == shortPair][0] #if the z-score matches this criterion, the SV-gene pair is positive if float(degPairInfo[5]) > 1.5 or float(degPairInfo[5]) < -1.5: #go through the instances of this SV-gene pair, and include only those that have gains and losses, and more than 1 instance. This should in principle not happen, but good to keep a check. instances = [] for instance in bagDict[pair]: if instance[0] == 0 and instance[1] == 0: continue instances.append(instance) if len(instances) < 1: continue ###Here do an extra check: #to make fig2A, we only look at TADs with SVs across the boundary, so those z-scores are in the set. #BUT some of these genes are not actually affected by the SV, since this doesn't lead to #regulatory elements gained/lost. SO, we need to remove those here to get the actual pairs. #This only goes wrong for duplications, because we also keep CNV amps that could be the same event, #but then the duplication does not lead to gains/losses, while the CNV amp does because it is slightly #longer. So if there is evidence of a cnv AMP, but no non-coding duplication linked, we can remove #this as a positive pair. if splitPair[7] not in cnvPatientsAmp: positiveBagPairNames.append(pair) positiveBags.append(instances) else: dupMatch = splitPair[0] + '_' + splitPair[7] + '_DUP' if splitPair[0] in cnvPatientsAmp[splitPair[7]] and dupMatch not in splitSVGenePairs: negativeBags.append(instances) negativeBagPairNames.append(pair) else: positiveBagPairNames.append(pair) positiveBags.append(instances) else: #if the z-score is anything else, this bag will be labeled negative. #get the right number of features per instance instances = [] for instance in bagDict[pair]: if instance[0] == 0 and instance[1] == 0: continue instances.append(instance) if len(instances) < 1: continue negativeBags.append(instances) negativeBagPairNames.append(pair) positiveBags = np.array(positiveBags) negativeBags = np.array(negativeBags) positiveBagPairNames = np.array(positiveBagPairNames) negativeBagPairNames = np.array(negativeBagPairNames) #fail-safe in case there are not enough SVs of this type if positiveBags.shape[0] < 2 or negativeBags.shape[0] < 2: continue #add the number of instances per bag as feature to the instances for bag in positiveBags: instCount = len(bag) for instance in bag: instance.append(instCount / positiveBags.shape[0]) for bag in negativeBags: instCount = len(bag) for instance in bag: instance.append(instCount / negativeBags.shape[0]) #remove instances with no variance posInstances = np.vstack(positiveBags) negInstances = np.vstack(negativeBags) allInstances = np.concatenate((posInstances, negInstances)) #remove instances with 0 variance across all instances. These are not useful for the classifier. from sklearn.feature_selection import VarianceThreshold t = 0 vt = VarianceThreshold(threshold=t) vt.fit(allInstances) idx = np.where(vt.variances_ > t)[0] badIdx = np.where(vt.variances_ <= t)[0] np.savetxt(finalOutDir + '/lowVarianceIdx_' + svType + '.txt', badIdx) newPositiveBags = [] newNegativeBags = [] for bag in positiveBags: instances = [] for instance in bag: filteredInstance = [] featureInd = 0 for feature in instance: if featureInd in idx: filteredInstance.append(feature) featureInd += 1 instances.append(filteredInstance) newPositiveBags.append(instances) for bag in negativeBags: instances = [] for instance in bag: filteredInstance = [] featureInd = 0 for feature in instance: if featureInd in idx: filteredInstance.append(feature) featureInd += 1 instances.append(filteredInstance) newNegativeBags.append(instances) positiveBags = np.array(newPositiveBags) negativeBags = np.array(newNegativeBags) print(positiveBags.shape) #subsample the positive bags if there are too many threshold = int(settings.general['bagThreshold']) if positiveBags.shape[0] > threshold: random.seed(785) #subsample the positive set to the threshold positiveBagsSubsampled = np.random.choice(positiveBags, threshold) positiveBagsSubsampleInd = np.random.choice(np.arange(positiveBags.shape[0]), threshold) positiveBagsSubsampled = positiveBags[positiveBagsSubsampleInd] positiveBags = positiveBagsSubsampled print('Number of positive bags: ', positiveBags.shape) print('Number of negative bags: ', negativeBags.shape) print('Number of positive instances: ', len(positiveInstanceLabels)) if positiveBags.shape[0] == 0 or negativeBags.shape[0] == 0: continue #subsample negative to the same number of positives. random.seed(785) #somehow the global setting doesn't work in the second loop? so set it here. #subsample the negative set to the same number of positives. negativeBagsSubsampled = np.random.choice(negativeBags, positiveBags.shape[0]) negativeBagsSubsampleInd = np.random.choice(np.arange(negativeBags.shape[0]), positiveBags.shape[0]) negativeBagsSubsampled = negativeBags[negativeBagsSubsampleInd] negativeBagPairNamesSubsampled = negativeBagPairNames[negativeBagsSubsampleInd] #posInstances = np.vstack(positiveBags) #negInstances = np.vstack(negativeBagsSubsampled) bagPairLabelsSubsampled = np.concatenate((positiveBagPairNames, negativeBagPairNamesSubsampled)) #save the bag pair labels for later np.save(finalOutDir + '/bagPairLabelsSubsampled_' + svType + '.npy', bagPairLabelsSubsampled) #merge the bags so that we can easily get to 1 similarity matrix and do all-to-all computations bagsSubsampled = np.concatenate((positiveBags, negativeBagsSubsampled)) #assign bag labels bagLabelsSubsampled = np.array([1]*positiveBags.shape[0] + [0]*negativeBagsSubsampled.shape[0]) np.save(finalOutDir + '/bagLabelsSubsampled_' + svType + '.npy', bagLabelsSubsampled) #stack the instances in the bags so that we can easily compute bag-instance distances instancesSubsampled = np.vstack(bagsSubsampled) #also output the instances for later np.save(finalOutDir + '/instancesSubsampled_' + svType + '.npy', instancesSubsampled) #and save the bags. np.save(finalOutDir + '/bagsSubsampled_' + svType + '.npy', bagsSubsampled) #in case of leave-one-patient out, we subsample later on bagPairLabels = np.concatenate((positiveBagPairNames, negativeBagPairNames)) #save the bag pair labels for later np.save(finalOutDir + '/bagPairLabelsNotSubsampled_' + svType + '.npy', bagPairLabels) #merge the bags so that we can easily get to 1 similarity matrix and do all-to-all computations bags = np.concatenate((positiveBags, negativeBags)) #assign bag labels bagLabels = np.array([1]*positiveBags.shape[0] + [0]*negativeBags.shape[0]) np.save(finalOutDir + '/bagLabelsNotSubsampled_' + svType + '.npy', bagLabels) #stack the instances in the bags so that we can easily compute bag-instance distances instances = np.vstack(bags) #also output the instances for later np.save(finalOutDir + '/instancesNotSubsampled_' + svType + '.npy', instances) #and save the bags. np.save(finalOutDir + '/bagsNotSubsampled_' + svType + '.npy', bags) print('size comparison: ') print('bags not subsampled: ', bags.shape) print('instances not subsampled: ', instances.shape) print('bag labels not subsampled: ', bagLabels.shape) print('bag pair labels not subsampled: ', bagPairLabels.shape) print('bags subsampled: ', bagsSubsampled.shape) print('instances subsampled: ', instancesSubsampled.shape) print('bag labels subsampled: ', bagLabelsSubsampled.shape) print('bag pair labels subsampled: ', bagPairLabelsSubsampled.shape) # if fullDataset == 'False': # bags = bagsSubsampled # instances = instancesSubsampled # bagPairLabels = bagPairLabelsSubsampled # bagLabels = bagLabelsSubsampled bags = bagsSubsampled instances = instancesSubsampled bagPairLabels = bagPairLabelsSubsampled bagLabels = bagLabelsSubsampled #Make an index where we can lookup at which position the instances are in the concatenated bag array. reverseBagMap = dict() #lookup instance by bag index bagMap = dict() #lookup bag by instance index instanceInd = 0 for bagInd in range(0, bags.shape[0]): reverseBagMap[bagInd] = [] for instance in bags[bagInd]: reverseBagMap[bagInd].append(instanceInd) bagMap[instanceInd] = bagInd instanceInd += 1 #save bagmap for later np.save(finalOutDir + '/bagMap_' + svType + '.npy', bagMap) #if we do feature elimination, randomize the features here featureCount = instances.shape[1] featureStart = featureCount-1 if featureElimination == "True": featureStart = 0 #set this to featureCount to run with all features. #if featureStart is not updated, this will run once #otherwise it will randomize a new feature each time for featureInd in range(featureStart, featureCount): print('current feature: ', featureInd+1) if featureElimination == "True": #in case of feature elimination, we use the leave-one-chromosome-out CV setting #per chromosome, shuffle the features in the training set. #then output the original test set #so we have per SV type, per chromosome CV, X files for the number of features shuffled chromosomes = ['chr1', 'chr2', 'chr3', 'chr4', 'chr5', 'chr6', 'chr7', 'chr8', 'chr9', 'chr10', 'chr11', 'chr12', 'chr13', 'chr14', 'chr15', 'chr16', 'chr17', 'chr18', 'chr19', 'chr20', 'chr21', 'chr22'] positiveBagsPerChromosome = dict() negativeBagsPerChromosome = dict() for labelInd in range(0, len(positiveBagPairNames)): label = positiveBagPairNames[labelInd] splitLabel = label.split('_') chromosome = splitLabel[1] if chromosome not in positiveBagsPerChromosome: positiveBagsPerChromosome[chromosome] = [] positiveBagsPerChromosome[chromosome].append(positiveBags[labelInd]) for labelInd in range(0, len(negativeBagPairNames)): label = negativeBagPairNames[labelInd] splitLabel = label.split('_') chromosome = splitLabel[1] if chromosome not in negativeBagsPerChromosome: negativeBagsPerChromosome[chromosome] = [] negativeBagsPerChromosome[chromosome].append(negativeBags[labelInd]) trainBags = dict() testBags = dict() trainLabels = dict() testLabels = dict() for chromosome in chromosomes: if chromosome not in positiveBagsPerChromosome: continue if chromosome not in negativeBagsPerChromosome: continue #make stratified testPositiveBags = positiveBagsPerChromosome[chromosome] testNegativeBags = negativeBagsPerChromosome[chromosome] testPositiveBags = np.array(testPositiveBags) testNegativeBags = np.array(testNegativeBags) randInd = random.sample(range(0, testNegativeBags.shape[0]), testPositiveBags.shape[0]) testSubsetNegativeBags = testNegativeBags[randInd] allTestBags = [] for bag in testPositiveBags: allTestBags.append(bag) for bag in testSubsetNegativeBags: #for bag in testNegativeBags: allTestBags.append(bag) allTestBags = np.array(allTestBags) testBags[chromosome] = allTestBags testLabels[chromosome] = [1]*testPositiveBags.shape[0] + [0]*testSubsetNegativeBags.shape[0] #testLabels[chromosome] = [1]*testPositiveBags.shape[0] + [0]*testNegativeBags.shape[0] testPositiveInstances = np.vstack(testPositiveBags) testNegativeInstances = np.vstack(testSubsetNegativeBags) testPositiveLabels = [1]*testPositiveInstances.shape[0] testNegativeLabels = [0]*testNegativeInstances.shape[0] #make training set from the rest trainingSet = [] trainingLabels = [] allTrainInstances = [] allTrainLabels = [] for chromosome2 in chromosomes: if chromosome == chromosome2: continue if chromosome2 not in positiveBagsPerChromosome: continue if chromosome2 not in negativeBagsPerChromosome: continue #make stratified chrPositiveBags = positiveBagsPerChromosome[chromosome2] chrNegativeBags = negativeBagsPerChromosome[chromosome2] chrPositiveBags = np.array(chrPositiveBags) chrNegativeBags = np.array(chrNegativeBags) random.seed(785) randInd = random.sample(range(0, chrNegativeBags.shape[0]), chrPositiveBags.shape[0]) subsetNegativeBags = chrNegativeBags[randInd] for bag in chrPositiveBags: trainingSet.append(bag) for bag in subsetNegativeBags: #for bag in chrNegativeBags: trainingSet.append(bag) trainingLabels += [1]*chrPositiveBags.shape[0] trainingLabels += [0]*subsetNegativeBags.shape[0] #trainingLabels += [0]*chrNegativeBags.shape[0] trainPositiveInstances = np.vstack(chrPositiveBags) trainNegativeInstances = np.vstack(subsetNegativeBags) trainPositiveLabels = [1]*trainPositiveInstances.shape[0] trainNegativeLabels = [0]*trainNegativeInstances.shape[0] trainBags[chromosome] = np.array(trainingSet) trainLabels[chromosome] = trainingLabels trainInstances = np.vstack(trainBags[chromosome]) #shuffle the training instances shuffledInstanceValues = trainInstances[:,featureInd] randomInd = np.arange(0, shuffledInstanceValues.shape[0]) np.random.shuffle(randomInd) #we compute the similarity matrix based on the instances #but the instance values need to be reset every iteration shuffledInstances = np.zeros(trainInstances.shape) for col in range(0, trainInstances.shape[1]): if col != featureInd: shuffledInstances[:,col] = trainInstances[:,col] else: shuffledInstances[:,col] = trainInstances[randomInd,col] reverseBagMapOtherPatients = dict() #lookup instance by bag index instanceInd = 0 for bagInd in range(0, trainBags[chromosome].shape[0]): reverseBagMapOtherPatients[bagInd] = [] for instance in trainBags[chromosome][bagInd]: reverseBagMapOtherPatients[bagInd].append(instanceInd) instanceInd += 1 similarityMatrixTrain = getSimilarityMatrix(trainBags[chromosome], shuffledInstances, reverseBagMapOtherPatients) #now the curent patient bags need to be to the instances of the training set similarityMatrixTest = getSimilarityMatrixTest(testBags[chromosome], shuffledInstances, testLabels) #output these to a file #write these data to disk so that we can access it later on np.save(featureEliminationOutDir + '/' + 'similarityMatrixTrain_' + svType + '_' + chromosome + '_' + str(featureInd) + '.npy', similarityMatrixTrain) np.save(featureEliminationOutDir + '/' + 'similarityMatrixTest_' + svType + '_' + chromosome + '_' + str(featureInd) + '.npy', similarityMatrixTest) #also save the labels np.save(featureEliminationOutDir + '/' + 'bagLabelsTrain_' + svType + '_' + chromosome + '_' + str(featureInd) + '.npy', trainLabels[chromosome]) np.save(featureEliminationOutDir + '/' + 'bagLabelsTest_' + svType + '_' + chromosome + '_' + str(featureInd) + '.npy', testLabels[chromosome]) elif featureElimination == 'False' and leaveOneChromosomeOut == 'True': ### leave-one-chromosome-out CV setting chromosomes = ['chr1', 'chr2', 'chr3', 'chr4', 'chr5', 'chr6', 'chr7', 'chr8', 'chr9', 'chr10', 'chr11', 'chr12', 'chr13', 'chr14', 'chr15', 'chr16', 'chr17', 'chr18', 'chr19', 'chr20', 'chr21', 'chr22'] positiveBagsPerChromosome = dict() negativeBagsPerChromosome = dict() for labelInd in range(0, len(positiveBagPairNames)): label = positiveBagPairNames[labelInd] splitLabel = label.split('_') chromosome = splitLabel[1] if chromosome not in positiveBagsPerChromosome: positiveBagsPerChromosome[chromosome] = [] positiveBagsPerChromosome[chromosome].append(positiveBags[labelInd]) for labelInd in range(0, len(negativeBagPairNames)): label = negativeBagPairNames[labelInd] splitLabel = label.split('_') chromosome = splitLabel[1] if chromosome not in negativeBagsPerChromosome: negativeBagsPerChromosome[chromosome] = [] negativeBagsPerChromosome[chromosome].append(negativeBags[labelInd]) trainBags = dict() testBags = dict() trainLabels = dict() testLabels = dict() for chromosome in chromosomes: print(chromosome) #if chromosome != 'chr16': # continue if chromosome not in positiveBagsPerChromosome: continue if chromosome not in negativeBagsPerChromosome: continue #make stratified testPositiveBags = positiveBagsPerChromosome[chromosome] testNegativeBags = negativeBagsPerChromosome[chromosome] testPositiveBags = np.array(testPositiveBags) testNegativeBags = np.array(testNegativeBags) random.seed(785) randInd = random.sample(range(0, testNegativeBags.shape[0]), testPositiveBags.shape[0]) testSubsetNegativeBags = testNegativeBags[randInd] allTestBags = [] for bag in testPositiveBags: allTestBags.append(bag) for bag in testSubsetNegativeBags: #for bag in testNegativeBags: allTestBags.append(bag) allTestBags = np.array(allTestBags) print(allTestBags.shape) testBags[chromosome] = allTestBags testLabels[chromosome] = [1]*testPositiveBags.shape[0] + [0]*testSubsetNegativeBags.shape[0] #make training set from the rest trainingSet = [] trainingLabels = [] allTrainInstances = [] allTrainLabels = [] for chromosome2 in chromosomes: if chromosome == chromosome2: continue if chromosome2 not in positiveBagsPerChromosome: continue if chromosome2 not in negativeBagsPerChromosome: continue #make stratified chrPositiveBags = positiveBagsPerChromosome[chromosome2] chrNegativeBags = negativeBagsPerChromosome[chromosome2] chrPositiveBags = np.array(chrPositiveBags) chrNegativeBags = np.array(chrNegativeBags) random.seed(785) randInd = random.sample(range(0, chrNegativeBags.shape[0]), chrPositiveBags.shape[0]) subsetNegativeBags = chrNegativeBags[randInd] for bag in chrPositiveBags: trainingSet.append(bag) for bag in subsetNegativeBags: #for bag in chrNegativeBags: trainingSet.append(bag) trainingLabels += [1]*chrPositiveBags.shape[0] trainingLabels += [0]*subsetNegativeBags.shape[0] trainBags[chromosome] = np.array(trainingSet) trainLabels[chromosome] = trainingLabels trainInstances = np.vstack(trainBags[chromosome]) reverseBagMapOtherPatients = dict() #lookup instance by bag index instanceInd = 0 for bagInd in range(0, trainBags[chromosome].shape[0]): reverseBagMapOtherPatients[bagInd] = [] for instance in trainBags[chromosome][bagInd]: reverseBagMapOtherPatients[bagInd].append(instanceInd) instanceInd += 1 similarityMatrixTrain = getSimilarityMatrix(trainBags[chromosome], trainInstances, reverseBagMapOtherPatients) print(similarityMatrixTrain.shape) #now the curent patient bags need to be to the instances of the training set similarityMatrixTest = getSimilarityMatrixTest(testBags[chromosome], trainInstances, testLabels) #output these to a file #write these data to disk so that we can access it later on np.save(leaveOneChromosomeOutDir + '/' + 'similarityMatrixTrain_' + chromosome + '_' + svType + '.npy', similarityMatrixTrain) np.save(leaveOneChromosomeOutDir + '/' + 'similarityMatrixTest_' + chromosome + '_' + svType + '.npy', similarityMatrixTest) #also save the labels np.save(leaveOneChromosomeOutDir + '/' + 'bagLabelsTrain_' + chromosome + '_' + svType + '.npy', trainLabels[chromosome]) np.save(leaveOneChromosomeOutDir + '/' + 'bagLabelsTest_' + chromosome + '_' + svType + '.npy', testLabels[chromosome]) elif featureElimination == 'False' and leaveBagsOut == 'True': ### leave-bags-out CV setting #divide into X bags, regardless of patients foldSize = 10 import math bagsPerFold = math.ceil((bags.shape[0] / foldSize) / 2) #in each fold, randomly sample positive bags and negative bags of same size trainBags = dict() testBags = dict() trainLabels = dict() testLabels = dict() testPairLabels = dict() #set random bags to use for each fold random.seed(785) randInd = random.sample(range(0, positiveBags.shape[0]), positiveBags.shape[0]) randIndNegative = random.sample(range(0, negativeBags.shape[0]), positiveBags.shape[0]) currentInd = 0 currentUntil = currentInd + bagsPerFold for foldInd in range(0, foldSize): #randomly sample x positive and negative bags randomPositive = positiveBags[randInd[currentInd:currentUntil]] randomNegative = negativeBags[randInd[currentInd:currentUntil]] #and labels positiveLabels = [1]*randomPositive.shape[0] negativeLabels = [0]*randomNegative.shape[0] testBags[foldInd] = np.concatenate((randomPositive, randomNegative)) testLabels[foldInd] = positiveLabels + negativeLabels #also get the pair labels testPairLabels[foldInd] = positiveBagPairNames[randInd[currentInd:currentUntil]] #then the training set will be all other bags otherPosInd = [] for ind in randInd: if ind not in randInd[currentInd:currentUntil]: otherPosInd.append(ind) otherNegInd = [] for ind in randInd: if ind not in randInd[currentInd:currentUntil]: otherNegInd.append(ind) positiveTrain = positiveBags[otherPosInd] negativeTrain = negativeBags[otherPosInd] trainPairLabels = positiveBagPairNames[otherPosInd] splitTrainPairs = dict() for pair in trainPairLabels: splitLabel = pair.split('_') splitTrainPairs[splitLabel[7] + '_' + splitLabel[0]] = pair for pair in testPairLabels[foldInd]: splitPair = pair.split('_') trainBags[foldInd] = np.concatenate((positiveTrain, negativeTrain)) trainLabels[foldInd] = [1]*len(otherPosInd) + [0]*len(otherNegInd) currentInd += bagsPerFold if currentUntil + bagsPerFold > positiveBags.shape[0]: currentUntil = positiveBags.shape[0] else: currentUntil += bagsPerFold for foldInd in range(0, foldSize): print(foldInd) #get instances trainInstances = np.vstack(trainBags[foldInd]) #this needs a bag map, which is changed each time we make subsets. reverseBagMapOtherPatients = dict() #lookup instance by bag index instanceInd = 0 for bagInd in range(0, trainBags[foldInd].shape[0]): reverseBagMapOtherPatients[bagInd] = [] for instance in trainBags[foldInd][bagInd]: reverseBagMapOtherPatients[bagInd].append(instanceInd) instanceInd += 1 #collect all this information as total bags/labels similarityMatrixTrain = getSimilarityMatrix(trainBags[foldInd], trainInstances, reverseBagMapOtherPatients) print(similarityMatrixTrain.shape) #now the curent patient bags need to be to the instances of the training set similarityMatrixTest = getSimilarityMatrixTest(testBags[foldInd], trainInstances, testLabels) print(similarityMatrixTest.shape) np.save(leaveBagsOutDir + '/similarityMatrixTrain_' + svType + '_' + str(foldInd) + '.npy', similarityMatrixTrain) np.save(leaveBagsOutDir + '/similarityMatrixTest_' + svType + '_' + str(foldInd) + '.npy', similarityMatrixTest) np.save(leaveBagsOutDir + '/bagLabelsTrain_' + svType + '_' + str(foldInd) + '.npy', trainLabels[foldInd]) np.save(leaveBagsOutDir + '/bagLabelsTest_' + svType + '_' + str(foldInd) + '.npy', testLabels[foldInd]) elif featureElimination == 'False' and leaveOnePatientOut == 'True': ### leave-one-patient-out CV setting random.seed(785) #first, get the bags and labels per patient perPatientPositiveBags = dict() for bagInd in range(0, positiveBags.shape[0]): #get the label of this bag bagPairLabel = positiveBagPairNames[bagInd] splitLabel = bagPairLabel.split('_') shortPair = splitLabel[7] + '_' + splitLabel[0] patientId = splitLabel[7] if patientId not in perPatientPositiveBags: perPatientPositiveBags[patientId] = dict() perPatientPositiveBags[patientId]['bags'] = [] perPatientPositiveBags[patientId]['pairLabels'] = [] perPatientPositiveBags[patientId]['bags'].append(positiveBags[bagInd]) perPatientPositiveBags[patientId]['pairLabels'].append(bagPairLabel) perPatientNegativeBags = dict() for bagInd in range(0, negativeBags.shape[0]): #get the label of this bag bagPairLabel = negativeBagPairNames[bagInd] splitLabel = bagPairLabel.split('_') patientId = splitLabel[7] if patientId not in perPatientNegativeBags: perPatientNegativeBags[patientId] = dict() perPatientNegativeBags[patientId]['bags'] = [] perPatientNegativeBags[patientId]['pairLabels'] = [] perPatientNegativeBags[patientId]['bags'].append(negativeBags[bagInd]) perPatientNegativeBags[patientId]['pairLabels'].append(bagPairLabel) print(len(perPatientPositiveBags)) print(len(perPatientNegativeBags)) #for each patient, randomly subsample as many negative bags as there are positives perPatientBags = dict() skippedPatients = 0 for patient in perPatientPositiveBags: if patient not in perPatientNegativeBags: skippedPatients += 1 continue if patient not in perPatientBags: perPatientBags[patient] = dict() perPatientBags[patient]['bags'] = [] perPatientBags[patient]['labels'] = [] perPatientBags[patient]['pairLabels'] = [] patientNegativeBags = perPatientNegativeBags[patient]['bags'] patientNegativeBags = np.array(patientNegativeBags) #also get the labels patientNegativeBagLabels = perPatientNegativeBags[patient]['pairLabels'] patientNegativeBagLabels = np.array(patientNegativeBagLabels) #add the same number of positives/negatives if len(perPatientPositiveBags[patient]['bags']) > patientNegativeBags.shape[0]: sampleCount = patientNegativeBags.shape[0] randomInd = random.sample(range(0, patientNegativeBags.shape[0]), sampleCount) print(patient) print(randomInd) randomNegativeBags = patientNegativeBags[randomInd] randomNegativeBagPairLabels = patientNegativeBagLabels[randomInd] for bag in randomNegativeBags: perPatientBags[patient]['bags'].append(bag) perPatientBags[patient]['labels'].append(0) for label in randomNegativeBagPairLabels: perPatientBags[patient]['pairLabels'].append(label) for bag in perPatientPositiveBags[patient]['bags']: perPatientBags[patient]['bags'].append(bag) perPatientBags[patient]['labels'].append(1) for label in perPatientPositiveBags[patient]['pairLabels']: perPatientBags[patient]['pairLabels'].append(label) else: sampleCount = len(perPatientPositiveBags[patient]['bags']) randomInd = random.sample(range(0, patientNegativeBags.shape[0]), sampleCount) print(patient) print(randomInd) randomNegativeBags = patientNegativeBags[randomInd] randomNegativeBagPairLabels = patientNegativeBagLabels[randomInd] for bag in randomNegativeBags: perPatientBags[patient]['bags'].append(bag) perPatientBags[patient]['labels'].append(0) for label in randomNegativeBagPairLabels: perPatientBags[patient]['pairLabels'].append(label) for bag in perPatientPositiveBags[patient]['bags']: perPatientBags[patient]['bags'].append(bag) perPatientBags[patient]['labels'].append(1) for label in perPatientPositiveBags[patient]['pairLabels']: perPatientBags[patient]['pairLabels'].append(label) print(skippedPatients) #go through each patient, and divide into train/test #the training set will be a merge of the bags of all other patients. #then for each patient, get the train/test combination testPatients = dict() trainPatients = dict() ind = 1 foldInd = 0 foldSize = 1 for patient in perPatientBags: if foldInd not in testPatients: testPatients[foldInd] = [] trainPatients[foldInd] = [] testPatients[foldInd].append(patient) if ind % foldSize == 0: for patient2 in perPatientBags: if patient2 not in testPatients[foldInd]: trainPatients[foldInd].append(patient2) foldInd += 1 ind += 1 #add remaining patients if foldInd in testPatients and len(trainPatients[foldInd]) < 1: for patient2 in perPatientBags: if patient2 not in testPatients[foldInd]: trainPatients[foldInd].append(patient2) for fold in testPatients: testBags = [] trainBags = [] testLabels = [] trainLabels = [] testPairLabels = [] for patient in perPatientBags: patientBags = perPatientBags[patient]['bags'] patientLabels = perPatientBags[patient]['labels'] patientPairLabels = perPatientBags[patient]['pairLabels'] if patient in testPatients[fold]: testBags += patientBags testLabels += patientLabels testPairLabels += patientPairLabels else: trainBags += patientBags trainLabels += patientLabels testBags = np.array(testBags) trainBags = np.array(trainBags) #get instances trainInstances = np.vstack(trainBags) #this needs a bag map, which is changed each time we make subsets. reverseBagMapOtherPatients = dict() #lookup instance by bag index instanceInd = 0 for bagInd in range(0, trainBags.shape[0]): reverseBagMapOtherPatients[bagInd] = [] for instance in trainBags[bagInd]: reverseBagMapOtherPatients[bagInd].append(instanceInd) instanceInd += 1 #collect all this information as total bags/labels similarityMatrixTrain = getSimilarityMatrix(trainBags, trainInstances, reverseBagMapOtherPatients) #now the curent patient bags need to be to the instances of the training set similarityMatrixTest = getSimilarityMatrixTest(testBags, trainInstances, testLabels) #write these data to disk so that we can access it later on np.save(leaveOnePatientOutDir + '/' + 'similarityMatrixTrain_' + str(fold) + '_' + svType + '.npy', similarityMatrixTrain) np.save(leaveOnePatientOutDir + '/' + 'similarityMatrixTest_' + str(fold) + '_' + svType + '.npy', similarityMatrixTest) #also save the labels np.save(leaveOnePatientOutDir + '/' + 'bagLabelsTrain_' + str(fold) + '_' + svType + '.npy', trainLabels) np.save(leaveOnePatientOutDir + '/' + 'bagLabelsTest_' + str(fold) + '_' + svType + '.npy', testLabels) #and the test pair labels np.save(leaveOnePatientOutDir + '/' + 'bagPairLabelsTest_' + str(fold) + '_' + svType + '.npy', testPairLabels) else: #output the whole similarity matrix #similarityMatrix = getSimilarityMatrix(bags, instances, reverseBagMap) similarityMatrix = getSimilarityMatrix(bags, instances, reverseBagMap) print('similarity matrix sizes: ', similarityMatrix.shape) print('bag size: ', bags.shape) #output these to a file #write these data to disk so that we can access it later on np.save(finalOutDir + '/' + 'similarityMatrix_' + svType + '.npy', similarityMatrix)
""" The goal of this script is to generate the similarity matrices for MIL The similarity matrices are pre-generated for the CV type that these will be used for. There is: - leave-one-chromosome-out CV - leave-one-patient-out CV - leave-bags-out CV - the similarity matrix on the whole dataset (used for feature importance) If we do feature elimination, we have similarity matrices for each feature output these as well. """ import sys import os import numpy as np import pickle as pkl import random random.seed(785) np.random.seed(785) import matplotlib matplotlib.use('Agg') path = sys.argv[7] sys.path.insert(1, path) import settings featureElimination = sys.argv[2] leaveOnePatientOut = sys.argv[3] #make the similarity matrices for each left out patient leaveOneChromosomeOut = sys.argv[4] #1 chromosome at a time in the test set leaveBagsOut = sys.argv[5] #random bags in each CV fold fullDataset = sys.argv[6] #generate sim matrix for the whole dataset. svTypes = ['DEL', 'DUP', 'INV', 'ITX'] #svTypes = ['ALL'] outDir = sys.argv[1] finalOutDir = outDir + '/multipleInstanceLearning/similarityMatrices/' if not os.path.exists(finalOutDir): os.makedirs(finalOutDir) if featureElimination == "True": featureEliminationOutDir = finalOutDir + '/featureSelection' if not os.path.exists(featureEliminationOutDir): os.makedirs(featureEliminationOutDir) if leaveOnePatientOut == 'True': leaveOnePatientOutDir = finalOutDir + '/leaveOnePatientOut' if not os.path.exists(leaveOnePatientOutDir): os.makedirs(leaveOnePatientOutDir) if leaveOneChromosomeOut == 'True': leaveOneChromosomeOutDir = finalOutDir + '/leaveOneChromosomeOut' if not os.path.exists(leaveOneChromosomeOutDir): os.makedirs(leaveOneChromosomeOutDir) if leaveBagsOut == 'True': leaveBagsOutDir = finalOutDir + '/leaveBagsOut' if not os.path.exists(leaveBagsOutDir): os.makedirs(leaveBagsOutDir) #input the normalized bags with open(outDir + '/linkedSVGenePairs/normalizedBags.pkl', 'rb') as handle: bagDict = pkl.load(handle) #get the information for the bag labels degPairs = np.loadtxt(outDir + '/tadDisruptionsZScores/zScores.txt', dtype='object') #labels print(degPairs) print("initial number of bags: ", len(bagDict)) print('initial deg pairs: ', degPairs.shape[0]) mutDir = outDir + '/patientGeneMutationPairs/' cnvPatientsAmp = np.load(mutDir + 'cnvPatientsAmp.npy', allow_pickle=True, encoding='latin1').item() svPatientsDup = np.load(mutDir + 'svPatientsDup.npy', allow_pickle=True, encoding='latin1').item() svGenePairs = np.loadtxt(outDir + '/linkedSVGenePairs/nonCoding_geneSVPairs.txt_', dtype='object') splitSVGenePairs = [] for pair in svGenePairs: splitPair = pair[0].split('_') splitSVGenePairs.append(splitPair[0] + '_' + splitPair[7] + '_' + splitPair[12]) def getSimilarityMatrix(bags, instances, reverseBagMap): """ function to get the similarity matrix. This is mainly used to make the sim matrix for the training set. To make the test set sim matrix, use the function below. bags (numpy array): all bags that we use for this matrix instances (numpy array): all instances in the bags reverseBagMap (dictionary): bag index as key, instance indices as values. Used to find out which instances are in which bag. """ bagIndices = np.arange(bags.shape[0]) similarityMatrix = np.zeros([bags.shape[0], instances.shape[0]]) for bagInd in range(0, bags.shape[0]): #Get the indices of the instances that are in this bag instanceIndices = reverseBagMap[bagInd] instanceSubset = instances[instanceIndices,:] #get the average of all instances in this bag instanceAvg = np.mean(instanceSubset, axis=0) #compute distance to all other instances from this bag average distance = np.abs(instanceAvg - instances) #sum the distances to get 1 similarity score summedDistance = np.sum(distance,axis=1) similarityMatrix[bagInd,:] = summedDistance return similarityMatrix def getSimilarityMatrixTest(testBags, trainInstances, labels): """ function to get the similarity matrix specific for the test case. The instances that we map the distance to are the provided train instances. testBags (numpy array): all test bags that we use for this matrix trainInstances (numpy array): all instances in the bags of the training data, we compute distance to these instances from the test bags labels (list): obsolete. """ similarityMatrix = np.zeros([testBags.shape[0], trainInstances.shape[0]]) #print(similarityMatrix.shape) for bagInd in range(0, testBags.shape[0]): #print(labels[bagInd]) #get the average of all instances in this test patient bag testInstances = testBags[bagInd] instanceAvg = np.mean(testInstances, axis=0) #compute distance to all other instances from this bag average distance = np.abs(instanceAvg - trainInstances) #sum the distances to get 1 similarity score summedDistance = np.sum(distance,axis=1) #print(summedDistance) similarityMatrix[bagInd,:] = summedDistance return similarityMatrix #Generate the similarity matrices for the SV types for svType in svTypes: bagLabels = [] positiveBagPairNames = [] negativeBagPairNames = [] positiveInstanceLabels = [] positiveBags = [] negativeBags = [] #for each SV-gene pair, get the instances for pair in bagDict: #check if the SV type matches our selection splitPair = pair.split("_") shortPair = splitPair[7] + '_' + splitPair[0] if svType != '' and svType != 'ALL': if splitPair[12] != svType: continue #get the label of the bag by checking if it exists in degPairs, some pairs do not have a z-score because the gene is excluded due to mutations. if shortPair in degPairs[:,0]: #get the z-score of the pair. degPairInfo = degPairs[degPairs[:,0] == shortPair][0] #if the z-score matches this criterion, the SV-gene pair is positive if float(degPairInfo[5]) > 1.5 or float(degPairInfo[5]) < -1.5: #go through the instances of this SV-gene pair, and include only those that have gains and losses, and more than 1 instance. This should in principle not happen, but good to keep a check. instances = [] for instance in bagDict[pair]: if instance[0] == 0 and instance[1] == 0: continue instances.append(instance) if len(instances) < 1: continue ###Here do an extra check: #to make fig2A, we only look at TADs with SVs across the boundary, so those z-scores are in the set. #BUT some of these genes are not actually affected by the SV, since this doesn't lead to #regulatory elements gained/lost. SO, we need to remove those here to get the actual pairs. #This only goes wrong for duplications, because we also keep CNV amps that could be the same event, #but then the duplication does not lead to gains/losses, while the CNV amp does because it is slightly #longer. So if there is evidence of a cnv AMP, but no non-coding duplication linked, we can remove #this as a positive pair. if splitPair[7] not in cnvPatientsAmp: positiveBagPairNames.append(pair) positiveBags.append(instances) else: dupMatch = splitPair[0] + '_' + splitPair[7] + '_DUP' if splitPair[0] in cnvPatientsAmp[splitPair[7]] and dupMatch not in splitSVGenePairs: negativeBags.append(instances) negativeBagPairNames.append(pair) else: positiveBagPairNames.append(pair) positiveBags.append(instances) else: #if the z-score is anything else, this bag will be labeled negative. #get the right number of features per instance instances = [] for instance in bagDict[pair]: if instance[0] == 0 and instance[1] == 0: continue instances.append(instance) if len(instances) < 1: continue negativeBags.append(instances) negativeBagPairNames.append(pair) positiveBags = np.array(positiveBags) negativeBags = np.array(negativeBags) positiveBagPairNames = np.array(positiveBagPairNames) negativeBagPairNames = np.array(negativeBagPairNames) #fail-safe in case there are not enough SVs of this type if positiveBags.shape[0] < 2 or negativeBags.shape[0] < 2: continue #add the number of instances per bag as feature to the instances for bag in positiveBags: instCount = len(bag) for instance in bag: instance.append(instCount / positiveBags.shape[0]) for bag in negativeBags: instCount = len(bag) for instance in bag: instance.append(instCount / negativeBags.shape[0]) #remove instances with no variance posInstances = np.vstack(positiveBags) negInstances = np.vstack(negativeBags) allInstances = np.concatenate((posInstances, negInstances)) #remove instances with 0 variance across all instances. These are not useful for the classifier. from sklearn.feature_selection import VarianceThreshold t = 0 vt = VarianceThreshold(threshold=t) vt.fit(allInstances) idx = np.where(vt.variances_ > t)[0] badIdx = np.where(vt.variances_ <= t)[0] np.savetxt(finalOutDir + '/lowVarianceIdx_' + svType + '.txt', badIdx) newPositiveBags = [] newNegativeBags = [] for bag in positiveBags: instances = [] for instance in bag: filteredInstance = [] featureInd = 0 for feature in instance: if featureInd in idx: filteredInstance.append(feature) featureInd += 1 instances.append(filteredInstance) newPositiveBags.append(instances) for bag in negativeBags: instances = [] for instance in bag: filteredInstance = [] featureInd = 0 for feature in instance: if featureInd in idx: filteredInstance.append(feature) featureInd += 1 instances.append(filteredInstance) newNegativeBags.append(instances) positiveBags = np.array(newPositiveBags) negativeBags = np.array(newNegativeBags) print(positiveBags.shape) #subsample the positive bags if there are too many threshold = int(settings.general['bagThreshold']) if positiveBags.shape[0] > threshold: random.seed(785) #subsample the positive set to the threshold positiveBagsSubsampled = np.random.choice(positiveBags, threshold) positiveBagsSubsampleInd = np.random.choice(np.arange(positiveBags.shape[0]), threshold) positiveBagsSubsampled = positiveBags[positiveBagsSubsampleInd] positiveBags = positiveBagsSubsampled print('Number of positive bags: ', positiveBags.shape) print('Number of negative bags: ', negativeBags.shape) print('Number of positive instances: ', len(positiveInstanceLabels)) if positiveBags.shape[0] == 0 or negativeBags.shape[0] == 0: continue #subsample negative to the same number of positives. random.seed(785) #somehow the global setting doesn't work in the second loop? so set it here. #subsample the negative set to the same number of positives. negativeBagsSubsampled = np.random.choice(negativeBags, positiveBags.shape[0]) negativeBagsSubsampleInd = np.random.choice(np.arange(negativeBags.shape[0]), positiveBags.shape[0]) negativeBagsSubsampled = negativeBags[negativeBagsSubsampleInd] negativeBagPairNamesSubsampled = negativeBagPairNames[negativeBagsSubsampleInd] #posInstances = np.vstack(positiveBags) #negInstances = np.vstack(negativeBagsSubsampled) bagPairLabelsSubsampled = np.concatenate((positiveBagPairNames, negativeBagPairNamesSubsampled)) #save the bag pair labels for later np.save(finalOutDir + '/bagPairLabelsSubsampled_' + svType + '.npy', bagPairLabelsSubsampled) #merge the bags so that we can easily get to 1 similarity matrix and do all-to-all computations bagsSubsampled = np.concatenate((positiveBags, negativeBagsSubsampled)) #assign bag labels bagLabelsSubsampled = np.array([1]*positiveBags.shape[0] + [0]*negativeBagsSubsampled.shape[0]) np.save(finalOutDir + '/bagLabelsSubsampled_' + svType + '.npy', bagLabelsSubsampled) #stack the instances in the bags so that we can easily compute bag-instance distances instancesSubsampled = np.vstack(bagsSubsampled) #also output the instances for later np.save(finalOutDir + '/instancesSubsampled_' + svType + '.npy', instancesSubsampled) #and save the bags. np.save(finalOutDir + '/bagsSubsampled_' + svType + '.npy', bagsSubsampled) #in case of leave-one-patient out, we subsample later on bagPairLabels = np.concatenate((positiveBagPairNames, negativeBagPairNames)) #save the bag pair labels for later np.save(finalOutDir + '/bagPairLabelsNotSubsampled_' + svType + '.npy', bagPairLabels) #merge the bags so that we can easily get to 1 similarity matrix and do all-to-all computations bags = np.concatenate((positiveBags, negativeBags)) #assign bag labels bagLabels = np.array([1]*positiveBags.shape[0] + [0]*negativeBags.shape[0]) np.save(finalOutDir + '/bagLabelsNotSubsampled_' + svType + '.npy', bagLabels) #stack the instances in the bags so that we can easily compute bag-instance distances instances = np.vstack(bags) #also output the instances for later np.save(finalOutDir + '/instancesNotSubsampled_' + svType + '.npy', instances) #and save the bags. np.save(finalOutDir + '/bagsNotSubsampled_' + svType + '.npy', bags) print('size comparison: ') print('bags not subsampled: ', bags.shape) print('instances not subsampled: ', instances.shape) print('bag labels not subsampled: ', bagLabels.shape) print('bag pair labels not subsampled: ', bagPairLabels.shape) print('bags subsampled: ', bagsSubsampled.shape) print('instances subsampled: ', instancesSubsampled.shape) print('bag labels subsampled: ', bagLabelsSubsampled.shape) print('bag pair labels subsampled: ', bagPairLabelsSubsampled.shape) # if fullDataset == 'False': # bags = bagsSubsampled # instances = instancesSubsampled # bagPairLabels = bagPairLabelsSubsampled # bagLabels = bagLabelsSubsampled bags = bagsSubsampled instances = instancesSubsampled bagPairLabels = bagPairLabelsSubsampled bagLabels = bagLabelsSubsampled #Make an index where we can lookup at which position the instances are in the concatenated bag array. reverseBagMap = dict() #lookup instance by bag index bagMap = dict() #lookup bag by instance index instanceInd = 0 for bagInd in range(0, bags.shape[0]): reverseBagMap[bagInd] = [] for instance in bags[bagInd]: reverseBagMap[bagInd].append(instanceInd) bagMap[instanceInd] = bagInd instanceInd += 1 #save bagmap for later np.save(finalOutDir + '/bagMap_' + svType + '.npy', bagMap) #if we do feature elimination, randomize the features here featureCount = instances.shape[1] featureStart = featureCount-1 if featureElimination == "True": featureStart = 0 #set this to featureCount to run with all features. #if featureStart is not updated, this will run once #otherwise it will randomize a new feature each time for featureInd in range(featureStart, featureCount): print('current feature: ', featureInd+1) if featureElimination == "True": #in case of feature elimination, we use the leave-one-chromosome-out CV setting #per chromosome, shuffle the features in the training set. #then output the original test set #so we have per SV type, per chromosome CV, X files for the number of features shuffled chromosomes = ['chr1', 'chr2', 'chr3', 'chr4', 'chr5', 'chr6', 'chr7', 'chr8', 'chr9', 'chr10', 'chr11', 'chr12', 'chr13', 'chr14', 'chr15', 'chr16', 'chr17', 'chr18', 'chr19', 'chr20', 'chr21', 'chr22'] positiveBagsPerChromosome = dict() negativeBagsPerChromosome = dict() for labelInd in range(0, len(positiveBagPairNames)): label = positiveBagPairNames[labelInd] splitLabel = label.split('_') chromosome = splitLabel[1] if chromosome not in positiveBagsPerChromosome: positiveBagsPerChromosome[chromosome] = [] positiveBagsPerChromosome[chromosome].append(positiveBags[labelInd]) for labelInd in range(0, len(negativeBagPairNames)): label = negativeBagPairNames[labelInd] splitLabel = label.split('_') chromosome = splitLabel[1] if chromosome not in negativeBagsPerChromosome: negativeBagsPerChromosome[chromosome] = [] negativeBagsPerChromosome[chromosome].append(negativeBags[labelInd]) trainBags = dict() testBags = dict() trainLabels = dict() testLabels = dict() for chromosome in chromosomes: if chromosome not in positiveBagsPerChromosome: continue if chromosome not in negativeBagsPerChromosome: continue #make stratified testPositiveBags = positiveBagsPerChromosome[chromosome] testNegativeBags = negativeBagsPerChromosome[chromosome] testPositiveBags = np.array(testPositiveBags) testNegativeBags = np.array(testNegativeBags) randInd = random.sample(range(0, testNegativeBags.shape[0]), testPositiveBags.shape[0]) testSubsetNegativeBags = testNegativeBags[randInd] allTestBags = [] for bag in testPositiveBags: allTestBags.append(bag) for bag in testSubsetNegativeBags: #for bag in testNegativeBags: allTestBags.append(bag) allTestBags = np.array(allTestBags) testBags[chromosome] = allTestBags testLabels[chromosome] = [1]*testPositiveBags.shape[0] + [0]*testSubsetNegativeBags.shape[0] #testLabels[chromosome] = [1]*testPositiveBags.shape[0] + [0]*testNegativeBags.shape[0] testPositiveInstances = np.vstack(testPositiveBags) testNegativeInstances = np.vstack(testSubsetNegativeBags) testPositiveLabels = [1]*testPositiveInstances.shape[0] testNegativeLabels = [0]*testNegativeInstances.shape[0] #make training set from the rest trainingSet = [] trainingLabels = [] allTrainInstances = [] allTrainLabels = [] for chromosome2 in chromosomes: if chromosome == chromosome2: continue if chromosome2 not in positiveBagsPerChromosome: continue if chromosome2 not in negativeBagsPerChromosome: continue #make stratified chrPositiveBags = positiveBagsPerChromosome[chromosome2] chrNegativeBags = negativeBagsPerChromosome[chromosome2] chrPositiveBags = np.array(chrPositiveBags) chrNegativeBags = np.array(chrNegativeBags) random.seed(785) randInd = random.sample(range(0, chrNegativeBags.shape[0]), chrPositiveBags.shape[0]) subsetNegativeBags = chrNegativeBags[randInd] for bag in chrPositiveBags: trainingSet.append(bag) for bag in subsetNegativeBags: #for bag in chrNegativeBags: trainingSet.append(bag) trainingLabels += [1]*chrPositiveBags.shape[0] trainingLabels += [0]*subsetNegativeBags.shape[0] #trainingLabels += [0]*chrNegativeBags.shape[0] trainPositiveInstances = np.vstack(chrPositiveBags) trainNegativeInstances = np.vstack(subsetNegativeBags) trainPositiveLabels = [1]*trainPositiveInstances.shape[0] trainNegativeLabels = [0]*trainNegativeInstances.shape[0] trainBags[chromosome] = np.array(trainingSet) trainLabels[chromosome] = trainingLabels trainInstances = np.vstack(trainBags[chromosome]) #shuffle the training instances shuffledInstanceValues = trainInstances[:,featureInd] randomInd = np.arange(0, shuffledInstanceValues.shape[0]) np.random.shuffle(randomInd) #we compute the similarity matrix based on the instances #but the instance values need to be reset every iteration shuffledInstances = np.zeros(trainInstances.shape) for col in range(0, trainInstances.shape[1]): if col != featureInd: shuffledInstances[:,col] = trainInstances[:,col] else: shuffledInstances[:,col] = trainInstances[randomInd,col] reverseBagMapOtherPatients = dict() #lookup instance by bag index instanceInd = 0 for bagInd in range(0, trainBags[chromosome].shape[0]): reverseBagMapOtherPatients[bagInd] = [] for instance in trainBags[chromosome][bagInd]: reverseBagMapOtherPatients[bagInd].append(instanceInd) instanceInd += 1 similarityMatrixTrain = getSimilarityMatrix(trainBags[chromosome], shuffledInstances, reverseBagMapOtherPatients) #now the curent patient bags need to be to the instances of the training set similarityMatrixTest = getSimilarityMatrixTest(testBags[chromosome], shuffledInstances, testLabels) #output these to a file #write these data to disk so that we can access it later on np.save(featureEliminationOutDir + '/' + 'similarityMatrixTrain_' + svType + '_' + chromosome + '_' + str(featureInd) + '.npy', similarityMatrixTrain) np.save(featureEliminationOutDir + '/' + 'similarityMatrixTest_' + svType + '_' + chromosome + '_' + str(featureInd) + '.npy', similarityMatrixTest) #also save the labels np.save(featureEliminationOutDir + '/' + 'bagLabelsTrain_' + svType + '_' + chromosome + '_' + str(featureInd) + '.npy', trainLabels[chromosome]) np.save(featureEliminationOutDir + '/' + 'bagLabelsTest_' + svType + '_' + chromosome + '_' + str(featureInd) + '.npy', testLabels[chromosome]) elif featureElimination == 'False' and leaveOneChromosomeOut == 'True': ### leave-one-chromosome-out CV setting chromosomes = ['chr1', 'chr2', 'chr3', 'chr4', 'chr5', 'chr6', 'chr7', 'chr8', 'chr9', 'chr10', 'chr11', 'chr12', 'chr13', 'chr14', 'chr15', 'chr16', 'chr17', 'chr18', 'chr19', 'chr20', 'chr21', 'chr22'] positiveBagsPerChromosome = dict() negativeBagsPerChromosome = dict() for labelInd in range(0, len(positiveBagPairNames)): label = positiveBagPairNames[labelInd] splitLabel = label.split('_') chromosome = splitLabel[1] if chromosome not in positiveBagsPerChromosome: positiveBagsPerChromosome[chromosome] = [] positiveBagsPerChromosome[chromosome].append(positiveBags[labelInd]) for labelInd in range(0, len(negativeBagPairNames)): label = negativeBagPairNames[labelInd] splitLabel = label.split('_') chromosome = splitLabel[1] if chromosome not in negativeBagsPerChromosome: negativeBagsPerChromosome[chromosome] = [] negativeBagsPerChromosome[chromosome].append(negativeBags[labelInd]) trainBags = dict() testBags = dict() trainLabels = dict() testLabels = dict() for chromosome in chromosomes: print(chromosome) #if chromosome != 'chr16': # continue if chromosome not in positiveBagsPerChromosome: continue if chromosome not in negativeBagsPerChromosome: continue #make stratified testPositiveBags = positiveBagsPerChromosome[chromosome] testNegativeBags = negativeBagsPerChromosome[chromosome] testPositiveBags = np.array(testPositiveBags) testNegativeBags = np.array(testNegativeBags) random.seed(785) randInd = random.sample(range(0, testNegativeBags.shape[0]), testPositiveBags.shape[0]) testSubsetNegativeBags = testNegativeBags[randInd] allTestBags = [] for bag in testPositiveBags: allTestBags.append(bag) for bag in testSubsetNegativeBags: #for bag in testNegativeBags: allTestBags.append(bag) allTestBags = np.array(allTestBags) print(allTestBags.shape) testBags[chromosome] = allTestBags testLabels[chromosome] = [1]*testPositiveBags.shape[0] + [0]*testSubsetNegativeBags.shape[0] #make training set from the rest trainingSet = [] trainingLabels = [] allTrainInstances = [] allTrainLabels = [] for chromosome2 in chromosomes: if chromosome == chromosome2: continue if chromosome2 not in positiveBagsPerChromosome: continue if chromosome2 not in negativeBagsPerChromosome: continue #make stratified chrPositiveBags = positiveBagsPerChromosome[chromosome2] chrNegativeBags = negativeBagsPerChromosome[chromosome2] chrPositiveBags = np.array(chrPositiveBags) chrNegativeBags = np.array(chrNegativeBags) random.seed(785) randInd = random.sample(range(0, chrNegativeBags.shape[0]), chrPositiveBags.shape[0]) subsetNegativeBags = chrNegativeBags[randInd] for bag in chrPositiveBags: trainingSet.append(bag) for bag in subsetNegativeBags: #for bag in chrNegativeBags: trainingSet.append(bag) trainingLabels += [1]*chrPositiveBags.shape[0] trainingLabels += [0]*subsetNegativeBags.shape[0] trainBags[chromosome] = np.array(trainingSet) trainLabels[chromosome] = trainingLabels trainInstances = np.vstack(trainBags[chromosome]) reverseBagMapOtherPatients = dict() #lookup instance by bag index instanceInd = 0 for bagInd in range(0, trainBags[chromosome].shape[0]): reverseBagMapOtherPatients[bagInd] = [] for instance in trainBags[chromosome][bagInd]: reverseBagMapOtherPatients[bagInd].append(instanceInd) instanceInd += 1 similarityMatrixTrain = getSimilarityMatrix(trainBags[chromosome], trainInstances, reverseBagMapOtherPatients) print(similarityMatrixTrain.shape) #now the curent patient bags need to be to the instances of the training set similarityMatrixTest = getSimilarityMatrixTest(testBags[chromosome], trainInstances, testLabels) #output these to a file #write these data to disk so that we can access it later on np.save(leaveOneChromosomeOutDir + '/' + 'similarityMatrixTrain_' + chromosome + '_' + svType + '.npy', similarityMatrixTrain) np.save(leaveOneChromosomeOutDir + '/' + 'similarityMatrixTest_' + chromosome + '_' + svType + '.npy', similarityMatrixTest) #also save the labels np.save(leaveOneChromosomeOutDir + '/' + 'bagLabelsTrain_' + chromosome + '_' + svType + '.npy', trainLabels[chromosome]) np.save(leaveOneChromosomeOutDir + '/' + 'bagLabelsTest_' + chromosome + '_' + svType + '.npy', testLabels[chromosome]) elif featureElimination == 'False' and leaveBagsOut == 'True': ### leave-bags-out CV setting #divide into X bags, regardless of patients foldSize = 10 import math bagsPerFold = math.ceil((bags.shape[0] / foldSize) / 2) #in each fold, randomly sample positive bags and negative bags of same size trainBags = dict() testBags = dict() trainLabels = dict() testLabels = dict() testPairLabels = dict() #set random bags to use for each fold random.seed(785) randInd = random.sample(range(0, positiveBags.shape[0]), positiveBags.shape[0]) randIndNegative = random.sample(range(0, negativeBags.shape[0]), positiveBags.shape[0]) currentInd = 0 currentUntil = currentInd + bagsPerFold for foldInd in range(0, foldSize): #randomly sample x positive and negative bags randomPositive = positiveBags[randInd[currentInd:currentUntil]] randomNegative = negativeBags[randInd[currentInd:currentUntil]] #and labels positiveLabels = [1]*randomPositive.shape[0] negativeLabels = [0]*randomNegative.shape[0] testBags[foldInd] = np.concatenate((randomPositive, randomNegative)) testLabels[foldInd] = positiveLabels + negativeLabels #also get the pair labels testPairLabels[foldInd] = positiveBagPairNames[randInd[currentInd:currentUntil]] #then the training set will be all other bags otherPosInd = [] for ind in randInd: if ind not in randInd[currentInd:currentUntil]: otherPosInd.append(ind) otherNegInd = [] for ind in randInd: if ind not in randInd[currentInd:currentUntil]: otherNegInd.append(ind) positiveTrain = positiveBags[otherPosInd] negativeTrain = negativeBags[otherPosInd] trainPairLabels = positiveBagPairNames[otherPosInd] splitTrainPairs = dict() for pair in trainPairLabels: splitLabel = pair.split('_') splitTrainPairs[splitLabel[7] + '_' + splitLabel[0]] = pair for pair in testPairLabels[foldInd]: splitPair = pair.split('_') trainBags[foldInd] = np.concatenate((positiveTrain, negativeTrain)) trainLabels[foldInd] = [1]*len(otherPosInd) + [0]*len(otherNegInd) currentInd += bagsPerFold if currentUntil + bagsPerFold > positiveBags.shape[0]: currentUntil = positiveBags.shape[0] else: currentUntil += bagsPerFold for foldInd in range(0, foldSize): print(foldInd) #get instances trainInstances = np.vstack(trainBags[foldInd]) #this needs a bag map, which is changed each time we make subsets. reverseBagMapOtherPatients = dict() #lookup instance by bag index instanceInd = 0 for bagInd in range(0, trainBags[foldInd].shape[0]): reverseBagMapOtherPatients[bagInd] = [] for instance in trainBags[foldInd][bagInd]: reverseBagMapOtherPatients[bagInd].append(instanceInd) instanceInd += 1 #collect all this information as total bags/labels similarityMatrixTrain = getSimilarityMatrix(trainBags[foldInd], trainInstances, reverseBagMapOtherPatients) print(similarityMatrixTrain.shape) #now the curent patient bags need to be to the instances of the training set similarityMatrixTest = getSimilarityMatrixTest(testBags[foldInd], trainInstances, testLabels) print(similarityMatrixTest.shape) np.save(leaveBagsOutDir + '/similarityMatrixTrain_' + svType + '_' + str(foldInd) + '.npy', similarityMatrixTrain) np.save(leaveBagsOutDir + '/similarityMatrixTest_' + svType + '_' + str(foldInd) + '.npy', similarityMatrixTest) np.save(leaveBagsOutDir + '/bagLabelsTrain_' + svType + '_' + str(foldInd) + '.npy', trainLabels[foldInd]) np.save(leaveBagsOutDir + '/bagLabelsTest_' + svType + '_' + str(foldInd) + '.npy', testLabels[foldInd]) elif featureElimination == 'False' and leaveOnePatientOut == 'True': ### leave-one-patient-out CV setting random.seed(785) #first, get the bags and labels per patient perPatientPositiveBags = dict() for bagInd in range(0, positiveBags.shape[0]): #get the label of this bag bagPairLabel = positiveBagPairNames[bagInd] splitLabel = bagPairLabel.split('_') shortPair = splitLabel[7] + '_' + splitLabel[0] patientId = splitLabel[7] if patientId not in perPatientPositiveBags: perPatientPositiveBags[patientId] = dict() perPatientPositiveBags[patientId]['bags'] = [] perPatientPositiveBags[patientId]['pairLabels'] = [] perPatientPositiveBags[patientId]['bags'].append(positiveBags[bagInd]) perPatientPositiveBags[patientId]['pairLabels'].append(bagPairLabel) perPatientNegativeBags = dict() for bagInd in range(0, negativeBags.shape[0]): #get the label of this bag bagPairLabel = negativeBagPairNames[bagInd] splitLabel = bagPairLabel.split('_') patientId = splitLabel[7] if patientId not in perPatientNegativeBags: perPatientNegativeBags[patientId] = dict() perPatientNegativeBags[patientId]['bags'] = [] perPatientNegativeBags[patientId]['pairLabels'] = [] perPatientNegativeBags[patientId]['bags'].append(negativeBags[bagInd]) perPatientNegativeBags[patientId]['pairLabels'].append(bagPairLabel) print(len(perPatientPositiveBags)) print(len(perPatientNegativeBags)) #for each patient, randomly subsample as many negative bags as there are positives perPatientBags = dict() skippedPatients = 0 for patient in perPatientPositiveBags: if patient not in perPatientNegativeBags: skippedPatients += 1 continue if patient not in perPatientBags: perPatientBags[patient] = dict() perPatientBags[patient]['bags'] = [] perPatientBags[patient]['labels'] = [] perPatientBags[patient]['pairLabels'] = [] patientNegativeBags = perPatientNegativeBags[patient]['bags'] patientNegativeBags = np.array(patientNegativeBags) #also get the labels patientNegativeBagLabels = perPatientNegativeBags[patient]['pairLabels'] patientNegativeBagLabels = np.array(patientNegativeBagLabels) #add the same number of positives/negatives if len(perPatientPositiveBags[patient]['bags']) > patientNegativeBags.shape[0]: sampleCount = patientNegativeBags.shape[0] randomInd = random.sample(range(0, patientNegativeBags.shape[0]), sampleCount) print(patient) print(randomInd) randomNegativeBags = patientNegativeBags[randomInd] randomNegativeBagPairLabels = patientNegativeBagLabels[randomInd] for bag in randomNegativeBags: perPatientBags[patient]['bags'].append(bag) perPatientBags[patient]['labels'].append(0) for label in randomNegativeBagPairLabels: perPatientBags[patient]['pairLabels'].append(label) for bag in perPatientPositiveBags[patient]['bags']: perPatientBags[patient]['bags'].append(bag) perPatientBags[patient]['labels'].append(1) for label in perPatientPositiveBags[patient]['pairLabels']: perPatientBags[patient]['pairLabels'].append(label) else: sampleCount = len(perPatientPositiveBags[patient]['bags']) randomInd = random.sample(range(0, patientNegativeBags.shape[0]), sampleCount) print(patient) print(randomInd) randomNegativeBags = patientNegativeBags[randomInd] randomNegativeBagPairLabels = patientNegativeBagLabels[randomInd] for bag in randomNegativeBags: perPatientBags[patient]['bags'].append(bag) perPatientBags[patient]['labels'].append(0) for label in randomNegativeBagPairLabels: perPatientBags[patient]['pairLabels'].append(label) for bag in perPatientPositiveBags[patient]['bags']: perPatientBags[patient]['bags'].append(bag) perPatientBags[patient]['labels'].append(1) for label in perPatientPositiveBags[patient]['pairLabels']: perPatientBags[patient]['pairLabels'].append(label) print(skippedPatients) #go through each patient, and divide into train/test #the training set will be a merge of the bags of all other patients. #then for each patient, get the train/test combination testPatients = dict() trainPatients = dict() ind = 1 foldInd = 0 foldSize = 1 for patient in perPatientBags: if foldInd not in testPatients: testPatients[foldInd] = [] trainPatients[foldInd] = [] testPatients[foldInd].append(patient) if ind % foldSize == 0: for patient2 in perPatientBags: if patient2 not in testPatients[foldInd]: trainPatients[foldInd].append(patient2) foldInd += 1 ind += 1 #add remaining patients if foldInd in testPatients and len(trainPatients[foldInd]) < 1: for patient2 in perPatientBags: if patient2 not in testPatients[foldInd]: trainPatients[foldInd].append(patient2) for fold in testPatients: testBags = [] trainBags = [] testLabels = [] trainLabels = [] testPairLabels = [] for patient in perPatientBags: patientBags = perPatientBags[patient]['bags'] patientLabels = perPatientBags[patient]['labels'] patientPairLabels = perPatientBags[patient]['pairLabels'] if patient in testPatients[fold]: testBags += patientBags testLabels += patientLabels testPairLabels += patientPairLabels else: trainBags += patientBags trainLabels += patientLabels testBags = np.array(testBags) trainBags = np.array(trainBags) #get instances trainInstances = np.vstack(trainBags) #this needs a bag map, which is changed each time we make subsets. reverseBagMapOtherPatients = dict() #lookup instance by bag index instanceInd = 0 for bagInd in range(0, trainBags.shape[0]): reverseBagMapOtherPatients[bagInd] = [] for instance in trainBags[bagInd]: reverseBagMapOtherPatients[bagInd].append(instanceInd) instanceInd += 1 #collect all this information as total bags/labels similarityMatrixTrain = getSimilarityMatrix(trainBags, trainInstances, reverseBagMapOtherPatients) #now the curent patient bags need to be to the instances of the training set similarityMatrixTest = getSimilarityMatrixTest(testBags, trainInstances, testLabels) #write these data to disk so that we can access it later on np.save(leaveOnePatientOutDir + '/' + 'similarityMatrixTrain_' + str(fold) + '_' + svType + '.npy', similarityMatrixTrain) np.save(leaveOnePatientOutDir + '/' + 'similarityMatrixTest_' + str(fold) + '_' + svType + '.npy', similarityMatrixTest) #also save the labels np.save(leaveOnePatientOutDir + '/' + 'bagLabelsTrain_' + str(fold) + '_' + svType + '.npy', trainLabels) np.save(leaveOnePatientOutDir + '/' + 'bagLabelsTest_' + str(fold) + '_' + svType + '.npy', testLabels) #and the test pair labels np.save(leaveOnePatientOutDir + '/' + 'bagPairLabelsTest_' + str(fold) + '_' + svType + '.npy', testPairLabels) else: #output the whole similarity matrix #similarityMatrix = getSimilarityMatrix(bags, instances, reverseBagMap) similarityMatrix = getSimilarityMatrix(bags, instances, reverseBagMap) print('similarity matrix sizes: ', similarityMatrix.shape) print('bag size: ', bags.shape) #output these to a file #write these data to disk so that we can access it later on np.save(finalOutDir + '/' + 'similarityMatrix_' + svType + '.npy', similarityMatrix)
en
0.863508
The goal of this script is to generate the similarity matrices for MIL The similarity matrices are pre-generated for the CV type that these will be used for. There is: - leave-one-chromosome-out CV - leave-one-patient-out CV - leave-bags-out CV - the similarity matrix on the whole dataset (used for feature importance) If we do feature elimination, we have similarity matrices for each feature output these as well. #make the similarity matrices for each left out patient #1 chromosome at a time in the test set #random bags in each CV fold #generate sim matrix for the whole dataset. #svTypes = ['ALL'] #input the normalized bags #get the information for the bag labels #labels function to get the similarity matrix. This is mainly used to make the sim matrix for the training set. To make the test set sim matrix, use the function below. bags (numpy array): all bags that we use for this matrix instances (numpy array): all instances in the bags reverseBagMap (dictionary): bag index as key, instance indices as values. Used to find out which instances are in which bag. #Get the indices of the instances that are in this bag #get the average of all instances in this bag #compute distance to all other instances from this bag average #sum the distances to get 1 similarity score function to get the similarity matrix specific for the test case. The instances that we map the distance to are the provided train instances. testBags (numpy array): all test bags that we use for this matrix trainInstances (numpy array): all instances in the bags of the training data, we compute distance to these instances from the test bags labels (list): obsolete. #print(similarityMatrix.shape) #print(labels[bagInd]) #get the average of all instances in this test patient bag #compute distance to all other instances from this bag average #sum the distances to get 1 similarity score #print(summedDistance) #Generate the similarity matrices for the SV types #for each SV-gene pair, get the instances #check if the SV type matches our selection #get the label of the bag by checking if it exists in degPairs, some pairs do not have a z-score because the gene is excluded due to mutations. #get the z-score of the pair. #if the z-score matches this criterion, the SV-gene pair is positive #go through the instances of this SV-gene pair, and include only those that have gains and losses, and more than 1 instance. This should in principle not happen, but good to keep a check. ###Here do an extra check: #to make fig2A, we only look at TADs with SVs across the boundary, so those z-scores are in the set. #BUT some of these genes are not actually affected by the SV, since this doesn't lead to #regulatory elements gained/lost. SO, we need to remove those here to get the actual pairs. #This only goes wrong for duplications, because we also keep CNV amps that could be the same event, #but then the duplication does not lead to gains/losses, while the CNV amp does because it is slightly #longer. So if there is evidence of a cnv AMP, but no non-coding duplication linked, we can remove #this as a positive pair. #if the z-score is anything else, this bag will be labeled negative. #get the right number of features per instance #fail-safe in case there are not enough SVs of this type #add the number of instances per bag as feature to the instances #remove instances with no variance #remove instances with 0 variance across all instances. These are not useful for the classifier. #subsample the positive bags if there are too many #subsample the positive set to the threshold #subsample negative to the same number of positives. #somehow the global setting doesn't work in the second loop? so set it here. #subsample the negative set to the same number of positives. #posInstances = np.vstack(positiveBags) #negInstances = np.vstack(negativeBagsSubsampled) #save the bag pair labels for later #merge the bags so that we can easily get to 1 similarity matrix and do all-to-all computations #assign bag labels #stack the instances in the bags so that we can easily compute bag-instance distances #also output the instances for later #and save the bags. #in case of leave-one-patient out, we subsample later on #save the bag pair labels for later #merge the bags so that we can easily get to 1 similarity matrix and do all-to-all computations #assign bag labels #stack the instances in the bags so that we can easily compute bag-instance distances #also output the instances for later #and save the bags. # if fullDataset == 'False': # bags = bagsSubsampled # instances = instancesSubsampled # bagPairLabels = bagPairLabelsSubsampled # bagLabels = bagLabelsSubsampled #Make an index where we can lookup at which position the instances are in the concatenated bag array. #lookup instance by bag index #lookup bag by instance index #save bagmap for later #if we do feature elimination, randomize the features here #set this to featureCount to run with all features. #if featureStart is not updated, this will run once #otherwise it will randomize a new feature each time #in case of feature elimination, we use the leave-one-chromosome-out CV setting #per chromosome, shuffle the features in the training set. #then output the original test set #so we have per SV type, per chromosome CV, X files for the number of features shuffled #make stratified #for bag in testNegativeBags: #testLabels[chromosome] = [1]*testPositiveBags.shape[0] + [0]*testNegativeBags.shape[0] #make training set from the rest #make stratified #for bag in chrNegativeBags: #trainingLabels += [0]*chrNegativeBags.shape[0] #shuffle the training instances #we compute the similarity matrix based on the instances #but the instance values need to be reset every iteration #lookup instance by bag index #now the curent patient bags need to be to the instances of the training set #output these to a file #write these data to disk so that we can access it later on #also save the labels ### leave-one-chromosome-out CV setting #if chromosome != 'chr16': # continue #make stratified #for bag in testNegativeBags: #make training set from the rest #make stratified #for bag in chrNegativeBags: #lookup instance by bag index #now the curent patient bags need to be to the instances of the training set #output these to a file #write these data to disk so that we can access it later on #also save the labels ### leave-bags-out CV setting #divide into X bags, regardless of patients #in each fold, randomly sample positive bags and negative bags of same size #set random bags to use for each fold #randomly sample x positive and negative bags #and labels #also get the pair labels #then the training set will be all other bags #get instances #this needs a bag map, which is changed each time we make subsets. #lookup instance by bag index #collect all this information as total bags/labels #now the curent patient bags need to be to the instances of the training set ### leave-one-patient-out CV setting #first, get the bags and labels per patient #get the label of this bag #get the label of this bag #for each patient, randomly subsample as many negative bags as there are positives #also get the labels #add the same number of positives/negatives #go through each patient, and divide into train/test #the training set will be a merge of the bags of all other patients. #then for each patient, get the train/test combination #add remaining patients #get instances #this needs a bag map, which is changed each time we make subsets. #lookup instance by bag index #collect all this information as total bags/labels #now the curent patient bags need to be to the instances of the training set #write these data to disk so that we can access it later on #also save the labels #and the test pair labels #output the whole similarity matrix #similarityMatrix = getSimilarityMatrix(bags, instances, reverseBagMap) #output these to a file #write these data to disk so that we can access it later on
3.027606
3
tests/unit/util/test_split_host_port.py
denssk/backup
69
6622409
import pytest from twindb_backup.util import split_host_port @pytest.mark.parametrize('pair, host, port', [ ( "10.20.31.1:3306", "10.20.31.1", 3306 ), ( "10.20.31.1", "10.20.31.1", None ), ( "10.20.31.1:", "10.20.31.1", None ), ( None, None, None ), ( "", None, None ) ]) def test_split_host_port(pair, host, port): assert split_host_port(pair) == (host, port)
import pytest from twindb_backup.util import split_host_port @pytest.mark.parametrize('pair, host, port', [ ( "10.20.31.1:3306", "10.20.31.1", 3306 ), ( "10.20.31.1", "10.20.31.1", None ), ( "10.20.31.1:", "10.20.31.1", None ), ( None, None, None ), ( "", None, None ) ]) def test_split_host_port(pair, host, port): assert split_host_port(pair) == (host, port)
none
1
2.758433
3
src/support/kernels/__init__.py
EuroPOND/deformetrica
1
6622410
from enum import Enum from support.kernels.abstract_kernel import AbstractKernel class Type(Enum): from support.kernels.torch_kernel import TorchKernel from support.kernels.keops_kernel import KeopsKernel from support.kernels.torch_cuda_kernel import TorchCudaKernel NO_KERNEL = None TORCH = TorchKernel KEOPS = KeopsKernel TORCH_CUDA = TorchCudaKernel def factory(kernel_type, *args, **kwargs): """Return an instance of a kernel corresponding to the requested kernel_type""" # turn enum string to enum object if isinstance(kernel_type, str): try: for c in [' ', '-']: # chars to be replaced for normalization kernel_type = kernel_type.replace(c, '_') kernel_type = Type[kernel_type.upper()] except: raise TypeError('kernel_type ' + kernel_type + ' could not be found') if not isinstance(kernel_type, Type): raise TypeError('kernel_type must be an instance of KernelType Enum') if kernel_type is Type.NO_KERNEL: return None return kernel_type.value(*args, **kwargs)
from enum import Enum from support.kernels.abstract_kernel import AbstractKernel class Type(Enum): from support.kernels.torch_kernel import TorchKernel from support.kernels.keops_kernel import KeopsKernel from support.kernels.torch_cuda_kernel import TorchCudaKernel NO_KERNEL = None TORCH = TorchKernel KEOPS = KeopsKernel TORCH_CUDA = TorchCudaKernel def factory(kernel_type, *args, **kwargs): """Return an instance of a kernel corresponding to the requested kernel_type""" # turn enum string to enum object if isinstance(kernel_type, str): try: for c in [' ', '-']: # chars to be replaced for normalization kernel_type = kernel_type.replace(c, '_') kernel_type = Type[kernel_type.upper()] except: raise TypeError('kernel_type ' + kernel_type + ' could not be found') if not isinstance(kernel_type, Type): raise TypeError('kernel_type must be an instance of KernelType Enum') if kernel_type is Type.NO_KERNEL: return None return kernel_type.value(*args, **kwargs)
en
0.614609
Return an instance of a kernel corresponding to the requested kernel_type # turn enum string to enum object # chars to be replaced for normalization
2.948452
3
cst/kostrov.py
gely/coseis
7
6622411
<filename>cst/kostrov.py """ Kostrov circular expanding crack analytical solution. """ import numpy def cee_integrand(x, a2, b2): return ( ((x + 0.5 * b2) ** 2.0 - x * numpy.sqrt((x + b2) * (x + a2))) / ((x + 1.0) * (x + 1.0) * numpy.sqrt(x + b2)) ) def cee_integral(a2, b2): import scipy.integrate x = scipy.integrate.quad(cee_integrand, 0.0, float('inf'), args=(a2, b2)) return x[0] def cee(a, b): """ a: Ratio of rupture to P-wave velocity, vrup/vp. b: Ratio of rupture to S-wave velocity, vrup/vs. """ a2 = a * a b2 = b * b f = numpy.vectorize(cee_integral) d = f(a2, b2) + 0.25 * b2 * (b + numpy.arccos(b) / numpy.sqrt(1.0 - b2)) return b * b2 / d def slip_rate(rho, vp, vs, vrup, dtau, r, t, C=None): """ rho: density vp: P-wave speed vs: S-wave speed vrup: rupture velocity dtau: stress drop r: hypocenter distance t: array of reduced-time samples (t=0 is rupture arrival time). C: optional C parameter from Dahlen (1974) Eqn (44). If not supplied, C is computed from vrup, vp and vs. """ t0 = r / vrup if C is None: C = cee(vrup / vp, vrup / vs) v = C * dtau / (rho * vs) * (t + t0) / numpy.sqrt(t * (t + 2.0 * t0)) return v
<filename>cst/kostrov.py """ Kostrov circular expanding crack analytical solution. """ import numpy def cee_integrand(x, a2, b2): return ( ((x + 0.5 * b2) ** 2.0 - x * numpy.sqrt((x + b2) * (x + a2))) / ((x + 1.0) * (x + 1.0) * numpy.sqrt(x + b2)) ) def cee_integral(a2, b2): import scipy.integrate x = scipy.integrate.quad(cee_integrand, 0.0, float('inf'), args=(a2, b2)) return x[0] def cee(a, b): """ a: Ratio of rupture to P-wave velocity, vrup/vp. b: Ratio of rupture to S-wave velocity, vrup/vs. """ a2 = a * a b2 = b * b f = numpy.vectorize(cee_integral) d = f(a2, b2) + 0.25 * b2 * (b + numpy.arccos(b) / numpy.sqrt(1.0 - b2)) return b * b2 / d def slip_rate(rho, vp, vs, vrup, dtau, r, t, C=None): """ rho: density vp: P-wave speed vs: S-wave speed vrup: rupture velocity dtau: stress drop r: hypocenter distance t: array of reduced-time samples (t=0 is rupture arrival time). C: optional C parameter from Dahlen (1974) Eqn (44). If not supplied, C is computed from vrup, vp and vs. """ t0 = r / vrup if C is None: C = cee(vrup / vp, vrup / vs) v = C * dtau / (rho * vs) * (t + t0) / numpy.sqrt(t * (t + 2.0 * t0)) return v
en
0.691787
Kostrov circular expanding crack analytical solution. a: Ratio of rupture to P-wave velocity, vrup/vp. b: Ratio of rupture to S-wave velocity, vrup/vs. rho: density vp: P-wave speed vs: S-wave speed vrup: rupture velocity dtau: stress drop r: hypocenter distance t: array of reduced-time samples (t=0 is rupture arrival time). C: optional C parameter from Dahlen (1974) Eqn (44). If not supplied, C is computed from vrup, vp and vs.
2.621117
3
appconfig/tasks/letsencrypt.py
Bibiko/appconfig
0
6622412
<filename>appconfig/tasks/letsencrypt.py from fabric.api import sudo from fabtools import require from appconfig import APPS from appconfig.config import App from appconfig import util from fabtools.system import distrib_codename def require_certbot(): require.deb.package('software-properties-common') util.ppa('ppa:certbot/certbot', lsb_codename=distrib_codename()) require.deb.package('python-certbot-nginx') def require_cert(domain): if isinstance(domain, App): domains = domain.domain if domain.with_www_subdomain: domains += ',www.{0}'.format(domain.domain) else: domains = domain # If an App instance is passed, we lookup its domain attribute: sudo('certbot --nginx -n -d {0} certonly --agree-tos --expand --email {1}'.format( domains, APPS.defaults['error_email'])) def delete(cert): sudo('certbot delete --cert-name {0}'.format(cert)) def renew(): sudo('certbot --nginx -n renew')
<filename>appconfig/tasks/letsencrypt.py from fabric.api import sudo from fabtools import require from appconfig import APPS from appconfig.config import App from appconfig import util from fabtools.system import distrib_codename def require_certbot(): require.deb.package('software-properties-common') util.ppa('ppa:certbot/certbot', lsb_codename=distrib_codename()) require.deb.package('python-certbot-nginx') def require_cert(domain): if isinstance(domain, App): domains = domain.domain if domain.with_www_subdomain: domains += ',www.{0}'.format(domain.domain) else: domains = domain # If an App instance is passed, we lookup its domain attribute: sudo('certbot --nginx -n -d {0} certonly --agree-tos --expand --email {1}'.format( domains, APPS.defaults['error_email'])) def delete(cert): sudo('certbot delete --cert-name {0}'.format(cert)) def renew(): sudo('certbot --nginx -n renew')
en
0.824112
# If an App instance is passed, we lookup its domain attribute:
2.06899
2
sklearn/plot_classification.py
aidiary/PRML
93
6622413
#coding:utf-8 import numpy as np import pylab as pl from matplotlib.colors import ListedColormap from sklearn import neighbors, datasets """k-NNのカラーマップ表示""" n_neighbors = 15 # irisデータをインポート iris = datasets.load_iris() X = iris.data[:, :2] y = iris.target # メッシュのステップサイズ h = 0.02 # カラーマップ cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF']) cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF']) for weights in ['uniform', 'distance']: # 分類器を学習 clf = neighbors.KNeighborsClassifier(n_neighbors, weights=weights) clf.fit(X, y) # データより少し広くなるように描画範囲を決定 x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 # 範囲をメッシュに区切ってその座標での分類結果Zを求める xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) # 分類結果を元に色を割り当てて描画 pl.figure() pl.pcolormesh(xx, yy, Z, cmap=cmap_light) # 訓練データをプロット pl.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold) pl.xlim(xx.min(), xx.max()) pl.ylim(yy.min(), yy.max()) pl.title("3-Class classification (k = %i, weights = '%s')" % (n_neighbors, weights)) pl.show()
#coding:utf-8 import numpy as np import pylab as pl from matplotlib.colors import ListedColormap from sklearn import neighbors, datasets """k-NNのカラーマップ表示""" n_neighbors = 15 # irisデータをインポート iris = datasets.load_iris() X = iris.data[:, :2] y = iris.target # メッシュのステップサイズ h = 0.02 # カラーマップ cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF']) cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF']) for weights in ['uniform', 'distance']: # 分類器を学習 clf = neighbors.KNeighborsClassifier(n_neighbors, weights=weights) clf.fit(X, y) # データより少し広くなるように描画範囲を決定 x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 # 範囲をメッシュに区切ってその座標での分類結果Zを求める xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) # 分類結果を元に色を割り当てて描画 pl.figure() pl.pcolormesh(xx, yy, Z, cmap=cmap_light) # 訓練データをプロット pl.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold) pl.xlim(xx.min(), xx.max()) pl.ylim(yy.min(), yy.max()) pl.title("3-Class classification (k = %i, weights = '%s')" % (n_neighbors, weights)) pl.show()
ja
0.999809
#coding:utf-8 k-NNのカラーマップ表示 # irisデータをインポート # メッシュのステップサイズ # カラーマップ # 分類器を学習 # データより少し広くなるように描画範囲を決定 # 範囲をメッシュに区切ってその座標での分類結果Zを求める # 分類結果を元に色を割り当てて描画 # 訓練データをプロット
2.711535
3
app/views/setupview.py
nandakoryaaa/pypy
0
6622414
<gh_stars>0 from app.views.logoview import LogoView from app.views.menuview import MenuView class SetupView(LogoView): def __init__(self, graphics, model): super().__init__(graphics, model) self.level_num = 0 self.apple_count = 0 self.menu_view = MenuView(graphics, model) self.x = self.center_axis(0, self.width, self.menu_view.width) fp = graphics.get_font_params('green_light') offset_y = fp.get_lines_height(2) self.y = self.center_axis( self.logo_height, self.height, self.menu_view.height + offset_y ) self.menu_view.set_pos(self.x, self.y + offset_y) def render(self): super().render() g = self.graphics g.set_font('white') str_title = 'SETUP' str_title_width = g.font_params.get_str_width(str_title) str_title_x = self.center_axis(0, self.width, str_title_width) self.graphics.draw_text(str_title, str_title_x, self.y) self.menu_view.render()
from app.views.logoview import LogoView from app.views.menuview import MenuView class SetupView(LogoView): def __init__(self, graphics, model): super().__init__(graphics, model) self.level_num = 0 self.apple_count = 0 self.menu_view = MenuView(graphics, model) self.x = self.center_axis(0, self.width, self.menu_view.width) fp = graphics.get_font_params('green_light') offset_y = fp.get_lines_height(2) self.y = self.center_axis( self.logo_height, self.height, self.menu_view.height + offset_y ) self.menu_view.set_pos(self.x, self.y + offset_y) def render(self): super().render() g = self.graphics g.set_font('white') str_title = 'SETUP' str_title_width = g.font_params.get_str_width(str_title) str_title_x = self.center_axis(0, self.width, str_title_width) self.graphics.draw_text(str_title, str_title_x, self.y) self.menu_view.render()
none
1
2.461587
2
reptile/train.py
mkhodak/ARUBA
7
6622415
import json import os; os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import pdb import pickle import random import sys from glob import glob from operator import itemgetter import tensorflow as tf try: tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) except AttributeError: tf.logging.set_verbosity(tf.logging.ERROR) from supervised_reptile.args import argument_parser, evaluate_kwargs, model_kwargs, train_kwargs from supervised_reptile.eval import evaluate from supervised_reptile.models import MiniImageNetModel, OmniglotModel from supervised_reptile.miniimagenet import read_dataset as mini_dataset from supervised_reptile.omniglot import read_dataset, split_dataset, augment_dataset from supervised_reptile.train import train DATA_DIR = {'omniglot': 'data/omniglot', 'miniimagenet': 'data/miniimagenet'} def main(): parser = argument_parser() parser.add_argument('--dataset', help='which dataset to use', default='omniglot', type=str) parser.add_argument('--trials', help='number of seeds', default=3, type=int) parser.add_argument('--val-samples', help='number of validation samples', default=100, type=int) parser.add_argument('--restore', help='restore from final training checkpoint', action='store_true') args = parser.parse_args() os.makedirs(args.checkpoint, exist_ok=True) with open(os.path.join(args.checkpoint, 'args.json'), 'w') as f: json.dump(vars(args), f, indent=4) random.seed(args.seed) if args.dataset == 'omniglot': train_set, test_set = split_dataset(read_dataset(DATA_DIR[args.dataset])) trainval_set = list(augment_dataset(train_set)) val_set = list(train_set[-200:]) train_set = list(augment_dataset(train_set[:-200])) test_set = list(test_set) else: train_set, val_set, test_set = mini_dataset(DATA_DIR[args.dataset]) trainval_set = train_set print('Training...') modes = ['train', 'test'] metrics = ['acc', 'loss'] try: with open(os.path.join(args.checkpoint, 'results.pkl'), 'rb') as f: results = pickle.load(f) except FileNotFoundError: results = {'regular': {mode: {metric: {} for metric in metrics} for mode in modes}, 'trials': set()} if args.transductive: results['transductive'] = {mode: {metric: {} for metric in metrics} for mode in modes} if args.adaptive: results['adaptive'] = {mode: {metric: {} for metric in metrics} for mode in modes} if args.transductive: results['adaptive_transductive'] = {mode: {metric: {} for metric in metrics} for mode in modes} for j in range(args.trials): if j in results['trials']: print('skipping trial', j) continue tf.reset_default_graph() model = OmniglotModel(args.classes, **model_kwargs(args)) if args.dataset == 'omniglot' else MiniImageNetModel(args.classes, **model_kwargs(args)) with tf.Session() as sess: checkpoint = os.path.join(args.checkpoint, 'final'+str(j)) if args.restore: print('Trial', j, 'Restoring...') tf.train.Saver().restore(sess, tf.train.latest_checkpoint(checkpoint)) args.restore = False else: os.makedirs(checkpoint, exist_ok=True) print('Trial', j, 'Training...') train(sess, model, trainval_set, test_set, checkpoint, **train_kwargs(args)) print('Trial', j, 'Evaluating...') for ev in results.keys(): if ev == 'trials': continue evkw = evaluate_kwargs(args) evkw['transductive'] = 'transductive' in ev evkw['adaptive'] = args.adaptive if 'adaptive' in ev else 0.0 for mode, dset in zip(modes, [trainval_set, test_set]): results[ev][mode]['acc'][j], results[ev][mode]['loss'][j] = evaluate(sess, model, dset, **evkw) results['trials'].add(j) with open(os.path.join(args.checkpoint, 'results.pkl'), 'wb') as f: pickle.dump(results, f) with open(os.path.join(args.checkpoint, 'results.json'), 'w') as f: tr = results.pop('trials') json.dump(results, f, indent=4) results['trials'] = tr print('Train Acc:', sum(results['regular']['train']['acc'].values())/args.trials) print('Test Acc:', sum(results['regular']['test']['acc'].values())/args.trials) if args.transductive: print('Transductive Train Acc:', sum(results['transductive']['train']['acc'].values())/args.trials) print('Transductive Test Acc:', sum(results['transductive']['test']['acc'].values())/args.trials) if args.adaptive: print('Adaptive Train Acc:', sum(results['adaptive']['train']['acc'].values())/args.trials) print('Adaptive Test Acc:', sum(results['adaptive']['test']['acc'].values())/args.trials) if args.transductive: print('Adaptive Transductive Train Acc:', sum(results['adaptive_transductive']['train']['acc'].values())/args.trials) print('Adaptive Transductive Test Acc:', sum(results['adaptive_transductive']['test']['acc'].values())/args.trials) if __name__ == '__main__': main()
import json import os; os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import pdb import pickle import random import sys from glob import glob from operator import itemgetter import tensorflow as tf try: tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) except AttributeError: tf.logging.set_verbosity(tf.logging.ERROR) from supervised_reptile.args import argument_parser, evaluate_kwargs, model_kwargs, train_kwargs from supervised_reptile.eval import evaluate from supervised_reptile.models import MiniImageNetModel, OmniglotModel from supervised_reptile.miniimagenet import read_dataset as mini_dataset from supervised_reptile.omniglot import read_dataset, split_dataset, augment_dataset from supervised_reptile.train import train DATA_DIR = {'omniglot': 'data/omniglot', 'miniimagenet': 'data/miniimagenet'} def main(): parser = argument_parser() parser.add_argument('--dataset', help='which dataset to use', default='omniglot', type=str) parser.add_argument('--trials', help='number of seeds', default=3, type=int) parser.add_argument('--val-samples', help='number of validation samples', default=100, type=int) parser.add_argument('--restore', help='restore from final training checkpoint', action='store_true') args = parser.parse_args() os.makedirs(args.checkpoint, exist_ok=True) with open(os.path.join(args.checkpoint, 'args.json'), 'w') as f: json.dump(vars(args), f, indent=4) random.seed(args.seed) if args.dataset == 'omniglot': train_set, test_set = split_dataset(read_dataset(DATA_DIR[args.dataset])) trainval_set = list(augment_dataset(train_set)) val_set = list(train_set[-200:]) train_set = list(augment_dataset(train_set[:-200])) test_set = list(test_set) else: train_set, val_set, test_set = mini_dataset(DATA_DIR[args.dataset]) trainval_set = train_set print('Training...') modes = ['train', 'test'] metrics = ['acc', 'loss'] try: with open(os.path.join(args.checkpoint, 'results.pkl'), 'rb') as f: results = pickle.load(f) except FileNotFoundError: results = {'regular': {mode: {metric: {} for metric in metrics} for mode in modes}, 'trials': set()} if args.transductive: results['transductive'] = {mode: {metric: {} for metric in metrics} for mode in modes} if args.adaptive: results['adaptive'] = {mode: {metric: {} for metric in metrics} for mode in modes} if args.transductive: results['adaptive_transductive'] = {mode: {metric: {} for metric in metrics} for mode in modes} for j in range(args.trials): if j in results['trials']: print('skipping trial', j) continue tf.reset_default_graph() model = OmniglotModel(args.classes, **model_kwargs(args)) if args.dataset == 'omniglot' else MiniImageNetModel(args.classes, **model_kwargs(args)) with tf.Session() as sess: checkpoint = os.path.join(args.checkpoint, 'final'+str(j)) if args.restore: print('Trial', j, 'Restoring...') tf.train.Saver().restore(sess, tf.train.latest_checkpoint(checkpoint)) args.restore = False else: os.makedirs(checkpoint, exist_ok=True) print('Trial', j, 'Training...') train(sess, model, trainval_set, test_set, checkpoint, **train_kwargs(args)) print('Trial', j, 'Evaluating...') for ev in results.keys(): if ev == 'trials': continue evkw = evaluate_kwargs(args) evkw['transductive'] = 'transductive' in ev evkw['adaptive'] = args.adaptive if 'adaptive' in ev else 0.0 for mode, dset in zip(modes, [trainval_set, test_set]): results[ev][mode]['acc'][j], results[ev][mode]['loss'][j] = evaluate(sess, model, dset, **evkw) results['trials'].add(j) with open(os.path.join(args.checkpoint, 'results.pkl'), 'wb') as f: pickle.dump(results, f) with open(os.path.join(args.checkpoint, 'results.json'), 'w') as f: tr = results.pop('trials') json.dump(results, f, indent=4) results['trials'] = tr print('Train Acc:', sum(results['regular']['train']['acc'].values())/args.trials) print('Test Acc:', sum(results['regular']['test']['acc'].values())/args.trials) if args.transductive: print('Transductive Train Acc:', sum(results['transductive']['train']['acc'].values())/args.trials) print('Transductive Test Acc:', sum(results['transductive']['test']['acc'].values())/args.trials) if args.adaptive: print('Adaptive Train Acc:', sum(results['adaptive']['train']['acc'].values())/args.trials) print('Adaptive Test Acc:', sum(results['adaptive']['test']['acc'].values())/args.trials) if args.transductive: print('Adaptive Transductive Train Acc:', sum(results['adaptive_transductive']['train']['acc'].values())/args.trials) print('Adaptive Transductive Test Acc:', sum(results['adaptive_transductive']['test']['acc'].values())/args.trials) if __name__ == '__main__': main()
none
1
2.157921
2
config/appdaemon/apps/light_with_motion_and_hue_switch.py
azogue/hassio_config
18
6622416
<reponame>azogue/hassio_config # -*- coding: utf-8 -*- """ Appdaemon app for motion + switch control of light in a room. """ from time import monotonic from typing import Any, Dict, Optional, Tuple import appdaemon.plugins.hass.hassapi as hass LOGGER = "motion_log" EVENT_LOG_LEVEL = "DEBUG" RWL_BUTTONS = { 1000: "1_click", 2000: "2_click", 3000: "3_click", 4000: "4_click", 1001: "1_hold", 2001: "2_hold", 3001: "3_hold", 4001: "4_hold", 1002: "1_click_up", 2002: "2_click_up", 3002: "3_click_up", 4002: "4_click_up", 1003: "1_hold_up", 2003: "2_hold_up", 3003: "3_hold_up", 4003: "4_hold_up", } # noinspection PyClassHasNoInit class HueSwitchAndMotionControl(hass.Hass): """ App to automate lights in a room with: - One or more motion sensors - A Hue Dimmer Switch for manual control, with priority over automatic. """ _main_constrain: str _light_group: str _scene_rotation: Dict[str, int] _default_scene: str _scenes: Dict[str, Tuple[Dict[str, Any], int]] = {} _time_windows: Dict[str, Tuple[str, str]] _delay_re_enable_motion_control: int _max_delay_motion_off: int _light_on: bool _motion_on: bool _motion_light_enabled: bool _last_switch_press: float _last_light_on: float _last_scene: str _motion_states: Dict[str, Any] _handler_turn_off_lights = None _handler_light_enabler = None def initialize(self): """Set up appdaemon app.""" remote_event = self.args.get("remote_event", "deconz_event") remote_event_filter = self.args.get("remote_event_filter", {}) motion_sensors = self.args.get("motion_sensors", []) self._light_group = self.args.get("light_group", "light.cocina") self._main_constrain = self.args.get("toggle_automation") self._delay_re_enable_motion_control = int( self.args.get("delay_re_enable_motion_control", 120) ) self._max_delay_motion_off = int( self.args.get("max_delay_motion_off", 900) ) self._scene_rotation = { scene_key: i for i, scene_key in enumerate(self.args.get("rotate_scene_order")) } _schedule_config = self.args.get("scene_schedule") self.log( f"[DEBUG] APP INIT with schedule_config {_schedule_config}", level="WARNING", log=LOGGER, ) self._default_scene = self.args.get("default_scene") self._scenes = {} self._time_windows = {} for scene_key, scene_data in self.args.get("scene_schedule").items(): self._time_windows[scene_key] = ( scene_data.get("from", "00:00:00"), scene_data.get("to", "00:00:00"), ) self._scenes[scene_key] = ( scene_data["turn_on_service_call"], scene_data["wait_to_turn_off"], ) light_st = self.get_state(self._light_group) self._light_on = light_st == "on" self._last_switch_press = 0.0 self._last_scene = self._default_scene self._motion_states = {} for sensor in motion_sensors: self._motion_states[sensor] = self.get_state(sensor) == "on" self.listen_state( self._motion_detected, sensor, constrain_input_boolean=self._main_constrain, ) self._motion_on = any(self._motion_states.values()) self._last_light_on = 0.0 if not self._motion_on else monotonic() self._motion_light_enabled = True self.listen_state(self._light_changed, self._light_group) self.listen_event( self._switch_event, remote_event, **remote_event_filter ) # Add listener to check light off after a long time self.listen_state( self._no_motion_for_long_time, motion_sensors[0], new="off", duration=self._max_delay_motion_off, # constrain_input_boolean=self._main_constrain, ) self.log( f"APP INIT with light {light_st}, motion: {self._motion_states}", level="WARNING", log=LOGGER, ) def _turn_lights_off(self, *_args, **kwargs): transition = kwargs.get("transition", 1) self.call_service( "light/turn_off", entity_id=self._light_group, transition=transition ) self._light_on = False if self._handler_turn_off_lights is not None: self.cancel_timer(self._handler_turn_off_lights) self._handler_turn_off_lights = None # Log off operation with ∆T on delta_on = monotonic() - self._last_light_on if "manual" in kwargs: self.log( f"MANUAL OFF (delta_T={delta_on / 60:.1f} min) ---", log=LOGGER ) else: self.log( f"AUTO OFF (delta_T={delta_on / 60:.1f} min) -----", level="WARNING", log=LOGGER, ) def _select_scene(self): scene_key = None for scene_key, (from_str, to_str) in self._time_windows.items(): if self.now_is_between(from_str, to_str): return scene_key return scene_key def _get_current_delay(self): return self._scenes[self._select_scene()][1] def _max_switch_delay(self): return 5 * self._get_current_delay() def _turn_lights_on(self, origin: str, scene_key: Optional[str] = None): level = "INFO" if scene_key is None: level = "WARNING" scene_key = self._select_scene() turn_on_data = self._scenes[scene_key][0] self.call_service( turn_on_data["service"], **turn_on_data["service_data"] ) self._light_on = True self._last_light_on = monotonic() self.log( f"ENCIENDE LUCES [{scene_key}] from {origin}", level=level, log=LOGGER, ) # Store scene to enable looping self._last_scene = scene_key def _reset_inactivity_timer(self, new_wait: Optional[int] = None): if self._handler_turn_off_lights is not None: self.cancel_timer(self._handler_turn_off_lights) self._handler_turn_off_lights = None if new_wait is None: self.log( f"Reset wait counter from switch", level=EVENT_LOG_LEVEL, log=LOGGER, ) if new_wait is not None: self.log( f"Set timer of {new_wait} s from deactivated switch", level=EVENT_LOG_LEVEL, log=LOGGER, ) self._handler_turn_off_lights = self.run_in( self._turn_lights_off, new_wait ) def _enable_motion_lights(self, *_args, **_kwargs): self._reset_light_enabler() self._motion_light_enabled = True self.log(f"Enabled motion lights after manual usage", log=LOGGER) def _reset_light_enabler(self, new_wait: Optional[int] = None): if self._handler_light_enabler is not None: self.cancel_timer(self._handler_light_enabler) self._handler_light_enabler = None if new_wait is not None: self._handler_light_enabler = self.run_in( self._enable_motion_lights, new_wait ) self.log( f"Re-enable light control in {new_wait} s", level=EVENT_LOG_LEVEL, log=LOGGER, ) def _light_changed(self, _entity, _attribute, old, new, _kwargs): """ Listener to changes on light, to catch external ones, not only manual usages of hue dimmer switch. """ is_on = new == "on" is_off = new == "off" if is_on and old == "off": if not self._light_on: self.log( "UNSYNCED ON LIGHT (stored as off)", level="WARNING", log=LOGGER, ) self._last_light_on = monotonic() self._light_on = True elif is_off and old == "on": if self._light_on: self.log( "UNSYNCED OFF LIGHT (stored as on)", level="ERROR", log=LOGGER, ) self._light_on = False elif not is_on and not is_off: self.log( f"Unavailable LIGHT? {new} (stored as {old})", log=LOGGER, ) else: self._light_on = is_on def _switch_event(self, _event, event_data, *_args, **_kwargs): """ Listener to manual press on Hue dimmer switch (for manual usage) Usually 2 events are received: 'X_click' and 'X_click_up', When ON/OFF buttons are used, motion lights are disabled for some time. """ new = RWL_BUTTONS[event_data["event"]] if new.endswith("_up"): # Ignore button release return ts_now = monotonic() delta = ts_now - self._last_switch_press self._last_switch_press = ts_now self.log( f"MANUAL SWITCH -> {new} (delta_T={delta:.2f}s)", level=EVENT_LOG_LEVEL, log=LOGGER, ) if new == "1_click": # Turn on, no motion control for some time if self._motion_light_enabled: self._motion_light_enabled = False self._motion_on = False self._reset_light_enabler(self._max_switch_delay()) self._reset_inactivity_timer() # Turn on light with "default_scene" self._turn_lights_on("switch", self._default_scene) elif new == "2_click": # Turn on, no motion control for some time if self._motion_light_enabled: self._motion_light_enabled = False self._motion_on = False self._reset_light_enabler(self._max_switch_delay()) self._reset_inactivity_timer() # Rotate through scenes idx = ( self._scene_rotation[self._last_scene] + 1 ) % len(self._scene_rotation) next_scene = next( filter(lambda x: x[1] == idx, self._scene_rotation.items()) )[0] self._turn_lights_on("switch_loop", next_scene) elif new == "3_hold": # Turn off, but enable motion control self._turn_lights_off(manual=True, transition=0) self._enable_motion_lights() elif new == "4_click": # Turn off, no motion control for some time if self._motion_light_enabled: self._motion_light_enabled = False self._motion_on = False self._reset_light_enabler(self._delay_re_enable_motion_control) self._reset_inactivity_timer() # Turn off light self._turn_lights_off(manual=True, transition=2) def _motion_detected(self, entity, _attribute, old, new, _kwargs): """ Listener to motion sensor changes. * New activated motion sensor turns on lights, if motion lights enabled * Each activated motion sensor resets the wait timer, if previously set * Last deactivated sensor sets a new wait timer to turn off lights. """ if new is None: self.log( f"Motion sensor disappeared: {entity} -> from {old} to {new}", level="WARNING", log=LOGGER, ) return activated = new == "on" if not self._motion_light_enabled: if activated and self._light_on: # reset wait for enable automatic control (4x mult) self._reset_light_enabler(4 * self._get_current_delay()) return self.log( f"Event: {entity:<25} -> {new:<3} (was {old})", level=EVENT_LOG_LEVEL, log=LOGGER, ) self._motion_states[entity] = activated any_active = any(self._motion_states.values()) if not self._motion_on and activated: # turn lights on (1st time) self._motion_on = True self._reset_inactivity_timer() if not self._light_on: self._turn_lights_on(entity) elif self._motion_on and not activated and not any_active: self._motion_on = False # wait some time before turning lights off self._reset_inactivity_timer( new_wait=self._get_current_delay() ) else: self._motion_on = any_active if activated: self._reset_inactivity_timer() def _no_motion_for_long_time(self, *_args, **_kwargs): """Listener to main motion sensor being off a long time.""" light_st = self.get_state(self._light_group) self._light_on = light_st == "on" if not self._light_on: return now = monotonic() self.log( f"NO MOTION FOR A LONG TIME (since {self._last_light_on:.0f} s)-> " f"{self._motion_states} / {self._motion_on}. " f"Handler off={self._handler_turn_off_lights}", log=LOGGER, ) if ( (now - self._last_light_on > self._max_delay_motion_off - 1) and (now - self._last_switch_press > self._max_switch_delay()) ) or ( self._handler_turn_off_lights is None ): # Safety turn off self.log( f"TURN OFF LIGHTS AFTER NO MOTION FOR A LONG TIME", level="ERROR", log=LOGGER, ) self._turn_lights_off()
# -*- coding: utf-8 -*- """ Appdaemon app for motion + switch control of light in a room. """ from time import monotonic from typing import Any, Dict, Optional, Tuple import appdaemon.plugins.hass.hassapi as hass LOGGER = "motion_log" EVENT_LOG_LEVEL = "DEBUG" RWL_BUTTONS = { 1000: "1_click", 2000: "2_click", 3000: "3_click", 4000: "4_click", 1001: "1_hold", 2001: "2_hold", 3001: "3_hold", 4001: "4_hold", 1002: "1_click_up", 2002: "2_click_up", 3002: "3_click_up", 4002: "4_click_up", 1003: "1_hold_up", 2003: "2_hold_up", 3003: "3_hold_up", 4003: "4_hold_up", } # noinspection PyClassHasNoInit class HueSwitchAndMotionControl(hass.Hass): """ App to automate lights in a room with: - One or more motion sensors - A Hue Dimmer Switch for manual control, with priority over automatic. """ _main_constrain: str _light_group: str _scene_rotation: Dict[str, int] _default_scene: str _scenes: Dict[str, Tuple[Dict[str, Any], int]] = {} _time_windows: Dict[str, Tuple[str, str]] _delay_re_enable_motion_control: int _max_delay_motion_off: int _light_on: bool _motion_on: bool _motion_light_enabled: bool _last_switch_press: float _last_light_on: float _last_scene: str _motion_states: Dict[str, Any] _handler_turn_off_lights = None _handler_light_enabler = None def initialize(self): """Set up appdaemon app.""" remote_event = self.args.get("remote_event", "deconz_event") remote_event_filter = self.args.get("remote_event_filter", {}) motion_sensors = self.args.get("motion_sensors", []) self._light_group = self.args.get("light_group", "light.cocina") self._main_constrain = self.args.get("toggle_automation") self._delay_re_enable_motion_control = int( self.args.get("delay_re_enable_motion_control", 120) ) self._max_delay_motion_off = int( self.args.get("max_delay_motion_off", 900) ) self._scene_rotation = { scene_key: i for i, scene_key in enumerate(self.args.get("rotate_scene_order")) } _schedule_config = self.args.get("scene_schedule") self.log( f"[DEBUG] APP INIT with schedule_config {_schedule_config}", level="WARNING", log=LOGGER, ) self._default_scene = self.args.get("default_scene") self._scenes = {} self._time_windows = {} for scene_key, scene_data in self.args.get("scene_schedule").items(): self._time_windows[scene_key] = ( scene_data.get("from", "00:00:00"), scene_data.get("to", "00:00:00"), ) self._scenes[scene_key] = ( scene_data["turn_on_service_call"], scene_data["wait_to_turn_off"], ) light_st = self.get_state(self._light_group) self._light_on = light_st == "on" self._last_switch_press = 0.0 self._last_scene = self._default_scene self._motion_states = {} for sensor in motion_sensors: self._motion_states[sensor] = self.get_state(sensor) == "on" self.listen_state( self._motion_detected, sensor, constrain_input_boolean=self._main_constrain, ) self._motion_on = any(self._motion_states.values()) self._last_light_on = 0.0 if not self._motion_on else monotonic() self._motion_light_enabled = True self.listen_state(self._light_changed, self._light_group) self.listen_event( self._switch_event, remote_event, **remote_event_filter ) # Add listener to check light off after a long time self.listen_state( self._no_motion_for_long_time, motion_sensors[0], new="off", duration=self._max_delay_motion_off, # constrain_input_boolean=self._main_constrain, ) self.log( f"APP INIT with light {light_st}, motion: {self._motion_states}", level="WARNING", log=LOGGER, ) def _turn_lights_off(self, *_args, **kwargs): transition = kwargs.get("transition", 1) self.call_service( "light/turn_off", entity_id=self._light_group, transition=transition ) self._light_on = False if self._handler_turn_off_lights is not None: self.cancel_timer(self._handler_turn_off_lights) self._handler_turn_off_lights = None # Log off operation with ∆T on delta_on = monotonic() - self._last_light_on if "manual" in kwargs: self.log( f"MANUAL OFF (delta_T={delta_on / 60:.1f} min) ---", log=LOGGER ) else: self.log( f"AUTO OFF (delta_T={delta_on / 60:.1f} min) -----", level="WARNING", log=LOGGER, ) def _select_scene(self): scene_key = None for scene_key, (from_str, to_str) in self._time_windows.items(): if self.now_is_between(from_str, to_str): return scene_key return scene_key def _get_current_delay(self): return self._scenes[self._select_scene()][1] def _max_switch_delay(self): return 5 * self._get_current_delay() def _turn_lights_on(self, origin: str, scene_key: Optional[str] = None): level = "INFO" if scene_key is None: level = "WARNING" scene_key = self._select_scene() turn_on_data = self._scenes[scene_key][0] self.call_service( turn_on_data["service"], **turn_on_data["service_data"] ) self._light_on = True self._last_light_on = monotonic() self.log( f"ENCIENDE LUCES [{scene_key}] from {origin}", level=level, log=LOGGER, ) # Store scene to enable looping self._last_scene = scene_key def _reset_inactivity_timer(self, new_wait: Optional[int] = None): if self._handler_turn_off_lights is not None: self.cancel_timer(self._handler_turn_off_lights) self._handler_turn_off_lights = None if new_wait is None: self.log( f"Reset wait counter from switch", level=EVENT_LOG_LEVEL, log=LOGGER, ) if new_wait is not None: self.log( f"Set timer of {new_wait} s from deactivated switch", level=EVENT_LOG_LEVEL, log=LOGGER, ) self._handler_turn_off_lights = self.run_in( self._turn_lights_off, new_wait ) def _enable_motion_lights(self, *_args, **_kwargs): self._reset_light_enabler() self._motion_light_enabled = True self.log(f"Enabled motion lights after manual usage", log=LOGGER) def _reset_light_enabler(self, new_wait: Optional[int] = None): if self._handler_light_enabler is not None: self.cancel_timer(self._handler_light_enabler) self._handler_light_enabler = None if new_wait is not None: self._handler_light_enabler = self.run_in( self._enable_motion_lights, new_wait ) self.log( f"Re-enable light control in {new_wait} s", level=EVENT_LOG_LEVEL, log=LOGGER, ) def _light_changed(self, _entity, _attribute, old, new, _kwargs): """ Listener to changes on light, to catch external ones, not only manual usages of hue dimmer switch. """ is_on = new == "on" is_off = new == "off" if is_on and old == "off": if not self._light_on: self.log( "UNSYNCED ON LIGHT (stored as off)", level="WARNING", log=LOGGER, ) self._last_light_on = monotonic() self._light_on = True elif is_off and old == "on": if self._light_on: self.log( "UNSYNCED OFF LIGHT (stored as on)", level="ERROR", log=LOGGER, ) self._light_on = False elif not is_on and not is_off: self.log( f"Unavailable LIGHT? {new} (stored as {old})", log=LOGGER, ) else: self._light_on = is_on def _switch_event(self, _event, event_data, *_args, **_kwargs): """ Listener to manual press on Hue dimmer switch (for manual usage) Usually 2 events are received: 'X_click' and 'X_click_up', When ON/OFF buttons are used, motion lights are disabled for some time. """ new = RWL_BUTTONS[event_data["event"]] if new.endswith("_up"): # Ignore button release return ts_now = monotonic() delta = ts_now - self._last_switch_press self._last_switch_press = ts_now self.log( f"MANUAL SWITCH -> {new} (delta_T={delta:.2f}s)", level=EVENT_LOG_LEVEL, log=LOGGER, ) if new == "1_click": # Turn on, no motion control for some time if self._motion_light_enabled: self._motion_light_enabled = False self._motion_on = False self._reset_light_enabler(self._max_switch_delay()) self._reset_inactivity_timer() # Turn on light with "default_scene" self._turn_lights_on("switch", self._default_scene) elif new == "2_click": # Turn on, no motion control for some time if self._motion_light_enabled: self._motion_light_enabled = False self._motion_on = False self._reset_light_enabler(self._max_switch_delay()) self._reset_inactivity_timer() # Rotate through scenes idx = ( self._scene_rotation[self._last_scene] + 1 ) % len(self._scene_rotation) next_scene = next( filter(lambda x: x[1] == idx, self._scene_rotation.items()) )[0] self._turn_lights_on("switch_loop", next_scene) elif new == "3_hold": # Turn off, but enable motion control self._turn_lights_off(manual=True, transition=0) self._enable_motion_lights() elif new == "4_click": # Turn off, no motion control for some time if self._motion_light_enabled: self._motion_light_enabled = False self._motion_on = False self._reset_light_enabler(self._delay_re_enable_motion_control) self._reset_inactivity_timer() # Turn off light self._turn_lights_off(manual=True, transition=2) def _motion_detected(self, entity, _attribute, old, new, _kwargs): """ Listener to motion sensor changes. * New activated motion sensor turns on lights, if motion lights enabled * Each activated motion sensor resets the wait timer, if previously set * Last deactivated sensor sets a new wait timer to turn off lights. """ if new is None: self.log( f"Motion sensor disappeared: {entity} -> from {old} to {new}", level="WARNING", log=LOGGER, ) return activated = new == "on" if not self._motion_light_enabled: if activated and self._light_on: # reset wait for enable automatic control (4x mult) self._reset_light_enabler(4 * self._get_current_delay()) return self.log( f"Event: {entity:<25} -> {new:<3} (was {old})", level=EVENT_LOG_LEVEL, log=LOGGER, ) self._motion_states[entity] = activated any_active = any(self._motion_states.values()) if not self._motion_on and activated: # turn lights on (1st time) self._motion_on = True self._reset_inactivity_timer() if not self._light_on: self._turn_lights_on(entity) elif self._motion_on and not activated and not any_active: self._motion_on = False # wait some time before turning lights off self._reset_inactivity_timer( new_wait=self._get_current_delay() ) else: self._motion_on = any_active if activated: self._reset_inactivity_timer() def _no_motion_for_long_time(self, *_args, **_kwargs): """Listener to main motion sensor being off a long time.""" light_st = self.get_state(self._light_group) self._light_on = light_st == "on" if not self._light_on: return now = monotonic() self.log( f"NO MOTION FOR A LONG TIME (since {self._last_light_on:.0f} s)-> " f"{self._motion_states} / {self._motion_on}. " f"Handler off={self._handler_turn_off_lights}", log=LOGGER, ) if ( (now - self._last_light_on > self._max_delay_motion_off - 1) and (now - self._last_switch_press > self._max_switch_delay()) ) or ( self._handler_turn_off_lights is None ): # Safety turn off self.log( f"TURN OFF LIGHTS AFTER NO MOTION FOR A LONG TIME", level="ERROR", log=LOGGER, ) self._turn_lights_off()
en
0.810556
# -*- coding: utf-8 -*- Appdaemon app for motion + switch control of light in a room. # noinspection PyClassHasNoInit App to automate lights in a room with: - One or more motion sensors - A Hue Dimmer Switch for manual control, with priority over automatic. Set up appdaemon app. # Add listener to check light off after a long time # constrain_input_boolean=self._main_constrain, # Log off operation with ∆T on # Store scene to enable looping Listener to changes on light, to catch external ones, not only manual usages of hue dimmer switch. Listener to manual press on Hue dimmer switch (for manual usage) Usually 2 events are received: 'X_click' and 'X_click_up', When ON/OFF buttons are used, motion lights are disabled for some time. # Ignore button release # Turn on, no motion control for some time # Turn on light with "default_scene" # Turn on, no motion control for some time # Rotate through scenes # Turn off, but enable motion control # Turn off, no motion control for some time # Turn off light Listener to motion sensor changes. * New activated motion sensor turns on lights, if motion lights enabled * Each activated motion sensor resets the wait timer, if previously set * Last deactivated sensor sets a new wait timer to turn off lights. # reset wait for enable automatic control (4x mult) # turn lights on (1st time) # wait some time before turning lights off Listener to main motion sensor being off a long time. # Safety turn off
2.521199
3
cm2metrics/cm_test.py
FisherDock/m2metrics
0
6622417
<gh_stars>0 # MIT License # Copyright (c) 2021 <NAME>(<EMAIL>) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # This is a simple demo to use cm2metrics to parse confusion matrix. from cm2metrics.parse_cm import ConfusionMatrixParser import pandas as pd class_names = {0:"class0", 1:"class1", 2:"class2"} df_cm = pd.DataFrame([(1,2,3),(4,5,6),(7,8,9)]) df_cm.rename(index=class_names, columns=class_names, inplace=True) cm_parser = ConfusionMatrixParser(df_cm) cm_parsed = cm_parser.parse_confusion_matrix() print(cm_parsed) tp = cm_parsed.loc["class0"].at["tp"] print(tp) cm_parser.print_summary(class_name="class0") cm_parser.print_summary(class_index=0) cm_parser.print_summary()
# MIT License # Copyright (c) 2021 <NAME>(<EMAIL>) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # This is a simple demo to use cm2metrics to parse confusion matrix. from cm2metrics.parse_cm import ConfusionMatrixParser import pandas as pd class_names = {0:"class0", 1:"class1", 2:"class2"} df_cm = pd.DataFrame([(1,2,3),(4,5,6),(7,8,9)]) df_cm.rename(index=class_names, columns=class_names, inplace=True) cm_parser = ConfusionMatrixParser(df_cm) cm_parsed = cm_parser.parse_confusion_matrix() print(cm_parsed) tp = cm_parsed.loc["class0"].at["tp"] print(tp) cm_parser.print_summary(class_name="class0") cm_parser.print_summary(class_index=0) cm_parser.print_summary()
en
0.754102
# MIT License # Copyright (c) 2021 <NAME>(<EMAIL>) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # This is a simple demo to use cm2metrics to parse confusion matrix.
2.526164
3
agnes/common/tests/CNN_Discrete.py
rotinov/CITUS
24
6622418
import agnes def test_config(): return dict( timesteps=128*4, nsteps=128, nminibatches=4, gamma=0.99, lam=0.95, noptepochs=4, max_grad_norm=0.5, learning_rate=2.5e-4, cliprange=0.1, vf_coef=0.5, ent_coef=.01, bptt=16 ) def test_single_cnn(): env_name = "PongNoFrameskip-v4" envs = agnes.make_env(env_name) runner = agnes.runners.Single(envs, agnes.PPO, agnes.CNN, config=test_config()) runner.log(agnes.TensorboardLogger(), agnes.log) runner.run() def test_single_cnn_rnn(): env_name = "PongNoFrameskip-v4" envs = agnes.make_env(env_name) runner = agnes.runners.Single(envs, agnes.PPO, agnes.LSTMCNN, config=test_config()) runner.run() def test_single_cnn_a2c(): env_name = "PongNoFrameskip-v4" envs = agnes.make_env(env_name) runner = agnes.runners.Single(envs, agnes.A2C, agnes.CNN, config=test_config()) runner.run() def test_single_cnn_ppo_rnd(): env_name = "PongNoFrameskip-v4" envs = agnes.make_env(env_name) runner = agnes.runners.Single(envs, agnes.PPORND, agnes.CNN, config=test_config()) runner.run()
import agnes def test_config(): return dict( timesteps=128*4, nsteps=128, nminibatches=4, gamma=0.99, lam=0.95, noptepochs=4, max_grad_norm=0.5, learning_rate=2.5e-4, cliprange=0.1, vf_coef=0.5, ent_coef=.01, bptt=16 ) def test_single_cnn(): env_name = "PongNoFrameskip-v4" envs = agnes.make_env(env_name) runner = agnes.runners.Single(envs, agnes.PPO, agnes.CNN, config=test_config()) runner.log(agnes.TensorboardLogger(), agnes.log) runner.run() def test_single_cnn_rnn(): env_name = "PongNoFrameskip-v4" envs = agnes.make_env(env_name) runner = agnes.runners.Single(envs, agnes.PPO, agnes.LSTMCNN, config=test_config()) runner.run() def test_single_cnn_a2c(): env_name = "PongNoFrameskip-v4" envs = agnes.make_env(env_name) runner = agnes.runners.Single(envs, agnes.A2C, agnes.CNN, config=test_config()) runner.run() def test_single_cnn_ppo_rnd(): env_name = "PongNoFrameskip-v4" envs = agnes.make_env(env_name) runner = agnes.runners.Single(envs, agnes.PPORND, agnes.CNN, config=test_config()) runner.run()
none
1
2.167032
2
markovflow/kernels/__init__.py
prakharverma/markovflow
17
6622419
# # Copyright (c) 2021 The Markovflow Contributors. # # 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. # """ Package containing kernels. """ from .constant import Constant from .kernel import Kernel from .latent_exp_generated import LatentExponentiallyGenerated from .matern import Matern12, Matern32, Matern52, OrnsteinUhlenbeck from .periodic import HarmonicOscillator from .piecewise_stationary import PiecewiseKernel from .sde_kernel import ( ConcatKernel, FactorAnalysisKernel, IndependentMultiOutput, IndependentMultiOutputStack, NonStationaryKernel, Product, SDEKernel, StackKernel, StationaryKernel, Sum, )
# # Copyright (c) 2021 The Markovflow Contributors. # # 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. # """ Package containing kernels. """ from .constant import Constant from .kernel import Kernel from .latent_exp_generated import LatentExponentiallyGenerated from .matern import Matern12, Matern32, Matern52, OrnsteinUhlenbeck from .periodic import HarmonicOscillator from .piecewise_stationary import PiecewiseKernel from .sde_kernel import ( ConcatKernel, FactorAnalysisKernel, IndependentMultiOutput, IndependentMultiOutputStack, NonStationaryKernel, Product, SDEKernel, StackKernel, StationaryKernel, Sum, )
en
0.852365
# # Copyright (c) 2021 The Markovflow Contributors. # # 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. # Package containing kernels.
0.965442
1
imgs/urls.py
swap-10/ImageApp
0
6622420
from django.contrib import admin from django.urls import path, reverse from django.urls.resolvers import URLPattern from . import views urlpatterns = [ path('', views.images, name='images'), path('upload/', views.upload, name="upload"), path('<int:id>/delete', views.delete), ]
from django.contrib import admin from django.urls import path, reverse from django.urls.resolvers import URLPattern from . import views urlpatterns = [ path('', views.images, name='images'), path('upload/', views.upload, name="upload"), path('<int:id>/delete', views.delete), ]
none
1
1.629021
2
doc/en_US/tutorials/config.py
flyingTan/QuantQuant
14
6622421
############## 1. Model ############### model = dict( type='ImageClassifier', backbone=dict( type='ResNet', depth=18, num_stages=4, out_indices=(3, ), style='pytorch'), neck=dict(type='GlobalAveragePooling'), head=dict( type='LinearClsHead', num_classes=1000, in_channels=512, loss=dict(type='CrossEntropyLoss', loss_weight=1.0), topk=(1, 5), )) ############## 2. Dataset setting ############### # dataset settings dataset_type = 'ImageNetV1' img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromNori'), dict(type='RandomResizedCrop', size=224), dict(type='RandomFlip', flip_prob=0.5, direction='horizontal'), dict(type='Normalize', **img_norm_cfg), dict(type='ImageToTensor', keys=['img']), dict(type='ToTensor', keys=['gt_label']), dict(type='Collect', keys=['img', 'gt_label']) ] test_pipeline = [ dict(type='LoadImageFromFile'), dict(type='Resize', size=(256, -1)), dict(type='CenterCrop', crop_size=224), dict(type='Normalize', **img_norm_cfg), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ] data = dict( samples_per_gpu=1, workers_per_gpu=0, train=dict( type=dataset_type, data_prefix= None, ann_file="/data/workspace/dataset/imagenet/imagenet.train.nori.list", pipeline=train_pipeline), val=dict( type=dataset_type, data_prefix=None, ann_file="/data/workspace/dataset/imagenet/imagenet.val.nori.list", pipeline=test_pipeline), test=dict( # replace `data/val` with `data/test` for standard test type=dataset_type, data_prefix= None, ann_file="/data/workspace/dataset/imagenet/imagenet.val.nori.list", pipeline=test_pipeline)) evaluation = dict(interval=2, metric='accuracy') ############## 3. quantization setting ############### quant_transformer = dict( type = "mTransformerV2", quan_policy=dict( Conv2d=dict(type='DSQConv', num_bit_w=3, num_bit_a=3, bSetQ=True), Linear=dict(type='DSQLinear', num_bit_w=3, num_bit_a=3) ), special_layers = dict( layers_name = [ 'backbone.conv1', 'head.fc'], convert_type = [dict(type='DSQConv', num_bit_w=8, num_bit_a=8, bSetQ=True, quant_activation=False), dict(type='DSQLinear', num_bit_w=8, num_bit_a=8)] ) ) ############## 4. optimizer, log, workdir, and etc ############### # checkpoint saving checkpoint_config = dict(interval=2) # optimizer num_nodes = 1 optimizer = dict(type='SGD', lr=0.001 * num_nodes, momentum=0.9, weight_decay=0.0001) optimizer_config = dict(grad_clip=None) # learning policy lr_config = dict( policy='step', # warmup='linear', # warmup_iters=3000, # warmup_ratio=0.25, step=[30, 60, 90]) total_epochs = 100 # logger setting log_level = 'INFO' log_config = dict( interval=200, hooks=[ dict(type='TextLoggerHook'), # dict(type='TensorboardLoggerHook') ]) dist_params = dict(backend='nccl') work_dir = '/data/workspace/lowbit_classification/workdirs/DSQ/res18/config1_res18_deq_m1_16_3w3f' workflow = [('train', 1)] load_from = '../thirdparty/modelzoo/res18.pth' resume_from = None cpu_only=True find_unused_parameters = True sycbn = False
############## 1. Model ############### model = dict( type='ImageClassifier', backbone=dict( type='ResNet', depth=18, num_stages=4, out_indices=(3, ), style='pytorch'), neck=dict(type='GlobalAveragePooling'), head=dict( type='LinearClsHead', num_classes=1000, in_channels=512, loss=dict(type='CrossEntropyLoss', loss_weight=1.0), topk=(1, 5), )) ############## 2. Dataset setting ############### # dataset settings dataset_type = 'ImageNetV1' img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromNori'), dict(type='RandomResizedCrop', size=224), dict(type='RandomFlip', flip_prob=0.5, direction='horizontal'), dict(type='Normalize', **img_norm_cfg), dict(type='ImageToTensor', keys=['img']), dict(type='ToTensor', keys=['gt_label']), dict(type='Collect', keys=['img', 'gt_label']) ] test_pipeline = [ dict(type='LoadImageFromFile'), dict(type='Resize', size=(256, -1)), dict(type='CenterCrop', crop_size=224), dict(type='Normalize', **img_norm_cfg), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ] data = dict( samples_per_gpu=1, workers_per_gpu=0, train=dict( type=dataset_type, data_prefix= None, ann_file="/data/workspace/dataset/imagenet/imagenet.train.nori.list", pipeline=train_pipeline), val=dict( type=dataset_type, data_prefix=None, ann_file="/data/workspace/dataset/imagenet/imagenet.val.nori.list", pipeline=test_pipeline), test=dict( # replace `data/val` with `data/test` for standard test type=dataset_type, data_prefix= None, ann_file="/data/workspace/dataset/imagenet/imagenet.val.nori.list", pipeline=test_pipeline)) evaluation = dict(interval=2, metric='accuracy') ############## 3. quantization setting ############### quant_transformer = dict( type = "mTransformerV2", quan_policy=dict( Conv2d=dict(type='DSQConv', num_bit_w=3, num_bit_a=3, bSetQ=True), Linear=dict(type='DSQLinear', num_bit_w=3, num_bit_a=3) ), special_layers = dict( layers_name = [ 'backbone.conv1', 'head.fc'], convert_type = [dict(type='DSQConv', num_bit_w=8, num_bit_a=8, bSetQ=True, quant_activation=False), dict(type='DSQLinear', num_bit_w=8, num_bit_a=8)] ) ) ############## 4. optimizer, log, workdir, and etc ############### # checkpoint saving checkpoint_config = dict(interval=2) # optimizer num_nodes = 1 optimizer = dict(type='SGD', lr=0.001 * num_nodes, momentum=0.9, weight_decay=0.0001) optimizer_config = dict(grad_clip=None) # learning policy lr_config = dict( policy='step', # warmup='linear', # warmup_iters=3000, # warmup_ratio=0.25, step=[30, 60, 90]) total_epochs = 100 # logger setting log_level = 'INFO' log_config = dict( interval=200, hooks=[ dict(type='TextLoggerHook'), # dict(type='TensorboardLoggerHook') ]) dist_params = dict(backend='nccl') work_dir = '/data/workspace/lowbit_classification/workdirs/DSQ/res18/config1_res18_deq_m1_16_3w3f' workflow = [('train', 1)] load_from = '../thirdparty/modelzoo/res18.pth' resume_from = None cpu_only=True find_unused_parameters = True sycbn = False
de
0.370191
############## 1. Model ############### ############## 2. Dataset setting ############### # dataset settings # replace `data/val` with `data/test` for standard test ############## 3. quantization setting ############### ############## 4. optimizer, log, workdir, and etc ############### # checkpoint saving # optimizer # learning policy # warmup='linear', # warmup_iters=3000, # warmup_ratio=0.25, # logger setting # dict(type='TensorboardLoggerHook')
2.090496
2
oas_dev/notebooks/global_comparisons/01_maps/01-02-lifetimes.py
sarambl/OAS-DEV
0
6622422
<filename>oas_dev/notebooks/global_comparisons/01_maps/01-02-lifetimes.py # --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.3.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %% from oas_dev.util.plot.plot_maps import plot_map_diff, fix_axis4map_plot, plot_map_abs_abs_diff, plot_map from useful_scit.imps import (np, xr, plt, pd) from oas_dev.util.imports import get_averaged_fields from IPython.display import clear_output # load and autoreload from IPython import get_ipython # noinspection PyBroadException try: _ipython = get_ipython() _magic = _ipython.magic _magic('load_ext autoreload') _magic('autoreload 2') except: pass # %% from oas_dev.util.slice_average.avg_pkg import average_model_var from oas_dev.data_info import get_nice_name_case # %% [markdown] # ## Ideas: # - Root mean square diffence?? # - Scatter plots of all values, e.g x-- sectional y-- non sectional color by lat/lev? Or lev lat difference. # %% [markdown] # # Map plots number concentration: # %% model = 'NorESM' startyear = '2008-01' endyear = '2014-12' pmin = 850. # minimum pressure level avg_over_lev = True # True#True#False#True pressure_adjust = True # Can only be false if avg_over_lev false. Plots particular hybrid sigma lev if avg_over_lev: pressure_adjust = True p_levels = [1013.,900., 800., 700., 600.] # used if not avg # %% [markdown] # ## Cases # %% cases_sec = ['SECTv21_ctrl_koagD'] cases_orig =['noSECTv21_default'] cases_orig =['noSECTv21_ox_ricc_dd'] cases = cases_orig + cases_sec cases2 = ['noSECTv21_default_dd']+cases_sec #['noSECTv11_ctrl_fbvoc', 'noSECTv11_noresm2_ctrl'] cases_all = cases_sec + cases_orig + ['noSECTv21_default_dd'] # %% def load_and_plot(var, cases,startyear, endyear, avg_over_lev=avg_over_lev, pmin=pmin, pressure_adjust=pressure_adjust, p_level=None, relative=False, kwargs_diff=None): maps_dic = get_averaged_fields.get_maps_cases(cases,[var],startyear, endyear, avg_over_lev=avg_over_lev, pmin=pmin, pressure_adjust=pressure_adjust, p_level=p_level) return plot_map_abs_abs_diff(var, cases, maps_dic, relative=relative, figsize=[18, 3], cbar_equal=True, kwargs_abs={}, kwargs_diff=kwargs_diff, axs=None, cmap_abs='Reds', cmap_diff='RdBu_r') # %% [markdown] # ## Mean to 850hPa weighted by pressure difference: # %% so4_spess_fac = dict(SO4_A1=3.06, SO4_A2=3.59, SO4_AC=3.06, SO4_NA=3.06, SO4_PR=3.06, SO4_A1_OCW=3.06, SO4_A2_OCW=3.59, SO4_AC_OCW=3.06, SO4_NA_OCW=3.06, SO4_PR_OCW=3.06 ) so4_spess = list(so4_spess_fac.keys()) # %% soa_spess = [ 'SOA_NA', 'OM_AI', 'OM_AC', 'OM_NI', 'SOA_NA_OCW', 'OM_AI_OCW', 'OM_AC_OCW', 'OM_NI_OCW' ] soa_spess_fac = {s:1 for s in soa_spess} # %% import itertools # %% core_vl = soa_spess + so4_spess var_ext = ["DDF","SFWET"] varl = [f'cb_{v}' for v in core_vl] varl = varl + [f'{v}{ext}' for (v,ext) in itertools.product(core_vl, var_ext)] # %% varl # %% #var_ext = [f"{v}DDF",f"{v}SFWET",f"{v}SFSIC",f"{v}SFSBC",f"{v}SFSIS",f"{v}SFSBS" # , f"{v}_mixnuc1"] v='SO4_NA' #varl=[] for v in ['SOA_NA','SO4_NA']:#, 'SOA_NA_OCW','SO4_NA_OCW']: varl = [f'{v}coagTend',f'{v}clcoagTend',f'{v}condTend']+ varl # f"{v}SFSIC",f"{v}SFSBC",f"{v}SFSIS",f"{v}SFSBS", f"{v}_mixnuc1", """ for v in [ 'SOA_NA_OCW','SO4_NA_OCW']: varl=varl+ [f'cb_{v}']#'LWDIR_Ghan']#, 'SO4_NAcondTend']#, 'leaveSecH2SO4','leaveSecSOA']#,'TGCLDCWP'] varl = [f"{v}DDF",f"{v}SFWET"]+ varl """ maps_dic = get_averaged_fields.get_maps_cases(cases_all,varl,startyear, endyear, avg_over_lev=avg_over_lev, pmin=pmin, pressure_adjust=pressure_adjust)#, p_level=p_level) # %% def calc_tot_LR(ds,v): return (-ds[f'{v}DDF'] + ds[f'{v}SFWET'] + ds[f'{v}coagTend'] + ds[f'{v}clcoagTend']) def LR_dd_wd(ds,v): return (-ds[f'{v}DDF'] + ds[f'{v}SFWET'])# + ds[f'{v}coagTend'] + ds[f'{v}clcoagTend']) # %% def comp_lifetime(ds, which, fac_dic ): lossrate_OCW_DD = 0 lossrate_OCW_WD = 0 lossrate_nOCW_DD = 0 lossrate_nOCW_WD = 0 cb_OCW = 0 cb_nOCW = 0 for v in fac_dic.keys(): f = fac_dic[v] if '_OCW' in v: cb_OCW = f*ds[f'cb_{v}'] + cb_OCW lossrate_OCW_DD = f*(-ds[f'{v}DDF']) + lossrate_OCW_DD lossrate_OCW_WD = f*(ds[f'{v}SFWET']) + lossrate_OCW_WD else: cb_nOCW = f*ds[f'cb_{v}'] + cb_nOCW lossrate_nOCW_DD = f*(-ds[f'{v}DDF']) + lossrate_nOCW_DD lossrate_nOCW_WD = f*(ds[f'{v}SFWET']) + lossrate_nOCW_WD ds[f'cb_{which}'] = cb_nOCW ds[f'cb_{which}_OCW'] = cb_OCW ds[f'cb_{which}_tot'] = cb_nOCW + cb_OCW ds[f'{which}_OCW_DD'] = lossrate_OCW_DD ds[f'{which}_OCW_WD'] = lossrate_OCW_WD ds[f'{which}_OCW_D'] = lossrate_OCW_WD + lossrate_OCW_DD ds[f'{which}_DD'] = lossrate_nOCW_DD ds[f'{which}_WD'] = lossrate_nOCW_WD ds[f'{which}_D'] = lossrate_nOCW_WD + lossrate_nOCW_DD ds[f'{which}_tot_WD'] = lossrate_nOCW_WD + lossrate_OCW_WD ds[f'{which}_tot_DD'] = lossrate_nOCW_DD + lossrate_OCW_DD ds[f'{which}_tot_D'] = lossrate_nOCW_DD + lossrate_OCW_DD + lossrate_nOCW_WD + lossrate_OCW_WD return ds # %% for case in cases_all: comp_lifetime(maps_dic[case], 'OA', soa_spess_fac ) comp_lifetime(maps_dic[case], 'SO4', so4_spess_fac ) # %% def comp_lossr(v, ext, _ds): cb = average_model_var(_ds, f'cb_{v}', area='Global', dim=None, minp=850., time_mask=None) lr = average_model_var(_ds, f'{v}{ext}', area='Global', dim=None, minp=850., time_mask=None) out = cb[f'cb_{v}']/lr[f'{v}{ext}']/(60*60*24) if out<0: out=abs(out) out.attrs['units']='days' return out # %% from oas_dev.data_info import get_nice_name_case # %% exts_dic = { '_D':'$\tau_{tot}$', '_DD':'$\tau_{DDF}$', '_WD':'$\tau_{WET}$', #'coagTend':'$\tau_{coag}$', #'clcoagTend':'$\tau_{clcoag}$' } dic_all ={} for var in ['SO4','SO4_OCW','SO4_tot','OA','OA_OCW','OA_tot',]: dic_all[var]={} for case in cases_all: nncase = get_nice_name_case(case) dic_all[var][nncase]={} for ext in exts_dic.keys(): val = comp_lossr(var,ext,maps_dic[case]) dic_all[var][nncase][exts_dic[ext]] = val.values # %% pd.DataFrame.from_dict(dic_all['SO4']) # %% pd.DataFrame.from_dict(dic_all['SO4_tot']) # %% pd.DataFrame.from_dict(dic_all['OA_tot']) # %% pd.DataFrame.from_dict(dic_all['OA']) # %% pd.DataFrame.from_dict(dic_all['OA_OCW']) # %% maps_dic[case] # %% lss_exts = ['DDF','SFWET','coagTend','clcoagTend'] v = 'SOA_NA' for v in ['SOA_NA','SO4_NA']: for case in cases_all: ds = maps_dic[case] ds[f'{v}_lr_tot'] = -(-ds[f'{v}DDF'] + ds[f'{v}SFWET'] + ds[f'{v}coagTend'] + ds[f'{v}clcoagTend']) ds[f'{v}_OCW_lr_tot'] = -(-ds[f'{v}_OCWDDF'] + ds[f'{v}_OCWSFWET'])# + ds[f'{v}coagTend'] + ds[f'{v}clcoagTend']) ds[f'{v}_lr_tot_inc'] =ds[f'{v}_OCW_lr_tot'] + ds[f'{v}_OCW_lr_tot'] ds[f'tau_new_{v}'] = ds[f'cb_{v}']/ds[f'{v}_lr_tot'] for ex in lss_exts: ds[f'tau_{ex}_{v}'] = (ds[f'cb_{v}']/ds[f'{v}{ex}'])/60/60/24 ds[f'tau_{ex}_{v}'].attrs['units'] = 'days' ds[f'tau_prod_{v}'] = ds[f'cb_{v}']/ds[f'{v}condTend']/(60*60*24) ds[f'tau_prod_{v}'].attrs['units'] = 'days' ds[f'cb_{v}_tot'] = ds[f'cb_{v}']+ ds[f'cb_{v}_OCW'] # %% from oas_dev.util.slice_average.avg_pkg import average_model_var from oas_dev.data_info import get_nice_name_case # %% def comp_lossr(v, ext, _ds): cb = average_model_var(_ds, f'cb_{v}', area='Global', dim=None, minp=850., time_mask=None) lr = average_model_var(_ds, f'{v}{ext}', area='Global', dim=None, minp=850., time_mask=None) out = cb[f'cb_{v}']/lr[f'{v}{ext}']/(60*60*24) if out<0: out=abs(out) out.attrs['units']='days' return out # %% [markdown] # ## NA-mode lifetime # %% exts_dic = { '_lr_tot':'$\tau_{tot}$', 'DDF':'$\tau_{DDF}$', 'SFWET':'$\tau_{WET}$', 'coagTend':'$\tau_{coag}$', 'clcoagTend':'$\tau_{clcoag}$'} dic_all ={} for var in ['SOA_NA','SO4_NA']: dic_all[var]={} for case in cases_all: nncase = get_nice_name_case(case) dic_all[var][nncase]={} for ext in exts_dic.keys(): val = comp_lossr(var,ext,maps_dic[case]) dic_all[var][nncase][exts_dic[ext]] = val.values # %% pd.DataFrame.from_dict(dic_all['SOA_NA']) # %% pd.DataFrame.from_dict(dic_all['SO4_NA']) # %%
<filename>oas_dev/notebooks/global_comparisons/01_maps/01-02-lifetimes.py # --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.3.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %% from oas_dev.util.plot.plot_maps import plot_map_diff, fix_axis4map_plot, plot_map_abs_abs_diff, plot_map from useful_scit.imps import (np, xr, plt, pd) from oas_dev.util.imports import get_averaged_fields from IPython.display import clear_output # load and autoreload from IPython import get_ipython # noinspection PyBroadException try: _ipython = get_ipython() _magic = _ipython.magic _magic('load_ext autoreload') _magic('autoreload 2') except: pass # %% from oas_dev.util.slice_average.avg_pkg import average_model_var from oas_dev.data_info import get_nice_name_case # %% [markdown] # ## Ideas: # - Root mean square diffence?? # - Scatter plots of all values, e.g x-- sectional y-- non sectional color by lat/lev? Or lev lat difference. # %% [markdown] # # Map plots number concentration: # %% model = 'NorESM' startyear = '2008-01' endyear = '2014-12' pmin = 850. # minimum pressure level avg_over_lev = True # True#True#False#True pressure_adjust = True # Can only be false if avg_over_lev false. Plots particular hybrid sigma lev if avg_over_lev: pressure_adjust = True p_levels = [1013.,900., 800., 700., 600.] # used if not avg # %% [markdown] # ## Cases # %% cases_sec = ['SECTv21_ctrl_koagD'] cases_orig =['noSECTv21_default'] cases_orig =['noSECTv21_ox_ricc_dd'] cases = cases_orig + cases_sec cases2 = ['noSECTv21_default_dd']+cases_sec #['noSECTv11_ctrl_fbvoc', 'noSECTv11_noresm2_ctrl'] cases_all = cases_sec + cases_orig + ['noSECTv21_default_dd'] # %% def load_and_plot(var, cases,startyear, endyear, avg_over_lev=avg_over_lev, pmin=pmin, pressure_adjust=pressure_adjust, p_level=None, relative=False, kwargs_diff=None): maps_dic = get_averaged_fields.get_maps_cases(cases,[var],startyear, endyear, avg_over_lev=avg_over_lev, pmin=pmin, pressure_adjust=pressure_adjust, p_level=p_level) return plot_map_abs_abs_diff(var, cases, maps_dic, relative=relative, figsize=[18, 3], cbar_equal=True, kwargs_abs={}, kwargs_diff=kwargs_diff, axs=None, cmap_abs='Reds', cmap_diff='RdBu_r') # %% [markdown] # ## Mean to 850hPa weighted by pressure difference: # %% so4_spess_fac = dict(SO4_A1=3.06, SO4_A2=3.59, SO4_AC=3.06, SO4_NA=3.06, SO4_PR=3.06, SO4_A1_OCW=3.06, SO4_A2_OCW=3.59, SO4_AC_OCW=3.06, SO4_NA_OCW=3.06, SO4_PR_OCW=3.06 ) so4_spess = list(so4_spess_fac.keys()) # %% soa_spess = [ 'SOA_NA', 'OM_AI', 'OM_AC', 'OM_NI', 'SOA_NA_OCW', 'OM_AI_OCW', 'OM_AC_OCW', 'OM_NI_OCW' ] soa_spess_fac = {s:1 for s in soa_spess} # %% import itertools # %% core_vl = soa_spess + so4_spess var_ext = ["DDF","SFWET"] varl = [f'cb_{v}' for v in core_vl] varl = varl + [f'{v}{ext}' for (v,ext) in itertools.product(core_vl, var_ext)] # %% varl # %% #var_ext = [f"{v}DDF",f"{v}SFWET",f"{v}SFSIC",f"{v}SFSBC",f"{v}SFSIS",f"{v}SFSBS" # , f"{v}_mixnuc1"] v='SO4_NA' #varl=[] for v in ['SOA_NA','SO4_NA']:#, 'SOA_NA_OCW','SO4_NA_OCW']: varl = [f'{v}coagTend',f'{v}clcoagTend',f'{v}condTend']+ varl # f"{v}SFSIC",f"{v}SFSBC",f"{v}SFSIS",f"{v}SFSBS", f"{v}_mixnuc1", """ for v in [ 'SOA_NA_OCW','SO4_NA_OCW']: varl=varl+ [f'cb_{v}']#'LWDIR_Ghan']#, 'SO4_NAcondTend']#, 'leaveSecH2SO4','leaveSecSOA']#,'TGCLDCWP'] varl = [f"{v}DDF",f"{v}SFWET"]+ varl """ maps_dic = get_averaged_fields.get_maps_cases(cases_all,varl,startyear, endyear, avg_over_lev=avg_over_lev, pmin=pmin, pressure_adjust=pressure_adjust)#, p_level=p_level) # %% def calc_tot_LR(ds,v): return (-ds[f'{v}DDF'] + ds[f'{v}SFWET'] + ds[f'{v}coagTend'] + ds[f'{v}clcoagTend']) def LR_dd_wd(ds,v): return (-ds[f'{v}DDF'] + ds[f'{v}SFWET'])# + ds[f'{v}coagTend'] + ds[f'{v}clcoagTend']) # %% def comp_lifetime(ds, which, fac_dic ): lossrate_OCW_DD = 0 lossrate_OCW_WD = 0 lossrate_nOCW_DD = 0 lossrate_nOCW_WD = 0 cb_OCW = 0 cb_nOCW = 0 for v in fac_dic.keys(): f = fac_dic[v] if '_OCW' in v: cb_OCW = f*ds[f'cb_{v}'] + cb_OCW lossrate_OCW_DD = f*(-ds[f'{v}DDF']) + lossrate_OCW_DD lossrate_OCW_WD = f*(ds[f'{v}SFWET']) + lossrate_OCW_WD else: cb_nOCW = f*ds[f'cb_{v}'] + cb_nOCW lossrate_nOCW_DD = f*(-ds[f'{v}DDF']) + lossrate_nOCW_DD lossrate_nOCW_WD = f*(ds[f'{v}SFWET']) + lossrate_nOCW_WD ds[f'cb_{which}'] = cb_nOCW ds[f'cb_{which}_OCW'] = cb_OCW ds[f'cb_{which}_tot'] = cb_nOCW + cb_OCW ds[f'{which}_OCW_DD'] = lossrate_OCW_DD ds[f'{which}_OCW_WD'] = lossrate_OCW_WD ds[f'{which}_OCW_D'] = lossrate_OCW_WD + lossrate_OCW_DD ds[f'{which}_DD'] = lossrate_nOCW_DD ds[f'{which}_WD'] = lossrate_nOCW_WD ds[f'{which}_D'] = lossrate_nOCW_WD + lossrate_nOCW_DD ds[f'{which}_tot_WD'] = lossrate_nOCW_WD + lossrate_OCW_WD ds[f'{which}_tot_DD'] = lossrate_nOCW_DD + lossrate_OCW_DD ds[f'{which}_tot_D'] = lossrate_nOCW_DD + lossrate_OCW_DD + lossrate_nOCW_WD + lossrate_OCW_WD return ds # %% for case in cases_all: comp_lifetime(maps_dic[case], 'OA', soa_spess_fac ) comp_lifetime(maps_dic[case], 'SO4', so4_spess_fac ) # %% def comp_lossr(v, ext, _ds): cb = average_model_var(_ds, f'cb_{v}', area='Global', dim=None, minp=850., time_mask=None) lr = average_model_var(_ds, f'{v}{ext}', area='Global', dim=None, minp=850., time_mask=None) out = cb[f'cb_{v}']/lr[f'{v}{ext}']/(60*60*24) if out<0: out=abs(out) out.attrs['units']='days' return out # %% from oas_dev.data_info import get_nice_name_case # %% exts_dic = { '_D':'$\tau_{tot}$', '_DD':'$\tau_{DDF}$', '_WD':'$\tau_{WET}$', #'coagTend':'$\tau_{coag}$', #'clcoagTend':'$\tau_{clcoag}$' } dic_all ={} for var in ['SO4','SO4_OCW','SO4_tot','OA','OA_OCW','OA_tot',]: dic_all[var]={} for case in cases_all: nncase = get_nice_name_case(case) dic_all[var][nncase]={} for ext in exts_dic.keys(): val = comp_lossr(var,ext,maps_dic[case]) dic_all[var][nncase][exts_dic[ext]] = val.values # %% pd.DataFrame.from_dict(dic_all['SO4']) # %% pd.DataFrame.from_dict(dic_all['SO4_tot']) # %% pd.DataFrame.from_dict(dic_all['OA_tot']) # %% pd.DataFrame.from_dict(dic_all['OA']) # %% pd.DataFrame.from_dict(dic_all['OA_OCW']) # %% maps_dic[case] # %% lss_exts = ['DDF','SFWET','coagTend','clcoagTend'] v = 'SOA_NA' for v in ['SOA_NA','SO4_NA']: for case in cases_all: ds = maps_dic[case] ds[f'{v}_lr_tot'] = -(-ds[f'{v}DDF'] + ds[f'{v}SFWET'] + ds[f'{v}coagTend'] + ds[f'{v}clcoagTend']) ds[f'{v}_OCW_lr_tot'] = -(-ds[f'{v}_OCWDDF'] + ds[f'{v}_OCWSFWET'])# + ds[f'{v}coagTend'] + ds[f'{v}clcoagTend']) ds[f'{v}_lr_tot_inc'] =ds[f'{v}_OCW_lr_tot'] + ds[f'{v}_OCW_lr_tot'] ds[f'tau_new_{v}'] = ds[f'cb_{v}']/ds[f'{v}_lr_tot'] for ex in lss_exts: ds[f'tau_{ex}_{v}'] = (ds[f'cb_{v}']/ds[f'{v}{ex}'])/60/60/24 ds[f'tau_{ex}_{v}'].attrs['units'] = 'days' ds[f'tau_prod_{v}'] = ds[f'cb_{v}']/ds[f'{v}condTend']/(60*60*24) ds[f'tau_prod_{v}'].attrs['units'] = 'days' ds[f'cb_{v}_tot'] = ds[f'cb_{v}']+ ds[f'cb_{v}_OCW'] # %% from oas_dev.util.slice_average.avg_pkg import average_model_var from oas_dev.data_info import get_nice_name_case # %% def comp_lossr(v, ext, _ds): cb = average_model_var(_ds, f'cb_{v}', area='Global', dim=None, minp=850., time_mask=None) lr = average_model_var(_ds, f'{v}{ext}', area='Global', dim=None, minp=850., time_mask=None) out = cb[f'cb_{v}']/lr[f'{v}{ext}']/(60*60*24) if out<0: out=abs(out) out.attrs['units']='days' return out # %% [markdown] # ## NA-mode lifetime # %% exts_dic = { '_lr_tot':'$\tau_{tot}$', 'DDF':'$\tau_{DDF}$', 'SFWET':'$\tau_{WET}$', 'coagTend':'$\tau_{coag}$', 'clcoagTend':'$\tau_{clcoag}$'} dic_all ={} for var in ['SOA_NA','SO4_NA']: dic_all[var]={} for case in cases_all: nncase = get_nice_name_case(case) dic_all[var][nncase]={} for ext in exts_dic.keys(): val = comp_lossr(var,ext,maps_dic[case]) dic_all[var][nncase][exts_dic[ext]] = val.values # %% pd.DataFrame.from_dict(dic_all['SOA_NA']) # %% pd.DataFrame.from_dict(dic_all['SO4_NA']) # %%
en
0.343366
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.3.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %% # load and autoreload # noinspection PyBroadException # %% # %% [markdown] # ## Ideas: # - Root mean square diffence?? # - Scatter plots of all values, e.g x-- sectional y-- non sectional color by lat/lev? Or lev lat difference. # %% [markdown] # # Map plots number concentration: # %% # minimum pressure level # True#True#False#True # Can only be false if avg_over_lev false. Plots particular hybrid sigma lev # used if not avg # %% [markdown] # ## Cases # %% #['noSECTv11_ctrl_fbvoc', 'noSECTv11_noresm2_ctrl'] # %% # %% [markdown] # ## Mean to 850hPa weighted by pressure difference: # %% # %% # %% # %% # %% # %% #var_ext = [f"{v}DDF",f"{v}SFWET",f"{v}SFSIC",f"{v}SFSBC",f"{v}SFSIS",f"{v}SFSBS" # , f"{v}_mixnuc1"] #varl=[] #, 'SOA_NA_OCW','SO4_NA_OCW']: # f"{v}SFSIC",f"{v}SFSBC",f"{v}SFSIS",f"{v}SFSBS", f"{v}_mixnuc1", for v in [ 'SOA_NA_OCW','SO4_NA_OCW']: varl=varl+ [f'cb_{v}']#'LWDIR_Ghan']#, 'SO4_NAcondTend']#, 'leaveSecH2SO4','leaveSecSOA']#,'TGCLDCWP'] varl = [f"{v}DDF",f"{v}SFWET"]+ varl #, p_level=p_level) # %% # + ds[f'{v}coagTend'] + ds[f'{v}clcoagTend']) # %% # %% # %% # %% # %% #'coagTend':'$\tau_{coag}$', #'clcoagTend':'$\tau_{clcoag}$' # %% # %% # %% # %% # %% # %% # %% # + ds[f'{v}coagTend'] + ds[f'{v}clcoagTend']) # %% # %% # %% [markdown] # ## NA-mode lifetime # %% # %% # %% # %%
1.834343
2
python_exercises/Curso_em_video/ex034.py
Matheus-IT/lang-python-related
0
6622423
<gh_stars>0 sal = float(input('\033[35mQual o seu salário? R$\033[m')) if sal <= 1250: aumento = sal + (0.15 * sal) else: aumento = sal + (0.10 * sal) print('\033[1;35mQuem ganhava R${:.2f} passa a ganhar R${:.2f} agora\033[m'.format(sal, aumento))
sal = float(input('\033[35mQual o seu salário? R$\033[m')) if sal <= 1250: aumento = sal + (0.15 * sal) else: aumento = sal + (0.10 * sal) print('\033[1;35mQuem ganhava R${:.2f} passa a ganhar R${:.2f} agora\033[m'.format(sal, aumento))
none
1
3.479313
3
code/model_kit/layer_norm.py
jiwoongim/IMsML
0
6622424
import os, sys import numpy as np import tensorflow as tf from utils.nn_utils import * from utils.tf_utils import * TINY = 1e-5 class Layer_Norm(object): def __init__(self, D, M, name, numpy_rng): self.W = initialize_weight(D, M, name, numpy_rng, 'uniform') self.eta = theano.shared(np.ones((M,), dtype=theano.config.floatX), name='eta') self.beta = theano.shared(np.zeros((M,), dtype=theano.config.floatX), name='beta') self.params = [self.W, self.eta, self.beta] def propagate(self, X, atype='sigmoid'): H = self.pre_activation(X) H = activation_fn_th(H, atype=atype) return H def pre_activation(self, X): Z = self.post_batch_norm(X, testF=testF) H = self.eta * Z + self.beta return H def post_batch_norm(self, X): Z = T.dot(X, self.W) mean = Z.mean(axis=-1) std = Z.std( axis=-1) Z = (Z - mean) / (std + TINY) return Z def layer_norm_fn(Z, beta, eta): mean, var = tf.nn.moments(Z,axes=[1]) Z = (Z - tf.expand_dims(mean, 1)) / \ tf.sqrt(tf.expand_dims(var,1) + TINY) H = tf.expand_dims(eta, 0) * Z + tf.expand_dims(beta, 0) return H
import os, sys import numpy as np import tensorflow as tf from utils.nn_utils import * from utils.tf_utils import * TINY = 1e-5 class Layer_Norm(object): def __init__(self, D, M, name, numpy_rng): self.W = initialize_weight(D, M, name, numpy_rng, 'uniform') self.eta = theano.shared(np.ones((M,), dtype=theano.config.floatX), name='eta') self.beta = theano.shared(np.zeros((M,), dtype=theano.config.floatX), name='beta') self.params = [self.W, self.eta, self.beta] def propagate(self, X, atype='sigmoid'): H = self.pre_activation(X) H = activation_fn_th(H, atype=atype) return H def pre_activation(self, X): Z = self.post_batch_norm(X, testF=testF) H = self.eta * Z + self.beta return H def post_batch_norm(self, X): Z = T.dot(X, self.W) mean = Z.mean(axis=-1) std = Z.std( axis=-1) Z = (Z - mean) / (std + TINY) return Z def layer_norm_fn(Z, beta, eta): mean, var = tf.nn.moments(Z,axes=[1]) Z = (Z - tf.expand_dims(mean, 1)) / \ tf.sqrt(tf.expand_dims(var,1) + TINY) H = tf.expand_dims(eta, 0) * Z + tf.expand_dims(beta, 0) return H
none
1
2.370528
2
fuzzinator/formatter/__init__.py
akosthekiss/fuzzinator
202
6622425
# Copyright (c) 2018-2021 <NAME>, <NAME>. # # Licensed under the BSD 3-Clause License # <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>. # This file may not be copied, modified, or distributed except # according to those terms. from .chevron_formatter import ChevronFormatter from .decoder_decorator import DecoderDecorator from .formatter import Formatter from .formatter_decorator import FormatterDecorator from .jinja_formatter import JinjaFormatter from .json_formatter import JsonFormatter from .markdown_decorator import MarkdownDecorator from .string_formatter import StringFormatter from .template_formatter import TemplateFormatter
# Copyright (c) 2018-2021 <NAME>, <NAME>. # # Licensed under the BSD 3-Clause License # <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>. # This file may not be copied, modified, or distributed except # according to those terms. from .chevron_formatter import ChevronFormatter from .decoder_decorator import DecoderDecorator from .formatter import Formatter from .formatter_decorator import FormatterDecorator from .jinja_formatter import JinjaFormatter from .json_formatter import JsonFormatter from .markdown_decorator import MarkdownDecorator from .string_formatter import StringFormatter from .template_formatter import TemplateFormatter
en
0.759298
# Copyright (c) 2018-2021 <NAME>, <NAME>. # # Licensed under the BSD 3-Clause License # <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>. # This file may not be copied, modified, or distributed except # according to those terms.
0.987339
1
src/dataset/augmentation.py
rs1004/yolo
0
6622426
<reponame>rs1004/yolo import torch from torchvision.transforms.functional import hflip from torchvision.transforms import ( Compose as C, ToTensor as TT, ColorJitter as CJ ) class Compose(C): """This is an extension of torchvision.transforms.Compose so that it can be applied to 'image' and 'gt'. Args: transforms (list of ``Transform`` objects): list of transforms to compose. """ def __init__(self, transforms): super(Compose, self).__init__(transforms) def __call__(self, img, gt): for t in self.transforms: img, gt = t(img, gt) return img, gt class ToTensor(TT): """This is an extension of torchvision.transforms.ToTensor so that it can be applied to 'image' and 'gt'. """ def __call__(self, img, gt): """ Args: img (PIL Image or numpy.ndarray): Image to be converted to tensor. Returns: Tensor: Converted image. """ return super(ToTensor, self).__call__(img), gt class RandomColorJitter(CJ): def __init__(self, p: float = 0.5, brightness=0.3, contrast=0.3, saturation=1.5, hue=0.1): super(RandomColorJitter, self).__init__(brightness, contrast, saturation, hue) self.p = p def __call__(self, img, gt): if torch.rand(1) < self.p: img = super(RandomColorJitter, self).__call__(img) return img, gt class RandomFlip(torch.nn.Module): def __init__(self, input_size: int, p: float = 0.5): """initialize Args: input_size (int): image size p (float, optional): probability of executing. Defaults to 0.5. """ self.input_size = input_size self.p = p def __call__(self, img, gt): if torch.rand(1) < self.p: img = hflip(img) gt[:, 0], gt[:, 2] = self.input_size - gt[:, 2], self.input_size - gt[:, 0] return img, gt
import torch from torchvision.transforms.functional import hflip from torchvision.transforms import ( Compose as C, ToTensor as TT, ColorJitter as CJ ) class Compose(C): """This is an extension of torchvision.transforms.Compose so that it can be applied to 'image' and 'gt'. Args: transforms (list of ``Transform`` objects): list of transforms to compose. """ def __init__(self, transforms): super(Compose, self).__init__(transforms) def __call__(self, img, gt): for t in self.transforms: img, gt = t(img, gt) return img, gt class ToTensor(TT): """This is an extension of torchvision.transforms.ToTensor so that it can be applied to 'image' and 'gt'. """ def __call__(self, img, gt): """ Args: img (PIL Image or numpy.ndarray): Image to be converted to tensor. Returns: Tensor: Converted image. """ return super(ToTensor, self).__call__(img), gt class RandomColorJitter(CJ): def __init__(self, p: float = 0.5, brightness=0.3, contrast=0.3, saturation=1.5, hue=0.1): super(RandomColorJitter, self).__init__(brightness, contrast, saturation, hue) self.p = p def __call__(self, img, gt): if torch.rand(1) < self.p: img = super(RandomColorJitter, self).__call__(img) return img, gt class RandomFlip(torch.nn.Module): def __init__(self, input_size: int, p: float = 0.5): """initialize Args: input_size (int): image size p (float, optional): probability of executing. Defaults to 0.5. """ self.input_size = input_size self.p = p def __call__(self, img, gt): if torch.rand(1) < self.p: img = hflip(img) gt[:, 0], gt[:, 2] = self.input_size - gt[:, 2], self.input_size - gt[:, 0] return img, gt
en
0.744135
This is an extension of torchvision.transforms.Compose so that it can be applied to 'image' and 'gt'. Args: transforms (list of ``Transform`` objects): list of transforms to compose. This is an extension of torchvision.transforms.ToTensor so that it can be applied to 'image' and 'gt'. Args: img (PIL Image or numpy.ndarray): Image to be converted to tensor. Returns: Tensor: Converted image. initialize Args: input_size (int): image size p (float, optional): probability of executing. Defaults to 0.5.
2.507135
3
empower/vbsp/ue_measurements/ue_measurements.py
gzaccaria/empower-runtime
0
6622427
<reponame>gzaccaria/empower-runtime #!/usr/bin/env python3 # # Copyright (c) 2016 <NAME> # # 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. """UE measurements module.""" import uuid from construct import SBInt16 from construct import UBInt8 from construct import UBInt16 from construct import UBInt32 from construct import Bytes from construct import Container from construct import Struct from construct import Array from construct import BitStruct from construct import Padding from construct import Bit from empower.core.app import EmpowerApp from empower.core.ue import UE from empower.vbsp.vbspserver import ModuleVBSPWorker from empower.core.module import ModulePeriodic from empower.vbsp import E_TYPE_TRIG from empower.vbsp import EP_OPERATION_ADD from empower.vbsp import EP_OPERATION_REM from empower.main import RUNTIME EP_ACT_UE_MEASURE = 0x05 UE_MEAS_REQUEST = Struct("ue_meas_request", UBInt8("type"), UBInt8("version"), Bytes("enbid", 8), UBInt16("cellid"), UBInt32("xid"), BitStruct("flags", Padding(15), Bit("dir")), UBInt32("seq"), UBInt16("length"), UBInt16("action"), UBInt8("opcode"), UBInt8("meas_id"), UBInt16("rnti"), UBInt16("earfcn"), UBInt16("interval"), UBInt16("max_cells"), UBInt16("max_meas")) UE_MEAS_ENTRY = Struct("ue_meas_entries", UBInt8("meas_id"), UBInt16("pci"), SBInt16("rsrp"), SBInt16("rsrq")) UE_MEAS_RESPONSE = Struct("ue_meas_response", UBInt32("nof_meas"), Array(lambda ctx: ctx.nof_meas, UE_MEAS_ENTRY)) class UEMeasurements(ModulePeriodic): """ UEMurements object. """ MODULE_NAME = "ue_measurements" REQUIRED = ['module_type', 'worker', 'tenant_id', 'ue', 'measurements'] def __init__(self): super().__init__() # parameters self._ue = None self._measurements = {} # stats self.results = {} # set this for auto-cleanup self.vbs = None def __eq__(self, other): return super().__eq__(other) and self.ue == other.ue and \ self.measurements == other.measurements @property def measurements(self): """Return measurements.""" return self._measurements @measurements.setter def measurements(self, values): """Set measurements.""" self._measurements = {} for i, value in enumerate(values): self._measurements[i] = { "meas_id": i, "earfcn": int(value["earfcn"]), "interval": int(value["interval"]), "max_cells": int(value["max_cells"]), "max_meas": int(value["max_meas"]) } @property def ue(self): """Return the ue.""" return self._ue @ue.setter def ue(self, value): """Set UE.""" if isinstance(value, UE): self._ue = value elif isinstance(value, str): self._ue = RUNTIME.ues[uuid.UUID(str(value))] else: raise Exception("Invalid ue value %s" % value) def to_dict(self): """ Return a JSON-serializable.""" out = super().to_dict() out['ue'] = self.ue out['measurements'] = self.measurements out['results'] = self.results return out def run_once(self): """Send out rate request.""" if self.tenant_id not in RUNTIME.tenants: self.log.info("Tenant %s not found", self.tenant_id) self.unload() return tenant = RUNTIME.tenants[self.tenant_id] if self.ue.ue_id not in tenant.ues: self.log.info("UE %u not found", self.ue.ue_id) self.unload() return if not self.ue.vbs or not self.ue.vbs.is_online(): self.log.info("VBS %s not connected", self.ue.vbs.addr) self.unload() return # if the vbs did not change since last time then return if self.vbs == self.ue.vbs: return if self.vbs: for i in self.measurements: msg = Container(meas_id=i, rnti=0, earfcn=0, interval=0, max_cells=0, max_meas=0, length=UE_MEAS_REQUEST.sizeof()) self.vbs.connection.send_message(msg, E_TYPE_TRIG, EP_ACT_UE_MEASURE, UE_MEAS_REQUEST, cellid=self.ue.cell.pci, opcode=EP_OPERATION_REM, xid=self.module_id) self.results = {} self.vbs = self.ue.vbs for i in self.measurements: measurement = self.measurements[i] msg = Container(meas_id=i, rnti=self.ue.rnti, earfcn=measurement["earfcn"], interval=measurement["interval"], max_cells=measurement["max_cells"], max_meas=measurement["max_meas"], length=UE_MEAS_REQUEST.sizeof()) self.vbs.connection.send_message(msg, E_TYPE_TRIG, EP_ACT_UE_MEASURE, UE_MEAS_REQUEST, cellid=self.ue.cell.pci, opcode=EP_OPERATION_ADD, xid=self.module_id) def handle_response(self, response): """Handle an incoming UE_MEASUREMENTS message. Args: meas, a UE_MEASUREMENTS message Returns: None """ for entry in response.ue_meas_entries: # save measurements in this object if entry.meas_id not in self.results: self.results[entry.meas_id] = {} self.results[entry.meas_id][entry.pci] = { "meas_id": entry.meas_id, "pci": entry.pci, "rsrp": entry.rsrp, "rsrq": entry.rsrq } # check if this measurement refers to a cell that is in this tenant earfcn = self.measurements[entry.meas_id]["earfcn"] for vbs in RUNTIME.tenants[self.tenant_id].vbses.values(): for cell in vbs.cells.values(): if cell.pci == entry.pci and cell.dl_earfcn == earfcn: if vbs.addr not in self.ue.ue_measurements: self.ue.ue_measurements[vbs.addr] = {} cell.ue_measurements[self.ue.ue_id] = { "rsrp": entry.rsrp, "rsrq": entry.rsrq } self.ue.ue_measurements[vbs.addr][cell.pci] = { "rsrp": entry.rsrp, "rsrq": entry.rsrq } # call callback self.handle_callback(self) class UEMeasurementsWorker(ModuleVBSPWorker): """ Counter worker. """ pass def ue_measurements(**kwargs): """Create a new module.""" module = UEMeasurementsWorker.__module__ return RUNTIME.components[module].add_module(**kwargs) def bound_ue_measurements(self, **kwargs): """Create a new module (app version).""" kwargs['tenant_id'] = self.tenant.tenant_id return ue_measurements(**kwargs) setattr(EmpowerApp, UEMeasurements.MODULE_NAME, bound_ue_measurements) def launch(): """ Initialize the module. """ return UEMeasurementsWorker(UEMeasurements, EP_ACT_UE_MEASURE, UE_MEAS_RESPONSE)
#!/usr/bin/env python3 # # Copyright (c) 2016 <NAME> # # 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. """UE measurements module.""" import uuid from construct import SBInt16 from construct import UBInt8 from construct import UBInt16 from construct import UBInt32 from construct import Bytes from construct import Container from construct import Struct from construct import Array from construct import BitStruct from construct import Padding from construct import Bit from empower.core.app import EmpowerApp from empower.core.ue import UE from empower.vbsp.vbspserver import ModuleVBSPWorker from empower.core.module import ModulePeriodic from empower.vbsp import E_TYPE_TRIG from empower.vbsp import EP_OPERATION_ADD from empower.vbsp import EP_OPERATION_REM from empower.main import RUNTIME EP_ACT_UE_MEASURE = 0x05 UE_MEAS_REQUEST = Struct("ue_meas_request", UBInt8("type"), UBInt8("version"), Bytes("enbid", 8), UBInt16("cellid"), UBInt32("xid"), BitStruct("flags", Padding(15), Bit("dir")), UBInt32("seq"), UBInt16("length"), UBInt16("action"), UBInt8("opcode"), UBInt8("meas_id"), UBInt16("rnti"), UBInt16("earfcn"), UBInt16("interval"), UBInt16("max_cells"), UBInt16("max_meas")) UE_MEAS_ENTRY = Struct("ue_meas_entries", UBInt8("meas_id"), UBInt16("pci"), SBInt16("rsrp"), SBInt16("rsrq")) UE_MEAS_RESPONSE = Struct("ue_meas_response", UBInt32("nof_meas"), Array(lambda ctx: ctx.nof_meas, UE_MEAS_ENTRY)) class UEMeasurements(ModulePeriodic): """ UEMurements object. """ MODULE_NAME = "ue_measurements" REQUIRED = ['module_type', 'worker', 'tenant_id', 'ue', 'measurements'] def __init__(self): super().__init__() # parameters self._ue = None self._measurements = {} # stats self.results = {} # set this for auto-cleanup self.vbs = None def __eq__(self, other): return super().__eq__(other) and self.ue == other.ue and \ self.measurements == other.measurements @property def measurements(self): """Return measurements.""" return self._measurements @measurements.setter def measurements(self, values): """Set measurements.""" self._measurements = {} for i, value in enumerate(values): self._measurements[i] = { "meas_id": i, "earfcn": int(value["earfcn"]), "interval": int(value["interval"]), "max_cells": int(value["max_cells"]), "max_meas": int(value["max_meas"]) } @property def ue(self): """Return the ue.""" return self._ue @ue.setter def ue(self, value): """Set UE.""" if isinstance(value, UE): self._ue = value elif isinstance(value, str): self._ue = RUNTIME.ues[uuid.UUID(str(value))] else: raise Exception("Invalid ue value %s" % value) def to_dict(self): """ Return a JSON-serializable.""" out = super().to_dict() out['ue'] = self.ue out['measurements'] = self.measurements out['results'] = self.results return out def run_once(self): """Send out rate request.""" if self.tenant_id not in RUNTIME.tenants: self.log.info("Tenant %s not found", self.tenant_id) self.unload() return tenant = RUNTIME.tenants[self.tenant_id] if self.ue.ue_id not in tenant.ues: self.log.info("UE %u not found", self.ue.ue_id) self.unload() return if not self.ue.vbs or not self.ue.vbs.is_online(): self.log.info("VBS %s not connected", self.ue.vbs.addr) self.unload() return # if the vbs did not change since last time then return if self.vbs == self.ue.vbs: return if self.vbs: for i in self.measurements: msg = Container(meas_id=i, rnti=0, earfcn=0, interval=0, max_cells=0, max_meas=0, length=UE_MEAS_REQUEST.sizeof()) self.vbs.connection.send_message(msg, E_TYPE_TRIG, EP_ACT_UE_MEASURE, UE_MEAS_REQUEST, cellid=self.ue.cell.pci, opcode=EP_OPERATION_REM, xid=self.module_id) self.results = {} self.vbs = self.ue.vbs for i in self.measurements: measurement = self.measurements[i] msg = Container(meas_id=i, rnti=self.ue.rnti, earfcn=measurement["earfcn"], interval=measurement["interval"], max_cells=measurement["max_cells"], max_meas=measurement["max_meas"], length=UE_MEAS_REQUEST.sizeof()) self.vbs.connection.send_message(msg, E_TYPE_TRIG, EP_ACT_UE_MEASURE, UE_MEAS_REQUEST, cellid=self.ue.cell.pci, opcode=EP_OPERATION_ADD, xid=self.module_id) def handle_response(self, response): """Handle an incoming UE_MEASUREMENTS message. Args: meas, a UE_MEASUREMENTS message Returns: None """ for entry in response.ue_meas_entries: # save measurements in this object if entry.meas_id not in self.results: self.results[entry.meas_id] = {} self.results[entry.meas_id][entry.pci] = { "meas_id": entry.meas_id, "pci": entry.pci, "rsrp": entry.rsrp, "rsrq": entry.rsrq } # check if this measurement refers to a cell that is in this tenant earfcn = self.measurements[entry.meas_id]["earfcn"] for vbs in RUNTIME.tenants[self.tenant_id].vbses.values(): for cell in vbs.cells.values(): if cell.pci == entry.pci and cell.dl_earfcn == earfcn: if vbs.addr not in self.ue.ue_measurements: self.ue.ue_measurements[vbs.addr] = {} cell.ue_measurements[self.ue.ue_id] = { "rsrp": entry.rsrp, "rsrq": entry.rsrq } self.ue.ue_measurements[vbs.addr][cell.pci] = { "rsrp": entry.rsrp, "rsrq": entry.rsrq } # call callback self.handle_callback(self) class UEMeasurementsWorker(ModuleVBSPWorker): """ Counter worker. """ pass def ue_measurements(**kwargs): """Create a new module.""" module = UEMeasurementsWorker.__module__ return RUNTIME.components[module].add_module(**kwargs) def bound_ue_measurements(self, **kwargs): """Create a new module (app version).""" kwargs['tenant_id'] = self.tenant.tenant_id return ue_measurements(**kwargs) setattr(EmpowerApp, UEMeasurements.MODULE_NAME, bound_ue_measurements) def launch(): """ Initialize the module. """ return UEMeasurementsWorker(UEMeasurements, EP_ACT_UE_MEASURE, UE_MEAS_RESPONSE)
en
0.750651
#!/usr/bin/env python3 # # Copyright (c) 2016 <NAME> # # 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. UE measurements module. UEMurements object. # parameters # stats # set this for auto-cleanup Return measurements. Set measurements. Return the ue. Set UE. Return a JSON-serializable. Send out rate request. # if the vbs did not change since last time then return Handle an incoming UE_MEASUREMENTS message. Args: meas, a UE_MEASUREMENTS message Returns: None # save measurements in this object # check if this measurement refers to a cell that is in this tenant # call callback Counter worker. Create a new module. Create a new module (app version). Initialize the module.
1.507045
2
src/intervals/intervaln.py
yuanagain/seniorthesis
0
6622428
<filename>src/intervals/intervaln.py """ Defines a basic n-dimensional interval and implements basic operations on said intervals. Author: <NAME> Princeton University """ from __future__ import division from interval import interval, inf, imath import operator class IntervalN: def __init__(self, x = [interval([0, 0]), interval([0, 0]), interval([0, 0]), interval([0, 0])]): """ Create defensive copy """ self.x = [interval(intvl) for intvl in x] def clone(self): """ Returns a clone of this interval """ return IntervalN([interval(intvl) for intvl in self.x ]) def midpoint(self): """ Returns the midpoint of the hypercube """ return IntervalN([intvl.midpoint for intvl in self.x ]) def isZero(self): """ Returns whether or not this interval is zero """ zero = interval([0]) is_zero = [intvl == zero for intvl in self.x] return sum(is_zero) == 0 def __contains__(self, other): for i in range(len(self.x)): if other.x[i] not in self.x[i]: return False return True def hull(self): """ Returns convex hull """ return IntervalN( [intvl.hull([intvl]) for intvl in self.x] ) def __add__(self, other): """ Adds two hypercubes """ return IntervalN( list(map(operator.sub, self.x, other.x)) ) def __mul__(self, other): """ Multiplies two hypercubes """ if type(other) == IntervalN: raise TypeError("IntervalN cannot multiply with IntervalN") return IntervalN( [intvl * other for intvl in self.x ] ) def __truediv__(self, other): """ Returns quotients of two hypercubes TODO: test more thoroughly """ if type(other) == IntervalN: raise TypeError("IntervalN cannot multiply with IntervalN") return IntervalN( [intvl / other for intvl in self.x ] ) #return IntervalN( list(map(operator.truediv, self.x, other.x)) ) def __sub__(self, other): """ Subtracts other from self """ return self.__add__(-other) def __neg__(self): """ Returns negation of interval """ return IntervalN([-intvl for intvl in self.x ]) def __str__(self): """ Returns string representation of complex interval """ return "IntervalN(" + str(self.x) + ")" def __eq__(self, other): """ Checks for equality between intervals """ is_nequal = [self.x[i] != other.x[i] for i in range(len(self.x)) ] return sum(is_nequal) == 0 def __ne__(self, other): """ Checks for equality between intervals """ return self.__eq__(other) == False ## Functions for generating copies of identities def _scalar(k = 0.0, dim = 4): """ Returns a complex interval representing zero """ return IntervalN( [interval([k]) for i in range(dim) ] ) def main(): print("Testing IntervalN") xa = interval([1, 2]) xb = interval([5, 6]) xc = interval([-2, 4]) xd = interval([-2, -9]) x = IntervalN([xa, xb, xc, xd]) x_clone = IntervalN([xa, xb, xc, xd]) x_clone2 = x.clone() ya = interval([10, 2]) yb = interval([52, 61]) yc = interval([-22, 41]) yd = interval([-34, -10]) y = IntervalN([ya, yb, yc, yd]) print("============================") print("Construction") print("----------------------------") print('x = ' + x.__str__()) print('y = ' + y.__str__()) print("============================") print("Comparisons") print("----------------------------") print(x_clone2 == x_clone) print(x_clone2 != x_clone) print(x_clone2 == y) print(x_clone2 != y) print(_scalar(7)) print(x * 4) print(x in y) print(x in x * 4) print(x in x * interval([0.999, 1.001])) print("============================") print("Operations") print("----------------------------") print(x + y) print(x - y) print(x * -2.1) print(x / 2) print(x.hull()) if __name__=="__main__": main()
<filename>src/intervals/intervaln.py """ Defines a basic n-dimensional interval and implements basic operations on said intervals. Author: <NAME> Princeton University """ from __future__ import division from interval import interval, inf, imath import operator class IntervalN: def __init__(self, x = [interval([0, 0]), interval([0, 0]), interval([0, 0]), interval([0, 0])]): """ Create defensive copy """ self.x = [interval(intvl) for intvl in x] def clone(self): """ Returns a clone of this interval """ return IntervalN([interval(intvl) for intvl in self.x ]) def midpoint(self): """ Returns the midpoint of the hypercube """ return IntervalN([intvl.midpoint for intvl in self.x ]) def isZero(self): """ Returns whether or not this interval is zero """ zero = interval([0]) is_zero = [intvl == zero for intvl in self.x] return sum(is_zero) == 0 def __contains__(self, other): for i in range(len(self.x)): if other.x[i] not in self.x[i]: return False return True def hull(self): """ Returns convex hull """ return IntervalN( [intvl.hull([intvl]) for intvl in self.x] ) def __add__(self, other): """ Adds two hypercubes """ return IntervalN( list(map(operator.sub, self.x, other.x)) ) def __mul__(self, other): """ Multiplies two hypercubes """ if type(other) == IntervalN: raise TypeError("IntervalN cannot multiply with IntervalN") return IntervalN( [intvl * other for intvl in self.x ] ) def __truediv__(self, other): """ Returns quotients of two hypercubes TODO: test more thoroughly """ if type(other) == IntervalN: raise TypeError("IntervalN cannot multiply with IntervalN") return IntervalN( [intvl / other for intvl in self.x ] ) #return IntervalN( list(map(operator.truediv, self.x, other.x)) ) def __sub__(self, other): """ Subtracts other from self """ return self.__add__(-other) def __neg__(self): """ Returns negation of interval """ return IntervalN([-intvl for intvl in self.x ]) def __str__(self): """ Returns string representation of complex interval """ return "IntervalN(" + str(self.x) + ")" def __eq__(self, other): """ Checks for equality between intervals """ is_nequal = [self.x[i] != other.x[i] for i in range(len(self.x)) ] return sum(is_nequal) == 0 def __ne__(self, other): """ Checks for equality between intervals """ return self.__eq__(other) == False ## Functions for generating copies of identities def _scalar(k = 0.0, dim = 4): """ Returns a complex interval representing zero """ return IntervalN( [interval([k]) for i in range(dim) ] ) def main(): print("Testing IntervalN") xa = interval([1, 2]) xb = interval([5, 6]) xc = interval([-2, 4]) xd = interval([-2, -9]) x = IntervalN([xa, xb, xc, xd]) x_clone = IntervalN([xa, xb, xc, xd]) x_clone2 = x.clone() ya = interval([10, 2]) yb = interval([52, 61]) yc = interval([-22, 41]) yd = interval([-34, -10]) y = IntervalN([ya, yb, yc, yd]) print("============================") print("Construction") print("----------------------------") print('x = ' + x.__str__()) print('y = ' + y.__str__()) print("============================") print("Comparisons") print("----------------------------") print(x_clone2 == x_clone) print(x_clone2 != x_clone) print(x_clone2 == y) print(x_clone2 != y) print(_scalar(7)) print(x * 4) print(x in y) print(x in x * 4) print(x in x * interval([0.999, 1.001])) print("============================") print("Operations") print("----------------------------") print(x + y) print(x - y) print(x * -2.1) print(x / 2) print(x.hull()) if __name__=="__main__": main()
en
0.716059
Defines a basic n-dimensional interval and implements basic operations on said intervals. Author: <NAME> Princeton University Create defensive copy Returns a clone of this interval Returns the midpoint of the hypercube Returns whether or not this interval is zero Returns convex hull Adds two hypercubes Multiplies two hypercubes Returns quotients of two hypercubes TODO: test more thoroughly #return IntervalN( list(map(operator.truediv, self.x, other.x)) ) Subtracts other from self Returns negation of interval Returns string representation of complex interval Checks for equality between intervals Checks for equality between intervals ## Functions for generating copies of identities Returns a complex interval representing zero
3.680801
4
Programas_Capitulo_06/Cap06_pagina_147_leer_datos_teclado.py
rojassergio/Aprendiendo-a-programar-en-Python-con-mi-computador
17
6622429
# -*- coding: utf-8 -*- ''' @author: <NAME> @contact: <EMAIL> -------------------------- Contenido bajo Atribución-NoComercial-CompartirIgual 3.0 Venezuela (CC BY-NC-SA 3.0 VE) http://creativecommons.org/licenses/by-nc-sa/3.0/ve/ Creado en abril 23, 2016 ''' def myinput(): """ Esta función permite leer datos desde el teclado sin ocuparnos de estar usando python 2 o python 3 """ import sys if sys.version[0]=="2": a = raw_input('\t Escriba la respuesta y presione ENTER/RETURN:--> : ') elif sys.version[0]=="3": a = input('\t Escriba la respuesta y presione ENTER/RETURN:--> : ') return a print('\n Ingresa tu nombre: ') nombre = myinput() print('\n Ingresa tu edad, {0:s}:'.format(nombre)) edad = int(myinput()) print('\n Ingresa tu estatura en metros, {0:s}:'.format(nombre)) altura = int(myinput()) print('\n Ingresa tu peso en kilogramos, {0:s}:'.format(nombre)) peso = int(myinput()) str1 = '\n {0:s} de {1:d} años, tiene la'.format(nombre, edad) str2 = 'estatura de {0:d} m y pesa {1:d} kgs.\n'.format(altura, peso) print(' *** {0:s} {1:s} *** '.format(str1, str2))
# -*- coding: utf-8 -*- ''' @author: <NAME> @contact: <EMAIL> -------------------------- Contenido bajo Atribución-NoComercial-CompartirIgual 3.0 Venezuela (CC BY-NC-SA 3.0 VE) http://creativecommons.org/licenses/by-nc-sa/3.0/ve/ Creado en abril 23, 2016 ''' def myinput(): """ Esta función permite leer datos desde el teclado sin ocuparnos de estar usando python 2 o python 3 """ import sys if sys.version[0]=="2": a = raw_input('\t Escriba la respuesta y presione ENTER/RETURN:--> : ') elif sys.version[0]=="3": a = input('\t Escriba la respuesta y presione ENTER/RETURN:--> : ') return a print('\n Ingresa tu nombre: ') nombre = myinput() print('\n Ingresa tu edad, {0:s}:'.format(nombre)) edad = int(myinput()) print('\n Ingresa tu estatura en metros, {0:s}:'.format(nombre)) altura = int(myinput()) print('\n Ingresa tu peso en kilogramos, {0:s}:'.format(nombre)) peso = int(myinput()) str1 = '\n {0:s} de {1:d} años, tiene la'.format(nombre, edad) str2 = 'estatura de {0:d} m y pesa {1:d} kgs.\n'.format(altura, peso) print(' *** {0:s} {1:s} *** '.format(str1, str2))
es
0.642887
# -*- coding: utf-8 -*- @author: <NAME> @contact: <EMAIL> -------------------------- Contenido bajo Atribución-NoComercial-CompartirIgual 3.0 Venezuela (CC BY-NC-SA 3.0 VE) http://creativecommons.org/licenses/by-nc-sa/3.0/ve/ Creado en abril 23, 2016 Esta función permite leer datos desde el teclado sin ocuparnos de estar usando python 2 o python 3
3.947926
4
client/minio.py
jupadhya1/Odometry_Signal_Anomaly
0
6622430
<reponame>jupadhya1/Odometry_Signal_Anomaly import logging import pickle import json from io import BytesIO, StringIO from typing import Union, Dict, List import pandas as pd from minio import Minio from minio.error import MinioException class MinioClient(Minio): """ A minio client adding extra features in existing minio client Parameters ---------- Minio ([type]): the actual client """ def create_bucket_if_not_exist(self, bucket_name: str): """ check if bucket exists otherwise create it Parameters ---------- bucket_name (str): name of bucket (s3 bucket) """ if not self.bucket_exists(bucket_name): self.make_bucket(bucket_name) def write_df_to_minio(self, df: pd.DataFrame, bucket_name: str, outname: str): """ writes pandas dataframe to minio bucket with given object path Parameters ---------- df (pd.DataFrame): pandas dataframe bucket_name (str): name of bucket (s3 bucket) outname (str): bucket object path (with file .csv) to which file should be saved """ logging.info( f"writing dataframe to {outname} in minio bucket {bucket_name}") csv_bytes = df.to_csv().encode('utf-8') csv_buffer = BytesIO(csv_bytes) self.create_bucket_if_not_exist(bucket_name) self.put_object(bucket_name, outname, data=csv_buffer, length=len(csv_bytes), content_type='application/csv') logging.info( f"Dump dataframe to minio bucket {bucket_name} as {outname}") def write_dict_to_minio(self, dict_obj: Dict, bucket_name: str, outname: str): """ writes dictionary to minio bucket with given object path as json object Parameters ---------- dict_obj (Dict): python dicitonary bucket_name (str): name of bucket (s3 bucket) outname (str): bucket object path (with file .json) to which file should be saved """ logging.info( f"writing json to {outname} in minio bucket {bucket_name}") json_bytes = json.dumps(dict_obj).encode('utf-8') json_buffer = BytesIO(json_bytes) self.create_bucket_if_not_exist(bucket_name) self.put_object(bucket_name, outname, data=json_buffer, length=len(json_bytes), content_type='application/json') logging.info( f"Dump json to minio bucket {bucket_name} as {outname}") def write_df_as_xls(self, df: pd.DataFrame, bucket_name: str, outname: str): """write dataframe to minio bucket as xls file Parameters ---------- df (pd.DataFrame): pandas dataframe bucket_name (str): name of bucket (s3 bucket) outname (str): bucket object path (with file .xls) to which file should be saved """ logging.info( f"writing dataframe to {outname} in minio bucket {bucket_name}") csv_bytes = df.to_csv(index=False).encode('utf-8') csv_buffer = BytesIO(csv_bytes) self.create_bucket_if_not_exist(bucket_name) self.put_object(bucket_name, outname, data=csv_buffer, length=len(csv_bytes), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') logging.info( f"Dump dataframe to minio bucket {bucket_name} as {outname}") def save_event_to_minio(self, df: pd.DataFrame, metadata, outname: str, bucket_name: str): """save pickel object to minio bucket Parameters ---------- df (pd.DataFrame): pandas dataframe metadata ([type]): metadata which to be saved outname (str): bucket object path (with file .pkl) to which file should be saved bucket_name (str): name of bucket (s3 bucket) """ logging.info( f"writing event dataframe as pickle object to {outname} in minio bucket {bucket_name}") pickle_byte_obj = pickle.dumps({"data": df, "metadata": metadata}) self.create_bucket_if_not_exist(bucket_name) self.put_object(bucket_name, outname, data=BytesIO(pickle_byte_obj), length=len(pickle_byte_obj)) logging.info( f"Dump event dataframe as pickle to minio bucket {bucket_name} as {outname}") def get_bytes_data(self, bucket_name: str, filename: str): """read data as bytes from minio bucket Parameters ---------- bucket_name (str): name of bucket (s3 bucket) filename (str): bucket object path (with any extension e.g .csv, .xls, .pkl) Returns: bytes: data as bytes """ try: logging.info(f"Getting {filename} from minio bucket {bucket_name}") data = self.get_object(bucket_name, filename) except: logging.error( f"Failed to Getting {filename} from minio bucket {bucket_name}") raise MinioException data = data.read() bytes_data = BytesIO(data) return bytes_data def get_dataframe(self, bucket_name: str, filename: str, index_col: Union[str, bool, int] = None): """Read files from bucket as dataframe Parameters ---------- bucket_name (str): name of bucket (s3 bucket) filename (str): bucket object path (with any extension e.g .csv, .xls, .pkl) index_col (Union[str, bool, int], optional): Column name or column index to place that column as a index. Defaults to None. Returns: pd.DataFrame: dataframe after reading from minio bucket """ bytes_data = self.get_bytes_data(bucket_name, filename) df = pd.read_csv(bytes_data, index_col=index_col) logging.info( f"Successfully got {filename} as dataframe from minio bucket {bucket_name}") return df def get_pickle(self, bucket_name: str, filename: str): """Read files from bucket as pickle object Parameters ---------- bucket_name (str): name of bucket (s3 bucket) filename (str): bucket object path (with extension .pkl) Returns: pickel: data as pickle object """ bytes_data = self.get_bytes_data(bucket_name, filename) pkl_data = pickle.load(bytes_data)["data"] logging.info( f"Successfully got {filename} as pickel from minio bucket {bucket_name}") return pkl_data def get_dict(self, bucket_name: str, filename: str): """Read files from bucket as dict Parameters ---------- bucket_name (str): name of bucket (s3 bucket) filename (str): bucket object path (with extension .json) Returns: ---------- pickel: data as dict object """ bytes_data = self.get_bytes_data(bucket_name, filename) data = json.load(bytes_data) logging.info( f"Successfully got {filename} as dict from minio bucket {bucket_name}") return data
import logging import pickle import json from io import BytesIO, StringIO from typing import Union, Dict, List import pandas as pd from minio import Minio from minio.error import MinioException class MinioClient(Minio): """ A minio client adding extra features in existing minio client Parameters ---------- Minio ([type]): the actual client """ def create_bucket_if_not_exist(self, bucket_name: str): """ check if bucket exists otherwise create it Parameters ---------- bucket_name (str): name of bucket (s3 bucket) """ if not self.bucket_exists(bucket_name): self.make_bucket(bucket_name) def write_df_to_minio(self, df: pd.DataFrame, bucket_name: str, outname: str): """ writes pandas dataframe to minio bucket with given object path Parameters ---------- df (pd.DataFrame): pandas dataframe bucket_name (str): name of bucket (s3 bucket) outname (str): bucket object path (with file .csv) to which file should be saved """ logging.info( f"writing dataframe to {outname} in minio bucket {bucket_name}") csv_bytes = df.to_csv().encode('utf-8') csv_buffer = BytesIO(csv_bytes) self.create_bucket_if_not_exist(bucket_name) self.put_object(bucket_name, outname, data=csv_buffer, length=len(csv_bytes), content_type='application/csv') logging.info( f"Dump dataframe to minio bucket {bucket_name} as {outname}") def write_dict_to_minio(self, dict_obj: Dict, bucket_name: str, outname: str): """ writes dictionary to minio bucket with given object path as json object Parameters ---------- dict_obj (Dict): python dicitonary bucket_name (str): name of bucket (s3 bucket) outname (str): bucket object path (with file .json) to which file should be saved """ logging.info( f"writing json to {outname} in minio bucket {bucket_name}") json_bytes = json.dumps(dict_obj).encode('utf-8') json_buffer = BytesIO(json_bytes) self.create_bucket_if_not_exist(bucket_name) self.put_object(bucket_name, outname, data=json_buffer, length=len(json_bytes), content_type='application/json') logging.info( f"Dump json to minio bucket {bucket_name} as {outname}") def write_df_as_xls(self, df: pd.DataFrame, bucket_name: str, outname: str): """write dataframe to minio bucket as xls file Parameters ---------- df (pd.DataFrame): pandas dataframe bucket_name (str): name of bucket (s3 bucket) outname (str): bucket object path (with file .xls) to which file should be saved """ logging.info( f"writing dataframe to {outname} in minio bucket {bucket_name}") csv_bytes = df.to_csv(index=False).encode('utf-8') csv_buffer = BytesIO(csv_bytes) self.create_bucket_if_not_exist(bucket_name) self.put_object(bucket_name, outname, data=csv_buffer, length=len(csv_bytes), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') logging.info( f"Dump dataframe to minio bucket {bucket_name} as {outname}") def save_event_to_minio(self, df: pd.DataFrame, metadata, outname: str, bucket_name: str): """save pickel object to minio bucket Parameters ---------- df (pd.DataFrame): pandas dataframe metadata ([type]): metadata which to be saved outname (str): bucket object path (with file .pkl) to which file should be saved bucket_name (str): name of bucket (s3 bucket) """ logging.info( f"writing event dataframe as pickle object to {outname} in minio bucket {bucket_name}") pickle_byte_obj = pickle.dumps({"data": df, "metadata": metadata}) self.create_bucket_if_not_exist(bucket_name) self.put_object(bucket_name, outname, data=BytesIO(pickle_byte_obj), length=len(pickle_byte_obj)) logging.info( f"Dump event dataframe as pickle to minio bucket {bucket_name} as {outname}") def get_bytes_data(self, bucket_name: str, filename: str): """read data as bytes from minio bucket Parameters ---------- bucket_name (str): name of bucket (s3 bucket) filename (str): bucket object path (with any extension e.g .csv, .xls, .pkl) Returns: bytes: data as bytes """ try: logging.info(f"Getting {filename} from minio bucket {bucket_name}") data = self.get_object(bucket_name, filename) except: logging.error( f"Failed to Getting {filename} from minio bucket {bucket_name}") raise MinioException data = data.read() bytes_data = BytesIO(data) return bytes_data def get_dataframe(self, bucket_name: str, filename: str, index_col: Union[str, bool, int] = None): """Read files from bucket as dataframe Parameters ---------- bucket_name (str): name of bucket (s3 bucket) filename (str): bucket object path (with any extension e.g .csv, .xls, .pkl) index_col (Union[str, bool, int], optional): Column name or column index to place that column as a index. Defaults to None. Returns: pd.DataFrame: dataframe after reading from minio bucket """ bytes_data = self.get_bytes_data(bucket_name, filename) df = pd.read_csv(bytes_data, index_col=index_col) logging.info( f"Successfully got {filename} as dataframe from minio bucket {bucket_name}") return df def get_pickle(self, bucket_name: str, filename: str): """Read files from bucket as pickle object Parameters ---------- bucket_name (str): name of bucket (s3 bucket) filename (str): bucket object path (with extension .pkl) Returns: pickel: data as pickle object """ bytes_data = self.get_bytes_data(bucket_name, filename) pkl_data = pickle.load(bytes_data)["data"] logging.info( f"Successfully got {filename} as pickel from minio bucket {bucket_name}") return pkl_data def get_dict(self, bucket_name: str, filename: str): """Read files from bucket as dict Parameters ---------- bucket_name (str): name of bucket (s3 bucket) filename (str): bucket object path (with extension .json) Returns: ---------- pickel: data as dict object """ bytes_data = self.get_bytes_data(bucket_name, filename) data = json.load(bytes_data) logging.info( f"Successfully got {filename} as dict from minio bucket {bucket_name}") return data
en
0.729478
A minio client adding extra features in existing minio client Parameters ---------- Minio ([type]): the actual client check if bucket exists otherwise create it Parameters ---------- bucket_name (str): name of bucket (s3 bucket) writes pandas dataframe to minio bucket with given object path Parameters ---------- df (pd.DataFrame): pandas dataframe bucket_name (str): name of bucket (s3 bucket) outname (str): bucket object path (with file .csv) to which file should be saved writes dictionary to minio bucket with given object path as json object Parameters ---------- dict_obj (Dict): python dicitonary bucket_name (str): name of bucket (s3 bucket) outname (str): bucket object path (with file .json) to which file should be saved write dataframe to minio bucket as xls file Parameters ---------- df (pd.DataFrame): pandas dataframe bucket_name (str): name of bucket (s3 bucket) outname (str): bucket object path (with file .xls) to which file should be saved save pickel object to minio bucket Parameters ---------- df (pd.DataFrame): pandas dataframe metadata ([type]): metadata which to be saved outname (str): bucket object path (with file .pkl) to which file should be saved bucket_name (str): name of bucket (s3 bucket) read data as bytes from minio bucket Parameters ---------- bucket_name (str): name of bucket (s3 bucket) filename (str): bucket object path (with any extension e.g .csv, .xls, .pkl) Returns: bytes: data as bytes Read files from bucket as dataframe Parameters ---------- bucket_name (str): name of bucket (s3 bucket) filename (str): bucket object path (with any extension e.g .csv, .xls, .pkl) index_col (Union[str, bool, int], optional): Column name or column index to place that column as a index. Defaults to None. Returns: pd.DataFrame: dataframe after reading from minio bucket Read files from bucket as pickle object Parameters ---------- bucket_name (str): name of bucket (s3 bucket) filename (str): bucket object path (with extension .pkl) Returns: pickel: data as pickle object Read files from bucket as dict Parameters ---------- bucket_name (str): name of bucket (s3 bucket) filename (str): bucket object path (with extension .json) Returns: ---------- pickel: data as dict object
2.63578
3
python/rbf/writer/htmlwriter.py
dandyvica/rbf
0
6622431
import os import sys from rbf.field import Field from rbf.record import Record #from rbf.config import settings """ set of methods used to print out record data as an HTML file """ class HtmlWriter: """ create a new HTML writer object :param output: text file name for output :type output: str :example: :: htmlwriter = HtmlWriter("myfile.html") """ def __init__(self, output): self._fh = open(output, "w") self._fh.write(r'<html><head><link href="{0}" rel="stylesheet" type="text/css"></head><body>'.format(settings.css)) #settings.logger.info("creating output file {0}".format(output)) def write(self, rec, description=False, cssclass="header1"): """ write a record as an HTML table :param rec: record object :type rec: a Record object :param description: True if field description is printed in the HTML table :type description: str :example: :: writer.write(rec) """ self._fh.write("<h2>{0} - {1}</h2>".format(rec.name, rec.description)) self._fh.write("<table>") self._fh.write("<tr>" + "".join(["<th class=\""+cssclass+"\">"+f.name+"</th>" for f in rec]) + "</tr>\n") if description: self._fh.write("<tr>" + "".join(["<td>"+f.description+"</td>" for f in rec]) + "</tr>\n") self._fh.write("<tr>" + "".join(["<td><pre>"+f.raw_value+"</pre></td>" for f in rec]) + "</tr>\n") self._fh.write("</table><br>") def close(self): self._fh.write("</body></html>\n") self._fh.close()
import os import sys from rbf.field import Field from rbf.record import Record #from rbf.config import settings """ set of methods used to print out record data as an HTML file """ class HtmlWriter: """ create a new HTML writer object :param output: text file name for output :type output: str :example: :: htmlwriter = HtmlWriter("myfile.html") """ def __init__(self, output): self._fh = open(output, "w") self._fh.write(r'<html><head><link href="{0}" rel="stylesheet" type="text/css"></head><body>'.format(settings.css)) #settings.logger.info("creating output file {0}".format(output)) def write(self, rec, description=False, cssclass="header1"): """ write a record as an HTML table :param rec: record object :type rec: a Record object :param description: True if field description is printed in the HTML table :type description: str :example: :: writer.write(rec) """ self._fh.write("<h2>{0} - {1}</h2>".format(rec.name, rec.description)) self._fh.write("<table>") self._fh.write("<tr>" + "".join(["<th class=\""+cssclass+"\">"+f.name+"</th>" for f in rec]) + "</tr>\n") if description: self._fh.write("<tr>" + "".join(["<td>"+f.description+"</td>" for f in rec]) + "</tr>\n") self._fh.write("<tr>" + "".join(["<td><pre>"+f.raw_value+"</pre></td>" for f in rec]) + "</tr>\n") self._fh.write("</table><br>") def close(self): self._fh.write("</body></html>\n") self._fh.close()
en
0.581668
#from rbf.config import settings set of methods used to print out record data as an HTML file create a new HTML writer object :param output: text file name for output :type output: str :example: :: htmlwriter = HtmlWriter("myfile.html") #settings.logger.info("creating output file {0}".format(output)) write a record as an HTML table :param rec: record object :type rec: a Record object :param description: True if field description is printed in the HTML table :type description: str :example: :: writer.write(rec)
3.026021
3
Examples/More/Stream/in_stream_with_non_looping_out_stream.py
iconservo/labjack-ljm
0
6622432
<reponame>iconservo/labjack-ljm """ Demonstrates setting up stream-in with stream-out that continuously updates. Streams in while streaming out arbitrary values. These arbitrary stream-out values act on DAC0 to alternate between increasing the voltage from 0 to 2.5 and decreasing from 5.0 to 2.5 on (approximately). Though these values are initially generated during the call to create_out_context, the values could be dynamically generated, read from a file, etc. To convert this example file into a program to suit your needs, the primary things you need to do are: 1. Edit the global setup variables in this file 2. Define your own create_out_context function or equivalent 3. Define your own process_stream_results function or equivalent You may also need to configure AIN, etc. """ import sys from labjack import ljm import ljm_stream_util # Setup IN_NAMES = ["AIN0", "AIN1"] """ STREAM_OUTS = [ { "target": str register name that stream-out values will be sent to, "buffer_num_bytes": int size in bytes for this stream-out buffer, "stream_out_index": int STREAM_OUT# offset. 0 would generate names like "STREAM_OUT0_BUFFER_STATUS", etc. "set_loop": int value to be written to STREAM_OUT#(0:3)_SET_LOOP }, ... ] """ STREAM_OUTS = [ { "target": "DAC0", "buffer_num_bytes": 512, "stream_out_index": 0, "set_loop": 2 }, { "target": "DAC1", "buffer_num_bytes": 512, "stream_out_index": 1, "set_loop": 3 } ] INITIAL_SCAN_RATE_HZ = 200 # Note: This program does not work well for large scan rates because # the value loops will start looping before new value loops can be written. # While testing on USB with 512 bytes in one stream-out buffer, 2000 Hz worked # without stream-out buffer loop repeating. # (Other machines may have different results.) # Increasing the size of the buffer_num_bytes will increase the maximum speed. # Using an Ethernet connection type will increase the maximum speed. NUM_CYCLES = INITIAL_SCAN_RATE_HZ / 10 NUM_CYCLES_MIN = 10 if NUM_CYCLES < NUM_CYCLES_MIN: NUM_CYCLES = NUM_CYCLES_MIN def print_register_value(handle, register_name): value = ljm.eReadName(handle, register_name) print("%s = %f" % (register_name, value)) def open_ljm_device(device_type, connection_type, identifier): try: handle = ljm.open(device_type, connection_type, identifier) except ljm.LJMError: print( "Error calling ljm.open(" + "device_type=" + str(device_type) + ", " + "connection_type=" + str(connection_type) + ", " + "identifier=" + identifier + ")" ) raise return handle def print_device_info(handle): info = ljm.getHandleInfo(handle) print( "Opened a LabJack with Device type: %i, Connection type: %i,\n" "Serial number: %i, IP address: %s, Port: %i,\nMax bytes per MB: %i\n" % (info[0], info[1], info[2], ljm.numberToIP(info[3]), info[4], info[5]) ) def main( initial_scan_rate_hz=INITIAL_SCAN_RATE_HZ, in_names=IN_NAMES, stream_outs=STREAM_OUTS, num_cycles=NUM_CYCLES ): print("Beginning...") handle = open_ljm_device(ljm.constants.dtANY, ljm.constants.ctANY, "ANY") print_device_info(handle) print("Initializing stream out buffers...") out_contexts = [] for stream_out in stream_outs: out_context = ljm_stream_util.create_out_context(stream_out) ljm_stream_util.initialize_stream_out(handle, out_context) out_contexts.append(out_context) print("") for out_context in out_contexts: print_register_value(handle, out_context["names"]["buffer_status"]) for out_context in out_contexts: update_str = "Updating %(stream_out)s buffer whenever " \ "%(buffer_status)s is greater or equal to " % out_context["names"] print(update_str + str(out_context["state_size"])) scans_per_read = int(min([context["state_size"] for context in out_contexts])) buffer_status_names = [out["names"]["buffer_status"] for out in out_contexts] try: scan_list = ljm_stream_util.create_scan_list( in_names=in_names, out_contexts=out_contexts ) print("scan_list: " + str(scan_list)) print("scans_per_read: " + str(scans_per_read)) scan_rate = ljm.eStreamStart(handle, scans_per_read, len(scan_list), scan_list, initial_scan_rate_hz) print("\nStream started with a scan rate of %0.0f Hz." % scan_rate) print("\nPerforming %i buffer updates." % num_cycles) iteration = 0 total_num_skipped_scans = 0 while iteration < num_cycles: buffer_statuses = [0] infinity_preventer = 0 while max(buffer_statuses) < out_context["state_size"]: buffer_statuses = ljm.eReadNames( handle, len(buffer_status_names), buffer_status_names ) infinity_preventer = infinity_preventer + 1 if infinity_preventer > scan_rate: raise ValueError( "Buffer statuses don't appear to be updating:" + str(buffer_status_names) + str(buffer_statuses) ) for out_context in out_contexts: ljm_stream_util.update_stream_out_buffer(handle, out_context) # ljm.eStreamRead will sleep until data has arrived stream_read = ljm.eStreamRead(handle) num_skipped_scans = ljm_stream_util.process_stream_results( iteration, stream_read, in_names, device_threshold=out_context["state_size"], ljm_threshold=out_context["state_size"] ) total_num_skipped_scans += num_skipped_scans iteration = iteration + 1 except ljm.LJMError: ljm_stream_util.prepare_for_exit(handle) raise except Exception: ljm_stream_util.prepare_for_exit(handle) raise ljm_stream_util.prepare_for_exit(handle) print("Total number of skipped scans: %d" % total_num_skipped_scans) if __name__ == "__main__": main()
""" Demonstrates setting up stream-in with stream-out that continuously updates. Streams in while streaming out arbitrary values. These arbitrary stream-out values act on DAC0 to alternate between increasing the voltage from 0 to 2.5 and decreasing from 5.0 to 2.5 on (approximately). Though these values are initially generated during the call to create_out_context, the values could be dynamically generated, read from a file, etc. To convert this example file into a program to suit your needs, the primary things you need to do are: 1. Edit the global setup variables in this file 2. Define your own create_out_context function or equivalent 3. Define your own process_stream_results function or equivalent You may also need to configure AIN, etc. """ import sys from labjack import ljm import ljm_stream_util # Setup IN_NAMES = ["AIN0", "AIN1"] """ STREAM_OUTS = [ { "target": str register name that stream-out values will be sent to, "buffer_num_bytes": int size in bytes for this stream-out buffer, "stream_out_index": int STREAM_OUT# offset. 0 would generate names like "STREAM_OUT0_BUFFER_STATUS", etc. "set_loop": int value to be written to STREAM_OUT#(0:3)_SET_LOOP }, ... ] """ STREAM_OUTS = [ { "target": "DAC0", "buffer_num_bytes": 512, "stream_out_index": 0, "set_loop": 2 }, { "target": "DAC1", "buffer_num_bytes": 512, "stream_out_index": 1, "set_loop": 3 } ] INITIAL_SCAN_RATE_HZ = 200 # Note: This program does not work well for large scan rates because # the value loops will start looping before new value loops can be written. # While testing on USB with 512 bytes in one stream-out buffer, 2000 Hz worked # without stream-out buffer loop repeating. # (Other machines may have different results.) # Increasing the size of the buffer_num_bytes will increase the maximum speed. # Using an Ethernet connection type will increase the maximum speed. NUM_CYCLES = INITIAL_SCAN_RATE_HZ / 10 NUM_CYCLES_MIN = 10 if NUM_CYCLES < NUM_CYCLES_MIN: NUM_CYCLES = NUM_CYCLES_MIN def print_register_value(handle, register_name): value = ljm.eReadName(handle, register_name) print("%s = %f" % (register_name, value)) def open_ljm_device(device_type, connection_type, identifier): try: handle = ljm.open(device_type, connection_type, identifier) except ljm.LJMError: print( "Error calling ljm.open(" + "device_type=" + str(device_type) + ", " + "connection_type=" + str(connection_type) + ", " + "identifier=" + identifier + ")" ) raise return handle def print_device_info(handle): info = ljm.getHandleInfo(handle) print( "Opened a LabJack with Device type: %i, Connection type: %i,\n" "Serial number: %i, IP address: %s, Port: %i,\nMax bytes per MB: %i\n" % (info[0], info[1], info[2], ljm.numberToIP(info[3]), info[4], info[5]) ) def main( initial_scan_rate_hz=INITIAL_SCAN_RATE_HZ, in_names=IN_NAMES, stream_outs=STREAM_OUTS, num_cycles=NUM_CYCLES ): print("Beginning...") handle = open_ljm_device(ljm.constants.dtANY, ljm.constants.ctANY, "ANY") print_device_info(handle) print("Initializing stream out buffers...") out_contexts = [] for stream_out in stream_outs: out_context = ljm_stream_util.create_out_context(stream_out) ljm_stream_util.initialize_stream_out(handle, out_context) out_contexts.append(out_context) print("") for out_context in out_contexts: print_register_value(handle, out_context["names"]["buffer_status"]) for out_context in out_contexts: update_str = "Updating %(stream_out)s buffer whenever " \ "%(buffer_status)s is greater or equal to " % out_context["names"] print(update_str + str(out_context["state_size"])) scans_per_read = int(min([context["state_size"] for context in out_contexts])) buffer_status_names = [out["names"]["buffer_status"] for out in out_contexts] try: scan_list = ljm_stream_util.create_scan_list( in_names=in_names, out_contexts=out_contexts ) print("scan_list: " + str(scan_list)) print("scans_per_read: " + str(scans_per_read)) scan_rate = ljm.eStreamStart(handle, scans_per_read, len(scan_list), scan_list, initial_scan_rate_hz) print("\nStream started with a scan rate of %0.0f Hz." % scan_rate) print("\nPerforming %i buffer updates." % num_cycles) iteration = 0 total_num_skipped_scans = 0 while iteration < num_cycles: buffer_statuses = [0] infinity_preventer = 0 while max(buffer_statuses) < out_context["state_size"]: buffer_statuses = ljm.eReadNames( handle, len(buffer_status_names), buffer_status_names ) infinity_preventer = infinity_preventer + 1 if infinity_preventer > scan_rate: raise ValueError( "Buffer statuses don't appear to be updating:" + str(buffer_status_names) + str(buffer_statuses) ) for out_context in out_contexts: ljm_stream_util.update_stream_out_buffer(handle, out_context) # ljm.eStreamRead will sleep until data has arrived stream_read = ljm.eStreamRead(handle) num_skipped_scans = ljm_stream_util.process_stream_results( iteration, stream_read, in_names, device_threshold=out_context["state_size"], ljm_threshold=out_context["state_size"] ) total_num_skipped_scans += num_skipped_scans iteration = iteration + 1 except ljm.LJMError: ljm_stream_util.prepare_for_exit(handle) raise except Exception: ljm_stream_util.prepare_for_exit(handle) raise ljm_stream_util.prepare_for_exit(handle) print("Total number of skipped scans: %d" % total_num_skipped_scans) if __name__ == "__main__": main()
en
0.84207
Demonstrates setting up stream-in with stream-out that continuously updates. Streams in while streaming out arbitrary values. These arbitrary stream-out values act on DAC0 to alternate between increasing the voltage from 0 to 2.5 and decreasing from 5.0 to 2.5 on (approximately). Though these values are initially generated during the call to create_out_context, the values could be dynamically generated, read from a file, etc. To convert this example file into a program to suit your needs, the primary things you need to do are: 1. Edit the global setup variables in this file 2. Define your own create_out_context function or equivalent 3. Define your own process_stream_results function or equivalent You may also need to configure AIN, etc. # Setup STREAM_OUTS = [ { "target": str register name that stream-out values will be sent to, "buffer_num_bytes": int size in bytes for this stream-out buffer, "stream_out_index": int STREAM_OUT# offset. 0 would generate names like "STREAM_OUT0_BUFFER_STATUS", etc. "set_loop": int value to be written to STREAM_OUT#(0:3)_SET_LOOP }, ... ] # Note: This program does not work well for large scan rates because # the value loops will start looping before new value loops can be written. # While testing on USB with 512 bytes in one stream-out buffer, 2000 Hz worked # without stream-out buffer loop repeating. # (Other machines may have different results.) # Increasing the size of the buffer_num_bytes will increase the maximum speed. # Using an Ethernet connection type will increase the maximum speed. # ljm.eStreamRead will sleep until data has arrived
3.363927
3
users/models.py
aanu1143/chat-app
0
6622433
<filename>users/models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.urls import reverse class CustomUser(AbstractUser): status = models.CharField(max_length=50, null=True) def get_absolute_url(self): return reverse('profile_detail',args=[str(self.id)])
<filename>users/models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.urls import reverse class CustomUser(AbstractUser): status = models.CharField(max_length=50, null=True) def get_absolute_url(self): return reverse('profile_detail',args=[str(self.id)])
none
1
2.405022
2
section4: methods and functions/1-functions.py
rpotter12/learning-python
2
6622434
# A function in Python is defined by a def statement. # The general syntax looks like this: def function-name(Parameter list): statements, i.e. the function body. # The parameter list consists of none or more parameters. # Parameters are called arguments, if the function is called. # functions allow us to create blocks of code that can be easily executed many times, without needing to constantly rewrite the entire block of code # SYNTAX- # def name_of_function(): # commands # we use the return keyword to send back the result of the function, instead of just printing it out. # return allow us to assign the output of the function to a new variable. def abc(): print('hello world') def sum(a,b): return a+b abc() print(sum(5,6))
# A function in Python is defined by a def statement. # The general syntax looks like this: def function-name(Parameter list): statements, i.e. the function body. # The parameter list consists of none or more parameters. # Parameters are called arguments, if the function is called. # functions allow us to create blocks of code that can be easily executed many times, without needing to constantly rewrite the entire block of code # SYNTAX- # def name_of_function(): # commands # we use the return keyword to send back the result of the function, instead of just printing it out. # return allow us to assign the output of the function to a new variable. def abc(): print('hello world') def sum(a,b): return a+b abc() print(sum(5,6))
en
0.806184
# A function in Python is defined by a def statement. # The general syntax looks like this: def function-name(Parameter list): statements, i.e. the function body. # The parameter list consists of none or more parameters. # Parameters are called arguments, if the function is called. # functions allow us to create blocks of code that can be easily executed many times, without needing to constantly rewrite the entire block of code # SYNTAX- # def name_of_function(): # commands # we use the return keyword to send back the result of the function, instead of just printing it out. # return allow us to assign the output of the function to a new variable.
4.155286
4
hackerrank/algorithms/contests/projecteuler/pdone/32.py
harry-7/mycodes
1
6622435
<reponame>harry-7/mycodes """ Author: <NAME> Handle:harry7 """ #!/usr/bin/python ''' From O'Reilly's Python Cookbook ''' def _combinators(_handle, items, n): if n==0: yield [] return for i, item in enumerate(items): this_one = [ item ] for cc in _combinators(_handle, _handle(items, i), n-1): yield this_one + cc def combinations(items, n): ''' take n distinct items, order matters ''' def skipIthItem(items, i): return items[:i] + items[i+1:] return _combinators(skipIthItem, items, n) def uniqueCombinations(items, n): ''' take n distinct items, order is irrelevant ''' def afterIthItem(items, i): return items[i+1:] return _combinators(afterIthItem, items, n) def selections(items, n): ''' take n (not necessarily distinct) items, order matters ''' def keepAllItems(items, i): return items return _combinators(keepAllItems, items, n) def permutations(items): ''' take all items, order matters ''' return combinations(items, len(items)) def val(n): s=0 for i in n:s=s*10+i return s m={} n=input() for perm in permutations(range(1,n+1)): for cross in xrange(1,n/2): for eq in xrange(cross+1,n/2+2): a=val(perm[0:cross]) b=val(perm[cross:eq]) c=val(perm[eq:n]) #print a,b,c if(a*b==c):m[c]=1 print sum(i for i in m)
""" Author: <NAME> Handle:harry7 """ #!/usr/bin/python ''' From O'Reilly's Python Cookbook ''' def _combinators(_handle, items, n): if n==0: yield [] return for i, item in enumerate(items): this_one = [ item ] for cc in _combinators(_handle, _handle(items, i), n-1): yield this_one + cc def combinations(items, n): ''' take n distinct items, order matters ''' def skipIthItem(items, i): return items[:i] + items[i+1:] return _combinators(skipIthItem, items, n) def uniqueCombinations(items, n): ''' take n distinct items, order is irrelevant ''' def afterIthItem(items, i): return items[i+1:] return _combinators(afterIthItem, items, n) def selections(items, n): ''' take n (not necessarily distinct) items, order matters ''' def keepAllItems(items, i): return items return _combinators(keepAllItems, items, n) def permutations(items): ''' take all items, order matters ''' return combinations(items, len(items)) def val(n): s=0 for i in n:s=s*10+i return s m={} n=input() for perm in permutations(range(1,n+1)): for cross in xrange(1,n/2): for eq in xrange(cross+1,n/2+2): a=val(perm[0:cross]) b=val(perm[cross:eq]) c=val(perm[eq:n]) #print a,b,c if(a*b==c):m[c]=1 print sum(i for i in m)
en
0.716947
Author: <NAME> Handle:harry7 #!/usr/bin/python From O'Reilly's Python Cookbook take n distinct items, order matters take n distinct items, order is irrelevant take n (not necessarily distinct) items, order matters take all items, order matters #print a,b,c
3.579591
4
notifications/signals.py
Natureshadow/django-notifs
0
6622436
<reponame>Natureshadow/django-notifs """Defines and listens to notification signals.""" import warnings from django.dispatch import Signal, receiver from . import NotificationError from .models import Notification from .tasks import send_notification # Expected arguments; 'source', 'source_display_name', 'recipient', 'action', # 'category' 'obj', 'url', 'short_description', 'extra_data', 'silent', # 'channels' notify = Signal() # Expected arguments: 'notify_id', 'recipient' read = Signal() @receiver(notify) def create_notification(**kwargs): """Notify signal receiver.""" warnings.warn( 'The \'notify\' Signal will be removed in 2.6.6 ' 'Please use the helper functions in notifications.utils', PendingDeprecationWarning ) # make fresh copy and retain kwargs params = kwargs.copy() del params['signal'] del params['sender'] try: del params['silent'] except KeyError: pass notification = Notification(**params) # If it's a not a silent notification, save the notification if not kwargs.get('silent', False): notification.save() # Send the notification asynchronously with celery send_notification.delay(notification.to_json()) @receiver(read) def read_notification(**kwargs): """ Mark notification as read. Raises NotificationError if the user doesn't have access to read the notification """ warnings.warn( 'The \'read\' Signal will be removed in 2.6.6 ' 'Please use the helper functions in notifications.utils', PendingDeprecationWarning ) notify_id = kwargs['notify_id'] recipient = kwargs['recipient'] notification = Notification.objects.get(id=notify_id) if recipient != notification.recipient: raise NotificationError('You cannot read this notification') notification.read()
"""Defines and listens to notification signals.""" import warnings from django.dispatch import Signal, receiver from . import NotificationError from .models import Notification from .tasks import send_notification # Expected arguments; 'source', 'source_display_name', 'recipient', 'action', # 'category' 'obj', 'url', 'short_description', 'extra_data', 'silent', # 'channels' notify = Signal() # Expected arguments: 'notify_id', 'recipient' read = Signal() @receiver(notify) def create_notification(**kwargs): """Notify signal receiver.""" warnings.warn( 'The \'notify\' Signal will be removed in 2.6.6 ' 'Please use the helper functions in notifications.utils', PendingDeprecationWarning ) # make fresh copy and retain kwargs params = kwargs.copy() del params['signal'] del params['sender'] try: del params['silent'] except KeyError: pass notification = Notification(**params) # If it's a not a silent notification, save the notification if not kwargs.get('silent', False): notification.save() # Send the notification asynchronously with celery send_notification.delay(notification.to_json()) @receiver(read) def read_notification(**kwargs): """ Mark notification as read. Raises NotificationError if the user doesn't have access to read the notification """ warnings.warn( 'The \'read\' Signal will be removed in 2.6.6 ' 'Please use the helper functions in notifications.utils', PendingDeprecationWarning ) notify_id = kwargs['notify_id'] recipient = kwargs['recipient'] notification = Notification.objects.get(id=notify_id) if recipient != notification.recipient: raise NotificationError('You cannot read this notification') notification.read()
en
0.692155
Defines and listens to notification signals. # Expected arguments; 'source', 'source_display_name', 'recipient', 'action', # 'category' 'obj', 'url', 'short_description', 'extra_data', 'silent', # 'channels' # Expected arguments: 'notify_id', 'recipient' Notify signal receiver. # make fresh copy and retain kwargs # If it's a not a silent notification, save the notification # Send the notification asynchronously with celery Mark notification as read. Raises NotificationError if the user doesn't have access to read the notification
2.423847
2
pyprob/nn/proposal_categorical_categorical.py
ammunk/pyprob
2
6622437
<filename>pyprob/nn/proposal_categorical_categorical.py import torch import torch.nn as nn from . import EmbeddingFeedForward from .. import util from ..distributions import Categorical class ProposalCategoricalCategorical(nn.Module): def __init__(self, input_shape, num_categories, num_layers=2, hidden_dim=None): super().__init__() input_shape = util.to_size(input_shape) self._ff = EmbeddingFeedForward(input_shape=input_shape, output_shape=torch.Size([num_categories]), num_layers=num_layers, activation=torch.relu, activation_last=None, hidden_dim=hidden_dim) self._total_train_iterations = 0 self._logsoftmax = nn.LogSoftmax(dim=1) def forward(self, x, prior_variables): batch_size = x.size(0) x = self._ff(x) logits = self._logsoftmax(x).view(batch_size, -1) return Categorical(logits=logits)
<filename>pyprob/nn/proposal_categorical_categorical.py import torch import torch.nn as nn from . import EmbeddingFeedForward from .. import util from ..distributions import Categorical class ProposalCategoricalCategorical(nn.Module): def __init__(self, input_shape, num_categories, num_layers=2, hidden_dim=None): super().__init__() input_shape = util.to_size(input_shape) self._ff = EmbeddingFeedForward(input_shape=input_shape, output_shape=torch.Size([num_categories]), num_layers=num_layers, activation=torch.relu, activation_last=None, hidden_dim=hidden_dim) self._total_train_iterations = 0 self._logsoftmax = nn.LogSoftmax(dim=1) def forward(self, x, prior_variables): batch_size = x.size(0) x = self._ff(x) logits = self._logsoftmax(x).view(batch_size, -1) return Categorical(logits=logits)
none
1
2.67763
3
Src/Clova/vendor/future/moves/configparser.py
NishiYusuke/Line-boot-award
2
6622438
from __future__ import absolute_import from future.utils import PY2 if PY2: from ConfigParser import * else: from configparser import *
from __future__ import absolute_import from future.utils import PY2 if PY2: from ConfigParser import * else: from configparser import *
none
1
1.446979
1
django/company/views.py
shortintern2020-A-labyrinth/TeamD
4
6622439
from rest_framework import generics, status, permissions from rest_framework.response import Response from rest_framework.decorators import api_view, permission_classes from django import forms import json, base64, io, os import random import string import time from .models import Company, Urls from video.models import video_post_validation, material_video_validation, save_video, remove_video, get_video_post, get_request_data, set_video_post from .util.models import post_mail from django.utils import timezone import hashlib from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse, HttpResponse from session.redis import SessionRedis from company.util.models import get_company_id from movie.models import making_movie from youtube.models import upload_movie @api_view(['GET']) def return_company_info(request): try: sessionRedis = SessionRedis() token = request.headers['Authorization'] str_time, company_id = sessionRedis.get(token) company = Company.objects.get(id=company_id) return Response( { 'name': company.name, 'description': company.description }, status=status.HTTP_200_OK ) except: return Response( { 'message': 'failed!' }, status=status.HTTP_400_BAD_REQUEST ) # 中原航大 # /api/company/ 時の処理 # GET: 投稿ビデオの取得 # POST: 動画投稿 @csrf_exempt @api_view(['GET', 'POST']) def video_view(request): if request.method == 'GET': token = request.headers['Authorization'] _, company_id = get_company_id(token) company_id = None if company_id == None else int(company_id) if company_id != None: videos = get_video_post(company_id) # [{'name':'hoge', 'youtube_url':'hoge.com', ・・・},・・・] return Response( { 'message': 'success!', 'videos': videos }, status=status.HTTP_200_OK ) elif request.method == 'POST': # 動画公開時の情報に対してバリデーション if not video_post_validation(request.POST): return Response( { 'message': 'video_post_validation error' }, status=status.HTTP_400_BAD_REQUEST ) # 素材動画に対してバリデーション if not material_video_validation(request.FILES): return Response( { 'message': 'material_video_validation error' }, status=status.HTTP_400_BAD_REQUEST ) data = get_request_data(request) # リクエストパラメータの取得 data = making_movie(data) #動画加工 data = upload_movie(data) #動画アップロード # 仮保存した動画を削除する for file_path in data['delete']: remove_video(file_path) set_video_post(data) # 公開した動画のURLをデータベースにいれる return Response( { 'message': 'success' }, status=status.HTTP_200_OK ) elif request.method == 'PUT': print() elif request.method == 'DELETE': print() @api_view(['POST']) def return_preview(request): # バリデーション if not material_video_validation(request.FILES): return Response( { 'message': 'material_video_validation error' }, status=status.HTTP_400_BAD_REQUEST ) data = get_request_data(request) #動画加工 data = making_movie(data) #編集後の動画返却 path = data['edit']['combine']['paths'] file_path = path[0] paths = file_path.split('/') paths[1] = "after-" + paths[1] after_file = '/'.join(paths) s = "ffmpeg -i {} -vcodec libx264 {}".format(file_path, after_file) # コーデックをh264に設定した os.system(s) video = io.open(after_file, 'r+b').read() encoded_video = base64.b64encode(video) # file削除 for file_path in data['delete']: remove_video(file_path) # after-〇〇.mp4 削除 remove_video(after_file) return HttpResponse(encoded_video.decode('ascii'), content_type='video/mp4') # try: # except: # return Response( # { # 'message': 'failed' # }, # status=status.HTTP_400_BAD_REQUEST # ) # 鎌塚直己↓ # session用 def randomSTR(n): randlst = [random.choice(string.ascii_letters + string.digits) for i in range(n)] return ''.join(randlst) @csrf_exempt @api_view(['POST']) def login(request): try: # emailとpasswordの一致確認 data = json.loads(request.body) email = data['email'] password = data['password'] company = Company.objects.get(email=email) is_accepted = company.is_accepted if password == company.password and is_accepted == 1: # random でsession作成 session = randomSTR(10) current_time = time.time() # session key: session, value: current_time sessionRedis = SessionRedis() sessionRedis.setToken(session, current_time, company.id) return Response({'token': session}) else: raise Exception except: return Response( { 'message': 'input data is not correct or not accepted yet' }, status=status.HTTP_400_BAD_REQUEST ) @csrf_exempt @api_view(['POST']) def logout(request): token = request.headers['Authorization'] sessionRedis = SessionRedis() sessionRedis.delete(token) return Response( { 'message': 'logged out successfully.' }, status=status.HTTP_200_OK ) @csrf_exempt def register_temporary_company(request): if request.method == 'GET': return Response({}) elif request.method == 'POST': data = json.loads(request.body) name = data['name'] email = data['email'] password = data['password'] description = data['description'] # 会員登録用トークン生成(メールアドレス + パスワード + システム日付のハッシュ値とする) date = timezone.now() tmp_str = email + password + date.strftime('%Y%m%d%H%M%S%f') token = hashlib.sha1(tmp_str.encode('utf-8')).hexdigest() # compnayテーブルにインサート company = Company(name=name, email=email, password=password, description=description, is_accepted=0, tokens=token) company.save() # urlsの登録 urls = data['urls'] for url in urls: value = url['value'] type = url['type'] if value == '': continue urls = Urls(value=value, type=type, company_id=company.id) urls.save() # 運営に申請メール送信 subject = "企業からの申請依頼のお知らせ" to_email = "<EMAIL>" body = "企業名: " + name + "\n メールアドレス:" + email + "\n 企業概要: " + \ description + "\n 申請する rakutenpv.app/api/admin/accept/company?token=" + token post_mail(subject, email, [to_email], body) return JsonResponse( { 'message': 'registerd successfully!' }, status=status.HTTP_200_OK ) elif request.method == 'PUT': print() elif request.method == 'DELETE': print() @api_view(['PUT']) def update_company_details(request): try: data = json.loads(request.body) token = request.headers['Authorization'] _, company_id = get_company_id(token) company_id = None if company_id == None else int(company_id) description = data['description'] company = Company.objects.get(id=company_id) company.description = description company.save() # urlsの登録 urls = data['urls'] if urls: for url in urls: value = url['value'] if value == '': continue type = url['type'] try: urls = Urls.objects.get(type=type, company_id=company.id) urls.value = value except Urls.DoesNotExist: urls = Urls(value=value, type=type, company_id=company.id) urls.save() return JsonResponse( { 'message': 'success' }, status=status.HTTP_200_OK ) except: return Response( { 'message': 'failed' }, status=status.HTTP_400_BAD_REQUEST ) # 運営に申請メール送信 # subject="企業からの申請依頼のお知らせ" # to_email="<EMAIL>" # body="企業名: " + company_name + "\n メールアドレス:" + email + "\n 企業概要: " + description + "\n 申請する rakutenpv.app/api//accept/company/?token=" + token # post_mail(subject, email, to_email, body)
from rest_framework import generics, status, permissions from rest_framework.response import Response from rest_framework.decorators import api_view, permission_classes from django import forms import json, base64, io, os import random import string import time from .models import Company, Urls from video.models import video_post_validation, material_video_validation, save_video, remove_video, get_video_post, get_request_data, set_video_post from .util.models import post_mail from django.utils import timezone import hashlib from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse, HttpResponse from session.redis import SessionRedis from company.util.models import get_company_id from movie.models import making_movie from youtube.models import upload_movie @api_view(['GET']) def return_company_info(request): try: sessionRedis = SessionRedis() token = request.headers['Authorization'] str_time, company_id = sessionRedis.get(token) company = Company.objects.get(id=company_id) return Response( { 'name': company.name, 'description': company.description }, status=status.HTTP_200_OK ) except: return Response( { 'message': 'failed!' }, status=status.HTTP_400_BAD_REQUEST ) # 中原航大 # /api/company/ 時の処理 # GET: 投稿ビデオの取得 # POST: 動画投稿 @csrf_exempt @api_view(['GET', 'POST']) def video_view(request): if request.method == 'GET': token = request.headers['Authorization'] _, company_id = get_company_id(token) company_id = None if company_id == None else int(company_id) if company_id != None: videos = get_video_post(company_id) # [{'name':'hoge', 'youtube_url':'hoge.com', ・・・},・・・] return Response( { 'message': 'success!', 'videos': videos }, status=status.HTTP_200_OK ) elif request.method == 'POST': # 動画公開時の情報に対してバリデーション if not video_post_validation(request.POST): return Response( { 'message': 'video_post_validation error' }, status=status.HTTP_400_BAD_REQUEST ) # 素材動画に対してバリデーション if not material_video_validation(request.FILES): return Response( { 'message': 'material_video_validation error' }, status=status.HTTP_400_BAD_REQUEST ) data = get_request_data(request) # リクエストパラメータの取得 data = making_movie(data) #動画加工 data = upload_movie(data) #動画アップロード # 仮保存した動画を削除する for file_path in data['delete']: remove_video(file_path) set_video_post(data) # 公開した動画のURLをデータベースにいれる return Response( { 'message': 'success' }, status=status.HTTP_200_OK ) elif request.method == 'PUT': print() elif request.method == 'DELETE': print() @api_view(['POST']) def return_preview(request): # バリデーション if not material_video_validation(request.FILES): return Response( { 'message': 'material_video_validation error' }, status=status.HTTP_400_BAD_REQUEST ) data = get_request_data(request) #動画加工 data = making_movie(data) #編集後の動画返却 path = data['edit']['combine']['paths'] file_path = path[0] paths = file_path.split('/') paths[1] = "after-" + paths[1] after_file = '/'.join(paths) s = "ffmpeg -i {} -vcodec libx264 {}".format(file_path, after_file) # コーデックをh264に設定した os.system(s) video = io.open(after_file, 'r+b').read() encoded_video = base64.b64encode(video) # file削除 for file_path in data['delete']: remove_video(file_path) # after-〇〇.mp4 削除 remove_video(after_file) return HttpResponse(encoded_video.decode('ascii'), content_type='video/mp4') # try: # except: # return Response( # { # 'message': 'failed' # }, # status=status.HTTP_400_BAD_REQUEST # ) # 鎌塚直己↓ # session用 def randomSTR(n): randlst = [random.choice(string.ascii_letters + string.digits) for i in range(n)] return ''.join(randlst) @csrf_exempt @api_view(['POST']) def login(request): try: # emailとpasswordの一致確認 data = json.loads(request.body) email = data['email'] password = data['password'] company = Company.objects.get(email=email) is_accepted = company.is_accepted if password == company.password and is_accepted == 1: # random でsession作成 session = randomSTR(10) current_time = time.time() # session key: session, value: current_time sessionRedis = SessionRedis() sessionRedis.setToken(session, current_time, company.id) return Response({'token': session}) else: raise Exception except: return Response( { 'message': 'input data is not correct or not accepted yet' }, status=status.HTTP_400_BAD_REQUEST ) @csrf_exempt @api_view(['POST']) def logout(request): token = request.headers['Authorization'] sessionRedis = SessionRedis() sessionRedis.delete(token) return Response( { 'message': 'logged out successfully.' }, status=status.HTTP_200_OK ) @csrf_exempt def register_temporary_company(request): if request.method == 'GET': return Response({}) elif request.method == 'POST': data = json.loads(request.body) name = data['name'] email = data['email'] password = data['password'] description = data['description'] # 会員登録用トークン生成(メールアドレス + パスワード + システム日付のハッシュ値とする) date = timezone.now() tmp_str = email + password + date.strftime('%Y%m%d%H%M%S%f') token = hashlib.sha1(tmp_str.encode('utf-8')).hexdigest() # compnayテーブルにインサート company = Company(name=name, email=email, password=password, description=description, is_accepted=0, tokens=token) company.save() # urlsの登録 urls = data['urls'] for url in urls: value = url['value'] type = url['type'] if value == '': continue urls = Urls(value=value, type=type, company_id=company.id) urls.save() # 運営に申請メール送信 subject = "企業からの申請依頼のお知らせ" to_email = "<EMAIL>" body = "企業名: " + name + "\n メールアドレス:" + email + "\n 企業概要: " + \ description + "\n 申請する rakutenpv.app/api/admin/accept/company?token=" + token post_mail(subject, email, [to_email], body) return JsonResponse( { 'message': 'registerd successfully!' }, status=status.HTTP_200_OK ) elif request.method == 'PUT': print() elif request.method == 'DELETE': print() @api_view(['PUT']) def update_company_details(request): try: data = json.loads(request.body) token = request.headers['Authorization'] _, company_id = get_company_id(token) company_id = None if company_id == None else int(company_id) description = data['description'] company = Company.objects.get(id=company_id) company.description = description company.save() # urlsの登録 urls = data['urls'] if urls: for url in urls: value = url['value'] if value == '': continue type = url['type'] try: urls = Urls.objects.get(type=type, company_id=company.id) urls.value = value except Urls.DoesNotExist: urls = Urls(value=value, type=type, company_id=company.id) urls.save() return JsonResponse( { 'message': 'success' }, status=status.HTTP_200_OK ) except: return Response( { 'message': 'failed' }, status=status.HTTP_400_BAD_REQUEST ) # 運営に申請メール送信 # subject="企業からの申請依頼のお知らせ" # to_email="<EMAIL>" # body="企業名: " + company_name + "\n メールアドレス:" + email + "\n 企業概要: " + description + "\n 申請する rakutenpv.app/api//accept/company/?token=" + token # post_mail(subject, email, to_email, body)
ja
0.970901
# 中原航大 # /api/company/ 時の処理 # GET: 投稿ビデオの取得 # POST: 動画投稿 # [{'name':'hoge', 'youtube_url':'hoge.com', ・・・},・・・] # 動画公開時の情報に対してバリデーション # 素材動画に対してバリデーション # リクエストパラメータの取得 #動画加工 #動画アップロード # 仮保存した動画を削除する # 公開した動画のURLをデータベースにいれる # バリデーション #動画加工 #編集後の動画返却 # コーデックをh264に設定した # file削除 # after-〇〇.mp4 削除 # try: # except: # return Response( # { # 'message': 'failed' # }, # status=status.HTTP_400_BAD_REQUEST # ) # 鎌塚直己↓ # session用 # emailとpasswordの一致確認 # random でsession作成 # session key: session, value: current_time # 会員登録用トークン生成(メールアドレス + パスワード + システム日付のハッシュ値とする) # compnayテーブルにインサート # urlsの登録 # 運営に申請メール送信 # urlsの登録 # 運営に申請メール送信 # subject="企業からの申請依頼のお知らせ" # to_email="<EMAIL>" # body="企業名: " + company_name + "\n メールアドレス:" + email + "\n 企業概要: " + description + "\n 申請する rakutenpv.app/api//accept/company/?token=" + token # post_mail(subject, email, to_email, body)
2.059417
2
main.py
tengfone/telegram_SUTDMountaineeringBanterBot
0
6622440
from telegram import ParseMode, ReplyKeyboardMarkup, ChatAction, InlineQueryResultArticle, InputTextMessageContent from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, InlineQueryHandler, CallbackQueryHandler, \ ConversationHandler, RegexHandler import logging, os, sys, re from functools import wraps # logger logger = logging.getLogger() logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) # global variable mode = os.environ['mode'] TOKEN = os.environ['TOKEN'] updater = Updater(token=TOKEN, use_context=True) dispatcher = updater.dispatcher # options to run if mode == "dev": def run(updater): updater.start_polling() elif mode == "prod": def run(updater): PORT = int(os.environ.get("PORT", "8443")) HEROKU_APP_NAME = os.environ.get("HEROKU_APP_NAME") updater.start_webhook(listen="0.0.0.0", port=PORT, url_path=TOKEN) updater.bot.set_webhook("https://{}.herokuapp.com/{}".format(HEROKU_APP_NAME, TOKEN)) else: logger.error("Error, Ensure Environment Variable is set.") sys.exit(1) def get_name(user): try: name = user.first_name except (NameError, AttributeError): try: name = user.username except (NameError, AttributeError): logger.info("No Username? Not possible.") return "" return name def shut_up(update, context): chat_id = update.message.chat_id name = get_name(update.message.from_user) name = name.upper() reply = "SHUT THE FUCK UP LA " + name + "!" update.message.reply_text(reply) def sorry(update, context): reply = "You sure you sorry anot? Or is it cause you stupid?" update.message.reply_text(reply) def yeet(update, context): reply = "I'll YEET your Milo" update.message.reply_text(reply) def main(): dispatcher.add_handler(MessageHandler(Filters.regex(re.compile(r'say.*real', re.IGNORECASE)), shut_up)) dispatcher.add_handler(MessageHandler(Filters.regex(re.compile(r'sorry', re.IGNORECASE)), sorry)) dispatcher.add_handler(MessageHandler(Filters.regex(re.compile(r'yeet', re.IGNORECASE)), yeet)) updater.start_polling() updater.idle() if __name__ == '__main__': main()
from telegram import ParseMode, ReplyKeyboardMarkup, ChatAction, InlineQueryResultArticle, InputTextMessageContent from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, InlineQueryHandler, CallbackQueryHandler, \ ConversationHandler, RegexHandler import logging, os, sys, re from functools import wraps # logger logger = logging.getLogger() logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) # global variable mode = os.environ['mode'] TOKEN = os.environ['TOKEN'] updater = Updater(token=TOKEN, use_context=True) dispatcher = updater.dispatcher # options to run if mode == "dev": def run(updater): updater.start_polling() elif mode == "prod": def run(updater): PORT = int(os.environ.get("PORT", "8443")) HEROKU_APP_NAME = os.environ.get("HEROKU_APP_NAME") updater.start_webhook(listen="0.0.0.0", port=PORT, url_path=TOKEN) updater.bot.set_webhook("https://{}.herokuapp.com/{}".format(HEROKU_APP_NAME, TOKEN)) else: logger.error("Error, Ensure Environment Variable is set.") sys.exit(1) def get_name(user): try: name = user.first_name except (NameError, AttributeError): try: name = user.username except (NameError, AttributeError): logger.info("No Username? Not possible.") return "" return name def shut_up(update, context): chat_id = update.message.chat_id name = get_name(update.message.from_user) name = name.upper() reply = "SHUT THE FUCK UP LA " + name + "!" update.message.reply_text(reply) def sorry(update, context): reply = "You sure you sorry anot? Or is it cause you stupid?" update.message.reply_text(reply) def yeet(update, context): reply = "I'll YEET your Milo" update.message.reply_text(reply) def main(): dispatcher.add_handler(MessageHandler(Filters.regex(re.compile(r'say.*real', re.IGNORECASE)), shut_up)) dispatcher.add_handler(MessageHandler(Filters.regex(re.compile(r'sorry', re.IGNORECASE)), sorry)) dispatcher.add_handler(MessageHandler(Filters.regex(re.compile(r'yeet', re.IGNORECASE)), yeet)) updater.start_polling() updater.idle() if __name__ == '__main__': main()
en
0.402377
# logger # global variable # options to run
2.403751
2
scripts/make_triplets.py
atypon/S2AND
39
6622441
import argparse import collections import gzip import json import logging import os import tqdm import numpy as np import s2and from s2and.data import ANDData from s2and.consts import CONFIG from s2and.text import counter_jaccard, cosine_sim, STOPWORDS logger = logging.getLogger(__name__) DATASETS = [ "aminer", "arnetminer", "inspire", "kisti", "pubmed", "qian", "zbmath", ] class NgramJaccardRanker: def __init__(self, papers): self.paper_ngrams = {k: self._unigrams(v["title"]) + self._unigrams(v["abstract"]) for k, v in papers.items()} def _unigrams(self, text): if text is None or len(text) == 0: return collections.Counter() text_split = [word for word in text.lower().split() if word not in STOPWORDS and len(word) > 1] unigrams = collections.Counter(text_split) return unigrams def __call__(self, sig1, sig2): paper1 = self.paper_ngrams[str(sig1.paper_id)] paper2 = self.paper_ngrams[str(sig2.paper_id)] return counter_jaccard(paper1, paper2) class SpecterRanker: def __init__(self, specters): self.paper2idx = {paper_id: idx for idx, paper_id in enumerate(specters[1])} self.specter = specters[0] def __call__(self, sig1, sig2): emb1 = self.specter[self.paper2idx[str(sig1.paper_id)]] emb2 = self.specter[self.paper2idx[str(sig2.paper_id)]] return cosine_sim(emb1, emb2) def generate_block_triplets( dataset, block_sigs, rng, num_queries=None, num_positives=None, num_negatives=None, negative_ranker_fn=None ): block_sigs = block_sigs.copy() rng.shuffle(block_sigs) for query_sig_id in block_sigs[:num_queries]: query_sig = dataset.signatures[query_sig_id] cluster_sigs = set(dataset.clusters[dataset.signature_to_cluster_id[query_sig_id]]["signature_ids"]) positives = [dataset.signatures[x] for x in cluster_sigs if x != query_sig_id] rng.shuffle(positives) negatives = [dataset.signatures[x] for x in block_sigs if x not in cluster_sigs] if negative_ranker_fn: negatives.sort(reverse=True, key=lambda neg: negative_ranker_fn(query_sig, neg)) else: rng.shuffle(negatives) for pos in positives[:num_positives]: for neg in negatives[:num_negatives]: yield (str(query_sig.paper_id), str(pos.paper_id), str(neg.paper_id)) def make_dataset_triplets(args, dataset): rng = np.random.default_rng(args.seed) ranker = NgramJaccardRanker(dataset.raw_papers) block_splits = dict() block_splits["train"], block_splits["dev"], block_splits["test"] = dataset.split_cluster_signatures() triplets = dict() for split_name, split_blocks in block_splits.items(): triplets[split_name] = [] pbar = tqdm.tqdm(split_blocks.items(), total=len(split_blocks)) for block_name, block_sigs in pbar: triplets[split_name].extend( generate_block_triplets( dataset, block_sigs, rng, num_queries=args.n_queries_per_block, num_positives=args.n_pos_per_query, num_negatives=args.n_neg_per_query, negative_ranker_fn=ranker, ) ) pbar.desc = "size={}".format(sum(len(x) for x in triplets.values())) if len(triplets[split_name]) > args.max_triplets_per_dataset_split: rng.shuffle(triplets[split_name]) triplets[split_name] = triplets[split_name][: args.max_triplets_per_dataset_split] return triplets def load_dataset(data_dir, dataset_name, seed, n_jobs=8): dataset_dir = os.path.join(data_dir, dataset_name) dataset = ANDData( signatures=os.path.join(dataset_dir, dataset_name + "_signatures.json"), papers=os.path.join(dataset_dir, dataset_name + "_papers.json"), name=dataset_name, mode="train", specter_embeddings=os.path.join(dataset_dir, dataset_name + "_specter.pickle"), clusters=os.path.join(dataset_dir, dataset_name + "_clusters.json"), block_type="s2", n_jobs=n_jobs, load_name_counts=False, preprocess=False, random_seed=seed, ) # Need raw papers for output and ngram ranker with open(os.path.join(data_dir, dataset_name, dataset_name + "_papers.json")) as f: dataset.raw_papers = json.load(f) return dataset def parse_cli_args(): parser = argparse.ArgumentParser() parser.add_argument("--output", required=True) parser.add_argument("--max_triplets_per_dataset_split", type=int, default=100000) parser.add_argument("--n_queries_per_block", type=int, default=None) parser.add_argument("--n_pos_per_query", type=int, default=None) parser.add_argument("--n_neg_per_query", type=int, default=None) parser.add_argument("--data_dir", default=CONFIG["main_data_dir"]) parser.add_argument("--compression", default="none", choices=["gzip", "none"]) parser.add_argument("--seed", type=int, default=1) return parser.parse_args() def paper_id_to_full(paper_id, raw_papers): raw_paper = raw_papers[paper_id] return { "corpus_id": raw_paper["paper_id"], "title": raw_paper["title"], "abstract": raw_paper["abstract"], } def main(): args = parse_cli_args() open_fn = None extension = None if args.compression == "gzip": open_fn = gzip.open extension = ".gz" elif args.compression == "none": open_fn = open extension = "" else: raise ValueError("Invalid compression {}".format(args.compression)) os.makedirs(args.output, exist_ok=True) with open_fn(os.path.join(args.output, "train.jsonl" + extension), "wt") as train_f, open_fn( os.path.join(args.output, "dev.jsonl" + extension), "wt" ) as dev_f, open_fn(os.path.join(args.output, "test.jsonl" + extension), "wt") as test_f: file_objs = {"train": train_f, "dev": dev_f, "test": test_f} for dataset_name in DATASETS: logger.info("loading {}".format(dataset_name)) dataset = load_dataset(args.data_dir, dataset_name, args.seed) triplets = make_dataset_triplets(args, dataset) logger.info( "made {} triplets for {}. Saving...".format(sum(len(x) for x in triplets.values()), dataset_name) ) for split_name, file_obj in file_objs.items(): for row in triplets[split_name]: file_obj.write( json.dumps( { "dataset": dataset_name, "seed": paper_id_to_full(row[0], dataset.raw_papers), "positive": paper_id_to_full(row[1], dataset.raw_papers), "negative": paper_id_to_full(row[2], dataset.raw_papers), } ) + "\n" ) if __name__ == "__main__": logging.basicConfig( format="%(asctime)s [%(levelname)s] (%(name)s): %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=logging.INFO, handlers=[ logging.StreamHandler(), ], ) s2and.logger.handlers = [] main()
import argparse import collections import gzip import json import logging import os import tqdm import numpy as np import s2and from s2and.data import ANDData from s2and.consts import CONFIG from s2and.text import counter_jaccard, cosine_sim, STOPWORDS logger = logging.getLogger(__name__) DATASETS = [ "aminer", "arnetminer", "inspire", "kisti", "pubmed", "qian", "zbmath", ] class NgramJaccardRanker: def __init__(self, papers): self.paper_ngrams = {k: self._unigrams(v["title"]) + self._unigrams(v["abstract"]) for k, v in papers.items()} def _unigrams(self, text): if text is None or len(text) == 0: return collections.Counter() text_split = [word for word in text.lower().split() if word not in STOPWORDS and len(word) > 1] unigrams = collections.Counter(text_split) return unigrams def __call__(self, sig1, sig2): paper1 = self.paper_ngrams[str(sig1.paper_id)] paper2 = self.paper_ngrams[str(sig2.paper_id)] return counter_jaccard(paper1, paper2) class SpecterRanker: def __init__(self, specters): self.paper2idx = {paper_id: idx for idx, paper_id in enumerate(specters[1])} self.specter = specters[0] def __call__(self, sig1, sig2): emb1 = self.specter[self.paper2idx[str(sig1.paper_id)]] emb2 = self.specter[self.paper2idx[str(sig2.paper_id)]] return cosine_sim(emb1, emb2) def generate_block_triplets( dataset, block_sigs, rng, num_queries=None, num_positives=None, num_negatives=None, negative_ranker_fn=None ): block_sigs = block_sigs.copy() rng.shuffle(block_sigs) for query_sig_id in block_sigs[:num_queries]: query_sig = dataset.signatures[query_sig_id] cluster_sigs = set(dataset.clusters[dataset.signature_to_cluster_id[query_sig_id]]["signature_ids"]) positives = [dataset.signatures[x] for x in cluster_sigs if x != query_sig_id] rng.shuffle(positives) negatives = [dataset.signatures[x] for x in block_sigs if x not in cluster_sigs] if negative_ranker_fn: negatives.sort(reverse=True, key=lambda neg: negative_ranker_fn(query_sig, neg)) else: rng.shuffle(negatives) for pos in positives[:num_positives]: for neg in negatives[:num_negatives]: yield (str(query_sig.paper_id), str(pos.paper_id), str(neg.paper_id)) def make_dataset_triplets(args, dataset): rng = np.random.default_rng(args.seed) ranker = NgramJaccardRanker(dataset.raw_papers) block_splits = dict() block_splits["train"], block_splits["dev"], block_splits["test"] = dataset.split_cluster_signatures() triplets = dict() for split_name, split_blocks in block_splits.items(): triplets[split_name] = [] pbar = tqdm.tqdm(split_blocks.items(), total=len(split_blocks)) for block_name, block_sigs in pbar: triplets[split_name].extend( generate_block_triplets( dataset, block_sigs, rng, num_queries=args.n_queries_per_block, num_positives=args.n_pos_per_query, num_negatives=args.n_neg_per_query, negative_ranker_fn=ranker, ) ) pbar.desc = "size={}".format(sum(len(x) for x in triplets.values())) if len(triplets[split_name]) > args.max_triplets_per_dataset_split: rng.shuffle(triplets[split_name]) triplets[split_name] = triplets[split_name][: args.max_triplets_per_dataset_split] return triplets def load_dataset(data_dir, dataset_name, seed, n_jobs=8): dataset_dir = os.path.join(data_dir, dataset_name) dataset = ANDData( signatures=os.path.join(dataset_dir, dataset_name + "_signatures.json"), papers=os.path.join(dataset_dir, dataset_name + "_papers.json"), name=dataset_name, mode="train", specter_embeddings=os.path.join(dataset_dir, dataset_name + "_specter.pickle"), clusters=os.path.join(dataset_dir, dataset_name + "_clusters.json"), block_type="s2", n_jobs=n_jobs, load_name_counts=False, preprocess=False, random_seed=seed, ) # Need raw papers for output and ngram ranker with open(os.path.join(data_dir, dataset_name, dataset_name + "_papers.json")) as f: dataset.raw_papers = json.load(f) return dataset def parse_cli_args(): parser = argparse.ArgumentParser() parser.add_argument("--output", required=True) parser.add_argument("--max_triplets_per_dataset_split", type=int, default=100000) parser.add_argument("--n_queries_per_block", type=int, default=None) parser.add_argument("--n_pos_per_query", type=int, default=None) parser.add_argument("--n_neg_per_query", type=int, default=None) parser.add_argument("--data_dir", default=CONFIG["main_data_dir"]) parser.add_argument("--compression", default="none", choices=["gzip", "none"]) parser.add_argument("--seed", type=int, default=1) return parser.parse_args() def paper_id_to_full(paper_id, raw_papers): raw_paper = raw_papers[paper_id] return { "corpus_id": raw_paper["paper_id"], "title": raw_paper["title"], "abstract": raw_paper["abstract"], } def main(): args = parse_cli_args() open_fn = None extension = None if args.compression == "gzip": open_fn = gzip.open extension = ".gz" elif args.compression == "none": open_fn = open extension = "" else: raise ValueError("Invalid compression {}".format(args.compression)) os.makedirs(args.output, exist_ok=True) with open_fn(os.path.join(args.output, "train.jsonl" + extension), "wt") as train_f, open_fn( os.path.join(args.output, "dev.jsonl" + extension), "wt" ) as dev_f, open_fn(os.path.join(args.output, "test.jsonl" + extension), "wt") as test_f: file_objs = {"train": train_f, "dev": dev_f, "test": test_f} for dataset_name in DATASETS: logger.info("loading {}".format(dataset_name)) dataset = load_dataset(args.data_dir, dataset_name, args.seed) triplets = make_dataset_triplets(args, dataset) logger.info( "made {} triplets for {}. Saving...".format(sum(len(x) for x in triplets.values()), dataset_name) ) for split_name, file_obj in file_objs.items(): for row in triplets[split_name]: file_obj.write( json.dumps( { "dataset": dataset_name, "seed": paper_id_to_full(row[0], dataset.raw_papers), "positive": paper_id_to_full(row[1], dataset.raw_papers), "negative": paper_id_to_full(row[2], dataset.raw_papers), } ) + "\n" ) if __name__ == "__main__": logging.basicConfig( format="%(asctime)s [%(levelname)s] (%(name)s): %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=logging.INFO, handlers=[ logging.StreamHandler(), ], ) s2and.logger.handlers = [] main()
en
0.61481
# Need raw papers for output and ngram ranker
2.46208
2
pytest_salt_formula/fixtures.py
martinwalsh/pytest-salt-formula
2
6622442
# -*- coding: utf-8 -*- import os import pytest import salt.utils import salt.config import salt.client from utils import abspath, touch from contextlib import contextmanager from salt.exceptions import SaltException @pytest.fixture(scope='session') def file_roots(request): file_roots = request.config.getini('SALT_FILE_ROOTS') if not file_roots: file_roots = [abspath(str(request.config.rootdir), '../')] return [str(p) for p in file_roots] @pytest.fixture(scope='session') def minion_opts(request, tmpdir_factory, file_roots): tmpdir = tmpdir_factory.mktemp('root') cachedir = tmpdir.mkdir('var').mkdir('cache') cachedir.join('.touch').write('') config = touch('/etc/salt/minion', tmpdir) __opts__ = salt.config.minion_config(str(config)) __opts__.update({ 'root_dir': str(tmpdir), 'file_client': 'local', 'file_roots': {'base': file_roots}, 'cachedir': str(cachedir), 'id': 'test-minion', }) if request.config.getini('SALT_MODULE_DIRS'): __opts__['module_dirs'] = request.config.getini('SALT_MODULE_DIRS') return __opts__ @pytest.fixture(scope='session') def minion(request, minion_opts): caller = salt.client.Caller(mopts=minion_opts) _cmd = caller.cmd def cmd(function, *args, **kwds): if function not in request.config.getini('SALT_FUNCTION_WHITELIST'): kwds['test'] = True kwds['mock'] = True return _cmd(function, *args, **kwds) caller.cmd = cmd return caller def get_file_content(source, state, minion, pillar): if state.get('template') is None: cached = minion.cmd('cp.get_file_str', path=source) if cached is not False: return cached else: cached = minion.cmd( 'cp.get_template', path=source, dest='', # an empty string forces download and cache of the rendered template template=state['template'], context=state.get('context'), pillar=pillar, ) if cached is not False: with open(cached) as f: return f.read() raise SaltException('Unable to locate source for {!r}'.format(source)) def attach_file_content(sls, minion, pillar): for state in sls: if state['state'] == 'file': if state['fun'] == 'rename': # the `source` of `file.rename` is not a local file continue if 'source' in state and 'sources' in state: raise SaltException( '`source` and `sources` are mutually exclusive in state with id `{}`.'.format(state['__id__']) ) if 'sources' in state: content = [] for source in state['sources']: content.append(get_file_content(source, state, minion, pillar)) state['__file_content'] = ''.join(content) if 'source' in state: if state['fun'] == 'recurse': files = {} prefix = state['source'][7:] # remove the salt:// portion of the source url for path in minion.cmd('cp.list_master', prefix=prefix): destination = os.path.join(state['name'], path[len(prefix)+1:]) files[destination] = get_file_content( 'salt://{}'.format(path), state, minion, pillar ) state['__file_content'] = files else: if not isinstance(state['source'], list): state['source'] = [state['source']] for source in state['source']: try: state['__file_content'] = get_file_content(source, state, minion, pillar) break except SaltException: pass else: raise SaltException('Unable to locate source for {!r}'.format(state['source'])) return sls class LowSLS(list): def __init__(self, sls, minion, pillar): self._sls = attach_file_content(sls, minion, pillar) list.__init__(self, sls) def to_yaml(self): return salt.utils.yamldumper.safe_dump(self._sls, default_flow_style=False) @pytest.fixture(scope='function') def show_low_sls(request, minion): @contextmanager def _show_low_sls(name, grains, pillar=None): for key, value in grains.items(): minion.cmd('grains.setval', key, value) try: sls = LowSLS(minion.cmd('state.show_low_sls', name, pillar=pillar), minion, pillar) if request.config.getoption('verbose') >= 2: print('$ salt-call --local state.show_low_sls {} --out yaml'.format(name)) print(sls.to_yaml()) yield sls finally: for key in grains.keys(): minion.cmd('grains.delkey', key) return _show_low_sls
# -*- coding: utf-8 -*- import os import pytest import salt.utils import salt.config import salt.client from utils import abspath, touch from contextlib import contextmanager from salt.exceptions import SaltException @pytest.fixture(scope='session') def file_roots(request): file_roots = request.config.getini('SALT_FILE_ROOTS') if not file_roots: file_roots = [abspath(str(request.config.rootdir), '../')] return [str(p) for p in file_roots] @pytest.fixture(scope='session') def minion_opts(request, tmpdir_factory, file_roots): tmpdir = tmpdir_factory.mktemp('root') cachedir = tmpdir.mkdir('var').mkdir('cache') cachedir.join('.touch').write('') config = touch('/etc/salt/minion', tmpdir) __opts__ = salt.config.minion_config(str(config)) __opts__.update({ 'root_dir': str(tmpdir), 'file_client': 'local', 'file_roots': {'base': file_roots}, 'cachedir': str(cachedir), 'id': 'test-minion', }) if request.config.getini('SALT_MODULE_DIRS'): __opts__['module_dirs'] = request.config.getini('SALT_MODULE_DIRS') return __opts__ @pytest.fixture(scope='session') def minion(request, minion_opts): caller = salt.client.Caller(mopts=minion_opts) _cmd = caller.cmd def cmd(function, *args, **kwds): if function not in request.config.getini('SALT_FUNCTION_WHITELIST'): kwds['test'] = True kwds['mock'] = True return _cmd(function, *args, **kwds) caller.cmd = cmd return caller def get_file_content(source, state, minion, pillar): if state.get('template') is None: cached = minion.cmd('cp.get_file_str', path=source) if cached is not False: return cached else: cached = minion.cmd( 'cp.get_template', path=source, dest='', # an empty string forces download and cache of the rendered template template=state['template'], context=state.get('context'), pillar=pillar, ) if cached is not False: with open(cached) as f: return f.read() raise SaltException('Unable to locate source for {!r}'.format(source)) def attach_file_content(sls, minion, pillar): for state in sls: if state['state'] == 'file': if state['fun'] == 'rename': # the `source` of `file.rename` is not a local file continue if 'source' in state and 'sources' in state: raise SaltException( '`source` and `sources` are mutually exclusive in state with id `{}`.'.format(state['__id__']) ) if 'sources' in state: content = [] for source in state['sources']: content.append(get_file_content(source, state, minion, pillar)) state['__file_content'] = ''.join(content) if 'source' in state: if state['fun'] == 'recurse': files = {} prefix = state['source'][7:] # remove the salt:// portion of the source url for path in minion.cmd('cp.list_master', prefix=prefix): destination = os.path.join(state['name'], path[len(prefix)+1:]) files[destination] = get_file_content( 'salt://{}'.format(path), state, minion, pillar ) state['__file_content'] = files else: if not isinstance(state['source'], list): state['source'] = [state['source']] for source in state['source']: try: state['__file_content'] = get_file_content(source, state, minion, pillar) break except SaltException: pass else: raise SaltException('Unable to locate source for {!r}'.format(state['source'])) return sls class LowSLS(list): def __init__(self, sls, minion, pillar): self._sls = attach_file_content(sls, minion, pillar) list.__init__(self, sls) def to_yaml(self): return salt.utils.yamldumper.safe_dump(self._sls, default_flow_style=False) @pytest.fixture(scope='function') def show_low_sls(request, minion): @contextmanager def _show_low_sls(name, grains, pillar=None): for key, value in grains.items(): minion.cmd('grains.setval', key, value) try: sls = LowSLS(minion.cmd('state.show_low_sls', name, pillar=pillar), minion, pillar) if request.config.getoption('verbose') >= 2: print('$ salt-call --local state.show_low_sls {} --out yaml'.format(name)) print(sls.to_yaml()) yield sls finally: for key in grains.keys(): minion.cmd('grains.delkey', key) return _show_low_sls
en
0.607626
# -*- coding: utf-8 -*- # an empty string forces download and cache of the rendered template # the `source` of `file.rename` is not a local file # remove the salt:// portion of the source url
1.889253
2
Week4/Day3/Exc3.py
malharlakdawala/DevelopersInstitute
0
6622443
<reponame>malharlakdawala/DevelopersInstitute<gh_stars>0 # Exercise 1: List Of Integers - Randoms # import random # # a=[] # b=random.randint(1,50) # while b!=0: # a.append(random.randint(-100,100)) # b=b-1 # # print(a) # # Exercise 2: Authentication CLI - Login: a = {"malhar": "abc", "vinod": "charlie", "twinkle": "rohan"} while True: first = input("do you want to login, signup or quit? ") if first == "quit": break elif first == "login": second = input("share username and password? ") second = second.split(",") d = tuple(second) print(d) if ((d[0] in a) and (a[d[0]] == d[1])): print("login succesful") logged_in = second[0] break else: print("wrong username password") break elif first == "signup": new_username=input("enter new username? ") if new_username not in a.keys(): new_password=input("enter password ") a[new_username]=new_password print(a) break else: print("username already present") break
# Exercise 1: List Of Integers - Randoms # import random # # a=[] # b=random.randint(1,50) # while b!=0: # a.append(random.randint(-100,100)) # b=b-1 # # print(a) # # Exercise 2: Authentication CLI - Login: a = {"malhar": "abc", "vinod": "charlie", "twinkle": "rohan"} while True: first = input("do you want to login, signup or quit? ") if first == "quit": break elif first == "login": second = input("share username and password? ") second = second.split(",") d = tuple(second) print(d) if ((d[0] in a) and (a[d[0]] == d[1])): print("login succesful") logged_in = second[0] break else: print("wrong username password") break elif first == "signup": new_username=input("enter new username? ") if new_username not in a.keys(): new_password=input("enter password ") a[new_username]=new_password print(a) break else: print("username already present") break
en
0.313946
# Exercise 1: List Of Integers - Randoms # import random # # a=[] # b=random.randint(1,50) # while b!=0: # a.append(random.randint(-100,100)) # b=b-1 # # print(a) # # Exercise 2: Authentication CLI - Login:
3.77005
4
src/listparser/opml.py
kurtmckee/listparser
47
6622444
# This file is part of listparser. # Copyright 2009-2021 <NAME> <<EMAIL>> # SPDX-License-Identifier: MIT # import copy from . import common from . import dates class OpmlMixin(common.CommonMixin): def start_opml_opml(self, attrs): self.harvest['version'] = 'opml' if attrs.get('version') in ('1.0', '1.1'): self.harvest['version'] = 'opml1' elif attrs.get('version') == '2.0': self.harvest['version'] = 'opml2' def start_opml_outline(self, attrs): url = None # Find an appropriate title in @text or @title (else empty) if attrs.get('text', '').strip(): title = attrs['text'].strip() else: title = attrs.get('title', '').strip() # Search for the URL regardless of xmlUrl's case for k, v in attrs.items(): if k.lower() == 'xmlurl': url = v.strip() break append_to = None # Determine whether the outline is a feed or subscription list if url is not None: # It's a feed append_to = 'feeds' if attrs.get('type', '').strip().lower() == 'source': # Actually, it's a subscription list! append_to = 'lists' elif attrs.get('type', '').lower() in ('link', 'include'): # It's a subscription list append_to = 'lists' url = attrs.get('url', '').strip() elif title: # Assume that this is a grouping node self.hierarchy.append(title) return # Look for an opportunity URL if not url and 'htmlurl' in (k.lower() for k in attrs.keys()): for k, v in attrs.items(): if k.lower() == 'htmlurl': url = v.strip() append_to = 'opportunities' if not url: # Maintain the hierarchy self.hierarchy.append('') return if url not in self.found_urls and append_to: # This is a brand new URL obj = common.SuperDict({'url': url, 'title': title}) self.found_urls[url] = (append_to, obj) self.harvest[append_to].append(obj) else: obj = self.found_urls[url][1] # Handle categories and tags obj.setdefault('categories', []) if 'category' in attrs.keys(): for i in attrs['category'].split(','): tmp = [j.strip() for j in i.split('/') if j.strip()] if tmp and tmp not in obj['categories']: obj['categories'].append(tmp) # Copy the current hierarchy into `categories` if self.hierarchy and self.hierarchy not in obj['categories']: obj['categories'].append(copy.copy(self.hierarchy)) # Copy all single-element `categories` into `tags` obj['tags'] = [i[0] for i in obj['categories'] if len(i) == 1] self.hierarchy.append('') def end_opml_outline(self): self.hierarchy.pop() start_opml_title = common.CommonMixin.expect_text def end_opml_title(self): value = self.get_text() if value: self.harvest['meta']['title'] = value start_opml_ownerId = common.CommonMixin.expect_text def end_opml_ownerId(self): value = self.get_text() if value: self.harvest['meta'].setdefault('author', common.SuperDict()) self.harvest['meta']['author']['url'] = value start_opml_ownerEmail = common.CommonMixin.expect_text def end_opml_ownerEmail(self): value = self.get_text() if value: self.harvest['meta'].setdefault('author', common.SuperDict()) self.harvest['meta']['author']['email'] = value start_opml_ownerName = common.CommonMixin.expect_text def end_opml_ownerName(self): value = self.get_text() if value: self.harvest['meta'].setdefault('author', common.SuperDict()) self.harvest['meta']['author']['name'] = value start_opml_dateCreated = common.CommonMixin.expect_text def end_opml_dateCreated(self): value = self.get_text() if value: self.harvest['meta']['created'] = value timestamp = dates.parse_rfc822(value) if timestamp: self.harvest['meta']['created_parsed'] = timestamp else: self.raise_bozo('dateCreated is not an RFC 822 datetime') start_opml_dateModified = common.CommonMixin.expect_text def end_opml_dateModified(self): value = self.get_text() if value: self.harvest['meta']['modified'] = value timestamp = dates.parse_rfc822(value) if timestamp: self.harvest['meta']['modified_parsed'] = timestamp else: self.raise_bozo('dateModified is not an RFC 822 datetime')
# This file is part of listparser. # Copyright 2009-2021 <NAME> <<EMAIL>> # SPDX-License-Identifier: MIT # import copy from . import common from . import dates class OpmlMixin(common.CommonMixin): def start_opml_opml(self, attrs): self.harvest['version'] = 'opml' if attrs.get('version') in ('1.0', '1.1'): self.harvest['version'] = 'opml1' elif attrs.get('version') == '2.0': self.harvest['version'] = 'opml2' def start_opml_outline(self, attrs): url = None # Find an appropriate title in @text or @title (else empty) if attrs.get('text', '').strip(): title = attrs['text'].strip() else: title = attrs.get('title', '').strip() # Search for the URL regardless of xmlUrl's case for k, v in attrs.items(): if k.lower() == 'xmlurl': url = v.strip() break append_to = None # Determine whether the outline is a feed or subscription list if url is not None: # It's a feed append_to = 'feeds' if attrs.get('type', '').strip().lower() == 'source': # Actually, it's a subscription list! append_to = 'lists' elif attrs.get('type', '').lower() in ('link', 'include'): # It's a subscription list append_to = 'lists' url = attrs.get('url', '').strip() elif title: # Assume that this is a grouping node self.hierarchy.append(title) return # Look for an opportunity URL if not url and 'htmlurl' in (k.lower() for k in attrs.keys()): for k, v in attrs.items(): if k.lower() == 'htmlurl': url = v.strip() append_to = 'opportunities' if not url: # Maintain the hierarchy self.hierarchy.append('') return if url not in self.found_urls and append_to: # This is a brand new URL obj = common.SuperDict({'url': url, 'title': title}) self.found_urls[url] = (append_to, obj) self.harvest[append_to].append(obj) else: obj = self.found_urls[url][1] # Handle categories and tags obj.setdefault('categories', []) if 'category' in attrs.keys(): for i in attrs['category'].split(','): tmp = [j.strip() for j in i.split('/') if j.strip()] if tmp and tmp not in obj['categories']: obj['categories'].append(tmp) # Copy the current hierarchy into `categories` if self.hierarchy and self.hierarchy not in obj['categories']: obj['categories'].append(copy.copy(self.hierarchy)) # Copy all single-element `categories` into `tags` obj['tags'] = [i[0] for i in obj['categories'] if len(i) == 1] self.hierarchy.append('') def end_opml_outline(self): self.hierarchy.pop() start_opml_title = common.CommonMixin.expect_text def end_opml_title(self): value = self.get_text() if value: self.harvest['meta']['title'] = value start_opml_ownerId = common.CommonMixin.expect_text def end_opml_ownerId(self): value = self.get_text() if value: self.harvest['meta'].setdefault('author', common.SuperDict()) self.harvest['meta']['author']['url'] = value start_opml_ownerEmail = common.CommonMixin.expect_text def end_opml_ownerEmail(self): value = self.get_text() if value: self.harvest['meta'].setdefault('author', common.SuperDict()) self.harvest['meta']['author']['email'] = value start_opml_ownerName = common.CommonMixin.expect_text def end_opml_ownerName(self): value = self.get_text() if value: self.harvest['meta'].setdefault('author', common.SuperDict()) self.harvest['meta']['author']['name'] = value start_opml_dateCreated = common.CommonMixin.expect_text def end_opml_dateCreated(self): value = self.get_text() if value: self.harvest['meta']['created'] = value timestamp = dates.parse_rfc822(value) if timestamp: self.harvest['meta']['created_parsed'] = timestamp else: self.raise_bozo('dateCreated is not an RFC 822 datetime') start_opml_dateModified = common.CommonMixin.expect_text def end_opml_dateModified(self): value = self.get_text() if value: self.harvest['meta']['modified'] = value timestamp = dates.parse_rfc822(value) if timestamp: self.harvest['meta']['modified_parsed'] = timestamp else: self.raise_bozo('dateModified is not an RFC 822 datetime')
en
0.613006
# This file is part of listparser. # Copyright 2009-2021 <NAME> <<EMAIL>> # SPDX-License-Identifier: MIT # # Find an appropriate title in @text or @title (else empty) # Search for the URL regardless of xmlUrl's case # Determine whether the outline is a feed or subscription list # It's a feed # Actually, it's a subscription list! # It's a subscription list # Assume that this is a grouping node # Look for an opportunity URL # Maintain the hierarchy # This is a brand new URL # Handle categories and tags # Copy the current hierarchy into `categories` # Copy all single-element `categories` into `tags`
2.22426
2
src/bot.py
AWhiteFox/discord-mafia-bot
1
6622445
import asyncio import os import discord from discord.ext import commands import checks import helpers from game import Game if os.path.isfile('../.env'): from dotenv import load_dotenv load_dotenv(encoding='utf8') bot = commands.Bot(os.environ['PREFIX']) game = None game_state_lock = asyncio.Lock() # Events @bot.event async def on_ready(): global game game = Game(await bot.fetch_guild(int(os.environ['GUILD']))) if 'STATUS' in os.environ: await bot.change_presence(activity=discord.Game(os.environ['STATUS'])) print('Ready!') @bot.event async def on_voice_state_update(member, before, after): if member.bot or not game.is_running(): return # If user joined current voice and game is running if before.channel != game.voice_channel and after.channel == game.voice_channel: await helpers.try_set_prefix(member, game.get_prefix(member)) # If user left current voice elif before.channel == game.voice_channel and after.channel != game.voice_channel: await helpers.try_remove_prefix(member) # Global checks @bot.check async def globally_check_server(ctx): return ctx.guild is None or ctx.guild == game.guild # Commands @bot.command() async def ping(ctx): await ctx.send(f':ping_pong: {round(bot.latency * 1000)}ms') @bot.command(aliases=['begin']) @checks.voice_only() async def start(ctx): async with game_state_lock: if game.is_running(): await ctx.send('Игра уже запущена') return await game.start_game(ctx.author.voice.channel, ctx.author) # Set prefixes await ctx.send(':gear: Раздаем префиксы...') for p in game.players: await helpers.try_set_prefix(p.member, game.get_prefix(p.member)) await ctx.send( f'Игра начинается в **{game.voice_channel}**! Ведущий - {ctx.author.mention}') @bot.command(aliases=['end']) @commands.guild_only() async def finish(ctx): async with game_state_lock: if not game.is_running(): await ctx.send('Игра не запущена') return # Remove prefixes await ctx.send(':gear: Убираем префиксы...') for p in game.voice_channel.members: await helpers.try_remove_prefix(p) await ctx.send(f'Игра в **{game.voice_channel}** завершена') await game.finish_game() # Commands for debugging @bot.command(aliases=['debug_sp']) @commands.is_owner() async def debug_set_prefix(ctx, member: discord.Member, prefix: str): await helpers.try_set_prefix(member, prefix) @bot.command(aliases=['debug_rp']) @commands.is_owner() async def debug_remove_prefix(ctx, member: discord.Member): await helpers.try_remove_prefix(member) bot.run(os.environ['TOKEN'])
import asyncio import os import discord from discord.ext import commands import checks import helpers from game import Game if os.path.isfile('../.env'): from dotenv import load_dotenv load_dotenv(encoding='utf8') bot = commands.Bot(os.environ['PREFIX']) game = None game_state_lock = asyncio.Lock() # Events @bot.event async def on_ready(): global game game = Game(await bot.fetch_guild(int(os.environ['GUILD']))) if 'STATUS' in os.environ: await bot.change_presence(activity=discord.Game(os.environ['STATUS'])) print('Ready!') @bot.event async def on_voice_state_update(member, before, after): if member.bot or not game.is_running(): return # If user joined current voice and game is running if before.channel != game.voice_channel and after.channel == game.voice_channel: await helpers.try_set_prefix(member, game.get_prefix(member)) # If user left current voice elif before.channel == game.voice_channel and after.channel != game.voice_channel: await helpers.try_remove_prefix(member) # Global checks @bot.check async def globally_check_server(ctx): return ctx.guild is None or ctx.guild == game.guild # Commands @bot.command() async def ping(ctx): await ctx.send(f':ping_pong: {round(bot.latency * 1000)}ms') @bot.command(aliases=['begin']) @checks.voice_only() async def start(ctx): async with game_state_lock: if game.is_running(): await ctx.send('Игра уже запущена') return await game.start_game(ctx.author.voice.channel, ctx.author) # Set prefixes await ctx.send(':gear: Раздаем префиксы...') for p in game.players: await helpers.try_set_prefix(p.member, game.get_prefix(p.member)) await ctx.send( f'Игра начинается в **{game.voice_channel}**! Ведущий - {ctx.author.mention}') @bot.command(aliases=['end']) @commands.guild_only() async def finish(ctx): async with game_state_lock: if not game.is_running(): await ctx.send('Игра не запущена') return # Remove prefixes await ctx.send(':gear: Убираем префиксы...') for p in game.voice_channel.members: await helpers.try_remove_prefix(p) await ctx.send(f'Игра в **{game.voice_channel}** завершена') await game.finish_game() # Commands for debugging @bot.command(aliases=['debug_sp']) @commands.is_owner() async def debug_set_prefix(ctx, member: discord.Member, prefix: str): await helpers.try_set_prefix(member, prefix) @bot.command(aliases=['debug_rp']) @commands.is_owner() async def debug_remove_prefix(ctx, member: discord.Member): await helpers.try_remove_prefix(member) bot.run(os.environ['TOKEN'])
en
0.856914
# Events # If user joined current voice and game is running # If user left current voice # Global checks # Commands # Set prefixes # Remove prefixes # Commands for debugging
2.288633
2
01-Native Baise com Python3/NativeBaise.py
sudo-ninguem/Analise-de-dados
0
6622446
## Usando o Native Baise vamos fazer um programa que preveja a probabilidade de acidentes de veiculos import pandas as pd ## Essa é a biblioteca que vamos usar para manipulação de dados from sklearn.model_selection import train_test_split from sklearn.naive_bayes import GaussianNB from sklearn.preprocessing import LabelEncoder from sklearn.metrics import accuracy_score ## Essa biblioteca permite fazermos a divisão entre os dados que serão utilizados para treino e para teste from yellowbrick.classifier import ConfusionMatrix ## Essa biblioteca vai nos permitir visualizar a matriz de confusão baseDados = pd.read_csv('insurance.csv') ## Nos estamos colocando dentro da váriavel (baseDados) os dados da planilha baseDados = baseDados.drop(columns=['Unnamed: 0']) ''' Bom geralmente por ordenação do banco de dados geralmente se coloca um indice em cada linha da coluna para poder manter um maior controle. Essa planilha de exemplo que estamos usando também tem esses indices na primeira coluna (para o Python começa do 0) sendo assim para evitar que esses números interfiram nos nossos calculos vamos apagar essa coluna referente ao indice CUIDADO PARA NÃO APAGAR COLUNA ERRADA ''' baseDados.Accident.unique() ## Aqui estamos só visualizando a coluna aonde esta nossas classes (o codigo não funcinou) ''' Nesse banco de dados de exemplo o NOME DA COLUNA AONDE ESTA NOSSAS CLASSES É "ACCIDENT". Nesta tabela não se adotou a convenção de colocar a classe como a ultima coluna da tabela, mas depois vamos fazer a repartição ''' atributos = baseDados.iloc[:,[0,1,2,3,4,5,6,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26]].values ''' Dentro das váriaveis atributos vamos guardar os atributos do nosso banco de dados, repare que temos todas as colunas com os atributos EatributosCETO A COLUNA 7 que é justamente a coluna com a nossa classe. além disso note que no final usamos um (.values) para deixar esses dados no formato suportado pelo Native Base Outra coisa que devemos observar é que o método que vai percorrer e retirar os elementos da variável para outra é o (.iloc) a primeira os primeiros colchetes com 2 pontos [:] significa que queremos percorrer TODAS AS LINHAS da nossa tabela. O segundo colchete com os números de tabela representa QUAIS COLUNAS QUEREMOS PASSAR PARA NOSSA VÁRIAVEL MAIS UMA VEZ REPARE QUE NÃO ESTAMOS PEGANDO A COLUNA REFERENTE A CLASSE ''' classe = baseDados.iloc[:,7].values ## Aqui é a mesma ideia criando uma váriavel para conter somente a coluna da nossa classe ####################### TRANSFORMAÇÃO DOS DADOS #################################### ''' Se olharmos nossa tabela e até mesmo nossas váriaveis vamos ver que os dados guardados dentro dela estão no formato literal (texto) entretanto o mais adequado, até mesmo por questão de processamento de dados, é utilizar valores numericos representando cada um dos elementos dos atributos atributos. Para fazer essa conversão podemos usar a função LabelEncoder() das bibliotecas que baixamos, mas para que possamos fazer em cada um dos valores de cada atributo devemos percorrer TODOS OS ATRIBUTOS. ''' labelencoder = LabelEncoder() ## Para não ter que ficar chamando a função toda hora vamos colocar a função LabelEncoder() dentro da váriavel atributos[:,0] = labelencoder.fit_transform(atributos[:,0]) atributos[:,1] = labelencoder.fit_transform(atributos[:,1]) atributos[:,2] = labelencoder.fit_transform(atributos[:,2]) atributos[:,3] = labelencoder.fit_transform(atributos[:,3]) atributos[:,4] = labelencoder.fit_transform(atributos[:,4]) atributos[:,5] = labelencoder.fit_transform(atributos[:,5]) atributos[:,6] = labelencoder.fit_transform(atributos[:,6]) atributos[:,7] = labelencoder.fit_transform(atributos[:,7]) atributos[:,8] = labelencoder.fit_transform(atributos[:,8]) atributos[:,9] = labelencoder.fit_transform(atributos[:,9]) atributos[:,10] = labelencoder.fit_transform(atributos[:,10]) atributos[:,11] = labelencoder.fit_transform(atributos[:,11]) atributos[:,12] = labelencoder.fit_transform(atributos[:,12]) atributos[:,13] = labelencoder.fit_transform(atributos[:,13]) atributos[:,14] = labelencoder.fit_transform(atributos[:,14]) atributos[:,15] = labelencoder.fit_transform(atributos[:,15]) atributos[:,16] = labelencoder.fit_transform(atributos[:,16]) atributos[:,17] = labelencoder.fit_transform(atributos[:,17]) atributos[:,18] = labelencoder.fit_transform(atributos[:,18]) atributos[:,19] = labelencoder.fit_transform(atributos[:,19]) atributos[:,20] = labelencoder.fit_transform(atributos[:,20]) atributos[:,21] = labelencoder.fit_transform(atributos[:,21]) atributos[:,22] = labelencoder.fit_transform(atributos[:,22]) atributos[:,23] = labelencoder.fit_transform(atributos[:,23]) atributos[:,24] = labelencoder.fit_transform(atributos[:,24]) atributos[:,25] = labelencoder.fit_transform(atributos[:,25]) ''' Aqui estamos justamente fazendo a TRANSFORMAÇÃO de cada atributo percorrendo toda a linha dele poderiamos usar um laço for, mas por questões didaticas foi feito dessa forma manual ''' ################################ CRIANDO AS VÁRIAVEIS PARA TREINO E TESTE ############################# atributosTreinamentos, atributosTestes, classeTreinamento, classeTeste = train_test_split(atributos, classe, test_size = 0.3, random_state = 0) ## aqui criamos váriaveis para receber dados de trei e de teste usando dados tanto de atributos quanto de classe ## usamos a função (train_test_split) que tinhamos baixado na biblioteca anterior. ## Note que essa função recebe como parametro na ordem os atributos e a classe ## Além disso devemos passar como parametro o (test_size) que é a quantidade por cento que queremos para teste. ## neste caso passamos 30% (0.3) ao passo que por consequencia os outros 70% (0.7) serão para treino ## o último parametro que devemos passar agora é o (random_state) para que definirmos quais dados usar ## neste caso como passamos o parametro (0) indica que queremos usar os mesmos dados. modelo = GaussianNB() ## Neste caso estamos criando o modelo usando a formula gausean Native Baise dentro da váriavel (modelo) modelo.fit(atributosTreinamentos, classeTreinamento) ''' Agora usamos a váriavel modelo (aonde está a native baise) para gerar o modelo usando os dados de treinamento.. No Python não temos como ver os modelos gerados (como ocorre no weka) perceba que para gerar o modelo usamos o método (.fit) ''' previsoes = modelo.predict(atributosTestes) ''' Agora nos criamos uma váriavel para, usando o modelo gerado anteriormente, fazermos os testes com os dados do (atributoTeste). Perceba que para gerar os testes usamos o método (.predict) Com as (previsoes) usando os atributos de Testes geramos previsoes que usando nossa I.A. Podemos comparar as (previsoes) com as (classesTestes), pois ela vai ter as respostas corretas assim podemos já observar a porcentagem de acerto da nossa I.A ''' acuracidade = accuracy_score(classeTeste, previsoes) ''' Usando a função (accuracy_score) passando como párametro a classeTeste e a nossá váriavel de previsões podemos gerar o valor de porcentagem de acertos da nossa I.A Neste exemplo nossa I.A acertou 0.8658 (86%) ''' ############################### MATRIZ DE CONFUSÃO ################################## ''' Por meio da nossa biblioteca (ConfusionMatrix) podemos gerar a matriz de confusão em Python mostrando assim de forma mais clara como foi o percentual de acerto da nossa I.A ''' confusao = ConfusionMatrix(modelo, classes= ["Nenhum", "Severo", "Leve", "Moderado"] ) confusao.fit(atributosTreinamentos, classeTreinamento) confusao.score(atributosTestes,classeTeste) confusao.poof() confusao = ConfusionMatrix(modelo, classes= ["None", "Severe", "Mild", "Moderate"] ) confusao.fit(atributosTreinamentos, classeTreinamento) confusao.score(atributosTestes,classeTeste) confusao.poof()
## Usando o Native Baise vamos fazer um programa que preveja a probabilidade de acidentes de veiculos import pandas as pd ## Essa é a biblioteca que vamos usar para manipulação de dados from sklearn.model_selection import train_test_split from sklearn.naive_bayes import GaussianNB from sklearn.preprocessing import LabelEncoder from sklearn.metrics import accuracy_score ## Essa biblioteca permite fazermos a divisão entre os dados que serão utilizados para treino e para teste from yellowbrick.classifier import ConfusionMatrix ## Essa biblioteca vai nos permitir visualizar a matriz de confusão baseDados = pd.read_csv('insurance.csv') ## Nos estamos colocando dentro da váriavel (baseDados) os dados da planilha baseDados = baseDados.drop(columns=['Unnamed: 0']) ''' Bom geralmente por ordenação do banco de dados geralmente se coloca um indice em cada linha da coluna para poder manter um maior controle. Essa planilha de exemplo que estamos usando também tem esses indices na primeira coluna (para o Python começa do 0) sendo assim para evitar que esses números interfiram nos nossos calculos vamos apagar essa coluna referente ao indice CUIDADO PARA NÃO APAGAR COLUNA ERRADA ''' baseDados.Accident.unique() ## Aqui estamos só visualizando a coluna aonde esta nossas classes (o codigo não funcinou) ''' Nesse banco de dados de exemplo o NOME DA COLUNA AONDE ESTA NOSSAS CLASSES É "ACCIDENT". Nesta tabela não se adotou a convenção de colocar a classe como a ultima coluna da tabela, mas depois vamos fazer a repartição ''' atributos = baseDados.iloc[:,[0,1,2,3,4,5,6,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26]].values ''' Dentro das váriaveis atributos vamos guardar os atributos do nosso banco de dados, repare que temos todas as colunas com os atributos EatributosCETO A COLUNA 7 que é justamente a coluna com a nossa classe. além disso note que no final usamos um (.values) para deixar esses dados no formato suportado pelo Native Base Outra coisa que devemos observar é que o método que vai percorrer e retirar os elementos da variável para outra é o (.iloc) a primeira os primeiros colchetes com 2 pontos [:] significa que queremos percorrer TODAS AS LINHAS da nossa tabela. O segundo colchete com os números de tabela representa QUAIS COLUNAS QUEREMOS PASSAR PARA NOSSA VÁRIAVEL MAIS UMA VEZ REPARE QUE NÃO ESTAMOS PEGANDO A COLUNA REFERENTE A CLASSE ''' classe = baseDados.iloc[:,7].values ## Aqui é a mesma ideia criando uma váriavel para conter somente a coluna da nossa classe ####################### TRANSFORMAÇÃO DOS DADOS #################################### ''' Se olharmos nossa tabela e até mesmo nossas váriaveis vamos ver que os dados guardados dentro dela estão no formato literal (texto) entretanto o mais adequado, até mesmo por questão de processamento de dados, é utilizar valores numericos representando cada um dos elementos dos atributos atributos. Para fazer essa conversão podemos usar a função LabelEncoder() das bibliotecas que baixamos, mas para que possamos fazer em cada um dos valores de cada atributo devemos percorrer TODOS OS ATRIBUTOS. ''' labelencoder = LabelEncoder() ## Para não ter que ficar chamando a função toda hora vamos colocar a função LabelEncoder() dentro da váriavel atributos[:,0] = labelencoder.fit_transform(atributos[:,0]) atributos[:,1] = labelencoder.fit_transform(atributos[:,1]) atributos[:,2] = labelencoder.fit_transform(atributos[:,2]) atributos[:,3] = labelencoder.fit_transform(atributos[:,3]) atributos[:,4] = labelencoder.fit_transform(atributos[:,4]) atributos[:,5] = labelencoder.fit_transform(atributos[:,5]) atributos[:,6] = labelencoder.fit_transform(atributos[:,6]) atributos[:,7] = labelencoder.fit_transform(atributos[:,7]) atributos[:,8] = labelencoder.fit_transform(atributos[:,8]) atributos[:,9] = labelencoder.fit_transform(atributos[:,9]) atributos[:,10] = labelencoder.fit_transform(atributos[:,10]) atributos[:,11] = labelencoder.fit_transform(atributos[:,11]) atributos[:,12] = labelencoder.fit_transform(atributos[:,12]) atributos[:,13] = labelencoder.fit_transform(atributos[:,13]) atributos[:,14] = labelencoder.fit_transform(atributos[:,14]) atributos[:,15] = labelencoder.fit_transform(atributos[:,15]) atributos[:,16] = labelencoder.fit_transform(atributos[:,16]) atributos[:,17] = labelencoder.fit_transform(atributos[:,17]) atributos[:,18] = labelencoder.fit_transform(atributos[:,18]) atributos[:,19] = labelencoder.fit_transform(atributos[:,19]) atributos[:,20] = labelencoder.fit_transform(atributos[:,20]) atributos[:,21] = labelencoder.fit_transform(atributos[:,21]) atributos[:,22] = labelencoder.fit_transform(atributos[:,22]) atributos[:,23] = labelencoder.fit_transform(atributos[:,23]) atributos[:,24] = labelencoder.fit_transform(atributos[:,24]) atributos[:,25] = labelencoder.fit_transform(atributos[:,25]) ''' Aqui estamos justamente fazendo a TRANSFORMAÇÃO de cada atributo percorrendo toda a linha dele poderiamos usar um laço for, mas por questões didaticas foi feito dessa forma manual ''' ################################ CRIANDO AS VÁRIAVEIS PARA TREINO E TESTE ############################# atributosTreinamentos, atributosTestes, classeTreinamento, classeTeste = train_test_split(atributos, classe, test_size = 0.3, random_state = 0) ## aqui criamos váriaveis para receber dados de trei e de teste usando dados tanto de atributos quanto de classe ## usamos a função (train_test_split) que tinhamos baixado na biblioteca anterior. ## Note que essa função recebe como parametro na ordem os atributos e a classe ## Além disso devemos passar como parametro o (test_size) que é a quantidade por cento que queremos para teste. ## neste caso passamos 30% (0.3) ao passo que por consequencia os outros 70% (0.7) serão para treino ## o último parametro que devemos passar agora é o (random_state) para que definirmos quais dados usar ## neste caso como passamos o parametro (0) indica que queremos usar os mesmos dados. modelo = GaussianNB() ## Neste caso estamos criando o modelo usando a formula gausean Native Baise dentro da váriavel (modelo) modelo.fit(atributosTreinamentos, classeTreinamento) ''' Agora usamos a váriavel modelo (aonde está a native baise) para gerar o modelo usando os dados de treinamento.. No Python não temos como ver os modelos gerados (como ocorre no weka) perceba que para gerar o modelo usamos o método (.fit) ''' previsoes = modelo.predict(atributosTestes) ''' Agora nos criamos uma váriavel para, usando o modelo gerado anteriormente, fazermos os testes com os dados do (atributoTeste). Perceba que para gerar os testes usamos o método (.predict) Com as (previsoes) usando os atributos de Testes geramos previsoes que usando nossa I.A. Podemos comparar as (previsoes) com as (classesTestes), pois ela vai ter as respostas corretas assim podemos já observar a porcentagem de acerto da nossa I.A ''' acuracidade = accuracy_score(classeTeste, previsoes) ''' Usando a função (accuracy_score) passando como párametro a classeTeste e a nossá váriavel de previsões podemos gerar o valor de porcentagem de acertos da nossa I.A Neste exemplo nossa I.A acertou 0.8658 (86%) ''' ############################### MATRIZ DE CONFUSÃO ################################## ''' Por meio da nossa biblioteca (ConfusionMatrix) podemos gerar a matriz de confusão em Python mostrando assim de forma mais clara como foi o percentual de acerto da nossa I.A ''' confusao = ConfusionMatrix(modelo, classes= ["Nenhum", "Severo", "Leve", "Moderado"] ) confusao.fit(atributosTreinamentos, classeTreinamento) confusao.score(atributosTestes,classeTeste) confusao.poof() confusao = ConfusionMatrix(modelo, classes= ["None", "Severe", "Mild", "Moderate"] ) confusao.fit(atributosTreinamentos, classeTreinamento) confusao.score(atributosTestes,classeTeste) confusao.poof()
pt
0.932501
## Usando o Native Baise vamos fazer um programa que preveja a probabilidade de acidentes de veiculos ## Essa é a biblioteca que vamos usar para manipulação de dados ## Essa biblioteca permite fazermos a divisão entre os dados que serão utilizados para treino e para teste ## Essa biblioteca vai nos permitir visualizar a matriz de confusão ## Nos estamos colocando dentro da váriavel (baseDados) os dados da planilha Bom geralmente por ordenação do banco de dados geralmente se coloca um indice em cada linha da coluna para poder manter um maior controle. Essa planilha de exemplo que estamos usando também tem esses indices na primeira coluna (para o Python começa do 0) sendo assim para evitar que esses números interfiram nos nossos calculos vamos apagar essa coluna referente ao indice CUIDADO PARA NÃO APAGAR COLUNA ERRADA ## Aqui estamos só visualizando a coluna aonde esta nossas classes (o codigo não funcinou) Nesse banco de dados de exemplo o NOME DA COLUNA AONDE ESTA NOSSAS CLASSES É "ACCIDENT". Nesta tabela não se adotou a convenção de colocar a classe como a ultima coluna da tabela, mas depois vamos fazer a repartição Dentro das váriaveis atributos vamos guardar os atributos do nosso banco de dados, repare que temos todas as colunas com os atributos EatributosCETO A COLUNA 7 que é justamente a coluna com a nossa classe. além disso note que no final usamos um (.values) para deixar esses dados no formato suportado pelo Native Base Outra coisa que devemos observar é que o método que vai percorrer e retirar os elementos da variável para outra é o (.iloc) a primeira os primeiros colchetes com 2 pontos [:] significa que queremos percorrer TODAS AS LINHAS da nossa tabela. O segundo colchete com os números de tabela representa QUAIS COLUNAS QUEREMOS PASSAR PARA NOSSA VÁRIAVEL MAIS UMA VEZ REPARE QUE NÃO ESTAMOS PEGANDO A COLUNA REFERENTE A CLASSE ## Aqui é a mesma ideia criando uma váriavel para conter somente a coluna da nossa classe ####################### TRANSFORMAÇÃO DOS DADOS #################################### Se olharmos nossa tabela e até mesmo nossas váriaveis vamos ver que os dados guardados dentro dela estão no formato literal (texto) entretanto o mais adequado, até mesmo por questão de processamento de dados, é utilizar valores numericos representando cada um dos elementos dos atributos atributos. Para fazer essa conversão podemos usar a função LabelEncoder() das bibliotecas que baixamos, mas para que possamos fazer em cada um dos valores de cada atributo devemos percorrer TODOS OS ATRIBUTOS. ## Para não ter que ficar chamando a função toda hora vamos colocar a função LabelEncoder() dentro da váriavel Aqui estamos justamente fazendo a TRANSFORMAÇÃO de cada atributo percorrendo toda a linha dele poderiamos usar um laço for, mas por questões didaticas foi feito dessa forma manual ################################ CRIANDO AS VÁRIAVEIS PARA TREINO E TESTE ############################# ## aqui criamos váriaveis para receber dados de trei e de teste usando dados tanto de atributos quanto de classe ## usamos a função (train_test_split) que tinhamos baixado na biblioteca anterior. ## Note que essa função recebe como parametro na ordem os atributos e a classe ## Além disso devemos passar como parametro o (test_size) que é a quantidade por cento que queremos para teste. ## neste caso passamos 30% (0.3) ao passo que por consequencia os outros 70% (0.7) serão para treino ## o último parametro que devemos passar agora é o (random_state) para que definirmos quais dados usar ## neste caso como passamos o parametro (0) indica que queremos usar os mesmos dados. ## Neste caso estamos criando o modelo usando a formula gausean Native Baise dentro da váriavel (modelo) Agora usamos a váriavel modelo (aonde está a native baise) para gerar o modelo usando os dados de treinamento.. No Python não temos como ver os modelos gerados (como ocorre no weka) perceba que para gerar o modelo usamos o método (.fit) Agora nos criamos uma váriavel para, usando o modelo gerado anteriormente, fazermos os testes com os dados do (atributoTeste). Perceba que para gerar os testes usamos o método (.predict) Com as (previsoes) usando os atributos de Testes geramos previsoes que usando nossa I.A. Podemos comparar as (previsoes) com as (classesTestes), pois ela vai ter as respostas corretas assim podemos já observar a porcentagem de acerto da nossa I.A Usando a função (accuracy_score) passando como párametro a classeTeste e a nossá váriavel de previsões podemos gerar o valor de porcentagem de acertos da nossa I.A Neste exemplo nossa I.A acertou 0.8658 (86%) ############################### MATRIZ DE CONFUSÃO ################################## Por meio da nossa biblioteca (ConfusionMatrix) podemos gerar a matriz de confusão em Python mostrando assim de forma mais clara como foi o percentual de acerto da nossa I.A
2.828327
3
vnpy/app/cta_strategy/strategies/momentum_hunter_strategy.py
tonywanggit/vnpy
11
6622447
from vnpy.app.cta_strategy import ( CtaTemplate, StopOrder, TickData, BarData, TradeData, OrderData, BarGenerator, ArrayManager, ) class MomentumHunterStrategy(CtaTemplate): """""" author = "KEKE" boll_window = 36 boll_dev = 2 atr_window = 30 atr_ma_window = 20 exit_window = 40 rsi_window = 30 rsi_entry = 14 dis_open = 56 dis_salir = 10 ultosc_entry = 14 fixed_size = 10 boll_up = 0 boll_down = 0 rsi_trend = 0 atr_value = 0 exit_up = 0 exit_down = 0 aroonosc_value = 0 trading_size = 0 parameters = [ "boll_window", "boll_dev", "atr_window", "dis_open", "dis_salir", "exit_window", "rsi_window", "rsi_entry", "ultosc_entry", "fixed_size" ] variables = [ "boll_up", "boll_down", "atr_value", "rsi_trend", "exit_up", "exit_down", "aroonosc_value", "trading_size" ] def __init__(self, cta_engine, strategy_name, vt_symbol, setting): """""" super().__init__(cta_engine, strategy_name, vt_symbol, setting) self.bg = BarGenerator(self.on_bar, 30, self.on_30min_bar) self.am = ArrayManager() self.bg2 = BarGenerator(self.on_bar, 60, self.on_60min_bar) self.am2 = ArrayManager() def on_init(self): """ Callback when strategy is inited. """ self.write_log("策略初始化") self.rsi_buy = 50 + self.rsi_entry self.rsi_sell = 50 - self.rsi_entry self.ultosc_buy = 50 + self.ultosc_entry self.ultosc_sell = 50 - self.ultosc_entry self.load_bar(10) def on_start(self): """ Callback when strategy is started. """ self.write_log("策略启动") def on_stop(self): """ Callback when strategy is stopped. """ self.write_log("策略停止") def on_tick(self, tick: TickData): """ Callback of new tick data update. """ self.bg.update_tick(tick) def on_bar(self, bar: BarData): """ Callback of new bar data update. """ self.bg.update_bar(bar) self.bg2.update_bar(bar) def on_30min_bar(self, bar: BarData): """""" self.cancel_all() am = self.am am.update_bar(bar) if not am.inited: return self.aroonosc_value = am.aroonosc(self.boll_window) self.exit_up, self.exit_down = self.am.donchian(self.exit_window) atr_array = am.atr(self.atr_window, array=True) self.atr_value = atr_array[-1] self.atr_ma = atr_array[-self.atr_ma_window:].mean() if self.pos == 0: self.trading_size = self.fixed_size * bar.close_price if self.atr_value > self.atr_ma and self.rsi_trend > 0: if self.aroonosc_value > self.dis_open: self.buy(bar.close_price + 10, self.trading_size) elif self.atr_value > self.atr_ma and self.rsi_trend < 0: if self.aroonosc_value < -self.dis_open: self.short(bar.close_price - 10, self.trading_size) elif self.pos > 0: if bar.low_price < (self.exit_down + self.dis_salir): self.sell(bar.close_price - 10, abs(self.pos)) elif self.pos < 0: if bar.high_price > (self.exit_up - self.dis_salir): self.cover(bar.close_price + 10, abs(self.pos)) self.put_event() def on_60min_bar(self, bar: BarData): """""" am2 = self.am2 am2.update_bar(bar) if not am2.inited: return ultosc_value = am2.ultosc() rsi_value = am2.rsi(self.rsi_window) if rsi_value > self.rsi_buy and ultosc_value > self.ultosc_buy: self.rsi_trend = 1 elif rsi_value < self.rsi_sell and ultosc_value < self.ultosc_sell: self.rsi_trend = -1 def on_order(self, order: OrderData): """ Callback of new order data update. """ pass def on_trade(self, trade: TradeData): """ Callback of new trade data update. """ self.put_event() def on_stop_order(self, stop_order: StopOrder): """ Callback of stop order update. """ pass
from vnpy.app.cta_strategy import ( CtaTemplate, StopOrder, TickData, BarData, TradeData, OrderData, BarGenerator, ArrayManager, ) class MomentumHunterStrategy(CtaTemplate): """""" author = "KEKE" boll_window = 36 boll_dev = 2 atr_window = 30 atr_ma_window = 20 exit_window = 40 rsi_window = 30 rsi_entry = 14 dis_open = 56 dis_salir = 10 ultosc_entry = 14 fixed_size = 10 boll_up = 0 boll_down = 0 rsi_trend = 0 atr_value = 0 exit_up = 0 exit_down = 0 aroonosc_value = 0 trading_size = 0 parameters = [ "boll_window", "boll_dev", "atr_window", "dis_open", "dis_salir", "exit_window", "rsi_window", "rsi_entry", "ultosc_entry", "fixed_size" ] variables = [ "boll_up", "boll_down", "atr_value", "rsi_trend", "exit_up", "exit_down", "aroonosc_value", "trading_size" ] def __init__(self, cta_engine, strategy_name, vt_symbol, setting): """""" super().__init__(cta_engine, strategy_name, vt_symbol, setting) self.bg = BarGenerator(self.on_bar, 30, self.on_30min_bar) self.am = ArrayManager() self.bg2 = BarGenerator(self.on_bar, 60, self.on_60min_bar) self.am2 = ArrayManager() def on_init(self): """ Callback when strategy is inited. """ self.write_log("策略初始化") self.rsi_buy = 50 + self.rsi_entry self.rsi_sell = 50 - self.rsi_entry self.ultosc_buy = 50 + self.ultosc_entry self.ultosc_sell = 50 - self.ultosc_entry self.load_bar(10) def on_start(self): """ Callback when strategy is started. """ self.write_log("策略启动") def on_stop(self): """ Callback when strategy is stopped. """ self.write_log("策略停止") def on_tick(self, tick: TickData): """ Callback of new tick data update. """ self.bg.update_tick(tick) def on_bar(self, bar: BarData): """ Callback of new bar data update. """ self.bg.update_bar(bar) self.bg2.update_bar(bar) def on_30min_bar(self, bar: BarData): """""" self.cancel_all() am = self.am am.update_bar(bar) if not am.inited: return self.aroonosc_value = am.aroonosc(self.boll_window) self.exit_up, self.exit_down = self.am.donchian(self.exit_window) atr_array = am.atr(self.atr_window, array=True) self.atr_value = atr_array[-1] self.atr_ma = atr_array[-self.atr_ma_window:].mean() if self.pos == 0: self.trading_size = self.fixed_size * bar.close_price if self.atr_value > self.atr_ma and self.rsi_trend > 0: if self.aroonosc_value > self.dis_open: self.buy(bar.close_price + 10, self.trading_size) elif self.atr_value > self.atr_ma and self.rsi_trend < 0: if self.aroonosc_value < -self.dis_open: self.short(bar.close_price - 10, self.trading_size) elif self.pos > 0: if bar.low_price < (self.exit_down + self.dis_salir): self.sell(bar.close_price - 10, abs(self.pos)) elif self.pos < 0: if bar.high_price > (self.exit_up - self.dis_salir): self.cover(bar.close_price + 10, abs(self.pos)) self.put_event() def on_60min_bar(self, bar: BarData): """""" am2 = self.am2 am2.update_bar(bar) if not am2.inited: return ultosc_value = am2.ultosc() rsi_value = am2.rsi(self.rsi_window) if rsi_value > self.rsi_buy and ultosc_value > self.ultosc_buy: self.rsi_trend = 1 elif rsi_value < self.rsi_sell and ultosc_value < self.ultosc_sell: self.rsi_trend = -1 def on_order(self, order: OrderData): """ Callback of new order data update. """ pass def on_trade(self, trade: TradeData): """ Callback of new trade data update. """ self.put_event() def on_stop_order(self, stop_order: StopOrder): """ Callback of stop order update. """ pass
en
0.637756
Callback when strategy is inited. Callback when strategy is started. Callback when strategy is stopped. Callback of new tick data update. Callback of new bar data update. Callback of new order data update. Callback of new trade data update. Callback of stop order update.
2.16334
2
ConformanceTests/TestPlugins/check_crd_status/check_crd_status.py
akashkeshari/arc-conformance-tests
0
6622448
<reponame>akashkeshari/arc-conformance-tests<gh_stars>0 import atexit import os import sys from junit_xml import TestCase from kubernetes import config, client from results_utility import save_results, create_results_dir, append_result_output from kubernetes_crd_utility import watch_crd_instance # This directory contains all result files corresponding to sonobuoy test run RESULTS_DIR = '/tmp/results' # Name of the tarfile containing all the result files RESULTS_TAR_FILENAME = 'results.tar.gz' # This file needs to be updated with the path to results file so that the sonobuoy worker understands that the test plugin container has completed its work. DONE_FILE = RESULTS_DIR + '/done' # This file is used to dump any logs from the test run OUT_FILE = RESULTS_DIR + '/out' # This file contains test result in xml formal. It will be used by sonobuoy to determine if the test passed/failed RESULT_FILE = RESULTS_DIR + '/result.xml' # Creating the results directory create_results_dir(RESULTS_DIR) # The exit code of the test. Defaults to 1 EXIT_CODE = 1 # Creating a test case for the test run test_cases = [TestCase('check-crd-instance')] # Saving results when code exits atexit.register(save_results, RESULTS_TAR_FILENAME, RESULTS_DIR, RESULT_FILE, DONE_FILE, EXIT_CODE, test_cases) # Loading in-cluster kube-config try: config.load_incluster_config() except Exception as e: sys.exit("Error loading the in-cluster config: " + str(e)) # Check environment variables crd_group = os.getenv('CRD_GROUP') if not crd_group: sys.exit('ERROR: variable CRD_GROUP is required.') crd_version = os.getenv('CRD_VERSION') if not crd_version: sys.exit('ERROR: variable CRD_VERSION is required.') crd_namespace = os.getenv('CRD_NAMESPACE') if not crd_namespace: sys.exit('ERROR: variable CRD_NAMESPACE is required.') crd_plural = os.getenv('CRD_PLURAL') if not crd_plural: sys.exit('ERROR: variable CRD_PLURAL is required.') crd_name = os.getenv('CRD_NAME') if not crd_name: sys.exit('ERROR: variable CRD_NAME is required.') # Setting a list of status fields that will be monitored for presence in the CRD instance events global status_list status_list = [] if os.getenv('CRD_STATUS_FIELDS'): # This environment variable should be provided as comma separated status fields that we want to monitor for the CRD instance crd_status_fields_list = os.getenv('CRD_STATUS_FIELDS').split(',') for status_fields in crd_status_fields_list: status_list.append(status_fields.strip()) append_result_output("Status List: {}\n".format(status_list), OUT_FILE) print("Generated the status fields list.") # The callback function to check if the crd event received has been updated with the status fields def crd_event_callback(event): try: append_result_output("{}\n".format(event), OUT_FILE) status_list = globals()['status_list'] crd_status = event['raw_object'].get('status') if not crd_status: return False for status_fields in status_list: if not crd_status.get(status_fields): return False return True except Exception as e: sys.exit("Error occured while processing crd event: " + str(e)) # Checking if CRD instance has been updated with status fields timeout = int(os.getenv('TIMEOUT')) if os.getenv('TIMEOUT') else 300 api_instance = client.CustomObjectsApi() watch_crd_instance(api_instance, crd_group, crd_version, crd_namespace, crd_plural, crd_name, timeout, crd_event_callback) print("The status fields have been successfully updated in the CRD instance") # Exit with success EXIT_CODE = 0 atexit.unregister(save_results) atexit.register(save_results, RESULTS_TAR_FILENAME, RESULTS_DIR, RESULT_FILE, DONE_FILE, EXIT_CODE, test_cases)
import atexit import os import sys from junit_xml import TestCase from kubernetes import config, client from results_utility import save_results, create_results_dir, append_result_output from kubernetes_crd_utility import watch_crd_instance # This directory contains all result files corresponding to sonobuoy test run RESULTS_DIR = '/tmp/results' # Name of the tarfile containing all the result files RESULTS_TAR_FILENAME = 'results.tar.gz' # This file needs to be updated with the path to results file so that the sonobuoy worker understands that the test plugin container has completed its work. DONE_FILE = RESULTS_DIR + '/done' # This file is used to dump any logs from the test run OUT_FILE = RESULTS_DIR + '/out' # This file contains test result in xml formal. It will be used by sonobuoy to determine if the test passed/failed RESULT_FILE = RESULTS_DIR + '/result.xml' # Creating the results directory create_results_dir(RESULTS_DIR) # The exit code of the test. Defaults to 1 EXIT_CODE = 1 # Creating a test case for the test run test_cases = [TestCase('check-crd-instance')] # Saving results when code exits atexit.register(save_results, RESULTS_TAR_FILENAME, RESULTS_DIR, RESULT_FILE, DONE_FILE, EXIT_CODE, test_cases) # Loading in-cluster kube-config try: config.load_incluster_config() except Exception as e: sys.exit("Error loading the in-cluster config: " + str(e)) # Check environment variables crd_group = os.getenv('CRD_GROUP') if not crd_group: sys.exit('ERROR: variable CRD_GROUP is required.') crd_version = os.getenv('CRD_VERSION') if not crd_version: sys.exit('ERROR: variable CRD_VERSION is required.') crd_namespace = os.getenv('CRD_NAMESPACE') if not crd_namespace: sys.exit('ERROR: variable CRD_NAMESPACE is required.') crd_plural = os.getenv('CRD_PLURAL') if not crd_plural: sys.exit('ERROR: variable CRD_PLURAL is required.') crd_name = os.getenv('CRD_NAME') if not crd_name: sys.exit('ERROR: variable CRD_NAME is required.') # Setting a list of status fields that will be monitored for presence in the CRD instance events global status_list status_list = [] if os.getenv('CRD_STATUS_FIELDS'): # This environment variable should be provided as comma separated status fields that we want to monitor for the CRD instance crd_status_fields_list = os.getenv('CRD_STATUS_FIELDS').split(',') for status_fields in crd_status_fields_list: status_list.append(status_fields.strip()) append_result_output("Status List: {}\n".format(status_list), OUT_FILE) print("Generated the status fields list.") # The callback function to check if the crd event received has been updated with the status fields def crd_event_callback(event): try: append_result_output("{}\n".format(event), OUT_FILE) status_list = globals()['status_list'] crd_status = event['raw_object'].get('status') if not crd_status: return False for status_fields in status_list: if not crd_status.get(status_fields): return False return True except Exception as e: sys.exit("Error occured while processing crd event: " + str(e)) # Checking if CRD instance has been updated with status fields timeout = int(os.getenv('TIMEOUT')) if os.getenv('TIMEOUT') else 300 api_instance = client.CustomObjectsApi() watch_crd_instance(api_instance, crd_group, crd_version, crd_namespace, crd_plural, crd_name, timeout, crd_event_callback) print("The status fields have been successfully updated in the CRD instance") # Exit with success EXIT_CODE = 0 atexit.unregister(save_results) atexit.register(save_results, RESULTS_TAR_FILENAME, RESULTS_DIR, RESULT_FILE, DONE_FILE, EXIT_CODE, test_cases)
en
0.879817
# This directory contains all result files corresponding to sonobuoy test run # Name of the tarfile containing all the result files # This file needs to be updated with the path to results file so that the sonobuoy worker understands that the test plugin container has completed its work. # This file is used to dump any logs from the test run # This file contains test result in xml formal. It will be used by sonobuoy to determine if the test passed/failed # Creating the results directory # The exit code of the test. Defaults to 1 # Creating a test case for the test run # Saving results when code exits # Loading in-cluster kube-config # Check environment variables # Setting a list of status fields that will be monitored for presence in the CRD instance events # This environment variable should be provided as comma separated status fields that we want to monitor for the CRD instance # The callback function to check if the crd event received has been updated with the status fields # Checking if CRD instance has been updated with status fields # Exit with success
2.196256
2
RPG/classes.py
lmello0/rpg-estudo
0
6622449
class Classes: def __init__(self, vNOME, vHP, vSP): self.nome = vNOME self.hp = vHP self.sp = vSP def getInfos(self): print('----- ATRIBUTOS -----') print('- NOME: {}'.format(self.nome)) print('- HP: {}'.format(self.hp)) print('- SP: {}'.format(self.sp)) def getNome(self): return self.nome def setHP(self, vHP): self.hp = vHP def setNome(self, vNOME): self.nome = vNOME def setSP(self, vSP): self.sp = vSP class Mago(Classes): def __init__(self, vNOME, vHP, vSP): super().__init__(vNOME, vHP, vSP) self.mp = vSP * 0.5 def getInfos(self): super().getInfos() print('- AP: {}'.format(self.mp)) print('---------------------') def getMP(self): return self.mp class Cavaleiro(Classes): def __init__(self, vNOME, vHP, vSP): super().__init__(vNOME, vHP, vSP) self.ad = vSP * 0.75 def getInfos(self): super().getInfos() print('- AD: {}'.format(self.ad)) print('---------------------') def getAD(self): return self.ad class Arqueiro(Classes): def __init__(self, vNOME, vHP, vSP): super().__init__(vNOME, vHP, vSP) self.rp = vSP * 0.6 def getInfos(self): super().getInfos() print('- RP: {}'.format(self.rp)) print('---------------------') def getRP(self): return self.rp
class Classes: def __init__(self, vNOME, vHP, vSP): self.nome = vNOME self.hp = vHP self.sp = vSP def getInfos(self): print('----- ATRIBUTOS -----') print('- NOME: {}'.format(self.nome)) print('- HP: {}'.format(self.hp)) print('- SP: {}'.format(self.sp)) def getNome(self): return self.nome def setHP(self, vHP): self.hp = vHP def setNome(self, vNOME): self.nome = vNOME def setSP(self, vSP): self.sp = vSP class Mago(Classes): def __init__(self, vNOME, vHP, vSP): super().__init__(vNOME, vHP, vSP) self.mp = vSP * 0.5 def getInfos(self): super().getInfos() print('- AP: {}'.format(self.mp)) print('---------------------') def getMP(self): return self.mp class Cavaleiro(Classes): def __init__(self, vNOME, vHP, vSP): super().__init__(vNOME, vHP, vSP) self.ad = vSP * 0.75 def getInfos(self): super().getInfos() print('- AD: {}'.format(self.ad)) print('---------------------') def getAD(self): return self.ad class Arqueiro(Classes): def __init__(self, vNOME, vHP, vSP): super().__init__(vNOME, vHP, vSP) self.rp = vSP * 0.6 def getInfos(self): super().getInfos() print('- RP: {}'.format(self.rp)) print('---------------------') def getRP(self): return self.rp
none
1
3.47036
3
uninas/utils/system.py
cogsys-tuebingen/uninas
18
6622450
<reponame>cogsys-tuebingen/uninas<gh_stars>10-100 import os import platform import subprocess import GPUtil from pip._internal.operations.freeze import freeze import torch.utils.collect_env as collect_env import torch.backends.cudnn as cudnn def headline(text: str) -> str: return '\n\n\n' + '-'*100 + '\n' + text + '\n' + '-'*100 + '\n' def get_command_result(command: str) -> str: try: sp = subprocess.Popen("exec %s" % command, shell=True, stdout=subprocess.PIPE) out = sp.stdout.read() sp.kill() sp.communicate() if len(out) > 0: return str(out).split("'")[1] return '<failed: no output>' except Exception as e: return '<failed: %s>' % str(e) def dump_system_info(file_path: str): if os.path.isfile(file_path): os.remove(file_path) with open(file_path, 'w+') as o: o.write(headline('torch collect_env')) o.write(collect_env.get_pretty_env_info()) o.write(headline('system info')) o.write('platform: %s\n' % platform.platform()) o.write('python: %s\n' % platform.python_version()) o.write(headline('gpus')) try: for i, gpu in enumerate(GPUtil.getGPUs()): o.write('gpu %d\n' % i) for k in ['id', 'driver', 'name', 'memoryTotal']: o.write('\t%s=%s\n' % (k, gpu.__dict__[k])) except ValueError as e: o.write("%s" % repr(e)) o.write(headline('cuda / cudnn')) o.write('cuda via cat: %s\n' % get_command_result('cat /usr/local/cuda/version.txt')) o.write('cuda via dpkg: %s\n' % get_command_result('dpkg -l | grep cuda-toolkit')) o.write('cuda via nvcc: %s\n' % get_command_result('nvcc --version')) o.write('cudnn version: %s\n' % cudnn.version()) # o.write('\nnvidia-smi:\n%s\n' % get_command_result('nvidia-smi')) o.write(headline('pip freeze')) for r in freeze(local_only=True): o.write('%s\n' % r) if __name__ == '__main__': dump_system_info('/tmp/uninas/sysinfo.txt')
import os import platform import subprocess import GPUtil from pip._internal.operations.freeze import freeze import torch.utils.collect_env as collect_env import torch.backends.cudnn as cudnn def headline(text: str) -> str: return '\n\n\n' + '-'*100 + '\n' + text + '\n' + '-'*100 + '\n' def get_command_result(command: str) -> str: try: sp = subprocess.Popen("exec %s" % command, shell=True, stdout=subprocess.PIPE) out = sp.stdout.read() sp.kill() sp.communicate() if len(out) > 0: return str(out).split("'")[1] return '<failed: no output>' except Exception as e: return '<failed: %s>' % str(e) def dump_system_info(file_path: str): if os.path.isfile(file_path): os.remove(file_path) with open(file_path, 'w+') as o: o.write(headline('torch collect_env')) o.write(collect_env.get_pretty_env_info()) o.write(headline('system info')) o.write('platform: %s\n' % platform.platform()) o.write('python: %s\n' % platform.python_version()) o.write(headline('gpus')) try: for i, gpu in enumerate(GPUtil.getGPUs()): o.write('gpu %d\n' % i) for k in ['id', 'driver', 'name', 'memoryTotal']: o.write('\t%s=%s\n' % (k, gpu.__dict__[k])) except ValueError as e: o.write("%s" % repr(e)) o.write(headline('cuda / cudnn')) o.write('cuda via cat: %s\n' % get_command_result('cat /usr/local/cuda/version.txt')) o.write('cuda via dpkg: %s\n' % get_command_result('dpkg -l | grep cuda-toolkit')) o.write('cuda via nvcc: %s\n' % get_command_result('nvcc --version')) o.write('cudnn version: %s\n' % cudnn.version()) # o.write('\nnvidia-smi:\n%s\n' % get_command_result('nvidia-smi')) o.write(headline('pip freeze')) for r in freeze(local_only=True): o.write('%s\n' % r) if __name__ == '__main__': dump_system_info('/tmp/uninas/sysinfo.txt')
en
0.070887
# o.write('\nnvidia-smi:\n%s\n' % get_command_result('nvidia-smi'))
2.292146
2