code stringlengths 21 1.03M | apis list | extract_api stringlengths 74 8.23M |
|---|---|---|
import sys
from google.cloud import vision_v1
from google.cloud.vision_v1 import enums
import io
import json
from google.cloud import storage
import os
def sample_batch_annotate_files(storage_uri):
# os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = r"C:\Users\user\Desktop\doc_ai\rmi-insights-3e257c9c456c.json"
"""Perform batch file annotation."""
mime_type = "application/pdf"
client = vision_v1.ImageAnnotatorClient()
gcs_source = {"uri": storage_uri}
input_config = {"gcs_source": gcs_source, "mime_type": mime_type}
features = [{"type": enums.Feature.Type.DOCUMENT_TEXT_DETECTION}]
# The service can process up to 5 pages per document file.
# Here we specify the first, second, and last page of the document to be
# processed.
pages = [1, 2, 3]
requests = [{"input_config": input_config, "features": features, "pages": pages}]
response = client.batch_annotate_files(requests)
#Accessing Internal memory 1
f = open("/home/srinidhi/angular/uploads/visionoutput.txt","w+")
for image_response in response.responses[0].responses:
f.write(image_response.full_text_annotation.text)
f.close()
#Reading it line by line
f1 = open("/home/srinidhi/angular/uploads/visionoutput.txt","r")
list_output = []
line = f1.readlines()
line = [x.rstrip('\\n').rstrip() for x in line]
print(line)
#Storing in a dictionary
dict_output ={}
dict_output['data'] = line
#Uploading file to bucket
#Filename is the name you want to store in bucket
storage_client = storage.Client()
bucket = storage_client.get_bucket('sample_pdf')
filename ="visionoutput.json"
blob = bucket.blob(filename)
#Removing Internal memory
# os.remove("visionoutput.txt")
# os.remove("visionoutput.json")
if __name__ == '__main__':
file_path = sys.argv[1]
sample_batch_annotate_files(file_path) | [
"google.cloud.vision_v1.ImageAnnotatorClient",
"google.cloud.storage.Client"
] | [((421, 453), 'google.cloud.vision_v1.ImageAnnotatorClient', 'vision_v1.ImageAnnotatorClient', ([], {}), '()\n', (451, 453), False, 'from google.cloud import vision_v1\n'), ((1631, 1647), 'google.cloud.storage.Client', 'storage.Client', ([], {}), '()\n', (1645, 1647), False, 'from google.cloud import storage\n')] |
# Based on ULN2003 driver lib: https://github.com/zhcong/ULN2003-for-ESP32
from utime import sleep_ms
from machine import Pin
from LogicalPins import physical_pin
STEPPER_INST = None
class StepperULN2003:
FULL_ROTATION = int(4075.7728395061727 / 8) # http://www.jangeox.be/2013/10/stepper-motor-28byj-48_25.html
def __init__(self, mode):
# Mode: FULL / HALF
if mode == 'FULL':
# FULL STEP - ~508
self.mode = [[1, 0, 1, 0],
[0, 1, 1, 0],
[0, 1, 0, 1],
[1, 0, 0, 1]]
self.delay = 10
else:
# HALF STEP - ~1016
self.mode = [[0, 0, 0, 1],
[0, 0, 1, 1],
[0, 0, 1, 0],
[0, 1, 1, 0],
[0, 1, 0, 0],
[1, 1, 0, 0],
[1, 0, 0, 0],
[1, 0, 0, 1]]
self.delay = 2
# Init stepper pins
self.pin1 = Pin(physical_pin('stppr_1'), Pin.OUT)
self.pin2 = Pin(physical_pin('stppr_2'), Pin.OUT)
self.pin3 = Pin(physical_pin('stppr_3'), Pin.OUT)
self.pin4 = Pin(physical_pin('stppr_4'), Pin.OUT)
# Initialize all value to 0 - "OFF"
self.reset()
def step(self, count, direction=1):
"""Rotate count steps. direction = -1 means backwards"""
if count < 0:
direction = -1
count = -count
for x in range(count):
for bit in self.mode[::direction]:
self.pin1(bit[0])
self.pin2(bit[1])
self.pin3(bit[2])
self.pin4(bit[3])
sleep_ms(self.delay)
self.reset()
def angle(self, r, direction=1):
if r < 0:
r *= -1
direction = -1
self.step(round(self.FULL_ROTATION * r / 360), direction)
def reset(self):
# Reset to 0, no holding, these are geared, you can't move them
self.pin1(0)
self.pin2(0)
self.pin3(0)
self.pin4(0)
@property
def speed_ms(self):
return self.delay
@speed_ms.setter
def speed_ms(self, ms):
# HALF STEP - delay check
if len(self.mode) > 4 and ms < 1:
ms = 1
# FULL STEP - delay check
elif ms < 10:
ms = 10
self.delay = ms
def __init_stepper(mode='HALF'):
global STEPPER_INST
if STEPPER_INST is None:
STEPPER_INST = StepperULN2003(mode)
return STEPPER_INST
def load_n_init(mode="HALF"):
__init_stepper(mode=mode)
def angle(dg, speed=None):
"""
:param dg: +/- 0-360 degree
:param speed: wait ms
:return: Info
"""
i = __init_stepper()
if speed:
i.speed_ms = speed
i.angle(dg)
return "Move {} degree ({} ms)".format(dg, i.speed_ms)
def step(st, speed=None):
i = __init_stepper()
if speed:
i.speed_ms = speed
i.step(st)
return "Move {} step ({} ms)".format(st, i.speed_ms)
def standby():
__init_stepper().reset()
return "Standby"
#######################
# LM helper functions #
#######################
def pinmap():
# Return module used PIN mapping
return {'stppr_1': physical_pin('stppr_1'), 'stppr_2': physical_pin('stppr_2'),
'stppr_3': physical_pin('stppr_3'), 'stppr_4': physical_pin('stppr_4')}
def help():
return 'angle dg=+/-360 speed=<ms>',\
'step st=+/-2 speed=<ms>',\
'standby',\
'load_n_init mode=<"HALF"/"FULL">', 'pinmap'\
'Info: stepper: 28byj-48 driver: ULN2003'
| [
"utime.sleep_ms",
"LogicalPins.physical_pin"
] | [((3304, 3327), 'LogicalPins.physical_pin', 'physical_pin', (['"""stppr_1"""'], {}), "('stppr_1')\n", (3316, 3327), False, 'from LogicalPins import physical_pin\n'), ((3340, 3363), 'LogicalPins.physical_pin', 'physical_pin', (['"""stppr_2"""'], {}), "('stppr_2')\n", (3352, 3363), False, 'from LogicalPins import physical_pin\n'), ((3388, 3411), 'LogicalPins.physical_pin', 'physical_pin', (['"""stppr_3"""'], {}), "('stppr_3')\n", (3400, 3411), False, 'from LogicalPins import physical_pin\n'), ((3424, 3447), 'LogicalPins.physical_pin', 'physical_pin', (['"""stppr_4"""'], {}), "('stppr_4')\n", (3436, 3447), False, 'from LogicalPins import physical_pin\n'), ((1058, 1081), 'LogicalPins.physical_pin', 'physical_pin', (['"""stppr_1"""'], {}), "('stppr_1')\n", (1070, 1081), False, 'from LogicalPins import physical_pin\n'), ((1116, 1139), 'LogicalPins.physical_pin', 'physical_pin', (['"""stppr_2"""'], {}), "('stppr_2')\n", (1128, 1139), False, 'from LogicalPins import physical_pin\n'), ((1174, 1197), 'LogicalPins.physical_pin', 'physical_pin', (['"""stppr_3"""'], {}), "('stppr_3')\n", (1186, 1197), False, 'from LogicalPins import physical_pin\n'), ((1232, 1255), 'LogicalPins.physical_pin', 'physical_pin', (['"""stppr_4"""'], {}), "('stppr_4')\n", (1244, 1255), False, 'from LogicalPins import physical_pin\n'), ((1743, 1763), 'utime.sleep_ms', 'sleep_ms', (['self.delay'], {}), '(self.delay)\n', (1751, 1763), False, 'from utime import sleep_ms\n')] |
"""
coding:utf-8
file: setting_window.py
@author: jiangwei
@contact: <EMAIL>
@time: 2020/6/27 23:07
@desc:
"""
import sys
from ui.setting_window import Ui_Form
from PyQt5.QtWidgets import QWidget, QApplication
from util.common_util import SYS_STYLE
class SettingWindow(Ui_Form, QWidget):
def __init__(self):
super(SettingWindow, self).__init__()
self.setupUi(self)
self.setStyleSheet(SYS_STYLE)
self.init_ui()
self.init_slot()
self.init_data()
def init_data(self):
pass
def init_ui(self):
self.pushButton.setProperty('class', 'Aqua')
self.pushButton.setMinimumWidth(70)
self.setStyleSheet(SYS_STYLE)
def init_slot(self):
self.pushButton.clicked.connect(self.save_setting)
def save_setting(self):
pass
if __name__ == '__main__':
app = QApplication(sys.argv)
win = SettingWindow()
win.show()
sys.exit(app.exec_())
| [
"PyQt5.QtWidgets.QApplication"
] | [((863, 885), 'PyQt5.QtWidgets.QApplication', 'QApplication', (['sys.argv'], {}), '(sys.argv)\n', (875, 885), False, 'from PyQt5.QtWidgets import QWidget, QApplication\n')] |
import os
from testtools import TestCase
from testtools.matchers import Contains
from . import makeprefs
from mock import Mock, patch
from StringIO import StringIO
from twisted.internet import defer
class CommandTest(TestCase):
def setUp(self):
super(CommandTest, self).setUp()
self.prefs = makeprefs()
self.home = os.path.join('t', 'data', 'home')
def tearDown(self):
super(CommandTest, self).tearDown()
def _makeit(self, *args, **kwargs):
from lacli.main import LaCommand
return LaCommand(*args, **kwargs)
def test_command(self):
assert self._makeit(Mock(), makeprefs(Mock()))
@patch('sys.stdin', new_callable=StringIO)
def test_loop_none(self, mock_stdin):
factory = Mock()
factory.return_value.async_account = defer.succeed(
{'email': 'foo'})
cli = self._makeit(Mock(), makeprefs(factory))
cli.cmdloop()
@patch('sys.stdout', new_callable=StringIO)
def test_dispatch(self, stdout):
cli = self._makeit(Mock(), makeprefs(Mock()))
cli.dispatch('foo', [])
self.assertThat(stdout.getvalue(),
Contains('Unrecognized command: foo'))
@patch('sys.stdout', new_callable=StringIO)
def test_dispatch_foo(self, stdout):
cli = self._makeit(Mock(), makeprefs(Mock()))
with patch.object(cli, 'foo', create=True) as foo:
foo.__doc__ = "Usage: lacli foo"
foo.makecmd.return_value = 'bar'
cli.dispatch('foo', [])
self.assertEqual('', stdout.getvalue())
foo.onecmd.assert_called_with('bar')
@patch('sys.stdout', new_callable=StringIO)
def test_dispatch_login(self, stdout):
factory = Mock()
factory.return_value.async_account = defer.succeed(
{'email': 'foo'})
cli = self._makeit(Mock(), makeprefs(factory))
cli.dispatch('login', [])
self.assertThat(stdout.getvalue(),
Contains('authentication succesfull'))
@patch('sys.stdout', new_callable=StringIO)
def test_do_login(self, stdout):
factory = Mock()
factory.return_value.async_account = defer.succeed(
{'email': 'foo'})
cli = self._makeit(Mock(), makeprefs(factory))
cli.onecmd('login')
self.assertThat(stdout.getvalue(),
Contains('authentication succesfull'))
@patch('sys.stdout', new_callable=StringIO)
def test_do_login_with_creds(self, stdout):
factory = Mock()
factory.return_value.async_account = defer.succeed(
{'email': 'foo'})
cli = self._makeit(Mock(), makeprefs(factory))
cli.onecmd('login username password')
self.assertThat(stdout.getvalue(),
Contains('authentication succesfull'))
@patch('sys.stdout', new_callable=StringIO)
def test_do_login_with_bad_creds(self, stdout):
factory = Mock()
factory.return_value.async_account = defer.fail(
Exception())
cli = self._makeit(Mock(), makeprefs(factory))
cli.onecmd('login username password')
self.assertThat(stdout.getvalue(),
Contains('authentication failed'))
| [
"os.path.join",
"mock.patch.object",
"testtools.matchers.Contains",
"twisted.internet.defer.succeed",
"mock.patch",
"mock.Mock",
"lacli.main.LaCommand"
] | [((663, 704), 'mock.patch', 'patch', (['"""sys.stdin"""'], {'new_callable': 'StringIO'}), "('sys.stdin', new_callable=StringIO)\n", (668, 704), False, 'from mock import Mock, patch\n'), ((945, 987), 'mock.patch', 'patch', (['"""sys.stdout"""'], {'new_callable': 'StringIO'}), "('sys.stdout', new_callable=StringIO)\n", (950, 987), False, 'from mock import Mock, patch\n'), ((1223, 1265), 'mock.patch', 'patch', (['"""sys.stdout"""'], {'new_callable': 'StringIO'}), "('sys.stdout', new_callable=StringIO)\n", (1228, 1265), False, 'from mock import Mock, patch\n'), ((1653, 1695), 'mock.patch', 'patch', (['"""sys.stdout"""'], {'new_callable': 'StringIO'}), "('sys.stdout', new_callable=StringIO)\n", (1658, 1695), False, 'from mock import Mock, patch\n'), ((2056, 2098), 'mock.patch', 'patch', (['"""sys.stdout"""'], {'new_callable': 'StringIO'}), "('sys.stdout', new_callable=StringIO)\n", (2061, 2098), False, 'from mock import Mock, patch\n'), ((2446, 2488), 'mock.patch', 'patch', (['"""sys.stdout"""'], {'new_callable': 'StringIO'}), "('sys.stdout', new_callable=StringIO)\n", (2451, 2488), False, 'from mock import Mock, patch\n'), ((2865, 2907), 'mock.patch', 'patch', (['"""sys.stdout"""'], {'new_callable': 'StringIO'}), "('sys.stdout', new_callable=StringIO)\n", (2870, 2907), False, 'from mock import Mock, patch\n'), ((346, 379), 'os.path.join', 'os.path.join', (['"""t"""', '"""data"""', '"""home"""'], {}), "('t', 'data', 'home')\n", (358, 379), False, 'import os\n'), ((546, 572), 'lacli.main.LaCommand', 'LaCommand', (['*args'], {}), '(*args, **kwargs)\n', (555, 572), False, 'from lacli.main import LaCommand\n'), ((765, 771), 'mock.Mock', 'Mock', ([], {}), '()\n', (769, 771), False, 'from mock import Mock, patch\n'), ((817, 848), 'twisted.internet.defer.succeed', 'defer.succeed', (["{'email': 'foo'}"], {}), "({'email': 'foo'})\n", (830, 848), False, 'from twisted.internet import defer\n'), ((1757, 1763), 'mock.Mock', 'Mock', ([], {}), '()\n', (1761, 1763), False, 'from mock import Mock, patch\n'), ((1809, 1840), 'twisted.internet.defer.succeed', 'defer.succeed', (["{'email': 'foo'}"], {}), "({'email': 'foo'})\n", (1822, 1840), False, 'from twisted.internet import defer\n'), ((2154, 2160), 'mock.Mock', 'Mock', ([], {}), '()\n', (2158, 2160), False, 'from mock import Mock, patch\n'), ((2206, 2237), 'twisted.internet.defer.succeed', 'defer.succeed', (["{'email': 'foo'}"], {}), "({'email': 'foo'})\n", (2219, 2237), False, 'from twisted.internet import defer\n'), ((2555, 2561), 'mock.Mock', 'Mock', ([], {}), '()\n', (2559, 2561), False, 'from mock import Mock, patch\n'), ((2607, 2638), 'twisted.internet.defer.succeed', 'defer.succeed', (["{'email': 'foo'}"], {}), "({'email': 'foo'})\n", (2620, 2638), False, 'from twisted.internet import defer\n'), ((2978, 2984), 'mock.Mock', 'Mock', ([], {}), '()\n', (2982, 2984), False, 'from mock import Mock, patch\n'), ((630, 636), 'mock.Mock', 'Mock', ([], {}), '()\n', (634, 636), False, 'from mock import Mock, patch\n'), ((889, 895), 'mock.Mock', 'Mock', ([], {}), '()\n', (893, 895), False, 'from mock import Mock, patch\n'), ((1052, 1058), 'mock.Mock', 'Mock', ([], {}), '()\n', (1056, 1058), False, 'from mock import Mock, patch\n'), ((1178, 1215), 'testtools.matchers.Contains', 'Contains', (['"""Unrecognized command: foo"""'], {}), "('Unrecognized command: foo')\n", (1186, 1215), False, 'from testtools.matchers import Contains\n'), ((1334, 1340), 'mock.Mock', 'Mock', ([], {}), '()\n', (1338, 1340), False, 'from mock import Mock, patch\n'), ((1374, 1411), 'mock.patch.object', 'patch.object', (['cli', '"""foo"""'], {'create': '(True)'}), "(cli, 'foo', create=True)\n", (1386, 1411), False, 'from mock import Mock, patch\n'), ((1881, 1887), 'mock.Mock', 'Mock', ([], {}), '()\n', (1885, 1887), False, 'from mock import Mock, patch\n'), ((2011, 2048), 'testtools.matchers.Contains', 'Contains', (['"""authentication succesfull"""'], {}), "('authentication succesfull')\n", (2019, 2048), False, 'from testtools.matchers import Contains\n'), ((2278, 2284), 'mock.Mock', 'Mock', ([], {}), '()\n', (2282, 2284), False, 'from mock import Mock, patch\n'), ((2401, 2438), 'testtools.matchers.Contains', 'Contains', (['"""authentication succesfull"""'], {}), "('authentication succesfull')\n", (2409, 2438), False, 'from testtools.matchers import Contains\n'), ((2679, 2685), 'mock.Mock', 'Mock', ([], {}), '()\n', (2683, 2685), False, 'from mock import Mock, patch\n'), ((2820, 2857), 'testtools.matchers.Contains', 'Contains', (['"""authentication succesfull"""'], {}), "('authentication succesfull')\n", (2828, 2857), False, 'from testtools.matchers import Contains\n'), ((3095, 3101), 'mock.Mock', 'Mock', ([], {}), '()\n', (3099, 3101), False, 'from mock import Mock, patch\n'), ((3236, 3269), 'testtools.matchers.Contains', 'Contains', (['"""authentication failed"""'], {}), "('authentication failed')\n", (3244, 3269), False, 'from testtools.matchers import Contains\n'), ((648, 654), 'mock.Mock', 'Mock', ([], {}), '()\n', (652, 654), False, 'from mock import Mock, patch\n'), ((1070, 1076), 'mock.Mock', 'Mock', ([], {}), '()\n', (1074, 1076), False, 'from mock import Mock, patch\n'), ((1352, 1358), 'mock.Mock', 'Mock', ([], {}), '()\n', (1356, 1358), False, 'from mock import Mock, patch\n')] |
import pytest
from hyper_prompt.theme import BasicTheme
@pytest.mark.parametrize(
"test, result",
[
("RESET", BasicTheme.RESET),
("TEST_FG", BasicTheme.FG),
("TEST_BG", BasicTheme.BG)
]
)
def test_get_key(test, result):
assert BasicTheme({}).get(test) == result
| [
"pytest.mark.parametrize",
"hyper_prompt.theme.BasicTheme"
] | [((59, 190), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""test, result"""', "[('RESET', BasicTheme.RESET), ('TEST_FG', BasicTheme.FG), ('TEST_BG',\n BasicTheme.BG)]"], {}), "('test, result', [('RESET', BasicTheme.RESET), (\n 'TEST_FG', BasicTheme.FG), ('TEST_BG', BasicTheme.BG)])\n", (82, 190), False, 'import pytest\n'), ((269, 283), 'hyper_prompt.theme.BasicTheme', 'BasicTheme', (['{}'], {}), '({})\n', (279, 283), False, 'from hyper_prompt.theme import BasicTheme\n')] |
#setup cython code
from setuptools import setup, find_packages
from Cython.Build import cythonize
import numpy
import os
import codecs
def read(rel_path):
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, rel_path), 'r') as fp:
return fp.read()
def get_version(rel_path):
for line in read(rel_path).splitlines():
if line.startswith('__version__'):
delim = '"' if '"' in line else "'"
return line.split(delim)[1]
else:
raise RuntimeError("Unable to find version string.")
setup(
name="LoopStructural",
install_requires=[
# 'Cython',
# 'numpy',
# 'pandas',
# 'scipy',
# 'matplotlib',
# # 'lavavu',
# 'scikit-image',
# 'scikit-learn'
],
version=get_version("LoopStructural/__init__.py"),
packages=find_packages(),
ext_modules=cythonize("LoopStructural/interpolators/cython/*.pyx",compiler_directives={"language_level": "3"}),
include_dirs=[numpy.get_include()],
include_package_data=True,
package_data={'LoopStructural':['datasets/data/*.csv','datasets/data/*.txt']},
)
| [
"os.path.join",
"os.path.dirname",
"setuptools.find_packages",
"numpy.get_include",
"Cython.Build.cythonize"
] | [((182, 207), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (197, 207), False, 'import os\n'), ((812, 827), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (825, 827), False, 'from setuptools import setup, find_packages\n'), ((842, 946), 'Cython.Build.cythonize', 'cythonize', (['"""LoopStructural/interpolators/cython/*.pyx"""'], {'compiler_directives': "{'language_level': '3'}"}), "('LoopStructural/interpolators/cython/*.pyx', compiler_directives=\n {'language_level': '3'})\n", (851, 946), False, 'from Cython.Build import cythonize\n'), ((230, 258), 'os.path.join', 'os.path.join', (['here', 'rel_path'], {}), '(here, rel_path)\n', (242, 258), False, 'import os\n'), ((957, 976), 'numpy.get_include', 'numpy.get_include', ([], {}), '()\n', (974, 976), False, 'import numpy\n')] |
import torch
import torch.nn as nn
class NCSNSampler(nn.Module):
def __init__(self, score, sigmas, alphas, n_steps_each: int):
super().__init__()
self.score = score
self.sigmas = sigmas
self.alphas = alphas
self.n_steps_each = n_steps_each
def forward(self, x_T: torch.Tensor):
for i, sigma_i in enumerate(self.sigmas):
labels = (i * torch.ones_like(x_T[0])).long()
for t in range(self.n_steps_each):
x_T = x_T + self.alphas[i] * self.score(x_T, labels) / 2 + self.alphas[i] * torch.randn_like(x_T)
return x_T
| [
"torch.randn_like",
"torch.ones_like"
] | [((405, 428), 'torch.ones_like', 'torch.ones_like', (['x_T[0]'], {}), '(x_T[0])\n', (420, 428), False, 'import torch\n'), ((576, 597), 'torch.randn_like', 'torch.randn_like', (['x_T'], {}), '(x_T)\n', (592, 597), False, 'import torch\n')] |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
def calculate_profit_from_columns(row):
profit = 0
if row['Buy']:
profit = row['Difference']
elif row['Sell']:
profit = row['Difference'] * -1
return profit
def convert_date(row):
return datetime.strptime(row['Datetime'], '%Y-%m-%d %H:%M:%S')
def get_day_of_week(row):
date = row['Datetime']
return date.weekday()
def get_hour(row):
date = row['Datetime']
return date.hour
def get_minute(row):
date = row['Datetime']
return date.minute
def filter_dataframe_by_days(dataframe, days):
return dataframe.loc[dataframe['Weekday'].isin(days)]
def filter_by_hours(dataframe, hours):
return dataframe.loc[dataframe['Hour'].isin(hours)]
def filter_by_minutes(dataframe, minutes):
return dataframe.loc[dataframe['Minute'].isin(minutes)]
def filter_by_buy_or_sell(dataframe, action):
return dataframe.loc[dataframe[action] == 1]
def get_header_row(dataframe):
return ','.join(list(dataframe.columns))
def append_moving_wealth_row(dataframe, start_wealth, bid_ask_spread=0, leverage=1, wealth_column_name='Wealth'):
if bid_ask_spread and wealth_column_name == 'Wealth':
wealth_column_name='Adjusted Wealth'
df = dataframe.reset_index()
wealth_array = [start_wealth]
for i in range(1, len(df)):
if not df.loc[i, 'Buy'] and not df.loc[i, 'Sell']:
wealth_array.append(wealth_array[-1])
else:
wealth_array.append(wealth_array[-1] * (1 + leverage * (df.loc[i, 'Profit'] - bid_ask_spread)))
dataframe[wealth_column_name] = np.array(wealth_array)
def plot_dataframe(dataframe, title, columns, colours=['blue', 'red', 'green']):
fig, ax = plt.subplots()
for i in range(len(columns)):
ax = dataframe.plot(ax=ax, x='Datetime', y=columns[i], c=colours[i], title=title)
def print_analysis(dataframe, filter_name):
num_trades = dataframe['Buy'].sum() + dataframe['Sell'].sum()
total_profit = dataframe.sum()['Profit']
avg_profit = dataframe.mean()['Profit']
max_profit = dataframe.max()['Profit']
max_loss = dataframe.min()['Profit']
print(f'\n\nSummary for data filtered by {filter_name}')
print('-------------------------------------------')
print(f'Total Trades Made: {num_trades}')
print(f'Total Profit Made: {total_profit}')
print(f'Average Profit Made Per Trade: {avg_profit}')
print(f'Largest Gain: {max_profit}')
print(f'Largest Loss: {max_loss}')
print('-------------------------------------------')
def add_columns_to_base_data(base_data, start_wealth=10000):
base_data['Profit'] = base_data.apply(lambda row: calculate_profit_from_columns(row), axis=1)
base_data['Datetime'] = base_data.apply(lambda row: convert_date(row), axis=1)
base_data['Weekday'] = base_data.apply(lambda row: get_day_of_week(row), axis=1)
base_data['Hour'] = base_data.apply(lambda row: get_hour(row), axis=1)
base_data['Minute'] = base_data.apply(lambda row: get_minute(row), axis=1) | [
"numpy.array",
"matplotlib.pyplot.subplots",
"datetime.datetime.strptime"
] | [((326, 381), 'datetime.datetime.strptime', 'datetime.strptime', (["row['Datetime']", '"""%Y-%m-%d %H:%M:%S"""'], {}), "(row['Datetime'], '%Y-%m-%d %H:%M:%S')\n", (343, 381), False, 'from datetime import datetime\n'), ((1665, 1687), 'numpy.array', 'np.array', (['wealth_array'], {}), '(wealth_array)\n', (1673, 1687), True, 'import numpy as np\n'), ((1784, 1798), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1796, 1798), True, 'import matplotlib.pyplot as plt\n')] |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 5 16:07:58 2016
@author: Administrator
"""
import unittest
from app import create_app,db
from app.models import User,Role
from flask import url_for
import re
class FlaskClientTestCase(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
self.app_context = self.app.app_context()
self.app_context.push()
db.create_all()
Role.insert_roles()
self.client = self.app.test_client(use_cookie=True)
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_context.pop()
def test_home_page(self):
response = self.client.get(url_for('main.index'))
self.assertTrue('Stranger' in response.get_data(as_text=True))
def test_register_and_login(self):
response = self.client.post(url_for('auth.register'),data={'email':'<EMAIL>','username':'john','password':'<PASSWORD>','password2':'<PASSWORD>'})
self.assertTrue(response.status_code == 302)
response = self.client.post(url_for('auth.login'),data={'email':'<EMAIL>','password':'<PASSWORD>'},follow_redirects=True)
data = response.get_data(as_text=True)
self.assertTrue(re.search('Hello,\s+john!',data))
self.assertTrue('You have not confirmed your account yet' in data)
user = User.query.filter_by(email='<EMAIL>').first()
token = user.generate_confirmation_token()
response = self.client.get(url_for('auth.confirm',token=token),follow_redirects=True)
data = response.get_data(as_text=True)
self.assertTrue('Your have confirmed your account' in data)
response = self.client.get(url_for('auth.logout'),follow_redirects=True)
data = response.get_data(as_text=True)
self.assertTrue('You have been logged out' in data) | [
"flask.url_for",
"app.models.Role.insert_roles",
"app.create_app",
"app.db.create_all",
"app.models.User.query.filter_by",
"re.search",
"app.db.drop_all",
"app.db.session.remove"
] | [((310, 331), 'app.create_app', 'create_app', (['"""testing"""'], {}), "('testing')\n", (320, 331), False, 'from app import create_app, db\n'), ((425, 440), 'app.db.create_all', 'db.create_all', ([], {}), '()\n', (438, 440), False, 'from app import create_app, db\n'), ((450, 469), 'app.models.Role.insert_roles', 'Role.insert_roles', ([], {}), '()\n', (467, 469), False, 'from app.models import User, Role\n'), ((575, 594), 'app.db.session.remove', 'db.session.remove', ([], {}), '()\n', (592, 594), False, 'from app import create_app, db\n'), ((604, 617), 'app.db.drop_all', 'db.drop_all', ([], {}), '()\n', (615, 617), False, 'from app import create_app, db\n'), ((727, 748), 'flask.url_for', 'url_for', (['"""main.index"""'], {}), "('main.index')\n", (734, 748), False, 'from flask import url_for\n'), ((909, 933), 'flask.url_for', 'url_for', (['"""auth.register"""'], {}), "('auth.register')\n", (916, 933), False, 'from flask import url_for\n'), ((1128, 1149), 'flask.url_for', 'url_for', (['"""auth.login"""'], {}), "('auth.login')\n", (1135, 1149), False, 'from flask import url_for\n'), ((1295, 1329), 're.search', 're.search', (['"""Hello,\\\\s+john!"""', 'data'], {}), "('Hello,\\\\s+john!', data)\n", (1304, 1329), False, 'import re\n'), ((1565, 1601), 'flask.url_for', 'url_for', (['"""auth.confirm"""'], {'token': 'token'}), "('auth.confirm', token=token)\n", (1572, 1601), False, 'from flask import url_for\n'), ((1787, 1809), 'flask.url_for', 'url_for', (['"""auth.logout"""'], {}), "('auth.logout')\n", (1794, 1809), False, 'from flask import url_for\n'), ((1431, 1468), 'app.models.User.query.filter_by', 'User.query.filter_by', ([], {'email': '"""<EMAIL>"""'}), "(email='<EMAIL>')\n", (1451, 1468), False, 'from app.models import User, Role\n')] |
import cv2
import imagezmq
import simplejpeg
# Instantiate and provide the first publisher address
image_hub = imagezmq.ImageHub(open_port="tcp://192.168.12.29:5555", REQ_REP=False)
# image_hub.connect('tcp://192.168.86.38:5555') # second publisher address
while True: # show received images
# sender_name, image = image_hub.recv_image()
sender_name, jpg_buffer = image_hub.recv_jpg()
image = simplejpeg.decode_jpeg(jpg_buffer, colorspace="BGR")
cv2.imshow(sender_name, image)
key = cv2.waitKey(1) & 0xFF
if key in [113, 27]:
break
| [
"cv2.imshow",
"simplejpeg.decode_jpeg",
"cv2.waitKey",
"imagezmq.ImageHub"
] | [((112, 182), 'imagezmq.ImageHub', 'imagezmq.ImageHub', ([], {'open_port': '"""tcp://192.168.12.29:5555"""', 'REQ_REP': '(False)'}), "(open_port='tcp://192.168.12.29:5555', REQ_REP=False)\n", (129, 182), False, 'import imagezmq\n'), ((411, 463), 'simplejpeg.decode_jpeg', 'simplejpeg.decode_jpeg', (['jpg_buffer'], {'colorspace': '"""BGR"""'}), "(jpg_buffer, colorspace='BGR')\n", (433, 463), False, 'import simplejpeg\n'), ((468, 498), 'cv2.imshow', 'cv2.imshow', (['sender_name', 'image'], {}), '(sender_name, image)\n', (478, 498), False, 'import cv2\n'), ((509, 523), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (520, 523), False, 'import cv2\n')] |
from __future__ import division
import gzip
import matplotlib.pyplot as plt
import numpy as np
import random
import math
def Randomize_Weights(weight_vector: np.ndarray):
rand_weights = weight_vector
for j in range(0,len(weight_vector)):
rand_weights[j][::1] = float(random.randint(-100, 100) / 100)
return rand_weights
def Forward_Pass(data: np.ndarray, weights, biases): # a Single Forward Pass, returns a vector output after the softmax
output = [0] * 10
probs = np.zeros(10)
output[::1] = (np.inner(weights[::1], data) + biases[::1])
sum = 0
for index,x in enumerate(output):
exp = math.exp(x)
sum += exp
probs[index] = exp
probs[::1] = probs[::1] * (1/sum)
return probs
def Label_Probs(probabilities): # returns a label, expects normalized data
return np.unravel_index(np.argmax(probabilities, axis=None), probabilities.shape)
def Test_NN(weights, biases): # Tests network and prints accuracy
test_im = np.zeros((10000, 784))
test_lb = None
with open('./data/test_images.gz', 'rb') as f, gzip.GzipFile(fileobj=f) as bytestream:
tmp = bytestream.read()
tmp = np.frombuffer(tmp, dtype=np.dtype('b'), offset=16)
tmp = np.reshape(tmp, (10000, 784))
test_im[:, 0:783] = (tmp[0:10000, 0:783] / 128) // 1
test_im.astype(int)
with open('./data/test_labels.gz', 'rb') as f, gzip.GzipFile(fileobj=f) as bytestream:
tmp = bytestream.read()
test_lb = np.frombuffer(tmp, dtype=np.dtype('b'), offset=8)
num_correct = 0
num_ran = 0
for i in range(0, 10000):
output = Label_Probs(Forward_Pass(test_im[i], weights, biases))
if output == test_lb[i]:
num_correct += 1
num_ran += 1
print("TEST RESULTS\nNUMBER CORRECT: {0}\nACCURACY: {1}%".format(num_correct, round((num_correct/num_ran)*100, 5)))
def GraphCost(cost: list):
for x in range(len(cost)):
plt.scatter(x, cost[x], c="black")
plt.show()
def Train_NN(weights, biases, max_iter: int, epsilon: float, step_size:float, images, labels): # Train network with training data
cost = []
iteration = -1
while iteration < max_iter: # each loop is a training session
iteration += 1
cost.append(0)
num_wrong = 0
for i in range(1, 10000): # go through each image
output = Forward_Pass(images[i], weights, biases) # probabilities dict, each key is 0...9
expected_label = labels[i]
predicted_label = Label_Probs(output)
if expected_label != predicted_label:
num_wrong += 1
for j in range(9):
if expected_label == j: # we want to maximize this if true
weights[j, 0:784] = weights[j, 0:784] - step_size * (images[i, 0:784] * -1 * (1-output[j]))
biases[j] = biases[j] - step_size * (-1 * (1-output[j]))
else: # minimize this
weights[j, 0:784] = weights[j, 0:784] - step_size * (images[i, 0:784] * output[j])
biases[j] = biases[j] - step_size * (1 * output[j])
cost[iteration] = cost[iteration] - math.log(output[expected_label])
if cost[iteration - 1] < cost[iteration]:
step_size /= 2
if cost[iteration] - cost[iteration - 1] <= epsilon and cost[iteration] - cost[iteration - 1] >= 0:
break
print("iteration: {0}/{1} Cost:{2} Num Wrong:{3}".format(iteration, max_iter, cost[iteration], num_wrong))
GraphCost(cost)
return weights, biases
if __name__ == "__main__":
# Import data
train_im = np.zeros((10000, 784))
train_lb = None
with open('./data/training_images.gz', 'rb') as f, gzip.GzipFile(fileobj=f) as bytestream:
tmp = bytestream.read()
tmp = np.frombuffer(tmp, dtype=np.dtype('b'), offset=16)
tmp = np.reshape(tmp, (60000, 784))
train_im[:, 0:783] = (tmp[0:10000, 0:783] / 128) // 1
train_im.astype(int)
with open('./data/training_labels.gz', 'rb') as f, gzip.GzipFile(fileobj=f) as bytestream:
tmp = bytestream.read()
tmp = np.frombuffer(tmp, dtype=np.dtype('b'), offset=8)
train_lb = tmp[0:10000]
weights = Randomize_Weights(np.zeros((10, 784)))
biases = np.zeros(10)
print("BEFORE TRAINING")
Test_NN(weights, biases)
print("TRAINING")
weights, biases = Train_NN(weights, biases, 20, .1, .2, train_im, train_lb)
print("AFTER TRAINING")
Test_NN(weights, biases)
for index,x in enumerate(weights):
print(index)
image = np.reshape(x, (28,28))
plt.imshow(image)
plt.show()
| [
"numpy.reshape",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.imshow",
"math.log",
"numpy.dtype",
"matplotlib.pyplot.show",
"numpy.inner",
"numpy.zeros",
"gzip.GzipFile",
"math.exp",
"numpy.argmax",
"random.randint"
] | [((500, 512), 'numpy.zeros', 'np.zeros', (['(10)'], {}), '(10)\n', (508, 512), True, 'import numpy as np\n'), ((998, 1020), 'numpy.zeros', 'np.zeros', (['(10000, 784)'], {}), '((10000, 784))\n', (1006, 1020), True, 'import numpy as np\n'), ((2000, 2010), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2008, 2010), True, 'import matplotlib.pyplot as plt\n'), ((3671, 3693), 'numpy.zeros', 'np.zeros', (['(10000, 784)'], {}), '((10000, 784))\n', (3679, 3693), True, 'import numpy as np\n'), ((4334, 4346), 'numpy.zeros', 'np.zeros', (['(10)'], {}), '(10)\n', (4342, 4346), True, 'import numpy as np\n'), ((532, 560), 'numpy.inner', 'np.inner', (['weights[::1]', 'data'], {}), '(weights[::1], data)\n', (540, 560), True, 'import numpy as np\n'), ((640, 651), 'math.exp', 'math.exp', (['x'], {}), '(x)\n', (648, 651), False, 'import math\n'), ((858, 893), 'numpy.argmax', 'np.argmax', (['probabilities'], {'axis': 'None'}), '(probabilities, axis=None)\n', (867, 893), True, 'import numpy as np\n'), ((1091, 1115), 'gzip.GzipFile', 'gzip.GzipFile', ([], {'fileobj': 'f'}), '(fileobj=f)\n', (1104, 1115), False, 'import gzip\n'), ((1242, 1271), 'numpy.reshape', 'np.reshape', (['tmp', '(10000, 784)'], {}), '(tmp, (10000, 784))\n', (1252, 1271), True, 'import numpy as np\n'), ((1412, 1436), 'gzip.GzipFile', 'gzip.GzipFile', ([], {'fileobj': 'f'}), '(fileobj=f)\n', (1425, 1436), False, 'import gzip\n'), ((1961, 1995), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'cost[x]'], {'c': '"""black"""'}), "(x, cost[x], c='black')\n", (1972, 1995), True, 'import matplotlib.pyplot as plt\n'), ((3769, 3793), 'gzip.GzipFile', 'gzip.GzipFile', ([], {'fileobj': 'f'}), '(fileobj=f)\n', (3782, 3793), False, 'import gzip\n'), ((3920, 3949), 'numpy.reshape', 'np.reshape', (['tmp', '(60000, 784)'], {}), '(tmp, (60000, 784))\n', (3930, 3949), True, 'import numpy as np\n'), ((4096, 4120), 'gzip.GzipFile', 'gzip.GzipFile', ([], {'fileobj': 'f'}), '(fileobj=f)\n', (4109, 4120), False, 'import gzip\n'), ((4300, 4319), 'numpy.zeros', 'np.zeros', (['(10, 784)'], {}), '((10, 784))\n', (4308, 4319), True, 'import numpy as np\n'), ((4641, 4664), 'numpy.reshape', 'np.reshape', (['x', '(28, 28)'], {}), '(x, (28, 28))\n', (4651, 4664), True, 'import numpy as np\n'), ((4672, 4689), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image'], {}), '(image)\n', (4682, 4689), True, 'import matplotlib.pyplot as plt\n'), ((4698, 4708), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4706, 4708), True, 'import matplotlib.pyplot as plt\n'), ((288, 313), 'random.randint', 'random.randint', (['(-100)', '(100)'], {}), '(-100, 100)\n', (302, 313), False, 'import random\n'), ((1202, 1215), 'numpy.dtype', 'np.dtype', (['"""b"""'], {}), "('b')\n", (1210, 1215), True, 'import numpy as np\n'), ((1527, 1540), 'numpy.dtype', 'np.dtype', (['"""b"""'], {}), "('b')\n", (1535, 1540), True, 'import numpy as np\n'), ((3201, 3233), 'math.log', 'math.log', (['output[expected_label]'], {}), '(output[expected_label])\n', (3209, 3233), False, 'import math\n'), ((3880, 3893), 'numpy.dtype', 'np.dtype', (['"""b"""'], {}), "('b')\n", (3888, 3893), True, 'import numpy as np\n'), ((4207, 4220), 'numpy.dtype', 'np.dtype', (['"""b"""'], {}), "('b')\n", (4215, 4220), True, 'import numpy as np\n')] |
# External Import
from django.contrib import admin
# Internal Import
from .models import Post
admin.site.register(Post)
| [
"django.contrib.admin.site.register"
] | [((96, 121), 'django.contrib.admin.site.register', 'admin.site.register', (['Post'], {}), '(Post)\n', (115, 121), False, 'from django.contrib import admin\n')] |
import json
twinkle_twinkle = ['c4','c4','g4','g4','a4','a4','g4',\
'f4','f4','e4','e4','d4','d4','c4',\
'g5','g5','f4','f4','e4','e4','d4',\
'g5','g5','f4','f4','e4','e4','d4',\
'c4','c4','g4','g4','a4','a4','g4',\
'f4','f4','e4','e4','d4','d4','c4',\
]
happy_birthday = ["g4", "g4", "a4", "g4", "c5", "b4",\
"g4", "g4", "a4", "g4", "d5", "c5",\
"g4", "g4", "g5", "e5", "c5", "b4", "a4",\
"f5", "f5", "e5", "c5", "d5", "c5"]
jan_gan_man = ['c5', 'd5', 'e5', 'e5', 'e5', 'e5', 'e5',\
'e5', 'e5', 'e5', 'e5', 'd5', 'e5', 'f5',\
'e5', 'e5', 'e5', 'd5', 'd5', 'd5', 'b4',\
'd5', 'c5', 'c5', 'g5', 'g5', 'g5', 'g5',\
'g5', 'f-5', 'g5', 'g5', 'g5', 'f-5', 'a5',\
'g5', 'f5', 'f5', 'f5', 'e5', 'e5', 'f5',\
'd5', 'f5', 'e5', 'e5', 'e5', 'e5', 'e5',\
'd5', 'g5', 'g5', 'g5', 'f5', 'f5', 'e5',\
'e5', 'e5', 'd5', 'd5', 'd5', 'd5', 'b4',\
'd5', 'c5', 'c5', 'd5', 'e5', 'e5', 'e5',\
'e5', 'd5', 'e5', 'f5', 'e5', 'f5', 'g5',\
'g5', 'g5', 'f5', 'e5', 'd5', 'f5', 'e5',\
'e5', 'e5', 'd5', 'd5', 'd5', 'd5', 'b4',\
'd5', 'c5', 'g5', 'g5', 'g5', 'g5', 'g5',\
'g5', 'f-5', 'g5', 'g5', 'g5', 'f-5', 'a5',\
'g5', 'f5', 'f5', 'f5', 'e5', 'e5', 'f5',\
'df', 'e5', 'c5', 'b4', 'c5', 'b4', 'a5',\
'b4', 'a5', 'g5', 'a5', 'c5', 'c5', 'd5',\
'd5', 'e5', 'e5', 'd5', 'e5', 'f5']
o_mere_dil_ke_chain = ['a4', 'g4', 'a4', 'a4', 'g4', 'a4',\
'g4', 'e4', 'b4', 'g4', 'a4', 'a4',\
'g4', 'a4', 'g4', 'e4', 'g4', 'e4',\
'd4', 'd4', 'e4', 'e4', 'g4', 'g4',\
'a4', 'a4', 'b4', 'b4', 'g4', 'a4',\
'b4', 'b4', 'g4', 'a4', 'c5', 'b4',\
'a4', 'c5', 'b4', 'a4', 'c5', 'b4', 'a4']
naruto_theme = ['a4', 'b4', 'a4', 'g4', 'e4', 'g4', 'a4', 'd4',\
'c4', 'd4', 'c4', 'a3', 'b3', 'a4', 'b4', 'a4',\
'g4', 'e4', 'g4', 'a4', 'd4', 'c4', 'd4', 'c4',\
'a3', 'a3', 'e4', 'd4', 'c4', 'a3', 'e4', 'd4',\
'e4', 'a4', 'c5', 'b4', 'a4', 'g4', 'a4', 'e4',\
'd4', 'e4', 'd4', 'b3', 'a3', 'a3', 'e4', 'd4',\
'c4', 'a3', 'e4', 'd4', 'e4', 'a4', 'c5', 'b4',\
'a4', 'g4', 'a4', 'e4', 'g4', 'a4', 'a4', 'b4',\
'a4', 'g4', 'e4', 'g4', 'a4', 'd4', 'c4', 'd4',\
'c4', 'a3', 'b3', 'g3', 'a4', 'b4', 'a4', 'g4',\
'e4', 'g4', 'a4', 'd4', 'c4', 'd4', 'c4', 'a3',\
'a3', 'e4', 'd4', 'c4', 'a3', 'e4', 'd4', 'e4',\
'a4', 'c5', 'b4', 'a4', 'g4', 'a4', 'e4', 'd4',\
'e4', 'd4', 'b3', 'a3', 'a3', 'e4', 'd4', 'c4',\
'a3', 'e4', 'd4', 'e4', 'a4', 'c5', 'b4', 'a4',\
'g4', 'a4', 'e4', 'g4', 'a4', 'a4', 'b4', 'a4',\
'g4', 'e4', 'g4', 'a4', 'd4', 'c4', 'd4', 'c4',\
'a3', 'b3', 'g3', 'a4', 'b4', 'a4', 'g4', 'e4',\
'g4', 'a4', 'd4', 'c4', 'd4', 'c4', 'a3']
notes = {
'1' : twinkle_twinkle,
'2' : happy_birthday,
'3' : jan_gan_man,
'4' : o_mere_dil_ke_chain,
'5' : naruto_theme
}
with open('notes.json', 'w') as file:
json.dump(notes, file)
| [
"json.dump"
] | [((3553, 3575), 'json.dump', 'json.dump', (['notes', 'file'], {}), '(notes, file)\n', (3562, 3575), False, 'import json\n')] |
# Generated by Django 2.1.1 on 2018-11-01 00:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('GestiRED', '0020_phase_observation'),
]
operations = [
migrations.RemoveField(
model_name='phase',
name='observation',
),
migrations.AlterField(
model_name='qualitycontrol',
name='observation',
field=models.CharField(max_length=200),
),
]
| [
"django.db.models.CharField",
"django.db.migrations.RemoveField"
] | [((235, 297), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""phase"""', 'name': '"""observation"""'}), "(model_name='phase', name='observation')\n", (257, 297), False, 'from django.db import migrations, models\n'), ((456, 488), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(200)'}), '(max_length=200)\n', (472, 488), False, 'from django.db import migrations, models\n')] |
from PyQt5.QtWidgets import QMainWindow, QStatusBar
from PyQt5.QtCore import QObject, QEvent
from PyQt5 import QtCore
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
mousePressed = QtCore.pyqtSignal(str)
def eventFilter(self, obj: 'QObject', event: 'QEvent') -> bool:
if event.type() == QEvent.MouseButtonPress and obj.isWidgetType():
self.mousePressed.emit(obj.objectName())
return False
return super(MainWindow, self).eventFilter(obj, event)
| [
"PyQt5.QtCore.pyqtSignal",
"PyQt5.QtWidgets.QMainWindow.__init__"
] | [((239, 261), 'PyQt5.QtCore.pyqtSignal', 'QtCore.pyqtSignal', (['str'], {}), '(str)\n', (256, 261), False, 'from PyQt5 import QtCore\n'), ((190, 216), 'PyQt5.QtWidgets.QMainWindow.__init__', 'QMainWindow.__init__', (['self'], {}), '(self)\n', (210, 216), False, 'from PyQt5.QtWidgets import QMainWindow, QStatusBar\n')] |
# Generated by Django 2.0.9 on 2018-12-05 11:07
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('users', '0006_auto_20181202_1125'),
('student', '0005_auto_20181203_1208'),
('bge', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='CommunicationLog',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True, null=True)),
('updated_at', models.DateTimeField(auto_now=True, null=True)),
('date', models.DateField(blank=True, null=True)),
('category', models.CharField(blank=True, max_length=80, null=True)),
('priority', models.IntegerField(blank=True, null=True)),
('comment', models.TextField(blank=True, null=True)),
('file', models.FileField(blank=True, null=True, upload_to='file')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='HostFamily',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True, null=True)),
('updated_at', models.DateTimeField(auto_now=True, null=True)),
('name', models.CharField(blank=True, max_length=80, null=True)),
('status', models.CharField(blank=True, choices=[('active', 'Active'), ('inactive', 'Inactive')], max_length=80, null=True)),
('address', models.CharField(blank=True, max_length=140, null=True)),
('phone', models.CharField(blank=True, max_length=80, null=True)),
('email', models.CharField(blank=True, max_length=140, null=True)),
('possible_school', models.TextField(blank=True, null=True)),
('occupation', models.CharField(blank=True, max_length=140, null=True)),
('employer', models.CharField(blank=True, max_length=80, null=True)),
('marital_status', models.CharField(blank=True, max_length=80, null=True)),
('children', models.CharField(blank=True, max_length=80, null=True)),
('pets', models.CharField(blank=True, max_length=80, null=True)),
('next_year_plan', models.CharField(blank=True, choices=[('same_student', 'Same-Student'), ('change_student', 'Change-student'), ('na', 'N/A'), ('a', 'A')], max_length=140, null=True)),
('student_preference', models.CharField(blank=True, choices=[('male', 'Male'), ('female', 'Female')], max_length=80, null=True)),
('hosting_capacity', models.CharField(blank=True, max_length=80, null=True)),
('starting_date', models.DateField(blank=True, null=True)),
('last_update_date', models.DateField(blank=True, null=True)),
('comment', models.TextField(blank=True, null=True)),
('provider', models.CharField(blank=True, max_length=80, null=True)),
('host_coordi', models.OneToOneField(null=True, on_delete=django.db.models.deletion.SET_NULL, to='users.BgeBranchAdminUser')),
('provider_branch', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='bge.BgeBranch')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='HostFile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True, null=True)),
('updated_at', models.DateTimeField(auto_now=True, null=True)),
('file', models.FileField(blank=True, null=True, upload_to='files')),
('host', models.OneToOneField(null=True, on_delete=django.db.models.deletion.CASCADE, to='branch.HostFamily')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='HostPhoto',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True, null=True)),
('updated_at', models.DateTimeField(auto_now=True, null=True)),
('photo', models.ImageField(blank=True, null=True, upload_to='images')),
('host', models.OneToOneField(null=True, on_delete=django.db.models.deletion.CASCADE, to='branch.HostFamily')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='HostStudent',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True, null=True)),
('updated_at', models.DateTimeField(auto_now=True, null=True)),
('host', models.OneToOneField(null=True, on_delete=django.db.models.deletion.CASCADE, to='branch.HostFamily')),
('student', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='student.Student')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='HostStudentReport',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True, null=True)),
('updated_at', models.DateTimeField(auto_now=True, null=True)),
('description', models.TextField(blank=True, null=True)),
('rate', models.CharField(blank=True, max_length=80, null=True)),
('improvement', models.NullBooleanField()),
('cultural_fluency', models.TextField(blank=True, null=True)),
('house_rule_attitude', models.TextField(blank=True, null=True)),
('responsibility', models.TextField(blank=True, null=True)),
('communication', models.TextField(blank=True, null=True)),
('sleeping_habits', models.TextField(blank=True, null=True)),
('school_attendance', models.TextField(blank=True, null=True)),
('comment', models.TextField(blank=True, null=True)),
('host', models.OneToOneField(null=True, on_delete=django.db.models.deletion.CASCADE, to='branch.HostFamily')),
('student', models.OneToOneField(null=True, on_delete=django.db.models.deletion.SET_NULL, to='student.Student')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='ReportFile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True, null=True)),
('updated_at', models.DateTimeField(auto_now=True, null=True)),
('file', models.FileField(blank=True, null=True, upload_to='file')),
('report', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='branch.HostStudentReport')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='ReportPhoto',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True, null=True)),
('updated_at', models.DateTimeField(auto_now=True, null=True)),
('photo', models.ImageField(blank=True, null=True, upload_to='image')),
('report', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='branch.HostStudentReport')),
],
options={
'abstract': False,
},
),
migrations.AddField(
model_name='communicationlog',
name='host',
field=models.OneToOneField(null=True, on_delete=django.db.models.deletion.CASCADE, to='branch.HostFamily'),
),
migrations.AddField(
model_name='communicationlog',
name='writer',
field=models.OneToOneField(null=True, on_delete=django.db.models.deletion.SET_NULL, to='users.BgeBranchAdminUser'),
),
]
| [
"django.db.models.NullBooleanField",
"django.db.models.ForeignKey",
"django.db.models.IntegerField",
"django.db.models.ImageField",
"django.db.models.FileField",
"django.db.models.DateTimeField",
"django.db.models.DateField",
"django.db.models.AutoField",
"django.db.models.TextField",
"django.db.m... | [((8718, 8822), 'django.db.models.OneToOneField', 'models.OneToOneField', ([], {'null': '(True)', 'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""branch.HostFamily"""'}), "(null=True, on_delete=django.db.models.deletion.CASCADE,\n to='branch.HostFamily')\n", (8738, 8822), False, 'from django.db import migrations, models\n'), ((8948, 9061), 'django.db.models.OneToOneField', 'models.OneToOneField', ([], {'null': '(True)', 'on_delete': 'django.db.models.deletion.SET_NULL', 'to': '"""users.BgeBranchAdminUser"""'}), "(null=True, on_delete=django.db.models.deletion.\n SET_NULL, to='users.BgeBranchAdminUser')\n", (8968, 9061), False, 'from django.db import migrations, models\n'), ((472, 565), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (488, 565), False, 'from django.db import migrations, models\n'), ((595, 645), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)', 'null': '(True)'}), '(auto_now_add=True, null=True)\n', (615, 645), False, 'from django.db import migrations, models\n'), ((679, 725), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now': '(True)', 'null': '(True)'}), '(auto_now=True, null=True)\n', (699, 725), False, 'from django.db import migrations, models\n'), ((753, 792), 'django.db.models.DateField', 'models.DateField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (769, 792), False, 'from django.db import migrations, models\n'), ((824, 878), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(80)', 'null': '(True)'}), '(blank=True, max_length=80, null=True)\n', (840, 878), False, 'from django.db import migrations, models\n'), ((910, 952), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (929, 952), False, 'from django.db import migrations, models\n'), ((983, 1022), 'django.db.models.TextField', 'models.TextField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (999, 1022), False, 'from django.db import migrations, models\n'), ((1050, 1107), 'django.db.models.FileField', 'models.FileField', ([], {'blank': '(True)', 'null': '(True)', 'upload_to': '"""file"""'}), "(blank=True, null=True, upload_to='file')\n", (1066, 1107), False, 'from django.db import migrations, models\n'), ((1315, 1408), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (1331, 1408), False, 'from django.db import migrations, models\n'), ((1438, 1488), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)', 'null': '(True)'}), '(auto_now_add=True, null=True)\n', (1458, 1488), False, 'from django.db import migrations, models\n'), ((1522, 1568), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now': '(True)', 'null': '(True)'}), '(auto_now=True, null=True)\n', (1542, 1568), False, 'from django.db import migrations, models\n'), ((1596, 1650), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(80)', 'null': '(True)'}), '(blank=True, max_length=80, null=True)\n', (1612, 1650), False, 'from django.db import migrations, models\n'), ((1680, 1796), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'choices': "[('active', 'Active'), ('inactive', 'Inactive')]", 'max_length': '(80)', 'null': '(True)'}), "(blank=True, choices=[('active', 'Active'), ('inactive',\n 'Inactive')], max_length=80, null=True)\n", (1696, 1796), False, 'from django.db import migrations, models\n'), ((1823, 1878), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(140)', 'null': '(True)'}), '(blank=True, max_length=140, null=True)\n', (1839, 1878), False, 'from django.db import migrations, models\n'), ((1907, 1961), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(80)', 'null': '(True)'}), '(blank=True, max_length=80, null=True)\n', (1923, 1961), False, 'from django.db import migrations, models\n'), ((1990, 2045), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(140)', 'null': '(True)'}), '(blank=True, max_length=140, null=True)\n', (2006, 2045), False, 'from django.db import migrations, models\n'), ((2084, 2123), 'django.db.models.TextField', 'models.TextField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (2100, 2123), False, 'from django.db import migrations, models\n'), ((2157, 2212), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(140)', 'null': '(True)'}), '(blank=True, max_length=140, null=True)\n', (2173, 2212), False, 'from django.db import migrations, models\n'), ((2244, 2298), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(80)', 'null': '(True)'}), '(blank=True, max_length=80, null=True)\n', (2260, 2298), False, 'from django.db import migrations, models\n'), ((2336, 2390), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(80)', 'null': '(True)'}), '(blank=True, max_length=80, null=True)\n', (2352, 2390), False, 'from django.db import migrations, models\n'), ((2422, 2476), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(80)', 'null': '(True)'}), '(blank=True, max_length=80, null=True)\n', (2438, 2476), False, 'from django.db import migrations, models\n'), ((2504, 2558), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(80)', 'null': '(True)'}), '(blank=True, max_length=80, null=True)\n', (2520, 2558), False, 'from django.db import migrations, models\n'), ((2596, 2769), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'choices': "[('same_student', 'Same-Student'), ('change_student', 'Change-student'), (\n 'na', 'N/A'), ('a', 'A')]", 'max_length': '(140)', 'null': '(True)'}), "(blank=True, choices=[('same_student', 'Same-Student'), (\n 'change_student', 'Change-student'), ('na', 'N/A'), ('a', 'A')],\n max_length=140, null=True)\n", (2612, 2769), False, 'from django.db import migrations, models\n'), ((2802, 2911), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'choices': "[('male', 'Male'), ('female', 'Female')]", 'max_length': '(80)', 'null': '(True)'}), "(blank=True, choices=[('male', 'Male'), ('female', 'Female'\n )], max_length=80, null=True)\n", (2818, 2911), False, 'from django.db import migrations, models\n'), ((2946, 3000), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(80)', 'null': '(True)'}), '(blank=True, max_length=80, null=True)\n', (2962, 3000), False, 'from django.db import migrations, models\n'), ((3037, 3076), 'django.db.models.DateField', 'models.DateField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (3053, 3076), False, 'from django.db import migrations, models\n'), ((3116, 3155), 'django.db.models.DateField', 'models.DateField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (3132, 3155), False, 'from django.db import migrations, models\n'), ((3186, 3225), 'django.db.models.TextField', 'models.TextField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (3202, 3225), False, 'from django.db import migrations, models\n'), ((3257, 3311), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(80)', 'null': '(True)'}), '(blank=True, max_length=80, null=True)\n', (3273, 3311), False, 'from django.db import migrations, models\n'), ((3346, 3459), 'django.db.models.OneToOneField', 'models.OneToOneField', ([], {'null': '(True)', 'on_delete': 'django.db.models.deletion.SET_NULL', 'to': '"""users.BgeBranchAdminUser"""'}), "(null=True, on_delete=django.db.models.deletion.\n SET_NULL, to='users.BgeBranchAdminUser')\n", (3366, 3459), False, 'from django.db import migrations, models\n'), ((3493, 3591), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'null': '(True)', 'on_delete': 'django.db.models.deletion.SET_NULL', 'to': '"""bge.BgeBranch"""'}), "(null=True, on_delete=django.db.models.deletion.SET_NULL,\n to='bge.BgeBranch')\n", (3510, 3591), False, 'from django.db import migrations, models\n'), ((3793, 3886), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (3809, 3886), False, 'from django.db import migrations, models\n'), ((3916, 3966), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)', 'null': '(True)'}), '(auto_now_add=True, null=True)\n', (3936, 3966), False, 'from django.db import migrations, models\n'), ((4000, 4046), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now': '(True)', 'null': '(True)'}), '(auto_now=True, null=True)\n', (4020, 4046), False, 'from django.db import migrations, models\n'), ((4074, 4132), 'django.db.models.FileField', 'models.FileField', ([], {'blank': '(True)', 'null': '(True)', 'upload_to': '"""files"""'}), "(blank=True, null=True, upload_to='files')\n", (4090, 4132), False, 'from django.db import migrations, models\n'), ((4160, 4264), 'django.db.models.OneToOneField', 'models.OneToOneField', ([], {'null': '(True)', 'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""branch.HostFamily"""'}), "(null=True, on_delete=django.db.models.deletion.CASCADE,\n to='branch.HostFamily')\n", (4180, 4264), False, 'from django.db import migrations, models\n'), ((4467, 4560), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (4483, 4560), False, 'from django.db import migrations, models\n'), ((4590, 4640), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)', 'null': '(True)'}), '(auto_now_add=True, null=True)\n', (4610, 4640), False, 'from django.db import migrations, models\n'), ((4674, 4720), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now': '(True)', 'null': '(True)'}), '(auto_now=True, null=True)\n', (4694, 4720), False, 'from django.db import migrations, models\n'), ((4749, 4809), 'django.db.models.ImageField', 'models.ImageField', ([], {'blank': '(True)', 'null': '(True)', 'upload_to': '"""images"""'}), "(blank=True, null=True, upload_to='images')\n", (4766, 4809), False, 'from django.db import migrations, models\n'), ((4837, 4941), 'django.db.models.OneToOneField', 'models.OneToOneField', ([], {'null': '(True)', 'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""branch.HostFamily"""'}), "(null=True, on_delete=django.db.models.deletion.CASCADE,\n to='branch.HostFamily')\n", (4857, 4941), False, 'from django.db import migrations, models\n'), ((5146, 5239), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (5162, 5239), False, 'from django.db import migrations, models\n'), ((5269, 5319), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)', 'null': '(True)'}), '(auto_now_add=True, null=True)\n', (5289, 5319), False, 'from django.db import migrations, models\n'), ((5353, 5399), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now': '(True)', 'null': '(True)'}), '(auto_now=True, null=True)\n', (5373, 5399), False, 'from django.db import migrations, models\n'), ((5427, 5531), 'django.db.models.OneToOneField', 'models.OneToOneField', ([], {'null': '(True)', 'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""branch.HostFamily"""'}), "(null=True, on_delete=django.db.models.deletion.CASCADE,\n to='branch.HostFamily')\n", (5447, 5531), False, 'from django.db import migrations, models\n'), ((5558, 5658), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'null': '(True)', 'on_delete': 'django.db.models.deletion.SET_NULL', 'to': '"""student.Student"""'}), "(null=True, on_delete=django.db.models.deletion.SET_NULL,\n to='student.Student')\n", (5575, 5658), False, 'from django.db import migrations, models\n'), ((5869, 5962), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (5885, 5962), False, 'from django.db import migrations, models\n'), ((5992, 6042), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)', 'null': '(True)'}), '(auto_now_add=True, null=True)\n', (6012, 6042), False, 'from django.db import migrations, models\n'), ((6076, 6122), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now': '(True)', 'null': '(True)'}), '(auto_now=True, null=True)\n', (6096, 6122), False, 'from django.db import migrations, models\n'), ((6157, 6196), 'django.db.models.TextField', 'models.TextField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (6173, 6196), False, 'from django.db import migrations, models\n'), ((6224, 6278), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(80)', 'null': '(True)'}), '(blank=True, max_length=80, null=True)\n', (6240, 6278), False, 'from django.db import migrations, models\n'), ((6313, 6338), 'django.db.models.NullBooleanField', 'models.NullBooleanField', ([], {}), '()\n', (6336, 6338), False, 'from django.db import migrations, models\n'), ((6378, 6417), 'django.db.models.TextField', 'models.TextField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (6394, 6417), False, 'from django.db import migrations, models\n'), ((6460, 6499), 'django.db.models.TextField', 'models.TextField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (6476, 6499), False, 'from django.db import migrations, models\n'), ((6537, 6576), 'django.db.models.TextField', 'models.TextField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (6553, 6576), False, 'from django.db import migrations, models\n'), ((6613, 6652), 'django.db.models.TextField', 'models.TextField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (6629, 6652), False, 'from django.db import migrations, models\n'), ((6691, 6730), 'django.db.models.TextField', 'models.TextField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (6707, 6730), False, 'from django.db import migrations, models\n'), ((6771, 6810), 'django.db.models.TextField', 'models.TextField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (6787, 6810), False, 'from django.db import migrations, models\n'), ((6841, 6880), 'django.db.models.TextField', 'models.TextField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (6857, 6880), False, 'from django.db import migrations, models\n'), ((6908, 7012), 'django.db.models.OneToOneField', 'models.OneToOneField', ([], {'null': '(True)', 'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""branch.HostFamily"""'}), "(null=True, on_delete=django.db.models.deletion.CASCADE,\n to='branch.HostFamily')\n", (6928, 7012), False, 'from django.db import migrations, models\n'), ((7039, 7143), 'django.db.models.OneToOneField', 'models.OneToOneField', ([], {'null': '(True)', 'on_delete': 'django.db.models.deletion.SET_NULL', 'to': '"""student.Student"""'}), "(null=True, on_delete=django.db.models.deletion.\n SET_NULL, to='student.Student')\n", (7059, 7143), False, 'from django.db import migrations, models\n'), ((7346, 7439), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (7362, 7439), False, 'from django.db import migrations, models\n'), ((7469, 7519), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)', 'null': '(True)'}), '(auto_now_add=True, null=True)\n', (7489, 7519), False, 'from django.db import migrations, models\n'), ((7553, 7599), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now': '(True)', 'null': '(True)'}), '(auto_now=True, null=True)\n', (7573, 7599), False, 'from django.db import migrations, models\n'), ((7627, 7684), 'django.db.models.FileField', 'models.FileField', ([], {'blank': '(True)', 'null': '(True)', 'upload_to': '"""file"""'}), "(blank=True, null=True, upload_to='file')\n", (7643, 7684), False, 'from django.db import migrations, models\n'), ((7714, 7822), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'null': '(True)', 'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""branch.HostStudentReport"""'}), "(null=True, on_delete=django.db.models.deletion.CASCADE,\n to='branch.HostStudentReport')\n", (7731, 7822), False, 'from django.db import migrations, models\n'), ((8027, 8120), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (8043, 8120), False, 'from django.db import migrations, models\n'), ((8150, 8200), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)', 'null': '(True)'}), '(auto_now_add=True, null=True)\n', (8170, 8200), False, 'from django.db import migrations, models\n'), ((8234, 8280), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now': '(True)', 'null': '(True)'}), '(auto_now=True, null=True)\n', (8254, 8280), False, 'from django.db import migrations, models\n'), ((8309, 8368), 'django.db.models.ImageField', 'models.ImageField', ([], {'blank': '(True)', 'null': '(True)', 'upload_to': '"""image"""'}), "(blank=True, null=True, upload_to='image')\n", (8326, 8368), False, 'from django.db import migrations, models\n'), ((8398, 8506), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'null': '(True)', 'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""branch.HostStudentReport"""'}), "(null=True, on_delete=django.db.models.deletion.CASCADE,\n to='branch.HostStudentReport')\n", (8415, 8506), False, 'from django.db import migrations, models\n')] |
#!/usr/bin/env python3
#
# submit_one_Door43_test.py
# Written: Jan 2019
# Last modified: 2019-12-09 RJH
#
# Python imports
import os
import sys
import json
import logging
import subprocess
# ======================================================================
# User settings
USE_LOCALCOMPOSE_URL = True
LOAD_FROM_DISK_FILE = False
OVERWRITE = False
REVIEW_FLAG = True # Shows all the URLs again at the end
AUTO_OPEN_IN_BROWSER = True
# Choose one of the following
# TEST_PREFIXES = ('',)
TEST_PREFIXES = ('dev-',)
# TEST_PREFIXES = ('', 'dev-',)
TEST_FILENAME = 'Door43-Catalog--vi_ulb--fork' # .json will be appended to this
LOCAL_FILEPATH = '/mnt/SSD/uW/Software/'
# ======================================================================
if USE_LOCALCOMPOSE_URL: assert TEST_PREFIXES == ('dev-',)
LOCAL_COMPOSE_URL = 'http://127.0.0.1:8080/'
TEST_FOLDER = f'{LOCAL_FILEPATH}/testPayloads/JSON/Door43/'
TEST_FILENAME = TEST_FILENAME.replace('/','--')
filepath = os.path.join(TEST_FOLDER, TEST_FILENAME+'.json')
test_json = None
if LOAD_FROM_DISK_FILE:
if os.path.isfile(filepath):
print(f"Loading '{filepath}'…")
with open(filepath, 'rt') as jf:
test_json = jf.read()
else:
logging.critical(f"LOAD_FROM_DISK_FILE was specified but '{filepath}' doesn't exist")
if not test_json:
print("Using locally pasted JSON string…")
test_json = """
{
"secret": "",
"forkee": {
"id": 22755,
"owner": {
"id": 4598,
"login": "Door43-Catalog",
"full_name": "Door43 Resource Catalog",
"email": "<EMAIL>",
"avatar_url": "https://git.door43.org/img/avatar_default.png",
"language": "",
"is_admin": false,
"last_login": "1970-01-01T00:00:00Z",
"created": "2016-10-18T19:03:36Z",
"username": "Door43-Catalog"
},
"name": "vi_ulb",
"full_name": "Door43-Catalog/vi_ulb",
"description": "Vietnamese ULB. STR https://git.door43.org/Door43/SourceTextRequestForm/issues/149\\r\\n\\r\\n",
"empty": false,
"private": false,
"fork": false,
"parent": null,
"mirror": false,
"size": 5376,
"html_url": "https://git.door43.org/Door43-Catalog/vi_ulb",
"ssh_url": "git@git.door43.org:Door43-Catalog/vi_ulb.git",
"clone_url": "https://git.door43.org/Door43-Catalog/vi_ulb.git",
"website": "",
"stars_count": 0,
"forks_count": 1,
"watchers_count": 9,
"open_issues_count": 0,
"default_branch": "master",
"archived": false,
"created_at": "2018-02-12T18:13:00Z",
"updated_at": "2020-08-24T04:10:55Z",
"permissions": {
"admin": true,
"push": true,
"pull": true
},
"has_issues": true,
"has_wiki": false,
"has_pull_requests": true,
"ignore_whitespace_conflicts": false,
"allow_merge_commits": true,
"allow_rebase": true,
"allow_rebase_explicit": true,
"allow_squash_merge": true,
"avatar_url": ""
},
"repository": {
"id": 58265,
"owner": {
"id": 6221,
"login": "STR",
"full_name": "",
"email": "",
"avatar_url": "https://git.door43.org/avatars/6221",
"language": "",
"is_admin": false,
"last_login": "1970-01-01T00:00:00Z",
"created": "2017-08-15T15:24:51Z",
"username": "STR"
},
"name": "vi_ulb",
"full_name": "STR/vi_ulb",
"description": "Vietnamese ULB. STR https://git.door43.org/Door43/SourceTextRequestForm/issues/149\\r\\n\\r\\n",
"empty": false,
"private": false,
"fork": true,
"parent": {
"id": 22755,
"owner": {
"id": 4598,
"login": "Door43-Catalog",
"full_name": "Door43 Resource Catalog",
"email": "<EMAIL>",
"avatar_url": "https://git.door43.org/img/avatar_default.png",
"language": "",
"is_admin": false,
"last_login": "1970-01-01T00:00:00Z",
"created": "2016-10-18T19:03:36Z",
"username": "Door43-Catalog"
},
"name": "vi_ulb",
"full_name": "Door43-Catalog/vi_ulb",
"description": "Vietnamese ULB. STR https://git.door43.org/Door43/SourceTextRequestForm/issues/149\\r\\n\\r\\n",
"empty": false,
"private": false,
"fork": false,
"parent": null,
"mirror": false,
"size": 5376,
"html_url": "https://git.door43.org/Door43-Catalog/vi_ulb",
"ssh_url": "<EMAIL>:Door43-Catalog/vi_ulb.git",
"clone_url": "https://git.door43.org/Door43-Catalog/vi_ulb.git",
"website": "",
"stars_count": 0,
"forks_count": 2,
"watchers_count": 9,
"open_issues_count": 0,
"default_branch": "master",
"archived": false,
"created_at": "2018-02-12T18:13:00Z",
"updated_at": "2020-08-24T04:10:55Z",
"permissions": {
"admin": true,
"push": true,
"pull": true
},
"has_issues": true,
"has_wiki": false,
"has_pull_requests": true,
"ignore_whitespace_conflicts": false,
"allow_merge_commits": true,
"allow_rebase": true,
"allow_rebase_explicit": true,
"allow_squash_merge": true,
"avatar_url": ""
},
"mirror": false,
"size": 0,
"html_url": "https://git.door43.org/STR/vi_ulb",
"ssh_url": "git@git.door43.org:STR/vi_ulb.git",
"clone_url": "https://git.door43.org/STR/vi_ulb.git",
"website": "",
"stars_count": 0,
"forks_count": 0,
"watchers_count": 0,
"open_issues_count": 0,
"default_branch": "master",
"archived": false,
"created_at": "2020-08-24T04:11:10Z",
"updated_at": "2020-08-24T04:11:10Z",
"permissions": {
"admin": true,
"push": true,
"pull": true
},
"has_issues": true,
"has_wiki": true,
"has_pull_requests": true,
"ignore_whitespace_conflicts": false,
"allow_merge_commits": true,
"allow_rebase": true,
"allow_rebase_explicit": true,
"allow_squash_merge": true,
"avatar_url": ""
},
"sender": {
"id": 6442,
"login": "RobH",
"full_name": "<NAME>",
"email": "<EMAIL>",
"avatar_url": "https://git.door43.org/avatars/f85d2867fead49449e89c6822dc77bc6",
"language": "en-US",
"is_admin": true,
"last_login": "2020-08-11T23:22:24Z",
"created": "2017-10-22T07:31:07Z",
"username": "RobH"
}
}
""" \
.replace('\\n','').replace('\n','') \
.replace("{'", '{"').replace("': ", '": ').replace(": '", ': "').replace("', ", '", ').replace(", '", ', "').replace("'}", '"}') \
.replace(': True,', ': true,').replace(': False,', ': false,').replace(': None,', ': null,') \
.replace(': True}', ': true}').replace(': False}', ': false}').replace(': None}', ': null}')
# print('test_json = ', test_json)
if 0 and TEST_FILENAME.replace('--','/') not in test_json:
print(f"Seems '{TEST_FILENAME}' can't be found in the JSON -- is it correct?")
print(f" {test_json[:600]}…")
sys.exit()
if OVERWRITE or not LOAD_FROM_DISK_FILE: # Write the json file
print(f"Writing '{filepath}'…")
with open(filepath, 'wt') as jf:
jf.write(test_json)
else:
print("(Not saving JSON file)")
if not os.path.isfile(filepath):
logging.critical(f"Unable to proceed coz '{filepath}' doesn't exist")
sys.exit()
webURL = ''
for prefix in TEST_PREFIXES:
long_prefix = 'develop' if prefix else 'git'
webhook = LOCAL_COMPOSE_URL if USE_LOCALCOMPOSE_URL else f'https://{long_prefix}.door43.org/client/webhook/'
print( f"\n{'(dev) ' if prefix else ''}'{TEST_FILENAME}' to {webhook}:" )
jsonFilename = f'{TEST_FOLDER}{TEST_FILENAME}.json'
with open(jsonFilename, 'rt') as jsonFile:
jsonString = jsonFile.read()
jsonDict = json.loads(jsonString)
if 'pusher' in jsonDict:
event = 'push'
elif 'release' in jsonDict:
event = 'release'
elif 'pull_request' in jsonDict:
event = 'pull_request'
elif 'ref_type' in jsonDict and jsonDict['ref_type']=='branch' and 'pusher_type' in jsonDict:
event = 'delete'
elif 'forkee' in jsonDict:
event = 'fork'
# elif 'ref_type' in jsonDict and jsonDict['ref_type']=='branch' and 'ref' in jsonDict:
# event = 'create'
else:
logging.critical(f"Can't determine event (push/release/delete/fork, etc.) from JSON")
halt
# Use curl to actually POST the JSON to the given webhook URL
parameters = ['curl', webhook,
'--data', f'@{jsonFilename}',
'--header', "Content-Type: application/json",
'--header', f"X-Gitea-Event: {event}",
]
myProcess = subprocess.Popen( parameters, stdout=subprocess.PIPE, stderr=subprocess.PIPE )
programOutputBytes, programErrorOutputBytes = myProcess.communicate()
# Process the output from curl
if programOutputBytes:
programOutputString = programOutputBytes.decode(encoding='utf-8', errors='replace')
#programOutputString = programOutputString.replace( baseFolder + ('' if baseFolder[-1]=='/' else '/'), '' ) # Remove long file paths to make it easier for the user to read
#with open( os.path.join( outputFolder, 'ScriptOutput.txt" ), 'wt', encoding='utf-8' ) as myFile: myFile.write( programOutputString )
#print( f"Response = {programOutputString!r}" )
if programOutputString.startswith('{'): # Assume it's a json dict
responseDict = json.loads(programOutputString)
if responseDict['status'] == 'queued':
print( " Job successfully queued" )
else:
print( f"Response dict = {responseDict}" )
else:
print( f"Response = {programOutputString!r}" )
if programErrorOutputBytes:
programErrorOutputString = programErrorOutputBytes.decode(encoding='utf-8', errors='replace')
#with open( os.path.join( outputFolder, 'ScriptErrorOutput.txt" ), 'wt', encoding='utf-8' ) as myFile: myFile.write( programErrorOutputString )
if not programErrorOutputString.startswith(' % Total'):
print( f"pEOS = {programErrorOutputString!r}" )
if webURL:
url = f"https://{'dev.' if prefix else ''}door43.org/u/{webURL}/"
print(f"View result at {url}")
if AUTO_OPEN_IN_BROWSER:
import webbrowser
webbrowser.open(url, new=0, autoraise=True)
#subprocess.Popen(['xdg-open', url])
| [
"os.path.join",
"subprocess.Popen",
"json.loads",
"os.path.isfile",
"webbrowser.open",
"logging.critical",
"sys.exit"
] | [((993, 1043), 'os.path.join', 'os.path.join', (['TEST_FOLDER', "(TEST_FILENAME + '.json')"], {}), "(TEST_FOLDER, TEST_FILENAME + '.json')\n", (1005, 1043), False, 'import os\n'), ((1090, 1114), 'os.path.isfile', 'os.path.isfile', (['filepath'], {}), '(filepath)\n', (1104, 1114), False, 'import os\n'), ((6905, 6915), 'sys.exit', 'sys.exit', ([], {}), '()\n', (6913, 6915), False, 'import sys\n'), ((7129, 7153), 'os.path.isfile', 'os.path.isfile', (['filepath'], {}), '(filepath)\n', (7143, 7153), False, 'import os\n'), ((7159, 7228), 'logging.critical', 'logging.critical', (['f"""Unable to proceed coz \'{filepath}\' doesn\'t exist"""'], {}), '(f"Unable to proceed coz \'{filepath}\' doesn\'t exist")\n', (7175, 7228), False, 'import logging\n'), ((7233, 7243), 'sys.exit', 'sys.exit', ([], {}), '()\n', (7241, 7243), False, 'import sys\n'), ((7681, 7703), 'json.loads', 'json.loads', (['jsonString'], {}), '(jsonString)\n', (7691, 7703), False, 'import json\n'), ((8607, 8683), 'subprocess.Popen', 'subprocess.Popen', (['parameters'], {'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.PIPE'}), '(parameters, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n', (8623, 8683), False, 'import subprocess\n'), ((1247, 1337), 'logging.critical', 'logging.critical', (['f"""LOAD_FROM_DISK_FILE was specified but \'{filepath}\' doesn\'t exist"""'], {}), '(\n f"LOAD_FROM_DISK_FILE was specified but \'{filepath}\' doesn\'t exist")\n', (1263, 1337), False, 'import logging\n'), ((9394, 9425), 'json.loads', 'json.loads', (['programOutputString'], {}), '(programOutputString)\n', (9404, 9425), False, 'import json\n'), ((10289, 10332), 'webbrowser.open', 'webbrowser.open', (['url'], {'new': '(0)', 'autoraise': '(True)'}), '(url, new=0, autoraise=True)\n', (10304, 10332), False, 'import webbrowser\n'), ((8196, 8286), 'logging.critical', 'logging.critical', (['f"""Can\'t determine event (push/release/delete/fork, etc.) from JSON"""'], {}), '(\n f"Can\'t determine event (push/release/delete/fork, etc.) from JSON")\n', (8212, 8286), False, 'import logging\n')] |
'''entre no programa com a altura e largura de uma parede
em mtr calcule a area e a quantidade de tinta necessária para
pintá-la considerando que cada litro de tinta pinta 2m²'''
from math import ceil
cores = {'limpa': '\033[m', 'azul': '\033[1;34m'}
print('{:-^40}'.format('CALCULO DE ÁREA'))
largura = float(input('Digite a largura da Parede: '))
altura = float(input('Digite a altura da Parede: '))
area = largura * altura
tinta = area / 2
print('Sua parede tem uma dimensão de \033[1;34m{}\033[m x \033[1;34m{}\033[mmtr. '.format(largura, altura))
print('{}{:.2f}M²{} é sua área de Parede. '.format(cores['azul'], area, cores['limpa']))
print('{}{}-Litros{} de tinta para pintar está área. '.format(cores['azul'], ceil(tinta), cores['limpa']))
print('{:-^40}'.format('FIM'))
| [
"math.ceil"
] | [((722, 733), 'math.ceil', 'ceil', (['tinta'], {}), '(tinta)\n', (726, 733), False, 'from math import ceil\n')] |
import numpy as np
import sympy as sp
import pandas as pd
import sys
#give input equation
expr = sp.sympify("x_1**2 + x_2*x_3")
#get number of columns from X dataframe and y dataframe
num_of_columns = 3+1 #dataframe features len(X.columns) +1
num_of_y_columns = 2 #dataframe features len(Y.columns) +1
#create equation variables as user prefers to enter like x_1 ** 2 + x_2 * x_3
symbols = sp.symarray('x',num_of_columns)
symbols = symbols[1:]
y_symbols = sp.symarray('y', num_of_y_columns)
y_symbols = y_symbols[1:]
print(symbols)
df = pd.DataFrame(
[[21, 72, 67.1],
[23, 78, 69.5],
[32, 74, 56.6],
[52, 54, 76.2]],
columns = ['x1','x2', 'x3'])
variable_tuple = [df[c].to_numpy() for i,c in enumerate(df.columns, start=1)]
mod = sys.modules[__name__]
for i,c in enumerate(df.columns, start=1):
setattr(mod, "x_"+str(i), df[c])
f = sp.lambdify(symbols, expr, 'numpy')
result = f(*variable_tuple)
print(result)
expr2 = sp.sympify("8*x_3/(pi * x_2^3)")
f = sp.lambdify(symbols, expr2, 'numpy')
result = f(*variable_tuple)
print(result)
| [
"pandas.DataFrame",
"sympy.sympify",
"sympy.symarray",
"sympy.lambdify"
] | [((97, 127), 'sympy.sympify', 'sp.sympify', (['"""x_1**2 + x_2*x_3"""'], {}), "('x_1**2 + x_2*x_3')\n", (107, 127), True, 'import sympy as sp\n'), ((390, 422), 'sympy.symarray', 'sp.symarray', (['"""x"""', 'num_of_columns'], {}), "('x', num_of_columns)\n", (401, 422), True, 'import sympy as sp\n'), ((456, 490), 'sympy.symarray', 'sp.symarray', (['"""y"""', 'num_of_y_columns'], {}), "('y', num_of_y_columns)\n", (467, 490), True, 'import sympy as sp\n'), ((537, 648), 'pandas.DataFrame', 'pd.DataFrame', (['[[21, 72, 67.1], [23, 78, 69.5], [32, 74, 56.6], [52, 54, 76.2]]'], {'columns': "['x1', 'x2', 'x3']"}), "([[21, 72, 67.1], [23, 78, 69.5], [32, 74, 56.6], [52, 54, 76.2\n ]], columns=['x1', 'x2', 'x3'])\n", (549, 648), True, 'import pandas as pd\n'), ((841, 876), 'sympy.lambdify', 'sp.lambdify', (['symbols', 'expr', '"""numpy"""'], {}), "(symbols, expr, 'numpy')\n", (852, 876), True, 'import sympy as sp\n'), ((927, 959), 'sympy.sympify', 'sp.sympify', (['"""8*x_3/(pi * x_2^3)"""'], {}), "('8*x_3/(pi * x_2^3)')\n", (937, 959), True, 'import sympy as sp\n'), ((964, 1000), 'sympy.lambdify', 'sp.lambdify', (['symbols', 'expr2', '"""numpy"""'], {}), "(symbols, expr2, 'numpy')\n", (975, 1000), True, 'import sympy as sp\n')] |
"""
Read sample documents from mongo db and write sample metadata files
to iRODS.
"""
import argparse
from itertools import islice
import json
import os
import pprint
import re
import sys
import time
import pymongo
import imicrobe.util.irods as irods
def write_sample_metadata_files(target_root, file_limit):
"""
This script is intended to run on a system with access to the iMicrobe MongoDB.
For each document in the 'sample' collection of the 'imicrobe' database write
the document contents as a CSV file to iRODS.
"""
print('target iRODS directory is "{}"'.format(target_root))
with irods.irods_session_manager() as irods_session:
if irods.irods_collection_exists(irods_session, target_root):
print(' target directory exists')
else:
print(' target directory does not exist')
exit(1)
print('\nsearching for samples in Mongo DB')
sequence_file_extensions = re.compile('\.(fa|fna|fasta|fastq)(\.tar)?(\.gz)?$')
t0 = time.time()
samples = {}
samples_missing_specimen_file = []
samples_missing_fasta_file = []
for sample_metadata in pymongo.MongoClient().imicrobe.sample.find(limit=file_limit):
sample_fn = None
#if sample_metadata is None:
# print('what is this all about?')
# raise Exception()
if 'specimen__file' in sample_metadata:
specimen_files = sample_metadata['specimen__file'].split()
##print('specimen__file:\n\t"{}"'.format('\n\t'.join(specimen_files)))
# find the FASTA file
for fp in specimen_files:
if not fp.startswith('/iplant/'):
# avoid ftp
pass
elif sequence_file_extensions.search(fp) is None:
pass
else:
sample_dp, sample_fn = os.path.split(fp)
metadata_fp = sequence_file_extensions.sub('.json', fp)
samples[metadata_fp] = sample_metadata
break
if sample_fn is None:
samples_missing_fasta_file.append(sample_metadata)
print('{}: no FASTA file in "{}"'.format(
len(samples_missing_fasta_file),
pprint.pformat(sample_metadata)))
else:
pass
#print('FASTA file: "{}"'.format(sample_fn))
else:
samples_missing_specimen_file.append(sample_metadata)
print('{}: no specimen__file in "{}"'.format(
len(samples_missing_specimen_file),
pprint.pformat(sample_metadata['_id'])))
print('found {} samples in {:5.2f}s'.format(len(samples), time.time()-t0))
print(' {} samples have no specimen__file'.format(len(samples_missing_specimen_file)))
print(' {} samples have no FASTA file'.format(len(samples_missing_fasta_file)))
t0 = time.time()
print('which files already exist?')
files_to_be_written = {}
with irods.irods_session_manager() as irods_session:
for metadata_fp, sample_metadata in sorted(samples.items()):
print('checking for "{}"'.format(metadata_fp))
if irods.irods_data_object_exists(irods_session, metadata_fp):
pass
else:
files_to_be_written[metadata_fp] = sample_metadata
print('found {} files to be written in {:5.2f}s'.format(len(files_to_be_written), time.time()-t0))
t0 = time.time()
print('\nwriting {} files'.format(len(files_to_be_written)))
with irods.irods_session_manager() as irods_session:
for metadata_fp, sample_metadata in sorted(files_to_be_written.items()):
print('writing {}'.format(metadata_fp))
# remove mongo _id field - it will not serialize
del sample_metadata['_id']
irods.irods_write_data_object(
irods_session,
metadata_fp,
content=json.dumps(sample_metadata, indent=2))
#print(json.dumps(sample_metadata, indent=2))
print('wrote {} metadata files in {:5.3f}s'.format(len(files_to_be_written), time.time()-t0))
def main(argv):
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('--target-root', default='/iplant/home/shared/imicrobe/projects')
arg_parser.add_argument('--file-limit', type=int, default=0, required=False)
args = arg_parser.parse_args(args=argv)
write_sample_metadata_files(
target_root=args.target_root,
file_limit=args.file_limit)
def cli():
main(sys.argv[1:])
if __name__ == '__main__':
cli()
| [
"imicrobe.util.irods.irods_collection_exists",
"pprint.pformat",
"imicrobe.util.irods.irods_session_manager",
"re.compile",
"argparse.ArgumentParser",
"json.dumps",
"imicrobe.util.irods.irods_data_object_exists",
"pymongo.MongoClient",
"time.time",
"os.path.split"
] | [((955, 1010), 're.compile', 're.compile', (['"""\\\\.(fa|fna|fasta|fastq)(\\\\.tar)?(\\\\.gz)?$"""'], {}), "('\\\\.(fa|fna|fasta|fastq)(\\\\.tar)?(\\\\.gz)?$')\n", (965, 1010), False, 'import re\n'), ((1017, 1028), 'time.time', 'time.time', ([], {}), '()\n', (1026, 1028), False, 'import time\n'), ((2947, 2958), 'time.time', 'time.time', ([], {}), '()\n', (2956, 2958), False, 'import time\n'), ((3507, 3518), 'time.time', 'time.time', ([], {}), '()\n', (3516, 3518), False, 'import time\n'), ((4230, 4255), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (4253, 4255), False, 'import argparse\n'), ((619, 648), 'imicrobe.util.irods.irods_session_manager', 'irods.irods_session_manager', ([], {}), '()\n', (646, 648), True, 'import imicrobe.util.irods as irods\n'), ((678, 735), 'imicrobe.util.irods.irods_collection_exists', 'irods.irods_collection_exists', (['irods_session', 'target_root'], {}), '(irods_session, target_root)\n', (707, 735), True, 'import imicrobe.util.irods as irods\n'), ((3037, 3066), 'imicrobe.util.irods.irods_session_manager', 'irods.irods_session_manager', ([], {}), '()\n', (3064, 3066), True, 'import imicrobe.util.irods as irods\n'), ((3593, 3622), 'imicrobe.util.irods.irods_session_manager', 'irods.irods_session_manager', ([], {}), '()\n', (3620, 3622), True, 'import imicrobe.util.irods as irods\n'), ((3228, 3286), 'imicrobe.util.irods.irods_data_object_exists', 'irods.irods_data_object_exists', (['irods_session', 'metadata_fp'], {}), '(irods_session, metadata_fp)\n', (3258, 3286), True, 'import imicrobe.util.irods as irods\n'), ((2743, 2754), 'time.time', 'time.time', ([], {}), '()\n', (2752, 2754), False, 'import time\n'), ((3480, 3491), 'time.time', 'time.time', ([], {}), '()\n', (3489, 3491), False, 'import time\n'), ((4179, 4190), 'time.time', 'time.time', ([], {}), '()\n', (4188, 4190), False, 'import time\n'), ((1148, 1169), 'pymongo.MongoClient', 'pymongo.MongoClient', ([], {}), '()\n', (1167, 1169), False, 'import pymongo\n'), ((2639, 2677), 'pprint.pformat', 'pprint.pformat', (["sample_metadata['_id']"], {}), "(sample_metadata['_id'])\n", (2653, 2677), False, 'import pprint\n'), ((4001, 4038), 'json.dumps', 'json.dumps', (['sample_metadata'], {'indent': '(2)'}), '(sample_metadata, indent=2)\n', (4011, 4038), False, 'import json\n'), ((1887, 1904), 'os.path.split', 'os.path.split', (['fp'], {}), '(fp)\n', (1900, 1904), False, 'import os\n'), ((2299, 2330), 'pprint.pformat', 'pprint.pformat', (['sample_metadata'], {}), '(sample_metadata)\n', (2313, 2330), False, 'import pprint\n')] |
import json
import pathlib
import random
import jsonpickle
class BankAccount:
def __init__(self, ssn, balance=0):
self._ssn = ssn
self._balance = balance
@property
def ssn(self):
return self._ssn
@property
def balance(self):
return self._balance
@staticmethod
def authentication(filename, ssn, account_number):
'''
Read JSON file and checks whether account number is valid
'''
with open(filename, "r") as json_file:
data = json.load(json_file)
stem = pathlib.Path(filename).stem
accounts = data[stem]
# Using ssn and account number check whether account number is valid or not
for account in accounts:
account = jsonpickle.decode(account)
if account.ssn == ssn and account.account_number == account_number:
return True
return False
class CheckingAccount(BankAccount):
def __init__(self, ssn, balance):
super().__init__(ssn, balance)
self._account_type = 'Checking'
self._account_number = random.randint(10000, 99999)
@property
def account_type(self):
return self._account_type
@property
def account_number(self):
return self._account_number
@property
def deposit(self):
return self._deposit
@deposit.setter
def deposit(self, deposit):
if deposit > 0:
self._deposit = deposit
self._deposit += 1
self._balance += self._deposit
else:
raise ValueError
@property
def withdrawal(self):
return self._withdraw
@withdrawal.setter
def withdrawal(self, withdraw):
if withdraw > 0:
self._withdraw = withdraw
self._balance -= self._withdraw
else:
raise ValueError
class SavingsAccount(BankAccount):
def __init__(self, ssn, balance):
super().__init__(ssn, balance)
self._account_type = "Savings"
self._account_number = random.randint(100000, 200000)
@property
def account_type(self):
return self._account_type
@property
def account_number(self):
return self._account_number
@property
def deposit(self):
return self._deposit
@deposit.setter
def deposit(self, deposit):
if deposit > 0:
self._deposit = deposit
self._deposit += 5
self._balance += self._deposit
else:
raise ValueError
@property
def withdrawal(self):
return self._withdraw
@withdrawal.setter
def withdrawal(self, withdraw):
if withdraw > 0:
self._withdraw = withdraw
self._balance -= self._withdraw
else:
raise ValueError | [
"jsonpickle.decode",
"json.load",
"pathlib.Path",
"random.randint"
] | [((1156, 1184), 'random.randint', 'random.randint', (['(10000)', '(99999)'], {}), '(10000, 99999)\n', (1170, 1184), False, 'import random\n'), ((2109, 2139), 'random.randint', 'random.randint', (['(100000)', '(200000)'], {}), '(100000, 200000)\n', (2123, 2139), False, 'import random\n'), ((543, 563), 'json.load', 'json.load', (['json_file'], {}), '(json_file)\n', (552, 563), False, 'import json\n'), ((583, 605), 'pathlib.Path', 'pathlib.Path', (['filename'], {}), '(filename)\n', (595, 605), False, 'import pathlib\n'), ((797, 823), 'jsonpickle.decode', 'jsonpickle.decode', (['account'], {}), '(account)\n', (814, 823), False, 'import jsonpickle\n')] |
#!/usr/bin/env python3
import sys
import argparse
import bz2
import pickle
import numpy
import textwrap
import tabulate
import copy
import math
import operator
import collections
import profileLib
import statistics
from xopen import xopen
def error(baseline, value, totalBaseline, totalValue, weight, fullTotalBaseline, fullTotalValue):
return value - baseline
def weightedError(baseline, value, totalBaseline, totalValue, weight, fullTotalBaseline, fullTotalValue):
return error(baseline, value, totalBaseline, totalValue, weight, fullTotalBaseline, fullTotalValue) * weight
def absoluteWeightedError(baseline, value, totalBaseline, totalValue, weight, fullTotalBaseline, fullTotalValue):
return abs(weightedError(baseline, value, totalBaseline, totalValue, weight, fullTotalBaseline, fullTotalValue))
def absoluteError(baseline, value, totalBaseline, totalValue, weight, fullTotalBaseline, fullTotalValue):
return abs(error(baseline, value, totalBaseline, totalValue, weight, fullTotalBaseline, fullTotalValue))
def relativeError(baseline, value, totalBaseline, totalValue, weight, fullTotalBaseline, fullTotalValue):
return error(baseline, value, totalBaseline, totalValue, weight, fullTotalBaseline, fullTotalValue) / baseline if (baseline != 0) else 0
def absoluteRelativeError(baseline, value, totalBaseline, totalValue, weight, fullTotalBaseline, fullTotalValue):
return abs(relativeError(baseline, value, totalBaseline, totalValue, weight, fullTotalBaseline, fullTotalValue))
def weightedRelativeError(baseline, value, totalBaseline, totalValue, weight, fullTotalBaseline, fullTotalValue):
return relativeError(baseline, value, totalBaseline, totalValue, weight, fullTotalBaseline, fullTotalValue) * weight
def absoluteWeightedRelativeError(baseline, value, totalBaseline, totalValue, weight, fullTotalBaseline, fullTotalValue):
return abs(weightedRelativeError(baseline, value, totalBaseline, totalValue, weight, fullTotalBaseline, fullTotalValue))
# values are already processed by errorFunction
def aggregateSum(baselines, values, totalBaseline, totalValue, weights, fullTotalBaseline, fullTotalValue):
return sum(values)
# values are already processed by errorFunction
def aggregateMin(baselines, values, totalBaseline, totalValue, weights, fullTotalBaseline, fullTotalValue):
return min(values)
# values are already processed by errorFunction
def aggregateMax(baselines, values, totalBaseline, totalValue, weights, fullTotalBaseline, fullTotalValue):
return max(values)
# values are already processed by errorFunction
def aggregateMean(baselines, values, totalBaseline, totalValue, weights, fullTotalBaseline, fullTotalValue):
return sum(values) / len(values)
# values are already processed by errorFunction
def aggregateRelativeBaseline(baselines, values, totalBaseline, totalValue, weights, fullTotalBaseline, fullTotalValue):
return (sum(values) / fullTotalBaseline) if fullTotalBaseline != 0 else 0
# values are already processed by errorFunction
def aggregateRelative(baselines, values, totalBaseline, totalValue, weights, fullTotalBaseline, fullTotalValue):
return (sum(values) / fullTotalValue) if fullTotalValue != 0 else 0
def aggregateWeightedMean(baselines, values, totalBaseline, totalValue, weights, fullTotalBaseline, fullTotalValue):
return sum([value * weight for value, weight in zip(values, weights)])
explodedData = []
for value, weight in zip(values, weights):
explodedData = numpy.append(explodedData, [value] * max(1, int(10000 * abs(weight))))
return statistics.mean(explodedData)
def aggregateRootMeanSquaredError(baselines, values, totalBaseline, totalValue, weights, fullTotalBaseline, fullTotalValue):
return math.sqrt(sum([math.pow(error(baseline, value, totalBaseline, totalValue, weight, fullTotalBaseline, fullTotalValue), 2) for baseline, value, weight in zip(baselines, values, weights)]) / len(values))
def aggregateWeightedRootMeanSquaredError(baselines, values, totalBaseline, totalValue, weights, fullTotalBaseline, fullTotalValue):
return math.sqrt(sum([math.pow(error(baseline, value, totalBaseline, totalValue, weight, fullTotalBaseline, fullTotalValue), 2) * weight for baseline, value, weight in zip(baselines, values, weights)]))
# [ parameter, description, error function, ]
errorFunctions = numpy.array([
['relative_error', 'Relative Error', relativeError],
['error', 'Error', error],
['absolute_error', 'Absolute Error', absoluteError],
['weighted_error', 'Weighted Error', weightedError],
['absolute_weighted_error', 'Absolute Weighted Error', absoluteWeightedError],
['absolute_relative_error', 'Absolute Relative Error', absoluteRelativeError],
['weighted_relative_error', 'Weighted Relative Error', weightedRelativeError],
['absolute_weighted_relative_error', 'Absolute Weighted Relative Error', absoluteWeightedRelativeError],
], dtype=object)
aggregateFunctions = numpy.array([
['sum', 'Total', aggregateSum, True],
['relative', 'Relative', aggregateRelative, True],
['relative_baseline', 'Relative', aggregateRelativeBaseline, True],
['min', 'Minimum', aggregateMin, True],
['max', 'Maximum', aggregateMax, True],
['mean', 'Mean', aggregateMean, True],
['wmean', 'Weighted Mean', aggregateWeightedMean, True],
['rmse', 'Root Mean Squared Error', aggregateRootMeanSquaredError, False],
['wrmse', 'Weighted Root Mean Squared Error', aggregateWeightedRootMeanSquaredError, False]
])
parser = argparse.ArgumentParser(description="Visualize profiles from intrvelf sampler.")
parser.add_argument("profile", help="baseline aggregated profile")
parser.add_argument("profiles", help="aggregated profiles to compare", nargs="+")
parser.add_argument("--use-time", help="compare time values", action="store_true", default=False)
parser.add_argument("--use-energy", help="compare energy values (default)", action="store_true", default=False)
parser.add_argument("--use-power", help="compare power values", action="store_true", default=False)
parser.add_argument("--use-samples", help="compare sample counters", action="store_true", default=False)
parser.add_argument("--use-share", help="compare the share (is combined with other --use options)", action="store_true", default=False)
parser.add_argument("--use-exec-times", help="compare execution time", action="store_true", default=False)
parser.add_argument("-e", "--error", help=f"error function (default: {errorFunctions[0][0]})", default=False, choices=errorFunctions[:, 0], type=str.lower)
parser.add_argument("-a", "--aggregate", help="aggregate erros", default=False, choices=aggregateFunctions[:, 0], type=str.lower)
parser.add_argument("-c", "--compensation", help="switch on latency compensation (experimental)", action="store_true", default=False)
parser.add_argument("--limit-time-top", help="include top n entries ranked after time", type=int, default=0)
parser.add_argument("--limit-time", help="include top entries until limit (in percent, e.g. 0.0 - 1.0)", type=float, default=0)
parser.add_argument("--time-threshold", help="time contribution threshold to include (in percent, e.g. 0.0 - 1.0)", type=float, default=0)
parser.add_argument("--limit-energy-top", help="include top n entries ranked after energy", type=int, default=0)
parser.add_argument("--limit-energy", help="include top entries until limit (in percent, e.g. 0.0 - 1.0)", type=float, default=0)
parser.add_argument("--energy-threshold", help="energy contribution threshold (in percent, e.g. 0.0 - 1.0)", type=float, default=0)
parser.add_argument("--exclude-binary", help="exclude these binaries", default=[], nargs='+', action="extend")
parser.add_argument("--exclude-file", help="exclude these files", default=[], nargs='+', action="extend")
parser.add_argument("--exclude-function", help="exclude these functions", default=[], nargs='+', action="extend")
parser.add_argument("--exclude-external", help="exclude external binaries", default=False, action="store_true")
parser.add_argument('--header', help='override header', default=None)
parser.add_argument('--names', help='names of the provided profiles', default=[], nargs="+", action="extend")
parser.add_argument('-n', '--name', action='append', help='name the provided profiles', default=[])
parser.add_argument("-t", "--table", help="output csv table")
parser.add_argument("--coverage", action="store_true", help="output coverage", default=False)
parser.add_argument("--totals", action="store_true", help="output total", default=False)
parser.add_argument("--weights", action="store_true", help="output importance", default=False)
parser.add_argument("-q", "--quiet", action="store_true", help="be quiet", default=False)
parser.add_argument("--cut-off-symbols", help="number of characters symbol to insert line break (positive) or cut off (negative)", type=int, default=64)
args = parser.parse_args()
if (not args.use_time and not args.use_energy and not args.use_power and not args.use_samples and not args.use_exec_times):
args.use_time = True
header = ""
cmpTime = 0
cmpPower = 1
cmpEnergy = 2
cmpRelSamples = 3
cmpExecs = 4
cmpShare = 5
subCmpOffset = cmpTime
if args.use_time:
header = "Time "
subCmpOffset = cmpTime
if args.use_power:
header = "Power "
subCmpOffset = cmpPower
if args.use_samples:
header = "Relative Samples "
subCmpOffset = cmpRelSamples
if args.use_exec_times:
header = "Execution Times "
subCmpOffset = cmpExecs
if args.use_energy:
header = "Energy "
subCmpOffset = cmpEnergy
cmpOffset = subCmpOffset
if args.use_share:
header += "Share "
cmpOffset = cmpShare
if (args.limit_time != 0 or args.limit_time_top != 0) and (args.limit_energy != 0 or args.limit_energy_top != 0):
print("ERROR: cannot simultanously limit after energy and time!")
parser.print_help()
sys.exit(1)
if args.limit_time_top != 0 and args.limit_time_top < 0:
print("ERROR: time limit top can't be negative")
parser.print_help()
sys.exit(0)
if (args.limit_time != 0 and (args.limit_time < 0 or args.limit_time > 1.0)):
print("ERROR: time limit out of range")
parser.print_help()
sys.exit(0)
if args.limit_energy_top != 0 and args.limit_energy_top < 0:
print("ERROR: energy limit top can't be negative")
parser.print_help()
sys.exit(0)
if (args.limit_energy != 0 and (args.limit_energy < 0 or args.limit_energy > 1.0)):
print("ERROR: energy limit out of range")
parser.print_help()
sys.exit(0)
if (args.time_threshold != 0 and (args.time_threshold < 0 or args.time_threshold > 1.0)):
print("ERROR: time threshold out of range")
parser.print_help()
sys.exit(0)
if (args.energy_threshold != 0 and (args.energy_threshold < 0 or args.energy_threshold > 1.0)):
print("ERROR: energy threshold out of range")
parser.print_help()
sys.exit(0)
if (args.quiet and not args.table):
print("ERROR: don't know what to do")
parser.print_help()
sys.exit(1)
if (not args.profiles) or (len(args.profiles) <= 0):
print("ERROR: unsufficient amount of profiles passed")
parser.print_help()
sys.exit(1)
try:
baselineProfile = pickle.load(xopen(args.profile, mode="rb"))
except Exception:
raise Exception(f'Could not open file {args.profile}')
if 'version' not in baselineProfile or baselineProfile['version'] != profileLib.aggProfileVersion:
raise Exception(f"Incompatible profile version (required: {profileLib.aggProfileVersion})")
errorFunction = False
aggregateFunction = False
if args.aggregate is not False:
chosenAggregateFunction = aggregateFunctions[numpy.where(aggregateFunctions == args.aggregate)[0][0]]
aggregateFunction = chosenAggregateFunction[2]
if args.aggregate is not False and not chosenAggregateFunction[3] and args.error is not False:
print(f"NOTICE: error function does not have an influence on '{chosenAggregateFunction[1]}'")
args.error = False
if args.error is False and args.aggregate is False: # default value
args.error = errorFunctions[0][0]
if args.error is not False:
chosenErrorFunction = errorFunctions[numpy.where(errorFunctions == args.error)[0][0]]
errorFunction = chosenErrorFunction[2]
chart = {'name': '', 'fullTotals': [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], 'totals': [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], 'keys': [], 'labels': [], 'values': [], 'errors': [], 'weights': []}
baselineChart = copy.deepcopy(chart)
baselineChart['name'] = f"{baselineProfile['samples'] / baselineProfile['samplingTime']:.2f} Hz, {baselineProfile['samplingTime']:.2f} s, {baselineProfile['latencyTime'] * 1000000 / baselineProfile['samples']:.2f} us"
if (args.limit_energy > 0 or args.limit_energy_top > 0):
baselineProfile['profile'] = collections.OrderedDict(sorted(baselineProfile['profile'].items(), key=lambda x: operator.itemgetter(profileLib.AGGSAMPLE.energy)(x[1]), reverse=True))
else:
baselineProfile['profile'] = collections.OrderedDict(sorted(baselineProfile['profile'].items(), key=lambda x: operator.itemgetter(profileLib.AGGSAMPLE.time)(x[1]), reverse=True))
filterAnything = args.exclude_external or len(args.exclude_binary) > 0 or len(args.exclude_file) > 0 or len(args.exclude_function) > 0
# Filter out exclude before anything else
if filterAnything:
for key in list(baselineProfile['profile'].keys()):
if (args.exclude_external and baselineProfile['profile'][key][profileLib.AGGSAMPLE.mappedSample][profileLib.SAMPLE.binary] != baselineProfile['target']) or \
(len(args.exclude_binary) > 0 and baselineProfile['profile'][key][profileLib.AGGSAMPLE.mappedSample][profileLib.SAMPLE.binary] in args.exclude_binary) or \
(len(args.exclude_file) > 0 and baselineProfile['profile'][key][profileLib.AGGSAMPLE.mappedSample][profileLib.SAMPLE.file] in args.exclude_file) or \
(len(args.exclude_function) > 0 and baselineProfile['profile'][key][profileLib.AGGSAMPLE.mappedSample][profileLib.SAMPLE.function] in args.exclude_function):
del baselineProfile['profile'][key]
for key in baselineProfile['profile']:
baselineChart['fullTotals'][cmpTime] += baselineProfile['profile'][key][profileLib.AGGSAMPLE.time]
baselineChart['fullTotals'][cmpEnergy] += baselineProfile['profile'][key][profileLib.AGGSAMPLE.energy]
baselineChart['fullTotals'][cmpExecs] += baselineProfile['profile'][key][profileLib.AGGSAMPLE.execs]
baselineChart['fullTotals'][cmpRelSamples] = 1
baselineChart['fullTotals'][cmpPower] = (baselineChart['fullTotals'][cmpEnergy] / baselineChart['fullTotals'][cmpTime])
baselineChart['fullTotals'][cmpShare] = 1
chart = {'name': '', 'fullTotals': [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], 'totals': [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], 'values': [], 'errors': [], 'weights': []}
errorCharts = [copy.deepcopy(chart) for x in args.profiles]
includedBaselineTime = 0.0
includedBaselineEnergy = 0.0
includedKeys = 0
for index, errorChart in enumerate(errorCharts):
# print(f"Compare profile {index+1}/{len(args.profiles)}")
try:
profile = pickle.load(xopen(args.profiles[index], mode="rb"))
except Exception:
raise Exception(f'Could not open file {args.profiles[index]}')
if 'version' not in profile or profile['version'] != profileLib.aggProfileVersion:
raise Exception(f"Incompatible profile version (required: {profileLib.aggProfileVersion})")
if len(args.name) > index:
errorCharts[index]['name'] = args.name[index]
else:
errorCharts[index]['name'] = f"{profile['samples'] / profile['samplingTime']:.2f} Hz, {profile['samplingTime']:.2f} s"
if filterAnything:
for key in list(profile['profile'].keys()):
if (args.exclude_external and profile['profile'][key][profileLib.AGGSAMPLE.mappedSample][profileLib.SAMPLE.binary] != profile['target']) or \
(len(args.exclude_binary) > 0 and profile['profile'][key][profileLib.AGGSAMPLE.mappedSample][profileLib.SAMPLE.binary] in args.exclude_binary) or \
(len(args.exclude_file) > 0 and profile['profile'][key][profileLib.AGGSAMPLE.mappedSample][profileLib.SAMPLE.file] in args.exclude_file) or \
(len(args.exclude_function) > 0 and profile['profile'][key][profileLib.AGGSAMPLE.mappedSample][profileLib.SAMPLE.function] in args.exclude_function):
del profile['profile'][key]
for key in profile['profile']:
errorChart['fullTotals'][cmpTime] += profile['profile'][key][profileLib.AGGSAMPLE.time]
errorChart['fullTotals'][cmpEnergy] += profile['profile'][key][profileLib.AGGSAMPLE.energy]
errorChart['fullTotals'][cmpExecs] += profile['profile'][key][profileLib.AGGSAMPLE.execs]
errorChart['fullTotals'][cmpRelSamples] = 1
errorChart['fullTotals'][cmpShare] = 1
errorChart['fullTotals'][cmpPower] = (errorChart['fullTotals'][cmpEnergy] / errorChart['fullTotals'][cmpTime])
for key in baselineProfile['profile']:
if key in profile['profile']:
# Key never seen before, so add it to the baseline and all charts
if key not in baselineChart['keys']:
# Key was never compared before, check thresholds and limitations whether to include or not
if (((args.limit_time_top != 0) and (includedKeys >= args.limit_time_top)) or
((args.limit_energy_top != 0) and (includedKeys >= args.limit_energy_top)) or
((args.limit_time != 0) and ((includedBaselineTime / baselineChart['fullTotals'][cmpTime]) >= args.limit_time)) or
((args.limit_energy != 0) and ((includedBaselineEnergy / baselineChart['fullTotals'][cmpEnergy]) >= args.limit_energy)) or
((args.time_threshold != 0) and ((baselineProfile['profile'][key][profileLib.AGGSAMPLE.time] / baselineChart['fullTotals'][cmpTime]) < args.time_threshold)) or
((args.energy_threshold != 0) and ((baselineProfile['profile'][key][profileLib.AGGSAMPLE.energy] / baselineChart['fullTotals'][cmpEnergy]) < args.energy_threshold))):
continue
baselineChart['keys'].append(key)
baselineChart['labels'].append(baselineProfile['profile'][key][profileLib.AGGSAMPLE.label])
baselineChart['values'].append([
baselineProfile['profile'][key][profileLib.AGGSAMPLE.time], # time
baselineProfile['profile'][key][profileLib.AGGSAMPLE.power], # power
baselineProfile['profile'][key][profileLib.AGGSAMPLE.energy], # energy
baselineProfile['profile'][key][profileLib.AGGSAMPLE.samples] / baselineProfile['samples'], # relSamples
baselineProfile['profile'][key][profileLib.AGGSAMPLE.time] / baselineProfile['profile'][key][profileLib.AGGSAMPLE.execs], # execTimes
0 # Share (will be filled in later)
])
includedBaselineTime += baselineProfile['profile'][key][profileLib.AGGSAMPLE.time]
includedBaselineEnergy += baselineProfile['profile'][key][profileLib.AGGSAMPLE.energy]
includedKeys += 1
for chart in errorCharts:
chart['values'].append([0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
# Index of the key correlates to the errorChart (same order)
keyIndex = baselineChart['keys'].index(key)
errorChart['values'][keyIndex] = [
profile['profile'][key][profileLib.AGGSAMPLE.time],
profile['profile'][key][profileLib.AGGSAMPLE.power],
profile['profile'][key][profileLib.AGGSAMPLE.energy],
profile['profile'][key][profileLib.AGGSAMPLE.samples] / profile['samples'],
profile['profile'][key][profileLib.AGGSAMPLE.time] / profile['profile'][key][profileLib.AGGSAMPLE.execs],
0
]
# Totals are the totals of only comparable keys
errorChart['totals'][cmpTime] += profile['profile'][key][profileLib.AGGSAMPLE.time]
errorChart['totals'][cmpEnergy] += profile['profile'][key][profileLib.AGGSAMPLE.energy]
errorChart['totals'][cmpExecs] += profile['profile'][key][profileLib.AGGSAMPLE.time] / profile['profile'][key][profileLib.AGGSAMPLE.execs]
# fullTotals are the metrics of all profile keys
# These can be calculated afterwards
errorChart['totals'][cmpPower] = (errorChart['totals'][cmpEnergy] / errorChart['totals'][cmpTime]) if errorChart['totals'][cmpTime] != 0 else 0
errorChart['totals'][cmpRelSamples] = 1
errorChart['totals'][cmpShare] = 1
del profile
if len(baselineChart['keys']) == 0:
raise Exception("Nothing found to compare, limit too strict?")
# calculate baseline total
values = numpy.array(baselineChart['values'])
baselineChart['totals'] = [
numpy.sum(values[:, 0]),
0.0,
numpy.sum(values[:, 2]),
1,
numpy.sum(values[:, 4]),
1
]
baselineChart['totals'][cmpPower] = (baselineChart['totals'][cmpEnergy] / baselineChart['totals'][cmpTime]) if baselineChart['totals'][cmpTime] != 0 else 0
baselineChart['totals'][cmpRelSamples] = 1
baselineChart['totals'][cmpShare] = 1
del values
# fill in the weights, based on baseline energy
for index, _ in enumerate(baselineChart['keys']):
baselineChart['values'][index][cmpShare] = baselineChart['values'][index][subCmpOffset] / baselineChart['totals'][subCmpOffset]
for chart in errorCharts:
chart['values'][index][cmpShare] = chart['values'][index][subCmpOffset] / chart['totals'][subCmpOffset]
if args.limit_energy:
chart['weights'].append(chart['values'][index][cmpEnergy] / baselineChart['fullTotals'][cmpEnergy])
else:
chart['weights'].append(chart['values'][index][cmpTime] / baselineChart['fullTotals'][cmpTime])
# fill in the errors
if errorFunction is not False:
for index, _ in enumerate(baselineChart['keys']):
for chart in errorCharts:
chart['errors'].append(errorFunction(baselineChart['values'][index][cmpOffset], chart['values'][index][cmpOffset], baselineChart['totals'][cmpOffset], chart['totals'][cmpOffset], chart['weights'][index], baselineChart['fullTotals'][cmpOffset], chart['fullTotals'][cmpOffset]))
# names = [ key, name1, name2, name3, name4 ]
# values = [ key, error1, error2, error3, error4 ]a
#
if aggregateFunction:
header += f"{chosenAggregateFunction[1]} "
if errorFunction:
header += f"{chosenErrorFunction[1]}"
header = header.strip()
if args.header is not None:
header = args.header
if errorFunction is not False and aggregateFunction is False:
headers = numpy.array([chart['name'] for chart in errorCharts])
rows = numpy.array(baselineChart['labels']).reshape(-1, 1)
weights = numpy.empty((rows.shape[0], 0))
barLabels = numpy.empty((rows.shape[0], 0))
for chart in errorCharts:
rows = numpy.append(rows, numpy.array(chart['errors']).reshape(-1, 1), axis=1)
weights = numpy.append(weights, numpy.array(chart['weights']).reshape(-1, 1), axis=1)
barLabels = numpy.append(barLabels, numpy.array(chart['weights']).reshape(-1, 1), axis=1) # weights
# barLabels = numpy.append(barLabels, chartValues[:, 4].reshape(-1, 1), axis=1) # execTimes
try:
# Try to sort after numeric values
asort = numpy.array(rows[:, 1], dtype=float).argsort()
except Exception:
asort = rows[:, 1].argsort()
rows = rows[asort]
weights = weights[asort]
barLabels = barLabels[asort]
if aggregateFunction is not False:
baselineValues = numpy.array(baselineChart['values'])
rows = numpy.array([chart['name'] for chart in errorCharts], dtype=object).reshape(-1, 1)
barLabels = numpy.array([''] * len(rows)).reshape(1, -1)
errors = numpy.empty(0)
for chart in errorCharts:
chartValues = numpy.array(chart['values'])
errors = numpy.append(errors, aggregateFunction(
baselineValues[:, cmpOffset],
chart['errors'] if errorFunction is not False else chartValues[:, cmpOffset],
baselineChart['totals'][cmpOffset],
chart['totals'][cmpOffset],
chart['weights'],
baselineChart['fullTotals'][cmpOffset],
chart['fullTotals'][cmpOffset]
))
rows = numpy.append(rows, errors.reshape(-1, 1), axis=1)
headers = numpy.array([header], dtype=object)
if aggregateFunction is False:
if args.totals:
total = ['_total']
for i in range(1, len(rows[0])):
total = numpy.append(total, numpy.sum(numpy.array(rows[:, (i)], dtype=float)))
weights = numpy.concatenate(([[0] * (len(total) - 1)], weights), axis=0)
rows = numpy.concatenate(([total], rows), axis=0)
if args.coverage:
coverage = ['_coverage']
coverage.extend([chart['totals'][cmpOffset] / chart['fullTotals'][cmpOffset] if chart['fullTotals'][cmpOffset] != 0 else 0 for chart in errorCharts])
weights = numpy.concatenate(([[0] * (len(coverage) - 1)], weights), axis=0)
rows = numpy.concatenate(([coverage], rows), axis=0)
if args.weights:
for i in range(0, len(rows[0]) - 1):
headers = numpy.insert(headers, (i * 2), 'Weights')
rows = numpy.insert(rows, (i * 2) + 1, weights[:, i], axis=1)
else:
header = 'Profile' # baselineProfile['name']
rows = rows[::-1]
if (args.table):
if args.table.endswith("bz2"):
table = bz2.BZ2File.open(args.table, "w")
else:
table = open(args.table, "w")
table.write(header + ";" + ';'.join(headers) + "\n")
for i, x in enumerate(rows):
table.write(';'.join([f"{y:.16f}" if not isinstance(y, str) else y for y in x]) + "\n")
table.close()
if not args.quiet:
print(f"CSV saved to {args.table}")
if (not args.quiet):
headers = numpy.append([header], headers)
if (args.cut_off_symbols > 0):
rows[:, 0] = [textwrap.fill(x, args.cut_off_symbols) for x in rows[:, 0]]
elif (args.cut_off_symbols < 0):
rows[:, 0] = [f"{x[0:abs(args.cut_off_symbols)]}..." if len(x) > abs(args.cut_off_symbols) else x for x in rows[:, 0]]
print(tabulate.tabulate(rows, headers=headers, floatfmt=".16f"))
| [
"tabulate.tabulate",
"copy.deepcopy",
"bz2.BZ2File.open",
"numpy.append",
"argparse.ArgumentParser",
"statistics.mean",
"numpy.sum",
"numpy.where",
"textwrap.fill",
"numpy.concatenate",
"numpy.empty",
"numpy.insert",
"numpy.array",
"sys.exit",
"xopen.xopen",
"operator.itemgetter"
] | [((4375, 4969), 'numpy.array', 'numpy.array', (["[['relative_error', 'Relative Error', relativeError], ['error', 'Error',\n error], ['absolute_error', 'Absolute Error', absoluteError], [\n 'weighted_error', 'Weighted Error', weightedError], [\n 'absolute_weighted_error', 'Absolute Weighted Error',\n absoluteWeightedError], ['absolute_relative_error',\n 'Absolute Relative Error', absoluteRelativeError], [\n 'weighted_relative_error', 'Weighted Relative Error',\n weightedRelativeError], ['absolute_weighted_relative_error',\n 'Absolute Weighted Relative Error', absoluteWeightedRelativeError]]"], {'dtype': 'object'}), "([['relative_error', 'Relative Error', relativeError], ['error',\n 'Error', error], ['absolute_error', 'Absolute Error', absoluteError], [\n 'weighted_error', 'Weighted Error', weightedError], [\n 'absolute_weighted_error', 'Absolute Weighted Error',\n absoluteWeightedError], ['absolute_relative_error',\n 'Absolute Relative Error', absoluteRelativeError], [\n 'weighted_relative_error', 'Weighted Relative Error',\n weightedRelativeError], ['absolute_weighted_relative_error',\n 'Absolute Weighted Relative Error', absoluteWeightedRelativeError]],\n dtype=object)\n", (4386, 4969), False, 'import numpy\n'), ((4988, 5535), 'numpy.array', 'numpy.array', (["[['sum', 'Total', aggregateSum, True], ['relative', 'Relative',\n aggregateRelative, True], ['relative_baseline', 'Relative',\n aggregateRelativeBaseline, True], ['min', 'Minimum', aggregateMin, True\n ], ['max', 'Maximum', aggregateMax, True], ['mean', 'Mean',\n aggregateMean, True], ['wmean', 'Weighted Mean', aggregateWeightedMean,\n True], ['rmse', 'Root Mean Squared Error',\n aggregateRootMeanSquaredError, False], ['wrmse',\n 'Weighted Root Mean Squared Error',\n aggregateWeightedRootMeanSquaredError, False]]"], {}), "([['sum', 'Total', aggregateSum, True], ['relative', 'Relative',\n aggregateRelative, True], ['relative_baseline', 'Relative',\n aggregateRelativeBaseline, True], ['min', 'Minimum', aggregateMin, True\n ], ['max', 'Maximum', aggregateMax, True], ['mean', 'Mean',\n aggregateMean, True], ['wmean', 'Weighted Mean', aggregateWeightedMean,\n True], ['rmse', 'Root Mean Squared Error',\n aggregateRootMeanSquaredError, False], ['wrmse',\n 'Weighted Root Mean Squared Error',\n aggregateWeightedRootMeanSquaredError, False]])\n", (4999, 5535), False, 'import numpy\n'), ((5551, 5636), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Visualize profiles from intrvelf sampler."""'}), "(description='Visualize profiles from intrvelf sampler.'\n )\n", (5574, 5636), False, 'import argparse\n'), ((12459, 12479), 'copy.deepcopy', 'copy.deepcopy', (['chart'], {}), '(chart)\n', (12472, 12479), False, 'import copy\n'), ((20834, 20870), 'numpy.array', 'numpy.array', (["baselineChart['values']"], {}), "(baselineChart['values'])\n", (20845, 20870), False, 'import numpy\n'), ((3598, 3627), 'statistics.mean', 'statistics.mean', (['explodedData'], {}), '(explodedData)\n', (3613, 3627), False, 'import statistics\n'), ((9900, 9911), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (9908, 9911), False, 'import sys\n'), ((10052, 10063), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (10060, 10063), False, 'import sys\n'), ((10215, 10226), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (10223, 10226), False, 'import sys\n'), ((10372, 10383), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (10380, 10383), False, 'import sys\n'), ((10543, 10554), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (10551, 10554), False, 'import sys\n'), ((10722, 10733), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (10730, 10733), False, 'import sys\n'), ((10909, 10920), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (10917, 10920), False, 'import sys\n'), ((11028, 11039), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (11036, 11039), False, 'import sys\n'), ((11181, 11192), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (11189, 11192), False, 'import sys\n'), ((14827, 14847), 'copy.deepcopy', 'copy.deepcopy', (['chart'], {}), '(chart)\n', (14840, 14847), False, 'import copy\n'), ((20903, 20926), 'numpy.sum', 'numpy.sum', (['values[:, 0]'], {}), '(values[:, 0])\n', (20912, 20926), False, 'import numpy\n'), ((20941, 20964), 'numpy.sum', 'numpy.sum', (['values[:, 2]'], {}), '(values[:, 2])\n', (20950, 20964), False, 'import numpy\n'), ((20977, 21000), 'numpy.sum', 'numpy.sum', (['values[:, 4]'], {}), '(values[:, 4])\n', (20986, 21000), False, 'import numpy\n'), ((22713, 22766), 'numpy.array', 'numpy.array', (["[chart['name'] for chart in errorCharts]"], {}), "([chart['name'] for chart in errorCharts])\n", (22724, 22766), False, 'import numpy\n'), ((22844, 22875), 'numpy.empty', 'numpy.empty', (['(rows.shape[0], 0)'], {}), '((rows.shape[0], 0))\n', (22855, 22875), False, 'import numpy\n'), ((22892, 22923), 'numpy.empty', 'numpy.empty', (['(rows.shape[0], 0)'], {}), '((rows.shape[0], 0))\n', (22903, 22923), False, 'import numpy\n'), ((23660, 23696), 'numpy.array', 'numpy.array', (["baselineChart['values']"], {}), "(baselineChart['values'])\n", (23671, 23696), False, 'import numpy\n'), ((23865, 23879), 'numpy.empty', 'numpy.empty', (['(0)'], {}), '(0)\n', (23876, 23879), False, 'import numpy\n'), ((24449, 24484), 'numpy.array', 'numpy.array', (['[header]'], {'dtype': 'object'}), '([header], dtype=object)\n', (24460, 24484), False, 'import numpy\n'), ((25934, 25965), 'numpy.append', 'numpy.append', (['[header]', 'headers'], {}), '([header], headers)\n', (25946, 25965), False, 'import numpy\n'), ((11233, 11263), 'xopen.xopen', 'xopen', (['args.profile'], {'mode': '"""rb"""'}), "(args.profile, mode='rb')\n", (11238, 11263), False, 'from xopen import xopen\n'), ((23932, 23960), 'numpy.array', 'numpy.array', (["chart['values']"], {}), "(chart['values'])\n", (23943, 23960), False, 'import numpy\n'), ((24793, 24835), 'numpy.concatenate', 'numpy.concatenate', (['([total], rows)'], {'axis': '(0)'}), '(([total], rows), axis=0)\n', (24810, 24835), False, 'import numpy\n'), ((25148, 25193), 'numpy.concatenate', 'numpy.concatenate', (['([coverage], rows)'], {'axis': '(0)'}), '(([coverage], rows), axis=0)\n', (25165, 25193), False, 'import numpy\n'), ((25545, 25578), 'bz2.BZ2File.open', 'bz2.BZ2File.open', (['args.table', '"""w"""'], {}), "(args.table, 'w')\n", (25561, 25578), False, 'import bz2\n'), ((26257, 26314), 'tabulate.tabulate', 'tabulate.tabulate', (['rows'], {'headers': 'headers', 'floatfmt': '""".16f"""'}), "(rows, headers=headers, floatfmt='.16f')\n", (26274, 26314), False, 'import tabulate\n'), ((15099, 15137), 'xopen.xopen', 'xopen', (['args.profiles[index]'], {'mode': '"""rb"""'}), "(args.profiles[index], mode='rb')\n", (15104, 15137), False, 'from xopen import xopen\n'), ((22778, 22814), 'numpy.array', 'numpy.array', (["baselineChart['labels']"], {}), "(baselineChart['labels'])\n", (22789, 22814), False, 'import numpy\n'), ((23708, 23775), 'numpy.array', 'numpy.array', (["[chart['name'] for chart in errorCharts]"], {'dtype': 'object'}), "([chart['name'] for chart in errorCharts], dtype=object)\n", (23719, 23775), False, 'import numpy\n'), ((25282, 25321), 'numpy.insert', 'numpy.insert', (['headers', '(i * 2)', '"""Weights"""'], {}), "(headers, i * 2, 'Weights')\n", (25294, 25321), False, 'import numpy\n'), ((25343, 25395), 'numpy.insert', 'numpy.insert', (['rows', '(i * 2 + 1)', 'weights[:, i]'], {'axis': '(1)'}), '(rows, i * 2 + 1, weights[:, i], axis=1)\n', (25355, 25395), False, 'import numpy\n'), ((26023, 26061), 'textwrap.fill', 'textwrap.fill', (['x', 'args.cut_off_symbols'], {}), '(x, args.cut_off_symbols)\n', (26036, 26061), False, 'import textwrap\n'), ((11669, 11718), 'numpy.where', 'numpy.where', (['(aggregateFunctions == args.aggregate)'], {}), '(aggregateFunctions == args.aggregate)\n', (11680, 11718), False, 'import numpy\n'), ((12172, 12213), 'numpy.where', 'numpy.where', (['(errorFunctions == args.error)'], {}), '(errorFunctions == args.error)\n', (12183, 12213), False, 'import numpy\n'), ((23412, 23448), 'numpy.array', 'numpy.array', (['rows[:, 1]'], {'dtype': 'float'}), '(rows[:, 1], dtype=float)\n', (23423, 23448), False, 'import numpy\n'), ((22988, 23016), 'numpy.array', 'numpy.array', (["chart['errors']"], {}), "(chart['errors'])\n", (22999, 23016), False, 'import numpy\n'), ((23081, 23110), 'numpy.array', 'numpy.array', (["chart['weights']"], {}), "(chart['weights'])\n", (23092, 23110), False, 'import numpy\n'), ((23179, 23208), 'numpy.array', 'numpy.array', (["chart['weights']"], {}), "(chart['weights'])\n", (23190, 23208), False, 'import numpy\n'), ((24656, 24692), 'numpy.array', 'numpy.array', (['rows[:, i]'], {'dtype': 'float'}), '(rows[:, i], dtype=float)\n', (24667, 24692), False, 'import numpy\n'), ((12870, 12918), 'operator.itemgetter', 'operator.itemgetter', (['profileLib.AGGSAMPLE.energy'], {}), '(profileLib.AGGSAMPLE.energy)\n', (12889, 12918), False, 'import operator\n'), ((13061, 13107), 'operator.itemgetter', 'operator.itemgetter', (['profileLib.AGGSAMPLE.time'], {}), '(profileLib.AGGSAMPLE.time)\n', (13080, 13107), False, 'import operator\n')] |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.auth.models import AbstractBaseUser
from django.db import models
# Create your models here.
class Account(AbstractBaseUser):
email = models.EmailField(unique=True)
username = models.CharField(max_length=40, unique=True)
is_admin = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
def __unicode__(self):
return self.email
| [
"django.db.models.DateTimeField",
"django.db.models.CharField",
"django.db.models.BooleanField",
"django.db.models.EmailField"
] | [((228, 258), 'django.db.models.EmailField', 'models.EmailField', ([], {'unique': '(True)'}), '(unique=True)\n', (245, 258), False, 'from django.db import models\n'), ((274, 318), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(40)', 'unique': '(True)'}), '(max_length=40, unique=True)\n', (290, 318), False, 'from django.db import models\n'), ((334, 368), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (353, 368), False, 'from django.db import models\n'), ((386, 425), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)'}), '(auto_now_add=True)\n', (406, 425), False, 'from django.db import models\n'), ((443, 478), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now': '(True)'}), '(auto_now=True)\n', (463, 478), False, 'from django.db import models\n')] |
# -*- coding: utf-8 -*-
"""
> :warning: This file is only for use by the Simmate team. Users should instead
access data via the load_remote_archive method.
This file is for pulling AFLOW data into the Simmate database.
AFLOW's supported REST API can be accessed via "AFLUX API". This is a separate
python package, which is maintained at https://github.com/rosenbrockc/aflow.
Note that this not from the official AFLOW team, but it is made such that keywords
are pulled dynamically from the AFLOW servers -- any updates in AFLOW's API should
be properly handled. Also structures are loaded as ASE Atom objects, which we then
convert to pymatgen.
"""
from tqdm import tqdm
from pymatgen.io.ase import AseAtomsAdaptor
from simmate.database.third_parties.aflow import AflowStructure
# AFLOW is not a dependency of simmate, so make sure you install it before using
# this module
try:
from aflow import K as AflowKeywords
from aflow.control import Query as AflowQuery
except:
raise ModuleNotFoundError(
"You must install aflow client with `conda install -c conda-forge aflow`"
)
def load_all_structures():
"""
Only use this function if you are part of the Simmate dev team!
Loads all structures directly for the AFLOW database into the local
Simmate database.
"""
# The way we build a query looks similar to the Django API, where we start
# with a Query object (similar to Table.objects manager) and build filters
# off of it.
data = (
AflowQuery(
# This is a list of the supported "catalogs" that AFLOW has -- which appear
# to be separately stored databases. I just use all of them by default.
catalog=[
"icsd", # 60,000 structures
"lib1", # 4,000 structures
"lib2", # 360,000 structures (binary phases)
"lib3", # 2,530,000 structures (ternary phases)
],
# The batch size the number of results to return per HTTP request.
batch_size=2000,
)
# .filter(
# # Now we want set the conditions for which structures to pull. Because we
# # want all of them, we normally comment this line out. For testing, we
# # can pull a smaller subset of the structures.
# # I use the element Dy because it gives about 1,300 structures
# AflowKeywords.species == "Dy",
# )
.select(
# Indicate what data we want to grab from each result. Note that we don't
# access the structure quite yet.
AflowKeywords.auid,
# This is the URL that leads to the rest of the data. Note it is a
# interactive REST endpoint, while the dashboard link is different.
# AflowKeywords.aurl,
# The date that the entry was added
# AflowKeywords.aflowlib_date,
# Band gap
# AflowKeywords.Egap,
# The calculated energy of the unit cell
AflowKeywords.enthalpy_cell,
# BUG: or should we use energy_cell? Aren't these the same in
# groundstate DFT?
)
)
# Let's sanitize all structures first. So iterate through each one in the list
# This also takes a while, so we use a progress bar (via tqdm)
for entry in tqdm(data):
# grab the structure -- this is loaded as an ASE atoms object
structure_ase = entry.atoms()
# convert the structure to pymatgen
structure_pmg = AseAtomsAdaptor.get_structure(structure_ase)
# now convert the entry to a database object
structure_db = AflowStructure.from_toolkit(
id=entry.auid.replace(":", "-"),
structure=structure_pmg,
energy=entry.enthalpy_cell,
)
# and save it to our database!
structure_db.save()
| [
"pymatgen.io.ase.AseAtomsAdaptor.get_structure",
"aflow.control.Query",
"tqdm.tqdm"
] | [((3358, 3368), 'tqdm.tqdm', 'tqdm', (['data'], {}), '(data)\n', (3362, 3368), False, 'from tqdm import tqdm\n'), ((3548, 3592), 'pymatgen.io.ase.AseAtomsAdaptor.get_structure', 'AseAtomsAdaptor.get_structure', (['structure_ase'], {}), '(structure_ase)\n', (3577, 3592), False, 'from pymatgen.io.ase import AseAtomsAdaptor\n'), ((1511, 1580), 'aflow.control.Query', 'AflowQuery', ([], {'catalog': "['icsd', 'lib1', 'lib2', 'lib3']", 'batch_size': '(2000)'}), "(catalog=['icsd', 'lib1', 'lib2', 'lib3'], batch_size=2000)\n", (1521, 1580), True, 'from aflow.control import Query as AflowQuery\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "<NAME>"
__email__ = "<EMAIL>"
import datetime
import numpy as np
import pandas as pd
class DataType(object):
INT = 1
STRING = 2
DECIMAL = 3
TIMESTAMP = 4
DATE = 5
ARRAY = 6
_converted_types = {
DataType.INT: int,
DataType.DECIMAL: float,
DataType.ARRAY: list,
DataType.STRING: np.dtype('O'), #TODO: check string type
DataType.TIMESTAMP: datetime.datetime,
DataType.DATE: datetime.date,
}
| [
"numpy.dtype"
] | [((384, 397), 'numpy.dtype', 'np.dtype', (['"""O"""'], {}), "('O')\n", (392, 397), True, 'import numpy as np\n')] |
#!/usr/bin/env python
import sys
# import all necessary stuff
import osg
import osgDB
import osgGA
import osgViewer
# create a root node
node = osg.Group()
# needed for python
filepath = osgDB.getLibraryFilePathList()
for item in sys.path: filepath.append(item)
osgDB.setLibraryFilePathList(filepath)
loadedmodel = osgDB.readNodeFile("cow.osg")
# open a file
node.addChild(loadedmodel)
# create a viewer
viewer = osgViewer.Viewer()
# configure default threading
viewer.setThreadingModel(osgViewer.Viewer.SingleThreaded)
# add handlers
viewer.addEventHandler(osgViewer.StatsHandler())
viewer.addEventHandler(osgViewer.WindowSizeHandler())
viewer.addEventHandler(osgViewer.ThreadingHandler())
viewer.addEventHandler(osgViewer.HelpHandler())
# add to the scene
viewer.setSceneData(node)
# loop until done
viewer.run()
| [
"osgDB.getLibraryFilePathList",
"osgDB.setLibraryFilePathList",
"osgViewer.ThreadingHandler",
"osgViewer.Viewer",
"osgViewer.StatsHandler",
"osgViewer.HelpHandler",
"osg.Group",
"osgDB.readNodeFile",
"osgViewer.WindowSizeHandler"
] | [((147, 158), 'osg.Group', 'osg.Group', ([], {}), '()\n', (156, 158), False, 'import osg\n'), ((191, 221), 'osgDB.getLibraryFilePathList', 'osgDB.getLibraryFilePathList', ([], {}), '()\n', (219, 221), False, 'import osgDB\n'), ((266, 304), 'osgDB.setLibraryFilePathList', 'osgDB.setLibraryFilePathList', (['filepath'], {}), '(filepath)\n', (294, 304), False, 'import osgDB\n'), ((320, 349), 'osgDB.readNodeFile', 'osgDB.readNodeFile', (['"""cow.osg"""'], {}), "('cow.osg')\n", (338, 349), False, 'import osgDB\n'), ((420, 438), 'osgViewer.Viewer', 'osgViewer.Viewer', ([], {}), '()\n', (436, 438), False, 'import osgViewer\n'), ((567, 591), 'osgViewer.StatsHandler', 'osgViewer.StatsHandler', ([], {}), '()\n', (589, 591), False, 'import osgViewer\n'), ((616, 645), 'osgViewer.WindowSizeHandler', 'osgViewer.WindowSizeHandler', ([], {}), '()\n', (643, 645), False, 'import osgViewer\n'), ((670, 698), 'osgViewer.ThreadingHandler', 'osgViewer.ThreadingHandler', ([], {}), '()\n', (696, 698), False, 'import osgViewer\n'), ((723, 746), 'osgViewer.HelpHandler', 'osgViewer.HelpHandler', ([], {}), '()\n', (744, 746), False, 'import osgViewer\n')] |
import json
import csv
labels = ["E10","E11","E12","E13","E14","E15","E16","E17","E18","E19","E20","E21","E22","E23","E24","E25","E26","E27","E28","E29","E30","E31","E32","E33","E34","E35","E36","E37","E38","E39","E40","E41","E42","E43","E44","E45","E46","E47","E48","E49","E50","E51","E52","E53","E54","E55","E56","E57","E58","E59","E60","E61","E62","E63","E64","E65","E66","E67","E68","E69"]
# train.csv 생성
def create_train():
with open('train_data.json', 'r', encoding="utf-8") as f:
json_data = json.load(f)
f = open('train.csv', 'a', newline='')
title = ['label', 'content']
wr = csv.writer(f)
wr.writerow(title)
for i in json_data:
tmp = i['talk']['content']
label = i['profile']['emotion']['type']
tmp2 = []
tmp2.append(int(labels.index(label)))
string = tmp['HS01'] + ' [SEP] ' + tmp['SS01'] + ' [SEP] ' + tmp['HS02']
tmp2.append(string)
wr = csv.writer(f)
wr.writerow(tmp2)
# dev.csv 생성
def create_dev():
with open('dev_data.json', 'r', encoding="utf-8") as f:
json_data = json.load(f)
f = open('dev.csv', 'a', newline='')
title = ['label', 'content']
wr = csv.writer(f)
wr.writerow(title)
for i in json_data:
tmp = i['talk']['content']
label = i['profile']['emotion']['type']
tmp2 = []
tmp2.append(int(labels.index(label)))
string = tmp['HS01'] + ' [SEP] ' + tmp['SS01'] + ' [SEP] ' + tmp['HS02']
tmp2.append(string)
wr = csv.writer(f)
wr.writerow(tmp2)
# test.csv 생성
def create_test():
# with open('test_data.json', 'r', encoding="utf-8") as f:
with open('final_test.json', 'r', encoding="utf-8") as f:
json_data = json.load(f)
f = open('final_test.csv', 'a', newline='')
title = ['content', 'talkid']
wr = csv.writer(f)
wr.writerow(title)
for i in json_data:
tmp = i['talk']['content']
id = i['talk']['id']['talk-id']
tmp2 = []
string = tmp['HS01'] + ' [SEP] ' + tmp['SS01'] + ' [SEP] ' + tmp['HS02']
tmp2.append(string)
tmp2.append(id)
wr = csv.writer(f)
wr.writerow(tmp2)
if __name__ == "__main__":
# create_train() # train.csv 생성
# create_dev() # dev.csv 생성
create_test() # test.csv 생성
| [
"csv.writer",
"json.load"
] | [((612, 625), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (622, 625), False, 'import csv\n'), ((1193, 1206), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (1203, 1206), False, 'import csv\n'), ((1850, 1863), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (1860, 1863), False, 'import csv\n'), ((513, 525), 'json.load', 'json.load', (['f'], {}), '(f)\n', (522, 525), False, 'import json\n'), ((944, 957), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (954, 957), False, 'import csv\n'), ((1096, 1108), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1105, 1108), False, 'import json\n'), ((1526, 1539), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (1536, 1539), False, 'import csv\n'), ((1745, 1757), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1754, 1757), False, 'import json\n'), ((2153, 2166), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (2163, 2166), False, 'import csv\n')] |
# Generated by Django 3.2.7 on 2021-10-08 08:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('firearm', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='firearm',
name='opType',
field=models.TextField(default=''),
),
migrations.AlterField(
model_name='firearm',
name='SerialNumber',
field=models.CharField(max_length=30),
),
]
| [
"django.db.models.CharField",
"django.db.models.TextField"
] | [((324, 352), 'django.db.models.TextField', 'models.TextField', ([], {'default': '""""""'}), "(default='')\n", (340, 352), False, 'from django.db import migrations, models\n'), ((481, 512), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(30)'}), '(max_length=30)\n', (497, 512), False, 'from django.db import migrations, models\n')] |
"""
This file is part of LiberaForms.
# SPDX-FileCopyrightText: 2021 LiberaForms.org
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
import os, shutil
def ensure_uploads_dir_tree(app):
uploads_dir = app.config['UPLOADS_DIR']
media_dir = os.path.join(uploads_dir, app.config['MEDIA_DIR'])
attachment_dir = os.path.join(uploads_dir, app.config['ATTACHMENT_DIR'])
if not os.path.isdir(media_dir):
os.makedirs(media_dir)
shutil.copytree(os.path.join(app.config['ROOT_DIR'], 'assets', 'brand'),
os.path.join(uploads_dir, app.config['BRAND_DIR']))
if not os.path.isdir(attachment_dir):
os.makedirs(attachment_dir)
#app.logger.info("Uploads dir tree in place")
| [
"os.path.join",
"os.path.isdir",
"os.makedirs"
] | [((250, 300), 'os.path.join', 'os.path.join', (['uploads_dir', "app.config['MEDIA_DIR']"], {}), "(uploads_dir, app.config['MEDIA_DIR'])\n", (262, 300), False, 'import os, shutil\n'), ((322, 377), 'os.path.join', 'os.path.join', (['uploads_dir', "app.config['ATTACHMENT_DIR']"], {}), "(uploads_dir, app.config['ATTACHMENT_DIR'])\n", (334, 377), False, 'import os, shutil\n'), ((389, 413), 'os.path.isdir', 'os.path.isdir', (['media_dir'], {}), '(media_dir)\n', (402, 413), False, 'import os, shutil\n'), ((423, 445), 'os.makedirs', 'os.makedirs', (['media_dir'], {}), '(media_dir)\n', (434, 445), False, 'import os, shutil\n'), ((614, 643), 'os.path.isdir', 'os.path.isdir', (['attachment_dir'], {}), '(attachment_dir)\n', (627, 643), False, 'import os, shutil\n'), ((653, 680), 'os.makedirs', 'os.makedirs', (['attachment_dir'], {}), '(attachment_dir)\n', (664, 680), False, 'import os, shutil\n'), ((470, 525), 'os.path.join', 'os.path.join', (["app.config['ROOT_DIR']", '"""assets"""', '"""brand"""'], {}), "(app.config['ROOT_DIR'], 'assets', 'brand')\n", (482, 525), False, 'import os, shutil\n'), ((551, 601), 'os.path.join', 'os.path.join', (['uploads_dir', "app.config['BRAND_DIR']"], {}), "(uploads_dir, app.config['BRAND_DIR'])\n", (563, 601), False, 'import os, shutil\n')] |
import datetime
import pytz
from sqlalchemy import DateTime
from sqlalchemy.types import TypeDecorator
def tzware_datetime():
"""
Return a timezone aware datetime.
:return: Datetime
"""
return datetime.datetime.now(pytz.utc)
class AwareDateTime(TypeDecorator):
"""
A DateTime type which can only store tz-aware DateTimes.
Source:
https://gist.github.com/inklesspen/90b554c864b99340747e
"""
cache_ok = True
impl = DateTime(timezone=True)
def process_bind_param(self, value, dialect):
if isinstance(value, datetime.datetime) and value.tzinfo is None:
raise ValueError("{!r} must be TZ-aware".format(value))
return value
def __repr__(self):
return "AwareDateTime()"
| [
"datetime.datetime.now",
"sqlalchemy.DateTime"
] | [((217, 248), 'datetime.datetime.now', 'datetime.datetime.now', (['pytz.utc'], {}), '(pytz.utc)\n', (238, 248), False, 'import datetime\n'), ((471, 494), 'sqlalchemy.DateTime', 'DateTime', ([], {'timezone': '(True)'}), '(timezone=True)\n', (479, 494), False, 'from sqlalchemy import DateTime\n')] |
from multiprocessing import Pool
import pandas as pd
import os
from model_based_analysis_tools import *
base_dir = '../../'
in_dirs = {
'data':'new-processed-model-processed-1en01',
'synthetic-data':'new-synthetic-model-processed-1en01',
'score-matched-data':'new-synthetic-score-matched-model-processed-1en01'}
subset = '1en01'
data_dirs = {
'data':'new-processed',
'synthetic-data':'new-synthetic-processed',
'score-matched-data':'new-synthetic-score-matched-processed'}
out_dir = base_dir + 'model-processed-results/'
try:
os.makedirs(out_dir)
except:
pass
def run(model):
in_dir = in_dirs[model]
data_dir = data_dirs[model]
results = {}
for game in os.listdir(base_dir + in_dir):
if game[-4:] != '.out':
continue
if game.split('_')[-2].split('-')[1] != subset:
continue
with open(base_dir + in_dir + '/' + game) as f:
data = pickle.load(f)
results[game] = get_all_divergences(data)
with open(out_dir + model + '.out', 'w') as h:
pickle.dump(results, h)
p = Pool(len(in_dirs))
p.map(run, in_dirs)
| [
"os.listdir",
"os.makedirs"
] | [((559, 579), 'os.makedirs', 'os.makedirs', (['out_dir'], {}), '(out_dir)\n', (570, 579), False, 'import os\n'), ((718, 747), 'os.listdir', 'os.listdir', (['(base_dir + in_dir)'], {}), '(base_dir + in_dir)\n', (728, 747), False, 'import os\n')] |
import sys
import numpy as np
import scipy as sp
import pandas as pd
import networkx as nx
import gensim.parsing.preprocessing as gpp
import sklearn.metrics.pairwise as smp
from .persistent_homology import PersistentHomology
__all__ = ['Model']
class Model(PersistentHomology):
"""
Attributes
----------
graph: networkx.DiGraph
graph_parent: networkx.DiGraph
vectors: scipy.sparse.csc_matrix
vectors_parent: scipy.sparse.csc_matrix
seeds: {node string: [scipy.sparse.csc_matrix]}
thresholds: {node string: [float]}
year: int
record: pandas.DataFrame
record of evolution
year_start: int
n_seeds: int
number of seeds per node
point, insert, delete: tuple
See ``mutate()``.
rvs: lambda n->float
random values for point mutations & insertions
dct: gensim.corpora.dictionary
create: lambda n-> float
thresholds of cosine similarity with parent
for node creation
crossover: float
threshold of cosine similarity with parent
for crossing over nodes
"""
def __init__(self, graph_parent, vectors_parent, year_start, start_nodes,
n_seeds, dct, point, insert, delete, rvs,
create, crossover=None):
"""
Parameters
----------
start_nodes: lambda wiki.Model -> list(networkx.Nodes)
"""
PersistentHomology.__init__(self)
self.graph_parent = graph_parent
self.vectors_parent = vectors_parent
self.year_start = year_start
self.year = year_start
self.seeds = {}
self.thresholds = {}
self.record = pd.DataFrame()
nodes = list(graph_parent.nodes)
self.start_nodes = start_nodes(self)
self.graph = graph_parent.subgraph(self.start_nodes).copy()
self.vectors = sp.sparse.hstack([
vectors_parent[:,nodes.index(n)]
for n in self.start_nodes
])
self.n_seeds = n_seeds
self.dct = dct
self.point = point
self.insert = insert
self.delete = delete
self.rvs = rvs
self.create = create
self.crossover = crossover
def __str__(self):
return f"Model\tparent: '{self.graph_parent.name}'\n" +\
f"\tyear_start: {self.year_start}\n" +\
f"\tstart_nodes: {self.start_nodes}\n" +\
f"\tn_seeds: {self.n_seeds}\n" +\
f"\tpoint: ({self.point[0]:.4f}, {self.point[1]:.4f})\n" +\
f"\tinsert: ({self.insert[0]}, {self.insert[1]:.4f}, {type(self.insert[2])})\n" +\
f"\tdelete: ({self.delete[0]}, {self.delete[1]:.4f})"
def __repr__(self):
return self.__str__()
def evolve(self, until, record=False):
""" Evolves a graph based on vector representations
until `until (lambda wiki.Model) == True`
"""
year_start = self.year
while not until(self):
sys.stdout.write(f"\r{year_start} > {self.year} "+\
f"n={self.graph.number_of_nodes()} ")
sys.stdout.flush()
self.initialize_seeds()
self.mutate_seeds()
self.create_nodes()
if record:
self.record = pd.concat(
[self.record] + \
[
pd.DataFrame(
{
'Year': self.year,
'Parent': seed,
'Seed number': i,
'Seed vectors': seed_vec
},
index=[0]
)
for seed, seed_vecs in self.seeds.items()
for i, seed_vec in enumerate(seed_vecs)
],
ignore_index=True, sort=False
)
self.year += 1
print('')
def initialize_seeds(self):
nodes = list(self.graph.nodes)
for i, node in enumerate(nodes):
if node not in self.seeds.keys():
self.seeds[node] = []
if node not in self.thresholds.keys():
self.thresholds[node] = []
while len(self.seeds[node]) < self.n_seeds:
self.seeds[node] += [self.vectors[:,i].copy()]
while len(self.thresholds[node]) < self.n_seeds:
self.thresholds[node] += [self.create(1)[0]]
def mutate_seeds(self):
for node, vecs in self.seeds.items():
self.seeds[node] = [
Model.mutate(
vec, self.rvs, self.point, self.insert, self.delete
)
for vec in vecs
]
def crossover_seeds(self):
nodes = list(self.graph.nodes)
for i in range(len(nodes)):
seeds_i = sp.sparse.hstack(self.seeds[nodes[i]])
for j in range(i+1,len(nodes)):
seeds_j = sp.sparse.hstack(self.seeds[nodes[j]])
similarity = smp.cosine_similarity(
seeds_i.transpose(), seeds_j.transpose()
)
for k,l in np.argwhere(similarity>self.threshold):
cross = Model.crossover(seeds_i[:,k], seeds_j[:,l])
choice = np.random.choice(2)
self.seeds[nodes[i]][k] = cross if choice else self.vectors[:,i]
self.seeds[nodes[j]][l] = cross if not choice else self.vectors[:,j]
def create_nodes(self):
nodes = list(self.graph.nodes)
for i, node in enumerate(nodes):
parent = self.vectors[:,i]
seeds = sp.sparse.hstack(self.seeds[node])
sim_to_parent = smp.cosine_similarity(parent.transpose(), seeds.transpose())
for j, seed_vec in enumerate(self.seeds[node]):
if sim_to_parent[0,j] < self.thresholds[node][j]:
Model.connect(seed_vec, self.graph, self.vectors, self.dct)
self.vectors = sp.sparse.hstack([self.vectors, seed_vec])
self.seeds[node].pop(j)
self.thresholds[node].pop(j)
for node in self.graph.nodes:
if 'year' not in self.graph.nodes[node].keys():
self.graph.nodes[node]['year'] = self.year
@staticmethod
def mutate(x, rvs, point=(0,0), insert=(0,0,None), delete=(0,0)):
""" Mutates vector ``x`` with point mutations,
insertions, and deletions. Insertions and point
mutations draw from a random process ``rvs``.
Parameters
----------
x: spipy.sparse.csc_matrix
rvs: lambda (n)-> float
returns ``n`` random weights in [0,1]
point: tuple (int n, float p)
n = number of elements to insert
p = probability of insertion for each trial
insert: tuple (n, p, iterable s)
s = set of elements from which to select
if None, select from all zero elements
delete: tuple (n, p)
max_weight: float
"""
data = x.data
idx = x.indices
if idx.size==0:
return x
n_point = np.random.binomial(point[0], point[1])
i_point = np.random.choice(x.size, size=n_point, replace=False)
data[i_point] = rvs(n_point)
# insertion
n_insert = np.random.binomial(insert[0], insert[1])
for _ in range(n_insert):
while True:
insert_idx = np.random.choice(insert[2]) if insert[2]\
else np.random.choice(x.shape[0])
if insert_idx not in idx: break
idx = np.append(idx, insert_idx)
data = np.append(data, rvs(1))
# deletion
n_delete = np.random.binomial(delete[0], delete[1])
i_delete = np.random.choice(idx.size, size=n_delete, replace=False)
idx = np.delete(idx, i_delete)
data = np.delete(data, i_delete)
y = sp.sparse.csc_matrix(
(data, (idx, np.zeros(idx.shape, dtype=int))),
shape=x.shape
)
return y
@staticmethod
def connect(seed_vector, graph, vectors, dct, top_words=10, match_n=6):
"""
Parameters
----------
seed_vector: scipy.sparse.csc_matrix
graph: networkx.DiGraph (not optional)
vectors: scipy.sparse.csc_matrix (not optional)
dct: gensim.corpora.dictionary (not optional)
top_words: int (default=5)
match_n: int
how many words should be matched by...
"""
seed_top_words, seed_top_idx = Model.find_top_words(seed_vector, dct)
seed_name = ' '.join(seed_top_words)
nodes = list(graph.nodes)
graph.add_node(seed_name)
for i, node in enumerate(nodes):
node_vector = vectors[:,i]
node_top_words, node_top_idx = Model.find_top_words(node_vector, dct)
if len(set(seed_top_idx).intersection(set(node_vector.indices))) >= match_n or\
len(set(node_top_idx).intersection(set(seed_vector.indices))) >= match_n:
graph.add_edge(node, seed_name)
@staticmethod
def find_top_words(x, dct, top_n=10):
"""
Parameters
----------
x: scipy.sparse.csc_matrix
dct: gensim.corpora.dictionary
top_n: int
Returns
-------
words:
idx_vector:
"""
top_idx = np.argsort(x.data)[-top_n:]
idx = [x.indices[i] for i in top_idx]
words = [dct[i] for i in idx]
words_nostop = gpp.remove_stopwords(' '.join(words)).split(' ')
idx_keep = list(map(lambda x: words.index(x), set(words).intersection(words_nostop)))
idx_nostop = list(map(idx.__getitem__, idx_keep))
return words_nostop, idx_nostop
@staticmethod
def crossover(v1, v2):
""" Crosses two vectors by combining half of one
and half of the other.
Parameters
----------
v1, v2: scipy.sparse.matrix
Returns
-------
v3: scipy.sparse.matrix
"""
idx1 = np.random.choice(v1.size, size=int(v1.size/2))
idx2 = np.random.choice(v2.size, size=int(v2.size/2))
data = np.array(
[v1.data[i] for i in idx1] + [v2.data[i] for i in idx2]
)
idx = np.array(
[v1.indices[i] for i in idx1] + [v2.indices[i] for i in idx2]
)
v3 = sp.sparse.csc_matrix(
(data, (idx, np.zeros(idx.shape, dtype=int))), shape=v1.shape
)
return v3
| [
"numpy.random.choice",
"numpy.append",
"numpy.argwhere",
"sys.stdout.flush",
"numpy.delete",
"numpy.random.binomial",
"numpy.zeros",
"numpy.array",
"pandas.DataFrame",
"numpy.argsort",
"scipy.sparse.hstack"
] | [((1666, 1680), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (1678, 1680), True, 'import pandas as pd\n'), ((7272, 7310), 'numpy.random.binomial', 'np.random.binomial', (['point[0]', 'point[1]'], {}), '(point[0], point[1])\n', (7290, 7310), True, 'import numpy as np\n'), ((7329, 7382), 'numpy.random.choice', 'np.random.choice', (['x.size'], {'size': 'n_point', 'replace': '(False)'}), '(x.size, size=n_point, replace=False)\n', (7345, 7382), True, 'import numpy as np\n'), ((7459, 7499), 'numpy.random.binomial', 'np.random.binomial', (['insert[0]', 'insert[1]'], {}), '(insert[0], insert[1])\n', (7477, 7499), True, 'import numpy as np\n'), ((7857, 7897), 'numpy.random.binomial', 'np.random.binomial', (['delete[0]', 'delete[1]'], {}), '(delete[0], delete[1])\n', (7875, 7897), True, 'import numpy as np\n'), ((7917, 7973), 'numpy.random.choice', 'np.random.choice', (['idx.size'], {'size': 'n_delete', 'replace': '(False)'}), '(idx.size, size=n_delete, replace=False)\n', (7933, 7973), True, 'import numpy as np\n'), ((7988, 8012), 'numpy.delete', 'np.delete', (['idx', 'i_delete'], {}), '(idx, i_delete)\n', (7997, 8012), True, 'import numpy as np\n'), ((8028, 8053), 'numpy.delete', 'np.delete', (['data', 'i_delete'], {}), '(data, i_delete)\n', (8037, 8053), True, 'import numpy as np\n'), ((10353, 10418), 'numpy.array', 'np.array', (['([v1.data[i] for i in idx1] + [v2.data[i] for i in idx2])'], {}), '([v1.data[i] for i in idx1] + [v2.data[i] for i in idx2])\n', (10361, 10418), True, 'import numpy as np\n'), ((10455, 10526), 'numpy.array', 'np.array', (['([v1.indices[i] for i in idx1] + [v2.indices[i] for i in idx2])'], {}), '([v1.indices[i] for i in idx1] + [v2.indices[i] for i in idx2])\n', (10463, 10526), True, 'import numpy as np\n'), ((3118, 3136), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (3134, 3136), False, 'import sys\n'), ((4931, 4969), 'scipy.sparse.hstack', 'sp.sparse.hstack', (['self.seeds[nodes[i]]'], {}), '(self.seeds[nodes[i]])\n', (4947, 4969), True, 'import scipy as sp\n'), ((5740, 5774), 'scipy.sparse.hstack', 'sp.sparse.hstack', (['self.seeds[node]'], {}), '(self.seeds[node])\n', (5756, 5774), True, 'import scipy as sp\n'), ((7749, 7775), 'numpy.append', 'np.append', (['idx', 'insert_idx'], {}), '(idx, insert_idx)\n', (7758, 7775), True, 'import numpy as np\n'), ((9552, 9570), 'numpy.argsort', 'np.argsort', (['x.data'], {}), '(x.data)\n', (9562, 9570), True, 'import numpy as np\n'), ((5040, 5078), 'scipy.sparse.hstack', 'sp.sparse.hstack', (['self.seeds[nodes[j]]'], {}), '(self.seeds[nodes[j]])\n', (5056, 5078), True, 'import scipy as sp\n'), ((5237, 5277), 'numpy.argwhere', 'np.argwhere', (['(similarity > self.threshold)'], {}), '(similarity > self.threshold)\n', (5248, 5277), True, 'import numpy as np\n'), ((5378, 5397), 'numpy.random.choice', 'np.random.choice', (['(2)'], {}), '(2)\n', (5394, 5397), True, 'import numpy as np\n'), ((6105, 6147), 'scipy.sparse.hstack', 'sp.sparse.hstack', (['[self.vectors, seed_vec]'], {}), '([self.vectors, seed_vec])\n', (6121, 6147), True, 'import scipy as sp\n'), ((7587, 7614), 'numpy.random.choice', 'np.random.choice', (['insert[2]'], {}), '(insert[2])\n', (7603, 7614), True, 'import numpy as np\n'), ((7654, 7682), 'numpy.random.choice', 'np.random.choice', (['x.shape[0]'], {}), '(x.shape[0])\n', (7670, 7682), True, 'import numpy as np\n'), ((8113, 8143), 'numpy.zeros', 'np.zeros', (['idx.shape'], {'dtype': 'int'}), '(idx.shape, dtype=int)\n', (8121, 8143), True, 'import numpy as np\n'), ((10609, 10639), 'numpy.zeros', 'np.zeros', (['idx.shape'], {'dtype': 'int'}), '(idx.shape, dtype=int)\n', (10617, 10639), True, 'import numpy as np\n'), ((3385, 3493), 'pandas.DataFrame', 'pd.DataFrame', (["{'Year': self.year, 'Parent': seed, 'Seed number': i, 'Seed vectors': seed_vec}"], {'index': '[0]'}), "({'Year': self.year, 'Parent': seed, 'Seed number': i,\n 'Seed vectors': seed_vec}, index=[0])\n", (3397, 3493), True, 'import pandas as pd\n')] |
import numpy as np
from scipy.special import expit
class NeuralNet:
def __init__(self, input_qty, hidden_dts, output_qty):
"""
input_qty : Quantidade de entradas que a rede vai receber.
hidden_dts : Uma tuple contedo os detalhes das camadas escondidas.
Primeiro valor quantidade de camadas escondidas.
Segundo valor quantidade de 'neurônios' em cada camada.
saida : Quantidade de saidas da rede.
"""
self.input_qty = input_qty
self.hidden_dts = hidden_dts
self.output_qty = output_qty
def fitting(self, inputs, weights):
inputs = np.asarray(inputs)
bias = -1
ini = 0
# INPUT LAYER
end = self.input_qty * self.hidden_dts[1]
newshape = (self.input_qty, self.hidden_dts[1])
new_input = self.neuron(weights[ini:end], inputs, newshape, bias)
ini = end
# HIDDENS LAYER
for _ in range(self.hidden_dts[0] - 1):
end = self.hidden_dts[1] ** self.hidden_dts[0] + ini
newshape = (self.hidden_dts[1], self.hidden_dts[1])
new_input = self.neuron(weights[ini:end], new_input, newshape, bias)
ini = end
# OUTPUT LAYER
end = self.hidden_dts[1] * self.output_qty + ini
newshape = (self.hidden_dts[1], self.output_qty)
output = self.neuron(weights[ini:end], new_input, newshape, bias, out=True)
return output
def neuron(self, weights, matrix_a, newshape, bias, out=False):
matrix_weights = np.reshape(weights, newshape)
output = np.dot(matrix_a, matrix_weights) + bias
if out:
output = expit(output)
else:
output = np.maximum(output, 0)
return output
def generate_weights(self):
input_qty = self.input_qty * self.hidden_dts[1]
hidden_qty = self.hidden_dts[1] ** self.hidden_dts[0]
output_qty = self.hidden_dts[1] * self.output_qty
total = input_qty + hidden_qty + output_qty
weights = np.random.uniform(-1, 1, total)
return weights
| [
"numpy.reshape",
"numpy.asarray",
"numpy.random.uniform",
"numpy.maximum",
"scipy.special.expit",
"numpy.dot"
] | [((661, 679), 'numpy.asarray', 'np.asarray', (['inputs'], {}), '(inputs)\n', (671, 679), True, 'import numpy as np\n'), ((1579, 1608), 'numpy.reshape', 'np.reshape', (['weights', 'newshape'], {}), '(weights, newshape)\n', (1589, 1608), True, 'import numpy as np\n'), ((2075, 2106), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1)', 'total'], {}), '(-1, 1, total)\n', (2092, 2106), True, 'import numpy as np\n'), ((1626, 1658), 'numpy.dot', 'np.dot', (['matrix_a', 'matrix_weights'], {}), '(matrix_a, matrix_weights)\n', (1632, 1658), True, 'import numpy as np\n'), ((1703, 1716), 'scipy.special.expit', 'expit', (['output'], {}), '(output)\n', (1708, 1716), False, 'from scipy.special import expit\n'), ((1752, 1773), 'numpy.maximum', 'np.maximum', (['output', '(0)'], {}), '(output, 0)\n', (1762, 1773), True, 'import numpy as np\n')] |
import gzip
from collections import OrderedDict
from typing import Dict, Tuple
import numpy as np
import tensorflow as tf
from tensorflow.python.lib.io import file_io
def random_normal_initializer(_, dim):
return np.random.normal(0, 0.01, dim)
def zero_initializer(_, dim):
return np.zeros(dim)
def read_vectors(path, max_vecs=1000000) -> Tuple[Dict[str, np.array], int]:
"""
Read word vectors from a specified path as float32 numpy arrays.
:param path: path to .gz file or text file
:param max_vecs: limit of vectors to read into memory
:return: tuple of the vector dictionary and the vector dimensionality
"""
vectors = OrderedDict()
dim = 0
with gzip.open(path, 'rt') if path.endswith('gz') else file_io.FileIO(path, 'r') as lines:
for line in lines:
if len(vectors) >= max_vecs:
break
fields = line.strip().split()
if len(fields) < 2:
continue
if dim == 0:
dim = len(fields) - 1
elif dim != len(fields) - 1:
tf.logging.warn('Skipping vector with unexpected number of dimensions in line %d: %s', len(vectors), line)
continue
vec = np.array([float(x) for x in fields[1:]], dtype=np.float32)
vectors[fields[0]] = vec
return vectors, dim
def write_vectors(vectors, path):
with file_io.FileIO(path, 'w') as lines:
for word, vector in vectors.items():
lines.write(word + ' ' + ' '.join([str(ele) for ele in vector]))
lines.write('\n')
def initialize_embedding_from_dict(vector_map, dim, vocabulary, zero_init=False, standardize=False):
"""
Initialize a numpy matrix from pre-exi\sting vectors with indices corresponding to a given vocabulary. Words in vocabulary
not in vectors are initialized using a given function.
:param vector_map: dictionary from words to numpy arrays
:param dim: dimensionality of vectors
:param vocabulary: dictionary from words to corresponding indices
:param zero_init: initialization function taking the word and dimensionality for words not in vector_map
:param standardize: set word embedding values to have standard deviation of 1
:return: numpy matrix with rows corresponding to vectors
"""
initializer = random_normal_initializer
if zero_init:
initializer = zero_initializer
emb = np.zeros([len(vocabulary), dim], dtype=np.float32)
for word, index in vocabulary.items():
if word not in vector_map:
vector_map[word] = initializer(word, dim)
emb[index] = vector_map[word]
if standardize:
emb = emb / np.std(emb)
return emb
| [
"tensorflow.python.lib.io.file_io.FileIO",
"numpy.std",
"numpy.random.normal",
"collections.OrderedDict",
"numpy.zeros",
"gzip.open"
] | [((220, 250), 'numpy.random.normal', 'np.random.normal', (['(0)', '(0.01)', 'dim'], {}), '(0, 0.01, dim)\n', (236, 250), True, 'import numpy as np\n'), ((294, 307), 'numpy.zeros', 'np.zeros', (['dim'], {}), '(dim)\n', (302, 307), True, 'import numpy as np\n'), ((665, 678), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (676, 678), False, 'from collections import OrderedDict\n'), ((1411, 1436), 'tensorflow.python.lib.io.file_io.FileIO', 'file_io.FileIO', (['path', '"""w"""'], {}), "(path, 'w')\n", (1425, 1436), False, 'from tensorflow.python.lib.io import file_io\n'), ((700, 721), 'gzip.open', 'gzip.open', (['path', '"""rt"""'], {}), "(path, 'rt')\n", (709, 721), False, 'import gzip\n'), ((750, 775), 'tensorflow.python.lib.io.file_io.FileIO', 'file_io.FileIO', (['path', '"""r"""'], {}), "(path, 'r')\n", (764, 775), False, 'from tensorflow.python.lib.io import file_io\n'), ((2701, 2712), 'numpy.std', 'np.std', (['emb'], {}), '(emb)\n', (2707, 2712), True, 'import numpy as np\n')] |
# MIT License
#
# Copyright (c) 2021 <NAME> and <NAME> and <NAME>
#
# 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.
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
from typing import Tuple
from openspeech.modules.wrapper import Linear
class LocationAwareAttention(nn.Module):
r"""
Applies a location-aware attention mechanism on the output features from the decoders.
Location-aware attention proposed in "Attention-Based Models for Speech Recognition" paper.
The location-aware attention mechanism is performing well in speech recognition tasks.
We refer to implementation of ClovaCall Attention style.
Args:
dim (int): dimension of model
attn_dim (int): dimension of attention
smoothing (bool): flag indication whether to use smoothing or not.
Inputs: query, value, last_attn
- **query** (batch, q_len, hidden_dim): tensor containing the output features from the decoders.
- **value** (batch, v_len, hidden_dim): tensor containing features of the encoded input sequence.
- **last_attn** (batch_size, v_len): tensor containing previous timestep`s attention (alignment)
Returns: output, attn
- **output** (batch, output_len, dimensions): tensor containing the feature from encoders outputs
- **attn** (batch * num_heads, v_len): tensor containing the attention (alignment) from the encoders outputs.
Reference:
<NAME> et al.: Attention-Based Models for Speech Recognition.
https://arxiv.org/abs/1506.07503
"""
def __init__(self, dim: int = 1024, attn_dim: int = 1024, smoothing: bool = False) -> None:
super(LocationAwareAttention, self).__init__()
self.location_conv = nn.Conv1d(in_channels=1, out_channels=attn_dim, kernel_size=3, padding=1)
self.query_proj = Linear(dim, attn_dim, bias=False)
self.value_proj = Linear(dim, attn_dim, bias=False)
self.bias = nn.Parameter(torch.rand(attn_dim).uniform_(-0.1, 0.1))
self.fc = Linear(attn_dim, 1, bias=True)
self.smoothing = smoothing
def forward(self, query: Tensor, value: Tensor, last_alignment_energy: Tensor) -> Tuple[Tensor, Tensor]:
batch_size, hidden_dim, seq_length = query.size(0), query.size(2), value.size(1)
if last_alignment_energy is None:
last_alignment_energy = value.new_zeros(batch_size, seq_length)
last_alignment_energy = self.location_conv(last_alignment_energy.unsqueeze(dim=1))
last_alignment_energy = last_alignment_energy.transpose(1, 2)
alignmment_energy = self.fc(torch.tanh(
self.query_proj(query)
+ self.value_proj(value)
+ last_alignment_energy
+ self.bias
)).squeeze(dim=-1)
if self.smoothing:
alignmment_energy = torch.sigmoid(alignmment_energy)
alignmment_energy = torch.div(alignmment_energy, alignmment_energy.sum(dim=-1).unsqueeze(dim=-1))
else:
alignmment_energy = F.softmax(alignmment_energy, dim=-1)
context = torch.bmm(alignmment_energy.unsqueeze(dim=1), value)
return context, alignmment_energy
| [
"torch.rand",
"torch.nn.functional.softmax",
"openspeech.modules.wrapper.Linear",
"torch.nn.Conv1d",
"torch.sigmoid"
] | [((2769, 2842), 'torch.nn.Conv1d', 'nn.Conv1d', ([], {'in_channels': '(1)', 'out_channels': 'attn_dim', 'kernel_size': '(3)', 'padding': '(1)'}), '(in_channels=1, out_channels=attn_dim, kernel_size=3, padding=1)\n', (2778, 2842), True, 'import torch.nn as nn\n'), ((2869, 2902), 'openspeech.modules.wrapper.Linear', 'Linear', (['dim', 'attn_dim'], {'bias': '(False)'}), '(dim, attn_dim, bias=False)\n', (2875, 2902), False, 'from openspeech.modules.wrapper import Linear\n'), ((2929, 2962), 'openspeech.modules.wrapper.Linear', 'Linear', (['dim', 'attn_dim'], {'bias': '(False)'}), '(dim, attn_dim, bias=False)\n', (2935, 2962), False, 'from openspeech.modules.wrapper import Linear\n'), ((3056, 3086), 'openspeech.modules.wrapper.Linear', 'Linear', (['attn_dim', '(1)'], {'bias': '(True)'}), '(attn_dim, 1, bias=True)\n', (3062, 3086), False, 'from openspeech.modules.wrapper import Linear\n'), ((3886, 3918), 'torch.sigmoid', 'torch.sigmoid', (['alignmment_energy'], {}), '(alignmment_energy)\n', (3899, 3918), False, 'import torch\n'), ((4076, 4112), 'torch.nn.functional.softmax', 'F.softmax', (['alignmment_energy'], {'dim': '(-1)'}), '(alignmment_energy, dim=-1)\n', (4085, 4112), True, 'import torch.nn.functional as F\n'), ((2996, 3016), 'torch.rand', 'torch.rand', (['attn_dim'], {}), '(attn_dim)\n', (3006, 3016), False, 'import torch\n')] |
TOKEN = ""
# YOUR BOT TOKEN
guildid = []
# YOUR GUILD ID
import discord
from discord.ext import commands
# pip install -U git+https://github.com/Rapptz/discord.py.git (recommended)
from discord_slash import SlashContext, SlashCommand
from discord_slash.model import SlashCommandOptionType
from discord_slash.utils.manage_commands import create_option, create_choice
# pip install discord_py_slash_command
channels = {} # ticket channels list
bot = commands.Bot(command_prefix="!")
slash = SlashCommand(bot, sync_commands=True)
@bot.event
async def on_ready():
print("구동 완료")
@bot.event
async def on_command_error(ctx, error):
pass
@slash.slash(
name="문의채널",
description="문의채널을 생성합니다.",
options=[
create_option(
name="method",
description="사용할 동작 (생성, 삭제)",
option_type=SlashCommandOptionType.STRING,
required=True,
choices=[
create_choice(name="create", value="create"),
create_choice(name="delete", value="delete")
]
)
],
guild_ids=guildid
)
async def ticket(ctx: SlashContext, method):
global channels
if (method == "create"):
if str(ctx.author.id) in channels:
await ctx.send("문의채널을 삭제하신 후 다시 시도해 주세요.")
return
if (not ctx.guild):
await ctx.send("DM 채널에서는 사용할 수 없습니다.")
return
overwrites = {
ctx.guild.default_role: discord.PermissionOverwrite(read_messages=False),
ctx.author: discord.PermissionOverwrite(read_messages=True, send_messages=True, manage_messages=True)
}
ticket_channel = await ctx.author.guild.create_text_channel(f"{ctx.author}님의 문의채널", overwrites=overwrites)
channels.setdefault(str(ctx.author.id), ticket_channel) # global channels
await ticket_channel.send(f'{ctx.author.mention}, 문의채널이 성공적으로 만들어졌습니다. 문의 후 문의채널을 삭제하세요.')
await ctx.send("문의채널이 정상적으로 만들어졌습니다.")
return
else:
if str(ctx.author.id) not in channels: # global channels
await ctx.send("이용 중인 문의채널이 없습니다.")
return
if (not ctx.guild):
await ctx.send("DM 채널에서는 사용할 수 없습니다.")
return
ticket_channel = channels.get(str(ctx.author.id)) # global channels
channels = {k: v for k, v in channels.items() if k != str(ctx.author.id)} # delete user
await ticket_channel.delete()
dm = await ctx.author.create_dm()
await dm.send("문의채널 삭제가 완료되었습니다.")
@slash.slash(
name="강제삭제",
description="문의채널을 강제 삭제합니다.",
options=[
create_option(
name="target",
description="강제 삭제할 유저",
option_type=SlashCommandOptionType.USER,
required=True
)
],
guild_ids=guildid
)
async def 강제삭제(ctx: SlashContext, target):
global channels
if (not ctx.author.guild_permissions.administrator):
await ctx.send("관리자 권한이 필요합니다.")
return
if (not ctx.guild):
dm = await ctx.author.create_dm()
await dm.send("DM 채널에서는 사용할 수 없습니다.")
return
if str(target.id) not in channels: # global channels
await ctx.send(f"{target}님이 이용 중인 문의채널이 없습니다.")
return
ticket_channel = channels.get(str(target.id)) # global channels
channels = {k: v for k, v in channels.items() if k != str(target.id)} # delete user
await ticket_channel.delete()
dm = await ctx.author.create_dm()
await dm.send("문의채널 삭제가 완료되었습니다.")
bot.run(TOKEN)
| [
"discord_slash.utils.manage_commands.create_choice",
"discord.PermissionOverwrite",
"discord.ext.commands.Bot",
"discord_slash.utils.manage_commands.create_option",
"discord_slash.SlashCommand"
] | [((460, 492), 'discord.ext.commands.Bot', 'commands.Bot', ([], {'command_prefix': '"""!"""'}), "(command_prefix='!')\n", (472, 492), False, 'from discord.ext import commands\n'), ((501, 538), 'discord_slash.SlashCommand', 'SlashCommand', (['bot'], {'sync_commands': '(True)'}), '(bot, sync_commands=True)\n', (513, 538), False, 'from discord_slash import SlashContext, SlashCommand\n'), ((1491, 1539), 'discord.PermissionOverwrite', 'discord.PermissionOverwrite', ([], {'read_messages': '(False)'}), '(read_messages=False)\n', (1518, 1539), False, 'import discord\n'), ((1565, 1658), 'discord.PermissionOverwrite', 'discord.PermissionOverwrite', ([], {'read_messages': '(True)', 'send_messages': '(True)', 'manage_messages': '(True)'}), '(read_messages=True, send_messages=True,\n manage_messages=True)\n', (1592, 1658), False, 'import discord\n'), ((2649, 2763), 'discord_slash.utils.manage_commands.create_option', 'create_option', ([], {'name': '"""target"""', 'description': '"""강제 삭제할 유저"""', 'option_type': 'SlashCommandOptionType.USER', 'required': '(True)'}), "(name='target', description='강제 삭제할 유저', option_type=\n SlashCommandOptionType.USER, required=True)\n", (2662, 2763), False, 'from discord_slash.utils.manage_commands import create_option, create_choice\n'), ((944, 988), 'discord_slash.utils.manage_commands.create_choice', 'create_choice', ([], {'name': '"""create"""', 'value': '"""create"""'}), "(name='create', value='create')\n", (957, 988), False, 'from discord_slash.utils.manage_commands import create_option, create_choice\n'), ((1006, 1050), 'discord_slash.utils.manage_commands.create_choice', 'create_choice', ([], {'name': '"""delete"""', 'value': '"""delete"""'}), "(name='delete', value='delete')\n", (1019, 1050), False, 'from discord_slash.utils.manage_commands import create_option, create_choice\n')] |
import pyopencl as cl
import numpy
from pyPaSWAS.Core.SmithWaterman import SmithWaterman
from pyPaSWAS.Core import STOP_DIRECTION, LEFT_DIRECTION, NO_DIRECTION, UPPER_DIRECTION, UPPER_LEFT_DIRECTION
from pyPaSWAS.Core.PaSWAS import CPUcode
from pyPaSWAS.Core.PaSWAS import GPUcode
from pyPaSWAS.Core.StartingPoint import StartingPoint
class SmithWatermanOcl(SmithWaterman):
'''
classdocs
'''
def __init__(self, logger, score, settings):
'''
Constructor
'''
SmithWaterman.__init__(self, logger, score, settings)
#self.oclcode = OCLcode(self.logger)
# platforms: A single ICD on a computer
self.platform = None
# device: device which will perform computation (for example a CPU or GPU)
self.device = None
# context: manages a command-queue, memory, program and kernel objects
self.ctx = None
# queue: stores instructions for the device
self.queue = None
# program: the compiled kernel program
self.program = None
# device_type: type of device to run computations on
self.device_type = 0
self._set_device_type(self.settings.device_type)
self._set_platform(self.settings.platform_name)
self._initialize_device(int(self.settings.device_number))
self.always_reallocate_memory = False
def _init_oclcode(self):
# Compiling part of the OpenCL code in advance
self.oclcode.set_shared_xy_code(self.shared_x, self.shared_y)
self.oclcode.set_direction_code(NO_DIRECTION, UPPER_LEFT_DIRECTION,
UPPER_DIRECTION, LEFT_DIRECTION,
STOP_DIRECTION)
def _execute_calculate_score_kernel(self, number_of_blocks, idx, idy):
''' Executes a single run of the calculate score kernel'''
pass
def _execute_traceback_kernel(self, number_of_blocks, idx, idy):
''' Executes a single run of the traceback kernel'''
pass
def _get_direction_byte_array(self):
'''
Get the resulting directions
@return gives the resulting direction array as byte array
'''
pass
def __del__(self):
'''Destructor. Removes the current running context'''
del self.program
del self.queue
del self.ctx
del self.device
del self.platform
self.device_type = 0
def _set_device_type(self, device_type):
'''Sets the device type'''
if device_type.upper() == 'ACCELERATOR':
self.device_type = cl.device_type.ACCELERATOR
elif device_type.upper() == 'GPU':
self.device_type = cl.device_type.GPU
elif device_type.upper() == 'CPU':
self.device_type = cl.device_type.CPU
else:
self.logger.warning("Warning: device type is set to default: GPU")
self.device_type = cl.device_type.GPU
def _set_platform(self, platform_name):
found_platform = False
for platform in cl.get_platforms():
for device in platform.get_devices():
if (platform_name.upper() in str(platform).upper()
and device.get_info(cl.device_info.TYPE) == self.device_type):
self.platform = platform
found_platform = True
break
if(found_platform):
self.logger.debug("Found platform {}".format(str(self.platform)))
break
if not (self.platform):
for platform in cl.get_platforms():
for device in platform.get_devices():
if (device.get_info(cl.device_info.TYPE) == self.device_type):
self.platform = platform
found_platform = True
break
if(found_platform):
self.logger.debug('Found platform {}, however this is not the platform indicated by the user'.format(str(self.platform)))
break
if not (self.platform):
raise RuntimeError('Failed to find platform')
def _initialize_device(self, device_number):
'''
Initalizes a device and verifies its computational abilities.
@param device_number: int value representing the device to use
'''
self.logger.debug('Initializing device {0}'.format(device_number))
self.device = self.platform.get_devices(device_type=self.device_type)[device_number]
if int(self.settings.number_of_compute_units) > 0:
self.device = self.device.create_sub_devices([cl.device_partition_property.EQUALLY,int(self.settings.number_of_compute_units)])[int(self.settings.sub_device)]
self.ctx = cl.Context(devices=[self.device])
self.queue = cl.CommandQueue(self.ctx)
#self.logger.debug("context:{}".format(self.ctx) )
def _device_global_mem_size(self):
#return clCharacterize.usable_local_mem_size(self.device)
# GLOBAL_MEM_SIZE
return self.device.get_info(cl.device_info.MAX_MEM_ALLOC_SIZE)
def _clear_memory(self):
'''Clears the claimed memory on the device.'''
if not self.always_reallocate_memory:
return
self.logger.debug('Clearing device memory.')
self._clear_normal_memory()
self._clear_zero_copy_memory()
try:
self.queue.finish()
except:
pass
def _clear_normal_memory(self):
self.logger.debug('Clearing normal device memory.')
if (self.d_sequences is not None):
try:
self.d_sequences.finish()
except:
pass
self.d_sequences.release()
if (self.d_targets is not None):
try:
self.d_targets.finish()
except:
pass
self.d_targets.release()
if (self.d_matrix is not None):
try:
self.d_matrix.finish()
except:
pass
self.d_matrix.release()
if (self.gap_extension and self.d_matrix_i is not None):
try:
self.d_matrix_i.finish()
except:
pass
self.d_matrix_i.release()
if (self.gap_extension and self.d_matrix_j is not None):
try:
self.d_matrix_j.finish()
except:
pass
self.d_matrix_j.release()
if (self.d_global_maxima is not None):
try:
self.d_global_maxima.finish()
except:
pass
self.d_global_maxima.release()
if (self.d_index_increment is not None):
try:
self.d_index_increment.finish()
except:
pass
self.d_index_increment.release()
def _clear_zero_copy_memory(self):
self.logger.debug('Clearing zero-copy device memory.')
if (self.d_starting_points_zero_copy is not None):
try:
self.d_starting_points_zero_copy.finish()
except:
pass
self.d_starting_points_zero_copy.release()
if (self.d_max_possible_score_zero_copy is not None):
try:
self.d_max_possible_score_zero_copy.finish()
except:
pass
self.d_max_possible_score_zero_copy.release()
def _need_reallocation(self, buffer, size):
if self.always_reallocate_memory:
return True
if buffer is None:
return True
if buffer.get_info(cl.mem_info.SIZE) < size:
try:
buffer.finish()
except:
pass
buffer.release()
return True
return False
def _init_normal_memory(self):
'''
#_init_memory will initialize all required memory on the device based on the current settings.
Make sure to initialize these values!
'''
# Sequence device memory
self.logger.debug('Initializing normal device memory.')
memory = self.length_of_x_sequences * self.number_of_sequences
if self._need_reallocation(self.d_sequences, memory):
self.d_sequences = cl.Buffer(self.ctx, cl.mem_flags.READ_ONLY, size=memory)
mem_size = memory
# Target device memory
memory = self.length_of_y_sequences * self.number_targets
if self._need_reallocation(self.d_targets, memory):
self.d_targets = cl.Buffer(self.ctx, cl.mem_flags.READ_ONLY, size=memory)
mem_size += memory
if self._need_reallocation(self.d_index_increment, SmithWaterman.int_size):
self.d_index_increment = cl.Buffer(self.ctx, cl.mem_flags.WRITE_ONLY, size=SmithWaterman.int_size)
return mem_size
def _init_zero_copy_memory(self):
self.logger.debug('Initializing zero-copy memory.')
# Starting points host memory allocation and device copy
memory = (self.size_of_startingpoint * self.maximum_number_starting_points * self.number_of_sequences *
self.number_targets)
if self._need_reallocation(self.d_starting_points_zero_copy, memory):
self.d_starting_points_zero_copy = cl.Buffer(self.ctx, cl.mem_flags.WRITE_ONLY | cl.mem_flags.ALLOC_HOST_PTR, size=memory)
mem_size = memory
# Maximum zero copy memory allocation and device copy
memory = (self.number_of_sequences * self.number_of_targets * SmithWaterman.float_size)
#self.d_max_possible_score_zero_copy = cl.Buffer(self.ctx, cl.mem_flags.READ_ONLY | cl.mem_flags.ALLOC_HOST_PTR, size=memory)
mem_size += memory
return mem_size
def _init_memory(self):
mem_size = self._init_normal_memory()
mem_size += self._init_zero_copy_memory()
self.logger.debug('Allocated: {}MB of memory'.format(str(mem_size / 1024.0 / 1024.00)))
def _init_zero_copy(self):
''' Initializes the index used for the 'zero copy' of the found starting points '''
index = numpy.zeros((1), dtype=numpy.int32)
cl.enqueue_copy(self.queue, self.d_index_increment, index)
def _compile_code(self):
"""Compile the device code with current settings"""
self.logger.debug('Compiling OpenCL code.')
code = self.oclcode.get_code(self.score, self.number_of_sequences, self.number_targets, self.length_of_x_sequences, self.length_of_y_sequences)
#self.logger.debug('Code: \n{}'.format(code))
self.program = cl.Program(self.ctx, code).build()
self.calculateScoreAffineGap_kernel = self.program.calculateScoreAffineGap
self.calculateScore_kernel = self.program.calculateScore
self.tracebackAffineGap_kernel = self.program.tracebackAffineGap
self.traceback_kernel = self.program.traceback
def copy_sequences(self, h_sequences, h_targets):
'''
Copy the sequences and targets to the device
@param h_sequences: the sequences to be copied. Should be a single string containing all sequences
@param h_targets: the targets to be copied. Should be a single string containing all sequences
'''
cl.enqueue_copy(self.queue, self.d_sequences, h_sequences, is_blocking=False)
cl.enqueue_copy(self.queue, self.d_targets, h_targets, is_blocking=False)
def _get_number_of_starting_points(self):
''' Returns the number of startingpoints. '''
self.logger.debug('Getting number of starting points.')
self.index = numpy.zeros((1), dtype=numpy.int32)
cl.enqueue_copy(self.queue, self.index, self.d_index_increment)
return self.index[0]
def _fill_max_possible_score(self, target_index, targets, i, index, records_seqs):
for tI in range(self.number_of_targets):
if tI+target_index < len(targets) and i+index < len(records_seqs):
self.set_minimum_score(tI*self.max_sequences + i, float(self.score.highest_score) * (len(records_seqs[i+index])
if len(records_seqs[i+index]) < len(targets[tI+target_index])
else len(targets[tI+target_index])) * float(self.filter_factor))
def _copy_min_score(self):
if self._need_reallocation(self.d_max_possible_score_zero_copy, self.min_score_np.nbytes):
self.d_max_possible_score_zero_copy = cl.Buffer(self.ctx, cl.mem_flags.READ_ONLY | cl.mem_flags.ALLOC_HOST_PTR, size=self.min_score_np.nbytes)
cl.enqueue_copy(self.queue, self.d_max_possible_score_zero_copy, self.min_score_np, is_blocking=False)
def _set_max_possible_score(self, target_index, targets, i, index, records_seqs):
'''fills the max_possible_score datastructure on the host'''
# self.h_max_possible_score_zero_copy = cl.enqueue_map_buffer(self.queue, self.d_max_possible_score_zero_copy,
# cl.map_flags.WRITE, 0,
# self.number_of_sequences * self.number_targets ,
# dtype=numpy.float32)[0]
self._fill_max_possible_score(target_index, targets, i, index, records_seqs)
#Unmap memory object
# del self.h_max_possible_score_zero_copy
def _get_starting_point_byte_array(self, number_of_starting_points):
'''
Get the resulting starting points
@return gives the resulting starting point array as byte array
'''
if self.h_starting_points_zero_copy is not None and len(self.h_starting_points_zero_copy) > 0 :
self.h_starting_points_zero_copy.base.release()
self.h_starting_points_zero_copy = cl.enqueue_map_buffer(self.queue, self.d_starting_points_zero_copy, cl.map_flags.READ, 0,
(self.size_of_startingpoint *
number_of_starting_points, 1), dtype=numpy.byte)[0]
return self.h_starting_points_zero_copy
class SmithWatermanCPU(SmithWatermanOcl):
'''
classdocs
'''
def __init__(self, logger, score, settings):
'''
Constructor
'''
SmithWatermanOcl.__init__(self, logger, score, settings)
self.oclcode = CPUcode(self.logger)
self.workload_x = 4
self.workload_y = 4
self.workgroup_x = self.shared_x // self.workload_x
self.workgroup_y = self.shared_y // self.workload_y
self.d_semaphores = None
self._init_oclcode()
def _init_normal_memory(self):
mem_size = SmithWatermanOcl._init_normal_memory(self)
# Input matrix device memory
memory = (SmithWaterman.float_size * (self.length_of_x_sequences + 1) * self.number_of_sequences *
(self.length_of_y_sequences + 1) * self.number_targets)
if self._need_reallocation(self.d_matrix, memory):
self.d_matrix = cl.Buffer(self.ctx, cl.mem_flags.READ_WRITE, size=memory)
mem_size += memory
pattern = numpy.zeros((1),dtype=numpy.float32)
cl.enqueue_fill_buffer(self.queue, self.d_matrix, pattern, 0, size = memory)
if self.gap_extension:
if self._need_reallocation(self.d_matrix_i, memory):
self.d_matrix_i = cl.Buffer(self.ctx, cl.mem_flags.READ_WRITE, size=memory)
mem_size += memory
if self._need_reallocation(self.d_matrix_j, memory):
self.d_matrix_j = cl.Buffer(self.ctx, cl.mem_flags.READ_WRITE, size=memory)
mem_size += memory
pattern = numpy.array([-1E10],dtype=numpy.float32)
cl.enqueue_fill_buffer(self.queue, self.d_matrix_i, pattern, 0, size = memory)
cl.enqueue_fill_buffer(self.queue, self.d_matrix_j, pattern, 0, size = memory)
# Maximum global device memory
memory = (SmithWaterman.float_size * self.x_div_shared_x * self.number_of_sequences *
self.y_div_shared_y * self.number_targets * self.workload_x * self.workload_y)
if self._need_reallocation(self.d_global_maxima, memory):
self.d_global_maxima = cl.Buffer(self.ctx, cl.mem_flags.READ_WRITE, size=memory)
mem_size += memory
memory = (SmithWaterman.int_size *
self.length_of_x_sequences *
self.number_of_sequences *
self.length_of_y_sequences *
self.number_targets)
if self._need_reallocation(self.d_semaphores, memory):
self.d_semaphores = cl.Buffer(self.ctx, cl.mem_flags.READ_WRITE, size=memory)
pattern = numpy.zeros((1),dtype=numpy.int32)
cl.enqueue_fill_buffer(self.queue, self.d_semaphores, pattern, 0, size=memory)
mem_size += memory
return mem_size
def _init_zero_copy_memory(self):
mem_size = SmithWatermanOcl._init_zero_copy_memory(self)
# Global directions host memory allocation and device copy
memory = (self.length_of_x_sequences * self.number_of_sequences * self.length_of_y_sequences * self.number_targets)
if self._need_reallocation(self.d_global_direction_zero_copy, memory):
self.d_global_direction_zero_copy = cl.Buffer(self.ctx, cl.mem_flags.READ_WRITE | cl.mem_flags.ALLOC_HOST_PTR, size=memory)
mem_size += memory
return mem_size
def _clear_normal_memory(self):
SmithWatermanOcl._clear_normal_memory(self)
if (self.d_semaphores is not None):
try:
self.d_semaphores.finish()
except:
pass
self.d_semaphores.release()
def _clear_zero_copy_memory(self):
SmithWatermanOcl._clear_zero_copy_memory(self)
if (self.d_global_direction_zero_copy is not None):
try:
self.d_global_direction_zero_copy.finish()
except:
pass
self.d_global_direction_zero_copy.release()
def _get_direction_byte_array(self):
'''
Get the resulting directions
@return gives the resulting direction array as byte array
'''
h_global_direction_zero_copy = cl.enqueue_map_buffer(self.queue, self.d_global_direction_zero_copy, cl.map_flags.READ, 0,
(self.number_of_sequences,
self.number_targets,
self.length_of_x_sequences,
self.length_of_y_sequences), dtype=numpy.byte)[0]
return h_global_direction_zero_copy
def _get_direction(self, direction_array, sequence, target, block_x, block_y, value_x, value_y):
return direction_array[sequence][target][block_x*self.shared_x + value_x][block_y*self.shared_y + value_y]
def _set_direction(self, direction, direction_array, sequence, target, block_x, block_y, value_x, value_y):
direction_array[sequence][target][block_x*self.shared_x + value_x][block_y*self.shared_y + value_y] = direction
def _execute_calculate_score_kernel(self, number_of_blocks, idx, idy):
''' Executes a single run of the calculate score kernel'''
dim_block = (self.workgroup_x, self.workgroup_y)
dim_grid_sw = (self.number_of_sequences * self.workgroup_x, self.number_targets * number_of_blocks * self.workgroup_y)
if self.gap_extension:
self.calculateScoreAffineGap_kernel(self.queue,
dim_grid_sw,
dim_block,
self.d_matrix,
self.d_matrix_i,
self.d_matrix_j,
numpy.int32(idx),
numpy.int32(idy),
numpy.int32(number_of_blocks),
self.d_sequences,
self.d_targets,
self.d_global_maxima,
self.d_global_direction_zero_copy)
else:
self.calculateScore_kernel(self.queue,
dim_grid_sw,
dim_block,
self.d_matrix,
numpy.int32(idx),
numpy.int32(idy),
numpy.int32(number_of_blocks),
self.d_sequences,
self.d_targets,
self.d_global_maxima,
self.d_global_direction_zero_copy)
def _execute_traceback_kernel(self, number_of_blocks, idx, idy):
''' Executes a single run of the traceback kernel'''
dim_block = (self.workgroup_x, self.workgroup_y)
dim_grid_sw = (self.number_of_sequences * self.workgroup_x, self.number_targets * number_of_blocks * self.workgroup_y)
if self.gap_extension:
self.tracebackAffineGap_kernel(self.queue, dim_grid_sw, dim_block,
self.d_matrix,
self.d_matrix_i,
self.d_matrix_j,
numpy.int32(idx),
numpy.int32(idy),
numpy.int32(number_of_blocks),
self.d_global_maxima,
self.d_global_direction_zero_copy,
self.d_index_increment,
self.d_starting_points_zero_copy,
self.d_max_possible_score_zero_copy,
self.d_semaphores)
else:
self.traceback_kernel(self.queue, dim_grid_sw, dim_block,
self.d_matrix,
numpy.int32(idx),
numpy.int32(idy),
numpy.int32(number_of_blocks),
self.d_global_maxima,
self.d_global_direction_zero_copy,
self.d_index_increment,
self.d_starting_points_zero_copy,
self.d_max_possible_score_zero_copy,
self.d_semaphores)
class SmithWatermanGPU(SmithWatermanOcl):
'''
classdocs
'''
def __init__(self, logger, score, settings):
'''
Constructor
'''
SmithWatermanOcl.__init__(self, logger, score, settings)
self.oclcode = GPUcode(self.logger)
self.d_global_direction = None
self.d_is_traceback_required = None
self._init_oclcode()
def _init_normal_memory(self):
mem_size = SmithWatermanOcl._init_normal_memory(self)
# Input matrix device memory
memory = (SmithWaterman.float_size * self.length_of_x_sequences * self.number_of_sequences *
self.length_of_y_sequences * self.number_targets)
if self._need_reallocation(self.d_matrix, memory):
self.d_matrix = cl.Buffer(self.ctx, cl.mem_flags.READ_WRITE, size=memory)
mem_size += memory
if self.gap_extension:
if self._need_reallocation(self.d_matrix_i, memory):
self.d_matrix_i = cl.Buffer(self.ctx, cl.mem_flags.READ_WRITE, size=memory)
mem_size += memory
if self._need_reallocation(self.d_matrix_j, memory):
self.d_matrix_j = cl.Buffer(self.ctx, cl.mem_flags.READ_WRITE, size=memory)
mem_size += memory
# Maximum global device memory
memory = (SmithWaterman.float_size * self.x_div_shared_x * self.number_of_sequences *
self.y_div_shared_y * self.number_targets)
if self._need_reallocation(self.d_global_maxima, memory):
self.d_global_maxima = cl.Buffer(self.ctx, cl.mem_flags.READ_WRITE, size=memory)
mem_size += memory
memory = (self.length_of_x_sequences * self.number_of_sequences * self.length_of_y_sequences * self.number_targets)
if self._need_reallocation(self.d_global_direction, memory):
self.d_global_direction = cl.Buffer(self.ctx, cl.mem_flags.READ_WRITE, size=memory)
mem_size += memory
memory = SmithWaterman.int_size
if self._need_reallocation(self.d_is_traceback_required, memory):
self.d_is_traceback_required = cl.Buffer(self.ctx, cl.mem_flags.WRITE_ONLY, size=memory)
flag = numpy.zeros((1), dtype=numpy.uint32)
cl.enqueue_fill_buffer(self.queue, self.d_is_traceback_required, flag, 0, size=memory)
return mem_size
def _clear_normal_memory(self):
SmithWatermanOcl._clear_normal_memory(self)
if (self.d_global_direction is not None):
try:
self.d_global_direction.finish()
except:
pass
self.d_global_direction.release()
if (self.d_is_traceback_required is not None):
try:
self.d_is_traceback_required.finish()
except:
pass
self.d_is_traceback_required.release()
def _compile_code(self):
"""Compile the device code with current settings"""
if self.program is None:
self.logger.debug('Compiling OpenCL code.')
code = self.oclcode.get_code(self.score, self.number_of_sequences, self.number_targets, self.length_of_x_sequences, self.length_of_y_sequences)
self.program = cl.Program(self.ctx, code).build(options=['-cl-fast-relaxed-math'])
self.calculateScoreAffineGap_kernel = self.program.calculateScoreAffineGap
self.calculateScore_kernel = self.program.calculateScore
self.tracebackAffineGap_kernel = self.program.tracebackAffineGap
self.traceback_kernel = self.program.traceback
def _get_direction_byte_array(self):
'''
Get the resulting directions
@return gives the resulting direction array as byte array
'''
h_global_direction = cl.enqueue_map_buffer(self.queue, self.d_global_direction, cl.map_flags.READ, 0,
(self.number_of_sequences,
self.number_targets,
self.x_div_shared_x,
self.y_div_shared_y,
self.shared_x,
self.shared_y), dtype=numpy.byte)[0]
return h_global_direction
def _execute_calculate_score_kernel(self, number_of_blocks, idx, idy):
''' Executes a single run of the calculate score kernel'''
dim_block = (self.shared_x, self.shared_y, 1)
dim_grid_sw = (number_of_blocks * self.shared_x, self.number_of_sequences * self.shared_y, self.number_targets)
if self.gap_extension:
self.calculateScoreAffineGap_kernel(self.queue, dim_grid_sw, dim_block,
numpy.uint32(self.number_of_sequences),
numpy.uint32(self.number_targets),
numpy.uint32(self.x_div_shared_x),
numpy.uint32(self.y_div_shared_y),
self.d_matrix,
self.d_matrix_i,
self.d_matrix_j,
numpy.uint32(idx),
numpy.uint32(idy),
self.d_sequences,
self.d_targets,
self.d_global_maxima,
self.d_global_direction,
self.d_max_possible_score_zero_copy,
self.d_is_traceback_required)
else:
self.calculateScore_kernel(self.queue, dim_grid_sw, dim_block,
numpy.uint32(self.number_of_sequences),
numpy.uint32(self.number_targets),
numpy.uint32(self.x_div_shared_x),
numpy.uint32(self.y_div_shared_y),
self.d_matrix,
numpy.uint32(idx),
numpy.uint32(idy),
self.d_sequences,
self.d_targets,
self.d_global_maxima,
self.d_global_direction,
self.d_max_possible_score_zero_copy,
self.d_is_traceback_required)
def _is_traceback_required(self):
'''Returns False if it is known after calculating scores that there are no possible
starting points, hence no need to run traceback.
'''
flag = numpy.zeros((1), dtype=numpy.uint32)
cl.enqueue_copy(self.queue, flag, self.d_is_traceback_required)
if flag[0]:
# Clear the flag
flag[0] = 0
cl.enqueue_fill_buffer(self.queue, self.d_is_traceback_required, flag, 0, size=SmithWaterman.int_size)
return True
else:
return False
def _execute_traceback_kernel(self, number_of_blocks, idx, idy):
''' Executes a single run of the traceback kernel'''
dim_block = (self.shared_x, self.shared_y, 1)
dim_grid_sw = (number_of_blocks * self.shared_x, self.number_of_sequences * self.shared_y, self.number_targets)
if self.gap_extension:
self.tracebackAffineGap_kernel(self.queue, dim_grid_sw, dim_block,
numpy.uint32(self.number_of_sequences),
numpy.uint32(self.number_targets),
numpy.uint32(self.x_div_shared_x),
numpy.uint32(self.y_div_shared_y),
self.d_matrix,
self.d_matrix_i,
self.d_matrix_j,
numpy.uint32(idx),
numpy.uint32(idy),
self.d_global_maxima,
self.d_global_direction,
self.d_index_increment,
self.d_starting_points_zero_copy,
self.d_max_possible_score_zero_copy)
else:
self.traceback_kernel(self.queue, dim_grid_sw, dim_block,
numpy.uint32(self.number_of_sequences),
numpy.uint32(self.number_targets),
numpy.uint32(self.x_div_shared_x),
numpy.uint32(self.y_div_shared_y),
self.d_matrix,
numpy.uint32(idx),
numpy.uint32(idy),
self.d_global_maxima,
self.d_global_direction,
self.d_index_increment,
self.d_starting_points_zero_copy,
self.d_max_possible_score_zero_copy)
| [
"numpy.uint32",
"pyPaSWAS.Core.PaSWAS.CPUcode",
"pyopencl.Program",
"pyPaSWAS.Core.PaSWAS.GPUcode",
"pyPaSWAS.Core.SmithWaterman.SmithWaterman.__init__",
"pyopencl.CommandQueue",
"numpy.int32",
"numpy.zeros",
"pyopencl.enqueue_fill_buffer",
"pyopencl.Buffer",
"numpy.array",
"pyopencl.get_platf... | [((509, 562), 'pyPaSWAS.Core.SmithWaterman.SmithWaterman.__init__', 'SmithWaterman.__init__', (['self', 'logger', 'score', 'settings'], {}), '(self, logger, score, settings)\n', (531, 562), False, 'from pyPaSWAS.Core.SmithWaterman import SmithWaterman\n'), ((3137, 3155), 'pyopencl.get_platforms', 'cl.get_platforms', ([], {}), '()\n', (3153, 3155), True, 'import pyopencl as cl\n'), ((4914, 4947), 'pyopencl.Context', 'cl.Context', ([], {'devices': '[self.device]'}), '(devices=[self.device])\n', (4924, 4947), True, 'import pyopencl as cl\n'), ((4969, 4994), 'pyopencl.CommandQueue', 'cl.CommandQueue', (['self.ctx'], {}), '(self.ctx)\n', (4984, 4994), True, 'import pyopencl as cl\n'), ((10367, 10400), 'numpy.zeros', 'numpy.zeros', (['(1)'], {'dtype': 'numpy.int32'}), '(1, dtype=numpy.int32)\n', (10378, 10400), False, 'import numpy\n'), ((10411, 10469), 'pyopencl.enqueue_copy', 'cl.enqueue_copy', (['self.queue', 'self.d_index_increment', 'index'], {}), '(self.queue, self.d_index_increment, index)\n', (10426, 10469), True, 'import pyopencl as cl\n'), ((11506, 11583), 'pyopencl.enqueue_copy', 'cl.enqueue_copy', (['self.queue', 'self.d_sequences', 'h_sequences'], {'is_blocking': '(False)'}), '(self.queue, self.d_sequences, h_sequences, is_blocking=False)\n', (11521, 11583), True, 'import pyopencl as cl\n'), ((11592, 11665), 'pyopencl.enqueue_copy', 'cl.enqueue_copy', (['self.queue', 'self.d_targets', 'h_targets'], {'is_blocking': '(False)'}), '(self.queue, self.d_targets, h_targets, is_blocking=False)\n', (11607, 11665), True, 'import pyopencl as cl\n'), ((11860, 11893), 'numpy.zeros', 'numpy.zeros', (['(1)'], {'dtype': 'numpy.int32'}), '(1, dtype=numpy.int32)\n', (11871, 11893), False, 'import numpy\n'), ((11904, 11967), 'pyopencl.enqueue_copy', 'cl.enqueue_copy', (['self.queue', 'self.index', 'self.d_index_increment'], {}), '(self.queue, self.index, self.d_index_increment)\n', (11919, 11967), True, 'import pyopencl as cl\n'), ((12970, 13077), 'pyopencl.enqueue_copy', 'cl.enqueue_copy', (['self.queue', 'self.d_max_possible_score_zero_copy', 'self.min_score_np'], {'is_blocking': '(False)'}), '(self.queue, self.d_max_possible_score_zero_copy, self.\n min_score_np, is_blocking=False)\n', (12985, 13077), True, 'import pyopencl as cl\n'), ((14870, 14890), 'pyPaSWAS.Core.PaSWAS.CPUcode', 'CPUcode', (['self.logger'], {}), '(self.logger)\n', (14877, 14890), False, 'from pyPaSWAS.Core.PaSWAS import CPUcode\n'), ((15670, 15705), 'numpy.zeros', 'numpy.zeros', (['(1)'], {'dtype': 'numpy.float32'}), '(1, dtype=numpy.float32)\n', (15681, 15705), False, 'import numpy\n'), ((15715, 15789), 'pyopencl.enqueue_fill_buffer', 'cl.enqueue_fill_buffer', (['self.queue', 'self.d_matrix', 'pattern', '(0)'], {'size': 'memory'}), '(self.queue, self.d_matrix, pattern, 0, size=memory)\n', (15737, 15789), True, 'import pyopencl as cl\n'), ((17275, 17308), 'numpy.zeros', 'numpy.zeros', (['(1)'], {'dtype': 'numpy.int32'}), '(1, dtype=numpy.int32)\n', (17286, 17308), False, 'import numpy\n'), ((17318, 17396), 'pyopencl.enqueue_fill_buffer', 'cl.enqueue_fill_buffer', (['self.queue', 'self.d_semaphores', 'pattern', '(0)'], {'size': 'memory'}), '(self.queue, self.d_semaphores, pattern, 0, size=memory)\n', (17340, 17396), True, 'import pyopencl as cl\n'), ((23863, 23883), 'pyPaSWAS.Core.PaSWAS.GPUcode', 'GPUcode', (['self.logger'], {}), '(self.logger)\n', (23870, 23883), False, 'from pyPaSWAS.Core.PaSWAS import GPUcode\n'), ((30678, 30712), 'numpy.zeros', 'numpy.zeros', (['(1)'], {'dtype': 'numpy.uint32'}), '(1, dtype=numpy.uint32)\n', (30689, 30712), False, 'import numpy\n'), ((30723, 30786), 'pyopencl.enqueue_copy', 'cl.enqueue_copy', (['self.queue', 'flag', 'self.d_is_traceback_required'], {}), '(self.queue, flag, self.d_is_traceback_required)\n', (30738, 30786), True, 'import pyopencl as cl\n'), ((3681, 3699), 'pyopencl.get_platforms', 'cl.get_platforms', ([], {}), '()\n', (3697, 3699), True, 'import pyopencl as cl\n'), ((8491, 8547), 'pyopencl.Buffer', 'cl.Buffer', (['self.ctx', 'cl.mem_flags.READ_ONLY'], {'size': 'memory'}), '(self.ctx, cl.mem_flags.READ_ONLY, size=memory)\n', (8500, 8547), True, 'import pyopencl as cl\n'), ((8769, 8825), 'pyopencl.Buffer', 'cl.Buffer', (['self.ctx', 'cl.mem_flags.READ_ONLY'], {'size': 'memory'}), '(self.ctx, cl.mem_flags.READ_ONLY, size=memory)\n', (8778, 8825), True, 'import pyopencl as cl\n'), ((8975, 9048), 'pyopencl.Buffer', 'cl.Buffer', (['self.ctx', 'cl.mem_flags.WRITE_ONLY'], {'size': 'SmithWaterman.int_size'}), '(self.ctx, cl.mem_flags.WRITE_ONLY, size=SmithWaterman.int_size)\n', (8984, 9048), True, 'import pyopencl as cl\n'), ((9521, 9612), 'pyopencl.Buffer', 'cl.Buffer', (['self.ctx', '(cl.mem_flags.WRITE_ONLY | cl.mem_flags.ALLOC_HOST_PTR)'], {'size': 'memory'}), '(self.ctx, cl.mem_flags.WRITE_ONLY | cl.mem_flags.ALLOC_HOST_PTR,\n size=memory)\n', (9530, 9612), True, 'import pyopencl as cl\n'), ((12857, 12965), 'pyopencl.Buffer', 'cl.Buffer', (['self.ctx', '(cl.mem_flags.READ_ONLY | cl.mem_flags.ALLOC_HOST_PTR)'], {'size': 'self.min_score_np.nbytes'}), '(self.ctx, cl.mem_flags.READ_ONLY | cl.mem_flags.ALLOC_HOST_PTR,\n size=self.min_score_np.nbytes)\n', (12866, 12965), True, 'import pyopencl as cl\n'), ((14251, 14428), 'pyopencl.enqueue_map_buffer', 'cl.enqueue_map_buffer', (['self.queue', 'self.d_starting_points_zero_copy', 'cl.map_flags.READ', '(0)', '(self.size_of_startingpoint * number_of_starting_points, 1)'], {'dtype': 'numpy.byte'}), '(self.queue, self.d_starting_points_zero_copy, cl.\n map_flags.READ, 0, (self.size_of_startingpoint *\n number_of_starting_points, 1), dtype=numpy.byte)\n', (14272, 14428), True, 'import pyopencl as cl\n'), ((15566, 15623), 'pyopencl.Buffer', 'cl.Buffer', (['self.ctx', 'cl.mem_flags.READ_WRITE'], {'size': 'memory'}), '(self.ctx, cl.mem_flags.READ_WRITE, size=memory)\n', (15575, 15623), True, 'import pyopencl as cl\n'), ((16222, 16272), 'numpy.array', 'numpy.array', (['[-10000000000.0]'], {'dtype': 'numpy.float32'}), '([-10000000000.0], dtype=numpy.float32)\n', (16233, 16272), False, 'import numpy\n'), ((16275, 16351), 'pyopencl.enqueue_fill_buffer', 'cl.enqueue_fill_buffer', (['self.queue', 'self.d_matrix_i', 'pattern', '(0)'], {'size': 'memory'}), '(self.queue, self.d_matrix_i, pattern, 0, size=memory)\n', (16297, 16351), True, 'import pyopencl as cl\n'), ((16366, 16442), 'pyopencl.enqueue_fill_buffer', 'cl.enqueue_fill_buffer', (['self.queue', 'self.d_matrix_j', 'pattern', '(0)'], {'size': 'memory'}), '(self.queue, self.d_matrix_j, pattern, 0, size=memory)\n', (16388, 16442), True, 'import pyopencl as cl\n'), ((16776, 16833), 'pyopencl.Buffer', 'cl.Buffer', (['self.ctx', 'cl.mem_flags.READ_WRITE'], {'size': 'memory'}), '(self.ctx, cl.mem_flags.READ_WRITE, size=memory)\n', (16785, 16833), True, 'import pyopencl as cl\n'), ((17199, 17256), 'pyopencl.Buffer', 'cl.Buffer', (['self.ctx', 'cl.mem_flags.READ_WRITE'], {'size': 'memory'}), '(self.ctx, cl.mem_flags.READ_WRITE, size=memory)\n', (17208, 17256), True, 'import pyopencl as cl\n'), ((17881, 17972), 'pyopencl.Buffer', 'cl.Buffer', (['self.ctx', '(cl.mem_flags.READ_WRITE | cl.mem_flags.ALLOC_HOST_PTR)'], {'size': 'memory'}), '(self.ctx, cl.mem_flags.READ_WRITE | cl.mem_flags.ALLOC_HOST_PTR,\n size=memory)\n', (17890, 17972), True, 'import pyopencl as cl\n'), ((18831, 19054), 'pyopencl.enqueue_map_buffer', 'cl.enqueue_map_buffer', (['self.queue', 'self.d_global_direction_zero_copy', 'cl.map_flags.READ', '(0)', '(self.number_of_sequences, self.number_targets, self.length_of_x_sequences,\n self.length_of_y_sequences)'], {'dtype': 'numpy.byte'}), '(self.queue, self.d_global_direction_zero_copy, cl.\n map_flags.READ, 0, (self.number_of_sequences, self.number_targets, self\n .length_of_x_sequences, self.length_of_y_sequences), dtype=numpy.byte)\n', (18852, 19054), True, 'import pyopencl as cl\n'), ((24405, 24462), 'pyopencl.Buffer', 'cl.Buffer', (['self.ctx', 'cl.mem_flags.READ_WRITE'], {'size': 'memory'}), '(self.ctx, cl.mem_flags.READ_WRITE, size=memory)\n', (24414, 24462), True, 'import pyopencl as cl\n'), ((25183, 25240), 'pyopencl.Buffer', 'cl.Buffer', (['self.ctx', 'cl.mem_flags.READ_WRITE'], {'size': 'memory'}), '(self.ctx, cl.mem_flags.READ_WRITE, size=memory)\n', (25192, 25240), True, 'import pyopencl as cl\n'), ((25500, 25557), 'pyopencl.Buffer', 'cl.Buffer', (['self.ctx', 'cl.mem_flags.READ_WRITE'], {'size': 'memory'}), '(self.ctx, cl.mem_flags.READ_WRITE, size=memory)\n', (25509, 25557), True, 'import pyopencl as cl\n'), ((25743, 25800), 'pyopencl.Buffer', 'cl.Buffer', (['self.ctx', 'cl.mem_flags.WRITE_ONLY'], {'size': 'memory'}), '(self.ctx, cl.mem_flags.WRITE_ONLY, size=memory)\n', (25752, 25800), True, 'import pyopencl as cl\n'), ((25820, 25854), 'numpy.zeros', 'numpy.zeros', (['(1)'], {'dtype': 'numpy.uint32'}), '(1, dtype=numpy.uint32)\n', (25831, 25854), False, 'import numpy\n'), ((25869, 25959), 'pyopencl.enqueue_fill_buffer', 'cl.enqueue_fill_buffer', (['self.queue', 'self.d_is_traceback_required', 'flag', '(0)'], {'size': 'memory'}), '(self.queue, self.d_is_traceback_required, flag, 0,\n size=memory)\n', (25891, 25959), True, 'import pyopencl as cl\n'), ((27411, 27644), 'pyopencl.enqueue_map_buffer', 'cl.enqueue_map_buffer', (['self.queue', 'self.d_global_direction', 'cl.map_flags.READ', '(0)', '(self.number_of_sequences, self.number_targets, self.x_div_shared_x, self.\n y_div_shared_y, self.shared_x, self.shared_y)'], {'dtype': 'numpy.byte'}), '(self.queue, self.d_global_direction, cl.map_flags.\n READ, 0, (self.number_of_sequences, self.number_targets, self.\n x_div_shared_x, self.y_div_shared_y, self.shared_x, self.shared_y),\n dtype=numpy.byte)\n', (27432, 27644), True, 'import pyopencl as cl\n'), ((30872, 30978), 'pyopencl.enqueue_fill_buffer', 'cl.enqueue_fill_buffer', (['self.queue', 'self.d_is_traceback_required', 'flag', '(0)'], {'size': 'SmithWaterman.int_size'}), '(self.queue, self.d_is_traceback_required, flag, 0,\n size=SmithWaterman.int_size)\n', (30894, 30978), True, 'import pyopencl as cl\n'), ((10841, 10867), 'pyopencl.Program', 'cl.Program', (['self.ctx', 'code'], {}), '(self.ctx, code)\n', (10851, 10867), True, 'import pyopencl as cl\n'), ((15923, 15980), 'pyopencl.Buffer', 'cl.Buffer', (['self.ctx', 'cl.mem_flags.READ_WRITE'], {'size': 'memory'}), '(self.ctx, cl.mem_flags.READ_WRITE, size=memory)\n', (15932, 15980), True, 'import pyopencl as cl\n'), ((16111, 16168), 'pyopencl.Buffer', 'cl.Buffer', (['self.ctx', 'cl.mem_flags.READ_WRITE'], {'size': 'memory'}), '(self.ctx, cl.mem_flags.READ_WRITE, size=memory)\n', (16120, 16168), True, 'import pyopencl as cl\n'), ((20583, 20599), 'numpy.int32', 'numpy.int32', (['idx'], {}), '(idx)\n', (20594, 20599), False, 'import numpy\n'), ((20649, 20665), 'numpy.int32', 'numpy.int32', (['idy'], {}), '(idy)\n', (20660, 20665), False, 'import numpy\n'), ((20715, 20744), 'numpy.int32', 'numpy.int32', (['number_of_blocks'], {}), '(number_of_blocks)\n', (20726, 20744), False, 'import numpy\n'), ((21290, 21306), 'numpy.int32', 'numpy.int32', (['idx'], {}), '(idx)\n', (21301, 21306), False, 'import numpy\n'), ((21347, 21363), 'numpy.int32', 'numpy.int32', (['idy'], {}), '(idy)\n', (21358, 21363), False, 'import numpy\n'), ((21404, 21433), 'numpy.int32', 'numpy.int32', (['number_of_blocks'], {}), '(number_of_blocks)\n', (21415, 21433), False, 'import numpy\n'), ((22347, 22363), 'numpy.int32', 'numpy.int32', (['idx'], {}), '(idx)\n', (22358, 22363), False, 'import numpy\n'), ((22408, 22424), 'numpy.int32', 'numpy.int32', (['idy'], {}), '(idy)\n', (22419, 22424), False, 'import numpy\n'), ((22469, 22498), 'numpy.int32', 'numpy.int32', (['number_of_blocks'], {}), '(number_of_blocks)\n', (22480, 22498), False, 'import numpy\n'), ((23096, 23112), 'numpy.int32', 'numpy.int32', (['idx'], {}), '(idx)\n', (23107, 23112), False, 'import numpy\n'), ((23148, 23164), 'numpy.int32', 'numpy.int32', (['idy'], {}), '(idy)\n', (23159, 23164), False, 'import numpy\n'), ((23200, 23229), 'numpy.int32', 'numpy.int32', (['number_of_blocks'], {}), '(number_of_blocks)\n', (23211, 23229), False, 'import numpy\n'), ((24620, 24677), 'pyopencl.Buffer', 'cl.Buffer', (['self.ctx', 'cl.mem_flags.READ_WRITE'], {'size': 'memory'}), '(self.ctx, cl.mem_flags.READ_WRITE, size=memory)\n', (24629, 24677), True, 'import pyopencl as cl\n'), ((24808, 24865), 'pyopencl.Buffer', 'cl.Buffer', (['self.ctx', 'cl.mem_flags.READ_WRITE'], {'size': 'memory'}), '(self.ctx, cl.mem_flags.READ_WRITE, size=memory)\n', (24817, 24865), True, 'import pyopencl as cl\n'), ((28469, 28507), 'numpy.uint32', 'numpy.uint32', (['self.number_of_sequences'], {}), '(self.number_of_sequences)\n', (28481, 28507), False, 'import numpy\n'), ((28557, 28590), 'numpy.uint32', 'numpy.uint32', (['self.number_targets'], {}), '(self.number_targets)\n', (28569, 28590), False, 'import numpy\n'), ((28640, 28673), 'numpy.uint32', 'numpy.uint32', (['self.x_div_shared_x'], {}), '(self.x_div_shared_x)\n', (28652, 28673), False, 'import numpy\n'), ((28723, 28756), 'numpy.uint32', 'numpy.uint32', (['self.y_div_shared_y'], {}), '(self.y_div_shared_y)\n', (28735, 28756), False, 'import numpy\n'), ((28999, 29016), 'numpy.uint32', 'numpy.uint32', (['idx'], {}), '(idx)\n', (29011, 29016), False, 'import numpy\n'), ((29066, 29083), 'numpy.uint32', 'numpy.uint32', (['idy'], {}), '(idy)\n', (29078, 29083), False, 'import numpy\n'), ((29649, 29687), 'numpy.uint32', 'numpy.uint32', (['self.number_of_sequences'], {}), '(self.number_of_sequences)\n', (29661, 29687), False, 'import numpy\n'), ((29728, 29761), 'numpy.uint32', 'numpy.uint32', (['self.number_targets'], {}), '(self.number_targets)\n', (29740, 29761), False, 'import numpy\n'), ((29802, 29835), 'numpy.uint32', 'numpy.uint32', (['self.x_div_shared_x'], {}), '(self.x_div_shared_x)\n', (29814, 29835), False, 'import numpy\n'), ((29876, 29909), 'numpy.uint32', 'numpy.uint32', (['self.y_div_shared_y'], {}), '(self.y_div_shared_y)\n', (29888, 29909), False, 'import numpy\n'), ((30004, 30021), 'numpy.uint32', 'numpy.uint32', (['idx'], {}), '(idx)\n', (30016, 30021), False, 'import numpy\n'), ((30062, 30079), 'numpy.uint32', 'numpy.uint32', (['idy'], {}), '(idy)\n', (30074, 30079), False, 'import numpy\n'), ((31501, 31539), 'numpy.uint32', 'numpy.uint32', (['self.number_of_sequences'], {}), '(self.number_of_sequences)\n', (31513, 31539), False, 'import numpy\n'), ((31584, 31617), 'numpy.uint32', 'numpy.uint32', (['self.number_targets'], {}), '(self.number_targets)\n', (31596, 31617), False, 'import numpy\n'), ((31662, 31695), 'numpy.uint32', 'numpy.uint32', (['self.x_div_shared_x'], {}), '(self.x_div_shared_x)\n', (31674, 31695), False, 'import numpy\n'), ((31740, 31773), 'numpy.uint32', 'numpy.uint32', (['self.y_div_shared_y'], {}), '(self.y_div_shared_y)\n', (31752, 31773), False, 'import numpy\n'), ((31996, 32013), 'numpy.uint32', 'numpy.uint32', (['idx'], {}), '(idx)\n', (32008, 32013), False, 'import numpy\n'), ((32058, 32075), 'numpy.uint32', 'numpy.uint32', (['idy'], {}), '(idy)\n', (32070, 32075), False, 'import numpy\n'), ((32552, 32590), 'numpy.uint32', 'numpy.uint32', (['self.number_of_sequences'], {}), '(self.number_of_sequences)\n', (32564, 32590), False, 'import numpy\n'), ((32626, 32659), 'numpy.uint32', 'numpy.uint32', (['self.number_targets'], {}), '(self.number_targets)\n', (32638, 32659), False, 'import numpy\n'), ((32695, 32728), 'numpy.uint32', 'numpy.uint32', (['self.x_div_shared_x'], {}), '(self.x_div_shared_x)\n', (32707, 32728), False, 'import numpy\n'), ((32764, 32797), 'numpy.uint32', 'numpy.uint32', (['self.y_div_shared_y'], {}), '(self.y_div_shared_y)\n', (32776, 32797), False, 'import numpy\n'), ((32882, 32899), 'numpy.uint32', 'numpy.uint32', (['idx'], {}), '(idx)\n', (32894, 32899), False, 'import numpy\n'), ((32935, 32952), 'numpy.uint32', 'numpy.uint32', (['idy'], {}), '(idy)\n', (32947, 32952), False, 'import numpy\n'), ((26853, 26879), 'pyopencl.Program', 'cl.Program', (['self.ctx', 'code'], {}), '(self.ctx, code)\n', (26863, 26879), True, 'import pyopencl as cl\n')] |
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
import board
from adafruit_turtle import turtle
turtle = turtle(board.DISPLAY)
turtle.pendown()
for _ in range(32):
turtle.circle(50, steps=6)
turtle.right(11.1111)
while True:
pass
| [
"adafruit_turtle.turtle",
"adafruit_turtle.turtle.pendown",
"adafruit_turtle.turtle.circle",
"adafruit_turtle.turtle.right"
] | [((153, 174), 'adafruit_turtle.turtle', 'turtle', (['board.DISPLAY'], {}), '(board.DISPLAY)\n', (159, 174), False, 'from adafruit_turtle import turtle\n'), ((175, 191), 'adafruit_turtle.turtle.pendown', 'turtle.pendown', ([], {}), '()\n', (189, 191), False, 'from adafruit_turtle import turtle\n'), ((217, 243), 'adafruit_turtle.turtle.circle', 'turtle.circle', (['(50)'], {'steps': '(6)'}), '(50, steps=6)\n', (230, 243), False, 'from adafruit_turtle import turtle\n'), ((248, 269), 'adafruit_turtle.turtle.right', 'turtle.right', (['(11.1111)'], {}), '(11.1111)\n', (260, 269), False, 'from adafruit_turtle import turtle\n')] |
import gym
from typing import Tuple
def configure_env(name: str) -> Tuple[gym.Env, bool, int, int, int]:
environment = gym.make(name)
is_discrete_env = type(environment.action_space) == gym.spaces.discrete.Discrete
if is_discrete_env:
action_dims = 1
num_actions = environment.action_space.n
state_dims = len(environment.observation_space.high)
else:
action_dims = environment.action_space.shape[0]
num_actions = None # Technically, there's an infinite number
state_dims = environment.observation_space.shape[0]
return environment, is_discrete_env, state_dims, action_dims, num_actions
def normalize(data, mean, std, eps=1e-8):
return (data-mean)/(std+eps)
def unnormalize(data, mean, std):
return data*std+mean
| [
"gym.make"
] | [((125, 139), 'gym.make', 'gym.make', (['name'], {}), '(name)\n', (133, 139), False, 'import gym\n')] |
import re
import shlex
from typing import List
from typing import Union
from lxml.etree import Element
from lxml.etree import SubElement
from xapiparser.exception import ParseError
from xapiparser.exception import UnsupportedError
COMMANDS = ('xCommand', 'xStatus', 'xConfiguration')
UNSUPPORTED = ('xGetxml', 'xEvent')
SSH_ONLY = ('Systemtools', 'Log', 'xPreferences', 'xFeedback', 'Echo')
INDEXED_TAG = r"\[(\d+)\]$"
def parse(cmd: str) -> Element:
expr = shlex.split(cmd)
return _XApiParser.parse(expr)
class _XApiParser:
@staticmethod
def parse(expr: List, root: Element = None, current: Union[Element, SubElement] = None) -> Element:
try:
# base case
if root is None:
if expr[0].lower() in [u.lower() for u in SSH_ONLY]:
raise UnsupportedError('CLI cmd is not supported in REST API')
if expr[0].lower() in [u.lower() for u in UNSUPPORTED]:
raise NotImplementedError('cmd is not currently supported by xapiparser lib')
if expr[0].lower() not in [c.lower() for c in COMMANDS]:
raise ParseError(f"Unknown command: {expr[0]}")
root = Element(expr[0][1:])
return _XApiParser.parse(expr[1:], root=root, current=root)
# exit case: end of cmd reached
elif not expr:
return root
# case: sub-element with text
elif expr[0][-1] == ":":
# [indexed] tag with value and trailing colon
if re.search(INDEXED_TAG, expr[0][:-1]):
tag = expr[0][:-1].split("[")[0]
child = SubElement(current, tag)
val = re.search(INDEXED_TAG, expr[0][:-1]).group(1)
child.set("item", val)
child.text = expr[1]
return _XApiParser.parse(expr[2:], root=root, current=current)
# only trailing colon
else:
child = SubElement(current, expr[0][:-1])
child.text = expr[1]
return _XApiParser.parse(expr[2:], root=root, current=current)
# case: [indexed] tag with value
elif re.search(INDEXED_TAG, expr[0]):
tag = expr[0].split("[")[0]
child = SubElement(current, tag)
val = re.search(INDEXED_TAG, expr[0]).group(1)
child.set("item", val)
child.text = expr[1]
return _XApiParser.parse(expr[2:], root=root, current=child)
# case: final element
elif len(expr) == 1:
child = SubElement(current, expr[0])
return _XApiParser.parse(expr[1:], root=root, current=child)
# case: index as next element and subsequent values are provided
elif expr[1].isdigit() and len(expr) > 2:
child = SubElement(current, expr[0])
child.set("item", expr[1])
return _XApiParser.parse(expr[2:], root=root, current=child)
# case: child element exists
else:
child = SubElement(current, expr[0])
return _XApiParser.parse(expr[1:], root=root, current=child)
except NotImplementedError as nie:
raise nie
except UnsupportedError as ue:
raise ue
except Exception:
raise ParseError("Parsing failed")
| [
"xapiparser.exception.ParseError",
"lxml.etree.Element",
"lxml.etree.SubElement",
"xapiparser.exception.UnsupportedError",
"re.search",
"shlex.split"
] | [((467, 483), 'shlex.split', 'shlex.split', (['cmd'], {}), '(cmd)\n', (478, 483), False, 'import shlex\n'), ((1215, 1235), 'lxml.etree.Element', 'Element', (['expr[0][1:]'], {}), '(expr[0][1:])\n', (1222, 1235), False, 'from lxml.etree import Element\n'), ((3470, 3498), 'xapiparser.exception.ParseError', 'ParseError', (['"""Parsing failed"""'], {}), "('Parsing failed')\n", (3480, 3498), False, 'from xapiparser.exception import ParseError\n'), ((824, 880), 'xapiparser.exception.UnsupportedError', 'UnsupportedError', (['"""CLI cmd is not supported in REST API"""'], {}), "('CLI cmd is not supported in REST API')\n", (840, 880), False, 'from xapiparser.exception import UnsupportedError\n'), ((1150, 1191), 'xapiparser.exception.ParseError', 'ParseError', (['f"""Unknown command: {expr[0]}"""'], {}), "(f'Unknown command: {expr[0]}')\n", (1160, 1191), False, 'from xapiparser.exception import ParseError\n'), ((1573, 1609), 're.search', 're.search', (['INDEXED_TAG', 'expr[0][:-1]'], {}), '(INDEXED_TAG, expr[0][:-1])\n', (1582, 1609), False, 'import re\n'), ((2265, 2296), 're.search', 're.search', (['INDEXED_TAG', 'expr[0]'], {}), '(INDEXED_TAG, expr[0])\n', (2274, 2296), False, 'import re\n'), ((1692, 1716), 'lxml.etree.SubElement', 'SubElement', (['current', 'tag'], {}), '(current, tag)\n', (1702, 1716), False, 'from lxml.etree import SubElement\n'), ((2044, 2077), 'lxml.etree.SubElement', 'SubElement', (['current', 'expr[0][:-1]'], {}), '(current, expr[0][:-1])\n', (2054, 2077), False, 'from lxml.etree import SubElement\n'), ((2366, 2390), 'lxml.etree.SubElement', 'SubElement', (['current', 'tag'], {}), '(current, tag)\n', (2376, 2390), False, 'from lxml.etree import SubElement\n'), ((2699, 2727), 'lxml.etree.SubElement', 'SubElement', (['current', 'expr[0]'], {}), '(current, expr[0])\n', (2709, 2727), False, 'from lxml.etree import SubElement\n'), ((1743, 1779), 're.search', 're.search', (['INDEXED_TAG', 'expr[0][:-1]'], {}), '(INDEXED_TAG, expr[0][:-1])\n', (1752, 1779), False, 'import re\n'), ((2413, 2444), 're.search', 're.search', (['INDEXED_TAG', 'expr[0]'], {}), '(INDEXED_TAG, expr[0])\n', (2422, 2444), False, 'import re\n'), ((2961, 2989), 'lxml.etree.SubElement', 'SubElement', (['current', 'expr[0]'], {}), '(current, expr[0])\n', (2971, 2989), False, 'from lxml.etree import SubElement\n'), ((3194, 3222), 'lxml.etree.SubElement', 'SubElement', (['current', 'expr[0]'], {}), '(current, expr[0])\n', (3204, 3222), False, 'from lxml.etree import SubElement\n')] |
import logging
from django.apps import AppConfig
class CrashbinAppConfig(AppConfig):
name = "crashbin_app"
def ready(self) -> None:
logging.basicConfig(level=logging.INFO)
# pylint: disable=unused-import
import crashbin_app.signals # noqa
from crashbin_app import utils
utils.load_plugins()
| [
"crashbin_app.utils.load_plugins",
"logging.basicConfig"
] | [((152, 191), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (171, 191), False, 'import logging\n'), ((324, 344), 'crashbin_app.utils.load_plugins', 'utils.load_plugins', ([], {}), '()\n', (342, 344), False, 'from crashbin_app import utils\n')] |
"""Main module."""
import argparse
import io
import os
import pathlib
import subprocess
import shutil
import sys
from tempfile import mkstemp
import stat
import re
import yaml
import dataclasses as dc
import datetime
import tarfile
import hashlib
import time
from .wheel_utils import parse_wheel_filename
from .utils import *
from .nuitkaflags import *
def fix_win_command(scmd):
'''
Из-за большего удобства, мы допускаем в YAML описывать некоторые пути через
прямые слеши — тогда не надо в кавычки (даже одинарные) заключать,
код выглядит более читаемым. Но виндовые пути, особенно при вызове команд
должны быть с виндовым обратным слешом, поэтому применяем грубую эвристику
чтобы починить слеши на месте.
Это не поможет, если пути ожидаются с обратными слешами где-то в параметрах,
но часто помогает.
'''
if not ' ' in scmd:
return scmd
path_, otherpart = scmd.split(' ', 1)
path_ = path_.replace('/', '\\')
scmd = f'{path_} {otherpart}'
return scmd
class TerrariumAssembler:
'''
Генерация переносимых бинарных дистрибутивов для Python-проектов под Windows
'''
def __init__(self):
self.curdir = os.getcwd()
self.output_dir = os.path.join(self.curdir, 'out')
self.root_dir = None
# self.buildroot_dir = 'C:/docmarking-buildroot'
self.ta_name = 'terrarium_assembler'
vars_ = {
# 'buildroot_dir': self.buildroot_dir
}
ap = argparse.ArgumentParser(description='Create a portable windows application')
ap.add_argument('--debug', default=False, action='store_true', help='Debug version of release')
ap.add_argument('--docs', default=False, action='store_true', help='Output documentation version')
# Основные этапы сборки
self.stages = {
'download-utilities' : 'download binary files',
# 'download-msvc' : 'download MSVC versions',
'checkout' : 'checkout sources',
'install-utilities': 'install downloaded utilities',
'download-wheels': 'download needed WHL-python packages',
'build-wheels': 'compile wheels for our python sources',
'install-wheels': 'Install our and external Python wheels',
'build-projects': 'Compile Python packages to executable',
# 'make-isoexe': 'Also make self-executable install archive and ISO disk',
# 'pack-me' : 'Pack current dir to time prefixed tar.bz2'
}
for stage, desc in self.stages.items():
ap.add_argument('--stage-%s' % stage, default=False, action='store_true', help='Stage for %s ' % desc)
ap.add_argument('--stage-build-and-pack', default='', type=str, help='Install, build and pack')
ap.add_argument('--stage-download-all', default=False, action='store_true', help='Download all — sources, packages')
ap.add_argument('--stage-my-source-changed', default='', type=str, help='Fast rebuild/repack if only pythonsourcechanged')
ap.add_argument('--stage-all', default='', type=str, help='Install, build and pack')
ap.add_argument('--stage-pack', default='', type=str, help='Stage pack to given destination directory')
ap.add_argument('specfile', type=str, help='Specification File')
self.args = args = ap.parse_args()
if self.args.stage_all:
self.args.stage_build_and_pack = self.args.stage_all
self.args.stage_download_all = True
if self.args.stage_build_and_pack:
self.args.stage_install_utilities = True
self.args.stage_build_wheels = True
self.args.stage_install_wheels = True
self.args.stage_build_projects = True
self.args.stage_pack = self.args.stage_build_and_pack
if self.args.stage_my_source_changed:
self.args.stage_checkout = True
self.args.stage_download_wheels = True
self.args.stage_build_wheels = True
self.args.stage_install_wheels = True
self.args.stage_build_projects = True
self.args.stage_pack = self.args.stage_my_source_changed
if self.args.stage_download_all:
self.args.stage_download_rpms = True
self.args.stage_checkout = True
self.args.stage_download_wheels = True
specfile_ = expandpath(args.specfile)
self.root_dir = os.path.split(specfile_)[0]
os.environ['TERRA_SPECDIR'] = os.path.split(specfile_)[0]
self.spec = yaml_load(specfile_, vars_)
self.start_dir = os.getcwd()
pass
def lines2bat(self, name, lines, stage=None):
'''
Записать в батник инструкции сборки,
и если соотвествующий этап активирован в опциях командной строки,
то и выполнить этот командный файл.
'''
import stat
os.chdir(self.curdir)
fname = name + '.bat'
with open(os.path.join(fname), 'w', encoding="utf-8") as lf:
lf.write(f"rem Generated {name} \n")
if stage:
desc = self.stages[stage]
stage_ = stage.replace('_', '-')
lf.write(f'''
rem Stage "{desc}"
rem Automatically called when {self.ta_name} --stage-{stage_} "{self.args.specfile}"
''')
lf.write("\n".join(lines))
st = os.stat(fname)
os.chmod(fname, st.st_mode | stat.S_IEXEC)
if stage:
param = stage.replace('-', '_')
option = "stage_" + param
dict_ = vars(self.args)
if option in dict_:
if dict_[option]:
print("*"*20)
print("Executing ", fname)
print("*"*20)
os.system(fname)
pass
# def build_projects(self):
# '''
# Генерация скриптов бинарной сборки для всех проектов.
# Поддерживается сборка
# * компиляция проектов MVSC
# * компиляция питон-проектов Nuitkой
# * компиляция JS-проектов (обычно скриптов)
# '''
# if not self.nuitkas:
# return
# tmpdir = os.path.join(self.curdir, "tmp/ta")
# tmpdir_ = os.path.relpath(tmpdir)
# bfiles = []
# #First pass
# module2build = {}
# standalone2build = []
# referenced_modules = set()
# for target_ in self.nuitkas.builds:
# if 'module' in target_:
# module2build[target_.module] = target_
# else:
# standalone2build.append(target_)
# if 'modules' in target_:
# referenced_modules |= set(target_.modules)
# for it_ in target_.modules:
# if it_ not in module2build:
# module2build[it_] = edict({'module':it_})
# #processing modules only
# for outputname, target_ in module2build.items():
# block_modules = None
# if 'block_modules' in target_:
# block_modules = target_.block_modules
# nflags = self.nuitkas.get_flags(os.path.join(tmpdir, 'modules', outputname), target_)
# if not nflags:
# continue
# target_dir = os.path.join(tmpdir, outputname + '.dist')
# target_dir_ = os.path.relpath(target_dir, start=self.curdir)
# target_list = target_dir_.replace('.dist', '.list')
# tmp_list = '/tmp/module.list'
# source_dir = dir4mnode(target_)
# flags_ = ''
# if 'flags' in target_:
# flags_ = target_.flags
# lines = []
# build_name = 'build_module_' + outputname
# nuitka_plugins_dir = self.nuitka_plugins_dir
# lines.append("""
# export PATH="/usr/lib64/ccache:$PATH"
# find %(source_dir)s -name "*.py" | xargs -i{} cksum {} > %(tmp_list)s
# if cmp -s %(tmp_list)s %(target_list)s
# then
# echo "Module '%(outputname)s' looks unchanged"
# """ % vars())
# lines.append(R"""
# else
# nice -19 python3 -m nuitka --include-plugin-directory=%(nuitka_plugins_dir)s %(nflags)s %(flags_)s 2>&1 >%(build_name)s.log
# RESULT=$?
# if [ $RESULT == 0 ]; then
# cp %(tmp_list)s %(target_list)s
# fi
# fi
# """ % vars())
# self.fs.folders.append(target_dir)
# if lines:
# self.lines2bat(build_name, lines, None)
# bfiles.append(build_name)
# for target_ in standalone2build:
# srcname = target_.utility
# outputname = target_.utility
# nflags = self.nuitkas.get_flags(tmpdir, target_)
# target_dir = os.path.join(tmpdir, outputname + '.dist')
# target_dir_ = os.path.relpath(target_dir, start=self.curdir)
# src_dir = os.path.relpath(self.src_dir, start=self.curdir)
# src = os.path.join(src_dir, target_.folder, target_.utility) + '.py'
# flags_ = ''
# if 'flags' in target_:
# flags_ = target_.flags
# lines = []
# lines.append("""
# export PATH="/usr/lib64/ccache:$PATH"
# """ % vars(self))
# build_name = 'build_' + srcname
# lines.append(R"""
# time nice -19 python3 -m nuitka %(nflags)s %(flags_)s %(src)s 2>&1 >%(build_name)s.log
# """ % vars())
# self.fs.folders.append(target_dir)
# if "outputname" in target_:
# srcname = target_.outputname
# lines.append(R"""
# mv %(target_dir_)s/%(outputname)s %(target_dir_)s/%(srcname)s
# """ % vars())
# if "modules" in target_:
# force_modules = []
# if 'force_modules' in target_:
# force_modules = target_.force_modules
# for it in target_.modules + force_modules:
# mdir_ = None
# try:
# mdir_ = dir4module(it)
# mdir__ = os.path.relpath(mdir_)
# if len(mdir__)<len(mdir_):
# mdir_ = mdir__
# except:
# pass
# try:
# mdir_ = module2build[it].folder
# except:
# pass
# if mdir_:
# lines.append(R"""
# rsync -rav --exclude=*.py --exclude=*.pyc --exclude=__pycache__ --prune-empty-dirs %(mdir_)s %(target_dir_)s/
# """ % vars())
# force_modules = []
# for it in target_.modules:
# lines.append(R"""
# rsync -av --include=*.so --include=*.bin --exclude=* %(tmpdir_)s/modules/%(it)s/ %(target_dir_)s/.
# rsync -rav %(tmpdir_)s/modules/%(it)s/%(it)s.dist/ %(target_dir_)s/.
# """ % vars())
# self.lines2bat(build_name, lines, None)
# bfiles.append(build_name)
# lines = []
# for b_ in bfiles:
# lines.append("./" + b_ + '.sh')
# self.lines2bat("40-build-projectss", lines, "build-projects")
# pass
# def generate_file_list_from_pips(self, pips):
# '''
# Для заданного списка PIP-пакетов, возвращаем список файлов в этих пакетах, которые нужны нам.
# '''
# file_list = []
# pips_ = [p.split('==')[0] for p in pips]
# import pkg_resources
# for dist in pkg_resources.working_set:
# if dist.key in pips_:
# if dist.has_metadata('RECORD'):
# lines = dist.get_metadata_lines('RECORD')
# paths = [line.split(',')[0] for line in lines]
# paths = [os.path.join(dist.location, p) for p in paths]
# file_list.extend(paths)
# pass
# res_ = [x for x in file_list if self.should_copy(x)]
# return res_
# pass
def generate_checkout_sources(self):
'''
Just checking out sources.
This stage should be done when we have authorization to check them out.
'''
if "projects" not in self.spec:
return
args = self.args
lines = []
lines2 = []
in_src = os.path.relpath(self.spec.src_dir, start=self.curdir)
lines.append(f'mkdir {in_src} ')
already_checkouted = set()
for git_url, td_ in self.spec.projects.items():
git_url, git_branch, path_to_dir_, _ = self.explode_pp_node(git_url, td_)
if path_to_dir_ not in already_checkouted:
probably_package_name = os.path.split(path_to_dir_)[-1]
already_checkouted.add(path_to_dir_)
path_to_dir = os.path.relpath(path_to_dir_, start=self.curdir)
newpath = path_to_dir + '.new'
lines.append(f'rmdir /S /Q "{newpath}"')
scmd = f'''
git --git-dir=/dev/null clone {git_url} {newpath}
pushd {newpath}
git checkout {git_branch}
popd
'''
lines.append(scmd)
lines2.append(f'''
pushd "{path_to_dir}"
git config core.fileMode false
git pull
{self.spec.python_dir}\python -m pip uninstall {probably_package_name} -y
{self.spec.python_dir}\python setup.py develop
popd
''')
# Fucking https://www.virtualbox.org/ticket/19086 + https://www.virtualbox.org/ticket/8761
lines.append(f"""
if exist "{newpath}\" (
rmdir /S /Q "{path_to_dir}"
move "{newpath}" "{path_to_dir}"
)
""")
self.lines2bat("06-checkout", lines, 'checkout')
self.lines2bat("96-pullall", lines2)
pass
def explode_pp_node(self, git_url, td_):
'''
Преобразует неоднозначное описание yaml-ноды пакета в git_url и branch
TODO: переписать, притащено из линуксового TA
'''
git_branch = 'master'
if 'branch' in td_:
git_branch = td_.branch
path_to_dir = os.path.join(self.spec.src_dir, giturl2folder(git_url))
setup_path = path_to_dir
# if 'subdir' in td_:
# subdir = td_.subdir
# setup_path = path_to_dir
return git_url, git_branch, path_to_dir, setup_path
def generate_build_projects(self):
'''
Генерация скриптов бинарной сборки для всех проектов.
Поддерживается сборка
* компиляция проектов MVSC
* компиляция питон-проектов Nuitkой
* компиляция JS-проектов (обычно скриптов)
'''
if "projects" not in self.spec:
return
args = self.args
lines = []
lines2 = []
bfiles = []
in_src = os.path.relpath(self.spec.src_dir, start=self.curdir)
tmpdir = os.path.join(self.spec.buildroot_dir, 'builds')
for git_url, td_ in self.spec.projects.items():
lines = []
git_url, git_branch, path_to_dir_, _ = self.explode_pp_node(git_url, td_)
projname_ = os.path.split(path_to_dir_)[-1]
build_name = 'build_' + projname_
path_to_dir = os.path.relpath(path_to_dir_, start=self.curdir)
if 'nuitkabuild' in td_:
nb_ = td_.nuitkabuild
srcname = nb_.input_py
defaultname = os.path.splitext(srcname)[0]
outputname = defaultname
if "output" in nb_:
outputname = nb_.output
nuitka_flags = nb_.nuitka_flags
nuitka_flags_inherit = self.spec[nuitka_flags.inherit]
# Пока считаем, что наследоваться можно только один раз
assert 'inherit' not in nuitka_flags_inherit
nfm_ = edict({**nuitka_flags_inherit})
for group in nuitka_flags:
if group in nfm_:
nfm_[group] = list(set(nfm_[group]).union(set(nuitka_flags[group])))
else:
nfm_[group] = nuitka_flags[group]
del nfm_['inherit']
nf_ = NuitkaFlags(**nfm_)
nflags_ = nf_.get_flags(tmpdir, nfm_)
target_dir = os.path.join(tmpdir, outputname + '.dist')
target_dir_ = os.path.relpath(target_dir, start=self.curdir)
src = os.path.join(path_to_dir, srcname)
flags_ = nflags_
lines.append(fr'''
{self.spec.python_dir}\python -m nuitka {nflags_} {src} 2>&1 > {build_name}.log
''')
if defaultname != outputname:
lines.append(fr'''
move {tmpdir}\{defaultname}.dist\{defaultname}.exe {tmpdir}\{defaultname}.dist\{outputname}.exe
''')
lines.append(fr'''
{self.spec.python_dir}\python -m pip freeze > {tmpdir}\{defaultname}.dist\{outputname}-pip-freeze.txt
''')
if 'copy' in nb_:
for it_ in nb_.copy:
is_file = os.path.splitext(it_)[1] != ''
cp_ = 'copy /-y' if is_file else 'xcopy /I /E /Y /D'
lines.append(fr'echo n | {cp_} "{it_}" {tmpdir}\{defaultname}.dist')
if 'copy_and_rename' in nb_:
for to_, from_ in nb_.copy_and_rename.items():
from_is_file = os.path.splitext(from_)[1] != ''
to_ = to_.replace('/', '\\')
from_ = from_.replace('/', '\\')
to_dir = os.path.split(to_)[0]
lines.append(fr'mkdir {tmpdir}\{defaultname}.dist\{to_dir}')
cp_ = 'copy /-y' if from_is_file else 'xcopy /I /E /Y /D'
scmd = fr'echo n | {cp_} "{from_}" "{tmpdir}\{defaultname}.dist\{to_}"'
lines.append(scmd)
if 'jsbuild' in td_:
build = td_.jsbuild
folder_ = path_to_dir_
if isinstance(build, dict) and 'folder' in build:
folder_ = os.path.join(folder_, build.folder)
outdir_ = fr'{tmpdir}\{projname_}-jsbuild'
lines.append(fR"mkdir {outdir_}")
for file_ in os.listdir(folder_):
if file_.endswith('.js'):
infile = os.path.join(folder_, file_)
outfile = os.path.join(outdir_, os.path.splitext(file_)[0] + '.exe')
lines.append(fR"""
C:\Windows\Microsoft.NET\Framework\v4.0.30319\jsc /out:{outfile} {infile}
""")
pass
if 'vsbuild' in td_:
build = td_.vsbuild
folder_ = path_to_dir_
if isinstance(build, dict) and 'folder' in build:
folder_ = os.path.join(folder_, build.folder)
projectfile_ = build.projfile
projectname_ = os.path.splitext(projectfile_)[0]
lines.append(R"""
call "C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\Common7\Tools\VsDevCmd.bat"
""" % vars(self))
if isinstance(build.platforms, list):
for platform_ in build.platforms:
odir_ = fr"{tmpdir}\{projectname_}-vsbuild\{platform_}"
lines.append(fR"""
msbuild /p:Configuration="{build.configuration}" /p:Platform="{platform_}" {folder_}\{projectfile_}
msbuild /p:OutputPath="{odir_}" /p:OutDir="{odir_}\\" /p:Configuration="{build.configuration}" /p:Platform="{platform_}" {folder_}\{projectfile_}
""")
else:
platform_ = build.platforms
odir_ = fr"{tmpdir}\{projectname_}-vsbuild\{platform_}"
lines.append(fR"""
msbuild /p:Configuration="{build.configuration}" /p:Platform="{platform_}" {folder_}\{projectfile_}
msbuild /p:OutputPath="{odir_}" /p:OutDir="{odir_}\\" /p:Configuration="{build.configuration}" /p:Platform="{platform_}" {folder_}\{projectfile_}
""")
if lines:
self.lines2bat(build_name, lines, None)
bfiles.append(build_name)
pass
lines = []
for b_ in bfiles:
lines.append("call " + b_ + '.bat')
self.lines2bat("40-build-projects", lines, "build-projects")
pass
def generate_download(self):
'''
Генерация скачивания бинарных утилит.
Практически всего необходимого, кроме зависимостей питон-пакетов, это отдельно.
'''
root_dir = self.root_dir
args = self.args
packages = []
lines = []
in_bin = os.path.relpath(self.spec.bin_dir, start=self.curdir)
def download_to(url_, to_, force_dir=False):
dir2download = to_
scmd = f'wget --no-check-certificate -P {dir2download} -c {url_} '
if os.path.splitext(to_) and not force_dir:
dir2download, filename = os.path.split(to_)
lines.append(f'mkdir {dir2download}'.replace('/','\\'))
scmd = f'wget --no-check-certificate -O {dir2download}/{filename} -c {url_} '
lines.append(scmd)
for to_, nd_ in self.spec.download.items():
if isinstance(nd_, list):
for url_ in nd_:
download_to(url_, to_, force_dir=True)
if isinstance(nd_, str):
download_to(nd_, to_)
for name_, it_ in self.spec.download_and_install.items():
if isinstance(it_, dict):
msvc_components = ''
if 'download' in it_:
download_ = it_.download
if isinstance(download_, dict):
for to_, nd_ in download_.items():
download_to(nd_, to_)
if 'components' in it_:
msvc_components = " ".join(["--add " + comp for comp in it_.components])
if 'postdownload' in it_:
scmd = it_.postdownload.format(**vars())
scmd = fix_win_command(scmd)
lines.append(scmd)
self.lines2bat("02-download-utilities", lines, "download-utilities")
pass
def generate_install(self):
'''
Генерация командного скрипта установки всего скачанного,
кроме питон-пакетов.
'''
root_dir = self.root_dir
args = self.args
packages = []
lines = []
in_bin = os.path.relpath(self.spec.bin_dir, start=self.curdir)
for name_, it_ in self.spec.download_and_install.items():
if isinstance(it_, dict):
msvc_components = ''
artefact = None
if 'download' in it_:
download_ = it_.download
if isinstance(download_, dict):
artefact = list(download_.keys())[-1]
if not artefact:
continue
if 'unzip' in it_:
to_ = it_.unzip
scmd = f'''powershell -command "Expand-Archive -Force '{artefact}' '{to_}'" '''
#scmd = f'''tar -xf "{artefact}" --directory "{to_}" '''
lines.append(scmd)
if 'unzip7' in it_:
to_ = it_.unzip7
scmd = f'7z -y x {artefact} -o{to_}'
lines.append(scmd)
if 'target' in it_:
to_ = it_.target
scmds = f'''
msiexec.exe /I {artefact} /QB-! INSTALLDIR="{to_}" TargetDir="{to_}"
set PATH={to_};%PATH%'''.split('\n')
lines += scmds
if 'components' in it_:
msvc_components = " ".join(["--add " + comp for comp in it_.components])
if 'run' in it_:
for line_ in it_.run.split("\n"):
scmd = line_.format(**vars())
lines.append(fix_win_command(scmd))
self.lines2bat("02-install-utilities", lines, "install-utilities")
pass
def write_sandbox(self):
'''
Генерация Windows-песочницы (облегченной виртуальной машины)
для чистой сборки в нулевой системе.
'''
root_dir = self.root_dir
with open('ta-sandbox.wsb', 'wt', encoding='utf-8') as lf:
lf.write(fr'''
<Configuration><MappedFolders>
<MappedFolder><HostFolder>{self.root_dir}</HostFolder>
<SandboxFolder>C:\Users\WDAGUtilityAccount\Desktop\distro</SandboxFolder>
<ReadOnly>false</ReadOnly></MappedFolder>
<MappedFolder><HostFolder>{self.root_dir}\out</HostFolder>
<SandboxFolder>C:\Users\WDAGUtilityAccount\Desktop\out</SandboxFolder>
<ReadOnly>false</ReadOnly></MappedFolder>
</MappedFolders>
<LogonCommand>
<Command>C:\Users\WDAGUtilityAccount\Desktop\distro\99-install-tools.bat</Command>
</LogonCommand>
</Configuration>
''')
if not os.path.exists(self.output_dir):
os.mkdir(self.output_dir)
scmd = R"""
@"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command " [System.Net.ServicePointManager]::SecurityProtocol = 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"
choco install -y far procmon wget
"""
self.lines2bat("99-install-tools", [scmd])
pass
def generate_download_wheels(self):
'''
Генерация скачивания всех пакетов по зависимостям.
'''
os.chdir(self.curdir)
root_dir = self.root_dir
args = self.args
lines = []
wheel_dir = self.spec.depswheel_dir.replace("/", "\\")
lines.append(fr'''
rmdir /S /Q {wheel_dir}\*
''')
for pp in self.spec.python_packages:
scmd = fr'echo "** Downloading wheel for {pp} **"'
lines.append(scmd)
scmd = fr"{self.spec.python_dir}\python -m pip download {pp} --dest {wheel_dir} "
lines.append(scmd)
for git_url, td_ in self.spec.projects.items():
if 'pybuild' not in td_:
continue
git_url, git_branch, path_to_dir_, _ = self.explode_pp_node(git_url, td_)
probably_package_name = os.path.split(path_to_dir_)[-1]
path_to_dir = os.path.relpath(path_to_dir_, start=self.curdir)
scmd = fr'echo "** Downloading dependend wheels for {path_to_dir} **"'
lines.append(scmd)
setup_path = path_to_dir
path_ = os.path.relpath(setup_path, start=self.curdir)
if os.path.exists(setup_path):
scmd = fr"{self.spec.python_dir}\python -m pip download {setup_path} --dest {wheel_dir} "
lines.append(fix_win_command(scmd))
pass
self.lines2bat("07-download-wheels", lines, "download-wheels")
pass
def generate_build_wheels(self):
'''
Генерация сборки пакетов по всем нашим питон модулям.
'''
os.chdir(self.curdir)
lines = []
python_dir = self.spec.python_dir.replace("/", "\\")
wheel_dir = self.spec.ourwheel_dir.replace("/", "\\")
wheelpath = wheel_dir
relwheelpath = os.path.relpath(wheelpath, start=self.curdir)
lines.append(fr"rmdir /S /Q {relwheelpath}\*.*")
for git_url, td_ in self.spec.projects.items():
if 'pybuild' not in td_:
continue
git_url, git_branch, path_to_dir_, _ = self.explode_pp_node(git_url, td_)
probably_package_name = os.path.split(path_to_dir_)[-1]
path_to_dir = os.path.relpath(path_to_dir_, start=self.curdir)
relwheelpath = os.path.relpath(wheelpath, start=path_to_dir_)
setup_path = path_to_dir
scmd = fr'echo "** Building wheel for {setup_path} **"'
lines.append(scmd)
setup_path = path_to_dir
path_ = os.path.relpath(setup_path, start=self.curdir)
if os.path.exists(setup_path):
scmd = "pushd %s" % (path_to_dir)
lines.append(scmd)
relwheelpath = os.path.relpath(wheelpath, start=path_to_dir)
scmd = fr"{python_dir}\python setup.py bdist_wheel -d {relwheelpath} "
lines.append(fix_win_command(scmd))
lines.append('popd')
pass
self.lines2bat("09-build-wheels", lines, "build-wheels")
pass
def generate_install_wheels(self):
os.chdir(self.curdir)
lines = []
pl_ = self.get_wheel_list_to_install()
#--use-feature=2020-resolver
scmd = fr'{self.spec.python_dir}/python -m pip install --no-deps --force-reinstall --no-dependencies --ignore-installed %s ' % (" ".join(pl_))
lines.append(fix_win_command(scmd))
for p_ in pl_:
scmd = fr'{self.spec.python_dir}/python -m pip install --no-deps --force-reinstall --ignore-installed %s ' % p_
lines.append(fix_win_command(scmd))
self.lines2bat("15-install-wheels", lines, "install-wheels")
pass
def get_wheel_list_to_install(self):
'''
Выбираем список wheel-пакетов для инсталляции, руководствуясь эвристиками:
* если несколько пакетов разных версий — берем большую версию
* Приоритеты пакетов таковы:
* скачанные насильно пакеты в extwheel_dir
* наши пакеты, собранные в ourwheel_dir
* пакеты, скачанные по зависимостям
* наши пакеты имеют больший приоритет, перед
'''
from packaging import version
os.chdir(self.curdir)
def get_most_new_wheel_list(wheels_dir):
wheels_dict = {}
if os.path.exists(wheels_dir):
for whl in [os.path.join(wheels_dir, whl)
for whl in os.listdir(wheels_dir)
if whl.endswith('.whl') or whl.endswith('.tar.gz') or whl.endswith('.tar.bz2')]:
pw_ = parse_wheel_filename(whl)
name_ = pw_.project
if name_ not in wheels_dict:
wheels_dict[name_] = whl
else:
if version.parse(parse_wheel_filename(whl).version) > version.parse(parse_wheel_filename(wheels_dict[name_]).version):
wheels_dict[name_] = whl
return wheels_dict
deps_ = get_most_new_wheel_list(self.spec.depswheel_dir)
exts_ = get_most_new_wheel_list(self.spec.extwheel_dir)
ours_ = get_most_new_wheel_list(self.spec.ourwheel_dir)
wheels_dict = {**deps_, **exts_, **ours_}
return list(wheels_dict.values())
# def pack_me(self):
# time_prefix = datetime.datetime.now().replace(microsecond=0).isoformat().replace(':', '-')
# parentdir, curname = os.path.split(self.curdir)
# disabled_suffix = curname + '.tar.bz2'
# banned_ext = ['.old', '.iso', disabled_suffix]
# banned_start = ['tmp']
# banned_mid = ['/out/', '/wtf/', '/.vagrant/', '/.git/']
# def filter_(tarinfo):
# for s in banned_ext:
# if tarinfo.name.endswith(s):
# print(tarinfo.name)
# return None
# for s in banned_start:
# if tarinfo.name.startswith(s):
# print(tarinfo.name)
# return None
# for s in banned_mid:
# if s in tarinfo.name:
# print(tarinfo.name)
# return None
# return tarinfo
# tbzname = os.path.join(self.curdir,
# "%(time_prefix)s-%(curname)s.tar.bz2" % vars())
# tar = tarfile.open(tbzname, "w:bz2")
# tar.add(self.curdir, recursive=True, filter=filter_)
# tar.close()
def generate_output(self):
lines = []
output_ = self.spec.output
out_dir = output_.distro_dir.replace('/', '\\')
lines.append(fR'rmdir /S /Q "{out_dir}" ')
lines.append(fR'mkdir "{out_dir}" ')
buildroot = self.spec.buildroot_dir
srcdir = self.spec.src_dir
bindir = self.spec.bin_dir
for folder, sources_ in output_.folders.items():
if isinstance(sources_, str):
sources_ = [s.strip() for s in sources_.strip().split("\n")]
dst_folder = (out_dir + os.path.sep + folder).replace('/', os.path.sep)
lines.append(fR"""
mkdir {dst_folder}
""")
for from_ in sources_:
from__ = from_
from__ = eval(f"fR'{from_}'")
if not os.path.splitext(from__)[1]:
from__ += R'\*'
lines.append(fR"""
echo n | xcopy /I /S /Y "{from__}" {dst_folder}\
""")
self.lines2bat('50-output', lines)
pass
def process(self):
'''
Основная процедура генерации проекта,
и возможно его выполнения, если соответствующие опции
командной строки активированы.
'''
self.write_sandbox()
self.generate_build_projects()
self.generate_download()
self.generate_install()
self.generate_checkout_sources()
self.generate_download_wheels()
for _ in range(2):
self.generate_build_wheels()
self.generate_install_wheels()
self.generate_output()
pass
| [
"os.path.join",
"os.listdir",
"os.getcwd",
"os.system",
"os.path.splitext",
"argparse.ArgumentParser",
"os.mkdir",
"os.chmod",
"os.path.exists",
"os.path.split",
"os.chdir",
"os.stat",
"os.path.relpath"
] | [((1199, 1210), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1208, 1210), False, 'import os\n'), ((1237, 1269), 'os.path.join', 'os.path.join', (['self.curdir', '"""out"""'], {}), "(self.curdir, 'out')\n", (1249, 1269), False, 'import os\n'), ((1502, 1578), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Create a portable windows application"""'}), "(description='Create a portable windows application')\n", (1525, 1578), False, 'import argparse\n'), ((4624, 4635), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (4633, 4635), False, 'import os\n'), ((4916, 4937), 'os.chdir', 'os.chdir', (['self.curdir'], {}), '(self.curdir)\n', (4924, 4937), False, 'import os\n'), ((5395, 5409), 'os.stat', 'os.stat', (['fname'], {}), '(fname)\n', (5402, 5409), False, 'import os\n'), ((5418, 5460), 'os.chmod', 'os.chmod', (['fname', '(st.st_mode | stat.S_IEXEC)'], {}), '(fname, st.st_mode | stat.S_IEXEC)\n', (5426, 5460), False, 'import os\n'), ((12469, 12522), 'os.path.relpath', 'os.path.relpath', (['self.spec.src_dir'], {'start': 'self.curdir'}), '(self.spec.src_dir, start=self.curdir)\n', (12484, 12522), False, 'import os\n'), ((14896, 14949), 'os.path.relpath', 'os.path.relpath', (['self.spec.src_dir'], {'start': 'self.curdir'}), '(self.spec.src_dir, start=self.curdir)\n', (14911, 14949), False, 'import os\n'), ((14967, 15014), 'os.path.join', 'os.path.join', (['self.spec.buildroot_dir', '"""builds"""'], {}), "(self.spec.buildroot_dir, 'builds')\n", (14979, 15014), False, 'import os\n'), ((20934, 20987), 'os.path.relpath', 'os.path.relpath', (['self.spec.bin_dir'], {'start': 'self.curdir'}), '(self.spec.bin_dir, start=self.curdir)\n', (20949, 20987), False, 'import os\n'), ((22798, 22851), 'os.path.relpath', 'os.path.relpath', (['self.spec.bin_dir'], {'start': 'self.curdir'}), '(self.spec.bin_dir, start=self.curdir)\n', (22813, 22851), False, 'import os\n'), ((25998, 26019), 'os.chdir', 'os.chdir', (['self.curdir'], {}), '(self.curdir)\n', (26006, 26019), False, 'import os\n'), ((27582, 27603), 'os.chdir', 'os.chdir', (['self.curdir'], {}), '(self.curdir)\n', (27590, 27603), False, 'import os\n'), ((27801, 27846), 'os.path.relpath', 'os.path.relpath', (['wheelpath'], {'start': 'self.curdir'}), '(wheelpath, start=self.curdir)\n', (27816, 27846), False, 'import os\n'), ((29140, 29161), 'os.chdir', 'os.chdir', (['self.curdir'], {}), '(self.curdir)\n', (29148, 29161), False, 'import os\n'), ((30268, 30289), 'os.chdir', 'os.chdir', (['self.curdir'], {}), '(self.curdir)\n', (30276, 30289), False, 'import os\n'), ((4453, 4477), 'os.path.split', 'os.path.split', (['specfile_'], {}), '(specfile_)\n', (4466, 4477), False, 'import os\n'), ((4519, 4543), 'os.path.split', 'os.path.split', (['specfile_'], {}), '(specfile_)\n', (4532, 4543), False, 'import os\n'), ((15309, 15357), 'os.path.relpath', 'os.path.relpath', (['path_to_dir_'], {'start': 'self.curdir'}), '(path_to_dir_, start=self.curdir)\n', (15324, 15357), False, 'import os\n'), ((25327, 25358), 'os.path.exists', 'os.path.exists', (['self.output_dir'], {}), '(self.output_dir)\n', (25341, 25358), False, 'import os\n'), ((25372, 25397), 'os.mkdir', 'os.mkdir', (['self.output_dir'], {}), '(self.output_dir)\n', (25380, 25397), False, 'import os\n'), ((26828, 26876), 'os.path.relpath', 'os.path.relpath', (['path_to_dir_'], {'start': 'self.curdir'}), '(path_to_dir_, start=self.curdir)\n', (26843, 26876), False, 'import os\n'), ((27078, 27124), 'os.path.relpath', 'os.path.relpath', (['setup_path'], {'start': 'self.curdir'}), '(setup_path, start=self.curdir)\n', (27093, 27124), False, 'import os\n'), ((27140, 27166), 'os.path.exists', 'os.path.exists', (['setup_path'], {}), '(setup_path)\n', (27154, 27166), False, 'import os\n'), ((28205, 28253), 'os.path.relpath', 'os.path.relpath', (['path_to_dir_'], {'start': 'self.curdir'}), '(path_to_dir_, start=self.curdir)\n', (28220, 28253), False, 'import os\n'), ((28281, 28327), 'os.path.relpath', 'os.path.relpath', (['wheelpath'], {'start': 'path_to_dir_'}), '(wheelpath, start=path_to_dir_)\n', (28296, 28327), False, 'import os\n'), ((28552, 28598), 'os.path.relpath', 'os.path.relpath', (['setup_path'], {'start': 'self.curdir'}), '(setup_path, start=self.curdir)\n', (28567, 28598), False, 'import os\n'), ((28614, 28640), 'os.path.exists', 'os.path.exists', (['setup_path'], {}), '(setup_path)\n', (28628, 28640), False, 'import os\n'), ((30385, 30411), 'os.path.exists', 'os.path.exists', (['wheels_dir'], {}), '(wheels_dir)\n', (30399, 30411), False, 'import os\n'), ((4987, 5006), 'os.path.join', 'os.path.join', (['fname'], {}), '(fname)\n', (4999, 5006), False, 'import os\n'), ((12952, 13000), 'os.path.relpath', 'os.path.relpath', (['path_to_dir_'], {'start': 'self.curdir'}), '(path_to_dir_, start=self.curdir)\n', (12967, 13000), False, 'import os\n'), ((15205, 15232), 'os.path.split', 'os.path.split', (['path_to_dir_'], {}), '(path_to_dir_)\n', (15218, 15232), False, 'import os\n'), ((16380, 16422), 'os.path.join', 'os.path.join', (['tmpdir', "(outputname + '.dist')"], {}), "(tmpdir, outputname + '.dist')\n", (16392, 16422), False, 'import os\n'), ((16453, 16499), 'os.path.relpath', 'os.path.relpath', (['target_dir'], {'start': 'self.curdir'}), '(target_dir, start=self.curdir)\n', (16468, 16499), False, 'import os\n'), ((16523, 16557), 'os.path.join', 'os.path.join', (['path_to_dir', 'srcname'], {}), '(path_to_dir, srcname)\n', (16535, 16557), False, 'import os\n'), ((18391, 18410), 'os.listdir', 'os.listdir', (['folder_'], {}), '(folder_)\n', (18401, 18410), False, 'import os\n'), ((21167, 21188), 'os.path.splitext', 'os.path.splitext', (['to_'], {}), '(to_)\n', (21183, 21188), False, 'import os\n'), ((21249, 21267), 'os.path.split', 'os.path.split', (['to_'], {}), '(to_)\n', (21262, 21267), False, 'import os\n'), ((26770, 26797), 'os.path.split', 'os.path.split', (['path_to_dir_'], {}), '(path_to_dir_)\n', (26783, 26797), False, 'import os\n'), ((28147, 28174), 'os.path.split', 'os.path.split', (['path_to_dir_'], {}), '(path_to_dir_)\n', (28160, 28174), False, 'import os\n'), ((28758, 28803), 'os.path.relpath', 'os.path.relpath', (['wheelpath'], {'start': 'path_to_dir'}), '(wheelpath, start=path_to_dir)\n', (28773, 28803), False, 'import os\n'), ((5799, 5815), 'os.system', 'os.system', (['fname'], {}), '(fname)\n', (5808, 5815), False, 'import os\n'), ((12837, 12864), 'os.path.split', 'os.path.split', (['path_to_dir_'], {}), '(path_to_dir_)\n', (12850, 12864), False, 'import os\n'), ((15502, 15527), 'os.path.splitext', 'os.path.splitext', (['srcname'], {}), '(srcname)\n', (15518, 15527), False, 'import os\n'), ((18216, 18251), 'os.path.join', 'os.path.join', (['folder_', 'build.folder'], {}), '(folder_, build.folder)\n', (18228, 18251), False, 'import os\n'), ((19019, 19054), 'os.path.join', 'os.path.join', (['folder_', 'build.folder'], {}), '(folder_, build.folder)\n', (19031, 19054), False, 'import os\n'), ((19140, 19170), 'os.path.splitext', 'os.path.splitext', (['projectfile_'], {}), '(projectfile_)\n', (19156, 19170), False, 'import os\n'), ((30441, 30470), 'os.path.join', 'os.path.join', (['wheels_dir', 'whl'], {}), '(wheels_dir, whl)\n', (30453, 30470), False, 'import os\n'), ((18491, 18519), 'os.path.join', 'os.path.join', (['folder_', 'file_'], {}), '(folder_, file_)\n', (18503, 18519), False, 'import os\n'), ((30515, 30537), 'os.listdir', 'os.listdir', (['wheels_dir'], {}), '(wheels_dir)\n', (30525, 30537), False, 'import os\n'), ((33472, 33496), 'os.path.splitext', 'os.path.splitext', (['from__'], {}), '(from__)\n', (33488, 33496), False, 'import os\n'), ((17683, 17701), 'os.path.split', 'os.path.split', (['to_'], {}), '(to_)\n', (17696, 17701), False, 'import os\n'), ((17154, 17175), 'os.path.splitext', 'os.path.splitext', (['it_'], {}), '(it_)\n', (17170, 17175), False, 'import os\n'), ((17507, 17530), 'os.path.splitext', 'os.path.splitext', (['from_'], {}), '(from_)\n', (17523, 17530), False, 'import os\n'), ((18576, 18599), 'os.path.splitext', 'os.path.splitext', (['file_'], {}), '(file_)\n', (18592, 18599), False, 'import os\n')] |
import unittest
from gruve import io
class TestIO(unittest.TestCase):
def test_dotEnv_exists(self):
actual = list(io.apiKeys())
self.assertGreater(len(actual), 0)
def test_getApiKey_present(self):
actual = io.getApiKey('OPENFDA_API_KEY')
self.assertTrue(actual)
def test_getApiKey_missing(self):
self.assertRaises(AssertionError, io.getApiKey, 'SOME_OTHER_KEY')
if __name__ == '__main__':
unittest.main()
| [
"gruve.io.apiKeys",
"gruve.io.getApiKey",
"unittest.main"
] | [((449, 464), 'unittest.main', 'unittest.main', ([], {}), '()\n', (462, 464), False, 'import unittest\n'), ((240, 271), 'gruve.io.getApiKey', 'io.getApiKey', (['"""OPENFDA_API_KEY"""'], {}), "('OPENFDA_API_KEY')\n", (252, 271), False, 'from gruve import io\n'), ((127, 139), 'gruve.io.apiKeys', 'io.apiKeys', ([], {}), '()\n', (137, 139), False, 'from gruve import io\n')] |
### 第二批数据:1:敏感语料(短语) 2:微博评论原文(senti100k,处理特殊字符),各6754条,测试集比例0.1
# 处理方式:
# 1.去掉表情符号,如:[哈哈] [鼓掌] [good]
# 2.去掉话题标记,如:##
# 3.去掉转发评论重的用户名等
# 4.去掉一些网址、无意义的词,如:转发微博等。
import pandas as pd
import re
def clean(text):
text = re.sub(r"(回复)?(//)?\s*@\S*?\s*(:| |$)", " ", text) # 去除正文中的@和回复/转发中的用户名
text = re.sub(r"\[\S+\]", "", text) # 去除表情符号
text = re.sub(r"#\S+#", "", text) # 去除话题内容
text = re.sub(r"【\S+】", "", text) # 去除标题
URL_REGEX = re.compile(
r'(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»“”‘’]))',
re.IGNORECASE)
text = re.sub(URL_REGEX, "", text) # 去除网址
text = text.replace("转发微博", "") # 去除无意义的词语
text = re.sub(r"\s+", " ", text) # 合并正文中过多的空格
return text.strip()
df_1 = pd.read_excel('/Users/leo/Data/项目数据/文德数慧-文本内容审核/分类实验/数据/网络信息语料 文德 20210122.xlsx', sheet_name='测试集')
df_0 = pd.read_csv('/Users/leo/Data/项目数据/文德数慧-文本内容审核/分类实验/数据/weibo_senti_100k.csv')
### proc weibo
df_0 = df_0[:100]
df_0['review_proc'] = ''
for i in range(len(df_0)):
df_0.loc[i,'review_proc'] = clean(df_0.iloc[i]['review'])
df_0[['label','review_proc']].to_csv('/Users/leo/Data/项目数据/文德数慧-文本内容审核/分类实验/数据/weibo_senti_100k_proc.csv',index=False)
exit()
###
df_0 = df_0.sample(n=10000).reset_index(drop=True) # 有一些处理之后为空的,不要
data = pd.DataFrame(columns=['label','text'])
count = 0
for i in range(len(df_0)):
label = 0
text = clean(df_0.iloc[i]['review'])
if text:
count += 1
data = data.append(pd.DataFrame({'label':[label],'text':[clean(text)]}),ignore_index=True)
if count == 6754:
break
for i in range(len(df_1)):
label = 1
text = df_1.iloc[i]['内容']
data = data.append(pd.DataFrame({'label':[label],'text':[text]}),ignore_index=True)
assert len(data) == 6754*2
data['label'] = data['label'].astype(int)
data = data.sample(frac=1).reset_index(drop=True)
data_test = data[:int(len(df_1)*0.2)]
data_train = data[int(len(df_1)*0.2):]
data_train.to_csv(r"/Users/leo/Data/项目数据/文德数慧-文本内容审核/分类实验/数据/data_bert/v2/train.tsv",sep='\t',header=False,index=False)
data_test.to_csv(r"/Users/leo/Data/项目数据/文德数慧-文本内容审核/分类实验/数据/data_bert/v2/test.tsv",sep='\t',header=False,index=False)
data_test.to_csv(r"/Users/leo/Data/项目数据/文德数慧-文本内容审核/分类实验/数据/data_bert/v2/dev.tsv",sep='\t',header=False,index=False)
| [
"re.compile",
"pandas.read_excel",
"pandas.read_csv",
"pandas.DataFrame",
"re.sub"
] | [((885, 993), 'pandas.read_excel', 'pd.read_excel', (['"""/Users/leo/Data/项目数据/文德数慧-文本内容审核/分类实验/数据/网络信息语料 文德 20210122.xlsx"""'], {'sheet_name': '"""测试集"""'}), "(\n '/Users/leo/Data/项目数据/文德数慧-文本内容审核/分类实验/数据/网络信息语料 文德 20210122.xlsx',\n sheet_name='测试集')\n", (898, 993), True, 'import pandas as pd\n'), ((992, 1068), 'pandas.read_csv', 'pd.read_csv', (['"""/Users/leo/Data/项目数据/文德数慧-文本内容审核/分类实验/数据/weibo_senti_100k.csv"""'], {}), "('/Users/leo/Data/项目数据/文德数慧-文本内容审核/分类实验/数据/weibo_senti_100k.csv')\n", (1003, 1068), True, 'import pandas as pd\n'), ((1426, 1465), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['label', 'text']"}), "(columns=['label', 'text'])\n", (1438, 1465), True, 'import pandas as pd\n'), ((222, 274), 're.sub', 're.sub', (['"""(回复)?(//)?\\\\s*@\\\\S*?\\\\s*(:| |$)"""', '""" """', 'text'], {}), "('(回复)?(//)?\\\\s*@\\\\S*?\\\\s*(:| |$)', ' ', text)\n", (228, 274), False, 'import re\n'), ((306, 336), 're.sub', 're.sub', (['"""\\\\[\\\\S+\\\\]"""', '""""""', 'text'], {}), "('\\\\[\\\\S+\\\\]', '', text)\n", (312, 336), False, 'import re\n'), ((360, 386), 're.sub', 're.sub', (['"""#\\\\S+#"""', '""""""', 'text'], {}), "('#\\\\S+#', '', text)\n", (366, 386), False, 'import re\n'), ((412, 438), 're.sub', 're.sub', (['"""【\\\\S+】"""', '""""""', 'text'], {}), "('【\\\\S+】', '', text)\n", (418, 438), False, 'import re\n'), ((467, 709), 're.compile', 're.compile', (['"""(?i)\\\\b((?:https?://|www\\\\d{0,3}[.]|[a-z0-9.\\\\-]+[.][a-z]{2,4}/)(?:[^\\\\s()<>]+|\\\\(([^\\\\s()<>]+|(\\\\([^\\\\s()<>]+\\\\)))*\\\\))+(?:\\\\(([^\\\\s()<>]+|(\\\\([^\\\\s()<>]+\\\\)))*\\\\)|[^\\\\s`!()\\\\[\\\\]{};:\\\\\'".,<>?«»“”‘’]))"""', 're.IGNORECASE'], {}), '(\n \'(?i)\\\\b((?:https?://|www\\\\d{0,3}[.]|[a-z0-9.\\\\-]+[.][a-z]{2,4}/)(?:[^\\\\s()<>]+|\\\\(([^\\\\s()<>]+|(\\\\([^\\\\s()<>]+\\\\)))*\\\\))+(?:\\\\(([^\\\\s()<>]+|(\\\\([^\\\\s()<>]+\\\\)))*\\\\)|[^\\\\s`!()\\\\[\\\\]{};:\\\\\\\'".,<>?«»“”‘’]))\'\n , re.IGNORECASE)\n', (477, 709), False, 'import re\n'), ((708, 735), 're.sub', 're.sub', (['URL_REGEX', '""""""', 'text'], {}), "(URL_REGEX, '', text)\n", (714, 735), False, 'import re\n'), ((813, 838), 're.sub', 're.sub', (['"""\\\\s+"""', '""" """', 'text'], {}), "('\\\\s+', ' ', text)\n", (819, 838), False, 'import re\n'), ((1828, 1876), 'pandas.DataFrame', 'pd.DataFrame', (["{'label': [label], 'text': [text]}"], {}), "({'label': [label], 'text': [text]})\n", (1840, 1876), True, 'import pandas as pd\n')] |
# -*- coding: utf-8 -*-
"""
=============================
Aligning two matrices with the procrustes function
=============================
In this example, we load in some synthetic data, rotate it, and then use the
procustes function to get the datasets back in alignment. The procrustes
function uses linear transformations to project a source matrix into the
space of a target matrix.
"""
# Code source: <NAME>
# License: MIT
# import
import hypertools as hyp
import numpy as np
import scipy
# load example data
geo = hyp.load('spiral')
geo.plot(title='Before Alignment')
# use procrusted to align the data
source, target = geo.get_data()
aligned = [hyp.tools.procrustes(source, target), target]
# after alignment
hyp.plot(aligned, ['-','--'], title='After alignment')
| [
"hypertools.plot",
"hypertools.tools.procrustes",
"hypertools.load"
] | [((526, 544), 'hypertools.load', 'hyp.load', (['"""spiral"""'], {}), "('spiral')\n", (534, 544), True, 'import hypertools as hyp\n'), ((724, 779), 'hypertools.plot', 'hyp.plot', (['aligned', "['-', '--']"], {'title': '"""After alignment"""'}), "(aligned, ['-', '--'], title='After alignment')\n", (732, 779), True, 'import hypertools as hyp\n'), ((659, 695), 'hypertools.tools.procrustes', 'hyp.tools.procrustes', (['source', 'target'], {}), '(source, target)\n', (679, 695), True, 'import hypertools as hyp\n')] |
#!/usr/bin/env python
import re
import sys
import ez_setup
ez_setup.use_setuptools()
from setuptools import setup, Extension
define_macros = []
import ctypes
if ctypes.sizeof(ctypes.c_double) == 8:
dv = ctypes.c_double(9006104071832581.0)
iv = ctypes.cast(ctypes.pointer(dv), ctypes.POINTER(ctypes.c_uint64))
if iv.contents.value == 0x433fff0102030405:
define_macros.append(('BLIST_FLOAT_RADIX_SORT', 1))
with open('blist/__init__.py') as f:
line = f.readline()
match = re.search(r'= *[\'"](.*)[\'"]', line)
version = match.group(1)
setup(name='blist',
version=version,
description='a list-like type with better asymptotic performance and similar performance on small lists',
author='Stutzbach Enterprises, LLC',
author_email='<EMAIL>',
url='http://stutzbachenterprises.com/blist/',
license = "BSD",
keywords = "blist list b+tree btree fast copy-on-write sparse array sortedlist sorted sortedset weak weaksortedlist weaksortedset sorteddict btuple",
ext_modules=[Extension('blist._blist', ['blist/_blist.c'],
define_macros=define_macros,
)],
packages=['blist'],
provides = ['blist'],
test_suite = "test_blist.test_suite",
zip_safe = False, # zips are broken on cygwin for C extension modules
classifiers = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: BSD License',
'Programming Language :: C',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.1',
'Programming Language :: Python :: 3.2',
],
long_description=open('README.rst').read()
)
| [
"ez_setup.use_setuptools",
"ctypes.POINTER",
"ctypes.pointer",
"ctypes.sizeof",
"re.search",
"ctypes.c_double",
"setuptools.Extension"
] | [((60, 85), 'ez_setup.use_setuptools', 'ez_setup.use_setuptools', ([], {}), '()\n', (83, 85), False, 'import ez_setup\n'), ((165, 195), 'ctypes.sizeof', 'ctypes.sizeof', (['ctypes.c_double'], {}), '(ctypes.c_double)\n', (178, 195), False, 'import ctypes\n'), ((211, 246), 'ctypes.c_double', 'ctypes.c_double', (['(9006104071832581.0)'], {}), '(9006104071832581.0)\n', (226, 246), False, 'import ctypes\n'), ((499, 539), 're.search', 're.search', (['"""= *[\\\\\'"](.*)[\\\\\'"]"""', 'line'], {}), '(\'= *[\\\\\\\'"](.*)[\\\\\\\'"]\', line)\n', (508, 539), False, 'import re\n'), ((268, 286), 'ctypes.pointer', 'ctypes.pointer', (['dv'], {}), '(dv)\n', (282, 286), False, 'import ctypes\n'), ((288, 319), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.c_uint64'], {}), '(ctypes.c_uint64)\n', (302, 319), False, 'import ctypes\n'), ((1043, 1117), 'setuptools.Extension', 'Extension', (['"""blist._blist"""', "['blist/_blist.c']"], {'define_macros': 'define_macros'}), "('blist._blist', ['blist/_blist.c'], define_macros=define_macros)\n", (1052, 1117), False, 'from setuptools import setup, Extension\n')] |
"""
Interface to OpenSSL object identifier database.
It is primarily intended to deal with OIDs which are compiled into the
database or defined in the openssl configuration files.
But see create() function.
OpenSSL maintains database of OIDs, which contain long and short
human-readable names, which correspond to Oid as well as canonical
dotted-decimal representation, and links it to small integer, named
numeric identifier or 'nid'. Most OpenSSL functions which deals with
ASN.1 structures such as certificates or cryptographic messages,
expect or return nids, but it is very bad idea to hardcode nids into
your app, because it can change after mere recompilation of OpenSSL
library.
This module provides Oid object which represents entry to OpenSSL
OID database.
"""
from ctypescrypto import libcrypto, pyver,bintype,chartype,inttype
from ctypes import c_char_p, c_void_p, c_int, create_string_buffer
from ctypescrypto.exception import LibCryptoError
__all__ = ['Oid', 'create', 'cleanup']
class Oid(object):
"""
Represents an OID (ASN.1 Object identifier).
It can be consturucted by textual
representation like Oid("commonName") or Oid("CN"),
dotted-decimal Oid("1.2.3.4") or using OpenSSL numeric
identifer (NID), which is typically returned or required by
OpenSSL API functions. If object is consturcted from textual
representation which is not present in the database, it fails
with ValueError
attribute nid - contains object nid.
"""
def __init__(self, value):
"""
Object constructor. Accepts string, integer, or another Oid
object.
Integer should be OpenSSL numeric identifier (nid) as returned
by some libcrypto function or extracted from some libcrypto
structure
"""
if isinstance(value, chartype):
value = value.encode('ascii')
if isinstance(value, bintype):
self.nid = libcrypto.OBJ_txt2nid(value)
if self.nid == 0:
raise ValueError("Cannot find object %s in the database" %
value)
elif isinstance(value, inttype):
short = libcrypto.OBJ_nid2sn(value)
if short is None:
raise ValueError("No such nid %d in the database" % value)
self.nid = value
elif isinstance(value, Oid):
self.nid = value.nid
else:
raise TypeError("Cannot convert this type to object identifier")
def __hash__(self):
" Hash of object is equal to nid because Oids with same nid are same"
return self.nid
def __eq__ (self, other):
return self.nid == other.nid
def __hash__(self):
""" Returns NID of object as hash value. Should make Oids with
identical NID compare equal and also let use Oids as
dictionary keys"""
return self.nid
def __str__(self):
" Default string representation of Oid is dotted-decimal "
return self.dotted()
def __repr__(self):
" Returns constructor call of Oid with dotted representation "
return "Oid('%s')" % (self.dotted())
if pyver == 2:
def shortname(self):
" Returns short name if any "
return libcrypto.OBJ_nid2sn(self.nid)
def longname(self):
" Returns long name if any "
return libcrypto.OBJ_nid2ln(self.nid)
else:
def shortname(self):
" Returns short name if any "
return libcrypto.OBJ_nid2sn(self.nid).decode('utf-8')
def longname(self):
" Returns long name if any "
return libcrypto.OBJ_nid2ln(self.nid).decode('utf-8')
def dotted(self):
" Returns dotted-decimal reperesentation "
obj = libcrypto.OBJ_nid2obj(self.nid)
buf = create_string_buffer(256)
libcrypto.OBJ_obj2txt(buf, 256, obj, 1)
if pyver == 2:
return buf.value
else:
return buf.value.decode('ascii')
@staticmethod
def fromobj(obj):
"""
Creates an OID object from the pointer to ASN1_OBJECT c structure.
This method intended for internal use for submodules which deal
with libcrypto ASN1 parsing functions, such as x509 or CMS
"""
nid = libcrypto.OBJ_obj2nid(obj)
if nid == 0:
buf = create_string_buffer(80)
dotted_len = libcrypto.OBJ_obj2txt(buf, 80, obj, 1)
dotted = buf[:dotted_len]
oid = create(dotted, dotted, dotted)
else:
oid = Oid(nid)
return oid
def create(dotted, shortname, longname):
"""
Creates new OID in the database
@param dotted - dotted-decimal representation of new OID
@param shortname - short name for new OID
@param longname - long name for new OID
@returns Oid object corresponding to new OID
This function should be used with exreme care. Whenever
possible, it is better to add new OIDs via OpenSSL configuration
file
Results of calling this function twice for same OIDor for
Oid alredy in database are undefined
"""
if pyver > 2:
dotted = dotted.encode('ascii')
shortname = shortname.encode('utf-8')
longname = longname.encode('utf-8')
nid = libcrypto.OBJ_create(dotted, shortname, longname)
if nid == 0:
raise LibCryptoError("Problem adding new OID to the database")
return Oid(nid)
def cleanup():
"""
Removes all the objects, dynamically added by current
application from database.
Note that in OpenSSL 1.1.0 and above OBJ_cleanup really does nothing
"""
if hasattr(libcrypto,"OBJ_cleanup"):
libcrypto.OBJ_cleanup()
libcrypto.OBJ_nid2sn.restype = c_char_p
libcrypto.OBJ_nid2ln.restype = c_char_p
libcrypto.OBJ_nid2obj.restype = c_void_p
libcrypto.OBJ_obj2nid.restype = c_int
libcrypto.OBJ_obj2txt.argtypes = (c_char_p, c_int, c_void_p, c_int)
libcrypto.OBJ_txt2nid.argtupes = (c_char_p, )
libcrypto.OBJ_obj2nid.argtupes = (c_void_p, )
libcrypto.OBJ_create.argtypes = (c_char_p, c_char_p, c_char_p)
| [
"ctypescrypto.libcrypto.OBJ_nid2sn",
"ctypescrypto.libcrypto.OBJ_nid2ln",
"ctypescrypto.libcrypto.OBJ_cleanup",
"ctypescrypto.libcrypto.OBJ_obj2txt",
"ctypescrypto.libcrypto.OBJ_create",
"ctypescrypto.exception.LibCryptoError",
"ctypes.create_string_buffer",
"ctypescrypto.libcrypto.OBJ_nid2obj",
"ct... | [((5327, 5376), 'ctypescrypto.libcrypto.OBJ_create', 'libcrypto.OBJ_create', (['dotted', 'shortname', 'longname'], {}), '(dotted, shortname, longname)\n', (5347, 5376), False, 'from ctypescrypto import libcrypto, pyver, bintype, chartype, inttype\n'), ((3803, 3834), 'ctypescrypto.libcrypto.OBJ_nid2obj', 'libcrypto.OBJ_nid2obj', (['self.nid'], {}), '(self.nid)\n', (3824, 3834), False, 'from ctypescrypto import libcrypto, pyver, bintype, chartype, inttype\n'), ((3849, 3874), 'ctypes.create_string_buffer', 'create_string_buffer', (['(256)'], {}), '(256)\n', (3869, 3874), False, 'from ctypes import c_char_p, c_void_p, c_int, create_string_buffer\n'), ((3883, 3922), 'ctypescrypto.libcrypto.OBJ_obj2txt', 'libcrypto.OBJ_obj2txt', (['buf', '(256)', 'obj', '(1)'], {}), '(buf, 256, obj, 1)\n', (3904, 3922), False, 'from ctypescrypto import libcrypto, pyver, bintype, chartype, inttype\n'), ((4326, 4352), 'ctypescrypto.libcrypto.OBJ_obj2nid', 'libcrypto.OBJ_obj2nid', (['obj'], {}), '(obj)\n', (4347, 4352), False, 'from ctypescrypto import libcrypto, pyver, bintype, chartype, inttype\n'), ((5408, 5465), 'ctypescrypto.exception.LibCryptoError', 'LibCryptoError', (['"""Problem adding new OID to the database"""'], {}), "('Problem adding new OID to the database')\n", (5422, 5465), False, 'from ctypescrypto.exception import LibCryptoError\n'), ((5730, 5753), 'ctypescrypto.libcrypto.OBJ_cleanup', 'libcrypto.OBJ_cleanup', ([], {}), '()\n', (5751, 5753), False, 'from ctypescrypto import libcrypto, pyver, bintype, chartype, inttype\n'), ((1938, 1966), 'ctypescrypto.libcrypto.OBJ_txt2nid', 'libcrypto.OBJ_txt2nid', (['value'], {}), '(value)\n', (1959, 1966), False, 'from ctypescrypto import libcrypto, pyver, bintype, chartype, inttype\n'), ((3269, 3299), 'ctypescrypto.libcrypto.OBJ_nid2sn', 'libcrypto.OBJ_nid2sn', (['self.nid'], {}), '(self.nid)\n', (3289, 3299), False, 'from ctypescrypto import libcrypto, pyver, bintype, chartype, inttype\n'), ((3389, 3419), 'ctypescrypto.libcrypto.OBJ_nid2ln', 'libcrypto.OBJ_nid2ln', (['self.nid'], {}), '(self.nid)\n', (3409, 3419), False, 'from ctypescrypto import libcrypto, pyver, bintype, chartype, inttype\n'), ((4392, 4416), 'ctypes.create_string_buffer', 'create_string_buffer', (['(80)'], {}), '(80)\n', (4412, 4416), False, 'from ctypes import c_char_p, c_void_p, c_int, create_string_buffer\n'), ((4442, 4480), 'ctypescrypto.libcrypto.OBJ_obj2txt', 'libcrypto.OBJ_obj2txt', (['buf', '(80)', 'obj', '(1)'], {}), '(buf, 80, obj, 1)\n', (4463, 4480), False, 'from ctypescrypto import libcrypto, pyver, bintype, chartype, inttype\n'), ((2173, 2200), 'ctypescrypto.libcrypto.OBJ_nid2sn', 'libcrypto.OBJ_nid2sn', (['value'], {}), '(value)\n', (2193, 2200), False, 'from ctypescrypto import libcrypto, pyver, bintype, chartype, inttype\n'), ((3520, 3550), 'ctypescrypto.libcrypto.OBJ_nid2sn', 'libcrypto.OBJ_nid2sn', (['self.nid'], {}), '(self.nid)\n', (3540, 3550), False, 'from ctypescrypto import libcrypto, pyver, bintype, chartype, inttype\n'), ((3656, 3686), 'ctypescrypto.libcrypto.OBJ_nid2ln', 'libcrypto.OBJ_nid2ln', (['self.nid'], {}), '(self.nid)\n', (3676, 3686), False, 'from ctypescrypto import libcrypto, pyver, bintype, chartype, inttype\n')] |
from abc import ABC, abstractmethod
from copy import deepcopy
import logging
from typing import Tuple, List, Dict
import numpy as np
import gym
from gridworld.log import logger
class ComponentEnv(gym.Env, ABC):
"""Base class for any environment used in the multiagent simulation."""
def __init__(
self,
name: str = None,
**kwargs
):
super().__init__()
self.name = name
self._real_power = 0.
self._reactive_power = 0.
self._obs_labels = []
@abstractmethod
def reset(self, **kwargs) -> Tuple[np.ndarray, dict]:
"""Standard gym reset method but with kwargs."""
return
@abstractmethod
def step(self, action: np.ndarray, **kwargs) -> Tuple[np.ndarray, float, bool, dict]:
"""Standard gym step method but with kwargs."""
return
@abstractmethod
def step_reward(self, **kwargs) -> Tuple[float, dict]:
"""Returns the current step reward and metadata dict."""
return
@abstractmethod
def get_obs(self, **kwargs) -> Tuple[np.ndarray, dict]:
"""Returns the current observation (state) and any metadata."""
return
@property
def real_power(self) -> float:
"""Returns the real power of the component, positive for load and
negative for generation."""
return self._real_power
@property
def reactive_power(self) -> float:
"""Returns the reactive power of the component, positive for load and
negative for generation."""
return self._reactive_power
@property
def obs_labels(self) -> list:
"""Returns a list of observation variable labels. External variables
coming from the multiagent env must be included here to indicate that
they are needed by the env. Otherwise this is optional."""
return self._obs_labels
class MultiComponentEnv(ComponentEnv):
"""Class for creating a single Gym environment from multiple component
environments. The action and observation spaces of the multi-component env
are taken as the union over the components.
"""
def __init__(
self,
name: str = None,
components: List[dict] = None,
**kwargs
):
super().__init__(name=name, **kwargs)
self.envs = []
for c in components:
env = c["cls"](name=c["name"], **c["config"])
self.envs.append(deepcopy(env))
self.observation_space = gym.spaces.Dict(
{e.name: e.observation_space for e in self.envs})
self.action_space = gym.spaces.Dict(
{e.name: e.action_space for e in self.envs})
self._obs_labels_dict = {e.name: e.obs_labels for e in self.envs}
obs_labels = []
for e in self.envs:
obs_labels += e.obs_labels
self._obs_labels = list(set(obs_labels))
def reset(self, **kwargs) -> dict:
"""Default reset method resets each component and returns the obs dict."""
_ = [e.reset(**kwargs) for e in self.envs]
return self.get_obs(**kwargs)
def step(self, action: dict, **kwargs) -> Tuple[dict, float, bool, dict]:
"""Default step method composes the obs, reward, done, meta dictionaries
from each component step."""
# Initialize outputs.
real_power = 0.
obs = {}
dones = []
metas = {}
# Loop over envs and collect real power injection/consumption.
for env in self.envs:
env_kwargs = {k: v for k,v in kwargs.items() if k in env.obs_labels}
ob, _, done, meta = env.step(action[env.name], **env_kwargs)
obs[env.name] = ob.copy()
dones.append(done)
metas[env.name] = meta.copy()
real_power += env.real_power
# Set real power attribute. TODO: Reactive power.
self._real_power = real_power
# Compute the step reward using user-implemented method.
step_reward, _ = self.step_reward()
return obs, step_reward, any(dones), metas
def step_reward(self) -> Tuple[float, dict]:
"""Default step reward simply sums those from the components. Overwrite
this method to customize how this is computed."""
# Initialize outputs.
reward = 0.
meta = {}
# Loop over envs and create the reward dict.
for env in self.envs:
r, m = env.step_reward()
reward += r
meta[env.name] = m.copy()
return reward, meta
def get_obs(self, **kwargs) -> Tuple[dict, dict]:
"""Default get obs composes a dictionary of observations from each
component env."""
# Initialize outputs.
obs = {}
meta = {}
# Loop over envs and create the observation dict (of dicts).
for env in self.envs:
env_kwargs = {k: v for k,v in kwargs.items() if k in env.obs_labels}
obs[env.name], meta[env.name] = env.get_obs(**env_kwargs)
return obs, meta
@property
def obs_labels_dict(self) -> Dict[str, list]:
return self._obs_labels_dict
@property
def env_dict(self) -> Dict[str, ComponentEnv]:
return {e.name: e for e in self.envs}
| [
"copy.deepcopy",
"gym.spaces.Dict"
] | [((2545, 2610), 'gym.spaces.Dict', 'gym.spaces.Dict', (['{e.name: e.observation_space for e in self.envs}'], {}), '({e.name: e.observation_space for e in self.envs})\n', (2560, 2610), False, 'import gym\n'), ((2653, 2713), 'gym.spaces.Dict', 'gym.spaces.Dict', (['{e.name: e.action_space for e in self.envs}'], {}), '({e.name: e.action_space for e in self.envs})\n', (2668, 2713), False, 'import gym\n'), ((2496, 2509), 'copy.deepcopy', 'deepcopy', (['env'], {}), '(env)\n', (2504, 2509), False, 'from copy import deepcopy\n')] |
import logging
from logging.handlers import RotatingFileHandler
log_format = '%(asctime)s - %(name)s - %(levelname)s - ' \
'%(funcName)s(%(lineno)d)- %(message)s'
"""
author: <NAME> <EMAIL>
"""
def set_up_logging(log_file, is_debug=False):
handlers = [get_console_handler(), get_log_file_handler(log_file)]
level = logging.INFO
if is_debug:
level = logging.DEBUG
logging.basicConfig(level=level, format=log_format,
handlers=handlers)
logging.info("started logging to: " + log_file)
def get_log_file_handler(log_file):
"""
Log into a file.
:param log_file: the name of the file for logging
:return: the handler to log into file
"""
# https://goo.gl/FxA4Mh
fh = RotatingFileHandler(log_file, mode='a', maxBytes=5 * 1024 * 1024,
backupCount=3, encoding=None, delay=0)
# create formatter
formatter = logging.Formatter(log_format)
# add formatter
fh.setFormatter(formatter)
return fh
def get_console_handler():
"""
Log into the console.
:return: console log handler
"""
# create console handler and set level to debug
ch = logging.StreamHandler()
# create formatter
formatter = logging.Formatter(log_format)
# add formatter
ch.setFormatter(formatter)
return ch
def get_logger(name=__name__):
# create logger
logger = logging.getLogger(name)
return logger
| [
"logging.Formatter",
"logging.getLogger",
"logging.basicConfig",
"logging.handlers.RotatingFileHandler",
"logging.StreamHandler",
"logging.info"
] | [((404, 474), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'level', 'format': 'log_format', 'handlers': 'handlers'}), '(level=level, format=log_format, handlers=handlers)\n', (423, 474), False, 'import logging\n'), ((503, 550), 'logging.info', 'logging.info', (["('started logging to: ' + log_file)"], {}), "('started logging to: ' + log_file)\n", (515, 550), False, 'import logging\n'), ((760, 868), 'logging.handlers.RotatingFileHandler', 'RotatingFileHandler', (['log_file'], {'mode': '"""a"""', 'maxBytes': '(5 * 1024 * 1024)', 'backupCount': '(3)', 'encoding': 'None', 'delay': '(0)'}), "(log_file, mode='a', maxBytes=5 * 1024 * 1024,\n backupCount=3, encoding=None, delay=0)\n", (779, 868), False, 'from logging.handlers import RotatingFileHandler\n'), ((933, 962), 'logging.Formatter', 'logging.Formatter', (['log_format'], {}), '(log_format)\n', (950, 962), False, 'import logging\n'), ((1194, 1217), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (1215, 1217), False, 'import logging\n'), ((1257, 1286), 'logging.Formatter', 'logging.Formatter', (['log_format'], {}), '(log_format)\n', (1274, 1286), False, 'import logging\n'), ((1418, 1441), 'logging.getLogger', 'logging.getLogger', (['name'], {}), '(name)\n', (1435, 1441), False, 'import logging\n')] |
from django.shortcuts import render
from django.shortcuts import redirect
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.views.generic import View
from .models import Post, Tag
from .utils import *
from .forms import TagForm, PostForm
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.paginator import Paginator
from django.db.models import Q
#POST
class PostDetail(ObjectDetailMixin, View):
model = Post
template = 'blog/post_detail.html'
class PostCreate(LoginRequiredMixin, ObjectCreateMixin, View):
model_form = PostForm
template = 'blog/post_create.html'
raise_exception = True
class PostUpdate(LoginRequiredMixin, ObjectUpdateMixin, View):
model = Post
model_form = PostForm
template = 'blog/post_update_form.html'
raise_exception = True
class PostDelete(LoginRequiredMixin, ObjectDeleteMixin, View):
model = Post
template = 'blog/post_delete_form.html'
redirect_url = 'posts_list_url'
raise_exception = True
posts_on_page = 2
def posts_list(request):
search_query = request.GET.get('search', '')
if search_query:
posts = Post.objects.filter(Q(title__icontains=search_query) | Q(body__icontains=search_query))
else:
posts = Post.objects.all()
paginator = Paginator(posts, posts_on_page)
page_number = request.GET.get('page', 1)
page = paginator.get_page(page_number)
is_paginated = page.has_other_pages()
if page.has_previous():
prev_url = '?page={}'.format(page.previous_page_number())
else:
prev_url = ''
if page.has_next():
next_url = '?page={}'.format(page.next_page_number())
else:
next_url = ''
context = {
'page_object':page,
'is_paginated':is_paginated,
'next_url':next_url,
'prev_url':prev_url
}
return render(request, 'blog/index.html', context=context)
#TAG
class TagDetail(ObjectDetailMixin, View):
model = Tag
template = 'blog/tag_detail.html'
class TagCreate(LoginRequiredMixin, ObjectCreateMixin, View):
model_form = TagForm
template = 'blog/tag_create.html'
raise_exception = True
class TagUpdate(LoginRequiredMixin, ObjectUpdateMixin, View):
model = Tag
model_form = TagForm
template = 'blog/tag_update_form.html'
raise_exception = True
class TagDelete(LoginRequiredMixin, ObjectDeleteMixin, View):
model = Tag
template = 'blog/tag_delete_form.html'
redirect_url = 'tags_list_url'
raise_exception = True
def tags_list(request):
tags = Tag.objects.all()
return render(request, 'blog/tags_list.html', context={'tags':tags})
| [
"django.shortcuts.render",
"django.core.paginator.Paginator",
"django.db.models.Q"
] | [((1324, 1355), 'django.core.paginator.Paginator', 'Paginator', (['posts', 'posts_on_page'], {}), '(posts, posts_on_page)\n', (1333, 1355), False, 'from django.core.paginator import Paginator\n'), ((1890, 1941), 'django.shortcuts.render', 'render', (['request', '"""blog/index.html"""'], {'context': 'context'}), "(request, 'blog/index.html', context=context)\n", (1896, 1941), False, 'from django.shortcuts import render\n'), ((2621, 2683), 'django.shortcuts.render', 'render', (['request', '"""blog/tags_list.html"""'], {'context': "{'tags': tags}"}), "(request, 'blog/tags_list.html', context={'tags': tags})\n", (2627, 2683), False, 'from django.shortcuts import render\n'), ((1194, 1226), 'django.db.models.Q', 'Q', ([], {'title__icontains': 'search_query'}), '(title__icontains=search_query)\n', (1195, 1226), False, 'from django.db.models import Q\n'), ((1229, 1260), 'django.db.models.Q', 'Q', ([], {'body__icontains': 'search_query'}), '(body__icontains=search_query)\n', (1230, 1260), False, 'from django.db.models import Q\n')] |
# o-------------------------------------------o
# | <NAME> |
# | Zendesk Internship challenge |
# | 11 / 24 / 2021 |
# o-------------------------------------------o
# used for handling get requests and auth
import requests
from requests.auth import AuthBase, HTTPBasicAuth
# global variables
page_size = 25
# default auth and subdomain to empty values. set by return of read_config
auth = AuthBase()
subdomain = ""
# a custom error type defined for unit test compatibility
class GeneralError(Exception):
pass
# reads authentication and account data and returns an AuthBase object and subdomain string
def read_config(config_path: str="config.txt"):
subdomain = ""
email = ""
password = ""
token = ""
with open(config_path, 'r') as f:
for line in f.readlines():
line = line.strip()
# get each parameter from the file
if line.startswith("subdomain:"):
subdomain = line.split(":")[1]
elif line.startswith("email:"):
email = line.split(":")[1]
elif line.startswith("password:"):
password = line.split(":")[1]
elif line.startswith("token:"):
token = line.split(":")[1]
# error checking
if subdomain == "":
raise GeneralError(f"Error: No subdomain found in {config_path}. Please specify by adding the line:\nsubdomain:your_subdomain")
if email == "":
raise GeneralError(f"Error: No email found in {config_path}. Please specify by adding the line:\nemail:your_email")
if password == "" and token == "":
raise GeneralError(f"Error: No password or token found in {config_path}. Please specify by adding the line:\npassword:your_password\nor\ntoken:your_api_token")
# make an auth object based on api_key or password. Pereference given to api token
if token != "":
return HTTPBasicAuth(f"{email}/token", token), subdomain
else:
return HTTPBasicAuth(email, password), subdomain
# returns a list of dictionaries of all the account's tickets and the number of pages of tickets
def get_all_tickets():
print(f"Getting all tickets from {subdomain}")
# get all of the tickets created since UNIX Epoch time
resp = requests.get(f"https://{subdomain}.zendesk.com/api/v2/incremental/tickets/cursor.json?start_time={0}", auth=auth, timeout=5)
code = resp.status_code
# on a successful call, return the tickets array and page count
if code == 200:
tickets = resp.json()['tickets']
page_count = ((len(tickets) - 1) // page_size)
return tickets, page_count
# otherwise, error
raise GeneralError(f"Error: Request recieved error response code {code}")
# renders a page of tickets. Returns True if it reached more than 25 tickets
def show_page(tickets: list, page: int, page_count: int):
start = page * page_size
# print header
print(f"\n\n\n\n\nShowing page {page+1}/{page_count+1}")
for i in range(start, len(tickets)):
if i >= start + page_size:
return True # cancel after page_size tickets have been printed
print(f"[id: {tickets[i]['id']}] | {tickets[i]['subject']}")
return False
# Gets information on a ticket by id and prints it in a formatted manner. immediate_breakout=True skips the wait for user input
def show_ticket(tickets: list, id: int, immediate_breakout: bool=False):
# get the ticket from the tickets array by id. Intentionally not limited by current page
ticket = None
for t in tickets:
if int(t['id']) == id:
ticket = t
break
# if a ticket was found, display it and wait for any key to return
if ticket:
# assemble relevant fields into a string and display it
print(f"Showing ticket {id}:")
# get the submitter's first email/uname
submitter = "N/A"
user_id = ticket['submitter_id']
try:
resp = requests.get(f"https://{subdomain}.zendesk.com/api/v2/users/{user_id}/identities", auth=auth, timeout=5)
if resp.status_code == 200:
content = resp.json()
if(content['identities'][0]['value']):
submitter = content['identities'][0]['value']
except Exception as e:
print("Error: could not connect to ZenDesk API. SHowing ticket without submitter email:")
text = f"\n\n\n\n\n[{id}] ({ticket['status']}) {ticket['subject']}\nsubmitter: {submitter}\n{ticket['description']}\n"
print(text)
# hold user on ticket page until finished
if not immediate_breakout:
input("Enter to continue")
return True
# otherwise, ticket id was out of bounds
print(f"No ticket with id {id} was found. Please enter a valid id")
return False
# parse the user input
def parse_command(command: str, page: int, page_count: int):
command = command.lower()
if command == 'q' or command == 'quit':
exit()
# if the command is an int, check for ticket id
id = -1
try:
id = int(command)
except ValueError:
pass # int() returns a value error if the string was not parsable
# if the id is valid, attempt to expand it
if (id >= 0):
show_ticket(tickets, id)
return page
# otherwise, this is a page operation.
if command == 'n' or command == 'next':
page += 1
elif command == 'p' or command == 'prev':
page -= 1
# if no command was recognized, explain so to the user
else:
print("No command recognized. Please enter a valid command")
# clamp page
if page > page_count:
page = page_count
elif page < 0:
page = 0
return page
if __name__ == "__main__":
# read config
try:
auth, subdomain = read_config("config.txt")
except Exception as e:
print(e)
exit()
# ping the server to make sure the api is online
try:
r = requests.get(f"https://{subdomain}.zendesk.com/api/v2", auth=auth, timeout=1)
except Exception as e:
print(f"Error: could not access the Zendesk Api.")
exit()
# get json data
try:
tickets, page_count = get_all_tickets()
except Exception as e:
print(e)
exit()
# show the first page
page = 0
show_page(tickets, page, page_count)
# enter main program loop
while (True):
command = input("q->quit, n->next page, p->prev page. Enter a ticket id to expand: ")
page = parse_command(command, page, page_count)
show_page(tickets, page, page_count)
| [
"requests.auth.AuthBase",
"requests.auth.HTTPBasicAuth",
"requests.get"
] | [((455, 465), 'requests.auth.AuthBase', 'AuthBase', ([], {}), '()\n', (463, 465), False, 'from requests.auth import AuthBase, HTTPBasicAuth\n'), ((2331, 2465), 'requests.get', 'requests.get', (['f"""https://{subdomain}.zendesk.com/api/v2/incremental/tickets/cursor.json?start_time={0}"""'], {'auth': 'auth', 'timeout': '(5)'}), "(\n f'https://{subdomain}.zendesk.com/api/v2/incremental/tickets/cursor.json?start_time={0}'\n , auth=auth, timeout=5)\n", (2343, 2465), False, 'import requests\n'), ((6111, 6188), 'requests.get', 'requests.get', (['f"""https://{subdomain}.zendesk.com/api/v2"""'], {'auth': 'auth', 'timeout': '(1)'}), "(f'https://{subdomain}.zendesk.com/api/v2', auth=auth, timeout=1)\n", (6123, 6188), False, 'import requests\n'), ((1970, 2008), 'requests.auth.HTTPBasicAuth', 'HTTPBasicAuth', (['f"""{email}/token"""', 'token'], {}), "(f'{email}/token', token)\n", (1983, 2008), False, 'from requests.auth import AuthBase, HTTPBasicAuth\n'), ((2045, 2075), 'requests.auth.HTTPBasicAuth', 'HTTPBasicAuth', (['email', 'password'], {}), '(email, password)\n', (2058, 2075), False, 'from requests.auth import AuthBase, HTTPBasicAuth\n'), ((4053, 4166), 'requests.get', 'requests.get', (['f"""https://{subdomain}.zendesk.com/api/v2/users/{user_id}/identities"""'], {'auth': 'auth', 'timeout': '(5)'}), "(\n f'https://{subdomain}.zendesk.com/api/v2/users/{user_id}/identities',\n auth=auth, timeout=5)\n", (4065, 4166), False, 'import requests\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 15 17:19:48 2019
@author: <NAME>
"""
#Functions for Rydberg library
import numpy as np
import SIunits as SIunits
import AtomData as atoms
import MatlabHacks as mfuncs
import WignerFuncs as Wigner
def numerovfunc(atom,nn,ll,jj):
'''Function for getting solution to the radial Schrodinger equation using Numerov algorithm'''
ZZ, spin, eneigval, alpha_c, a_1, a_2, a_3, a_4, r_c, ionlim, delta_nlj = GetAtomParams(atom,nn,ll,jj)
hh = 0.01 #Choose this to be small so that O(h**6) may be ignored
h2 = hh**2 #For efficiecy
r_i = hh/2 #Define starting point
r_o = 2*nn*(nn+15) #Define end point
x_i = np.log(r_i) #Change of variables
x_o = np.log(r_o)
xx = np.arange(x_i,x_o+hh,hh)
rr = np.exp(xx) #For efficiency
#Set up Schrodinger equation from Gallagher (2005), note Pritchard (2012)
LdotS = (jj*(jj+1)-ll*(ll+1)-spin*(spin+1))/2 #Spin-orbit coupling
spinorbitpotential = np.divide((SIunits.finestrucconst**2)*LdotS,np.multiply(np.power(rr,3),2)) #Fine structure splitting
radialcharge = np.add(1,np.subtract(np.multiply(np.exp(np.multiply(rr,-a_1)),(ZZ-1)),np.multiply(rr,np.multiply(np.exp(np.multiply(rr,-a_2)),np.add(np.multiply(rr,a_4),a_3))))) #Effective nuclear charge
coulombpotential = np.multiply(np.add(np.divide(radialcharge,rr),np.multiply(np.divide(alpha_c,np.multiply(np.power(rr,4),2)),np.subtract(1,np.exp(np.multiply(np.power(np.divide(rr,r_c),6),-1))))),-1) #Coulomb potential
totalpotential = np.add(spinorbitpotential,coulombpotential) #Total potential
cenfugterm = (ll + 1/2)**2 #Centifugal term for Schrodinger equation
#Apply Numerov method
G_x = np.add(np.multiply(np.multiply(np.exp(np.multiply(xx,2)),2),np.subtract(totalpotential,eneigval)),cenfugterm) #Coefficient in differential equation
T_x = np.multiply(G_x,h2/12) #For effiency
Ysoln_vec = np.zeros(np.shape(xx)) #Generate a place holder array for solutions
Ysoln_vec[len(Ysoln_vec.tolist())-1] = -1e-10 #The function must go to zero at infinity
Ysoln_vec[len(Ysoln_vec.tolist())-2] = -2e-10
#To perform the iteration with convenient indexing the vectors xx, T_x and Ysoln_vec are flipped
fYsoln = np.flip(Ysoln_vec,axis=0)
fT_x = np.flip(T_x,axis=0)
itr = 2
while (itr<len(xx.tolist())):
fYsoln[itr] = ((2 + 10*fT_x[itr-1])*fYsoln[itr-1] - (1 - fT_x[itr-2])*fYsoln[itr-2])/(1-fT_x[itr])
itr+=1
Ysoln_vec = np.flip(fYsoln,axis=0) #Return solutions to proper ordering
#Normalise (method adapted from Gallagher)
normconstvec = np.zeros(len(rr.tolist())-1)
itr = 1
while (itr<len(rr.tolist())):
deltar = rr[itr]-rr[itr-1]
normconstvec[itr-1] = (Ysoln_vec[itr]**2)*rr[itr]*deltar
itr+=1
normconst = np.sqrt(normconstvec.sum())
normY_sol = np.divide(Ysoln_vec,normconst)
filename = filenamemake(atom,nn,ll,jj)
np.savetxt(filename, np.array([rr, normY_sol]).T,header='rr normY_sol')
return normY_sol, rr
def Radiative_Lifetimes(atom,nn,ll,jj):
'''Function for calculating Rydberg state lifetimes'''
temp = 300 #Approximation of room temperature in K
ZZ, spin, eneigval, alpha_c, a_1, a_2, a_3, a_4, r_c, ionlim, delta_nlj = GetAtomParams(atom,nn,ll,jj)
if (atom=='87Rb'):
loadparam, stateenvec, Rdecayratevec, qvec1, qvec4 = atoms.Rb87decaypaths(nn,ll,jj)
for qq in range(qvec1,qvec4+1):
#Get matrix element
matrixelementSI = matrix_elements(atom,nn,ll,jj,loadparam[qq,0],loadparam[qq,1],loadparam[qq,2])[1]
#Compute energies
enlow = stateenvec[qq]-ionlim #Energy of lower state in eV
eneigvaleV = eneigval*SIunits.atomenergy #Energy of state |n,l,j> in eV
#Perform calculation
omega = np.absolute((eneigvaleV-enlow)/SIunits.rpceV) #Angular frequency of transimission
term1 = (omega**3)/(3*np.pi*SIunits.vacpmtvty*SIunits.rpcJ*(SIunits.lightc**3)) #splitting terms to make reading easier
term2 = (2*jj+1)/(2*loadparam[qq,2]+1)
Rdecayratevec[qq] = term1*term2*(matrixelementSI**2) #Radiative decay rate
Rdecayrate = Rdecayratevec.sum()
#Account for black body radiation Beterov et al. (2009)
neff = nn - delta_nlj #Effective principal quantum number
if (atom=='87Rb'):
BBdecayrate = atoms.Rb87blackbody(neff,temp,ll,jj)
decayrate = Rdecayrate + BBdecayrate #Total decay rate
lifetime = 1/decayrate
return lifetime
def BlockadeShift(atom,nn,ll,jj,mj):
'''Function for calculating Rydberg blockade shifts.'''
pceV = 2*np.pi*SIunits.rpceV #Planck's constant in eV
if (atom=='87Rb'):
ZZ, spin, eneigval, alpha_c, a_1, a_2, a_3, a_4, r_c, ionlim, delta_nlj = GetAtomParams(atom,nn,ll,jj)
#Create ranges for theta and R (R in atomic units)
theta = np.arange(0,np.pi/2+0.005,0.01)
RRSI = np.multiply(np.arange(4,10.0005,0.001),1e-6)
RR = np.divide(RRSI,SIunits.bohrrad)
#Set defect threshold
defectmax = 100e9 #Maximum energy defect in Hz
entol = defectmax*pceV/SIunits.atomenergy #Converted to atomic units
ntol = 4 #Maximum change in n
#Determine the single particle state energy
singen = eneigval
#Create set of allowable interacting state quantum numbers
nvec = mfuncs.rectpulse(np.arange(nn-ntol,nn+ntol+1),ll+2).T.ravel()
lcands = np.arange(ll-1,ll+2,2)
lcands = lcands[lcands>=0]
if (lcands[0]==0):
smalllvec = np.array([0] + mfuncs.rectpulse(lcands[1:len(lcands.tolist())],2).T.ravel().tolist())
jmaker = np.array([0.5] + mfuncs.repmat(np.array([-0.5,0.5]),1,len(lcands[1:len(lcands.tolist())])).ravel().tolist())
else:
smalllvec = mfuncs.rectpulse(lcands,2).T.ravel()
jmaker = mfuncs.repmat(np.array([-0.5,0.5]),1,len(lcands.tolist())).ravel()
smalljvec = np.add(smalllvec,jmaker)
lvec = mfuncs.repmat(smalllvec,1,int(len(nvec.tolist())/len(smalllvec.tolist()))).ravel()
jvec = mfuncs.repmat(smalljvec,1,int(len(nvec.tolist())/len(smalljvec.tolist()))).ravel()
truncspace1 = np.array([nvec.tolist(),lvec.tolist(),jvec.tolist()])
pairs1 = mfuncs.combvec(truncspace1,truncspace1)
Sp1 = np.shape(pairs1)
#Check which of these states satisfy the infinite separation energy defect condition and selection rules for j
pindex = np.zeros(Sp1[1])
defects = np.zeros(Sp1[1])
for kk in range(0,Sp1[1]):
energy1 = envalfunc(atom,pairs1[0,kk],pairs1[1,kk],pairs1[2,kk])
energy2 = envalfunc(atom,pairs1[3,kk],pairs1[4,kk],pairs1[5,kk])
defects[kk] = energy1 + energy2 - 2*singen #Energy defect
j1check = (pairs1[2,kk]==np.arange(jj-1,jj+1.5)).sum()
j2check = (pairs1[5,kk]==np.arange(jj-1,jj+1.5)).sum()
if ((np.absolute(defects[kk])<=entol) and (j1check==1) and (j2check==1)):
pindex[kk] = 1
pindex = np.where(pindex==1)[0]
pairs2L = []
for row in pairs1:
pairs2L.append(row[pindex].tolist())
pairs2L.append(defects[pindex].tolist())
pairs2 = np.array(pairs2L)
matel2part = np.zeros((len(theta.tolist()),np.shape(pairs2)[1])) #Vector to store matrix elements in
#Call function to calculate matrix elements
for kk in range(0,np.shape(pairs2)[1]):
matel2part[:,kk] = matrixel2p(atom,nn,ll,jj,mj,pairs2[0,kk],pairs2[1,kk],pairs2[2,kk],pairs2[3,kk],pairs2[4,kk],pairs2[5,kk],pairs2[6,kk],theta)
#Compute the blockade shift in atomic units
summation = np.multiply(np.sum(matel2part,axis=1),-1)
kindex = np.where(np.absolute(summation)==np.absolute(summation).max())[0][0] #Find the index of maximum blockade shift
blockadeshiftau = np.divide(summation[kindex],np.power(RR,6))
RRmesh, summationmesh = np.meshgrid(RR,summation)
blockadeshiftaumesh = np.divide(summationmesh,np.power(RRmesh,6))
#Convert units to GHz
encon = (SIunits.atomenergy/pceV)*1e-9 #Factor from atomic energy units to GHz
blockadeshiftGHz = np.multiply(blockadeshiftau,encon)
blockadeshiftGHzmesh = np.multiply(blockadeshiftaumesh,encon)
#C6
C_6val = float(blockadeshiftGHz[len(blockadeshiftGHz.tolist())-1]*(RRSI[len(RRSI.tolist())-1]**6)) #GHz/m^6
return RRSI, theta, blockadeshiftGHzmesh, C_6val
def matrix_elements(atom,nn1,ll1,jj1,nn2,ll2,jj2):
'''Function for calculating dipole matrix elements based on results from numerovfunc()'''
matrixelement = radiel(atom,nn1,ll1,jj1,nn2,ll2,jj2)
matrixelementSI = matrixelement*SIunits.bohrrad*SIunits.eleccharge
return matrixelement, matrixelementSI
def radiel(atom,nn1,ll1,jj1,nn2,ll2,jj2):
'''function to evaluate radial matrix elements'''
#first load radial wavefunctions for calculating the radial part of the matrix element
try:
rscale1, radial1 = np.loadtxt(filenamemake(atom,nn1,ll1,jj1), unpack=True)
except (FileNotFoundError,OSError):
radial1, rscale1 = numerovfunc(atom,nn1,ll1,jj1)
try:
rscale2, radial2 = np.loadtxt(filenamemake(atom,nn2,ll2,jj2), unpack=True)
except (FileNotFoundError,OSError):
radial2, rscale2 = numerovfunc(atom,nn2,ll2,jj2)
#Calculate the radial matrix element
if (nn1 >= nn2):
Yk1 = radial1
Yk2 = radial2
rscale = rscale1
else:
Yk1 = radial2
Yk2 = radial1
rscale = rscale2
#Resize smaller solution vector by attaching zeros to the end such that the two solution vectors are the same length
if not(len(Yk1.tolist())==len(Yk2.tolist())):
szero = np.zeros(len(Yk1.tolist())-len(Yk2.tolist())).tolist()
Yk2conc = np.array(Yk2.tolist()+szero)
else:
Yk2conc = np.copy(Yk2)
#Solve the matrix elements using method adapted from Zimmerman et al. (1979)
deltar = np.subtract(rscale[1:(len(rscale.tolist())-1)],rscale[0:(len(rscale.tolist())-2)])
numervec = np.multiply(Yk1[1:(len(Yk1.tolist())-1)],np.multiply(Yk2conc[1:(len(Yk2conc.tolist())-1)],np.multiply(np.power(rscale[1:(len(rscale.tolist())-1)],2),deltar)))
matrixelement = numervec.sum()
return matrixelement
def matrixel2p(atom,nni,lli,jji,mji,nn1,ll1,jj1,nn2,ll2,jj2,defect,theta):
'''Function for calculating the two particle matrix elements required for second order perturbation theory evaluation of the blockade shift'''
sint = np.sin(theta) #For efficiency
cost = np.cos(theta)
sin2t = np.power(sint,2)
cos2t = np.power(cost,2)
#first calculate angular factors as vectors [minus, zero, plus] for each single particle interaction state
angvec1 = angcalc(lli,jji,mji,ll1,jj1)
angvec2 = angcalc(lli,jji,mji,ll2,jj2)
#Radial matrix elements
matelem1i = radiel(atom,nni,lli,jji,nn1,ll1,jj1)
matelem2i = radiel(atom,nni,lli,jji,nn2,ll2,jj2)
#Calculate terms in two particle matrix element using Wigner-Eckhart theorem (Pritchard, 2012), (Reinhard et al., 2007).
line1 = np.add(angvec1[2]*angvec2[2] + angvec1[0]*angvec2[2],np.multiply(angvec1[1]*angvec2[1],np.subtract(1,np.multiply(3,cos2t))))
line2 = np.multiply(np.multiply(-3/2,sin2t),angvec1[2]*angvec2[2]+angvec1[2]*angvec2[0] + angvec1[0]*angvec2[2] + angvec1[0]*angvec2[0])
line3 = np.multiply(-(3/np.sqrt(2)),np.multiply(np.multiply(sint,cost),angvec1[2]*angvec2[1] + angvec1[0]*angvec2[1] + angvec1[1]*angvec2[2] + angvec1[1]*angvec2[0]))
matrixelement = np.multiply(np.multiply(matelem1i,matelem2i),np.add(line1,np.add(line2,line3)))
mel2p = np.divide(np.power(matrixelement,2),defect)
return mel2p
def angcalc(lli,jji,mji,ll1,jj1):
angvec1 = np.zeros(3)
for qq in range(-1,2):
mj1 = mji - qq
tf1 = (mj1==np.arange(-jj1,jj1+0.5)).sum()
if (tf1==1):
ang11 = (-1)**(jji-mji+SIunits.espin+jj1+1)
ang12 = np.sqrt((2*jji+1)*(2*jj1+1)*(2*lli+1)*(2*ll1+1))
ang13 = Wigner.Wigner6j(jji,1,jj1,ll1,SIunits.espin,lli)
ang14 = Wigner.Wigner3j(jji,1,jj1,-mji,qq,mj1)
ang15 = Wigner.Wigner3j(lli,1,ll1,0,0,0)
angvec1[qq+1] = ang11*ang12*ang13*ang14*ang15 #Shift for Python indexing
return angvec1
def envalfunc(atom,nn,ll,jj):
return GetAtomParams(atom,nn,ll,jj)[2]
def GetAtomParams(atom,nn,ll,jj):
if (atom=='87Rb'):
ZZ, spin, eneigval, alpha_c, a_1, a_2, a_3, a_4, r_c, ionlim, delta_nlj = atoms.Rb87Numbers(nn,ll,jj)
return ZZ, spin, eneigval, alpha_c, a_1, a_2, a_3, a_4, r_c, ionlim, delta_nlj
def filenamemake(atom,nn,ll,jj):
'''Function for constructing filenames'''
jstring = str(jj).replace('.','_')
filename = 'Wavefunctions/' + atom + str(nn) + 'n' + str(ll) + 'l' + jstring + 'j.txt'
return filename | [
"AtomData.Rb87decaypaths",
"numpy.power",
"numpy.copy",
"numpy.where",
"numpy.sum",
"numpy.zeros",
"numpy.log",
"numpy.arange",
"numpy.absolute",
"numpy.sqrt",
"numpy.flip",
"numpy.sin",
"AtomData.Rb87blackbody",
"numpy.multiply",
"MatlabHacks.combvec",
"WignerFuncs.Wigner3j",
"Matla... | [((702, 713), 'numpy.log', 'np.log', (['r_i'], {}), '(r_i)\n', (708, 713), True, 'import numpy as np\n'), ((745, 756), 'numpy.log', 'np.log', (['r_o'], {}), '(r_o)\n', (751, 756), True, 'import numpy as np\n'), ((766, 794), 'numpy.arange', 'np.arange', (['x_i', '(x_o + hh)', 'hh'], {}), '(x_i, x_o + hh, hh)\n', (775, 794), True, 'import numpy as np\n'), ((800, 810), 'numpy.exp', 'np.exp', (['xx'], {}), '(xx)\n', (806, 810), True, 'import numpy as np\n'), ((1584, 1628), 'numpy.add', 'np.add', (['spinorbitpotential', 'coulombpotential'], {}), '(spinorbitpotential, coulombpotential)\n', (1590, 1628), True, 'import numpy as np\n'), ((1932, 1957), 'numpy.multiply', 'np.multiply', (['G_x', '(h2 / 12)'], {}), '(G_x, h2 / 12)\n', (1943, 1957), True, 'import numpy as np\n'), ((2324, 2350), 'numpy.flip', 'np.flip', (['Ysoln_vec'], {'axis': '(0)'}), '(Ysoln_vec, axis=0)\n', (2331, 2350), True, 'import numpy as np\n'), ((2361, 2381), 'numpy.flip', 'np.flip', (['T_x'], {'axis': '(0)'}), '(T_x, axis=0)\n', (2368, 2381), True, 'import numpy as np\n'), ((2579, 2602), 'numpy.flip', 'np.flip', (['fYsoln'], {'axis': '(0)'}), '(fYsoln, axis=0)\n', (2586, 2602), True, 'import numpy as np\n'), ((2969, 3000), 'numpy.divide', 'np.divide', (['Ysoln_vec', 'normconst'], {}), '(Ysoln_vec, normconst)\n', (2978, 3000), True, 'import numpy as np\n'), ((5038, 5075), 'numpy.arange', 'np.arange', (['(0)', '(np.pi / 2 + 0.005)', '(0.01)'], {}), '(0, np.pi / 2 + 0.005, 0.01)\n', (5047, 5075), True, 'import numpy as np\n'), ((5135, 5167), 'numpy.divide', 'np.divide', (['RRSI', 'SIunits.bohrrad'], {}), '(RRSI, SIunits.bohrrad)\n', (5144, 5167), True, 'import numpy as np\n'), ((5585, 5613), 'numpy.arange', 'np.arange', (['(ll - 1)', '(ll + 2)', '(2)'], {}), '(ll - 1, ll + 2, 2)\n', (5594, 5613), True, 'import numpy as np\n'), ((6061, 6086), 'numpy.add', 'np.add', (['smalllvec', 'jmaker'], {}), '(smalllvec, jmaker)\n', (6067, 6086), True, 'import numpy as np\n'), ((6359, 6399), 'MatlabHacks.combvec', 'mfuncs.combvec', (['truncspace1', 'truncspace1'], {}), '(truncspace1, truncspace1)\n', (6373, 6399), True, 'import MatlabHacks as mfuncs\n'), ((6409, 6425), 'numpy.shape', 'np.shape', (['pairs1'], {}), '(pairs1)\n', (6417, 6425), True, 'import numpy as np\n'), ((6559, 6575), 'numpy.zeros', 'np.zeros', (['Sp1[1]'], {}), '(Sp1[1])\n', (6567, 6575), True, 'import numpy as np\n'), ((6590, 6606), 'numpy.zeros', 'np.zeros', (['Sp1[1]'], {}), '(Sp1[1])\n', (6598, 6606), True, 'import numpy as np\n'), ((7269, 7286), 'numpy.array', 'np.array', (['pairs2L'], {}), '(pairs2L)\n', (7277, 7286), True, 'import numpy as np\n'), ((7986, 8012), 'numpy.meshgrid', 'np.meshgrid', (['RR', 'summation'], {}), '(RR, summation)\n', (7997, 8012), True, 'import numpy as np\n'), ((8219, 8254), 'numpy.multiply', 'np.multiply', (['blockadeshiftau', 'encon'], {}), '(blockadeshiftau, encon)\n', (8230, 8254), True, 'import numpy as np\n'), ((8281, 8320), 'numpy.multiply', 'np.multiply', (['blockadeshiftaumesh', 'encon'], {}), '(blockadeshiftaumesh, encon)\n', (8292, 8320), True, 'import numpy as np\n'), ((10610, 10623), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (10616, 10623), True, 'import numpy as np\n'), ((10651, 10664), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (10657, 10664), True, 'import numpy as np\n'), ((10677, 10694), 'numpy.power', 'np.power', (['sint', '(2)'], {}), '(sint, 2)\n', (10685, 10694), True, 'import numpy as np\n'), ((10706, 10723), 'numpy.power', 'np.power', (['cost', '(2)'], {}), '(cost, 2)\n', (10714, 10723), True, 'import numpy as np\n'), ((11893, 11904), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (11901, 11904), True, 'import numpy as np\n'), ((1999, 2011), 'numpy.shape', 'np.shape', (['xx'], {}), '(xx)\n', (2007, 2011), True, 'import numpy as np\n'), ((3510, 3542), 'AtomData.Rb87decaypaths', 'atoms.Rb87decaypaths', (['nn', 'll', 'jj'], {}), '(nn, ll, jj)\n', (3530, 3542), True, 'import AtomData as atoms\n'), ((3945, 3994), 'numpy.absolute', 'np.absolute', (['((eneigvaleV - enlow) / SIunits.rpceV)'], {}), '((eneigvaleV - enlow) / SIunits.rpceV)\n', (3956, 3994), True, 'import numpy as np\n'), ((4513, 4552), 'AtomData.Rb87blackbody', 'atoms.Rb87blackbody', (['neff', 'temp', 'll', 'jj'], {}), '(neff, temp, ll, jj)\n', (4532, 4552), True, 'import AtomData as atoms\n'), ((5093, 5121), 'numpy.arange', 'np.arange', (['(4)', '(10.0005)', '(0.001)'], {}), '(4, 10.0005, 0.001)\n', (5102, 5121), True, 'import numpy as np\n'), ((7103, 7124), 'numpy.where', 'np.where', (['(pindex == 1)'], {}), '(pindex == 1)\n', (7111, 7124), True, 'import numpy as np\n'), ((7728, 7754), 'numpy.sum', 'np.sum', (['matel2part'], {'axis': '(1)'}), '(matel2part, axis=1)\n', (7734, 7754), True, 'import numpy as np\n'), ((7937, 7952), 'numpy.power', 'np.power', (['RR', '(6)'], {}), '(RR, 6)\n', (7945, 7952), True, 'import numpy as np\n'), ((8062, 8081), 'numpy.power', 'np.power', (['RRmesh', '(6)'], {}), '(RRmesh, 6)\n', (8070, 8081), True, 'import numpy as np\n'), ((9932, 9944), 'numpy.copy', 'np.copy', (['Yk2'], {}), '(Yk2)\n', (9939, 9944), True, 'import numpy as np\n'), ((11368, 11394), 'numpy.multiply', 'np.multiply', (['(-3 / 2)', 'sin2t'], {}), '(-3 / 2, sin2t)\n', (11379, 11394), True, 'import numpy as np\n'), ((11693, 11726), 'numpy.multiply', 'np.multiply', (['matelem1i', 'matelem2i'], {}), '(matelem1i, matelem2i)\n', (11704, 11726), True, 'import numpy as np\n'), ((11788, 11814), 'numpy.power', 'np.power', (['matrixelement', '(2)'], {}), '(matrixelement, 2)\n', (11796, 11814), True, 'import numpy as np\n'), ((12651, 12680), 'AtomData.Rb87Numbers', 'atoms.Rb87Numbers', (['nn', 'll', 'jj'], {}), '(nn, ll, jj)\n', (12668, 12680), True, 'import AtomData as atoms\n'), ((1072, 1087), 'numpy.power', 'np.power', (['rr', '(3)'], {}), '(rr, 3)\n', (1080, 1087), True, 'import numpy as np\n'), ((1376, 1403), 'numpy.divide', 'np.divide', (['radialcharge', 'rr'], {}), '(radialcharge, rr)\n', (1385, 1403), True, 'import numpy as np\n'), ((1829, 1866), 'numpy.subtract', 'np.subtract', (['totalpotential', 'eneigval'], {}), '(totalpotential, eneigval)\n', (1840, 1866), True, 'import numpy as np\n'), ((3078, 3103), 'numpy.array', 'np.array', (['[rr, normY_sol]'], {}), '([rr, normY_sol])\n', (3086, 3103), True, 'import numpy as np\n'), ((7472, 7488), 'numpy.shape', 'np.shape', (['pairs2'], {}), '(pairs2)\n', (7480, 7488), True, 'import numpy as np\n'), ((11537, 11560), 'numpy.multiply', 'np.multiply', (['sint', 'cost'], {}), '(sint, cost)\n', (11548, 11560), True, 'import numpy as np\n'), ((11739, 11759), 'numpy.add', 'np.add', (['line2', 'line3'], {}), '(line2, line3)\n', (11745, 11759), True, 'import numpy as np\n'), ((12103, 12173), 'numpy.sqrt', 'np.sqrt', (['((2 * jji + 1) * (2 * jj1 + 1) * (2 * lli + 1) * (2 * ll1 + 1))'], {}), '((2 * jji + 1) * (2 * jj1 + 1) * (2 * lli + 1) * (2 * ll1 + 1))\n', (12110, 12173), True, 'import numpy as np\n'), ((12172, 12225), 'WignerFuncs.Wigner6j', 'Wigner.Wigner6j', (['jji', '(1)', 'jj1', 'll1', 'SIunits.espin', 'lli'], {}), '(jji, 1, jj1, ll1, SIunits.espin, lli)\n', (12187, 12225), True, 'import WignerFuncs as Wigner\n'), ((12241, 12284), 'WignerFuncs.Wigner3j', 'Wigner.Wigner3j', (['jji', '(1)', 'jj1', '(-mji)', 'qq', 'mj1'], {}), '(jji, 1, jj1, -mji, qq, mj1)\n', (12256, 12284), True, 'import WignerFuncs as Wigner\n'), ((12300, 12337), 'WignerFuncs.Wigner3j', 'Wigner.Wigner3j', (['lli', '(1)', 'll1', '(0)', '(0)', '(0)'], {}), '(lli, 1, ll1, 0, 0, 0)\n', (12315, 12337), True, 'import WignerFuncs as Wigner\n'), ((6994, 7018), 'numpy.absolute', 'np.absolute', (['defects[kk]'], {}), '(defects[kk])\n', (7005, 7018), True, 'import numpy as np\n'), ((7339, 7355), 'numpy.shape', 'np.shape', (['pairs2'], {}), '(pairs2)\n', (7347, 7355), True, 'import numpy as np\n'), ((11320, 11341), 'numpy.multiply', 'np.multiply', (['(3)', 'cos2t'], {}), '(3, cos2t)\n', (11331, 11341), True, 'import numpy as np\n'), ((11513, 11523), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (11520, 11523), True, 'import numpy as np\n'), ((1181, 1202), 'numpy.multiply', 'np.multiply', (['rr', '(-a_1)'], {}), '(rr, -a_1)\n', (1192, 1202), True, 'import numpy as np\n'), ((1807, 1825), 'numpy.multiply', 'np.multiply', (['xx', '(2)'], {}), '(xx, 2)\n', (1818, 1825), True, 'import numpy as np\n'), ((5527, 5562), 'numpy.arange', 'np.arange', (['(nn - ntol)', '(nn + ntol + 1)'], {}), '(nn - ntol, nn + ntol + 1)\n', (5536, 5562), True, 'import numpy as np\n'), ((5924, 5951), 'MatlabHacks.rectpulse', 'mfuncs.rectpulse', (['lcands', '(2)'], {}), '(lcands, 2)\n', (5940, 5951), True, 'import MatlabHacks as mfuncs\n'), ((5992, 6013), 'numpy.array', 'np.array', (['[-0.5, 0.5]'], {}), '([-0.5, 0.5])\n', (6000, 6013), True, 'import numpy as np\n'), ((6888, 6915), 'numpy.arange', 'np.arange', (['(jj - 1)', '(jj + 1.5)'], {}), '(jj - 1, jj + 1.5)\n', (6897, 6915), True, 'import numpy as np\n'), ((6951, 6978), 'numpy.arange', 'np.arange', (['(jj - 1)', '(jj + 1.5)'], {}), '(jj - 1, jj + 1.5)\n', (6960, 6978), True, 'import numpy as np\n'), ((7780, 7802), 'numpy.absolute', 'np.absolute', (['summation'], {}), '(summation)\n', (7791, 7802), True, 'import numpy as np\n'), ((11975, 12001), 'numpy.arange', 'np.arange', (['(-jj1)', '(jj1 + 0.5)'], {}), '(-jj1, jj1 + 0.5)\n', (11984, 12001), True, 'import numpy as np\n'), ((1245, 1266), 'numpy.multiply', 'np.multiply', (['rr', '(-a_2)'], {}), '(rr, -a_2)\n', (1256, 1266), True, 'import numpy as np\n'), ((1274, 1294), 'numpy.multiply', 'np.multiply', (['rr', 'a_4'], {}), '(rr, a_4)\n', (1285, 1294), True, 'import numpy as np\n'), ((1445, 1460), 'numpy.power', 'np.power', (['rr', '(4)'], {}), '(rr, 4)\n', (1453, 1460), True, 'import numpy as np\n'), ((7804, 7826), 'numpy.absolute', 'np.absolute', (['summation'], {}), '(summation)\n', (7815, 7826), True, 'import numpy as np\n'), ((1506, 1524), 'numpy.divide', 'np.divide', (['rr', 'r_c'], {}), '(rr, r_c)\n', (1515, 1524), True, 'import numpy as np\n'), ((5816, 5837), 'numpy.array', 'np.array', (['[-0.5, 0.5]'], {}), '([-0.5, 0.5])\n', (5824, 5837), True, 'import numpy as np\n')] |
import math
import datetime
from django.conf import settings
from django.db import models
from django.db.models import Count, Sum, Avg
from django.db.models.signals import post_save, pre_save
from django.dispatch import Signal, receiver
from angalabiri.shop.models.productmodels import (
Product,
ProductFile,
ProductVariation,
ProductionImage,
)
from angalabiri.shop.models.cartmodels import Cart
from angalabiri.shop.models.ordermodels import Order
from angalabiri.shop.models.addressmodels import Address
from angalabiri.utils.models import unique_slug_generator
from paystackapi.product import Product as PaystackProduct
@receiver(pre_save, sender=Product)
def create_product_slug(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = unique_slug_generator(instance)
if not instance.product_id:
product = PaystackProduct.create(
name=instance.title,
description=instance.description,
price=instance.price,
currency="NGN",
**kwargs
)
instance.product_id = product.id
def product_post_saved_receiver(sender, instance, created, *args, **kwargs):
product = instance
variations = product.variation_set.all()
if variations.count() == 0:
new_var = ProductVariation()
new_var.product = product
new_var.title = product.title
new_var.price = product.price
new_var.save()
post_save.connect(product_post_saved_receiver, sender=Product)
| [
"paystackapi.product.Product.create",
"django.db.models.signals.post_save.connect",
"django.dispatch.receiver",
"angalabiri.utils.models.unique_slug_generator",
"angalabiri.shop.models.productmodels.ProductVariation"
] | [((646, 680), 'django.dispatch.receiver', 'receiver', (['pre_save'], {'sender': 'Product'}), '(pre_save, sender=Product)\n', (654, 680), False, 'from django.dispatch import Signal, receiver\n'), ((1461, 1523), 'django.db.models.signals.post_save.connect', 'post_save.connect', (['product_post_saved_receiver'], {'sender': 'Product'}), '(product_post_saved_receiver, sender=Product)\n', (1478, 1523), False, 'from django.db.models.signals import post_save, pre_save\n'), ((791, 822), 'angalabiri.utils.models.unique_slug_generator', 'unique_slug_generator', (['instance'], {}), '(instance)\n', (812, 822), False, 'from angalabiri.utils.models import unique_slug_generator\n'), ((873, 1003), 'paystackapi.product.Product.create', 'PaystackProduct.create', ([], {'name': 'instance.title', 'description': 'instance.description', 'price': 'instance.price', 'currency': '"""NGN"""'}), "(name=instance.title, description=instance.\n description, price=instance.price, currency='NGN', **kwargs)\n", (895, 1003), True, 'from paystackapi.product import Product as PaystackProduct\n'), ((1307, 1325), 'angalabiri.shop.models.productmodels.ProductVariation', 'ProductVariation', ([], {}), '()\n', (1323, 1325), False, 'from angalabiri.shop.models.productmodels import Product, ProductFile, ProductVariation, ProductionImage\n')] |
from aiohttp import hdrs, BasicAuth
from tests.conftest import USERNAME, PASSWORD
async def test_any_views_respond_401_when_auth_forced(aiohttp_client, app_factory): # noqa
app = app_factory(auth_force=True)
client = await aiohttp_client(app)
resp = await client.get('/')
assert resp.status == 401
async def test_public_views_respond_200_when_auth_not_forced(aiohttp_client, app_factory): # noqa
app = app_factory(auth_force=False)
client = await aiohttp_client(app)
resp = await client.get('/')
assert resp.status == 200
async def test_protected_views_respond_401_when_auth_not_forced(aiohttp_client, app_factory): # noqa
app = app_factory(auth_force=False)
client = await aiohttp_client(app)
resp = await client.get('/secret')
assert resp.status == 401
async def test_server_asks_for_auth(aiohttp_client, app_factory): # noqa
app = app_factory(auth_force=True)
client = await aiohttp_client(app)
resp = await client.get('/')
assert resp.status == 401
assert resp.headers[hdrs.WWW_AUTHENTICATE] == 'Basic realm=""'
async def test_server_asks_for_auth_custom_realm(aiohttp_client, app_factory): # noqa
realm = 'Protected Area'
app = app_factory(auth_force=True, realm=realm)
client = await aiohttp_client(app)
resp = await client.get('/')
assert resp.status == 401
assert resp.headers[hdrs.WWW_AUTHENTICATE] == 'Basic realm="%s"' % realm
async def test_protected_views_respond_200_when_passing_auth_headers(aiohttp_client, app_factory): # noqa
app = app_factory(auth_force=True)
client = await aiohttp_client(app)
resp = await client.get('/secret', auth=BasicAuth(USERNAME, PASSWORD))
assert resp.status == 200
async def test_protected_views_respond_401_when_passing_invalid_credentials(aiohttp_client, app_factory): # noqa
app = app_factory(auth_force=True)
client = await aiohttp_client(app)
resp = await client.get(
'/secret',
auth=BasicAuth(USERNAME, PASSWORD + '<PASSWORD>')
)
assert resp.status == 401
| [
"aiohttp.BasicAuth"
] | [((1733, 1762), 'aiohttp.BasicAuth', 'BasicAuth', (['USERNAME', 'PASSWORD'], {}), '(USERNAME, PASSWORD)\n', (1742, 1762), False, 'from aiohttp import hdrs, BasicAuth\n'), ((2060, 2104), 'aiohttp.BasicAuth', 'BasicAuth', (['USERNAME', "(PASSWORD + '<PASSWORD>')"], {}), "(USERNAME, PASSWORD + '<PASSWORD>')\n", (2069, 2104), False, 'from aiohttp import hdrs, BasicAuth\n')] |
# -*- coding: utf-8 -*-
############################################################################
#
# Copyright © 2013, 2015 OnlineGroups.net and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
############################################################################
from __future__ import unicode_literals
from urllib import quote
from zope.cachedescriptors.property import Lazy
from zope.component import createObject
from Products.Five.browser.pagetemplatefile import ZopeTwoPageTemplateFile
from gs.errormesg.baseerror import BaseErrorPage
class EmailVerifyError(BaseErrorPage):
def __init__(self, context, request):
BaseErrorPage.__init__(self, context, request)
self.verificationId = request.form.get('verificationId', '')
self.linkAddress = '%s/r/verify/%s' % \
(self.siteInfo.url, self.verificationId)
class VerifyIdNotFound(EmailVerifyError):
fileName = 'browser/templates/verify_id_not_found.pt'
index = ZopeTwoPageTemplateFile(fileName)
def __init__(self, context, request):
EmailVerifyError.__init__(self, context, request)
m = 'Hi! I tried verifying my email address using the link %s but '\
'I saw an Email Verification Error page. I tried... but it '\
'did not help.' % self.linkAddress
self.message = quote(m)
def __call__(self, *args, **kw):
self.request.response.setHeader(b'Content-Type',
b'text/html; charset=UTF-8')
# Return 404: Not Found
self.request.response.setStatus(404)
return self.index(self, *args, **kw)
class VerifyIdUsed(EmailVerifyError):
fileName = 'browser/templates/verify_id_used.pt'
index = ZopeTwoPageTemplateFile(fileName)
def __init__(self, context, request):
EmailVerifyError.__init__(self, context, request)
m = 'Hi! I tried verifying my email address using the link %s but '\
'I saw an Email Verification Link Used page. I was trying '\
'to...' % self.linkAddress
self.__loggedInUser = None
self.message = quote(m)
@Lazy
def loggedInUser(self):
retval = createObject('groupserver.LoggedInUser', self.context)
return retval
def __call__(self, *args, **kw):
self.request.response.setHeader(b'Content-Type',
b'text/html; charset=UTF-8')
# Return 410: Gone
self.request.response.setStatus(410)
return self.index(self, *args, **kw)
class VerifyNoId(BaseErrorPage):
fileName = 'browser/templates/verify_no_id.pt'
index = ZopeTwoPageTemplateFile(fileName)
def __init__(self, context, request):
BaseErrorPage.__init__(self, context, request)
self.linkAddress = '%s/r/verify/' % self.siteInfo.url
m = 'Hi! I followed the the link %s but I saw an Email '\
'Verification Link Error page. I was trying to get to... I '\
'found the link in...' % self.linkAddress
self.message = quote(m)
def __call__(self, *args, **kw):
self.request.response.setHeader(b'Content-Type',
b'text/html; charset=UTF-8')
# Return 400: Bad Request
self.request.response.setStatus(400)
return self.index(self, *args, **kw)
| [
"urllib.quote",
"Products.Five.browser.pagetemplatefile.ZopeTwoPageTemplateFile",
"gs.errormesg.baseerror.BaseErrorPage.__init__",
"zope.component.createObject"
] | [((1360, 1393), 'Products.Five.browser.pagetemplatefile.ZopeTwoPageTemplateFile', 'ZopeTwoPageTemplateFile', (['fileName'], {}), '(fileName)\n', (1383, 1393), False, 'from Products.Five.browser.pagetemplatefile import ZopeTwoPageTemplateFile\n'), ((2116, 2149), 'Products.Five.browser.pagetemplatefile.ZopeTwoPageTemplateFile', 'ZopeTwoPageTemplateFile', (['fileName'], {}), '(fileName)\n', (2139, 2149), False, 'from Products.Five.browser.pagetemplatefile import ZopeTwoPageTemplateFile\n'), ((3019, 3052), 'Products.Five.browser.pagetemplatefile.ZopeTwoPageTemplateFile', 'ZopeTwoPageTemplateFile', (['fileName'], {}), '(fileName)\n', (3042, 3052), False, 'from Products.Five.browser.pagetemplatefile import ZopeTwoPageTemplateFile\n'), ((1029, 1075), 'gs.errormesg.baseerror.BaseErrorPage.__init__', 'BaseErrorPage.__init__', (['self', 'context', 'request'], {}), '(self, context, request)\n', (1051, 1075), False, 'from gs.errormesg.baseerror import BaseErrorPage\n'), ((1716, 1724), 'urllib.quote', 'quote', (['m'], {}), '(m)\n', (1721, 1724), False, 'from urllib import quote\n'), ((2498, 2506), 'urllib.quote', 'quote', (['m'], {}), '(m)\n', (2503, 2506), False, 'from urllib import quote\n'), ((2563, 2617), 'zope.component.createObject', 'createObject', (['"""groupserver.LoggedInUser"""', 'self.context'], {}), "('groupserver.LoggedInUser', self.context)\n", (2575, 2617), False, 'from zope.component import createObject\n'), ((3104, 3150), 'gs.errormesg.baseerror.BaseErrorPage.__init__', 'BaseErrorPage.__init__', (['self', 'context', 'request'], {}), '(self, context, request)\n', (3126, 3150), False, 'from gs.errormesg.baseerror import BaseErrorPage\n'), ((3430, 3438), 'urllib.quote', 'quote', (['m'], {}), '(m)\n', (3435, 3438), False, 'from urllib import quote\n')] |
# Generated by Django 2.2 on 2019-11-23 14:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('courses', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='course',
name='learn_times',
field=models.IntegerField(default=0, verbose_name='需要学习时长(分钟数)'),
),
]
| [
"django.db.models.IntegerField"
] | [((326, 384), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'default': '(0)', 'verbose_name': '"""需要学习时长(分钟数)"""'}), "(default=0, verbose_name='需要学习时长(分钟数)')\n", (345, 384), False, 'from django.db import migrations, models\n')] |
#!/usr/bin/env python
# Class autogenerated from /home/sam/Downloads/aldebaran_sw/nao/naoqi-sdk-2.1.4.13-linux64/include/alproxies/alsegmentation3dproxy.h
# by <NAME> <Sammy.Pfeiffer at student.uts.edu.au> generator
# You need an ALBroker running
from naoqi import ALProxy
class ALSegmentation3D(object):
def __init__(self, session):
self.proxy = None
self.session = session
def force_connect(self):
self.proxy = ALProxy("ALSegmentation3D")
def getActiveCamera(self):
"""
:returns int:
"""
if not self.proxy:
self.proxy = ALProxy("ALSegmentation3D")
return self.proxy.getActiveCamera()
def getBlobTrackingDistance(self):
"""Gets the distance (in meters) for the blob tracker
:returns float:
"""
if not self.proxy:
self.proxy = ALProxy("ALSegmentation3D")
return self.proxy.getBlobTrackingDistance()
def getCurrentPeriod(self):
"""Gets the current period.
:returns int: Refresh period (in milliseconds).
"""
if not self.proxy:
self.proxy = ALProxy("ALSegmentation3D")
return self.proxy.getCurrentPeriod()
def getCurrentPrecision(self):
"""Gets the current precision.
:returns float: Precision of the extractor.
"""
if not self.proxy:
self.proxy = ALProxy("ALSegmentation3D")
return self.proxy.getCurrentPrecision()
def getDeltaDepthThreshold(self):
"""Gets the value of the depth threshold (in meters) used for the segmentation
:returns float: Current depth threshold (in meters)
"""
if not self.proxy:
self.proxy = ALProxy("ALSegmentation3D")
return self.proxy.getDeltaDepthThreshold()
def getEventList(self):
"""Get the list of events updated in ALMemory.
:returns std::vector<std::string>: Array of events updated by this extractor in ALMemory
"""
if not self.proxy:
self.proxy = ALProxy("ALSegmentation3D")
return self.proxy.getEventList()
def getFrameRate(self):
"""
:returns int:
"""
if not self.proxy:
self.proxy = ALProxy("ALSegmentation3D")
return self.proxy.getFrameRate()
def getMemoryKeyList(self):
"""Get the list of events updated in ALMemory.
:returns std::vector<std::string>: Array of events updated by this extractor in ALMemory
"""
if not self.proxy:
self.proxy = ALProxy("ALSegmentation3D")
return self.proxy.getMemoryKeyList()
def getMyPeriod(self, name):
"""Gets the period for a specific subscription.
:param str name: Name of the module which has subscribed.
:returns int: Refresh period (in milliseconds).
"""
if not self.proxy:
self.proxy = ALProxy("ALSegmentation3D")
return self.proxy.getMyPeriod(name)
def getMyPrecision(self, name):
"""Gets the precision for a specific subscription.
:param str name: name of the module which has subscribed
:returns float: precision of the extractor
"""
if not self.proxy:
self.proxy = ALProxy("ALSegmentation3D")
return self.proxy.getMyPrecision(name)
def getOutputNames(self):
"""Get the list of values updated in ALMemory.
:returns std::vector<std::string>: Array of values updated by this extractor in ALMemory
"""
if not self.proxy:
self.proxy = ALProxy("ALSegmentation3D")
return self.proxy.getOutputNames()
def getResolution(self):
"""
:returns int:
"""
if not self.proxy:
self.proxy = ALProxy("ALSegmentation3D")
return self.proxy.getResolution()
def getSubscribersInfo(self):
"""Gets the parameters given by the module.
:returns AL::ALValue: Array of names and parameters of all subscribers.
"""
if not self.proxy:
self.proxy = ALProxy("ALSegmentation3D")
return self.proxy.getSubscribersInfo()
def getTopOfBlob(self, distance, frame, applyVerticalOffset):
"""Returns the position of the top of the blob most in the center of the depth image, at the given distance, in the given frame.
:param float distance: Estimation of the distance (in meters) of the blob or -1 for the nearest blob
:param int frame: Frame in which to return the position (-1: FRAME_IMAGE, 0: FRAME_TORSO, 1: FRAME_WORLD, 2: FRAME_ROBOT
:param bool applyVerticalOffset: True to apply the VerticalOffset when computing the position, False otherwise
:returns AL::ALValue: Position of the top of the corresponding blob (if one is found) in the given frame (Format: [yaw,pitch,distance] in FRAME_IMAGE, [x,y,z] in the other frame).
"""
if not self.proxy:
self.proxy = ALProxy("ALSegmentation3D")
return self.proxy.getTopOfBlob(distance, frame, applyVerticalOffset)
def getVerticalOffset(self):
"""Sets the value of vertical offset (in meters) for the blob tracker
:returns float: Current vertical offset of the blob tracker
"""
if not self.proxy:
self.proxy = ALProxy("ALSegmentation3D")
return self.proxy.getVerticalOffset()
def isBlobTrackingEnabled(self):
"""Gets the current status of the blob tracker. When the blob tracker is running, events containing the position of the top of the tracked blob are raised.
:returns bool: True if the blob tracker is enabled, False otherwise.
"""
if not self.proxy:
self.proxy = ALProxy("ALSegmentation3D")
return self.proxy.isBlobTrackingEnabled()
def isPaused(self):
"""
:returns bool:
"""
if not self.proxy:
self.proxy = ALProxy("ALSegmentation3D")
return self.proxy.isPaused()
def isProcessing(self):
"""
:returns bool:
"""
if not self.proxy:
self.proxy = ALProxy("ALSegmentation3D")
return self.proxy.isProcessing()
def pause(self, status):
"""
:param bool status:
"""
if not self.proxy:
self.proxy = ALProxy("ALSegmentation3D")
return self.proxy.pause(status)
def ping(self):
"""Just a ping. Always returns true
:returns bool: returns true
"""
if not self.proxy:
self.proxy = ALProxy("ALSegmentation3D")
return self.proxy.ping()
def setActiveCamera(self, cameraID):
"""
:param int cameraID:
:returns bool:
"""
if not self.proxy:
self.proxy = ALProxy("ALSegmentation3D")
return self.proxy.setActiveCamera(cameraID)
def setBlobTrackingDistance(self, distance):
"""Sets the distance (in meters) for the blob tracker
:param float distance: New value (in meters)
"""
if not self.proxy:
self.proxy = ALProxy("ALSegmentation3D")
return self.proxy.setBlobTrackingDistance(distance)
def setBlobTrackingEnabled(self, status):
"""Turn the blob tracker on or off. When the blob tracker is running, events containing the position of the top of the tracked blob are raised.
:param bool status: True to turn it on, False to turn it off.
"""
if not self.proxy:
self.proxy = ALProxy("ALSegmentation3D")
return self.proxy.setBlobTrackingEnabled(status)
def setDeltaDepthThreshold(self, value):
"""Sets the value of the depth threshold (in meters) used for the segmentation
:param float value: New depth threshold (in meters) for the segmentation
"""
if not self.proxy:
self.proxy = ALProxy("ALSegmentation3D")
return self.proxy.setDeltaDepthThreshold(value)
def setFrameRate(self, value):
"""
:param int value:
:returns bool:
"""
if not self.proxy:
self.proxy = ALProxy("ALSegmentation3D")
return self.proxy.setFrameRate(value)
def setResolution(self, resolution):
"""
:param int resolution:
:returns bool:
"""
if not self.proxy:
self.proxy = ALProxy("ALSegmentation3D")
return self.proxy.setResolution(resolution)
def setVerticalOffset(self, value):
"""Sets the value of vertical offset (in meters) for the blob tracker
:param float value: New vertical offset (in meters), added if positive, substracted if negative
"""
if not self.proxy:
self.proxy = ALProxy("ALSegmentation3D")
return self.proxy.setVerticalOffset(value)
def subscribe(self, name, period, precision):
"""Subscribes to the extractor. This causes the extractor to start writing information to memory using the keys described by getOutputNames(). These can be accessed in memory using ALMemory.getData("keyName"). In many cases you can avoid calling subscribe on the extractor by just calling ALMemory.subscribeToEvent() supplying a callback method. This will automatically subscribe to the extractor for you.
:param str name: Name of the module which subscribes.
:param int period: Refresh period (in milliseconds) if relevant.
:param float precision: Precision of the extractor if relevant.
"""
if not self.proxy:
self.proxy = ALProxy("ALSegmentation3D")
return self.proxy.subscribe(name, period, precision)
def subscribe2(self, name):
"""Subscribes to the extractor. This causes the extractor to start writing information to memory using the keys described by getOutputNames(). These can be accessed in memory using ALMemory.getData("keyName"). In many cases you can avoid calling subscribe on the extractor by just calling ALMemory.subscribeToEvent() supplying a callback method. This will automatically subscribe to the extractor for you.
:param str name: Name of the module which subscribes.
"""
if not self.proxy:
self.proxy = ALProxy("ALSegmentation3D")
return self.proxy.subscribe(name)
def unsubscribe(self, name):
"""Unsubscribes from the extractor.
:param str name: Name of the module which had subscribed.
"""
if not self.proxy:
self.proxy = ALProxy("ALSegmentation3D")
return self.proxy.unsubscribe(name)
def updatePeriod(self, name, period):
"""Updates the period if relevant.
:param str name: Name of the module which has subscribed.
:param int period: Refresh period (in milliseconds).
"""
if not self.proxy:
self.proxy = ALProxy("ALSegmentation3D")
return self.proxy.updatePeriod(name, period)
def updatePrecision(self, name, precision):
"""Updates the precision if relevant.
:param str name: Name of the module which has subscribed.
:param float precision: Precision of the extractor.
"""
if not self.proxy:
self.proxy = ALProxy("ALSegmentation3D")
return self.proxy.updatePrecision(name, precision)
def version(self):
"""Returns the version of the module.
:returns str: A string containing the version of the module.
"""
if not self.proxy:
self.proxy = ALProxy("ALSegmentation3D")
return self.proxy.version()
| [
"naoqi.ALProxy"
] | [((451, 478), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (458, 478), False, 'from naoqi import ALProxy\n'), ((611, 638), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (618, 638), False, 'from naoqi import ALProxy\n'), ((875, 902), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (882, 902), False, 'from naoqi import ALProxy\n'), ((1145, 1172), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (1152, 1172), False, 'from naoqi import ALProxy\n'), ((1410, 1437), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (1417, 1437), False, 'from naoqi import ALProxy\n'), ((1737, 1764), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (1744, 1764), False, 'from naoqi import ALProxy\n'), ((2062, 2089), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (2069, 2089), False, 'from naoqi import ALProxy\n'), ((2260, 2287), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (2267, 2287), False, 'from naoqi import ALProxy\n'), ((2579, 2606), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (2586, 2606), False, 'from naoqi import ALProxy\n'), ((2929, 2956), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (2936, 2956), False, 'from naoqi import ALProxy\n'), ((3278, 3305), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (3285, 3305), False, 'from naoqi import ALProxy\n'), ((3601, 3628), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (3608, 3628), False, 'from naoqi import ALProxy\n'), ((3802, 3829), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (3809, 3829), False, 'from naoqi import ALProxy\n'), ((4104, 4131), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (4111, 4131), False, 'from naoqi import ALProxy\n'), ((4993, 5020), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (5000, 5020), False, 'from naoqi import ALProxy\n'), ((5343, 5370), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (5350, 5370), False, 'from naoqi import ALProxy\n'), ((5761, 5788), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (5768, 5788), False, 'from naoqi import ALProxy\n'), ((5965, 5992), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (5972, 5992), False, 'from naoqi import ALProxy\n'), ((6160, 6187), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (6167, 6187), False, 'from naoqi import ALProxy\n'), ((6365, 6392), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (6372, 6392), False, 'from naoqi import ALProxy\n'), ((6599, 6626), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (6606, 6626), False, 'from naoqi import ALProxy\n'), ((6833, 6860), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (6840, 6860), False, 'from naoqi import ALProxy\n'), ((7143, 7170), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (7150, 7170), False, 'from naoqi import ALProxy\n'), ((7565, 7592), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (7572, 7592), False, 'from naoqi import ALProxy\n'), ((7929, 7956), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (7936, 7956), False, 'from naoqi import ALProxy\n'), ((8177, 8204), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (8184, 8204), False, 'from naoqi import ALProxy\n'), ((8426, 8453), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (8433, 8453), False, 'from naoqi import ALProxy\n'), ((8794, 8821), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (8801, 8821), False, 'from naoqi import ALProxy\n'), ((9610, 9637), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (9617, 9637), False, 'from naoqi import ALProxy\n'), ((10273, 10300), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (10280, 10300), False, 'from naoqi import ALProxy\n'), ((10552, 10579), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (10559, 10579), False, 'from naoqi import ALProxy\n'), ((10902, 10929), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (10909, 10929), False, 'from naoqi import ALProxy\n'), ((11269, 11296), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (11276, 11296), False, 'from naoqi import ALProxy\n'), ((11560, 11587), 'naoqi.ALProxy', 'ALProxy', (['"""ALSegmentation3D"""'], {}), "('ALSegmentation3D')\n", (11567, 11587), False, 'from naoqi import ALProxy\n')] |
import datetime
from fp17 import treatments
def annotate(bcds1):
bcds1.patient.surname = "BULWELL"
bcds1.patient.forename = "LILY"
bcds1.patient.address = ["18 HIGH STREET"]
bcds1.patient.sex = 'F'
bcds1.patient.date_of_birth = datetime.date(1968, 4, 28)
bcds1.date_of_acceptance = datetime.date(2017, 4, 1)
bcds1.date_of_completion = datetime.date(2017, 4, 1)
# Treatments: "Ethnic Origin 1"
bcds1.treatments = [
treatments.PRESCRIPTION,
treatments.ETHNIC_ORIGIN_1_WHITE_BRITISH,
]
return bcds1
| [
"datetime.date"
] | [((251, 277), 'datetime.date', 'datetime.date', (['(1968)', '(4)', '(28)'], {}), '(1968, 4, 28)\n', (264, 277), False, 'import datetime\n'), ((310, 335), 'datetime.date', 'datetime.date', (['(2017)', '(4)', '(1)'], {}), '(2017, 4, 1)\n', (323, 335), False, 'import datetime\n'), ((367, 392), 'datetime.date', 'datetime.date', (['(2017)', '(4)', '(1)'], {}), '(2017, 4, 1)\n', (380, 392), False, 'import datetime\n')] |
import math
import pandas as pd
from dataclasses import dataclass
from typing import Dict, List, Optional, Tuple
# document id -> judgement for that document
JudgedDocuments = Dict[str, float]
@dataclass
class JudgedQuery:
query: str
judgements: JudgedDocuments
def __post_init__(self):
self.documents_in_ideal_order: List[Tuple[str, float]] = sorted(self.judgements.items(),
key=lambda item: item[1], reverse=True)
def get_judgement(self, doc_id: str) -> Optional[float]:
return self.judgements.get(doc_id)
def idcg(self, at_n: int = 10):
idcg = 0
for i in range(min(len(self.documents_in_ideal_order), at_n)):
denom = math.log(i + 2, 2)
idcg += self.documents_in_ideal_order[i][1] / denom
return idcg
def read_judgements_file(filename: str) -> pd.DataFrame:
df = pd.read_csv(filename, header=0, dtype={'query': str, 'docid': str, 'rating': float})
return df
def read_judgements_to_dict(filename: str) -> Dict[str, JudgedQuery]:
df = read_judgements_file(filename)
judgements: Dict[str, JudgedQuery] = {}
for row in df.itertuples():
judged_query = judgements.get(row.query, JudgedQuery(row.query, {}))
if not math.isnan(row.rating):
judged_query.judgements.update({row.docid: row.rating})
judgements.update({row.query: judged_query})
judged_query.__post_init__()
return judgements
class Judgements:
def __init__(self, judgements_file: str):
self.judged_queries: Dict[str, JudgedQuery] = read_judgements_to_dict(judgements_file)
def get_judgements_for_query(self, query: str) -> Optional[JudgedQuery]:
return self.judged_queries.get(query)
def get_judgement(self, query: str, doc: str) -> Optional[float]:
return self.get_judgements_for_query(query).get_judgement(doc)
| [
"math.isnan",
"pandas.read_csv",
"math.log"
] | [((935, 1023), 'pandas.read_csv', 'pd.read_csv', (['filename'], {'header': '(0)', 'dtype': "{'query': str, 'docid': str, 'rating': float}"}), "(filename, header=0, dtype={'query': str, 'docid': str, 'rating':\n float})\n", (946, 1023), True, 'import pandas as pd\n'), ((764, 782), 'math.log', 'math.log', (['(i + 2)', '(2)'], {}), '(i + 2, 2)\n', (772, 782), False, 'import math\n'), ((1314, 1336), 'math.isnan', 'math.isnan', (['row.rating'], {}), '(row.rating)\n', (1324, 1336), False, 'import math\n')] |
import requests
from flask import Flask, request, render_template
from forms.analysis import AnalysisForm
from utils.rest import invoke_get_request, get_chart_url
from utils import config
app = Flask(__name__)
app.config['SECRET_KEY'] = 'ebs-salinization-bentre'
@app.route('/')
@app.route('/index')
def home():
form = AnalysisForm()
return render_template('home.html', form=form)
@app.route('/forecast', methods=['GET', 'POST'])
def forecast():
if request.method == 'GET':
station = request.args.get('station')
start = request.args.get('start')
end = request.args.get('end')
else:
station = request.form['station']
start = request.form['start']
end = request.form['end']
result = invoke_get_request(f'/forecast/{station}/{start}/{end}')
return render_template('result.html', station=station, result=result, len=len(result.get('data')), chart=f'/chart/{result.get("chart")}')
@app.route('/chart/<string:file>', methods=['GET'])
def stream_chart(file):
return requests.get(get_chart_url(file)).content
@app.route('/about')
def about():
return render_template('about.html')
if __name__ == '__main__':
debug = config.get_config()['rest']['debug'].get(True)
# host 0.0.0.0 allows the app running on host machine ip
app.run(host='0.0.0.0', port=5000, debug=debug) | [
"utils.config.get_config",
"utils.rest.invoke_get_request",
"forms.analysis.AnalysisForm",
"flask.request.args.get",
"flask.render_template",
"utils.rest.get_chart_url",
"flask.Flask"
] | [((197, 212), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (202, 212), False, 'from flask import Flask, request, render_template\n'), ((327, 341), 'forms.analysis.AnalysisForm', 'AnalysisForm', ([], {}), '()\n', (339, 341), False, 'from forms.analysis import AnalysisForm\n'), ((353, 392), 'flask.render_template', 'render_template', (['"""home.html"""'], {'form': 'form'}), "('home.html', form=form)\n", (368, 392), False, 'from flask import Flask, request, render_template\n'), ((756, 812), 'utils.rest.invoke_get_request', 'invoke_get_request', (['f"""/forecast/{station}/{start}/{end}"""'], {}), "(f'/forecast/{station}/{start}/{end}')\n", (774, 812), False, 'from utils.rest import invoke_get_request, get_chart_url\n'), ((1138, 1167), 'flask.render_template', 'render_template', (['"""about.html"""'], {}), "('about.html')\n", (1153, 1167), False, 'from flask import Flask, request, render_template\n'), ((510, 537), 'flask.request.args.get', 'request.args.get', (['"""station"""'], {}), "('station')\n", (526, 537), False, 'from flask import Flask, request, render_template\n'), ((554, 579), 'flask.request.args.get', 'request.args.get', (['"""start"""'], {}), "('start')\n", (570, 579), False, 'from flask import Flask, request, render_template\n'), ((594, 617), 'flask.request.args.get', 'request.args.get', (['"""end"""'], {}), "('end')\n", (610, 617), False, 'from flask import Flask, request, render_template\n'), ((1062, 1081), 'utils.rest.get_chart_url', 'get_chart_url', (['file'], {}), '(file)\n', (1075, 1081), False, 'from utils.rest import invoke_get_request, get_chart_url\n'), ((1209, 1228), 'utils.config.get_config', 'config.get_config', ([], {}), '()\n', (1226, 1228), False, 'from utils import config\n')] |
"""
Test sphinx extensions.
"""
from code_annotations.contrib.sphinx.extensions.base import find_annotations, quote_value
def test_collect_pii_for_sphinx():
annotations = find_annotations(
"tests/extensions/python_test_files/simple_success.pyt",
"tests/test_configurations/.annotations_test",
".. pii:",
)
assert {
".. pii_types:": ["id", "name"],
".. pii_retirement:": ["local_api", "consumer_api"],
"filename": "simple_success.pyt",
"line_number": 1,
} == annotations["Annotation 1"]
assert {
".. pii_types:": ["id", "name"],
".. pii_retirement:": ["local_api", "consumer_api"],
"filename": "simple_success.pyt",
"line_number": 11,
} == annotations["Annotation 2"]
assert 5 == len(annotations)
def test_quote_value():
assert "True" == quote_value("True")
assert "None" == quote_value("None")
assert "1" == quote_value("1")
assert "1.414" == quote_value("1.414")
assert '"some string"' == quote_value("some string")
| [
"code_annotations.contrib.sphinx.extensions.base.quote_value",
"code_annotations.contrib.sphinx.extensions.base.find_annotations"
] | [((177, 312), 'code_annotations.contrib.sphinx.extensions.base.find_annotations', 'find_annotations', (['"""tests/extensions/python_test_files/simple_success.pyt"""', '"""tests/test_configurations/.annotations_test"""', '""".. pii:"""'], {}), "('tests/extensions/python_test_files/simple_success.pyt',\n 'tests/test_configurations/.annotations_test', '.. pii:')\n", (193, 312), False, 'from code_annotations.contrib.sphinx.extensions.base import find_annotations, quote_value\n'), ((863, 882), 'code_annotations.contrib.sphinx.extensions.base.quote_value', 'quote_value', (['"""True"""'], {}), "('True')\n", (874, 882), False, 'from code_annotations.contrib.sphinx.extensions.base import find_annotations, quote_value\n'), ((904, 923), 'code_annotations.contrib.sphinx.extensions.base.quote_value', 'quote_value', (['"""None"""'], {}), "('None')\n", (915, 923), False, 'from code_annotations.contrib.sphinx.extensions.base import find_annotations, quote_value\n'), ((942, 958), 'code_annotations.contrib.sphinx.extensions.base.quote_value', 'quote_value', (['"""1"""'], {}), "('1')\n", (953, 958), False, 'from code_annotations.contrib.sphinx.extensions.base import find_annotations, quote_value\n'), ((981, 1001), 'code_annotations.contrib.sphinx.extensions.base.quote_value', 'quote_value', (['"""1.414"""'], {}), "('1.414')\n", (992, 1001), False, 'from code_annotations.contrib.sphinx.extensions.base import find_annotations, quote_value\n'), ((1032, 1058), 'code_annotations.contrib.sphinx.extensions.base.quote_value', 'quote_value', (['"""some string"""'], {}), "('some string')\n", (1043, 1058), False, 'from code_annotations.contrib.sphinx.extensions.base import find_annotations, quote_value\n')] |
import pandas as pd
import numpy as np
import tensorflow as tf
import dask
import scipy
import time
from functools import partial
from abc import ABCMeta, abstractmethod
from sklearn.decomposition import PCA
from sklearn.preprocessing import scale
from sklearn.linear_model import LinearRegression
import tensorflowModel
class LinearProjection(tensorflowModel.tensorflowModel):
#######################################################################################################
#Construction functions
#######################################################################################################
def __init__(self,
learningRate,
hyperParameters,
nbUnitsPerLayer,
nbFactors,
modelName = "./bestLinearModel"):
super().__init__(learningRate,
hyperParameters,
nbUnitsPerLayer,
nbFactors,
modelName)
def buildArchitecture(self):
self.inputTensor = tf.placeholder(tf.float32,
shape=[None, self.nbUnitsPerLayer['Input Layer']])#batch size along
if self.verbose :
print(self.inputTensor)
self.factorTensor = self.buildDenseLayer(self.nbFactors,
self.inputTensor,
activation = None)
if self.verbose :
print(self.factorTensor)
self.nbEncoderLayer = len(self.layers)
# DECODE --------------------------------------------------------------------
lastTensor = self.factorTensor
for k in range(self.nbEncoderLayer):
lastTensor = self.buildInverseLayer(lastTensor)
self.outputTensor = lastTensor
if self.verbose :
print(self.outputTensor)
return
def getDecoderCoefficients(self):
#Rebuild tensor graph
self.restoringGraph()
#Evaluating surface for these factor Values
projectionMatrix = None
with tf.Session() as sess :
#Restoring Model
sess.run(self.init)
self.restoreWeights(sess)
#We know that latest layer is fylly connected one without activation function
projectionMatrix = self.layers[-1].weights.eval()
return projectionMatrix
class PCAScaled(LinearProjection):
#######################################################################################################
#Construction functions
#######################################################################################################
def __init__(self,
learningRate,
hyperParameters,
nbUnitsPerLayer,
nbFactors,
modelName = "./bestPCAScaledModel"):
self.components = None
super().__init__(learningRate,
hyperParameters,
nbUnitsPerLayer,
nbFactors,
modelName)
#Build a tensor that construct
def buildReconstructionTensor(self, factorTensor):
l = tf.matmul(factorTensor, self.components, adjoint_b=True)
return l * self.std + self.mean
def buildArchitecture(self):
self.inputTensor = tf.placeholder(tf.float32,
shape=[None, self.nbUnitsPerLayer['Input Layer']])#batch size along
self.components = tf.Variable(np.ones(shape=(self.nbUnitsPerLayer['Input Layer'],
self.nbFactors)).astype(np.float32))
self.mean = tf.Variable(np.zeros(shape=(self.nbUnitsPerLayer['Input Layer'])).astype(np.float32))
self.std = tf.Variable(np.ones(shape=(self.nbUnitsPerLayer['Input Layer'])).astype(np.float32))
scaledInputTensor = (self.inputTensor - self.mean) / self.std
self.factorTensor = tf.matmul(scaledInputTensor, self.components)
scaledOutputTensor = tf.matmul(self.factorTensor, self.components, adjoint_b=True)
self.outputTensor = scaledOutputTensor * self.std + self.mean
return
#Build the architecture, losses and optimizer.
def buildModel(self):
tf.reset_default_graph()
if self.verbose :
print("build architecture, loss and penalisations")
self.buildArchitecture()
self.reconstructionLoss = self.buildReconstructionLoss(self.outputTensor,
self.inputTensor,
"reconstructionLoss")
self.reducedReconstructionLoss = self.normalizeLoss(self.reconstructionLoss,
"reducedReconstructionLoss")
self.penalizationList = self.buildPenalization()
self.loss = tf.add_n([self.reducedReconstructionLoss] + self.penalizationList,
name="loss")
self.optimizer = tf.train.AdamOptimizer(self.learningRate, name="optimizer")
self.componentsHolder = tf.placeholder(self.components.dtype,
shape=self.components.get_shape())
self.meansHolder = tf.placeholder(self.mean.dtype,
shape=self.mean.get_shape())
self.stdsHolder = tf.placeholder(self.std.dtype,
shape=self.std.get_shape())
self.trainingMean = self.mean.assign(self.meansHolder)
self.trainingStd = self.std.assign(self.stdsHolder)
self.trainingOperator = self.components.assign(self.componentsHolder)
self.init = tf.global_variables_initializer()
self.saver = tf.train.Saver(name="saver", save_relative_paths=True)
return
def createFeedDictEncoder(self, *args):
feedDict = None
if len(args)==1 :
feedDict = {self.inputTensor : args[0][0]}
else :
feedDict = {self.inputTensor : args[0][0],
self.componentsHolder : args[1],
self.meansHolder : args[2],
self.stdsHolder : args[3]}
return feedDict
#######################################################################################################
#Training functions
#######################################################################################################
def gradientDescent(self,
session,
datasetTrain,
nbEpoch,
dataSetTest,
trainingLoss,
gradientStep,
validationLoss):
epochLosses = []
useValidationDataSet = (('validationPercentage' in self.hyperParameters) &
(self.hyperParameters['validationPercentage'] > 0.001))
validationSet, trainingSet = self.splitValidationAndTrainingSet(datasetTrain)
validationLosses = []
epsilon = 0.00001
testingSet = dataSetTest if (dataSetTest is not None) else trainingSet
pca = PCA(n_components=self.nbFactors)
_ = pca.fit_transform(scale(trainingSet[0]))
muTrain = trainingSet[0].mean(axis=0)
stdTrain = trainingSet[0].std(axis=0)
feedDict = self.createFeedDictEncoder(trainingSet, pca.components_.T, muTrain, stdTrain)
session.run([self.trainingOperator, self.trainingMean, self.trainingStd],
feed_dict=feedDict)
epochLosses.append(trainingLoss.eval(feed_dict=self.createFeedDictEncoder(testingSet)))
self.explained_variance_ratio_ = pca.explained_variance_ratio_
validationLosses.append(
validationLoss.eval(feed_dict=self.createFeedDictEncoder(validationSet)))
if self.verbose :
print("Epoch : ", 0, " , Validation Loss : ", validationLosses)
save_path = self.saveModel(session, self.metaModelName)
if self.verbose :
print(validationLoss.eval(feed_dict=self.createFeedDictEncoder(validationSet)))
return np.array(epochLosses), np.array(validationLosses)
def getDecoderCoefficients(self):
#raise NotImplementedError("Not allowed for PCA because of mean rescaling !")
return None
#Build a tensor that construct a surface from factors values
def buildAutoEncoderTensor(self, surfaceTensor):
lastTensor = (surfaceTensor - self.mean) / self.std
lastTensor = tf.matmul(lastTensor, self.components)
lastTensor = tf.matmul(lastTensor, self.components, adjoint_b=True)
return lastTensor * self.std + self.mean
# def buildCompletionLoss(self, factorTensor, calibrationLoss, completedSurfaceTensor):
# previousPenalization = super().buildCompletionLoss(factorTensor, calibrationLoss, completedSurfaceTensor)
# finalCalibrationLoss = previousPenalization
# if "lambdaCompletionEncodings" in self.hyperParameters :
#completedEncodings = self.buildEncoderTensor(completedSurfaceTensor)
# reconstructedSurface = self.buildAutoEncoderTensor(completedSurfaceTensor)
# calibrationLoss = self.buildLoss(reconstructedSurface,
# self.sparseSurfaceTensor,
# name="calibrationLossOutlier" )
#outlierRegularization = tf.reduce_mean(self.buildReconstructionLoss(completedSurfaceTensor,
# reconstructedSurface,
# "EncodingRegularization"))
#finalCalibrationLoss += self.hyperParameters["lambdaCompletionEncodings"] * outlierRegularization
# finalCalibrationLoss = calibrationLoss
# return finalCalibrationLoss
def completeDataTensor(self,
sparseSurfaceList,
initialValueForFactors,
nbCalibrationStep,
*args):
#Rebuild tensor graph
self.restoringGraph()
#Build tensor for reconstruction
reshapedSparseSurface = np.reshape([sparseSurfaceList[0]],
(1,sparseSurfaceList[0].shape[0]))
reshapedValueForFactors = np.reshape([initialValueForFactors],
(1,initialValueForFactors.shape[0]))
dataSetList = [reshapedSparseSurface]
for k in args :
dataSetList.append(np.reshape([k], (1,k.shape[0])))
#Opening session for calibration
with tf.Session() as sess :
#Restoring Model
#self.saver = tf.train.import_meta_graph(self.metaModelName + '.meta')
sess.run(self.init)
self.restoreWeights(sess)
reconstructionMatrix = self.components.eval() #(56, 5)
mu = self.mean.eval() #(56,)
sigma = self.std.eval() #(56,)
nonMissingColumns = np.argwhere(~np.isnan(reshapedSparseSurface))[:,1] #(8,)
nonMissingPoints = (reshapedSparseSurface - mu) / sigma #(1,56)
#factorsCalibrated, residuals, _, _ = np.linalg.lstsq(reconstructionMatrix[nonMissingColumns,:],
# nonMissingPoints[:, nonMissingColumns].T) #((8,5), (8,)) -> (5,)
factorsCalibrated = np.linalg.pinv(reconstructionMatrix[nonMissingColumns,:]) @ nonMissingPoints[:, nonMissingColumns].T
reconstructedSurface = (reconstructionMatrix @ factorsCalibrated).T * sigma + mu #(56,1)
completedSurface = np.where(np.isnan(reshapedSparseSurface),
reconstructedSurface,
reshapedSparseSurface)
calibrationLosses = [np.sqrt(np.nanmean(np.square(completedSurface.T - sparseSurfaceList[0].values)[:, nonMissingColumns]))]
#Get results for best calibration
bestCalibration = np.argmin(calibrationLosses)
bestFactors = [np.ravel(factorsCalibrated.astype(np.float32))]
bestSurface = pd.Series(np.reshape(completedSurface, sparseSurfaceList[0].shape),
index=sparseSurfaceList[0].index,
name=sparseSurfaceList[0].name)
return calibrationLosses[bestCalibration] , bestFactors[0], bestSurface, pd.Series(calibrationLosses)
| [
"tensorflow.train.AdamOptimizer",
"numpy.isnan",
"numpy.zeros",
"numpy.square",
"numpy.ones",
"numpy.reshape",
"tensorflow.Session",
"sklearn.preprocessing.scale",
"numpy.linalg.pinv",
"tensorflow.global_variables_initializer",
"tensorflow.placeholder",
"pandas.Series",
"tensorflow.add_n",
... | [((1143, 1220), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': "[None, self.nbUnitsPerLayer['Input Layer']]"}), "(tf.float32, shape=[None, self.nbUnitsPerLayer['Input Layer']])\n", (1157, 1220), True, 'import tensorflow as tf\n'), ((3515, 3571), 'tensorflow.matmul', 'tf.matmul', (['factorTensor', 'self.components'], {'adjoint_b': '(True)'}), '(factorTensor, self.components, adjoint_b=True)\n', (3524, 3571), True, 'import tensorflow as tf\n'), ((3681, 3758), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': "[None, self.nbUnitsPerLayer['Input Layer']]"}), "(tf.float32, shape=[None, self.nbUnitsPerLayer['Input Layer']])\n", (3695, 3758), True, 'import tensorflow as tf\n'), ((4333, 4378), 'tensorflow.matmul', 'tf.matmul', (['scaledInputTensor', 'self.components'], {}), '(scaledInputTensor, self.components)\n', (4342, 4378), True, 'import tensorflow as tf\n'), ((4419, 4480), 'tensorflow.matmul', 'tf.matmul', (['self.factorTensor', 'self.components'], {'adjoint_b': '(True)'}), '(self.factorTensor, self.components, adjoint_b=True)\n', (4428, 4480), True, 'import tensorflow as tf\n'), ((4676, 4700), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (4698, 4700), True, 'import tensorflow as tf\n'), ((5336, 5415), 'tensorflow.add_n', 'tf.add_n', (['([self.reducedReconstructionLoss] + self.penalizationList)'], {'name': '"""loss"""'}), "([self.reducedReconstructionLoss] + self.penalizationList, name='loss')\n", (5344, 5415), True, 'import tensorflow as tf\n'), ((5473, 5532), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['self.learningRate'], {'name': '"""optimizer"""'}), "(self.learningRate, name='optimizer')\n", (5495, 5532), True, 'import tensorflow as tf\n'), ((6203, 6236), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (6234, 6236), True, 'import tensorflow as tf\n'), ((6259, 6313), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {'name': '"""saver"""', 'save_relative_paths': '(True)'}), "(name='saver', save_relative_paths=True)\n", (6273, 6313), True, 'import tensorflow as tf\n'), ((7780, 7812), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': 'self.nbFactors'}), '(n_components=self.nbFactors)\n', (7783, 7812), False, 'from sklearn.decomposition import PCA\n'), ((9231, 9269), 'tensorflow.matmul', 'tf.matmul', (['lastTensor', 'self.components'], {}), '(lastTensor, self.components)\n', (9240, 9269), True, 'import tensorflow as tf\n'), ((9292, 9346), 'tensorflow.matmul', 'tf.matmul', (['lastTensor', 'self.components'], {'adjoint_b': '(True)'}), '(lastTensor, self.components, adjoint_b=True)\n', (9301, 9346), True, 'import tensorflow as tf\n'), ((11068, 11138), 'numpy.reshape', 'np.reshape', (['[sparseSurfaceList[0]]', '(1, sparseSurfaceList[0].shape[0])'], {}), '([sparseSurfaceList[0]], (1, sparseSurfaceList[0].shape[0]))\n', (11078, 11138), True, 'import numpy as np\n'), ((11217, 11291), 'numpy.reshape', 'np.reshape', (['[initialValueForFactors]', '(1, initialValueForFactors.shape[0])'], {}), '([initialValueForFactors], (1, initialValueForFactors.shape[0]))\n', (11227, 11291), True, 'import numpy as np\n'), ((12983, 13011), 'numpy.argmin', 'np.argmin', (['calibrationLosses'], {}), '(calibrationLosses)\n', (12992, 13011), True, 'import numpy as np\n'), ((2330, 2342), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (2340, 2342), True, 'import tensorflow as tf\n'), ((7844, 7865), 'sklearn.preprocessing.scale', 'scale', (['trainingSet[0]'], {}), '(trainingSet[0])\n', (7849, 7865), False, 'from sklearn.preprocessing import scale\n'), ((8815, 8836), 'numpy.array', 'np.array', (['epochLosses'], {}), '(epochLosses)\n', (8823, 8836), True, 'import numpy as np\n'), ((8838, 8864), 'numpy.array', 'np.array', (['validationLosses'], {}), '(validationLosses)\n', (8846, 8864), True, 'import numpy as np\n'), ((11540, 11552), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (11550, 11552), True, 'import tensorflow as tf\n'), ((12350, 12408), 'numpy.linalg.pinv', 'np.linalg.pinv', (['reconstructionMatrix[nonMissingColumns, :]'], {}), '(reconstructionMatrix[nonMissingColumns, :])\n', (12364, 12408), True, 'import numpy as np\n'), ((12606, 12637), 'numpy.isnan', 'np.isnan', (['reshapedSparseSurface'], {}), '(reshapedSparseSurface)\n', (12614, 12637), True, 'import numpy as np\n'), ((13117, 13173), 'numpy.reshape', 'np.reshape', (['completedSurface', 'sparseSurfaceList[0].shape'], {}), '(completedSurface, sparseSurfaceList[0].shape)\n', (13127, 13173), True, 'import numpy as np\n'), ((13391, 13419), 'pandas.Series', 'pd.Series', (['calibrationLosses'], {}), '(calibrationLosses)\n', (13400, 13419), True, 'import pandas as pd\n'), ((11441, 11473), 'numpy.reshape', 'np.reshape', (['[k]', '(1, k.shape[0])'], {}), '([k], (1, k.shape[0]))\n', (11451, 11473), True, 'import numpy as np\n'), ((3858, 3926), 'numpy.ones', 'np.ones', ([], {'shape': "(self.nbUnitsPerLayer['Input Layer'], self.nbFactors)"}), "(shape=(self.nbUnitsPerLayer['Input Layer'], self.nbFactors))\n", (3865, 3926), True, 'import numpy as np\n'), ((4034, 4085), 'numpy.zeros', 'np.zeros', ([], {'shape': "self.nbUnitsPerLayer['Input Layer']"}), "(shape=self.nbUnitsPerLayer['Input Layer'])\n", (4042, 4085), True, 'import numpy as np\n'), ((4140, 4190), 'numpy.ones', 'np.ones', ([], {'shape': "self.nbUnitsPerLayer['Input Layer']"}), "(shape=self.nbUnitsPerLayer['Input Layer'])\n", (4147, 4190), True, 'import numpy as np\n'), ((11969, 12000), 'numpy.isnan', 'np.isnan', (['reshapedSparseSurface'], {}), '(reshapedSparseSurface)\n', (11977, 12000), True, 'import numpy as np\n'), ((12818, 12877), 'numpy.square', 'np.square', (['(completedSurface.T - sparseSurfaceList[0].values)'], {}), '(completedSurface.T - sparseSurfaceList[0].values)\n', (12827, 12877), True, 'import numpy as np\n')] |
import itertools
from copy import deepcopy
def print_result(unique_permutations):
result = []
for perm in list(sorted(unique_permutations)):
pair_list = []
for pair in perm:
pair_str = f'|{pair[0]}-{pair[1]}|'
pair_list.append(pair_str)
result.append(' # '.join(pair_list))
print(len(unique_permutations))
[print(line) for line in result]
sticks_count = int(input())
all_sizes = []
for _ in range(sticks_count):
size = tuple(input().split())
all_sizes.append(size)
permutations = list(itertools.permutations(all_sizes, sticks_count))
all_sizes_copy = deepcopy(all_sizes)
for index, pair in enumerate(all_sizes_copy):
reversed_pair = all_sizes_copy[index][::-1]
temp_sizes_list = all_sizes_copy[:index] + [reversed_pair] + all_sizes_copy[index + 1:]
permutations.extend(list(itertools.permutations(temp_sizes_list, sticks_count)))
unique_permutations = set(permutations)
print_result(unique_permutations)
| [
"itertools.permutations",
"copy.deepcopy"
] | [((632, 651), 'copy.deepcopy', 'deepcopy', (['all_sizes'], {}), '(all_sizes)\n', (640, 651), False, 'from copy import deepcopy\n'), ((564, 611), 'itertools.permutations', 'itertools.permutations', (['all_sizes', 'sticks_count'], {}), '(all_sizes, sticks_count)\n', (586, 611), False, 'import itertools\n'), ((867, 920), 'itertools.permutations', 'itertools.permutations', (['temp_sizes_list', 'sticks_count'], {}), '(temp_sizes_list, sticks_count)\n', (889, 920), False, 'import itertools\n')] |
from django import forms
from .models import File
from captcha.fields import ReCaptchaField
from captcha.widgets import ReCaptchaV3
# Model form
class FileUploadModelForm(forms.ModelForm):
class Meta:
model = File
labels = {
'file': ''
}
fields = ['file']
widgets = {
'file': forms.ClearableFileInput(attrs={'class': 'form-control'})
}
def clean_file(self):
file = self.cleaned_data['file']
ext = file.name.split('.')[-1].lower()
if ext != "xls":
raise forms.ValidationError(".xls以外の拡張子ファイルはアップロードいただけません。")
# return cleaned data is very important.
return file
captcha = ReCaptchaField(
label='',
widget=ReCaptchaV3(
attrs={'required_score': 0.7}
)
)
| [
"django.forms.ClearableFileInput",
"django.forms.ValidationError",
"captcha.widgets.ReCaptchaV3"
] | [((346, 403), 'django.forms.ClearableFileInput', 'forms.ClearableFileInput', ([], {'attrs': "{'class': 'form-control'}"}), "(attrs={'class': 'form-control'})\n", (370, 403), False, 'from django import forms\n'), ((572, 626), 'django.forms.ValidationError', 'forms.ValidationError', (['""".xls以外の拡張子ファイルはアップロードいただけません。"""'], {}), "('.xls以外の拡張子ファイルはアップロードいただけません。')\n", (593, 626), False, 'from django import forms\n'), ((760, 802), 'captcha.widgets.ReCaptchaV3', 'ReCaptchaV3', ([], {'attrs': "{'required_score': 0.7}"}), "(attrs={'required_score': 0.7})\n", (771, 802), False, 'from captcha.widgets import ReCaptchaV3\n')] |
import torch
import pickle
import cv2
import random
import numpy as np
import math
from torch.utils.data import DataLoader,Dataset
from albumentations import (
Blur,GaussianBlur,MedianBlur,
HueSaturationValue,
RandomBrightnessContrast,
Normalize,
OneOf, Compose,
NoOp,
)
MEAN_LANDMARK = np.array([
0.2435, 0.3053, 0.3996, 0.3032, 0.5115, 0.3064, 0.6159, 0.2999, 0.7380,
0.2975, 0.4218, 0.6247, 0.6028, 0.6202, 0.5181, 0.4753, 0.5136, 0.8485], np.float32)
class CZ_Head_Landmark(Dataset):
def __init__(self, cfg, is_train):
super(CZ_Head_Landmark, self).__init__()
root_dir = cfg.DATA.label_dir
self.infos = []
if is_train:
self.infos = pickle.load(open(root_dir+'train_infos.pkl', 'rb'))
else:
self.infos = pickle.load(open(root_dir + 'val_infos.pkl', 'rb'))
self.aug_train = self._aug_train()
self.aug_norm = self._aug_test()
self.cfg = cfg
self.is_train = is_train
print('samples: ', len(self.infos))
def _crop_by_bbox_aug(self, img, landmarks, bbox):
x, y, w, h = bbox
new_w = w + w * random.randint(4, 10) / 10 ## 1.4 -- 2.0
new_h = h + h * random.randint(4, 10) / 10 ## 1.4 -- 2.0
if not self.is_train:
new_w = w + w * 1.4
new_h = h + h * 1.4
x0 = x + w/2 - new_w/2
y0 = y + h/2 - new_h/2
x1 = x + w / 2 + new_w / 2
y1 = y + h / 2 + new_h / 2
#y1 biaz
y1 = y1 - 0.2*h
x0 = 0 if x0 < 0 else x0
y0 = 0 if y0 < 0 else y0
x1 = img.shape[1] - 1 if x1 > img.shape[1] - 1 else x1
y1 = img.shape[0] - 1 if y1 > img.shape[0] - 1 else y1
landmarks_crop = []
img_crop = img[int(y0):int(y1), int(x0):int(x1)].copy()
for p in landmarks:
landmarks_crop.append([p[0]-x0, p[1]-y0 ])
return img_crop, landmarks_crop
def _resize_and_norm_landmarks(self, img, landmarks):
size = self.cfg.DATA.input_size
landmarks_resized = []
rw = size / img.shape[1]
rh = size / img.shape[0]
img_resized = cv2.resize(img, (size, size), cv2.INTER_CUBIC)
for p in landmarks:
landmarks_resized.append([p[0]*rw / size, p[1]*rh / size])
return img_resized, landmarks_resized
def _aug_train(self):
aug = Compose(
[
OneOf(
[
HueSaturationValue(hue_shift_limit=20,
sat_shift_limit=20,
val_shift_limit=20,
p=0.5),
RandomBrightnessContrast(brightness_limit=0.2, contrast_limit=0.2)
]
)
],
p=1.0)
return aug
def _aug_test(self):
aug = Compose(
[
# Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225))
Normalize(mean=(0.485, 0.456, 0.406), std=(1.0 / 255, 1.0 / 255, 1.0 / 255))
],
p=1.0)
return aug
def __len__(self):
return len(self.infos)
def __getitem__(self, inx):
info = self.infos[inx]
img_fn = info['img_full_path']
bbox = info['bounding_bbox']
landmarks = info['landmarks']
#norm_base_dis = info['norm_base_dis']
img = cv2.imread(img_fn)
assert img is not None, img_fn
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
if self.is_train:
img = self.aug_train(image=img)['image']
if random.random() > 0.2:
img, landmarks = self._crop_by_bbox_aug(img, landmarks, bbox)
else:
img, landmarks = self._crop_by_bbox_aug(img, landmarks, bbox)
img, landmarks = self._resize_and_norm_landmarks(img, landmarks)
##debug
# gui = img.copy()
# for p in landmarks:
# p[0] = p[0]* img.shape[1]
# p[1] = p[1] * img.shape[0]
# cv2.circle(gui, (int(p[0]), int(p[1])), 2, (0, 255, 0), -1)
# for i in range(9):
# p = [0,1]
# p[0] = MEAN_LANDMARK[2*i] * img.shape[1]
# p[1] = MEAN_LANDMARK[2*i+1] * img.shape[0]
# cv2.circle(gui, (int(p[0]), int(p[1])), 2, (0, 0, 255), -1)
# cv2.imwrite('/home/lhw/gui.jpg', gui)
img = self.aug_norm(image=img)['image']
img = img.transpose((2, 0, 1))
img = torch.from_numpy(img)
norm_base_dis = (landmarks[1][0] - landmarks[3][0]) * (landmarks[1][0] - landmarks[3][0]) + \
(landmarks[1][1] - landmarks[3][1]) * (landmarks[1][1] - landmarks[3][1])
norm_base_dis = math.sqrt(norm_base_dis)
landmarks = np.array(landmarks, np.float32).reshape(-1)
landmarks = landmarks- MEAN_LANDMARK
label = torch.from_numpy(landmarks)
norm_base_dis = torch.FloatTensor([norm_base_dis])
return img, label,norm_base_dis, img_fn
if __name__ == '__main__':
import tqdm
from fer_pytorch.config.default_cfg import get_fer_cfg_defaults
cfg = get_fer_cfg_defaults()
cfg.DATA.label_dir = '/home/lhw/data/FaceDataset/LS3D_W_CZUR_9_landmark/'
cfg.DATA.input_size = 128
dataset = CZ_Head_Landmark(cfg, is_train=True)
all_label = torch.zeros((18), dtype=torch.float32)
for img, label,dis, fn in tqdm.tqdm(dataset):
# print(img.shape)
# print(label.shape)
print(dis)
all_label += label
exit()
print('mean shape: ', all_label / len(dataset))
| [
"torch.FloatTensor",
"random.random",
"numpy.array",
"tqdm.tqdm",
"albumentations.Normalize",
"torch.from_numpy",
"cv2.imread",
"fer_pytorch.config.default_cfg.get_fer_cfg_defaults",
"cv2.cvtColor",
"math.sqrt",
"torch.zeros",
"albumentations.RandomBrightnessContrast",
"albumentations.HueSat... | [((335, 510), 'numpy.array', 'np.array', (['[0.2435, 0.3053, 0.3996, 0.3032, 0.5115, 0.3064, 0.6159, 0.2999, 0.738, \n 0.2975, 0.4218, 0.6247, 0.6028, 0.6202, 0.5181, 0.4753, 0.5136, 0.8485]', 'np.float32'], {}), '([0.2435, 0.3053, 0.3996, 0.3032, 0.5115, 0.3064, 0.6159, 0.2999, \n 0.738, 0.2975, 0.4218, 0.6247, 0.6028, 0.6202, 0.5181, 0.4753, 0.5136, \n 0.8485], np.float32)\n', (343, 510), True, 'import numpy as np\n'), ((5387, 5409), 'fer_pytorch.config.default_cfg.get_fer_cfg_defaults', 'get_fer_cfg_defaults', ([], {}), '()\n', (5407, 5409), False, 'from fer_pytorch.config.default_cfg import get_fer_cfg_defaults\n'), ((5590, 5626), 'torch.zeros', 'torch.zeros', (['(18)'], {'dtype': 'torch.float32'}), '(18, dtype=torch.float32)\n', (5601, 5626), False, 'import torch\n'), ((5660, 5678), 'tqdm.tqdm', 'tqdm.tqdm', (['dataset'], {}), '(dataset)\n', (5669, 5678), False, 'import tqdm\n'), ((2246, 2292), 'cv2.resize', 'cv2.resize', (['img', '(size, size)', 'cv2.INTER_CUBIC'], {}), '(img, (size, size), cv2.INTER_CUBIC)\n', (2256, 2292), False, 'import cv2\n'), ((3601, 3619), 'cv2.imread', 'cv2.imread', (['img_fn'], {}), '(img_fn)\n', (3611, 3619), False, 'import cv2\n'), ((3675, 3711), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2RGB'], {}), '(img, cv2.COLOR_BGR2RGB)\n', (3687, 3711), False, 'import cv2\n'), ((4714, 4735), 'torch.from_numpy', 'torch.from_numpy', (['img'], {}), '(img)\n', (4730, 4735), False, 'import torch\n'), ((4965, 4989), 'math.sqrt', 'math.sqrt', (['norm_base_dis'], {}), '(norm_base_dis)\n', (4974, 4989), False, 'import math\n'), ((5120, 5147), 'torch.from_numpy', 'torch.from_numpy', (['landmarks'], {}), '(landmarks)\n', (5136, 5147), False, 'import torch\n'), ((5173, 5207), 'torch.FloatTensor', 'torch.FloatTensor', (['[norm_base_dis]'], {}), '([norm_base_dis])\n', (5190, 5207), False, 'import torch\n'), ((3159, 3235), 'albumentations.Normalize', 'Normalize', ([], {'mean': '(0.485, 0.456, 0.406)', 'std': '(1.0 / 255, 1.0 / 255, 1.0 / 255)'}), '(mean=(0.485, 0.456, 0.406), std=(1.0 / 255, 1.0 / 255, 1.0 / 255))\n', (3168, 3235), False, 'from albumentations import Blur, GaussianBlur, MedianBlur, HueSaturationValue, RandomBrightnessContrast, Normalize, OneOf, Compose, NoOp\n'), ((3811, 3826), 'random.random', 'random.random', ([], {}), '()\n', (3824, 3826), False, 'import random\n'), ((5013, 5044), 'numpy.array', 'np.array', (['landmarks', 'np.float32'], {}), '(landmarks, np.float32)\n', (5021, 5044), True, 'import numpy as np\n'), ((1209, 1230), 'random.randint', 'random.randint', (['(4)', '(10)'], {}), '(4, 10)\n', (1223, 1230), False, 'import random\n'), ((1278, 1299), 'random.randint', 'random.randint', (['(4)', '(10)'], {}), '(4, 10)\n', (1292, 1299), False, 'import random\n'), ((2582, 2672), 'albumentations.HueSaturationValue', 'HueSaturationValue', ([], {'hue_shift_limit': '(20)', 'sat_shift_limit': '(20)', 'val_shift_limit': '(20)', 'p': '(0.5)'}), '(hue_shift_limit=20, sat_shift_limit=20, val_shift_limit=\n 20, p=0.5)\n', (2600, 2672), False, 'from albumentations import Blur, GaussianBlur, MedianBlur, HueSaturationValue, RandomBrightnessContrast, Normalize, OneOf, Compose, NoOp\n'), ((2826, 2892), 'albumentations.RandomBrightnessContrast', 'RandomBrightnessContrast', ([], {'brightness_limit': '(0.2)', 'contrast_limit': '(0.2)'}), '(brightness_limit=0.2, contrast_limit=0.2)\n', (2850, 2892), False, 'from albumentations import Blur, GaussianBlur, MedianBlur, HueSaturationValue, RandomBrightnessContrast, Normalize, OneOf, Compose, NoOp\n')] |
from discord.ext import commands
class AdminCog:
def __init__(self, bot):
self.bot = bot
@commands.command(name = "ban")
async def ban(self, ctx):
print("Here")
await ctx.send("Works")
def setup(bot):
bot.add_cog(AdminCog(bot)) | [
"discord.ext.commands.command"
] | [((108, 136), 'discord.ext.commands.command', 'commands.command', ([], {'name': '"""ban"""'}), "(name='ban')\n", (124, 136), False, 'from discord.ext import commands\n')] |
#!/usr/bin/python3
#-*- encoding: Utf-8 -*-
from struct import pack, unpack, unpack_from, calcsize
from collections import OrderedDict
from logging import warning, info
from time import sleep
from ctypes import *
from protocol.messages import *
"""
This module exposes a class from which a module may inherit in order to
enable logging packets.
"""
LOG_CONFIG_RETRIEVE_ID_RANGES_OP = 1
LOG_CONFIG_SET_MASK_OP = 3
LOG_CONFIG_SUCCESS_S = 0
class DiagVernoResponse(LittleEndianStructure):
_pack_ = 1
_fields_ = [
('comp_date', c_char * 11),
('comp_time', c_char * 8),
('rel_date', c_char * 11),
('rel_time', c_char * 8),
('ver_dir', c_char * 8),
('scm', c_ubyte),
('mob_cai_rev', c_ubyte),
('mob_model', c_ubyte),
('mob_firm_rev', c_uint16),
('slot_cycle_index', c_ubyte),
('hw_maj_ver', c_ubyte),
('hw_min_ver', c_ubyte)
]
def print_row(key, value):
print('[+] %s %s' % ((key + ':').ljust(20), value))
class InfoRetriever:
def __init__(self, diag_input):
self.diag_input = diag_input
def on_init(self):
print()
opcode, payload = self.diag_input.send_recv(DIAG_VERNO_F, b'', accept_error = False)
if opcode == DIAG_VERNO_F: # No error occured
info = DiagVernoResponse.from_buffer(bytearray(payload))
print_row('Compilation date', '%s %s' % (info.comp_date.decode('ascii'), info.comp_time.decode('ascii')))
print_row('Release date', '%s %s' % (info.rel_date.decode('ascii'), info.rel_time.decode('ascii')))
print_row('Version directory', info.ver_dir.decode('ascii'))
print()
print_row('Common air interface information', '')
print_row(' Station classmark', info.scm)
print_row(' Common air interface revision', info.mob_cai_rev)
print_row(' Mobile model', info.mob_model)
print_row(' Mobile firmware revision', info.mob_firm_rev)
print_row(' Slot cycle index', info.slot_cycle_index)
print_row(' Hardware revision', '0x%x%02x (%d.%d)' % (
info.hw_maj_ver, info.hw_min_ver,
info.hw_maj_ver, info.hw_min_ver
))
print()
opcode, payload = self.diag_input.send_recv(DIAG_EXT_BUILD_ID_F, b'', accept_error = True)
if opcode == DIAG_EXT_BUILD_ID_F:
(msm_hw_version_format, msm_hw_version, mobile_model_id), ver_strings = unpack('<B2xII', payload[:11]), payload[11:]
build_id, model_string, _ = ver_strings.split(b'\x00')
if msm_hw_version_format == 2:
version, partnum = msm_hw_version >> 28, (msm_hw_version >> 12) & 0xffff
else:
version, partnum = msm_hw_version & 0b1111, (msm_hw_version >> 12) >> 4
# Duplicate with information from DIAG_VERNO_F:
# print_row('Hardware revision', '0x%x (%d.%d)' % (partnum, partnum >> 8, partnum & 0xff))
# Sometimes duplicate with information from DIAG_VERNO_F:
if mobile_model_id > 255:
print_row('Mobile model ID', '0x%x' % mobile_model_id)
print_row('Chip version', version)
print_row('Firmware build ID', build_id.decode('ascii'))
if model_string:
print_row('Model string', model_string.decode('ascii'))
print()
opcode, payload = self.diag_input.send_recv(DIAG_DIAG_VER_F, b'', accept_error = True)
if opcode == DIAG_DIAG_VER_F:
print_row('Diag version', unpack('<H', payload)[0])
print()
opcode, payload = self.diag_input.send_recv(DIAG_ESN_F, b'', accept_error = True)
if opcode == DIAG_ESN_F:
esn = unpack('<I', payload)[0]
if esn != 0xdeadd00d:
print_row('Serial number', esn)
print()
| [
"logging.info.rel_time.decode",
"logging.info.ver_dir.decode",
"logging.info.comp_time.decode",
"logging.info.rel_date.decode",
"struct.unpack",
"logging.info.comp_date.decode"
] | [((1785, 1813), 'logging.info.ver_dir.decode', 'info.ver_dir.decode', (['"""ascii"""'], {}), "('ascii')\n", (1804, 1813), False, 'from logging import warning, info\n'), ((2692, 2722), 'struct.unpack', 'unpack', (['"""<B2xII"""', 'payload[:11]'], {}), "('<B2xII', payload[:11])\n", (2698, 2722), False, 'from struct import pack, unpack, unpack_from, calcsize\n'), ((4158, 4179), 'struct.unpack', 'unpack', (['"""<I"""', 'payload'], {}), "('<I', payload)\n", (4164, 4179), False, 'from struct import pack, unpack, unpack_from, calcsize\n'), ((3927, 3948), 'struct.unpack', 'unpack', (['"""<H"""', 'payload'], {}), "('<H', payload)\n", (3933, 3948), False, 'from struct import pack, unpack, unpack_from, calcsize\n'), ((1565, 1595), 'logging.info.comp_date.decode', 'info.comp_date.decode', (['"""ascii"""'], {}), "('ascii')\n", (1586, 1595), False, 'from logging import warning, info\n'), ((1597, 1627), 'logging.info.comp_time.decode', 'info.comp_time.decode', (['"""ascii"""'], {}), "('ascii')\n", (1618, 1627), False, 'from logging import warning, info\n'), ((1679, 1708), 'logging.info.rel_date.decode', 'info.rel_date.decode', (['"""ascii"""'], {}), "('ascii')\n", (1699, 1708), False, 'from logging import warning, info\n'), ((1710, 1739), 'logging.info.rel_time.decode', 'info.rel_time.decode', (['"""ascii"""'], {}), "('ascii')\n", (1730, 1739), False, 'from logging import warning, info\n')] |
from sqlalchemy import Column, Integer, String, Float, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
base = declarative_base()
class Video(base):
__tablename__ = "video"
id = Column(Integer, primary_key=True)
media_id = Column(Integer, ForeignKey("media.id"))
codec_id = Column(String)
media_type = Column(String)
duration = Column(Float)
bit_rate = Column(Integer)
width = Column(Integer)
height = Column(Integer)
frame_rate_mode = Column(String)
frame_rate = Column(Float)
frame_count = Column(Integer)
bit_depth = Column(Integer)
size = Column(Integer)
class Audio(base):
__tablename__ = "audio"
id = Column(Integer, primary_key=True)
media_id = Column(Integer, ForeignKey("media.id"))
format = Column(String)
codec_id = Column(String)
duration = Column(Float)
bit_rate_mode = Column(String)
bit_rate = Column(Integer)
channels = Column(Integer)
sample_rate = Column(Integer)
bit_depth = Column(Integer)
size = Column(Integer)
language = Column(String)
class Media(base):
__tablename__ = "media"
id = Column(Integer, primary_key=True)
title = Column(String)
extension = Column(String)
format = Column(String)
location = Column(String)
videos = relationship(Video)
audios = relationship(Audio)
| [
"sqlalchemy.ext.declarative.declarative_base",
"sqlalchemy.orm.relationship",
"sqlalchemy.Column",
"sqlalchemy.ForeignKey"
] | [((170, 188), 'sqlalchemy.ext.declarative.declarative_base', 'declarative_base', ([], {}), '()\n', (186, 188), False, 'from sqlalchemy.ext.declarative import declarative_base\n'), ((248, 281), 'sqlalchemy.Column', 'Column', (['Integer'], {'primary_key': '(True)'}), '(Integer, primary_key=True)\n', (254, 281), False, 'from sqlalchemy import Column, Integer, String, Float, ForeignKey\n'), ((353, 367), 'sqlalchemy.Column', 'Column', (['String'], {}), '(String)\n', (359, 367), False, 'from sqlalchemy import Column, Integer, String, Float, ForeignKey\n'), ((385, 399), 'sqlalchemy.Column', 'Column', (['String'], {}), '(String)\n', (391, 399), False, 'from sqlalchemy import Column, Integer, String, Float, ForeignKey\n'), ((415, 428), 'sqlalchemy.Column', 'Column', (['Float'], {}), '(Float)\n', (421, 428), False, 'from sqlalchemy import Column, Integer, String, Float, ForeignKey\n'), ((444, 459), 'sqlalchemy.Column', 'Column', (['Integer'], {}), '(Integer)\n', (450, 459), False, 'from sqlalchemy import Column, Integer, String, Float, ForeignKey\n'), ((472, 487), 'sqlalchemy.Column', 'Column', (['Integer'], {}), '(Integer)\n', (478, 487), False, 'from sqlalchemy import Column, Integer, String, Float, ForeignKey\n'), ((501, 516), 'sqlalchemy.Column', 'Column', (['Integer'], {}), '(Integer)\n', (507, 516), False, 'from sqlalchemy import Column, Integer, String, Float, ForeignKey\n'), ((540, 554), 'sqlalchemy.Column', 'Column', (['String'], {}), '(String)\n', (546, 554), False, 'from sqlalchemy import Column, Integer, String, Float, ForeignKey\n'), ((572, 585), 'sqlalchemy.Column', 'Column', (['Float'], {}), '(Float)\n', (578, 585), False, 'from sqlalchemy import Column, Integer, String, Float, ForeignKey\n'), ((604, 619), 'sqlalchemy.Column', 'Column', (['Integer'], {}), '(Integer)\n', (610, 619), False, 'from sqlalchemy import Column, Integer, String, Float, ForeignKey\n'), ((637, 652), 'sqlalchemy.Column', 'Column', (['Integer'], {}), '(Integer)\n', (643, 652), False, 'from sqlalchemy import Column, Integer, String, Float, ForeignKey\n'), ((665, 680), 'sqlalchemy.Column', 'Column', (['Integer'], {}), '(Integer)\n', (671, 680), False, 'from sqlalchemy import Column, Integer, String, Float, ForeignKey\n'), ((740, 773), 'sqlalchemy.Column', 'Column', (['Integer'], {'primary_key': '(True)'}), '(Integer, primary_key=True)\n', (746, 773), False, 'from sqlalchemy import Column, Integer, String, Float, ForeignKey\n'), ((843, 857), 'sqlalchemy.Column', 'Column', (['String'], {}), '(String)\n', (849, 857), False, 'from sqlalchemy import Column, Integer, String, Float, ForeignKey\n'), ((873, 887), 'sqlalchemy.Column', 'Column', (['String'], {}), '(String)\n', (879, 887), False, 'from sqlalchemy import Column, Integer, String, Float, ForeignKey\n'), ((903, 916), 'sqlalchemy.Column', 'Column', (['Float'], {}), '(Float)\n', (909, 916), False, 'from sqlalchemy import Column, Integer, String, Float, ForeignKey\n'), ((938, 952), 'sqlalchemy.Column', 'Column', (['String'], {}), '(String)\n', (944, 952), False, 'from sqlalchemy import Column, Integer, String, Float, ForeignKey\n'), ((968, 983), 'sqlalchemy.Column', 'Column', (['Integer'], {}), '(Integer)\n', (974, 983), False, 'from sqlalchemy import Column, Integer, String, Float, ForeignKey\n'), ((1000, 1015), 'sqlalchemy.Column', 'Column', (['Integer'], {}), '(Integer)\n', (1006, 1015), False, 'from sqlalchemy import Column, Integer, String, Float, ForeignKey\n'), ((1035, 1050), 'sqlalchemy.Column', 'Column', (['Integer'], {}), '(Integer)\n', (1041, 1050), False, 'from sqlalchemy import Column, Integer, String, Float, ForeignKey\n'), ((1067, 1082), 'sqlalchemy.Column', 'Column', (['Integer'], {}), '(Integer)\n', (1073, 1082), False, 'from sqlalchemy import Column, Integer, String, Float, ForeignKey\n'), ((1094, 1109), 'sqlalchemy.Column', 'Column', (['Integer'], {}), '(Integer)\n', (1100, 1109), False, 'from sqlalchemy import Column, Integer, String, Float, ForeignKey\n'), ((1126, 1140), 'sqlalchemy.Column', 'Column', (['String'], {}), '(String)\n', (1132, 1140), False, 'from sqlalchemy import Column, Integer, String, Float, ForeignKey\n'), ((1200, 1233), 'sqlalchemy.Column', 'Column', (['Integer'], {'primary_key': '(True)'}), '(Integer, primary_key=True)\n', (1206, 1233), False, 'from sqlalchemy import Column, Integer, String, Float, ForeignKey\n'), ((1246, 1260), 'sqlalchemy.Column', 'Column', (['String'], {}), '(String)\n', (1252, 1260), False, 'from sqlalchemy import Column, Integer, String, Float, ForeignKey\n'), ((1277, 1291), 'sqlalchemy.Column', 'Column', (['String'], {}), '(String)\n', (1283, 1291), False, 'from sqlalchemy import Column, Integer, String, Float, ForeignKey\n'), ((1305, 1319), 'sqlalchemy.Column', 'Column', (['String'], {}), '(String)\n', (1311, 1319), False, 'from sqlalchemy import Column, Integer, String, Float, ForeignKey\n'), ((1335, 1349), 'sqlalchemy.Column', 'Column', (['String'], {}), '(String)\n', (1341, 1349), False, 'from sqlalchemy import Column, Integer, String, Float, ForeignKey\n'), ((1364, 1383), 'sqlalchemy.orm.relationship', 'relationship', (['Video'], {}), '(Video)\n', (1376, 1383), False, 'from sqlalchemy.orm import relationship\n'), ((1397, 1416), 'sqlalchemy.orm.relationship', 'relationship', (['Audio'], {}), '(Audio)\n', (1409, 1416), False, 'from sqlalchemy.orm import relationship\n'), ((313, 335), 'sqlalchemy.ForeignKey', 'ForeignKey', (['"""media.id"""'], {}), "('media.id')\n", (323, 335), False, 'from sqlalchemy import Column, Integer, String, Float, ForeignKey\n'), ((805, 827), 'sqlalchemy.ForeignKey', 'ForeignKey', (['"""media.id"""'], {}), "('media.id')\n", (815, 827), False, 'from sqlalchemy import Column, Integer, String, Float, ForeignKey\n')] |
# coding=utf-8
__author__ = "<NAME>"
from abc import ABC
import torch
from omegaconf import DictConfig, OmegaConf
from pytorch_lightning import Trainer
from torch.nn import L1Loss
from mridc.collections.common.losses.ssim import SSIMLoss
from mridc.collections.common.parts.fft import fft2c, ifft2c
from mridc.collections.common.parts.utils import complex_conj, complex_mul
from mridc.collections.reconstruction.models.base import BaseMRIReconstructionModel, BaseSensitivityModel
from mridc.collections.reconstruction.models.conv.conv2d import Conv2d
from mridc.collections.reconstruction.models.didn.didn import DIDN
from mridc.collections.reconstruction.models.mwcnn.mwcnn import MWCNN
from mridc.collections.reconstruction.models.primaldual.pd import DualNet, PrimalNet
from mridc.collections.reconstruction.models.unet_base.unet_block import NormUnet
from mridc.collections.reconstruction.parts.utils import center_crop_to_smallest
from mridc.core.classes.common import typecheck
__all__ = ["LPDNet"]
class LPDNet(BaseMRIReconstructionModel, ABC):
"""
Learned Primal Dual network implementation inspired by [1]_.
References
----------
.. [1] Adler, Jonas, and <NAME>. “Learned Primal-Dual Reconstruction.” IEEE Transactions on Medical Imaging,
vol. 37, no. 6, June 2018, pp. 1322–32. arXiv.org, https://doi.org/10.1109/TMI.2018.2799231.
"""
def __init__(self, cfg: DictConfig, trainer: Trainer = None):
# init superclass
super().__init__(cfg=cfg, trainer=trainer)
cfg_dict = OmegaConf.to_container(cfg, resolve=True)
self.num_iter = cfg_dict.get("num_iter")
self.num_primal = cfg_dict.get("num_primal")
self.num_dual = cfg_dict.get("num_dual")
primal_model_architecture = cfg_dict.get("primal_model_architecture")
if primal_model_architecture == "MWCNN":
primal_model = torch.nn.Sequential(
*[
MWCNN(
input_channels=2 * (self.num_primal + 1),
first_conv_hidden_channels=cfg_dict.get("primal_mwcnn_hidden_channels"),
num_scales=cfg_dict.get("primal_mwcnn_num_scales"),
bias=cfg_dict.get("primal_mwcnn_bias"),
batchnorm=cfg_dict.get("primal_mwcnn_batchnorm"),
),
torch.nn.Conv2d(2 * (self.num_primal + 1), 2 * self.num_primal, kernel_size=1),
]
)
elif primal_model_architecture in ["UNET", "NORMUNET"]:
primal_model = NormUnet(
cfg_dict.get("primal_unet_num_filters"),
cfg_dict.get("primal_unet_num_pool_layers"),
in_chans=2 * (self.num_primal + 1),
out_chans=2 * self.num_primal,
drop_prob=cfg_dict.get("primal_unet_dropout_probability"),
padding_size=cfg_dict.get("primal_unet_padding_size"),
normalize=cfg_dict.get("primal_unet_normalize"),
)
else:
raise NotImplementedError(
f"LPDNet is currently implemented for primal_model_architecture == 'CONV' or 'UNet'."
f"Got primal_model_architecture == {primal_model_architecture}."
)
dual_model_architecture = cfg_dict.get("dual_model_architecture")
if dual_model_architecture == "CONV":
dual_model = Conv2d(
in_channels=2 * (self.num_dual + 2),
out_channels=2 * self.num_dual,
hidden_channels=cfg_dict.get("kspace_conv_hidden_channels"),
n_convs=cfg_dict.get("kspace_conv_n_convs"),
batchnorm=cfg_dict.get("kspace_conv_batchnorm"),
)
elif dual_model_architecture == "DIDN":
dual_model = DIDN(
in_channels=2 * (self.num_dual + 2),
out_channels=2 * self.num_dual,
hidden_channels=cfg_dict.get("kspace_didn_hidden_channels"),
num_dubs=cfg_dict.get("kspace_didn_num_dubs"),
num_convs_recon=cfg_dict.get("kspace_didn_num_convs_recon"),
)
elif dual_model_architecture in ["UNET", "NORMUNET"]:
dual_model = NormUnet(
cfg_dict.get("dual_unet_num_filters"),
cfg_dict.get("dual_unet_num_pool_layers"),
in_chans=2 * (self.num_dual + 2),
out_chans=2 * self.num_dual,
drop_prob=cfg_dict.get("dual_unet_dropout_probability"),
padding_size=cfg_dict.get("dual_unet_padding_size"),
normalize=cfg_dict.get("dual_unet_normalize"),
)
else:
raise NotImplementedError(
f"LPDNet is currently implemented for dual_model_architecture == 'CONV' or 'DIDN' or 'UNet'."
f"Got dual_model_architecture == {dual_model_architecture}."
)
self.primal_net = torch.nn.ModuleList(
[PrimalNet(self.num_primal, primal_architecture=primal_model) for _ in range(self.num_iter)]
)
self.dual_net = torch.nn.ModuleList(
[DualNet(self.num_dual, dual_architecture=dual_model) for _ in range(self.num_iter)]
)
self.fft_type = cfg_dict.get("fft_type")
self._coil_dim = 1
# Initialize the sensitivity network if use_sens_net is True
self.use_sens_net = cfg_dict.get("use_sens_net")
if self.use_sens_net:
self.sens_net = BaseSensitivityModel(
cfg_dict.get("sens_chans"),
cfg_dict.get("sens_pools"),
fft_type=self.fft_type,
mask_type=cfg_dict.get("sens_mask_type"),
normalize=cfg_dict.get("sens_normalize"),
)
self.train_loss_fn = SSIMLoss() if cfg_dict.get("train_loss_fn") == "ssim" else L1Loss()
self.eval_loss_fn = SSIMLoss() if cfg_dict.get("eval_loss_fn") == "ssim" else L1Loss()
self.output_type = cfg_dict.get("output_type")
self.accumulate_estimates = False
@typecheck()
def forward(
self,
y: torch.Tensor,
sensitivity_maps: torch.Tensor,
mask: torch.Tensor,
init_pred: torch.Tensor,
target: torch.Tensor,
) -> torch.Tensor:
"""
Forward pass of the network.
Args:
y: torch.Tensor, shape [batch_size, n_coils, n_x, n_y, 2], masked kspace data
sensitivity_maps: torch.Tensor, shape [batch_size, n_coils, n_x, n_y, 2], coil sensitivity maps
mask: torch.Tensor, shape [1, 1, n_x, n_y, 1], sampling mask
init_pred: torch.Tensor, shape [batch_size, n_x, n_y, 2], initial guess for pred
target: torch.Tensor, shape [batch_size, n_x, n_y, 2], target data
Returns:
Final prediction of the network.
"""
sensitivity_maps = self.sens_net(y, mask) if self.use_sens_net else sensitivity_maps
input_image = complex_mul(
ifft2c(torch.where(mask == 0, torch.tensor([0.0], dtype=y.dtype).to(y.device), y), fft_type=self.fft_type),
complex_conj(sensitivity_maps),
).sum(1)
dual_buffer = torch.cat([y] * self.num_dual, -1).to(y.device)
primal_buffer = torch.cat([input_image] * self.num_primal, -1).to(y.device)
for idx in range(self.num_iter):
# Dual
f_2 = primal_buffer[..., 2:4].clone()
f_2 = torch.where(
mask == 0,
torch.tensor([0.0], dtype=f_2.dtype).to(f_2.device),
fft2c(complex_mul(f_2.unsqueeze(1), sensitivity_maps), fft_type=self.fft_type).type(f_2.type()),
)
dual_buffer = self.dual_net[idx](dual_buffer, f_2, y)
# Primal
h_1 = dual_buffer[..., 0:2].clone()
h_1 = complex_mul(
ifft2c(
torch.where(mask == 0, torch.tensor([0.0], dtype=h_1.dtype).to(h_1.device), h_1),
fft_type=self.fft_type,
),
complex_conj(sensitivity_maps),
).sum(1)
primal_buffer = self.primal_net[idx](primal_buffer, h_1)
output = primal_buffer[..., 0:2]
output = (output**2).sum(-1).sqrt()
_, output = center_crop_to_smallest(target, output)
return output
| [
"torch.nn.L1Loss",
"mridc.collections.common.losses.ssim.SSIMLoss",
"mridc.core.classes.common.typecheck",
"mridc.collections.reconstruction.models.primaldual.pd.DualNet",
"omegaconf.OmegaConf.to_container",
"mridc.collections.common.parts.utils.complex_conj",
"torch.tensor",
"mridc.collections.recons... | [((6103, 6114), 'mridc.core.classes.common.typecheck', 'typecheck', ([], {}), '()\n', (6112, 6114), False, 'from mridc.core.classes.common import typecheck\n'), ((1544, 1585), 'omegaconf.OmegaConf.to_container', 'OmegaConf.to_container', (['cfg'], {'resolve': '(True)'}), '(cfg, resolve=True)\n', (1566, 1585), False, 'from omegaconf import DictConfig, OmegaConf\n'), ((8335, 8374), 'mridc.collections.reconstruction.parts.utils.center_crop_to_smallest', 'center_crop_to_smallest', (['target', 'output'], {}), '(target, output)\n', (8358, 8374), False, 'from mridc.collections.reconstruction.parts.utils import center_crop_to_smallest\n'), ((5836, 5846), 'mridc.collections.common.losses.ssim.SSIMLoss', 'SSIMLoss', ([], {}), '()\n', (5844, 5846), False, 'from mridc.collections.common.losses.ssim import SSIMLoss\n'), ((5895, 5903), 'torch.nn.L1Loss', 'L1Loss', ([], {}), '()\n', (5901, 5903), False, 'from torch.nn import L1Loss\n'), ((5932, 5942), 'mridc.collections.common.losses.ssim.SSIMLoss', 'SSIMLoss', ([], {}), '()\n', (5940, 5942), False, 'from mridc.collections.common.losses.ssim import SSIMLoss\n'), ((5990, 5998), 'torch.nn.L1Loss', 'L1Loss', ([], {}), '()\n', (5996, 5998), False, 'from torch.nn import L1Loss\n'), ((5010, 5070), 'mridc.collections.reconstruction.models.primaldual.pd.PrimalNet', 'PrimalNet', (['self.num_primal'], {'primal_architecture': 'primal_model'}), '(self.num_primal, primal_architecture=primal_model)\n', (5019, 5070), False, 'from mridc.collections.reconstruction.models.primaldual.pd import DualNet, PrimalNet\n'), ((5170, 5222), 'mridc.collections.reconstruction.models.primaldual.pd.DualNet', 'DualNet', (['self.num_dual'], {'dual_architecture': 'dual_model'}), '(self.num_dual, dual_architecture=dual_model)\n', (5177, 5222), False, 'from mridc.collections.reconstruction.models.primaldual.pd import DualNet, PrimalNet\n'), ((7238, 7272), 'torch.cat', 'torch.cat', (['([y] * self.num_dual)', '(-1)'], {}), '([y] * self.num_dual, -1)\n', (7247, 7272), False, 'import torch\n'), ((7310, 7356), 'torch.cat', 'torch.cat', (['([input_image] * self.num_primal)', '(-1)'], {}), '([input_image] * self.num_primal, -1)\n', (7319, 7356), False, 'import torch\n'), ((7167, 7197), 'mridc.collections.common.parts.utils.complex_conj', 'complex_conj', (['sensitivity_maps'], {}), '(sensitivity_maps)\n', (7179, 7197), False, 'from mridc.collections.common.parts.utils import complex_conj, complex_mul\n'), ((2381, 2459), 'torch.nn.Conv2d', 'torch.nn.Conv2d', (['(2 * (self.num_primal + 1))', '(2 * self.num_primal)'], {'kernel_size': '(1)'}), '(2 * (self.num_primal + 1), 2 * self.num_primal, kernel_size=1)\n', (2396, 2459), False, 'import torch\n'), ((7555, 7591), 'torch.tensor', 'torch.tensor', (['[0.0]'], {'dtype': 'f_2.dtype'}), '([0.0], dtype=f_2.dtype)\n', (7567, 7591), False, 'import torch\n'), ((8107, 8137), 'mridc.collections.common.parts.utils.complex_conj', 'complex_conj', (['sensitivity_maps'], {}), '(sensitivity_maps)\n', (8119, 8137), False, 'from mridc.collections.common.parts.utils import complex_conj, complex_mul\n'), ((7077, 7111), 'torch.tensor', 'torch.tensor', (['[0.0]'], {'dtype': 'y.dtype'}), '([0.0], dtype=y.dtype)\n', (7089, 7111), False, 'import torch\n'), ((7969, 8005), 'torch.tensor', 'torch.tensor', (['[0.0]'], {'dtype': 'h_1.dtype'}), '([0.0], dtype=h_1.dtype)\n', (7981, 8005), False, 'import torch\n')] |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import uuid
from botbuilder.schema import (
Activity,
ActivityEventNames,
ActivityTypes,
ConversationReference,
)
def get_continuation_activity(reference: ConversationReference) -> Activity:
return Activity(
type=ActivityTypes.event,
name=ActivityEventNames.continue_conversation,
id=str(uuid.uuid1()),
channel_id=reference.channel_id,
service_url=reference.service_url,
conversation=reference.conversation,
recipient=reference.bot,
from_property=reference.user,
relates_to=reference,
)
| [
"uuid.uuid1"
] | [((428, 440), 'uuid.uuid1', 'uuid.uuid1', ([], {}), '()\n', (438, 440), False, 'import uuid\n')] |
'''
Created on Feb 6, 2015
@author: cmccully
'''
from __future__ import absolute_import, division, print_function
from future.utils import iteritems
import time
import om10
import numpy as np
import re
import json
import os
import pandas as pd
import copy
import gzip
import shutil
from lsst.utils import getPackageDir
from lsst.sims.utils import SpecMap, defaultSpecMap
from lsst.sims.catUtils.baseCatalogModels import GalaxyTileCompoundObj
from lsst.sims.catUtils.matchSED import matchBase
from lsst.sims.photUtils import Bandpass, BandpassDict, Sed
from lsst.sims.utils import radiansFromArcsec
from lsst.sims.catUtils.supernovae import SNObject
__all__ = ['sprinklerCompound', 'sprinkler']
class sprinklerCompound(GalaxyTileCompoundObj):
objid = 'sprinklerCompound'
objectTypeId = 66
cached_sprinkling = False
agn_cache_file = None
sne_cache_file = None
defs_file = None
sed_path = None
def _final_pass(self, results):
#From the original GalaxyTileCompoundObj final pass method
for name in results.dtype.fields:
if 'raJ2000' in name or 'decJ2000' in name:
results[name] = np.radians(results[name])
# the stored procedure on fatboy that queries the galaxies
# constructs galtileid by taking
#
# tileid*10^8 + galid
#
# this causes galtileid to be so large that the uniqueIDs in the
# Twinkles InstanceCatalogs are too large for PhoSim to handle.
# Since Twinkles is only focused on one tile on the sky, we will remove
# the factor of 10^8, making the uniqueIDs a more manageable size
# results['galtileid'] = results['galtileid']#%100000000
#Use Sprinkler now
sp = sprinkler(results, self.mjd, self.specFileMap, self.sed_path,
density_param=1.0,
cached_sprinkling=self.cached_sprinkling,
agn_cache_file=self.agn_cache_file,
sne_cache_file=self.sne_cache_file,
defs_file=self.defs_file)
results = sp.sprinkle()
return results
class sprinkler():
def __init__(self, catsim_cat, visit_mjd, specFileMap, sed_path,
om10_cat='twinkles_lenses_v2.fits',
sne_cat='dc2_sne_cat.csv', density_param=1., cached_sprinkling=False,
agn_cache_file=None, sne_cache_file=None, defs_file=None,
write_sn_sed=True):
"""
Parameters
----------
catsim_cat: catsim catalog
The results array from an instance catalog.
visit_mjd: float
The mjd of the visit
specFileMap:
This will tell the instance catalog where to write the files
sed_path: str
This tells where to write out SNe SED files
om10_cat: optional, defaults to 'twinkles_lenses_v2.fits
fits file with OM10 catalog
sne_cat: optional, defaults to 'dc2_sne_cat.csv'
density_param: `np.float`, optioanl, defaults to 1.0
the fraction of eligible agn objects that become lensed and should
be between 0.0 and 1.0.
cached_sprinkling: boolean
If true then pick from a preselected list of galtileids
agn_cache_file: str
sne_cache_file: str
defs_file: str
write_sn_sed: boolean
Controls whether or not to actually write supernova
SEDs to disk (default=True)
Returns
-------
input_catalog:
results array with lens systems added.
"""
t_start = time.time()
twinklesDir = getPackageDir('Twinkles')
om10_cat = os.path.join(twinklesDir, 'data', om10_cat)
self.write_sn_sed = write_sn_sed
self.catalog_column_names = catsim_cat.dtype.names
# ****** THIS ASSUMES THAT THE ENVIRONMENT VARIABLE OM10_DIR IS SET *******
lensdb = om10.DB(catalog=om10_cat, vb=False)
self.lenscat = lensdb.lenses.copy()
self.density_param = density_param
self.bandpassDict = BandpassDict.loadTotalBandpassesFromFiles(bandpassNames=['i'])
self.lsst_band_indexes = {'u':0, 'g':1, 'r':2, 'i':3, 'z':4, 'y':5}
self.sne_catalog = pd.read_csv(os.path.join(twinklesDir, 'data', sne_cat))
#self.sne_catalog = self.sne_catalog.iloc[:101] ### Remove this after testing
self.used_systems = []
self._visit_mjd = visit_mjd
self.sn_obj = SNObject(0., 0.)
self.write_dir = specFileMap.subdir_map['(^specFileGLSN)']
self.sed_path = sed_path
self.cached_sprinkling = cached_sprinkling
if self.cached_sprinkling is True:
if ((agn_cache_file is None) | (sne_cache_file is None)):
raise AttributeError('Must specify cache files if using cached_sprinkling.')
#agn_cache_file = os.path.join(twinklesDir, 'data', 'test_agn_galtile_cache.csv')
self.agn_cache = pd.read_csv(agn_cache_file)
#sne_cache_file = os.path.join(twinklesDir, 'data', 'test_sne_galtile_cache.csv')
self.sne_cache = pd.read_csv(sne_cache_file)
else:
self.agn_cache = None
self.sne_cache = None
if defs_file is None:
self.defs_file = os.path.join(twinklesDir, 'data', 'catsim_defs.csv')
else:
self.defs_file = defs_file
self.sedDir = getPackageDir('sims_sed_library')
self.imSimBand = Bandpass()
self.imSimBand.imsimBandpass()
#self.LRG_name = 'Burst.25E09.1Z.spec'
#self.LRG = Sed()
#self.LRG.readSED_flambda(str(galDir + self.LRG_name))
#return
#Calculate imsimband magnitudes of source galaxies for matching
agn_fname = str(getPackageDir('sims_sed_library') + '/agnSED/agn.spec.gz')
src_iband = self.lenscat['MAGI_IN']
src_z = self.lenscat['ZSRC']
self.src_mag_norm = []
for src, s_z in zip(src_iband, src_z):
agn_sed = Sed()
agn_sed.readSED_flambda(agn_fname)
agn_sed.redshiftSED(s_z, dimming=True)
self.src_mag_norm.append(matchBase().calcMagNorm([src],
agn_sed,
self.bandpassDict))
#self.src_mag_norm = matchBase().calcMagNorm(src_iband,
# [agn_sed]*len(src_iband),
#
# self.bandpassDict)
has_sn_truth_params = False
for name in self.catalog_column_names:
if 'sn_truth_params' in name:
has_sn_truth_params = True
break
self.defs_dict = {}
self.logging_is_sprinkled = False
self.store_sn_truth_params = False
with open(self.defs_file, 'r') as f:
for line in f:
line_defs = line.strip().split(',')
if len(line_defs) > 1:
if 'is_sprinkled' in line_defs[1]:
self.logging_is_sprinkled = True
if 'sn_truth_params' in line_defs[1] and has_sn_truth_params:
self.store_sn_truth_params = True
if len(line_defs) == 2:
self.defs_dict[line_defs[0]] = line_defs[1]
else:
self.defs_dict[line_defs[0]] = tuple((ll for ll in line_defs[1:]))
duration = time.time()-t_start
duration /= 3600.0
print('initialized sprinkler in %e hours' % duration)
@property
def visit_mjd(self):
return self._visit_mjd
@visit_mjd.setter
def visit_mjd(self, val):
self._visit_mjd = val
def sprinkle(self, input_catalog, catalog_band):
# Define a list that we can write out to a text file
lenslines = []
# For each galaxy in the catsim catalog
if isinstance(self.defs_dict['galtileid'], tuple):
galid_dex = self.defs_dict['galtileid'][0]
else:
galid_dex = self.defs_dict['galtileid']
agn_magnorm_dex = self.defs_dict['galaxyAgn_magNorm']
agn_magnorm_array = np.array([row[agn_magnorm_dex] for row in input_catalog])
nan_magnorm = np.isnan(agn_magnorm_array)
if self.cached_sprinkling:
if not hasattr(self, '_unq_agn_gid'):
self._unq_agn_gid = np.unique(self.agn_cache['galtileid'].values)
self._unq_sne_gid = np.unique(self.sne_cache['galtileid'].values)
galtileid_array = np.array([row[galid_dex] for row in input_catalog])
valid_agn = np.where(np.logical_and(np.logical_not(nan_magnorm),
np.in1d(galtileid_array,
self._unq_agn_gid,
assume_unique=True)))[0]
valid_sne = np.where(np.logical_and(nan_magnorm,
np.in1d(galtileid_array,
self._unq_sne_gid,
assume_unique=True)))[0]
else:
valid_agn = np.where(np.logical_not(nan_magnorm))[0]
valid_sne = np.where(nan_magnorm)[0]
new_rows = []
# print("Running sprinkler. Catalog Length: ", len(input_catalog))
for rowNum in valid_agn:
row = input_catalog[rowNum]
galtileid = row[galid_dex]
if not self.cached_sprinkling:
candidates = self.find_lens_candidates(row[self.defs_dict['galaxyAgn_redshift']],
row[self.defs_dict['galaxyAgn_magNorm']])
rng = np.random.RandomState(galtileid % (2**32 -1))
pick_value = rng.uniform()
if len(candidates) == 0 or pick_value>self.density_param:
# If there aren't any lensed sources at this redshift from
# OM10 move on the next object
continue
# Randomly choose one the lens systems
# (can decide with or without replacement)
# Sort first to make sure the same choice is made every time
candidates = candidates[np.argsort(candidates['twinklesId'])]
newlens = rng.choice(candidates)
else:
twinkles_sys_cache = self.agn_cache.query('galtileid == %i' % galtileid)['twinkles_system'].values[0]
newlens = self.lenscat[np.where(self.lenscat['twinklesId'] == twinkles_sys_cache)[0]][0]
#varString = json.loads(row[self.defs_dict['galaxyAgn_varParamStr']])
# varString[self.defs_dict['pars']]['t0_mjd'] = 59300.0
#row[self.defs_dict['galaxyAgn_varParamStr']] = json.dumps(varString)
# Append the lens galaxy
# For each image, append the lens images
default_lensrow = None
if newlens['NIMG'] > 0:
default_lensrow = row.copy()
default_lensrow[self.defs_dict['galaxyDisk_majorAxis']] = 0.0
default_lensrow[self.defs_dict['galaxyDisk_minorAxis']] = 0.0
default_lensrow[self.defs_dict['galaxyDisk_positionAngle']] = 0.0
default_lensrow[self.defs_dict['galaxyDisk_internalAv']] = 0.0
default_lensrow[self.defs_dict['galaxyDisk_magNorm']] = 999.
default_lensrow[self.defs_dict['galaxyDisk_sedFilename']] = None
default_lensrow[self.defs_dict['galaxyBulge_majorAxis']] = 0.0
default_lensrow[self.defs_dict['galaxyBulge_minorAxis']] = 0.0
default_lensrow[self.defs_dict['galaxyBulge_positionAngle']] = 0.0
default_lensrow[self.defs_dict['galaxyBulge_internalAv']] = 0.0
default_lensrow[self.defs_dict['galaxyBulge_magNorm']] = 999.
default_lensrow[self.defs_dict['galaxyBulge_sedFilename']] = None
default_lensrow[self.defs_dict['galaxyBulge_redshift']] = newlens['ZSRC']
default_lensrow[self.defs_dict['galaxyDisk_redshift']] = newlens['ZSRC']
default_lensrow[self.defs_dict['galaxyAgn_redshift']] = newlens['ZSRC']
for i in range(newlens['NIMG']):
lensrow = default_lensrow.copy()
# XIMG and YIMG are in arcseconds
# raPhSim and decPhoSim are in radians
# Shift all parts of the lensed object,
# not just its agn part
delta_dec = np.radians(newlens['YIMG'][i] / 3600.0)
delta_ra = np.radians(newlens['XIMG'][i] / 3600.0)
lens_ra = lensrow[self.defs_dict['raJ2000']]
lens_dec = lensrow[self.defs_dict['decJ2000']]
lensrow[self.defs_dict['raJ2000']] = lens_ra + delta_ra/np.cos(lens_dec)
lensrow[self.defs_dict['decJ2000']] = lens_dec + delta_dec
mag_adjust = 2.5*np.log10(np.abs(newlens['MAG'][i]))
lensrow[self.defs_dict['galaxyAgn_magNorm']] -= mag_adjust
varString = json.loads(lensrow[self.defs_dict['galaxyAgn_varParamStr']])
varString[self.defs_dict['pars']]['t0Delay'] = newlens['DELAY'][i]
varString[self.defs_dict['varMethodName']] = 'applyAgnTimeDelay'
lensrow[self.defs_dict['galaxyAgn_varParamStr']] = json.dumps(varString)
if self.logging_is_sprinkled:
lensrow[self.defs_dict['galaxyAgn_is_sprinkled']] = 1
lensrow[self.defs_dict['galaxyBulge_is_sprinkled']] = 1
lensrow[self.defs_dict['galaxyDisk_is_sprinkled']] = 1
#To get back twinklesID in lens catalog from phosim catalog id number
#just use np.right_shift(phosimID-28, 10). Take the floor of the last
#3 numbers to get twinklesID in the twinkles lens catalog and the remainder is
#the image number minus 1.
if not isinstance(self.defs_dict['galtileid'], tuple):
lensrow[self.defs_dict['galtileid']] = ((lensrow[self.defs_dict['galtileid']]+int(1.5e10))*100000 +
newlens['twinklesId']*8 + i)
else:
for col_name in self.defs_dict['galtileid']:
lensrow[col_name] = ((lensrow[col_name]+int(1.5e10))*100000 +
newlens['twinklesId']*8 + i)
new_rows.append(lensrow)
#Now manipulate original entry to be the lens galaxy with desired properties
#Start by deleting Disk and AGN properties
if not np.isnan(row[self.defs_dict['galaxyDisk_magNorm']]):
row[self.defs_dict['galaxyDisk_majorAxis']] = 0.0
row[self.defs_dict['galaxyDisk_minorAxis']] = 0.0
row[self.defs_dict['galaxyDisk_positionAngle']] = 0.0
row[self.defs_dict['galaxyDisk_internalAv']] = 0.0
row[self.defs_dict['galaxyDisk_magNorm']] = 999.
row[self.defs_dict['galaxyDisk_sedFilename']] = None
row[self.defs_dict['galaxyAgn_magNorm']] = None
row[self.defs_dict['galaxyDisk_magNorm']] = 999.
row[self.defs_dict['galaxyAgn_sedFilename']] = None
#Now insert desired Bulge properties
row[self.defs_dict['galaxyBulge_sedFilename']] = newlens['lens_sed']
row[self.defs_dict['galaxyBulge_redshift']] = newlens['ZLENS']
row[self.defs_dict['galaxyDisk_redshift']] = newlens['ZLENS']
row[self.defs_dict['galaxyAgn_redshift']] = newlens['ZLENS']
row_lens_sed = Sed()
row_lens_sed.readSED_flambda(os.path.join(self.sedDir,
newlens['lens_sed']))
row_lens_sed.redshiftSED(newlens['ZLENS'], dimming=True)
# Get the correct magnorm to maintain galaxy colors
row[self.defs_dict['galaxyBulge_magNorm']] = newlens['sed_magNorm'][self.lsst_band_indexes[catalog_band]]
row[self.defs_dict['galaxyBulge_majorAxis']] = radiansFromArcsec(newlens['REFF'] / np.sqrt(1 - newlens['ELLIP']))
row[self.defs_dict['galaxyBulge_minorAxis']] = radiansFromArcsec(newlens['REFF'] * np.sqrt(1 - newlens['ELLIP']))
#Convert orientation angle to west of north from east of north by *-1.0 and convert to radians
row[self.defs_dict['galaxyBulge_positionAngle']] = newlens['PHIE']*(-1.0)*np.pi/180.0
row[self.defs_dict['galaxyBulge_internalAv']] = newlens['lens_av']
row[self.defs_dict['galaxyBulge_internalRv']] = newlens['lens_rv']
if self.logging_is_sprinkled:
row[self.defs_dict['galaxyAgn_is_sprinkled']] = 1
row[self.defs_dict['galaxyBulge_is_sprinkled']] = 1
row[self.defs_dict['galaxyDisk_is_sprinkled']] = 1
#Replace original entry with new entry
input_catalog[rowNum] = row
for rowNum in valid_sne:
row = input_catalog[rowNum]
galtileid = row[galid_dex]
if self.cached_sprinkling is True:
if galtileid in self.sne_cache['galtileid'].values:
use_system = self.sne_cache.query('galtileid == %i' % galtileid)['twinkles_system'].values
use_df = self.sne_catalog.query('twinkles_sysno == %i' % use_system)
self.used_systems.append(use_system)
else:
continue
else:
lens_sne_candidates = self.find_sne_lens_candidates(row[self.defs_dict['galaxyDisk_redshift']])
candidate_sysno = np.unique(lens_sne_candidates['twinkles_sysno'])
num_candidates = len(candidate_sysno)
if num_candidates == 0:
continue
used_already = np.array([sys_num in self.used_systems for sys_num in candidate_sysno])
unused_sysno = candidate_sysno[~used_already]
if len(unused_sysno) == 0:
continue
rng2 = np.random.RandomState(galtileid % (2**32 -1))
use_system = rng2.choice(unused_sysno)
use_df = self.sne_catalog.query('twinkles_sysno == %i' % use_system)
default_lensrow = row.copy()
default_lensrow[self.defs_dict['galaxyDisk_majorAxis']] = 0.0
default_lensrow[self.defs_dict['galaxyDisk_minorAxis']] = 0.0
default_lensrow[self.defs_dict['galaxyDisk_positionAngle']] = 0.0
default_lensrow[self.defs_dict['galaxyDisk_internalAv']] = 0.0
default_lensrow[self.defs_dict['galaxyDisk_magNorm']] = 999.
default_lensrow[self.defs_dict['galaxyDisk_sedFilename']] = None
default_lensrow[self.defs_dict['galaxyBulge_majorAxis']] = 0.0
default_lensrow[self.defs_dict['galaxyBulge_minorAxis']] = 0.0
default_lensrow[self.defs_dict['galaxyBulge_positionAngle']] = 0.0
default_lensrow[self.defs_dict['galaxyBulge_internalAv']] = 0.0
default_lensrow[self.defs_dict['galaxyBulge_magNorm']] = 999.
default_lensrow[self.defs_dict['galaxyBulge_sedFilename']] = None
varString = 'None'
default_lensrow[self.defs_dict['galaxyAgn_varParamStr']] = varString
for i in range(len(use_df)):
lensrow = default_lensrow.copy()
delta_ra = np.radians(use_df['x'].iloc[i] / 3600.0)
delta_dec = np.radians(use_df['y'].iloc[i] / 3600.0)
lens_ra = lensrow[self.defs_dict['raJ2000']]
lens_dec = lensrow[self.defs_dict['decJ2000']]
lensrow[self.defs_dict['raJ2000']] = lens_ra + delta_ra/np.cos(lens_dec)
lensrow[self.defs_dict['decJ2000']] = lens_dec + delta_dec
# varString = json.loads(lensrow[self.defs_dict['galaxyAgn_varParamStr']])
z_s = use_df['zs'].iloc[i]
lensrow[self.defs_dict['galaxyBulge_redshift']] = z_s
lensrow[self.defs_dict['galaxyDisk_redshift']] = z_s
lensrow[self.defs_dict['galaxyAgn_redshift']] = z_s
#To get back twinklesID in lens catalog from phosim catalog id number
#just use np.right_shift(phosimID-28, 10). Take the floor of the last
#3 numbers to get twinklesID in the twinkles lens catalog and the remainder is
#the image number minus 1.
if not isinstance(self.defs_dict['galtileid'], tuple):
lensrow[self.defs_dict['galtileid']] = ((lensrow[self.defs_dict['galtileid']]+int(1.5e10))*100000 +
use_system*8 + i)
else:
for col_name in self.defs_dict['galtileid']:
lensrow[col_name] = ((lensrow[col_name]+int(1.5e10))*100000 +
use_system*8 + i)
(add_to_cat, sn_magnorm,
sn_fname, sn_param_dict) = self.create_sn_sed(use_df.iloc[i],
lensrow[self.defs_dict['raJ2000']],
lensrow[self.defs_dict['decJ2000']],
self.visit_mjd,
write_sn_sed=self.write_sn_sed)
if self.store_sn_truth_params:
add_to_cat = True
lensrow[self.defs_dict['galaxyAgn_sn_truth_params']] = json.dumps(sn_param_dict)
lensrow[self.defs_dict['galaxyAgn_sn_t0']] = sn_param_dict['t0']
lensrow[self.defs_dict['galaxyAgn_sedFilename']] = sn_fname
lensrow[self.defs_dict['galaxyAgn_magNorm']] = sn_magnorm #This will need to be adjusted to proper band
mag_adjust = 2.5*np.log10(np.abs(use_df['mu'].iloc[i]))
lensrow[self.defs_dict['galaxyAgn_magNorm']] -= mag_adjust
if self.logging_is_sprinkled:
lensrow[self.defs_dict['galaxyAgn_is_sprinkled']] = 1
lensrow[self.defs_dict['galaxyBulge_is_sprinkled']] = 1
lensrow[self.defs_dict['galaxyDisk_is_sprinkled']] = 1
if add_to_cat is True:
new_rows.append(lensrow)
#Now manipulate original entry to be the lens galaxy with desired properties
#Start by deleting Disk and AGN properties
if not np.isnan(row[self.defs_dict['galaxyDisk_magNorm']]):
row[self.defs_dict['galaxyDisk_majorAxis']] = 0.0
row[self.defs_dict['galaxyDisk_minorAxis']] = 0.0
row[self.defs_dict['galaxyDisk_positionAngle']] = 0.0
row[self.defs_dict['galaxyDisk_internalAv']] = 0.0
row[self.defs_dict['galaxyDisk_magNorm']] = 999.
row[self.defs_dict['galaxyDisk_sedFilename']] = None
row[self.defs_dict['galaxyAgn_magNorm']] = None
row[self.defs_dict['galaxyDisk_magNorm']] = 999.
row[self.defs_dict['galaxyAgn_sedFilename']] = None
#Now insert desired Bulge properties
row[self.defs_dict['galaxyBulge_sedFilename']] = use_df['lensgal_sed'].iloc[0]
row[self.defs_dict['galaxyBulge_redshift']] = use_df['zl'].iloc[0]
row[self.defs_dict['galaxyDisk_redshift']] = use_df['zl'].iloc[0]
row[self.defs_dict['galaxyAgn_redshift']] = use_df['zl'].iloc[0]
row[self.defs_dict['galaxyBulge_magNorm']] = use_df['lensgal_magnorm_%s' % catalog_band].iloc[0]
# row[self.defs_dict['galaxyBulge_magNorm']] = matchBase().calcMagNorm([newlens['APMAG_I']], self.LRG, self.bandpassDict) #Changed from i band to imsimband
row[self.defs_dict['galaxyBulge_majorAxis']] = radiansFromArcsec(use_df['lensgal_reff'].iloc[0] / np.sqrt(1 - use_df['e'].iloc[0]))
row[self.defs_dict['galaxyBulge_minorAxis']] = radiansFromArcsec(use_df['lensgal_reff'].iloc[0] * np.sqrt(1 - use_df['e'].iloc[0]))
#Convert orientation angle to west of north from east of north by *-1.0 and convert to radians
row[self.defs_dict['galaxyBulge_positionAngle']] = use_df['theta_e'].iloc[0]*(-1.0)*np.pi/180.0
row[self.defs_dict['galaxyBulge_internalAv']] = use_df['lens_av'].iloc[0]
row[self.defs_dict['galaxyBulge_internalRv']] = use_df['lens_rv'].iloc[0]
if self.logging_is_sprinkled:
row[self.defs_dict['galaxyAgn_is_sprinkled']] = 1
row[self.defs_dict['galaxyBulge_is_sprinkled']] = 1
row[self.defs_dict['galaxyDisk_is_sprinkled']] = 1
#Replace original entry with new entry
input_catalog[rowNum] = row
if len(new_rows)>0:
input_catalog = np.append(input_catalog, new_rows)
return input_catalog
def find_lens_candidates(self, galz, gal_mag):
# search the OM10 catalog for all sources +- 0.1 dex in redshift
# and within .25 mags of the CATSIM source
w = np.where((np.abs(np.log10(self.lenscat['ZSRC']) - np.log10(galz)) <= 0.1) &
(np.abs(self.src_mag_norm - gal_mag) <= .25))[0]
lens_candidates = self.lenscat[w]
return lens_candidates
def find_sne_lens_candidates(self, galz):
w = np.where((np.abs(np.log10(self.sne_catalog['zs']) - np.log10(galz)) <= 0.1))
lens_candidates = self.sne_catalog.iloc[w]
return lens_candidates
def create_sn_sed(self, system_df, sn_ra, sn_dec, sed_mjd, write_sn_sed=True):
sn_param_dict = copy.deepcopy(self.sn_obj.SNstate)
sn_param_dict['_ra'] = sn_ra
sn_param_dict['_dec'] = sn_dec
sn_param_dict['z'] = system_df['zs']
sn_param_dict['c'] = system_df['c']
sn_param_dict['x0'] = system_df['x0']
sn_param_dict['x1'] = system_df['x1']
sn_param_dict['t0'] = system_df['t_start']
#sn_param_dict['t0'] = 62746.27 #+1500. ### For testing only
current_sn_obj = self.sn_obj.fromSNState(sn_param_dict)
current_sn_obj.mwEBVfromMaps()
wavelen_max = 1800.
wavelen_min = 30.
wavelen_step = 0.1
sn_sed_obj = current_sn_obj.SNObjectSED(time=sed_mjd,
wavelen=np.arange(wavelen_min, wavelen_max,
wavelen_step))
flux_500 = sn_sed_obj.flambda[np.where(sn_sed_obj.wavelen >= 499.99)][0]
if flux_500 > 0.:
add_to_cat = True
sn_magnorm = current_sn_obj.catsimBandMag(self.imSimBand, sed_mjd)
sn_name = None
if write_sn_sed:
sn_name = 'specFileGLSN_%i_%i_%.4f.txt' % (system_df['twinkles_sysno'],
system_df['imno'], sed_mjd)
sed_filename = '%s/%s' % (self.sed_path, sn_name)
sn_sed_obj.writeSED(sed_filename)
with open(sed_filename, 'rb') as f_in, gzip.open(str(sed_filename + '.gz'), 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
os.remove(sed_filename)
else:
add_to_cat = False
sn_magnorm = np.nan
sn_name = None
return add_to_cat, sn_magnorm, sn_name, current_sn_obj.SNstate
def update_catsim(self):
# Remove the catsim object
# Add lensed images to the catsim given source brightness and magnifications
# Add lens galaxy to catsim
return
def catsim_to_phosim(self):
# Pass this catsim to phosim to make images
return
| [
"lsst.utils.getPackageDir",
"json.dumps",
"shutil.copyfileobj",
"numpy.where",
"os.remove",
"numpy.isnan",
"pandas.read_csv",
"numpy.radians",
"numpy.arange",
"numpy.argsort",
"lsst.sims.catUtils.supernovae.SNObject",
"numpy.log10",
"numpy.random.RandomState",
"numpy.sqrt",
"numpy.logica... | [((3640, 3651), 'time.time', 'time.time', ([], {}), '()\n', (3649, 3651), False, 'import time\n'), ((3674, 3699), 'lsst.utils.getPackageDir', 'getPackageDir', (['"""Twinkles"""'], {}), "('Twinkles')\n", (3687, 3699), False, 'from lsst.utils import getPackageDir\n'), ((3719, 3762), 'os.path.join', 'os.path.join', (['twinklesDir', '"""data"""', 'om10_cat'], {}), "(twinklesDir, 'data', om10_cat)\n", (3731, 3762), False, 'import os\n'), ((3964, 3999), 'om10.DB', 'om10.DB', ([], {'catalog': 'om10_cat', 'vb': '(False)'}), '(catalog=om10_cat, vb=False)\n', (3971, 3999), False, 'import om10\n'), ((4115, 4177), 'lsst.sims.photUtils.BandpassDict.loadTotalBandpassesFromFiles', 'BandpassDict.loadTotalBandpassesFromFiles', ([], {'bandpassNames': "['i']"}), "(bandpassNames=['i'])\n", (4156, 4177), False, 'from lsst.sims.photUtils import Bandpass, BandpassDict, Sed\n'), ((4513, 4531), 'lsst.sims.catUtils.supernovae.SNObject', 'SNObject', (['(0.0)', '(0.0)'], {}), '(0.0, 0.0)\n', (4521, 4531), False, 'from lsst.sims.catUtils.supernovae import SNObject\n'), ((5461, 5494), 'lsst.utils.getPackageDir', 'getPackageDir', (['"""sims_sed_library"""'], {}), "('sims_sed_library')\n", (5474, 5494), False, 'from lsst.utils import getPackageDir\n'), ((5521, 5531), 'lsst.sims.photUtils.Bandpass', 'Bandpass', ([], {}), '()\n', (5529, 5531), False, 'from lsst.sims.photUtils import Bandpass, BandpassDict, Sed\n'), ((8299, 8356), 'numpy.array', 'np.array', (['[row[agn_magnorm_dex] for row in input_catalog]'], {}), '([row[agn_magnorm_dex] for row in input_catalog])\n', (8307, 8356), True, 'import numpy as np\n'), ((8379, 8406), 'numpy.isnan', 'np.isnan', (['agn_magnorm_array'], {}), '(agn_magnorm_array)\n', (8387, 8406), True, 'import numpy as np\n'), ((26235, 26269), 'copy.deepcopy', 'copy.deepcopy', (['self.sn_obj.SNstate'], {}), '(self.sn_obj.SNstate)\n', (26248, 26269), False, 'import copy\n'), ((4294, 4336), 'os.path.join', 'os.path.join', (['twinklesDir', '"""data"""', 'sne_cat'], {}), "(twinklesDir, 'data', sne_cat)\n", (4306, 4336), False, 'import os\n'), ((5011, 5038), 'pandas.read_csv', 'pd.read_csv', (['agn_cache_file'], {}), '(agn_cache_file)\n', (5022, 5038), True, 'import pandas as pd\n'), ((5162, 5189), 'pandas.read_csv', 'pd.read_csv', (['sne_cache_file'], {}), '(sne_cache_file)\n', (5173, 5189), True, 'import pandas as pd\n'), ((5332, 5384), 'os.path.join', 'os.path.join', (['twinklesDir', '"""data"""', '"""catsim_defs.csv"""'], {}), "(twinklesDir, 'data', 'catsim_defs.csv')\n", (5344, 5384), False, 'import os\n'), ((6061, 6066), 'lsst.sims.photUtils.Sed', 'Sed', ([], {}), '()\n', (6064, 6066), False, 'from lsst.sims.photUtils import Bandpass, BandpassDict, Sed\n'), ((7578, 7589), 'time.time', 'time.time', ([], {}), '()\n', (7587, 7589), False, 'import time\n'), ((8688, 8739), 'numpy.array', 'np.array', (['[row[galid_dex] for row in input_catalog]'], {}), '([row[galid_dex] for row in input_catalog])\n', (8696, 8739), True, 'import numpy as np\n'), ((16028, 16033), 'lsst.sims.photUtils.Sed', 'Sed', ([], {}), '()\n', (16031, 16033), False, 'from lsst.sims.photUtils import Bandpass, BandpassDict, Sed\n'), ((25433, 25467), 'numpy.append', 'np.append', (['input_catalog', 'new_rows'], {}), '(input_catalog, new_rows)\n', (25442, 25467), True, 'import numpy as np\n'), ((1155, 1180), 'numpy.radians', 'np.radians', (['results[name]'], {}), '(results[name])\n', (1165, 1180), True, 'import numpy as np\n'), ((5821, 5854), 'lsst.utils.getPackageDir', 'getPackageDir', (['"""sims_sed_library"""'], {}), "('sims_sed_library')\n", (5834, 5854), False, 'from lsst.utils import getPackageDir\n'), ((8529, 8574), 'numpy.unique', 'np.unique', (["self.agn_cache['galtileid'].values"], {}), "(self.agn_cache['galtileid'].values)\n", (8538, 8574), True, 'import numpy as np\n'), ((8611, 8656), 'numpy.unique', 'np.unique', (["self.sne_cache['galtileid'].values"], {}), "(self.sne_cache['galtileid'].values)\n", (8620, 8656), True, 'import numpy as np\n'), ((9440, 9461), 'numpy.where', 'np.where', (['nan_magnorm'], {}), '(nan_magnorm)\n', (9448, 9461), True, 'import numpy as np\n'), ((9936, 9984), 'numpy.random.RandomState', 'np.random.RandomState', (['(galtileid % (2 ** 32 - 1))'], {}), '(galtileid % (2 ** 32 - 1))\n', (9957, 9984), True, 'import numpy as np\n'), ((12807, 12846), 'numpy.radians', 'np.radians', (["(newlens['YIMG'][i] / 3600.0)"], {}), "(newlens['YIMG'][i] / 3600.0)\n", (12817, 12846), True, 'import numpy as np\n'), ((12874, 12913), 'numpy.radians', 'np.radians', (["(newlens['XIMG'][i] / 3600.0)"], {}), "(newlens['XIMG'][i] / 3600.0)\n", (12884, 12913), True, 'import numpy as np\n'), ((13374, 13434), 'json.loads', 'json.loads', (["lensrow[self.defs_dict['galaxyAgn_varParamStr']]"], {}), "(lensrow[self.defs_dict['galaxyAgn_varParamStr']])\n", (13384, 13434), False, 'import json\n'), ((13666, 13687), 'json.dumps', 'json.dumps', (['varString'], {}), '(varString)\n', (13676, 13687), False, 'import json\n'), ((15008, 15059), 'numpy.isnan', 'np.isnan', (["row[self.defs_dict['galaxyDisk_magNorm']]"], {}), "(row[self.defs_dict['galaxyDisk_magNorm']])\n", (15016, 15059), True, 'import numpy as np\n'), ((16075, 16121), 'os.path.join', 'os.path.join', (['self.sedDir', "newlens['lens_sed']"], {}), "(self.sedDir, newlens['lens_sed'])\n", (16087, 16121), False, 'import os\n'), ((18080, 18128), 'numpy.unique', 'np.unique', (["lens_sne_candidates['twinkles_sysno']"], {}), "(lens_sne_candidates['twinkles_sysno'])\n", (18089, 18128), True, 'import numpy as np\n'), ((18283, 18356), 'numpy.array', 'np.array', (['[(sys_num in self.used_systems) for sys_num in candidate_sysno]'], {}), '([(sys_num in self.used_systems) for sys_num in candidate_sysno])\n', (18291, 18356), True, 'import numpy as np\n'), ((18512, 18560), 'numpy.random.RandomState', 'np.random.RandomState', (['(galtileid % (2 ** 32 - 1))'], {}), '(galtileid % (2 ** 32 - 1))\n', (18533, 18560), True, 'import numpy as np\n'), ((19878, 19918), 'numpy.radians', 'np.radians', (["(use_df['x'].iloc[i] / 3600.0)"], {}), "(use_df['x'].iloc[i] / 3600.0)\n", (19888, 19918), True, 'import numpy as np\n'), ((19947, 19987), 'numpy.radians', 'np.radians', (["(use_df['y'].iloc[i] / 3600.0)"], {}), "(use_df['y'].iloc[i] / 3600.0)\n", (19957, 19987), True, 'import numpy as np\n'), ((23072, 23123), 'numpy.isnan', 'np.isnan', (["row[self.defs_dict['galaxyDisk_magNorm']]"], {}), "(row[self.defs_dict['galaxyDisk_magNorm']])\n", (23080, 23123), True, 'import numpy as np\n'), ((26951, 27000), 'numpy.arange', 'np.arange', (['wavelen_min', 'wavelen_max', 'wavelen_step'], {}), '(wavelen_min, wavelen_max, wavelen_step)\n', (26960, 27000), True, 'import numpy as np\n'), ((27106, 27144), 'numpy.where', 'np.where', (['(sn_sed_obj.wavelen >= 499.99)'], {}), '(sn_sed_obj.wavelen >= 499.99)\n', (27114, 27144), True, 'import numpy as np\n'), ((27808, 27831), 'os.remove', 'os.remove', (['sed_filename'], {}), '(sed_filename)\n', (27817, 27831), False, 'import os\n'), ((9384, 9411), 'numpy.logical_not', 'np.logical_not', (['nan_magnorm'], {}), '(nan_magnorm)\n', (9398, 9411), True, 'import numpy as np\n'), ((10492, 10528), 'numpy.argsort', 'np.argsort', (["candidates['twinklesId']"], {}), "(candidates['twinklesId'])\n", (10502, 10528), True, 'import numpy as np\n'), ((16524, 16553), 'numpy.sqrt', 'np.sqrt', (["(1 - newlens['ELLIP'])"], {}), "(1 - newlens['ELLIP'])\n", (16531, 16553), True, 'import numpy as np\n'), ((16650, 16679), 'numpy.sqrt', 'np.sqrt', (["(1 - newlens['ELLIP'])"], {}), "(1 - newlens['ELLIP'])\n", (16657, 16679), True, 'import numpy as np\n'), ((22088, 22113), 'json.dumps', 'json.dumps', (['sn_param_dict'], {}), '(sn_param_dict)\n', (22098, 22113), False, 'import json\n'), ((24474, 24506), 'numpy.sqrt', 'np.sqrt', (["(1 - use_df['e'].iloc[0])"], {}), "(1 - use_df['e'].iloc[0])\n", (24481, 24506), True, 'import numpy as np\n'), ((24618, 24650), 'numpy.sqrt', 'np.sqrt', (["(1 - use_df['e'].iloc[0])"], {}), "(1 - use_df['e'].iloc[0])\n", (24625, 24650), True, 'import numpy as np\n'), ((27760, 27791), 'shutil.copyfileobj', 'shutil.copyfileobj', (['f_in', 'f_out'], {}), '(f_in, f_out)\n', (27778, 27791), False, 'import shutil\n'), ((6202, 6213), 'lsst.sims.catUtils.matchSED.matchBase', 'matchBase', ([], {}), '()\n', (6211, 6213), False, 'from lsst.sims.catUtils.matchSED import matchBase\n'), ((8788, 8815), 'numpy.logical_not', 'np.logical_not', (['nan_magnorm'], {}), '(nan_magnorm)\n', (8802, 8815), True, 'import numpy as np\n'), ((8865, 8928), 'numpy.in1d', 'np.in1d', (['galtileid_array', 'self._unq_agn_gid'], {'assume_unique': '(True)'}), '(galtileid_array, self._unq_agn_gid, assume_unique=True)\n', (8872, 8928), True, 'import numpy as np\n'), ((9156, 9219), 'numpy.in1d', 'np.in1d', (['galtileid_array', 'self._unq_sne_gid'], {'assume_unique': '(True)'}), '(galtileid_array, self._unq_sne_gid, assume_unique=True)\n', (9163, 9219), True, 'import numpy as np\n'), ((13110, 13126), 'numpy.cos', 'np.cos', (['lens_dec'], {}), '(lens_dec)\n', (13116, 13126), True, 'import numpy as np\n'), ((13244, 13269), 'numpy.abs', 'np.abs', (["newlens['MAG'][i]"], {}), "(newlens['MAG'][i])\n", (13250, 13269), True, 'import numpy as np\n'), ((20184, 20200), 'numpy.cos', 'np.cos', (['lens_dec'], {}), '(lens_dec)\n', (20190, 20200), True, 'import numpy as np\n'), ((22438, 22466), 'numpy.abs', 'np.abs', (["use_df['mu'].iloc[i]"], {}), "(use_df['mu'].iloc[i])\n", (22444, 22466), True, 'import numpy as np\n'), ((25784, 25819), 'numpy.abs', 'np.abs', (['(self.src_mag_norm - gal_mag)'], {}), '(self.src_mag_norm - gal_mag)\n', (25790, 25819), True, 'import numpy as np\n'), ((25983, 26015), 'numpy.log10', 'np.log10', (["self.sne_catalog['zs']"], {}), "(self.sne_catalog['zs'])\n", (25991, 26015), True, 'import numpy as np\n'), ((26018, 26032), 'numpy.log10', 'np.log10', (['galz'], {}), '(galz)\n', (26026, 26032), True, 'import numpy as np\n'), ((10754, 10812), 'numpy.where', 'np.where', (["(self.lenscat['twinklesId'] == twinkles_sys_cache)"], {}), "(self.lenscat['twinklesId'] == twinkles_sys_cache)\n", (10762, 10812), True, 'import numpy as np\n'), ((25703, 25733), 'numpy.log10', 'np.log10', (["self.lenscat['ZSRC']"], {}), "(self.lenscat['ZSRC'])\n", (25711, 25733), True, 'import numpy as np\n'), ((25736, 25750), 'numpy.log10', 'np.log10', (['galz'], {}), '(galz)\n', (25744, 25750), True, 'import numpy as np\n')] |
from collections import deque
import numpy as np
import imutils
import cv2
import numpy as np
import time
import wiringpi as wp
import time
import serial
wp.wiringPiSetupGpio()
def motor(x, y, pwm): #FUNCTION FOR THE MOTOR PINS AND ITS PWM
wp.pinMode(x, 1)
wp.pinMode(y, 1)
wp.pinMode(pwm, 1)
wp.softPwmCreate(pwm, 0, 100)
return x, y, pwm
def forward(motor1, speed1, motor2, speed2): #FUNCTION FOR THE SPEED AND DIRECTION
(x1, y1, pwm1) = motor1
(x2, y2, pwm2) = motor2
wp.digitalWrite(x1, 0)
wp.digitalWrite(y1, 1)
wp.digitalWrite(x2, 1)
wp.digitalWrite(y2 ,0)
wp.softPwmWrite(pwm1, speed1)
wp.softPwmWrite(pwm2, speed2)
motor1 = motor(18, 24, 25) #INITIALIZING THE MOTOR1
motor2 = motor(12, 17, 23) #INITIALIZING THE MOTOR1
lowerBound=np.array([73, 170, 151])
upperBound=np.array([179, 255, 255])
while True:
if(wp.digitalRead(20)==1): # REACHING THE TREE LINE
forward(motor1, 0, motor2, 0)
print("IMAGE PROCESSING")
cam= cv2.VideoCapture(-1)
kernelOpen=np.ones((5,5))
kernelClose=np.ones((20,20))
font=cv2.cv.InitFont(cv2.cv.CV_FONT_HERSHEY_SIMPLEX,2,0.5,0,3,1)
print("SCANNING FOR RIPE FRUITS") #WRIST OF THE ROBOT STARTS MOVING
x=0
ser=serial.Serial("/dev/ttyUSB0",9600)
time.sleep(5)
ser.write('3')
while True:
y=ser.read()
if(y==9):
break
ret, img=cam.read()
cb=0;
img=cv2.resize(img,(340,220))
#convert BGR to HSV
imgHSV= cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
# create the Mask to hide the back ground
mask=cv2.inRange(imgHSV,lowerBound,upperBound)
#morphology
maskOpen=cv2.morphologyEx(mask,cv2.MORPH_OPEN,kernelOpen)
maskClose=cv2.morphologyEx(maskOpen,cv2.MORPH_CLOSE,kernelClose)
maskFinal=maskClose
conts,h=cv2.findContours(maskFinal.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
cb=cv2.countNonZero(maskClose)
print(cb)
if(cb>3000):
ser.write('2')
#cv2.drawContours(img,conts,-1,(255,0,0),3)
for i in range(len(conts)):
x,y,w,h=cv2.boundingRect(conts[i])
cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255), 2)
cv2.cv.PutText(cv2.cv.fromarray(img), str(i+1),(x,y+h),font,(0,255,255))
cv2.imshow("maskClose",maskClose)
cv2.imshow("maskOpen",maskOpen)
cv2.imshow("mask",mask)
cv2.imshow("cam",img)
cv2.waitKey(10)
k= cv2.waitKey(1)
if k==27:
break
cam.release()
cv2.destroyAllWindows()
for i in range(100):
forward(motor1, 70, motor2, 80)
else:
if ((wp.digitalRead(21)==1) & (wp.digitalRead(22)==1)): #forward
forward(motor1, 70, motor2, 80)
print("forward")
elif ((wp.digitalRead(21)==0) & (wp.digitalRead(22)==1)): #right turn
forward(motor1, 0, motor2, 30)
print("right")
elif ((wp.digitalRead(21)==1) & (wp.digitalRead(22)==0)): #left turn
forward(motor1, 30, motor2, 0)
print("left")
else: #stay still
forward(motor1, 0, motor2, 0)
print("stop")
| [
"cv2.imshow",
"cv2.boundingRect",
"cv2.cv.fromarray",
"wiringpi.pinMode",
"serial.Serial",
"cv2.cvtColor",
"numpy.ones",
"cv2.countNonZero",
"wiringpi.digitalRead",
"cv2.morphologyEx",
"wiringpi.softPwmWrite",
"wiringpi.wiringPiSetupGpio",
"wiringpi.softPwmCreate",
"cv2.cv.InitFont",
"cv... | [((183, 205), 'wiringpi.wiringPiSetupGpio', 'wp.wiringPiSetupGpio', ([], {}), '()\n', (203, 205), True, 'import wiringpi as wp\n'), ((885, 909), 'numpy.array', 'np.array', (['[73, 170, 151]'], {}), '([73, 170, 151])\n', (893, 909), True, 'import numpy as np\n'), ((924, 949), 'numpy.array', 'np.array', (['[179, 255, 255]'], {}), '([179, 255, 255])\n', (932, 949), True, 'import numpy as np\n'), ((281, 297), 'wiringpi.pinMode', 'wp.pinMode', (['x', '(1)'], {}), '(x, 1)\n', (291, 297), True, 'import wiringpi as wp\n'), ((305, 321), 'wiringpi.pinMode', 'wp.pinMode', (['y', '(1)'], {}), '(y, 1)\n', (315, 321), True, 'import wiringpi as wp\n'), ((329, 347), 'wiringpi.pinMode', 'wp.pinMode', (['pwm', '(1)'], {}), '(pwm, 1)\n', (339, 347), True, 'import wiringpi as wp\n'), ((355, 384), 'wiringpi.softPwmCreate', 'wp.softPwmCreate', (['pwm', '(0)', '(100)'], {}), '(pwm, 0, 100)\n', (371, 384), True, 'import wiringpi as wp\n'), ((565, 587), 'wiringpi.digitalWrite', 'wp.digitalWrite', (['x1', '(0)'], {}), '(x1, 0)\n', (580, 587), True, 'import wiringpi as wp\n'), ((595, 617), 'wiringpi.digitalWrite', 'wp.digitalWrite', (['y1', '(1)'], {}), '(y1, 1)\n', (610, 617), True, 'import wiringpi as wp\n'), ((625, 647), 'wiringpi.digitalWrite', 'wp.digitalWrite', (['x2', '(1)'], {}), '(x2, 1)\n', (640, 647), True, 'import wiringpi as wp\n'), ((655, 677), 'wiringpi.digitalWrite', 'wp.digitalWrite', (['y2', '(0)'], {}), '(y2, 0)\n', (670, 677), True, 'import wiringpi as wp\n'), ((685, 714), 'wiringpi.softPwmWrite', 'wp.softPwmWrite', (['pwm1', 'speed1'], {}), '(pwm1, speed1)\n', (700, 714), True, 'import wiringpi as wp\n'), ((722, 751), 'wiringpi.softPwmWrite', 'wp.softPwmWrite', (['pwm2', 'speed2'], {}), '(pwm2, speed2)\n', (737, 751), True, 'import wiringpi as wp\n'), ((979, 997), 'wiringpi.digitalRead', 'wp.digitalRead', (['(20)'], {}), '(20)\n', (993, 997), True, 'import wiringpi as wp\n'), ((1129, 1149), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(-1)'], {}), '(-1)\n', (1145, 1149), False, 'import cv2\n'), ((1170, 1185), 'numpy.ones', 'np.ones', (['(5, 5)'], {}), '((5, 5))\n', (1177, 1185), True, 'import numpy as np\n'), ((1206, 1223), 'numpy.ones', 'np.ones', (['(20, 20)'], {}), '((20, 20))\n', (1213, 1223), True, 'import numpy as np\n'), ((1237, 1301), 'cv2.cv.InitFont', 'cv2.cv.InitFont', (['cv2.cv.CV_FONT_HERSHEY_SIMPLEX', '(2)', '(0.5)', '(0)', '(3)', '(1)'], {}), '(cv2.cv.CV_FONT_HERSHEY_SIMPLEX, 2, 0.5, 0, 3, 1)\n', (1252, 1301), False, 'import cv2\n'), ((1405, 1440), 'serial.Serial', 'serial.Serial', (['"""/dev/ttyUSB0"""', '(9600)'], {}), "('/dev/ttyUSB0', 9600)\n", (1418, 1440), False, 'import serial\n'), ((1451, 1464), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (1461, 1464), False, 'import time\n'), ((1657, 1684), 'cv2.resize', 'cv2.resize', (['img', '(340, 220)'], {}), '(img, (340, 220))\n', (1667, 1684), False, 'import cv2\n'), ((1749, 1785), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2HSV'], {}), '(img, cv2.COLOR_BGR2HSV)\n', (1761, 1785), False, 'import cv2\n'), ((1864, 1907), 'cv2.inRange', 'cv2.inRange', (['imgHSV', 'lowerBound', 'upperBound'], {}), '(imgHSV, lowerBound, upperBound)\n', (1875, 1907), False, 'import cv2\n'), ((1953, 2003), 'cv2.morphologyEx', 'cv2.morphologyEx', (['mask', 'cv2.MORPH_OPEN', 'kernelOpen'], {}), '(mask, cv2.MORPH_OPEN, kernelOpen)\n', (1969, 2003), False, 'import cv2\n'), ((2025, 2081), 'cv2.morphologyEx', 'cv2.morphologyEx', (['maskOpen', 'cv2.MORPH_CLOSE', 'kernelClose'], {}), '(maskOpen, cv2.MORPH_CLOSE, kernelClose)\n', (2041, 2081), False, 'import cv2\n'), ((2227, 2254), 'cv2.countNonZero', 'cv2.countNonZero', (['maskClose'], {}), '(maskClose)\n', (2243, 2254), False, 'import cv2\n'), ((2690, 2724), 'cv2.imshow', 'cv2.imshow', (['"""maskClose"""', 'maskClose'], {}), "('maskClose', maskClose)\n", (2700, 2724), False, 'import cv2\n'), ((2737, 2769), 'cv2.imshow', 'cv2.imshow', (['"""maskOpen"""', 'maskOpen'], {}), "('maskOpen', maskOpen)\n", (2747, 2769), False, 'import cv2\n'), ((2782, 2806), 'cv2.imshow', 'cv2.imshow', (['"""mask"""', 'mask'], {}), "('mask', mask)\n", (2792, 2806), False, 'import cv2\n'), ((2819, 2841), 'cv2.imshow', 'cv2.imshow', (['"""cam"""', 'img'], {}), "('cam', img)\n", (2829, 2841), False, 'import cv2\n'), ((2854, 2869), 'cv2.waitKey', 'cv2.waitKey', (['(10)'], {}), '(10)\n', (2865, 2869), False, 'import cv2\n'), ((2886, 2900), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (2897, 2900), False, 'import cv2\n'), ((2987, 3010), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (3008, 3010), False, 'import cv2\n'), ((2495, 2521), 'cv2.boundingRect', 'cv2.boundingRect', (['conts[i]'], {}), '(conts[i])\n', (2511, 2521), False, 'import cv2\n'), ((2539, 2597), 'cv2.rectangle', 'cv2.rectangle', (['img', '(x, y)', '(x + w, y + h)', '(0, 0, 255)', '(2)'], {}), '(img, (x, y), (x + w, y + h), (0, 0, 255), 2)\n', (2552, 2597), False, 'import cv2\n'), ((3122, 3140), 'wiringpi.digitalRead', 'wp.digitalRead', (['(21)'], {}), '(21)\n', (3136, 3140), True, 'import wiringpi as wp\n'), ((3148, 3166), 'wiringpi.digitalRead', 'wp.digitalRead', (['(22)'], {}), '(22)\n', (3162, 3166), True, 'import wiringpi as wp\n'), ((2619, 2640), 'cv2.cv.fromarray', 'cv2.cv.fromarray', (['img'], {}), '(img)\n', (2635, 2640), False, 'import cv2\n'), ((3292, 3310), 'wiringpi.digitalRead', 'wp.digitalRead', (['(21)'], {}), '(21)\n', (3306, 3310), True, 'import wiringpi as wp\n'), ((3318, 3336), 'wiringpi.digitalRead', 'wp.digitalRead', (['(22)'], {}), '(22)\n', (3332, 3336), True, 'import wiringpi as wp\n'), ((3461, 3479), 'wiringpi.digitalRead', 'wp.digitalRead', (['(21)'], {}), '(21)\n', (3475, 3479), True, 'import wiringpi as wp\n'), ((3487, 3505), 'wiringpi.digitalRead', 'wp.digitalRead', (['(22)'], {}), '(22)\n', (3501, 3505), True, 'import wiringpi as wp\n')] |
from django.db import models
from hashlib import blake2b
from django.utils import timezone
class Placement(models.Model):
placement_name = models.CharField(max_length=300)
company = models.CharField(max_length=300)
role = models.CharField(max_length=100)
description = models.TextField()
eligible_batches = models.JSONField(default=list)
eligible_branches = models.JSONField(default=list)
eligible_programmes = models.JSONField(default=list)
deadline = models.DateTimeField("deadline")
key = models.CharField(max_length=20, editable=False, default=None)
def save(self, *args, **kwargs):
if self.key is None:
timestamp = timezone.now()
Hash = blake2b(digest_size=8)
Hash.update(str(self.placement_name).encode())
Hash.update(str(timestamp).encode())
self.key = Hash.hexdigest()
super(Placement, self).save(*args, **kwargs)
def __str__(self):
return self.placement_name
| [
"django.db.models.DateTimeField",
"django.db.models.JSONField",
"django.utils.timezone.now",
"django.db.models.TextField",
"hashlib.blake2b",
"django.db.models.CharField"
] | [((145, 177), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(300)'}), '(max_length=300)\n', (161, 177), False, 'from django.db import models\n'), ((192, 224), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(300)'}), '(max_length=300)\n', (208, 224), False, 'from django.db import models\n'), ((236, 268), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)'}), '(max_length=100)\n', (252, 268), False, 'from django.db import models\n'), ((287, 305), 'django.db.models.TextField', 'models.TextField', ([], {}), '()\n', (303, 305), False, 'from django.db import models\n'), ((329, 359), 'django.db.models.JSONField', 'models.JSONField', ([], {'default': 'list'}), '(default=list)\n', (345, 359), False, 'from django.db import models\n'), ((384, 414), 'django.db.models.JSONField', 'models.JSONField', ([], {'default': 'list'}), '(default=list)\n', (400, 414), False, 'from django.db import models\n'), ((441, 471), 'django.db.models.JSONField', 'models.JSONField', ([], {'default': 'list'}), '(default=list)\n', (457, 471), False, 'from django.db import models\n'), ((487, 519), 'django.db.models.DateTimeField', 'models.DateTimeField', (['"""deadline"""'], {}), "('deadline')\n", (507, 519), False, 'from django.db import models\n'), ((530, 591), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(20)', 'editable': '(False)', 'default': 'None'}), '(max_length=20, editable=False, default=None)\n', (546, 591), False, 'from django.db import models\n'), ((683, 697), 'django.utils.timezone.now', 'timezone.now', ([], {}), '()\n', (695, 697), False, 'from django.utils import timezone\n'), ((717, 739), 'hashlib.blake2b', 'blake2b', ([], {'digest_size': '(8)'}), '(digest_size=8)\n', (724, 739), False, 'from hashlib import blake2b\n')] |
import numpy as np
def arr2dic(arr, thresh=None):
"""Keep the index and the values of an array if they are larger than the threshold.
Args:
arr (:obj:`numpy.array` of :obj:`float`): Array of numbers.
thresh (:obj:`int`): Keep values larger than the threshold.
Returns:
(:obj:`dict`): Dictionary where of the format dict({arr index, arr value})
"""
if thresh is not None:
ids = np.where(arr >= thresh)[0]
else:
ids = np.arange(len(arr))
return {id_: arr[id_] for id_ in ids}
| [
"numpy.where"
] | [((434, 457), 'numpy.where', 'np.where', (['(arr >= thresh)'], {}), '(arr >= thresh)\n', (442, 457), True, 'import numpy as np\n')] |
# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import os
import re
SIGNALS_RE = '^signals'
MUX_ROOT = '/sys/kernel/debug/omap_mux'
def use_omapmux():
"""Whether or not to utilize the Kernel OMAPMUX Controls.
If the omap mux controls exists utilize them, otherwise assume the
device-tree has been properly configured.
Returns:
True is the device-tree path exists and is not populated. False otherwise.
"""
if not os.path.exists(MUX_ROOT):
return False
for mux_file in os.listdir(MUX_ROOT):
mux_file_path = os.path.join(MUX_ROOT, mux_file)
if os.path.isfile(mux_file_path):
return True
return False
class BBmuxController(object):
"""Provides omap mux controls to interfaces that require them.
Class Variables:
_pin_name_map : Map of signal name to pin name.
_pin_mode_map : Map of signal name to the correct mode to select it.
"""
# These values are the same regardless of instance so once we have generated
# them once, share it amongst the different instances.
_pin_mode_map = {}
_pin_name_map = {}
def __init__(self):
self._logger = logging.getLogger('BBmuxController')
self._logger.debug('')
if not BBmuxController._pin_name_map:
self._init_pin_maps()
def _init_pin_maps(self):
"""Create a map pairing pins to the correct mux control file.
This function goes through each mux file in the omap_mux folder.
Each file has a signals line listing the signals this mux controls.
For example:
signals: sig1 | sig2 | sig3 | mmc2_dat6 | NA | NA | NA | gpio0_26
The end result is two maps that for a given signal name we can determine
which mux file it belongs to and what is the value to select it.
"""
# TODO (sbasi/tbroch) crbug.com/241623 - default these gpios on boot.
for mux_file in os.listdir(MUX_ROOT):
mux_file_path = os.path.join(MUX_ROOT, mux_file)
if os.path.isdir(mux_file_path):
# Skip any folders in the mux directory.
continue
with open(mux_file_path, 'r') as f:
for line in f:
# Check if this is the signals line.
if re.match(SIGNALS_RE, line):
# The line starts with 'signals:' which is not a field. So start
# counting from -1.
control_num = -1
for field in line.split():
if field is not '|':
BBmuxController._pin_mode_map[field] = control_num
BBmuxController._pin_name_map[field] = mux_file
self._logger.debug('Pin %s in in file %s with mode %s', field,
self._pin_name_map[field],
self._pin_mode_map[field])
control_num += 1
def set_muxfile(self, mux, mode_val, sel_val):
"""Allow direct access to the muxfiles.
Useful if a mux is incorrectly labelled.
Args:
mux : Mux we want to set.
mode_val : Mode we want to assign to this i/o. Should be a 3-bit hex
number.
Bit 2: 1=Input 0=Output
Bit 1: 1=Pull Up 0=Pull Down
Bit 0: 1=Pull Enabled 0=Pull Disabled.
sel_val : Signal we want to choose. Should be a 3-bit hex number.
"""
mode = mode_val * 16 + sel_val
mux = os.path.join(MUX_ROOT, mux)
with open(mux, 'w') as mux_file:
# We want to set the Pin Mux to the correct setting + mode.
self._logger.debug('Writing 0x%02x to %s', mode, mux)
mux_file.write('0x%02x' % mode)
def set_pin_mode(self, pin_name, mode_val):
"""Select/setup a pin to be used by the Beaglebone.
Args:
pin_name : Pin we want to select.
mode_val : Mode we want to assign to this i/o. Should be a 3-bit hex
number.
Bit 2: 1=Input 0=Output
Bit 1: 1=Pull Up 0=Pull Down
Bit 0: 1=Pull Enabled 0=Pull Disabled.
"""
mux_name = BBmuxController._pin_name_map[pin_name]
sel_val = BBmuxController._pin_mode_map[pin_name]
self.set_muxfile(mux_name, mode_val, sel_val)
| [
"os.path.join",
"re.match",
"os.listdir",
"logging.getLogger",
"os.path.isfile",
"os.path.exists",
"os.path.isdir"
] | [((633, 653), 'os.listdir', 'os.listdir', (['MUX_ROOT'], {}), '(MUX_ROOT)\n', (643, 653), False, 'import os\n'), ((571, 595), 'os.path.exists', 'os.path.exists', (['MUX_ROOT'], {}), '(MUX_ROOT)\n', (585, 595), False, 'import os\n'), ((675, 707), 'os.path.join', 'os.path.join', (['MUX_ROOT', 'mux_file'], {}), '(MUX_ROOT, mux_file)\n', (687, 707), False, 'import os\n'), ((715, 744), 'os.path.isfile', 'os.path.isfile', (['mux_file_path'], {}), '(mux_file_path)\n', (729, 744), False, 'import os\n'), ((1256, 1292), 'logging.getLogger', 'logging.getLogger', (['"""BBmuxController"""'], {}), "('BBmuxController')\n", (1273, 1292), False, 'import logging\n'), ((1966, 1986), 'os.listdir', 'os.listdir', (['MUX_ROOT'], {}), '(MUX_ROOT)\n', (1976, 1986), False, 'import os\n'), ((3431, 3458), 'os.path.join', 'os.path.join', (['MUX_ROOT', 'mux'], {}), '(MUX_ROOT, mux)\n', (3443, 3458), False, 'import os\n'), ((2010, 2042), 'os.path.join', 'os.path.join', (['MUX_ROOT', 'mux_file'], {}), '(MUX_ROOT, mux_file)\n', (2022, 2042), False, 'import os\n'), ((2052, 2080), 'os.path.isdir', 'os.path.isdir', (['mux_file_path'], {}), '(mux_file_path)\n', (2065, 2080), False, 'import os\n'), ((2273, 2299), 're.match', 're.match', (['SIGNALS_RE', 'line'], {}), '(SIGNALS_RE, line)\n', (2281, 2299), False, 'import re\n')] |
__all__ = ('tokenize',)
import collections
import re
from dumbc.errors import DumbValueError
from dumbc.ast import ast
Token = collections.namedtuple('Token', ('kind', 'value', 'loc'))
KEYWORDS = {
'func',
'return',
'if',
'else',
'while',
'break',
'continue',
'as',
'var'
}
# (a token kind, regex to match the token kind)
TOKENS = (
('FLOAT', r'\d*\.\d+([eE][-+]?\d+)?'),
('INTEGER', r'\d+'),
('BOOL', r'true|false'),
('STR', r'"([^"\\]*(\\.[^"\\]*)*)"|\'([^\'\\]*(\\.[^\'\\]*)*)\''),
('IDENT', r'[a-zA-Z_][a-zA-Z_0-9]*'),
('SHLEQ', r'<<='),
('SHREQ', r'>>='),
('SHL', r'<<'),
('SHR', r'>>'),
('LOGICAL_OR', r'\|\|'),
('LOGICAL_AND', r'&&'),
('LE', r'<='),
('LT', r'<'),
('GE', r'>='),
('GT', r'>'),
('EQ', r'=='),
('NE', r'!='),
('PLUSEQ', r'\+='),
('PLUS', r'\+'),
('MINUSEQ', r'\-='),
('MINUS', r'\-'),
('STAREQ', r'\*='),
('STAR', r'\*'),
('SLASHEQ', r'/='),
('SLASH', r'/'),
('PERCENTEQ', r'%='),
('PERCENT', r'%'),
('OREQ', r'\|='),
('OR', r'\|'),
('ANDEQ', r'&='),
('AND', r'&'),
('XOREQ', r'\^='),
('XOR', r'\^'),
('LOGICAL_NOT', r'!'),
('ASSIGN', r'='),
('NOT', r'~'),
('ATTR_START', r'#\['),
('LEFT_PAREN', r'\('),
('RIGHT_PAREN', r'\)'),
('LEFT_CURLY_BRACKET', r'{'),
('RIGHT_CURLY_BRACKET', r'}'),
('LEFT_SQ_BRACKET', r'\['),
('RIGHT_SQ_BRACKET', r'\]'),
('COLON', r':'),
('SEMICOLON', r';'),
('COMMA', r','),
('COMMENT', r'#.*'),
('NEWLINE', r'\n'),
('WS', r'[ \t]+')
)
def tokenize(text):
"""Tokenize input string.
Args:
text (str): String with a source code.
Yields:
Token: Piece of the text that has some assigned
meaning(a number, a keyword, etc).
Raises:
ValueError: Met some not "allowed" character.
"""
tokens_regex = '|'.join('(?P<%s>%s)' % token for token in TOKENS)
pat = re.compile(tokens_regex)
scanner = pat.scanner(text)
line = 1
line_pos = -1
pos = 0
for m in iter(scanner.match, None):
kind = m.lastgroup
if kind == 'NEWLINE':
line_pos = pos
line += 1
elif kind == 'WS' or kind == 'COMMENT':
pass
else:
value = m.group()
if kind == 'IDENT' and value in KEYWORDS:
kind = value.upper()
loc = ast.Location(line, pos - line_pos, len(value))
yield Token(kind, value, loc)
pos = m.end()
if pos != len(text):
raise DumbValueError('unexpected symbol at %d:%d' % (line, pos - line_pos))
loc = ast.Location(line, pos - line_pos, 0)
yield Token('EOF', None, loc)
| [
"dumbc.errors.DumbValueError",
"collections.namedtuple",
"dumbc.ast.ast.Location",
"re.compile"
] | [((131, 188), 'collections.namedtuple', 'collections.namedtuple', (['"""Token"""', "('kind', 'value', 'loc')"], {}), "('Token', ('kind', 'value', 'loc'))\n", (153, 188), False, 'import collections\n'), ((2010, 2034), 're.compile', 're.compile', (['tokens_regex'], {}), '(tokens_regex)\n', (2020, 2034), False, 'import re\n'), ((2709, 2746), 'dumbc.ast.ast.Location', 'ast.Location', (['line', '(pos - line_pos)', '(0)'], {}), '(line, pos - line_pos, 0)\n', (2721, 2746), False, 'from dumbc.ast import ast\n'), ((2628, 2697), 'dumbc.errors.DumbValueError', 'DumbValueError', (["('unexpected symbol at %d:%d' % (line, pos - line_pos))"], {}), "('unexpected symbol at %d:%d' % (line, pos - line_pos))\n", (2642, 2697), False, 'from dumbc.errors import DumbValueError\n')] |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2020 Fetch.AI Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ------------------------------------------------------------------------------
"""This package contains the handlers of the erc1155 deploy skill AEA."""
from typing import Optional, cast
from aea.configurations.base import ProtocolId
from aea.decision_maker.messages.transaction import TransactionMessage
from aea.helpers.search.models import Description
from aea.protocols.base import Message
from aea.protocols.default.message import DefaultMessage
from aea.protocols.default.serialization import DefaultSerializer
from aea.skills.base import Handler
from packages.fetchai.contracts.erc1155.contract import ERC1155Contract
from packages.fetchai.protocols.fipa.message import FipaMessage
from packages.fetchai.protocols.fipa.serialization import FipaSerializer
from packages.fetchai.skills.erc1155_deploy.dialogues import Dialogue, Dialogues
from packages.fetchai.skills.erc1155_deploy.strategy import Strategy
class FIPAHandler(Handler):
"""This class implements a FIPA handler."""
SUPPORTED_PROTOCOL = FipaMessage.protocol_id # type: Optional[ProtocolId]
def setup(self) -> None:
"""Implement the setup for the handler."""
pass
def handle(self, message: Message) -> None:
"""
Implement the reaction to a message.
:param message: the message
:return: None
"""
fipa_msg = cast(FipaMessage, message)
dialogue_reference = fipa_msg.dialogue_reference
dialogues = cast(Dialogues, self.context.dialogues)
if dialogues.is_belonging_to_registered_dialogue(
fipa_msg, self.context.agent_address
):
dialogue = cast(
Dialogue, dialogues.get_dialogue(fipa_msg, self.context.agent_address)
)
dialogue.incoming_extend(fipa_msg)
elif dialogues.is_permitted_for_new_dialogue(fipa_msg):
dialogue = cast(
Dialogue,
dialogues.create_opponent_initiated(
fipa_msg.counterparty, dialogue_reference, is_seller=True
),
)
dialogue.incoming_extend(fipa_msg)
else:
self._handle_unidentified_dialogue(fipa_msg)
return
if fipa_msg.performative == FipaMessage.Performative.CFP:
self._handle_cfp(fipa_msg, dialogue)
elif fipa_msg.performative == FipaMessage.Performative.ACCEPT_W_INFORM:
self._handle_accept_w_inform(fipa_msg, dialogue)
def teardown(self) -> None:
"""
Implement the handler teardown.
:return: None
"""
pass
def _handle_unidentified_dialogue(self, msg: FipaMessage) -> None:
"""
Handle an unidentified dialogue.
Respond to the sender with a default message containing the appropriate error information.
:param msg: the message
:return: None
"""
self.context.logger.info(
"[{}]: unidentified dialogue.".format(self.context.agent_name)
)
default_msg = DefaultMessage(
dialogue_reference=("", ""),
message_id=1,
target=0,
performative=DefaultMessage.Performative.ERROR,
error_code=DefaultMessage.ErrorCode.INVALID_DIALOGUE,
error_msg="Invalid dialogue.",
error_data={"fipa_message": b""},
)
self.context.outbox.put_message(
to=msg.counterparty,
sender=self.context.agent_address,
protocol_id=DefaultMessage.protocol_id,
message=DefaultSerializer().encode(default_msg),
)
def _handle_cfp(self, msg: FipaMessage, dialogue: Dialogue) -> None:
"""
Handle the CFP.
If the CFP matches the supplied services then send a PROPOSE, otherwise send a DECLINE.
:param msg: the message
:param dialogue: the dialogue object
:return: None
"""
new_message_id = msg.message_id + 1
new_target = msg.message_id
self.context.logger.info(
"[{}]: received CFP from sender={}".format(
self.context.agent_name, msg.counterparty[-5:]
)
)
if self.context.behaviours.service_registration.is_items_minted:
# simply send the same proposal, independent of the query
strategy = cast(Strategy, self.context.strategy)
contract = cast(ERC1155Contract, self.context.contracts.erc1155)
trade_nonce = contract.generate_trade_nonce(self.context.agent_address)
token_id = self.context.behaviours.service_registration.token_ids[0]
proposal = Description(
{
"contract_address": contract.instance.address,
"token_id": str(token_id),
"trade_nonce": str(trade_nonce),
"from_supply": str(strategy.from_supply),
"to_supply": str(strategy.to_supply),
"value": str(strategy.value),
}
)
dialogue.proposal = proposal
proposal_msg = FipaMessage(
message_id=new_message_id,
dialogue_reference=dialogue.dialogue_label.dialogue_reference,
target=new_target,
performative=FipaMessage.Performative.PROPOSE,
proposal=proposal,
)
dialogue.outgoing_extend(proposal_msg)
self.context.logger.info(
"[{}]: Sending PROPOSE to agent={}: proposal={}".format(
self.context.agent_name, msg.counterparty[-5:], proposal.values
)
)
self.context.outbox.put_message(
to=msg.counterparty,
sender=self.context.agent_address,
protocol_id=FipaMessage.protocol_id,
message=FipaSerializer().encode(proposal_msg),
)
else:
self.context.logger.info("Contract items not minted yet. Try again later.")
def _handle_accept_w_inform(self, msg: FipaMessage, dialogue: Dialogue) -> None:
"""
Handle the ACCEPT_W_INFORM.
If the ACCEPT_W_INFORM message contains the signed transaction, sign it too, otherwise do nothing.
:param msg: the message
:param dialogue: the dialogue object
:return: None
"""
tx_signature = msg.info.get("tx_signature", None)
if tx_signature is not None:
self.context.logger.info(
"[{}]: received ACCEPT_W_INFORM from sender={}: tx_signature={}".format(
self.context.agent_name, msg.counterparty[-5:], tx_signature
)
)
contract = cast(ERC1155Contract, self.context.contracts.erc1155)
tx = contract.get_atomic_swap_single_transaction_proposal(
from_address=self.context.agent_address,
to_address=msg.counterparty,
token_id=int(dialogue.proposal.values["token_id"]),
from_supply=int(dialogue.proposal.values["from_supply"]),
to_supply=int(dialogue.proposal.values["to_supply"]),
value=int(dialogue.proposal.values["value"]),
trade_nonce=int(dialogue.proposal.values["trade_nonce"]),
ledger_api=self.context.ledger_apis.ethereum_api,
skill_callback_id=self.context.skill_id,
signature=tx_signature,
)
self.context.logger.debug(
"[{}]: sending single atomic swap to decision maker.".format(
self.context.agent_name
)
)
self.context.decision_maker_message_queue.put(tx)
else:
self.context.logger.info(
"[{}]: received ACCEPT_W_INFORM from sender={} with no signature.".format(
self.context.agent_name, msg.counterparty[-5:]
)
)
class TransactionHandler(Handler):
"""Implement the transaction handler."""
SUPPORTED_PROTOCOL = TransactionMessage.protocol_id # type: Optional[ProtocolId]
def setup(self) -> None:
"""Implement the setup for the handler."""
pass
def handle(self, message: Message) -> None:
"""
Implement the reaction to a message.
:param message: the message
:return: None
"""
tx_msg_response = cast(TransactionMessage, message)
contract = cast(ERC1155Contract, self.context.contracts.erc1155)
if tx_msg_response.tx_id == contract.Performative.CONTRACT_DEPLOY.value:
tx_signed = tx_msg_response.signed_payload.get("tx_signed")
tx_digest = self.context.ledger_apis.ethereum_api.send_signed_transaction(
is_waiting_for_confirmation=True, tx_signed=tx_signed
)
transaction = self.context.ledger_apis.ethereum_api.get_transaction_status( # type: ignore
tx_digest=tx_digest
)
if transaction.status != 1:
self.context.is_active = False
self.context.logger.info(
"[{}]: Failed to deploy. Aborting...".format(
self.context.agent_name
)
)
else:
contract.set_address(
self.context.ledger_apis.ethereum_api, transaction.contractAddress
)
self.context.logger.info(
"[{}]: Successfully deployed the contract. Transaction digest: {}".format(
self.context.agent_name, tx_digest
)
)
elif tx_msg_response.tx_id == contract.Performative.CONTRACT_CREATE_BATCH.value:
tx_signed = tx_msg_response.signed_payload.get("tx_signed")
tx_digest = self.context.ledger_apis.ethereum_api.send_signed_transaction(
is_waiting_for_confirmation=True, tx_signed=tx_signed
)
transaction = self.context.ledger_apis.ethereum_api.get_transaction_status( # type: ignore
tx_digest=tx_digest
)
if transaction.status != 1:
self.context.is_active = False
self.context.logger.info(
"[{}]: Failed to create items. Aborting...".format(
self.context.agent_name
)
)
else:
self.context.behaviours.service_registration.is_items_created = True
self.context.logger.info(
"[{}]: Successfully created items. Transaction digest: {}".format(
self.context.agent_name, tx_digest
)
)
elif tx_msg_response.tx_id == contract.Performative.CONTRACT_MINT_BATCH.value:
tx_signed = tx_msg_response.signed_payload.get("tx_signed")
tx_digest = self.context.ledger_apis.ethereum_api.send_signed_transaction(
is_waiting_for_confirmation=True, tx_signed=tx_signed
)
transaction = self.context.ledger_apis.ethereum_api.get_transaction_status( # type: ignore
tx_digest=tx_digest
)
if transaction.status != 1:
self.context.is_active = False
self.context.logger.info(
"[{}]: Failed to mint items. Aborting...".format(
self.context.agent_name
)
)
else:
self.context.behaviours.service_registration.is_items_minted = True
self.context.logger.info(
"[{}]: Successfully minted items. Transaction digest: {}".format(
self.context.agent_name, tx_digest
)
)
result = contract.get_balance_of_batch(
address=self.context.agent_address,
token_ids=self.context.behaviours.service_registration.token_ids,
)
self.context.logger.info(
"[{}]: Current balances: {}".format(self.context.agent_name, result)
)
elif (
tx_msg_response.tx_id
== contract.Performative.CONTRACT_ATOMIC_SWAP_SINGLE.value
):
tx_signed = tx_msg_response.signed_payload.get("tx_signed")
tx_digest = self.context.ledger_apis.ethereum_api.send_signed_transaction(
is_waiting_for_confirmation=True, tx_signed=tx_signed
)
transaction = self.context.ledger_apis.ethereum_api.get_transaction_status( # type: ignore
tx_digest=tx_digest
)
if transaction.status != 1:
self.context.is_active = False
self.context.logger.info(
"[{}]: Failed to conduct atomic swap. Aborting...".format(
self.context.agent_name
)
)
else:
self.context.logger.info(
"[{}]: Successfully conducted atomic swap. Transaction digest: {}".format(
self.context.agent_name, tx_digest
)
)
result = contract.get_balance_of_batch(
address=self.context.agent_address,
token_ids=self.context.behaviours.service_registration.token_ids,
)
self.context.logger.info(
"[{}]: Current balances: {}".format(self.context.agent_name, result)
)
def teardown(self) -> None:
"""
Implement the handler teardown.
:return: None
"""
pass
| [
"packages.fetchai.protocols.fipa.message.FipaMessage",
"packages.fetchai.protocols.fipa.serialization.FipaSerializer",
"aea.protocols.default.serialization.DefaultSerializer",
"aea.protocols.default.message.DefaultMessage",
"typing.cast"
] | [((2080, 2106), 'typing.cast', 'cast', (['FipaMessage', 'message'], {}), '(FipaMessage, message)\n', (2084, 2106), False, 'from typing import Optional, cast\n'), ((2185, 2224), 'typing.cast', 'cast', (['Dialogues', 'self.context.dialogues'], {}), '(Dialogues, self.context.dialogues)\n', (2189, 2224), False, 'from typing import Optional, cast\n'), ((3763, 4011), 'aea.protocols.default.message.DefaultMessage', 'DefaultMessage', ([], {'dialogue_reference': "('', '')", 'message_id': '(1)', 'target': '(0)', 'performative': 'DefaultMessage.Performative.ERROR', 'error_code': 'DefaultMessage.ErrorCode.INVALID_DIALOGUE', 'error_msg': '"""Invalid dialogue."""', 'error_data': "{'fipa_message': b''}"}), "(dialogue_reference=('', ''), message_id=1, target=0,\n performative=DefaultMessage.Performative.ERROR, error_code=\n DefaultMessage.ErrorCode.INVALID_DIALOGUE, error_msg=\n 'Invalid dialogue.', error_data={'fipa_message': b''})\n", (3777, 4011), False, 'from aea.protocols.default.message import DefaultMessage\n'), ((9202, 9235), 'typing.cast', 'cast', (['TransactionMessage', 'message'], {}), '(TransactionMessage, message)\n', (9206, 9235), False, 'from typing import Optional, cast\n'), ((9255, 9308), 'typing.cast', 'cast', (['ERC1155Contract', 'self.context.contracts.erc1155'], {}), '(ERC1155Contract, self.context.contracts.erc1155)\n', (9259, 9308), False, 'from typing import Optional, cast\n'), ((5079, 5116), 'typing.cast', 'cast', (['Strategy', 'self.context.strategy'], {}), '(Strategy, self.context.strategy)\n', (5083, 5116), False, 'from typing import Optional, cast\n'), ((5140, 5193), 'typing.cast', 'cast', (['ERC1155Contract', 'self.context.contracts.erc1155'], {}), '(ERC1155Contract, self.context.contracts.erc1155)\n', (5144, 5193), False, 'from typing import Optional, cast\n'), ((5850, 6046), 'packages.fetchai.protocols.fipa.message.FipaMessage', 'FipaMessage', ([], {'message_id': 'new_message_id', 'dialogue_reference': 'dialogue.dialogue_label.dialogue_reference', 'target': 'new_target', 'performative': 'FipaMessage.Performative.PROPOSE', 'proposal': 'proposal'}), '(message_id=new_message_id, dialogue_reference=dialogue.\n dialogue_label.dialogue_reference, target=new_target, performative=\n FipaMessage.Performative.PROPOSE, proposal=proposal)\n', (5861, 6046), False, 'from packages.fetchai.protocols.fipa.message import FipaMessage\n'), ((7487, 7540), 'typing.cast', 'cast', (['ERC1155Contract', 'self.context.contracts.erc1155'], {}), '(ERC1155Contract, self.context.contracts.erc1155)\n', (7491, 7540), False, 'from typing import Optional, cast\n'), ((4286, 4305), 'aea.protocols.default.serialization.DefaultSerializer', 'DefaultSerializer', ([], {}), '()\n', (4303, 4305), False, 'from aea.protocols.default.serialization import DefaultSerializer\n'), ((6620, 6636), 'packages.fetchai.protocols.fipa.serialization.FipaSerializer', 'FipaSerializer', ([], {}), '()\n', (6634, 6636), False, 'from packages.fetchai.protocols.fipa.serialization import FipaSerializer\n')] |
"""
Contributed by blha303
API key can be retrieved from the android app with Root Browser
(/data/data/au.gov.wa.pta.transperth/com.jeppesen.transperth.xml)
Please don't abuse this service, you'll ruin it for the rest of us.
"""
from lxml.etree import fromstring
import datetime
import dateutil.parser
import logging
import requests
from . import BASE
from .utils import prepare_url
logging.basicConfig(level=logging.DEBUG)
class RateLimitExceeded(Exception):
pass
def timetable_for_stop(
stop_num: int, time: datetime.datetime,
apikey: str,
dataset='PerthRestricted'):
"""
Produces a list of 2 long tuples; (<bus_num>, <time>)
"""
url = BASE + "/rest/Datasets/:dataset/StopTimetable"
url = prepare_url(url, {'dataset': dataset})
req = requests.get(
url,
params={
"stop": stop_num,
"time": time.strftime('%Y-%m-%dT%H:%M'),
"ApiKey": apikey,
"timeband": "1440"
}
)
xml = req.text
xml = xml.replace('xmlns="http://www.jeppesen.com/journeyplanner" ', "")
xml = fromstring(xml)
status = xml.xpath('Status')[0]
severity = status.xpath("Severity/text()")[0]
if severity != "Success":
code = status.xpath("Details/StatusDetail/Code/text()")[0]
if code == "APIKeyDailyLimitExceeded":
raise RateLimitExceeded()
raise Exception("{} fetching {}".format(
severity,
stop_num
))
return _parse_timetable_response(xml)
def _parse_timetable_response(xml):
return [
(
b.xpath("Summary/RouteCode/text()")[0],
dateutil.parser.parse(b.xpath("DepartTime/text()")[0])
)
for b in xml.xpath('Trips/StopTimetableTrip')
]
| [
"logging.basicConfig",
"lxml.etree.fromstring"
] | [((388, 428), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG'}), '(level=logging.DEBUG)\n', (407, 428), False, 'import logging\n'), ((1110, 1125), 'lxml.etree.fromstring', 'fromstring', (['xml'], {}), '(xml)\n', (1120, 1125), False, 'from lxml.etree import fromstring\n')] |
import json
import os
from pathlib import Path
from typing import List, NewType, Optional, Tuple, Union
from starkware.starknet.services.api.contract_definition import ContractDefinition
from starkware.cairo.lang.compiler.constants import MAIN_SCOPE, LIBS_DIR_ENVVAR
from starkware.cairo.lang.cairo_constants import DEFAULT_PRIME
from starkware.cairo.lang.compiler.cairo_compile import (
get_module_reader,
)
from starkware.cairo.lang.compiler.preprocessor.preprocess_codes import preprocess_codes
from starkware.starknet.compiler.compile import assemble_starknet_contract
from starkware.starknet.compiler.starknet_pass_manager import starknet_pass_manager
CairoSourceCode = NewType("CairoSourceCode", str)
CairoFilename = NewType("CairoFilename", str)
StarknetCompilationSource = NewType(
"CairoSource", Union[CairoSourceCode, List[CairoFilename]]
)
class Compiler:
"""
Class for compiling Cairo contracts
"""
def __init__(
self,
contract_source: List[StarknetCompilationSource],
cairo_path: Optional[List[str]] = None,
):
"""
Initializes compiler.
:param contract_source: a list of source files paths
:param cairo_path: a ``list`` of paths used by starknet_compile to resolve dependencies within contracts
"""
self.contract_source = contract_source
self.search_paths = cairo_path
def compile_contract(self) -> str:
"""
Compiles a contract and returns it as string
:return: string of compiled contract
"""
return starknet_compile(self.contract_source, search_paths=self.search_paths)
def create_contract_definition(
compiled_contract: str,
) -> ContractDefinition:
"""
Creates ContractDefinition either from already compiled contract
:return: a ContractDefinition
"""
return ContractDefinition.loads(compiled_contract)
def load_cairo_source_code(filename: CairoFilename) -> str:
source_file = Path(filename)
if not source_file.is_file():
raise ValueError(f"{filename} does not exist")
if source_file.suffix != ".cairo":
raise ValueError(f"{filename} is not a cairo source file")
return Path(filename).read_text("utf-8")
def load_source_code(
src: List[StarknetCompilationSource],
) -> List[Tuple[str, str]]:
if isinstance(src, str):
return [(src, str(hash(src)))]
return [(load_cairo_source_code(filename), filename) for filename in src]
def starknet_compile(
source: List[StarknetCompilationSource],
search_paths: Optional[List[str]] = None,
):
file_contents_for_debug_info = {}
cairo_path: List[str] = list(
filter(None, os.getenv(LIBS_DIR_ENVVAR, "").split(":"))
)
if search_paths is not None:
cairo_path += search_paths
module_reader = get_module_reader(cairo_path=cairo_path)
pass_manager = starknet_pass_manager(
prime=DEFAULT_PRIME,
read_module=module_reader.read,
disable_hint_validation=True,
)
preprocessed = preprocess_codes(
codes=load_source_code(source),
pass_manager=pass_manager,
main_scope=MAIN_SCOPE,
)
assembled_program = assemble_starknet_contract(
preprocessed,
main_scope=MAIN_SCOPE,
add_debug_info=False,
file_contents_for_debug_info=file_contents_for_debug_info,
)
return json.dumps(
assembled_program.Schema().dump(assembled_program),
indent=4,
sort_keys=True,
)
| [
"starkware.starknet.services.api.contract_definition.ContractDefinition.loads",
"starkware.starknet.compiler.compile.assemble_starknet_contract",
"pathlib.Path",
"starkware.cairo.lang.compiler.cairo_compile.get_module_reader",
"os.getenv",
"starkware.starknet.compiler.starknet_pass_manager.starknet_pass_m... | [((681, 712), 'typing.NewType', 'NewType', (['"""CairoSourceCode"""', 'str'], {}), "('CairoSourceCode', str)\n", (688, 712), False, 'from typing import List, NewType, Optional, Tuple, Union\n'), ((729, 758), 'typing.NewType', 'NewType', (['"""CairoFilename"""', 'str'], {}), "('CairoFilename', str)\n", (736, 758), False, 'from typing import List, NewType, Optional, Tuple, Union\n'), ((787, 854), 'typing.NewType', 'NewType', (['"""CairoSource"""', 'Union[CairoSourceCode, List[CairoFilename]]'], {}), "('CairoSource', Union[CairoSourceCode, List[CairoFilename]])\n", (794, 854), False, 'from typing import List, NewType, Optional, Tuple, Union\n'), ((1863, 1906), 'starkware.starknet.services.api.contract_definition.ContractDefinition.loads', 'ContractDefinition.loads', (['compiled_contract'], {}), '(compiled_contract)\n', (1887, 1906), False, 'from starkware.starknet.services.api.contract_definition import ContractDefinition\n'), ((1987, 2001), 'pathlib.Path', 'Path', (['filename'], {}), '(filename)\n', (1991, 2001), False, 'from pathlib import Path\n'), ((2836, 2876), 'starkware.cairo.lang.compiler.cairo_compile.get_module_reader', 'get_module_reader', ([], {'cairo_path': 'cairo_path'}), '(cairo_path=cairo_path)\n', (2853, 2876), False, 'from starkware.cairo.lang.compiler.cairo_compile import get_module_reader\n'), ((2897, 3005), 'starkware.starknet.compiler.starknet_pass_manager.starknet_pass_manager', 'starknet_pass_manager', ([], {'prime': 'DEFAULT_PRIME', 'read_module': 'module_reader.read', 'disable_hint_validation': '(True)'}), '(prime=DEFAULT_PRIME, read_module=module_reader.read,\n disable_hint_validation=True)\n', (2918, 3005), False, 'from starkware.starknet.compiler.starknet_pass_manager import starknet_pass_manager\n'), ((3208, 3361), 'starkware.starknet.compiler.compile.assemble_starknet_contract', 'assemble_starknet_contract', (['preprocessed'], {'main_scope': 'MAIN_SCOPE', 'add_debug_info': '(False)', 'file_contents_for_debug_info': 'file_contents_for_debug_info'}), '(preprocessed, main_scope=MAIN_SCOPE,\n add_debug_info=False, file_contents_for_debug_info=\n file_contents_for_debug_info)\n', (3234, 3361), False, 'from starkware.starknet.compiler.compile import assemble_starknet_contract\n'), ((2211, 2225), 'pathlib.Path', 'Path', (['filename'], {}), '(filename)\n', (2215, 2225), False, 'from pathlib import Path\n'), ((2697, 2727), 'os.getenv', 'os.getenv', (['LIBS_DIR_ENVVAR', '""""""'], {}), "(LIBS_DIR_ENVVAR, '')\n", (2706, 2727), False, 'import os\n')] |
import torch
import torch.optim as optim
import torch.nn as nn
from torch.autograd import Variable
from torch.utils.data import DataLoader
from neurotorch.datasets.dataset import AlignedVolume, TorchVolume
import torch.cuda
import numpy as np
class Trainer(object):
"""
Trains a PyTorch neural network with a given input and label dataset
"""
def __init__(self, net, aligned_volume, checkpoint=None,
optimizer=None, criterion=None, max_epochs=10,
gpu_device=None, validation_split=0.2):
"""
Sets up the parameters for training
:param net: A PyTorch neural network
:param inputs_volume: A PyTorch dataset containing inputs
:param labels_volume: A PyTorch dataset containing corresponding labels
"""
self.max_epochs = max_epochs
self.device = torch.device("cuda:{}".format(gpu_device)
if gpu_device is not None
else "cpu")
self.net = net.to(self.device)
if checkpoint is not None:
self.net.load_state_dict(torch.load(checkpoint))
if optimizer is None:
self.optimizer = optim.Adam(self.net.parameters())
else:
self.optimizer = optimizer(self.net.parameters())
if criterion is None:
self.criterion = nn.BCEWithLogitsLoss()
else:
self.criterion = criterion
if gpu_device is not None:
self.gpu_device = gpu_device
self.useGpu = True
self.volume = TorchVolume(aligned_volume)
def run_epoch(self, sample_batch):
"""
Runs an epoch with a given batch of samples
:param sample_batch: A dictionary containing inputs and labels with the keys
"input" and "label", respectively
"""
inputs = Variable(sample_batch[0]).float()
labels = Variable(sample_batch[1]).float()
inputs, labels = inputs.to(self.device), labels.to(self.device)
self.optimizer.zero_grad()
outputs = self.net(inputs)
loss = self.criterion(torch.cat(outputs), labels)
loss_hist = loss.cpu().item()
loss.backward()
self.optimizer.step()
return loss_hist
def evaluate(self, batch):
with torch.no_grad():
inputs = Variable(batch[0]).float()
labels = Variable(batch[1]).float()
inputs, labels = inputs.to(self.device), labels.to(self.device)
outputs = self.net(inputs)
loss = self.criterion(torch.cat(outputs), labels)
accuracy = torch.sum((torch.cat(outputs) > 0) & labels.byte()).float()
accuracy /= torch.sum((torch.cat(outputs) > 0) | labels.byte()).float()
return loss.cpu().item(), accuracy.cpu().item(), torch.stack(outputs).cpu().numpy()
def run_training(self):
"""
Trains the given neural network
"""
num_epoch = 1
num_iter = 1
validation_split = 0.2
valid_indexes = self.getTrainer().volume.getValidData()
random_idx = np.random.permutation(valid_indexes)
train_idx = random_idx[:int(len(valid_indexes)*(1-validation_split))].copy()
val_idx = random_idx[int(len(valid_indexes)*validation_split):].copy()
train_idx = train_idx[:(len(train_idx) - len(train_idx) % 16)]
train_idx = train_idx.reshape((-1, 16))
while num_epoch <= self.getTrainer().max_epochs:
np.random.shuffle(train_idx)
for i in range(train_idx.shape[0]):
sample_batch = list(zip(*[self.getTrainer().volume[idx] for idx in train_idx[i]]))
sample_batch = [np.stack(batch) for batch in sample_batch]
sample_batch[1] = sample_batch[1] > 0
if num_epoch > self.getTrainer().max_epochs:
break
if (sample_batch[1] == 0).all():
continue
print("Iteration: {}".format(num_iter))
self.run_epoch([torch.from_numpy(batch) for batch in sample_batch])
if num_iter % 10 == 0:
val_batch = list(zip(*[self.getTrainer().volume[idx]
for idx in val_idx[:1]]))
val_batch = [np.stack(batch) for batch in val_batch]
val_batch[1] = val_batch[1] > 0
loss, accuracy, _ = self.evaluate([torch.from_numpy(batch) for batch in val_batch])
print("Iteration: {}".format(num_iter),
"Epoch {}/{} ".format(num_epoch,
self.getTrainer().max_epochs),
"Loss: {:.4f}".format(loss),
"Accuracy: {:.2f}".format(accuracy*100))
num_iter += 1
num_epoch += 1
class TrainerDecorator(Trainer):
"""
A wrapper class to a features for training
"""
def __init__(self, trainer):
self.setTrainer(trainer)
def setTrainer(self, trainer):
self._trainer = trainer
def getTrainer(self):
if isinstance(self._trainer, TrainerDecorator) or issubclass(type(self._trainer), TrainerDecorator):
return self._trainer.getTrainer()
if isinstance(self._trainer, Trainer):
return self._trainer
def run_epoch(self, sample_batch):
return self._trainer.run_epoch(sample_batch)
def evaluate(self, batch):
return self._trainer.evaluate(batch)
def run_training(self):
"""
Trains the given neural network
"""
num_epoch = 1
num_iter = 1
validation_split = 0.2
valid_indexes = self.getTrainer().volume.getVolume().getValidData()
random_idx = np.random.permutation(valid_indexes)
train_idx = random_idx[:int(len(valid_indexes)*(1-validation_split))].copy()
val_idx = random_idx[int(len(valid_indexes)*validation_split):].copy()
train_idx = train_idx[:(len(train_idx) - len(train_idx) % 8)]
train_idx = train_idx.reshape((-1, 8))
while num_epoch <= self.getTrainer().max_epochs:
np.random.shuffle(train_idx)
for i in range(train_idx.shape[0]):
sample_batch = list(zip(*[self.getTrainer().volume[idx] for idx in train_idx[i]]))
sample_batch = [np.stack(batch) for batch in sample_batch]
sample_batch[1] = sample_batch[1] > 0
if num_epoch > self.getTrainer().max_epochs:
break
print("Iteration: {}".format(num_iter))
self.run_epoch([torch.from_numpy(batch.astype(np.float)) for batch in sample_batch])
if num_iter % 10 == 0:
self.getTrainer().volume.getVolume().setAugmentation(False)
val_batch = list(zip(*[self.getTrainer().volume[idx]
for idx in val_idx[:16]]))
val_batch = [np.stack(batch) for batch in val_batch]
val_batch[1] = val_batch[1] > 0
loss, accuracy, _ = self.evaluate([torch.from_numpy(batch.astype(np.float)) for batch in val_batch])
print("Iteration: {}".format(num_iter),
"Epoch {}/{} ".format(num_epoch,
self.getTrainer().max_epochs),
"Loss: {:.4f}".format(loss),
"Accuracy: {:.2f}".format(accuracy*100))
self.getTrainer().volume.getVolume().setAugmentation(True)
num_iter += 1
num_epoch += 1
| [
"torch.load",
"neurotorch.datasets.dataset.TorchVolume",
"torch.nn.BCEWithLogitsLoss",
"numpy.random.shuffle",
"torch.autograd.Variable",
"numpy.random.permutation",
"torch.from_numpy",
"torch.no_grad",
"torch.stack",
"numpy.stack",
"torch.cat"
] | [((1583, 1610), 'neurotorch.datasets.dataset.TorchVolume', 'TorchVolume', (['aligned_volume'], {}), '(aligned_volume)\n', (1594, 1610), False, 'from neurotorch.datasets.dataset import AlignedVolume, TorchVolume\n'), ((3123, 3159), 'numpy.random.permutation', 'np.random.permutation', (['valid_indexes'], {}), '(valid_indexes)\n', (3144, 3159), True, 'import numpy as np\n'), ((5845, 5881), 'numpy.random.permutation', 'np.random.permutation', (['valid_indexes'], {}), '(valid_indexes)\n', (5866, 5881), True, 'import numpy as np\n'), ((1376, 1398), 'torch.nn.BCEWithLogitsLoss', 'nn.BCEWithLogitsLoss', ([], {}), '()\n', (1396, 1398), True, 'import torch.nn as nn\n'), ((2126, 2144), 'torch.cat', 'torch.cat', (['outputs'], {}), '(outputs)\n', (2135, 2144), False, 'import torch\n'), ((2317, 2332), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2330, 2332), False, 'import torch\n'), ((3514, 3542), 'numpy.random.shuffle', 'np.random.shuffle', (['train_idx'], {}), '(train_idx)\n', (3531, 3542), True, 'import numpy as np\n'), ((6234, 6262), 'numpy.random.shuffle', 'np.random.shuffle', (['train_idx'], {}), '(train_idx)\n', (6251, 6262), True, 'import numpy as np\n'), ((1122, 1144), 'torch.load', 'torch.load', (['checkpoint'], {}), '(checkpoint)\n', (1132, 1144), False, 'import torch\n'), ((1865, 1890), 'torch.autograd.Variable', 'Variable', (['sample_batch[0]'], {}), '(sample_batch[0])\n', (1873, 1890), False, 'from torch.autograd import Variable\n'), ((1916, 1941), 'torch.autograd.Variable', 'Variable', (['sample_batch[1]'], {}), '(sample_batch[1])\n', (1924, 1941), False, 'from torch.autograd import Variable\n'), ((2582, 2600), 'torch.cat', 'torch.cat', (['outputs'], {}), '(outputs)\n', (2591, 2600), False, 'import torch\n'), ((2355, 2373), 'torch.autograd.Variable', 'Variable', (['batch[0]'], {}), '(batch[0])\n', (2363, 2373), False, 'from torch.autograd import Variable\n'), ((2403, 2421), 'torch.autograd.Variable', 'Variable', (['batch[1]'], {}), '(batch[1])\n', (2411, 2421), False, 'from torch.autograd import Variable\n'), ((3722, 3737), 'numpy.stack', 'np.stack', (['batch'], {}), '(batch)\n', (3730, 3737), True, 'import numpy as np\n'), ((6442, 6457), 'numpy.stack', 'np.stack', (['batch'], {}), '(batch)\n', (6450, 6457), True, 'import numpy as np\n'), ((4073, 4096), 'torch.from_numpy', 'torch.from_numpy', (['batch'], {}), '(batch)\n', (4089, 4096), False, 'import torch\n'), ((4340, 4355), 'numpy.stack', 'np.stack', (['batch'], {}), '(batch)\n', (4348, 4355), True, 'import numpy as np\n'), ((7080, 7095), 'numpy.stack', 'np.stack', (['batch'], {}), '(batch)\n', (7088, 7095), True, 'import numpy as np\n'), ((2835, 2855), 'torch.stack', 'torch.stack', (['outputs'], {}), '(outputs)\n', (2846, 2855), False, 'import torch\n'), ((4488, 4511), 'torch.from_numpy', 'torch.from_numpy', (['batch'], {}), '(batch)\n', (4504, 4511), False, 'import torch\n'), ((2644, 2662), 'torch.cat', 'torch.cat', (['outputs'], {}), '(outputs)\n', (2653, 2662), False, 'import torch\n'), ((2728, 2746), 'torch.cat', 'torch.cat', (['outputs'], {}), '(outputs)\n', (2737, 2746), False, 'import torch\n')] |
#<NAME>
#Weekly task 8
#A program that displays a plot of the functions
#f(x)=x, g(x)=x2 and h(x)=x3 in the range [0, 4] on the one set of axes.
#Type ipython into command line.
#Type %logstart to activate auto-logging.
#When working with plots, import numpy
#numpy provides a data structure when working with numberical data
import numpy as np
#matplotlib.pyplot helps us create plots when working with numberical data
import matplotlib.pyplot as plt
#.arange() can take 1, 2, or 3 numbers as input and will provide you with lists based on the numbers
#that you have input as arguments
#note: python's range() command will only give you integers, numpy's arange() command will give you float
#range [0, 4] on the one set of axes.
x = np.arange(0.0,5.0,1.0)
#display the numpy array
x
#g(x)= x2
g1 = x ** 2
#display g1
g1
#h(x)=x3
h1 = x ** 3
#display h
h1
#plot x in green line
plt.plot(x, x, 'g', label="x")
#plot x2 in blue line
plt.plot(x, g1, 'b', label="x2")
#plot x3 in yellow line
plt.plot(x, h1, 'y', label="x3")
#add a legend to plot
plt.legend()
#add title
plt.title('f(x)=x, g(x)=x2 and h(x)=x3 in the range [0, 4] ', fontsize=18)
#show the plot
plt.show()
# References;
# Moodle Course video on plots which is very good and gave a solid understanding of how to start creating plots
# https://numpy.org/
# https://matplotlib.org/api/pyplot_summary.html
# https://realpython.com/python-matplotlib-guide/
| [
"matplotlib.pyplot.show",
"matplotlib.pyplot.title",
"matplotlib.pyplot.legend",
"numpy.arange",
"matplotlib.pyplot.plot"
] | [((763, 787), 'numpy.arange', 'np.arange', (['(0.0)', '(5.0)', '(1.0)'], {}), '(0.0, 5.0, 1.0)\n', (772, 787), True, 'import numpy as np\n'), ((931, 961), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'x', '"""g"""'], {'label': '"""x"""'}), "(x, x, 'g', label='x')\n", (939, 961), True, 'import matplotlib.pyplot as plt\n'), ((989, 1021), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'g1', '"""b"""'], {'label': '"""x2"""'}), "(x, g1, 'b', label='x2')\n", (997, 1021), True, 'import matplotlib.pyplot as plt\n'), ((1050, 1082), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'h1', '"""y"""'], {'label': '"""x3"""'}), "(x, h1, 'y', label='x3')\n", (1058, 1082), True, 'import matplotlib.pyplot as plt\n'), ((1109, 1121), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (1119, 1121), True, 'import matplotlib.pyplot as plt\n'), ((1137, 1211), 'matplotlib.pyplot.title', 'plt.title', (['"""f(x)=x, g(x)=x2 and h(x)=x3 in the range [0, 4] """'], {'fontsize': '(18)'}), "('f(x)=x, g(x)=x2 and h(x)=x3 in the range [0, 4] ', fontsize=18)\n", (1146, 1211), True, 'import matplotlib.pyplot as plt\n'), ((1231, 1241), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1239, 1241), True, 'import matplotlib.pyplot as plt\n')] |
import logging
from Config import *
from DiscordClient import DiscordClient
logger = logging.getLogger('discord')
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)
client = DiscordClient()
client.run(DIDCODE_TOKEN) | [
"DiscordClient.DiscordClient",
"logging.getLogger",
"logging.FileHandler",
"logging.Formatter"
] | [((90, 118), 'logging.getLogger', 'logging.getLogger', (['"""discord"""'], {}), "('discord')\n", (107, 118), False, 'import logging\n'), ((162, 233), 'logging.FileHandler', 'logging.FileHandler', ([], {'filename': '"""discord.log"""', 'encoding': '"""utf-8"""', 'mode': '"""w"""'}), "(filename='discord.log', encoding='utf-8', mode='w')\n", (181, 233), False, 'import logging\n'), ((366, 381), 'DiscordClient.DiscordClient', 'DiscordClient', ([], {}), '()\n', (379, 381), False, 'from DiscordClient import DiscordClient\n'), ((256, 324), 'logging.Formatter', 'logging.Formatter', (['"""%(asctime)s:%(levelname)s:%(name)s: %(message)s"""'], {}), "('%(asctime)s:%(levelname)s:%(name)s: %(message)s')\n", (273, 324), False, 'import logging\n')] |
import os
import shutil
from glob import glob
from logging import getLogger
from os.path import join, basename, isdir, isfile
from typing import Dict, List
import dirsync
from deepmerge.exception import InvalidMerge
from deprecated.classic import deprecated
from orjson import JSONDecodeError
from pydantic import ValidationError
from sqlalchemy.exc import DatabaseError, StatementError
from app import settings
from app.models.orm import RegisteredActor, Domain
from app.models.schema.domain_models import DomainLang, DomainBase
from app.services import schemas
from app.services.schemas import domain_data_schema_file
from app.services.service_worker import ServiceWorker
from app.settings import env_settings, INIT_DOMAINS_FOLDER
from app.setup.init_data.init_entries import init_entries
from app.setup.init_data.plugin_import import init_plugin_import
from app.util.consts import NO_DOMAIN, NAME, DEFAULT_LANGUAGE, LANGUAGE, TITLE, CONTENT
from app.util.dict_rearrange import deep_merge, check_model_active
from app.util.files import read_orjson, JSONPath
from app.util.language import get_language_code_from_domain_path
logger = getLogger(__name__)
def get_domain_folder(domain_name: str):
return join(INIT_DOMAINS_FOLDER, domain_name)
def get_domain_lang_folder(domain_name: str, language: str):
return join(INIT_DOMAINS_FOLDER, domain_name, language)
def get_domain_lang_type_folder(domain_name, language, type_name: str):
return join(INIT_DOMAINS_FOLDER, domain_name, language, type_name)
def init_domains(sw: ServiceWorker, actor: RegisteredActor):
"""
loads all init-data from all domains specified in the settings: LOAD_DOMAINS or
(if empty) given in the INIT_DOMAINS_FOLDER folder
@param sw: service
@param actor: the actor assigned as creator (normally admin)
"""
logger.debug("*** Domains")
# todo should also be used to kick out domains again
domain_folders = glob(INIT_DOMAINS_FOLDER + "/*")
domain_folders = list(filter(lambda f: os.path.isdir(f), domain_folders))
domains_to_load = [basename(d) for d in domain_folders]
domains_to_load = list(
filter(lambda name: not name.startswith("_"), domains_to_load)
)
if not domain_folders:
logger.error(
f"No domain folders found in {INIT_DOMAINS_FOLDER}. You need to include at least 'no_domain"
)
return
# load no_domain first for codes, templates...
if NO_DOMAIN in domains_to_load:
domains_to_load.remove(NO_DOMAIN)
domains_to_load = [NO_DOMAIN] + domains_to_load
logger.info(f"domains to load:{domains_to_load}")
for domain_name in domains_to_load:
init_domain(domain_name, sw, actor)
def init_domain(domain_name: str, sw: ServiceWorker, actor: RegisteredActor):
"""
Initialize one domain: domain-meta, domain (in languages) and its entries
@param domain_name: name of the domain (looking for data in the corresponding folder)
@param sw: service
@param actor: actor as creator for all the entries
"""
logger.debug(f"Domain: {domain_name}")
domain_base_folder = join(INIT_DOMAINS_FOLDER, domain_name)
update_domain_images(domain_name)
init_plugin_import(domain_name)
update_domain_js_plugin(domain_name)
# read, validate and insert domainmeta
domain_base_file_path = join(domain_base_folder, "domain.json")
try:
meta_file = JSONPath(domain_base_file_path)
meta_data = meta_file.read_insert(
insert={NAME: domain_name},
setdefault={DEFAULT_LANGUAGE: env_settings().DEFAULT_LANGUAGE},
)
meta_model = DomainBase.parse_obj(meta_data)
meta_object = sw.domain.insert_or_update_meta(meta_model)
except (FileNotFoundError, ValueError, JSONDecodeError, ValidationError) as err:
logger.error(err)
logger.error(f"Skipping domain: {domain_name}")
return
# return if not active
if not meta_object.is_active:
logger.info(f"Domain {domain_name} is not active. Not loading language files")
return
# get all language files...
lang_domain_files = [
JSONPath(_) for _ in glob(domain_base_folder + "/lang/*/domain.json")
]
if len(lang_domain_files) == 0:
logger.warning(f"Domain in no language: {domain_name}")
# put the language file which has the language defined as default_language first
# this will be set to active and all other need to include (at least) those
# text fields (text, label, description, ...)
# in their aspects & items...
default_lang_file_found = False
for (index, f) in enumerate(lang_domain_files):
if f.parent.name == meta_model.default_language:
lang_domain_files[0], lang_domain_files[index] = (
lang_domain_files[index],
lang_domain_files[0],
)
default_lang_file_found = True
break
if not default_lang_file_found:
logger.error(
f"No domain language file found for the domain: {meta_model.name}. Not doing anything with this domain"
)
return
default_language_domain_model = None
# read, validate, merge (with meta) and insert domain-lang objects
for lang_domain_file in lang_domain_files:
language = basename(lang_domain_file.parent)
l_msg_name = f"{domain_name}/{language}"
logger.debug(f"Domain ({l_msg_name})")
try:
domain_lang_data = lang_domain_file.read_insert(
insert={"language": language}
)
domain_lang_model = DomainLang.parse_obj(domain_lang_data)
domain_lang_model.content = deep_merge(
domain_lang_model.content.dict(exclude_none=True),
meta_model.content.dict(exclude_none=True),
True,
)
if language == meta_model.default_language:
domain_lang_model.is_active = True
default_language_domain_model = domain_lang_model
else:
title = domain_lang_model.title
lang = domain_lang_model.language
domain_lang_model.is_active = check_model_active(
default_language_domain_model,
domain_lang_model,
{"title", "content"},
f"{title}/{lang}",
False,
True,
)
sw.domain.insert_or_update_domain(domain_lang_model, meta_object)
if not sw.messages.has_language(language):
sw.messages.add_language(language)
except (
FileNotFoundError,
ValueError,
JSONDecodeError,
ValidationError,
InvalidMerge,
) as err:
logger.exception(err)
logger.error(f"Skipping domain: {l_msg_name}")
if language == meta_model.default_language:
logger.error(f"Skipping all other languages...")
break
# update database objects that have no files
dlang_objects: List[Domain] = meta_object.language_domain_data
lang_file_languages = [basename(file.parent) for file in lang_domain_files]
for db_obj in dlang_objects:
if db_obj.language not in lang_file_languages:
ident = f"{domain_name}: {db_obj.language}"
logger.info(f"Updating database domain object: {ident}")
try:
domain_lang_model = DomainLang.parse_obj(
{**DomainLang.from_orm(db_obj).dict(), LANGUAGE: db_obj.language}
)
domain_lang_model.content = deep_merge(
domain_lang_model.content.dict(exclude_none=True),
meta_model.content.dict(exclude_none=True),
True,
)
domain_lang_model.is_active = check_model_active(
default_language_domain_model,
domain_lang_model,
{TITLE, CONTENT},
f"{db_obj.title}/{db_obj.language}",
False,
True,
)
sw.domain.insert_or_update_domain(domain_lang_model, meta_object)
except (ValidationError, InvalidMerge) as err:
logger.warning(
f"Could not merge database language domain entry: {ident}"
)
db_obj.is_active = False
logger.warning(err)
try:
sw.db_session.commit()
except (StatementError, DatabaseError) as err:
logger.exception(err)
logger.error(f"Insertion failed for all rows of domain: {domain_name}")
sw.db_session.rollback()
sw.data.sync_domain_assets(domain_name)
if env_settings().INIT_TEMPLATES_CODES:
init_entries(meta_object, sw, actor)
missing_entries = sw.domain.validate_entry_refs(meta_model)
if missing_entries:
meta_object.is_active = False
sw.db_session.commit()
logger.warning(
f"Some entries are missing...: {missing_entries} deactivating domain"
)
def update_domain_images(domain_name: str):
src_path = join(INIT_DOMAINS_FOLDER, domain_name)
dest_path = join(settings.DOMAINS_IMAGE_FOLDER, domain_name)
files = ["banner.jpg", "icon.png"]
for file in files:
file_path = join(src_path, file)
if not isfile(file_path):
if domain_name == NO_DOMAIN:
raise FileNotFoundError(f"NO_DOMAIN must have image {file}")
logger.warning(f"Missing {file} for {domain_name}. copying from NO_DOMAIN")
shutil.copy(join(INIT_DOMAINS_FOLDER, NO_DOMAIN, file), file_path)
try:
dirsync.sync(
src_path,
dest_path,
"sync",
**{
"create": True,
"only": files,
"logger": logger,
},
)
except ValueError as err:
logger.error(f"Skipping domain-images for {domain_name}")
logger.exception(err)
def update_domain_js_plugin(domain_name: str):
src_path = join(INIT_DOMAINS_FOLDER, domain_name, "plugins")
if not isfile(join(src_path, domain_name + ".js")):
return
dest_path = join(settings.JS_PLUGIN_FOLDER)
if not isdir(dest_path):
os.makedirs(dest_path)
try:
dirsync.sync(
src_path,
dest_path,
"sync",
**{
"create": True,
"only": [domain_name + ".js"],
"logger": logger,
},
)
except ValueError as err:
logger.error(f"Skipping domain-images for {domain_name}")
logger.exception(err)
@deprecated
def read_domain_data(domain_folder: str) -> Dict:
"""
Reads the domain-data from the domain.json files for all languages
"""
files = glob(domain_folder + "/lang/*/domain.json")
domain_translations = {}
for file in files:
lang_code = get_language_code_from_domain_path(file)
lang_domain_data = read_orjson(file)
try:
schemas.validate(domain_data_schema_file, lang_domain_data)
domain_translations[lang_code] = lang_domain_data
except ValidationError as exc:
logger.exception(exc) # exc.path
logger.warning(
f"Domain data for domain: {domain_folder}, language: {lang_code} is not valid and will be ignored"
)
return domain_translations
| [
"app.setup.init_data.init_entries.init_entries",
"app.util.language.get_language_code_from_domain_path",
"os.path.isfile",
"app.util.files.read_orjson",
"app.settings.env_settings",
"os.makedirs",
"glob.glob",
"dirsync.sync",
"app.services.schemas.validate",
"app.setup.init_data.plugin_import.init... | [((1137, 1156), 'logging.getLogger', 'getLogger', (['__name__'], {}), '(__name__)\n', (1146, 1156), False, 'from logging import getLogger\n'), ((1211, 1249), 'os.path.join', 'join', (['INIT_DOMAINS_FOLDER', 'domain_name'], {}), '(INIT_DOMAINS_FOLDER, domain_name)\n', (1215, 1249), False, 'from os.path import join, basename, isdir, isfile\n'), ((1324, 1372), 'os.path.join', 'join', (['INIT_DOMAINS_FOLDER', 'domain_name', 'language'], {}), '(INIT_DOMAINS_FOLDER, domain_name, language)\n', (1328, 1372), False, 'from os.path import join, basename, isdir, isfile\n'), ((1458, 1517), 'os.path.join', 'join', (['INIT_DOMAINS_FOLDER', 'domain_name', 'language', 'type_name'], {}), '(INIT_DOMAINS_FOLDER, domain_name, language, type_name)\n', (1462, 1517), False, 'from os.path import join, basename, isdir, isfile\n'), ((1935, 1967), 'glob.glob', 'glob', (["(INIT_DOMAINS_FOLDER + '/*')"], {}), "(INIT_DOMAINS_FOLDER + '/*')\n", (1939, 1967), False, 'from glob import glob\n'), ((3127, 3165), 'os.path.join', 'join', (['INIT_DOMAINS_FOLDER', 'domain_name'], {}), '(INIT_DOMAINS_FOLDER, domain_name)\n', (3131, 3165), False, 'from os.path import join, basename, isdir, isfile\n'), ((3210, 3241), 'app.setup.init_data.plugin_import.init_plugin_import', 'init_plugin_import', (['domain_name'], {}), '(domain_name)\n', (3228, 3241), False, 'from app.setup.init_data.plugin_import import init_plugin_import\n'), ((3355, 3394), 'os.path.join', 'join', (['domain_base_folder', '"""domain.json"""'], {}), "(domain_base_folder, 'domain.json')\n", (3359, 3394), False, 'from os.path import join, basename, isdir, isfile\n'), ((9268, 9306), 'os.path.join', 'join', (['INIT_DOMAINS_FOLDER', 'domain_name'], {}), '(INIT_DOMAINS_FOLDER, domain_name)\n', (9272, 9306), False, 'from os.path import join, basename, isdir, isfile\n'), ((9323, 9371), 'os.path.join', 'join', (['settings.DOMAINS_IMAGE_FOLDER', 'domain_name'], {}), '(settings.DOMAINS_IMAGE_FOLDER, domain_name)\n', (9327, 9371), False, 'from os.path import join, basename, isdir, isfile\n'), ((10218, 10267), 'os.path.join', 'join', (['INIT_DOMAINS_FOLDER', 'domain_name', '"""plugins"""'], {}), "(INIT_DOMAINS_FOLDER, domain_name, 'plugins')\n", (10222, 10267), False, 'from os.path import join, basename, isdir, isfile\n'), ((10355, 10386), 'os.path.join', 'join', (['settings.JS_PLUGIN_FOLDER'], {}), '(settings.JS_PLUGIN_FOLDER)\n', (10359, 10386), False, 'from os.path import join, basename, isdir, isfile\n'), ((10987, 11030), 'glob.glob', 'glob', (["(domain_folder + '/lang/*/domain.json')"], {}), "(domain_folder + '/lang/*/domain.json')\n", (10991, 11030), False, 'from glob import glob\n'), ((2069, 2080), 'os.path.basename', 'basename', (['d'], {}), '(d)\n', (2077, 2080), False, 'from os.path import join, basename, isdir, isfile\n'), ((3424, 3455), 'app.util.files.JSONPath', 'JSONPath', (['domain_base_file_path'], {}), '(domain_base_file_path)\n', (3432, 3455), False, 'from app.util.files import read_orjson, JSONPath\n'), ((3646, 3677), 'app.models.schema.domain_models.DomainBase.parse_obj', 'DomainBase.parse_obj', (['meta_data'], {}), '(meta_data)\n', (3666, 3677), False, 'from app.models.schema.domain_models import DomainLang, DomainBase\n'), ((4157, 4168), 'app.util.files.JSONPath', 'JSONPath', (['_'], {}), '(_)\n', (4165, 4168), False, 'from app.util.files import read_orjson, JSONPath\n'), ((5326, 5359), 'os.path.basename', 'basename', (['lang_domain_file.parent'], {}), '(lang_domain_file.parent)\n', (5334, 5359), False, 'from os.path import join, basename, isdir, isfile\n'), ((7214, 7235), 'os.path.basename', 'basename', (['file.parent'], {}), '(file.parent)\n', (7222, 7235), False, 'from os.path import join, basename, isdir, isfile\n'), ((8852, 8866), 'app.settings.env_settings', 'env_settings', ([], {}), '()\n', (8864, 8866), False, 'from app.settings import env_settings, INIT_DOMAINS_FOLDER\n'), ((8897, 8933), 'app.setup.init_data.init_entries.init_entries', 'init_entries', (['meta_object', 'sw', 'actor'], {}), '(meta_object, sw, actor)\n', (8909, 8933), False, 'from app.setup.init_data.init_entries import init_entries\n'), ((9454, 9474), 'os.path.join', 'join', (['src_path', 'file'], {}), '(src_path, file)\n', (9458, 9474), False, 'from os.path import join, basename, isdir, isfile\n'), ((9811, 9909), 'dirsync.sync', 'dirsync.sync', (['src_path', 'dest_path', '"""sync"""'], {}), "(src_path, dest_path, 'sync', **{'create': True, 'only': files,\n 'logger': logger})\n", (9823, 9909), False, 'import dirsync\n'), ((10398, 10414), 'os.path.isdir', 'isdir', (['dest_path'], {}), '(dest_path)\n', (10403, 10414), False, 'from os.path import join, basename, isdir, isfile\n'), ((10424, 10446), 'os.makedirs', 'os.makedirs', (['dest_path'], {}), '(dest_path)\n', (10435, 10446), False, 'import os\n'), ((10464, 10579), 'dirsync.sync', 'dirsync.sync', (['src_path', 'dest_path', '"""sync"""'], {}), "(src_path, dest_path, 'sync', **{'create': True, 'only': [\n domain_name + '.js'], 'logger': logger})\n", (10476, 10579), False, 'import dirsync\n'), ((11103, 11143), 'app.util.language.get_language_code_from_domain_path', 'get_language_code_from_domain_path', (['file'], {}), '(file)\n', (11137, 11143), False, 'from app.util.language import get_language_code_from_domain_path\n'), ((11171, 11188), 'app.util.files.read_orjson', 'read_orjson', (['file'], {}), '(file)\n', (11182, 11188), False, 'from app.util.files import read_orjson, JSONPath\n'), ((4178, 4226), 'glob.glob', 'glob', (["(domain_base_folder + '/lang/*/domain.json')"], {}), "(domain_base_folder + '/lang/*/domain.json')\n", (4182, 4226), False, 'from glob import glob\n'), ((5622, 5660), 'app.models.schema.domain_models.DomainLang.parse_obj', 'DomainLang.parse_obj', (['domain_lang_data'], {}), '(domain_lang_data)\n', (5642, 5660), False, 'from app.models.schema.domain_models import DomainLang, DomainBase\n'), ((9490, 9507), 'os.path.isfile', 'isfile', (['file_path'], {}), '(file_path)\n', (9496, 9507), False, 'from os.path import join, basename, isdir, isfile\n'), ((10286, 10321), 'os.path.join', 'join', (['src_path', "(domain_name + '.js')"], {}), "(src_path, domain_name + '.js')\n", (10290, 10321), False, 'from os.path import join, basename, isdir, isfile\n'), ((11214, 11273), 'app.services.schemas.validate', 'schemas.validate', (['domain_data_schema_file', 'lang_domain_data'], {}), '(domain_data_schema_file, lang_domain_data)\n', (11230, 11273), False, 'from app.services import schemas\n'), ((2011, 2027), 'os.path.isdir', 'os.path.isdir', (['f'], {}), '(f)\n', (2024, 2027), False, 'import os\n'), ((6213, 6340), 'app.util.dict_rearrange.check_model_active', 'check_model_active', (['default_language_domain_model', 'domain_lang_model', "{'title', 'content'}", 'f"""{title}/{lang}"""', '(False)', '(True)'], {}), "(default_language_domain_model, domain_lang_model, {\n 'title', 'content'}, f'{title}/{lang}', False, True)\n", (6231, 6340), False, 'from app.util.dict_rearrange import deep_merge, check_model_active\n'), ((7941, 8081), 'app.util.dict_rearrange.check_model_active', 'check_model_active', (['default_language_domain_model', 'domain_lang_model', '{TITLE, CONTENT}', 'f"""{db_obj.title}/{db_obj.language}"""', '(False)', '(True)'], {}), "(default_language_domain_model, domain_lang_model, {TITLE,\n CONTENT}, f'{db_obj.title}/{db_obj.language}', False, True)\n", (7959, 8081), False, 'from app.util.dict_rearrange import deep_merge, check_model_active\n'), ((9739, 9781), 'os.path.join', 'join', (['INIT_DOMAINS_FOLDER', 'NO_DOMAIN', 'file'], {}), '(INIT_DOMAINS_FOLDER, NO_DOMAIN, file)\n', (9743, 9781), False, 'from os.path import join, basename, isdir, isfile\n'), ((3581, 3595), 'app.settings.env_settings', 'env_settings', ([], {}), '()\n', (3593, 3595), False, 'from app.settings import env_settings, INIT_DOMAINS_FOLDER\n'), ((7579, 7606), 'app.models.schema.domain_models.DomainLang.from_orm', 'DomainLang.from_orm', (['db_obj'], {}), '(db_obj)\n', (7598, 7606), False, 'from app.models.schema.domain_models import DomainLang, DomainBase\n')] |
"""Run, agentq, run!
Module for running agentq through a session.
"""
import sys
sys.path.insert(0, '/home/aaron/src/github.com/AAorris/agentq')
import gym
import tensorflow as tf
from agentq import actor, utils
def cartpole():
env = gym.make('CartPole-v1')
state = env.reset()
observations = tf.placeholder(tf.float32, [None, env.spec.max_episode_steps])
model = actor.thin_nn_model
agentq = actor.create_actor(observations, model, env.action_space.n)
for episode in range(10):
rewards = []
for transitions, prospects in utils.run_episode(env, agentq):
discounted_reward, advantage = prospects
rewards.append(discounted_reward)
print('Avg Reward: {}'.format(sum(rewards) / float(len(rewards))))
cartpole()
| [
"gym.make",
"agentq.utils.run_episode",
"sys.path.insert",
"agentq.actor.create_actor",
"tensorflow.placeholder"
] | [((82, 145), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""/home/aaron/src/github.com/AAorris/agentq"""'], {}), "(0, '/home/aaron/src/github.com/AAorris/agentq')\n", (97, 145), False, 'import sys\n'), ((243, 266), 'gym.make', 'gym.make', (['"""CartPole-v1"""'], {}), "('CartPole-v1')\n", (251, 266), False, 'import gym\n'), ((311, 373), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, env.spec.max_episode_steps]'], {}), '(tf.float32, [None, env.spec.max_episode_steps])\n', (325, 373), True, 'import tensorflow as tf\n'), ((420, 479), 'agentq.actor.create_actor', 'actor.create_actor', (['observations', 'model', 'env.action_space.n'], {}), '(observations, model, env.action_space.n)\n', (438, 479), False, 'from agentq import actor, utils\n'), ((570, 600), 'agentq.utils.run_episode', 'utils.run_episode', (['env', 'agentq'], {}), '(env, agentq)\n', (587, 600), False, 'from agentq import actor, utils\n')] |
from subprocess import CalledProcessError
import os
import re
from vee import log
from vee.cli import style_note, style_warning, style_error, style
from vee.environment import Environment
from vee.exceptions import CliMixin
from vee.git import GitRepo
from vee.manifest import Manifest, Header
from vee.packageset import PackageSet
from vee.utils import cached_property, makedirs
class EnvironmentRepo(GitRepo):
def __init__(self, dbrow, home):
super(EnvironmentRepo, self).__init__(
work_tree=dbrow['path'] or home._abs_path('repos', dbrow['name']),
remote_name=dbrow['remote'],
branch_name=dbrow['branch'],
)
self.id = dbrow['id']
self.name = dbrow['name']
self.home = home
self._req_path = os.path.join(self.work_tree, 'manifest.txt')
def fetch(self):
return super(EnvironmentRepo, self).fetch(self.remote_name, self.branch_name)
def checkout(self, force=False):
super(EnvironmentRepo, self).checkout(
revision='%s/%s' % (self.remote_name, self.branch_name),
branch=self.branch_name,
force=force
)
def get_environment(self):
return Environment(repo=self, home=self.home)
def load_manifest(self, revision=None):
manifest = Manifest(repo=self, home=self.home)
if revision:
manifest.parse_file(os.path.basename(self._req_path), alt_open=lambda x: self.show(revision, x).splitlines())
elif os.path.exists(self._req_path):
manifest.parse_file(self._req_path)
return manifest
def dump_manifest(self, req_set):
return req_set.dump(self._req_path)
def commit(self, message, semver_level=None):
manifest = self.load_manifest()
version_header = manifest.headers.get('Version')
if not version_header:
version_header = manifest.add_header('Version', '0.0.0')
if semver_level is not None:
version = []
for i, x in enumerate(re.split(r'[.-]', version_header.value)):
try:
version.append(int(x))
except ValueError:
version.append(x)
while len(version) <= semver_level:
version.append(0)
version[semver_level] = version[semver_level] + 1
for i in range(semver_level + 1, len(version)):
version[i] = 0
version_header.value = '.'.join(str(x) for x in version)
from vee import __about__ as about
manifest.set_header('Vee-Revision', about.__version__ + '+' + about.__revision__)
paths = self.dump_manifest(manifest)
for path in paths:
self.git('add', path, silent=True)
status = list(self.status())
if not status:
raise RuntimeError('nothing to commit')
# Make sure there are no other changes.
for idx, tree, name in status:
if tree.strip():
raise RuntimeError('work-tree is dirty')
self.git('commit', '-m', message, silent=True)
def update(self, force=False):
log.info(style_note('Updating repo', self.name))
self.clone_if_not_exists()
if self.remote_name not in self.remotes():
log.warning('"%s" does not have remote "%s"' % (self.name, self.remote_name))
return True
rev = self.fetch()
if not force and not self.check_ff_safety(rev):
log.error('Cannot fast-forward; skipping.')
return False
self.checkout(force=force)
return True
def upgrade(self, dirty=False, subset=None, reinstall=False, relink=False,
no_deps=False, force_branch_link=True
):
self.clone_if_not_exists()
try:
head = self.head
except CalledProcessError:
log.warning('no commits in repository')
head = None
try:
remote_head = self.rev_parse('%s/%s' % (self.remote_name, self.branch_name))
except ValueError:
log.warning('tracked %s/%s does not exist in self' % (self.remote_name, self.branch_name))
remote_head = None
if remote_head and head != remote_head:
log.warning('%s repo not checked out to %s/%s' % (
self.name, self.remote_name, self.branch_name))
dirty = bool(list(self.status()))
if not dirty and self.is_dirty():
log.error('%s repo is dirty; force with --dirty' % self.name)
return False
env = self.get_environment()
manifest = self.load_manifest()
packages = PackageSet(env=env, home=self.home)
# Register the whole set, so that dependencies are pulled from here instead
# of weakly resolved from installed packages.
# TODO: This blanket reinstalls things, even if no_deps is set.
packages.resolve_set(manifest, check_existing=not reinstall)
# Install and/or link.
packages.install(subset or None, link_env=env, reinstall=reinstall, relink=relink, no_deps=no_deps)
if packages._errored and not force_branch_link:
log.warning("Not creating branch or version links; force with --force-branch-link")
return False
# Create a symlink by branch.
path_by_branch = self.home._abs_path('environments', self.name, self.branch_name)
if os.path.lexists(path_by_branch):
os.unlink(path_by_branch)
makedirs(os.path.dirname(path_by_branch))
os.symlink(env.path, path_by_branch)
# Create a symlink by version.
version = manifest.headers.get('Version')
if version:
path_by_version = self.home._abs_path('environments', self.name, 'versions', version.value + ('-dirty' if dirty else ''))
if os.path.lexists(path_by_version):
os.unlink(path_by_version)
makedirs(os.path.dirname(path_by_version))
os.symlink(env.path, path_by_version)
return True
| [
"os.path.join",
"os.path.basename",
"vee.log.warning",
"vee.manifest.Manifest",
"os.path.dirname",
"vee.log.error",
"os.symlink",
"vee.packageset.PackageSet",
"os.path.exists",
"os.path.lexists",
"vee.environment.Environment",
"os.unlink",
"vee.cli.style_note",
"re.split"
] | [((785, 829), 'os.path.join', 'os.path.join', (['self.work_tree', '"""manifest.txt"""'], {}), "(self.work_tree, 'manifest.txt')\n", (797, 829), False, 'import os\n'), ((1211, 1249), 'vee.environment.Environment', 'Environment', ([], {'repo': 'self', 'home': 'self.home'}), '(repo=self, home=self.home)\n', (1222, 1249), False, 'from vee.environment import Environment\n'), ((1318, 1353), 'vee.manifest.Manifest', 'Manifest', ([], {'repo': 'self', 'home': 'self.home'}), '(repo=self, home=self.home)\n', (1326, 1353), False, 'from vee.manifest import Manifest, Header\n'), ((4705, 4740), 'vee.packageset.PackageSet', 'PackageSet', ([], {'env': 'env', 'home': 'self.home'}), '(env=env, home=self.home)\n', (4715, 4740), False, 'from vee.packageset import PackageSet\n'), ((5487, 5518), 'os.path.lexists', 'os.path.lexists', (['path_by_branch'], {}), '(path_by_branch)\n', (5502, 5518), False, 'import os\n'), ((5616, 5652), 'os.symlink', 'os.symlink', (['env.path', 'path_by_branch'], {}), '(env.path, path_by_branch)\n', (5626, 5652), False, 'import os\n'), ((1510, 1540), 'os.path.exists', 'os.path.exists', (['self._req_path'], {}), '(self._req_path)\n', (1524, 1540), False, 'import os\n'), ((3196, 3234), 'vee.cli.style_note', 'style_note', (['"""Updating repo"""', 'self.name'], {}), "('Updating repo', self.name)\n", (3206, 3234), False, 'from vee.cli import style_note, style_warning, style_error, style\n'), ((3336, 3413), 'vee.log.warning', 'log.warning', (['(\'"%s" does not have remote "%s"\' % (self.name, self.remote_name))'], {}), '(\'"%s" does not have remote "%s"\' % (self.name, self.remote_name))\n', (3347, 3413), False, 'from vee import log\n'), ((3535, 3578), 'vee.log.error', 'log.error', (['"""Cannot fast-forward; skipping."""'], {}), "('Cannot fast-forward; skipping.')\n", (3544, 3578), False, 'from vee import log\n'), ((4308, 4410), 'vee.log.warning', 'log.warning', (["('%s repo not checked out to %s/%s' % (self.name, self.remote_name, self.\n branch_name))"], {}), "('%s repo not checked out to %s/%s' % (self.name, self.\n remote_name, self.branch_name))\n", (4319, 4410), False, 'from vee import log\n'), ((4520, 4581), 'vee.log.error', 'log.error', (["('%s repo is dirty; force with --dirty' % self.name)"], {}), "('%s repo is dirty; force with --dirty' % self.name)\n", (4529, 4581), False, 'from vee import log\n'), ((5238, 5326), 'vee.log.warning', 'log.warning', (['"""Not creating branch or version links; force with --force-branch-link"""'], {}), "(\n 'Not creating branch or version links; force with --force-branch-link')\n", (5249, 5326), False, 'from vee import log\n'), ((5532, 5557), 'os.unlink', 'os.unlink', (['path_by_branch'], {}), '(path_by_branch)\n', (5541, 5557), False, 'import os\n'), ((5575, 5606), 'os.path.dirname', 'os.path.dirname', (['path_by_branch'], {}), '(path_by_branch)\n', (5590, 5606), False, 'import os\n'), ((5912, 5944), 'os.path.lexists', 'os.path.lexists', (['path_by_version'], {}), '(path_by_version)\n', (5927, 5944), False, 'import os\n'), ((6056, 6093), 'os.symlink', 'os.symlink', (['env.path', 'path_by_version'], {}), '(env.path, path_by_version)\n', (6066, 6093), False, 'import os\n'), ((1407, 1439), 'os.path.basename', 'os.path.basename', (['self._req_path'], {}), '(self._req_path)\n', (1423, 1439), False, 'import os\n'), ((2048, 2086), 're.split', 're.split', (['"""[.-]"""', 'version_header.value'], {}), "('[.-]', version_header.value)\n", (2056, 2086), False, 'import re\n'), ((3919, 3958), 'vee.log.warning', 'log.warning', (['"""no commits in repository"""'], {}), "('no commits in repository')\n", (3930, 3958), False, 'from vee import log\n'), ((4125, 4219), 'vee.log.warning', 'log.warning', (["('tracked %s/%s does not exist in self' % (self.remote_name, self.branch_name))"], {}), "('tracked %s/%s does not exist in self' % (self.remote_name,\n self.branch_name))\n", (4136, 4219), False, 'from vee import log\n'), ((5962, 5988), 'os.unlink', 'os.unlink', (['path_by_version'], {}), '(path_by_version)\n', (5971, 5988), False, 'import os\n'), ((6010, 6042), 'os.path.dirname', 'os.path.dirname', (['path_by_version'], {}), '(path_by_version)\n', (6025, 6042), False, 'import os\n')] |
from train import train_and_classify
from utils import split_train_test
from features import zcr_features
GEN_SPLIT_CASE = False
def start_test():
feat = zcr_features('training/training-a/a0001.wav')
# print(feat)
return
def start():
"""
starting function
:return: None
"""
folder = 'a'
if GEN_SPLIT_CASE:
split_train_test(folder)
print("Split completed")
train_and_classify(folder, all_folders=True)
return
if __name__ == "__main__":
start()
| [
"train.train_and_classify",
"features.zcr_features",
"utils.split_train_test"
] | [((162, 207), 'features.zcr_features', 'zcr_features', (['"""training/training-a/a0001.wav"""'], {}), "('training/training-a/a0001.wav')\n", (174, 207), False, 'from features import zcr_features\n'), ((418, 462), 'train.train_and_classify', 'train_and_classify', (['folder'], {'all_folders': '(True)'}), '(folder, all_folders=True)\n', (436, 462), False, 'from train import train_and_classify\n'), ((356, 380), 'utils.split_train_test', 'split_train_test', (['folder'], {}), '(folder)\n', (372, 380), False, 'from utils import split_train_test\n')] |
#!/usr/bin/env python3
import korali
import sys
import argparse
sys.path.append("_model/")
from model import *
k = korali.Engine()
e = korali.Experiment()
# Parsing arguments
parser = argparse.ArgumentParser(description='Runs the Aphros Fishbone experiment with Korali.')
parser.add_argument('--resultFolder', '-r', help='Path to the resuls folder', default='_result', required=False)
parser.add_argument('--samples', '-s', help='Number of CMAES samples per generation.', default=32, required=False)
parser.add_argument('--concurrency', '-c', help='Number of concurrent Aphros instances.', default=1, required=False)
parser.add_argument('--objective', '-obj', help='Optimization objective', choices=['maxNumCoal', 'minNumCoal', 'maxMeanVel'], required=True)
parser.add_argument('--ngens', '-ng', help='Number of generations to run per job.', default=200, required=False)
args = parser.parse_args()
# Parsing inputs
objective = str(args.objective)
ngens = int(args.ngens)
# Loading previous results if they exist
resultFolder = args.resultFolder
e["File Output"]["Path"] = resultFolder
found = e.loadState(resultFolder + '/latest')
# If, found adding number of generations to the termination criteria
if (found == True):
e["Solver"]["Termination Criteria"]["Max Generations"] = e["Current Generation"] + ngens
else:
e["Solver"]["Termination Criteria"]["Max Generations"] = ngens
# Setting up the reference likelihood for the Bayesian Problem
e["Problem"]["Type"] = "Optimization"
e["Problem"]["Objective Function"] = lambda x: model(x, resultFolder, objective)
e["Variables"][0]["Name"] = "Arc Width 1"
e["Variables"][0]["Lower Bound"] = 0.5
e["Variables"][0]["Upper Bound"] = 1.5
e["Variables"][0]["Initial Standard Deviation"] = 0.5
e["Variables"][1]["Name"] = "Arc Width 1"
e["Variables"][1]["Lower Bound"] = 0.5
e["Variables"][1]["Upper Bound"] = 1.5
e["Variables"][1]["Initial Standard Deviation"] = 0.5
e["Variables"][2]["Name"] = "Arc Width 2"
e["Variables"][2]["Lower Bound"] = 0.5
e["Variables"][2]["Upper Bound"] = 1.5
e["Variables"][2]["Initial Standard Deviation"] = 0.5
e["Variables"][3]["Name"] = "Arc Width 3"
e["Variables"][3]["Lower Bound"] = 0.5
e["Variables"][3]["Upper Bound"] = 1.5
e["Variables"][3]["Initial Standard Deviation"] = 0.5
e["Variables"][4]["Name"] = "Arc Width 4"
e["Variables"][4]["Lower Bound"] = 0.5
e["Variables"][4]["Upper Bound"] = 1.5
e["Variables"][4]["Initial Standard Deviation"] = 0.5
e["Variables"][5]["Name"] = "Arc Offset 1"
e["Variables"][5]["Lower Bound"] = -0.5
e["Variables"][5]["Upper Bound"] = 0.5
e["Variables"][5]["Initial Standard Deviation"] = 0.5
e["Variables"][6]["Name"] = "Arc Offset 2"
e["Variables"][6]["Lower Bound"] = -0.5
e["Variables"][6]["Upper Bound"] = 0.5
e["Variables"][6]["Initial Standard Deviation"] = 0.5
e["Variables"][7]["Name"] = "Arc Offset 3"
e["Variables"][7]["Lower Bound"] = -0.5
e["Variables"][7]["Upper Bound"] = 0.5
e["Variables"][7]["Initial Standard Deviation"] = 0.5
e["Variables"][8]["Name"] = "Arc Offset 4"
e["Variables"][8]["Lower Bound"] = -0.5
e["Variables"][8]["Upper Bound"] = 0.5
e["Variables"][8]["Initial Standard Deviation"] = 0.5
e["Variables"][9]["Name"] = "Arc Offset 5"
e["Variables"][9]["Lower Bound"] = -0.5
e["Variables"][9]["Upper Bound"] = 0.5
e["Variables"][9]["Initial Standard Deviation"] = 0.5
# Configuring CMA-ES parameters
e["Solver"]["Type"] = "Optimizer/CMAES"
e["Solver"]["Population Size"] = args.samples
# Result Settings
e["File Output"]["Path"] = resultFolder
e["File Output"]["Frequency"] = 1 # Saving every state
# Selecting external conduit
k["Conduit"]["Type"] = "Concurrent"
k["Conduit"]["Concurrent Jobs"] = int(args.concurrency)
# Reproducibility Settings
e["Random Seed"] = 0xC0FFEE
e["Preserve Random Number Generator States"] = True
# Configuring base parameter file
parameterString = ''
# Logging configuration
print('--------------------------------------------------')
print('Running Korali+Aphros Pipe experiment.')
print('Result Folder: ' + resultFolder)
print('Generations per job: ' + str(args.ngens))
print('CMAES samples per generation: ' + str(args.samples))
print('Concurrent Aphros instances: ' + str(args.concurrency))
print('Objective: ' + objective)
print('Base Configuration:')
print(parameterString, end='')
print('--------------------------------------------------')
# Storing base parameter file
configFile='_config/par.py'
with open(configFile, 'w') as f:
print('[Korali] Creating: ' + configFile + '...')
f.write(parameterString)
k.run(e)
| [
"sys.path.append",
"argparse.ArgumentParser",
"korali.Experiment",
"korali.Engine"
] | [((64, 90), 'sys.path.append', 'sys.path.append', (['"""_model/"""'], {}), "('_model/')\n", (79, 90), False, 'import sys\n'), ((116, 131), 'korali.Engine', 'korali.Engine', ([], {}), '()\n', (129, 131), False, 'import korali\n'), ((136, 155), 'korali.Experiment', 'korali.Experiment', ([], {}), '()\n', (153, 155), False, 'import korali\n'), ((186, 278), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Runs the Aphros Fishbone experiment with Korali."""'}), "(description=\n 'Runs the Aphros Fishbone experiment with Korali.')\n", (209, 278), False, 'import argparse\n')] |
'''Unit test package for module "tws._OrderState".'''
__copyright__ = "Copyright (c) 2008 <NAME>"
__version__ = "$Id$"
import unittest
from tws import OrderState
class test_OrderState(unittest.TestCase):
'''Test type "tws.OrderState"'''
def test_init(self):
test1 = OrderState()
test2 = OrderState("ab", "cd", "ef", "gh", 3.5, 4.5, 5.5, "ij", "kl")
self.assertEqual(test1.m_status, "")
self.assertEqual(test1.m_initMargin, "")
self.assertEqual(test1.m_maintMargin, "")
self.assertEqual(test1.m_equityWithLoan, "")
self.assertEqual(test1.m_commission, 0.0)
self.assertEqual(test1.m_minCommission, 0.0)
self.assertEqual(test1.m_maxCommission, 0.0)
self.assertEqual(test1.m_commissionCurrency, "")
self.assertEqual(test1.m_warningText, "")
self.assertEqual(test2.m_status, "ab")
self.assertEqual(test2.m_initMargin, "cd")
self.assertEqual(test2.m_maintMargin, "ef")
self.assertEqual(test2.m_equityWithLoan, "gh")
self.assertEqual(test2.m_commission, 3.5)
self.assertEqual(test2.m_minCommission, 4.5)
self.assertEqual(test2.m_maxCommission, 5.5)
self.assertEqual(test2.m_commissionCurrency, "ij")
self.assertEqual(test2.m_warningText, "kl")
def test_fields(self):
test = OrderState()
test.m_status = "ab"
test.m_initMargin = "cd"
test.m_maintMargin = "ef"
test.m_equityWithLoan = "gh"
test.m_commission = 3.5
test.m_minCommission = 4.5
test.m_maxCommission = 5.5
test.m_commissionCurrency = "ij"
test.m_warningText = "kl"
self.assertEqual(test.m_status, "ab")
self.assertEqual(test.m_initMargin, "cd")
self.assertEqual(test.m_maintMargin, "ef")
self.assertEqual(test.m_equityWithLoan, "gh")
self.assertEqual(test.m_commission, 3.5)
self.assertEqual(test.m_minCommission, 4.5)
self.assertEqual(test.m_maxCommission, 5.5)
self.assertEqual(test.m_commissionCurrency, "ij")
self.assertEqual(test.m_warningText, "kl")
def test_equals(self):
test1 = OrderState()
test2 = OrderState()
test3 = OrderState("ab", "cd", "ef", "gh", 3.5, 4.5, 5.5, "ij", "kl")
self.assertEqual(test1, test1)
self.assertEqual(test1, test2)
self.assertNotEqual(test1, None)
self.assertNotEqual(test1, "")
self.assertEqual(test3, test3)
self.assertNotEqual(test1, test3)
| [
"tws.OrderState"
] | [((289, 301), 'tws.OrderState', 'OrderState', ([], {}), '()\n', (299, 301), False, 'from tws import OrderState\n'), ((318, 379), 'tws.OrderState', 'OrderState', (['"""ab"""', '"""cd"""', '"""ef"""', '"""gh"""', '(3.5)', '(4.5)', '(5.5)', '"""ij"""', '"""kl"""'], {}), "('ab', 'cd', 'ef', 'gh', 3.5, 4.5, 5.5, 'ij', 'kl')\n", (328, 379), False, 'from tws import OrderState\n'), ((1357, 1369), 'tws.OrderState', 'OrderState', ([], {}), '()\n', (1367, 1369), False, 'from tws import OrderState\n'), ((2189, 2201), 'tws.OrderState', 'OrderState', ([], {}), '()\n', (2199, 2201), False, 'from tws import OrderState\n'), ((2218, 2230), 'tws.OrderState', 'OrderState', ([], {}), '()\n', (2228, 2230), False, 'from tws import OrderState\n'), ((2247, 2308), 'tws.OrderState', 'OrderState', (['"""ab"""', '"""cd"""', '"""ef"""', '"""gh"""', '(3.5)', '(4.5)', '(5.5)', '"""ij"""', '"""kl"""'], {}), "('ab', 'cd', 'ef', 'gh', 3.5, 4.5, 5.5, 'ij', 'kl')\n", (2257, 2308), False, 'from tws import OrderState\n')] |
from Machine import Machine
from typing import Set, Dict
class MachineCluster:
def __init__(self, mach_type: str, stable_state_set: Set[str], time_out: int):
self.time_out = time_out
self.mach_type = mach_type
self.stable_state_set = stable_state_set
self.machine_dict: Dict[int, Machine] = {}
def __str__(self):
return self.mach_type + ': ' + str(len(self.machine_dict))
def register_cache_block(self, mach_type: str, mach_id: int, line_address: str, time_stamp: int,
start_state: str, final_state: str):
if mach_type == self.mach_type:
if mach_id not in self.machine_dict:
self.machine_dict[mach_id] = Machine(mach_type, mach_id, self.stable_state_set, self.time_out)
self.machine_dict[mach_id].register_cache_block(line_address, time_stamp, start_state, final_state)
def check_deadlock(self, cur_time_stamp: int):
for machine in self.machine_dict.values():
machine.check_deadlock(cur_time_stamp)
| [
"Machine.Machine"
] | [((726, 791), 'Machine.Machine', 'Machine', (['mach_type', 'mach_id', 'self.stable_state_set', 'self.time_out'], {}), '(mach_type, mach_id, self.stable_state_set, self.time_out)\n', (733, 791), False, 'from Machine import Machine\n')] |
"""
STATUS:OK/NOK
STATUS:OK pymkts can write nanoseconds and query correctly
BUG: when writing with csv_writer on the 1Sec and 1Min timeframe, you can only write microseconds and it will return Nanoseconds. If you write nanoseconds, the nanoseconds will not be parsed and the returned Nanoseconds field will be 0.
MIGRATION_STATUS:OK -> `test_csv_writer` is marked as XFAIL and skipped when `marketstore` is not accessible.
"""
import pytest
import random
import numpy as np
import pandas as pd
from subprocess import run, PIPE
import time
import os
import pymarketstore as pymkts
import pathlib
from . import utils
from shutil import which
use_grpc = os.getenv("USE_GRPC", "false") == "true"
client = pymkts.Client(f"http://127.0.0.1:{os.getenv('MARKETSTORE_PORT',5993)}/rpc",
grpc=(use_grpc))
pathlib.Path("/tmp/test_intermediate_data").mkdir(exist_ok=True)
@pytest.mark.parametrize(
"symbol,timeframe,size,start,window",
[
("PYW_TEST_01VA", "1Min", 400, "2016-01-01 10:00:00", "5s"),
("PYW_TEST_02VA", "1Min", 800, "2016-01-01 10:00:00", "5s"),
("PYW_TEST_03VA", "1Sec", 400, "2016-01-01 10:00:00", "5s"),
("PYW_TEST_04VA", "1Sec", 800, "2016-01-01 10:00:00", "5s"),
# ("PYW_TEST_05VB", "1Min", 50000, "2016-01-01 10:00:00", "4H"),
# ("PYW_TEST_06VB", "1Min", 100_000, "2016-01-01 10:00:00", "4H"),
# ("PYW_TEST_07VB", "1Min", 500_000, "2016-01-01 10:00:00", "4H"),
# ("PYW_TEST_08VB", "1Min", 1_000_000, "2016-01-01 10:00:00", "4H"),
# ("PYW_TEST_09VB", "1Sec", 50000, "2016-01-01 10:00:00", "4H"),
# ("PYW_TEST_10VB", "1Sec", 100_000, "2016-01-01 10:00:00", "4H"),
# ("PYW_TEST_11VB", "1Sec", 500_000, "2016-01-01 10:00:00", "4H"),
# ("PYW_TEST_12VB", "1Sec", 1_000_000, "2016-01-01 10:00:00", "4H"),
],
)
def test_write_pymkts(symbol, timeframe, size, start, window):
db_symbol = symbol + "_PY"
client.destroy(tbk=f"{db_symbol}/{timeframe}/TICK")
window = pd.Timedelta(window)
start = pd.Timestamp(start, tz="utc")
end = start + window
np.random.seed(42)
random.seed(42)
df = utils.generate_dataframe(size, start, end, random_data=False)
result = write_with_pymkts(df.copy(), db_symbol, timeframe)
# In case of grpc, a MultiServerResponse is returned and need to be handled differently.
if not use_grpc:
assert result["responses"] is None
assert_query_result(df, db_symbol, size, timeframe, start, end)
def write_with_pymkts(df: pd.DataFrame, symbol: str, timeframe: str):
"""
Write with pymarketstore client: function to benchmark
"""
records = utils.to_records(df, extract_nanoseconds=True)
tbk = f"{symbol}/{timeframe}/TICK"
return client.write(records, tbk, isvariablelength=True)
@pytest.mark.parametrize(
"symbol,timeframe,size,start,window,format",
[
# (dakimura, 2020-08-02, let me comment out this test for now as it needs some refactor...)
# ("CSVW_TEST_01VA", "1Min", 400, "2016-01-01 10:00:00", "5s", "ms"),
# ("CSVW_TEST_02VA", "1Min", 800, "2016-01-01 10:00:00", "5s", "ms"),
# ("CSVW_TEST_03VA", "1Sec", 400, "2016-01-01 10:00:00", "5s", "ms"),
# ("CSVW_TEST_04VA", "1Sec", 800, "2016-01-01 10:00:00", "5s", "ms"),
# ("CSVW_TEST_05VA", "1Min", 50000, "2016-01-01 10:00:00", "4H", "ms"),
# ("CSVW_TEST_06VA", "1Min", 100_000, "2016-01-01 10:00:00", "4H", "ms"),
# ("CSVW_TEST_07VA", "1Min", 500_000, "2016-01-01 10:00:00", "4H", "ms"),
# ("CSVW_TEST_08VA", "1Min", 1_000_000, "2016-01-01 10:00:00", "4H", "ms"),
# ("CSVW_TEST_09VA", "1Sec", 50000, "2016-01-01 10:00:00", "4H", "ms"),
# ("CSVW_TEST_10VA", "1Sec", 100_000, "2016-01-01 10:00:00", "4H", "ms"),
# ("CSVW_TEST_11VA", "1Sec", 500_000, "2016-01-01 10:00:00", "4H", "ms"),
# ("CSVW_TEST_12VA", "1Sec", 1_000_000, "2016-01-01 10:00:00", "4H", "ms"),
# ("CSVW_TEST_01VB", "1Min", 400, "2016-01-01 10:00:00", "5s", "ns"),
# ("CSVW_TEST_02VB", "1Min", 800, "2016-01-01 10:00:00", "5s", "ns"),
# ("CSVW_TEST_03VB", "1Sec", 400, "2016-01-01 10:00:00", "5s", "ns"),
# ("CSVW_TEST_04VB", "1Sec", 800, "2016-01-01 10:00:00", "5s", "ns"),
# ("CSVW_TEST_05VB", "1Min", 50000, "2016-01-01 10:00:00", "4H", "ns"),
# ("CSVW_TEST_06VB", "1Min", 100_000, "2016-01-01 10:00:00", "4H", "ns"),
# ("CSVW_TEST_07VB", "1Min", 500_000, "2016-01-01 10:00:00", "4H", "ns"),
# ("CSVW_TEST_08VB", "1Min", 1_000_000, "2016-01-01 10:00:00", "4H", "ns"),
# ("CSVW_TEST_09VB", "1Sec", 50000, "2016-01-01 10:00:00", "4H", "ns"),
# ("CSVW_TEST_10VB", "1Sec", 100_000, "2016-01-01 10:00:00", "4H", "ns"),
# ("CSVW_TEST_11VB", "1Sec", 500_000, "2016-01-01 10:00:00", "4H", "ns"),
# ("CSVW_TEST_12VB", "1Sec", 1_000_000, "2016-01-01 10:00:00", "4H", "ns"),
],
)
def test_csv_writer(symbol, timeframe, size, start, window, format):
"""
All tests outputting to format='ns' fail (even in 1Min timeframe, the
testing condition is just relaxed because of the issue with nanoseconds precision)
"""
if not is_marketstore_client_available():
pytest.xfail("Marketstore client is not available, the test will fail.")
db_symbol = symbol + "_CSV"
client.destroy(tbk="{db_symbol}/{timeframe}/TICK")
window = pd.Timedelta(window)
start = pd.Timestamp(start, tz="utc")
end = start + window
np.random.seed(42)
random.seed(42)
df = utils.generate_dataframe(size, start, end, random_data=False)
# remove the nanoseconds to milliseconds
if format == "ms":
total_ns = df.index.astype("i8")
df.index = pd.to_datetime(total_ns // 10 ** 3, unit="us", utc=True)
result = write_with_csv_writer_from_filename(df, db_symbol, timeframe, format)
print(result)
assert f"Read next {size} lines from CSV file" in result
# NOTE: the 1st time you write a symbol with csv_writer, you need to restart it to
# make it queryable
restart_marketstore()
assert_query_result(df, db_symbol, size, timeframe, start, end)
def write_with_csv_writer_from_filename(df, symbol, timeframe, format):
csv_filename = f"/tmp/test_intermediate_data/{symbol}.csv"
if format == "ns":
# BUG: for some reason with pandas when formatting with "%Y%m%d %H:%M:%S %f"
# it only output up to microseconds and not nanoseconds...
str_dates = df.index.strftime("%Y%m%d %H:%M:%S")
str_ns = ["{:09d}".format(el) for el in (df.index.astype("i8") % (10 ** 9))]
formatted_df = df.copy()
formatted_df["Epoch"] = str_dates + " " + str_ns
formatted_df[["Epoch", "Ask", "Bid"]].to_csv(
csv_filename, header=True, index=False
)
tmpdf = pd.read_csv(csv_filename, dtype=str).head()
assert len(tmpdf["Epoch"].iloc[0].split(" ")[-1]) == 9
elif format == "ms":
df[["Ask", "Bid"]].to_csv(
csv_filename, header=True, date_format="%Y%m%d %H:%M:%S %f"
)
tmpdf = pd.read_csv(csv_filename, dtype=str).head()
assert len(tmpdf["Epoch"].iloc[0].split(" ")[-1]) == 6
print(df.head().index.values)
print(df.head().values)
print(tmpdf.head().values)
config = 'firstRowHasColumnNames: true\ntimeFormat: "20060102 15:04:05"'
config_filename = f"/tmp/test_intermediate_data/{symbol}.yaml"
with open(config_filename, "w") as fp:
fp.write(config)
input = (
f"\create {symbol}/{timeframe}/TICK:Symbol/Timeframe/AttributeGroup Bid,Ask/float32 variable\n" # noqa
# f"\getinfo {symbol}/{timeframe}/TICK\n"
f"\load {symbol}/{timeframe}/TICK {csv_filename} {config_filename}\n"
# f"\show {symbol}/{timeframe}/TICK 1970-01-01\n"
# f"\getinfo {symbol}/{timeframe}/TICK\n"
# "\o test_ticks.csv\n" ?
)
cmd = ["marketstore", "connect", "-d", "/tmp/mktsdb"]
p = run(cmd, stdout=PIPE, input=input, encoding="ascii")
assert p.returncode == 0
print(p.stdout)
return p.stdout
def restart_marketstore():
cmd = ["pkill", "marketstore"]
p = run(cmd, stdout=PIPE, encoding="ascii")
time.sleep(3)
assert p.returncode == 0
print(p.stdout)
return p.stdout
def assert_query_result(df, symbol, size, timeframe, start, end):
start = pd.Timestamp(start).tz_convert("utc")
end = pd.Timestamp(end).tz_convert("utc")
param = pymkts.Params([symbol], timeframe, "TICK", start=start, end=end)
out_df = client.query(param).first().df()
processed_out_df = utils.process_query_result(out_df, inplace=False)
assert not out_df.empty
assert size == len(out_df)
assert out_df.index.is_monotonic_increasing
try:
if timeframe == "1Sec":
pd.testing.assert_frame_equal(df, processed_out_df, check_less_precise=True)
else:
# remove all nanoseconds information for now because of the precision issue
# on nanoseconds
# BUG
# though whe nwe look at the raw value of the nanoseconds returned, we can
# see it has the same issue as for 1sec: it is set to 0 which is then
# flipped to 99999999xx due to precision issue
pd.testing.assert_frame_equal(
rm_ns_from_idx(df),
rm_ns_from_idx(processed_out_df),
# check_less_precise=True,
# commented out as the warning shown:
# FutureWarning: The 'check_less_precise' keyword in testing.assert_*_equal is deprecated and will be removed
# in a future version. You can stop passing 'check_less_precise' to silence this warning. check_less_precise=True,
)
except AssertionError:
if len(df) != len(out_df):
print("lengths do not match, inspect manually")
raise
bad_locations = df.index != processed_out_df.index
dilated_bad_locations = np.convolve(
bad_locations.astype(int), [1, 1, 1], mode="same"
).astype(bool)
print("Show dilated bad locations".center(40, "-"))
print("\ninput df")
print(df.loc[dilated_bad_locations, :])
print("\noutput df, postprocessed")
print(processed_out_df.loc[dilated_bad_locations, :])
print("\noutput df, raw")
print(out_df.loc[dilated_bad_locations, :])
raise
def rm_ns_from_idx(df):
df = df.copy()
df.index = pd.to_datetime(
df.index.strftime("%Y%m%d %H:%M:%S"), utc=True
)
return df
def is_marketstore_client_available():
"""Check whether `marketstore` command line client is in the PATH and executable."""
return which('marketstore') is not None
| [
"random.seed",
"subprocess.run",
"pandas.to_datetime",
"pandas.Timedelta",
"pandas.testing.assert_frame_equal",
"pandas.Timestamp",
"pathlib.Path",
"shutil.which",
"pytest.xfail",
"pytest.mark.parametrize",
"os.getenv",
"pandas.read_csv",
"numpy.random.seed",
"pymarketstore.Params",
"tim... | [((889, 1216), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""symbol,timeframe,size,start,window"""', "[('PYW_TEST_01VA', '1Min', 400, '2016-01-01 10:00:00', '5s'), (\n 'PYW_TEST_02VA', '1Min', 800, '2016-01-01 10:00:00', '5s'), (\n 'PYW_TEST_03VA', '1Sec', 400, '2016-01-01 10:00:00', '5s'), (\n 'PYW_TEST_04VA', '1Sec', 800, '2016-01-01 10:00:00', '5s')]"], {}), "('symbol,timeframe,size,start,window', [(\n 'PYW_TEST_01VA', '1Min', 400, '2016-01-01 10:00:00', '5s'), (\n 'PYW_TEST_02VA', '1Min', 800, '2016-01-01 10:00:00', '5s'), (\n 'PYW_TEST_03VA', '1Sec', 400, '2016-01-01 10:00:00', '5s'), (\n 'PYW_TEST_04VA', '1Sec', 800, '2016-01-01 10:00:00', '5s')])\n", (912, 1216), False, 'import pytest\n'), ((2821, 2893), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""symbol,timeframe,size,start,window,format"""', '[]'], {}), "('symbol,timeframe,size,start,window,format', [])\n", (2844, 2893), False, 'import pytest\n'), ((654, 684), 'os.getenv', 'os.getenv', (['"""USE_GRPC"""', '"""false"""'], {}), "('USE_GRPC', 'false')\n", (663, 684), False, 'import os\n'), ((2011, 2031), 'pandas.Timedelta', 'pd.Timedelta', (['window'], {}), '(window)\n', (2023, 2031), True, 'import pandas as pd\n'), ((2044, 2073), 'pandas.Timestamp', 'pd.Timestamp', (['start'], {'tz': '"""utc"""'}), "(start, tz='utc')\n", (2056, 2073), True, 'import pandas as pd\n'), ((2103, 2121), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (2117, 2121), True, 'import numpy as np\n'), ((2126, 2141), 'random.seed', 'random.seed', (['(42)'], {}), '(42)\n', (2137, 2141), False, 'import random\n'), ((5422, 5442), 'pandas.Timedelta', 'pd.Timedelta', (['window'], {}), '(window)\n', (5434, 5442), True, 'import pandas as pd\n'), ((5455, 5484), 'pandas.Timestamp', 'pd.Timestamp', (['start'], {'tz': '"""utc"""'}), "(start, tz='utc')\n", (5467, 5484), True, 'import pandas as pd\n'), ((5514, 5532), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (5528, 5532), True, 'import numpy as np\n'), ((5537, 5552), 'random.seed', 'random.seed', (['(42)'], {}), '(42)\n', (5548, 5552), False, 'import random\n'), ((8008, 8060), 'subprocess.run', 'run', (['cmd'], {'stdout': 'PIPE', 'input': 'input', 'encoding': '"""ascii"""'}), "(cmd, stdout=PIPE, input=input, encoding='ascii')\n", (8011, 8060), False, 'from subprocess import run, PIPE\n'), ((8202, 8241), 'subprocess.run', 'run', (['cmd'], {'stdout': 'PIPE', 'encoding': '"""ascii"""'}), "(cmd, stdout=PIPE, encoding='ascii')\n", (8205, 8241), False, 'from subprocess import run, PIPE\n'), ((8246, 8259), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (8256, 8259), False, 'import time\n'), ((8506, 8570), 'pymarketstore.Params', 'pymkts.Params', (['[symbol]', 'timeframe', '"""TICK"""'], {'start': 'start', 'end': 'end'}), "([symbol], timeframe, 'TICK', start=start, end=end)\n", (8519, 8570), True, 'import pymarketstore as pymkts\n'), ((821, 864), 'pathlib.Path', 'pathlib.Path', (['"""/tmp/test_intermediate_data"""'], {}), "('/tmp/test_intermediate_data')\n", (833, 864), False, 'import pathlib\n'), ((5247, 5319), 'pytest.xfail', 'pytest.xfail', (['"""Marketstore client is not available, the test will fail."""'], {}), "('Marketstore client is not available, the test will fail.')\n", (5259, 5319), False, 'import pytest\n'), ((5753, 5809), 'pandas.to_datetime', 'pd.to_datetime', (['(total_ns // 10 ** 3)'], {'unit': '"""us"""', 'utc': '(True)'}), "(total_ns // 10 ** 3, unit='us', utc=True)\n", (5767, 5809), True, 'import pandas as pd\n'), ((10774, 10794), 'shutil.which', 'which', (['"""marketstore"""'], {}), "('marketstore')\n", (10779, 10794), False, 'from shutil import which\n'), ((738, 773), 'os.getenv', 'os.getenv', (['"""MARKETSTORE_PORT"""', '(5993)'], {}), "('MARKETSTORE_PORT', 5993)\n", (747, 773), False, 'import os\n'), ((8409, 8428), 'pandas.Timestamp', 'pd.Timestamp', (['start'], {}), '(start)\n', (8421, 8428), True, 'import pandas as pd\n'), ((8457, 8474), 'pandas.Timestamp', 'pd.Timestamp', (['end'], {}), '(end)\n', (8469, 8474), True, 'import pandas as pd\n'), ((8854, 8930), 'pandas.testing.assert_frame_equal', 'pd.testing.assert_frame_equal', (['df', 'processed_out_df'], {'check_less_precise': '(True)'}), '(df, processed_out_df, check_less_precise=True)\n', (8883, 8930), True, 'import pandas as pd\n'), ((6857, 6893), 'pandas.read_csv', 'pd.read_csv', (['csv_filename'], {'dtype': 'str'}), '(csv_filename, dtype=str)\n', (6868, 6893), True, 'import pandas as pd\n'), ((7123, 7159), 'pandas.read_csv', 'pd.read_csv', (['csv_filename'], {'dtype': 'str'}), '(csv_filename, dtype=str)\n', (7134, 7159), True, 'import pandas as pd\n')] |
from ..world_object import WorldObject, COLLIDER, TRIGGER
from unittest.mock import Mock
import unittest
class TestWorldObject(unittest.TestCase):
"""Test functionality of the ``WorldObject`` class."""
def test_register_collider(self):
"""Registering a collider creates a new object."""
geometry = Mock()
entry = WorldObject(geometry, COLLIDER)
self.assertEqual(geometry, entry.object)
self.assertEqual(COLLIDER, entry.type)
def test_register_trigger(self):
"""Registering a trigger creates a new object."""
geometry = Mock()
entry = WorldObject(geometry, TRIGGER)
self.assertEqual(geometry, entry.object)
self.assertEqual(TRIGGER, entry.type)
def test_register_invalid_method_raises_an_exception(self):
"""Registering for invalid type raises ValueError."""
with self.assertRaises(ValueError):
WorldObject(Mock(), 999)
| [
"unittest.mock.Mock"
] | [((325, 331), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (329, 331), False, 'from unittest.mock import Mock\n'), ((592, 598), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (596, 598), False, 'from unittest.mock import Mock\n'), ((937, 943), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (941, 943), False, 'from unittest.mock import Mock\n')] |
from flask_restx import Model, fields
eventModel = Model(
"Event",
{
"id": fields.String(
description="Event ID - League, Event, and Date of Event Concatenated with Spaces Removed",
readonly=True,
example="TestLeagueCarse2000-01-01",
),
"name": fields.String(
description="Event Name", required=True, example="<NAME>"
),
"date": fields.String(description="Date of the Event", example="2020-10-14"),
"website": fields.String(
description="Website for the event", example="https://example.com"
),
"organiser": fields.String(
description="Organiser of the Event", example="<NAME>"
),
"moreInformation": fields.String(
description="Extra Information About the Event",
example="Postponed from January",
),
"league": fields.String(
description="The League to Which the Event Belongs",
example="(not) Sprintelope 2020",
required=True,
),
"resultUploaded": fields.Boolean(
description="Have Results Been Uploaded", readonly=True, default=False
),
"results": fields.String(
description="Link to external results page for the event (for example, theoriginal results from club)",
example="https://example.com",
),
"winsplits": fields.String(
description="Link to a Winsplits page for the event",
example="https://example.com",
),
"routegadget": fields.String(
description="Link to a Routegadget page for the event",
example="https://example.com",
),
"userSubmittedResults": fields.Boolean(
description="Allow Users to Submit Results", default=False
),
"secondaryLeague": fields.String(
description="Name of a Second League the Results Are to Be Used In",
default=None,
example="Sprintelope",
),
"requiredInTotal": fields.Boolean(
description="Is this Event Always Included in the Total Points?",
default=False,
example=False,
),
"additionalSettings": fields.String(
description="Extra Settings for the Event", default=""
),
},
)
eventModelWithUploadKey = eventModel.inherit(
"Event With Upload Key",
{
"uploadKey": fields.String(
description="Secret required to upload the results for the event",
example="<KEY>",
),
},
)
| [
"flask_restx.fields.Boolean",
"flask_restx.fields.String"
] | [((93, 260), 'flask_restx.fields.String', 'fields.String', ([], {'description': '"""Event ID - League, Event, and Date of Event Concatenated with Spaces Removed"""', 'readonly': '(True)', 'example': '"""TestLeagueCarse2000-01-01"""'}), "(description=\n 'Event ID - League, Event, and Date of Event Concatenated with Spaces Removed'\n , readonly=True, example='TestLeagueCarse2000-01-01')\n", (106, 260), False, 'from flask_restx import Model, fields\n'), ((315, 387), 'flask_restx.fields.String', 'fields.String', ([], {'description': '"""Event Name"""', 'required': '(True)', 'example': '"""<NAME>"""'}), "(description='Event Name', required=True, example='<NAME>')\n", (328, 387), False, 'from flask_restx import Model, fields\n'), ((427, 495), 'flask_restx.fields.String', 'fields.String', ([], {'description': '"""Date of the Event"""', 'example': '"""2020-10-14"""'}), "(description='Date of the Event', example='2020-10-14')\n", (440, 495), False, 'from flask_restx import Model, fields\n'), ((516, 602), 'flask_restx.fields.String', 'fields.String', ([], {'description': '"""Website for the event"""', 'example': '"""https://example.com"""'}), "(description='Website for the event', example=\n 'https://example.com')\n", (529, 602), False, 'from flask_restx import Model, fields\n'), ((642, 711), 'flask_restx.fields.String', 'fields.String', ([], {'description': '"""Organiser of the Event"""', 'example': '"""<NAME>"""'}), "(description='Organiser of the Event', example='<NAME>')\n", (655, 711), False, 'from flask_restx import Model, fields\n'), ((762, 863), 'flask_restx.fields.String', 'fields.String', ([], {'description': '"""Extra Information About the Event"""', 'example': '"""Postponed from January"""'}), "(description='Extra Information About the Event', example=\n 'Postponed from January')\n", (775, 863), False, 'from flask_restx import Model, fields\n'), ((913, 1033), 'flask_restx.fields.String', 'fields.String', ([], {'description': '"""The League to Which the Event Belongs"""', 'example': '"""(not) Sprintelope 2020"""', 'required': '(True)'}), "(description='The League to Which the Event Belongs', example=\n '(not) Sprintelope 2020', required=True)\n", (926, 1033), False, 'from flask_restx import Model, fields\n'), ((1103, 1193), 'flask_restx.fields.Boolean', 'fields.Boolean', ([], {'description': '"""Have Results Been Uploaded"""', 'readonly': '(True)', 'default': '(False)'}), "(description='Have Results Been Uploaded', readonly=True,\n default=False)\n", (1117, 1193), False, 'from flask_restx import Model, fields\n'), ((1232, 1390), 'flask_restx.fields.String', 'fields.String', ([], {'description': '"""Link to external results page for the event (for example, theoriginal results from club)"""', 'example': '"""https://example.com"""'}), "(description=\n 'Link to external results page for the event (for example, theoriginal results from club)'\n , example='https://example.com')\n", (1245, 1390), False, 'from flask_restx import Model, fields\n'), ((1438, 1541), 'flask_restx.fields.String', 'fields.String', ([], {'description': '"""Link to a Winsplits page for the event"""', 'example': '"""https://example.com"""'}), "(description='Link to a Winsplits page for the event', example\n ='https://example.com')\n", (1451, 1541), False, 'from flask_restx import Model, fields\n'), ((1596, 1700), 'flask_restx.fields.String', 'fields.String', ([], {'description': '"""Link to a Routegadget page for the event"""', 'example': '"""https://example.com"""'}), "(description='Link to a Routegadget page for the event',\n example='https://example.com')\n", (1609, 1700), False, 'from flask_restx import Model, fields\n'), ((1765, 1839), 'flask_restx.fields.Boolean', 'fields.Boolean', ([], {'description': '"""Allow Users to Submit Results"""', 'default': '(False)'}), "(description='Allow Users to Submit Results', default=False)\n", (1779, 1839), False, 'from flask_restx import Model, fields\n'), ((1890, 2018), 'flask_restx.fields.String', 'fields.String', ([], {'description': '"""Name of a Second League the Results Are to Be Used In"""', 'default': 'None', 'example': '"""Sprintelope"""'}), "(description=\n 'Name of a Second League the Results Are to Be Used In', default=None,\n example='Sprintelope')\n", (1903, 2018), False, 'from flask_restx import Model, fields\n'), ((2085, 2204), 'flask_restx.fields.Boolean', 'fields.Boolean', ([], {'description': '"""Is this Event Always Included in the Total Points?"""', 'default': '(False)', 'example': '(False)'}), "(description=\n 'Is this Event Always Included in the Total Points?', default=False,\n example=False)\n", (2099, 2204), False, 'from flask_restx import Model, fields\n'), ((2274, 2343), 'flask_restx.fields.String', 'fields.String', ([], {'description': '"""Extra Settings for the Event"""', 'default': '""""""'}), "(description='Extra Settings for the Event', default='')\n", (2287, 2343), False, 'from flask_restx import Model, fields\n'), ((2479, 2581), 'flask_restx.fields.String', 'fields.String', ([], {'description': '"""Secret required to upload the results for the event"""', 'example': '"""<KEY>"""'}), "(description=\n 'Secret required to upload the results for the event', example='<KEY>')\n", (2492, 2581), False, 'from flask_restx import Model, fields\n')] |
from brownie import AdvancedCollectible, network
from scripts.helpful_scripts import get_camPos
from metadata.sample_metadata import metadata_template
from pathlib import Path
from scripts.upload_to_pinata import upload_to_pinata
import json
# import requests
def main():
advanced_collectible = AdvancedCollectible[-1]
number_of_advanced_collectibles = advanced_collectible.tokenCounter()
print(f"You have created {number_of_advanced_collectibles} collectibles!")
for token_id in range(number_of_advanced_collectibles):
camPos = get_camPos(advanced_collectible.tokenIdToCamPos(token_id))
metadata_file_path = (
f"./metadata/{network.show_active()}/{token_id}-{camPos}.json"
)
collectible_metadata = metadata_template
if Path(metadata_file_path).exists():
print(f"{metadata_file_path} already exists! Delete it to overwrite")
else:
print(f"Creating metadata file: {metadata_file_path}")
collectible_metadata["name"] = camPos
collectible_metadata["description"] = f"Teddy number {camPos}!"
image_path = "./img/" + camPos.lower() + ".png"
# image_uri = upload_to_ipfs(image_path)
filename = image_path.split("/")[-1:][0]
print("Uploading image to Pinata!")
image_uri = f"https://ipfs.io/ipfs/{upload_to_pinata(image_path)}?filename={filename}"
print(f"Image URI: {image_uri}")
collectible_metadata["image_uri"] = image_uri
with open(metadata_file_path, "w") as file:
json.dump(collectible_metadata, file)
print("Uploading JSON to Pinata!")
metadata_file_name = metadata_file_path.split("/")[-1:][0]
json_uri = f"https://ipfs.io/ipfs/{upload_to_pinata(metadata_file_path)}?filename={metadata_file_name}"
print(f"JSON URI: {json_uri}")
# def upload_to_ipfs(filepath):
# with Path(filepath).open("rb") as fp:
# image_binary = fp.read()
# ipfs_url = "http://127.0.0.1:5001"
# endpoint = "/api/v0/add"
# response = requests.post(ipfs_url + endpoint, files={"file": image_binary})
# ipfs_hash = response.json()["Hash"]
# filename = filepath.split("/")[-1:][0]
# image_uri = f"https://ipfs.io/ipfs/{ipfs_hash}?filename={filename}"
# print(image_uri)
# return image_uri
| [
"scripts.upload_to_pinata.upload_to_pinata",
"brownie.network.show_active",
"json.dump",
"pathlib.Path"
] | [((672, 693), 'brownie.network.show_active', 'network.show_active', ([], {}), '()\n', (691, 693), False, 'from brownie import AdvancedCollectible, network\n'), ((791, 815), 'pathlib.Path', 'Path', (['metadata_file_path'], {}), '(metadata_file_path)\n', (795, 815), False, 'from pathlib import Path\n'), ((1603, 1640), 'json.dump', 'json.dump', (['collectible_metadata', 'file'], {}), '(collectible_metadata, file)\n', (1612, 1640), False, 'import json\n'), ((1377, 1405), 'scripts.upload_to_pinata.upload_to_pinata', 'upload_to_pinata', (['image_path'], {}), '(image_path)\n', (1393, 1405), False, 'from scripts.upload_to_pinata import upload_to_pinata\n'), ((1806, 1842), 'scripts.upload_to_pinata.upload_to_pinata', 'upload_to_pinata', (['metadata_file_path'], {}), '(metadata_file_path)\n', (1822, 1842), False, 'from scripts.upload_to_pinata import upload_to_pinata\n')] |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import datetime
class Migration(migrations.Migration):
dependencies = [
('index', '0003_auto_20170416_2031'),
]
operations = [
migrations.AlterField(
model_name='staticcontent',
name='created',
field=models.DateTimeField(default=datetime.datetime(2017, 4, 16, 20, 32, 22, 79799), auto_now_add=True),
preserve_default=False,
),
migrations.AlterField(
model_name='staticcontent',
name='updated',
field=models.DateTimeField(default=datetime.datetime(2017, 4, 16, 20, 32, 26, 221448), auto_now=True),
preserve_default=False,
),
]
| [
"datetime.datetime"
] | [((403, 452), 'datetime.datetime', 'datetime.datetime', (['(2017)', '(4)', '(16)', '(20)', '(32)', '(22)', '(79799)'], {}), '(2017, 4, 16, 20, 32, 22, 79799)\n', (420, 452), False, 'import datetime\n'), ((667, 717), 'datetime.datetime', 'datetime.datetime', (['(2017)', '(4)', '(16)', '(20)', '(32)', '(26)', '(221448)'], {}), '(2017, 4, 16, 20, 32, 26, 221448)\n', (684, 717), False, 'import datetime\n')] |
import inspect
import os
from datetime import date
from itertools import chain
import sphinx_py3doc_enhanced_theme
from docutils import nodes
from docutils.parsers.rst import Directive
from docutils.parsers.rst.directives import unchanged
from docutils.statemachine import ViewList
from pkg_resources import get_distribution
from sphinx.util import nested_parse_with_titles
from sphinx.util.docstrings import prepare_docstring
from sphinx_autodoc_typehints import format_annotation
from sphinxarg.parser import parse_parser
release = get_distribution('toxn').version
extensions = ['sphinx.ext.autodoc',
'sphinx.ext.extlinks',
'sphinx.ext.intersphinx',
'sphinx.ext.viewcode',
'sphinxarg.ext',
'sphinx_autodoc_typehints']
project = u'toxn'
version = release
author = '<NAME>'
year = date.today().year
copyright = u'2017-{}, {}'.format(year, author)
master_doc = 'index'
source_suffix = '.rst'
pygments_style = 'sphinx'
html_theme = "theme"
html_theme_path = [sphinx_py3doc_enhanced_theme.get_html_theme_path(), "."]
html_theme_options = {
'githuburl': 'https://github.com/gaborbernat/toxn',
'appendcss': '',
}
html_logo = 'theme/static/tox.png'
html_favicon = 'theme/static/toxfavi.ico'
tls_cacerts = os.getenv('SSL_CERT_FILE') # we don't care here about the validity of certificates
linkcheck_timeout = 30
intersphinx_mapping = {'https://docs.python.org/3': None}
autoclass_content = 'class'
autodoc_default_flags = ["members", "undoc-members", "inherited-members"]
def process_sig(app, what, name, obj, options, signature, return_annotation):
return '', return_annotation
class TableAutoClassDoc(Directive):
has_content = True
required_arguments = 2
def run(self):
of_class = self.arguments[0].split('.')
class_type = getattr(__import__('.'.join(of_class[:-1]), fromlist=[of_class[-1]]), of_class[-1])
def predicate(a):
return isinstance(a, property)
class_members = inspect.getmembers(class_type, predicate=predicate)
return_types = [inspect.signature(p.fget).return_annotation for _, p in class_members]
docs = [inspect.getdoc(p) or '' for _, p in class_members]
table = nodes.table()
t_group = nodes.tgroup(cols=4)
t_group += nodes.colspec(colwidth=1)
t_group += nodes.colspec(colwidth=1)
t_group += nodes.colspec(colwidth=1)
t_group += nodes.colspec(colwidth=10)
# header
t_group += nodes.thead('', nodes.row('', *[nodes.entry('', nodes.line(text=c)) for c in
["field", "type", "note", "description"]]))
t_body = nodes.tbody()
for (name, _), return_type, doc in zip(class_members, return_types, docs):
doc_l = doc.split('\n')
location = next((i for i in doc_l if i.startswith(':note:')), '')[len(':note:'):]
doc_stripped = '\n'.join(i for i in doc_l if not i.startswith(':note:'))
doc_stripped_node = self.render_content(doc_stripped)
return_type_node = self.render_content(format_annotation(return_type))
ref_key = '{}.{}'.format(self.arguments[1], name)
name_node = nodes.reference('', name, refid=ref_key)
ref = nodes.paragraph('', '', name_node)
t_body += nodes.row(name,
nodes.entry('', ref),
nodes.entry('', return_type_node),
nodes.entry('', nodes.literal(text=location)),
nodes.entry('', doc_stripped_node),
ids=[ref_key])
t_group += t_body
table += t_group
return [table]
def render_content(self, doc_stripped):
doc_stripped_view = ViewList(prepare_docstring(doc_stripped))
doc_stripped_node = nodes.container()
nested_parse_with_titles(self.state, doc_stripped_view, doc_stripped_node)
return doc_stripped_node
class Cli(Directive):
has_content = True
option_spec = dict(module=unchanged, func=unchanged,
prog=unchanged,
noepilog=unchanged, nodescription=unchanged, )
def run(self):
module_name, attr_name, prog = self.options['module'], self.options['func'], self.options['prog']
parser = getattr(__import__(module_name, fromlist=[attr_name]), attr_name)()
result = parse_parser(parser)
table = nodes.table()
t_group = nodes.tgroup(cols=4)
t_group += nodes.colspec(colwidth=1.5)
t_group += nodes.colspec(colwidth=1.5)
t_group += nodes.colspec(colwidth=8)
# header
t_group += nodes.thead('', nodes.row('', *[nodes.entry('', nodes.line(text=c)) for c in
["name", "default", "help"]]))
# rows
t_body = nodes.tbody()
for option in chain.from_iterable(g['options'] for g in result['action_groups']):
names, default, help_text, choice = option['name'], option['default'], option['help'], option.get('choices')
refs, name_nodes = [], []
ref = nodes.paragraph('', '')
first = True
for name in names:
if not first:
ref.append(nodes.Text(', '))
else:
first = False
ref_key = '{} {}'.format(prog, name)
ref_node = nodes.reference('', '', refid=ref_key)
ref_node += nodes.literal(text=name)
ref += ref_node
refs.append(ref_key)
help_body = nodes.paragraph('', '', nodes.Text(help_text))
if choice is not None:
help_body += nodes.Text('; one of: ')
help_body += nodes.literal(text=', '.join(choice))
if default is None:
default_body = nodes.paragraph('', text='')
else:
if default and default[0] == '"' and default[-1] == '"':
default = default[1:-1]
default_body = nodes.literal(text=default)
t_body += nodes.row('',
nodes.entry('', ref),
nodes.entry('', default_body),
nodes.entry('', help_body),
ids=refs)
t_group += t_body
table += t_group
return [nodes.literal_block(text=result['usage']),
table]
def literal_data(rawtext, app, type, slug, options):
"""Create a link to a BitBucket resource."""
of_class = type.split('.')
data = getattr(__import__('.'.join(of_class[:-1]), fromlist=[of_class[-1]]), of_class[-1])
return [nodes.literal('', text=','.join(data))], []
def setup(app):
app.add_directive('auto_doc_class_table', TableAutoClassDoc)
app.add_directive('table_cli', Cli)
app.add_role('literal_data', literal_data)
| [
"docutils.nodes.literal",
"datetime.date.today",
"docutils.nodes.paragraph",
"docutils.nodes.colspec",
"pkg_resources.get_distribution",
"inspect.getmembers",
"sphinx.util.docstrings.prepare_docstring",
"docutils.nodes.entry",
"docutils.nodes.tbody",
"docutils.nodes.container",
"inspect.signatur... | [((1286, 1312), 'os.getenv', 'os.getenv', (['"""SSL_CERT_FILE"""'], {}), "('SSL_CERT_FILE')\n", (1295, 1312), False, 'import os\n'), ((536, 560), 'pkg_resources.get_distribution', 'get_distribution', (['"""toxn"""'], {}), "('toxn')\n", (552, 560), False, 'from pkg_resources import get_distribution\n'), ((856, 868), 'datetime.date.today', 'date.today', ([], {}), '()\n', (866, 868), False, 'from datetime import date\n'), ((1035, 1085), 'sphinx_py3doc_enhanced_theme.get_html_theme_path', 'sphinx_py3doc_enhanced_theme.get_html_theme_path', ([], {}), '()\n', (1083, 1085), False, 'import sphinx_py3doc_enhanced_theme\n'), ((2023, 2074), 'inspect.getmembers', 'inspect.getmembers', (['class_type'], {'predicate': 'predicate'}), '(class_type, predicate=predicate)\n', (2041, 2074), False, 'import inspect\n'), ((2254, 2267), 'docutils.nodes.table', 'nodes.table', ([], {}), '()\n', (2265, 2267), False, 'from docutils import nodes\n'), ((2286, 2306), 'docutils.nodes.tgroup', 'nodes.tgroup', ([], {'cols': '(4)'}), '(cols=4)\n', (2298, 2306), False, 'from docutils import nodes\n'), ((2327, 2352), 'docutils.nodes.colspec', 'nodes.colspec', ([], {'colwidth': '(1)'}), '(colwidth=1)\n', (2340, 2352), False, 'from docutils import nodes\n'), ((2372, 2397), 'docutils.nodes.colspec', 'nodes.colspec', ([], {'colwidth': '(1)'}), '(colwidth=1)\n', (2385, 2397), False, 'from docutils import nodes\n'), ((2417, 2442), 'docutils.nodes.colspec', 'nodes.colspec', ([], {'colwidth': '(1)'}), '(colwidth=1)\n', (2430, 2442), False, 'from docutils import nodes\n'), ((2462, 2488), 'docutils.nodes.colspec', 'nodes.colspec', ([], {'colwidth': '(10)'}), '(colwidth=10)\n', (2475, 2488), False, 'from docutils import nodes\n'), ((2716, 2729), 'docutils.nodes.tbody', 'nodes.tbody', ([], {}), '()\n', (2727, 2729), False, 'from docutils import nodes\n'), ((3932, 3949), 'docutils.nodes.container', 'nodes.container', ([], {}), '()\n', (3947, 3949), False, 'from docutils import nodes\n'), ((3958, 4032), 'sphinx.util.nested_parse_with_titles', 'nested_parse_with_titles', (['self.state', 'doc_stripped_view', 'doc_stripped_node'], {}), '(self.state, doc_stripped_view, doc_stripped_node)\n', (3982, 4032), False, 'from sphinx.util import nested_parse_with_titles\n'), ((4507, 4527), 'sphinxarg.parser.parse_parser', 'parse_parser', (['parser'], {}), '(parser)\n', (4519, 4527), False, 'from sphinxarg.parser import parse_parser\n'), ((4545, 4558), 'docutils.nodes.table', 'nodes.table', ([], {}), '()\n', (4556, 4558), False, 'from docutils import nodes\n'), ((4577, 4597), 'docutils.nodes.tgroup', 'nodes.tgroup', ([], {'cols': '(4)'}), '(cols=4)\n', (4589, 4597), False, 'from docutils import nodes\n'), ((4618, 4645), 'docutils.nodes.colspec', 'nodes.colspec', ([], {'colwidth': '(1.5)'}), '(colwidth=1.5)\n', (4631, 4645), False, 'from docutils import nodes\n'), ((4665, 4692), 'docutils.nodes.colspec', 'nodes.colspec', ([], {'colwidth': '(1.5)'}), '(colwidth=1.5)\n', (4678, 4692), False, 'from docutils import nodes\n'), ((4712, 4737), 'docutils.nodes.colspec', 'nodes.colspec', ([], {'colwidth': '(8)'}), '(colwidth=8)\n', (4725, 4737), False, 'from docutils import nodes\n'), ((4967, 4980), 'docutils.nodes.tbody', 'nodes.tbody', ([], {}), '()\n', (4978, 4980), False, 'from docutils import nodes\n'), ((5003, 5069), 'itertools.chain.from_iterable', 'chain.from_iterable', (["(g['options'] for g in result['action_groups'])"], {}), "(g['options'] for g in result['action_groups'])\n", (5022, 5069), False, 'from itertools import chain\n'), ((3265, 3305), 'docutils.nodes.reference', 'nodes.reference', (['""""""', 'name'], {'refid': 'ref_key'}), "('', name, refid=ref_key)\n", (3280, 3305), False, 'from docutils import nodes\n'), ((3324, 3358), 'docutils.nodes.paragraph', 'nodes.paragraph', (['""""""', '""""""', 'name_node'], {}), "('', '', name_node)\n", (3339, 3358), False, 'from docutils import nodes\n'), ((3871, 3902), 'sphinx.util.docstrings.prepare_docstring', 'prepare_docstring', (['doc_stripped'], {}), '(doc_stripped)\n', (3888, 3902), False, 'from sphinx.util.docstrings import prepare_docstring\n'), ((5249, 5272), 'docutils.nodes.paragraph', 'nodes.paragraph', (['""""""', '""""""'], {}), "('', '')\n", (5264, 5272), False, 'from docutils import nodes\n'), ((6545, 6586), 'docutils.nodes.literal_block', 'nodes.literal_block', ([], {'text': "result['usage']"}), "(text=result['usage'])\n", (6564, 6586), False, 'from docutils import nodes\n'), ((2099, 2124), 'inspect.signature', 'inspect.signature', (['p.fget'], {}), '(p.fget)\n', (2116, 2124), False, 'import inspect\n'), ((2186, 2203), 'inspect.getdoc', 'inspect.getdoc', (['p'], {}), '(p)\n', (2200, 2203), False, 'import inspect\n'), ((3146, 3176), 'sphinx_autodoc_typehints.format_annotation', 'format_annotation', (['return_type'], {}), '(return_type)\n', (3163, 3176), False, 'from sphinx_autodoc_typehints import format_annotation\n'), ((3430, 3450), 'docutils.nodes.entry', 'nodes.entry', (['""""""', 'ref'], {}), "('', ref)\n", (3441, 3450), False, 'from docutils import nodes\n'), ((3484, 3517), 'docutils.nodes.entry', 'nodes.entry', (['""""""', 'return_type_node'], {}), "('', return_type_node)\n", (3495, 3517), False, 'from docutils import nodes\n'), ((3630, 3664), 'docutils.nodes.entry', 'nodes.entry', (['""""""', 'doc_stripped_node'], {}), "('', doc_stripped_node)\n", (3641, 3664), False, 'from docutils import nodes\n'), ((5544, 5582), 'docutils.nodes.reference', 'nodes.reference', (['""""""', '""""""'], {'refid': 'ref_key'}), "('', '', refid=ref_key)\n", (5559, 5582), False, 'from docutils import nodes\n'), ((5611, 5635), 'docutils.nodes.literal', 'nodes.literal', ([], {'text': 'name'}), '(text=name)\n', (5624, 5635), False, 'from docutils import nodes\n'), ((5754, 5775), 'docutils.nodes.Text', 'nodes.Text', (['help_text'], {}), '(help_text)\n', (5764, 5775), False, 'from docutils import nodes\n'), ((5841, 5865), 'docutils.nodes.Text', 'nodes.Text', (['"""; one of: """'], {}), "('; one of: ')\n", (5851, 5865), False, 'from docutils import nodes\n'), ((5997, 6025), 'docutils.nodes.paragraph', 'nodes.paragraph', (['""""""'], {'text': '""""""'}), "('', text='')\n", (6012, 6025), False, 'from docutils import nodes\n'), ((6192, 6219), 'docutils.nodes.literal', 'nodes.literal', ([], {'text': 'default'}), '(text=default)\n', (6205, 6219), False, 'from docutils import nodes\n'), ((6289, 6309), 'docutils.nodes.entry', 'nodes.entry', (['""""""', 'ref'], {}), "('', ref)\n", (6300, 6309), False, 'from docutils import nodes\n'), ((6343, 6372), 'docutils.nodes.entry', 'nodes.entry', (['""""""', 'default_body'], {}), "('', default_body)\n", (6354, 6372), False, 'from docutils import nodes\n'), ((6406, 6432), 'docutils.nodes.entry', 'nodes.entry', (['""""""', 'help_body'], {}), "('', help_body)\n", (6417, 6432), False, 'from docutils import nodes\n'), ((3567, 3595), 'docutils.nodes.literal', 'nodes.literal', ([], {'text': 'location'}), '(text=location)\n', (3580, 3595), False, 'from docutils import nodes\n'), ((5390, 5406), 'docutils.nodes.Text', 'nodes.Text', (['""", """'], {}), "(', ')\n", (5400, 5406), False, 'from docutils import nodes\n'), ((2574, 2592), 'docutils.nodes.line', 'nodes.line', ([], {'text': 'c'}), '(text=c)\n', (2584, 2592), False, 'from docutils import nodes\n'), ((4823, 4841), 'docutils.nodes.line', 'nodes.line', ([], {'text': 'c'}), '(text=c)\n', (4833, 4841), False, 'from docutils import nodes\n')] |
from distutils.core import setup
import glob
bin_files = glob.glob("bin/*.py") + glob.glob("bin/*.txt")
# The main call
setup(name='despyfitsutils',
version='1.0.1',
license="GPL",
description="A set of handy Python fitsfile-related utility functions for DESDM",
author="<NAME>, <NAME>",
author_email="<EMAIL>",
packages=['despyfitsutils'],
package_dir={'': 'python'},
scripts=bin_files,
data_files=[('ups', ['ups/despyfitsutils.table']), ]
)
| [
"distutils.core.setup",
"glob.glob"
] | [((122, 459), 'distutils.core.setup', 'setup', ([], {'name': '"""despyfitsutils"""', 'version': '"""1.0.1"""', 'license': '"""GPL"""', 'description': '"""A set of handy Python fitsfile-related utility functions for DESDM"""', 'author': '"""<NAME>, <NAME>"""', 'author_email': '"""<EMAIL>"""', 'packages': "['despyfitsutils']", 'package_dir': "{'': 'python'}", 'scripts': 'bin_files', 'data_files': "[('ups', ['ups/despyfitsutils.table'])]"}), "(name='despyfitsutils', version='1.0.1', license='GPL', description=\n 'A set of handy Python fitsfile-related utility functions for DESDM',\n author='<NAME>, <NAME>', author_email='<EMAIL>', packages=[\n 'despyfitsutils'], package_dir={'': 'python'}, scripts=bin_files,\n data_files=[('ups', ['ups/despyfitsutils.table'])])\n", (127, 459), False, 'from distutils.core import setup\n'), ((58, 79), 'glob.glob', 'glob.glob', (['"""bin/*.py"""'], {}), "('bin/*.py')\n", (67, 79), False, 'import glob\n'), ((82, 104), 'glob.glob', 'glob.glob', (['"""bin/*.txt"""'], {}), "('bin/*.txt')\n", (91, 104), False, 'import glob\n')] |
import unittest
from os import path
from glob import glob
def sensor_stypes(sensor):
'''
STYPE and lenght infos for each measurement for each sensor type.
'''
kinds = {
"ers_co2": {
0x01: 2,
0x02: 1,
0x04: 2,
0x05: 1,
0x06: 2,
0x07: 2
},
"ers_sound" : {
0x01: 2,
0x02: 1,
0x04: 2,
0x05: 1,
0x07: 2,
0x15: 2
},
"ers_eye": {
0x01: 2,
0x02: 1,
0x04: 2,
0x05: 1,
0x07: 2,
0x11: 1,
0x13: 65
},
"ems_door" : {
0x03: 3,
0x07: 2,
0x0a: 2,
0x0b: 4,
0x0d: 1,
0x0f: 1 # not in docs
},
"ems_desk" : {
0x01: 2,
0x02: 1,
0x03: 3,
0x07: 2,
0x10: 4, # not in docs
0x11: 1
},
"elt_2hp" : {
0x01: 2,
0x02: 1,
0x03: 3, #not in docs
0x07: 2,
0x08: 2,
0x0a: 2,
0x0b: 4,
0x0c: 2,
0x0d: 1,
0x0e: 2,
0x0f: 1,
0x10: 4,
0x12: 1,
0x14: 4,
0x16: 2,
0x17: 4,
0x18: 2,
0x19: 2,
0x1a: 1
}
}
return kinds[sensor]
def bin_to_original(dir):
'''
Forms a list of integers from a file of binary values.
Drops bytes that describe the lenght of the upcoming value
as they are not included in the original payload.
'''
payload = []
with open(dir, "rb") as binary:
length_byte = 1 + int.from_bytes(binary.read(1), byteorder="big")
byte = 1 # Insert true value for first iteration
while byte:
# Add bytes to list as integers
if length_byte > 0:
byte = binary.read(1)
payload.append((int.from_bytes(byte, byteorder="big")))
length_byte -= 1 # Keep track of when next length byte is coming
else:
# drop lenght byte of upcoming value
length_byte = 1 + int.from_bytes(binary.read(1), byteorder="big")
return payload[:-1] # exclude file ending zero
def test_payload(payload, kind):
'''
Test if payload formatting is correct.
'''
j = 0 # keep track of the index of the payload
stypes = sensor_stypes(kind)
while len(payload) > j:
stype = payload[j]
length = stypes.pop(stype) # unvalid stype causes failure
j = j + length + 1 # move index to next STYPE
class TestBinary(unittest.TestCase):
'''
Tests if the payload is in valid format.
Does not test the values itself.
'''
def test_files(self):
dirs = glob("assets/binary/*") # get all payload directories
self.assertNotEqual(len(dirs), 0, msg="There should be payload files")
for dir in dirs:
filepath, kind = path.split(dir)
# get all files from each directory
files = glob(filepath + "/" + kind + "/*")
for file in files:
filepath, filename = path.split(file)
with self.subTest(file=filename):
payload = bin_to_original(filepath + "/" + filename)
test_payload(payload, kind)
if __name__ == "__main__":
unittest.main()
| [
"os.path.split",
"glob.glob",
"unittest.main"
] | [((3550, 3565), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3563, 3565), False, 'import unittest\n'), ((2932, 2955), 'glob.glob', 'glob', (['"""assets/binary/*"""'], {}), "('assets/binary/*')\n", (2936, 2955), False, 'from glob import glob\n'), ((3129, 3144), 'os.path.split', 'path.split', (['dir'], {}), '(dir)\n', (3139, 3144), False, 'from os import path\n'), ((3213, 3247), 'glob.glob', 'glob', (["(filepath + '/' + kind + '/*')"], {}), "(filepath + '/' + kind + '/*')\n", (3217, 3247), False, 'from glob import glob\n'), ((3329, 3345), 'os.path.split', 'path.split', (['file'], {}), '(file)\n', (3339, 3345), False, 'from os import path\n')] |
from hypothesis import given, note
from hypothesis.strategies import booleans, floats, from_type
import numpy as np
from pysketcher import Angle
from tests.utils import given_inferred
class TestAngle:
@given_inferred
def test_range(self, x: Angle):
assert -np.pi < x
assert x <= np.pi
@given_inferred
def test_equality(self, x: float):
if -np.pi < x < np.pi:
assert x == Angle(x)
else:
assert Angle(x) == Angle(x)
@given_inferred
def test_addition(self, a: Angle, b: Angle):
c = a + b
assert type(c) == Angle
assert -np.pi <= c
assert c <= np.pi
@given_inferred
def test_subtraction(self, a: Angle, b: Angle):
c = a - b
assert type(c) == Angle
assert -np.pi <= c
assert c <= np.pi
@given_inferred
def test_multiplication(self, a: Angle, b: float):
c = a * b
assert type(c) == Angle
assert c <= np.pi
assert -np.pi < c
@given(from_type(Angle), floats(min_value=1e-6, max_value=1e6), booleans())
def test_division(self, a: Angle, b: float, negate: bool):
if negate:
b = -b
c = a / b
note(c)
assert type(c) == Angle
assert -np.pi <= c
assert c <= np.pi
| [
"hypothesis.note",
"hypothesis.strategies.booleans",
"hypothesis.strategies.from_type",
"pysketcher.Angle",
"hypothesis.strategies.floats"
] | [((1225, 1232), 'hypothesis.note', 'note', (['c'], {}), '(c)\n', (1229, 1232), False, 'from hypothesis import given, note\n'), ((1029, 1045), 'hypothesis.strategies.from_type', 'from_type', (['Angle'], {}), '(Angle)\n', (1038, 1045), False, 'from hypothesis.strategies import booleans, floats, from_type\n'), ((1047, 1091), 'hypothesis.strategies.floats', 'floats', ([], {'min_value': '(1e-06)', 'max_value': '(1000000.0)'}), '(min_value=1e-06, max_value=1000000.0)\n', (1053, 1091), False, 'from hypothesis.strategies import booleans, floats, from_type\n'), ((1086, 1096), 'hypothesis.strategies.booleans', 'booleans', ([], {}), '()\n', (1094, 1096), False, 'from hypothesis.strategies import booleans, floats, from_type\n'), ((427, 435), 'pysketcher.Angle', 'Angle', (['x'], {}), '(x)\n', (432, 435), False, 'from pysketcher import Angle\n'), ((469, 477), 'pysketcher.Angle', 'Angle', (['x'], {}), '(x)\n', (474, 477), False, 'from pysketcher import Angle\n'), ((481, 489), 'pysketcher.Angle', 'Angle', (['x'], {}), '(x)\n', (486, 489), False, 'from pysketcher import Angle\n')] |
import random
from PIL import Image, ImageFont, ImageDraw, ImageFilter
def get_random_color():
return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
def validate_picture(length):
msg = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890'
width = 130
height = 50
im = Image.new('RGB', (width, height), color=get_random_color())
# 创建字体对象
font = ImageFont.truetype('arial.ttf', 40)
# 创建ImageDraw对象
draw = ImageDraw.Draw(im)
s = ''
for i in range(length):
m = random.choice(msg)
s += m
draw.text((5 + random.randint(4, 7) + 20 * i, 5 + random.randint(3, 7)), text=m, fill=get_random_color(),
font=font)
# draw.text((13, 5), text=s, fill=get_random_color(), font=font)
# 绘制干扰线
for n in range(8):
x1 = random.randint(0, width / 2)
y1 = random.randint(0, height / 2)
x2 = random.randint(0, width)
y2 = random.randint(height / 2, height)
draw.line(((x1, y1), (x2, y2)), fill=get_random_color(), width=1)
# 添加滤镜
im = im.filter(ImageFilter.EDGE_ENHANCE)
# with open("validCode.png", "wb") as f:
# im.save(f, "png")
return im, s
if __name__ == '__main__':
validate_picture(4)
| [
"random.choice",
"PIL.ImageFont.truetype",
"PIL.ImageDraw.Draw",
"random.randint"
] | [((429, 464), 'PIL.ImageFont.truetype', 'ImageFont.truetype', (['"""arial.ttf"""', '(40)'], {}), "('arial.ttf', 40)\n", (447, 464), False, 'from PIL import Image, ImageFont, ImageDraw, ImageFilter\n'), ((498, 516), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['im'], {}), '(im)\n', (512, 516), False, 'from PIL import Image, ImageFont, ImageDraw, ImageFilter\n'), ((116, 138), 'random.randint', 'random.randint', (['(0)', '(255)'], {}), '(0, 255)\n', (130, 138), False, 'import random\n'), ((140, 162), 'random.randint', 'random.randint', (['(0)', '(255)'], {}), '(0, 255)\n', (154, 162), False, 'import random\n'), ((164, 186), 'random.randint', 'random.randint', (['(0)', '(255)'], {}), '(0, 255)\n', (178, 186), False, 'import random\n'), ((571, 589), 'random.choice', 'random.choice', (['msg'], {}), '(msg)\n', (584, 589), False, 'import random\n'), ((874, 902), 'random.randint', 'random.randint', (['(0)', '(width / 2)'], {}), '(0, width / 2)\n', (888, 902), False, 'import random\n'), ((917, 946), 'random.randint', 'random.randint', (['(0)', '(height / 2)'], {}), '(0, height / 2)\n', (931, 946), False, 'import random\n'), ((963, 987), 'random.randint', 'random.randint', (['(0)', 'width'], {}), '(0, width)\n', (977, 987), False, 'import random\n'), ((1002, 1036), 'random.randint', 'random.randint', (['(height / 2)', 'height'], {}), '(height / 2, height)\n', (1016, 1036), False, 'import random\n'), ((665, 685), 'random.randint', 'random.randint', (['(3)', '(7)'], {}), '(3, 7)\n', (679, 685), False, 'import random\n'), ((630, 650), 'random.randint', 'random.randint', (['(4)', '(7)'], {}), '(4, 7)\n', (644, 650), False, 'import random\n')] |
from sys import argv, stderr
from dependencies import Game
class ToManyPlayersError(Exception):
pass
def read_args():
arguments = argv[1:]
try:
players = abs(int(arguments[0]))
if players > 7:
raise ToManyPlayersError
return players
except IndexError:
stderr.write("python3 main.py NUMBER_OF_PLAYERS\n")
exit(-1)
except ToManyPlayersError:
stderr.write("Number of players between 1 to 7\n")
exit(-1)
def main():
number_of_players = read_args()
game_session = Game(number_of_players)
while "y" in input("\033[1;34mDo you want to play?[y/n]\033[0;0m").lower():
game_session.start()
print("Ok! Good bye!!")
if __name__ == '__main__':
main()
| [
"dependencies.Game",
"sys.stderr.write"
] | [((561, 584), 'dependencies.Game', 'Game', (['number_of_players'], {}), '(number_of_players)\n', (565, 584), False, 'from dependencies import Game\n'), ((316, 367), 'sys.stderr.write', 'stderr.write', (['"""python3 main.py NUMBER_OF_PLAYERS\n"""'], {}), "('python3 main.py NUMBER_OF_PLAYERS\\n')\n", (328, 367), False, 'from sys import argv, stderr\n'), ((424, 474), 'sys.stderr.write', 'stderr.write', (['"""Number of players between 1 to 7\n"""'], {}), "('Number of players between 1 to 7\\n')\n", (436, 474), False, 'from sys import argv, stderr\n')] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.