code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import os
import glob
from PIL import Image, ImageDraw
# ground truth directory
gt_text_dir = './DB/PLATE/gt' #"./DB/ICDAR2015/test/gt" #"./DB/ICDAR2015/train/gt"
# original images directory
image_dir = './DB/PLATE/*.jpg'#"./DB/ICDAR2015/test/*.jpg" #"./DB/ICDAR2015/train/*.jpg"
imgDirs = []
imgLists = glob.glob(image_dir)
# where to save the images with ground truth boxes
imgs_save_dir = './DB/PLATE/gt_labeled' #"./DB/ICDAR2015/labeledTestWithGT" #"./DB/ICDAR2015/labeledTrainWithGt"
if not os.path.exists(imgs_save_dir):
os.mkdir(imgs_save_dir)
for item in imgLists:
imgDirs.append(item)
for img_dir in imgDirs:
img = Image.open(img_dir)
dr = ImageDraw.Draw(img)
# extract the basename of the image address and split it from its suffix.
img_basename = os.path.basename(img_dir)
(img_name, suffix) = os.path.splitext(img_basename)
# open the ground truth text file use the basename of the associated image
img_gt_text_name = "gt_" + img_name + ".txt"
print(img_gt_text_name)
# read the gt txt, split as line to constitute a list.
bf = open(os.path.join(gt_text_dir, img_gt_text_name), encoding='utf-8-sig').read().splitlines()
for idx in bf:
rect = []
spt = idx.split(',')
rect.append(float(spt[0]) * img.size[0])
rect.append(float(spt[1]) * img.size[1])
rect.append(float(spt[2]) * img.size[0])
rect.append(float(spt[3]) * img.size[1])
rect.append(float(spt[4]) * img.size[0])
rect.append(float(spt[5]) * img.size[1])
rect.append(float(spt[6]) * img.size[0])
rect.append(float(spt[7]) * img.size[1])
# draw the polygon with (x_1, y_1, x_2, y_2, x_3, y_3, x_4, y_4)
dr.polygon((rect[0], rect[1], rect[2], rect[3], rect[4], rect[5], rect[6], rect[7]), outline="red")
# save the gt labeled image
img.save(os.path.join(imgs_save_dir, img_basename))
| [
"os.path.exists",
"PIL.Image.open",
"os.path.splitext",
"os.path.join",
"PIL.ImageDraw.Draw",
"os.mkdir",
"os.path.basename",
"glob.glob"
] | [((306, 326), 'glob.glob', 'glob.glob', (['image_dir'], {}), '(image_dir)\n', (315, 326), False, 'import glob\n'), ((499, 528), 'os.path.exists', 'os.path.exists', (['imgs_save_dir'], {}), '(imgs_save_dir)\n', (513, 528), False, 'import os\n'), ((531, 554), 'os.mkdir', 'os.mkdir', (['imgs_save_dir'], {}), '(imgs_save_dir)\n', (539, 554), False, 'import os\n'), ((632, 651), 'PIL.Image.open', 'Image.open', (['img_dir'], {}), '(img_dir)\n', (642, 651), False, 'from PIL import Image, ImageDraw\n'), ((658, 677), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['img'], {}), '(img)\n', (672, 677), False, 'from PIL import Image, ImageDraw\n'), ((769, 794), 'os.path.basename', 'os.path.basename', (['img_dir'], {}), '(img_dir)\n', (785, 794), False, 'import os\n'), ((817, 847), 'os.path.splitext', 'os.path.splitext', (['img_basename'], {}), '(img_basename)\n', (833, 847), False, 'import os\n'), ((1755, 1796), 'os.path.join', 'os.path.join', (['imgs_save_dir', 'img_basename'], {}), '(imgs_save_dir, img_basename)\n', (1767, 1796), False, 'import os\n'), ((1062, 1105), 'os.path.join', 'os.path.join', (['gt_text_dir', 'img_gt_text_name'], {}), '(gt_text_dir, img_gt_text_name)\n', (1074, 1105), False, 'import os\n')] |
### hack to avoid hardlinking through python setup.py sdist - doesn't work on vboxfs
import os
del os.link
###
from distutils.core import setup, Extension
#
# https://docs.python.org/3.3/extending/building.html#building
#
module1 = Extension('ipcbridge',
define_macros = [('MAJOR_VERSION', '0'),
('MINOR_VERSION', '0.5')],
include_dirs = ['/usr/include'],
libraries = ['pthread'],
library_dirs = ['/usr/lib'],
sources = ['ipcbridge.c'])
setup( name = 'IpcBridge',
version = '0.0.5',
description = 'python IPC bridge module',
author = '<NAME>',
author_email = '<EMAIL>',
url = 'https://github.com/johannesdo/ipcbridge',
long_description = '''
python IPC bridge module.
''',
ext_modules = [module1])
| [
"distutils.core.Extension",
"distutils.core.setup"
] | [((235, 439), 'distutils.core.Extension', 'Extension', (['"""ipcbridge"""'], {'define_macros': "[('MAJOR_VERSION', '0'), ('MINOR_VERSION', '0.5')]", 'include_dirs': "['/usr/include']", 'libraries': "['pthread']", 'library_dirs': "['/usr/lib']", 'sources': "['ipcbridge.c']"}), "('ipcbridge', define_macros=[('MAJOR_VERSION', '0'), (\n 'MINOR_VERSION', '0.5')], include_dirs=['/usr/include'], libraries=[\n 'pthread'], library_dirs=['/usr/lib'], sources=['ipcbridge.c'])\n", (244, 439), False, 'from distutils.core import setup, Extension\n'), ((578, 835), 'distutils.core.setup', 'setup', ([], {'name': '"""IpcBridge"""', 'version': '"""0.0.5"""', 'description': '"""python IPC bridge module"""', 'author': '"""<NAME>"""', 'author_email': '"""<EMAIL>"""', 'url': '"""https://github.com/johannesdo/ipcbridge"""', 'long_description': '"""\npython IPC bridge module.\n"""', 'ext_modules': '[module1]'}), '(name=\'IpcBridge\', version=\'0.0.5\', description=\n \'python IPC bridge module\', author=\'<NAME>\', author_email=\'<EMAIL>\',\n url=\'https://github.com/johannesdo/ipcbridge\', long_description=\n """\npython IPC bridge module.\n""", ext_modules=[module1])\n', (583, 835), False, 'from distutils.core import setup, Extension\n')] |
import geoalchemy2
from sqlalchemy import String, Column, DateTime, ARRAY, TEXT, Integer, ForeignKey, Boolean, Numeric
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.dialects.postgresql import UUID, JSONB
from api.db.base_class import BaseTable, BaseAudit
from api.v1.user.db_models import User
import uuid
class GeneratedWatershed(BaseAudit):
__tablename__ = 'generated_watershed'
__table_args__ = {'schema': 'public'}
generated_watershed_id = Column(Integer, primary_key=True)
wally_watershed_id = Column(String, comment='WALLY watershed identifier used to recreate watersheds. '
'The format is the upstream delineation method followed by '
'the POI encoded as base64.')
processing_time = Column(
Numeric, comment='How long it took to calculate this watershed.')
upstream_method = Column(
String, comment='The method used to calculate this watershed e.g. FWA+UPSTREAM, DEM+FWA etc.')
is_near_border = Column(Boolean, comment='Indicates whether this watershed was determined to be near a border. '
'This affects how it was generated and refined.')
dem_source = Column(
String, comment='The name of the Digital Elevation Model used, e.g. CDEM or SRTM', nullable=True)
click_point = Column(
geoalchemy2.types.Geometry(
geometry_type='POINT', srid=4326), comment='The coordinates of the original click point.')
snapped_point = Column(
geoalchemy2.types.Geometry(geometry_type='POINT', srid=4326),
comment='The coordinates used for delineation after snapping to a Flow Accumulation raster stream line.')
area_sqm = Column(Numeric, comment='Area in square metres')
cached_polygon = relationship(
"WatershedCache", backref="generated_watershed", passive_deletes=True)
dem_error = Column(
Boolean,
comment='Indicates if an error with the DEM watershed was flagged. '
'The generated watershed will fall back on the FWA polygon watershed. '
'Only applies to type DEM+FWA.')
class ApproxBorders(BaseTable):
""" approximate border locations with WA/ID/MT/AB/NWT/YK/AK
note that these may be drawn within BC, near the actual border, to help warn when approaching a boundary.
"""
__tablename__ = 'fwa_approx_borders'
__table_args__ = {'schema': 'public'}
approx_border_id = Column(Integer, primary_key=True)
border = Column(TEXT, autoincrement=False, nullable=True)
geom = Column(geoalchemy2.types.Geometry(
geometry_type='LINESTRING', srid=3005, spatial_index=True))
class WatershedCache(BaseTable):
__tablename__ = 'watershed_cache'
__table_args__ = {'schema': 'public'}
generated_watershed_id = Column(
Integer, ForeignKey(GeneratedWatershed.generated_watershed_id),
comment='The GeneratedWatershed record this cached polygon is associated with.', primary_key=True)
watershed = Column(JSONB, nullable=False)
last_accessed_date: Column(DateTime, nullable=False)
class StreamBurnedCDEMTile(BaseTable):
""" Footprints for stream-burned CDEM tiles
A filename reference is included for use with GDAL /vsis3/
virtual filesystem and Minio/S3 storage.
All filenames referenced in this table must be present in the S3 storage 'raster' bucket.
"""
__tablename__ = 'stream_burned_cdem_tile'
__table_args__ = {'schema': 'public'}
stream_burned_cdem_tile_id = Column(Integer, primary_key=True)
resolution = Column(
Numeric, comment="The approximate/nominal resolution of this tile in metres per pixel", nullable=False)
z_precision = Column(
Integer, comment="Approximate precision of the z/elevation value. 0 for CDEM to indicate 1 m increments.",
nullable=False)
filename = Column(TEXT, comment="An s3 filename reference. Do not include bucket name.", nullable=False)
geom = Column(geoalchemy2.types.Geometry(
geometry_type='MULTIPOLYGON', srid=4326, spatial_index=True))
| [
"sqlalchemy.orm.relationship",
"sqlalchemy.ForeignKey",
"sqlalchemy.Column",
"geoalchemy2.types.Geometry"
] | [((525, 558), 'sqlalchemy.Column', 'Column', (['Integer'], {'primary_key': '(True)'}), '(Integer, primary_key=True)\n', (531, 558), False, 'from sqlalchemy import String, Column, DateTime, ARRAY, TEXT, Integer, ForeignKey, Boolean, Numeric\n'), ((584, 760), 'sqlalchemy.Column', 'Column', (['String'], {'comment': '"""WALLY watershed identifier used to recreate watersheds. The format is the upstream delineation method followed by the POI encoded as base64."""'}), "(String, comment=\n 'WALLY watershed identifier used to recreate watersheds. The format is the upstream delineation method followed by the POI encoded as base64.'\n )\n", (590, 760), False, 'from sqlalchemy import String, Column, DateTime, ARRAY, TEXT, Integer, ForeignKey, Boolean, Numeric\n'), ((875, 947), 'sqlalchemy.Column', 'Column', (['Numeric'], {'comment': '"""How long it took to calculate this watershed."""'}), "(Numeric, comment='How long it took to calculate this watershed.')\n", (881, 947), False, 'from sqlalchemy import String, Column, DateTime, ARRAY, TEXT, Integer, ForeignKey, Boolean, Numeric\n'), ((979, 1090), 'sqlalchemy.Column', 'Column', (['String'], {'comment': '"""The method used to calculate this watershed e.g. FWA+UPSTREAM, DEM+FWA etc."""'}), "(String, comment=\n 'The method used to calculate this watershed e.g. FWA+UPSTREAM, DEM+FWA etc.'\n )\n", (985, 1090), False, 'from sqlalchemy import String, Column, DateTime, ARRAY, TEXT, Integer, ForeignKey, Boolean, Numeric\n'), ((1111, 1263), 'sqlalchemy.Column', 'Column', (['Boolean'], {'comment': '"""Indicates whether this watershed was determined to be near a border. This affects how it was generated and refined."""'}), "(Boolean, comment=\n 'Indicates whether this watershed was determined to be near a border. This affects how it was generated and refined.'\n )\n", (1117, 1263), False, 'from sqlalchemy import String, Column, DateTime, ARRAY, TEXT, Integer, ForeignKey, Boolean, Numeric\n'), ((1302, 1415), 'sqlalchemy.Column', 'Column', (['String'], {'comment': '"""The name of the Digital Elevation Model used, e.g. CDEM or SRTM"""', 'nullable': '(True)'}), "(String, comment=\n 'The name of the Digital Elevation Model used, e.g. CDEM or SRTM',\n nullable=True)\n", (1308, 1415), False, 'from sqlalchemy import String, Column, DateTime, ARRAY, TEXT, Integer, ForeignKey, Boolean, Numeric\n'), ((1808, 1856), 'sqlalchemy.Column', 'Column', (['Numeric'], {'comment': '"""Area in square metres"""'}), "(Numeric, comment='Area in square metres')\n", (1814, 1856), False, 'from sqlalchemy import String, Column, DateTime, ARRAY, TEXT, Integer, ForeignKey, Boolean, Numeric\n'), ((1878, 1965), 'sqlalchemy.orm.relationship', 'relationship', (['"""WatershedCache"""'], {'backref': '"""generated_watershed"""', 'passive_deletes': '(True)'}), "('WatershedCache', backref='generated_watershed',\n passive_deletes=True)\n", (1890, 1965), False, 'from sqlalchemy.orm import relationship\n'), ((1987, 2180), 'sqlalchemy.Column', 'Column', (['Boolean'], {'comment': '"""Indicates if an error with the DEM watershed was flagged. The generated watershed will fall back on the FWA polygon watershed. Only applies to type DEM+FWA."""'}), "(Boolean, comment=\n 'Indicates if an error with the DEM watershed was flagged. The generated watershed will fall back on the FWA polygon watershed. Only applies to type DEM+FWA.'\n )\n", (1993, 2180), False, 'from sqlalchemy import String, Column, DateTime, ARRAY, TEXT, Integer, ForeignKey, Boolean, Numeric\n'), ((2536, 2569), 'sqlalchemy.Column', 'Column', (['Integer'], {'primary_key': '(True)'}), '(Integer, primary_key=True)\n', (2542, 2569), False, 'from sqlalchemy import String, Column, DateTime, ARRAY, TEXT, Integer, ForeignKey, Boolean, Numeric\n'), ((2583, 2631), 'sqlalchemy.Column', 'Column', (['TEXT'], {'autoincrement': '(False)', 'nullable': '(True)'}), '(TEXT, autoincrement=False, nullable=True)\n', (2589, 2631), False, 'from sqlalchemy import String, Column, DateTime, ARRAY, TEXT, Integer, ForeignKey, Boolean, Numeric\n'), ((3095, 3124), 'sqlalchemy.Column', 'Column', (['JSONB'], {'nullable': '(False)'}), '(JSONB, nullable=False)\n', (3101, 3124), False, 'from sqlalchemy import String, Column, DateTime, ARRAY, TEXT, Integer, ForeignKey, Boolean, Numeric\n'), ((3149, 3181), 'sqlalchemy.Column', 'Column', (['DateTime'], {'nullable': '(False)'}), '(DateTime, nullable=False)\n', (3155, 3181), False, 'from sqlalchemy import String, Column, DateTime, ARRAY, TEXT, Integer, ForeignKey, Boolean, Numeric\n'), ((3615, 3648), 'sqlalchemy.Column', 'Column', (['Integer'], {'primary_key': '(True)'}), '(Integer, primary_key=True)\n', (3621, 3648), False, 'from sqlalchemy import String, Column, DateTime, ARRAY, TEXT, Integer, ForeignKey, Boolean, Numeric\n'), ((3666, 3785), 'sqlalchemy.Column', 'Column', (['Numeric'], {'comment': '"""The approximate/nominal resolution of this tile in metres per pixel"""', 'nullable': '(False)'}), "(Numeric, comment=\n 'The approximate/nominal resolution of this tile in metres per pixel',\n nullable=False)\n", (3672, 3785), False, 'from sqlalchemy import String, Column, DateTime, ARRAY, TEXT, Integer, ForeignKey, Boolean, Numeric\n'), ((3804, 3944), 'sqlalchemy.Column', 'Column', (['Integer'], {'comment': '"""Approximate precision of the z/elevation value. 0 for CDEM to indicate 1 m increments."""', 'nullable': '(False)'}), "(Integer, comment=\n 'Approximate precision of the z/elevation value. 0 for CDEM to indicate 1 m increments.'\n , nullable=False)\n", (3810, 3944), False, 'from sqlalchemy import String, Column, DateTime, ARRAY, TEXT, Integer, ForeignKey, Boolean, Numeric\n'), ((3967, 4065), 'sqlalchemy.Column', 'Column', (['TEXT'], {'comment': '"""An s3 filename reference. Do not include bucket name."""', 'nullable': '(False)'}), "(TEXT, comment=\n 'An s3 filename reference. Do not include bucket name.', nullable=False)\n", (3973, 4065), False, 'from sqlalchemy import String, Column, DateTime, ARRAY, TEXT, Integer, ForeignKey, Boolean, Numeric\n'), ((1450, 1510), 'geoalchemy2.types.Geometry', 'geoalchemy2.types.Geometry', ([], {'geometry_type': '"""POINT"""', 'srid': '(4326)'}), "(geometry_type='POINT', srid=4326)\n", (1476, 1510), False, 'import geoalchemy2\n'), ((1617, 1677), 'geoalchemy2.types.Geometry', 'geoalchemy2.types.Geometry', ([], {'geometry_type': '"""POINT"""', 'srid': '(4326)'}), "(geometry_type='POINT', srid=4326)\n", (1643, 1677), False, 'import geoalchemy2\n'), ((2651, 2740), 'geoalchemy2.types.Geometry', 'geoalchemy2.types.Geometry', ([], {'geometry_type': '"""LINESTRING"""', 'srid': '(3005)', 'spatial_index': '(True)'}), "(geometry_type='LINESTRING', srid=3005,\n spatial_index=True)\n", (2677, 2740), False, 'import geoalchemy2\n'), ((2917, 2970), 'sqlalchemy.ForeignKey', 'ForeignKey', (['GeneratedWatershed.generated_watershed_id'], {}), '(GeneratedWatershed.generated_watershed_id)\n', (2927, 2970), False, 'from sqlalchemy import String, Column, DateTime, ARRAY, TEXT, Integer, ForeignKey, Boolean, Numeric\n'), ((4079, 4170), 'geoalchemy2.types.Geometry', 'geoalchemy2.types.Geometry', ([], {'geometry_type': '"""MULTIPOLYGON"""', 'srid': '(4326)', 'spatial_index': '(True)'}), "(geometry_type='MULTIPOLYGON', srid=4326,\n spatial_index=True)\n", (4105, 4170), False, 'import geoalchemy2\n')] |
# coding:utf8
'''
利用synset的embedding,基于SPWE进行义原推荐
输入:所有synset(名词)的embedding,训练集synset及其义原,测试集synset
输出:测试集义原,正确率
'''
import sys
import os
import numpy as np
from numpy import linalg
import time
import random
outputMode = eval(sys.argv[1])
def ReadSysnetSememe(fileName):
'''
读取已经标注好义原的sysnet
'''
start = time.clock()
synsetSememeDict = {}
with open(fileName, 'r', encoding = 'utf-8') as file:
for line in file:
synset, sememes = line.strip().split('\t')
synsetSememeDict[synset] = sememes.split()
print('Have read', len(synsetSememeDict), 'synsets with sememes.')
return synsetSememeDict
def Read_Test2id(fileName):
'''
读取测试集,获取正确答案
'''
sememeStd_test = {}
first_relation_per_head = set()
with open(fileName, 'r', encoding = 'utf-8') as fin:
for line in fin:
synset_id, sememe_id, synset_type = line.strip().split()
if synset_id in sememeStd_test:
sememeStd_test[synset_id].append(sememe_id)
else:
sememeStd_test[synset_id] = [sememe_id]
first_relation_per_head.add((synset_id, sememe_id, synset_type))
return sememeStd_test, first_relation_per_head
def ReadSynsetVec(fileName, synsetList):
'''
Read synset vectors from the word embedding file
'''
synsetVecDict = dict.fromkeys(synsetList, False)
readNum = 0
with open(fileName, 'r') as file:
synsetNum, dimension = file.readline().strip().split()
for line in file:
items = line.strip().split()
if len(items) == eval(dimension) + 1:
readNum += 1
synset = items[0]
if synset in synsetList:
vec = np.array(list(map(eval, items[1:])))
if linalg.norm(vec) != 0:
synsetVecDict[synset] = vec / \
linalg.norm(vec) # Normalization
print('Have read', readNum, 'synsets with embeddings')
return synsetVecDict
def ReadList(fileName):
se = set()
with open(fileName, 'r', encoding = 'utf-8') as file:
for line in file:
synset = line.strip().split()[0]
if synset.endswith('n'):
se.add(synset)
return list(se)
def Get_AP(sememeStd, sememePre):
'''
Calculate the Average Precision of sememe prediction
'''
AP = 0
hit = 0
for i in range(len(sememePre)):
if sememePre[i] in sememeStd:
hit += 1
AP += float(hit) / (i + 1)
if AP == 0:
print('Calculate AP Error')
print('Sememe Standard:' + ' '.join(sememeStd))
print('Sememe Predicted:' + ' '.join(sememePre))
return 0
else:
AP /= float(len(sememeStd))
return AP
def Get_F1(sememeStdList, sememeSelectList):
'''
Calculate the F1 score of sememe prediction
'''
TP = len(set(sememeStdList) & set(sememeSelectList))
FP = len(sememeSelectList) - TP
FN = len(sememeStdList) - TP
precision = float(TP) / (TP + FN)
recall = float(TP) / (TP + FP)
if (precision + recall) == 0:
return 0
F1 = 2 * precision * recall / (precision + recall)
return F1
#测试集内获得的标准答案
test2id_filename = '../data-noun/test.txt'
synset_answer, first_relation_per_head = Read_Test2id(test2id_filename)
print('Start to read sememes of synsts')
synsetSememeFileName = '../BabelSememe/synset_sememes.txt'
synsetSememeDict = ReadSysnetSememe(synsetSememeFileName)
print('Start to read synset vectors')
synsetVecFileName = 'synset_vec.txt'
synsetVecDict = ReadSynsetVec(synsetVecFileName, list(synsetSememeDict.keys()))
# Start Predicting Sememes
# Set hyper-parameters
K = 100 # number of nearest source words for each target word when predicting
c = 0.8 # declining coefficient
simThresh = 0.5 # threshold of chosen sememe score
numThresh = 0
start = time.clock()
synsetListAll = list(synsetSememeDict.keys())
synsetList = []
for synset in synsetListAll:
if synset.endswith('n'): # 这里只选名词synset
synsetList.append(synset)
random.shuffle(synsetList)
testNum = round(len(synsetList) * 0.1)
#testSynsetList = synsetList[:testNum]
#trainSynsetList = synsetList[testNum:]
testSynsetList = ReadList('../data-noun/test.txt')
trainSynsetList = ReadList('../data-noun/train.txt')
print(len(testSynsetList))
print(len(trainSynsetList))
fout = open('sememePre_SPWE.txt','w',encoding='utf-8')
now = 0
allResults = []
for testSynset in testSynsetList:
if type(synsetVecDict[testSynset]) == type(False):
continue
now += 1
if now % 100 == 0:
print('Have looked for sememes for %d sysnets' % now)
print('Time Used: %f' % (time.clock() - start))
testSynsetVec = synsetVecDict[testSynset]
# Sort source words according the cosine similarity
synsetSimList = []
for trainSynset in trainSynsetList:
if type(synsetVecDict[trainSynset]) == type(False):
continue
if trainSynset == testSynset:
#print('error A', trainSynset,testSynset)
continue
if trainSynset not in synsetVecDict:
#print('error B')
continue
trainSynsetVec = synsetVecDict[trainSynset]
#print(trainSynsetVec.shape,testSynsetVec.shape)
cosSim = np.dot(trainSynsetVec, testSynsetVec)
#print(type(cosSim))
synsetSimList.append((trainSynset, cosSim))
synsetSimList.sort(key=lambda x: x[1], reverse=True)
synsetSimList = synsetSimList[:K]
# Calculate the score of each sememe
sememeScore = {}
rank = 1
for trainSynset, cosSim in synsetSimList:
sememes = synsetSememeDict[trainSynset]
for sememe in sememes:
if sememe in sememeScore:
sememeScore[sememe] += cosSim * pow(c, rank)
else:
sememeScore[sememe] = cosSim * pow(c, rank)
rank += 1
# Save the sorted sememes and their scores
sortedSememe = sorted(sememeScore.items(),
key=lambda x: x[1], reverse=True)
sememePreList = [x[0] for x in sortedSememe]
#sememeStdList = synsetSememeDict[testSynset]
sememeStdList = synset_answer[testSynset]
# Calculate MAP
AP = Get_AP(sememeStdList, sememePreList)
sortedSememe = sortedSememe[0:100]
print(testSynset, end='\t', file = fout)
print(round(AP,2), end='\t', file=fout)
print(len(sememeStdList),end='\t',file = fout)
print(end=',',file = fout)
print(' '.join(sememeStdList),end=',',file=fout)
for i,item in enumerate(sortedSememe):
print(item[0],end=' ', file=fout)
print(end=',',file = fout)
for i,item in enumerate(sortedSememe):
print(round(item[1],3),end=' ', file=fout)
print(file=fout)
# if AP == 1.0:
# print('1.0', sememeStdList, sememePreList)
# print('AP:', AP)
# time.sleep(1)
# Calculate F1 score
tmp = [x for x in sortedSememe if x[1] > simThresh]
if tmp == []:
# Choose the first one sememe if all the semems get scores lower than
# the threshold
tmp = sortedSememe[:1]
sememeSelectList = [x[0] for x in tmp]
numThresh += len(sememeSelectList)
F1 = Get_F1(sememeStdList, sememeSelectList)
allResults.append([testSynset, synsetSimList, sortedSememe, AP, F1])
fout.close()
print('Sememe Prediction Complete')
print('mAP: %f' % np.mean([x[3] for x in allResults]))
print('mean F1: %f' % np.mean([x[4] for x in allResults]))
print('numThresh:', numThresh)
# Save all the results into the file
if outputMode > 0:
with open('SememePreResults.txt', 'w') as file:
file.write('Synset\tAP\tF1\n')
for testSynset, synsetSimList, sortedSememe, AP, F1 in allResults:
file.write(testSynset + '\t' + str(AP) + '\t' + str(F1) + '\n')
if outputMode > 1:
file.write('\tCorrect Sememes: ' +
' '.join(synsetSememeDict[testSynset]) + '\n')
file.write('\tNeartest Synsets (Cosine Similarity): ' + ' '.join(
[synset + '(' + str(cosSim) + ')' for synset, cosSim in synsetSimList]) + '\n')
file.write('\tSememes (Scores): ' + ' '.join(
[sememe + '(' + str(score) + ')' for sememe, score in sortedSememe]) + '\n')
| [
"numpy.mean",
"random.shuffle",
"time.clock",
"numpy.dot",
"numpy.linalg.norm"
] | [((4069, 4081), 'time.clock', 'time.clock', ([], {}), '()\n', (4079, 4081), False, 'import time\n'), ((4260, 4286), 'random.shuffle', 'random.shuffle', (['synsetList'], {}), '(synsetList)\n', (4274, 4286), False, 'import random\n'), ((345, 357), 'time.clock', 'time.clock', ([], {}), '()\n', (355, 357), False, 'import time\n'), ((5538, 5575), 'numpy.dot', 'np.dot', (['trainSynsetVec', 'testSynsetVec'], {}), '(trainSynsetVec, testSynsetVec)\n', (5544, 5575), True, 'import numpy as np\n'), ((7713, 7748), 'numpy.mean', 'np.mean', (['[x[3] for x in allResults]'], {}), '([x[3] for x in allResults])\n', (7720, 7748), True, 'import numpy as np\n'), ((7773, 7808), 'numpy.mean', 'np.mean', (['[x[4] for x in allResults]'], {}), '([x[4] for x in allResults])\n', (7780, 7808), True, 'import numpy as np\n'), ((4907, 4919), 'time.clock', 'time.clock', ([], {}), '()\n', (4917, 4919), False, 'import time\n'), ((1892, 1908), 'numpy.linalg.norm', 'linalg.norm', (['vec'], {}), '(vec)\n', (1903, 1908), False, 'from numpy import linalg\n'), ((2001, 2017), 'numpy.linalg.norm', 'linalg.norm', (['vec'], {}), '(vec)\n', (2012, 2017), False, 'from numpy import linalg\n')] |
#! /usr/bin/python
# -*- coding: utf-8 -*-
import re
from subprocess import Popen, PIPE
def getIP(interface):
p = Popen('ifconfig %s' % interface, stdout=PIPE, stderr=PIPE, shell=True)
stdout = p.communicate()[0]
r = re.search('inet addr:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})', stdout)
ip = r.group(1)
return ip
| [
"subprocess.Popen",
"re.search"
] | [((121, 191), 'subprocess.Popen', 'Popen', (["('ifconfig %s' % interface)"], {'stdout': 'PIPE', 'stderr': 'PIPE', 'shell': '(True)'}), "('ifconfig %s' % interface, stdout=PIPE, stderr=PIPE, shell=True)\n", (126, 191), False, 'from subprocess import Popen, PIPE\n'), ((232, 306), 're.search', 're.search', (['"""inet addr:(\\\\d{1,3}\\\\.\\\\d{1,3}\\\\.\\\\d{1,3}\\\\.\\\\d{1,3})"""', 'stdout'], {}), "('inet addr:(\\\\d{1,3}\\\\.\\\\d{1,3}\\\\.\\\\d{1,3}\\\\.\\\\d{1,3})', stdout)\n", (241, 306), False, 'import re\n')] |
# coding: utf-8
# Standard Library
import os
import argparse
# Local
import payu
from payu import cli
from payu.experiment import Experiment
from payu.laboratory import Laboratory
import payu.subcommands.args as args
title = 'run'
parameters = {'description': 'Run the model experiment'}
arguments = [args.model, args.config, args.initial, args.nruns,
args.laboratory]
def runcmd(model_type, config_path, init_run, n_runs, lab_path):
# Get job submission configuration
pbs_config = cli.get_config(config_path)
pbs_vars = cli.set_env_vars(init_run, n_runs, lab_path)
# Set the queue
# NOTE: Maybe force all jobs on the normal queue
if 'queue' not in pbs_config:
pbs_config['queue'] = 'normal'
# TODO: Create drivers for servers
max_cpus_per_node = 16
# Adjust the CPUs for any model-specific settings
# TODO: Incorporate this into the Model driver
mask_table = pbs_config.get('mask_table', False)
if mask_table:
# Check if a mask table exists
# TODO: Is control_path defined at this stage?
mask_table_fname = None
for f in os.listdir(os.curdir):
if f.startswith('mask_table'):
mask_table_fname = f
# TODO TODO
# Increase the cpu request to match a complete node
if 'submodels' in pbs_config and 'ncpus' not in pbs_config:
submodel_config = pbs_config['submodels']
n_cpus_request = 0
for model in submodel_config:
n_cpus_request += submodel_config[model].get('ncpus', 0)
else:
n_cpus_request = pbs_config.get('ncpus', 1)
n_cpus = n_cpus_request
n_cpus_per_node = pbs_config.get('npernode', max_cpus_per_node)
assert n_cpus_per_node <= max_cpus_per_node
node_misalignment = n_cpus % max_cpus_per_node != 0
node_increase = n_cpus_per_node < max_cpus_per_node
# Increase the CPUs to accomodate the cpu-per-node request
if n_cpus > max_cpus_per_node and (node_increase or node_misalignment):
# Number of requested nodes
n_nodes = 1 + (n_cpus - 1) // n_cpus_per_node
n_cpu_request = max_cpus_per_node * n_nodes
n_inert_cpus = n_cpu_request - n_cpus
print('payu: warning: Job request includes {} unused CPUs.'
''.format(n_inert_cpus))
# Increase CPU request to match the effective node request
n_cpus = max_cpus_per_node * n_nodes
# Update the ncpus field in the config
if n_cpus != n_cpus_request:
print('payu: warning: CPU request increased from {} to {}'
''.format(n_cpus_request, n_cpus))
# Update the (possibly unchanged) value of ncpus
pbs_config['ncpus'] = n_cpus
# Set memory to use the complete node if unspeficied
# TODO: Move RAM per node as variable
pbs_mem = pbs_config.get('mem')
if not pbs_mem and n_cpus > max_cpus_per_node:
pbs_config['mem'] = '{}GB'.format((n_cpus // max_cpus_per_node) * 31)
cli.submit_job('payu-run', pbs_config, pbs_vars)
def runscript():
parser = argparse.ArgumentParser()
for arg in arguments:
parser.add_argument(*arg['flags'], **arg['parameters'])
run_args = parser.parse_args()
lab = Laboratory(run_args.model_type, run_args.config_path,
run_args.lab_path)
expt = Experiment(lab)
expt.setup()
expt.run()
expt.archive()
if expt.n_runs > 0:
expt.resubmit()
| [
"payu.laboratory.Laboratory",
"payu.cli.get_config",
"os.listdir",
"argparse.ArgumentParser",
"payu.cli.set_env_vars",
"payu.experiment.Experiment",
"payu.cli.submit_job"
] | [((510, 537), 'payu.cli.get_config', 'cli.get_config', (['config_path'], {}), '(config_path)\n', (524, 537), False, 'from payu import cli\n'), ((553, 597), 'payu.cli.set_env_vars', 'cli.set_env_vars', (['init_run', 'n_runs', 'lab_path'], {}), '(init_run, n_runs, lab_path)\n', (569, 597), False, 'from payu import cli\n'), ((3003, 3051), 'payu.cli.submit_job', 'cli.submit_job', (['"""payu-run"""', 'pbs_config', 'pbs_vars'], {}), "('payu-run', pbs_config, pbs_vars)\n", (3017, 3051), False, 'from payu import cli\n'), ((3085, 3110), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (3108, 3110), False, 'import argparse\n'), ((3248, 3320), 'payu.laboratory.Laboratory', 'Laboratory', (['run_args.model_type', 'run_args.config_path', 'run_args.lab_path'], {}), '(run_args.model_type, run_args.config_path, run_args.lab_path)\n', (3258, 3320), False, 'from payu.laboratory import Laboratory\n'), ((3353, 3368), 'payu.experiment.Experiment', 'Experiment', (['lab'], {}), '(lab)\n', (3363, 3368), False, 'from payu.experiment import Experiment\n'), ((1134, 1155), 'os.listdir', 'os.listdir', (['os.curdir'], {}), '(os.curdir)\n', (1144, 1155), False, 'import os\n')] |
from app.persian import PersianCalendar
from django.db import models
from .enums import UnitNameEnum,ProductRequestStatusEnum,LetterStatusEnum,AgentRoleEnum
from app.enums import ColorEnum,IconsEnum,EmployeeEnum,DegreeLevelEnum
from django.shortcuts import reverse
from app.settings import ADMIN_URL
from django.utils.translation import gettext as _
from .apps import APP_NAME
from app.models import OurWork
class WorkUnit(models.Model):
title=models.CharField(_("title"),choices=UnitNameEnum.choices,default=UnitNameEnum.ACCOUNTING, max_length=50)
icon=models.CharField(_("icon"),choices=IconsEnum.choices,default=IconsEnum.link, max_length=50)
color=models.CharField(_("color"),choices=ColorEnum.choices,default=ColorEnum.PRIMARY, max_length=50)
employees=models.ManyToManyField("Employee", verbose_name=_("نیروی انسانی"),blank=True)
description=models.CharField(_("description"), max_length=500,null=True,blank=True)
class Meta:
verbose_name = _("WorkUnit")
verbose_name_plural = _("WorkUnits - واحد های سازمانی")
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("automation:work_unit", kwargs={"work_unit_id": self.pk})
def get_edit_url(self):
return f'{ADMIN_URL}{APP_NAME}/workunit/{self.pk}/change/'
class ProductRequestSignature(models.Model):
signature=models.ForeignKey("app.Signature", verbose_name=_("signatures"), on_delete=models.PROTECT)
status=models.CharField(_("status"),choices=ProductRequestStatusEnum.choices,default=ProductRequestStatusEnum.REQUESTED, max_length=50)
def get_status_tag(self):
color='primary'
if self.status==ProductRequestStatusEnum.ACCEPTED:
color='success'
if self.status==ProductRequestStatusEnum.CANCELED:
color='secondary'
if self.status==ProductRequestStatusEnum.COMPLETED:
color='primary'
if self.status==ProductRequestStatusEnum.DENIED:
color='danger'
if self.status==ProductRequestStatusEnum.PROCCESSING:
color='light'
if self.status==ProductRequestStatusEnum.IN_PROGRESS:
color='warning'
if self.status==ProductRequestStatusEnum.REQUESTED:
color='info'
return f'<span class="badge badge-{color}">{self.status}</span>'
class Meta:
verbose_name = _("ProductRequestSignature")
verbose_name_plural = _("ProductRequestSignatures -امضاهای درخواست های خرید")
def __str__(self):
return f'{self.signature.profile.name()} : {self.status}'
def get_absolute_url(self):
return reverse("ProductRequestSignature_detail", kwargs={"pk": self.pk})
class Employee(models.Model):
profile=models.ForeignKey("app.Profile",related_name='automationprofile', verbose_name=_("profile"),null=True,blank=True, on_delete=models.PROTECT)
role=models.CharField(_("نقش"),choices=EmployeeEnum.choices,default=EmployeeEnum.DEFAULT, max_length=50)
degree=models.CharField(_("مدرک"),choices=DegreeLevelEnum.choices,default=DegreeLevelEnum.KARSHENASI, max_length=50)
major=models.CharField(_("رشته تحصیلی"),null=True,blank=True, max_length=50)
introducer=models.CharField(_("معرف"),null=True,blank=True, max_length=50)
def __str__(self):
return self.profile.name()
def name(self):
if self.profile is not None:
return self.profile.name()
return "پروفایل خالی"
class Meta:
verbose_name = _("Employee")
verbose_name_plural = _("کارمندان")
def get_absolute_url(self):
return reverse('app:profile',kwargs={'profile_id':self.profile.pk})
def get_edit_url(self):
if self.profile is not None:
return self.profile.get_edit_url()
class ProductRequest(models.Model):
employee=models.ForeignKey("Employee", verbose_name=_("پرسنل"),null=True,blank=True, on_delete=models.SET_NULL)
work_unit=models.ForeignKey("WorkUnit", verbose_name=_("واحد سازمانی"), on_delete=models.PROTECT)
product=models.ForeignKey("market.Product", verbose_name=_("کالا"), on_delete=models.PROTECT)
product_unit=models.CharField(_("واحد"), max_length=50)
quantity=models.IntegerField(_("تعداد"))
date_added=models.DateTimeField(_("date_added"), auto_now=False, auto_now_add=True)
status=models.CharField(_("وضعیت"),choices=ProductRequestStatusEnum.choices,default=ProductRequestStatusEnum.REQUESTED, max_length=50)
purchase_agent=models.ForeignKey("PurchaseAgent", verbose_name=_("مسئول خرید"), on_delete=models.PROTECT,null=True,blank=True)
signatures=models.ManyToManyField("ProductRequestSignature", verbose_name=_("امضا ها"),blank=True)
class Meta:
verbose_name = _("ProductRequest")
verbose_name_plural = _("ProductRequests -درخواست های خرید")
def get_status_tag(self):
color='primary'
if self.status==ProductRequestStatusEnum.ACCEPTED:
color='success'
if self.status==ProductRequestStatusEnum.CANCELED:
color='secondary'
if self.status==ProductRequestStatusEnum.COMPLETED:
color='primary'
if self.status==ProductRequestStatusEnum.DENIED:
color='danger'
if self.status==ProductRequestStatusEnum.PROCCESSING:
color='light'
if self.status==ProductRequestStatusEnum.IN_PROGRESS:
color='warning'
if self.status==ProductRequestStatusEnum.REQUESTED:
color='info'
return f'<span class="badge badge-{color}">{self.status}</span>'
def __str__(self):
return f'{self.work_unit.title} / {self.product.name} : {self.quantity} {self.product_unit}'
def get_edit_url(self):
return ADMIN_URL+APP_NAME+'/productrequest/'+str(self.pk)+'/change/'
def get_absolute_url(self):
return reverse("automation:product_request", kwargs={"product_request_id": self.pk})
class PurchaseAgent(models.Model):
profile=models.ForeignKey("app.Profile", verbose_name=_("profile"), on_delete=models.CASCADE)
rank=models.IntegerField(_("rank"),default=0)
class Meta:
verbose_name = _("PurchaseAgent")
verbose_name_plural = _("PurchaseAgents - مسئول های خرید")
def __str__(self):
return f'{self.profile.name()} ({self.rank})'
def get_absolute_url(self):
return reverse("PurchaseAgent_detail", kwargs={"pk": self.pk})
class LetterSignature(models.Model):
signature=models.ForeignKey("app.Signature", verbose_name=_("signatures"), on_delete=models.PROTECT)
status=models.CharField(_("status"),choices=LetterStatusEnum.choices,default=LetterStatusEnum.DRAFT, max_length=50)
class Meta:
verbose_name = _("LetterSignature")
verbose_name_plural = _("LetterSignatures - امضا های نامه ها")
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("LetterSignature_detail", kwargs={"pk": self.pk})
class Letter(models.Model):
sender=models.ForeignKey("app.Profile", verbose_name=_("فرستنده"), on_delete=models.CASCADE)
work_unit=models.ForeignKey("WorkUnit", verbose_name=_("گیرنده"), on_delete=models.CASCADE)
title=models.CharField(_("title"), max_length=50)
body=models.CharField(_("body"), max_length=50)
date_added=models.DateTimeField(_("date_added"), auto_now=False, auto_now_add=True)
signatures=models.ManyToManyField("LetterSignature", verbose_name=_("signatures"),blank=True)
class Meta:
verbose_name = _("Letter")
verbose_name_plural = _("Lettes - نامه ها")
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("Letter_detail", kwargs={"pk": self.pk})
class Project(OurWork):
work_units=models.ManyToManyField("WorkUnit", verbose_name=_("work_units"),blank=True)
warehouses=models.ManyToManyField("market.WareHouse", verbose_name=_("warehouses"),blank=True)
class Meta:
verbose_name = _("Project")
verbose_name_plural = _("Projects - پروژه ها")
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("automation:project", kwargs={"project_id": self.pk})
def get_edit_url(self):
return f'{ADMIN_URL}{APP_NAME}/project/{self.pk}/change/'
| [
"django.utils.translation.gettext",
"django.shortcuts.reverse"
] | [((466, 476), 'django.utils.translation.gettext', '_', (['"""title"""'], {}), "('title')\n", (467, 476), True, 'from django.utils.translation import gettext as _\n'), ((580, 589), 'django.utils.translation.gettext', '_', (['"""icon"""'], {}), "('icon')\n", (581, 589), True, 'from django.utils.translation import gettext as _\n'), ((682, 692), 'django.utils.translation.gettext', '_', (['"""color"""'], {}), "('color')\n", (683, 692), True, 'from django.utils.translation import gettext as _\n'), ((886, 902), 'django.utils.translation.gettext', '_', (['"""description"""'], {}), "('description')\n", (887, 902), True, 'from django.utils.translation import gettext as _\n'), ((980, 993), 'django.utils.translation.gettext', '_', (['"""WorkUnit"""'], {}), "('WorkUnit')\n", (981, 993), True, 'from django.utils.translation import gettext as _\n'), ((1024, 1057), 'django.utils.translation.gettext', '_', (['"""WorkUnits - واحد های سازمانی"""'], {}), "('WorkUnits - واحد های سازمانی')\n", (1025, 1057), True, 'from django.utils.translation import gettext as _\n'), ((1156, 1221), 'django.shortcuts.reverse', 'reverse', (['"""automation:work_unit"""'], {'kwargs': "{'work_unit_id': self.pk}"}), "('automation:work_unit', kwargs={'work_unit_id': self.pk})\n", (1163, 1221), False, 'from django.shortcuts import reverse\n'), ((1497, 1508), 'django.utils.translation.gettext', '_', (['"""status"""'], {}), "('status')\n", (1498, 1508), True, 'from django.utils.translation import gettext as _\n'), ((2392, 2420), 'django.utils.translation.gettext', '_', (['"""ProductRequestSignature"""'], {}), "('ProductRequestSignature')\n", (2393, 2420), True, 'from django.utils.translation import gettext as _\n'), ((2451, 2506), 'django.utils.translation.gettext', '_', (['"""ProductRequestSignatures -امضاهای درخواست های خرید"""'], {}), "('ProductRequestSignatures -امضاهای درخواست های خرید')\n", (2452, 2506), True, 'from django.utils.translation import gettext as _\n'), ((2645, 2710), 'django.shortcuts.reverse', 'reverse', (['"""ProductRequestSignature_detail"""'], {'kwargs': "{'pk': self.pk}"}), "('ProductRequestSignature_detail', kwargs={'pk': self.pk})\n", (2652, 2710), False, 'from django.shortcuts import reverse\n'), ((2925, 2933), 'django.utils.translation.gettext', '_', (['"""نقش"""'], {}), "('نقش')\n", (2926, 2933), True, 'from django.utils.translation import gettext as _\n'), ((3036, 3045), 'django.utils.translation.gettext', '_', (['"""مدرک"""'], {}), "('مدرک')\n", (3037, 3045), True, 'from django.utils.translation import gettext as _\n'), ((3156, 3172), 'django.utils.translation.gettext', '_', (['"""رشته تحصیلی"""'], {}), "('رشته تحصیلی')\n", (3157, 3172), True, 'from django.utils.translation import gettext as _\n'), ((3242, 3251), 'django.utils.translation.gettext', '_', (['"""معرف"""'], {}), "('معرف')\n", (3243, 3251), True, 'from django.utils.translation import gettext as _\n'), ((3517, 3530), 'django.utils.translation.gettext', '_', (['"""Employee"""'], {}), "('Employee')\n", (3518, 3530), True, 'from django.utils.translation import gettext as _\n'), ((3561, 3574), 'django.utils.translation.gettext', '_', (['"""کارمندان"""'], {}), "('کارمندان')\n", (3562, 3574), True, 'from django.utils.translation import gettext as _\n'), ((3627, 3689), 'django.shortcuts.reverse', 'reverse', (['"""app:profile"""'], {'kwargs': "{'profile_id': self.profile.pk}"}), "('app:profile', kwargs={'profile_id': self.profile.pk})\n", (3634, 3689), False, 'from django.shortcuts import reverse\n'), ((4187, 4196), 'django.utils.translation.gettext', '_', (['"""واحد"""'], {}), "('واحد')\n", (4188, 4196), True, 'from django.utils.translation import gettext as _\n'), ((4246, 4256), 'django.utils.translation.gettext', '_', (['"""تعداد"""'], {}), "('تعداد')\n", (4247, 4256), True, 'from django.utils.translation import gettext as _\n'), ((4294, 4309), 'django.utils.translation.gettext', '_', (['"""date_added"""'], {}), "('date_added')\n", (4295, 4309), True, 'from django.utils.translation import gettext as _\n'), ((4374, 4384), 'django.utils.translation.gettext', '_', (['"""وضعیت"""'], {}), "('وضعیت')\n", (4375, 4384), True, 'from django.utils.translation import gettext as _\n'), ((4758, 4777), 'django.utils.translation.gettext', '_', (['"""ProductRequest"""'], {}), "('ProductRequest')\n", (4759, 4777), True, 'from django.utils.translation import gettext as _\n'), ((4808, 4846), 'django.utils.translation.gettext', '_', (['"""ProductRequests -درخواست های خرید"""'], {}), "('ProductRequests -درخواست های خرید')\n", (4809, 4846), True, 'from django.utils.translation import gettext as _\n'), ((5863, 5940), 'django.shortcuts.reverse', 'reverse', (['"""automation:product_request"""'], {'kwargs': "{'product_request_id': self.pk}"}), "('automation:product_request', kwargs={'product_request_id': self.pk})\n", (5870, 5940), False, 'from django.shortcuts import reverse\n'), ((6104, 6113), 'django.utils.translation.gettext', '_', (['"""rank"""'], {}), "('rank')\n", (6105, 6113), True, 'from django.utils.translation import gettext as _\n'), ((6165, 6183), 'django.utils.translation.gettext', '_', (['"""PurchaseAgent"""'], {}), "('PurchaseAgent')\n", (6166, 6183), True, 'from django.utils.translation import gettext as _\n'), ((6214, 6250), 'django.utils.translation.gettext', '_', (['"""PurchaseAgents - مسئول های خرید"""'], {}), "('PurchaseAgents - مسئول های خرید')\n", (6215, 6250), True, 'from django.utils.translation import gettext as _\n'), ((6377, 6432), 'django.shortcuts.reverse', 'reverse', (['"""PurchaseAgent_detail"""'], {'kwargs': "{'pk': self.pk}"}), "('PurchaseAgent_detail', kwargs={'pk': self.pk})\n", (6384, 6432), False, 'from django.shortcuts import reverse\n'), ((6604, 6615), 'django.utils.translation.gettext', '_', (['"""status"""'], {}), "('status')\n", (6605, 6615), True, 'from django.utils.translation import gettext as _\n'), ((6746, 6766), 'django.utils.translation.gettext', '_', (['"""LetterSignature"""'], {}), "('LetterSignature')\n", (6747, 6766), True, 'from django.utils.translation import gettext as _\n'), ((6797, 6837), 'django.utils.translation.gettext', '_', (['"""LetterSignatures - امضا های نامه ها"""'], {}), "('LetterSignatures - امضا های نامه ها')\n", (6798, 6837), True, 'from django.utils.translation import gettext as _\n'), ((6935, 6992), 'django.shortcuts.reverse', 'reverse', (['"""LetterSignature_detail"""'], {'kwargs': "{'pk': self.pk}"}), "('LetterSignature_detail', kwargs={'pk': self.pk})\n", (6942, 6992), False, 'from django.shortcuts import reverse\n'), ((7242, 7252), 'django.utils.translation.gettext', '_', (['"""title"""'], {}), "('title')\n", (7243, 7252), True, 'from django.utils.translation import gettext as _\n'), ((7295, 7304), 'django.utils.translation.gettext', '_', (['"""body"""'], {}), "('body')\n", (7296, 7304), True, 'from django.utils.translation import gettext as _\n'), ((7357, 7372), 'django.utils.translation.gettext', '_', (['"""date_added"""'], {}), "('date_added')\n", (7358, 7372), True, 'from django.utils.translation import gettext as _\n'), ((7551, 7562), 'django.utils.translation.gettext', '_', (['"""Letter"""'], {}), "('Letter')\n", (7552, 7562), True, 'from django.utils.translation import gettext as _\n'), ((7593, 7614), 'django.utils.translation.gettext', '_', (['"""Lettes - نامه ها"""'], {}), "('Lettes - نامه ها')\n", (7594, 7614), True, 'from django.utils.translation import gettext as _\n'), ((7713, 7761), 'django.shortcuts.reverse', 'reverse', (['"""Letter_detail"""'], {'kwargs': "{'pk': self.pk}"}), "('Letter_detail', kwargs={'pk': self.pk})\n", (7720, 7761), False, 'from django.shortcuts import reverse\n'), ((8023, 8035), 'django.utils.translation.gettext', '_', (['"""Project"""'], {}), "('Project')\n", (8024, 8035), True, 'from django.utils.translation import gettext as _\n'), ((8066, 8090), 'django.utils.translation.gettext', '_', (['"""Projects - پروژه ها"""'], {}), "('Projects - پروژه ها')\n", (8067, 8090), True, 'from django.utils.translation import gettext as _\n'), ((8189, 8250), 'django.shortcuts.reverse', 'reverse', (['"""automation:project"""'], {'kwargs': "{'project_id': self.pk}"}), "('automation:project', kwargs={'project_id': self.pk})\n", (8196, 8250), False, 'from django.shortcuts import reverse\n'), ((823, 840), 'django.utils.translation.gettext', '_', (['"""نیروی انسانی"""'], {}), "('نیروی انسانی')\n", (824, 840), True, 'from django.utils.translation import gettext as _\n'), ((1426, 1441), 'django.utils.translation.gettext', '_', (['"""signatures"""'], {}), "('signatures')\n", (1427, 1441), True, 'from django.utils.translation import gettext as _\n'), ((2833, 2845), 'django.utils.translation.gettext', '_', (['"""profile"""'], {}), "('profile')\n", (2834, 2845), True, 'from django.utils.translation import gettext as _\n'), ((3893, 3903), 'django.utils.translation.gettext', '_', (['"""پرسنل"""'], {}), "('پرسنل')\n", (3894, 3903), True, 'from django.utils.translation import gettext as _\n'), ((4010, 4027), 'django.utils.translation.gettext', '_', (['"""واحد سازمانی"""'], {}), "('واحد سازمانی')\n", (4011, 4027), True, 'from django.utils.translation import gettext as _\n'), ((4116, 4125), 'django.utils.translation.gettext', '_', (['"""کالا"""'], {}), "('کالا')\n", (4117, 4125), True, 'from django.utils.translation import gettext as _\n'), ((4552, 4567), 'django.utils.translation.gettext', '_', (['"""مسئول خرید"""'], {}), "('مسئول خرید')\n", (4553, 4567), True, 'from django.utils.translation import gettext as _\n'), ((4694, 4706), 'django.utils.translation.gettext', '_', (['"""امضا ها"""'], {}), "('امضا ها')\n", (4695, 4706), True, 'from django.utils.translation import gettext as _\n'), ((6035, 6047), 'django.utils.translation.gettext', '_', (['"""profile"""'], {}), "('profile')\n", (6036, 6047), True, 'from django.utils.translation import gettext as _\n'), ((6533, 6548), 'django.utils.translation.gettext', '_', (['"""signatures"""'], {}), "('signatures')\n", (6534, 6548), True, 'from django.utils.translation import gettext as _\n'), ((7079, 7091), 'django.utils.translation.gettext', '_', (['"""فرستنده"""'], {}), "('فرستنده')\n", (7080, 7091), True, 'from django.utils.translation import gettext as _\n'), ((7176, 7187), 'django.utils.translation.gettext', '_', (['"""گیرنده"""'], {}), "('گیرنده')\n", (7177, 7187), True, 'from django.utils.translation import gettext as _\n'), ((7479, 7494), 'django.utils.translation.gettext', '_', (['"""signatures"""'], {}), "('signatures')\n", (7480, 7494), True, 'from django.utils.translation import gettext as _\n'), ((7850, 7865), 'django.utils.translation.gettext', '_', (['"""work_units"""'], {}), "('work_units')\n", (7851, 7865), True, 'from django.utils.translation import gettext as _\n'), ((7949, 7964), 'django.utils.translation.gettext', '_', (['"""warehouses"""'], {}), "('warehouses')\n", (7950, 7964), True, 'from django.utils.translation import gettext as _\n')] |
# Generated by Django 3.1.3 on 2021-01-23 15:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('KNSQueries', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='person',
name='is_current',
),
migrations.AlterField(
model_name='knsquery',
name='query_id',
field=models.IntegerField(unique=True),
),
migrations.AlterField(
model_name='ministry',
name='ministry_id',
field=models.IntegerField(unique=True),
),
migrations.AlterField(
model_name='person',
name='person_id',
field=models.IntegerField(unique=True),
),
]
| [
"django.db.migrations.RemoveField",
"django.db.models.IntegerField"
] | [((227, 289), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""person"""', 'name': '"""is_current"""'}), "(model_name='person', name='is_current')\n", (249, 289), False, 'from django.db import migrations, models\n'), ((439, 471), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'unique': '(True)'}), '(unique=True)\n', (458, 471), False, 'from django.db import migrations, models\n'), ((600, 632), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'unique': '(True)'}), '(unique=True)\n', (619, 632), False, 'from django.db import migrations, models\n'), ((757, 789), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'unique': '(True)'}), '(unique=True)\n', (776, 789), False, 'from django.db import migrations, models\n')] |
from PyQt5.Qt import *
from Login_Pane import LoginPane
from Query_Pane import QueryPane
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
login_pane = LoginPane()
login_pane.show()
query_pane = QueryPane()
def success_login_slot(content):
print(content)
login_pane.hide()
query_pane.setWindowTitle(content)
query_pane.show()
login_pane.success_login.connect(success_login_slot)
sys.exit(app.exec()) | [
"Login_Pane.LoginPane",
"Query_Pane.QueryPane"
] | [((184, 195), 'Login_Pane.LoginPane', 'LoginPane', ([], {}), '()\n', (193, 195), False, 'from Login_Pane import LoginPane\n'), ((236, 247), 'Query_Pane.QueryPane', 'QueryPane', ([], {}), '()\n', (245, 247), False, 'from Query_Pane import QueryPane\n')] |
from dipsim import multiframe, util
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import matplotlib.patches as patches
import os; import time; start = time.time(); print('Running...')
import matplotlib.gridspec as gridspec
# Main input parameters
col_labels = ['Geometry\n (NA = 0.6, $\\beta=80{}^{\circ}$)', 'Uncertainty Ellipses', r'$\sigma_{\Omega}$ [sr]', 'Median$\{\sigma_{\Omega}\}$ [sr]', 'MAD$\{\sigma_{\Omega}\}$ [sr]', '', '']
fig_labels = ['a)', 'b)', 'c)', 'd)', 'e)', 'f)', 'g)']
n_pts = 5000 #Points on sphere
n_pts_sphere = 50000 # Points on sphere
n_grid_pts = 21
n_line_pts = 50
n_rows, n_cols = 1, len(col_labels)
inch_fig = 5
dpi = 300
# Setup figure and axes
fig = plt.figure(figsize=(2.2*inch_fig, 3*inch_fig))
gs0 = gridspec.GridSpec(3, 1, wspace=0, hspace=0.2, height_ratios=[0.9,1,1])
gs_up = gridspec.GridSpecFromSubplotSpec(1, 4, subplot_spec=gs0[0], width_ratios=[1, 1, 1, 0.06], wspace=0.1)
gs_middle = gridspec.GridSpecFromSubplotSpec(1, 2, subplot_spec=gs0[1], width_ratios=[1, 1], wspace=0.4)
gs_down = gridspec.GridSpecFromSubplotSpec(1, 2, subplot_spec=gs0[2], width_ratios=[1, 1], wspace=0.4)
gs_middle_left = gridspec.GridSpecFromSubplotSpec(1, 2, subplot_spec=gs_middle[0], width_ratios=[1, 0.05], wspace=0.1)
gs_middle_right = gridspec.GridSpecFromSubplotSpec(1, 2, subplot_spec=gs_middle[1], width_ratios=[1, 0.05], wspace=0.1)
gs_down_left = gridspec.GridSpecFromSubplotSpec(1, 2, subplot_spec=gs_down[0], width_ratios=[1, 0.05], wspace=0.1)
gs_down_right = gridspec.GridSpecFromSubplotSpec(1, 2, subplot_spec=gs_down[1], width_ratios=[1, 0.05], wspace=0.1)
ax0 = plt.subplot(gs_up[0])
ax1 = plt.subplot(gs_up[1])
ax2 = plt.subplot(gs_up[2])
cax2 = plt.subplot(gs_up[3])
ax3 = plt.subplot(gs_middle_left[0])
cax3 = plt.subplot(gs_middle_left[1])
ax4 = plt.subplot(gs_middle_right[0])
cax4 = plt.subplot(gs_middle_right[1])
ax5 = plt.subplot(gs_down_left[0])
cax5 = plt.subplot(gs_down_left[1]); cax5.axis('off');
ax6 = plt.subplot(gs_down_right[0])
cax6 = plt.subplot(gs_down_right[1]); cax6.axis('off');
for ax, col_label, fig_label in zip([ax0, ax1, ax2, ax3, ax4, ax5, ax6], col_labels, fig_labels):
ax.annotate(col_label, xy=(0,0), xytext=(0.5, 1.06), textcoords='axes fraction',
va='center', ha='center', fontsize=14, annotation_clip=False)
ax.annotate(fig_label, xy=(0,0), xytext=(0, 1.06), textcoords='axes fraction',
va='center', ha='center', fontsize=14, annotation_clip=False)
for ax in [ax0, ax1, ax2, ax3, ax4, ax5, ax6]:
ax.tick_params(axis='both', labelsize=14)
for cax in [cax2, cax3, cax4]:
cax.tick_params(axis='both', labelsize=14)
# Calculate a list of points to sample in region
n = 1.33
NA_max = n*np.sin(np.pi/4)
NA = np.linspace(0, n, 1000)
lens_bound = np.rad2deg(2*np.arcsin(NA/n))
cover_bound = np.rad2deg(np.pi - 2*np.arcsin(NA/n))
pts = np.mgrid[n/n_grid_pts/2:n:n_grid_pts*1j,0:180:n_grid_pts*1j].reshape((2, n_grid_pts**2)).T.tolist()
def is_feasible(pt):
if pt[1] < np.rad2deg(np.pi - 2*np.arcsin(pt[0]/n)) + 20 and pt[1] > np.rad2deg(2*np.arcsin(pt[0]/n)) - 20 and pt[0] < NA_max + 0.1:
return True
else:
return False
pts_list = [pt for pt in pts if is_feasible(pt)]
pts = np.array(pts_list).T
# Calculate med and mad for each point
def calc_stats(param):
na = param[0]
angle = param[1]
exp = multiframe.MultiFrameMicroscope(ill_thetas=[np.deg2rad(angle/2), -np.deg2rad(angle/2)], det_thetas=[-np.deg2rad(angle/2), np.deg2rad(angle/2)],
ill_nas=2*[na], det_nas=2*[na],
ill_types=2*['wide'], det_types=2*['lens'],
colors=['(1,0,0)', '(0,0,1)'], n_frames=4,
n_pts=n_pts, max_photons=500, n_samp=1.33)
exp.calc_estimation_stats()
data = exp.sa_uncert
med = np.median(data)
return med, np.median(np.abs(data - med))
med = []
mad = []
for i, pt in enumerate(pts.T):
print('Calculating microscope '+str(i+1)+'/'+str(pts.shape[1]))
x = calc_stats(pt)
med.append(x[0])
mad.append(x[1])
# Plot 2D regions
def plot_2d_regions(ax, cax, pts, data, special_pt=(-1,-1),
line_pt0=None, line_pt1=None):
ax.plot(NA, lens_bound, 'k-', zorder=11)
ax.plot(NA, cover_bound, 'k-', zorder=11)
# Set y ticks
from matplotlib.ticker import FuncFormatter, FixedLocator
def degrees(x, pos):
return str(int(x)) + '${}^{\circ}$'
ax.yaxis.set_major_locator(FixedLocator([0, 45, 90, 135, 180]))
ax.yaxis.set_major_formatter(FuncFormatter(degrees))
from matplotlib.ticker import FuncFormatter, FixedLocator
ax.set_xticks([0, 0.25, 0.5, 0.75, 1.0, 1.33])
ax.set_xticklabels(['0', '0.25', '0.5', '0.75', '1.0', '1.33'])
# Annotation
def my_annotate(ax, annotation, xy, fontsize=9, rotation=0):
ax.annotate(annotation, xy=(0,0), xytext=xy, textcoords='axes fraction',
va='center', ha='center', fontsize=fontsize,
annotation_clip=False, rotation=rotation, zorder=13)
my_annotate(ax, 'NA', (0.5, -0.12), fontsize=14)
my_annotate(ax, '$\\beta$, Angle Between Objectives', (-0.25, 0.5), fontsize=14, rotation=90)
my_annotate(ax, 'Objectives collide\nwith cover slip', (0.65, 0.85), fontsize=14)
my_annotate(ax, 'Objectives collide\nwith each other', (0.65, 0.15), fontsize=14)
my_annotate(ax, 'Feasible', (0.3, 0.5), fontsize=14)
# Calculate colors
color_map='coolwarm'
color_norm='log'
color_min=1e-4
color_max=1e1
if color_norm == 'linear':
norm = matplotlib.colors.Normalize(vmin=color_min, vmax=color_max)
elif color_norm == 'log':
norm = matplotlib.colors.LogNorm(vmin=color_min, vmax=color_max)
elif color_norm == 'linlog':
norm = matplotlib.colors.SymLogNorm(linthresh=linthresh, vmin=-color_max, vmax=color_max)
elif color_norm == 'power':
norm = matplotlib.colors.PowerNorm(gamma=gamma, vmin=data.min(), vmax=data.max())
norm_data = norm(data).data
norm_data2 = np.expand_dims(norm_data, 1)
cmap = matplotlib.cm.get_cmap(color_map)
colors = np.apply_along_axis(cmap, 1, norm_data2)
# Plot scatter for colorbar
sc = ax.scatter(pts[0,:], pts[1,:], c=data, s=0, cmap=cmap, norm=norm,
marker='s', lw=0)
ax.plot([line_pt0[0], line_pt1[0]], [line_pt0[1], line_pt1[1]], '-', color='darkmagenta', lw=3, zorder=1)
ax.plot(special_pt[0], special_pt[1], 'kx', markersize=5)
# Plot patches
width = n/(n_grid_pts)
for i, (pt, c) in enumerate(zip(pts_list, colors)):
if pt[1] == 0:
height = 180/14.5
if pt[1] == 0:
height = 180/(n_grid_pts-0.5)
ax.add_patch(patches.Rectangle((pt[0] - width/2, pt[1] - height/2), width, height, facecolor=c, edgecolor=c))
fig.colorbar(sc, cax=cax, orientation='vertical')
# Mask around lines
ax.fill_between(NA, lens_bound, 0, color='white', zorder=2)
ax.fill_between(NA, cover_bound, 180, color='white', zorder=2)
ax.set(xlim=[0, 1.33], ylim=[0, 180])
# Plot 1D region
def plot_1d_regions(ax, pts, data, special_pt=(-1,-1), y_pos=None, y_lim=None, xtitle=None):
# Set y ticks
from matplotlib.ticker import FuncFormatter, FixedLocator
def degrees(x, pos):
return str(int(x)) + '${}^{\circ}$'
ax.xaxis.set_major_locator(FixedLocator([53, 90, 135, 127]))
ax.xaxis.set_major_formatter(FuncFormatter(degrees))
from matplotlib.ticker import FuncFormatter, FixedLocator
ax.set_yticks(y_pos)
ax.set_yticklabels(["{:.1e}".format(x).replace('e-0', 'e-') for x in y_pos])
# Annotation
def my_annotate(ax, annotation, xy, fontsize=9, rotation=0):
ax.annotate(annotation, xy=(0,0), xytext=xy, textcoords='axes fraction',
va='center', ha='center', fontsize=fontsize,
annotation_clip=False, rotation=rotation, zorder=13)
my_annotate(ax, '$\\beta$, Angle Between Objectives', (0.5, -0.12), fontsize=14)
my_annotate(ax, xtitle, (-0.25, 0.5), fontsize=14, rotation=90)
ax.set(xlim=[53, 127], ylim=y_lim)
ax.plot(pts, data, '-', color='darkmagenta', lw=3, zorder=1)
# Plot first two columns
angle = 80
na = 0.6
exp = multiframe.MultiFrameMicroscope(ill_thetas=[np.deg2rad(angle/2), -np.deg2rad(angle/2)], det_thetas=[-np.deg2rad(angle/2), np.deg2rad(angle/2)],
ill_nas=2*[na], det_nas=2*[na],
ill_types=2*['wide'], det_types=2*['lens'],
colors=['(1,0,0)', '(0,0,1)'], n_frames=4,
n_pts=n_pts_sphere, max_photons=500, n_samp=1.33)
exp.calc_estimation_stats()
# Make scene string
scene_string = exp.scene_string()
line_string = "draw(O--expi(theta, 0));\n"
line_string = line_string.replace('theta', str(np.deg2rad(angle/2)))
scene_string += line_string
line_string = "draw(O--expi(theta, 0));\n"
line_string = line_string.replace('theta', str(np.deg2rad(-angle/2)))
scene_string += line_string
arc_string = 'draw(L=Label("$\\beta$", align=N), arc(O, 0.1*expi(-theta, 0), 0.1*expi(theta, 0), normal=Y));\n'
arc_string = arc_string.replace('theta', str(np.deg2rad(angle/2)))
scene_string += arc_string
util.draw_scene(scene_string, my_ax=ax0, dpi=dpi)
util.draw_scene(exp.ellipse_string(n_pts=250), my_ax=ax1, dpi=dpi)
util.plot_sphere(directions=exp.directions, data=exp.sa_uncert,
color_norm='log', linthresh=1e-4,
color_min=1e-4, color_max=1e1,
my_ax=ax2, my_cax=cax2)
# Find profile points
line_na = 0.6
min_beta = np.rad2deg(2*np.arcsin(line_na/n))
max_beta = 180 - np.rad2deg(2*np.arcsin(line_na/n))
# Plots last two columns
plot_2d_regions(ax3, cax3, pts, med, special_pt=(na, angle), line_pt0=(line_na, min_beta), line_pt1=(line_na, max_beta))
plot_2d_regions(ax4, cax4, pts, mad, special_pt=(na, angle), line_pt0=(line_na, min_beta), line_pt1=(line_na, max_beta))
# Calculate and plot profile
line_beta = np.linspace(min_beta, max_beta, n_line_pts)
line_na = 0.6*np.ones(line_beta.shape)
line_pts = np.vstack([line_na, line_beta])
line_med = []
line_mad = []
for i, pt in enumerate(line_pts.T):
print('Calculating microscope '+str(i+1)+'/'+str(line_pts.shape[1]))
x = calc_stats(pt)
line_med.append(x[0])
line_mad.append(x[1])
plot_1d_regions(ax5, line_beta, line_med, special_pt=angle, y_pos=[4.5e-3, 5e-3, 5.5e-3], y_lim=[4.4e-3, 5.6e-3], xtitle='Median$\{\sigma_{\Omega}\}$ [sr]')
plot_1d_regions(ax6, line_beta, line_mad, special_pt=angle, y_pos=[1e-3, 1.5e-3, 2e-3], y_lim=[8e-4, 2e-3], xtitle='MAD$\{\sigma_{\Omega}\}$ [sr]')
# Label axes and save
print('Saving final figure.')
fig.savefig('../paper/symmetric-widefield.pdf', dpi=250)
print('Total time: '+str(np.round(time.time() - start, 2)))
os.system('say "done"')
| [
"numpy.array",
"numpy.sin",
"dipsim.util.draw_scene",
"matplotlib.gridspec.GridSpecFromSubplotSpec",
"matplotlib.colors.LogNorm",
"matplotlib.ticker.FuncFormatter",
"matplotlib.gridspec.GridSpec",
"numpy.linspace",
"dipsim.util.plot_sphere",
"numpy.vstack",
"matplotlib.cm.get_cmap",
"numpy.abs... | [((174, 185), 'time.time', 'time.time', ([], {}), '()\n', (183, 185), False, 'import time\n'), ((710, 760), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(2.2 * inch_fig, 3 * inch_fig)'}), '(figsize=(2.2 * inch_fig, 3 * inch_fig))\n', (720, 760), True, 'import matplotlib.pyplot as plt\n'), ((763, 835), 'matplotlib.gridspec.GridSpec', 'gridspec.GridSpec', (['(3)', '(1)'], {'wspace': '(0)', 'hspace': '(0.2)', 'height_ratios': '[0.9, 1, 1]'}), '(3, 1, wspace=0, hspace=0.2, height_ratios=[0.9, 1, 1])\n', (780, 835), True, 'import matplotlib.gridspec as gridspec\n'), ((842, 947), 'matplotlib.gridspec.GridSpecFromSubplotSpec', 'gridspec.GridSpecFromSubplotSpec', (['(1)', '(4)'], {'subplot_spec': 'gs0[0]', 'width_ratios': '[1, 1, 1, 0.06]', 'wspace': '(0.1)'}), '(1, 4, subplot_spec=gs0[0], width_ratios=[1,\n 1, 1, 0.06], wspace=0.1)\n', (874, 947), True, 'import matplotlib.gridspec as gridspec\n'), ((956, 1052), 'matplotlib.gridspec.GridSpecFromSubplotSpec', 'gridspec.GridSpecFromSubplotSpec', (['(1)', '(2)'], {'subplot_spec': 'gs0[1]', 'width_ratios': '[1, 1]', 'wspace': '(0.4)'}), '(1, 2, subplot_spec=gs0[1], width_ratios=[1,\n 1], wspace=0.4)\n', (988, 1052), True, 'import matplotlib.gridspec as gridspec\n'), ((1059, 1155), 'matplotlib.gridspec.GridSpecFromSubplotSpec', 'gridspec.GridSpecFromSubplotSpec', (['(1)', '(2)'], {'subplot_spec': 'gs0[2]', 'width_ratios': '[1, 1]', 'wspace': '(0.4)'}), '(1, 2, subplot_spec=gs0[2], width_ratios=[1,\n 1], wspace=0.4)\n', (1091, 1155), True, 'import matplotlib.gridspec as gridspec\n'), ((1169, 1274), 'matplotlib.gridspec.GridSpecFromSubplotSpec', 'gridspec.GridSpecFromSubplotSpec', (['(1)', '(2)'], {'subplot_spec': 'gs_middle[0]', 'width_ratios': '[1, 0.05]', 'wspace': '(0.1)'}), '(1, 2, subplot_spec=gs_middle[0],\n width_ratios=[1, 0.05], wspace=0.1)\n', (1201, 1274), True, 'import matplotlib.gridspec as gridspec\n'), ((1289, 1394), 'matplotlib.gridspec.GridSpecFromSubplotSpec', 'gridspec.GridSpecFromSubplotSpec', (['(1)', '(2)'], {'subplot_spec': 'gs_middle[1]', 'width_ratios': '[1, 0.05]', 'wspace': '(0.1)'}), '(1, 2, subplot_spec=gs_middle[1],\n width_ratios=[1, 0.05], wspace=0.1)\n', (1321, 1394), True, 'import matplotlib.gridspec as gridspec\n'), ((1406, 1509), 'matplotlib.gridspec.GridSpecFromSubplotSpec', 'gridspec.GridSpecFromSubplotSpec', (['(1)', '(2)'], {'subplot_spec': 'gs_down[0]', 'width_ratios': '[1, 0.05]', 'wspace': '(0.1)'}), '(1, 2, subplot_spec=gs_down[0],\n width_ratios=[1, 0.05], wspace=0.1)\n', (1438, 1509), True, 'import matplotlib.gridspec as gridspec\n'), ((1522, 1625), 'matplotlib.gridspec.GridSpecFromSubplotSpec', 'gridspec.GridSpecFromSubplotSpec', (['(1)', '(2)'], {'subplot_spec': 'gs_down[1]', 'width_ratios': '[1, 0.05]', 'wspace': '(0.1)'}), '(1, 2, subplot_spec=gs_down[1],\n width_ratios=[1, 0.05], wspace=0.1)\n', (1554, 1625), True, 'import matplotlib.gridspec as gridspec\n'), ((1629, 1650), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs_up[0]'], {}), '(gs_up[0])\n', (1640, 1650), True, 'import matplotlib.pyplot as plt\n'), ((1657, 1678), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs_up[1]'], {}), '(gs_up[1])\n', (1668, 1678), True, 'import matplotlib.pyplot as plt\n'), ((1685, 1706), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs_up[2]'], {}), '(gs_up[2])\n', (1696, 1706), True, 'import matplotlib.pyplot as plt\n'), ((1714, 1735), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs_up[3]'], {}), '(gs_up[3])\n', (1725, 1735), True, 'import matplotlib.pyplot as plt\n'), ((1742, 1772), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs_middle_left[0]'], {}), '(gs_middle_left[0])\n', (1753, 1772), True, 'import matplotlib.pyplot as plt\n'), ((1780, 1810), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs_middle_left[1]'], {}), '(gs_middle_left[1])\n', (1791, 1810), True, 'import matplotlib.pyplot as plt\n'), ((1817, 1848), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs_middle_right[0]'], {}), '(gs_middle_right[0])\n', (1828, 1848), True, 'import matplotlib.pyplot as plt\n'), ((1856, 1887), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs_middle_right[1]'], {}), '(gs_middle_right[1])\n', (1867, 1887), True, 'import matplotlib.pyplot as plt\n'), ((1894, 1922), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs_down_left[0]'], {}), '(gs_down_left[0])\n', (1905, 1922), True, 'import matplotlib.pyplot as plt\n'), ((1930, 1958), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs_down_left[1]'], {}), '(gs_down_left[1])\n', (1941, 1958), True, 'import matplotlib.pyplot as plt\n'), ((1984, 2013), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs_down_right[0]'], {}), '(gs_down_right[0])\n', (1995, 2013), True, 'import matplotlib.pyplot as plt\n'), ((2021, 2050), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs_down_right[1]'], {}), '(gs_down_right[1])\n', (2032, 2050), True, 'import matplotlib.pyplot as plt\n'), ((2761, 2784), 'numpy.linspace', 'np.linspace', (['(0)', 'n', '(1000)'], {}), '(0, n, 1000)\n', (2772, 2784), True, 'import numpy as np\n'), ((9373, 9422), 'dipsim.util.draw_scene', 'util.draw_scene', (['scene_string'], {'my_ax': 'ax0', 'dpi': 'dpi'}), '(scene_string, my_ax=ax0, dpi=dpi)\n', (9388, 9422), False, 'from dipsim import multiframe, util\n'), ((9490, 9656), 'dipsim.util.plot_sphere', 'util.plot_sphere', ([], {'directions': 'exp.directions', 'data': 'exp.sa_uncert', 'color_norm': '"""log"""', 'linthresh': '(0.0001)', 'color_min': '(0.0001)', 'color_max': '(10.0)', 'my_ax': 'ax2', 'my_cax': 'cax2'}), "(directions=exp.directions, data=exp.sa_uncert, color_norm=\n 'log', linthresh=0.0001, color_min=0.0001, color_max=10.0, my_ax=ax2,\n my_cax=cax2)\n", (9506, 9656), False, 'from dipsim import multiframe, util\n'), ((10139, 10182), 'numpy.linspace', 'np.linspace', (['min_beta', 'max_beta', 'n_line_pts'], {}), '(min_beta, max_beta, n_line_pts)\n', (10150, 10182), True, 'import numpy as np\n'), ((10233, 10264), 'numpy.vstack', 'np.vstack', (['[line_na, line_beta]'], {}), '([line_na, line_beta])\n', (10242, 10264), True, 'import numpy as np\n'), ((10958, 10981), 'os.system', 'os.system', (['"""say "done\\""""'], {}), '(\'say "done"\')\n', (10967, 10981), False, 'import os\n'), ((2740, 2757), 'numpy.sin', 'np.sin', (['(np.pi / 4)'], {}), '(np.pi / 4)\n', (2746, 2757), True, 'import numpy as np\n'), ((3253, 3271), 'numpy.array', 'np.array', (['pts_list'], {}), '(pts_list)\n', (3261, 3271), True, 'import numpy as np\n'), ((3912, 3927), 'numpy.median', 'np.median', (['data'], {}), '(data)\n', (3921, 3927), True, 'import numpy as np\n'), ((6137, 6165), 'numpy.expand_dims', 'np.expand_dims', (['norm_data', '(1)'], {}), '(norm_data, 1)\n', (6151, 6165), True, 'import numpy as np\n'), ((6181, 6214), 'matplotlib.cm.get_cmap', 'matplotlib.cm.get_cmap', (['color_map'], {}), '(color_map)\n', (6203, 6214), False, 'import matplotlib\n'), ((6228, 6268), 'numpy.apply_along_axis', 'np.apply_along_axis', (['cmap', '(1)', 'norm_data2'], {}), '(cmap, 1, norm_data2)\n', (6247, 6268), True, 'import numpy as np\n'), ((10197, 10221), 'numpy.ones', 'np.ones', (['line_beta.shape'], {}), '(line_beta.shape)\n', (10204, 10221), True, 'import numpy as np\n'), ((2811, 2828), 'numpy.arcsin', 'np.arcsin', (['(NA / n)'], {}), '(NA / n)\n', (2820, 2828), True, 'import numpy as np\n'), ((4559, 4594), 'matplotlib.ticker.FixedLocator', 'FixedLocator', (['[0, 45, 90, 135, 180]'], {}), '([0, 45, 90, 135, 180])\n', (4571, 4594), False, 'from matplotlib.ticker import FuncFormatter, FixedLocator\n'), ((4629, 4651), 'matplotlib.ticker.FuncFormatter', 'FuncFormatter', (['degrees'], {}), '(degrees)\n', (4642, 4651), False, 'from matplotlib.ticker import FuncFormatter, FixedLocator\n'), ((5671, 5730), 'matplotlib.colors.Normalize', 'matplotlib.colors.Normalize', ([], {'vmin': 'color_min', 'vmax': 'color_max'}), '(vmin=color_min, vmax=color_max)\n', (5698, 5730), False, 'import matplotlib\n'), ((7476, 7508), 'matplotlib.ticker.FixedLocator', 'FixedLocator', (['[53, 90, 135, 127]'], {}), '([53, 90, 135, 127])\n', (7488, 7508), False, 'from matplotlib.ticker import FuncFormatter, FixedLocator\n'), ((7543, 7565), 'matplotlib.ticker.FuncFormatter', 'FuncFormatter', (['degrees'], {}), '(degrees)\n', (7556, 7565), False, 'from matplotlib.ticker import FuncFormatter, FixedLocator\n'), ((8975, 8996), 'numpy.deg2rad', 'np.deg2rad', (['(angle / 2)'], {}), '(angle / 2)\n', (8985, 8996), True, 'import numpy as np\n'), ((9115, 9137), 'numpy.deg2rad', 'np.deg2rad', (['(-angle / 2)'], {}), '(-angle / 2)\n', (9125, 9137), True, 'import numpy as np\n'), ((9323, 9344), 'numpy.deg2rad', 'np.deg2rad', (['(angle / 2)'], {}), '(angle / 2)\n', (9333, 9344), True, 'import numpy as np\n'), ((9755, 9777), 'numpy.arcsin', 'np.arcsin', (['(line_na / n)'], {}), '(line_na / n)\n', (9764, 9777), True, 'import numpy as np\n'), ((2863, 2880), 'numpy.arcsin', 'np.arcsin', (['(NA / n)'], {}), '(NA / n)\n', (2872, 2880), True, 'import numpy as np\n'), ((3954, 3972), 'numpy.abs', 'np.abs', (['(data - med)'], {}), '(data - med)\n', (3960, 3972), True, 'import numpy as np\n'), ((5776, 5833), 'matplotlib.colors.LogNorm', 'matplotlib.colors.LogNorm', ([], {'vmin': 'color_min', 'vmax': 'color_max'}), '(vmin=color_min, vmax=color_max)\n', (5801, 5833), False, 'import matplotlib\n'), ((6835, 6938), 'matplotlib.patches.Rectangle', 'patches.Rectangle', (['(pt[0] - width / 2, pt[1] - height / 2)', 'width', 'height'], {'facecolor': 'c', 'edgecolor': 'c'}), '((pt[0] - width / 2, pt[1] - height / 2), width, height,\n facecolor=c, edgecolor=c)\n', (6852, 6938), True, 'import matplotlib.patches as patches\n'), ((8397, 8418), 'numpy.deg2rad', 'np.deg2rad', (['(angle / 2)'], {}), '(angle / 2)\n', (8407, 8418), True, 'import numpy as np\n'), ((8475, 8496), 'numpy.deg2rad', 'np.deg2rad', (['(angle / 2)'], {}), '(angle / 2)\n', (8485, 8496), True, 'import numpy as np\n'), ((9807, 9829), 'numpy.arcsin', 'np.arcsin', (['(line_na / n)'], {}), '(line_na / n)\n', (9816, 9829), True, 'import numpy as np\n'), ((3430, 3451), 'numpy.deg2rad', 'np.deg2rad', (['(angle / 2)'], {}), '(angle / 2)\n', (3440, 3451), True, 'import numpy as np\n'), ((3508, 3529), 'numpy.deg2rad', 'np.deg2rad', (['(angle / 2)'], {}), '(angle / 2)\n', (3518, 3529), True, 'import numpy as np\n'), ((5882, 5969), 'matplotlib.colors.SymLogNorm', 'matplotlib.colors.SymLogNorm', ([], {'linthresh': 'linthresh', 'vmin': '(-color_max)', 'vmax': 'color_max'}), '(linthresh=linthresh, vmin=-color_max, vmax=\n color_max)\n', (5910, 5969), False, 'import matplotlib\n'), ((8419, 8440), 'numpy.deg2rad', 'np.deg2rad', (['(angle / 2)'], {}), '(angle / 2)\n', (8429, 8440), True, 'import numpy as np\n'), ((8454, 8475), 'numpy.deg2rad', 'np.deg2rad', (['(angle / 2)'], {}), '(angle / 2)\n', (8464, 8475), True, 'import numpy as np\n'), ((3452, 3473), 'numpy.deg2rad', 'np.deg2rad', (['(angle / 2)'], {}), '(angle / 2)\n', (3462, 3473), True, 'import numpy as np\n'), ((3487, 3508), 'numpy.deg2rad', 'np.deg2rad', (['(angle / 2)'], {}), '(angle / 2)\n', (3497, 3508), True, 'import numpy as np\n'), ((10932, 10943), 'time.time', 'time.time', ([], {}), '()\n', (10941, 10943), False, 'import time\n'), ((3095, 3115), 'numpy.arcsin', 'np.arcsin', (['(pt[0] / n)'], {}), '(pt[0] / n)\n', (3104, 3115), True, 'import numpy as np\n'), ((3045, 3065), 'numpy.arcsin', 'np.arcsin', (['(pt[0] / n)'], {}), '(pt[0] / n)\n', (3054, 3065), True, 'import numpy as np\n')] |
import json
import uuid
from jsonfield import JSONField
from django.db import models
class Uploadable(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
url = models.URLField(default="")
meta_data = JSONField(blank=True, null=True)
class Meta:
abstract = True
# MODEL PROPERTIES
@property
def file_type(self):
if self.meta_data and isinstance(self.meta_data, str):
self.meta_data = json.loads(self.meta_data)
try:
return self.meta_data.get('type', "") if self.meta_data else ""
except:
return ""
@property
def name(self):
if self.meta_data and isinstance(self.meta_data, str):
self.meta_data = json.loads(self.meta_data)
return self.meta_data.get('name', "") if self.meta_data else ""
@property
def file_extension(self):
if self.meta_data and isinstance(self.meta_data, str):
self.meta_data = json.loads(self.meta_data)
return self.meta_data.get('ext', "") if self.meta_data else ""
@property
def link_title(self):
if self.name:
title = self.name
elif 'etc' in self.meta_data:
title = (self.meta_data['etc'] or "").upper()
else:
title = (self.meta_data['type'] or
"").upper() if 'type' in self.meta_data else ""
if 'ext' in self.meta_data:
title = title + " .%s" % (self.meta_data['ext'] or "").upper()
return title
| [
"django.db.models.URLField",
"jsonfield.JSONField",
"django.db.models.UUIDField",
"json.loads"
] | [((129, 199), 'django.db.models.UUIDField', 'models.UUIDField', ([], {'primary_key': '(True)', 'default': 'uuid.uuid4', 'editable': '(False)'}), '(primary_key=True, default=uuid.uuid4, editable=False)\n', (145, 199), False, 'from django.db import models\n'), ((211, 238), 'django.db.models.URLField', 'models.URLField', ([], {'default': '""""""'}), "(default='')\n", (226, 238), False, 'from django.db import models\n'), ((255, 287), 'jsonfield.JSONField', 'JSONField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (264, 287), False, 'from jsonfield import JSONField\n'), ((484, 510), 'json.loads', 'json.loads', (['self.meta_data'], {}), '(self.meta_data)\n', (494, 510), False, 'import json\n'), ((765, 791), 'json.loads', 'json.loads', (['self.meta_data'], {}), '(self.meta_data)\n', (775, 791), False, 'import json\n'), ((1001, 1027), 'json.loads', 'json.loads', (['self.meta_data'], {}), '(self.meta_data)\n', (1011, 1027), False, 'import json\n')] |
import numpy as np
import matplotlib.pyplot as plt
import pickle
from scipy.stats import multivariate_normal
def draw_heatmap(mux, muy, sx, sy, rho, plt = None, bound = 0.1):
x, y = np.meshgrid(np.linspace(mux - bound, mux + bound, 200),
np.linspace(muy - bound, muy + bound, 200))
mean = [mux, muy]
# Extract covariance matrix
cov = [[sx * sx, rho * sx * sy], [rho * sx * sy, sy * sy]]
gaussian = multivariate_normal(mean = mean, cov = cov)
d = np.dstack([x, y])
z = gaussian.pdf(d)
z_min, z_max = -np.abs(z).max(), np.abs(z).max()
plt.pcolormesh(x, y, z, cmap='RdBu', vmin=z_min, vmax=z_max, alpha = 0.5)
def visual():
data_file = "./pred_results.pkl"
f = open(data_file, "rb")
visual_data = pickle.load(f)
f.close()
pred_trajs = visual_data[0]
truth_trajs = visual_data[1]
gauss_params = visual_data[2]
traj_num = len(pred_trajs)
for index in range(traj_num):
visual_trajectories(pred_trajs[index], truth_trajs[index], gauss_params[index])
def visual_trajectories(pred_traj, true_traj, gauss_param):
fig_width = 10
fig_height = 10
fig = plt.figure(figsize=(fig_width, fig_width))
plt.plot(true_traj[:, 0], true_traj[:, 1], color = 'G', linestyle = '-.', linewidth = 3,
marker = 'p', markersize = 15, markeredgecolor = 'g', markerfacecolor = 'g')
plt.plot(pred_traj[:, 0], pred_traj[:, 1], color = 'R', linestyle = '-.', linewidth = 3,
marker = 'p', markersize = 10, markeredgecolor = 'r', markerfacecolor = 'r')
plt.show()
visual() | [
"numpy.dstack",
"numpy.abs",
"scipy.stats.multivariate_normal",
"matplotlib.pyplot.plot",
"pickle.load",
"matplotlib.pyplot.pcolormesh",
"matplotlib.pyplot.figure",
"numpy.linspace",
"matplotlib.pyplot.show"
] | [((453, 492), 'scipy.stats.multivariate_normal', 'multivariate_normal', ([], {'mean': 'mean', 'cov': 'cov'}), '(mean=mean, cov=cov)\n', (472, 492), False, 'from scipy.stats import multivariate_normal\n'), ((505, 522), 'numpy.dstack', 'np.dstack', (['[x, y]'], {}), '([x, y])\n', (514, 522), True, 'import numpy as np\n'), ((606, 677), 'matplotlib.pyplot.pcolormesh', 'plt.pcolormesh', (['x', 'y', 'z'], {'cmap': '"""RdBu"""', 'vmin': 'z_min', 'vmax': 'z_max', 'alpha': '(0.5)'}), "(x, y, z, cmap='RdBu', vmin=z_min, vmax=z_max, alpha=0.5)\n", (620, 677), True, 'import matplotlib.pyplot as plt\n'), ((781, 795), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (792, 795), False, 'import pickle\n'), ((1178, 1220), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(fig_width, fig_width)'}), '(figsize=(fig_width, fig_width))\n', (1188, 1220), True, 'import matplotlib.pyplot as plt\n'), ((1226, 1385), 'matplotlib.pyplot.plot', 'plt.plot', (['true_traj[:, 0]', 'true_traj[:, 1]'], {'color': '"""G"""', 'linestyle': '"""-."""', 'linewidth': '(3)', 'marker': '"""p"""', 'markersize': '(15)', 'markeredgecolor': '"""g"""', 'markerfacecolor': '"""g"""'}), "(true_traj[:, 0], true_traj[:, 1], color='G', linestyle='-.',\n linewidth=3, marker='p', markersize=15, markeredgecolor='g',\n markerfacecolor='g')\n", (1234, 1385), True, 'import matplotlib.pyplot as plt\n'), ((1405, 1564), 'matplotlib.pyplot.plot', 'plt.plot', (['pred_traj[:, 0]', 'pred_traj[:, 1]'], {'color': '"""R"""', 'linestyle': '"""-."""', 'linewidth': '(3)', 'marker': '"""p"""', 'markersize': '(10)', 'markeredgecolor': '"""r"""', 'markerfacecolor': '"""r"""'}), "(pred_traj[:, 0], pred_traj[:, 1], color='R', linestyle='-.',\n linewidth=3, marker='p', markersize=10, markeredgecolor='r',\n markerfacecolor='r')\n", (1413, 1564), True, 'import matplotlib.pyplot as plt\n'), ((1584, 1594), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1592, 1594), True, 'import matplotlib.pyplot as plt\n'), ((199, 241), 'numpy.linspace', 'np.linspace', (['(mux - bound)', '(mux + bound)', '(200)'], {}), '(mux - bound, mux + bound, 200)\n', (210, 241), True, 'import numpy as np\n'), ((266, 308), 'numpy.linspace', 'np.linspace', (['(muy - bound)', '(muy + bound)', '(200)'], {}), '(muy - bound, muy + bound, 200)\n', (277, 308), True, 'import numpy as np\n'), ((585, 594), 'numpy.abs', 'np.abs', (['z'], {}), '(z)\n', (591, 594), True, 'import numpy as np\n'), ((568, 577), 'numpy.abs', 'np.abs', (['z'], {}), '(z)\n', (574, 577), True, 'import numpy as np\n')] |
#!/home/knielbo/virtenvs/ndhl/bin/python
"""
Describe feature distributions of (meta)data
@author: <EMAIL>
"""
import os
import matplotlib.pyplot as plt
from util import load_pcl
from datetime import datetime
def main():
fname = os.path.join("..", "dat", "target.pcl")
db = load_pcl(fname)
metadata = db["metadata"]
print("#"*100, file=open("output.txt", "a"))
print(datetime.now(), file=open("output.txt", "a"))
print(metadata.corr(), file=open("output.txt", "a"))
print("\n\n",file=open("output.txt", "a"))
print(metadata.describe(), file=open("output.txt", "a"))
for i, col in enumerate(metadata):
bins = len(list(set(metadata[col].values)))
metadata[col].hist(bins=bins,color="k")
plt.title(col)
plt.savefig(os.path.join("..","fig","DIST_{}.png".format(col)))
plt.close()
if __name__ == "__main__":
main() | [
"os.path.join",
"matplotlib.pyplot.close",
"datetime.datetime.now",
"util.load_pcl",
"matplotlib.pyplot.title"
] | [((235, 274), 'os.path.join', 'os.path.join', (['""".."""', '"""dat"""', '"""target.pcl"""'], {}), "('..', 'dat', 'target.pcl')\n", (247, 274), False, 'import os\n'), ((284, 299), 'util.load_pcl', 'load_pcl', (['fname'], {}), '(fname)\n', (292, 299), False, 'from util import load_pcl\n'), ((390, 404), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (402, 404), False, 'from datetime import datetime\n'), ((753, 767), 'matplotlib.pyplot.title', 'plt.title', (['col'], {}), '(col)\n', (762, 767), True, 'import matplotlib.pyplot as plt\n'), ((848, 859), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (857, 859), True, 'import matplotlib.pyplot as plt\n')] |
# Copyright [2020] [Toyota Research Institute]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Unit tests for maccor protcol files to biologic modulo bat protcol files"""
import os
import unittest
import xmltodict
import copy
import pandas as pd
from monty.tempfile import ScratchDir
from pydash import get
from beep.protocol import (
PROTOCOL_SCHEMA_DIR,
BIOLOGIC_TEMPLATE_DIR,
PROCEDURE_TEMPLATE_DIR,
)
from beep.protocol.maccor import Procedure
from beep.protocol.maccor_to_biologic_mb import (
MaccorToBiologicMb,
CycleAdvancementRules,
CycleAdvancementRulesSerializer
)
TEST_DIR = os.path.dirname(__file__)
TEST_FILE_DIR = os.path.join(TEST_DIR, "test_files")
class ConversionTest(unittest.TestCase):
maxDiff = None
def maccor_values_to_biologic_value_and_unit_test(self, func, tests):
for value_str, expected_value_str, expected_unit in tests:
actual_value, actual_unit = func(value_str)
self.assertEqual(actual_value, expected_value_str)
self.assertEqual(actual_unit, expected_unit)
def test_convert_volts(self):
converter = MaccorToBiologicMb()
tests = [
("0.1429", "142.900", "mV"),
("0.1429e3", "142.900", "V"),
("159.3624", "159362.400", "mV"),
("152.9", "152.900", "V")
]
self.maccor_values_to_biologic_value_and_unit_test(
converter._convert_volts,
tests,
)
def test_convert_amps(self):
converter = MaccorToBiologicMb()
tests = [
("0.1429", "142.900", "mA"),
("1.23", "1.230", "A"),
("152.9", "152.900", "A"),
("1.2e-4", "120.000", "\N{Micro Sign}A")
]
self.maccor_values_to_biologic_value_and_unit_test(
converter._convert_amps,
tests,
)
def test_convert_watts(self):
converter = MaccorToBiologicMb()
tests = [
("0.1429", "142.900", "mW"),
("1.23", "1.230", "W"),
("152.9", "152.900", "W"),
("1.2e-5", "12.000", "\N{Micro Sign}W")
]
self.maccor_values_to_biologic_value_and_unit_test(
converter._convert_watts,
tests,
)
def test_convert_ohms(self):
converter = MaccorToBiologicMb()
tests = [
("0.1429", "142.900", "mOhms"),
("1.459e4", "14.590", "kOhms"),
("152.9", "152.900", "Ohms"),
("1.2e-4", "120.000", "\N{Micro Sign}Ohms")
]
self.maccor_values_to_biologic_value_and_unit_test(
converter._convert_ohms,
tests,
)
def test_convert_time(self):
converter = MaccorToBiologicMb()
tests = [
("::.01", "10.000", "ms"),
("03::", "3.000", "h"),
("03:30:", "210.000", "mn"),
("00:00:50", "50.000", "s")
]
self.maccor_values_to_biologic_value_and_unit_test(
converter._convert_time,
tests,
)
def single_step_to_single_seq_test(self, test_step_xml, diff_dict):
"""
test utility for testing proc_step_to_seq
"""
proc = xmltodict.parse(test_step_xml)
test_step = proc["MaccorTestProcedure"]["ProcSteps"]["TestStep"]
converter = MaccorToBiologicMb()
expected = converter._blank_seq.copy()
expected["Ns"] = 0
expected["lim1_seq"] = 1
expected["lim2_seq"] = 1
expected["lim3_seq"] = 1
expected.update(diff_dict)
step_num = 1
seq_nums_by_step_num = {
step_num: [0],
step_num + 1: [1],
}
result = converter._convert_step_parts(
step_parts=[test_step],
step_num=step_num,
seq_nums_by_step_num=seq_nums_by_step_num,
goto_lowerbound=0,
goto_upperbound=3,
end_step_num=4,
)[0]
for key, value in expected.items():
self.assertEqual(
value,
result[key],
msg="Expected {0}: {1} got {0}: {2}".format(key, value, result[key]),
)
def test_partition_steps_into_techniques(self):
converter = MaccorToBiologicMb()
ast = converter.load_maccor_ast(
os.path.join(PROCEDURE_TEMPLATE_DIR, "diagnosticV5.000")
)
steps = get(ast, "MaccorTestProcedure.ProcSteps.TestStep")
self.assertEqual(True, len(steps) > 71)
# existence of looped tech 2
nested_loop_open_idx = 36
nested_loop_open_type = get(steps[nested_loop_open_idx], 'StepType')
self.assertEqual(nested_loop_open_type, "Do 1")
nested_loop_close_idx = 68
nested_loop_close_type = get(steps[nested_loop_close_idx], 'StepType')
self.assertEqual(nested_loop_close_type, "Loop 1")
technique_partitions = converter._partition_steps_into_techniques(steps)
self.assertEqual(3, len(technique_partitions))
partition1, partition2, partition3 = technique_partitions
self.assertEqual(partition1.technique_num, 1)
self.assertEqual(partition2.technique_num, 2)
self.assertEqual(partition3.technique_num, 4)
self.assertEqual(partition1.tech_does_loop, False)
self.assertEqual(partition2.tech_does_loop, True)
self.assertEqual(partition3.tech_does_loop, False)
self.assertEqual(partition2.num_loops, 1000)
self.assertEqual(partition1.step_num_offset, 0)
self.assertEqual(partition2.step_num_offset, nested_loop_open_idx + 1)
self.assertEqual(partition3.step_num_offset, nested_loop_close_idx + 1)
self.assertEqual(len(partition1.steps), 36)
# trim opening/closing loops
self.assertEqual(len(partition2.steps), nested_loop_close_idx - nested_loop_open_idx - 1)
self.assertEqual(len(partition3.steps), 27)
def test_apply_step_mappings_global_noop(self):
xml = (step_with_bounds_template).format(
voltage_v_lowerbound = 2.2,
voltage_v_upperbound = 4.2,
current_a_lowerbound = 0.1,
current_a_upperbound = 1.0,
)
step = get(
xmltodict.parse(xml, process_namespaces=False, strip_whitespace=True),
'TestStep',
)
converter = MaccorToBiologicMb()
# no limits no mappings
unmapped_step = converter._apply_step_mappings([step])[0]
self.assertEqual(step, unmapped_step)
# limits outside of bounds, don't
converter.max_voltage_v = 10.0
converter.min_voltage_v = -10.0
converter.max_current_a = 10.0
converter.min_current_a = -10.0
unmapped_step = converter._apply_step_mappings([step])[0]
self.assertEqual(step, unmapped_step)
def test_apply_step_mappings_global_voltage(self):
xml = (step_with_bounds_template).format(
voltage_v_lowerbound = 2.2,
voltage_v_upperbound = 4.2,
current_a_lowerbound = 0.1,
current_a_upperbound = 1.0,
)
step = get(
xmltodict.parse(xml, process_namespaces=False, strip_whitespace=True),
'TestStep',
)
converter = MaccorToBiologicMb()
converter.max_voltage_v = 3.9
converter.min_voltage_v = 3.1
step_without_voltage_end_entries = converter._apply_step_mappings([step])[0]
end_entries = get(step_without_voltage_end_entries, "Ends.EndEntry")
self.assertEqual(2, len(end_entries))
self.assertEqual("Current", get(end_entries[0], "EndType"))
self.assertEqual("Current", get(end_entries[1], "EndType"))
# check there was not mutation
original_end_entries = get(step, 'Ends.EndEntry')
self.assertEqual(4, len(original_end_entries))
def test_apply_step_mappings_all_global_limits(self):
xml = (step_with_bounds_template).format(
voltage_v_lowerbound = 2.2,
voltage_v_upperbound = 4.2,
current_a_lowerbound = 0.1,
current_a_upperbound = 1.0,
)
step = get(
xmltodict.parse(xml, process_namespaces=False, strip_whitespace=True),
'TestStep',
)
converter = MaccorToBiologicMb()
converter.max_voltage_v = 3.9
converter.min_voltage_v = 3.1
converter.max_current_a = 0.7
converter.min_current_a = 0.3
step_with_no_end_entries = converter._apply_step_mappings([step])[0]
self.assertEqual(None, get(step_with_no_end_entries, "Ends.EndEntry"))
# check there was not mutation
original_end_entries = get(step, 'Ends.EndEntry')
self.assertEqual(4, len(original_end_entries))
def test_rest_step_conversion(self):
xml = (
'<?xml version="1.0" encoding="UTF-8"?>'
"<MaccorTestProcedure>"
" <ProcSteps>"
" <TestStep>"
" <StepType> Rest </StepType>"
" <StepMode> </StepMode>"
" <StepValue></StepValue>"
" <Limits/>"
" <Ends>"
" <EndEntry>"
" <EndType>Voltage </EndType>"
" <SpecialType> </SpecialType>"
" <Oper>>= </Oper>"
" <Step>002</Step>"
" <Value>4.4</Value>"
" </EndEntry>"
" <EndEntry>"
" <EndType>Voltage </EndType>"
" <SpecialType> </SpecialType>"
" <Oper><= </Oper>"
" <Step>002</Step>"
" <Value>2.5</Value>"
" </EndEntry>"
" </Ends>"
" <Reports>"
" <ReportEntry>"
" <ReportType>Voltage</ReportType>"
" <Value>2.2</Value>"
" </ReportEntry>"
" </Reports>"
" <Range>A</Range>"
" <Option1>N</Option1>"
" <Option2>N</Option2>"
" <Option3>N</Option3>"
" <StepNote></StepNote>"
" </TestStep>"
" </ProcSteps>"
"</MaccorTestProcedure>"
)
diff_dict = {
"ctrl_type": "Rest",
"Apply I/C": "I",
"N": "1.00",
"charge/discharge": "Charge",
"lim_nb": 2,
"lim1_type": "Ecell",
"lim1_comp": ">",
"lim1_value": "4.400",
"lim1_value_unit": "V",
"lim2_type": "Ecell",
"lim2_comp": "<",
"lim2_value": "2.500",
"lim2_value_unit": "V",
"rec_nb": 1,
"rec1_type": "Ecell",
"rec1_value": "2.200",
"rec1_value_unit": "V",
}
self.single_step_to_single_seq_test(xml, diff_dict)
pass
def test_discharge_current_step_conversion(self):
xml = (
'<?xml version="1.0" encoding="UTF-8"?>'
"<MaccorTestProcedure>"
" <ProcSteps>"
" <TestStep>"
# mispelling taken directly from sample file
" <StepType>Dischrge</StepType>"
" <StepMode>Current </StepMode>"
" <StepValue>1.0</StepValue>"
" <Limits/>"
" <Ends>"
" <EndEntry>"
" <EndType>StepTime</EndType>"
" <SpecialType> </SpecialType>"
" <Oper> = </Oper>"
" <Step>002</Step>"
" <Value>00:00:30</Value>"
" </EndEntry>"
" <EndEntry>"
" <EndType>Voltage </EndType>"
" <SpecialType> </SpecialType>"
" <Oper><= </Oper>"
" <Step>002</Step>"
" <Value>2.7</Value>"
" </EndEntry>"
" <EndEntry>"
" <EndType>Voltage </EndType>"
" <SpecialType> </SpecialType>"
" <Oper>>= </Oper>"
" <Step>002</Step>"
" <Value>4.4</Value>"
" </EndEntry>"
" </Ends>"
" <Reports>"
" <ReportEntry>"
" <ReportType>Voltage </ReportType>"
" <Value>0.001</Value>"
" </ReportEntry>"
" <ReportEntry>"
" <ReportType>StepTime</ReportType>"
# 10ms
" <Value>::.01</Value>"
" </ReportEntry>"
" </Reports>"
" <Range>A</Range>"
" <Option1>N</Option1>"
" <Option2>N</Option2>"
" <Option3>N</Option3>"
" <StepNote></StepNote>"
" </TestStep>"
" </ProcSteps>"
"</MaccorTestProcedure>"
)
diff_dict = {
"ctrl_type": "CC",
"Apply I/C": "I",
"ctrl1_val": "1.000",
"ctrl1_val_unit": "A",
"ctrl1_val_vs": "<None>",
"N": "15.00",
"charge/discharge": "Discharge",
"lim_nb": 3,
"lim1_type": "Time",
"lim1_comp": ">",
"lim1_value": "30.000",
"lim1_value_unit": "s",
"lim2_type": "Ecell",
"lim2_comp": "<",
"lim2_value": "2.700",
"lim2_value_unit": "V",
"lim3_type": "Ecell",
"lim3_comp": ">",
"lim3_value": "4.400",
"lim3_value_unit": "V",
"rec_nb": 2,
"rec1_type": "Ecell",
"rec1_value": "1.000",
"rec1_value_unit": "mV",
"rec2_type": "Time",
"rec2_value": "10.000",
"rec2_value_unit": "ms",
}
self.single_step_to_single_seq_test(xml, diff_dict)
pass
def test_conversion_with_updated(self):
converter = MaccorToBiologicMb()
with ScratchDir(".") as scratch_dir:
# Generate a protocol that can be used with the existing cells for testing purposes
reg_params = {
'project_name': {0: 'FormDegrade'},
'seq_num': {0: 0},
'template': {0: 'diagnosticV5.000'},
'charge_constant_current_1': {0: 3.0},
'charge_percent_limit_1': {0: 30},
'charge_constant_current_2': {0: 3.0},
'charge_cutoff_voltage': {0: 4.3},
'charge_constant_voltage_time': {0: 60},
'charge_rest_time': {0: 5},
'discharge_constant_current': {0: 2.0},
'discharge_cutoff_voltage': {0: 2.7},
'discharge_rest_time': {0: 15},
'cell_temperature_nominal': {0: 25},
'cell_type': {0: 'LiFun240'},
'capacity_nominal': {0: 0.240},
'diagnostic_type': {0: 'HPPC+RPT'},
'diagnostic_parameter_set': {0: 'LiFunForm'},
'diagnostic_start_cycle': {0: 100},
'diagnostic_interval': {0: 100}
}
protocol_params_df = pd.DataFrame.from_dict(reg_params)
index = 0
protocol_params = protocol_params_df.iloc[index]
diag_params_df = pd.read_csv(
os.path.join(PROCEDURE_TEMPLATE_DIR, "PreDiag_parameters - DP.csv")
)
diagnostic_params = diag_params_df[
diag_params_df["diagnostic_parameter_set"]
== protocol_params["diagnostic_parameter_set"]
].squeeze()
procedure = Procedure.generate_procedure_regcyclev3(index, protocol_params)
procedure.generate_procedure_diagcyclev3(
protocol_params["capacity_nominal"], diagnostic_params
)
procedure.set_skip_to_end_diagnostic(4.4, 2.0, step_key="070", new_step_key="095")
procedure.to_file(os.path.join(scratch_dir, "BioTest_000001.000"))
# Setup the converter and run it
def set_i_range(tech_num, seq, idx):
seq_copy = copy.deepcopy(seq)
seq_copy["I Range"] = "100 mA"
return seq_copy
converter.seq_mappers.append(set_i_range)
converter.min_voltage_v = 2.0
converter.max_voltage_v = 4.4
converter.convert(os.path.join(scratch_dir, "BioTest_000001.000"),
TEST_FILE_DIR, "BioTest_000001")
f = open(os.path.join(TEST_FILE_DIR, "BioTest_000001.mps"), encoding="ISO-8859-1")
file = f.readlines()
control_list = [
'ctrl_type', 'Rest', 'CC', 'Rest', 'CC', 'CV', 'CC', 'Loop', 'CC', 'CV', 'Rest', 'CC',
'Rest', 'CC', 'CC', 'Loop', 'CV', 'CC', 'CC', 'CV', 'CC', 'CC', 'CV', 'CC', 'CC', 'CV',
'CC', 'CC', 'CC', 'CV', 'Rest', 'CC', 'Rest', 'Loop'
]
self.assertListEqual(control_list, file[35].split())
value_list = [
'ctrl1_val', '240.000', '34.300', '4.400', '34.300', '100.000', '80.000', '4.400', '240.000',
'180.000', '80.000', '100.000', '3.000', '80.000', '48.000', '4.400', '48.000', '48.000', '4.400',
'240.000', '48.000', '4.400', '480.000', '720.000', '720.000', '4.300', '480.000', '100.000'
]
self.assertListEqual(value_list, file[37].split())
voltage_min = '\tEcell min = 2.00 V\n'
self.assertEqual(voltage_min, file[9])
voltage_max = '\tEcell max = 4.40 V\n'
self.assertEqual(voltage_max, file[10])
def test_cycle_transition_serialization(self):
cycle_transition_rules = CycleAdvancementRules(
tech_num=2,
tech_does_loop=True,
adv_cycle_on_start = 1,
adv_cycle_on_tech_loop = 1,
adv_cycle_seq_transitions = {(2, 5): 1, (14, 17): 1},
debug_adv_cycle_on_step_transitions = {(72, 71): 1, (72, 75): 1},
)
serializer = CycleAdvancementRulesSerializer()
json_str = serializer.json(cycle_transition_rules)
parsed_cycle_transition_rules = serializer.parse_json(json_str)
self.assertEqual(
cycle_transition_rules.__repr__(),
parsed_cycle_transition_rules.__repr__(),
)
step_with_bounds_template = (
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<TestStep>\n"
# mispelling taken directly from sample file
" <StepType>Dischrge</StepType>\n"
" <StepMode>Current </StepMode>\n"
" <StepValue>1.0</StepValue>\n"
" <Limits/>\n"
" <Ends>\n"
" <EndEntry>\n"
" <EndType>Voltage </EndType>\n"
" <SpecialType> </SpecialType>\n"
" <Oper><= </Oper>\n"
" <Step>002</Step>\n"
" <Value>{voltage_v_lowerbound}</Value>\n"
" </EndEntry>\n"
" <EndEntry>\n"
" <EndType>Voltage </EndType>\n"
" <SpecialType> </SpecialType>\n"
" <Oper>>= </Oper>\n"
" <Step>002</Step>\n"
" <Value>{voltage_v_upperbound}</Value>\n"
" </EndEntry>\n"
" <EndEntry>\n"
" <EndType>Current </EndType>\n"
" <SpecialType> </SpecialType>\n"
" <Oper><= </Oper>\n"
" <Step>002</Step>\n"
" <Value>{current_a_lowerbound}</Value>\n"
" </EndEntry>\n"
" <EndEntry>\n"
" <EndType>Current </EndType>\n"
" <SpecialType> </SpecialType>\n"
" <Oper>>= </Oper>\n"
" <Step>002</Step>\n"
" <Value>{current_a_upperbound}</Value>\n"
" </EndEntry>\n"
" </Ends>\n"
" <Reports></Reports>\n"
" <Range>A</Range>\n"
" <Option1>N</Option1>\n"
" <Option2>N</Option2>\n"
" <Option3>N</Option3>\n"
" <StepNote></StepNote>\n"
"</TestStep>\n"
) | [
"copy.deepcopy",
"xmltodict.parse",
"os.path.join",
"beep.protocol.maccor_to_biologic_mb.CycleAdvancementRulesSerializer",
"pandas.DataFrame.from_dict",
"os.path.dirname",
"pydash.get",
"beep.protocol.maccor_to_biologic_mb.CycleAdvancementRules",
"beep.protocol.maccor.Procedure.generate_procedure_re... | [((1113, 1138), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (1128, 1138), False, 'import os\n'), ((1155, 1191), 'os.path.join', 'os.path.join', (['TEST_DIR', '"""test_files"""'], {}), "(TEST_DIR, 'test_files')\n", (1167, 1191), False, 'import os\n'), ((1639, 1659), 'beep.protocol.maccor_to_biologic_mb.MaccorToBiologicMb', 'MaccorToBiologicMb', ([], {}), '()\n', (1657, 1659), False, 'from beep.protocol.maccor_to_biologic_mb import MaccorToBiologicMb, CycleAdvancementRules, CycleAdvancementRulesSerializer\n'), ((2041, 2061), 'beep.protocol.maccor_to_biologic_mb.MaccorToBiologicMb', 'MaccorToBiologicMb', ([], {}), '()\n', (2059, 2061), False, 'from beep.protocol.maccor_to_biologic_mb import MaccorToBiologicMb, CycleAdvancementRules, CycleAdvancementRulesSerializer\n'), ((2441, 2461), 'beep.protocol.maccor_to_biologic_mb.MaccorToBiologicMb', 'MaccorToBiologicMb', ([], {}), '()\n', (2459, 2461), False, 'from beep.protocol.maccor_to_biologic_mb import MaccorToBiologicMb, CycleAdvancementRules, CycleAdvancementRulesSerializer\n'), ((2840, 2860), 'beep.protocol.maccor_to_biologic_mb.MaccorToBiologicMb', 'MaccorToBiologicMb', ([], {}), '()\n', (2858, 2860), False, 'from beep.protocol.maccor_to_biologic_mb import MaccorToBiologicMb, CycleAdvancementRules, CycleAdvancementRulesSerializer\n'), ((3260, 3280), 'beep.protocol.maccor_to_biologic_mb.MaccorToBiologicMb', 'MaccorToBiologicMb', ([], {}), '()\n', (3278, 3280), False, 'from beep.protocol.maccor_to_biologic_mb import MaccorToBiologicMb, CycleAdvancementRules, CycleAdvancementRulesSerializer\n'), ((3755, 3785), 'xmltodict.parse', 'xmltodict.parse', (['test_step_xml'], {}), '(test_step_xml)\n', (3770, 3785), False, 'import xmltodict\n'), ((3879, 3899), 'beep.protocol.maccor_to_biologic_mb.MaccorToBiologicMb', 'MaccorToBiologicMb', ([], {}), '()\n', (3897, 3899), False, 'from beep.protocol.maccor_to_biologic_mb import MaccorToBiologicMb, CycleAdvancementRules, CycleAdvancementRulesSerializer\n'), ((4806, 4826), 'beep.protocol.maccor_to_biologic_mb.MaccorToBiologicMb', 'MaccorToBiologicMb', ([], {}), '()\n', (4824, 4826), False, 'from beep.protocol.maccor_to_biologic_mb import MaccorToBiologicMb, CycleAdvancementRules, CycleAdvancementRulesSerializer\n'), ((4963, 5013), 'pydash.get', 'get', (['ast', '"""MaccorTestProcedure.ProcSteps.TestStep"""'], {}), "(ast, 'MaccorTestProcedure.ProcSteps.TestStep')\n", (4966, 5013), False, 'from pydash import get\n'), ((5174, 5218), 'pydash.get', 'get', (['steps[nested_loop_open_idx]', '"""StepType"""'], {}), "(steps[nested_loop_open_idx], 'StepType')\n", (5177, 5218), False, 'from pydash import get\n'), ((5343, 5388), 'pydash.get', 'get', (['steps[nested_loop_close_idx]', '"""StepType"""'], {}), "(steps[nested_loop_close_idx], 'StepType')\n", (5346, 5388), False, 'from pydash import get\n'), ((6941, 6961), 'beep.protocol.maccor_to_biologic_mb.MaccorToBiologicMb', 'MaccorToBiologicMb', ([], {}), '()\n', (6959, 6961), False, 'from beep.protocol.maccor_to_biologic_mb import MaccorToBiologicMb, CycleAdvancementRules, CycleAdvancementRulesSerializer\n'), ((7865, 7885), 'beep.protocol.maccor_to_biologic_mb.MaccorToBiologicMb', 'MaccorToBiologicMb', ([], {}), '()\n', (7883, 7885), False, 'from beep.protocol.maccor_to_biologic_mb import MaccorToBiologicMb, CycleAdvancementRules, CycleAdvancementRulesSerializer\n'), ((8071, 8125), 'pydash.get', 'get', (['step_without_voltage_end_entries', '"""Ends.EndEntry"""'], {}), "(step_without_voltage_end_entries, 'Ends.EndEntry')\n", (8074, 8125), False, 'from pydash import get\n'), ((8379, 8405), 'pydash.get', 'get', (['step', '"""Ends.EndEntry"""'], {}), "(step, 'Ends.EndEntry')\n", (8382, 8405), False, 'from pydash import get\n'), ((8901, 8921), 'beep.protocol.maccor_to_biologic_mb.MaccorToBiologicMb', 'MaccorToBiologicMb', ([], {}), '()\n', (8919, 8921), False, 'from beep.protocol.maccor_to_biologic_mb import MaccorToBiologicMb, CycleAdvancementRules, CycleAdvancementRulesSerializer\n'), ((9304, 9330), 'pydash.get', 'get', (['step', '"""Ends.EndEntry"""'], {}), "(step, 'Ends.EndEntry')\n", (9307, 9330), False, 'from pydash import get\n'), ((14861, 14881), 'beep.protocol.maccor_to_biologic_mb.MaccorToBiologicMb', 'MaccorToBiologicMb', ([], {}), '()\n', (14879, 14881), False, 'from beep.protocol.maccor_to_biologic_mb import MaccorToBiologicMb, CycleAdvancementRules, CycleAdvancementRulesSerializer\n'), ((18685, 18912), 'beep.protocol.maccor_to_biologic_mb.CycleAdvancementRules', 'CycleAdvancementRules', ([], {'tech_num': '(2)', 'tech_does_loop': '(True)', 'adv_cycle_on_start': '(1)', 'adv_cycle_on_tech_loop': '(1)', 'adv_cycle_seq_transitions': '{(2, 5): 1, (14, 17): 1}', 'debug_adv_cycle_on_step_transitions': '{(72, 71): 1, (72, 75): 1}'}), '(tech_num=2, tech_does_loop=True, adv_cycle_on_start=1,\n adv_cycle_on_tech_loop=1, adv_cycle_seq_transitions={(2, 5): 1, (14, 17\n ): 1}, debug_adv_cycle_on_step_transitions={(72, 71): 1, (72, 75): 1})\n', (18706, 18912), False, 'from beep.protocol.maccor_to_biologic_mb import MaccorToBiologicMb, CycleAdvancementRules, CycleAdvancementRulesSerializer\n'), ((19017, 19050), 'beep.protocol.maccor_to_biologic_mb.CycleAdvancementRulesSerializer', 'CycleAdvancementRulesSerializer', ([], {}), '()\n', (19048, 19050), False, 'from beep.protocol.maccor_to_biologic_mb import MaccorToBiologicMb, CycleAdvancementRules, CycleAdvancementRulesSerializer\n'), ((4880, 4936), 'os.path.join', 'os.path.join', (['PROCEDURE_TEMPLATE_DIR', '"""diagnosticV5.000"""'], {}), "(PROCEDURE_TEMPLATE_DIR, 'diagnosticV5.000')\n", (4892, 4936), False, 'import os\n'), ((6816, 6885), 'xmltodict.parse', 'xmltodict.parse', (['xml'], {'process_namespaces': '(False)', 'strip_whitespace': '(True)'}), '(xml, process_namespaces=False, strip_whitespace=True)\n', (6831, 6885), False, 'import xmltodict\n'), ((7740, 7809), 'xmltodict.parse', 'xmltodict.parse', (['xml'], {'process_namespaces': '(False)', 'strip_whitespace': '(True)'}), '(xml, process_namespaces=False, strip_whitespace=True)\n', (7755, 7809), False, 'import xmltodict\n'), ((8208, 8238), 'pydash.get', 'get', (['end_entries[0]', '"""EndType"""'], {}), "(end_entries[0], 'EndType')\n", (8211, 8238), False, 'from pydash import get\n'), ((8276, 8306), 'pydash.get', 'get', (['end_entries[1]', '"""EndType"""'], {}), "(end_entries[1], 'EndType')\n", (8279, 8306), False, 'from pydash import get\n'), ((8776, 8845), 'xmltodict.parse', 'xmltodict.parse', (['xml'], {'process_namespaces': '(False)', 'strip_whitespace': '(True)'}), '(xml, process_namespaces=False, strip_whitespace=True)\n', (8791, 8845), False, 'import xmltodict\n'), ((9185, 9231), 'pydash.get', 'get', (['step_with_no_end_entries', '"""Ends.EndEntry"""'], {}), "(step_with_no_end_entries, 'Ends.EndEntry')\n", (9188, 9231), False, 'from pydash import get\n'), ((14896, 14911), 'monty.tempfile.ScratchDir', 'ScratchDir', (['"""."""'], {}), "('.')\n", (14906, 14911), False, 'from monty.tempfile import ScratchDir\n'), ((16085, 16119), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (['reg_params'], {}), '(reg_params)\n', (16107, 16119), True, 'import pandas as pd\n'), ((16566, 16629), 'beep.protocol.maccor.Procedure.generate_procedure_regcyclev3', 'Procedure.generate_procedure_regcyclev3', (['index', 'protocol_params'], {}), '(index, protocol_params)\n', (16605, 16629), False, 'from beep.protocol.maccor import Procedure\n'), ((16261, 16328), 'os.path.join', 'os.path.join', (['PROCEDURE_TEMPLATE_DIR', '"""PreDiag_parameters - DP.csv"""'], {}), "(PROCEDURE_TEMPLATE_DIR, 'PreDiag_parameters - DP.csv')\n", (16273, 16328), False, 'import os\n'), ((16894, 16941), 'os.path.join', 'os.path.join', (['scratch_dir', '"""BioTest_000001.000"""'], {}), "(scratch_dir, 'BioTest_000001.000')\n", (16906, 16941), False, 'import os\n'), ((17065, 17083), 'copy.deepcopy', 'copy.deepcopy', (['seq'], {}), '(seq)\n', (17078, 17083), False, 'import copy\n'), ((17332, 17379), 'os.path.join', 'os.path.join', (['scratch_dir', '"""BioTest_000001.000"""'], {}), "(scratch_dir, 'BioTest_000001.000')\n", (17344, 17379), False, 'import os\n'), ((17465, 17514), 'os.path.join', 'os.path.join', (['TEST_FILE_DIR', '"""BioTest_000001.mps"""'], {}), "(TEST_FILE_DIR, 'BioTest_000001.mps')\n", (17477, 17514), False, 'import os\n')] |
from flask_mail import Mail, Message
from flask import Flask
app =Flask(__name__)
app.config['MAIL_SERVER']='smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = '<EMAIL>'
app.config['MAIL_PASSWORD'] = '<PASSWORD>%'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
mail = Mail(app)
@app.route("/")
def index():
msg = Message('Hello', sender = '<EMAIL>', recipients = ['<EMAIL>','<EMAIL>'])
msg.body = "PATREC Contract created"
mail.send(msg)
return "Sent"
if __name__ == '__main__':
app.run(debug = True) | [
"flask_mail.Mail",
"flask_mail.Message",
"flask.Flask"
] | [((69, 84), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (74, 84), False, 'from flask import Flask\n'), ((319, 328), 'flask_mail.Mail', 'Mail', (['app'], {}), '(app)\n', (323, 328), False, 'from flask_mail import Mail, Message\n'), ((369, 438), 'flask_mail.Message', 'Message', (['"""Hello"""'], {'sender': '"""<EMAIL>"""', 'recipients': "['<EMAIL>', '<EMAIL>']"}), "('Hello', sender='<EMAIL>', recipients=['<EMAIL>', '<EMAIL>'])\n", (376, 438), False, 'from flask_mail import Mail, Message\n')] |
from .. import berrymq
import os
import glob
import time
import threading
class FileObserver(object):
def __init__(self, target_dir, id_name, interval=5):
self.id_name = id_name
self.target_dir = target_dir
self.interval = interval
self.fileinfo = self._get_fileinfo()
self.thread = threading.Thread(target=self._checkdir)
self.thread.setDaemon(True)
self.running = True
self.thread.start()
def stop(self):
self.running = False
def _checkdir(self):
while self.running:
time.sleep(self.interval)
new_info = self._get_fileinfo()
old_info = self.fileinfo
newfiles = set(new_info.keys())
oldfiles = set(old_info.keys())
for created_file in (newfiles - oldfiles):
berrymq.twitter("%s:created" % self.id_name, created_file)
for remove_file in (oldfiles - newfiles):
berrymq.twitter("%s:removed" % self.id_name, remove_file)
for remain_file in (oldfiles & newfiles):
if new_info[remain_file] != old_info[remain_file]:
berrymq.twitter("%s:modified" % self.id_name, remain_file)
self.fileinfo = new_info
def _get_fileinfo(self):
result = {}
for filename in glob.glob(self.target_dir):
result[filename] = os.path.getmtime(filename)
return result
| [
"threading.Thread",
"time.sleep",
"os.path.getmtime",
"glob.glob"
] | [((328, 367), 'threading.Thread', 'threading.Thread', ([], {'target': 'self._checkdir'}), '(target=self._checkdir)\n', (344, 367), False, 'import threading\n'), ((1348, 1374), 'glob.glob', 'glob.glob', (['self.target_dir'], {}), '(self.target_dir)\n', (1357, 1374), False, 'import glob\n'), ((584, 609), 'time.sleep', 'time.sleep', (['self.interval'], {}), '(self.interval)\n', (594, 609), False, 'import time\n'), ((1407, 1433), 'os.path.getmtime', 'os.path.getmtime', (['filename'], {}), '(filename)\n', (1423, 1433), False, 'import os\n')] |
import os
from redisrpc import RedisRPC
# Add REDIS_URI application enviroment
os.environ.setdefault("REDIS_URI", "redis://:PpkJfHHNph9X5hB5@localhost:6379/0")
rpc = RedisRPC("channel_name") # rename what you want
# event lists
def calc_square(response): # `response` is a sender data
power_of_number = response ** 2
return power_of_number # sent to client
def calc_cube(response): # `response` is a sender data
cube_of_number = response ** 3
return cube_of_number # sent to client
rpc.register(calc_square, "square") # event name default function name
rpc.register(calc_cube)
rpc.listen()
| [
"os.environ.setdefault",
"redisrpc.RedisRPC"
] | [((81, 166), 'os.environ.setdefault', 'os.environ.setdefault', (['"""REDIS_URI"""', '"""redis://:PpkJfHHNph9X5hB5@localhost:6379/0"""'], {}), "('REDIS_URI', 'redis://:PpkJfHHNph9X5hB5@localhost:6379/0'\n )\n", (102, 166), False, 'import os\n'), ((169, 193), 'redisrpc.RedisRPC', 'RedisRPC', (['"""channel_name"""'], {}), "('channel_name')\n", (177, 193), False, 'from redisrpc import RedisRPC\n')] |
import requests
from server_generator.server_generator import MagicRouter
from tests.utils import start_test_bottle_app
class HelloNameURLHandler(MagicRouter):
route_name = 'hello_name'
def handler(self):
return 'hello {}'.format(self.name)
def test_setup():
route = HelloNameURLHandler()
start_test_bottle_app(route)
# url = URL('hello_name')
# url.get()
r = requests.get('http://localhost:8080/hello/world')
assert r.status_code == 200
assert 'hello world' in r.text
| [
"requests.get",
"tests.utils.start_test_bottle_app"
] | [((319, 347), 'tests.utils.start_test_bottle_app', 'start_test_bottle_app', (['route'], {}), '(route)\n', (340, 347), False, 'from tests.utils import start_test_bottle_app\n'), ((402, 451), 'requests.get', 'requests.get', (['"""http://localhost:8080/hello/world"""'], {}), "('http://localhost:8080/hello/world')\n", (414, 451), False, 'import requests\n')] |
from GPy.kern import Kern
from GPy.core.parameterization import Param
import numpy as np
import sys
from paramz.transformations import Logexp
from ..kernels.tree.C_tree_kernel import wrapper_raw_SubsetTreeKernel
class SubsetTreeKernel(Kern):
"""
The SST kernel by Moschitti(2006), with two hyperparameters (lambda and sigma).
small lambda restricts the influence of large fragments, sigma controls the sparsity (sigma=0 only allows fragments with terminal symbols)
We calculate gradients w.r.t kernel phyperparameters following Beck (2015)
This is mainly a wrapper for a Cython implementation (see C_tree_kernel.pyx).
The Cython kernel is stored on the "kernel" attribute.
Following the GPy stanard, we require input in the form of 2-d numpy arrays of strings with dtype=object
e.g
X=np.array([['(S (NP ns) (VP v))'],
['(S (NP n) (VP v))'],
['(S (NP (N a)) (VP (V c)))'],
['(S (NP (Det a) (N b)) (VP (V c)))'],
['(S (NP (ADJ colorless) (N ideas)) (VP (V sleep) (ADV furiously)))']],
dtype=object)
Each inidivudal string should be in the prolog format e.g. "(C (B c) (D a))" for
C
/ \
B D
| |
c a
"""
def __init__(self, _lambda=1, _sigma=1, normalize=True, active_dims=None):
super(SubsetTreeKernel, self).__init__(1, active_dims, 'sstk')
self._lambda = Param('Lambda', _lambda,Logexp())
self._sigma = Param('Sigma', _sigma,Logexp())
self.link_parameters(self._lambda, self._sigma)
self.normalize = normalize
self.kernel = wrapper_raw_SubsetTreeKernel(_lambda, _sigma, normalize)
def _get_params(self):
# return kernel parameter values
return np.hstack((self._lambda, self._sigma))
def _set_params(self, x):
# set kernel parameters
self._lambda = x[0]
self._sigma = x[1]
def _get_param_names(self):
# return parameter names
return ['Lambda', 'Sigma']
def K(self, X, X2):
# calc the kernel for input X
# also calc the gradients w.r.t kernel parameters
self.kernel._lambda = self._lambda
self.kernel._sigma = self._sigma
result, dl, ds = self.kernel.K(X, X2)
self.dlambda = dl
self.dsigma = ds
return result
def Kdiag(self, X):
# Calc just the diagonal elements of a kernel matrix
self.kernel._lambda = self._lambda
self.kernel._sigma = self._sigma
if self.normalize:
# if normalizing then this will just be ones
return np.ones(X.shape[0])
else:
return self.kernel.Kdiag(X)
def dK_dtheta(self, dL_dK, X, X2):
# return the kerenl gradients w.r.t kernel parameter over the dataset
self.K(X,X2)
return np.array([np.sum(self.dlambda * dL_dK),
np.sum(self.dsigma * dL_dK)])
def update_gradients_full(self, dL_dK, X, X2):
# update gradients for optimization of kernel parameters
self._lambda.gradient = np.sum(self.dlambda * dL_dK)
self._sigma.gradient = np.sum(self.dsigma * dL_dK)
if __name__ == "__main__":
#Simple Demo
X=np.array([['(S (NP ns) (VP v))'],
['(S (NP n) (VP v))'],
['(S (NP (N a)) (VP (V c)))'],
['(S (NP (Det a) (N b)) (VP (V c)))'],
['(S (NP (ADJ colorless) (N ideas)) (VP (V sleep) (ADV furiously)))']],
dtype=object)
kern = SubsetTreeKernel(_lambda=1)
print("test calculations with normalization")
print(str(kern.K(X))+"\n should be\n"+str(np.array([[ 1., 0.5, 0.10540926, 0.08333333, 0.06711561],
[ 0.5, 1., 0.10540926, 0.08333333, 0.06711561],
[ 0.10540926, 0.10540926, 1., 0.31622777, 0.04244764],
[ 0.08333333, 0.08333333, 0.31622777, 1., 0.0335578 ],
[ 0.06711561, 0.06711561, 0.04244764, 0.0335578, 1. ]])))
| [
"numpy.ones",
"paramz.transformations.Logexp",
"numpy.hstack",
"numpy.array",
"numpy.sum"
] | [((3309, 3535), 'numpy.array', 'np.array', (["[['(S (NP ns) (VP v))'], ['(S (NP n) (VP v))'], [\n '(S (NP (N a)) (VP (V c)))'], ['(S (NP (Det a) (N b)) (VP (V c)))'], [\n '(S (NP (ADJ colorless) (N ideas)) (VP (V sleep) (ADV furiously)))']]"], {'dtype': 'object'}), "([['(S (NP ns) (VP v))'], ['(S (NP n) (VP v))'], [\n '(S (NP (N a)) (VP (V c)))'], ['(S (NP (Det a) (N b)) (VP (V c)))'], [\n '(S (NP (ADJ colorless) (N ideas)) (VP (V sleep) (ADV furiously)))']],\n dtype=object)\n", (3317, 3535), True, 'import numpy as np\n'), ((1851, 1889), 'numpy.hstack', 'np.hstack', (['(self._lambda, self._sigma)'], {}), '((self._lambda, self._sigma))\n', (1860, 1889), True, 'import numpy as np\n'), ((3169, 3197), 'numpy.sum', 'np.sum', (['(self.dlambda * dL_dK)'], {}), '(self.dlambda * dL_dK)\n', (3175, 3197), True, 'import numpy as np\n'), ((3229, 3256), 'numpy.sum', 'np.sum', (['(self.dsigma * dL_dK)'], {}), '(self.dsigma * dL_dK)\n', (3235, 3256), True, 'import numpy as np\n'), ((1525, 1533), 'paramz.transformations.Logexp', 'Logexp', ([], {}), '()\n', (1531, 1533), False, 'from paramz.transformations import Logexp\n'), ((1579, 1587), 'paramz.transformations.Logexp', 'Logexp', ([], {}), '()\n', (1585, 1587), False, 'from paramz.transformations import Logexp\n'), ((2706, 2725), 'numpy.ones', 'np.ones', (['X.shape[0]'], {}), '(X.shape[0])\n', (2713, 2725), True, 'import numpy as np\n'), ((2944, 2972), 'numpy.sum', 'np.sum', (['(self.dlambda * dL_dK)'], {}), '(self.dlambda * dL_dK)\n', (2950, 2972), True, 'import numpy as np\n'), ((2990, 3017), 'numpy.sum', 'np.sum', (['(self.dsigma * dL_dK)'], {}), '(self.dsigma * dL_dK)\n', (2996, 3017), True, 'import numpy as np\n'), ((3787, 4071), 'numpy.array', 'np.array', (['[[1.0, 0.5, 0.10540926, 0.08333333, 0.06711561], [0.5, 1.0, 0.10540926, \n 0.08333333, 0.06711561], [0.10540926, 0.10540926, 1.0, 0.31622777, \n 0.04244764], [0.08333333, 0.08333333, 0.31622777, 1.0, 0.0335578], [\n 0.06711561, 0.06711561, 0.04244764, 0.0335578, 1.0]]'], {}), '([[1.0, 0.5, 0.10540926, 0.08333333, 0.06711561], [0.5, 1.0, \n 0.10540926, 0.08333333, 0.06711561], [0.10540926, 0.10540926, 1.0, \n 0.31622777, 0.04244764], [0.08333333, 0.08333333, 0.31622777, 1.0, \n 0.0335578], [0.06711561, 0.06711561, 0.04244764, 0.0335578, 1.0]])\n', (3795, 4071), True, 'import numpy as np\n')] |
import matplotlib.pyplot as plt
import numpy as np
from scipy.io import wavfile
from common import balance, file_name, view, correction
# Read the audio file
rate, audio = wavfile.read(file_name)
audio = balance(audio)
count = audio.shape[0] # Number of data points
length = count / rate # Length of the recording (seconds)
print(f'Audio length: {length:.2f}s')
print(f'Audio rate: {rate}; Count: {count}')
transform = np.abs(np.fft.fft(audio)) # Apply Fourier
time_series = np.linspace(0, rate, count) # Create the corresponding time series
print(f'Maximum magnitude: {np.amax(transform[:count // 2]) / count:.0f}')
# Prepare matplotlib
plt.plot(time_series[:count // 2] * correction, transform[:count // 2] / count)
plt.xlabel('Frequency [Hz]')
plt.ylabel('Magnitude')
if view is None or view.__len__() != 2:
sub_title = 'Rate: {rate} [$1/s$]'
save_file = f'figs/{file_name[5:-4]}.png'
plt.xlim(20, 20000) # Audible frequency range
else:
sub_title = f'Rate: {rate} [$1/s$]; Zoomed ({view[0]} - {view[1]} Hz)'
save_file = f'figs/{file_name[5:-4]}-zoomed-{view[0]}-{view[1]}.png'
plt.xlim(view[0], view[1])
plt.title(f'Fourier analysis of {file_name}\n{sub_title} (c: {correction:.3f})')
plt.savefig(save_file)
plt.show()
| [
"matplotlib.pyplot.savefig",
"common.balance",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.fft.fft",
"common.view.__len__",
"numpy.linspace",
"scipy.io.wavfile.read",
"matplotlib.pyplot.title",
"matplotlib.pyplot.xlim",
"numpy.amax",
"matplotlib.p... | [((174, 197), 'scipy.io.wavfile.read', 'wavfile.read', (['file_name'], {}), '(file_name)\n', (186, 197), False, 'from scipy.io import wavfile\n'), ((206, 220), 'common.balance', 'balance', (['audio'], {}), '(audio)\n', (213, 220), False, 'from common import balance, file_name, view, correction\n'), ((483, 510), 'numpy.linspace', 'np.linspace', (['(0)', 'rate', 'count'], {}), '(0, rate, count)\n', (494, 510), True, 'import numpy as np\n'), ((649, 728), 'matplotlib.pyplot.plot', 'plt.plot', (['(time_series[:count // 2] * correction)', '(transform[:count // 2] / count)'], {}), '(time_series[:count // 2] * correction, transform[:count // 2] / count)\n', (657, 728), True, 'import matplotlib.pyplot as plt\n'), ((730, 758), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Frequency [Hz]"""'], {}), "('Frequency [Hz]')\n", (740, 758), True, 'import matplotlib.pyplot as plt\n'), ((759, 782), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Magnitude"""'], {}), "('Magnitude')\n", (769, 782), True, 'import matplotlib.pyplot as plt\n'), ((1146, 1234), 'matplotlib.pyplot.title', 'plt.title', (['f"""Fourier analysis of {file_name}\n{sub_title} (c: {correction:.3f})"""'], {}), '(\n f"""Fourier analysis of {file_name}\n{sub_title} (c: {correction:.3f})""")\n', (1155, 1234), True, 'import matplotlib.pyplot as plt\n'), ((1227, 1249), 'matplotlib.pyplot.savefig', 'plt.savefig', (['save_file'], {}), '(save_file)\n', (1238, 1249), True, 'import matplotlib.pyplot as plt\n'), ((1250, 1260), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1258, 1260), True, 'import matplotlib.pyplot as plt\n'), ((433, 450), 'numpy.fft.fft', 'np.fft.fft', (['audio'], {}), '(audio)\n', (443, 450), True, 'import numpy as np\n'), ((913, 932), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(20)', '(20000)'], {}), '(20, 20000)\n', (921, 932), True, 'import matplotlib.pyplot as plt\n'), ((1118, 1144), 'matplotlib.pyplot.xlim', 'plt.xlim', (['view[0]', 'view[1]'], {}), '(view[0], view[1])\n', (1126, 1144), True, 'import matplotlib.pyplot as plt\n'), ((803, 817), 'common.view.__len__', 'view.__len__', ([], {}), '()\n', (815, 817), False, 'from common import balance, file_name, view, correction\n'), ((580, 611), 'numpy.amax', 'np.amax', (['transform[:count // 2]'], {}), '(transform[:count // 2])\n', (587, 611), True, 'import numpy as np\n')] |
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..','..'))
import numpy as np
import pickle
import random
import json
from collections import OrderedDict
import itertools as it
from src.neuralNetwork.policyValueResNet import GenerateModel, Train, saveVariables, sampleData, ApproximateValue,ApproximatePolicy, restoreVariables
import src.constrainedChasingEscapingEnv.envNoPhysics as env
import src.constrainedChasingEscapingEnv.reward as reward
from src.constrainedChasingEscapingEnv.policies import HeatSeekingContinuesDeterministicPolicy, HeatSeekingDiscreteDeterministicPolicy, stationaryAgentPolicy
from src.constrainedChasingEscapingEnv.state import GetAgentPosFromState
from src.constrainedChasingEscapingEnv.analyticGeometryFunctions import computeAngleBetweenVectors
from src.episode import chooseGreedyAction,SampleTrajectory
from src.constrainedChasingEscapingEnv.envNoPhysics import TransiteForNoPhysics, Reset,IsTerminal,StayInBoundaryByReflectVelocity
from src.constrainedChasingEscapingEnv.envNoPhysics import IsTerminal, TransiteForNoPhysics, Reset
import time
from exec.trajectoriesSaveLoad import GetSavePath, saveToPickle
class SampleTrajectoryWithRender:
def __init__(self, maxRunningSteps, transit, isTerminal, reset, chooseAction, render, renderOn):
self.maxRunningSteps = maxRunningSteps
self.transit = transit
self.isTerminal = isTerminal
self.reset = reset
self.chooseAction = chooseAction
self.render = render
self.renderOn = renderOn
def __call__(self, policy):
state = self.reset()
while self.isTerminal(state):
state = self.reset()
trajectory = []
for runningStep in range(self.maxRunningSteps):
if self.isTerminal(state):
trajectory.append((state, None, None))
break
if self.renderOn:
self.render(state,runningStep)
actionDists = policy(state)
action = [choose(action) for choose, action in zip(self.chooseAction, actionDists)]
trajectory.append((state, action, actionDists))
actionFortransit=[action[0],action[1][0],action[1][1]]
nextState = self.transit(state, actionFortransit)
state = nextState
return trajectory
def main():
parametersForTrajectoryPath = json.loads(sys.argv[1])
startSampleIndex = int(sys.argv[2])
endSampleIndex = int(sys.argv[3])
# parametersForTrajectoryPath['sampleOneStepPerTraj']=1 #0
# parametersForTrajectoryPath['sampleIndex'] = (startSampleIndex, endSampleIndex)
trainSteps = int(parametersForTrajectoryPath['trainSteps'])
depth=int(parametersForTrajectoryPath['depth'])
dataSize=int(parametersForTrajectoryPath['dataSize'])
# parametersForTrajectoryPath = {}
# depth = 5
# dataSize = 5000
# trainSteps = 50000
# startSampleIndex = 0
# endSampleIndex = 100
killzoneRadius = 25
numSimulations = 200
maxRunningSteps = 100
fixedParameters = {'maxRunningSteps': maxRunningSteps, 'numSimulations': numSimulations, 'killzoneRadius': killzoneRadius}
trajectorySaveExtension = '.pickle'
dirName = os.path.dirname(__file__)
trajectoriesSaveDirectory = os.path.join(dirName, '..','..', '..', 'data','evaluateSupervisedLearning', 'multiMCTSAgentResNetNoPhysicsCenterControl','evaluateCenterControlTrajByCondition')
if not os.path.exists(trajectoriesSaveDirectory):
os.makedirs(trajectoriesSaveDirectory)
generateTrajectorySavePath = GetSavePath(trajectoriesSaveDirectory, trajectorySaveExtension, fixedParameters)
trajectorySavePath = generateTrajectorySavePath(parametersForTrajectoryPath)
if not os.path.isfile(trajectorySavePath):
numOfAgent=3
sheepId = 0
wolvesId = 1
wolfOneId = 1
wolfTwoId = 2
xPosIndex = [0, 1]
xBoundary = [0,600]
yBoundary = [0,600]
reset = Reset(xBoundary, yBoundary, numOfAgent)
getSheepXPos = GetAgentPosFromState(sheepId, xPosIndex)
getWolfOneXPos = GetAgentPosFromState(wolfOneId, xPosIndex)
getWolfTwoXPos = GetAgentPosFromState(wolfTwoId, xPosIndex)
isTerminalOne = IsTerminal(getWolfOneXPos, getSheepXPos, killzoneRadius)
isTerminalTwo = IsTerminal(getWolfTwoXPos, getSheepXPos, killzoneRadius)
isTerminal=lambda state:isTerminalOne(state) or isTerminalTwo(state)
stayInBoundaryByReflectVelocity = StayInBoundaryByReflectVelocity(xBoundary, yBoundary)
transit = TransiteForNoPhysics(stayInBoundaryByReflectVelocity)
actionSpace = [(10, 0), (7, 7), (0, 10), (-7, 7), (-10, 0), (-7, -7), (0, -10), (7, -7),(0,0)]
preyPowerRatio = 3
sheepActionSpace = list(map(tuple, np.array(actionSpace) * preyPowerRatio))
predatorPowerRatio = 2
wolfActionOneSpace = list(map(tuple, np.array(actionSpace) * predatorPowerRatio))
wolfActionTwoSpace = list(map(tuple, np.array(actionSpace) * predatorPowerRatio))
wolvesActionSpace =list(it.product(wolfActionOneSpace,wolfActionTwoSpace))
# neural network init
numStateSpace = 6
numSheepActionSpace=len(sheepActionSpace)
numWolvesActionSpace=len(wolvesActionSpace)
regularizationFactor = 1e-4
sharedWidths = [128]
actionLayerWidths = [128]
valueLayerWidths = [128]
generateSheepModel = GenerateModel(numStateSpace, numSheepActionSpace, regularizationFactor)
# load save dir
NNModelSaveExtension = ''
NNModelSaveDirectory = os.path.join(dirName, '..','..', '..', 'data', 'evaluateEscapeMultiChasingNoPhysics', 'trainedResNNModelsMultiStillAction')
NNModelFixedParameters = {'agentId': 0, 'maxRunningSteps': 150, 'numSimulations': 200,'miniBatchSize':256,'learningRate':0.0001}
getNNModelSavePath = GetSavePath(NNModelSaveDirectory, NNModelSaveExtension, NNModelFixedParameters)
if not os.path.exists(NNModelSaveDirectory):
os.makedirs(NNModelSaveDirectory)
resBlockSize = 2
dropoutRate = 0.0
initializationMethod = 'uniform'
initSheepNNModel = generateSheepModel(sharedWidths * 5, actionLayerWidths, valueLayerWidths, resBlockSize, initializationMethod, dropoutRate)
sheepTrainedModelPath = getNNModelSavePath({'trainSteps':50000,'depth':5})
sheepTrainedModel = restoreVariables(initSheepNNModel, sheepTrainedModelPath)
sheepPolicy = ApproximatePolicy(sheepTrainedModel, sheepActionSpace)
generateWolvesModel = GenerateModel(numStateSpace, numWolvesActionSpace, regularizationFactor)
initWolvesNNModel = generateWolvesModel(sharedWidths * depth, actionLayerWidths, valueLayerWidths, resBlockSize, initializationMethod, dropoutRate)
NNModelSaveDirectory = os.path.join(dirName, '..', '..', '..', 'data', 'evaluateSupervisedLearning', 'multiMCTSAgentResNetNoPhysicsCenterControl', 'trainedResNNModels')
wolfId = 1
NNModelFixedParametersWolves = {'agentId': wolfId, 'maxRunningSteps': maxRunningSteps, 'numSimulations': numSimulations,'miniBatchSize':256,'learningRate':0.0001,}
getNNModelSavePath = GetSavePath(NNModelSaveDirectory, NNModelSaveExtension, NNModelFixedParametersWolves)
wolvesTrainedModelPath = getNNModelSavePath({'trainSteps':trainSteps,'depth':depth,'dataSize':dataSize})
wolvesTrainedModel = restoreVariables(initWolvesNNModel, wolvesTrainedModelPath)
wolfPolicy = ApproximatePolicy(wolvesTrainedModel, wolvesActionSpace)
from exec.evaluateNoPhysicsEnvWithRender import Render
import pygame as pg
from pygame.color import THECOLORS
screenColor = THECOLORS['black']
circleColorList = [THECOLORS['green'], THECOLORS['red'],THECOLORS['orange']]
circleSize = 10
saveImage = False
saveImageDir = os.path.join(dirName, '..','..', '..', 'data','demoImg')
if not os.path.exists(saveImageDir):
os.makedirs(saveImageDir)
renderOn = False
render=None
if renderOn:
screen = pg.display.set_mode([xBoundary[1], yBoundary[1]])
render = Render(numOfAgent, xPosIndex,screen, screenColor, circleColorList, circleSize, saveImage, saveImageDir)
chooseActionList = [chooseGreedyAction,chooseGreedyAction]
sampleTrajectory = SampleTrajectoryWithRender(maxRunningSteps, transit, isTerminal, reset, chooseActionList,render,renderOn)
# All agents' policies
policy = lambda state:[sheepPolicy(state),wolfPolicy(state)]
trajectories = [sampleTrajectory(policy) for sampleIndex in range(startSampleIndex, endSampleIndex)]
saveToPickle(trajectories, trajectorySavePath)
if __name__ == "__main__":
main() | [
"src.constrainedChasingEscapingEnv.envNoPhysics.TransiteForNoPhysics",
"src.neuralNetwork.policyValueResNet.restoreVariables",
"numpy.array",
"os.path.exists",
"src.neuralNetwork.policyValueResNet.ApproximatePolicy",
"exec.trajectoriesSaveLoad.GetSavePath",
"pygame.display.set_mode",
"itertools.produc... | [((2400, 2423), 'json.loads', 'json.loads', (['sys.argv[1]'], {}), '(sys.argv[1])\n', (2410, 2423), False, 'import json\n'), ((3245, 3270), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (3260, 3270), False, 'import os\n'), ((3303, 3478), 'os.path.join', 'os.path.join', (['dirName', '""".."""', '""".."""', '""".."""', '"""data"""', '"""evaluateSupervisedLearning"""', '"""multiMCTSAgentResNetNoPhysicsCenterControl"""', '"""evaluateCenterControlTrajByCondition"""'], {}), "(dirName, '..', '..', '..', 'data',\n 'evaluateSupervisedLearning',\n 'multiMCTSAgentResNetNoPhysicsCenterControl',\n 'evaluateCenterControlTrajByCondition')\n", (3315, 3478), False, 'import os\n'), ((3598, 3683), 'exec.trajectoriesSaveLoad.GetSavePath', 'GetSavePath', (['trajectoriesSaveDirectory', 'trajectorySaveExtension', 'fixedParameters'], {}), '(trajectoriesSaveDirectory, trajectorySaveExtension, fixedParameters\n )\n', (3609, 3683), False, 'from exec.trajectoriesSaveLoad import GetSavePath, saveToPickle\n'), ((50, 75), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (65, 75), False, 'import os\n'), ((3475, 3516), 'os.path.exists', 'os.path.exists', (['trajectoriesSaveDirectory'], {}), '(trajectoriesSaveDirectory)\n', (3489, 3516), False, 'import os\n'), ((3526, 3564), 'os.makedirs', 'os.makedirs', (['trajectoriesSaveDirectory'], {}), '(trajectoriesSaveDirectory)\n', (3537, 3564), False, 'import os\n'), ((3772, 3806), 'os.path.isfile', 'os.path.isfile', (['trajectorySavePath'], {}), '(trajectorySavePath)\n', (3786, 3806), False, 'import os\n'), ((4015, 4054), 'src.constrainedChasingEscapingEnv.envNoPhysics.Reset', 'Reset', (['xBoundary', 'yBoundary', 'numOfAgent'], {}), '(xBoundary, yBoundary, numOfAgent)\n', (4020, 4054), False, 'from src.constrainedChasingEscapingEnv.envNoPhysics import IsTerminal, TransiteForNoPhysics, Reset\n'), ((4079, 4119), 'src.constrainedChasingEscapingEnv.state.GetAgentPosFromState', 'GetAgentPosFromState', (['sheepId', 'xPosIndex'], {}), '(sheepId, xPosIndex)\n', (4099, 4119), False, 'from src.constrainedChasingEscapingEnv.state import GetAgentPosFromState\n'), ((4145, 4187), 'src.constrainedChasingEscapingEnv.state.GetAgentPosFromState', 'GetAgentPosFromState', (['wolfOneId', 'xPosIndex'], {}), '(wolfOneId, xPosIndex)\n', (4165, 4187), False, 'from src.constrainedChasingEscapingEnv.state import GetAgentPosFromState\n'), ((4213, 4255), 'src.constrainedChasingEscapingEnv.state.GetAgentPosFromState', 'GetAgentPosFromState', (['wolfTwoId', 'xPosIndex'], {}), '(wolfTwoId, xPosIndex)\n', (4233, 4255), False, 'from src.constrainedChasingEscapingEnv.state import GetAgentPosFromState\n'), ((4281, 4337), 'src.constrainedChasingEscapingEnv.envNoPhysics.IsTerminal', 'IsTerminal', (['getWolfOneXPos', 'getSheepXPos', 'killzoneRadius'], {}), '(getWolfOneXPos, getSheepXPos, killzoneRadius)\n', (4291, 4337), False, 'from src.constrainedChasingEscapingEnv.envNoPhysics import IsTerminal, TransiteForNoPhysics, Reset\n'), ((4362, 4418), 'src.constrainedChasingEscapingEnv.envNoPhysics.IsTerminal', 'IsTerminal', (['getWolfTwoXPos', 'getSheepXPos', 'killzoneRadius'], {}), '(getWolfTwoXPos, getSheepXPos, killzoneRadius)\n', (4372, 4418), False, 'from src.constrainedChasingEscapingEnv.envNoPhysics import IsTerminal, TransiteForNoPhysics, Reset\n'), ((4539, 4592), 'src.constrainedChasingEscapingEnv.envNoPhysics.StayInBoundaryByReflectVelocity', 'StayInBoundaryByReflectVelocity', (['xBoundary', 'yBoundary'], {}), '(xBoundary, yBoundary)\n', (4570, 4592), False, 'from src.constrainedChasingEscapingEnv.envNoPhysics import TransiteForNoPhysics, Reset, IsTerminal, StayInBoundaryByReflectVelocity\n'), ((4611, 4664), 'src.constrainedChasingEscapingEnv.envNoPhysics.TransiteForNoPhysics', 'TransiteForNoPhysics', (['stayInBoundaryByReflectVelocity'], {}), '(stayInBoundaryByReflectVelocity)\n', (4631, 4664), False, 'from src.constrainedChasingEscapingEnv.envNoPhysics import IsTerminal, TransiteForNoPhysics, Reset\n'), ((5496, 5567), 'src.neuralNetwork.policyValueResNet.GenerateModel', 'GenerateModel', (['numStateSpace', 'numSheepActionSpace', 'regularizationFactor'], {}), '(numStateSpace, numSheepActionSpace, regularizationFactor)\n', (5509, 5567), False, 'from src.neuralNetwork.policyValueResNet import GenerateModel, Train, saveVariables, sampleData, ApproximateValue, ApproximatePolicy, restoreVariables\n'), ((5658, 5791), 'os.path.join', 'os.path.join', (['dirName', '""".."""', '""".."""', '""".."""', '"""data"""', '"""evaluateEscapeMultiChasingNoPhysics"""', '"""trainedResNNModelsMultiStillAction"""'], {}), "(dirName, '..', '..', '..', 'data',\n 'evaluateEscapeMultiChasingNoPhysics', 'trainedResNNModelsMultiStillAction'\n )\n", (5670, 5791), False, 'import os\n'), ((5948, 6027), 'exec.trajectoriesSaveLoad.GetSavePath', 'GetSavePath', (['NNModelSaveDirectory', 'NNModelSaveExtension', 'NNModelFixedParameters'], {}), '(NNModelSaveDirectory, NNModelSaveExtension, NNModelFixedParameters)\n', (5959, 6027), False, 'from exec.trajectoriesSaveLoad import GetSavePath, saveToPickle\n'), ((6483, 6540), 'src.neuralNetwork.policyValueResNet.restoreVariables', 'restoreVariables', (['initSheepNNModel', 'sheepTrainedModelPath'], {}), '(initSheepNNModel, sheepTrainedModelPath)\n', (6499, 6540), False, 'from src.neuralNetwork.policyValueResNet import GenerateModel, Train, saveVariables, sampleData, ApproximateValue, ApproximatePolicy, restoreVariables\n'), ((6563, 6617), 'src.neuralNetwork.policyValueResNet.ApproximatePolicy', 'ApproximatePolicy', (['sheepTrainedModel', 'sheepActionSpace'], {}), '(sheepTrainedModel, sheepActionSpace)\n', (6580, 6617), False, 'from src.neuralNetwork.policyValueResNet import GenerateModel, Train, saveVariables, sampleData, ApproximateValue, ApproximatePolicy, restoreVariables\n'), ((6650, 6722), 'src.neuralNetwork.policyValueResNet.GenerateModel', 'GenerateModel', (['numStateSpace', 'numWolvesActionSpace', 'regularizationFactor'], {}), '(numStateSpace, numWolvesActionSpace, regularizationFactor)\n', (6663, 6722), False, 'from src.neuralNetwork.policyValueResNet import GenerateModel, Train, saveVariables, sampleData, ApproximateValue, ApproximatePolicy, restoreVariables\n'), ((6910, 7063), 'os.path.join', 'os.path.join', (['dirName', '""".."""', '""".."""', '""".."""', '"""data"""', '"""evaluateSupervisedLearning"""', '"""multiMCTSAgentResNetNoPhysicsCenterControl"""', '"""trainedResNNModels"""'], {}), "(dirName, '..', '..', '..', 'data',\n 'evaluateSupervisedLearning',\n 'multiMCTSAgentResNetNoPhysicsCenterControl', 'trainedResNNModels')\n", (6922, 7063), False, 'import os\n'), ((7277, 7366), 'exec.trajectoriesSaveLoad.GetSavePath', 'GetSavePath', (['NNModelSaveDirectory', 'NNModelSaveExtension', 'NNModelFixedParametersWolves'], {}), '(NNModelSaveDirectory, NNModelSaveExtension,\n NNModelFixedParametersWolves)\n', (7288, 7366), False, 'from exec.trajectoriesSaveLoad import GetSavePath, saveToPickle\n'), ((7505, 7564), 'src.neuralNetwork.policyValueResNet.restoreVariables', 'restoreVariables', (['initWolvesNNModel', 'wolvesTrainedModelPath'], {}), '(initWolvesNNModel, wolvesTrainedModelPath)\n', (7521, 7564), False, 'from src.neuralNetwork.policyValueResNet import GenerateModel, Train, saveVariables, sampleData, ApproximateValue, ApproximatePolicy, restoreVariables\n'), ((7586, 7642), 'src.neuralNetwork.policyValueResNet.ApproximatePolicy', 'ApproximatePolicy', (['wolvesTrainedModel', 'wolvesActionSpace'], {}), '(wolvesTrainedModel, wolvesActionSpace)\n', (7603, 7642), False, 'from src.neuralNetwork.policyValueResNet import GenerateModel, Train, saveVariables, sampleData, ApproximateValue, ApproximatePolicy, restoreVariables\n'), ((7978, 8036), 'os.path.join', 'os.path.join', (['dirName', '""".."""', '""".."""', '""".."""', '"""data"""', '"""demoImg"""'], {}), "(dirName, '..', '..', '..', 'data', 'demoImg')\n", (7990, 8036), False, 'import os\n'), ((8798, 8844), 'exec.trajectoriesSaveLoad.saveToPickle', 'saveToPickle', (['trajectories', 'trajectorySavePath'], {}), '(trajectories, trajectorySavePath)\n', (8810, 8844), False, 'from exec.trajectoriesSaveLoad import GetSavePath, saveToPickle\n'), ((5124, 5174), 'itertools.product', 'it.product', (['wolfActionOneSpace', 'wolfActionTwoSpace'], {}), '(wolfActionOneSpace, wolfActionTwoSpace)\n', (5134, 5174), True, 'import itertools as it\n'), ((6044, 6080), 'os.path.exists', 'os.path.exists', (['NNModelSaveDirectory'], {}), '(NNModelSaveDirectory)\n', (6058, 6080), False, 'import os\n'), ((6094, 6127), 'os.makedirs', 'os.makedirs', (['NNModelSaveDirectory'], {}), '(NNModelSaveDirectory)\n', (6105, 6127), False, 'import os\n'), ((8050, 8078), 'os.path.exists', 'os.path.exists', (['saveImageDir'], {}), '(saveImageDir)\n', (8064, 8078), False, 'import os\n'), ((8092, 8117), 'os.makedirs', 'os.makedirs', (['saveImageDir'], {}), '(saveImageDir)\n', (8103, 8117), False, 'import os\n'), ((8205, 8254), 'pygame.display.set_mode', 'pg.display.set_mode', (['[xBoundary[1], yBoundary[1]]'], {}), '([xBoundary[1], yBoundary[1]])\n', (8224, 8254), True, 'import pygame as pg\n'), ((8276, 8384), 'exec.evaluateNoPhysicsEnvWithRender.Render', 'Render', (['numOfAgent', 'xPosIndex', 'screen', 'screenColor', 'circleColorList', 'circleSize', 'saveImage', 'saveImageDir'], {}), '(numOfAgent, xPosIndex, screen, screenColor, circleColorList,\n circleSize, saveImage, saveImageDir)\n', (8282, 8384), False, 'from exec.evaluateNoPhysicsEnvWithRender import Render\n'), ((4839, 4860), 'numpy.array', 'np.array', (['actionSpace'], {}), '(actionSpace)\n', (4847, 4860), True, 'import numpy as np\n'), ((4957, 4978), 'numpy.array', 'np.array', (['actionSpace'], {}), '(actionSpace)\n', (4965, 4978), True, 'import numpy as np\n'), ((5047, 5068), 'numpy.array', 'np.array', (['actionSpace'], {}), '(actionSpace)\n', (5055, 5068), True, 'import numpy as np\n')] |
# Usage:
# Find and download fred series data
# then find the specific data on yyyy-mm-dd
import requests # used for downloading text files from FRED
import os # used for removing temporary text files
# Usage : download series data in the form of text file and extract data on given date
# param:
# series: the series number
# year : target year. Format: 4 digit YYYY
# month : target month. Format: 2 digit MM
# day : target day. Format: 2 digit DD
def fred_crawler(series, year, month, day):
r = requests.get('https://fred.stlouisfed.org/data/' + series + '.txt')
fname = series + 'txt'
with open(fname, 'wb') as f:
f.write(r.content)
with open(fname, 'r', encoding='utf-8') as f:
lines = f.readlines()
data_file = dict()
for line in lines:
if not line[0].isdigit():
continue
else:
temp = line.rstrip().split()
data_file[temp[0]] = temp[1]
if len(month) == 1:
month = '0' + mm
if len(day) == 1:
day = '0' + day
date = year + '-' + month + '-' + day
# print('The result is: {}'.format(data_file[date]))
print("{} {}: {}".format(series.upper(), date, data_file[date]))
os.remove(fname)
if __name__ == "__main__":
query = input('Please enter the series ID ==> ').upper()
yyyy = input('Year == > ')
mm = input('Month ==> ')
dd = input('Day ==> ')
fred_crawler(query, yyyy, mm, dd)
| [
"requests.get",
"os.remove"
] | [((547, 614), 'requests.get', 'requests.get', (["('https://fred.stlouisfed.org/data/' + series + '.txt')"], {}), "('https://fred.stlouisfed.org/data/' + series + '.txt')\n", (559, 614), False, 'import requests\n'), ((1163, 1179), 'os.remove', 'os.remove', (['fname'], {}), '(fname)\n', (1172, 1179), False, 'import os\n')] |
import pymongo
import requests
from collections import OrderedDict
from hashlib import sha512
API_URL = 'https://api.coinmarketcap.com/v2/ticker/'
API_URL_START = 'https://api.coinmarketcap.com/v2/ticker/?start={}'
API_URL_LISTINGS = 'https://api.coinmarketcap.com/v2/listings/'
def get_db_connection(uri):
"""
Define la conexión a la BD.
MongoClient por defecto se conecta al localhost.
:param uri: URI de conexión.
:return: BD a utilizar.
"""
client = pymongo.MongoClient(uri)
return client.cryptongo
def get_hash(value):
"""
:param value: String con todos los valores de los campos del documento concatenados.
:return: String hash generado con sha-512.
"""
return sha512(value.encode('utf-8')).hexdigest()
def field_name(field):
"""
:param field: Tupla que tiene el nombre y valor de un campo del documento original.
:return: El nombre del campo.
"""
return field[0]
def remove_element_dictionary(dictionary, key):
"""
Un diccionario puede ser dinámico, por lo cuál se utiliza este método para eliminar un elemento del mismo.
:param dictionary:
:param key:
:return: Diccionario con el elemento eliminado.
"""
r = dict(dictionary)
del r[key]
return r
def get_ticker_hash(ticker_data):
"""
Genera el hash a partir de cada uno de los valores del documento.
El documento (o diccionario) será ordenado alfabéticamente según su key.
Como no se está ordenando los elementos del subdocumento 'quotes' se elimina temporalmente del diccionario
para no tenerlo en cuenta al momento de la creación del hash.
Si existe un valor diferente para el campo last_updated indica que los valores del subdocumento quotes también
cambió, por lo cuál este documento será almacenado posteriormente en la BD.
:param ticker_data: Documento de la criptomoneda.
:return: La función que genera el hash según el string con todos los valores del documento concatenados.
"""
ticker_data = remove_element_dictionary(ticker_data, 'quotes')
ticker_data = OrderedDict(sorted(ticker_data.items(), key=field_name))
# Se concatena en un string todos los valores ordenados del diccionario.
ticker_value = ''
for _, value in ticker_data.items():
ticker_value += str(value)
return get_hash(ticker_value)
def get_cryptocurrencies_from_api(position):
"""
De la API de CoinMarketCap se obtiene los documentos desde una posición inicial.
La API por cada endpoint sólo permite 100 documentos.
:return: Resultado de la consulta en formato json.
"""
url = API_URL_START.format(position)
r = requests.get(url)
if r.status_code == 200:
result = r.json()
return result
raise Exception('API Error') # Lanzar una excepción.
def get_num_cryptocurrencies_from_api():
"""
De la API de CoinMarketCap se obtiene la cantidad de criptomonedas existentes.
:return: Valor entero con la cantidad de documentos.
"""
r = requests.get(API_URL_LISTINGS)
if r.status_code == 200:
result = r.json()
return result['metadata']['num_cryptocurrencies']
raise Exception('API Error')
def check_if_exists(db_connection, ticker_hash):
"""
Verifica si la información ya existe en la BD (por medio de un hash).
La BD almacenará un historico de las criptomonedas.
:param db_connection: Conexión a la BD.
:param ticker_hash: Hash del documento generado previamente.
:return: Verdadero si el documento ya se encuentra, Falso si no.
"""
if db_connection.tickers.find_one({'ticker_hash': ticker_hash}):
return True
return False
def save_ticker(db_connection, ticker_data=None):
"""
Almacena el documento en la BD siempre y cuando no exista.
Se identifica si el documento ya fue almacenado o no por la generación de un hash.
:param db_connection:
:param ticker_data: Datos del documento.
:return: Verdadero si almacena el documento.
"""
# Evita operaciones si no existe información.
if not ticker_data:
return False
ticker_hash = get_ticker_hash(ticker_data)
if check_if_exists(db_connection, ticker_hash):
return False
ticker_data['ticker_hash'] = ticker_hash
# Almacena el documento en la BD de Mongo por medio de insertOne()
db_connection.tickers.insert_one(ticker_data)
return True
if __name__ == '__main__':
"""
Para crear la conexión ssh del contenedor de Docker,
es necesario que el programa inicialmente se este ejecutando contantemente.
import time
while True:
time.sleep(300)
"""
connection = get_db_connection('mongodb://crypto-mongodb-dev:27017/')
num_cryptocurrencies = get_num_cryptocurrencies_from_api()
print('\nCryptomonedas actuales en Coin Market Cap: {}'.format(num_cryptocurrencies))
cont = 0
for i in range(1, num_cryptocurrencies, 100):
tickers = get_cryptocurrencies_from_api(i)
tickers_data = tickers['data']
for value in tickers_data.values():
if save_ticker(connection, value):
cont += 1
print('Tickers almacenados... {}'.format(cont)) if cont > 0 else print('...')
print('\nCryptomonedas totales almacenadas: {}'.format(cont))
| [
"pymongo.MongoClient",
"requests.get"
] | [((485, 509), 'pymongo.MongoClient', 'pymongo.MongoClient', (['uri'], {}), '(uri)\n', (504, 509), False, 'import pymongo\n'), ((2675, 2692), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (2687, 2692), False, 'import requests\n'), ((3037, 3067), 'requests.get', 'requests.get', (['API_URL_LISTINGS'], {}), '(API_URL_LISTINGS)\n', (3049, 3067), False, 'import requests\n')] |
# -*- coding: utf-8 -*-
__author__ = 'gzp'
from danmaku_robot.models import RobotSettings
class Settings(object):
_settings = dict([
('room_id', 'int'),
('cookie', 'str'),
('question_prefix', 'str'),
('answer_prefix', 'str'),
('confidence', 'float'),
('question_robot', 'bool'),
('robot_self_debug', 'bool'),
('merge_thank_gift', 'str'),
('thank_gift', 'bool')
])
def __getattr__(self, item):
if item not in self._settings.keys():
raise AttributeError
return RobotSettings.get_setting_value(item)
def __setattr__(self, key, value):
if key not in self._settings.keys():
raise AttributeError
RobotSettings.set_setting_value(key, value, default_type=self._settings[key])
def values(self):
return {
key: getattr(self, key)
for key in self._settings.keys()
}
def fields(self):
return [key for key in self._settings.keys()]
| [
"danmaku_robot.models.RobotSettings.get_setting_value",
"danmaku_robot.models.RobotSettings.set_setting_value"
] | [((576, 613), 'danmaku_robot.models.RobotSettings.get_setting_value', 'RobotSettings.get_setting_value', (['item'], {}), '(item)\n', (607, 613), False, 'from danmaku_robot.models import RobotSettings\n'), ((741, 818), 'danmaku_robot.models.RobotSettings.set_setting_value', 'RobotSettings.set_setting_value', (['key', 'value'], {'default_type': 'self._settings[key]'}), '(key, value, default_type=self._settings[key])\n', (772, 818), False, 'from danmaku_robot.models import RobotSettings\n')] |
#!/usr/bin/env python
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkFiltersSources import vtkSuperquadricSource
from vtkmodules.vtkIOXML import vtkXMLPolyDataReader
from vtkmodules.vtkInteractionWidgets import vtkOrientationMarkerWidget
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkDataSetMapper,
vtkPolyDataMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
colors = vtkNamedColors()
file_name = get_program_parameters()
# Read the polydata for the icon
reader = vtkXMLPolyDataReader()
reader.SetFileName(file_name)
icon_mapper = vtkDataSetMapper()
icon_mapper.SetInputConnection(reader.GetOutputPort())
icon_actor = vtkActor()
icon_actor.SetMapper(icon_mapper)
icon_actor.GetProperty().SetColor(colors.GetColor3d('Silver'))
# Set up the renderer, window, and interactor
renderer = vtkRenderer()
renderer.SetBackground(colors.GetColor3d('SlateGray'))
ren_win = vtkRenderWindow()
ren_win.AddRenderer(renderer)
ren_win.SetSize(400, 400)
ren_win.SetWindowName('OrientationMarkerWidget1')
iren = vtkRenderWindowInteractor()
iren.SetRenderWindow(ren_win)
rgb = [0.0, 0.0, 0.0]
colors.GetColorRGB('Wheat', rgb)
# Set up the widget
widget = vtkOrientationMarkerWidget()
widget.SetOrientationMarker(icon_actor)
widget.SetInteractor(iren)
widget.SetViewport(0.0, 0.0, 0.2, 0.2)
widget.SetOutlineColor(*rgb)
widget.SetEnabled(1)
widget.InteractiveOn()
# Create a superquadric
superquadric_source = vtkSuperquadricSource()
superquadric_source.SetPhiRoundness(.2)
superquadric_source.SetThetaRoundness(.8)
# Create a mapper and actor
superquadric_mapper = vtkPolyDataMapper()
superquadric_mapper.SetInputConnection(superquadric_source.GetOutputPort())
superquadric_actor = vtkActor()
superquadric_actor.SetMapper(superquadric_mapper)
superquadric_actor.GetProperty().SetInterpolationToFlat()
superquadric_actor.GetProperty().SetDiffuseColor(colors.GetColor3d('Carrot'))
superquadric_actor.GetProperty().SetSpecularColor(colors.GetColor3d('White'))
superquadric_actor.GetProperty().SetDiffuse(0.6)
superquadric_actor.GetProperty().SetSpecular(0.5)
superquadric_actor.GetProperty().SetSpecularPower(5.0)
renderer.AddActor(superquadric_actor)
renderer.ResetCamera()
ren_win.Render()
iren.Initialize()
iren.Start()
def get_program_parameters():
import argparse
description = 'OrientationMarkerWidget1'
epilogue = """
"""
parser = argparse.ArgumentParser(description=description, epilog=epilogue,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('file_name', help='Bunny.vtp')
args = parser.parse_args()
return args.file_name
if __name__ == '__main__':
main()
| [
"vtkmodules.vtkRenderingCore.vtkActor",
"vtkmodules.vtkInteractionWidgets.vtkOrientationMarkerWidget",
"vtkmodules.vtkFiltersSources.vtkSuperquadricSource",
"argparse.ArgumentParser",
"vtkmodules.vtkRenderingCore.vtkDataSetMapper",
"vtkmodules.vtkRenderingCore.vtkRenderWindow",
"vtkmodules.vtkRenderingC... | [((614, 630), 'vtkmodules.vtkCommonColor.vtkNamedColors', 'vtkNamedColors', ([], {}), '()\n', (628, 630), False, 'from vtkmodules.vtkCommonColor import vtkNamedColors\n'), ((724, 746), 'vtkmodules.vtkIOXML.vtkXMLPolyDataReader', 'vtkXMLPolyDataReader', ([], {}), '()\n', (744, 746), False, 'from vtkmodules.vtkIOXML import vtkXMLPolyDataReader\n'), ((800, 818), 'vtkmodules.vtkRenderingCore.vtkDataSetMapper', 'vtkDataSetMapper', ([], {}), '()\n', (816, 818), False, 'from vtkmodules.vtkRenderingCore import vtkActor, vtkDataSetMapper, vtkPolyDataMapper, vtkRenderWindow, vtkRenderWindowInteractor, vtkRenderer\n'), ((896, 906), 'vtkmodules.vtkRenderingCore.vtkActor', 'vtkActor', ([], {}), '()\n', (904, 906), False, 'from vtkmodules.vtkRenderingCore import vtkActor, vtkDataSetMapper, vtkPolyDataMapper, vtkRenderWindow, vtkRenderWindowInteractor, vtkRenderer\n'), ((1078, 1091), 'vtkmodules.vtkRenderingCore.vtkRenderer', 'vtkRenderer', ([], {}), '()\n', (1089, 1091), False, 'from vtkmodules.vtkRenderingCore import vtkActor, vtkDataSetMapper, vtkPolyDataMapper, vtkRenderWindow, vtkRenderWindowInteractor, vtkRenderer\n'), ((1166, 1183), 'vtkmodules.vtkRenderingCore.vtkRenderWindow', 'vtkRenderWindow', ([], {}), '()\n', (1181, 1183), False, 'from vtkmodules.vtkRenderingCore import vtkActor, vtkDataSetMapper, vtkPolyDataMapper, vtkRenderWindow, vtkRenderWindowInteractor, vtkRenderer\n'), ((1314, 1341), 'vtkmodules.vtkRenderingCore.vtkRenderWindowInteractor', 'vtkRenderWindowInteractor', ([], {}), '()\n', (1339, 1341), False, 'from vtkmodules.vtkRenderingCore import vtkActor, vtkDataSetMapper, vtkPolyDataMapper, vtkRenderWindow, vtkRenderWindowInteractor, vtkRenderer\n'), ((1477, 1505), 'vtkmodules.vtkInteractionWidgets.vtkOrientationMarkerWidget', 'vtkOrientationMarkerWidget', ([], {}), '()\n', (1503, 1505), False, 'from vtkmodules.vtkInteractionWidgets import vtkOrientationMarkerWidget\n'), ((1764, 1787), 'vtkmodules.vtkFiltersSources.vtkSuperquadricSource', 'vtkSuperquadricSource', ([], {}), '()\n', (1785, 1787), False, 'from vtkmodules.vtkFiltersSources import vtkSuperquadricSource\n'), ((1937, 1956), 'vtkmodules.vtkRenderingCore.vtkPolyDataMapper', 'vtkPolyDataMapper', ([], {}), '()\n', (1954, 1956), False, 'from vtkmodules.vtkRenderingCore import vtkActor, vtkDataSetMapper, vtkPolyDataMapper, vtkRenderWindow, vtkRenderWindowInteractor, vtkRenderer\n'), ((2063, 2073), 'vtkmodules.vtkRenderingCore.vtkActor', 'vtkActor', ([], {}), '()\n', (2071, 2073), False, 'from vtkmodules.vtkRenderingCore import vtkActor, vtkDataSetMapper, vtkPolyDataMapper, vtkRenderWindow, vtkRenderWindowInteractor, vtkRenderer\n'), ((2789, 2912), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': 'description', 'epilog': 'epilogue', 'formatter_class': 'argparse.RawDescriptionHelpFormatter'}), '(description=description, epilog=epilogue,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n', (2812, 2912), False, 'import argparse\n')] |
from django.urls import path
from . import views
app_name = 'todos'
urlpatterns = [
path('', views.index, name="index"),
path('add', views.add, name="add"),
path('complete', views.complete, name="complete"),
path('delete', views.delete, name="delete")
]
| [
"django.urls.path"
] | [((90, 125), 'django.urls.path', 'path', (['""""""', 'views.index'], {'name': '"""index"""'}), "('', views.index, name='index')\n", (94, 125), False, 'from django.urls import path\n'), ((131, 165), 'django.urls.path', 'path', (['"""add"""', 'views.add'], {'name': '"""add"""'}), "('add', views.add, name='add')\n", (135, 165), False, 'from django.urls import path\n'), ((171, 220), 'django.urls.path', 'path', (['"""complete"""', 'views.complete'], {'name': '"""complete"""'}), "('complete', views.complete, name='complete')\n", (175, 220), False, 'from django.urls import path\n'), ((226, 269), 'django.urls.path', 'path', (['"""delete"""', 'views.delete'], {'name': '"""delete"""'}), "('delete', views.delete, name='delete')\n", (230, 269), False, 'from django.urls import path\n')] |
from datetime import date
from decimal import Decimal
from typing import List, Dict, Iterable, Optional
from vacations.config import (
APPROVE_BUTTON_ACTION_ID,
DENY_BUTTON_ACTION_ID,
DATEPICKER_START_ACTION_ID,
DATEPICKER_END_ACTION_ID,
REASON_INPUT_ACTION_ID,
REQUEST_VIEW_ID,
LEAVE_TYPES,
VACATION_TYPE_ACTION_ID
)
STATUS_EMOJIS = {
'unapproved': ':eight_spoked_asterisk:',
'approved': ':white_check_mark:',
'denied': ':negative_squared_cross_mark:'
}
DIVIDER = {
'type': 'divider'
}
def build_admin_request_notification(
leave_type: str,
date_from: date,
date_to: date,
duration: int,
days_left: int,
reason: str,
request_id: str,
user: str
) -> List[Dict]:
return [
{
'type': 'section',
'text': {
'type': 'mrkdwn',
'text': f'<!channel>\n<@{user}> has requested to go on a leave '
f'for *{duration} days*.'
}
},
_build_request_info_block(
date_from, date_to, leave_type, reason, days_left
),
{
'type': 'context',
'elements': [
{
'type': 'mrkdwn',
'text': f'Request #`{request_id}`'
}
]
},
{
'type': 'actions',
'elements': [
{
'type': 'button',
'text': {
'type': 'plain_text',
'emoji': True,
'text': 'Approve'
},
'style': 'primary',
'value': request_id,
'action_id': APPROVE_BUTTON_ACTION_ID
},
{
'type': 'button',
'text': {
'type': 'plain_text',
'emoji': True,
'text': 'Deny'
},
'style': 'danger',
'value': request_id,
'action_id': DENY_BUTTON_ACTION_ID
}
]
}
]
def build_request_view(days: Dict[str, Decimal]) -> Dict:
today = date.today().isoformat()
blocks = build_days_blocks(days) + [
{
'type': 'input',
'block_id': 'type',
'element': {
'type': 'static_select',
'action_id': VACATION_TYPE_ACTION_ID,
'placeholder': {
'type': 'plain_text',
'text': 'Select an item',
'emoji': True
},
'options': [
{
'text': {
'type': 'plain_text',
'text': type_.capitalize(),
'emoji': True
},
'value': type_
} for type_ in LEAVE_TYPES
]
},
'label': {
'type': 'plain_text',
'text': 'Leave Type',
'emoji': True
}
},
{
'type': 'input',
'block_id': 'start',
'element': {
'type': 'datepicker',
'action_id': DATEPICKER_START_ACTION_ID,
'initial_date': today,
'placeholder': {
'type': 'plain_text',
'text': 'Select a date',
'emoji': True
}
},
'label': {
'type': 'plain_text',
'text': 'Start Date',
'emoji': True
},
'hint': {
'type': 'plain_text',
'text': 'Pick a date you want to start your leave on'
}
},
{
'type': 'input',
'block_id': 'end',
'element': {
'type': 'datepicker',
'action_id': DATEPICKER_END_ACTION_ID,
'initial_date': today,
'placeholder': {
'type': 'plain_text',
'text': 'Select a date',
'emoji': True
}
},
'label': {
'type': 'plain_text',
'text': 'End Date',
'emoji': True
},
'hint': {
'type': 'plain_text',
'text': 'Pick a date you want to end your leave on'
}
},
{
'type': 'input',
'block_id': 'reason',
'optional': True,
'element': {
'type': 'plain_text_input',
'action_id': REASON_INPUT_ACTION_ID,
'multiline': True
},
'label': {
'type': 'plain_text',
'text': 'Reason'
},
'hint': {
'type': 'plain_text',
'text': 'The reason for your leave'
}
}
]
return {
'type': 'modal',
'callback_id': REQUEST_VIEW_ID,
'title': {
'type': 'plain_text',
'text': 'Request a leave',
'emoji': True
},
'submit': {
'type': 'plain_text',
'text': 'Request',
'emoji': True
},
'close': {
'type': 'plain_text',
'text': 'Cancel',
'emoji': True
},
'blocks': blocks
}
def build_history_blocks(history: Iterable[Dict]) -> List[Dict]:
blocks: List[Dict] = [DIVIDER]
for request in history:
blocks += _build_request_blocks(request)
return blocks
def _build_request_blocks(request: Dict) -> List[Dict]:
date_from = request['date_from'].date()
date_to = request['date_to'].date()
leave_type = request['leave_type']
reason = request['reason']
request_id = str(request['_id'])
return [
_build_request_info_block(date_from, date_to, leave_type, reason),
{
'type': 'context',
'elements': [
{
'type': 'mrkdwn',
'text': f'Request #`{request_id}`'
}
]
},
DIVIDER
]
def _build_request_info_block(
date_from: date,
date_to: date,
leave_type: str,
reason: str,
days_left: Optional[int] = None,
) -> Dict:
days_left_text = (
f'(*{days_left} days* left)' if days_left is not None else ''
)
return {
'type': 'section',
'fields': [
{
'type': 'mrkdwn',
'text': f'*Start:*\n{date_from.isoformat()}'
},
{
'type': 'mrkdwn',
'text': f'*End:*\n{date_to.isoformat()}'
},
{
'type': 'mrkdwn',
'text': f'*Type:*\n{leave_type.capitalize()} {days_left_text}'
},
{
'type': 'mrkdwn',
'text': f'*Reason:*\n{reason}'
},
]
}
def build_days_blocks(days: Dict[str, Decimal]) -> List[Dict]:
return [
{
'type': 'section',
'text': {
'type': 'mrkdwn',
'text': 'Days available:'
}
},
{
'type': 'section',
'fields': [
{
'type': 'mrkdwn',
'text': f'*{type_.capitalize()}:* {int(value)}'
} for type_, value in days.items()
]
}
]
| [
"datetime.date.today"
] | [((2323, 2335), 'datetime.date.today', 'date.today', ([], {}), '()\n', (2333, 2335), False, 'from datetime import date\n')] |
from datetime import datetime
def greetingTime():
current_hour = datetime.now().hour
if current_hour < 12:
return "Buenos días"
elif 12 <= current_hour < 18:
return "Buenas tardes"
else:
return "Buenas noches" | [
"datetime.datetime.now"
] | [((70, 84), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (82, 84), False, 'from datetime import datetime\n')] |
'''
0) Setup Data
1) Design Model (input_size, output_size, forward_pass)
2) Construct Loss, Optimizer
3) Training Loop
- forward pass
- gradients
- update weights
'''
import torch
import torch as th
import torch.nn as nn
import numpy as np
# Data process
from sklearn import datasets
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
# 0) prepare data
bc = datasets.load_breast_cancer()
X,y = bc.data, bc.target
n_samples, n_features = X.shape
print(n_samples,n_features)
X_train, X_test, y_train,y_test = train_test_split(X,y, test_size=0.2, random_state=123)
# scale features
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test) # use mean and std from training data
# to torch
X_train = th.from_numpy(X_train.astype(np.float32))
X_test = th.from_numpy(X_test.astype(np.float32))
y_train = th.from_numpy(y_train.astype(np.float32))
y_test = th.from_numpy(y_test.astype(np.float32))
# reshape y
y_train, y_test = y_train.view(y_train.shape[0], 1), y_test.view(y_test.shape[0],1)
# 1) model
class LogisticRegression(nn.Module):
def __init__(self, n_input_features):
super(LogisticRegression, self).__init__()
self.lin = nn.Linear(n_input_features, 1)
def forward(self, x):
y_pred = th.sigmoid(self.lin(x))
return y_pred
model = LogisticRegression(n_features)
#2) Loss
criterion = nn.BCELoss()
optimizer = torch.optim.SGD(model.parameters(), lr = 0.01)
# 3) training epoch
num_epochs = 100
for epoch in range(num_epochs):
# forward
y_pred = model(X_train)
# loss
loss = criterion(y_pred, y_train)
# gradients
loss.backward()
# updates and zero gradients
optimizer.step()
optimizer.zero_grad()
# epoch info
if (epoch + 1)%10==0:
print(f'epoch:{epoch+1},loss={loss.item():.8f}')
with torch.no_grad():
y_predicted = model(X_test) # sigmoid return
y_predicted_class = y_predicted.round() # >0.5 1 else 0
acc = y_predicted_class.eq(y_test).sum() / float(y_test.shape[0])
print(f'Accuracy: {acc:.3f}')
| [
"sklearn.model_selection.train_test_split",
"sklearn.datasets.load_breast_cancer",
"sklearn.preprocessing.StandardScaler",
"torch.nn.BCELoss",
"torch.nn.Linear",
"torch.no_grad"
] | [((425, 454), 'sklearn.datasets.load_breast_cancer', 'datasets.load_breast_cancer', ([], {}), '()\n', (452, 454), False, 'from sklearn import datasets\n'), ((576, 631), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.2)', 'random_state': '(123)'}), '(X, y, test_size=0.2, random_state=123)\n', (592, 631), False, 'from sklearn.model_selection import train_test_split\n'), ((654, 670), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (668, 670), False, 'from sklearn.preprocessing import StandardScaler\n'), ((1435, 1447), 'torch.nn.BCELoss', 'nn.BCELoss', ([], {}), '()\n', (1445, 1447), True, 'import torch.nn as nn\n'), ((1897, 1912), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1910, 1912), False, 'import torch\n'), ((1251, 1281), 'torch.nn.Linear', 'nn.Linear', (['n_input_features', '(1)'], {}), '(n_input_features, 1)\n', (1260, 1281), True, 'import torch.nn as nn\n')] |
from rest_framework import serializers
from .models import *
import backend.settings.dev as settings
from rest_framework.validators import UniqueValidator
import jwt
from rest_framework_jwt.utils import jwt_payload_handler
class ProfilePicSerializer(serializers.ModelSerializer):
class Meta:
model = MygUser
fields = ['profile_pic']
#owner = serializers.Field(source='user.username')
class MygUserSerializer(serializers.ModelSerializer):
avatar=serializers.SerializerMethodField()
class Meta:
model=MygUser
exlude=['user']
fields=('avatar','mom','dad',)
read_only_fields = ['profile_pic']
def get_avatar(self,MygUser):
request = self.context.get('request')
try:
IMG_url = MygUser.profile_pic.url
except:
IMG_url='/media/profile/e2.png'
return IMG_url
class UserSerializer(serializers.ModelSerializer):
myg_user = MygUserSerializer()
class Meta:
model = User
fields = ['username','password','first_name','last_name','myg_user','is_staff','is_superuser','is_authenticated',]
def create(self, validated_data):
myg_user = validated_data.pop('myg_user')
user = User.objects.create(**validated_data)
MygUser.objects.create(user=user, **myg_user)
user.set_password(user.password)
user.save()
return user
def update(self, instance, validated_data):
myg_user = validated_data.pop('myg_user')
myg_user = instance.myg_user
instance.username = validated_data.get('username', instance.username)
instance.email = validated_data.get('email', instance.email)
instance.save()
myg_user.save()
return instance
| [
"rest_framework.serializers.SerializerMethodField"
] | [((480, 515), 'rest_framework.serializers.SerializerMethodField', 'serializers.SerializerMethodField', ([], {}), '()\n', (513, 515), False, 'from rest_framework import serializers\n')] |
#!/usr/bin/env python
# Superficies de revolucion
import OpenGL
OpenGL.ERROR_ON_COPY = True
from OpenGL.GL import *
from OpenGL.GLU import gluOrtho2D
from OpenGL.GLUT import *
import sys, time
from sympy.core.sympify import sympify
from sympy import *
from OpenGL.constants import GLfloat
from OpenGL.GL.ARB.multisample import GL_MULTISAMPLE_ARB
import math
vec4 = GLfloat_4
tStart = t0 = time.time()
frames = 0
vertices = []
triangulos = []
normales_vertices = []
normales_triangulos = []
colores_vertices = []
colores_triangulos = []
camara_angulo_x = +10
camara_angulo_y = -45
ventana_pos_x = 50
ventana_pos_y = 50
ventana_tam_x = 1024
ventana_tam_y = 800
frustum_factor_escala = 1.0
frustum_dis_del = 0.1
frustum_dis_tra = 10.0
frustum_ancho = 0.5 * frustum_dis_del
frustum_factor_escala = 1.0
modoPunto = False
modoAlambre = False
modoSolido = False
modoSolidoColoreado = True
modoNormalesVertices = False
strings_ayuda = ["Teclas:"," 1 - Modo puntos"," 2 - Modo alambre",
" 3 - Modo solido"," 4 - Modo solido coloreado"," 5 - Activar/Desactivar normales"]
def fijarProyeccion():
ratioYX = float(ventana_tam_y) / float(ventana_tam_x)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glFrustum(-frustum_ancho, +frustum_ancho, -frustum_ancho*ratioYX, +frustum_ancho*ratioYX, +frustum_dis_del, +frustum_dis_tra)
glTranslatef( 0.0,0.0,-0.5*(frustum_dis_del+frustum_dis_tra))
glScalef( frustum_factor_escala, frustum_factor_escala, frustum_factor_escala )
def fijarViewportProyeccion():
glViewport( 0, 0, ventana_tam_x, ventana_tam_y )
fijarProyeccion()
def fijarCamara():
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glRotatef(camara_angulo_x,1,0,0)
glRotatef(camara_angulo_y,0,1,0)
def dibujarEjes():
long_ejes = 30.0
# establecer modo de dibujo a lineas (podría estar en puntos)
glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
# Ancho de línea
glLineWidth( 1.5 );
# dibujar tres segmentos
glBegin(GL_LINES)
# eje X, color rojo
glColor3f( 1.0, 0.0, 0.0 )
glVertex3f( -long_ejes, 0.0, 0.0 )
glVertex3f( +long_ejes, 0.0, 0.0 )
# eje Y, color verde
glColor3f( 0.0, 1.0, 0.0 )
glVertex3f( 0.0, -long_ejes, 0.0 )
glVertex3f( 0.0, +long_ejes, 0.0 )
# eje Z, color azul
glColor3f( 0.0, 0.0, 1.0 )
glVertex3f( 0.0, 0.0, -long_ejes )
glVertex3f( 0.0, 0.0, +long_ejes )
glEnd()
def dibujarObjetos():
if modoPunto == True:
glColor3f(0.0,0.0,0.0)
glBegin(GL_POINTS)
for v in vertices:
glVertex3f(v[0],v[1],v[2])
glEnd()
elif modoAlambre == True:
glColor3f(0.0,0.0,0.0)
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE)
glBegin( GL_TRIANGLES )
for tri in triangulos:
for j in range(3):
v = vertices[tri[j]]
glVertex3f(v[0],v[1],v[2])
glEnd()
elif modoSolido == True:
glColor3f(0.5,0.5,0.5)
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL)
glBegin( GL_TRIANGLES )
for tri in triangulos:
for j in range(3):
v = vertices[tri[j]]
glVertex3f(v[0],v[1],v[2])
glEnd()
elif modoSolidoColoreado == True:
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL)
glBegin( GL_TRIANGLES )
for tri in triangulos:
for j in range(3):
v = vertices[tri[j]]
c1 = colores_vertices[tri[j]][0]
c2 = colores_vertices[tri[j]][1]
c3 = colores_vertices[tri[j]][2]
glColor3f(c1,c2,c3)
glVertex3f(v[0],v[1],v[2])
glEnd()
'''
elif modoSolidoColoreadoCaras == True:
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL)
glBegin( GL_TRIANGLES )
i = 0
for tri in triangulos:
c1 = colores_triangulos[i][0]
c2 = colores_triangulos[i][1]
c3 = colores_triangulos[i][2]
glColor3f(c1,c2,c3)
i+=1
for j in range(3):
v = vertices[tri[j]]
glVertex3f(v[0],v[1],v[2])
glEnd()
'''
if modoNormalesVertices == True:
glColor3f(0.0,0.0,0.0)
glBegin( GL_LINES )
for i in range(len(vertices)):
v = vertices[i]
n = normales_vertices[i]
glVertex3f(v[0],v[1],v[2])
glVertex3f(v[0]+n[0]*0.25,v[1]+n[1]*0.25,v[2]+n[2]*0.25)
glEnd()
def ayuda():
glMatrixMode(GL_PROJECTION)
glPushMatrix()
glLoadIdentity()
gluOrtho2D(0.0, ventana_tam_x, 0.0, ventana_tam_y)
glMatrixMode(GL_MODELVIEW)
glPushMatrix()
glLoadIdentity()
glColor3f(1.0, 0.0, 0.0)
num_lineas = 0
for s in strings_ayuda:
glWindowPos2i(10, ventana_tam_y - 15*(num_lineas + 1))
for c in s:
glutBitmapCharacter(GLUT_BITMAP_9_BY_15, ord(c));
num_lineas += 1
glMatrixMode(GL_MODELVIEW)
glPopMatrix()
glMatrixMode(GL_PROJECTION)
glPopMatrix()
# Función de dibujado
def dibujar():
rotationRate = (time.time() - tStart) * 1.05
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
fijarViewportProyeccion()
fijarCamara()
dibujarEjes()
dibujarObjetos()
ayuda()
glutSwapBuffers()
def resetearEstados():
global modoPunto,modoAlambre,modoSolido,modoSolidoColoreado
modoPunto = False
modoAlambre = False
modoSolido = False
modoSolidoColoreado = False
# Teclas normales: para cambiar escala y velocidad
def teclaNormal(k, x, y):
global frustum_factor_escala, vertice_actual, velocidad, camara_angulo_x, camara_angulo_y, dibujoEvoluta
global modoPunto,modoAlambre,modoSolido,modoSolidoColoreado,modoSolidoColoreado,modoNormalesVertices
if k == b'+':
frustum_factor_escala *= 1.05
elif k == b'-':
frustum_factor_escala /= 1.05
elif k == b'1':
resetearEstados()
modoPunto = True
elif k == b'2':
resetearEstados()
modoAlambre = True
elif k == b'3':
resetearEstados()
modoSolido = True
elif k == b'4':
resetearEstados()
modoSolidoColoreado = True
elif k == b'5':
modoNormalesVertices = not modoNormalesVertices
elif k == b'r':
camara_angulo_x = camara_angulo_y = 0.0
elif k == b'q' or k == b'Q' or ord(k) == 27: # Escape
sys.exit(0)
else:
return
glutPostRedisplay()
# Teclas especiales: para cambiar la cámara
def teclaEspecial(k, x, y):
global camara_angulo_x, camara_angulo_y
if k == GLUT_KEY_UP:
camara_angulo_x += 5.0
elif k == GLUT_KEY_DOWN:
camara_angulo_x -= 5.0
elif k == GLUT_KEY_LEFT:
camara_angulo_y += 5.0
elif k == GLUT_KEY_RIGHT:
camara_angulo_y -= 5.0
else:
return
glutPostRedisplay()
# Nuevo tamaño de ventana
def cambioTamanio(width, height):
global ventana_tam_x,ventana_tam_y
ventana_tam_x = width
ventana_tam_y = height
fijarViewportProyeccion()
glutPostRedisplay()
origen = [-1,-1]
def pulsarRaton(boton,estado,x,y):
da = 5.0
redisp = False
global frustum_factor_escala,origen,camara_angulo_x,camara_angulo_y
if boton == GLUT_LEFT_BUTTON:
if estado == GLUT_UP:
origen = [-1,-1]
else:
origen = [x,y]
elif boton == 3: # Rueda arriba aumenta el zoom
frustum_factor_escala *= 1.05;
redisp = True
elif boton == 4: # Rueda abajo disminuye el zoom
frustum_factor_escala /= 1.05;
redisp = True
elif boton == 5: # Llevar la rueda a la izquierda gira la cámara a la izquierda
camara_angulo_y -= da
redisp = True
elif boton == 6: # Llevar la rueda a la derecha gira la cámara a la derecha
camara_angulo_y += da
redisp = True
if redisp:
glutPostRedisplay();
def moverRaton(x,y):
global camara_angulo_x,camara_angulo_y, origen
if origen[0] >= 0 and origen[1] >= 0:
camara_angulo_x += (y - origen[1])*0.25;
camara_angulo_y += (x - origen[0])*0.25;
origen[0] = x;
origen[1] = y;
# Redibujar
glutPostRedisplay();
def rotacionEjeY(v,angulo):
c = math.cos(angulo)
s = math.sin(angulo)
x = v[0]
y = v[1]
z = v[2]
vertice_rotado = [c*x+s*z,y,c*z-s*x]
return vertice_rotado
def sumaVectores(v1,v2):
vector_suma = [v1[0]+v2[0],v1[1]+v2[1],v1[2]+v2[2]]
return vector_suma
def restaVectores(v1,v2):
vector_resta = [v1[0]-v2[0],v1[1]-v2[1],v1[2]-v2[2]]
return vector_resta
def productoEscalar(v1,v2):
x1 = v1[0]
y1 = v1[1]
z1 = v1[2]
x2 = v2[0]
y2 = v2[1]
z2 = v2[2]
producto_escalar = x1*x2 + y1*y2 + z1*z2
return producto_escalar
def vectorNormalizado(v):
longitud = v[0]**2 + v[1]**2 + v[2]**2
norma = math.sqrt(longitud)
vector_normalizado = [v[0]/norma,v[1]/norma,v[2]/norma]
return vector_normalizado
def productoVectorial(v1,v2):
x1 = v1[0]
y1 = v1[1]
z1 = v1[2]
x2 = v2[0]
y2 = v2[1]
z2 = v2[2]
vector_producto_vectorial = [y1*z2 - z1*y2,z1*x2 - x1*z2,x1*y2 - y1*x2]
return vector_producto_vectorial
def creaNormales():
for tri in triangulos:
A = vertices[tri[0]]
B = vertices[tri[1]]
C = vertices[tri[2]]
B_A = restaVectores(B,A)
C_B = restaVectores(C,B)
nor_tri = productoVectorial(B_A,C_B)
normales_triangulos.append(vectorNormalizado(nor_tri))
normales_vertices_aux = [[0,0,0] for v in vertices]
for i in range(len(triangulos)):
normales_vertices_aux[triangulos[i][0]] = sumaVectores(normales_vertices_aux[triangulos[i][0]],normales_triangulos[i])
normales_vertices_aux[triangulos[i][1]] = sumaVectores(normales_vertices_aux[triangulos[i][1]],normales_triangulos[i])
normales_vertices_aux[triangulos[i][2]] = sumaVectores(normales_vertices_aux[triangulos[i][2]],normales_triangulos[i])
for v in normales_vertices_aux:
normales_vertices.append(vectorNormalizado(v))
def vectorValorAbsoluto(v):
vector_valor_absoluto = [abs(v[0]),abs(v[1]),abs(v[2])]
return vector_valor_absoluto
def creaColoresSegunNormales():
for v in normales_vertices:
colores_vertices.append(vectorValorAbsoluto(v))
for v in normales_triangulos:
colores_triangulos.append(vectorValorAbsoluto(v))
def revoluciona(vueltas):
for v in vertices:
if v[0] <= 0:
print("Error: debe verificarse f(t)>0")
sys.exit(-1)
copia_perfil = list(vertices)
num_ver_copia_perfil = len(copia_perfil)
angulo_inicial = 2*math.pi/(vueltas)
angulo = angulo_inicial
for i in range(vueltas-1):
for v in copia_perfil:
vertices.append(rotacionEjeY(v,angulo))
angulo += angulo_inicial
for perfil_i in range(vueltas):
for j in range(num_ver_copia_perfil-1):
primer_ver_perfil_i = num_ver_copia_perfil * perfil_i
if perfil_i == vueltas-1:
primer_ver_sig_perfil = 0
else:
primer_ver_sig_perfil = primer_ver_perfil_i + num_ver_copia_perfil
triangulos.append([primer_ver_perfil_i+j,primer_ver_sig_perfil+j,primer_ver_perfil_i+j+1])
triangulos.append([primer_ver_perfil_i+j+1,primer_ver_sig_perfil+j,primer_ver_sig_perfil+j+1])
creaNormales();
creaColoresSegunNormales();
def inicializar(argumentos):
if len(argumentos) < 6:
print("Es necesario introducir 6 argumentos")
print("Uso: python SuperficieRevolucion.py <f(t)> <g(t)> <número de puntos> <inicio> <fin>")
sys.exit(-1)
global vertices, x_t, y_t, z_t
t = symbols('t')
x_t = sympify(argumentos[1])
y_t = sympify(argumentos[2])
z_t = sympify('0')
num_puntos = int(argumentos[3])
inicio = float(argumentos[4])
final = float(argumentos[5])
vueltas = 32
longitud = final - inicio
incremento = longitud / (num_puntos - 1)
curva = Matrix([x_t,y_t,z_t])
for indice_punto in range(num_puntos):
t_var = inicio + indice_punto*incremento
vertices.append([curva[0].subs(t,t_var),curva[1].subs(t,t_var),curva[2].subs(t,t_var)])
revoluciona(vueltas)
glEnable(GL_NORMALIZE)
glEnable(GL_MULTISAMPLE_ARB);
glClearColor( 1.0, 1.0, 1.0, 1.0 ) ;
glColor3f(0.0,0.0,0.0)
def main(argumentos):
glutInit(argumentos)
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH | GLUT_MULTISAMPLE | GLUT_ALPHA)
glutInitWindowPosition(0, 0)
glutInitWindowSize(ventana_tam_x, ventana_tam_y)
glutCreateWindow("Superficie de revolucion")
inicializar(argumentos)
glEnable( GL_DEPTH_TEST )
glutDisplayFunc(dibujar)
glutReshapeFunc(cambioTamanio)
glutKeyboardFunc(teclaNormal)
glutSpecialFunc(teclaEspecial)
glutMouseFunc(pulsarRaton)
glutMotionFunc(moverRaton)
glutMainLoop()
if __name__ == '__main__':
main(sys.argv)
| [
"OpenGL.GLU.gluOrtho2D",
"sympy.core.sympify.sympify",
"math.sqrt",
"math.cos",
"sys.exit",
"math.sin",
"time.time"
] | [((392, 403), 'time.time', 'time.time', ([], {}), '()\n', (401, 403), False, 'import sys, time\n'), ((4597, 4647), 'OpenGL.GLU.gluOrtho2D', 'gluOrtho2D', (['(0.0)', 'ventana_tam_x', '(0.0)', 'ventana_tam_y'], {}), '(0.0, ventana_tam_x, 0.0, ventana_tam_y)\n', (4607, 4647), False, 'from OpenGL.GLU import gluOrtho2D\n'), ((8292, 8308), 'math.cos', 'math.cos', (['angulo'], {}), '(angulo)\n', (8300, 8308), False, 'import math\n'), ((8317, 8333), 'math.sin', 'math.sin', (['angulo'], {}), '(angulo)\n', (8325, 8333), False, 'import math\n'), ((8936, 8955), 'math.sqrt', 'math.sqrt', (['longitud'], {}), '(longitud)\n', (8945, 8955), False, 'import math\n'), ((11888, 11910), 'sympy.core.sympify.sympify', 'sympify', (['argumentos[1]'], {}), '(argumentos[1])\n', (11895, 11910), False, 'from sympy.core.sympify import sympify\n'), ((11929, 11951), 'sympy.core.sympify.sympify', 'sympify', (['argumentos[2]'], {}), '(argumentos[2])\n', (11936, 11951), False, 'from sympy.core.sympify import sympify\n'), ((11970, 11982), 'sympy.core.sympify.sympify', 'sympify', (['"""0"""'], {}), "('0')\n", (11977, 11982), False, 'from sympy.core.sympify import sympify\n'), ((11799, 11811), 'sys.exit', 'sys.exit', (['(-1)'], {}), '(-1)\n', (11807, 11811), False, 'import sys, time\n'), ((5124, 5135), 'time.time', 'time.time', ([], {}), '()\n', (5133, 5135), False, 'import sys, time\n'), ((10654, 10666), 'sys.exit', 'sys.exit', (['(-1)'], {}), '(-1)\n', (10662, 10666), False, 'import sys, time\n'), ((6438, 6449), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (6446, 6449), False, 'import sys, time\n')] |
"""Test /v1/datasets endpoints"""
import json
from unittest.mock import patch
import boto3
import botocore
from moto import mock_s3
from covid_api.core.config import INDICATOR_BUCKET
DATASET_METADATA_FILENAME = "dev-dataset-metadata.json"
DATASET_METADATA_GENERATOR_FUNCTION_NAME = "dev-dataset-metadata-generator"
@mock_s3
def _setup_s3(empty=False):
s3 = boto3.resource("s3")
bucket = s3.Bucket(INDICATOR_BUCKET)
bucket.create()
if empty:
return bucket
s3_keys = [
("indicators/test/super.csv", b"test"),
(
DATASET_METADATA_FILENAME,
json.dumps(
{
"_all": {
"co2": {
"domain": ["2019-01-01T00:00:00Z", "2020-01-01T00:00:00Z"]
},
"detections-plane": {
"domain": [
"2019-01-01T00:00:00Z",
"2019-10-10T00:00:00Z",
"2020-01-01T:00:00:00Z",
]
},
},
"global": {
"co2": {
"domain": ["2019-01-01T00:00:00Z", "2020-01-01T00:00:00Z"]
}
},
"tk": {
"detections-plane": {
"domain": [
"2019-01-01T00:00:00Z",
"2019-10-10T00:00:00Z",
"2020-01-01T:00:00:00Z",
]
}
},
"ny": {
"detections-ship": {
"domain": [
"2019-01-01T00:00:00Z",
"2019-10-10T00:00:00Z",
"2020-01-01T:00:00:00Z",
]
}
},
}
),
),
]
for key, content in s3_keys:
bucket.put_object(Body=content, Key=key)
return bucket
@mock_s3
def test_metadata_file_generation_triggered_if_not_found(
app, dataset_manager, monkeypatch
):
_setup_s3(empty=True)
with patch("covid_api.db.static.datasets.invoke_lambda") as mocked_invoke_lambda:
mocked_invoke_lambda.return_value = {"result": "success"}
# Load dataset will invoke the mocked-lambda and then attempt to load the file
# from S3 once the lambda finished executing. Since the mocked lambda
# doesn't actually write anything to S3 in this test, the call to load the file
# from S3 will fail. This is not a problem since this test is just to ascertain
# that the lambda was in fact triggered.
try:
dataset_manager()._load_domain_metadata()
except botocore.exceptions.ClientError as e:
if e.response["Error"]["Code"] == "404":
pass
mocked_invoke_lambda.assert_called_with(
lambda_function_name=DATASET_METADATA_GENERATOR_FUNCTION_NAME
)
@mock_s3
def test_datasets(app):
_setup_s3()
response = app.get("v1/datasets")
assert response.status_code == 200
content = json.loads(response.content)
assert "co2" in [d["id"] for d in content["datasets"]]
assert "detections-plane" in [d["id"] for d in content["datasets"]]
@mock_s3
def test_spotlight_datasets(app):
_setup_s3()
response = app.get("v1/datasets/tk")
assert response.status_code == 200
content = json.loads(response.content)
assert "co2" in [d["id"] for d in content["datasets"]]
assert "detections-plane" in [d["id"] for d in content["datasets"]]
assert "detections-ship" not in [d["id"] for d in content["datasets"]]
@mock_s3
def test_incorrect_dataset_id(app):
_setup_s3()
response = app.get("/v1/datasets/NOT_A_VALID_DATASET")
assert response.status_code == 404
| [
"boto3.resource",
"json.dumps",
"unittest.mock.patch",
"json.loads"
] | [((368, 388), 'boto3.resource', 'boto3.resource', (['"""s3"""'], {}), "('s3')\n", (382, 388), False, 'import boto3\n'), ((3379, 3407), 'json.loads', 'json.loads', (['response.content'], {}), '(response.content)\n', (3389, 3407), False, 'import json\n'), ((3697, 3725), 'json.loads', 'json.loads', (['response.content'], {}), '(response.content)\n', (3707, 3725), False, 'import json\n'), ((2374, 2425), 'unittest.mock.patch', 'patch', (['"""covid_api.db.static.datasets.invoke_lambda"""'], {}), "('covid_api.db.static.datasets.invoke_lambda')\n", (2379, 2425), False, 'from unittest.mock import patch\n'), ((611, 1151), 'json.dumps', 'json.dumps', (["{'_all': {'co2': {'domain': ['2019-01-01T00:00:00Z', '2020-01-01T00:00:00Z'\n ]}, 'detections-plane': {'domain': ['2019-01-01T00:00:00Z',\n '2019-10-10T00:00:00Z', '2020-01-01T:00:00:00Z']}}, 'global': {'co2': {\n 'domain': ['2019-01-01T00:00:00Z', '2020-01-01T00:00:00Z']}}, 'tk': {\n 'detections-plane': {'domain': ['2019-01-01T00:00:00Z',\n '2019-10-10T00:00:00Z', '2020-01-01T:00:00:00Z']}}, 'ny': {\n 'detections-ship': {'domain': ['2019-01-01T00:00:00Z',\n '2019-10-10T00:00:00Z', '2020-01-01T:00:00:00Z']}}}"], {}), "({'_all': {'co2': {'domain': ['2019-01-01T00:00:00Z',\n '2020-01-01T00:00:00Z']}, 'detections-plane': {'domain': [\n '2019-01-01T00:00:00Z', '2019-10-10T00:00:00Z', '2020-01-01T:00:00:00Z'\n ]}}, 'global': {'co2': {'domain': ['2019-01-01T00:00:00Z',\n '2020-01-01T00:00:00Z']}}, 'tk': {'detections-plane': {'domain': [\n '2019-01-01T00:00:00Z', '2019-10-10T00:00:00Z', '2020-01-01T:00:00:00Z'\n ]}}, 'ny': {'detections-ship': {'domain': ['2019-01-01T00:00:00Z',\n '2019-10-10T00:00:00Z', '2020-01-01T:00:00:00Z']}}})\n", (621, 1151), False, 'import json\n')] |
import arrow
from helpers import read_data, write_data, get_settings, package_comment
import api
settings = get_settings()
sync_dates = read_data('sync_dates')
last_sync = arrow.get(sync_dates['comments'])
article_map = read_data('article_map')
comment_map = read_data('comment_map')
comment_article_map = read_data('comment_article_map')
for src_article in article_map:
dst_article = article_map[src_article]
print('\nGetting comments in article {}...'.format(src_article))
url = '{}/{}/articles/{}/comments.json'.format(settings['src_root'], settings['locale'], src_article)
comments = api.get_resource_list(url)
if not comments:
print('- no comments found')
continue
for src_comment in comments:
if src_comment['body'] == '':
continue
if last_sync < arrow.get(src_comment['created_at']):
print('- adding new comment {} to article {}'.format(src_comment['id'], dst_article))
url = '{}/articles/{}/comments.json'.format(settings['dst_root'], dst_article)
payload = package_comment(src_comment)
new_comment = api.post_resource(url, payload)
if new_comment is False:
print('Skipping comment {}'.format(src_comment['id']))
continue
comment_map[str(src_comment['id'])] = new_comment['id']
comment_article_map[str(src_comment['id'])] = src_article
continue
if last_sync < arrow.get(src_comment['updated_at']):
print('- updating comment {} in article {}'.format(src_comment['id'], dst_article))
dst_comment = comment_map[str(src_comment['id'])]
url = '{}/articles/{}/comments/{}.json'.format(settings['dst_root'], dst_article, dst_comment)
payload = package_comment(src_comment, put=True)
response = api.put_resource(url, payload)
if response is False:
print('Skipping comment {}'.format(src_comment['id']))
continue
print('- comment {} is up to date'.format(src_comment['id']))
utc = arrow.utcnow()
sync_dates['comments'] = utc.format()
write_data(sync_dates, 'sync_dates')
write_data(comment_map, 'comment_map')
write_data(comment_article_map, 'comment_article_map')
| [
"helpers.get_settings",
"arrow.utcnow",
"helpers.write_data",
"api.put_resource",
"api.get_resource_list",
"helpers.read_data",
"arrow.get",
"helpers.package_comment",
"api.post_resource"
] | [((111, 125), 'helpers.get_settings', 'get_settings', ([], {}), '()\n', (123, 125), False, 'from helpers import read_data, write_data, get_settings, package_comment\n'), ((139, 162), 'helpers.read_data', 'read_data', (['"""sync_dates"""'], {}), "('sync_dates')\n", (148, 162), False, 'from helpers import read_data, write_data, get_settings, package_comment\n'), ((175, 208), 'arrow.get', 'arrow.get', (["sync_dates['comments']"], {}), "(sync_dates['comments'])\n", (184, 208), False, 'import arrow\n'), ((223, 247), 'helpers.read_data', 'read_data', (['"""article_map"""'], {}), "('article_map')\n", (232, 247), False, 'from helpers import read_data, write_data, get_settings, package_comment\n'), ((262, 286), 'helpers.read_data', 'read_data', (['"""comment_map"""'], {}), "('comment_map')\n", (271, 286), False, 'from helpers import read_data, write_data, get_settings, package_comment\n'), ((309, 341), 'helpers.read_data', 'read_data', (['"""comment_article_map"""'], {}), "('comment_article_map')\n", (318, 341), False, 'from helpers import read_data, write_data, get_settings, package_comment\n'), ((2097, 2111), 'arrow.utcnow', 'arrow.utcnow', ([], {}), '()\n', (2109, 2111), False, 'import arrow\n'), ((2150, 2186), 'helpers.write_data', 'write_data', (['sync_dates', '"""sync_dates"""'], {}), "(sync_dates, 'sync_dates')\n", (2160, 2186), False, 'from helpers import read_data, write_data, get_settings, package_comment\n'), ((2187, 2225), 'helpers.write_data', 'write_data', (['comment_map', '"""comment_map"""'], {}), "(comment_map, 'comment_map')\n", (2197, 2225), False, 'from helpers import read_data, write_data, get_settings, package_comment\n'), ((2226, 2280), 'helpers.write_data', 'write_data', (['comment_article_map', '"""comment_article_map"""'], {}), "(comment_article_map, 'comment_article_map')\n", (2236, 2280), False, 'from helpers import read_data, write_data, get_settings, package_comment\n'), ((608, 634), 'api.get_resource_list', 'api.get_resource_list', (['url'], {}), '(url)\n', (629, 634), False, 'import api\n'), ((825, 861), 'arrow.get', 'arrow.get', (["src_comment['created_at']"], {}), "(src_comment['created_at'])\n", (834, 861), False, 'import arrow\n'), ((1074, 1102), 'helpers.package_comment', 'package_comment', (['src_comment'], {}), '(src_comment)\n', (1089, 1102), False, 'from helpers import read_data, write_data, get_settings, package_comment\n'), ((1129, 1160), 'api.post_resource', 'api.post_resource', (['url', 'payload'], {}), '(url, payload)\n', (1146, 1160), False, 'import api\n'), ((1476, 1512), 'arrow.get', 'arrow.get', (["src_comment['updated_at']"], {}), "(src_comment['updated_at'])\n", (1485, 1512), False, 'import arrow\n'), ((1801, 1839), 'helpers.package_comment', 'package_comment', (['src_comment'], {'put': '(True)'}), '(src_comment, put=True)\n', (1816, 1839), False, 'from helpers import read_data, write_data, get_settings, package_comment\n'), ((1863, 1893), 'api.put_resource', 'api.put_resource', (['url', 'payload'], {}), '(url, payload)\n', (1879, 1893), False, 'import api\n')] |
# coding: utf-8
# !/usr/bin/env python3
import csv
import os, os.path
import sys
import argparse
from WriteExcel import Excel
from log import debug, info, error
from baidu_traslate import *
class Nessus(object):
"""处理Nessus扫描结果"""
def __init__(self, csv_name):
self.csv_name = csv_name
self.all_csv_res = []
if os.path.isfile(self.csv_name):
os.chdir(os.path.dirname(os.path.abspath(self.csv_name)))
self.read_csv(self.csv_name)
else:
os.chdir(self.csv_name)
self.file_list = [file for file in os.listdir() if os.path.isfile(file) and file.endswith('.csv')]
for file in self.file_list:
debug(file)
self.read_csv(file)
def __len__(self):
return len(self.all_csv_res)
def __iter__(self):
return iter(self.all_csv_res)
def __next__(self):
pass
def read_csv(self, file):
with open(file, 'r') as csv_file:
csv_res = csv.reader(csv_file)
debug(csv_res)
for row in csv_res:
debug(row)
if row not in self.all_csv_res:
self.all_csv_res.append(row)
all_res = self.all_csv_res
return all_res
def check_risk(risk):
if risk == 'None':
return 'None'
elif risk == 'Low':
return '低危'
elif risk == 'Medium':
return '中危'
elif risk == 'High':
return '高危'
elif risk == 'Critical':
return '严重'
def get_args():
parser = argparse.ArgumentParser(prog='nessusor', description='默认在程序目录下生成xls格式文档')
parser.add_argument("-p", help="输入报告所在目录或Nessus所在的完整路径", type=str)
parser.add_argument("-s", help="保存的文件名称", type=str)
args = parser.parse_args()
return vars(args)
if __name__ == '__main__':
args = get_args()
path = args['p']
output = args['s']
if path is None or output is None:
print("""python3 Nessus.py -p /path/nessus.csv or /path -s xxx""")
sys.exit(0)
try:
# nessus = Nessus('/Users/m1k3/127_0_0_1_yi2b5q.csv')
nessus = Nessus(path)
new_nessus = []
for i in nessus:
risk = check_risk(i[3])
if risk == 'None':
pass
# CVE CVSS Risk Host Protocol Port Name Synopsis Description Solution
else:
name = translate(i[7])
synopsis = translate(i[8])
description = translate(i[9])
solution = translate(i[10])
row = (i[1], i[2], risk, i[4], i[5], i[6], name, synopsis, description, solution)
# info(list(row))
new_nessus.append(list(row))
excel = Excel(output + '.xls', '/Users/m1k3', new_nessus)
excel.write_data()
except (Exception,KeyboardInterrupt) as e:
error(e)
| [
"os.listdir",
"WriteExcel.Excel",
"argparse.ArgumentParser",
"log.error",
"os.path.isfile",
"os.chdir",
"log.debug",
"sys.exit",
"os.path.abspath",
"csv.reader"
] | [((1560, 1633), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'prog': '"""nessusor"""', 'description': '"""默认在程序目录下生成xls格式文档"""'}), "(prog='nessusor', description='默认在程序目录下生成xls格式文档')\n", (1583, 1633), False, 'import argparse\n'), ((349, 378), 'os.path.isfile', 'os.path.isfile', (['self.csv_name'], {}), '(self.csv_name)\n', (363, 378), False, 'import os, os.path\n'), ((2033, 2044), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (2041, 2044), False, 'import sys\n'), ((2752, 2801), 'WriteExcel.Excel', 'Excel', (["(output + '.xls')", '"""/Users/m1k3"""', 'new_nessus'], {}), "(output + '.xls', '/Users/m1k3', new_nessus)\n", (2757, 2801), False, 'from WriteExcel import Excel\n'), ((517, 540), 'os.chdir', 'os.chdir', (['self.csv_name'], {}), '(self.csv_name)\n', (525, 540), False, 'import os, os.path\n'), ((1013, 1033), 'csv.reader', 'csv.reader', (['csv_file'], {}), '(csv_file)\n', (1023, 1033), False, 'import csv\n'), ((1046, 1060), 'log.debug', 'debug', (['csv_res'], {}), '(csv_res)\n', (1051, 1060), False, 'from log import debug, info, error\n'), ((2884, 2892), 'log.error', 'error', (['e'], {}), '(e)\n', (2889, 2892), False, 'from log import debug, info, error\n'), ((708, 719), 'log.debug', 'debug', (['file'], {}), '(file)\n', (713, 719), False, 'from log import debug, info, error\n'), ((1109, 1119), 'log.debug', 'debug', (['row'], {}), '(row)\n', (1114, 1119), False, 'from log import debug, info, error\n'), ((417, 447), 'os.path.abspath', 'os.path.abspath', (['self.csv_name'], {}), '(self.csv_name)\n', (432, 447), False, 'import os, os.path\n'), ((588, 600), 'os.listdir', 'os.listdir', ([], {}), '()\n', (598, 600), False, 'import os, os.path\n'), ((604, 624), 'os.path.isfile', 'os.path.isfile', (['file'], {}), '(file)\n', (618, 624), False, 'import os, os.path\n')] |
from django.test import TestCase
from django.core.urlresolvers import reverse
from django.utils import timezone
from django.core.urlresolvers import reverse
from mainapp.forms import CreateReviewForm
from mainapp.models import Researcher, Review, Paper, Query
from django.contrib.auth.models import User
# tests for sysreviewer app models (only testing custom methods) - model testing tests for unicode returns and slug creation
# Researcher model testing
class ResearcherMethodTests(TestCase):
#test unicode representation
def test_unicode_researcher_representation(self):
#create test user for foreign key
testUser=User(username = "bill")
testUser.save()
#create test researcher
testResearcher = Researcher(user= testUser, name="bill", surname="bill")
testResearcher.save()
#test
self.assertEqual(unicode(testResearcher), testResearcher.name)
# review model testing
class ReviewMethodTests(TestCase):
#test unicode representation
def test_unicode_Review_representation(self):
#create test user for foreign key
testCreator=User(username="bill")
testCreator.save()
#create test review
testReview = Review(creator=testCreator , name= "Test the review unicode")
testReview.save()
#test
self.assertEqual(unicode(testReview), testReview.name)
#test slug representation
def test_slug_Review_representation(self):
#create test user for foreign key
testCreator=User(username="bill")
testCreator.save()
#create test review
testReview = Review(creator=testCreator, name= "Test the review slug")
testReview.save()
#test
self.assertEqual(testReview.slug, "test-the-review-slug")
# query model testing
class QueryMethodTests(TestCase):
#test unicode representation
def test_unicode_query_representation(self):
#create test user for foreign key in review
testCreator=User(username="bill")
testCreator.save()
#create test review for foreign key in query
testReview = Review(creator=testCreator, name= "Test Review for testing" )
testReview.save()
#create test query
testQuery = Query(review=testReview,query_string="test the query unicode")
testQuery.save()
#test
self.assertEqual(unicode(testQuery), testQuery.query_string)
#paper model test
class paperMethodTests(TestCase):
#test unicode representation
def test_unicode_paper_representation(self):
#create test user for foreign key in review
testCreator=User(username="bill")
testCreator.save()
#create test review for foreign key in paper
testReview = Review(creator=testCreator, name= "Test Review for testing" )
testReview.save()
#create paper
testPaper = Paper(review=testReview,title="test the paper unicode")
testPaper.save()
#test
self.assertEqual(unicode(testPaper), testPaper.title)
# testing views
#test index view
class IndexViewTests(TestCase):
#set up test user
def setUp(self):
user = User.objects.create_user(username='bill', email='<EMAIL>', password='<PASSWORD>')
# test index content with no user logged in
def test_index_view_with_no_login(self):
response = self.client.get(reverse('index'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, "Welcome to SysReviewer - The Systematic Review App")
#test when user logged in
def test_index_view_with_login(self):
self.client.login(username='bill', password='<PASSWORD>')
response = self.client.get(reverse('index'), follow=True)
user = User.objects.get(username='bill')
self.assertEqual(response.status_code, 200)
self.assertContains(response, "You aren't working on any reviews")
self.assertEqual(response.context['user'], user)
#test CreateReviewForm form
class CreateReviewFormTests(TestCase):
def test_valid_review_form(self):
#create test data
data = {'name': 'test the form', 'description':'test the form',}
#create form
form = CreateReviewForm(data=data)
#check form is valid
self.assertTrue(form.is_valid())
def test_invalid_review_form(self):
#create test incorrect data
data = {'name': '', 'description':'test the form',}
#create form
form = CreateReviewForm(data=data)
#check form is not valid
self.assertFalse(form.is_valid())
| [
"django.contrib.auth.models.User",
"django.core.urlresolvers.reverse",
"django.contrib.auth.models.User.objects.create_user",
"mainapp.models.Researcher",
"mainapp.models.Query",
"mainapp.forms.CreateReviewForm",
"django.contrib.auth.models.User.objects.get",
"mainapp.models.Paper",
"mainapp.models.... | [((647, 668), 'django.contrib.auth.models.User', 'User', ([], {'username': '"""bill"""'}), "(username='bill')\n", (651, 668), False, 'from django.contrib.auth.models import User\n'), ((752, 806), 'mainapp.models.Researcher', 'Researcher', ([], {'user': 'testUser', 'name': '"""bill"""', 'surname': '"""bill"""'}), "(user=testUser, name='bill', surname='bill')\n", (762, 806), False, 'from mainapp.models import Researcher, Review, Paper, Query\n'), ((1128, 1149), 'django.contrib.auth.models.User', 'User', ([], {'username': '"""bill"""'}), "(username='bill')\n", (1132, 1149), False, 'from django.contrib.auth.models import User\n'), ((1226, 1285), 'mainapp.models.Review', 'Review', ([], {'creator': 'testCreator', 'name': '"""Test the review unicode"""'}), "(creator=testCreator, name='Test the review unicode')\n", (1232, 1285), False, 'from mainapp.models import Researcher, Review, Paper, Query\n'), ((1531, 1552), 'django.contrib.auth.models.User', 'User', ([], {'username': '"""bill"""'}), "(username='bill')\n", (1535, 1552), False, 'from django.contrib.auth.models import User\n'), ((1629, 1685), 'mainapp.models.Review', 'Review', ([], {'creator': 'testCreator', 'name': '"""Test the review slug"""'}), "(creator=testCreator, name='Test the review slug')\n", (1635, 1685), False, 'from mainapp.models import Researcher, Review, Paper, Query\n'), ((2005, 2026), 'django.contrib.auth.models.User', 'User', ([], {'username': '"""bill"""'}), "(username='bill')\n", (2009, 2026), False, 'from django.contrib.auth.models import User\n'), ((2128, 2187), 'mainapp.models.Review', 'Review', ([], {'creator': 'testCreator', 'name': '"""Test Review for testing"""'}), "(creator=testCreator, name='Test Review for testing')\n", (2134, 2187), False, 'from mainapp.models import Researcher, Review, Paper, Query\n'), ((2263, 2326), 'mainapp.models.Query', 'Query', ([], {'review': 'testReview', 'query_string': '"""test the query unicode"""'}), "(review=testReview, query_string='test the query unicode')\n", (2268, 2326), False, 'from mainapp.models import Researcher, Review, Paper, Query\n'), ((2642, 2663), 'django.contrib.auth.models.User', 'User', ([], {'username': '"""bill"""'}), "(username='bill')\n", (2646, 2663), False, 'from django.contrib.auth.models import User\n'), ((2765, 2824), 'mainapp.models.Review', 'Review', ([], {'creator': 'testCreator', 'name': '"""Test Review for testing"""'}), "(creator=testCreator, name='Test Review for testing')\n", (2771, 2824), False, 'from mainapp.models import Researcher, Review, Paper, Query\n'), ((2895, 2951), 'mainapp.models.Paper', 'Paper', ([], {'review': 'testReview', 'title': '"""test the paper unicode"""'}), "(review=testReview, title='test the paper unicode')\n", (2900, 2951), False, 'from mainapp.models import Researcher, Review, Paper, Query\n'), ((3178, 3264), 'django.contrib.auth.models.User.objects.create_user', 'User.objects.create_user', ([], {'username': '"""bill"""', 'email': '"""<EMAIL>"""', 'password': '"""<PASSWORD>"""'}), "(username='bill', email='<EMAIL>', password=\n '<PASSWORD>')\n", (3202, 3264), False, 'from django.contrib.auth.models import User\n'), ((3771, 3804), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', ([], {'username': '"""bill"""'}), "(username='bill')\n", (3787, 3804), False, 'from django.contrib.auth.models import User\n'), ((4231, 4258), 'mainapp.forms.CreateReviewForm', 'CreateReviewForm', ([], {'data': 'data'}), '(data=data)\n', (4247, 4258), False, 'from mainapp.forms import CreateReviewForm\n'), ((4502, 4529), 'mainapp.forms.CreateReviewForm', 'CreateReviewForm', ([], {'data': 'data'}), '(data=data)\n', (4518, 4529), False, 'from mainapp.forms import CreateReviewForm\n'), ((3389, 3405), 'django.core.urlresolvers.reverse', 'reverse', (['"""index"""'], {}), "('index')\n", (3396, 3405), False, 'from django.core.urlresolvers import reverse\n'), ((3725, 3741), 'django.core.urlresolvers.reverse', 'reverse', (['"""index"""'], {}), "('index')\n", (3732, 3741), False, 'from django.core.urlresolvers import reverse\n')] |
"""
Django settings for webDe project.
Generated by 'django-admin startproject' using Django 2.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
from django.urls import reverse_lazy
try:
from .LocalSetting import *
DEBUG = True
ALLOWED_HOSTS = ['*']
except:
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY =')z(66-zt@g3y_=mh(n(xs8!es%yi0f7aczob9m&m)xikyrx#*6'
# SECURITY WARNING: don't run with debug turned on in production!
#DEBUG = True
#ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'apps.accounts',
'apps.entradas',
#'social_django',
'taggit',
'sslserver',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'webDe.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'social_django.context_processors.backends',
'social_django.context_processors.login_redirect',
],
},
},
]
WSGI_APPLICATION = 'webDe.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticRoot')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL ='/media/'
#Social Media Login
AUTHENTICATION_BACKENDS = (
# 'social_core.backends.amazon.AmazonOAuth2',
# # 'social_core.backends.bitbucket.BitbucketOAuth',
# 'social_core.backends.facebook.FacebookAppOAuth2',
# 'social_core.backends.facebook.FacebookOAuth2',
# 'social_core.backends.github.GithubOAuth2',
# 'social_core.backends.gitlab.GitLabOAuth2',
# 'social_core.backends.google.GoogleOAuth',
# 'social_core.backends.google.GoogleOAuth2',
# 'social_core.backends.google.GoogleOpenId',
# 'social_core.backends.google.GooglePlusAuth',
# 'social_core.backends.google_openidconnect.GoogleOpenIdConnect',
# 'social_core.backends.instagram.InstagramOAuth2',
# 'social_core.backends.linkedin.LinkedinOAuth',
# 'social_core.backends.linkedin.LinkedinOAuth2',
# 'social_core.backends.spotify.SpotifyOAuth2',
# 'social_core.backends.trello.TrelloOAuth',
# 'social_core.backends.tumblr.TumblrOAuth',
# 'social_core.backends.twitter.TwitterOAuth',
# 'social_core.backends.yahoo.YahooOAuth',
# 'social_core.backends.yahoo.YahooOpenId',
'django.contrib.auth.backends.ModelBackend',
)
#Para esto hay que tenerlo con https la redireccion
#SOCIAL_AUTH_FACEBOOK_KEY = FACEBOOK_KEY
#SOCIAL_AUTH_FACEBOOK_SECRET = FACEBOOK_SECRET
#para traer el email
#SOCIAL_AUTH_FACEBOOK_SCOPE = ['email']
#SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = {
# 'fields': 'id,name,email',
#}
#SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = GOOGLE_KEY
#SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = GOOGLE_SECRET
#SOCIAL_AUTH_USERNAME_IS_FULL_EMAIL = True
#SOCIAL_AUTH_PIPELINE = (
#revisar para implementar que nose repitan los email
# 'utilsSocialPipe.check_email_exists',
# 'social_core.pipeline.social_auth.social_details',
# 'social_core.pipeline.social_auth.social_uid',
# 'social_core.pipeline.social_auth.auth_allowed',
# 'social_core.pipeline.social_auth.social_user',
# 'social_core.pipeline.user.get_username',
# 'social_core.pipeline.mail.mail_validation',
# 'social_core.pipeline.user.create_user',
# 'social_core.pipeline.social_auth.associate_user',
# 'social_core.pipeline.debug.debug',
# 'social_core.pipeline.social_auth.load_extra_data',
# 'social_core.pipeline.user.user_details',
# 'social_core.pipeline.debug.debug'
#)
#Login opcions
#LOGIN_URL = '/login/'
LOGOUT_REDIRECT_URL = reverse_lazy('accounts:login')
LOGIN_REDIRECT_URL = reverse_lazy('entradas:index')
#SSL
SECURE_SSL_REDIRECT = True
CSRF_COOKIE_SECURE = True
#config file
FILE_UPLOAD_PERMISSIONS = 0o644
| [
"os.path.abspath",
"os.path.join",
"django.urls.reverse_lazy"
] | [((3652, 3688), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""staticRoot"""'], {}), "(BASE_DIR, 'staticRoot')\n", (3664, 3688), False, 'import os\n'), ((3702, 3733), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""media"""'], {}), "(BASE_DIR, 'media')\n", (3714, 3733), False, 'import os\n'), ((6097, 6127), 'django.urls.reverse_lazy', 'reverse_lazy', (['"""accounts:login"""'], {}), "('accounts:login')\n", (6109, 6127), False, 'from django.urls import reverse_lazy\n'), ((6149, 6179), 'django.urls.reverse_lazy', 'reverse_lazy', (['"""entradas:index"""'], {}), "('entradas:index')\n", (6161, 6179), False, 'from django.urls import reverse_lazy\n'), ((3603, 3635), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""static"""'], {}), "(BASE_DIR, 'static')\n", (3615, 3635), False, 'import os\n'), ((671, 696), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (686, 696), False, 'import os\n'), ((2710, 2746), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""db.sqlite3"""'], {}), "(BASE_DIR, 'db.sqlite3')\n", (2722, 2746), False, 'import os\n'), ((1952, 1987), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""templates"""'], {}), "(BASE_DIR, 'templates')\n", (1964, 1987), False, 'import os\n')] |
#! python3
# randomQUizGenerator.py - Cria provas com perguntas e respostas em ordem aleatória
# juntamente com os gabaritos contendo as respostas.
import random
captals = {'Acre (AC)': 'Rio Branco', 'Alagoas (AL)': 'Maceió', 'Amapá (AP)': 'Macapá', 'Amazonas (AM)': 'Manaus',
'Bahia (BA)': 'Salvador', 'Ceará (CE)': 'Fortaleza', 'Distrito Federal (DF)': 'Brasília',
'Espírito Santo (ES)': 'Vitória', 'Goiás (GO)': 'Goiânia', 'Maranhão (MA)': 'São Luís', 'Mato Grosso (MT)':
'Cuiabá', 'Mato Grosso do Sul (MS)': 'Campo Grande', 'Minas Gerais (MG)': 'Belo Horizonte', 'Pará (PA)':
'Belém', 'Paraíba (PB)': 'João Pessoa', 'Paraná (PR)': 'Curitiba', 'Pernambuco (PE)': 'Recife',
'Piauí (PI)': 'Teresina', 'Rio de Janeiro (RJ)': 'Rio de Janeiro', 'Rio Grande do Norte (RN)': 'Natal',
'Rio Grande do Sul (RS)': 'Porto Alegre', 'Rondônia (RO)': 'Porto Velho', 'Roraima (RR)': 'Boa Vista',
'Santa Catarina (SC)': 'Florianópolis', 'São Paulo (SP)': 'São Paulo', 'Sergipe (SE)': 'Aracaju',
'Tocantins (TO)': 'Palmas'}
# Gera os arquivos contendo as provas de acordo com a quantidade de loopings.
for quizNum in range(1):
# Cria os arquivos de prova e gabarito
quizFile = open(f'captalsquiz{quizNum + 1}.txt', 'w', encoding='utf-8')
answerKeyFile = open(f'capital_answers{quizNum + 1}.txt', "w", encoding='UTF-8')
# Escreve o cabeçalho da prova
quizFile.write(f'Name: \n\nDate: \n\nPeriod: \n\n')
quizFile.write(f'{"*" * 20} State Captals Quiz (Form {quizNum + 1})')
quizFile.write('\n\n')
# Embaralha a lista de estados
states = list(captals.keys())
random.shuffle(states)
# Percorre todos os estados criando um looping para gerar uma pergunta para cada
for questionNum, _ in enumerate(states):
correctAnswer = captals[states[questionNum]]
wrongAnswers = list(captals.values())
del wrongAnswers[wrongAnswers.index(correctAnswer)]
wrongAnswers = random.sample(wrongAnswers, 3)
answerOptions = wrongAnswers + [correctAnswer]
random.shuffle(answerOptions)
# Grava pergunta e as opções de resposta no arquivo de prova
quizFile.write(f'{questionNum + 1}. What is the captal of {states[questionNum]}? \n')
for i in range(4):
quizFile.write(f'\t( {"ABCD"[i]} ) {answerOptions[i]}\n')
quizFile.write('\n')
# Grava o gabarito com as respostas em um arquivo
answerKeyFile.write(f'{questionNum + 1}. {"ABCD"[answerOptions.index(correctAnswer)]}\n')
quizFile.close()
answerKeyFile.close()
| [
"random.sample",
"random.shuffle"
] | [((1675, 1697), 'random.shuffle', 'random.shuffle', (['states'], {}), '(states)\n', (1689, 1697), False, 'import random\n'), ((2011, 2041), 'random.sample', 'random.sample', (['wrongAnswers', '(3)'], {}), '(wrongAnswers, 3)\n', (2024, 2041), False, 'import random\n'), ((2105, 2134), 'random.shuffle', 'random.shuffle', (['answerOptions'], {}), '(answerOptions)\n', (2119, 2134), False, 'import random\n')] |
import pathlib
from setuptools import find_packages, setup
HERE = pathlib.Path(__file__).parent
VERSION = '0.0.0'
PACKAGE_NAME = 'cramer'
AUTHOR = '<NAME>'
AUTHOR_EMAIL = '<EMAIL>'
URL = 'https://github.com/TeengardenB/cramer'
LICENSE = 'MIT'
DESCRIPTION = 'This is a library designed to solve systems of linear equations using the cramer solution method.'
LONG_DESCRIPTION = (HERE / "README.md").read_text(encoding='utf-8')
LONG_DESC_TYPE = "text/markdown"
INSTALL_REQUIRES = [
'numpy'
]
setup(
name=PACKAGE_NAME,
version=VERSION,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
long_description_content_type=LONG_DESC_TYPE,
author=AUTHOR,
author_email=AUTHOR_EMAIL,
url=URL,
install_requires=INSTALL_REQUIRES,
license=LICENSE,
packages=find_packages(),
include_package_data=True
) | [
"setuptools.find_packages",
"pathlib.Path"
] | [((70, 92), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (82, 92), False, 'import pathlib\n'), ((849, 864), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (862, 864), False, 'from setuptools import find_packages, setup\n')] |
#!/usr/bin/env python
import sys
import os
from datetime import datetime
from argparse import ArgumentParser
template="""#!/usr/bin/env python
'''
File: {0}
Author: <NAME> <<EMAIL>>
Org: TralahTek LLC <https://github.com/TralahTek>
Date: {1}
'''
""".format(sys.argv[1],datetime.now().date())
if __name__=='__main__':
parser=ArgumentParser(epilog=template)
parser.add_argument(action='store',dest='filename',help='python filename to create.')
args=parser.parse_args()
with open(args.filename,'w') as py:
py.write(template)
print(args.filename," written.")
os.system('vim '+args.filename)
os.sys.exit(0)
| [
"os.system",
"datetime.datetime.now",
"os.sys.exit",
"argparse.ArgumentParser"
] | [((333, 364), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'epilog': 'template'}), '(epilog=template)\n', (347, 364), False, 'from argparse import ArgumentParser\n'), ((593, 626), 'os.system', 'os.system', (["('vim ' + args.filename)"], {}), "('vim ' + args.filename)\n", (602, 626), False, 'import os\n'), ((629, 643), 'os.sys.exit', 'os.sys.exit', (['(0)'], {}), '(0)\n', (640, 643), False, 'import os\n'), ((273, 287), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (285, 287), False, 'from datetime import datetime\n')] |
import zmq
import simpleaudio as sa
import os
from time import sleep
# ----------------------------------------------------------------------------------------------------------------------
# A few ways of playing .wav files ... comment these out but keep for reference
# import pyaudio
# import wave
# from pydub import AudioSegment
# from pydub.playback import play
# def play_pydub(wavefile: str):
# silent_segment = AudioSegment.silent(duration=1000)
# speech = AudioSegment.from_wav(wavefile)
# final_speech = silent_segment + speech
# play(final_speech)
#
#
# def play_wave(wavefile: str):
# CHUNK = 1024
#
# wf = wave.open(wavefile, 'rb')
#
# # instantiate PyAudio (1)
# p = pyaudio.PyAudio()
#
# # open stream (2)
# stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
# channels=wf.getnchannels(),
# rate=wf.getframerate(),
# output=True)
#
# # read data
# data = wf.readframes(CHUNK)
#
# # play stream (3)
# while len(data) > 0:
# stream.write(data)
# data = wf.readframes(CHUNK)
#
# # stop stream (4)
# stream.stop_stream()
# stream.close()
#
# # close PyAudio (5)
# p.terminate()
def talk_pico2wave(text: str, tmp_file="tmp.wav"):
""" This is very hacky. I don't like writing a file, playing it and then deleting ...
but, the pico2speaker command seems to be defunct and so I'm stuck with pico2wave"""
text = " ... " + text
# write speech to a .wav file
pico_command = 'pico2wave -w ' + tmp_file + ' -l en-GB "' + text + ' "'
print(pico_command)
os.system(pico_command) # this blocks
# play .wav file using simple audio
# simple audio
wave_obj = sa.WaveObject.from_wave_file(tmp_file)
play_obj = wave_obj.play()
play_obj.wait_done() # Wait until sound has finished playing
print("done speaking")
# delete .wav file (clean up)
rm_command = 'rm ' + tmp_file
os.system(rm_command)
def text_to_speech_main(port_config=None):
"""The intended functionality here is to speak only one response at a time. Specifically
receive text as a zmq message, speak it, and then reply with a message that the text has been
spoken. As such, this function is deliberately blocking.
In between we listen for system commands if needed."""
if port_config is None:
port_config = {"system_sync_port": 5553, # report for system to check that modules are sync'ed properly
"pub_to_proxy_port": 5554, # port to publish to proxy so in the proxy it is xsub
"sub_to_proxy_port": 5555, # port to subscribe to the proxy so in the proxy it is xpub
"stt_req_rep_port": 5556, # REQ-REP control port for the stt pub sub
"tts_req_rep_port": 5557, # REQ-REP port for the text to speech
}
t_sleep = 0.1
# ------------------------------------------------------------------------------------------------------------------
# Make context and sockets
context = zmq.Context()
sockets_list = []
# system sync socket
socket_system_sync = context.socket(zmq.REQ)
socket_system_sync.connect("tcp://localhost:{}".format(port_config["system_sync_port"]))
sockets_list.append(socket_system_sync)
# socket for publishing to proxy
socket_publisher = context.socket(zmq.PUB)
socket_publisher.connect("tcp://localhost:{}".format(port_config["pub_to_proxy_port"]))
sockets_list.append(socket_publisher)
# socket for subscribing to proxy
socket_subscriber = context.socket(zmq.SUB)
socket_subscriber.connect("tcp://localhost:{}".format(port_config["sub_to_proxy_port"]))
socket_subscriber.setsockopt(zmq.SUBSCRIBE, b"SYSTEM")
sockets_list.append(socket_subscriber)
# open tts_reply socket
socket_tts_reply = context.socket(zmq.REP)
socket_tts_reply.bind("tcp://*:{}".format(port_config["tts_req_rep_port"]))
sockets_list.append(socket_tts_reply)
# make poller because we are listening to both the subscriber and the stt_reply sockets
poller = zmq.Poller()
poller.register(socket_subscriber, zmq.POLLIN)
poller.register(socket_tts_reply, zmq.POLLIN)
# ------------------------------------------------------------------------------------------------------------------
# inform the system that we have connected all sockets and are ready to go
socket_system_sync.send(b"SPEECH TO TEXT MODULE")
msg = socket_system_sync.recv() # this one can be blocking
# ------------------------------------------------------------------------------------------------------------------
# main loop
while True:
try:
socks = dict(poller.poll(100)) # poll for .1 ms don't block
# if a message from the system
if socket_subscriber in socks and socks[socket_subscriber] == zmq.POLLIN:
topic, message = socket_subscriber.recv_multipart()
print(topic.decode(), message.decode())
if message == b"SHUTDOWN":
break
# if a request to listen for speech
elif socket_tts_reply in socks and socks[socket_tts_reply] == zmq.POLLIN:
text = socket_tts_reply.recv().decode()
talk_pico2wave(text)
sleep(t_sleep)
socket_tts_reply.send(b"text spoken")
except KeyboardInterrupt:
break
sleep(t_sleep)
if __name__ == "__main__":
text_to_speech_main()
| [
"simpleaudio.WaveObject.from_wave_file",
"time.sleep",
"zmq.Poller",
"os.system",
"zmq.Context"
] | [((1659, 1682), 'os.system', 'os.system', (['pico_command'], {}), '(pico_command)\n', (1668, 1682), False, 'import os\n'), ((1773, 1811), 'simpleaudio.WaveObject.from_wave_file', 'sa.WaveObject.from_wave_file', (['tmp_file'], {}), '(tmp_file)\n', (1801, 1811), True, 'import simpleaudio as sa\n'), ((2009, 2030), 'os.system', 'os.system', (['rm_command'], {}), '(rm_command)\n', (2018, 2030), False, 'import os\n'), ((3139, 3152), 'zmq.Context', 'zmq.Context', ([], {}), '()\n', (3150, 3152), False, 'import zmq\n'), ((4192, 4204), 'zmq.Poller', 'zmq.Poller', ([], {}), '()\n', (4202, 4204), False, 'import zmq\n'), ((5564, 5578), 'time.sleep', 'sleep', (['t_sleep'], {}), '(t_sleep)\n', (5569, 5578), False, 'from time import sleep\n'), ((5433, 5447), 'time.sleep', 'sleep', (['t_sleep'], {}), '(t_sleep)\n', (5438, 5447), False, 'from time import sleep\n')] |
from python_framework import Controller, ControllerMethod, HttpStatus
from Role import *
from dto.FeatureDataDto import *
@Controller(url = '/feature-datas', tag='FeatureData', description='Single FeatureData controller')
class FeatureDataController:
@ControllerMethod(url='/<string:featureKey>/<string:sampleKey>',
responseClass=FeatureDataResponseDto,
roleRequired=[USER, ADMIN, API])
def get(self, featureKey, sampleKey):
return self.service.featureData.queryByFeatureKeyAndSampleKey(featureKey, sampleKey), HttpStatus.OK
@ControllerMethod(url='/<string:featureKey>/<string:sampleKey>',
roleRequired=[USER, ADMIN, API])
def delete(self, featureKey, sampleKey):
self.service.featureData.deleteByFeatureKeyAndSampleKey(featureKey, sampleKey), HttpStatus.NO_CONTENT
return {}, HttpStatus.NO_CONTENT
@Controller(url = '/feature-datas/batch', tag='FeatureData', description='Multiple FeatureData controller')
class FeatureDataBatchController:
@ControllerMethod(url='/<string:featureKey>',
responseClass=[[FeatureDataResponseDto]],
roleRequired=[ADMIN, API])
def get(self, featureKey):
return self.service.featureData.queryAllByFeatureKey(featureKey), HttpStatus.OK
| [
"python_framework.ControllerMethod",
"python_framework.Controller"
] | [((125, 226), 'python_framework.Controller', 'Controller', ([], {'url': '"""/feature-datas"""', 'tag': '"""FeatureData"""', 'description': '"""Single FeatureData controller"""'}), "(url='/feature-datas', tag='FeatureData', description=\n 'Single FeatureData controller')\n", (135, 226), False, 'from python_framework import Controller, ControllerMethod, HttpStatus\n'), ((870, 979), 'python_framework.Controller', 'Controller', ([], {'url': '"""/feature-datas/batch"""', 'tag': '"""FeatureData"""', 'description': '"""Multiple FeatureData controller"""'}), "(url='/feature-datas/batch', tag='FeatureData', description=\n 'Multiple FeatureData controller')\n", (880, 979), False, 'from python_framework import Controller, ControllerMethod, HttpStatus\n'), ((259, 397), 'python_framework.ControllerMethod', 'ControllerMethod', ([], {'url': '"""/<string:featureKey>/<string:sampleKey>"""', 'responseClass': 'FeatureDataResponseDto', 'roleRequired': '[USER, ADMIN, API]'}), "(url='/<string:featureKey>/<string:sampleKey>',\n responseClass=FeatureDataResponseDto, roleRequired=[USER, ADMIN, API])\n", (275, 397), False, 'from python_framework import Controller, ControllerMethod, HttpStatus\n'), ((566, 666), 'python_framework.ControllerMethod', 'ControllerMethod', ([], {'url': '"""/<string:featureKey>/<string:sampleKey>"""', 'roleRequired': '[USER, ADMIN, API]'}), "(url='/<string:featureKey>/<string:sampleKey>',\n roleRequired=[USER, ADMIN, API])\n", (582, 666), False, 'from python_framework import Controller, ControllerMethod, HttpStatus\n'), ((1017, 1135), 'python_framework.ControllerMethod', 'ControllerMethod', ([], {'url': '"""/<string:featureKey>"""', 'responseClass': '[[FeatureDataResponseDto]]', 'roleRequired': '[ADMIN, API]'}), "(url='/<string:featureKey>', responseClass=[[\n FeatureDataResponseDto]], roleRequired=[ADMIN, API])\n", (1033, 1135), False, 'from python_framework import Controller, ControllerMethod, HttpStatus\n')] |
import matplotlib.pyplot as plt
import numpy as np
def tunediagram(order=range(1,4),integer=[0,0],lines=[1,1,1,1],colors='ordered',linestyle='-',fig=plt.gcf()):
'''
plot resonance diagram up to specified order
mx + ny = p
x = (p-ny)/m
x = 1 where y = (p-m)/n
EXAMPLE:
tunediagram(order=[1,2,3])
tunediagram([1,2,3],integer=[6,8],lines=[0,0,1,1])
tunediagram([1,2,3],integer=[6,8],lines=[0,0,1,1], colors='black3', linestyle='--')
INPUT:
1. order - array of tune orders to plot. e.g. up to 3rd order, [1,2,3]
2. integers - integer part of the tune to plot in x,y, default is [0,0]. e.g. plot from 6-7 and 9-10, integer=[6,9]
2. lines - a boolean of which resonance lines to plot. e.g. [vertical,horizontal,sum,diff]. e.g. plot only vert/horz lines, lines = [1,1,0,0]
4. colors - option to plot lines in different colors. default is ordered. color options only go up to 10th order
ordered - each order resonance is a different color
black - all lines are black
blackX - X here is a number. all resonances X+ will be in black. e.g. black3 means plot resonances 1-2 in color and 3,4,5,... in black
6. linestyle - linestyle option from matplotlib
7. fig - pass in a handle to a figure, otherwise things will be plotted in the current figure.
Written by <NAME>
University of Maryland, Department of Physics
Oct 2018
'''
# define some variables
pval = 40 # increase for more/higher order lines
p = np.linspace(0,pval,pval+1)
qxmin,qymin = integer[0],integer[1]
qxmax,qymax = qxmin+1,qymin+1
# define different colors, up to 10th order
color = ['C0','C1','C2','C3','C4','C5','C6','C7','C8','C9']
if colors == 'black':
color = ['k']*10
elif colors[0:-1] == 'black':
idx = int(colors[-1])
color = color[0:idx-1] + (['k']*10)[idx-1:]
# adjust plot limits
plt.xlim((qxmin-0.01, qxmax+0.01))
plt.ylim((qymin-0.01, qymax+0.01))
# Plotting formula
# we plot resonances in reverse order
for i in order[::-1]:
m = np.linspace(-i,i,2*i+1)
n1 = (i-np.abs(m))
n2 = -1*n1
for j in range(0,m.size,1):
# check to see equation is divided by 0 or not
# ver & hor res lines
if ((n1[j] == 0 and lines[1]) or (m[j] == 0 and lines[0])):
# vertical lines
if n1[j] == 0 and lines[1]:
plt.vlines(p/m[j],qymin,qymax,color=color[i-1],linestyle=linestyle);
# horizontal lines
if m[j] == 0 and lines[0]:
plt.hlines(p/n1[j],qxmin,qxmax,color=color[i-1],linestyle=linestyle);
plt.hlines(p/n2[j],qxmin,qxmax,color=color[i-1],linestyle=linestyle);
# sum and dif res lines
elif not(n1[j] == 0) and not(m[j] == 0):
# resonance sum lines
if lines[2]:
if np.sign(m[j]) > 0:
plt.plot([[qxmin]*p.size,[qxmax]*p.size],[p/n2[j] - np.array(m[j]*qxmin/n2[j]), p/n2[j] - np.array(m[j]*qxmax/n2[j])],color=color[i-1],linestyle=linestyle);
else:
plt.plot([[qxmin]*p.size,[qxmax]*p.size],[p/n1[j] - np.array(m[j]*qxmin/n1[j]), p/n1[j] - np.array(m[j]*qxmax/n1[j])],color=color[i-1],linestyle=linestyle);
# resonance dif lines
if lines[3]:
if np.sign(m[j]) > 0:
plt.plot([[qxmin]*p.size,[qxmax]*p.size],[p/n1[j] - np.array(m[j]*qxmin/n1[j]), p/n1[j] - np.array(m[j]*qxmax/n1[j])],color=color[i-1],linestyle=linestyle);
else:
plt.plot([[qxmin]*p.size,[qxmax]*p.size],[p/n2[j] - np.array(m[j]*qxmin/n2[j]), p/n2[j] - np.array(m[j]*qxmax/n2[j])],color=color[i-1],linestyle=linestyle);
| [
"numpy.abs",
"matplotlib.pyplot.vlines",
"matplotlib.pyplot.gcf",
"matplotlib.pyplot.hlines",
"numpy.array",
"numpy.linspace",
"numpy.sign",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.xlim"
] | [((151, 160), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (158, 160), True, 'import matplotlib.pyplot as plt\n'), ((1533, 1563), 'numpy.linspace', 'np.linspace', (['(0)', 'pval', '(pval + 1)'], {}), '(0, pval, pval + 1)\n', (1544, 1563), True, 'import numpy as np\n'), ((1957, 1995), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(qxmin - 0.01, qxmax + 0.01)'], {}), '((qxmin - 0.01, qxmax + 0.01))\n', (1965, 1995), True, 'import matplotlib.pyplot as plt\n'), ((1996, 2034), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(qymin - 0.01, qymax + 0.01)'], {}), '((qymin - 0.01, qymax + 0.01))\n', (2004, 2034), True, 'import matplotlib.pyplot as plt\n'), ((2139, 2168), 'numpy.linspace', 'np.linspace', (['(-i)', 'i', '(2 * i + 1)'], {}), '(-i, i, 2 * i + 1)\n', (2150, 2168), True, 'import numpy as np\n'), ((2179, 2188), 'numpy.abs', 'np.abs', (['m'], {}), '(m)\n', (2185, 2188), True, 'import numpy as np\n'), ((2507, 2582), 'matplotlib.pyplot.vlines', 'plt.vlines', (['(p / m[j])', 'qymin', 'qymax'], {'color': 'color[i - 1]', 'linestyle': 'linestyle'}), '(p / m[j], qymin, qymax, color=color[i - 1], linestyle=linestyle)\n', (2517, 2582), True, 'import matplotlib.pyplot as plt\n'), ((2674, 2750), 'matplotlib.pyplot.hlines', 'plt.hlines', (['(p / n1[j])', 'qxmin', 'qxmax'], {'color': 'color[i - 1]', 'linestyle': 'linestyle'}), '(p / n1[j], qxmin, qxmax, color=color[i - 1], linestyle=linestyle)\n', (2684, 2750), True, 'import matplotlib.pyplot as plt\n'), ((2764, 2840), 'matplotlib.pyplot.hlines', 'plt.hlines', (['(p / n2[j])', 'qxmin', 'qxmax'], {'color': 'color[i - 1]', 'linestyle': 'linestyle'}), '(p / n2[j], qxmin, qxmax, color=color[i - 1], linestyle=linestyle)\n', (2774, 2840), True, 'import matplotlib.pyplot as plt\n'), ((3013, 3026), 'numpy.sign', 'np.sign', (['m[j]'], {}), '(m[j])\n', (3020, 3026), True, 'import numpy as np\n'), ((3510, 3523), 'numpy.sign', 'np.sign', (['m[j]'], {}), '(m[j])\n', (3517, 3523), True, 'import numpy as np\n'), ((3108, 3138), 'numpy.array', 'np.array', (['(m[j] * qxmin / n2[j])'], {}), '(m[j] * qxmin / n2[j])\n', (3116, 3138), True, 'import numpy as np\n'), ((3146, 3176), 'numpy.array', 'np.array', (['(m[j] * qxmax / n2[j])'], {}), '(m[j] * qxmax / n2[j])\n', (3154, 3176), True, 'import numpy as np\n'), ((3315, 3345), 'numpy.array', 'np.array', (['(m[j] * qxmin / n1[j])'], {}), '(m[j] * qxmin / n1[j])\n', (3323, 3345), True, 'import numpy as np\n'), ((3353, 3383), 'numpy.array', 'np.array', (['(m[j] * qxmax / n1[j])'], {}), '(m[j] * qxmax / n1[j])\n', (3361, 3383), True, 'import numpy as np\n'), ((3605, 3635), 'numpy.array', 'np.array', (['(m[j] * qxmin / n1[j])'], {}), '(m[j] * qxmin / n1[j])\n', (3613, 3635), True, 'import numpy as np\n'), ((3643, 3673), 'numpy.array', 'np.array', (['(m[j] * qxmax / n1[j])'], {}), '(m[j] * qxmax / n1[j])\n', (3651, 3673), True, 'import numpy as np\n'), ((3812, 3842), 'numpy.array', 'np.array', (['(m[j] * qxmin / n2[j])'], {}), '(m[j] * qxmin / n2[j])\n', (3820, 3842), True, 'import numpy as np\n'), ((3850, 3880), 'numpy.array', 'np.array', (['(m[j] * qxmax / n2[j])'], {}), '(m[j] * qxmax / n2[j])\n', (3858, 3880), True, 'import numpy as np\n')] |
import os
import pytest
import shutil
from cloudify_agent.api import exceptions
from cloudify_agent.api import utils
from cloudify_agent.tests.utils import get_daemon_storage
from cloudify_agent.tests import random_id
def test_new_initd(daemon_factory, agent_ssl_cert):
daemon_name = 'test-daemon-{0}'.format(random_id(with_prefix=False))
daemon = daemon_factory.new(
**get_daemon_params(daemon_name, agent_ssl_cert))
assert daemon_name == daemon.name
assert 'queue' == daemon.queue
assert '127.0.0.1' == daemon.rest_host
assert 'user' == daemon.user
assert agent_ssl_cert.local_cert_path() == daemon.local_rest_cert_file
def test_save_load_delete(daemon_factory, agent_ssl_cert):
daemon_name = 'test-daemon-{0}'.format(random_id(with_prefix=False))
daemon = daemon_factory.new(
**get_daemon_params(daemon_name, agent_ssl_cert))
daemon_factory.save(daemon)
loaded = daemon_factory.load(daemon_name)
assert 'init.d' == loaded.PROCESS_MANAGEMENT
assert daemon_name == loaded.name
assert 'queue' == loaded.queue
assert '127.0.0.1' == loaded.rest_host
assert 'user' == loaded.user
daemon_factory.delete(daemon.name)
pytest.raises(exceptions.DaemonNotFoundError,
daemon_factory.load, daemon.name)
def test_new_no_implementation(daemon_factory):
pytest.raises(exceptions.DaemonNotImplementedError,
daemon_factory.new,
process_management='no-impl')
def test_load_non_existing(daemon_factory):
pytest.raises(exceptions.DaemonNotFoundError,
daemon_factory.load,
'non_existing_name')
def test_load_all(daemon_factory, agent_ssl_cert, tmp_path):
def _save_daemon(name):
daemon_name = 'test-daemon-{0}'.format(random_id(with_prefix=False))
params = get_daemon_params(daemon_name, agent_ssl_cert).copy()
params['name'] = name
daemon = daemon_factory.new(**params)
daemon_factory.save(daemon)
if os.path.exists(get_daemon_storage(str(tmp_path))):
shutil.rmtree(get_daemon_storage(str(tmp_path)))
daemons = daemon_factory.load_all()
assert 0 == len(daemons)
_save_daemon(utils.internal.generate_agent_name())
_save_daemon(utils.internal.generate_agent_name())
_save_daemon(utils.internal.generate_agent_name())
daemons = daemon_factory.load_all()
assert 3 == len(daemons)
def test_new_existing_agent(daemon_factory, agent_ssl_cert):
daemon_name = 'test-daemon-{0}'.format(random_id(with_prefix=False))
daemon = daemon_factory.new(
**get_daemon_params(daemon_name, agent_ssl_cert))
daemon_factory.save(daemon)
# without no_overwrite, this will overwrite the existing daemon
daemon = daemon_factory.new(
**get_daemon_params(daemon_name, agent_ssl_cert))
pytest.raises(exceptions.DaemonAlreadyExistsError,
daemon_factory.new,
no_overwrite=True,
**get_daemon_params(daemon_name, agent_ssl_cert))
def get_daemon_params(name, ssl_cert):
return {
'process_management': 'init.d',
'name': name,
'queue': 'queue',
'rest_host': '127.0.0.1',
'broker_ip': '127.0.0.1',
'user': 'user',
'broker_url': '127.0.0.1',
'broker_ssl_enabled': True,
'local_rest_cert_file': ssl_cert.local_cert_path(),
}
| [
"cloudify_agent.tests.random_id",
"cloudify_agent.api.utils.internal.generate_agent_name",
"pytest.raises"
] | [((1206, 1285), 'pytest.raises', 'pytest.raises', (['exceptions.DaemonNotFoundError', 'daemon_factory.load', 'daemon.name'], {}), '(exceptions.DaemonNotFoundError, daemon_factory.load, daemon.name)\n', (1219, 1285), False, 'import pytest\n'), ((1358, 1463), 'pytest.raises', 'pytest.raises', (['exceptions.DaemonNotImplementedError', 'daemon_factory.new'], {'process_management': '"""no-impl"""'}), "(exceptions.DaemonNotImplementedError, daemon_factory.new,\n process_management='no-impl')\n", (1371, 1463), False, 'import pytest\n'), ((1546, 1637), 'pytest.raises', 'pytest.raises', (['exceptions.DaemonNotFoundError', 'daemon_factory.load', '"""non_existing_name"""'], {}), "(exceptions.DaemonNotFoundError, daemon_factory.load,\n 'non_existing_name')\n", (1559, 1637), False, 'import pytest\n'), ((316, 344), 'cloudify_agent.tests.random_id', 'random_id', ([], {'with_prefix': '(False)'}), '(with_prefix=False)\n', (325, 344), False, 'from cloudify_agent.tests import random_id\n'), ((765, 793), 'cloudify_agent.tests.random_id', 'random_id', ([], {'with_prefix': '(False)'}), '(with_prefix=False)\n', (774, 793), False, 'from cloudify_agent.tests import random_id\n'), ((2224, 2260), 'cloudify_agent.api.utils.internal.generate_agent_name', 'utils.internal.generate_agent_name', ([], {}), '()\n', (2258, 2260), False, 'from cloudify_agent.api import utils\n'), ((2279, 2315), 'cloudify_agent.api.utils.internal.generate_agent_name', 'utils.internal.generate_agent_name', ([], {}), '()\n', (2313, 2315), False, 'from cloudify_agent.api import utils\n'), ((2334, 2370), 'cloudify_agent.api.utils.internal.generate_agent_name', 'utils.internal.generate_agent_name', ([], {}), '()\n', (2368, 2370), False, 'from cloudify_agent.api import utils\n'), ((2548, 2576), 'cloudify_agent.tests.random_id', 'random_id', ([], {'with_prefix': '(False)'}), '(with_prefix=False)\n', (2557, 2576), False, 'from cloudify_agent.tests import random_id\n'), ((1808, 1836), 'cloudify_agent.tests.random_id', 'random_id', ([], {'with_prefix': '(False)'}), '(with_prefix=False)\n', (1817, 1836), False, 'from cloudify_agent.tests import random_id\n')] |
import asynctest
from uuid import uuid4
from .client import CLIENT
from ...settings import BucketSettings
from ...models.file import FileModel
from ...bucket.awaiting import AwaitingFile
class TestAwaitingFiles(asynctest.TestCase):
use_default_loop = True
async def test_file_listing_names(self):
_, bucket = await CLIENT.create_bucket(BucketSettings(
"file test {}".format(uuid4())
))
async for data, file, name, id_ in bucket.file_versions():
self.assertIsInstance(
data, FileModel
)
self.assertIsInstance(
file, AwaitingFile
)
self.assertTrue(type(name) == str)
self.assertTrue(type(id_) == str)
async for data, file, name in bucket.file_names():
self.assertIsInstance(
data, FileModel
)
self.assertIsInstance(
file, AwaitingFile
)
self.assertTrue(type(name) == str)
await bucket.delete()
| [
"uuid.uuid4"
] | [((410, 417), 'uuid.uuid4', 'uuid4', ([], {}), '()\n', (415, 417), False, 'from uuid import uuid4\n')] |
# Import external modules.
from google.appengine.ext import ndb
import logging
# Import local modules.
from configuration import const as conf
from constants import Constants
const = Constants()
const.MAX_RETRY = 3
# Parent key: none
class RequestForProposals(ndb.Model):
title = ndb.StringProperty()
detail = ndb.StringProperty()
creator = ndb.StringProperty()
allowEdit = ndb.BooleanProperty()
# Store frozen-flag in request-for-proposals record, because storing frozen-flag in link-key-record
# may be inconsistent if multiple link-keys exist, and link-key-record is designed to be constant.
freezeUserInput = ndb.BooleanProperty( default=False )
# Experimental
hideReasons = ndb.BooleanProperty( default=False )
@ndb.transactional( retries=const.MAX_RETRY )
def setEditable( requestId, editable ):
logging.debug( 'setEditable() editable={}'.format(editable) )
requestRecord = RequestForProposals.get_by_id( int(requestId) )
requestRecord.allowEdit = editable
requestRecord.put()
| [
"constants.Constants",
"google.appengine.ext.ndb.transactional",
"google.appengine.ext.ndb.BooleanProperty",
"google.appengine.ext.ndb.StringProperty"
] | [((185, 196), 'constants.Constants', 'Constants', ([], {}), '()\n', (194, 196), False, 'from constants import Constants\n'), ((761, 803), 'google.appengine.ext.ndb.transactional', 'ndb.transactional', ([], {'retries': 'const.MAX_RETRY'}), '(retries=const.MAX_RETRY)\n', (778, 803), False, 'from google.appengine.ext import ndb\n'), ((288, 308), 'google.appengine.ext.ndb.StringProperty', 'ndb.StringProperty', ([], {}), '()\n', (306, 308), False, 'from google.appengine.ext import ndb\n'), ((322, 342), 'google.appengine.ext.ndb.StringProperty', 'ndb.StringProperty', ([], {}), '()\n', (340, 342), False, 'from google.appengine.ext import ndb\n'), ((357, 377), 'google.appengine.ext.ndb.StringProperty', 'ndb.StringProperty', ([], {}), '()\n', (375, 377), False, 'from google.appengine.ext import ndb\n'), ((394, 415), 'google.appengine.ext.ndb.BooleanProperty', 'ndb.BooleanProperty', ([], {}), '()\n', (413, 415), False, 'from google.appengine.ext import ndb\n'), ((646, 680), 'google.appengine.ext.ndb.BooleanProperty', 'ndb.BooleanProperty', ([], {'default': '(False)'}), '(default=False)\n', (665, 680), False, 'from google.appengine.ext import ndb\n'), ((721, 755), 'google.appengine.ext.ndb.BooleanProperty', 'ndb.BooleanProperty', ([], {'default': '(False)'}), '(default=False)\n', (740, 755), False, 'from google.appengine.ext import ndb\n')] |
from selenium.webdriver.support.ui import Select
from model.contact import Contact
import re
class ContactHelper:
def __init__(self, app):
self.app = app
def open_home_page(self):
wd = self.app.wd
if not (wd.current_url.endswith("/index.php") and
len(wd.find_elements_by_xpath("//input[@value='Send e-Mail']"))) > 0:
wd.get(self.app.base_url)
def open_new_contact_page(self):
wd = self.app.wd
wd.find_element_by_link_text("add new").click()
def fill_contact_form(self, contact):
wd = self.app.wd
# fill first name
self.change_field_value("firstname", contact.firstname)
# fill middle name
self.change_field_value("middlename", contact.middlename)
# fill last name
self.change_field_value("lastname", contact.lastname)
# fill nickname
self.change_field_value("nickname", contact.nickname)
# fill title
self.change_field_value("title", contact.title)
# fill company
self.change_field_value("company", contact.company)
# fill address
self.change_field_value("address", contact.address)
# fill home phone
self.change_field_value("home", contact.home_phone)
# fill mobile phone
self.change_field_value("mobile", contact.mobile)
# fill work phone
self.change_field_value("work", contact.work_phone)
# fill fax
self.change_field_value("fax", contact.fax)
# fill email
self.change_field_value("email", contact.email)
# fill email2
self.change_field_value("email2", contact.email2)
# fill email3
self.change_field_value("email3", contact.email3)
# fill homepage
self.change_field_value("homepage", contact.homepage)
# select birthday
self.change_dropdown_value("bday", contact.birthday)
# select birth month
self.change_dropdown_value("bmonth", contact.birthmonth)
# fill birth year
self.change_field_value("byear", contact.birthyear)
# fill address2
self.change_field_value("address2", contact.address2)
# fill home
self.change_field_value("phone2", contact.secondary_phone)
# fill notes
self.change_field_value("notes", contact.notes)
def change_field_value(self, field_name, text):
wd = self.app.wd
if text is not None:
wd.find_element_by_name(field_name).click()
wd.find_element_by_name(field_name).clear()
wd.find_element_by_name(field_name).send_keys(text)
def change_dropdown_value(self, field_name, data):
wd = self.app.wd
if data is not None:
wd.find_element_by_name(field_name).click()
Select(wd.find_element_by_name(field_name)).select_by_visible_text(data)
wd.find_element_by_xpath("//option[@value='" + data + "']").click()
def create(self, contact):
wd = self.app.wd
self.open_new_contact_page()
# fill contact form
self.fill_contact_form(contact)
# submit creation
wd.find_element_by_name("submit").click()
self.return_to_homepage()
self.contact_cache = None
def edit_first_contact(self, new_contact_data):
self.edit_contact_by_index(0, new_contact_data)
def edit_contact_by_index(self, index, new_contact_data):
# open home page
wd = self.app.wd
self.open_home_page()
self.click_edit_by_index(index)
# fill contact form
self.fill_contact_form(new_contact_data)
# submit edition
wd.find_element_by_name("update").click()
self.return_to_homepage()
self.contact_cache = None
def edit_contact_by_id(self, id, new_contact_data):
# open home page
wd = self.app.wd
self.open_home_page()
self.click_edit_by_id(id)
# fill contact form
self.fill_contact_form(new_contact_data)
# submit edition
wd.find_element_by_name("update").click()
self.return_to_homepage()
self.contact_cache = None
def delete_first(self):
self.delete_contact_by_index(0)
def delete_contact_by_index(self, index):
# open home page
wd = self.app.wd
self.open_home_page()
self.select_contact_by_index(index)
# submit deletion
wd.find_element_by_xpath("//input[@value='Delete']").click()
wd.switch_to.alert.accept()
self.return_to_homepage()
self.contact_cache = None
def delete_contact_by_id(self, id):
# open home page
wd = self.app.wd
self.open_home_page()
self.select_contact_by_id(id)
# submit deletion
wd.find_element_by_xpath("//input[@value='Delete']").click()
wd.switch_to.alert.accept()
self.return_to_homepage()
self.contact_cache = None
def return_to_homepage(self):
wd = self.app.wd
wd.find_element_by_link_text("home").click()
def count_contact(self):
wd = self.app.wd
self.open_home_page()
return len(wd.find_elements_by_name("selected[]"))
def lastname(self):
wd = self.app.wd
self.select_first_contact()
wd.find_element_by_xpath("//img[@alt='Edit']").click()
element = wd.find_element_by_name("lastname").get_attribute("value")
return len(element)
def select_first_contact(self):
wd = self.app.wd
wd.find_element_by_name("selected[]").click()
def select_contact_by_index(self, index):
wd = self.app.wd
wd.find_elements_by_name("selected[]")[index].click()
def select_contact_by_id(self, id):
wd = self.app.wd
wd.find_element_by_css_selector("input[value='%s']" % id).click()
def click_edit_by_index(self, index):
wd = self.app.wd
wd.find_elements_by_xpath("//img[@alt='Edit']")[index].click()
def click_edit_by_id(self, id):
wd = self.app.wd
wd.find_element_by_xpath("//input[@value='%s']/../..//*[@title='Edit']" % id).click()
contact_cache = None
def get_contact_list(self):
if self.contact_cache is None:
wd = self.app.wd
self.open_home_page()
self.contact_cache = []
for element in wd.find_elements_by_name("entry"):
lastname = element.find_element_by_xpath(".//td[2]").text
firstname = element.find_element_by_xpath(".//td[3]").text
id = element.find_element_by_name("selected[]").get_attribute("value")
all_phones = element.find_element_by_xpath(".//td[6]").text
all_email = element.find_element_by_xpath(".//td[5]").text
address = element.find_element_by_xpath(".//td[4]").text
self.contact_cache.append(Contact(lastname=lastname, firstname=firstname, id=id, address=address,
all_phones_from_home_page=all_phones,
all_email_from_home_page=all_email))
return list(self.contact_cache)
def open_contact_to_edit_by_index(self, index):
wd = self.app.wd
self.open_home_page()
row = wd.find_elements_by_name("entry")[index]
cell = row.find_elements_by_tag_name("td")[7]
cell.find_element_by_tag_name("a").click()
def get_contact_info_from_edit_page(self, index):
wd = self.app.wd
self.open_contact_to_edit_by_index(index)
home_phone = wd.find_element_by_name("home").get_attribute("value")
mobile = wd.find_element_by_name("mobile").get_attribute("value")
work_phone = wd.find_element_by_name("work").get_attribute("value")
secondary_phone = wd.find_element_by_name("phone2").get_attribute("value")
firstname = wd.find_element_by_name("firstname").get_attribute("value")
lastname = wd.find_element_by_name("lastname").get_attribute("value")
id = wd.find_element_by_name("id").get_attribute("value")
email = wd.find_element_by_name("email").get_attribute("value")
email2 = wd.find_element_by_name("email2").get_attribute("value")
email3 = wd.find_element_by_name("email3").get_attribute("value")
address = wd.find_element_by_name("address").text
return Contact(firstname=firstname, lastname=lastname, id=id, address=address, home_phone=home_phone, mobile=mobile,
work_phone=work_phone, secondary_phone=secondary_phone, email=email, email2=email2, email3=email3)
def open_contact_view_page_by_index(self, index):
wd = self.app.wd
self.open_home_page()
row = wd.find_elements_by_name("entry")[index]
cell = row.find_elements_by_tag_name("td")[6]
cell.find_element_by_tag_name("a").click()
def get_contact_from_view_page(self, index):
wd = self.app.wd
self.open_contact_view_page_by_index(index)
text = wd.find_element_by_id("content").text
home_phone = re.search("H: (.*)", text).group(1)
mobile = re.search("M: (.*)", text).group(1)
work_phone = re.search("W: (.*)", text).group(1)
secondary_phone = re.search("P: (.*)", text).group(1)
return Contact(home_phone=home_phone, mobile=mobile, work_phone=work_phone,
secondary_phone=secondary_phone)
def add_contact_to_group(self, groupId):
wd = self.app.wd
wd.find_element_by_name("to_group").click()
Select(wd.find_element_by_name("to_group")).select_by_value('%s' % groupId)
wd.find_element_by_name("add").click()
def assign_contact_by_id_to_group(self, id, groupId):
wd = self.app.wd
self.open_home_page()
self.select_contact_by_id(id)
self.add_contact_to_group(groupId)
self.return_to_homepage()
def get_contacts_in_group(self, groupId):
wd = self.app.wd
self.open_home_page()
self.select_group_from_groups_list(groupId)
contacts_list = []
for element in wd.find_elements_by_name("entry"):
lastname = element.find_element_by_xpath(".//td[2]").text
firstname = element.find_element_by_xpath(".//td[3]").text
id = element.find_element_by_name("selected[]").get_attribute("value")
all_phones = element.find_element_by_xpath(".//td[6]").text
all_email = element.find_element_by_xpath(".//td[5]").text
address = element.find_element_by_xpath(".//td[4]").text
contacts_list.append(Contact(lastname=lastname, firstname=firstname, id=id, address=address,
all_phones_from_home_page=all_phones,
all_email_from_home_page=all_email))
return contacts_list
def delete_contact_from_group(self, id, groupId):
wd = self.app.wd
self.open_home_page()
self.select_group_from_groups_list(groupId)
self.select_contact_by_id(id)
wd.find_element_by_name("remove").click()
self.return_to_selected_group_page(groupId)
def return_to_selected_group_page(self, groupId):
wd = self.app.wd
self.open_home_page()
self.select_group_from_groups_list(groupId)
def select_group_from_groups_list(self, groupId):
wd = self.app.wd
wd.find_element_by_name("group").click()
Select(wd.find_element_by_name("group")).select_by_value('%s' % groupId)
| [
"model.contact.Contact",
"re.search"
] | [((8447, 8663), 'model.contact.Contact', 'Contact', ([], {'firstname': 'firstname', 'lastname': 'lastname', 'id': 'id', 'address': 'address', 'home_phone': 'home_phone', 'mobile': 'mobile', 'work_phone': 'work_phone', 'secondary_phone': 'secondary_phone', 'email': 'email', 'email2': 'email2', 'email3': 'email3'}), '(firstname=firstname, lastname=lastname, id=id, address=address,\n home_phone=home_phone, mobile=mobile, work_phone=work_phone,\n secondary_phone=secondary_phone, email=email, email2=email2, email3=email3)\n', (8454, 8663), False, 'from model.contact import Contact\n'), ((9374, 9479), 'model.contact.Contact', 'Contact', ([], {'home_phone': 'home_phone', 'mobile': 'mobile', 'work_phone': 'work_phone', 'secondary_phone': 'secondary_phone'}), '(home_phone=home_phone, mobile=mobile, work_phone=work_phone,\n secondary_phone=secondary_phone)\n', (9381, 9479), False, 'from model.contact import Contact\n'), ((9151, 9177), 're.search', 're.search', (['"""H: (.*)"""', 'text'], {}), "('H: (.*)', text)\n", (9160, 9177), False, 'import re\n'), ((9204, 9230), 're.search', 're.search', (['"""M: (.*)"""', 'text'], {}), "('M: (.*)', text)\n", (9213, 9230), False, 'import re\n'), ((9261, 9287), 're.search', 're.search', (['"""W: (.*)"""', 'text'], {}), "('W: (.*)', text)\n", (9270, 9287), False, 'import re\n'), ((9323, 9349), 're.search', 're.search', (['"""P: (.*)"""', 'text'], {}), "('P: (.*)', text)\n", (9332, 9349), False, 'import re\n'), ((10691, 10840), 'model.contact.Contact', 'Contact', ([], {'lastname': 'lastname', 'firstname': 'firstname', 'id': 'id', 'address': 'address', 'all_phones_from_home_page': 'all_phones', 'all_email_from_home_page': 'all_email'}), '(lastname=lastname, firstname=firstname, id=id, address=address,\n all_phones_from_home_page=all_phones, all_email_from_home_page=all_email)\n', (10698, 10840), False, 'from model.contact import Contact\n'), ((6935, 7084), 'model.contact.Contact', 'Contact', ([], {'lastname': 'lastname', 'firstname': 'firstname', 'id': 'id', 'address': 'address', 'all_phones_from_home_page': 'all_phones', 'all_email_from_home_page': 'all_email'}), '(lastname=lastname, firstname=firstname, id=id, address=address,\n all_phones_from_home_page=all_phones, all_email_from_home_page=all_email)\n', (6942, 7084), False, 'from model.contact import Contact\n')] |
import numpy as np
import pandas as pd
import pytest
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import TheilSenRegressor
from etna.analysis import get_residuals
from etna.analysis import plot_residuals
from etna.analysis import plot_trend
from etna.analysis.plotters import _get_labels_names
from etna.datasets import TSDataset
from etna.metrics import MAE
from etna.models import LinearPerSegmentModel
from etna.pipeline import Pipeline
from etna.transforms import BinsegTrendTransform
from etna.transforms import LagTransform
from etna.transforms import LinearTrendTransform
from etna.transforms import STLTransform
from etna.transforms import TheilSenTrendTransform
@pytest.fixture
def residuals():
timestamp = pd.date_range("2020-01-01", periods=100, freq="D")
df = pd.DataFrame(
{
"timestamp": timestamp.tolist() * 2,
"segment": ["segment_0"] * len(timestamp) + ["segment_1"] * len(timestamp),
"target": np.arange(len(timestamp)).tolist() + (np.arange(len(timestamp)) + 1).tolist(),
}
)
df_wide = TSDataset.to_dataset(df)
ts = TSDataset(df=df_wide, freq="D")
forecast_df = ts[timestamp[10:], :, :]
forecast_df.loc[:, pd.IndexSlice["segment_0", "target"]] = -1
forecast_df.loc[:, pd.IndexSlice["segment_1", "target"]] = 1
residuals_df = ts[timestamp[10:], :, :]
residuals_df.loc[:, pd.IndexSlice["segment_0", "target"]] += 1
residuals_df.loc[:, pd.IndexSlice["segment_1", "target"]] -= 1
return residuals_df, forecast_df, ts
def test_get_residuals(residuals):
"""Test that get_residuals finds residuals correctly."""
residuals_df, forecast_df, ts = residuals
actual_residuals = get_residuals(forecast_df=forecast_df, ts=ts)
assert actual_residuals.to_pandas().equals(residuals_df)
def test_get_residuals_not_matching_lengths(residuals):
"""Test that get_residuals fails to find residuals correctly if ts hasn't answers."""
residuals_df, forecast_df, ts = residuals
ts = TSDataset(df=ts[ts.index[:-10], :, :], freq="D")
with pytest.raises(KeyError):
_ = get_residuals(forecast_df=forecast_df, ts=ts)
def test_get_residuals_not_matching_segments(residuals):
"""Test that get_residuals fails to find residuals correctly if segments of dataset and forecast differ."""
residuals_df, forecast_df, ts = residuals
columns_frame = forecast_df.columns.to_frame()
columns_frame["segment"] = ["segment_0", "segment_3"]
forecast_df.columns = pd.MultiIndex.from_frame(columns_frame)
with pytest.raises(KeyError, match="Segments of `ts` and `forecast_df` should be the same"):
_ = get_residuals(forecast_df=forecast_df, ts=ts)
def test_plot_residuals_fails_unkown_feature(example_tsdf):
"""Test that plot_residuals fails if meet unknown feature."""
pipeline = Pipeline(
model=LinearPerSegmentModel(), transforms=[LagTransform(in_column="target", lags=[5, 6, 7])], horizon=5
)
metrics, forecast_df, info = pipeline.backtest(ts=example_tsdf, metrics=[MAE()], n_folds=3)
with pytest.raises(ValueError, match="Given feature isn't present in the dataset"):
plot_residuals(forecast_df=forecast_df, ts=example_tsdf, feature="unkown_feature")
@pytest.mark.parametrize(
"poly_degree, trend_transform_class",
(
[1, LinearTrendTransform],
[2, LinearTrendTransform],
[1, TheilSenTrendTransform],
[2, TheilSenTrendTransform],
),
)
def test_plot_trend(poly_degree, example_tsdf, trend_transform_class):
plot_trend(ts=example_tsdf, trend_transform=trend_transform_class(in_column="target", poly_degree=poly_degree))
@pytest.mark.parametrize("detrend_model", (TheilSenRegressor(), LinearRegression()))
def test_plot_bin_seg(example_tsdf, detrend_model):
plot_trend(ts=example_tsdf, trend_transform=BinsegTrendTransform(in_column="target", detrend_model=detrend_model))
@pytest.mark.parametrize("period", (7, 30))
def test_plot_stl(example_tsdf, period):
plot_trend(ts=example_tsdf, trend_transform=STLTransform(in_column="target", period=period))
@pytest.mark.parametrize(
"poly_degree, expect_values, trend_class",
(
[1, True, LinearTrendTransform],
[2, False, LinearTrendTransform],
[1, True, TheilSenTrendTransform],
[2, False, TheilSenTrendTransform],
),
)
def test_get_labels_names_linear_coeffs(example_tsdf, poly_degree, expect_values, trend_class):
ln_tr = trend_class(in_column="target", poly_degree=poly_degree)
example_tsdf.fit_transform([ln_tr])
segments = example_tsdf.segments
_, linear_coeffs = _get_labels_names([ln_tr], segments)
if expect_values:
assert list(linear_coeffs.values()) != ["", ""]
else:
assert list(linear_coeffs.values()) == ["", ""]
| [
"pandas.MultiIndex.from_frame",
"sklearn.linear_model.LinearRegression",
"etna.datasets.TSDataset.to_dataset",
"etna.transforms.BinsegTrendTransform",
"etna.datasets.TSDataset",
"etna.analysis.plot_residuals",
"etna.models.LinearPerSegmentModel",
"sklearn.linear_model.TheilSenRegressor",
"etna.metri... | [((3282, 3465), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""poly_degree, trend_transform_class"""', '([1, LinearTrendTransform], [2, LinearTrendTransform], [1,\n TheilSenTrendTransform], [2, TheilSenTrendTransform])'], {}), "('poly_degree, trend_transform_class', ([1,\n LinearTrendTransform], [2, LinearTrendTransform], [1,\n TheilSenTrendTransform], [2, TheilSenTrendTransform]))\n", (3305, 3465), False, 'import pytest\n'), ((3956, 3998), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""period"""', '(7, 30)'], {}), "('period', (7, 30))\n", (3979, 3998), False, 'import pytest\n'), ((4140, 4355), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""poly_degree, expect_values, trend_class"""', '([1, True, LinearTrendTransform], [2, False, LinearTrendTransform], [1, \n True, TheilSenTrendTransform], [2, False, TheilSenTrendTransform])'], {}), "('poly_degree, expect_values, trend_class', ([1, \n True, LinearTrendTransform], [2, False, LinearTrendTransform], [1, True,\n TheilSenTrendTransform], [2, False, TheilSenTrendTransform]))\n", (4163, 4355), False, 'import pytest\n'), ((754, 804), 'pandas.date_range', 'pd.date_range', (['"""2020-01-01"""'], {'periods': '(100)', 'freq': '"""D"""'}), "('2020-01-01', periods=100, freq='D')\n", (767, 804), True, 'import pandas as pd\n'), ((1106, 1130), 'etna.datasets.TSDataset.to_dataset', 'TSDataset.to_dataset', (['df'], {}), '(df)\n', (1126, 1130), False, 'from etna.datasets import TSDataset\n'), ((1140, 1171), 'etna.datasets.TSDataset', 'TSDataset', ([], {'df': 'df_wide', 'freq': '"""D"""'}), "(df=df_wide, freq='D')\n", (1149, 1171), False, 'from etna.datasets import TSDataset\n'), ((1735, 1780), 'etna.analysis.get_residuals', 'get_residuals', ([], {'forecast_df': 'forecast_df', 'ts': 'ts'}), '(forecast_df=forecast_df, ts=ts)\n', (1748, 1780), False, 'from etna.analysis import get_residuals\n'), ((2045, 2093), 'etna.datasets.TSDataset', 'TSDataset', ([], {'df': 'ts[ts.index[:-10], :, :]', 'freq': '"""D"""'}), "(df=ts[ts.index[:-10], :, :], freq='D')\n", (2054, 2093), False, 'from etna.datasets import TSDataset\n'), ((2538, 2577), 'pandas.MultiIndex.from_frame', 'pd.MultiIndex.from_frame', (['columns_frame'], {}), '(columns_frame)\n', (2562, 2577), True, 'import pandas as pd\n'), ((4662, 4698), 'etna.analysis.plotters._get_labels_names', '_get_labels_names', (['[ln_tr]', 'segments'], {}), '([ln_tr], segments)\n', (4679, 4698), False, 'from etna.analysis.plotters import _get_labels_names\n'), ((2103, 2126), 'pytest.raises', 'pytest.raises', (['KeyError'], {}), '(KeyError)\n', (2116, 2126), False, 'import pytest\n'), ((2140, 2185), 'etna.analysis.get_residuals', 'get_residuals', ([], {'forecast_df': 'forecast_df', 'ts': 'ts'}), '(forecast_df=forecast_df, ts=ts)\n', (2153, 2185), False, 'from etna.analysis import get_residuals\n'), ((2587, 2678), 'pytest.raises', 'pytest.raises', (['KeyError'], {'match': '"""Segments of `ts` and `forecast_df` should be the same"""'}), "(KeyError, match=\n 'Segments of `ts` and `forecast_df` should be the same')\n", (2600, 2678), False, 'import pytest\n'), ((2687, 2732), 'etna.analysis.get_residuals', 'get_residuals', ([], {'forecast_df': 'forecast_df', 'ts': 'ts'}), '(forecast_df=forecast_df, ts=ts)\n', (2700, 2732), False, 'from etna.analysis import get_residuals\n'), ((3109, 3186), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""Given feature isn\'t present in the dataset"""'}), '(ValueError, match="Given feature isn\'t present in the dataset")\n', (3122, 3186), False, 'import pytest\n'), ((3196, 3283), 'etna.analysis.plot_residuals', 'plot_residuals', ([], {'forecast_df': 'forecast_df', 'ts': 'example_tsdf', 'feature': '"""unkown_feature"""'}), "(forecast_df=forecast_df, ts=example_tsdf, feature=\n 'unkown_feature')\n", (3210, 3283), False, 'from etna.analysis import plot_residuals\n'), ((3740, 3759), 'sklearn.linear_model.TheilSenRegressor', 'TheilSenRegressor', ([], {}), '()\n', (3757, 3759), False, 'from sklearn.linear_model import TheilSenRegressor\n'), ((3761, 3779), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (3777, 3779), False, 'from sklearn.linear_model import LinearRegression\n'), ((2900, 2923), 'etna.models.LinearPerSegmentModel', 'LinearPerSegmentModel', ([], {}), '()\n', (2921, 2923), False, 'from etna.models import LinearPerSegmentModel\n'), ((3882, 3951), 'etna.transforms.BinsegTrendTransform', 'BinsegTrendTransform', ([], {'in_column': '"""target"""', 'detrend_model': 'detrend_model'}), "(in_column='target', detrend_model=detrend_model)\n", (3902, 3951), False, 'from etna.transforms import BinsegTrendTransform\n'), ((4088, 4135), 'etna.transforms.STLTransform', 'STLTransform', ([], {'in_column': '"""target"""', 'period': 'period'}), "(in_column='target', period=period)\n", (4100, 4135), False, 'from etna.transforms import STLTransform\n'), ((2937, 2985), 'etna.transforms.LagTransform', 'LagTransform', ([], {'in_column': '"""target"""', 'lags': '[5, 6, 7]'}), "(in_column='target', lags=[5, 6, 7])\n", (2949, 2985), False, 'from etna.transforms import LagTransform\n'), ((3081, 3086), 'etna.metrics.MAE', 'MAE', ([], {}), '()\n', (3084, 3086), False, 'from etna.metrics import MAE\n')] |
import requests
import io
import zipfile
import shutil
STOREPATH = '/data/csv/'
def download_extract_zip(url, dirpath):
response = requests.get(url)
with zipfile.ZipFile(io.BytesIO(response.content)) as zfile:
store_at = STOREPATH + dirpath
zfile.extractall( store_at )
def download_chunk(url, dirpath):
path = dirpath + 'dataset.zip'
r = requests.get(url, stream = True)
with open(path, 'wb') as f:
for ch in r:
f.write(ch)
def unzip_chunk( dirpath ):
path = dirpath + 'dataset.zip'
with open(path, 'rb') as zf:
with zipfile.ZipFile( zf, allowZip64=True ) as zfile:
for member in zfile.infolist():
store_at = dirpath + member.filename
with open(store_at, 'wb') as outfile, zfile.open(member) as infile:
shutil.copyfileobj(infile, outfile)
url = 'http://api.gbif.org/v1/occurrence/download/request/0020324-191105090559680.zip'
dirpath = '/data/csv/'
download_chunk(url, dirpath)
unzip_chunk( dirpath )
| [
"zipfile.ZipFile",
"io.BytesIO",
"shutil.copyfileobj",
"requests.get"
] | [((136, 153), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (148, 153), False, 'import requests\n'), ((368, 398), 'requests.get', 'requests.get', (['url'], {'stream': '(True)'}), '(url, stream=True)\n', (380, 398), False, 'import requests\n'), ((178, 206), 'io.BytesIO', 'io.BytesIO', (['response.content'], {}), '(response.content)\n', (188, 206), False, 'import io\n'), ((584, 620), 'zipfile.ZipFile', 'zipfile.ZipFile', (['zf'], {'allowZip64': '(True)'}), '(zf, allowZip64=True)\n', (599, 620), False, 'import zipfile\n'), ((822, 857), 'shutil.copyfileobj', 'shutil.copyfileobj', (['infile', 'outfile'], {}), '(infile, outfile)\n', (840, 857), False, 'import shutil\n')] |
""" Serializers for API views """
# Module imports
from rest_framework import serializers
from django.contrib.auth import authenticate
from funds.models import Wallet
class TransactionSerializer(serializers.Serializer):
""" Serializer for transaction model """
pass
class WalletSerializer(serializers.Serializer):
""" Serializer for 'get-wallet' endpoint """
# Incoming data from request
wallet_name = serializers.CharField(max_length=250)
wallet_description = serializers.CharField(max_length=1000)
def create(self, validated_data):
""" Create a wallet object with the data received """
return Wallet(**validated_data)
def update(self, instance, validated_data):
""" Update a wallet with new data """
instance.wallet_name = validated_data.get(
'wallet_name', instance.wallet_name)
instance.wallet_description = validated_data.get(
'wallet_description', instance.wallet_description)
return instance
class DepositFundsSerializer(serializers.Serializer):
""" Serializer for 'deposit-wallet' endpoint """
# Incoming data from request
amount = serializers.FloatField()
# response data generated
status = serializers.BooleanField(default=False, read_only=True)
status_message = serializers.CharField(max_length=1000, read_only=True)
def validate(self, data):
""" Method to validate the data received and to generate and output """
return {
'status': data.get('user')
}
class WithdrawFundsSerializer(serializers.Serializer):
""" Serializer for 'withdraw-wallet' endpoint """
# Incoming data from request
amount = serializers.FloatField()
# response data generated
status = serializers.BooleanField(default=False, read_only=True)
status_message = serializers.CharField(max_length=1000, read_only=True)
def validate(self, data):
""" Method to validate the data received and to generate and output """
return {
'status': data.get('user')
}
| [
"rest_framework.serializers.FloatField",
"rest_framework.serializers.CharField",
"funds.models.Wallet",
"rest_framework.serializers.BooleanField"
] | [((428, 465), 'rest_framework.serializers.CharField', 'serializers.CharField', ([], {'max_length': '(250)'}), '(max_length=250)\n', (449, 465), False, 'from rest_framework import serializers\n'), ((491, 529), 'rest_framework.serializers.CharField', 'serializers.CharField', ([], {'max_length': '(1000)'}), '(max_length=1000)\n', (512, 529), False, 'from rest_framework import serializers\n'), ((1167, 1191), 'rest_framework.serializers.FloatField', 'serializers.FloatField', ([], {}), '()\n', (1189, 1191), False, 'from rest_framework import serializers\n'), ((1236, 1291), 'rest_framework.serializers.BooleanField', 'serializers.BooleanField', ([], {'default': '(False)', 'read_only': '(True)'}), '(default=False, read_only=True)\n', (1260, 1291), False, 'from rest_framework import serializers\n'), ((1313, 1367), 'rest_framework.serializers.CharField', 'serializers.CharField', ([], {'max_length': '(1000)', 'read_only': '(True)'}), '(max_length=1000, read_only=True)\n', (1334, 1367), False, 'from rest_framework import serializers\n'), ((1703, 1727), 'rest_framework.serializers.FloatField', 'serializers.FloatField', ([], {}), '()\n', (1725, 1727), False, 'from rest_framework import serializers\n'), ((1772, 1827), 'rest_framework.serializers.BooleanField', 'serializers.BooleanField', ([], {'default': '(False)', 'read_only': '(True)'}), '(default=False, read_only=True)\n', (1796, 1827), False, 'from rest_framework import serializers\n'), ((1849, 1903), 'rest_framework.serializers.CharField', 'serializers.CharField', ([], {'max_length': '(1000)', 'read_only': '(True)'}), '(max_length=1000, read_only=True)\n', (1870, 1903), False, 'from rest_framework import serializers\n'), ((646, 670), 'funds.models.Wallet', 'Wallet', ([], {}), '(**validated_data)\n', (652, 670), False, 'from funds.models import Wallet\n')] |
from setup_api import setup
from mailwizz.endpoint.customers import Customers
"""
SETUP THE API
"""
setup()
"""
CREATE THE ENDPOINT
"""
endpoint = Customers()
"""
CREATE CUSTOMER
"""
response = endpoint.create({
'customer': {
'first_name': 'John',
'last_name': 'Doe',
'email': '<EMAIL>',
'password': '<PASSWORD>',
'timezone': 'UTC',
'birthDate': '1979-07-30'
},
# company is optional, unless required from app settings
'company': {
'name': '<NAME> LLC',
'country': 'United States', # see the countries endpoint for available countries and their zones
'zone': 'New York', # see the countries endpoint for available countries and their zones
'city': 'Brooklyn',
'zip_code': 11222,
'address_1': 'Some Address',
'address_2': 'Some Other Address',
},
})
"""
DISPLAY RESPONSE
"""
print(response.content)
| [
"mailwizz.endpoint.customers.Customers",
"setup_api.setup"
] | [((101, 108), 'setup_api.setup', 'setup', ([], {}), '()\n', (106, 108), False, 'from setup_api import setup\n'), ((149, 160), 'mailwizz.endpoint.customers.Customers', 'Customers', ([], {}), '()\n', (158, 160), False, 'from mailwizz.endpoint.customers import Customers\n')] |
import argparse
import copy
import datetime
import re
import shlex
from typing import Union
import time
import discord
from discord.ext import commands
class Arguments(argparse.ArgumentParser):
def error(self, message):
raise RuntimeError(message)
def setup(bot):
bot.add_cog(Moderation(bot))
def is_owner(ctx):
return ctx.author == ctx.guild.owner_id
class Moderation(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(hidden=True)
@commands.check(is_owner)
async def sudo(self, ctx, who: Union[discord.Member, discord.User], *, command: str):
"""Run a command as another user."""
msg = copy.copy(ctx.message)
msg.author = who
msg.content = ctx.prefix + command
new_ctx = await self.bot.get_context(msg, cls=type(ctx))
await self.bot.invoke(new_ctx)
| [
"discord.ext.commands.check",
"discord.ext.commands.command",
"copy.copy"
] | [((471, 500), 'discord.ext.commands.command', 'commands.command', ([], {'hidden': '(True)'}), '(hidden=True)\n', (487, 500), False, 'from discord.ext import commands\n'), ((506, 530), 'discord.ext.commands.check', 'commands.check', (['is_owner'], {}), '(is_owner)\n', (520, 530), False, 'from discord.ext import commands\n'), ((680, 702), 'copy.copy', 'copy.copy', (['ctx.message'], {}), '(ctx.message)\n', (689, 702), False, 'import copy\n')] |
from pulp.amply import Amply, AmplyError
from StringIO import StringIO
from nose.tools import assert_raises
def test_data():
result = Amply("param T := 4;")['T']
assert result == 4
result = Amply("param T := -4;")['T']
assert result == -4
result = Amply("param T := 0.04;")['T']
assert result == 0.04
result = Amply("param T := -0.04;")['T']
assert result == -0.04
def test_set():
result = Amply("set month := Jan Feb Mar Apr;")['month']
assert result == ['Jan', 'Feb', 'Mar', 'Apr']
result = Amply("set month Jan Feb Mar Apr;")['month']
assert result == ['Jan', 'Feb', 'Mar', 'Apr']
assert [i for i in result] == ['Jan', 'Feb', 'Mar', 'Apr']
assert result != []
assert 'Jan' in result
assert 'Foo' not in result
assert len(result) == 4
def test_param():
result = Amply("param T := 4;")['T']
assert result != [4]
result = Amply("param T{foo}; param T := 1 2;")['T']
assert not (result == 2)
assert (result != 2)
def test_attr_access():
result = Amply("param T:= 4;").T
assert result == 4
def test_from_file():
s = StringIO("param T:= 4;")
assert Amply.from_file(s).T == 4
def test_load_string():
a = Amply("param T:= 4; param X{foo};")
a.load_string("param S := 6; param X := 1 2;")
assert a.T == 4
assert a.S == 6
assert a.X[1] == 2
def test_load_file():
a = Amply("param T:= 4; param X{foo};")
s = StringIO("param S := 6; param X := 1 2;")
a.load_file(s)
assert a.T == 4
assert a.S == 6
assert a.X[1] == 2
def test_empty_init():
a = Amply()
a.load_string("param T := 4;")
assert a.T == 4
def test_set_dimen2():
result = Amply(
"""
set twotups dimen 2;
set twotups := (1, 2) (2, 3) (4, 2) (3, 1);
"""
)['twotups']
assert result == [(1, 2), (2, 3), (4, 2), (3, 1)]
def test_set_dimen_error():
a = """
set dim1 dimen 1;
set dim1 := (1, 2) (2, 3) (3, 2);
"""
assert_raises(AmplyError, lambda: Amply(a))
def test_set_dimen2_noparen():
result = Amply(
"""
set twotups dimen 2;
set twotups := 1 2 2 3 4 2 3 1;
"""
)['twotups']
assert result == [(1, 2), (2, 3), (4, 2), (3, 1)]
def test_set_subscript():
result = Amply(
"""
set days{months};
set days[Jan] := 1 2 3 4;
set days[Feb] := 5 6 7 8;
"""
)['days']
j = result['Jan']
assert j == [1, 2, 3, 4]
f = result['Feb']
assert f == [5, 6, 7, 8]
def test_set_subscript2():
result = Amply(
"""
set days{months, days};
set days[Jan, 3] := 1 2 3 4;
set days[Feb, 'Ham '] := 5 6 7 8;
"""
)['days']
j = result['Jan'][3]
assert j == [1, 2, 3, 4]
f = result['Feb']['Ham ']
assert f == [5, 6, 7, 8]
def test_set_subscript2_tuples():
result = Amply(
"""
set days{months, days};
set days[Jan, 3] := 1 2 3 4;
set days[Feb, 'Ham '] := 5 6 7 8;
"""
)['days']
j = result['Jan', 3]
assert j == [1, 2, 3, 4]
f = result['Feb', 'Ham ']
assert f == [5, 6, 7, 8]
def test_set_matrix():
result = Amply(
"""
set A : 1 2 3 :=
1 + - -
2 + + -
3 - + -
;
"""
)
a = result.A
assert a == [(1, 1), (2, 1), (2, 2), (3, 2)]
def test_set_matrix_tr():
result = Amply(
"""
set A (tr) : 1 2 3 :=
1 + - -
2 + + -
3 - + -
;
"""
)
a = result.A
assert a == [(1, 1), (1, 2), (2, 2), (2, 3)]
def test_set_splice():
result = Amply(
"""
set A dimen 3;
set A := (1, 2, 3), (1, 1, *) 2 4 (3, *, *) 1 1;
"""
)
a = result.A
assert a == [(1, 2, 3), (1, 1, 2), (1, 1, 4), (3, 1, 1)]
def test_set_splice_matrix():
result = Amply(
"""
set A dimen 3;
set A (1, *, *) : 1 2 3 :=
1 + - -
2 + - +
3 - - -
(2, *, *) : 1 2 3 :=
1 + - +
2 - + -
3 - - +
;
"""
)
a = result.A
assert a == [(1,1,1),(1,2,1),(1,2,3),(2,1,1),(2,1,3),(2,2,2),
(2,3,3)]
def test_simple_params():
result = Amply("param T := 4;")['T']
assert result == 4
def test_sub1_params():
result = Amply(
"""
param foo {s};
param foo := 1 Jan 2 Feb 3 Mar;
"""
)
j = result['foo'][1]
assert j == 'Jan'
f = result['foo'][2]
assert f == 'Feb'
def test_sub1_param_error():
a = """
param foo{s};
param foo := 1 Jan 2 Feb 3;
"""
assert_raises(AmplyError, lambda :Amply(a))
def test_param_default():
result = Amply(
"""
param foo {s} default 3;
param foo := Jan 1 Feb 2 Mar 3;
"""
)
j = result['foo']['Jan']
assert j == 1
m = result['foo']['Mar']
assert m == 3
d = result['foo']['FOO']
assert d == 3
def test_param_undefined():
result = Amply(
"""
param foo {s} ;
param foo := Jan 1 Feb 2 Mar 3;
"""
)
j = result['foo']['Jan']
assert j == 1
assert_raises(KeyError, lambda : result['foo']['Apr'])
def test_sub2_params():
result = Amply(
"""
param foo {s, t};
param foo := 1 2 Hi 99 3 4;
"""
)
h = result['foo'][1][2]
assert h == 'Hi'
f = result['foo'][99][3]
assert f == 4
def test_2d_param():
result = Amply(
"""
param demand {item, location};
param demand
: FRA DET LAN :=
spoons 200 100 30
plates 30 120 90
cups 666 13 29 ;
"""
)['demand']
s = result['spoons']
assert s == { 'FRA': 200, 'DET': 100, 'LAN': 30 }
assert result['plates'] == { 'FRA': 30, 'DET': 120, 'LAN': 90 }
assert result['cups'] == { 'FRA': 666, 'DET': 13, 'LAN': 29 }
def test_2d_numeric_param():
result = Amply(
"""
param square {x, y};
param square : 1 2 :=
4 4 8
3 3 6
;
"""
)['square']
f = result[4, 1]
assert f == 4
assert result[4, 2] == 8
assert result[3, 1] == 3
assert result[3, 2] == 6
def test_2d_param_defaults():
result = Amply(
"""
param demand {item, location};
param demand default 42
: FRA DET LAN :=
spoons 200 . 30
plates 30 120 .
cups . . 29 ;
"""
)['demand']
s = result['spoons']
assert s == { 'FRA': 200, 'DET': 42, 'LAN': 30 }
assert result['plates'] == { 'FRA': 30, 'DET': 120, 'LAN': 42 }
assert result['cups'] == { 'FRA': 42, 'DET': 42, 'LAN': 29 }
def test_2tables():
result = Amply(
"""
param demand {item, location};
param demand default 42
: FRA DET LAN :=
spoons 200 . 30
plates 30 120 .
cups . . 29
;
param square {foo, foo};
param square
: A B :=
A 1 6
B 6 36
;
"""
)
demand = result['demand']
assert demand['spoons'] == {'FRA': 200, 'DET': 42, 'LAN': 30 }
assert demand['plates'] == { 'FRA': 30, 'DET': 120, 'LAN': 42 }
assert demand['cups'] == { 'FRA': 42, 'DET': 42, 'LAN': 29 }
square = result['square']
assert square['A'] == {'A': 1, 'B': 6}
assert square['B'] == {'A': 6, 'B': 36}
def test_2d_param_transpose():
result = Amply(
"""
param demand {location, item};
param demand default 42 (tr)
: FRA DET LAN :=
spoons 200 . 30
plates 30 120 .
cups . . 29 ;
"""
)['demand']
f = result['FRA']
assert f == { 'spoons': 200, 'plates': 30, 'cups': 42 }
assert result['DET'] == { 'spoons': 42, 'plates': 120, 'cups': 42 }
assert result['LAN'] == { 'spoons': 30, 'plates': 42, 'cups': 29 }
def test_2d_slice1():
result = Amply(
"""
param demand {location, item};
param demand :=
[Jan, *] Foo 1 Bar 2;
"""
)['demand']
f = result['Jan']['Foo']
assert f == 1
assert result['Jan']['Bar'] == 2
def test_3d_slice2():
result = Amply(
"""
param trans_cost{src, dest, product};
param trans_cost :=
[*,*,bands]: FRA DET LAN :=
GARY 30 10 8
CLEV 22 7 10
[*,*,coils]: FRA DET LAN :=
GARY 39 14 11
CLEV 27 9 12
[*,*,plate]: FRA DET LAN :=
GARY 41 15 12
CLEV 29 9 13
;
"""
)['trans_cost']
f = result['GARY']['FRA']['bands']
assert f == 30
assert result['GARY']['DET']['plate'] == 15
assert result['CLEV']['LAN']['coils'] == 12
def test_3d_slice2b():
result = Amply(
"""
param trans_cost{src, product, dest};
param trans_cost :=
[*,bands,*]: FRA DET LAN :=
GARY 30 10 8
CLEV 22 7 10
[*,coils,*]: FRA DET LAN :=
GARY 39 14 11
CLEV 27 9 12
[*,plate,*]: FRA DET LAN :=
GARY 41 15 12
CLEV 29 9 13
;
"""
)['trans_cost']
f = result['GARY']['bands']['FRA']
assert f == 30
assert result['GARY']['plate']['DET'] == 15
assert result['CLEV']['coils']['LAN'] == 12
def test_single_tabbing_data():
result = Amply(
"""
set elem;
param init_stock{elem};
param cost{elem};
param value{elem};
param : init_stock cost value :=
iron 7 25 1
nickel 35 3 2
;
"""
)
s = result['init_stock']
assert s == {'iron': 7, 'nickel': 35}
assert result['cost'] == {'iron': 25, 'nickel': 3}
assert result['value'] == {'iron': 1, 'nickel': 2}
def test_single_tabbing_data_with_set():
result = Amply(
"""
set elem;
param init_stock{elem};
param cost{elem};
param value{elem};
param : elem : init_stock cost value :=
iron 7 25 1
nickel 35 3 2
;
"""
)
s = result['init_stock']
assert s == {'iron': 7, 'nickel': 35}
assert result['cost'] == {'iron': 25, 'nickel': 3}
assert result['value'] == {'iron': 1, 'nickel': 2}
def test_set2_tabbing():
result = Amply(
"""
set elem dimen 2;
set elem := 0 0 1 1 2 2;
param cost{elem};
param value{elem};
param : cost value :=
0 0 7 25
1 1 35 3
;
"""
)
assert result['elem'] == [(0,0),(1,1),(2,2)]
def test_undefined_tabbing_param():
assert_raises(AmplyError, lambda: Amply(
"""
param cost{elem};
param : cost value :=
0 1 2
3 4 5
;
"""
))
def test_2dset_simpleparam():
result = Amply(
"""
set elem dimen 2;
param foo{elem};
param foo :=
1 2 3
2 3 4
3 4 5
;
"""
)['foo']
f = result[1][2]
assert f == 3
assert result[2][3] == 4
assert result[3][4] == 5
def test_tuple_param():
result = Amply(
"""
set elem dimen 2;
param foo{elem};
param foo :=
1 2 3
2 3 4
3 4 5
;
"""
)['foo']
f = result[1,2]
assert f == 3
assert result[2,3] == 4
assert result[3,4] == 5
| [
"StringIO.StringIO",
"pulp.amply.Amply",
"pulp.amply.Amply.from_file",
"nose.tools.assert_raises"
] | [((1124, 1148), 'StringIO.StringIO', 'StringIO', (['"""param T:= 4;"""'], {}), "('param T:= 4;')\n", (1132, 1148), False, 'from StringIO import StringIO\n'), ((1219, 1254), 'pulp.amply.Amply', 'Amply', (['"""param T:= 4; param X{foo};"""'], {}), "('param T:= 4; param X{foo};')\n", (1224, 1254), False, 'from pulp.amply import Amply, AmplyError\n'), ((1400, 1435), 'pulp.amply.Amply', 'Amply', (['"""param T:= 4; param X{foo};"""'], {}), "('param T:= 4; param X{foo};')\n", (1405, 1435), False, 'from pulp.amply import Amply, AmplyError\n'), ((1444, 1485), 'StringIO.StringIO', 'StringIO', (['"""param S := 6; param X := 1 2;"""'], {}), "('param S := 6; param X := 1 2;')\n", (1452, 1485), False, 'from StringIO import StringIO\n'), ((1600, 1607), 'pulp.amply.Amply', 'Amply', ([], {}), '()\n', (1605, 1607), False, 'from pulp.amply import Amply, AmplyError\n'), ((3213, 3346), 'pulp.amply.Amply', 'Amply', (['"""\n set A : 1 2 3 :=\n 1 + - -\n 2 + + -\n 3 - + -\n ;\n """'], {}), '(\n """\n set A : 1 2 3 :=\n 1 + - -\n 2 + + -\n 3 - + -\n ;\n """\n )\n', (3218, 3346), False, 'from pulp.amply import Amply, AmplyError\n'), ((3457, 3610), 'pulp.amply.Amply', 'Amply', (['"""\n set A (tr) : 1 2 3 :=\n 1 + - -\n 2 + + -\n 3 - + -\n ;\n """'], {}), '(\n """\n set A (tr) : 1 2 3 :=\n 1 + - -\n 2 + + -\n 3 - + -\n ;\n """\n )\n', (3462, 3610), False, 'from pulp.amply import Amply, AmplyError\n'), ((3718, 3830), 'pulp.amply.Amply', 'Amply', (['"""\n set A dimen 3;\n set A := (1, 2, 3), (1, 1, *) 2 4 (3, *, *) 1 1;\n """'], {}), '(\n """\n set A dimen 3;\n set A := (1, 2, 3), (1, 1, *) 2 4 (3, *, *) 1 1;\n """\n )\n', (3723, 3830), False, 'from pulp.amply import Amply, AmplyError\n'), ((3957, 4284), 'pulp.amply.Amply', 'Amply', (['"""\n set A dimen 3;\n set A (1, *, *) : 1 2 3 :=\n 1 + - -\n 2 + - +\n 3 - - -\n (2, *, *) : 1 2 3 :=\n 1 + - +\n 2 - + -\n 3 - - +\n ;\n """'], {}), '(\n """\n set A dimen 3;\n set A (1, *, *) : 1 2 3 :=\n 1 + - -\n 2 + - +\n 3 - - -\n (2, *, *) : 1 2 3 :=\n 1 + - +\n 2 - + -\n 3 - - +\n ;\n """\n )\n', (3962, 4284), False, 'from pulp.amply import Amply, AmplyError\n'), ((4530, 4625), 'pulp.amply.Amply', 'Amply', (['"""\n param foo {s};\n param foo := 1 Jan 2 Feb 3 Mar;\n """'], {}), '(\n """\n param foo {s};\n param foo := 1 Jan 2 Feb 3 Mar;\n """\n )\n', (4535, 4625), False, 'from pulp.amply import Amply, AmplyError\n'), ((4925, 5030), 'pulp.amply.Amply', 'Amply', (['"""\n param foo {s} default 3;\n param foo := Jan 1 Feb 2 Mar 3;\n """'], {}), '(\n """\n param foo {s} default 3;\n param foo := Jan 1 Feb 2 Mar 3;\n """\n )\n', (4930, 5030), False, 'from pulp.amply import Amply, AmplyError\n'), ((5218, 5314), 'pulp.amply.Amply', 'Amply', (['"""\n param foo {s} ;\n param foo := Jan 1 Feb 2 Mar 3;\n """'], {}), '(\n """\n param foo {s} ;\n param foo := Jan 1 Feb 2 Mar 3;\n """\n )\n', (5223, 5314), False, 'from pulp.amply import Amply, AmplyError\n'), ((5370, 5424), 'nose.tools.assert_raises', 'assert_raises', (['KeyError', "(lambda : result['foo']['Apr'])"], {}), "(KeyError, lambda : result['foo']['Apr'])\n", (5383, 5424), False, 'from nose.tools import assert_raises\n'), ((5463, 5557), 'pulp.amply.Amply', 'Amply', (['"""\n param foo {s, t};\n param foo := 1 2 Hi 99 3 4;\n """'], {}), '(\n """\n param foo {s, t};\n param foo := 1 2 Hi 99 3 4;\n """\n )\n', (5468, 5557), False, 'from pulp.amply import Amply, AmplyError\n'), ((6985, 7342), 'pulp.amply.Amply', 'Amply', (['"""\n param demand {item, location};\n param demand default 42\n : FRA DET LAN :=\n spoons 200 . 30 \n plates 30 120 .\n cups . . 29 \n ;\n\n param square {foo, foo};\n param square\n : A B :=\n A 1 6\n B 6 36\n ;\n """'], {}), '(\n """\n param demand {item, location};\n param demand default 42\n : FRA DET LAN :=\n spoons 200 . 30 \n plates 30 120 .\n cups . . 29 \n ;\n\n param square {foo, foo};\n param square\n : A B :=\n A 1 6\n B 6 36\n ;\n """\n )\n', (6990, 7342), False, 'from pulp.amply import Amply, AmplyError\n'), ((9833, 10099), 'pulp.amply.Amply', 'Amply', (['"""\n set elem;\n param init_stock{elem};\n param cost{elem};\n param value{elem};\n param : init_stock cost value :=\n iron 7 25 1\n nickel 35 3 2\n ;\n """'], {}), '(\n """\n set elem;\n param init_stock{elem};\n param cost{elem};\n param value{elem};\n param : init_stock cost value :=\n iron 7 25 1\n nickel 35 3 2\n ;\n """\n )\n', (9838, 10099), False, 'from pulp.amply import Amply, AmplyError\n'), ((10340, 10613), 'pulp.amply.Amply', 'Amply', (['"""\n set elem;\n param init_stock{elem};\n param cost{elem};\n param value{elem};\n param : elem : init_stock cost value :=\n iron 7 25 1\n nickel 35 3 2\n ;\n """'], {}), '(\n """\n set elem;\n param init_stock{elem};\n param cost{elem};\n param value{elem};\n param : elem : init_stock cost value :=\n iron 7 25 1\n nickel 35 3 2\n ;\n """\n )\n', (10345, 10613), False, 'from pulp.amply import Amply, AmplyError\n'), ((10838, 11067), 'pulp.amply.Amply', 'Amply', (['"""\n set elem dimen 2;\n set elem := 0 0 1 1 2 2;\n param cost{elem};\n param value{elem};\n param : cost value :=\n 0 0 7 25\n 1 1 35 3\n ;\n """'], {}), '(\n """\n set elem dimen 2;\n set elem := 0 0 1 1 2 2;\n param cost{elem};\n param value{elem};\n param : cost value :=\n 0 0 7 25\n 1 1 35 3\n ;\n """\n )\n', (10843, 11067), False, 'from pulp.amply import Amply, AmplyError\n'), ((140, 162), 'pulp.amply.Amply', 'Amply', (['"""param T := 4;"""'], {}), "('param T := 4;')\n", (145, 162), False, 'from pulp.amply import Amply, AmplyError\n'), ((204, 227), 'pulp.amply.Amply', 'Amply', (['"""param T := -4;"""'], {}), "('param T := -4;')\n", (209, 227), False, 'from pulp.amply import Amply, AmplyError\n'), ((270, 295), 'pulp.amply.Amply', 'Amply', (['"""param T := 0.04;"""'], {}), "('param T := 0.04;')\n", (275, 295), False, 'from pulp.amply import Amply, AmplyError\n'), ((340, 366), 'pulp.amply.Amply', 'Amply', (['"""param T := -0.04;"""'], {}), "('param T := -0.04;')\n", (345, 366), False, 'from pulp.amply import Amply, AmplyError\n'), ((429, 467), 'pulp.amply.Amply', 'Amply', (['"""set month := Jan Feb Mar Apr;"""'], {}), "('set month := Jan Feb Mar Apr;')\n", (434, 467), False, 'from pulp.amply import Amply, AmplyError\n'), ((542, 577), 'pulp.amply.Amply', 'Amply', (['"""set month Jan Feb Mar Apr;"""'], {}), "('set month Jan Feb Mar Apr;')\n", (547, 577), False, 'from pulp.amply import Amply, AmplyError\n'), ((844, 866), 'pulp.amply.Amply', 'Amply', (['"""param T := 4;"""'], {}), "('param T := 4;')\n", (849, 866), False, 'from pulp.amply import Amply, AmplyError\n'), ((910, 948), 'pulp.amply.Amply', 'Amply', (['"""param T{foo}; param T := 1 2;"""'], {}), "('param T{foo}; param T := 1 2;')\n", (915, 948), False, 'from pulp.amply import Amply, AmplyError\n'), ((1046, 1067), 'pulp.amply.Amply', 'Amply', (['"""param T:= 4;"""'], {}), "('param T:= 4;')\n", (1051, 1067), False, 'from pulp.amply import Amply, AmplyError\n'), ((1700, 1813), 'pulp.amply.Amply', 'Amply', (['"""\n set twotups dimen 2;\n set twotups := (1, 2) (2, 3) (4, 2) (3, 1);\n """'], {}), '(\n """\n set twotups dimen 2;\n set twotups := (1, 2) (2, 3) (4, 2) (3, 1);\n """\n )\n', (1705, 1813), False, 'from pulp.amply import Amply, AmplyError\n'), ((2097, 2198), 'pulp.amply.Amply', 'Amply', (['"""\n set twotups dimen 2;\n set twotups := 1 2 2 3 4 2 3 1;\n """'], {}), '(\n """\n set twotups dimen 2;\n set twotups := 1 2 2 3 4 2 3 1;\n """\n )\n', (2102, 2198), False, 'from pulp.amply import Amply, AmplyError\n'), ((2308, 2434), 'pulp.amply.Amply', 'Amply', (['"""\n set days{months};\n set days[Jan] := 1 2 3 4;\n set days[Feb] := 5 6 7 8;\n """'], {}), '(\n """\n set days{months};\n set days[Jan] := 1 2 3 4;\n set days[Feb] := 5 6 7 8;\n """\n )\n', (2313, 2434), False, 'from pulp.amply import Amply, AmplyError\n'), ((2590, 2733), 'pulp.amply.Amply', 'Amply', (['"""\n set days{months, days};\n set days[Jan, 3] := 1 2 3 4;\n set days[Feb, \'Ham \'] := 5 6 7 8;\n """'], {}), '(\n """\n set days{months, days};\n set days[Jan, 3] := 1 2 3 4;\n set days[Feb, \'Ham \'] := 5 6 7 8;\n """\n )\n', (2595, 2733), False, 'from pulp.amply import Amply, AmplyError\n'), ((2907, 3050), 'pulp.amply.Amply', 'Amply', (['"""\n set days{months, days};\n set days[Jan, 3] := 1 2 3 4;\n set days[Feb, \'Ham \'] := 5 6 7 8;\n """'], {}), '(\n """\n set days{months, days};\n set days[Jan, 3] := 1 2 3 4;\n set days[Feb, \'Ham \'] := 5 6 7 8;\n """\n )\n', (2912, 3050), False, 'from pulp.amply import Amply, AmplyError\n'), ((4439, 4461), 'pulp.amply.Amply', 'Amply', (['"""param T := 4;"""'], {}), "('param T := 4;')\n", (4444, 4461), False, 'from pulp.amply import Amply, AmplyError\n'), ((5693, 5901), 'pulp.amply.Amply', 'Amply', (['"""\n param demand {item, location};\n param demand\n : FRA DET LAN :=\n spoons 200 100 30 \n plates 30 120 90\n cups 666 13 29 ;\n """'], {}), '(\n """\n param demand {item, location};\n param demand\n : FRA DET LAN :=\n spoons 200 100 30 \n plates 30 120 90\n cups 666 13 29 ;\n """\n )\n', (5698, 5901), False, 'from pulp.amply import Amply, AmplyError\n'), ((6173, 6326), 'pulp.amply.Amply', 'Amply', (['"""\n param square {x, y};\n param square : 1 2 :=\n 4 4 8\n 3 3 6\n ;\n """'], {}), '(\n """\n param square {x, y};\n param square : 1 2 :=\n 4 4 8\n 3 3 6\n ;\n """\n )\n', (6178, 6326), False, 'from pulp.amply import Amply, AmplyError\n'), ((6511, 6724), 'pulp.amply.Amply', 'Amply', (['"""\n param demand {item, location};\n param demand default 42\n : FRA DET LAN :=\n spoons 200 . 30 \n plates 30 120 .\n cups . . 29 ;\n """'], {}), '(\n """\n param demand {item, location};\n param demand default 42\n : FRA DET LAN :=\n spoons 200 . 30 \n plates 30 120 .\n cups . . 29 ;\n """\n )\n', (6516, 6724), False, 'from pulp.amply import Amply, AmplyError\n'), ((7741, 7959), 'pulp.amply.Amply', 'Amply', (['"""\n param demand {location, item};\n param demand default 42 (tr)\n : FRA DET LAN :=\n spoons 200 . 30 \n plates 30 120 .\n cups . . 29 ;\n """'], {}), '(\n """\n param demand {location, item};\n param demand default 42 (tr)\n : FRA DET LAN :=\n spoons 200 . 30 \n plates 30 120 .\n cups . . 29 ;\n """\n )\n', (7746, 7959), False, 'from pulp.amply import Amply, AmplyError\n'), ((8236, 8365), 'pulp.amply.Amply', 'Amply', (['"""\n param demand {location, item};\n param demand :=\n [Jan, *] Foo 1 Bar 2;\n """'], {}), '(\n """\n param demand {location, item};\n param demand :=\n [Jan, *] Foo 1 Bar 2;\n """\n )\n', (8241, 8365), False, 'from pulp.amply import Amply, AmplyError\n'), ((8500, 8951), 'pulp.amply.Amply', 'Amply', (['"""\n param trans_cost{src, dest, product};\n param trans_cost :=\n [*,*,bands]: FRA DET LAN :=\n GARY 30 10 8\n CLEV 22 7 10\n [*,*,coils]: FRA DET LAN :=\n GARY 39 14 11\n CLEV 27 9 12\n [*,*,plate]: FRA DET LAN :=\n GARY 41 15 12\n CLEV 29 9 13\n ;\n """'], {}), '(\n """\n param trans_cost{src, dest, product};\n param trans_cost :=\n [*,*,bands]: FRA DET LAN :=\n GARY 30 10 8\n CLEV 22 7 10\n [*,*,coils]: FRA DET LAN :=\n GARY 39 14 11\n CLEV 27 9 12\n [*,*,plate]: FRA DET LAN :=\n GARY 41 15 12\n CLEV 29 9 13\n ;\n """\n )\n', (8505, 8951), False, 'from pulp.amply import Amply, AmplyError\n'), ((9162, 9613), 'pulp.amply.Amply', 'Amply', (['"""\n param trans_cost{src, product, dest};\n param trans_cost :=\n [*,bands,*]: FRA DET LAN :=\n GARY 30 10 8\n CLEV 22 7 10\n [*,coils,*]: FRA DET LAN :=\n GARY 39 14 11\n CLEV 27 9 12\n [*,plate,*]: FRA DET LAN :=\n GARY 41 15 12\n CLEV 29 9 13\n ;\n """'], {}), '(\n """\n param trans_cost{src, product, dest};\n param trans_cost :=\n [*,bands,*]: FRA DET LAN :=\n GARY 30 10 8\n CLEV 22 7 10\n [*,coils,*]: FRA DET LAN :=\n GARY 39 14 11\n CLEV 27 9 12\n [*,plate,*]: FRA DET LAN :=\n GARY 41 15 12\n CLEV 29 9 13\n ;\n """\n )\n', (9167, 9613), False, 'from pulp.amply import Amply, AmplyError\n'), ((11389, 11569), 'pulp.amply.Amply', 'Amply', (['"""\n set elem dimen 2;\n param foo{elem};\n param foo :=\n 1 2 3\n 2 3 4\n 3 4 5\n ;\n """'], {}), '(\n """\n set elem dimen 2;\n param foo{elem};\n param foo :=\n 1 2 3\n 2 3 4\n 3 4 5\n ;\n """\n )\n', (11394, 11569), False, 'from pulp.amply import Amply, AmplyError\n'), ((11717, 11897), 'pulp.amply.Amply', 'Amply', (['"""\n set elem dimen 2;\n param foo{elem};\n param foo :=\n 1 2 3\n 2 3 4\n 3 4 5\n ;\n """'], {}), '(\n """\n set elem dimen 2;\n param foo{elem};\n param foo :=\n 1 2 3\n 2 3 4\n 3 4 5\n ;\n """\n )\n', (11722, 11897), False, 'from pulp.amply import Amply, AmplyError\n'), ((1160, 1178), 'pulp.amply.Amply.from_file', 'Amply.from_file', (['s'], {}), '(s)\n', (1175, 1178), False, 'from pulp.amply import Amply, AmplyError\n'), ((2042, 2050), 'pulp.amply.Amply', 'Amply', (['a'], {}), '(a)\n', (2047, 2050), False, 'from pulp.amply import Amply, AmplyError\n'), ((4875, 4883), 'pulp.amply.Amply', 'Amply', (['a'], {}), '(a)\n', (4880, 4883), False, 'from pulp.amply import Amply, AmplyError\n'), ((11197, 11339), 'pulp.amply.Amply', 'Amply', (['"""\n param cost{elem};\n param : cost value :=\n 0 1 2\n 3 4 5\n ;\n """'], {}), '(\n """\n param cost{elem};\n param : cost value :=\n 0 1 2\n 3 4 5\n ;\n """\n )\n', (11202, 11339), False, 'from pulp.amply import Amply, AmplyError\n')] |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import glob
import os
import zipfile
from spack import *
class PyFlitCore(PythonPackage):
"""Distribution-building parts of Flit."""
homepage = "https://github.com/takluyver/flit"
url = "https://github.com/takluyver/flit/archive/refs/tags/3.3.0.tar.gz"
maintainers = ['takluyver']
version('3.3.0', sha256='f5340b268563dd408bf8e2df6dbc8d4d08bc76cdff0d8c7f8a4be94e5f01f22f')
depends_on('python@3.4:', type=('build', 'run'))
depends_on('py-toml', type=('build', 'run'))
def build(self, spec, prefix):
with working_dir('flit_core'):
python('build_dists.py')
def install(self, spec, prefix):
wheel = glob.glob(os.path.join('flit_core', 'dist', '*.whl'))[0]
with zipfile.ZipFile(wheel) as f:
f.extractall(python_purelib)
| [
"os.path.join",
"zipfile.ZipFile"
] | [((935, 957), 'zipfile.ZipFile', 'zipfile.ZipFile', (['wheel'], {}), '(wheel)\n', (950, 957), False, 'import zipfile\n'), ((875, 917), 'os.path.join', 'os.path.join', (['"""flit_core"""', '"""dist"""', '"""*.whl"""'], {}), "('flit_core', 'dist', '*.whl')\n", (887, 917), False, 'import os\n')] |
import os
import matplotlib.pyplot as plt
from torch.utils.tensorboard import SummaryWriter
writer = SummaryWriter(log_dir="./logs")
from tqdm import tqdm
import numpy as np
import torch
import torchvision.datasets as dset
import torch.nn as nn
import torchvision.transforms as transforms
import pyro
import pyro.distributions as dist
from pyro.infer import SVI, Trace_ELBO
from pyro.optim import Adam
device = 'cuda:0' if torch.cuda.is_available() else 'cpu'
# I think the trickiest part of this tutorial is realizing that we need to define a separate z_i
# for each sample x_i because each z_i has a unique prior/posterior.
# We really cannot represent the VAE properly if we only have two variables, one for z and one
# for x. The setting is much better represented using "plates" or replications of the variables.
# In Pyro, the z_i's and x_i's are called local variables, those that are different for each
# data samples. The mu_i's and sigma_i's are local parameters.
# A second tricky point is the plates have dimension (mini)batch_size rather than the entire
# dataset size. This is because new random variables are being constructed in each batch. We're
# doing optimization of the dynamics P(X|Z) at the same time we're doing inference q(Z|X). In
# each minibatch, we're improving our inference q(Zb|Xb) on a particular batch of data Xb.
# Hopefully there's transfer between the data samples, s.t. improving the inference on one
# batch helps the infrence on another batch - that's the idea of tying the dynamics of the
# samples together with a neural network.
# At the same time, in each minibatch, given the current inference q(Zb|Xb), we try to improve
# the dynamics P(X|Z) to the "true dynamics" given the posterior is correct.
# for loading and batching MNIST dataset
def setup_data_loaders(batch_size=128, use_cuda=False):
root = './data'
download = True
trans = transforms.ToTensor()
train_set = dset.MNIST(root=root, train=True, transform=trans,
download=download)
test_set = dset.MNIST(root=root, train=False, transform=trans)
kwargs = {'num_workers': 1, 'pin_memory': use_cuda}
train_loader = torch.utils.data.DataLoader(dataset=train_set,
batch_size=batch_size, shuffle=True, **kwargs)
test_loader = torch.utils.data.DataLoader(dataset=test_set,
batch_size=batch_size, shuffle=False, **kwargs)
return train_loader, test_loader
# prediction model
class Decoder(nn.Module):
def __init__(self, z_dim, hidden_dim):
super(Decoder, self).__init__()
self.fc1 = nn.Linear(z_dim, hidden_dim)
self.fc21 = nn.Linear(hidden_dim, 784)
self.softplus = nn.Softplus() # soft relu
self.sigmoid = nn.Sigmoid()
def forward(self, z):
hidden = self.softplus(self.fc1(z))
loc_img = self.sigmoid(self.fc21(hidden))
return loc_img
# (latent) inference model
class Encoder(nn.Module):
def __init__(self, z_dim, hidden_dim):
super(Encoder, self).__init__()
self.fc1 = nn.Linear(784, hidden_dim)
self.fc21 = nn.Linear(hidden_dim, z_dim)
self.fc22 = nn.Linear(hidden_dim, z_dim)
self.softplus = nn.Softplus()
def forward(self, x):
x = x.reshape(-1, 784)
hidden = self.softplus(self.fc1(x))
z_loc = self.fc21(hidden)
z_scale = torch.exp(self.fc22(hidden))
return z_loc, z_scale
class VAE(nn.Module):
def __init__(self, z_dim=50, hidden_dim=400, use_cuda=False):
super(VAE, self).__init__()
# create the encoder and decoder networks
self.encoder = Encoder(z_dim, hidden_dim)
self.decoder = Decoder(z_dim, hidden_dim)
self.use_cuda = use_cuda
self.z_dim = z_dim
# define the model p(x|z)p(z)
# x: is batch_size X 784 size
def model(self, x):
pyro.module("decoder", self.decoder)
with pyro.plate("data", x.shape[0]): # we need to identify a separate z for each x, each z_i has a unique prior/posterior
# setup hyperparameters for prior p(z)
z_loc = x.new_zeros(torch.Size((x.shape[0], self.z_dim))) # unit Gaussian prior, constant values
z_scale = x.new_ones(torch.Size((x.shape[0], self.z_dim)))
# sample from prior (value will be sampled by guide when computing the ELBO)
z = pyro.sample("latent", dist.Normal(z_loc, z_scale).to_event(1)) # prior distribution
# to_event makes sure this is a multivariate normal instead of many univariate ones
# decode the latent code z
loc_img = self.decoder.forward(z) # forward dynamics
# score against actual images
pyro.sample("obs", dist.Bernoulli(loc_img).to_event(1), obs=x.reshape(-1, 784)) # observational distribution
# to_event because the neural networks ties the pixels together
return loc_img
# define the guide (i.e. variational distribution) q(z|x)
def guide(self, x):
pyro.module("encoder", self.encoder)
with pyro.plate("data", x.shape[0]): # we need to identify a separate z for each x, each z_i has a unique prior/posterior
z_loc, z_scale = self.encoder.forward(x)
pyro.sample("latent", dist.Normal(z_loc, z_scale).to_event(1)) # approximate posterior, why are the dims dependent? the covariate matrix is diagonal
# because the neural networks tie them together
def reconstruct_img(self, x):
z_loc, z_scale = self.encoder(x)
z = dist.Normal(z_loc, z_scale).sample()
loc_img = self.decoder(z)
return loc_img
vae = VAE().to(device)
optimizer = Adam({"lr": 1.0e-3})
svi = SVI(vae.model, vae.guide, optimizer, loss=Trace_ELBO())
train_loader, test_loader = setup_data_loaders()
def train(train_loader):
epoch_loss = 0
for batch, _ in tqdm(train_loader):
batch = batch.to(device)
epoch_loss += svi.step(batch)
return epoch_loss/len(train_loader.dataset)
def plot_vae_samples(vae, epoch):
x = torch.zeros([1, 784]).to(device)
for i in range(10):
sample_loc_i = vae.model(x)
img = sample_loc_i[0].view(1, 28, 28).cpu().data.numpy()
writer.add_image('image', img, epoch)
def evaluate(test_loader, epoch):
test_loss = 0.
for i, (batch, _) in enumerate(tqdm(test_loader)):
batch = batch.to(device)
test_loss += svi.evaluate_loss(batch)
if i == 0:
plot_vae_samples(vae, epoch)
return test_loss / len(test_loader.dataset)
num_epochs = 50
pyro.clear_param_store()
train_elbo = []
test_elbo = []
for epoch in range(num_epochs):
total_epoch_loss_train = train(train_loader)
train_elbo.append(-total_epoch_loss_train)
writer.add_scalar('ELBO/train', -total_epoch_loss_train, epoch)
print("[epoch %03d] average training loss: %.4f" % (epoch, total_epoch_loss_train))
if epoch % 2 == 0:
# report test diagnostics
total_epoch_loss_test = evaluate(test_loader, epoch)
test_elbo.append(-total_epoch_loss_test)
writer.add_scalar('ELBO/test', -total_epoch_loss_test, epoch)
print("[epoch %03d] average test loss: %.4f" % (epoch, total_epoch_loss_test)) | [
"torch.nn.Softplus",
"torch.utils.tensorboard.SummaryWriter",
"torch.nn.Sigmoid",
"pyro.distributions.Normal",
"pyro.module",
"pyro.clear_param_store",
"tqdm.tqdm",
"pyro.distributions.Bernoulli",
"pyro.infer.Trace_ELBO",
"torch.cuda.is_available",
"torchvision.datasets.MNIST",
"torch.utils.da... | [((101, 132), 'torch.utils.tensorboard.SummaryWriter', 'SummaryWriter', ([], {'log_dir': '"""./logs"""'}), "(log_dir='./logs')\n", (114, 132), False, 'from torch.utils.tensorboard import SummaryWriter\n'), ((5683, 5702), 'pyro.optim.Adam', 'Adam', (["{'lr': 0.001}"], {}), "({'lr': 0.001})\n", (5687, 5702), False, 'from pyro.optim import Adam\n'), ((6588, 6612), 'pyro.clear_param_store', 'pyro.clear_param_store', ([], {}), '()\n', (6610, 6612), False, 'import pyro\n'), ((427, 452), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (450, 452), False, 'import torch\n'), ((1901, 1922), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (1920, 1922), True, 'import torchvision.transforms as transforms\n'), ((1939, 2008), 'torchvision.datasets.MNIST', 'dset.MNIST', ([], {'root': 'root', 'train': '(True)', 'transform': 'trans', 'download': 'download'}), '(root=root, train=True, transform=trans, download=download)\n', (1949, 2008), True, 'import torchvision.datasets as dset\n'), ((2051, 2102), 'torchvision.datasets.MNIST', 'dset.MNIST', ([], {'root': 'root', 'train': '(False)', 'transform': 'trans'}), '(root=root, train=False, transform=trans)\n', (2061, 2102), True, 'import torchvision.datasets as dset\n'), ((2179, 2276), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', ([], {'dataset': 'train_set', 'batch_size': 'batch_size', 'shuffle': '(True)'}), '(dataset=train_set, batch_size=batch_size,\n shuffle=True, **kwargs)\n', (2206, 2276), False, 'import torch\n'), ((2299, 2396), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', ([], {'dataset': 'test_set', 'batch_size': 'batch_size', 'shuffle': '(False)'}), '(dataset=test_set, batch_size=batch_size,\n shuffle=False, **kwargs)\n', (2326, 2396), False, 'import torch\n'), ((5883, 5901), 'tqdm.tqdm', 'tqdm', (['train_loader'], {}), '(train_loader)\n', (5887, 5901), False, 'from tqdm import tqdm\n'), ((2586, 2614), 'torch.nn.Linear', 'nn.Linear', (['z_dim', 'hidden_dim'], {}), '(z_dim, hidden_dim)\n', (2595, 2614), True, 'import torch.nn as nn\n'), ((2635, 2661), 'torch.nn.Linear', 'nn.Linear', (['hidden_dim', '(784)'], {}), '(hidden_dim, 784)\n', (2644, 2661), True, 'import torch.nn as nn\n'), ((2686, 2699), 'torch.nn.Softplus', 'nn.Softplus', ([], {}), '()\n', (2697, 2699), True, 'import torch.nn as nn\n'), ((2736, 2748), 'torch.nn.Sigmoid', 'nn.Sigmoid', ([], {}), '()\n', (2746, 2748), True, 'import torch.nn as nn\n'), ((3050, 3076), 'torch.nn.Linear', 'nn.Linear', (['(784)', 'hidden_dim'], {}), '(784, hidden_dim)\n', (3059, 3076), True, 'import torch.nn as nn\n'), ((3097, 3125), 'torch.nn.Linear', 'nn.Linear', (['hidden_dim', 'z_dim'], {}), '(hidden_dim, z_dim)\n', (3106, 3125), True, 'import torch.nn as nn\n'), ((3146, 3174), 'torch.nn.Linear', 'nn.Linear', (['hidden_dim', 'z_dim'], {}), '(hidden_dim, z_dim)\n', (3155, 3174), True, 'import torch.nn as nn\n'), ((3199, 3212), 'torch.nn.Softplus', 'nn.Softplus', ([], {}), '()\n', (3210, 3212), True, 'import torch.nn as nn\n'), ((3867, 3903), 'pyro.module', 'pyro.module', (['"""decoder"""', 'self.decoder'], {}), "('decoder', self.decoder)\n", (3878, 3903), False, 'import pyro\n'), ((5021, 5057), 'pyro.module', 'pyro.module', (['"""encoder"""', 'self.encoder'], {}), "('encoder', self.encoder)\n", (5032, 5057), False, 'import pyro\n'), ((5752, 5764), 'pyro.infer.Trace_ELBO', 'Trace_ELBO', ([], {}), '()\n', (5762, 5764), False, 'from pyro.infer import SVI, Trace_ELBO\n'), ((6361, 6378), 'tqdm.tqdm', 'tqdm', (['test_loader'], {}), '(test_loader)\n', (6365, 6378), False, 'from tqdm import tqdm\n'), ((3917, 3947), 'pyro.plate', 'pyro.plate', (['"""data"""', 'x.shape[0]'], {}), "('data', x.shape[0])\n", (3927, 3947), False, 'import pyro\n'), ((5071, 5101), 'pyro.plate', 'pyro.plate', (['"""data"""', 'x.shape[0]'], {}), "('data', x.shape[0])\n", (5081, 5101), False, 'import pyro\n'), ((6066, 6087), 'torch.zeros', 'torch.zeros', (['[1, 784]'], {}), '([1, 784])\n', (6077, 6087), False, 'import torch\n'), ((4118, 4154), 'torch.Size', 'torch.Size', (['(x.shape[0], self.z_dim)'], {}), '((x.shape[0], self.z_dim))\n', (4128, 4154), False, 'import torch\n'), ((4229, 4265), 'torch.Size', 'torch.Size', (['(x.shape[0], self.z_dim)'], {}), '((x.shape[0], self.z_dim))\n', (4239, 4265), False, 'import torch\n'), ((5552, 5579), 'pyro.distributions.Normal', 'dist.Normal', (['z_loc', 'z_scale'], {}), '(z_loc, z_scale)\n', (5563, 5579), True, 'import pyro.distributions as dist\n'), ((4394, 4421), 'pyro.distributions.Normal', 'dist.Normal', (['z_loc', 'z_scale'], {}), '(z_loc, z_scale)\n', (4405, 4421), True, 'import pyro.distributions as dist\n'), ((4732, 4755), 'pyro.distributions.Bernoulli', 'dist.Bernoulli', (['loc_img'], {}), '(loc_img)\n', (4746, 4755), True, 'import pyro.distributions as dist\n'), ((5276, 5303), 'pyro.distributions.Normal', 'dist.Normal', (['z_loc', 'z_scale'], {}), '(z_loc, z_scale)\n', (5287, 5303), True, 'import pyro.distributions as dist\n')] |
# Copyright 2014: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import functools
import traceback
from oslo_config import cfg
from oslo_log import handlers
from oslo_log import log as oslogging
import six
log = __import__("logging")
DEBUG_OPTS = [cfg.BoolOpt(
"rally-debug",
default=False,
help="Print debugging output only for Rally. "
"Off-site components stay quiet.")]
CONF = cfg.CONF
CONF.register_cli_opts(DEBUG_OPTS)
oslogging.register_options(CONF)
log.RDEBUG = log.DEBUG + 1
log.addLevelName(log.RDEBUG, "RALLYDEBUG")
CRITICAL = log.CRITICAL # 50
FATAL = log.FATAL # 50
ERROR = log.ERROR # 40
WARN = log.WARN # 30
WARNING = log.WARNING # 30
INFO = log.INFO # 20
RDEBUG = log.RDEBUG # 11
DEBUG = log.DEBUG # 10
NOTSET = log.NOTSET # 0
def setup(product_name, version="unknown"):
dbg_color = handlers.ColorHandler.LEVEL_COLORS[log.DEBUG]
handlers.ColorHandler.LEVEL_COLORS[log.RDEBUG] = dbg_color
oslogging.setup(CONF, product_name, version)
if CONF.rally_debug:
oslogging.getLogger(
project=product_name).logger.setLevel(log.RDEBUG)
class RallyContextAdapter(oslogging.KeywordArgumentAdapter):
_posargs_msg = "Do not use *args for string formatting for log message: %s"
_exc_msg = ("Do not transmit an exception objects to logging. It will "
"be included automagically. Transmit a user-friendly "
"explanation instead.")
@staticmethod
def _find_the_caller(i=0):
"""Finds the caller of logging method
:param i: number of upper elements relatively to the place of calling
`_find_the_caller` method
:return: a tuple where the first element is a filename, the second is
a line number and the third is a line of code
"""
import inspect
# the first 2 elements in the stack are the current line and the line
# of caller of `_find_the_caller`
i = i + 2
caller = inspect.stack()[i]
return caller[1], caller[2], caller[4][0].rstrip("\n").strip()
def _check_args(self, msg, *args):
if args:
caller = self._find_the_caller(1)
logger = getLogger("%s:%s" % (caller[0], caller[1]))
logger.warning("[%s] %s" % (caller[2], self._posargs_msg % msg))
def debug(self, msg, *args, **kwargs):
self._check_args(msg, *args)
self.log(log.RDEBUG, msg, *args, **kwargs)
def info(self, msg, *args, **kwargs):
self._check_args(msg, *args)
self.log(log.INFO, msg, *args, **kwargs)
def warning(self, msg, *args, **kwargs):
self._check_args(msg, *args)
self.log(log.WARNING, msg, *args, **kwargs)
def error(self, msg, *args, **kwargs):
self._check_args(msg, *args)
self.log(log.ERROR, msg, *args, **kwargs)
def exception(self, msg, exc_info=True, *args, **kwargs):
if not isinstance(msg, (six.text_type, six.string_types)):
caller = self._find_the_caller()
logger = getLogger("%s:%s" % (caller[0], caller[1]))
logger.warning("[%s] %s" % (caller[2], self._exc_msg))
super(RallyContextAdapter, self).exception(msg, exc_info=exc_info,
*args, **kwargs)
def getLogger(name="unknown", version="unknown"):
if name not in oslogging._loggers:
oslogging._loggers[name] = RallyContextAdapter(log.getLogger(name),
{"project": "rally",
"version": version})
return oslogging._loggers[name]
LOG = getLogger(__name__)
class ExceptionLogger(object):
"""Context that intercepts and logs exceptions.
Usage::
LOG = logging.getLogger(__name__)
...
def foobar():
with ExceptionLogger(LOG, "foobar warning") as e:
return house_of_raising_exception()
if e.exception:
raise e.exception # remove if not required
"""
def __init__(self, logger, warn=None):
self.logger = logger
self.warn = warn
self.exception = None
def __enter__(self):
return self
def __exit__(self, type_, value, traceback):
if value:
self.exception = value
if self.warn:
self.logger.warning(self.warn)
self.logger.debug(value)
if is_debug():
self.logger.exception(value)
return True
class CatcherHandler(log.handlers.BufferingHandler):
def __init__(self):
log.handlers.BufferingHandler.__init__(self, 0)
def shouldFlush(self):
return False
def emit(self, record):
self.buffer.append(record)
class LogCatcher(object):
"""Context manager that catches log messages.
User can make an assertion on their content or fetch them all.
Usage::
LOG = logging.getLogger(__name__)
...
def foobar():
with LogCatcher(LOG) as catcher_in_rye:
LOG.warning("Running Kids")
catcher_in_rye.assertInLogs("Running Kids")
"""
def __init__(self, logger):
self.logger = getattr(logger, "logger", logger)
self.handler = CatcherHandler()
def __enter__(self):
self.logger.addHandler(self.handler)
return self
def __exit__(self, type_, value, traceback):
self.logger.removeHandler(self.handler)
def assertInLogs(self, msg):
"""Assert that `msg' is a substring at least of one logged message.
:param msg: Substring to look for.
:return: Log messages where the `msg' was found.
Raises AssertionError if none.
"""
in_logs = [record.msg
for record in self.handler.buffer if msg in record.msg]
if not in_logs:
raise AssertionError("Expected `%s' is not in logs" % msg)
return in_logs
def fetchLogRecords(self):
"""Returns all logged Records."""
return self.handler.buffer
def fetchLogs(self):
"""Returns all logged messages."""
return [record.msg for record in self.handler.buffer]
def _log_wrapper(obj, log_function, msg, **kw):
"""A logging wrapper for any method of a class.
Class instances that use this decorator should have self.task or
self.deployment attribute. The wrapper produces logs messages both
before and after the method execution, in the following format
(example for tasks):
"Task <Task UUID> | Starting: <Logging message>"
[Method execution...]
"Task <Task UUID> | Completed: <Logging message>"
:param obj: task or deployment which must be attribute of "self"
:param log_function: Logging method to be used, e.g. LOG.info
:param msg: Text message (possibly parameterized) to be put to the log
:param **kw: Parameters for msg
"""
def decorator(f):
@functools.wraps(f)
def wrapper(self, *args, **kwargs):
params = {"msg": msg % kw, "obj_name": obj.title(),
"uuid": getattr(self, obj)["uuid"]}
log_function("%(obj_name)s %(uuid)s | Starting: %(msg)s"
% params)
result = f(self, *args, **kwargs)
log_function("%(obj_name)s %(uuid)s | Completed: %(msg)s"
% params)
return result
return wrapper
return decorator
def log_task_wrapper(log_function, msg, **kw):
return _log_wrapper("task", log_function, msg, **kw)
def log_deploy_wrapper(log_function, msg, **kw):
return _log_wrapper("deployment", log_function, msg, **kw)
def log_verification_wrapper(log_function, msg, **kw):
return _log_wrapper("verification", log_function, msg, **kw)
def log_deprecated(message, rally_version, log_function=None, once=False):
"""A wrapper marking a certain method as deprecated.
:param message: Message that describes why the method was deprecated
:param rally_version: version of Rally when the method was deprecated
:param log_function: Logging method to be used, e.g. LOG.info
:param once: Show only once (default is each)
"""
log_function = log_function or LOG.warning
msg = ("`%(func)s()' is deprecated in v%(version)s: %(msg)s."
" Used at %(caller)s")
def decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
if not (once and getattr(f, "_warned_dep_method", False)):
log_function(msg % {
"msg": message,
"version": rally_version,
"func": f.__name__,
"caller": str(traceback.extract_stack()[-2])
})
f._warned_dep_method = True
return f(*args, **kwargs)
return wrapper
return decorator
def log_deprecated_args(message, rally_version, deprecated_args,
log_function=None, once=False):
"""A wrapper marking certain arguments as deprecated.
:param message: Message that describes why the arguments were deprecated
:param rally_version: version of Rally when the arguments were deprecated
:param deprecated_args: List of deprecated args.
:param log_function: Logging method to be used, e.g. LOG.info
:param once: Show only once (default is each)
"""
log_function = log_function or LOG.warning
msg = ("Argument(s): %(args)s of `%(func)s()' are deprecated in "
"v%(version)s: %(msg)s. Used at %(caller)s")
def decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
if not (once and getattr(f, "_warned_dep_args", False)):
deprecated = ", ".join([
"`%s'" % x for x in deprecated_args if x in kwargs])
if deprecated:
log_function(msg % {
"msg": message,
"version": rally_version,
"args": deprecated,
"func": f.__name__,
"caller": str(traceback.extract_stack()[-2])
})
f._warned_dep_args = True
return f(*args, **kwargs)
return wrapper
return decorator
def is_debug():
return CONF.debug or CONF.rally_debug
| [
"traceback.extract_stack",
"inspect.stack",
"oslo_config.cfg.BoolOpt",
"functools.wraps",
"oslo_log.log.setup",
"oslo_log.log.register_options",
"oslo_log.log.getLogger"
] | [((1016, 1048), 'oslo_log.log.register_options', 'oslogging.register_options', (['CONF'], {}), '(CONF)\n', (1042, 1048), True, 'from oslo_log import log as oslogging\n'), ((817, 942), 'oslo_config.cfg.BoolOpt', 'cfg.BoolOpt', (['"""rally-debug"""'], {'default': '(False)', 'help': '"""Print debugging output only for Rally. Off-site components stay quiet."""'}), "('rally-debug', default=False, help=\n 'Print debugging output only for Rally. Off-site components stay quiet.')\n", (828, 942), False, 'from oslo_config import cfg\n'), ((1566, 1610), 'oslo_log.log.setup', 'oslogging.setup', (['CONF', 'product_name', 'version'], {}), '(CONF, product_name, version)\n', (1581, 1610), True, 'from oslo_log import log as oslogging\n'), ((7614, 7632), 'functools.wraps', 'functools.wraps', (['f'], {}), '(f)\n', (7629, 7632), False, 'import functools\n'), ((9052, 9070), 'functools.wraps', 'functools.wraps', (['f'], {}), '(f)\n', (9067, 9070), False, 'import functools\n'), ((10267, 10285), 'functools.wraps', 'functools.wraps', (['f'], {}), '(f)\n', (10282, 10285), False, 'import functools\n'), ((2601, 2616), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (2614, 2616), False, 'import inspect\n'), ((1645, 1686), 'oslo_log.log.getLogger', 'oslogging.getLogger', ([], {'project': 'product_name'}), '(project=product_name)\n', (1664, 1686), True, 'from oslo_log import log as oslogging\n'), ((9373, 9398), 'traceback.extract_stack', 'traceback.extract_stack', ([], {}), '()\n', (9396, 9398), False, 'import traceback\n'), ((10795, 10820), 'traceback.extract_stack', 'traceback.extract_stack', ([], {}), '()\n', (10818, 10820), False, 'import traceback\n')] |
from kivy.uix.screenmanager import Screen
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivymd.app import MDApp
from kivymd.uix.tab import MDTabsBase
from kivymd.icon_definitions import md_icons
from kivymd.uix.button import MDRectangleFlatButton
from kivy.lang import Builder
from kivymd.uix.taptargetview import MDTapTargetView
from kivy.clock import Clock
from kivy.lang import Builder
from kivy.factory import Factory
from kivy.properties import StringProperty
from kivymd.uix.button import MDIconButton
from kivymd.uix.list import ILeftBodyTouch, OneLineIconListItem
from kivymd.theming import ThemeManager
from kivymd.utils import asynckivy
from kivymd.uix.button import MDFloatingActionButtonSpeedDial
from kivy.core.window import Window
from kivymd.uix.filemanager import MDFileManager
from kivymd.toast import toast
kv = """
Screen:
BoxLayout:
orientation: 'vertical'
MDToolbar:
title: "Hictchhicher"
left_action_items: [["menu", lambda x: nav_draw.set_state()]]
MDTabs:
id: tabs
FloatLayout:
MDFillRoundFlatIconButton:
text: "Pull a Request"
icon: "language-python"
line_color: 0, 1, 0, 1
pos_hint: {"center_x": .5, "center_y": .07}
on_release: app.tap_target_start()
NavigationLayout:
ScreenManager:
id: screen_manager
Screen:
name: "scr1"
MDLabel:
text: "Welcome to Hicthhicker! Want to ask for some help from your neighbours?"
halign: "center"
color: "white"
Screen:
name: "scr2"
MDLabel:
text: "Screen 2"
halign: "center"
MDNavigationDrawer:
id: nav_draw
orientation: "vertical"
padding: "8dp"
spacing: "8dp"
AnchorLayout:
anchor_x: "left"
size_hint_y: None
height: avatar.height
Image:
id: avatar
size_hint: None, None
size: "56dp", "56dp"
source: "data/logo/kivy-icon-256.png"
MDLabel:
text: "RODINcode"
font_style: "Button"
size_hint_y: None
height: self.texture_size[1]
MDLabel:
text: "<EMAIL>"
font_style: "Caption"
size_hint_y: None
height: self.texture_size[1]
ScrollView:
MDList:
OneLineAvatarListItem:
on_press:
nav_draw.set_state("close")
screen_manager.current = "scr1"
text: "Home"
IconLeftWidget:
icon: "home"
OneLineAvatarListItem:
on_press:
nav_draw.set_state("close")
screen_manager.current = "scr2"
text: "About"
IconLeftWidget:
icon: 'information'
Widget:
MDFloatingActionButton:
id: button
icon: "plus"
pos: 10, 10
<Tab>:
MDIconButton:
id: icon
icon: app.icons[0]
user_font_size: "48sp"
pos_hint: {"center_x": .5, "center_y": .5}
"""
class Tab(FloatLayout, MDTabsBase):
'''Class implementing content for a tab.'''
class IconLeftSampleWidget(ILeftBodyTouch, MDIconButton):
pass
class ItemForList(OneLineIconListItem):
icon = StringProperty()
class MyApp(MDApp):
def __init__(self, **kwargs):
super().__init__(**kwargs)
Window.bind(on_keyboard=self.events)
self.manager_open = False
self.file_manager = MDFileManager(
exit_manager=self.exit_manager,
select_path=self.select_path,
preview=True,
)
icons = list(md_icons.keys())[0:30]
data = {
'language-python': 'Python',
'language-php': 'PHP',
'language-cpp': 'C++',
}
def build(self):
self.theme_cls.theme_style = "Dark" # "Light"
self.theme_cls.primary_palette = "Green" # "Purple", "Red"
self.theme_cls.primary_hue = "A700" # "500"
self.theme_cls.accent_palette = 'Lime'
speed_dial = MDFloatingActionButtonSpeedDial()
speed_dial.hint_animation= True
speed_dial.right_pad = True
speed_dial.data = self.data
speed_dial.root_button_anim = True
screen= Builder.load_string(kv)
screen.add_widget(speed_dial)
self.tap_target_view = MDTapTargetView(
widget=screen.ids.button,
title_text="Add Trip",
description_text="Let people know where are you heading",
widget_position="left_bottom",
)
return screen
def on_start(self):
for name_tab in self.icons:
self.root.ids.tabs.add_widget(Tab(text=name_tab))
def on_tab_switch(
self, instance_tabs, instance_tab, instance_tab_label, tab_text
):
'''Called when switching tabs.
:type instance_tabs: <kivymd.uix.tab.MDTabs object>;
:param instance_tab: <__main__.Tab object>;
:param instance_tab_label: <kivymd.uix.tab.MDTabsLabel object>;
:param tab_text: text or name icon of tab;
'''
count_icon = [k for k, v in md_icons.items() if v == tab_text]
instance_tab.ids.icon.icon = count_icon[0]
def tap_target_start(self):
if self.tap_target_view.state == "close":
self.tap_target_view.start()
else:
self.tap_target_view.stop()
def set_list(self):
async def set_list():
names_icons_list = list(md_icons.keys())[self.x:self.y]
for name_icon in names_icons_list:
await asynckivy.sleep(0)
self.screen.ids.box.add_widget(
ItemForList(icon=name_icon, text=name_icon))
asynckivy.start(set_list())
def refresh_callback(self, *args):
'''A method that updates the state of your application
while the spinner remains on the screen.'''
def refresh_callback(interval):
self.screen.ids.box.clear_widgets()
if self.x == 0:
self.x, self.y = 15, 30
else:
self.x, self.y = 0, 15
self.set_list()
self.screen.ids.refresh_layout.refresh_done()
self.tick = 0
Clock.schedule_once(refresh_callback, 1)
def file_manager_open(self):
self.file_manager.show('/') # output manager to the screen
self.manager_open = True
def select_path(self, path):
'''It will be called when you click on the file name
or the catalog selection button.
:type path: str;
:param path: path to the selected directory or file;
'''
self.exit_manager()
toast(path)
def exit_manager(self, *args):
'''Called when the user reaches the root of the directory tree.'''
self.manager_open = False
self.file_manager.close()
def events(self, instance, keyboard, keycode, text, modifiers):
'''Called when buttons are pressed on the mobile device.'''
if keyboard in (1001, 27):
if self.manager_open:
self.file_manager.back()
return True
MyApp().run()
| [
"kivymd.utils.asynckivy.sleep",
"kivy.lang.Builder.load_string",
"kivymd.uix.filemanager.MDFileManager",
"kivymd.uix.taptargetview.MDTapTargetView",
"kivy.core.window.Window.bind",
"kivymd.icon_definitions.md_icons.items",
"kivymd.uix.button.MDFloatingActionButtonSpeedDial",
"kivy.clock.Clock.schedule... | [((4082, 4098), 'kivy.properties.StringProperty', 'StringProperty', ([], {}), '()\n', (4096, 4098), False, 'from kivy.properties import StringProperty\n'), ((4202, 4238), 'kivy.core.window.Window.bind', 'Window.bind', ([], {'on_keyboard': 'self.events'}), '(on_keyboard=self.events)\n', (4213, 4238), False, 'from kivy.core.window import Window\n'), ((4303, 4396), 'kivymd.uix.filemanager.MDFileManager', 'MDFileManager', ([], {'exit_manager': 'self.exit_manager', 'select_path': 'self.select_path', 'preview': '(True)'}), '(exit_manager=self.exit_manager, select_path=self.select_path,\n preview=True)\n', (4316, 4396), False, 'from kivymd.uix.filemanager import MDFileManager\n'), ((4885, 4918), 'kivymd.uix.button.MDFloatingActionButtonSpeedDial', 'MDFloatingActionButtonSpeedDial', ([], {}), '()\n', (4916, 4918), False, 'from kivymd.uix.button import MDFloatingActionButtonSpeedDial\n'), ((5095, 5118), 'kivy.lang.Builder.load_string', 'Builder.load_string', (['kv'], {}), '(kv)\n', (5114, 5118), False, 'from kivy.lang import Builder\n'), ((5190, 5351), 'kivymd.uix.taptargetview.MDTapTargetView', 'MDTapTargetView', ([], {'widget': 'screen.ids.button', 'title_text': '"""Add Trip"""', 'description_text': '"""Let people know where are you heading"""', 'widget_position': '"""left_bottom"""'}), "(widget=screen.ids.button, title_text='Add Trip',\n description_text='Let people know where are you heading',\n widget_position='left_bottom')\n", (5205, 5351), False, 'from kivymd.uix.taptargetview import MDTapTargetView\n'), ((7155, 7195), 'kivy.clock.Clock.schedule_once', 'Clock.schedule_once', (['refresh_callback', '(1)'], {}), '(refresh_callback, 1)\n', (7174, 7195), False, 'from kivy.clock import Clock\n'), ((7618, 7629), 'kivymd.toast.toast', 'toast', (['path'], {}), '(path)\n', (7623, 7629), False, 'from kivymd.toast import toast\n'), ((4468, 4483), 'kivymd.icon_definitions.md_icons.keys', 'md_icons.keys', ([], {}), '()\n', (4481, 4483), False, 'from kivymd.icon_definitions import md_icons\n'), ((6009, 6025), 'kivymd.icon_definitions.md_icons.items', 'md_icons.items', ([], {}), '()\n', (6023, 6025), False, 'from kivymd.icon_definitions import md_icons\n'), ((6375, 6390), 'kivymd.icon_definitions.md_icons.keys', 'md_icons.keys', ([], {}), '()\n', (6388, 6390), False, 'from kivymd.icon_definitions import md_icons\n'), ((6478, 6496), 'kivymd.utils.asynckivy.sleep', 'asynckivy.sleep', (['(0)'], {}), '(0)\n', (6493, 6496), False, 'from kivymd.utils import asynckivy\n')] |
import json
from typing import List
from sortedcontainers import SortedList
from .allocator import Allocator
from .character import Character
from .char_position import CharPosition
class Doc:
def __init__(self, site=0) -> None:
"""
Create a new document
:param site: author id
:type site: int
"""
self.__site: int = site
self._alloc = Allocator(self.site)
self.__clock: int = 0
self.__doc: SortedList[Character] = SortedList()
self.__doc.add(Character("", CharPosition([0], [-1]), self.__clock))
base_bits = CharPosition.BASE_BITS
self.__doc.add(Character("", CharPosition([2 ** base_bits - 1], [-1]),
self.__clock))
def insert(self, position, char) -> str:
"""
Insert char at specified document pos
:param position: flat pos index in document text
:type position: int
:param char: character to insert
:type char: str
:return: patch with specified insert operation
"""
self.__clock += 1
p, q = self.__doc[position].position, self.__doc[position + 1].position
new_char = Character(char, self._alloc(p, q), self.__clock)
self.__doc.add(new_char)
return self.__export("i", new_char)
def delete(self, position) -> str:
"""
Delete char from specified document pos
:param position: flat pos index in document text
:type position: int
:return: patch with specified delete operation
"""
self.__clock += 1
old_char = self.__doc[position + 1]
self.__doc.remove(old_char)
return self.__export("d", old_char)
def apply_patch(self, raw_patch) -> None:
"""
Apply existing patch to internal document
:param raw_patch: raw patch
:type raw_patch: str
"""
patch = json.loads(raw_patch)
if patch["op"] == "i":
patch = Character(patch["char"], CharPosition(
patch["pos"], patch["sites"]), patch["clock"])
self.__doc.add(patch)
elif patch["op"] == "d":
patch = next(c for c in self.__doc if
c.position.position == patch["pos"] and
c.position.sites == patch["sites"] and
c.clock == patch["clock"]
)
self.__doc.remove(patch)
@staticmethod
def __export(op, char) -> str:
"""
Export serialized operation on specified character.
:param op: operation (insert/delete)
:param char: character
:type op: str
:type char: Character
:return: operation serialized as json
"""
patch = {
"op": op,
"char": char.char,
"pos": char.position.position,
"sites": char.position.sites,
"clock": char.clock,
}
return json.dumps(patch, sort_keys=True)
def get_real_position(self, patch):
json_char = json.loads(patch)
idx = next((i for i, c in enumerate(self.__doc) if
c.position.position == json_char["pos"] and
c.position.sites == json_char["sites"] and
c.clock == json_char["clock"]
), None)
return idx
@property
def site(self) -> int:
return self.__site
@site.setter
def site(self, value) -> None:
"""
On site change, refresh Allocator
:param value: author site id
:type value: int
"""
self.__site = value
self._alloc = Allocator(value)
@property
def text(self) -> str:
return "".join([c.char for c in self.__doc])
@property
def authors(self) -> List[int]:
return [c.author for c in self.__doc]
@property
def patch_set(self) -> set:
return {self.__export("i", c) for c in self.__doc[1:-1]}
| [
"json.dumps",
"json.loads",
"sortedcontainers.SortedList"
] | [((495, 507), 'sortedcontainers.SortedList', 'SortedList', ([], {}), '()\n', (505, 507), False, 'from sortedcontainers import SortedList\n'), ((1933, 1954), 'json.loads', 'json.loads', (['raw_patch'], {}), '(raw_patch)\n', (1943, 1954), False, 'import json\n'), ((2995, 3028), 'json.dumps', 'json.dumps', (['patch'], {'sort_keys': '(True)'}), '(patch, sort_keys=True)\n', (3005, 3028), False, 'import json\n'), ((3090, 3107), 'json.loads', 'json.loads', (['patch'], {}), '(patch)\n', (3100, 3107), False, 'import json\n')] |
from unittest import TestCase
import global_functions
import app
from app import flask_app
class TestApp(TestCase):
def setUp(self):
self.app = app
self.username = "newuser"
self.pword = "<PASSWORD>"
self.test_client_app = flask_app.test_client()
self.test_client_app.testing = True
def tearDown(self):
self.app = None
self.username = None
self.pword = None
self.test_client_app = None
def test_user_accounts_is_dict(self):
self.assertIsInstance(self.app.user_accounts, dict)
def test_create_user_account_without_username(self):
self.assertEqual(
self.app.create_user_account("", "pword"),
"User must provide a username"
)
def test_create_user_account_with_invalid_username(self):
self.assertEqual(
self.app.create_user_account([], "pword"),
"Username must be string"
)
def test_create_user_account_with_invalid_username_characters(self):
self.assertEqual(
self.app.create_user_account("@#^&&", "pword"),
"Username should only contain letters and numbers"
)
def test_create_user_account_without_password(self):
self.assertEqual(
self.app.create_user_account("username", ""),
"User must provide a pword"
)
def test_create_user_account_with_invalid_password(self):
self.assertEqual(
self.app.create_user_account("username", 12546),
"Password provided must be a string"
)
def test_create_user_account_with_short_password(self):
self.assertEqual(
self.app.create_user_account("username", "<PASSWORD>"),
"Password should have at-least 6 characters"
)
def test_create_user_account(self):
self.app.create_user_account("username", "1234567")
self.assertTrue(len(self.app.user_accounts) == 1)
def test_create_user_account_password_is_hashed(self):
self.app.create_user_account(self.username, self.pword)
stored_password = self.app.user_accounts[self.username].password_hash
self.assertEqual(
stored_password,
global_functions.sha1_hash(self.pword),
msg="Stored passwords should be Hashed"
)
def test_create_user_with_duplicate_username(self):
self.app.create_user_account("username", "1234567")
self.assertEqual(
self.app.create_user_account("username", "1234567"),
"Username username is already taken. Use a unique username"
)
def test_login_without_password(self):
self.assertEqual(
self.app.login("username", None),
"Password must be provided"
)
def test_login_with_invalid_password(self):
self.assertEqual(
self.app.login("username", "asdasdsds"),
"Wrong credentials combination"
)
def test_login_without_username(self):
self.assertEqual(
self.app.login(None, "asdasdsds"),
"Username must be provided"
)
def test_login_with_invalid_username(self):
self.assertEqual(
self.app.login("non-existent-username", "asdasdsds"),
"Wrong credentials combination"
)
| [
"global_functions.sha1_hash",
"app.flask_app.test_client"
] | [((261, 284), 'app.flask_app.test_client', 'flask_app.test_client', ([], {}), '()\n', (282, 284), False, 'from app import flask_app\n'), ((2241, 2279), 'global_functions.sha1_hash', 'global_functions.sha1_hash', (['self.pword'], {}), '(self.pword)\n', (2267, 2279), False, 'import global_functions\n')] |
# -*- coding: utf-8 -*- #
"""*********************************************************************************************"""
# FileName [ discriminator.py ]
# Synopsis [ Discriminator model ]
# Author [ <NAME> (Andi611) ]
# Copyright [ Copyleft(c), NTUEE, NTU, Taiwan ]
"""*********************************************************************************************"""
###############
# IMPORTATION #
###############
import math
import tensorflow as tf
from configuration import config, BUCKETS
#######################
# CLASS DISCRIMINATOR #
#######################
"""
A CNN Discriminator model for text classification:
Uses an embedding layer, followed by a convolutional, max-pooling and softmax layer.
"""
class Discriminator(object):
##################
# INITIALIZATION #
##################
"""
Loads Discriminator parameters and construct model.
"""
def __init__(self, config, vocab_size):
#--general settings--#
self.vocab_size = vocab_size
self.max_seq_len = BUCKETS[-1][0] + BUCKETS[-1][1]
self.batch_size = config.batch_size
#--discriminator hyper-parameters--#
self.lr = config.d_lr
self.embedding_dim = config.d_embedding_dim
self.num_class = config.d_num_class
self.l2_reg_lambda = config.d_l2_reg_lambda
self.dropout_keep_prob = tf.get_variable(name='dropout_keep_prob', shape=[], initializer=tf.constant_initializer(config.d_dropout_keep_prob))
#--discriminator constant-parameters--#
self.filter_sizes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20]
self.num_filters = [100, 200, 200, 200, 200, 100, 100, 100, 100, 100, 160, 160]
#--placeholders--#
self.input_x = tf.placeholder('int32', [None, self.max_seq_len], name='input_x')
self.input_y = tf.placeholder('float32', [None, self.num_class], name='input_y')
#--construct model--#
self.build_model()
###############
# BUILD MODEL #
###############
"""
Construct tensorflow model.
"""
def build_model(self):
with tf.variable_scope('discriminator'):
#--embedding layer--#
with tf.device('/cpu:0'), tf.variable_scope('word_embedding'):
self.W = tf.get_variable(name='W',
shape=[self.vocab_size, self.embedding_dim],
initializer=tf.truncated_normal_initializer(stddev=6/math.sqrt(self.embedding_dim)))
self.word_embedding = tf.nn.embedding_lookup(params=self.W, ids=self.input_x)
self.word_embedding_expanded = tf.expand_dims(input=self.word_embedding, axis=-1)
#--convolution+maxpool layer for each filter size--#
pooled_outputs = []
for filter_size, num_filter in zip(self.filter_sizes, self.num_filters):
with tf.variable_scope('conv_maxpool_%s' % filter_size):
#--convolution layer--#
filter_shape = [filter_size, self.embedding_dim, 1, num_filter]
W = tf.get_variable(name='W', shape=filter_shape, initializer=tf.truncated_normal_initializer(stddev=0.1))
b = tf.get_variable(name='b', shape=[num_filter], initializer=tf.constant_initializer(0.1))
conv = tf.nn.conv2d(input=self.word_embedding_expanded,
filter=W,
strides=[1, 1, 1, 1],
padding='VALID',
name='conv')
#--add bias and nonlinearity--#
conv_b = tf.nn.bias_add(value=conv, bias=b, name='conv_b')
h = tf.nn.relu(conv_b, name='relu')
#--maxpooling--#
pooled = tf.nn.max_pool(value=h,
ksize=[1, self.max_seq_len - filter_size + 1, 1, 1],
strides=[1, 1, 1, 1],
padding='VALID',
name='max_pooling')
pooled_outputs.append(pooled)
#--combine all the pooled features--#
total_num_filters = sum(self.num_filters)
self.h_pool = tf.concat(values=pooled_outputs, axis=3)
self.h_pool_flat = tf.reshape(self.h_pool, [-1, total_num_filters])
#--add highway--#
with tf.name_scope('highway'):
self.h_highway = self._highway(input_=self.h_pool_flat, size=self.h_pool_flat.get_shape()[1], num_layers=1, bias=0)
#--add dropout--#
with tf.name_scope('dropout'):
self.h_drop = tf.nn.dropout(x=self.h_highway, keep_prob=self.dropout_keep_prob)
#--l2 regularization loss--#
l2_loss = tf.constant(0.0)
#--final (unnormalized) scores and predictions--#
with tf.name_scope('output'):
W = tf.get_variable(name='W', shape=[total_num_filters, self.num_class], initializer=tf.truncated_normal_initializer(stddev=0.1))
b = tf.get_variable(name='b', shape=[self.num_class], initializer=tf.constant_initializer(0.1))
l2_loss += tf.nn.l2_loss(W)
l2_loss += tf.nn.l2_loss(b)
self.scores = tf.nn.xw_plus_b(self.h_drop, W, b, name="scores")
self.ypred_for_auc = tf.nn.softmax(self.scores)
self.predictions = tf.argmax(self.scores, 1, name="predictions")
#--calculat mean cross-entropy loss--#
with tf.name_scope("loss"):
losses = tf.nn.softmax_cross_entropy_with_logits_v2(logits=self.scores, labels=self.input_y)
self.loss = tf.reduce_mean(losses) + self.l2_reg_lambda * l2_loss
#--train_op--#
self.optimizer = tf.train.AdamOptimizer(self.lr)
self.params = [param for param in tf.trainable_variables() if 'discriminator' in param.name]
gradients = self.optimizer.compute_gradients(loss=self.loss, var_list=self.params, aggregation_method=2)
self.train_op = self.optimizer.apply_gradients(gradients)
#****************************************************#
#***************** HELPER FUNCTIONS *****************#
#****************************************************#
############
# _HIGHWAY #
############
"""
Called by build_model(). Highway Network (cf. http://arxiv.org/abs/1505.00387).
t = sigmoid(Wy + b)
z = t * g(Wy + b) + (1 - t) * y
where g is nonlinearity, t is transform gate, and (1 - t) is carry gate.
borrowed from https://github.com/mkroutikov/tf-lstm-char-cnn.
"""
def _highway(self, input_, size, num_layers=1, bias=-2.0, f=tf.nn.relu, scope='Highway'):
with tf.variable_scope(scope):
for idx in range(num_layers):
g = f(self._linear(input_, size, scope='highway_lin_%d' % idx))
t = tf.sigmoid(self._linear(input_, size, scope='highway_gate_%d' % idx) + bias)
output = t * g + (1. - t) * input_
input_ = output
return output
###########
# _LINEAR #
###########
"""
Called by _highway().
An alternative to tf.nn.rnn_cell._linear function, which has been removed in Tensorfow 1.0.1
Linear map: output[k] = sum_i(Matrix[k, i] * input_[i] ) + Bias[k]
Args:
input_: a tensor or a list of 2D, batch x n, Tensors.
output_size: int, second dimension of W[i].
scope: VariableScope for the created subgraph; defaults to "Linear".
Returns:
A 2D Tensor with shape [batch x output_size] equal to
sum_i(input_[i] * W[i]), where W[i]s are newly created matrices.
Raises:
ValueError: if some of the arguments has unspecified or wrong shape.
"""
def _linear(self, input_, output_size, scope=None):
shape = input_.get_shape().as_list()
if len(shape) != 2:
raise ValueError("Linear is expecting 2D arguments: %s" % str(shape))
if not shape[1]:
raise ValueError("Linear expects shape[1] of arguments: %s" % str(shape))
input_size = shape[1]
with tf.variable_scope(scope or "SimpleLinear"):
matrix = tf.get_variable("Matrix", [output_size, input_size], dtype=input_.dtype)
bias_term = tf.get_variable("Bias", [output_size], dtype=input_.dtype)
return tf.matmul(input_, tf.transpose(matrix)) + bias_term
########
# MAIN #
########
"""
For testing and debug purpose
"""
if __name__ == '__main__':
discriminator = Discriminator(config)
| [
"tensorflow.get_variable",
"tensorflow.transpose",
"math.sqrt",
"tensorflow.truncated_normal_initializer",
"tensorflow.nn.dropout",
"tensorflow.nn.softmax",
"tensorflow.reduce_mean",
"tensorflow.nn.embedding_lookup",
"tensorflow.placeholder",
"tensorflow.concat",
"tensorflow.train.AdamOptimizer"... | [((1653, 1718), 'tensorflow.placeholder', 'tf.placeholder', (['"""int32"""', '[None, self.max_seq_len]'], {'name': '"""input_x"""'}), "('int32', [None, self.max_seq_len], name='input_x')\n", (1667, 1718), True, 'import tensorflow as tf\n'), ((1736, 1801), 'tensorflow.placeholder', 'tf.placeholder', (['"""float32"""', '[None, self.num_class]'], {'name': '"""input_y"""'}), "('float32', [None, self.num_class], name='input_y')\n", (1750, 1801), True, 'import tensorflow as tf\n'), ((4990, 5021), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['self.lr'], {}), '(self.lr)\n', (5012, 5021), True, 'import tensorflow as tf\n'), ((1972, 2006), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""discriminator"""'], {}), "('discriminator')\n", (1989, 2006), True, 'import tensorflow as tf\n'), ((3647, 3687), 'tensorflow.concat', 'tf.concat', ([], {'values': 'pooled_outputs', 'axis': '(3)'}), '(values=pooled_outputs, axis=3)\n', (3656, 3687), True, 'import tensorflow as tf\n'), ((3710, 3758), 'tensorflow.reshape', 'tf.reshape', (['self.h_pool', '[-1, total_num_filters]'], {}), '(self.h_pool, [-1, total_num_filters])\n', (3720, 3758), True, 'import tensorflow as tf\n'), ((4121, 4137), 'tensorflow.constant', 'tf.constant', (['(0.0)'], {}), '(0.0)\n', (4132, 4137), True, 'import tensorflow as tf\n'), ((5884, 5908), 'tensorflow.variable_scope', 'tf.variable_scope', (['scope'], {}), '(scope)\n', (5901, 5908), True, 'import tensorflow as tf\n'), ((7129, 7171), 'tensorflow.variable_scope', 'tf.variable_scope', (["(scope or 'SimpleLinear')"], {}), "(scope or 'SimpleLinear')\n", (7146, 7171), True, 'import tensorflow as tf\n'), ((7185, 7257), 'tensorflow.get_variable', 'tf.get_variable', (['"""Matrix"""', '[output_size, input_size]'], {'dtype': 'input_.dtype'}), "('Matrix', [output_size, input_size], dtype=input_.dtype)\n", (7200, 7257), True, 'import tensorflow as tf\n'), ((7273, 7331), 'tensorflow.get_variable', 'tf.get_variable', (['"""Bias"""', '[output_size]'], {'dtype': 'input_.dtype'}), "('Bias', [output_size], dtype=input_.dtype)\n", (7288, 7331), True, 'import tensorflow as tf\n'), ((1372, 1423), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['config.d_dropout_keep_prob'], {}), '(config.d_dropout_keep_prob)\n', (1395, 1423), True, 'import tensorflow as tf\n'), ((2042, 2061), 'tensorflow.device', 'tf.device', (['"""/cpu:0"""'], {}), "('/cpu:0')\n", (2051, 2061), True, 'import tensorflow as tf\n'), ((2063, 2098), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""word_embedding"""'], {}), "('word_embedding')\n", (2080, 2098), True, 'import tensorflow as tf\n'), ((2317, 2372), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', ([], {'params': 'self.W', 'ids': 'self.input_x'}), '(params=self.W, ids=self.input_x)\n', (2339, 2372), True, 'import tensorflow as tf\n'), ((2408, 2458), 'tensorflow.expand_dims', 'tf.expand_dims', ([], {'input': 'self.word_embedding', 'axis': '(-1)'}), '(input=self.word_embedding, axis=-1)\n', (2422, 2458), True, 'import tensorflow as tf\n'), ((3789, 3813), 'tensorflow.name_scope', 'tf.name_scope', (['"""highway"""'], {}), "('highway')\n", (3802, 3813), True, 'import tensorflow as tf\n'), ((3965, 3989), 'tensorflow.name_scope', 'tf.name_scope', (['"""dropout"""'], {}), "('dropout')\n", (3978, 3989), True, 'import tensorflow as tf\n'), ((4009, 4074), 'tensorflow.nn.dropout', 'tf.nn.dropout', ([], {'x': 'self.h_highway', 'keep_prob': 'self.dropout_keep_prob'}), '(x=self.h_highway, keep_prob=self.dropout_keep_prob)\n', (4022, 4074), True, 'import tensorflow as tf\n'), ((4200, 4223), 'tensorflow.name_scope', 'tf.name_scope', (['"""output"""'], {}), "('output')\n", (4213, 4223), True, 'import tensorflow as tf\n'), ((4474, 4490), 'tensorflow.nn.l2_loss', 'tf.nn.l2_loss', (['W'], {}), '(W)\n', (4487, 4490), True, 'import tensorflow as tf\n'), ((4506, 4522), 'tensorflow.nn.l2_loss', 'tf.nn.l2_loss', (['b'], {}), '(b)\n', (4519, 4522), True, 'import tensorflow as tf\n'), ((4541, 4590), 'tensorflow.nn.xw_plus_b', 'tf.nn.xw_plus_b', (['self.h_drop', 'W', 'b'], {'name': '"""scores"""'}), "(self.h_drop, W, b, name='scores')\n", (4556, 4590), True, 'import tensorflow as tf\n'), ((4616, 4642), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['self.scores'], {}), '(self.scores)\n', (4629, 4642), True, 'import tensorflow as tf\n'), ((4666, 4711), 'tensorflow.argmax', 'tf.argmax', (['self.scores', '(1)'], {'name': '"""predictions"""'}), "(self.scores, 1, name='predictions')\n", (4675, 4711), True, 'import tensorflow as tf\n'), ((4763, 4784), 'tensorflow.name_scope', 'tf.name_scope', (['"""loss"""'], {}), "('loss')\n", (4776, 4784), True, 'import tensorflow as tf\n'), ((4799, 4887), 'tensorflow.nn.softmax_cross_entropy_with_logits_v2', 'tf.nn.softmax_cross_entropy_with_logits_v2', ([], {'logits': 'self.scores', 'labels': 'self.input_y'}), '(logits=self.scores, labels=self.\n input_y)\n', (4841, 4887), True, 'import tensorflow as tf\n'), ((5058, 5082), 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (5080, 5082), True, 'import tensorflow as tf\n'), ((7360, 7380), 'tensorflow.transpose', 'tf.transpose', (['matrix'], {}), '(matrix)\n', (7372, 7380), True, 'import tensorflow as tf\n'), ((2624, 2674), 'tensorflow.variable_scope', 'tf.variable_scope', (["('conv_maxpool_%s' % filter_size)"], {}), "('conv_maxpool_%s' % filter_size)\n", (2641, 2674), True, 'import tensorflow as tf\n'), ((2996, 3110), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', ([], {'input': 'self.word_embedding_expanded', 'filter': 'W', 'strides': '[1, 1, 1, 1]', 'padding': '"""VALID"""', 'name': '"""conv"""'}), "(input=self.word_embedding_expanded, filter=W, strides=[1, 1, 1,\n 1], padding='VALID', name='conv')\n", (3008, 3110), True, 'import tensorflow as tf\n'), ((3198, 3247), 'tensorflow.nn.bias_add', 'tf.nn.bias_add', ([], {'value': 'conv', 'bias': 'b', 'name': '"""conv_b"""'}), "(value=conv, bias=b, name='conv_b')\n", (3212, 3247), True, 'import tensorflow as tf\n'), ((3257, 3288), 'tensorflow.nn.relu', 'tf.nn.relu', (['conv_b'], {'name': '"""relu"""'}), "(conv_b, name='relu')\n", (3267, 3288), True, 'import tensorflow as tf\n'), ((3325, 3464), 'tensorflow.nn.max_pool', 'tf.nn.max_pool', ([], {'value': 'h', 'ksize': '[1, self.max_seq_len - filter_size + 1, 1, 1]', 'strides': '[1, 1, 1, 1]', 'padding': '"""VALID"""', 'name': '"""max_pooling"""'}), "(value=h, ksize=[1, self.max_seq_len - filter_size + 1, 1, 1],\n strides=[1, 1, 1, 1], padding='VALID', name='max_pooling')\n", (3339, 3464), True, 'import tensorflow as tf\n'), ((4899, 4921), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['losses'], {}), '(losses)\n', (4913, 4921), True, 'import tensorflow as tf\n'), ((4314, 4357), 'tensorflow.truncated_normal_initializer', 'tf.truncated_normal_initializer', ([], {'stddev': '(0.1)'}), '(stddev=0.1)\n', (4345, 4357), True, 'import tensorflow as tf\n'), ((4429, 4457), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.1)'], {}), '(0.1)\n', (4452, 4457), True, 'import tensorflow as tf\n'), ((2842, 2885), 'tensorflow.truncated_normal_initializer', 'tf.truncated_normal_initializer', ([], {'stddev': '(0.1)'}), '(stddev=0.1)\n', (2873, 2885), True, 'import tensorflow as tf\n'), ((2954, 2982), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.1)'], {}), '(0.1)\n', (2977, 2982), True, 'import tensorflow as tf\n'), ((2259, 2288), 'math.sqrt', 'math.sqrt', (['self.embedding_dim'], {}), '(self.embedding_dim)\n', (2268, 2288), False, 'import math\n')] |
#!/usr/bin/env python3
# Created on 05/01/2018
# @author: <NAME>
# @license: MIT-license
# Purpose: example of a simple finite state machine with a text-based game agent
# Explanation:
from enum import Enum
import time
import random
class state_type(Enum):
state_run = "Run Away"
state_patrol = "Patrol"
state_attack = "Attack"
class enemy_type(Enum):
state_strong = "I'm a strong enemy"
state_weak = "I'm a weak enemy"
state_present = "I'm an enemy"
state_missing = "There is no enemy"
class simple_agent:
def __init__(self, initial_state):
self.state = initial_state
def current_state(self):
return self.state
def change_state(self, state, enemy_state):
if state == state_type.state_patrol:
if enemy_type.state_strong:
self.state = state_type.state_run
elif enemy_type.state_weak:
self.state = state_type.state_attack
elif enemy_state.state_missing:
self.state = state_type.state_patrol
#elif state == state_type.state_run:
#if enemy_type.state_present:
# self.state = state_type.state_run
#elif enemy_type.state_missing:
# self.state = state_type.state_patrol
elif state == state_type.state_attack:
if enemy_type.state_strong:
self.state = state_type.state_run
elif enemy_type.state_weak:
self.state = state_type.state_patrol
def run(self, enemy_strong):
#do run
if enemy_strong == True:
print("Running away...")
if enemy_type.state_present:
self.state = state_type.state_run
elif enemy_type.state_missing:
self.state = state_type.state_patrol
def patrol(self, enemy_present):
#do patrol
if enemy_present == False:
print("Patroling...")
elif enemy_present == True:
print("Oh no! Enemy is here...")
def attack(self, enemy_weak):
#do attack
if enemy_weak == True:
print("Attacking...")
else:
self.run(True)
def is_enemy_present():
present = random.randint(0,1)
if present == 0:
presence = False
elif present == 1:
presence = True
return presence
def main():
#create the agent object and set default state to patrol
agent = simple_agent(state_type.state_patrol)
#loop until we quit
while True:
try:
if agent.current_state() == state_type.state_patrol:
agent.patrol(is_enemy_present())
agent.change_state(agent.current_state, enemy_type.state_weak)
time.sleep(5)
except EOFError:
break
main() | [
"random.randint",
"time.sleep"
] | [((2224, 2244), 'random.randint', 'random.randint', (['(0)', '(1)'], {}), '(0, 1)\n', (2238, 2244), False, 'import random\n'), ((2759, 2772), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (2769, 2772), False, 'import time\n')] |
import logging
import logging.config
import requests
logging.config.fileConfig('logging.conf', disable_existing_loggers=False)
logger = logging.getLogger(__name__)
def log_response_and_raise_for_status(
response: requests.models.Response) -> None:
logger.debug(f'API response details:\n' \
f'\t- URL: {response.url}\n' \
f'\t- HTTP status code: {response.status_code}\n' \
f'\t- Encoding: {response.encoding}')
response.raise_for_status()
| [
"logging.getLogger",
"logging.config.fileConfig"
] | [((54, 127), 'logging.config.fileConfig', 'logging.config.fileConfig', (['"""logging.conf"""'], {'disable_existing_loggers': '(False)'}), "('logging.conf', disable_existing_loggers=False)\n", (79, 127), False, 'import logging\n'), ((137, 164), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (154, 164), False, 'import logging\n')] |
from sklearn.linear_model import RidgeClassifierCV as _RidgeClassifierCV
from script.sklearn_like_toolkit.warpper.base.BaseWrapperClf import BaseWrapperClf
from script.sklearn_like_toolkit.warpper.base.MixIn import MetaBaseWrapperClfWithABC
class skRidgeCVClf(_RidgeClassifierCV, BaseWrapperClf, metaclass=MetaBaseWrapperClfWithABC):
def __init__(self, alphas=(0.1, 1.0, 10.0), fit_intercept=True, normalize=False, scoring=None, cv=None,
class_weight=None):
_RidgeClassifierCV.__init__(self, alphas, fit_intercept, normalize, scoring, cv, class_weight)
BaseWrapperClf.__init__(self)
HyperOpt_space = {}
tuning_grid = {
# shape positive float
'alphas': (0.1, 1.0, 10.0),
# 'cv': None,
# 'scoring': None,
# 'class_weight': None
# 'fit_intercept': True,
# 'normalize': False,
}
| [
"script.sklearn_like_toolkit.warpper.base.BaseWrapperClf.BaseWrapperClf.__init__",
"sklearn.linear_model.RidgeClassifierCV.__init__"
] | [((501, 599), 'sklearn.linear_model.RidgeClassifierCV.__init__', '_RidgeClassifierCV.__init__', (['self', 'alphas', 'fit_intercept', 'normalize', 'scoring', 'cv', 'class_weight'], {}), '(self, alphas, fit_intercept, normalize, scoring,\n cv, class_weight)\n', (528, 599), True, 'from sklearn.linear_model import RidgeClassifierCV as _RidgeClassifierCV\n'), ((605, 634), 'script.sklearn_like_toolkit.warpper.base.BaseWrapperClf.BaseWrapperClf.__init__', 'BaseWrapperClf.__init__', (['self'], {}), '(self)\n', (628, 634), False, 'from script.sklearn_like_toolkit.warpper.base.BaseWrapperClf import BaseWrapperClf\n')] |
import random
from loader import *
import pygame
from spritesheet import *
class Powerup(pygame.sprite.Sprite):
#type e o tipo de powerups
def __init__(self,tipo,screen):
pygame.sprite.Sprite.__init__(self)
self.tipo = tipo
if tipo == 1:
#e um escudo
ss = spritesheet('shields.png')
#indice = random.randrange(0,8)
indice = 7
indicefinal = (indice)+20
self.image = ss.image_at((indice*25, 0, indicefinal, 25),-1)
self.rect = self.image.get_rect()
self.som = load_sound('powerup.wav')
self.som.play()
#calcular factor de cura do escudo
self.healfactor = 0
i = 0
while i <= indice:
self.healfactor += 0.05
i = i +1
elif tipo == 2:
ss = spritesheet('weapons.png')
indice = random.randrange(0,2)
indice += 1
indicefinal = (indice)+20
self.image = ss.image_at((indice*25, 0, indicefinal, 25),-1)
self.rect = self.image.get_rect()
self.som = load_sound('powerup.wav')
self.som.play()
#double ou quad damage
if indice == 1:
self.damagefactor = 2
self.ammo = 5
else:
self.damagefactor = 4
self.ammo = 10
elif tipo == 3:
ss = spritesheet('weapons.png')
indice = 0
indicefinal = (indice)+20
self.image = ss.image_at((indice*25, 0, indicefinal, 25),-1)
self.rect = self.image.get_rect()
self.som = load_sound('powerup.wav')
self.som.play()
randomx = random.randrange(70,screen[0]-70)
randomy = random.randrange(70,screen[1]-70)
self.rect.center = (randomx,randomy)
def get_powerup_pos():
return self.rect.center
| [
"pygame.sprite.Sprite.__init__",
"random.randrange"
] | [((194, 229), 'pygame.sprite.Sprite.__init__', 'pygame.sprite.Sprite.__init__', (['self'], {}), '(self)\n', (223, 229), False, 'import pygame\n'), ((1805, 1841), 'random.randrange', 'random.randrange', (['(70)', '(screen[0] - 70)'], {}), '(70, screen[0] - 70)\n', (1821, 1841), False, 'import random\n'), ((1857, 1893), 'random.randrange', 'random.randrange', (['(70)', '(screen[1] - 70)'], {}), '(70, screen[1] - 70)\n', (1873, 1893), False, 'import random\n'), ((944, 966), 'random.randrange', 'random.randrange', (['(0)', '(2)'], {}), '(0, 2)\n', (960, 966), False, 'import random\n')] |
"""
Encoding = UTF-8
By <NAME>, 2019/3/18
Usage: get image file from the onstage
"""
from flask import request
import cv2
import os
def get_image():
img = request.files.get('photo')
path = "static/images/"
file_path = path + img.filename
img.save(file_path)
img = cv2.imread(file_path)
cv2.imwrite(os.path.join('static/images', 'test.jpg'), img)
| [
"os.path.join",
"flask.request.files.get",
"cv2.imread"
] | [((160, 186), 'flask.request.files.get', 'request.files.get', (['"""photo"""'], {}), "('photo')\n", (177, 186), False, 'from flask import request\n'), ((285, 306), 'cv2.imread', 'cv2.imread', (['file_path'], {}), '(file_path)\n', (295, 306), False, 'import cv2\n'), ((323, 364), 'os.path.join', 'os.path.join', (['"""static/images"""', '"""test.jpg"""'], {}), "('static/images', 'test.jpg')\n", (335, 364), False, 'import os\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from subprocess import run, PIPE, TimeoutExpired
from xmltodict import parse as parsexml
# timeout
# errorcode
class IpsetError(RuntimeError):
"""ipset returned an error"""
def _run_cmd(command, args=[]):
"""
Helper function to help calling and decoding ipset output
:param command: command to run
:param args: list of additional arguments
:return: tuple (bool, dict, str), representing command success, parsed output, and raw error output
"""
result = run(["ipset", command, "-output", "xml"] + args, stdout=PIPE, stderr=PIPE, timeout=2)
success = result.returncode == 0
out = result.stdout.decode("UTF-8")
err = result.stderr.decode("UTF-8")
if out:
return (success, parsexml(out), err or None)
else:
return (success, None, err or None)
class Ipset:
def __init__(self, name):
"""
Instantiate this class, but actually does nothing.
:param name: name of the set.
"""
self.name = name
def create(self, typ, timeout=None, counters=True, skbinfo=True, comment=False, exist=True, **kwargs):
"""
Create the set with given configuration options. Additional options can be given by kwargs.
"""
args = [self.name, typ]
if timeout:
args += ["timeout", timeout]
if counters:
args += ["counters"]
if comment:
args += ["comment"]
if skbinfo:
args += ["skbinfo"]
if exist:
args += ["-exist"]
for k,v in [(k, kwargs[k]) for k in kwargs]:
if type(v) == bool or v == None:
if v:
args += [k]
else:
args += [k, v]
success, _, err = _run_cmd("create", args)
if not success:
raise IpsetError(err)
def destroy(self):
"""
Destroy the set.
"""
success, _, err = _run_cmd("destroy", [self.name])
if not success:
raise IpsetError(err)
def add(self, entry, exist=True, nomatch=False):
"""
Add entry to the set.
:param entry: either a raw value such as an ip, or an Entry allowing to give additional properties such as comment or skb values.
:param exist: don't fail if entry already exists.
:param nomatch: see ipset(8).
"""
if type(entry) is Entry:
args = [self.name] + entry.to_cmd()
else:
args = [self.name, entry]
if nomatch:
args += ["nomatch"]
if exist:
args += ["-exist"]
success, _, err = _run_cmd("add", args)
if not success:
raise IpsetError(err)
def delete(self, entry, exist=True):
"""
Delete entry from the set.
:param entry: either a raw value such as an ip, or an Entry.
:param exist: don't fail if entry does not exist.
"""
if type(entry) is Entry:
args = [self.name, entry.elem]
else:
args = [self.name, entry]
if exist:
args += ["-exist"]
success, _, err = _run_cmd("del", args)
if not success:
raise IpsetError(err)
def test(self, entry):
"""
Test if entry exist in set.
:param entry: either a raw value such as an ip, or an Entry.
:retur: bool was the entry found.
"""
if type(entry) is Entry:
args = [entry.elem]
else:
args = [entry]
success, _, err = _run_cmd("test", args)
if success:
return True
if "is NOT in set" in err:
return False
raise IpsetError(err)
def list(self):
"""
List entries in set.
:return: Set instance containing datas about the ipset and it's content.
"""
success, res, err = _run_cmd("list", [self.name])
if not success:
raise IpsetError(err)
return Set.from_dict(res["ipsets"]["ipset"])
def flush(self):
"""
Flush all entries from the set.
"""
success, _, err = _run_cmd("flush", [self.name])
if not success:
raise IpsetError(err)
def rename(self, name):
"""
Rename the set.
:param name: the new name.
"""
success, _, err = _run_cmd("rename", [self.name, name])
if not success:
raise IpsetError(err)
self.name = name
def swap(self, other):
"""
Swap two sets.
They must be compatible for the operation to success.
:param other: Ipset, the other set to swap with.
"""
success, _, err = _run_cmd("swap", [self.name, other.name])
if not success:
raise IpsetError(err)
self.name,other.name = other.name,self.name
def real(self):
"""
Is this a real ipset or a mock?
:return: True
"""
return True
class Set:
"""
A dataclass representing the state of an ipset at a given time.
"""
def __init__(self, name, typ, header, entries):
self.name = name # string
self.type = typ # string
self.header = header # dict
self.entries = entries # list of entries
def from_dict(data):
"""
Deserialize itself from ipset output
"""
if data["members"] is None:
entries = []
elif type(data["members"]["member"]) is list:
entries = [Entry(**e) for e in data["members"]["member"]]
else:
entries = [Entry(**data["members"]["member"])]
return Set(data["@name"], data["type"], dict(data["header"]), entries)
class Entry:
"""
A dataclass representing a single (to be or existing) entry in an ipset.
"""
def __init__(self, elem, timeout=None, packets=None, bytes=None, comment=None, skbmark=None, skbprio=None, skbqueue=None):
self.elem = elem
self.comment = comment.replace('"', '')
self.timeout = int(timeout) if timeout is not None else None
self.packets = int(packets) if packets is not None else None
self.bytes = int(bytes) if bytes is not None else None
self.skbqueue = int(skbqueue) if skbqueue is not None else None
if skbmark is None:
self.skbmark = None
elif type(skbmark) is int:
self.skbmark = (skbmark, 2**32-1)
elif type(skbmark) is tuple:
self.skbmark = skbmark
else:
if "/" in skbmark:
mark,mask = skbmark.split("/")
self.skbmark = (int(mark, 16), int(mask,16))
else:
self.skbmark = (int(skbmark, 16), 2**32-1)
if skbprio is None:
self.skbprio = None
elif type(skbprio) is tuple:
self.skbprio = skbprio
else:
maj,min = skbprio.split(":")
self.skbprio = (int(maj), int(min))
def to_cmd(self):
"""
Serialize itself to the parameters that would add it to an ipset.
:return: list of strings, the arguments that would add it to a set.
"""
res = [self.elem]
if self.comment is not None:
res += ["comment", self.comment]
if self.timeout is not None:
res += ["timeout", str(self.timeout)]
if self.packets is not None:
res += ["packets", str(self.packets)]
if self.bytes is not None:
res += ["bytes", str(self.bytes)]
if self.skbqueue is not None:
res += ["skbqueue", str(self.skbqueue)]
if self.skbmark is not None:
res += ["skbmark", '0x{:x}/0x{:x}'.format(*self.skbmark)]
if self.skbprio is not None:
res += ["skbprio", '{}:{}'.format(*self.skbprio)]
return res
| [
"subprocess.run",
"xmltodict.parse"
] | [((539, 628), 'subprocess.run', 'run', (["(['ipset', command, '-output', 'xml'] + args)"], {'stdout': 'PIPE', 'stderr': 'PIPE', 'timeout': '(2)'}), "(['ipset', command, '-output', 'xml'] + args, stdout=PIPE, stderr=PIPE,\n timeout=2)\n", (542, 628), False, 'from subprocess import run, PIPE, TimeoutExpired\n'), ((779, 792), 'xmltodict.parse', 'parsexml', (['out'], {}), '(out)\n', (787, 792), True, 'from xmltodict import parse as parsexml\n')] |
import os
import paramiko
import queue
from botocore.exceptions import EndpointConnectionError
from ebcli.objects.exceptions import NoRegionError
from ebcli.objects.exceptions import ServiceError
from os.path import expanduser
from paramiko.ssh_exception import SSHException
from threading import Thread
from queue import Empty
from util.aws_util import authorize_ssh, revoke_ssh_authorization, format_aws_file
from util.curl_util import curl_post_data
from classes.get_last_rotated_logs import GetLastRotatedLogs
class TailEC2Instance(object):
def __init__(self, eb_environment_id, instance_id, host, user, files, key_pem,
instance_dict, api_endpoint=None, keep_files=True, logger=None):
self.eb_environment_id = eb_environment_id
self.instance_id = instance_id
self.host = host
self.user = user
self.files = files
if os.path.basename(key_pem) == key_pem:
sep = os.path.sep
p = '~' + sep + '.ssh' + sep
p = expanduser(p)
self.key_pem_path = p + key_pem
else:
self.key_pem_path = key_pem
self.instance_dict = instance_dict
self.api_endpoint = api_endpoint
self.keep_files = keep_files
self.logger = logger
# SSH-specific variables
self.threads = []
self.queue = queue.Queue()
self.responses = []
self.group = None
def run(self):
"""
Orchestrates a single EC2 instance log tailing process
- loads the dictionary of files
- grant an SSH connection into the EC2 instance if needed
- collects the regular log files (and the rotated ones if needed) and saves them locally
- sends the logs to a third-party platform if set
- clears all saved log files if set and revokes the SSH authorization
- updates the instance dictionary with the updated number of lines
:return:
"""
try:
# Checks if log file path exist in instance_dictionary
for file in self.files:
if file['name'] not in self.instance_dict:
self.instance_dict[file['name']] = {}
# Pre-Tail step
self.group = authorize_ssh(self.instance_id, self.logger)
# Part 1: Tail regular log files and, if enabled, rotated ones from archives
regular_files = self.tail_regular_logs()
rotated_files = self.tail_rotated_logs()
# Part 2 (optional): Send logs to a third-party platform
if self.api_endpoint is not None: self.send_log_files(regular_files + rotated_files)
# Part 3 (optional): Clear saved files of logs
if not self.keep_files: self.clear_log_files(regular_files + rotated_files)
# Post-Tail step
revoke_ssh_authorization(self.instance_id, self.group, self.logger)
self.logger.info("{instance}: Tailing logs completed".format(instance=self.instance_id))
except KeyError as e:
self.logger.error("{instance}: {error}".format(instance=self.instance_id, error=str(e)))
except NoRegionError:
self.logger.error("{instance}: region should be specified with 'ebcli.classes.aws.set_region'".format(instance=self.instance_id))
except EndpointConnectionError as e:
self.logger.error("{instance}: {error}".format(instance=self.instance_id, error=str(e)))
except ServiceError as e:
self.logger.error("{instance}: code ({code}), message({message})".format(instance=self.instance_id, code=e.code, message=str(e)))
except Exception as e:
self.logger.error("{instance}: {error}".format(instance=self.instance_id, error=str(e)))
finally:
return self.instance_dict
def tail_regular_logs(self):
"""
Tails and saves the remotely regular log files
:return:
"""
try:
commands = []
self.logger.debug("{instance}: SSH into instance and tail logs".format(instance=self.instance_id))
for file in self.files:
commands.append("tail --lines=+0 {log_file}".format(log_file=file['name']))
for i, cmd in enumerate(commands):
thread = Thread(target=self.ssh_exec_command, args=(cmd, self.files[i]['name'], self.queue))
thread.start()
self.threads.append(thread)
for thread in self.threads:
thread.join()
while True:
self.responses.append(self.queue.get(False))
except Empty as e:
self.logger.debug("{instance}: Queue emptied".format(instance=self.instance_id))
return self.save_regular_log_files()
except Exception as e:
self.logger.error("{instance}: Error type ({type})".format(instance=self.instance_id, type=type(e)))
self.logger.error("{instance}: Error ({error})".format(instance=self.instance_id, error=str(e)))
raise e
def tail_rotated_logs(self):
"""
Collects the logs from the most recent archive if a rotation happened
:return:
"""
rotated_files = []
for response in self.responses:
output = response['output']
filename = response['file']
new_nb_lines = len(output)
rotated = [file['rotated'] for file in self.files if file['name'] == filename][0]
try:
# The number of lines might have never been set yet
if 'nb_lines' in self.instance_dict[filename]:
old_nb_lines = self.instance_dict[filename]['nb_lines']
# If already set, we have to know whether or not we are facing a log rotation
if rotated and old_nb_lines > new_nb_lines:
rotated_file_name = self.save_rotated_log_files(filename, old_nb_lines)
if rotated_file_name is not False:
rotated_files.append(rotated_file_name)
# We want to update the regular log file whether or not it's empty
self.instance_dict[filename]['nb_lines'] = new_nb_lines
except Exception as e:
self.logger.error("{instance}: Exception when updating instance dictionary, {err}".format(instance=self.instance_id, err=str(e)))
raise e
return rotated_files
def save_rotated_log_files(self, filename, old_nb_lines):
"""
Saves one rotated log file from its last rotated archive
:param filename:
:param old_nb_lines:
:return:
"""
self.logger.debug("{instance} retrieving the most recent archive for {filename}".format(instance=self.instance_id, filename=filename))
# Instantiate LastRotatedLogs to retrieve the most recent archive and copy it locally
local_rotated_file = GetLastRotatedLogs(filename, self.instance_id, self.host, self.user,
os.curdir, self.key_pem_path, self.logger).get_rotated_file()
# We just want the logs we haven't previously processed
if local_rotated_file is not False:
lines = open(local_rotated_file).readlines()
len_rotated_archive = len(lines)
difference = len_rotated_archive - old_nb_lines
if difference > 0:
self.logger.debug("{instance}: {old_nb_lines} logs previously retrieved in {filename}".format(instance=self.instance_id, old_nb_lines=old_nb_lines, filename=filename))
self.logger.debug("{instance}: keeping {diff} new logs for {filename}".format(instance=self.instance_id, diff=difference, filename=filename))
with open(local_rotated_file, 'w') as rotated_logs:
for log in lines[old_nb_lines:len_rotated_archive]:
formatted_log = "[{eb_env}] - {log}".format(eb_env=self.eb_environment_id, log=log)
rotated_logs.write(formatted_log)
else:
os.remove(local_rotated_file)
local_rotated_file = False
else:
self.logger.error("{instance}: failed to get the rotated archive for {file}".format(instance=self.instance_id, file=filename))
return local_rotated_file
def save_regular_log_files(self):
"""
Saves regular log files whether or not the given outputs contain rows
Automatically take into consideration new logs and skips ones previously processed
:return:
"""
self.logger.debug("{instance}: Saving logs into disk".format(instance=self.instance_id))
files = []
for response in self.responses:
file_name = format_aws_file(os.path.basename(response['file']), self.instance_id)
file = response['file']
old_nb_lines = self.instance_dict[file]['nb_lines'] if 'nb_lines' in self.instance_dict[file] else 0
output = response['output']
output = output[old_nb_lines:len(output)]
error = response['error']
difference = len(output)
self.instance_dict[file]['nb_lines'] = old_nb_lines + difference
if len(error) > 0:
self.logger.error("{instance}: Errors in response during SSH, {error}".format(instance=self.instance_id, error=error))
if difference == 0: continue
with open(file_name, 'w') as log_file:
for log in output:
formatted_log = "[{eb_env}] - {log}".format(eb_env=self.eb_environment_id, log=log)
log_file.write(formatted_log)
files.append(file_name)
self.logger.debug("{instance}: {nb} new logs saved for {file}".format(instance=self.instance_id, nb=difference, file=file_name))
return files
def send_log_files(self, files):
"""
Sends logs from the saved files to a third-party platform through an endpoint
:param files:
:return:
"""
self.logger.debug("{instance}: send logs to a third-party platform".format(instance=self.instance_id))
for file_name in files:
self.logger.debug("{instance}: using {api_endpoint} endpoint to perform curl".format(instance=self.instance_id, api_endpoint=self.api_endpoint))
self.logger.debug("{instance}: post log file {file_name}".format(instance=self.instance_id, file_name=file_name))
curl_post_data(self.api_endpoint, file_name, self.logger)
def clear_log_files(self, files):
"""
Clears the previously saved log files (the regular and the rotated ones)
:param files:
:return:
"""
if len(files) > 0:
self.logger.info("{instance}: Clearing saved logs".format(instance=self.instance_id))
else:
self.logger.info("{instance}: Nothing to clear".format(instance=self.instance_id))
for file_name in files:
os.remove(file_name)
self.logger.info("{instance}: {file} removed from local disk".format(instance=self.instance_id, file=file_name))
def ssh_exec_command(self, cmd, filename, queue):
"""
Executes command for a specific log file with its own SSH client
:param cmd:
:param filename:
:param queue:
:return:
"""
ssh_cli = paramiko.SSHClient()
ssh_cli.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_cli.load_system_host_keys()
try:
ssh_cli.connect(hostname=self.host, username=self.user, key_filename=self.key_pem_path)
stdin, stdout, stderr = ssh_cli.exec_command(cmd)
self.logger.debug("{instance}: Executing {cmd} through SSH".format(instance=self.instance_id, cmd=cmd))
out = stdout.readlines()
err = stderr.readlines()
queue.put({"file": filename, "output": out, "error": err})
except SSHException as e:
self.logger.error("{instance}: ssh exception says {error} ".format(instance=self.instance_id, error=str(e)))
except FileNotFoundError:
self.logger.error("{instance}: {key_pem} pem file not found".format(instance=self.instance_id, key_pem=self.key_pem_path))
except Exception as e:
self.logger.error("{instance}: ssh_exec_command - {type}".format(instance=self.instance_id, type=type(e)))
self.logger.error("{instance}: ssh_exec_command - {error} ".format(instance=self.instance_id, error=str(e)))
finally:
ssh_cli.close()
| [
"classes.get_last_rotated_logs.GetLastRotatedLogs",
"paramiko.AutoAddPolicy",
"util.aws_util.authorize_ssh",
"util.aws_util.revoke_ssh_authorization",
"queue.put",
"os.path.basename",
"util.curl_util.curl_post_data",
"threading.Thread",
"queue.Queue",
"paramiko.SSHClient",
"os.path.expanduser",
... | [((1364, 1377), 'queue.Queue', 'queue.Queue', ([], {}), '()\n', (1375, 1377), False, 'import queue\n'), ((11548, 11568), 'paramiko.SSHClient', 'paramiko.SSHClient', ([], {}), '()\n', (11566, 11568), False, 'import paramiko\n'), ((895, 920), 'os.path.basename', 'os.path.basename', (['key_pem'], {}), '(key_pem)\n', (911, 920), False, 'import os\n'), ((1020, 1033), 'os.path.expanduser', 'expanduser', (['p'], {}), '(p)\n', (1030, 1033), False, 'from os.path import expanduser\n'), ((2282, 2326), 'util.aws_util.authorize_ssh', 'authorize_ssh', (['self.instance_id', 'self.logger'], {}), '(self.instance_id, self.logger)\n', (2295, 2326), False, 'from util.aws_util import authorize_ssh, revoke_ssh_authorization, format_aws_file\n'), ((2880, 2947), 'util.aws_util.revoke_ssh_authorization', 'revoke_ssh_authorization', (['self.instance_id', 'self.group', 'self.logger'], {}), '(self.instance_id, self.group, self.logger)\n', (2904, 2947), False, 'from util.aws_util import authorize_ssh, revoke_ssh_authorization, format_aws_file\n'), ((10628, 10685), 'util.curl_util.curl_post_data', 'curl_post_data', (['self.api_endpoint', 'file_name', 'self.logger'], {}), '(self.api_endpoint, file_name, self.logger)\n', (10642, 10685), False, 'from util.curl_util import curl_post_data\n'), ((11148, 11168), 'os.remove', 'os.remove', (['file_name'], {}), '(file_name)\n', (11157, 11168), False, 'import os\n'), ((11613, 11637), 'paramiko.AutoAddPolicy', 'paramiko.AutoAddPolicy', ([], {}), '()\n', (11635, 11637), False, 'import paramiko\n'), ((12056, 12114), 'queue.put', 'queue.put', (["{'file': filename, 'output': out, 'error': err}"], {}), "({'file': filename, 'output': out, 'error': err})\n", (12065, 12114), False, 'import queue\n'), ((4345, 4433), 'threading.Thread', 'Thread', ([], {'target': 'self.ssh_exec_command', 'args': "(cmd, self.files[i]['name'], self.queue)"}), "(target=self.ssh_exec_command, args=(cmd, self.files[i]['name'], self\n .queue))\n", (4351, 4433), False, 'from threading import Thread\n'), ((7031, 7147), 'classes.get_last_rotated_logs.GetLastRotatedLogs', 'GetLastRotatedLogs', (['filename', 'self.instance_id', 'self.host', 'self.user', 'os.curdir', 'self.key_pem_path', 'self.logger'], {}), '(filename, self.instance_id, self.host, self.user, os.\n curdir, self.key_pem_path, self.logger)\n', (7049, 7147), False, 'from classes.get_last_rotated_logs import GetLastRotatedLogs\n'), ((8192, 8221), 'os.remove', 'os.remove', (['local_rotated_file'], {}), '(local_rotated_file)\n', (8201, 8221), False, 'import os\n'), ((8898, 8932), 'os.path.basename', 'os.path.basename', (["response['file']"], {}), "(response['file'])\n", (8914, 8932), False, 'import os\n')] |
from sanic_openapi import doc
'''**********************************************************
>>> 策略model <<<
StrategyDto:入口,tradeCondition:交易条件,riskControl:风险控制
tradeCondition:{
'params':{
'args':[],
'logic':logic
}
}
**********************************************************'''
class logic:
compare = doc.String("比较方法", choices="le")
byValue = doc.Float("比较值", choices=0.8)
byMax = doc.Float("比较区间最大值", choices=5)
class params:
args = doc.List(items=[doc.Integer("输入参数", choices=5)])
logic = logic
class tradeCondition:
modName = doc.String("模块名称", choices="ma_indicator")
clsName = doc.String("类名称", choices="iMaCompare")
params = params
# params = doc.Dictionary(fileds = {"args":doc.List(items=[])})
class rule:
tradeCondition = doc.List(tradeCondition, description="buy or sell rule")
class riskControl:
maxRPS = doc.Float("单只股票最大资金占比", choices=0.35)
maxAllPositionRate = doc.Float("每次交易现有资金的最大使用比例", choices=0.35)
maxStocks = doc.Integer("最大持有股票数", choices=5)
distribute = doc.Integer("?", choices=0)
afterDaySell = doc.Integer("最长持有股票天数", choices=5)
class StrategyDto:
strategyExecuteId = doc.Integer("策略job 唯一 ID 由 md5 生成", choices=1017)
bullBear = doc.Integer("?", choices=0)
startCash = doc.Integer("初始资金", choices=10000)
commission = doc.Float("commission", choices=0.001)
stampDuty = doc.Float("stampDuty", choices=0.001)
startDay = doc.String("开始日期", choices="2018-01-01")
endDay = doc.String("结束日期",choices="2018-11-01")
kline = doc.String("k线类型", choices="kline_day")
myStocks = doc.List(items=[doc.String("股票code", choices="SH.600000")])
buyRule = rule
sellRule = rule
riskControl = riskControl
class APIVALIDATION:
api_key=doc.String('api_key',choices= "<KEY>",)
seceret_key=doc.String('seceret_key',choices= "5F6DDA0C9C825B360651EEF3013AA724",)
passphrase=doc.String('passphrase <PASSWORD>',choices= "<PASSWORD>",)
exchange=doc.String('交易所 OKEX HUOBI BINANCE',choices= "OKEX")
class YieldDto:
user = doc.Integer("用户id", choices=1)
api = doc.Integer("交易所apiID", choices=1) | [
"sanic_openapi.doc.List",
"sanic_openapi.doc.String",
"sanic_openapi.doc.Float",
"sanic_openapi.doc.Integer"
] | [((446, 478), 'sanic_openapi.doc.String', 'doc.String', (['"""比较方法"""'], {'choices': '"""le"""'}), "('比较方法', choices='le')\n", (456, 478), False, 'from sanic_openapi import doc\n'), ((493, 522), 'sanic_openapi.doc.Float', 'doc.Float', (['"""比较值"""'], {'choices': '(0.8)'}), "('比较值', choices=0.8)\n", (502, 522), False, 'from sanic_openapi import doc\n'), ((535, 566), 'sanic_openapi.doc.Float', 'doc.Float', (['"""比较区间最大值"""'], {'choices': '(5)'}), "('比较区间最大值', choices=5)\n", (544, 566), False, 'from sanic_openapi import doc\n'), ((697, 739), 'sanic_openapi.doc.String', 'doc.String', (['"""模块名称"""'], {'choices': '"""ma_indicator"""'}), "('模块名称', choices='ma_indicator')\n", (707, 739), False, 'from sanic_openapi import doc\n'), ((754, 793), 'sanic_openapi.doc.String', 'doc.String', (['"""类名称"""'], {'choices': '"""iMaCompare"""'}), "('类名称', choices='iMaCompare')\n", (764, 793), False, 'from sanic_openapi import doc\n'), ((916, 972), 'sanic_openapi.doc.List', 'doc.List', (['tradeCondition'], {'description': '"""buy or sell rule"""'}), "(tradeCondition, description='buy or sell rule')\n", (924, 972), False, 'from sanic_openapi import doc\n'), ((1006, 1043), 'sanic_openapi.doc.Float', 'doc.Float', (['"""单只股票最大资金占比"""'], {'choices': '(0.35)'}), "('单只股票最大资金占比', choices=0.35)\n", (1015, 1043), False, 'from sanic_openapi import doc\n'), ((1069, 1111), 'sanic_openapi.doc.Float', 'doc.Float', (['"""每次交易现有资金的最大使用比例"""'], {'choices': '(0.35)'}), "('每次交易现有资金的最大使用比例', choices=0.35)\n", (1078, 1111), False, 'from sanic_openapi import doc\n'), ((1128, 1161), 'sanic_openapi.doc.Integer', 'doc.Integer', (['"""最大持有股票数"""'], {'choices': '(5)'}), "('最大持有股票数', choices=5)\n", (1139, 1161), False, 'from sanic_openapi import doc\n'), ((1179, 1206), 'sanic_openapi.doc.Integer', 'doc.Integer', (['"""?"""'], {'choices': '(0)'}), "('?', choices=0)\n", (1190, 1206), False, 'from sanic_openapi import doc\n'), ((1226, 1260), 'sanic_openapi.doc.Integer', 'doc.Integer', (['"""最长持有股票天数"""'], {'choices': '(5)'}), "('最长持有股票天数', choices=5)\n", (1237, 1260), False, 'from sanic_openapi import doc\n'), ((1305, 1354), 'sanic_openapi.doc.Integer', 'doc.Integer', (['"""策略job 唯一 ID 由 md5 生成"""'], {'choices': '(1017)'}), "('策略job 唯一 ID 由 md5 生成', choices=1017)\n", (1316, 1354), False, 'from sanic_openapi import doc\n'), ((1370, 1397), 'sanic_openapi.doc.Integer', 'doc.Integer', (['"""?"""'], {'choices': '(0)'}), "('?', choices=0)\n", (1381, 1397), False, 'from sanic_openapi import doc\n'), ((1414, 1448), 'sanic_openapi.doc.Integer', 'doc.Integer', (['"""初始资金"""'], {'choices': '(10000)'}), "('初始资金', choices=10000)\n", (1425, 1448), False, 'from sanic_openapi import doc\n'), ((1466, 1504), 'sanic_openapi.doc.Float', 'doc.Float', (['"""commission"""'], {'choices': '(0.001)'}), "('commission', choices=0.001)\n", (1475, 1504), False, 'from sanic_openapi import doc\n'), ((1521, 1558), 'sanic_openapi.doc.Float', 'doc.Float', (['"""stampDuty"""'], {'choices': '(0.001)'}), "('stampDuty', choices=0.001)\n", (1530, 1558), False, 'from sanic_openapi import doc\n'), ((1574, 1614), 'sanic_openapi.doc.String', 'doc.String', (['"""开始日期"""'], {'choices': '"""2018-01-01"""'}), "('开始日期', choices='2018-01-01')\n", (1584, 1614), False, 'from sanic_openapi import doc\n'), ((1628, 1668), 'sanic_openapi.doc.String', 'doc.String', (['"""结束日期"""'], {'choices': '"""2018-11-01"""'}), "('结束日期', choices='2018-11-01')\n", (1638, 1668), False, 'from sanic_openapi import doc\n'), ((1680, 1719), 'sanic_openapi.doc.String', 'doc.String', (['"""k线类型"""'], {'choices': '"""kline_day"""'}), "('k线类型', choices='kline_day')\n", (1690, 1719), False, 'from sanic_openapi import doc\n'), ((1899, 1937), 'sanic_openapi.doc.String', 'doc.String', (['"""api_key"""'], {'choices': '"""<KEY>"""'}), "('api_key', choices='<KEY>')\n", (1909, 1937), False, 'from sanic_openapi import doc\n'), ((1955, 2024), 'sanic_openapi.doc.String', 'doc.String', (['"""seceret_key"""'], {'choices': '"""5F6DDA0C9C825B360651EEF3013AA724"""'}), "('seceret_key', choices='5F6DDA0C9C825B360651EEF3013AA724')\n", (1965, 2024), False, 'from sanic_openapi import doc\n'), ((2041, 2098), 'sanic_openapi.doc.String', 'doc.String', (['"""passphrase <PASSWORD>"""'], {'choices': '"""<PASSWORD>"""'}), "('passphrase <PASSWORD>', choices='<PASSWORD>')\n", (2051, 2098), False, 'from sanic_openapi import doc\n'), ((2113, 2165), 'sanic_openapi.doc.String', 'doc.String', (['"""交易所 OKEX HUOBI BINANCE"""'], {'choices': '"""OKEX"""'}), "('交易所 OKEX HUOBI BINANCE', choices='OKEX')\n", (2123, 2165), False, 'from sanic_openapi import doc\n'), ((2194, 2224), 'sanic_openapi.doc.Integer', 'doc.Integer', (['"""用户id"""'], {'choices': '(1)'}), "('用户id', choices=1)\n", (2205, 2224), False, 'from sanic_openapi import doc\n'), ((2235, 2269), 'sanic_openapi.doc.Integer', 'doc.Integer', (['"""交易所apiID"""'], {'choices': '(1)'}), "('交易所apiID', choices=1)\n", (2246, 2269), False, 'from sanic_openapi import doc\n'), ((609, 639), 'sanic_openapi.doc.Integer', 'doc.Integer', (['"""输入参数"""'], {'choices': '(5)'}), "('输入参数', choices=5)\n", (620, 639), False, 'from sanic_openapi import doc\n'), ((1751, 1792), 'sanic_openapi.doc.String', 'doc.String', (['"""股票code"""'], {'choices': '"""SH.600000"""'}), "('股票code', choices='SH.600000')\n", (1761, 1792), False, 'from sanic_openapi import doc\n')] |
from handler.base_plugin import BasePlugin
from vk.helpers import parse_user_id
import peewee_async, peewee, asyncio, random, time
# Requirements:
# PeeweePlugin
#
class DuelerPlugin(BasePlugin):
__slots__ = ("commands", "prefixes", "models", "pwmanager", "active")
def __init__(self, prefixes=("",), _help="дуэли помощь", me="я", pay="зп", duel="вызов", top="топ",
accept="принять", auct="аукцион", bet="ставка", add="добавить", remove="удалить", postprefix=""):
"""Nice game "Dueler"."""
super().__init__()
self.commands = [(postprefix + " " if postprefix else "") + c.lower() for c in (me, _help, pay, duel, accept, auct, bet, add, remove, top,)] # [-1] == [10]
self.prefixes = prefixes
self.pwmanager = None
self.models = []
self.active = True
self.description = ["Игра \"Dueler\"",
f"{self.prefixes[0]}{self.commands[1]} - показать помощь по игре."]
def initiate(self):
if self.pwmanager is None:
raise ValueError("Please, use PeeweePlugin with set_manager=True for this plugin to work or set pwmanager for plugin yourself.")
class Equipment(peewee.Model):
name = peewee.TextField()
slot = peewee.TextField()
power = peewee.IntegerField()
class Meta:
database = self.pwmanager.database
indexes = (
(('name', 'power', 'slot'), True),
)
class Player(peewee.Model):
user_id = peewee.BigIntegerField()
chat_id = peewee.BigIntegerField()
last_payout = peewee.BigIntegerField(default=0)
lastmsg = peewee.BigIntegerField(default=0)
lastreq = peewee.BigIntegerField(default=0)
state = peewee.IntegerField(default=0)
money = peewee.IntegerField(default=0)
wins = peewee.IntegerField(default=0)
losses = peewee.IntegerField(default=0)
helm = peewee.ForeignKeyField(Equipment, on_delete='SET NULL', null=True, related_name="hemled")
chest = peewee.ForeignKeyField(Equipment, on_delete='SET NULL', null=True, related_name="chested")
weapon = peewee.ForeignKeyField(Equipment, on_delete='SET NULL', null=True, related_name="weaponed")\
class Meta:
database = self.pwmanager.database
indexes = (
(('user_id', 'chat_id'), True),
)
class Auct(peewee.Model):
chat_id = peewee.BigIntegerField()
lot1 = peewee.ForeignKeyField(Equipment, on_delete='SET NULL', null=True, related_name="lot1ed")
lot2 = peewee.ForeignKeyField(Equipment, on_delete='SET NULL', null=True, related_name="lot2ed")
lot3 = peewee.ForeignKeyField(Equipment, on_delete='SET NULL', null=True, related_name="lot3ed")
lot4 = peewee.ForeignKeyField(Equipment, on_delete='SET NULL', null=True, related_name="lot4ed")
lot5 = peewee.ForeignKeyField(Equipment, on_delete='SET NULL', null=True, related_name="lot5ed")
bet1 = peewee.IntegerField(default=0)
bet2 = peewee.IntegerField(default=0)
bet3 = peewee.IntegerField(default=0)
bet4 = peewee.IntegerField(default=0)
bet5 = peewee.IntegerField(default=0)
buyer1 = peewee.BigIntegerField(default=0)
buyer2 = peewee.BigIntegerField(default=0)
buyer3 = peewee.BigIntegerField(default=0)
buyer4 = peewee.BigIntegerField(default=0)
buyer5 = peewee.BigIntegerField(default=0)
endt = peewee.BigIntegerField(default=0)
class Meta:
database = self.pwmanager.database
indexes = (
(('user_id', ), True),
)
class Duel(peewee.Model):
userid1 = peewee.BigIntegerField()
userid2 = peewee.BigIntegerField()
chat_id = peewee.BigIntegerField()
class Meta:
database = self.pwmanager.database
indexes = (
(('chat_id', 'userid1', 'userid2'), True),
)
with self.pwmanager.allow_sync():
Equipment.create_table(True)
Player.create_table(True)
Duel.create_table(True)
Auct.create_table(True)
self.models = Auct, Duel, Player, Equipment
@staticmethod
def get_level(score):
e = 0
for i in range(100):
score -= e * 1.2 + 50
if score <= 0:
return i, -score
return 100, -1
async def global_before_message_checks(self, msg):
msg.meta["__cplayer"] = await self.get_or_create_player(msg.chat_id, msg.user_id)
if time.time() - msg.meta["__cplayer"].lastmsg < 15:
return
if msg.meta["__cplayer"].lastmsg == 0 or time.time() - msg.meta["__cplayer"].lastmsg < 60 * 5:
msg.meta["__cplayer"].state = min(100, msg.meta["__cplayer"].state + 2)
elif time.time() - msg.meta["__cplayer"].lastmsg < 60 * 10:
msg.meta["__cplayer"].state = min(100, msg.meta["__cplayer"].state + 1)
elif time.time() - msg.meta["__cplayer"].lastmsg < 60 * 20:
msg.meta["__cplayer"].state = max(0, msg.meta["__cplayer"].state - 10)
elif time.time() - msg.meta["__cplayer"].lastmsg >= 60 * 20:
msg.meta["__cplayer"].state = max(0, msg.meta["__cplayer"].state - 50)
msg.meta["__cplayer"].lastmsg = time.time()
async def check_message(self, msg):
prefix = None
pltext = ""
for p in self.prefixes:
if msg.full_text.startswith(p):
prefix = p
pltext = msg.full_text.replace(p, "", 1)
break
if prefix is None:
return False
for c in self.commands:
if pltext.startswith(c + " ") or pltext.startswith(c + "\n") or pltext == c:
break
else:
return False
msg.meta["__prefix"] = prefix
msg.meta["__pltext"] = pltext
return True
async def get_or_create_player(self, chat_id, user_id):
Auct, Duel, Player, Equipment = self.models
try:
equipments = (
Equipment
.select()
)
players = (
Player
.select()
.where(
(Player.chat_id == chat_id) &
(Player.user_id == user_id)
)
)
player = list(await self.pwmanager.prefetch(players, equipments))[0]
except IndexError:
player = await peewee_async.create_object(Player, chat_id=chat_id, user_id=user_id)
return player
async def get_or_create_auct(self, chat_id):
Auct, Duel, Player, Equipment = self.models
try:
equipments = (
Equipment
.select()
)
aucts = (
Auct
.select()
.where(
Auct.chat_id == chat_id
)
)
auct = list(await self.pwmanager.prefetch(aucts, equipments))[0]
except IndexError:
auct = await peewee_async.create_object(Auct, chat_id=chat_id)
return auct
async def process_message(self, msg):
if msg.meta["__pltext"].lower() == self.commands[1]:
me, _help, pay, duel, accept, auct, bet, add, remove, top, = self.commands
p = self.prefixes[0]
return await msg.answer(f'''У каждoго учаcтникa чата есть свой игровой пeрсoнаж, имеющий:
- Оcновная xapaктеpиcтика - cилу 🤛, золото 💰 и cнaряжeниe (шлeм ⛑, брoня 🛡, оружиe ⚔), котopoe увеличивает силу персoнaжа и пoкупается нa aукциoнe. Такжe у пepсонажа eсть состояние (в %) - онo определяетcя отноcитeльно текущeгo актива учacтника в чaтe.
- Аукциoн мoжно пpoвoдить не чащe, чeм pаз в чaс, и каждый paз нa нeм выcтавляются cлучайнoе снapяжeние со cлучайными xарактериcтикaми (чeм выше xapактеpистики, тeм pеже выпaдaeт).
- Рaз в час вcем пеpсoнажам чaта можнo выдавать жалованиe - oбщая сумма для чaтa завиcит oт кoличеcтвa активныx в пocлeднee врeмя учаcтников, a количество жaлoвaния на кaждoгo пepcонaжа - в завиcимocти oт поcледнего актива учaстников относитeльно oбщего (у жaловaния нет нaкoплений, eсли нe выдавaть жалoвание - оно cгoрaет)
- Пeрсoнaжи могут вызывaть друг дpуга нa дуэли (кaждый пepcонаж мoжет вызвaть проводить дуэль рaз в час)
На дуэли cpавниваeтся oбщая cилa учаcтникoв, кoтoрая являeтcя cуммoй:
1) вcего cнaряжeния учacтникa
2) состояния
3) удaчи, каждый рaз oпpеделяется случaйным oбpaзoм, но не бoльше 15% oт oбщeй силы
У того, у кoго итоговая сила бoльше, больше вероятностей победить!
Команды:
{p}{me} - информация о персонаже.
{p}{pay} - собрать вознаграждение.
{p}{duel} -вызвать на дуэль.
{p}{accept} -принять вызов.
{p}{auct} - начать аукцион.
{p}{top} - показать лучших бойцов.
{p}{_help} - помощь''')
Auct, Duel, Player, Equipment = self.models
player = msg.meta["__cplayer"] or await self.get_or_create_player(msg.chat_id, msg.user_id)
if msg.meta["__pltext"].lower().startswith(self.commands[9]):
top = await self.pwmanager.execute(Player.select().where(Player.chat_id == msg.chat_id).order_by(Player.wins.desc()).limit(10))
text = "👑 Самые мощные игроки:\n"
users = {}
if "__chat_data" in msg.meta:
for u in msg.meta["__chat_data"].users:
users[u["id"]] = u["first_name"] + " " + u["last_name"]
for i, player in enumerate(top):
text += (
str(i + 1) + ". 😎 " + users.get(player.user_id, f"Пользователь \"{player.user_id}\"") +
"\nПобед: " + str(player.wins) + " // Поражений: " + str(player.losses) + "\n"
)
return await msg.answer(text)
if msg.meta["__pltext"].lower().startswith(self.commands[8]):
if not msg.meta.get("is_admin") and not msg.meta.get("is_moder"):
return msg.answer("Недостаточно прав.")
try:
name = " ".join(msg.meta["__pltext"][len(self.commands[8]):].strip().split(" "))
if not name:
raise ValueError()
except (ValueError, KeyError, IndexError):
return await msg.answer("Как надо: " + self.prefixes[0] + self.commands[8] + " [название предмета]")
await self.pwmanager.execute(Equipment.delete().where(Equipment.name == name))
return await msg.answer("Готово!")
if msg.meta["__pltext"].lower().startswith(self.commands[7]):
if not msg.meta.get("is_admin") and not msg.meta.get("is_moder"):
return await msg.answer("Недостаточно прав.")
try:
power, slot, *names = msg.meta["__pltext"][len(self.commands[7]):].strip().split(" ")
name = " ".join(names)
if not name:
raise ValueError()
except (ValueError, KeyError, IndexError):
return await msg.answer("Как надо: " + self.prefixes[0] + self.commands[7] + " [сила] [слот (helm, weapon или chest)] [название предмета]")
if slot not in ("helm", "weapon", "chest"):
return await msg.answer("Доступные слоты для экипировки: helm, weapon, chest")
for i in range(5):
tpower = round((0.75 + random.random() * 0.5) * round(float(power)))
try:
await peewee_async.create_object(Equipment, name=name, slot=slot, power=tpower)
except peewee.IntegrityError:
pass
return await msg.answer("Готово!")
if msg.meta["__pltext"].lower().startswith(self.commands[6]):
auct = await self.get_or_create_auct(msg.chat_id)
if time.time() - auct.endt >= 0:
return await msg.answer("Аукцион закончен")
try:
_, lot, bet = msg.meta["__pltext"][len(self.commands[6]):].split(" ")
bet = int(bet)
except (KeyError, ValueError):
return await msg.answer("Как надо ставить: " + self.prefixes[0] + self.commands[6] + " [номер лота] [ставка]")
olot = getattr(auct, f"lot{lot}")
obet = getattr(auct, f"bet{lot}")
obuyer = getattr(auct, f"buyer{lot}")
if obet >= bet:
return await msg.answer("Ставка должна быть больше текущей!")
if player.money < bet:
return await msg.answer("У вас недостаточно средств для ставки!")
if obuyer != 0:
prbuyer = await self.get_or_create_player(msg.chat_id, obuyer)
prbuyer.money += obet
await self.pwmanager.update(prbuyer)
player.money -= bet
setattr(auct, f"bet{lot}", bet)
setattr(auct, f"buyer{lot}", player.user_id)
await self.pwmanager.update(auct)
await self.pwmanager.update(player)
text = "💰 Аукцион:\n"
for i in range(1, 6):
olot = getattr(auct, f"lot{i}")
obet = getattr(auct, f"bet{i}")
text += (
f"{i}. " + ("⛑" if olot.slot == "helm" else ("🛡" if olot.slot == "chest" else "⚔")) +
" " + olot.name + " (🤛 " + str(olot.power) + ") - " + str(obet) + "$\n"
)
text += "\nАукцион закончится через 5 минут. Вещи получат игроки, поставившие наибольшую ставку на предмет. "\
"Предметы заменят текущие. Проигравшим вернут деньги.\n\nСтавка: " + self.prefixes[0] + self.commands[6] + " [номер лота] [ставка]"
return await msg.answer(text)
if msg.meta["__pltext"].lower() == self.commands[5]:
auct = await self.get_or_create_auct(msg.chat_id)
if time.time() - auct.endt < 60 * 60:
return await msg.answer(f"💰 Вы сможете начать аукцион через {60 - round((time.time() - auct.endt) / 60)} мин.")
equipments = list(await self.pwmanager.execute(Equipment.select()))
if len(equipments) == 0:
return await msg.answer("Недостаточно экипировки.")
if len(equipments) < 5:
equipments = [equipments[0]] * 5
random.shuffle(equipments)
text = "💰 Аукцион:\n"
for i in range(5):
setattr(auct, f"lot{i + 1}", equipments[i])
setattr(auct, f"buyer{i + 1}", 0)
bet = 0
for _ in range(max(1, equipments[i].power - 3)):
bet += 20 + round(random.random() * 10)
setattr(auct, f"bet{i + 1}", bet)
text += (
f"{i + 1}. " + ("⛑" if equipments[i].slot == "helm" else ("🛡" if equipments[i].slot == "chest" else "⚔")) +
" " + equipments[i].name + " (" + str(equipments[i].power) + ") - " + str(bet) + "$\n"
)
auct.endt = time.time() + 60 * 5
await self.pwmanager.update(player)
await self.pwmanager.update(auct)
text += "\nАукцион закончится через 5 минут. Вещи получат игроки, поставившие наибольшую ставку на предмет. "\
"Предметы заменят текущие. Проигравшим вернут деньги.\n\nСтавка: " + self.prefixes[0] + self.commands[6] + " [номер лота] [ставка]"
async def finish_auct(chat_id):
await asyncio.sleep(60 * 5)
auct = await self.get_or_create_auct(msg.chat_id)
for i in range(1, 6):
olot = getattr(auct, f"lot{i}")
obuyer = getattr(auct, f"buyer{i}")
if obuyer == 0:
continue
p = await self.get_or_create_player(chat_id=chat_id, user_id=obuyer)
if olot.slot == "helm":
p.helm = olot
elif olot.slot == "chest":
p.chest = olot
else:
p.weapon = olot
await self.pwmanager.update(p)
return await msg.answer("Аукцион закончен.")
asyncio.ensure_future(finish_auct(chat_id=msg.chat_id))
return await msg.answer(text)
if msg.meta["__pltext"].lower() == self.commands[4]:
try:
duel = await self.pwmanager.get(Duel, chat_id=msg.chat_id, userid2=msg.user_id)
except Duel.DoesNotExist:
return await msg.answer("Никто не вызывал вас на дуэль!")
player1 = await self.get_or_create_player(msg.chat_id, duel.userid1)
player2 = player
await peewee_async.delete_object(duel)
level1, _ = self.get_level(player1.wins * 10 + player1.losses * 5)
level2, _ = self.get_level(player2.wins * 10 + player2.losses * 5)
epower1 = 9
if player1.helm:
epower1 += player1.helm.power
if player1.chest:
epower1 += player1.chest.power
if player1.weapon:
epower1 += player1.weapon.power
apower1 = epower1 + round(epower1 * (player1.state / 100), 2)
lpower1 = apower1 + round(apower1 * level1 / 100, 2)
power1 = lpower1 + round(lpower1 * 0.15 * random.random(), 2)
epower2 = 9
if player2.helm:
epower2 += player2.helm.power
if player2.chest:
epower2 += player2.chest.power
if player2.weapon:
epower2 += player2.weapon.power
apower2 = epower2 + round(epower2 * (player2.state / 100), 2)
lpower2 = apower2 + round(apower2 * level2 / 100, 2)
power2 = lpower2 + round(lpower2 * 0.15 * random.random(), 2)
player1win = random.random() * (power1 + power2) < power1
users = await self.api.users.get(user_ids=f"{duel.userid1},{duel.userid2}")
if len(users) == 1:
users.append(users[0])
text = (
"Битва персонажей 🤺\"" + users[0]["first_name"] + " " + users[0]["last_name"] + "\" и "
"🤺\"" + users[1]["first_name"] + " " + users[1]["last_name"] + "\"\n"
"Характеристика персонажа" + users[0]["first_name"] + " " + users[0]["last_name"] + "\n"
"🤛 Уровень: " + str(level1) + "\n"
"🤛 Cостояния: " + str(player1.state) + "%" + "\n"
"🤛 Экипировка: " + str(epower1) + "\n"
"🤛 Актив сила: " + str(round(apower1 - epower1, 2)) + "\n"
"🤛 Сила опыта: " + str(round(lpower1 - apower1, 2)) + "\n\n"
"🤛 Сила удачи: " + str(round(power1 - lpower1, 2)) + "\n\n"
"🤛 СИЛА: " + str(round(power1, 2)) + "\n\n"
"Характеристика персонажа" + users[1]["first_name"] + " " + users[1]["last_name"] + "\n"
"🤛 Уровень: " + str(level2) + "\n"
"🤛 Cостояния: " + str(player2.state) + "%" + "\n"
"🤛 Экипировка: " + str(epower2) + "\n"
"🤛 Актив сила: " + str(round(apower2 - epower1, 2)) + "\n"
"🤛 Сила опыта: " + str(round(lpower2 - apower1, 2)) + "\n\n"
"🤛 Сила удачи: " + str(round(power2 - lpower1, 2)) + "\n\n"
"🤛 СИЛА: " + str(round(power2, 2)) + "\n\n"
)
if player1win:
text += (
"После долгой схватки, " + users[0]["first_name"] + " " + users[0]["last_name"] +
" и " + (player1.weapon.name.lower() if player1.weapon else "ничего") + " пробили "
+ (player2.chest.name.lower() if player2.chest else "грудь") + " своего оппонента."
)
player1.wins += 1
player1.money += 5
player2.losses += 1
else:
text += (
"После долгой схватки, " + users[1]["first_name"] + " " + users[1]["last_name"] +
" и " + (player2.weapon.name.lower() if player2.weapon else "ничего") + " пробили "
+ (player1.chest.name.lower() if player1.chest else "грудь") + " своего оппонента."
)
player2.wins += 1
player2.money += 5
player1.losses += 1
text += "\n\nПобедитель: " + (users[0]["first_name"] + " " + users[0]["last_name"] if player1win
else users[1]["first_name"] + " " + users[1]["last_name"]) + " (награда - 5$)"
await self.pwmanager.update(player1)
await self.pwmanager.update(player2)
return await msg.answer(text)
if msg.meta["__pltext"].lower().startswith(self.commands[3]):
if time.time() - player.lastreq < 60 * 60:
return await msg.answer(f"Вы можете бросать не более 1 вызова в час. Осталось: {60 * 60 - round(time.time() - player.lastreq)} сек.")
target_id = await parse_user_id(msg)
if not target_id or target_id < 0:
return await msg.answer("Укажите вашу цель или перешлите её сообщение.")
if msg.user_id == target_id:
return await msg.answer("Вы не можете вызвать на дуэль себя.")
try:
await peewee_async.create_object(Duel, chat_id=msg.chat_id, userid1=msg.user_id, userid2=target_id)
except peewee.IntegrityError:
return await msg.answer(f"[id{target_id}|Вы готовы принять вызов?]\nНапишите \"{self.prefixes[0]}{self.commands[4]}\", чтобы принять.")
player.lastreq = time.time()
await self.pwmanager.update(player)
return await msg.answer(f"[id{target_id}|Вы готовы принять вызов?]\nНапишите \"{self.prefixes[0]}{self.commands[4]}\", чтобы принять.")
if msg.meta["__pltext"].lower().startswith(self.commands[2]):
if time.time() - player.last_payout >= 60 * 60:
gain = 25 + round((player.state / 100) * 200)
player.last_payout = time.time()
player.money += gain
await self.pwmanager.update(player)
return await msg.answer(f"💰 Вы заработали: {gain}$\n💰 Заходите через час!" "\n"
f"💰 Ваш баланс {player.money}$")
await self.pwmanager.update(player)
return await msg.answer(f"💰 Вы сможете получить свою зп через {60 - round((time.time() - player.last_payout) / 60)} мин.")
elif msg.meta["__pltext"].lower() == self.commands[0]:
users =await self.api.users.get(user_ids=msg.user_id)
user = users[0]
level, exp_left = self.get_level(player.wins * 10 + player.losses * 5)
text = (
"💬 Информация о персонаже: {user['first_name']} {user['last_name']}\n"
f"🌳 Уровень: {level}\n"
f"🌳 Опыта до повышения уровня: {round(exp_left)}\n"
f"🌳 Состояние: {player.state}%\n"
f"🌳 Деньги: {player.money}$\n"
f"🌳 Победы: {player.wins}\n"
f"🌳 Поражения: {player.loses}\n"
"🌳 Снаряжение:\n"
)
if player.helm:
text += "- ⛑ " + player.helm.name + " (🤛 " + str(player.helm.power) + ")"
else:
text += "- ⛑ Ничего"
text += "\n"
if player.chest:
text += "- 🛡 " + player.chest.name + " (🤛 " + str(player.chest.power) + ")"
else:
text += "- 🛡 Ничего"
text += "\n"
if player.weapon:
text += "- ⚔ " + player.weapon.name + " (🤛 " + str(player.weapon.power) + ")"
else:
text += "- ⚔ Ничего"
await self.pwmanager.update(player)
return await msg.answer(text)
| [
"random.shuffle",
"peewee.BigIntegerField",
"peewee.ForeignKeyField",
"peewee.IntegerField",
"peewee.TextField",
"peewee_async.delete_object",
"peewee_async.create_object",
"vk.helpers.parse_user_id",
"asyncio.sleep",
"random.random",
"time.time"
] | [((5641, 5652), 'time.time', 'time.time', ([], {}), '()\n', (5650, 5652), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((1241, 1259), 'peewee.TextField', 'peewee.TextField', ([], {}), '()\n', (1257, 1259), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((1279, 1297), 'peewee.TextField', 'peewee.TextField', ([], {}), '()\n', (1295, 1297), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((1318, 1339), 'peewee.IntegerField', 'peewee.IntegerField', ([], {}), '()\n', (1337, 1339), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((1576, 1600), 'peewee.BigIntegerField', 'peewee.BigIntegerField', ([], {}), '()\n', (1598, 1600), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((1623, 1647), 'peewee.BigIntegerField', 'peewee.BigIntegerField', ([], {}), '()\n', (1645, 1647), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((1675, 1708), 'peewee.BigIntegerField', 'peewee.BigIntegerField', ([], {'default': '(0)'}), '(default=0)\n', (1697, 1708), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((1732, 1765), 'peewee.BigIntegerField', 'peewee.BigIntegerField', ([], {'default': '(0)'}), '(default=0)\n', (1754, 1765), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((1788, 1821), 'peewee.BigIntegerField', 'peewee.BigIntegerField', ([], {'default': '(0)'}), '(default=0)\n', (1810, 1821), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((1843, 1873), 'peewee.IntegerField', 'peewee.IntegerField', ([], {'default': '(0)'}), '(default=0)\n', (1862, 1873), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((1894, 1924), 'peewee.IntegerField', 'peewee.IntegerField', ([], {'default': '(0)'}), '(default=0)\n', (1913, 1924), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((1945, 1975), 'peewee.IntegerField', 'peewee.IntegerField', ([], {'default': '(0)'}), '(default=0)\n', (1964, 1975), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((1997, 2027), 'peewee.IntegerField', 'peewee.IntegerField', ([], {'default': '(0)'}), '(default=0)\n', (2016, 2027), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((2048, 2141), 'peewee.ForeignKeyField', 'peewee.ForeignKeyField', (['Equipment'], {'on_delete': '"""SET NULL"""', 'null': '(True)', 'related_name': '"""hemled"""'}), "(Equipment, on_delete='SET NULL', null=True,\n related_name='hemled')\n", (2070, 2141), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((2158, 2252), 'peewee.ForeignKeyField', 'peewee.ForeignKeyField', (['Equipment'], {'on_delete': '"""SET NULL"""', 'null': '(True)', 'related_name': '"""chested"""'}), "(Equipment, on_delete='SET NULL', null=True,\n related_name='chested')\n", (2180, 2252), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((2270, 2365), 'peewee.ForeignKeyField', 'peewee.ForeignKeyField', (['Equipment'], {'on_delete': '"""SET NULL"""', 'null': '(True)', 'related_name': '"""weaponed"""'}), "(Equipment, on_delete='SET NULL', null=True,\n related_name='weaponed')\n", (2292, 2365), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((2594, 2618), 'peewee.BigIntegerField', 'peewee.BigIntegerField', ([], {}), '()\n', (2616, 2618), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((2639, 2732), 'peewee.ForeignKeyField', 'peewee.ForeignKeyField', (['Equipment'], {'on_delete': '"""SET NULL"""', 'null': '(True)', 'related_name': '"""lot1ed"""'}), "(Equipment, on_delete='SET NULL', null=True,\n related_name='lot1ed')\n", (2661, 2732), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((2748, 2841), 'peewee.ForeignKeyField', 'peewee.ForeignKeyField', (['Equipment'], {'on_delete': '"""SET NULL"""', 'null': '(True)', 'related_name': '"""lot2ed"""'}), "(Equipment, on_delete='SET NULL', null=True,\n related_name='lot2ed')\n", (2770, 2841), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((2857, 2950), 'peewee.ForeignKeyField', 'peewee.ForeignKeyField', (['Equipment'], {'on_delete': '"""SET NULL"""', 'null': '(True)', 'related_name': '"""lot3ed"""'}), "(Equipment, on_delete='SET NULL', null=True,\n related_name='lot3ed')\n", (2879, 2950), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((2966, 3059), 'peewee.ForeignKeyField', 'peewee.ForeignKeyField', (['Equipment'], {'on_delete': '"""SET NULL"""', 'null': '(True)', 'related_name': '"""lot4ed"""'}), "(Equipment, on_delete='SET NULL', null=True,\n related_name='lot4ed')\n", (2988, 3059), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((3075, 3168), 'peewee.ForeignKeyField', 'peewee.ForeignKeyField', (['Equipment'], {'on_delete': '"""SET NULL"""', 'null': '(True)', 'related_name': '"""lot5ed"""'}), "(Equipment, on_delete='SET NULL', null=True,\n related_name='lot5ed')\n", (3097, 3168), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((3185, 3215), 'peewee.IntegerField', 'peewee.IntegerField', ([], {'default': '(0)'}), '(default=0)\n', (3204, 3215), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((3235, 3265), 'peewee.IntegerField', 'peewee.IntegerField', ([], {'default': '(0)'}), '(default=0)\n', (3254, 3265), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((3285, 3315), 'peewee.IntegerField', 'peewee.IntegerField', ([], {'default': '(0)'}), '(default=0)\n', (3304, 3315), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((3335, 3365), 'peewee.IntegerField', 'peewee.IntegerField', ([], {'default': '(0)'}), '(default=0)\n', (3354, 3365), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((3385, 3415), 'peewee.IntegerField', 'peewee.IntegerField', ([], {'default': '(0)'}), '(default=0)\n', (3404, 3415), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((3438, 3471), 'peewee.BigIntegerField', 'peewee.BigIntegerField', ([], {'default': '(0)'}), '(default=0)\n', (3460, 3471), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((3493, 3526), 'peewee.BigIntegerField', 'peewee.BigIntegerField', ([], {'default': '(0)'}), '(default=0)\n', (3515, 3526), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((3548, 3581), 'peewee.BigIntegerField', 'peewee.BigIntegerField', ([], {'default': '(0)'}), '(default=0)\n', (3570, 3581), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((3603, 3636), 'peewee.BigIntegerField', 'peewee.BigIntegerField', ([], {'default': '(0)'}), '(default=0)\n', (3625, 3636), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((3658, 3691), 'peewee.BigIntegerField', 'peewee.BigIntegerField', ([], {'default': '(0)'}), '(default=0)\n', (3680, 3691), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((3712, 3745), 'peewee.BigIntegerField', 'peewee.BigIntegerField', ([], {'default': '(0)'}), '(default=0)\n', (3734, 3745), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((3968, 3992), 'peewee.BigIntegerField', 'peewee.BigIntegerField', ([], {}), '()\n', (3990, 3992), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((4015, 4039), 'peewee.BigIntegerField', 'peewee.BigIntegerField', ([], {}), '()\n', (4037, 4039), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((4062, 4086), 'peewee.BigIntegerField', 'peewee.BigIntegerField', ([], {}), '()\n', (4084, 4086), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((14657, 14683), 'random.shuffle', 'random.shuffle', (['equipments'], {}), '(equipments)\n', (14671, 14683), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((22069, 22080), 'time.time', 'time.time', ([], {}), '()\n', (22078, 22080), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((4885, 4896), 'time.time', 'time.time', ([], {}), '()\n', (4894, 4896), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((15367, 15378), 'time.time', 'time.time', ([], {}), '()\n', (15376, 15378), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((17092, 17124), 'peewee_async.delete_object', 'peewee_async.delete_object', (['duel'], {}), '(duel)\n', (17118, 17124), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((21434, 21452), 'vk.helpers.parse_user_id', 'parse_user_id', (['msg'], {}), '(msg)\n', (21447, 21452), False, 'from vk.helpers import parse_user_id\n'), ((22510, 22521), 'time.time', 'time.time', ([], {}), '()\n', (22519, 22521), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((5004, 5015), 'time.time', 'time.time', ([], {}), '()\n', (5013, 5015), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((5156, 5167), 'time.time', 'time.time', ([], {}), '()\n', (5165, 5167), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((6836, 6904), 'peewee_async.create_object', 'peewee_async.create_object', (['Player'], {'chat_id': 'chat_id', 'user_id': 'user_id'}), '(Player, chat_id=chat_id, user_id=user_id)\n', (6862, 6904), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((7436, 7485), 'peewee_async.create_object', 'peewee_async.create_object', (['Auct'], {'chat_id': 'chat_id'}), '(Auct, chat_id=chat_id)\n', (7462, 7485), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((12148, 12159), 'time.time', 'time.time', ([], {}), '()\n', (12157, 12159), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((14208, 14219), 'time.time', 'time.time', ([], {}), '()\n', (14217, 14219), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((15818, 15839), 'asyncio.sleep', 'asyncio.sleep', (['(60 * 5)'], {}), '(60 * 5)\n', (15831, 15839), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((18248, 18263), 'random.random', 'random.random', ([], {}), '()\n', (18261, 18263), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((21212, 21223), 'time.time', 'time.time', ([], {}), '()\n', (21221, 21223), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((21751, 21848), 'peewee_async.create_object', 'peewee_async.create_object', (['Duel'], {'chat_id': 'msg.chat_id', 'userid1': 'msg.user_id', 'userid2': 'target_id'}), '(Duel, chat_id=msg.chat_id, userid1=msg.user_id,\n userid2=target_id)\n', (21777, 21848), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((22365, 22376), 'time.time', 'time.time', ([], {}), '()\n', (22374, 22376), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((5309, 5320), 'time.time', 'time.time', ([], {}), '()\n', (5318, 5320), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((11806, 11879), 'peewee_async.create_object', 'peewee_async.create_object', (['Equipment'], {'name': 'name', 'slot': 'slot', 'power': 'tpower'}), '(Equipment, name=name, slot=slot, power=tpower)\n', (11832, 11879), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((17733, 17748), 'random.random', 'random.random', ([], {}), '()\n', (17746, 17748), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((18202, 18217), 'random.random', 'random.random', ([], {}), '()\n', (18215, 18217), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((5461, 5472), 'time.time', 'time.time', ([], {}), '()\n', (5470, 5472), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((11712, 11727), 'random.random', 'random.random', ([], {}), '()\n', (11725, 11727), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((14989, 15004), 'random.random', 'random.random', ([], {}), '()\n', (15002, 15004), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((21402, 21413), 'time.time', 'time.time', ([], {}), '()\n', (21411, 21413), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((22939, 22950), 'time.time', 'time.time', ([], {}), '()\n', (22948, 22950), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((14362, 14373), 'time.time', 'time.time', ([], {}), '()\n', (14371, 14373), False, 'import peewee_async, peewee, asyncio, random, time\n')] |
# Loads the data and an autoencoder model. The original data is passed
# through the AE and the latent space is fed to the qsvm network.
import sys
import os
import numpy as np
sys.path.append("..")
from .terminal_colors import tcols
from autoencoders import data as aedata
from autoencoders import util as aeutil
class qdata:
"""
Data loader class. qdata is used to load the train/validation/test datasets
for the quantum ML model training given a pre-trained Auto-Encoder model
that reduces the number of features of the initial dataset.
Args:
data_folder (str): Path to the input data of the Auto-Encoder.
norm_name (str): Specify the normalisation of the input data
e.g., minmax, maxabs etc.
nevents (float): Number of signal data samples in the input data file.
Conventionally, we encode this number in the file
name, e.g., nevents = 7.20e+05.
model_path (str): Path to the save PyTorch Auto-Encoder model.
train_events (int): Number of desired train events to be loaded by
qdata.
valid_events (int): Number of desired validation events to be loaded
by qdata.
test_events (int): Number of desired test events to be loaded by
qdata.
kfolds (int): Number of folds (i.e. statistiaclly independent datasets)
to use for validation/testing of the trained QML models.
seed (int): Seed for the shufling of the train/test/validation and
k-folds datasets.
"""
def __init__(
self,
data_folder,
norm_name,
nevents,
model_path,
train_events=0,
valid_events=0,
test_events=0,
kfolds=0,
seed=None,
):
device = "cpu"
model_folder = os.path.dirname(model_path)
hp_file = os.path.join(model_folder, "hyperparameters.json")
hp = aeutil.import_hyperparams(hp_file)
print(tcols.OKCYAN + "\nLoading data:" + tcols.ENDC)
self.ae_data = aedata.AE_data(
data_folder,
norm_name,
nevents,
train_events,
valid_events,
test_events,
seed,
)
self.model = aeutil.choose_ae_model(hp["ae_type"], device, hp)
self.model.load_model(model_path)
self.ntrain = self.ae_data.trdata.shape[0]
self.nvalid = self.ae_data.vadata.shape[0]
self.ntest = self.ae_data.tedata.shape[0]
self.seed = seed
if kfolds > 0:
print(tcols.OKCYAN + "Loading k-folded valid data:" + tcols.ENDC)
self.kfolds = kfolds
self.ae_kfold_data = aedata.AE_data(
data_folder,
norm_name,
nevents,
0,
kfolds * valid_events,
kfolds * test_events,
seed,
)
def get_latent_space(self, datat) -> np.ndarray:
"""
Get the latent space depending on the data set you want.
@datat :: String of the data type.
returns :: Output of the ae depending on the given data type.
"""
if datat == "train":
return self.model.predict(self.ae_data.trdata)[0]
if datat == "valid":
return self.model.predict(self.ae_data.vadata)[0]
if datat == "test":
return self.model.predict(self.ae_data.tedata)[0]
raise TypeError("Given data type does not exist!")
def fold(self, data: np.array, target: np.array, events_per_kfold: int,
latent: bool):
"""
Fold the data, given a number of events you want per fold.
All data that is not folded is then discarded.
For the case of kfold=n and kfold=m, we should not expect any of the
folds to be the same between each other. That is, the input @data
contains self.ntest samples which are then split (create the folds),
concatenated and shuffled again. Hence, we should not expect identical
folds between these two different cases, even for the same self.ntest.
Args:
data: 2D data to be folded (already shuffled once).
target: 1D target data corresponding to the @data.
events_per_kfold: The number of events wanted per fold.
latent: Whether the data should be passed through an ae (True) or not.
Returns:
Folded data set with a certain number of events per fold.
"""
data_sig, data_bkg = self.ae_data.split_sig_bkg(data, target)
data_sig = data_sig.reshape(-1, int(events_per_kfold / 2), data_sig.shape[1])
data_bkg = data_bkg.reshape(-1, int(events_per_kfold / 2), data_bkg.shape[1])
data = np.concatenate((data_sig, data_bkg), axis=1)
target = np.array(
[
np.concatenate(
(
np.ones(int(events_per_kfold / 2)),
np.zeros(int(events_per_kfold / 2)),
)
)
for kfold in range(self.kfolds)
]
)
shuffling = np.random.RandomState(seed=self.seed).permutation(events_per_kfold)
data = data[:, shuffling]
target = target[:, shuffling]
if not latent:
return data, target
data = [self.model.predict(kfold)[0] for kfold in data]
return data, target
def get_kfolded_data(self, datat: str, latent: bool):
"""Get the kfolded data for either the validation or testing data. Choose
whether this data should be passed through an autoencoder or not.
Args:
datat: The data type, i.e., either 'valid' or 'test'.
latent: Whether the data should be passed through an ae (True) or not.
Returns:
Folded data set with a certain number of events per fold.
"""
if datat == "valid":
return self.fold(
self.ae_kfold_data.vadata,
self.ae_kfold_data.vatarget,
self.nvalid,
latent
)
if datat == "test":
return self.fold(
self.ae_kfold_data.tedata,
self.ae_kfold_data.tetarget,
self.ntest,
latent
)
raise TypeError("Given data type does not exist!")
@staticmethod
def batchify(data, batch_size):
"""
Reshape the training data into an array of arrays, the sub arrays
containing the amount of events that are contained in a batch.
@data :: Array of data to be split.
@batch_size :: Int of the batch size.
"""
num_splits = np.ceil(data.shape[0]/batch_size)
return np.array_split(data, num_splits)
@staticmethod
def to_onehot(target):
"""
Reshape the target that such that it follows onehot encoding.
@target :: Numpy array with target data.
"""
onehot_target = np.zeros((target.size, int(target.max() + 1)))
onehot_target[np.arange(target.size), target.astype(int)] = 1
return onehot_target
| [
"numpy.ceil",
"autoencoders.data.AE_data",
"numpy.arange",
"os.path.join",
"autoencoders.util.choose_ae_model",
"numpy.array_split",
"os.path.dirname",
"autoencoders.util.import_hyperparams",
"numpy.concatenate",
"sys.path.append",
"numpy.random.RandomState"
] | [((178, 199), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (193, 199), False, 'import sys\n'), ((1928, 1955), 'os.path.dirname', 'os.path.dirname', (['model_path'], {}), '(model_path)\n', (1943, 1955), False, 'import os\n'), ((1974, 2024), 'os.path.join', 'os.path.join', (['model_folder', '"""hyperparameters.json"""'], {}), "(model_folder, 'hyperparameters.json')\n", (1986, 2024), False, 'import os\n'), ((2038, 2072), 'autoencoders.util.import_hyperparams', 'aeutil.import_hyperparams', (['hp_file'], {}), '(hp_file)\n', (2063, 2072), True, 'from autoencoders import util as aeutil\n'), ((2158, 2256), 'autoencoders.data.AE_data', 'aedata.AE_data', (['data_folder', 'norm_name', 'nevents', 'train_events', 'valid_events', 'test_events', 'seed'], {}), '(data_folder, norm_name, nevents, train_events, valid_events,\n test_events, seed)\n', (2172, 2256), True, 'from autoencoders import data as aedata\n'), ((2369, 2418), 'autoencoders.util.choose_ae_model', 'aeutil.choose_ae_model', (["hp['ae_type']", 'device', 'hp'], {}), "(hp['ae_type'], device, hp)\n", (2391, 2418), True, 'from autoencoders import util as aeutil\n'), ((4901, 4945), 'numpy.concatenate', 'np.concatenate', (['(data_sig, data_bkg)'], {'axis': '(1)'}), '((data_sig, data_bkg), axis=1)\n', (4915, 4945), True, 'import numpy as np\n'), ((6881, 6916), 'numpy.ceil', 'np.ceil', (['(data.shape[0] / batch_size)'], {}), '(data.shape[0] / batch_size)\n', (6888, 6916), True, 'import numpy as np\n'), ((6930, 6962), 'numpy.array_split', 'np.array_split', (['data', 'num_splits'], {}), '(data, num_splits)\n', (6944, 6962), True, 'import numpy as np\n'), ((2807, 2913), 'autoencoders.data.AE_data', 'aedata.AE_data', (['data_folder', 'norm_name', 'nevents', '(0)', '(kfolds * valid_events)', '(kfolds * test_events)', 'seed'], {}), '(data_folder, norm_name, nevents, 0, kfolds * valid_events, \n kfolds * test_events, seed)\n', (2821, 2913), True, 'from autoencoders import data as aedata\n'), ((5294, 5331), 'numpy.random.RandomState', 'np.random.RandomState', ([], {'seed': 'self.seed'}), '(seed=self.seed)\n', (5315, 5331), True, 'import numpy as np\n'), ((7245, 7267), 'numpy.arange', 'np.arange', (['target.size'], {}), '(target.size)\n', (7254, 7267), True, 'import numpy as np\n')] |
# Twisted Imports
from twisted.python.constants import ValueConstant, Values
class State (Values):
READY = ValueConstant("ready")
RUNNING = ValueConstant("running")
PAUSED = ValueConstant("paused")
COMPLETE = ValueConstant("complete")
CANCELLED = ValueConstant("cancelled")
ERROR = ValueConstant("error")
class Event (Values):
NEW_EXPERIMENT = ValueConstant("new-expt")
EXPERIMENT = ValueConstant("e")
INTERFACE = ValueConstant("i")
STEP = ValueConstant("s")
LOG = ValueConstant("l")
TIMEZERO = ValueConstant("z")
| [
"twisted.python.constants.ValueConstant"
] | [((109, 131), 'twisted.python.constants.ValueConstant', 'ValueConstant', (['"""ready"""'], {}), "('ready')\n", (122, 131), False, 'from twisted.python.constants import ValueConstant, Values\n'), ((143, 167), 'twisted.python.constants.ValueConstant', 'ValueConstant', (['"""running"""'], {}), "('running')\n", (156, 167), False, 'from twisted.python.constants import ValueConstant, Values\n'), ((178, 201), 'twisted.python.constants.ValueConstant', 'ValueConstant', (['"""paused"""'], {}), "('paused')\n", (191, 201), False, 'from twisted.python.constants import ValueConstant, Values\n'), ((214, 239), 'twisted.python.constants.ValueConstant', 'ValueConstant', (['"""complete"""'], {}), "('complete')\n", (227, 239), False, 'from twisted.python.constants import ValueConstant, Values\n'), ((253, 279), 'twisted.python.constants.ValueConstant', 'ValueConstant', (['"""cancelled"""'], {}), "('cancelled')\n", (266, 279), False, 'from twisted.python.constants import ValueConstant, Values\n'), ((289, 311), 'twisted.python.constants.ValueConstant', 'ValueConstant', (['"""error"""'], {}), "('error')\n", (302, 311), False, 'from twisted.python.constants import ValueConstant, Values\n'), ((353, 378), 'twisted.python.constants.ValueConstant', 'ValueConstant', (['"""new-expt"""'], {}), "('new-expt')\n", (366, 378), False, 'from twisted.python.constants import ValueConstant, Values\n'), ((393, 411), 'twisted.python.constants.ValueConstant', 'ValueConstant', (['"""e"""'], {}), "('e')\n", (406, 411), False, 'from twisted.python.constants import ValueConstant, Values\n'), ((425, 443), 'twisted.python.constants.ValueConstant', 'ValueConstant', (['"""i"""'], {}), "('i')\n", (438, 443), False, 'from twisted.python.constants import ValueConstant, Values\n'), ((452, 470), 'twisted.python.constants.ValueConstant', 'ValueConstant', (['"""s"""'], {}), "('s')\n", (465, 470), False, 'from twisted.python.constants import ValueConstant, Values\n'), ((478, 496), 'twisted.python.constants.ValueConstant', 'ValueConstant', (['"""l"""'], {}), "('l')\n", (491, 496), False, 'from twisted.python.constants import ValueConstant, Values\n'), ((509, 527), 'twisted.python.constants.ValueConstant', 'ValueConstant', (['"""z"""'], {}), "('z')\n", (522, 527), False, 'from twisted.python.constants import ValueConstant, Values\n')] |
import numpy as np
import torch
from torch import nn
def identity(x):
return x
def fanin_init(tensor):
size = tensor.size()
if len(size) == 2:
fan_in = size[0]
elif len(size) > 2:
fan_in = np.prod(size[1:])
else:
raise Exception("Tensor shape must have dimensions >= 2")
bound = 1. / np.sqrt(fan_in)
return tensor.data.uniform_(-bound, bound)
def product_of_gaussians(mus, sigmas_squared):
'''
compute mu, sigma of product of gaussians
'''
sigmas_squared = torch.clamp(sigmas_squared, min=1e-7)
sigma_squared = 1. / torch.sum(torch.reciprocal(sigmas_squared), dim=0)
mu = sigma_squared * torch.sum(mus / sigmas_squared, dim=0)
return mu, sigma_squared
class LayerNorm(nn.Module):
"""
Simple 1D LayerNorm.
"""
def __init__(self, features, center=True, scale=False, eps=1e-6):
super().__init__()
self.center = center
self.scale = scale
self.eps = eps
if self.scale:
self.scale_param = nn.Parameter(torch.ones(features))
else:
self.scale_param = None
if self.center:
self.center_param = nn.Parameter(torch.zeros(features))
else:
self.center_param = None
def forward(self, x):
mean = x.mean(-1, keepdim=True)
std = x.std(-1, keepdim=True)
output = (x - mean) / (std + self.eps)
if self.scale:
output = output * self.scale_param
if self.center:
output = output + self.center_param
return output
def zeros(*sizes, **kwargs):
return torch.zeros(*sizes, **kwargs).to(device)
def ones(*sizes, **kwargs):
return torch.ones(*sizes, **kwargs).to(device)
def normal(*args, **kwargs):
return torch.normal(*args, **kwargs).to(device) | [
"numpy.prod",
"numpy.sqrt",
"torch.reciprocal",
"torch.sum",
"torch.normal",
"torch.zeros",
"torch.clamp",
"torch.ones"
] | [((530, 568), 'torch.clamp', 'torch.clamp', (['sigmas_squared'], {'min': '(1e-07)'}), '(sigmas_squared, min=1e-07)\n', (541, 568), False, 'import torch\n'), ((336, 351), 'numpy.sqrt', 'np.sqrt', (['fan_in'], {}), '(fan_in)\n', (343, 351), True, 'import numpy as np\n'), ((669, 707), 'torch.sum', 'torch.sum', (['(mus / sigmas_squared)'], {'dim': '(0)'}), '(mus / sigmas_squared, dim=0)\n', (678, 707), False, 'import torch\n'), ((225, 242), 'numpy.prod', 'np.prod', (['size[1:]'], {}), '(size[1:])\n', (232, 242), True, 'import numpy as np\n'), ((603, 635), 'torch.reciprocal', 'torch.reciprocal', (['sigmas_squared'], {}), '(sigmas_squared)\n', (619, 635), False, 'import torch\n'), ((1625, 1654), 'torch.zeros', 'torch.zeros', (['*sizes'], {}), '(*sizes, **kwargs)\n', (1636, 1654), False, 'import torch\n'), ((1707, 1735), 'torch.ones', 'torch.ones', (['*sizes'], {}), '(*sizes, **kwargs)\n', (1717, 1735), False, 'import torch\n'), ((1789, 1818), 'torch.normal', 'torch.normal', (['*args'], {}), '(*args, **kwargs)\n', (1801, 1818), False, 'import torch\n'), ((1052, 1072), 'torch.ones', 'torch.ones', (['features'], {}), '(features)\n', (1062, 1072), False, 'import torch\n'), ((1193, 1214), 'torch.zeros', 'torch.zeros', (['features'], {}), '(features)\n', (1204, 1214), False, 'import torch\n')] |
from dataclasses import dataclass
import netCDF4
import numpy as np
from openamundsen import constants, errors, fileio, util
import pandas as pd
import pandas.tseries.frequencies
import pyproj
import xarray as xr
_ALLOWED_OFFSETS = [
pd.tseries.offsets.YearEnd,
pd.tseries.offsets.YearBegin,
pd.tseries.offsets.MonthEnd,
pd.tseries.offsets.MonthBegin,
pd.tseries.offsets.Day,
pd.tseries.offsets.Hour,
pd.tseries.offsets.Minute,
]
@dataclass
class OutputField:
"""
Class for defining an output field, i.e., a state variable that should be
written at specified dates.
Parameters
----------
var : str
Name of the state variable (e.g. "meteo.temp").
output_name : str
Output name.
agg : str, optional
Aggregation function. Can be either None (if instantaneous values
should be written), "sum" or "mean".
write_dates : pd.DatetimeIndex
Dates at which the field should be written.
data : np.array, optional
Current state of the aggregated values (only used if `agg` is not None).
num_aggregations : int, default 0
Current number of aggregations (required for calculating a running mean).
"""
var: str
output_name: str
agg: str
write_dates: pd.DatetimeIndex
data: np.array = None
num_aggregations: int = 0
def _field_key(field):
return (tuple(field.write_dates), field.agg is None)
class GriddedOutputManager:
"""
Class for managing and storing gridded output data which should be written at
specified dates.
Parameters
----------
model : OpenAmundsen
openAMUNDSEN model instance.
"""
def __init__(self, model):
config = model.config.output_data.grids
fields = []
for field_cfg in config.variables:
try:
output_name = field_cfg['name']
except KeyError:
output_name = None
try:
freq = field_cfg['freq']
except KeyError:
freq = model.dates.freqstr
try:
agg = field_cfg['agg']
except KeyError:
agg = None
if 'dates' in field_cfg:
write_dates = pd.to_datetime(field_cfg['dates'])
else:
write_dates = _freq_write_dates(model.dates, freq, agg is not None)
write_dates = write_dates[
(write_dates >= model.dates[0])
& (write_dates <= model.dates[-1])
]
if len(write_dates) == 0:
model.logger.debug(f'Discarding grid output variable {field_cfg["var"]}'
' (nothing to be written)')
continue
if output_name is None:
output_name = field_cfg.var.split('.')[-1]
if output_name in [f.output_name for f in fields]:
raise errors.ConfigurationError(f'Duplicate grid output name: {output_name}')
fields.append(OutputField(
var=field_cfg['var'],
output_name=output_name,
agg=agg,
write_dates=write_dates,
))
self.model = model
self.fields = fields
self.format = config.format
self.nc_file_created = False
self.data = None
def update(self):
"""
Update the output fields for the current time step, i.e., update the
aggregated fields (if aggregation functions are used) and write the
variables to file at the specified dates.
"""
# If there is nothing to be written, return right away
if len(self.fields) == 0:
return
self.model.logger.debug('Updating field outputs')
date = self.model.date
roi = self.model.grid.roi
if self.format == 'netcdf':
nc_file = self.model.config.results_dir / 'output_grids.nc'
if not self.nc_file_created:
ds = self._create_dataset()
ds.to_netcdf(nc_file)
self.nc_file_created = True
ds = netCDF4.Dataset(nc_file, 'r+')
elif self.format == 'memory':
if self.data is None:
self.data = self._create_dataset()
# Loop through all fields, update aggregations where necessary and write files at the
# specified dates
for field in self.fields:
if field.agg is not None:
if field.data is None:
meta = self.model.state.meta(field.var)
if meta.dim3 == 0:
arr = np.full(self.model.grid.shape, np.nan)
arr[roi] = 0
else:
arr = np.full((meta.dim3, *self.model.grid.shape), np.nan)
arr[:, roi] = 0
field.data = arr
data_cur = self.model.state[field.var]
if field.agg == 'sum':
if field.data.ndim == 2:
field.data[roi] += data_cur[roi]
else:
field.data[:, roi] += data_cur[:, roi]
elif field.agg == 'mean':
if field.data.ndim == 2:
field.data[roi] += (data_cur[roi] - field.data[roi]) / (field.num_aggregations + 1)
else:
field.data[:, roi] += (data_cur[:, roi] - field.data[:, roi]) / (field.num_aggregations + 1)
field.num_aggregations += 1
if date in field.write_dates:
date_idx = np.flatnonzero(field.write_dates == date)[0]
if field.agg is None:
data = self.model.state[field.var]
else:
data = field.data
if self.format == 'netcdf':
ds[field.output_name][date_idx, :, :] = data
elif self.format in ('ascii', 'geotiff'):
if self.format == 'ascii':
ext = 'asc'
rio_meta = {'driver': 'AAIGrid'}
# (do not add CRS information when using AAIGrid output to avoid writing
# .prj files)
elif self.format == 'geotiff':
ext = 'tif'
rio_meta = {
'driver': 'GTiff',
'crs': self.model.grid.crs,
}
if field.agg is None:
date_str = f'{date:%Y-%m-%dT%H%M}'
else:
# Find the start date of the current output interval for the output file
# name
if date_idx == 0:
start_date = self.model.dates[0]
else:
start_date = field.write_dates[date_idx - 1] + pd.Timedelta(
seconds=self.model.timestep)
date_str = f'{start_date:%Y-%m-%dT%H%M}_{date:%Y-%m-%dT%H%M}'
if data.ndim == 2:
filename = self.model.config.results_dir / f'{field.output_name}_{date_str}.{ext}'
self.model.logger.debug(f'Writing field {field.var} to {filename}')
fileio.write_raster_file(
filename,
data,
self.model.grid.transform,
**rio_meta,
)
else:
# For 3-dimensional variables, write each layer as a separate file
for layer_num in range(data.shape[0]):
filename = (
self.model.config.results_dir
/ f'{field.output_name}_{layer_num}_{date_str}.{ext}'
)
self.model.logger.debug(f'Writing field {field.var} (layer {layer_num})'
' to {filename}')
fileio.write_raster_file(
filename,
data[layer_num, :, :],
self.model.grid.transform,
**rio_meta,
)
elif self.format == 'memory':
self.data[field.output_name].values[date_idx, :, :] = data
else:
raise NotImplementedError
field.data = None
field.num_aggregations = 0
if self.format == 'netcdf':
ds.close()
def _create_dataset(self):
"""
Create a CF-compliant Dataset covering the specified output variables
and dates.
Returns
-------
ds : xr.Dataset
"""
# Define names of time variables - if there is only one time variable simply name it "time",
# otherwise they are named "time1", "time2", ...
time_var_names = {}
num_time_vars = 0
for field in self.fields:
key = _field_key(field)
if key not in time_var_names:
num_time_vars += 1
time_var_names[key] = f'time{num_time_vars}'
if num_time_vars == 1:
key = next(iter(time_var_names))
time_var_names[key] = 'time'
times = {} # dict for storing times and boundaries (for aggregated variables) of the time variables
field_time_vars = [] # contains for each field the name of the respective NetCDF time variable
for field in self.fields:
key = _field_key(field)
time_var_name = time_var_names[key]
time_vals = field.write_dates.values
if field.agg is None:
time_vals = field.write_dates
time_bounds = None
else:
time_bounds = np.repeat(time_vals[:, np.newaxis], 2, axis=1).copy()
time_bounds[1:, 0] = time_bounds[:-1, 1]
time_bounds[0, 0] = self.model.dates[0]
field_time_vars.append(time_var_name)
if time_var_name not in times:
times[time_var_name] = (time_vals, time_bounds)
x_coords = self.model.grid.X[0, :]
y_coords = self.model.grid.Y[:, 0]
# Define coordinate variables
coords = {}
for time_var, (time_vals, time_bounds) in times.items():
time_attrs = {}
if time_bounds is not None:
bound_var_name = f'{time_var}_bounds'
time_attrs['bounds'] = bound_var_name
coords[bound_var_name] = (
[time_var, 'nbnd'],
time_bounds,
{
'long_name': 'time interval endpoints',
}
)
coords[time_var] = (
time_var,
time_vals,
time_attrs,
)
coords['x'] = (
['x'],
x_coords,
{
'standard_name': 'projection_x_coordinate',
'long_name': 'x coordinate of projection',
'units': 'm',
},
)
coords['y'] = (
['y'],
y_coords,
{
'standard_name': 'projection_y_coordinate',
'long_name': 'y coordinate of projection',
'units': 'm',
},
)
coords['crs'] = (
[],
np.array(0),
pyproj.crs.CRS(self.model.grid.crs).to_cf(),
)
# Define data variables
data = {}
three_dim_coords = {}
for field, field_time_var in zip(self.fields, field_time_vars):
meta = self.model.state.meta(field.var)
attrs = {}
for attr in ('standard_name', 'long_name', 'units'):
attr_val = getattr(meta, attr)
if attr_val is not None:
attrs[attr] = attr_val
attrs['grid_mapping'] = 'crs'
# Assign output data type - float-like variables are written as float32, integer
# variables as int32 or float32 (the latter if agg == 'mean')
if (
np.issubdtype(self.model.state.meta(field.var).dtype, np.integer)
and field.agg != 'mean'
):
dtype = np.int32
else:
dtype = np.float32
if meta.dim3 == 0: # 2-dimensional variable
data[field.output_name] = (
[field_time_var, 'y', 'x'],
np.full((len(field.write_dates), len(y_coords), len(x_coords)), np.nan, dtype=dtype),
attrs,
)
else: # 3-dimensional variable
category = self.model.state.parse(field.var)[0]
coord_name = f'{category}_layer'
if category in three_dim_coords:
if three_dim_coords[coord_name] != meta.dim3:
# We assume that all 3-dimensional variables within a category have the
# same shape (e.g. "soil.temp" must have the same shape as "soil.therm_cond");
# varying numbers of layers within a category are not supported
raise Exception('Inconsistent length of third variable dimension')
else:
three_dim_coords[coord_name] = meta.dim3
data[field.output_name] = (
[field_time_var, coord_name, 'y', 'x'],
np.full(
(len(field.write_dates), meta.dim3, len(y_coords), len(x_coords)),
np.nan,
dtype=dtype,
),
attrs,
)
# Add 3-dimensional coordinates
for coord_name, coord_len in three_dim_coords.items():
coords[coord_name] = ([coord_name], np.arange(coord_len))
ds = xr.Dataset(data, coords=coords)
ds.attrs['Conventions'] = 'CF-1.7'
for time_var in times:
ds[time_var].attrs['standard_name'] = 'time'
# Set time units manually because otherwise the units of the time and the time bounds
# variables might be different which is not recommended by CF standards
ds[time_var].encoding['units'] = f'hours since {self.model.dates[0]:%Y-%m-%d %H:%M}'
# Store time variables as doubles for CF compliance
ds[time_var].encoding['dtype'] = np.float64
if f'{time_var}_bounds' in ds:
ds[f'{time_var}_bounds'].encoding['dtype'] = np.float64
return ds
def _freq_write_dates(dates, out_freq, agg):
"""
Calculate output dates for gridded outputs when a frequency string is set.
For non-aggregated fields the write dates are assigned to the start of the
respective intervals for non-anchored and begin-anchored offsets (e.g. 'D',
'MS', 'AS'), and to the end of the intervals for end-anchored offsets (e.g.
'M', 'A'). For aggregated fields, the write dates are always assigned to the
end of the intervals.
Parameters
----------
dates : pd.DatetimeIndex
Simulation dates.
out_freq : str
Output frequency as a pandas offset string (e.g. '3H', 'M').
agg : boolean
Prepare write dates for aggregated outputs (if True) or for
instantaneous values.
Returns
-------
write_dates : pd.DatetimeIndex
Examples
--------
>>> dates = pd.date_range(
... start='2021-01-01 00:00',
... end='2021-12-31 23:00',
... freq='H',
... )
... _freq_write_dates(dates, 'A', False)
DatetimeIndex(['2021-12-31 23:00:00'], dtype='datetime64[ns]', freq=None)
>>> _freq_write_dates(dates, 'AS', False)
DatetimeIndex(['2021-01-01'], dtype='datetime64[ns]', freq='AS-JAN')
>>> _freq_write_dates(dates, 'D', False)
DatetimeIndex(['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04',
'2021-01-05', '2021-01-06', '2021-01-07', '2021-01-08',
'2021-01-09', '2021-01-10',
...
'2021-12-22', '2021-12-23', '2021-12-24', '2021-12-25',
'2021-12-26', '2021-12-27', '2021-12-28', '2021-12-29',
'2021-12-30', '2021-12-31'],
dtype='datetime64[ns]', length=365, freq='D')
>>> _freq_write_dates(dates, 'D', True)
DatetimeIndex(['2021-01-01 23:00:00', '2021-01-02 23:00:00',
'2021-01-03 23:00:00', '2021-01-04 23:00:00',
'2021-01-05 23:00:00', '2021-01-06 23:00:00',
'2021-01-07 23:00:00', '2021-01-08 23:00:00',
'2021-01-09 23:00:00', '2021-01-10 23:00:00',
...
'2021-12-22 23:00:00', '2021-12-23 23:00:00',
'2021-12-24 23:00:00', '2021-12-25 23:00:00',
'2021-12-26 23:00:00', '2021-12-27 23:00:00',
'2021-12-28 23:00:00', '2021-12-29 23:00:00',
'2021-12-30 23:00:00', '2021-12-31 23:00:00'],
dtype='datetime64[ns]', length=365, freq='D')
"""
model_freq = dates.freqstr
model_freq_td = util.offset_to_timedelta(model_freq)
try:
out_offset = pandas.tseries.frequencies.to_offset(out_freq)
if not any([isinstance(out_offset, o) for o in _ALLOWED_OFFSETS]):
raise ValueError
except ValueError:
allowed_offsets_str = ", ".join([o().__class__.__name__ for o in _ALLOWED_OFFSETS])
raise errors.ConfigurationError(f'Unsupported output frequency: {out_freq}. '
f'Supported offsets: {allowed_offsets_str}')
if not out_offset.is_anchored():
# For non-anchored offsets (e.g., '3H', 'D'), the output frequency must be a multiple of
# (and not smaller than) the model timestep
out_freq_td = util.offset_to_timedelta(out_freq)
if out_freq_td < model_freq_td:
raise ValueError('Output frequency must not be smaller than the model timestep')
elif not (out_freq_td.total_seconds() / model_freq_td.total_seconds()).is_integer():
raise ValueError('Output frequency must be a multiple of the model timestep')
if agg:
if out_offset.is_anchored(): # e.g. 'M', 'A'
if model_freq_td.total_seconds() > constants.HOURS_PER_DAY * constants.SECONDS_PER_HOUR:
raise NotImplementedError('Aggregation of gridded outputs with anchored offsets '
'not supported for timesteps > 1d')
period_end_dates = (
pd.period_range(
start=dates[0],
end=dates[-1],
freq=out_freq,
)
.asfreq(model_freq, how='end')
.to_timestamp()
)
d0 = dates[dates <= period_end_dates[0]][-1]
write_dates = period_end_dates + (d0 - period_end_dates[0])
if period_end_dates[0] - write_dates[0] > pd.Timedelta('1d'):
write_dates = write_dates.delete(0)
# Keep the last output interval only if it is fully covered (e.g., do not write half
# months)
if len(write_dates) > 0 and write_dates[-1] > dates[-1]:
write_dates = write_dates.delete(-1)
else:
write_dates = pd.date_range(
start=dates[0] + out_freq_td - model_freq_td,
end=dates[-1],
freq=out_freq,
)
else:
write_dates = pd.date_range(
start=dates[0],
end=dates[-1],
freq=out_freq,
)
if any([isinstance(out_offset, o) for o in (
pd.tseries.offsets.YearEnd,
pd.tseries.offsets.MonthEnd,
)]) and model_freq_td < pd.Timedelta(days=1):
write_dates += pd.Timedelta(days=1) - model_freq_td
return write_dates
| [
"openamundsen.errors.ConfigurationError",
"pyproj.crs.CRS",
"numpy.repeat",
"numpy.arange",
"pandas.Timedelta",
"netCDF4.Dataset",
"pandas.to_datetime",
"numpy.flatnonzero",
"xarray.Dataset",
"numpy.array",
"openamundsen.util.offset_to_timedelta",
"pandas.period_range",
"openamundsen.fileio.... | [((17670, 17706), 'openamundsen.util.offset_to_timedelta', 'util.offset_to_timedelta', (['model_freq'], {}), '(model_freq)\n', (17694, 17706), False, 'from openamundsen import constants, errors, fileio, util\n'), ((14361, 14392), 'xarray.Dataset', 'xr.Dataset', (['data'], {'coords': 'coords'}), '(data, coords=coords)\n', (14371, 14392), True, 'import xarray as xr\n'), ((18384, 18418), 'openamundsen.util.offset_to_timedelta', 'util.offset_to_timedelta', (['out_freq'], {}), '(out_freq)\n', (18408, 18418), False, 'from openamundsen import constants, errors, fileio, util\n'), ((20088, 20147), 'pandas.date_range', 'pd.date_range', ([], {'start': 'dates[0]', 'end': 'dates[-1]', 'freq': 'out_freq'}), '(start=dates[0], end=dates[-1], freq=out_freq)\n', (20101, 20147), True, 'import pandas as pd\n'), ((4173, 4203), 'netCDF4.Dataset', 'netCDF4.Dataset', (['nc_file', '"""r+"""'], {}), "(nc_file, 'r+')\n", (4188, 4203), False, 'import netCDF4\n'), ((11820, 11831), 'numpy.array', 'np.array', (['(0)'], {}), '(0)\n', (11828, 11831), True, 'import numpy as np\n'), ((18018, 18140), 'openamundsen.errors.ConfigurationError', 'errors.ConfigurationError', (['f"""Unsupported output frequency: {out_freq}. Supported offsets: {allowed_offsets_str}"""'], {}), "(\n f'Unsupported output frequency: {out_freq}. Supported offsets: {allowed_offsets_str}'\n )\n", (18043, 18140), False, 'from openamundsen import constants, errors, fileio, util\n'), ((19903, 19996), 'pandas.date_range', 'pd.date_range', ([], {'start': '(dates[0] + out_freq_td - model_freq_td)', 'end': 'dates[-1]', 'freq': 'out_freq'}), '(start=dates[0] + out_freq_td - model_freq_td, end=dates[-1],\n freq=out_freq)\n', (19916, 19996), True, 'import pandas as pd\n'), ((2273, 2307), 'pandas.to_datetime', 'pd.to_datetime', (["field_cfg['dates']"], {}), "(field_cfg['dates'])\n", (2287, 2307), True, 'import pandas as pd\n'), ((2960, 3031), 'openamundsen.errors.ConfigurationError', 'errors.ConfigurationError', (['f"""Duplicate grid output name: {output_name}"""'], {}), "(f'Duplicate grid output name: {output_name}')\n", (2985, 3031), False, 'from openamundsen import constants, errors, fileio, util\n'), ((14325, 14345), 'numpy.arange', 'np.arange', (['coord_len'], {}), '(coord_len)\n', (14334, 14345), True, 'import numpy as np\n'), ((19549, 19567), 'pandas.Timedelta', 'pd.Timedelta', (['"""1d"""'], {}), "('1d')\n", (19561, 19567), True, 'import pandas as pd\n'), ((20370, 20390), 'pandas.Timedelta', 'pd.Timedelta', ([], {'days': '(1)'}), '(days=1)\n', (20382, 20390), True, 'import pandas as pd\n'), ((20419, 20439), 'pandas.Timedelta', 'pd.Timedelta', ([], {'days': '(1)'}), '(days=1)\n', (20431, 20439), True, 'import pandas as pd\n'), ((5692, 5733), 'numpy.flatnonzero', 'np.flatnonzero', (['(field.write_dates == date)'], {}), '(field.write_dates == date)\n', (5706, 5733), True, 'import numpy as np\n'), ((11845, 11880), 'pyproj.crs.CRS', 'pyproj.crs.CRS', (['self.model.grid.crs'], {}), '(self.model.grid.crs)\n', (11859, 11880), False, 'import pyproj\n'), ((4689, 4727), 'numpy.full', 'np.full', (['self.model.grid.shape', 'np.nan'], {}), '(self.model.grid.shape, np.nan)\n', (4696, 4727), True, 'import numpy as np\n'), ((4821, 4873), 'numpy.full', 'np.full', (['(meta.dim3, *self.model.grid.shape)', 'np.nan'], {}), '((meta.dim3, *self.model.grid.shape), np.nan)\n', (4828, 4873), True, 'import numpy as np\n'), ((10174, 10220), 'numpy.repeat', 'np.repeat', (['time_vals[:, np.newaxis]', '(2)'], {'axis': '(1)'}), '(time_vals[:, np.newaxis], 2, axis=1)\n', (10183, 10220), True, 'import numpy as np\n'), ((7476, 7555), 'openamundsen.fileio.write_raster_file', 'fileio.write_raster_file', (['filename', 'data', 'self.model.grid.transform'], {}), '(filename, data, self.model.grid.transform, **rio_meta)\n', (7500, 7555), False, 'from openamundsen import constants, errors, fileio, util\n'), ((19130, 19191), 'pandas.period_range', 'pd.period_range', ([], {'start': 'dates[0]', 'end': 'dates[-1]', 'freq': 'out_freq'}), '(start=dates[0], end=dates[-1], freq=out_freq)\n', (19145, 19191), True, 'import pandas as pd\n'), ((8293, 8394), 'openamundsen.fileio.write_raster_file', 'fileio.write_raster_file', (['filename', 'data[layer_num, :, :]', 'self.model.grid.transform'], {}), '(filename, data[layer_num, :, :], self.model.grid.\n transform, **rio_meta)\n', (8317, 8394), False, 'from openamundsen import constants, errors, fileio, util\n'), ((7051, 7092), 'pandas.Timedelta', 'pd.Timedelta', ([], {'seconds': 'self.model.timestep'}), '(seconds=self.model.timestep)\n', (7063, 7092), True, 'import pandas as pd\n')] |
# Autogenerated by onnx-model-maker. Don't modify it manually.
import onnx
import onnx.helper
import onnx.numpy_helper
from onnx_model_maker import omm
from onnx_model_maker import onnx_mm_export
from onnx_model_maker.ops.op_helper import _add_input
@onnx_mm_export("v2.LabelEncoder")
def LabelEncoder(X, **kwargs):
_inputs = []
for i in (X, ):
_add_input(i, _inputs)
idx = omm.op_counter["LabelEncoder"]
omm.op_counter["LabelEncoder"] += 1
node = onnx.helper.make_node("LabelEncoder",
_inputs, [f'_t_LabelEncoder_{idx}_Y'],
name=f"LabelEncoder_{idx}",
**kwargs)
onnx.checker.check_node(node, omm.ctx)
omm.model.graph.node.append(node)
return node
@onnx_mm_export("v2.Split")
def Split(input, **kwargs):
_inputs = []
for i in (input, ):
_add_input(i, _inputs)
idx = omm.op_counter["Split"]
omm.op_counter["Split"] += 1
node = onnx.helper.make_node("Split",
_inputs, [f"_t_Split_{idx}_{i}" for i in range(len(kwargs["split"]))],
name=f"Split_{idx}",
**kwargs)
onnx.checker.check_node(node, omm.ctx)
omm.model.graph.node.append(node)
return node
@onnx_mm_export("v2.Pad")
def Pad(data, **kwargs):
_inputs = []
for i in (data, ):
_add_input(i, _inputs)
idx = omm.op_counter["Pad"]
omm.op_counter["Pad"] += 1
node = onnx.helper.make_node("Pad",
_inputs, [f'_t_Pad_{idx}_output'],
name=f"Pad_{idx}",
**kwargs)
onnx.checker.check_node(node, omm.ctx)
omm.model.graph.node.append(node)
return node
@onnx_mm_export("v2.LpPool")
def LpPool(X, **kwargs):
_inputs = []
for i in (X, ):
_add_input(i, _inputs)
idx = omm.op_counter["LpPool"]
omm.op_counter["LpPool"] += 1
node = onnx.helper.make_node("LpPool",
_inputs, [f'_t_LpPool_{idx}_Y'],
name=f"LpPool_{idx}",
**kwargs)
onnx.checker.check_node(node, omm.ctx)
omm.model.graph.node.append(node)
return node
@onnx_mm_export("v2.GlobalLpPool")
def GlobalLpPool(X, **kwargs):
_inputs = []
for i in (X, ):
_add_input(i, _inputs)
idx = omm.op_counter["GlobalLpPool"]
omm.op_counter["GlobalLpPool"] += 1
node = onnx.helper.make_node("GlobalLpPool",
_inputs, [f'_t_GlobalLpPool_{idx}_Y'],
name=f"GlobalLpPool_{idx}",
**kwargs)
onnx.checker.check_node(node, omm.ctx)
omm.model.graph.node.append(node)
return node
| [
"onnx_model_maker.ops.op_helper._add_input",
"onnx.helper.make_node",
"onnx_model_maker.omm.model.graph.node.append",
"onnx.checker.check_node",
"onnx_model_maker.onnx_mm_export"
] | [((254, 287), 'onnx_model_maker.onnx_mm_export', 'onnx_mm_export', (['"""v2.LabelEncoder"""'], {}), "('v2.LabelEncoder')\n", (268, 287), False, 'from onnx_model_maker import onnx_mm_export\n'), ((768, 794), 'onnx_model_maker.onnx_mm_export', 'onnx_mm_export', (['"""v2.Split"""'], {}), "('v2.Split')\n", (782, 794), False, 'from onnx_model_maker import onnx_mm_export\n'), ((1280, 1304), 'onnx_model_maker.onnx_mm_export', 'onnx_mm_export', (['"""v2.Pad"""'], {}), "('v2.Pad')\n", (1294, 1304), False, 'from onnx_model_maker import onnx_mm_export\n'), ((1742, 1769), 'onnx_model_maker.onnx_mm_export', 'onnx_mm_export', (['"""v2.LpPool"""'], {}), "('v2.LpPool')\n", (1756, 1769), False, 'from onnx_model_maker import onnx_mm_export\n'), ((2214, 2247), 'onnx_model_maker.onnx_mm_export', 'onnx_mm_export', (['"""v2.GlobalLpPool"""'], {}), "('v2.GlobalLpPool')\n", (2228, 2247), False, 'from onnx_model_maker import onnx_mm_export\n'), ((466, 584), 'onnx.helper.make_node', 'onnx.helper.make_node', (['"""LabelEncoder"""', '_inputs', "[f'_t_LabelEncoder_{idx}_Y']"], {'name': 'f"""LabelEncoder_{idx}"""'}), "('LabelEncoder', _inputs, [f'_t_LabelEncoder_{idx}_Y'],\n name=f'LabelEncoder_{idx}', **kwargs)\n", (487, 584), False, 'import onnx\n'), ((676, 714), 'onnx.checker.check_node', 'onnx.checker.check_node', (['node', 'omm.ctx'], {}), '(node, omm.ctx)\n', (699, 714), False, 'import onnx\n'), ((717, 750), 'onnx_model_maker.omm.model.graph.node.append', 'omm.model.graph.node.append', (['node'], {}), '(node)\n', (744, 750), False, 'from onnx_model_maker import omm\n'), ((1188, 1226), 'onnx.checker.check_node', 'onnx.checker.check_node', (['node', 'omm.ctx'], {}), '(node, omm.ctx)\n', (1211, 1226), False, 'import onnx\n'), ((1229, 1262), 'onnx_model_maker.omm.model.graph.node.append', 'omm.model.graph.node.append', (['node'], {}), '(node)\n', (1256, 1262), False, 'from onnx_model_maker import omm\n'), ((1462, 1559), 'onnx.helper.make_node', 'onnx.helper.make_node', (['"""Pad"""', '_inputs', "[f'_t_Pad_{idx}_output']"], {'name': 'f"""Pad_{idx}"""'}), "('Pad', _inputs, [f'_t_Pad_{idx}_output'], name=\n f'Pad_{idx}', **kwargs)\n", (1483, 1559), False, 'import onnx\n'), ((1650, 1688), 'onnx.checker.check_node', 'onnx.checker.check_node', (['node', 'omm.ctx'], {}), '(node, omm.ctx)\n', (1673, 1688), False, 'import onnx\n'), ((1691, 1724), 'onnx_model_maker.omm.model.graph.node.append', 'omm.model.graph.node.append', (['node'], {}), '(node)\n', (1718, 1724), False, 'from onnx_model_maker import omm\n'), ((1930, 2031), 'onnx.helper.make_node', 'onnx.helper.make_node', (['"""LpPool"""', '_inputs', "[f'_t_LpPool_{idx}_Y']"], {'name': 'f"""LpPool_{idx}"""'}), "('LpPool', _inputs, [f'_t_LpPool_{idx}_Y'], name=\n f'LpPool_{idx}', **kwargs)\n", (1951, 2031), False, 'import onnx\n'), ((2122, 2160), 'onnx.checker.check_node', 'onnx.checker.check_node', (['node', 'omm.ctx'], {}), '(node, omm.ctx)\n', (2145, 2160), False, 'import onnx\n'), ((2163, 2196), 'onnx_model_maker.omm.model.graph.node.append', 'omm.model.graph.node.append', (['node'], {}), '(node)\n', (2190, 2196), False, 'from onnx_model_maker import omm\n'), ((2426, 2544), 'onnx.helper.make_node', 'onnx.helper.make_node', (['"""GlobalLpPool"""', '_inputs', "[f'_t_GlobalLpPool_{idx}_Y']"], {'name': 'f"""GlobalLpPool_{idx}"""'}), "('GlobalLpPool', _inputs, [f'_t_GlobalLpPool_{idx}_Y'],\n name=f'GlobalLpPool_{idx}', **kwargs)\n", (2447, 2544), False, 'import onnx\n'), ((2636, 2674), 'onnx.checker.check_node', 'onnx.checker.check_node', (['node', 'omm.ctx'], {}), '(node, omm.ctx)\n', (2659, 2674), False, 'import onnx\n'), ((2677, 2710), 'onnx_model_maker.omm.model.graph.node.append', 'omm.model.graph.node.append', (['node'], {}), '(node)\n', (2704, 2710), False, 'from onnx_model_maker import omm\n'), ((356, 378), 'onnx_model_maker.ops.op_helper._add_input', '_add_input', (['i', '_inputs'], {}), '(i, _inputs)\n', (366, 378), False, 'from onnx_model_maker.ops.op_helper import _add_input\n'), ((864, 886), 'onnx_model_maker.ops.op_helper._add_input', '_add_input', (['i', '_inputs'], {}), '(i, _inputs)\n', (874, 886), False, 'from onnx_model_maker.ops.op_helper import _add_input\n'), ((1370, 1392), 'onnx_model_maker.ops.op_helper._add_input', '_add_input', (['i', '_inputs'], {}), '(i, _inputs)\n', (1380, 1392), False, 'from onnx_model_maker.ops.op_helper import _add_input\n'), ((1832, 1854), 'onnx_model_maker.ops.op_helper._add_input', '_add_input', (['i', '_inputs'], {}), '(i, _inputs)\n', (1842, 1854), False, 'from onnx_model_maker.ops.op_helper import _add_input\n'), ((2316, 2338), 'onnx_model_maker.ops.op_helper._add_input', '_add_input', (['i', '_inputs'], {}), '(i, _inputs)\n', (2326, 2338), False, 'from onnx_model_maker.ops.op_helper import _add_input\n')] |
import shutil
import os
import filecmp
from src.masonite.commands.presets.Remove import Remove
import unittest
class TestRemove(unittest.TestCase):
def test_update_package_array(self):
expected_packages = {}
# Verify it works with no existing packages
self.assertDictEqual(expected_packages, Remove().update_package_array())
removed_packages = {
'bootstrap': '1.2.3',
'jquery': '1.2.3',
'popper.js': '1.2.3',
'vue': '1.2.3',
'vue-template-compiler': '1.2.3',
'@babel/preset-react': '1.2.3',
'react': '1.2.3',
'react-dom': '1.2.3'
}
# Verify it works to remove Vue, React, and Bootstrap
self.assertDictEqual(expected_packages, Remove().update_package_array(packages=removed_packages))
extra_packages = {
'bootstrap': '1.2.3',
'jquery': '1.2.3',
'popper.js': '1.2.3',
'vue': '1.2.3',
'vue-template-compiler': '1.2.3',
'@babel/preset-react': '1.2.3',
'react': '1.2.3',
'react-dom': '1.2.3',
'dummy': '4.5.6'
}
expected_packages['dummy'] = '4.5.6'
# Verify it works to remove Vue, React, and Bootstrap but leaves extra packages intact
self.assertDictEqual(expected_packages, Remove().update_package_array(packages=extra_packages))
def test_update_webpack_configuration(self):
Remove().update_webpack_configuration()
self.assertTrue(filecmp.cmp('src/masonite/commands/presets/remove-stubs/webpack.mix.js', 'webpack.mix.js'))
os.remove('webpack.mix.js')
def test_update_bootstrapping(self):
Remove().update_bootstrapping()
self.assertTrue(os.path.exists('resources/sass/app.scss'))
self.assertTrue(filecmp.cmp('src/masonite/commands/presets/remove-stubs/app.js', 'resources/js/app.js'))
self.assertTrue(filecmp.cmp('src/masonite/commands/presets/remove-stubs/bootstrap.js', 'resources/js/bootstrap.js'))
shutil.rmtree('resources/js')
shutil.rmtree('resources/sass')
def test_install(self):
shutil.copyfile('package.json', 'package.json.save')
Remove().install()
self.assertTrue(filecmp.cmp('src/masonite/commands/presets/remove-stubs/webpack.mix.js', 'webpack.mix.js'))
self.assertTrue(os.path.exists('resources/sass/app.scss'))
self.assertTrue(filecmp.cmp('src/masonite/commands/presets/remove-stubs/app.js', 'resources/js/app.js'))
self.assertTrue(filecmp.cmp('src/masonite/commands/presets/remove-stubs/bootstrap.js', 'resources/js/bootstrap.js'))
self.assertFalse(os.path.exists('resources/sass/_variables.scss'))
self.assertFalse(os.path.exists('resources/js/components'))
self.assertFalse(os.path.exists('public/css'))
self.assertFalse(os.path.exists('public/js'))
shutil.rmtree('resources/js')
shutil.rmtree('resources/sass')
os.remove('webpack.mix.js')
shutil.copyfile('package.json.save', 'package.json')
os.remove('package.json.save')
| [
"os.path.exists",
"shutil.copyfile",
"shutil.rmtree",
"filecmp.cmp",
"src.masonite.commands.presets.Remove.Remove",
"os.remove"
] | [((1658, 1685), 'os.remove', 'os.remove', (['"""webpack.mix.js"""'], {}), "('webpack.mix.js')\n", (1667, 1685), False, 'import os\n'), ((2081, 2110), 'shutil.rmtree', 'shutil.rmtree', (['"""resources/js"""'], {}), "('resources/js')\n", (2094, 2110), False, 'import shutil\n'), ((2119, 2150), 'shutil.rmtree', 'shutil.rmtree', (['"""resources/sass"""'], {}), "('resources/sass')\n", (2132, 2150), False, 'import shutil\n'), ((2188, 2240), 'shutil.copyfile', 'shutil.copyfile', (['"""package.json"""', '"""package.json.save"""'], {}), "('package.json', 'package.json.save')\n", (2203, 2240), False, 'import shutil\n'), ((2949, 2978), 'shutil.rmtree', 'shutil.rmtree', (['"""resources/js"""'], {}), "('resources/js')\n", (2962, 2978), False, 'import shutil\n'), ((2987, 3018), 'shutil.rmtree', 'shutil.rmtree', (['"""resources/sass"""'], {}), "('resources/sass')\n", (3000, 3018), False, 'import shutil\n'), ((3027, 3054), 'os.remove', 'os.remove', (['"""webpack.mix.js"""'], {}), "('webpack.mix.js')\n", (3036, 3054), False, 'import os\n'), ((3063, 3115), 'shutil.copyfile', 'shutil.copyfile', (['"""package.json.save"""', '"""package.json"""'], {}), "('package.json.save', 'package.json')\n", (3078, 3115), False, 'import shutil\n'), ((3124, 3154), 'os.remove', 'os.remove', (['"""package.json.save"""'], {}), "('package.json.save')\n", (3133, 3154), False, 'import os\n'), ((1558, 1652), 'filecmp.cmp', 'filecmp.cmp', (['"""src/masonite/commands/presets/remove-stubs/webpack.mix.js"""', '"""webpack.mix.js"""'], {}), "('src/masonite/commands/presets/remove-stubs/webpack.mix.js',\n 'webpack.mix.js')\n", (1569, 1652), False, 'import filecmp\n'), ((1792, 1833), 'os.path.exists', 'os.path.exists', (['"""resources/sass/app.scss"""'], {}), "('resources/sass/app.scss')\n", (1806, 1833), False, 'import os\n'), ((1859, 1950), 'filecmp.cmp', 'filecmp.cmp', (['"""src/masonite/commands/presets/remove-stubs/app.js"""', '"""resources/js/app.js"""'], {}), "('src/masonite/commands/presets/remove-stubs/app.js',\n 'resources/js/app.js')\n", (1870, 1950), False, 'import filecmp\n'), ((1972, 2075), 'filecmp.cmp', 'filecmp.cmp', (['"""src/masonite/commands/presets/remove-stubs/bootstrap.js"""', '"""resources/js/bootstrap.js"""'], {}), "('src/masonite/commands/presets/remove-stubs/bootstrap.js',\n 'resources/js/bootstrap.js')\n", (1983, 2075), False, 'import filecmp\n'), ((2292, 2386), 'filecmp.cmp', 'filecmp.cmp', (['"""src/masonite/commands/presets/remove-stubs/webpack.mix.js"""', '"""webpack.mix.js"""'], {}), "('src/masonite/commands/presets/remove-stubs/webpack.mix.js',\n 'webpack.mix.js')\n", (2303, 2386), False, 'import filecmp\n'), ((2408, 2449), 'os.path.exists', 'os.path.exists', (['"""resources/sass/app.scss"""'], {}), "('resources/sass/app.scss')\n", (2422, 2449), False, 'import os\n'), ((2475, 2566), 'filecmp.cmp', 'filecmp.cmp', (['"""src/masonite/commands/presets/remove-stubs/app.js"""', '"""resources/js/app.js"""'], {}), "('src/masonite/commands/presets/remove-stubs/app.js',\n 'resources/js/app.js')\n", (2486, 2566), False, 'import filecmp\n'), ((2588, 2691), 'filecmp.cmp', 'filecmp.cmp', (['"""src/masonite/commands/presets/remove-stubs/bootstrap.js"""', '"""resources/js/bootstrap.js"""'], {}), "('src/masonite/commands/presets/remove-stubs/bootstrap.js',\n 'resources/js/bootstrap.js')\n", (2599, 2691), False, 'import filecmp\n'), ((2714, 2762), 'os.path.exists', 'os.path.exists', (['"""resources/sass/_variables.scss"""'], {}), "('resources/sass/_variables.scss')\n", (2728, 2762), False, 'import os\n'), ((2789, 2830), 'os.path.exists', 'os.path.exists', (['"""resources/js/components"""'], {}), "('resources/js/components')\n", (2803, 2830), False, 'import os\n'), ((2857, 2885), 'os.path.exists', 'os.path.exists', (['"""public/css"""'], {}), "('public/css')\n", (2871, 2885), False, 'import os\n'), ((2912, 2939), 'os.path.exists', 'os.path.exists', (['"""public/js"""'], {}), "('public/js')\n", (2926, 2939), False, 'import os\n'), ((1494, 1502), 'src.masonite.commands.presets.Remove.Remove', 'Remove', ([], {}), '()\n', (1500, 1502), False, 'from src.masonite.commands.presets.Remove import Remove\n'), ((1736, 1744), 'src.masonite.commands.presets.Remove.Remove', 'Remove', ([], {}), '()\n', (1742, 1744), False, 'from src.masonite.commands.presets.Remove import Remove\n'), ((2249, 2257), 'src.masonite.commands.presets.Remove.Remove', 'Remove', ([], {}), '()\n', (2255, 2257), False, 'from src.masonite.commands.presets.Remove import Remove\n'), ((325, 333), 'src.masonite.commands.presets.Remove.Remove', 'Remove', ([], {}), '()\n', (331, 333), False, 'from src.masonite.commands.presets.Remove import Remove\n'), ((787, 795), 'src.masonite.commands.presets.Remove.Remove', 'Remove', ([], {}), '()\n', (793, 795), False, 'from src.masonite.commands.presets.Remove import Remove\n'), ((1380, 1388), 'src.masonite.commands.presets.Remove.Remove', 'Remove', ([], {}), '()\n', (1386, 1388), False, 'from src.masonite.commands.presets.Remove import Remove\n')] |
from django.contrib.auth import forms
from django.contrib.auth import models
from django.contrib.auth.models import User
from django import forms
from django.forms import fields, widgets
from .models import Comment, Post, Profile
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit,Layout,Field
class PostForm(forms.ModelForm):
helper = FormHelper()
helper.form_method = 'POST'
helper.add_input(Submit('post', 'post',css_class = 'btn btn-success'))
class Meta:
model = Post
fields = [
'image',
'caption'
]
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['comment_body',]
widgets = {
'comment_body':forms.Textarea(attrs={'class': 'form-control'}),
}
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['image']
class UserUpdateForm(forms.ModelForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email']
| [
"django.forms.Textarea",
"django.forms.EmailField",
"crispy_forms.layout.Submit",
"crispy_forms.helper.FormHelper"
] | [((373, 385), 'crispy_forms.helper.FormHelper', 'FormHelper', ([], {}), '()\n', (383, 385), False, 'from crispy_forms.helper import FormHelper\n'), ((986, 1004), 'django.forms.EmailField', 'forms.EmailField', ([], {}), '()\n', (1002, 1004), False, 'from django import forms\n'), ((439, 490), 'crispy_forms.layout.Submit', 'Submit', (['"""post"""', '"""post"""'], {'css_class': '"""btn btn-success"""'}), "('post', 'post', css_class='btn btn-success')\n", (445, 490), False, 'from crispy_forms.layout import Submit, Layout, Field\n'), ((764, 811), 'django.forms.Textarea', 'forms.Textarea', ([], {'attrs': "{'class': 'form-control'}"}), "(attrs={'class': 'form-control'})\n", (778, 811), False, 'from django import forms\n')] |
# coding: utf-8
# Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
from __future__ import absolute_import
import lazy_import as _lazy_import
Bucket = _lazy_import.lazy_class("oci.object_storage.models.bucket.Bucket")
BucketSummary = _lazy_import.lazy_class("oci.object_storage.models.bucket_summary.BucketSummary")
CommitMultipartUploadDetails = _lazy_import.lazy_class("oci.object_storage.models.commit_multipart_upload_details.CommitMultipartUploadDetails")
CommitMultipartUploadPartDetails = _lazy_import.lazy_class("oci.object_storage.models.commit_multipart_upload_part_details.CommitMultipartUploadPartDetails")
CopyObjectDetails = _lazy_import.lazy_class("oci.object_storage.models.copy_object_details.CopyObjectDetails")
CreateBucketDetails = _lazy_import.lazy_class("oci.object_storage.models.create_bucket_details.CreateBucketDetails")
CreateMultipartUploadDetails = _lazy_import.lazy_class("oci.object_storage.models.create_multipart_upload_details.CreateMultipartUploadDetails")
CreatePreauthenticatedRequestDetails = _lazy_import.lazy_class("oci.object_storage.models.create_preauthenticated_request_details.CreatePreauthenticatedRequestDetails")
ListObjects = _lazy_import.lazy_class("oci.object_storage.models.list_objects.ListObjects")
MultipartUpload = _lazy_import.lazy_class("oci.object_storage.models.multipart_upload.MultipartUpload")
MultipartUploadPartSummary = _lazy_import.lazy_class("oci.object_storage.models.multipart_upload_part_summary.MultipartUploadPartSummary")
NamespaceMetadata = _lazy_import.lazy_class("oci.object_storage.models.namespace_metadata.NamespaceMetadata")
ObjectLifecyclePolicy = _lazy_import.lazy_class("oci.object_storage.models.object_lifecycle_policy.ObjectLifecyclePolicy")
ObjectLifecycleRule = _lazy_import.lazy_class("oci.object_storage.models.object_lifecycle_rule.ObjectLifecycleRule")
ObjectNameFilter = _lazy_import.lazy_class("oci.object_storage.models.object_name_filter.ObjectNameFilter")
ObjectSummary = _lazy_import.lazy_class("oci.object_storage.models.object_summary.ObjectSummary")
PreauthenticatedRequest = _lazy_import.lazy_class("oci.object_storage.models.preauthenticated_request.PreauthenticatedRequest")
PreauthenticatedRequestSummary = _lazy_import.lazy_class("oci.object_storage.models.preauthenticated_request_summary.PreauthenticatedRequestSummary")
PutObjectLifecyclePolicyDetails = _lazy_import.lazy_class("oci.object_storage.models.put_object_lifecycle_policy_details.PutObjectLifecyclePolicyDetails")
RenameObjectDetails = _lazy_import.lazy_class("oci.object_storage.models.rename_object_details.RenameObjectDetails")
RestoreObjectsDetails = _lazy_import.lazy_class("oci.object_storage.models.restore_objects_details.RestoreObjectsDetails")
UpdateBucketDetails = _lazy_import.lazy_class("oci.object_storage.models.update_bucket_details.UpdateBucketDetails")
UpdateNamespaceMetadataDetails = _lazy_import.lazy_class("oci.object_storage.models.update_namespace_metadata_details.UpdateNamespaceMetadataDetails")
WorkRequest = _lazy_import.lazy_class("oci.object_storage.models.work_request.WorkRequest")
WorkRequestError = _lazy_import.lazy_class("oci.object_storage.models.work_request_error.WorkRequestError")
WorkRequestLogEntry = _lazy_import.lazy_class("oci.object_storage.models.work_request_log_entry.WorkRequestLogEntry")
WorkRequestResource = _lazy_import.lazy_class("oci.object_storage.models.work_request_resource.WorkRequestResource")
WorkRequestSummary = _lazy_import.lazy_class("oci.object_storage.models.work_request_summary.WorkRequestSummary")
# Maps type names to classes for object_storage services.
object_storage_type_mapping = {
"Bucket": Bucket,
"BucketSummary": BucketSummary,
"CommitMultipartUploadDetails": CommitMultipartUploadDetails,
"CommitMultipartUploadPartDetails": CommitMultipartUploadPartDetails,
"CopyObjectDetails": CopyObjectDetails,
"CreateBucketDetails": CreateBucketDetails,
"CreateMultipartUploadDetails": CreateMultipartUploadDetails,
"CreatePreauthenticatedRequestDetails": CreatePreauthenticatedRequestDetails,
"ListObjects": ListObjects,
"MultipartUpload": MultipartUpload,
"MultipartUploadPartSummary": MultipartUploadPartSummary,
"NamespaceMetadata": NamespaceMetadata,
"ObjectLifecyclePolicy": ObjectLifecyclePolicy,
"ObjectLifecycleRule": ObjectLifecycleRule,
"ObjectNameFilter": ObjectNameFilter,
"ObjectSummary": ObjectSummary,
"PreauthenticatedRequest": PreauthenticatedRequest,
"PreauthenticatedRequestSummary": PreauthenticatedRequestSummary,
"PutObjectLifecyclePolicyDetails": PutObjectLifecyclePolicyDetails,
"RenameObjectDetails": RenameObjectDetails,
"RestoreObjectsDetails": RestoreObjectsDetails,
"UpdateBucketDetails": UpdateBucketDetails,
"UpdateNamespaceMetadataDetails": UpdateNamespaceMetadataDetails,
"WorkRequest": WorkRequest,
"WorkRequestError": WorkRequestError,
"WorkRequestLogEntry": WorkRequestLogEntry,
"WorkRequestResource": WorkRequestResource,
"WorkRequestSummary": WorkRequestSummary
}
| [
"lazy_import.lazy_class"
] | [((181, 247), 'lazy_import.lazy_class', '_lazy_import.lazy_class', (['"""oci.object_storage.models.bucket.Bucket"""'], {}), "('oci.object_storage.models.bucket.Bucket')\n", (204, 247), True, 'import lazy_import as _lazy_import\n'), ((264, 350), 'lazy_import.lazy_class', '_lazy_import.lazy_class', (['"""oci.object_storage.models.bucket_summary.BucketSummary"""'], {}), "(\n 'oci.object_storage.models.bucket_summary.BucketSummary')\n", (287, 350), True, 'import lazy_import as _lazy_import\n'), ((377, 500), 'lazy_import.lazy_class', '_lazy_import.lazy_class', (['"""oci.object_storage.models.commit_multipart_upload_details.CommitMultipartUploadDetails"""'], {}), "(\n 'oci.object_storage.models.commit_multipart_upload_details.CommitMultipartUploadDetails'\n )\n", (400, 500), True, 'import lazy_import as _lazy_import\n'), ((526, 658), 'lazy_import.lazy_class', '_lazy_import.lazy_class', (['"""oci.object_storage.models.commit_multipart_upload_part_details.CommitMultipartUploadPartDetails"""'], {}), "(\n 'oci.object_storage.models.commit_multipart_upload_part_details.CommitMultipartUploadPartDetails'\n )\n", (549, 658), True, 'import lazy_import as _lazy_import\n'), ((669, 764), 'lazy_import.lazy_class', '_lazy_import.lazy_class', (['"""oci.object_storage.models.copy_object_details.CopyObjectDetails"""'], {}), "(\n 'oci.object_storage.models.copy_object_details.CopyObjectDetails')\n", (692, 764), True, 'import lazy_import as _lazy_import\n'), ((782, 881), 'lazy_import.lazy_class', '_lazy_import.lazy_class', (['"""oci.object_storage.models.create_bucket_details.CreateBucketDetails"""'], {}), "(\n 'oci.object_storage.models.create_bucket_details.CreateBucketDetails')\n", (805, 881), True, 'import lazy_import as _lazy_import\n'), ((908, 1031), 'lazy_import.lazy_class', '_lazy_import.lazy_class', (['"""oci.object_storage.models.create_multipart_upload_details.CreateMultipartUploadDetails"""'], {}), "(\n 'oci.object_storage.models.create_multipart_upload_details.CreateMultipartUploadDetails'\n )\n", (931, 1031), True, 'import lazy_import as _lazy_import\n'), ((1061, 1200), 'lazy_import.lazy_class', '_lazy_import.lazy_class', (['"""oci.object_storage.models.create_preauthenticated_request_details.CreatePreauthenticatedRequestDetails"""'], {}), "(\n 'oci.object_storage.models.create_preauthenticated_request_details.CreatePreauthenticatedRequestDetails'\n )\n", (1084, 1200), True, 'import lazy_import as _lazy_import\n'), ((1205, 1282), 'lazy_import.lazy_class', '_lazy_import.lazy_class', (['"""oci.object_storage.models.list_objects.ListObjects"""'], {}), "('oci.object_storage.models.list_objects.ListObjects')\n", (1228, 1282), True, 'import lazy_import as _lazy_import\n'), ((1301, 1391), 'lazy_import.lazy_class', '_lazy_import.lazy_class', (['"""oci.object_storage.models.multipart_upload.MultipartUpload"""'], {}), "(\n 'oci.object_storage.models.multipart_upload.MultipartUpload')\n", (1324, 1391), True, 'import lazy_import as _lazy_import\n'), ((1416, 1535), 'lazy_import.lazy_class', '_lazy_import.lazy_class', (['"""oci.object_storage.models.multipart_upload_part_summary.MultipartUploadPartSummary"""'], {}), "(\n 'oci.object_storage.models.multipart_upload_part_summary.MultipartUploadPartSummary'\n )\n", (1439, 1535), True, 'import lazy_import as _lazy_import\n'), ((1546, 1640), 'lazy_import.lazy_class', '_lazy_import.lazy_class', (['"""oci.object_storage.models.namespace_metadata.NamespaceMetadata"""'], {}), "(\n 'oci.object_storage.models.namespace_metadata.NamespaceMetadata')\n", (1569, 1640), True, 'import lazy_import as _lazy_import\n'), ((1660, 1763), 'lazy_import.lazy_class', '_lazy_import.lazy_class', (['"""oci.object_storage.models.object_lifecycle_policy.ObjectLifecyclePolicy"""'], {}), "(\n 'oci.object_storage.models.object_lifecycle_policy.ObjectLifecyclePolicy')\n", (1683, 1763), True, 'import lazy_import as _lazy_import\n'), ((1781, 1880), 'lazy_import.lazy_class', '_lazy_import.lazy_class', (['"""oci.object_storage.models.object_lifecycle_rule.ObjectLifecycleRule"""'], {}), "(\n 'oci.object_storage.models.object_lifecycle_rule.ObjectLifecycleRule')\n", (1804, 1880), True, 'import lazy_import as _lazy_import\n'), ((1895, 1988), 'lazy_import.lazy_class', '_lazy_import.lazy_class', (['"""oci.object_storage.models.object_name_filter.ObjectNameFilter"""'], {}), "(\n 'oci.object_storage.models.object_name_filter.ObjectNameFilter')\n", (1918, 1988), True, 'import lazy_import as _lazy_import\n'), ((2000, 2086), 'lazy_import.lazy_class', '_lazy_import.lazy_class', (['"""oci.object_storage.models.object_summary.ObjectSummary"""'], {}), "(\n 'oci.object_storage.models.object_summary.ObjectSummary')\n", (2023, 2086), True, 'import lazy_import as _lazy_import\n'), ((2108, 2219), 'lazy_import.lazy_class', '_lazy_import.lazy_class', (['"""oci.object_storage.models.preauthenticated_request.PreauthenticatedRequest"""'], {}), "(\n 'oci.object_storage.models.preauthenticated_request.PreauthenticatedRequest'\n )\n", (2131, 2219), True, 'import lazy_import as _lazy_import\n'), ((2243, 2369), 'lazy_import.lazy_class', '_lazy_import.lazy_class', (['"""oci.object_storage.models.preauthenticated_request_summary.PreauthenticatedRequestSummary"""'], {}), "(\n 'oci.object_storage.models.preauthenticated_request_summary.PreauthenticatedRequestSummary'\n )\n", (2266, 2369), True, 'import lazy_import as _lazy_import\n'), ((2394, 2524), 'lazy_import.lazy_class', '_lazy_import.lazy_class', (['"""oci.object_storage.models.put_object_lifecycle_policy_details.PutObjectLifecyclePolicyDetails"""'], {}), "(\n 'oci.object_storage.models.put_object_lifecycle_policy_details.PutObjectLifecyclePolicyDetails'\n )\n", (2417, 2524), True, 'import lazy_import as _lazy_import\n'), ((2537, 2636), 'lazy_import.lazy_class', '_lazy_import.lazy_class', (['"""oci.object_storage.models.rename_object_details.RenameObjectDetails"""'], {}), "(\n 'oci.object_storage.models.rename_object_details.RenameObjectDetails')\n", (2560, 2636), True, 'import lazy_import as _lazy_import\n'), ((2656, 2759), 'lazy_import.lazy_class', '_lazy_import.lazy_class', (['"""oci.object_storage.models.restore_objects_details.RestoreObjectsDetails"""'], {}), "(\n 'oci.object_storage.models.restore_objects_details.RestoreObjectsDetails')\n", (2679, 2759), True, 'import lazy_import as _lazy_import\n'), ((2777, 2876), 'lazy_import.lazy_class', '_lazy_import.lazy_class', (['"""oci.object_storage.models.update_bucket_details.UpdateBucketDetails"""'], {}), "(\n 'oci.object_storage.models.update_bucket_details.UpdateBucketDetails')\n", (2800, 2876), True, 'import lazy_import as _lazy_import\n'), ((2905, 3032), 'lazy_import.lazy_class', '_lazy_import.lazy_class', (['"""oci.object_storage.models.update_namespace_metadata_details.UpdateNamespaceMetadataDetails"""'], {}), "(\n 'oci.object_storage.models.update_namespace_metadata_details.UpdateNamespaceMetadataDetails'\n )\n", (2928, 3032), True, 'import lazy_import as _lazy_import\n'), ((3037, 3114), 'lazy_import.lazy_class', '_lazy_import.lazy_class', (['"""oci.object_storage.models.work_request.WorkRequest"""'], {}), "('oci.object_storage.models.work_request.WorkRequest')\n", (3060, 3114), True, 'import lazy_import as _lazy_import\n'), ((3134, 3227), 'lazy_import.lazy_class', '_lazy_import.lazy_class', (['"""oci.object_storage.models.work_request_error.WorkRequestError"""'], {}), "(\n 'oci.object_storage.models.work_request_error.WorkRequestError')\n", (3157, 3227), True, 'import lazy_import as _lazy_import\n'), ((3245, 3345), 'lazy_import.lazy_class', '_lazy_import.lazy_class', (['"""oci.object_storage.models.work_request_log_entry.WorkRequestLogEntry"""'], {}), "(\n 'oci.object_storage.models.work_request_log_entry.WorkRequestLogEntry')\n", (3268, 3345), True, 'import lazy_import as _lazy_import\n'), ((3363, 3462), 'lazy_import.lazy_class', '_lazy_import.lazy_class', (['"""oci.object_storage.models.work_request_resource.WorkRequestResource"""'], {}), "(\n 'oci.object_storage.models.work_request_resource.WorkRequestResource')\n", (3386, 3462), True, 'import lazy_import as _lazy_import\n'), ((3479, 3576), 'lazy_import.lazy_class', '_lazy_import.lazy_class', (['"""oci.object_storage.models.work_request_summary.WorkRequestSummary"""'], {}), "(\n 'oci.object_storage.models.work_request_summary.WorkRequestSummary')\n", (3502, 3576), True, 'import lazy_import as _lazy_import\n')] |
import matplotlib.pyplot as plt
import seaborn as sns
import pandas
import sklearn.tree
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import GridSearchCV
from sklearn.ensemble import RandomForestClassifier
encoder = LabelEncoder()
data = pandas.read_csv('adult.data',sep=",",names=['age', 'workclass', 'fnlwgt', 'education', 'education-num',
'marital-status', 'occupation', 'relationship', 'race',
'sex', 'capital-gain', 'capital-loss', 'hours-per-week',
'native-country', 'Income'])
print("************ Data Exploration **************")
print("Adult Data:\n", data.head())
print("\n Data Type:\n", data.dtypes)
print("\n Data Description:\n", data.describe())
# numeric conversion
data['workclass'] = encoder.fit_transform(data['workclass'])
data['education'] = encoder.fit_transform(data['education'])
data['marital-status'] = encoder.fit_transform(data['marital-status'])
data['occupation'] = encoder.fit_transform(data['occupation'])
data['relationship'] = encoder.fit_transform(data['relationship'])
data['race'] = encoder.fit_transform(data['race'])
data['sex'] = encoder.fit_transform(data['sex'])
data['native-country'] = encoder.fit_transform(data['native-country'])
data['Income'] = encoder.fit_transform(data['Income'])
# dropping Nan values
data = data.dropna()
# plotting data
# age
sns.barplot(x=data.Income, y=data.age)
plt.show()
'''feature and label'''
X = data.loc[:, data.columns != 'Income']
Y = data['Income']
# splitting data
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.3)
'''Random Forest Classifier'''
print("************ Random Forest Classifier **************")
#Create a Random Forest Classifier object
clf=RandomForestClassifier(n_estimators=500)
#Train the model using the training sets
clf.fit(X_train,y_train)
ypred=clf.predict(X_test)
print("Random Forest: ", accuracy_score(ypred, y_test))
'''Getting Best Hyperparameter using Grid Search'''
print("************ Best Hyperparameters for Decision Tree Classifier using Grid Search **************")
parameter = {
'max_depth': [2,3,4,5,6,10,20,30],
'min_samples_leaf': [5,10,15,20,25,30,35,40,45,50],
'criterion': ['gini', 'entropy']
}
dtree_model = DecisionTreeClassifier()
grid_search = GridSearchCV(estimator=dtree_model,
param_grid=parameter,
cv=4, n_jobs=-1, verbose=1, scoring = "accuracy")
grid_search.fit(X_train, y_train)
print(grid_search.best_estimator_)
'''Distillation Process'''
print("************ Decision Tree Classifier using Distillation process **************")
# target probability
y_pred = clf.predict_proba(X)
# assigning probability to dataframe
df_test = pandas.DataFrame()
df_test['prob_0'] = y_pred[:,0]
df_test['prob_1'] = y_pred[:,1]
# create bin using pandas
labels = ['0.0 - 0.2', '0.2 - 0.4', '0.4 - 0.6', '0.6 - 0.8', '0.8 - 1.0']
X['range_0'] = pandas.cut(df_test['prob_0'],labels=labels, bins=[0.0,0.2,0.4,0.6,0.8,1.0])
X['range_1'] = pandas.cut(df_test['prob_1'],labels=labels, bins=[0.0,0.2,0.4,0.6,0.8,1.0])
X = X.dropna()
# get df_bin
df_bin = pandas.DataFrame()
df_bin['range_0'] = X['range_0']
df_bin['range_1'] = X['range_1']
# plot for range 0
plt.bar(X['range_0'], X['age'], width = 0.4)
plt.show()
# plot for range 0
plt.bar(X['range_1'], X['age'], width = 0.4)
plt.show()
X = X.drop(['range_0', 'range_1'], axis=1)
print("Binned Probability:\n", df_bin.head())
# split dataset after distillation of target variable
xtrain, xtest, ytrain, ytest = train_test_split(X, df_bin, test_size=0.3)
dtree_model = DecisionTreeClassifier(max_depth=10, min_samples_split=2, min_samples_leaf=20, criterion='gini').fit(xtrain, ytrain)
dtree_predictions = dtree_model.predict(xtest)
ytest_lst = []
for i in ytest.values:
if(i[0]>=i[1]):
ytest_lst.append(i[0])
else:
ytest_lst.append(i[1])
dtree_predictions_lst =[]
for i in dtree_predictions:
if (i[0] >= i[1]):
dtree_predictions_lst.append(i[0])
else:
dtree_predictions_lst.append(i[1])
print("Decision Tree (Distillation): ", accuracy_score(dtree_predictions_lst, ytest_lst))
# tree plot
figure = plt.figure()
_ = sklearn.tree.plot_tree(dtree_model, feature_names = X.columns, class_names=df_bin.columns)
figure.savefig("adult_distillation_decision_tree.png")
'''Decision Tree'''
print("************ Decision Tree Classifier **************")
dtree_model = DecisionTreeClassifier(max_depth=10, min_samples_split=2, min_samples_leaf=20, criterion='gini').fit(X_train, y_train)
dtree_pred = dtree_model.predict(X_test)
print("Decision Tree: ", accuracy_score(dtree_pred, y_test))
# tree plot
figure = plt.figure()
_ = sklearn.tree.plot_tree(dtree_model, feature_names = X.columns, class_names=df_bin.columns)
figure.savefig("adult_decision_tree.png")
| [
"sklearn.model_selection.GridSearchCV",
"sklearn.preprocessing.LabelEncoder",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"sklearn.tree.DecisionTreeClassifier",
"sklearn.ensemble.RandomForestClassifier",
"pandas.cut",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.figure",
"pandas.... | [((400, 414), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (412, 414), False, 'from sklearn.preprocessing import LabelEncoder\n'), ((423, 682), 'pandas.read_csv', 'pandas.read_csv', (['"""adult.data"""'], {'sep': '""","""', 'names': "['age', 'workclass', 'fnlwgt', 'education', 'education-num',\n 'marital-status', 'occupation', 'relationship', 'race', 'sex',\n 'capital-gain', 'capital-loss', 'hours-per-week', 'native-country',\n 'Income']"}), "('adult.data', sep=',', names=['age', 'workclass', 'fnlwgt',\n 'education', 'education-num', 'marital-status', 'occupation',\n 'relationship', 'race', 'sex', 'capital-gain', 'capital-loss',\n 'hours-per-week', 'native-country', 'Income'])\n", (438, 682), False, 'import pandas\n'), ((1664, 1702), 'seaborn.barplot', 'sns.barplot', ([], {'x': 'data.Income', 'y': 'data.age'}), '(x=data.Income, y=data.age)\n', (1675, 1702), True, 'import seaborn as sns\n'), ((1704, 1714), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1712, 1714), True, 'import matplotlib.pyplot as plt\n'), ((1861, 1898), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'Y'], {'test_size': '(0.3)'}), '(X, Y, test_size=0.3)\n', (1877, 1898), False, 'from sklearn.model_selection import train_test_split\n'), ((2044, 2084), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'n_estimators': '(500)'}), '(n_estimators=500)\n', (2066, 2084), False, 'from sklearn.ensemble import RandomForestClassifier\n'), ((2570, 2594), 'sklearn.tree.DecisionTreeClassifier', 'DecisionTreeClassifier', ([], {}), '()\n', (2592, 2594), False, 'from sklearn.tree import DecisionTreeClassifier\n'), ((2612, 2721), 'sklearn.model_selection.GridSearchCV', 'GridSearchCV', ([], {'estimator': 'dtree_model', 'param_grid': 'parameter', 'cv': '(4)', 'n_jobs': '(-1)', 'verbose': '(1)', 'scoring': '"""accuracy"""'}), "(estimator=dtree_model, param_grid=parameter, cv=4, n_jobs=-1,\n verbose=1, scoring='accuracy')\n", (2624, 2721), False, 'from sklearn.model_selection import GridSearchCV\n'), ((3075, 3093), 'pandas.DataFrame', 'pandas.DataFrame', ([], {}), '()\n', (3091, 3093), False, 'import pandas\n'), ((3281, 3366), 'pandas.cut', 'pandas.cut', (["df_test['prob_0']"], {'labels': 'labels', 'bins': '[0.0, 0.2, 0.4, 0.6, 0.8, 1.0]'}), "(df_test['prob_0'], labels=labels, bins=[0.0, 0.2, 0.4, 0.6, 0.8,\n 1.0])\n", (3291, 3366), False, 'import pandas\n'), ((3373, 3458), 'pandas.cut', 'pandas.cut', (["df_test['prob_1']"], {'labels': 'labels', 'bins': '[0.0, 0.2, 0.4, 0.6, 0.8, 1.0]'}), "(df_test['prob_1'], labels=labels, bins=[0.0, 0.2, 0.4, 0.6, 0.8,\n 1.0])\n", (3383, 3458), False, 'import pandas\n'), ((3491, 3509), 'pandas.DataFrame', 'pandas.DataFrame', ([], {}), '()\n', (3507, 3509), False, 'import pandas\n'), ((3601, 3643), 'matplotlib.pyplot.bar', 'plt.bar', (["X['range_0']", "X['age']"], {'width': '(0.4)'}), "(X['range_0'], X['age'], width=0.4)\n", (3608, 3643), True, 'import matplotlib.pyplot as plt\n'), ((3647, 3657), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3655, 3657), True, 'import matplotlib.pyplot as plt\n'), ((3681, 3723), 'matplotlib.pyplot.bar', 'plt.bar', (["X['range_1']", "X['age']"], {'width': '(0.4)'}), "(X['range_1'], X['age'], width=0.4)\n", (3688, 3723), True, 'import matplotlib.pyplot as plt\n'), ((3727, 3737), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3735, 3737), True, 'import matplotlib.pyplot as plt\n'), ((3920, 3962), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'df_bin'], {'test_size': '(0.3)'}), '(X, df_bin, test_size=0.3)\n', (3936, 3962), False, 'from sklearn.model_selection import train_test_split\n'), ((4586, 4598), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (4596, 4598), True, 'import matplotlib.pyplot as plt\n'), ((5100, 5112), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (5110, 5112), True, 'import matplotlib.pyplot as plt\n'), ((2208, 2237), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['ypred', 'y_test'], {}), '(ypred, y_test)\n', (2222, 2237), False, 'from sklearn.metrics import accuracy_score\n'), ((4511, 4559), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['dtree_predictions_lst', 'ytest_lst'], {}), '(dtree_predictions_lst, ytest_lst)\n', (4525, 4559), False, 'from sklearn.metrics import accuracy_score\n'), ((5039, 5073), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['dtree_pred', 'y_test'], {}), '(dtree_pred, y_test)\n', (5053, 5073), False, 'from sklearn.metrics import accuracy_score\n'), ((3978, 4079), 'sklearn.tree.DecisionTreeClassifier', 'DecisionTreeClassifier', ([], {'max_depth': '(10)', 'min_samples_split': '(2)', 'min_samples_leaf': '(20)', 'criterion': '"""gini"""'}), "(max_depth=10, min_samples_split=2, min_samples_leaf=\n 20, criterion='gini')\n", (4000, 4079), False, 'from sklearn.tree import DecisionTreeClassifier\n'), ((4852, 4953), 'sklearn.tree.DecisionTreeClassifier', 'DecisionTreeClassifier', ([], {'max_depth': '(10)', 'min_samples_split': '(2)', 'min_samples_leaf': '(20)', 'criterion': '"""gini"""'}), "(max_depth=10, min_samples_split=2, min_samples_leaf=\n 20, criterion='gini')\n", (4874, 4953), False, 'from sklearn.tree import DecisionTreeClassifier\n')] |
# Copyright 2021 DengBoCong. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""模型功能顶层封装类,包含train、evaluate等等模式
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
import time
import torch
from torch.utils.data import DataLoader
from torch.optim import Optimizer
from dialogue.pytorch.load_dataset import load_data
from dialogue.pytorch.utils import save_checkpoint
from dialogue.tools import get_dict_string
from dialogue.tools import ProgressBar
from typing import AnyStr
from typing import Dict
from typing import NoReturn
from typing import Tuple
class Modules(abc.ABC):
def __init__(self, batch_size: int, max_sentence: int, train_data_type: str, valid_data_type: str,
dict_path: str = "", num_workers: int = 2, model: torch.nn.Module = None,
encoder: torch.nn.Module = None, decoder: torch.nn.Module = None,
device: torch.device = None) -> NoReturn:
"""model以及(encoder,decoder)两类模型传其中一种即可,具体在各自继承之后的训练步中使用
Note:
a): 模型训练指标中,保证至少返回到当前batch为止的平均训练损失
:param batch_size: Dataset加载批大小
:param max_sentence: 最大句子长度
:param train_data_type: 读取训练数据类型,单轮/多轮...
:param valid_data_type: 读取验证数据类型,单轮/多轮...
:param dict_path: 字典路径,若使用phoneme则不用传
:param num_workers: 数据加载器的工作线程
:param model: 模型
:param encoder: encoder模型
:param decoder: decoder模型
:param device: 指定运行设备
:return: 返回历史指标数据
"""
self.batch_size = batch_size
self.max_sentence = max_sentence
self.train_data_type = train_data_type
self.valid_data_type = valid_data_type
self.dict_path = dict_path
self.num_workers = num_workers
self.model = model
self.encoder = encoder
self.decoder = decoder
self.device = device
@abc.abstractmethod
def _train_step(self, batch_dataset: Tuple[torch.Tensor, torch.Tensor, torch.Tensor],
optimizer: Optimizer, *args, **kwargs) -> Dict:
"""该方法用于定于训练步中,模型实际训练的核心代码(在train方法中使用)
Note:
a): 返回所得指标字典
b): batch_dataset、optimizer为模型训练必需
"""
raise NotImplementedError("Must be implemented in subclasses.")
@abc.abstractmethod
def _valid_step(self, loader: DataLoader, steps_per_epoch: int,
progress_bar: ProgressBar, *args, **kwargs) -> Dict:
""" 该方法用于定义验证模型逻辑
Note:
a): 返回所得指标字典
b): DataLoader为模型验证必需
"""
raise NotImplementedError("Must be implemented in subclasses.")
def train(self, optimizer: torch.optim.Optimizer, train_data_path: str, epochs: int, checkpoint_save_freq: int,
checkpoint_dir: str = "", valid_data_split: float = 0.0, max_train_data_size: int = 0,
valid_data_path: str = "", max_valid_data_size: int = 0, history: dict = {}, **kwargs) -> Dict:
""" 训练模块
:param optimizer: 优化器
:param train_data_path: 文本数据路径
:param epochs: 训练周期
:param checkpoint_save_freq: 检查点保存频率
:param checkpoint_dir: 检查点保存目录路径
:param valid_data_split: 用于从训练数据中划分验证数据
:param max_train_data_size: 最大训练数据量
:param valid_data_path: 验证数据文本路径
:param max_valid_data_size: 最大验证数据量
:param history: 用于保存训练过程中的历史指标数据
:return: 返回历史指标数据
"""
print('训练开始,正在准备数据中...')
train_loader, valid_loader, train_steps_per_epoch, valid_steps_per_epoch = load_data(
dict_path=self.dict_path, batch_size=self.batch_size, train_data_type=self.train_data_type,
valid_data_type=self.valid_data_type, max_sentence=self.max_sentence, valid_data_split=valid_data_split,
train_data_path=train_data_path, valid_data_path=valid_data_path, max_train_data_size=max_train_data_size,
max_valid_data_size=max_valid_data_size, num_workers=self.num_workers, **kwargs
)
progress_bar = ProgressBar()
for epoch in range(epochs):
print("Epoch {}/{}".format(epoch + 1, epochs))
start_time = time.time()
progress_bar.reset(total=train_steps_per_epoch, num=self.batch_size)
for (batch, batch_dataset) in enumerate(train_loader):
train_metrics = self._train_step(batch_dataset=batch_dataset, optimizer=optimizer, **kwargs)
progress_bar(current=batch + 1, metrics=get_dict_string(data=train_metrics))
progress_bar.done(step_time=time.time() - start_time)
for key, value in train_metrics.items():
history[key].append(value)
if (epoch + 1) % checkpoint_save_freq == 0:
save_checkpoint(checkpoint_dir=checkpoint_dir, optimizer=optimizer,
model=self.model, encoder=self.encoder, decoder=self.decoder)
if valid_steps_per_epoch == 0 or valid_loader is None:
print("验证数据量过小,小于batch_size,已跳过验证轮次")
else:
valid_metrics = self._valid_step(loader=valid_loader, progress_bar=progress_bar,
steps_per_epoch=valid_steps_per_epoch, **kwargs)
for key, value in valid_metrics.items():
history[key].append(value)
print("训练结束")
return history
def evaluate(self, valid_data_path: str = "", max_valid_data_size: int = 0, **kwargs) -> NoReturn:
""" 验证模块
:param valid_data_path: 验证数据文本路径
:param max_valid_data_size: 最大验证数据量
:return: 返回历史指标数据
"""
print("验证开始,正在准备数据中")
_, valid_loader, _, valid_steps_per_epoch = load_data(
dict_path=self.dict_path, batch_size=self.batch_size, train_data_type=self.train_data_type,
valid_data_type=self.valid_data_type, max_sentence=self.max_sentence, valid_data_path=valid_data_path,
max_valid_data_size=max_valid_data_size, num_workers=self.num_workers, **kwargs
)
progress_bar = ProgressBar()
_ = self._valid_step(loader=valid_loader, progress_bar=progress_bar,
steps_per_epoch=valid_steps_per_epoch, **kwargs)
print("验证结束")
@abc.abstractmethod
def inference(self, *args, **kwargs) -> AnyStr:
""" 对话推断模块
"""
raise NotImplementedError("Must be implemented in subclasses.")
| [
"dialogue.tools.get_dict_string",
"dialogue.pytorch.load_dataset.load_data",
"dialogue.pytorch.utils.save_checkpoint",
"dialogue.tools.ProgressBar",
"time.time"
] | [((4153, 4574), 'dialogue.pytorch.load_dataset.load_data', 'load_data', ([], {'dict_path': 'self.dict_path', 'batch_size': 'self.batch_size', 'train_data_type': 'self.train_data_type', 'valid_data_type': 'self.valid_data_type', 'max_sentence': 'self.max_sentence', 'valid_data_split': 'valid_data_split', 'train_data_path': 'train_data_path', 'valid_data_path': 'valid_data_path', 'max_train_data_size': 'max_train_data_size', 'max_valid_data_size': 'max_valid_data_size', 'num_workers': 'self.num_workers'}), '(dict_path=self.dict_path, batch_size=self.batch_size,\n train_data_type=self.train_data_type, valid_data_type=self.\n valid_data_type, max_sentence=self.max_sentence, valid_data_split=\n valid_data_split, train_data_path=train_data_path, valid_data_path=\n valid_data_path, max_train_data_size=max_train_data_size,\n max_valid_data_size=max_valid_data_size, num_workers=self.num_workers,\n **kwargs)\n', (4162, 4574), False, 'from dialogue.pytorch.load_dataset import load_data\n'), ((4630, 4643), 'dialogue.tools.ProgressBar', 'ProgressBar', ([], {}), '()\n', (4641, 4643), False, 'from dialogue.tools import ProgressBar\n'), ((6370, 6674), 'dialogue.pytorch.load_dataset.load_data', 'load_data', ([], {'dict_path': 'self.dict_path', 'batch_size': 'self.batch_size', 'train_data_type': 'self.train_data_type', 'valid_data_type': 'self.valid_data_type', 'max_sentence': 'self.max_sentence', 'valid_data_path': 'valid_data_path', 'max_valid_data_size': 'max_valid_data_size', 'num_workers': 'self.num_workers'}), '(dict_path=self.dict_path, batch_size=self.batch_size,\n train_data_type=self.train_data_type, valid_data_type=self.\n valid_data_type, max_sentence=self.max_sentence, valid_data_path=\n valid_data_path, max_valid_data_size=max_valid_data_size, num_workers=\n self.num_workers, **kwargs)\n', (6379, 6674), False, 'from dialogue.pytorch.load_dataset import load_data\n'), ((6726, 6739), 'dialogue.tools.ProgressBar', 'ProgressBar', ([], {}), '()\n', (6737, 6739), False, 'from dialogue.tools import ProgressBar\n'), ((4765, 4776), 'time.time', 'time.time', ([], {}), '()\n', (4774, 4776), False, 'import time\n'), ((5367, 5501), 'dialogue.pytorch.utils.save_checkpoint', 'save_checkpoint', ([], {'checkpoint_dir': 'checkpoint_dir', 'optimizer': 'optimizer', 'model': 'self.model', 'encoder': 'self.encoder', 'decoder': 'self.decoder'}), '(checkpoint_dir=checkpoint_dir, optimizer=optimizer, model=\n self.model, encoder=self.encoder, decoder=self.decoder)\n', (5382, 5501), False, 'from dialogue.pytorch.utils import save_checkpoint\n'), ((5093, 5128), 'dialogue.tools.get_dict_string', 'get_dict_string', ([], {'data': 'train_metrics'}), '(data=train_metrics)\n', (5108, 5128), False, 'from dialogue.tools import get_dict_string\n'), ((5171, 5182), 'time.time', 'time.time', ([], {}), '()\n', (5180, 5182), False, 'import time\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Importa as bibliotecas básicas para o funcionamento da tradução
import json
import xml
import xmltodict
import jsonschema
# Classe Model é responsável por validar o Input/Output, i.e., a estrutura do autômato
class Model(object):
def __init__(self):
self.model_file = "models/json/struct.json"
self.entry = None
self.output = None
self.states = None
self.transitions = None
self.__message = None
# Método para retornar mensagens de erro
def alerts(self):
return self.__message
# Método para criar mensagens de erro
def create_alert(self, msg):
self.__message = str(msg)
# Método responsável por ler o arquivo de regras de estruturação do Autômato (i.e. o padrão de I/O)
def read_schema(self):
try:
with open(self.model_file, "r") as data_file:
return json.load(data_file)
except IOError:
self.create_alert("Erro ler modelo de I/O!")
return None
# Método para verificar a síntaxe do Input, conforme as regras de estruturações presentes no
# arquivo ´models/json/struct.json´
def check_syntax(self, automaton):
try:
jsonschema.Draft4Validator(self.read_schema()).validate(automaton)
return True
except jsonschema.exceptions.ValidationError as error:
self.create_alert(
"Erro de sintaxe: " +
error.message.replace("u'", "'") +
"\nPor favor, revise seu autômato conforme as definições dispostas na Documentação."
)
return False
# Carrega a estrutura do Input para os atributos da classe
def load_base_struct(self):
self.states = self.entry["structure"]["automaton"]["state"]
self.transitions = self.entry["structure"]["automaton"]["transition"]
# Ordena os estados pela propriedade ´id´ e as transições pela propriedade ´from´
def sort_object(self):
self.states = sorted(self.states, key=lambda x: int(x["@id"]))
self.transitions = sorted(self.transitions, key=lambda x: int(x["from"]))
# Jflap é a classe responsável por realizar a Importação e Exportação de arquivos no formato JFLAP#
# Obs.: Ela herda propriedades da classe ´Model´
class Jflap(Model):
def __init__(self):
super(Jflap, self).__init__()
# Método responsável por remover algumas propriedades inúteis para a tradução presente na estrutura
# do arquivo JFLAP, além de consertar o tipo das propriedades de interesse
def __fix_values_types(self):
for i in self.states:
i["@id"] = int(i["@id"])
i.pop("x")
i.pop("y")
try:
i["initial"] = True if i["initial"] is None else True
except KeyError:
pass
try:
i["final"] = True if i["final"] is None else True
except KeyError:
pass
try:
i.pop("label")
except KeyError:
pass
for i in self.transitions:
i["from"] = int(i["from"])
i["to"] = int(i["to"])
# Método responsável por realizar a conversão, através da biblioteca ´xmltodict´, de um modelo
# JFLAP para json (método utilizado no processo de importação)
def jff2json(self):
try:
self.entry = json.loads(json.dumps(xmltodict.parse(self.entry)))
self.load_base_struct()
self.__fix_values_types()
self.sort_object()
except xml.parsers.expat.ExpatError as error:
self.create_alert("Impossível realizar conversão do arquivo .jff!\n" + error.message)
# Método reponsável por características importantes para a execução do modelo gerado
# no JFLAP (método utilizado no processo d exportação)
@staticmethod
def prepare_layout_jff(content):
try:
if not content["type"]:
content.update({u"type": u"fa"})
except KeyError:
pass
return content
# Método responsável por realizar a conversão de um arquivo de entrada (json ou dict)
# para o formato JFLAP compatível
def make_jff(self, content):
temp = json.loads(content)
temp = self.prepare_layout_jff(temp)
return xmltodict.unparse(temp, pretty=True)
# Classe principal no processo de tradução AFN -> AFD
# herda propriedades da classe ´Jflap´ que, por sua vez, herda da classe ´Model´
# Ou seja, a classe ´Translator´ tem acesso a todos os métodos e atributos não privados das classes anteriores
class Translator(Jflap):
def __init__(self, entry):
super(Translator, self).__init__()
self.entry = entry
self.initial_state = None
self.final_state = []
self.new_transitions = []
# Método responsável identificar e listar o alfabeto utilizado pelo autômato de entrada
def __get_alphabet(self):
alphabet = [str(item["read"]) for item in self.transitions]
return sorted(list(set(alphabet)))
# Método responsável por identificar os estados iniciais e finais, bem como
# realizar a ordenação dos mesmos
def __get_az_states(self):
for i in self.states:
try:
if i["initial"] is None or True:
self.initial_state = i
except KeyError:
pass
try:
if i["final"] is None or True:
self.final_state.append(i)
except KeyError:
pass
self.final_state = sorted(self.final_state, key=lambda x: int(x["@id"]))
# Método responsável por último estado criado
def __get_last_state_id(self):
return self.states[-1]["@id"]
# Método responsável por retornar todas as propriedades de dado estado
def __get_state(self, state_id):
return [item for item in self.states if item["@id"] == state_id][0]
# Método responsável por listar todas as transições ´de um determinado estado´ lendo ´determinado símbolo´
# das transições do AFD a ser gerado
def __get_transitions(self, from_id, reading):
return [item["to"] for item in self.new_transitions if item["from"] == from_id and item["read"] == reading]
# Método responsável por listar todas as transições ´de um determinado estado´ lendo ´determinado símbolo´
# das transições do AFN de entrada
def __get_transitions_afn(self, from_id, reading):
return [item["to"] for item in self.transitions if item["from"] == from_id and item["read"] == reading]
# Método responsável apagar uma determinada transição de um ´determinado estado´ lendo ´determinado símbolo´
def __pop_transition_from(self, state_id, reading):
state_transitions = [item for item in self.new_transitions if item["from"] == state_id and item["read"] == reading]
for i in state_transitions:
self.new_transitions.remove(i)
# Verifica se ´determinado estado´ é um estado inicial (boolean)
def __is_initial_state(self, state_id):
return True if self.initial_state["@id"] is state_id else False
# Verifica se ´determinado estado´ é um estado final (boolean)
def __is_final_state(self, states_id):
for item in self.final_state:
for state in states_id:
if item["@id"] == state:
return True
return False
# Retorna um nome para um novo estado
# esse nome segue o padrão: q + id_do_estado (e.g. q0, q1, q0q1 etc)
@staticmethod
def __set_name_tuple(symbols, n_id=None):
name = ""
if isinstance(symbols, list):
for i in symbols:
name += "q"+str(i)
return name
else:
name = "q" + str(n_id)
return name
# Cria uma nova transição ´de um determinado estado´ para outro ´determinado estado´ lendo ´um símbolo´
def __new_transition(self, from_id, to_id, reading):
transition = {}
transition.update({u"from": from_id})
transition.update({u"to": to_id})
transition.update({u"read": reading})
self.new_transitions.append(transition)
# Cria um novo estado
def __new_state(self, is_initial, is_final, name=None):
this_id = self.__get_last_state_id() + 1
state = {}
state.update({u"@id": this_id})
state.update({u"@name": self.__set_name_tuple(name, n_id=this_id)})
state.update({u"initial": True}) if is_initial is True else None
state.update({u"final": True}) if is_final is True else None
self.states.append(state)
return this_id
# Realiza a união de todas as transições de um ´determinado conjunto de estados´ lendo ´um símbolo´
# e verifica se essa união dá origem a um novo estado ou a um estado já existente
def __get_transitions_union(self, transitions, symbol, new_state):
new_state_transitions = []
for i in transitions:
new_state_transitions.append(self.__get_transitions_afn(i, symbol))
new_state_transitions = list(set([item for sublist in new_state_transitions for item in sublist]))
if new_state_transitions == transitions:
return [new_state]
else:
return new_state_transitions
# Função principal para a criação do afn
def __create_afd_by_afn(self):
self.load_base_struct()
self.__get_az_states()
# Faz um backup das transições presentes no AFN para ter como base para as novas do AFD
self.new_transitions += self.transitions
# Dicionário de referência: ´conjunto de transições´ vão para ´este novo estado´
transictions_dict = {}
# Para casa estado faça
for state in self.states:
# Lendo cada símbolo desse estado faça
for symbol in self.__get_alphabet():
# Lista as transições que esse estado tem lendo o símbolo atual (AFD)
actual_transitions = list(set(self.__get_transitions(state["@id"], symbol)))
# Lista as transições que esse estado tem lendo o símbolo atual (AFN) (novo)
actual_transitions_afn = list(set(self.__get_transitions_afn(state["@id"], symbol)))
# Caso esse estado atual possua mais de uma transição (não determístico), faça...
if len(actual_transitions) > 1:
# Crie um novo estado
new_state = self.__new_state(
False,
self.__is_final_state(actual_transitions_afn),
name=actual_transitions_afn
)
# Salve a refêrencia de transição
transictions_dict.update({
str(actual_transitions): new_state
})
# Apague as transições velhas
self.__pop_transition_from(state["@id"], symbol)
# Crie uma transição do estado atual para o novo estado criado
self.__new_transition(state["@id"], new_state, symbol)
# Configuração das transições para cada símbolo do novo estado
# Para cada símbolo do alfabeto, lendo-se para o novo estado, faça...
for symbol_b in self.__get_alphabet():
# obtêm a união das transições do estado atual lendo este símbolo da iteração
new_transitions = self.__get_transitions_union(actual_transitions, symbol_b, new_state)
# caso o símbolo dessa iteração seja o mesmo da principal, i.e
# o novo estado receberá a união das transições do estado que o gerou
if symbol_b == symbol:
for node in new_transitions:
self.__new_transition(new_state, node, symbol)
else:
for node in new_transitions:
# se o número de novas transições for maior que 1, i.e,
# o estado não recebe uma transição para ele mesmo, então
if len(new_transitions) > 1:
try:
# cria-se uma transição do novo estado para uma transição referênciada no dicionário de referências de transições
self.__new_transition(new_state, transictions_dict[str(new_transitions)], symbol_b)
except KeyError as error:
# Caso a referência não exista
self.create_alert(
"Erro ao adicionar novas transições! \n\n" +
json.dumps(transictions_dict, sort_keys=True, indent=4, separators=(',', ': ')) +
"\n\nnew_transitions=" + str(new_transitions) +
"\n\nKeyError not found: " + error.message
)
break
else:
self.__new_transition(new_state, node, symbol_b)
# função main para verificação da estrutura e encaminhamento para a conversão
def convert(self):
# verifica se o autômato de entrada está em condições sintáticas de ser traduzido
if isinstance(self.entry, dict) is not True:
try:
self.entry = json.loads(self.entry)
except ValueError as error:
self.create_alert(error)
# se estier tudo ok, ele começa o processo de tradução
if self.check_syntax(self.entry):
self.__create_afd_by_afn()
# Método responsável por montar uma tabela de transição mais 'visual' para o usuário
def show_automaton(self):
output = "\n"
for state in self.states:
for symbol in self.__get_alphabet():
output += "q{0} * {1} → {2}\n".format(state["@id"], symbol, ['q'+str(i) for i in self.__get_transitions(state["@id"], symbol)]).replace("u'", "'").replace("['", "").replace("']", "").replace("'", "").replace("'", "").replace("[]", "λ")
return output
| [
"json.loads",
"xmltodict.parse",
"json.dumps",
"xmltodict.unparse",
"json.load"
] | [((4306, 4325), 'json.loads', 'json.loads', (['content'], {}), '(content)\n', (4316, 4325), False, 'import json\n'), ((4386, 4422), 'xmltodict.unparse', 'xmltodict.unparse', (['temp'], {'pretty': '(True)'}), '(temp, pretty=True)\n', (4403, 4422), False, 'import xmltodict\n'), ((934, 954), 'json.load', 'json.load', (['data_file'], {}), '(data_file)\n', (943, 954), False, 'import json\n'), ((13757, 13779), 'json.loads', 'json.loads', (['self.entry'], {}), '(self.entry)\n', (13767, 13779), False, 'import json\n'), ((3475, 3502), 'xmltodict.parse', 'xmltodict.parse', (['self.entry'], {}), '(self.entry)\n', (3490, 3502), False, 'import xmltodict\n'), ((12994, 13073), 'json.dumps', 'json.dumps', (['transictions_dict'], {'sort_keys': '(True)', 'indent': '(4)', 'separators': "(',', ': ')"}), "(transictions_dict, sort_keys=True, indent=4, separators=(',', ': '))\n", (13004, 13073), False, 'import json\n')] |
import sys
import numpy as np
import mc3
def quad(p, x):
"""
Quadratic polynomial function.
Parameters
p: Polynomial constant, linear, and quadratic coefficients.
x: Array of dependent variables where to evaluate the polynomial.
Returns
y: Polinomial evaluated at x: y(x) = p0 + p1*x + p2*x^2
"""
y = p[0] + p[1]*x + p[2]*x**2.0
return y
# ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
# Preamble (create a synthetic dataset, in a real scenario you would
# get your dataset from your own data analysis pipeline):
np.random.seed(314)
x = np.linspace(0, 10, 1000)
p0 = [3, -2.4, 0.5]
y = quad(p0, x)
uncert = np.sqrt(np.abs(y))
error = np.random.normal(0, uncert)
data = y + error
# ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
# Define the modeling function as a callable:
func = quad
# List of additional arguments of func (if necessary):
indparams = [x]
# Array of initial-guess values of fitting parameters:
params = np.array([ 10.0, -2.0, 0.1])
# Lower and upper boundaries for the MCMC exploration:
pmin = np.array([-10.0, -20.0, -10.0])
pmax = np.array([ 40.0, 20.0, 10.0])
# Parameters' stepping behavior:
pstep = np.array([1.0, 0.5, 0.1])
# Parameter prior probability distributions:
prior = np.array([ 0.0, 0.0, 0.0])
priorlow = np.array([ 0.0, 0.0, 0.0])
priorup = np.array([ 0.0, 0.0, 0.0])
# Parameter names:
pnames = ['y0', 'alpha', 'beta']
texnames = [r'$y_{0}$', r'$\alpha$', r'$\beta$']
# Sampler algorithm, choose from: 'snooker', 'demc' or 'mrw'.
sampler = 'snooker'
# MCMC setup:
nsamples = 1e5
burnin = 1000
nchains = 14
ncpu = 7
thinning = 1
# MCMC initial draw, choose from: 'normal' or 'uniform'
kickoff = 'normal'
# DEMC snooker pre-MCMC sample size:
hsize = 10
# Optimization before MCMC, choose from: 'lm' or 'trf':
leastsq = 'lm'
chisqscale = False
# MCMC Convergence:
grtest = True
grbreak = 1.01
grnmin = 0.5
# Logging:
log = 'MCMC_tutorial.log'
# File outputs:
savefile = 'MCMC_tutorial.npz'
plots = True
rms = True
# <NAME> (2009) Wavelet-likelihood method:
wlike = False
# Run the MCMC:
mc3_output = mc3.sample(data=data, uncert=uncert, func=func, params=params,
indparams=indparams, pmin=pmin, pmax=pmax, pstep=pstep,
pnames=pnames, texnames=texnames,
prior=prior, priorlow=priorlow, priorup=priorup,
sampler=sampler, nsamples=nsamples, nchains=nchains,
ncpu=ncpu, burnin=burnin, thinning=thinning,
leastsq=leastsq, chisqscale=chisqscale,
grtest=grtest, grbreak=grbreak, grnmin=grnmin,
hsize=hsize, kickoff=kickoff,
wlike=wlike, log=log,
plots=plots, savefile=savefile, rms=rms)
| [
"numpy.random.normal",
"numpy.abs",
"numpy.array",
"numpy.linspace",
"mc3.sample",
"numpy.random.seed"
] | [((593, 612), 'numpy.random.seed', 'np.random.seed', (['(314)'], {}), '(314)\n', (607, 612), True, 'import numpy as np\n'), ((618, 642), 'numpy.linspace', 'np.linspace', (['(0)', '(10)', '(1000)'], {}), '(0, 10, 1000)\n', (629, 642), True, 'import numpy as np\n'), ((718, 745), 'numpy.random.normal', 'np.random.normal', (['(0)', 'uncert'], {}), '(0, uncert)\n', (734, 745), True, 'import numpy as np\n'), ((1032, 1059), 'numpy.array', 'np.array', (['[10.0, -2.0, 0.1]'], {}), '([10.0, -2.0, 0.1])\n', (1040, 1059), True, 'import numpy as np\n'), ((1123, 1154), 'numpy.array', 'np.array', (['[-10.0, -20.0, -10.0]'], {}), '([-10.0, -20.0, -10.0])\n', (1131, 1154), True, 'import numpy as np\n'), ((1162, 1190), 'numpy.array', 'np.array', (['[40.0, 20.0, 10.0]'], {}), '([40.0, 20.0, 10.0])\n', (1170, 1190), True, 'import numpy as np\n'), ((1235, 1260), 'numpy.array', 'np.array', (['[1.0, 0.5, 0.1]'], {}), '([1.0, 0.5, 0.1])\n', (1243, 1260), True, 'import numpy as np\n'), ((1318, 1343), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0]'], {}), '([0.0, 0.0, 0.0])\n', (1326, 1343), True, 'import numpy as np\n'), ((1356, 1381), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0]'], {}), '([0.0, 0.0, 0.0])\n', (1364, 1381), True, 'import numpy as np\n'), ((1394, 1419), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0]'], {}), '([0.0, 0.0, 0.0])\n', (1402, 1419), True, 'import numpy as np\n'), ((2194, 2701), 'mc3.sample', 'mc3.sample', ([], {'data': 'data', 'uncert': 'uncert', 'func': 'func', 'params': 'params', 'indparams': 'indparams', 'pmin': 'pmin', 'pmax': 'pmax', 'pstep': 'pstep', 'pnames': 'pnames', 'texnames': 'texnames', 'prior': 'prior', 'priorlow': 'priorlow', 'priorup': 'priorup', 'sampler': 'sampler', 'nsamples': 'nsamples', 'nchains': 'nchains', 'ncpu': 'ncpu', 'burnin': 'burnin', 'thinning': 'thinning', 'leastsq': 'leastsq', 'chisqscale': 'chisqscale', 'grtest': 'grtest', 'grbreak': 'grbreak', 'grnmin': 'grnmin', 'hsize': 'hsize', 'kickoff': 'kickoff', 'wlike': 'wlike', 'log': 'log', 'plots': 'plots', 'savefile': 'savefile', 'rms': 'rms'}), '(data=data, uncert=uncert, func=func, params=params, indparams=\n indparams, pmin=pmin, pmax=pmax, pstep=pstep, pnames=pnames, texnames=\n texnames, prior=prior, priorlow=priorlow, priorup=priorup, sampler=\n sampler, nsamples=nsamples, nchains=nchains, ncpu=ncpu, burnin=burnin,\n thinning=thinning, leastsq=leastsq, chisqscale=chisqscale, grtest=\n grtest, grbreak=grbreak, grnmin=grnmin, hsize=hsize, kickoff=kickoff,\n wlike=wlike, log=log, plots=plots, savefile=savefile, rms=rms)\n', (2204, 2701), False, 'import mc3\n'), ((698, 707), 'numpy.abs', 'np.abs', (['y'], {}), '(y)\n', (704, 707), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
# Copyright 2020 <NAME>
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import trio
try:
import importlib.resources as pkg_resources
except ImportError:
import importlib_resources as pkg_resources # Try backported to PY<37 `importlib_resources`.
from . import static
DEFAULT_PATH_MAP = {
"/": pkg_resources.read_text(static, "device.html"),
"/connector": pkg_resources.read_text(static, "connector.js"),
"/display_firmware": pkg_resources.read_text(static, "display_firmware.js"),
# "/keyboard_firmware": pkg_resources.read_text(static, "keyboard_firmware.js"),
# "/mouse_firmware": pkg_resources.read_text(static, "mouse_firmware.js")
}
async def http_main(path_map=DEFAULT_PATH_MAP):
async def http_handler(stream):
req = (await stream.receive_some()).decode('utf-8')
method, path, proto_version = req.split('\n')[0].split()
print(f"GET Request for path {path}")
if path_map is None or path not in path_map:
await stream.send_all(f"HTTP/1.1 404 Not Found\n\nError Not Found\n".encode('utf-8'))
return
response_body = path_map[path]
await stream.send_all(f"HTTP/1.1 200 OK\n\n{response_body}\n".encode('utf-8'))
async with trio.open_nursery() as n:
n.start_soon(trio.serve_tcp, http_handler, 8080) | [
"trio.open_nursery",
"importlib_resources.read_text"
] | [((828, 874), 'importlib_resources.read_text', 'pkg_resources.read_text', (['static', '"""device.html"""'], {}), "(static, 'device.html')\n", (851, 874), True, 'import importlib_resources as pkg_resources\n'), ((894, 941), 'importlib_resources.read_text', 'pkg_resources.read_text', (['static', '"""connector.js"""'], {}), "(static, 'connector.js')\n", (917, 941), True, 'import importlib_resources as pkg_resources\n'), ((968, 1022), 'importlib_resources.read_text', 'pkg_resources.read_text', (['static', '"""display_firmware.js"""'], {}), "(static, 'display_firmware.js')\n", (991, 1022), True, 'import importlib_resources as pkg_resources\n'), ((1756, 1775), 'trio.open_nursery', 'trio.open_nursery', ([], {}), '()\n', (1773, 1775), False, 'import trio\n')] |
from typing import List
from fastapi import APIRouter, UploadFile, File, Depends
import file.controllers as file_controller
import level.controllers as level_controller
from decorators import proto_resp
from level.models import Level
from file.models import File as FileT
from level.views import LevelMetaDataOut, LevelMetaDataCreate, LevelMetaDatasOut
from user.controllers import get_current_active_user
from user.views import UserOut
router = APIRouter()
@router.post("/", tags=["level"])
@proto_resp
async def upload_level(create: LevelMetaDataCreate = Depends(), levelFiles: UploadFile = File(...), current_user: UserOut = Depends(get_current_active_user)):
file: FileT = await file_controller.upload_file(levelFiles)
level: Level = level_controller.add_level(create)
level_controller.add_file_to_level(file.id, level.ulid)
level_controller.add_level_download(level.ulid)
level_controller.add_user_to_level(current_user.id, level.ulid)
return LevelMetaDataOut.from_orm(level)
@router.get("/all", tags=["level"])
@proto_resp
async def get_all_level_meta_datas():
metaDatas: List[Level] = level_controller.get_levels()
l = LevelMetaDatasOut(levels = metaDatas)
return l
@router.delete("/")
async def remove_level(ulid: int,_UserOut = Depends(get_current_active_user)):
level_controller.remove_level(ulid)
@router.get("/", tags=["level"])
@proto_resp
async def get_level_meta_data(ulid: int):
metaData = level_controller.get_level(ulid)
return LevelMetaDataOut.from_orm(metaData)
@router.get("/download", tags=["level"])
@proto_resp
async def download_level(ulid: int):
level_controller.increment(ulid)
file: File = level_controller.get_files_of_level(ulid)[0]
f = await file_controller.download_file(file.id)
return f
| [
"level.controllers.add_user_to_level",
"level.views.LevelMetaDataOut.from_orm",
"level.controllers.remove_level",
"file.controllers.download_file",
"level.controllers.add_level",
"level.views.LevelMetaDatasOut",
"level.controllers.increment",
"level.controllers.get_level",
"level.controllers.get_lev... | [((449, 460), 'fastapi.APIRouter', 'APIRouter', ([], {}), '()\n', (458, 460), False, 'from fastapi import APIRouter, UploadFile, File, Depends\n'), ((562, 571), 'fastapi.Depends', 'Depends', ([], {}), '()\n', (569, 571), False, 'from fastapi import APIRouter, UploadFile, File, Depends\n'), ((598, 607), 'fastapi.File', 'File', (['...'], {}), '(...)\n', (602, 607), False, 'from fastapi import APIRouter, UploadFile, File, Depends\n'), ((633, 665), 'fastapi.Depends', 'Depends', (['get_current_active_user'], {}), '(get_current_active_user)\n', (640, 665), False, 'from fastapi import APIRouter, UploadFile, File, Depends\n'), ((751, 785), 'level.controllers.add_level', 'level_controller.add_level', (['create'], {}), '(create)\n', (777, 785), True, 'import level.controllers as level_controller\n'), ((790, 845), 'level.controllers.add_file_to_level', 'level_controller.add_file_to_level', (['file.id', 'level.ulid'], {}), '(file.id, level.ulid)\n', (824, 845), True, 'import level.controllers as level_controller\n'), ((850, 897), 'level.controllers.add_level_download', 'level_controller.add_level_download', (['level.ulid'], {}), '(level.ulid)\n', (885, 897), True, 'import level.controllers as level_controller\n'), ((902, 965), 'level.controllers.add_user_to_level', 'level_controller.add_user_to_level', (['current_user.id', 'level.ulid'], {}), '(current_user.id, level.ulid)\n', (936, 965), True, 'import level.controllers as level_controller\n'), ((977, 1009), 'level.views.LevelMetaDataOut.from_orm', 'LevelMetaDataOut.from_orm', (['level'], {}), '(level)\n', (1002, 1009), False, 'from level.views import LevelMetaDataOut, LevelMetaDataCreate, LevelMetaDatasOut\n'), ((1128, 1157), 'level.controllers.get_levels', 'level_controller.get_levels', ([], {}), '()\n', (1155, 1157), True, 'import level.controllers as level_controller\n'), ((1166, 1201), 'level.views.LevelMetaDatasOut', 'LevelMetaDatasOut', ([], {'levels': 'metaDatas'}), '(levels=metaDatas)\n', (1183, 1201), False, 'from level.views import LevelMetaDataOut, LevelMetaDataCreate, LevelMetaDatasOut\n'), ((1282, 1314), 'fastapi.Depends', 'Depends', (['get_current_active_user'], {}), '(get_current_active_user)\n', (1289, 1314), False, 'from fastapi import APIRouter, UploadFile, File, Depends\n'), ((1321, 1356), 'level.controllers.remove_level', 'level_controller.remove_level', (['ulid'], {}), '(ulid)\n', (1350, 1356), True, 'import level.controllers as level_controller\n'), ((1462, 1494), 'level.controllers.get_level', 'level_controller.get_level', (['ulid'], {}), '(ulid)\n', (1488, 1494), True, 'import level.controllers as level_controller\n'), ((1506, 1541), 'level.views.LevelMetaDataOut.from_orm', 'LevelMetaDataOut.from_orm', (['metaData'], {}), '(metaData)\n', (1531, 1541), False, 'from level.views import LevelMetaDataOut, LevelMetaDataCreate, LevelMetaDatasOut\n'), ((1638, 1670), 'level.controllers.increment', 'level_controller.increment', (['ulid'], {}), '(ulid)\n', (1664, 1670), True, 'import level.controllers as level_controller\n'), ((692, 731), 'file.controllers.upload_file', 'file_controller.upload_file', (['levelFiles'], {}), '(levelFiles)\n', (719, 731), True, 'import file.controllers as file_controller\n'), ((1688, 1729), 'level.controllers.get_files_of_level', 'level_controller.get_files_of_level', (['ulid'], {}), '(ulid)\n', (1723, 1729), True, 'import level.controllers as level_controller\n'), ((1747, 1785), 'file.controllers.download_file', 'file_controller.download_file', (['file.id'], {}), '(file.id)\n', (1776, 1785), True, 'import file.controllers as file_controller\n')] |
#!/usr/bin/python3
# Copyright 2018 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
import os
import readline
import nltk
import tensorflow as tf
import numpy
from tflmlib import AttribContainer
from tflmlib import InputData
from tflmlib import LMBasic
from tflmlib import SNLPConnection
from tflmlib import Vocab
from configs import snlp_server
from configs import config
try: # python2/3 compatibility
input = raw_input
except NameError:
pass
class Processor(object):
def __init__(self, model_dir, tokenizer, strip_period):
self.snlp = SNLPConnection(snlp_server.port)
self.tokenizer = tokenizer
self.strip_period = strip_period
self.config = AttribContainer.fromJSON(os.path.join(model_dir, 'config.json'))
self.config.batch_size = 5
self.config.seq_length = 7
self.indata = InputData(self.config.batch_size, self.config.seq_length,
history_size=self.config.history_size)
self.vocab = Vocab(self.config.data_dir)
self.model, self.session = self.model_setup()
def predict(self, text):
# Tokenize / index words
sent = self.snlp.process(text)
tokens = self.tokenizer.tokenizeSentence(sent)
# Smart tokenizer automatically puts a '.' at the end of everything, so strip it
if self.strip_period and tokens[-1] == '.':
tokens = tokens[:-1]
indexes = self.vocab.toIndexes(tokens)
pad_len = self.indata.batch_size * self.config.seq_length - (
len(indexes) % self.indata.batch_size) + 1
indexes += [0] * pad_len
indexes = numpy.array(indexes)
self.indata.data_to_batches(indexes) # convert to 3D arrays for input to the model
self.indata.batches_per_epoch = self.indata.num_batches
self.indata.epoch_offset = 0
# Run the model and get back a flattened softmax list
probs = self.model.predict(self.session, self.indata)
probs = LMBasic.flattenProbs3D(probs)
# Find the most likely next words
maxes = numpy.argmax(probs, axis=1)
widx = len(tokens) - 1 # next predicted word for the last word in the sentence
next_words = self.vocab.toWords(list(range(probs.shape[1])))
next_probs = [probs[widx, i] for i in range(probs.shape[1])]
ret_data = sorted(zip(next_words, next_probs), key=lambda x: x[1], reverse=True)
return tokens, ret_data
def model_setup(self):
# Get the last checkpoint's filename
model_fn = LMBasic.get_model_fn(self.config.model_dir)
if not model_fn:
msg = "Could not open and/or read model from {}"
raise Exception(msg.format(self.config.model_dir))
print('Using model ', model_fn)
print()
# Setup the model
with tf.variable_scope("Model", reuse=False):
model_test = LMBasic(self.config, False)
# Restore the parameters
session = LMBasic.restore_session(model_fn)
return model_test, session
if __name__ == '__main__':
print('*' * 80)
print()
# Pick the vocabulary type
if 0: # Simple vocab
from tflmlib import TokenizerSimple
# model_dir = os.path.join(config.data_repo, 'L1_512_512-Simple')
model_dir = os.path.join(config.data_repo, 'L1_2048_512-Simple')
tokenizer = TokenizerSimple()
proc = Processor(model_dir, tokenizer, False)
else:
from tflmlib import TokenizerSmartA
# model_dir = os.path.join(config.data_repo, 'L1_512_512-SmartA')
model_dir = os.path.join(config.data_repo, 'L1_2048_512-SmartA')
dict_fn = config.sys_dict
tokenizer = TokenizerSmartA(dict_fn)
proc = Processor(model_dir, tokenizer, True)
print('Loading model/config from ', model_dir)
topn = 20
print('Enter a phrase and this will predict the next word')
print
while 1:
# Input the test phrase and correct next word
text = input('Match phrase > ')
if not text or text == 'q':
break
# Run the model to see what the most likely next words are
tokens, best_next_words = proc.predict(text)
print('Best matches for phrase : ', tokens)
for i, (word, prob) in enumerate(best_next_words):
print(' %8.2e : %s' % (prob, word))
if i >= topn - 1: break
print()
print()
| [
"tflmlib.LMBasic.get_model_fn",
"tflmlib.InputData",
"tflmlib.TokenizerSimple",
"tensorflow.variable_scope",
"tflmlib.LMBasic.restore_session",
"os.path.join",
"numpy.argmax",
"tflmlib.LMBasic",
"numpy.array",
"tflmlib.Vocab",
"tflmlib.SNLPConnection",
"tflmlib.TokenizerSmartA",
"tflmlib.LMB... | [((1119, 1151), 'tflmlib.SNLPConnection', 'SNLPConnection', (['snlp_server.port'], {}), '(snlp_server.port)\n', (1133, 1151), False, 'from tflmlib import SNLPConnection\n'), ((1407, 1508), 'tflmlib.InputData', 'InputData', (['self.config.batch_size', 'self.config.seq_length'], {'history_size': 'self.config.history_size'}), '(self.config.batch_size, self.config.seq_length, history_size=self\n .config.history_size)\n', (1416, 1508), False, 'from tflmlib import InputData\n'), ((1558, 1585), 'tflmlib.Vocab', 'Vocab', (['self.config.data_dir'], {}), '(self.config.data_dir)\n', (1563, 1585), False, 'from tflmlib import Vocab\n'), ((2194, 2214), 'numpy.array', 'numpy.array', (['indexes'], {}), '(indexes)\n', (2205, 2214), False, 'import numpy\n'), ((2550, 2579), 'tflmlib.LMBasic.flattenProbs3D', 'LMBasic.flattenProbs3D', (['probs'], {}), '(probs)\n', (2572, 2579), False, 'from tflmlib import LMBasic\n'), ((2645, 2672), 'numpy.argmax', 'numpy.argmax', (['probs'], {'axis': '(1)'}), '(probs, axis=1)\n', (2657, 2672), False, 'import numpy\n'), ((3128, 3171), 'tflmlib.LMBasic.get_model_fn', 'LMBasic.get_model_fn', (['self.config.model_dir'], {}), '(self.config.model_dir)\n', (3148, 3171), False, 'from tflmlib import LMBasic\n'), ((3561, 3594), 'tflmlib.LMBasic.restore_session', 'LMBasic.restore_session', (['model_fn'], {}), '(model_fn)\n', (3584, 3594), False, 'from tflmlib import LMBasic\n'), ((3888, 3940), 'os.path.join', 'os.path.join', (['config.data_repo', '"""L1_2048_512-Simple"""'], {}), "(config.data_repo, 'L1_2048_512-Simple')\n", (3900, 3940), False, 'import os\n'), ((3961, 3978), 'tflmlib.TokenizerSimple', 'TokenizerSimple', ([], {}), '()\n', (3976, 3978), False, 'from tflmlib import TokenizerSimple\n'), ((4181, 4233), 'os.path.join', 'os.path.join', (['config.data_repo', '"""L1_2048_512-SmartA"""'], {}), "(config.data_repo, 'L1_2048_512-SmartA')\n", (4193, 4233), False, 'import os\n'), ((4290, 4314), 'tflmlib.TokenizerSmartA', 'TokenizerSmartA', (['dict_fn'], {}), '(dict_fn)\n', (4305, 4314), False, 'from tflmlib import TokenizerSmartA\n'), ((1275, 1313), 'os.path.join', 'os.path.join', (['model_dir', '"""config.json"""'], {}), "(model_dir, 'config.json')\n", (1287, 1313), False, 'import os\n'), ((3416, 3455), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""Model"""'], {'reuse': '(False)'}), "('Model', reuse=False)\n", (3433, 3455), True, 'import tensorflow as tf\n'), ((3482, 3509), 'tflmlib.LMBasic', 'LMBasic', (['self.config', '(False)'], {}), '(self.config, False)\n', (3489, 3509), False, 'from tflmlib import LMBasic\n')] |
# !usr/bin/env python
# -*- coding: utf-8 -*-
#
# Licensed under a 3-clause BSD license.
#
# @Author: <NAME>
# @Date: 2018-10-11 17:51:43
# @Last modified by: <NAME>
# @Last Modified time: 2018-11-29 17:23:15
from __future__ import print_function, division, absolute_import
import numpy as np
import astropy
import astropy.units as u
import marvin.tools
from marvin.tools.quantities.spectrum import Spectrum
from marvin.utils.general.general import get_drpall_table
from marvin.utils.plot.scatter import plot as scatplot
from marvin import log
from .base import VACMixIn, VACTarget
def choose_best_spectrum(par1, par2, conf_thresh=0.1):
'''choose optimal HI spectrum based on the following criteria:
(1) If both detected and unconfused, choose highest SNR
(2) If both detected and both confused, choose lower confusion prob.
(3) If both detected and one confused, choose non-confused
(4) If one non-confused detection and one non-detection, go with detection
(5) If one confused detetion and one non-detection, go with non-detection
(6) If niether detected, choose lowest rms
par1 and par2 are dictionaries with the following parameters:
program - gbt or alfalfa
snr - integrated SNR
rms - rms noise level
conf_prob - confusion probability
conf_thresh = maximum confusion probability below which we classify
the object as essentially unconfused. Default to 0.1 following
(Stark+21)
'''
programs = [par1['program'],par2['program']]
sel_high_snr = np.argmax([par1['snr'],par2['snr']])
sel_low_rms = np.argmin([par1['rms'],par2['rms']])
sel_low_conf = np.argmin([par1['conf_prob'],par2['conf_prob']])
#both detected
if (par1['snr'] > 0) & (par2['snr'] > 0):
if (par1['conf_prob'] <= conf_thresh) & (par2['conf_prob'] <= conf_thresh):
pick = sel_high_snr
elif (par1['conf_prob'] <= conf_thresh) & (par2['conf_prob'] > conf_thresh):
pick = 0
elif (par1['conf_prob'] > conf_thresh) & (par2['conf_prob'] <= conf_thresh):
pick = 1
elif (par1['conf_prob'] > conf_thresh) & (par2['conf_prob'] > conf_thresh):
pick = sel_low_conf
#both nondetected
elif (par1['snr'] <= 0) & (par2['snr'] <= 0):
pick = sel_low_rms
#one detected
elif (par1['snr'] > 0) & (par2['snr'] <= 0):
if par1['conf_prob'] < conf_thresh:
pick=0
else:
pick=1
elif (par1['snr'] <= 0) & (par2['snr'] > 0):
if par2['conf_prob'] < conf_thresh:
pick=1
else:
pick=0
return programs[pick]
class HIVAC(VACMixIn):
"""Provides access to the MaNGA-HI VAC.
VAC name: HI
URL: https://www.sdss.org/dr17/data_access/value-added-catalogs/?vac_id=hi-manga-data-release-1
Description: Returns HI summary data and spectra
Authors: <NAME> and <NAME>
"""
# Required parameters
name = 'HI'
description = 'Returns HI summary data and spectra'
version = {'MPL-7': 'v1_0_1', 'DR15': 'v1_0_1', 'DR16': 'v1_0_2', 'DR17': 'v2_0_1', 'MPL-11': 'v2_0_1'}
display_name = 'HI'
url = 'https://www.sdss.org/dr17/data_access/value-added-catalogs/?vac_id=hi-manga-data-release-1'
# optional Marvin Tools to attach your vac to
include = (marvin.tools.cube.Cube, marvin.tools.maps.Maps, marvin.tools.modelcube.ModelCube)
# optional methods to attach to your main VAC tool in ~marvin.tools.vacs.VACs
add_methods = ['plot_mass_fraction']
# Required method
def set_summary_file(self, release):
''' Sets the path to the HI summary file '''
# define the variables to build a unique path to your VAC file
self.path_params = {'ver': self.version[release], 'type': 'all', 'program': 'GBT16A_095'}
# get_path returns False if the files do not exist locally
self.summary_file = self.get_path("mangahisum", path_params=self.path_params)
def set_program(self,plateifu):
# download the vac from the SAS if it does not already exist locally
if not self.file_exists(self.summary_file):
self.summary_file = self.download_vac('mangahisum', path_params=self.path_params)
# Find all entries in summary file with this plate-ifu.
# Need the full summary file data.
# Find best entry between GBT/ALFALFA based on dept and confusion.
# Then update self.path_params['program'] with alfalfa or gbt.
summary = HITarget(plateifu, vacfile=self.summary_file)._data
galinfo = summary[summary['plateifu'] == plateifu]
if len(galinfo) == 1 and galinfo['session']=='ALFALFA':
program = 'alfalfa'
elif len(galinfo) in [0, 1]:
# if no entry found or session is GBT, default program to gbt
program = 'gbt'
else:
par1 = {'program': 'gbt','snr': 0.,'rms': galinfo[0]['rms'], 'conf_prob': galinfo[0]['conf_prob']}
par2 = {'program': 'gbt','snr': 0.,'rms': galinfo[1]['rms'], 'conf_prob': galinfo[1]['conf_prob']}
if galinfo[0]['session']=='ALFALFA':
par1['program'] = 'alfalfa'
if galinfo[1]['session']=='ALFALFA':
par2['program'] = 'alfalfa'
if galinfo[0]['fhi'] > 0:
par1['snr'] = galinfo[0]['fhi']/galinfo[0]['efhi']
if galinfo[1]['fhi'] > 0:
par2['snr'] = galinfo[1]['fhi']/galinfo[1]['efhi']
program = choose_best_spectrum(par1,par2)
log.info('Using HI data from {0}'.format(program))
# get path to ancillary VAC file for target HI spectra
self.update_path_params({'program':program})
# Required method
def get_target(self, parent_object):
''' Accesses VAC data for a specific target from a Marvin Tool object '''
# get any parameters you need from the parent object
plateifu = parent_object.plateifu
self.update_path_params({'plateifu': plateifu})
if parent_object.release in ['DR17', 'MPL-11']:
self.set_program(plateifu)
specfile = self.get_path('mangahispectra', path_params=self.path_params)
# create container for more complex return data
hidata = HITarget(plateifu, vacfile=self.summary_file, specfile=specfile)
# get the spectral data for that row if it exists
if hidata._indata and not self.file_exists(specfile):
hidata._specfile = self.download_vac('mangahispectra', path_params=self.path_params)
return hidata
class HITarget(VACTarget):
''' A customized target class to also display HI spectra
This class handles data from both the HI summary file and the
individual spectral files. Row data from the summary file for the given target
is returned via the `data` property. Spectral data can be displayed via
the the `plot_spectrum` method.
Parameters:
targetid (str):
The plateifu or mangaid designation
vacfile (str):
The path of the VAC summary file
specfile (str):
The path to the HI spectra
Attributes:
data:
The target row data from the main VAC file
targetid (str):
The target identifier
'''
def __init__(self, targetid, vacfile, specfile=None):
super(HITarget, self).__init__(targetid, vacfile)
self._specfile = specfile
self._specdata = None
def plot_spectrum(self):
''' Plot the HI spectrum '''
if self._specfile:
if not self._specdata:
self._specdata = self._get_data(self._specfile)
vel = self._specdata['VHI'][0]
flux = self._specdata['FHI'][0]
spec = Spectrum(flux, unit=u.Jy, wavelength=vel,
wavelength_unit=u.km / u.s)
ax = spec.plot(
ylabel='HI\ Flux\ Density', xlabel='Velocity', title=self.targetid, ytrim='minmax'
)
return ax
return None
#
# Functions to become available on your VAC in marvin.tools.vacs.VACs
def plot_mass_fraction(vacdata_object):
''' Plot the HI mass fraction
Computes and plots the HI mass fraction using
the NSA elliptical Petrosian stellar mass from the
MaNGA DRPall file. Only plots data for subset of
targets in both the HI VAC and the DRPall file.
Parameters:
vacdata_object (object):
The `~.VACDataClass` instance of the HI VAC
Example:
>>> from marvin.tools.vacs import VACs
>>> v = VACs()
>>> hi = v.HI
>>> hi.plot_mass_fraction()
'''
drpall = get_drpall_table()
drpall.add_index('plateifu')
data = vacdata_object.data[1].data
subset = drpall.loc[data['plateifu']]
log_stmass = np.log10(subset['nsa_elpetro_mass'])
diff = data['logMHI'] - log_stmass
fig, axes = scatplot(
log_stmass,
diff,
with_hist=False,
ylim=[-5, 5],
xlabel=r'log $M_*$',
ylabel=r'log $M_{HI}/M_*$',
)
return axes[0]
| [
"numpy.log10",
"numpy.argmax",
"marvin.utils.general.general.get_drpall_table",
"marvin.utils.plot.scatter.plot",
"marvin.tools.quantities.spectrum.Spectrum",
"numpy.argmin"
] | [((1530, 1567), 'numpy.argmax', 'np.argmax', (["[par1['snr'], par2['snr']]"], {}), "([par1['snr'], par2['snr']])\n", (1539, 1567), True, 'import numpy as np\n'), ((1585, 1622), 'numpy.argmin', 'np.argmin', (["[par1['rms'], par2['rms']]"], {}), "([par1['rms'], par2['rms']])\n", (1594, 1622), True, 'import numpy as np\n'), ((1641, 1690), 'numpy.argmin', 'np.argmin', (["[par1['conf_prob'], par2['conf_prob']]"], {}), "([par1['conf_prob'], par2['conf_prob']])\n", (1650, 1690), True, 'import numpy as np\n'), ((8779, 8797), 'marvin.utils.general.general.get_drpall_table', 'get_drpall_table', ([], {}), '()\n', (8795, 8797), False, 'from marvin.utils.general.general import get_drpall_table\n'), ((8929, 8965), 'numpy.log10', 'np.log10', (["subset['nsa_elpetro_mass']"], {}), "(subset['nsa_elpetro_mass'])\n", (8937, 8965), True, 'import numpy as np\n'), ((9021, 9130), 'marvin.utils.plot.scatter.plot', 'scatplot', (['log_stmass', 'diff'], {'with_hist': '(False)', 'ylim': '[-5, 5]', 'xlabel': '"""log $M_*$"""', 'ylabel': '"""log $M_{HI}/M_*$"""'}), "(log_stmass, diff, with_hist=False, ylim=[-5, 5], xlabel=\n 'log $M_*$', ylabel='log $M_{HI}/M_*$')\n", (9029, 9130), True, 'from marvin.utils.plot.scatter import plot as scatplot\n'), ((7863, 7932), 'marvin.tools.quantities.spectrum.Spectrum', 'Spectrum', (['flux'], {'unit': 'u.Jy', 'wavelength': 'vel', 'wavelength_unit': '(u.km / u.s)'}), '(flux, unit=u.Jy, wavelength=vel, wavelength_unit=u.km / u.s)\n', (7871, 7932), False, 'from marvin.tools.quantities.spectrum import Spectrum\n')] |
import pathlib
from secret import API_KEY
PATH_ROOT = pathlib.Path(__file__).parent
PATH_REPLAYS_STUB = PATH_ROOT / "replays"
API_BASE = "https://osu.ppy.sh/api/"
API_REPLAY = API_BASE + "get_replay?k=" + API_KEY + "&m=0&b={}&u={}"
API_SCORES_ALL = API_BASE + "get_scores?k=" + API_KEY + "&m=0&b={}&limit={}"
API_SCORES_USER = API_BASE + "get_scores?k=" + API_KEY + "&m=0&b={}&u={}"
# cookiezi, ryuk, rafis, azr8, toy,
WHITELIST = ["124493", "6304246", "2558286", "2562987", "2757689"]
PATH_DB = PATH_ROOT / "db" / "cache.db" # /absolute/path/db/cache.db
VERSION = "1.1"
| [
"pathlib.Path"
] | [((56, 78), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (68, 78), False, 'import pathlib\n')] |
# -*- coding: utf-8 -*-
import logging
from speaklater import make_lazy_string
from quokka.modules.accounts.models import User
logger = logging.getLogger()
def lazy_str_setting(key, default=None):
from flask import current_app
return make_lazy_string(
lambda: current_app.config.get(key, default)
)
def get_current_user():
from flask.ext.security import current_user
try:
if not current_user.is_authenticated():
return None
except RuntimeError:
# Flask-Testing will fail
pass
try:
return User.objects.get(id=current_user.id)
except Exception as e:
logger.warning("No user found: %s" % e.message)
return None
| [
"logging.getLogger",
"quokka.modules.accounts.models.User.objects.get",
"flask.ext.security.current_user.is_authenticated",
"flask.current_app.config.get"
] | [((137, 156), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (154, 156), False, 'import logging\n'), ((574, 610), 'quokka.modules.accounts.models.User.objects.get', 'User.objects.get', ([], {'id': 'current_user.id'}), '(id=current_user.id)\n', (590, 610), False, 'from quokka.modules.accounts.models import User\n'), ((279, 315), 'flask.current_app.config.get', 'current_app.config.get', (['key', 'default'], {}), '(key, default)\n', (301, 315), False, 'from flask import current_app\n'), ((420, 451), 'flask.ext.security.current_user.is_authenticated', 'current_user.is_authenticated', ([], {}), '()\n', (449, 451), False, 'from flask.ext.security import current_user\n')] |
from __future__ import annotations
from parla.cpu_impl import cpu
from parla.task_runtime import get_current_devices, get_scheduler_context
from parla.device import Device
from .coherence import MemoryOperation, Coherence, CPU_INDEX
import threading
import numpy
try: # if the system has no GPU
import cupy
num_devices = cupy.cuda.runtime.getDeviceCount()
except (ImportError):
# PArray only considers numpy or cupy array
# work around of checking cupy.ndarray when cupy could not be imported
cupy = numpy
num_devices = 0
class PArray:
"""Multi-dimensional array on a CPU or CUDA device.
This class is a wrapper around :class:`numpy.ndarray` and :class:`cupy.ndarray`,
It is used to support Parla sheduler optimization and automatic data movement.
Args:
array: :class:`cupy.ndarray` or :class:`numpy.array` object
Note: some methods should be called within the current task context
"""
def __init__(self, array) -> None:
# _array works as a per device buffer of data
self._array = {n: None for n in range(num_devices)} # add gpu id
self._array[CPU_INDEX] = None # add cpu id
# get the array's location
if isinstance(array, numpy.ndarray):
location = CPU_INDEX
else:
location = int(array.device)
self._array[location] = array
self._coherence = Coherence(location, num_devices) # coherence protocol for managing data among multi device
self._coherence_lock = threading.Lock() # a lock to greb when update coherence and move data
self.size = array.size
self.nbytes = array.nbytes
# Register the parray with the scheduler
get_scheduler_context().scheduler._available_resources.track_parray(self)
# Properties:
@property
def array(self):
"""
The reference to cupy/numpy array on current device.
Note: should be called within the current task context
"""
return self._array[self._current_device_index]
@property
def _on_gpu(self) -> bool:
"""
True if the array is on GPU.
Note: should be called within the current task context
"""
return self._current_device_index != CPU_INDEX
@property
def _current_device_index(self) -> int:
"""
-1 if the current device is CPU.
Otherwise GPU ID.
Note: should be called within the current task context
"""
device = PArray._get_current_device()
if device.architecture == cpu:
return CPU_INDEX
else:
# assume GPU here, won't check device.architecture == gpu
# to avoid import `gpu`, which is slow to setup.
return device.index
# Public API:
def exists_on_device(self, device_id):
return (self._array[device_id] is not None)
def update(self, array) -> None:
""" Update the copy on current device.
Args:
array: :class:`cupy.ndarray` or :class:`numpy.array` object
Note: should be called within the current task context
Note: data should be put in OUT/INOUT fields of spawn
"""
self.size = array.size
self.nbytes = array.nbytes
this_device = self._current_device_index
if isinstance(array, numpy.ndarray):
if this_device != CPU_INDEX: # CPU to GPU
self._array[this_device] = cupy.asarray(array)
else: # data already in CPU
self._array[this_device] = array
else:
if this_device == CPU_INDEX: # GPU to CPU
self._array[this_device] = cupy.asnumpy(array)
else: # GPU to GPU
if int(array.device) == this_device: # data already in this device
self._array[this_device] = array
else: # GPU to GPU
dst_data = cupy.empty_like(array)
dst_data.data.copy_from_device_async(array.data, array.nbytes)
cupy.cuda.get_current_stream().synchronize()
self._array[this_device] = dst_data
def evict_all(self) -> None:
"""
Evict all copies from buffer, and clean all related fields
Note: this object should not be accessed anymore after called this method
"""
self._array = None
self._coherence = None
def evict(self, device_id: int = None, keep_one_copy: bool = True) -> None:
"""
Evict a device's copy and update coherence states.
Args:
device_id: if is this not None, data will be moved to this device,
else move to current device
keep_one_copy: if it is True and this is the last copy,
write it back to CPU before evict.
Note: if this device has the last copy and `keep_one_copy` is false,
the whole protocol state will be INVALID then.
And the system will lose the copy. Be careful when evict the last copy.
"""
if device_id is None:
device_id = self._current_device_index
with self._coherence_lock:
operations = self._coherence.evict(device_id, keep_one_copy)
for op in operations:
self._process_operation(op)
# Coherence update operations:
def _coherence_read(self, device_id: int = None) -> None:
""" Tell the coherence protocol a read happened on a device.
And do data movement based on the operations given by protocol.
Args:
device_id: if is this not None, data will be moved to this device,
else move to current device
Note: should be called within the current task context
"""
if device_id is None:
device_id = self._current_device_index
# update protocol and get operation
with self._coherence_lock:
operation = self._coherence.read(device_id)
self._process_operation(operation)
stream = cupy.cuda.get_current_stream()
# The coherence lock does not protect GPU calls.
# This could cause a data race when multiple readers on one data exist.
# LOAD operation is an asynchronous CUDA copy which does not block
# a CPU thread. This is problematic since other readers
# could trigger another LOAD operation from a location where
# it is still being copied. This stream synchronization blocks
# a CPU core until all copies are done.
# TODO(lhc): this synchronization overhead could be alleviated
# if we do static dependency analysis and allow
# ONLY siblings to simultaneously copy data
# without this synchronization.
# In this case, sync. is required for different levels
# on a task graph.
stream.synchronize()
def _coherence_write(self, device_id: int = None) -> None:
"""Tell the coherence protocol a write happened on a device.
And do data movement based on the operations given by protocol.
Args:
device_id: if is this not None, data will be moved to this device,
else move to current device
Note: should be called within the current task context
"""
if device_id is None:
device_id = self._current_device_index
# update protocol and get list of operations
# use lock to avoid race in between data movement and protocol updating
# TODO(Yineng): improve the lock or propose a lock free protocol
with self._coherence_lock:
operations = self._coherence.write(device_id)
for op in operations:
self._process_operation(op)
# Device management methods:
def _process_operation(self, operation: MemoryOperation) -> None:
"""
Process the given memory operations.
Data will be moved, and protocol states is kept unchanged.
"""
if operation.inst == MemoryOperation.NOOP:
return # do nothing
elif operation.inst == MemoryOperation.LOAD:
self._copy_data_between_device(operation.dst, operation.src)
elif operation.inst == MemoryOperation.EVICT:
self._array[operation.src] = None # decrement the reference counter, relying on GC to free the memory
elif operation.inst == MemoryOperation.ERROR:
raise RuntimeError(f"PArray gets invalid memory operation from coherence protocol, "
f"detail: opcode {operation.inst}, dst {operation.dst}, src {operation.src}")
else:
raise RuntimeError(f"PArray gets invalid memory operation from coherence protocol, "
f"detail: opcode {operation.inst}, dst {operation.dst}, src {operation.src}")
def _copy_data_between_device(self, dst, src) -> None:
"""
Copy data from src to dst.
"""
if src == dst:
return
elif src == CPU_INDEX: # copy from CPU to GPU
self._array[dst] = cupy.asarray(self._array[src])
elif dst != CPU_INDEX: # copy from GPU to GPU
src_data = self._array[src]
dst_data = cupy.empty_like(src_data)
dst_data.data.copy_from_device_async(src_data.data, src_data.nbytes)
cupy.cuda.stream.get_current_stream().synchronize()
self._array[dst] = dst_data
else: # copy from GPU to CPU
self._array[CPU_INDEX] = cupy.asnumpy(self._array[src])
@staticmethod
def _get_current_device() -> Device:
"""
Get current device from task environment.
Note: should be called within the current task context
"""
return get_current_devices()[0]
def _auto_move(self, device_id: int = None, do_write: bool = False) -> None:
""" Automatically move data to current device.
Multiple copies on different devices will be made based on coherence protocol.
Args:
device_id: current device id. CPU use CPU_INDEX as id
do_write: True if want make the device MO in coherence protocol
False if this is only for read only in current task
Note: should be called within the current task context
"""
if do_write:
self._coherence_write(device_id)
else:
self._coherence_read(device_id)
def _on_same_device(self, other: PArray) -> bool:
"""
Return True if the two PArrays are in the same device.
Note: other has to be a PArray object.
"""
this_device = self._current_device_index
return this_device in other._array and other._array[this_device] is not None
# NumPy/CuPy methods redirection
def __getattr__(self, item):
"""
A proxy method that redirect call to methods in :class:`numpy.ndarray` or :class:`cupy.ndarray`
"""
return getattr(self.array, item)
# Comparison operators:
def __lt__(x, y):
if isinstance(y, PArray):
if not x._on_same_device(y):
raise ValueError("Arrays are not on the same device")
return x.array.__lt__(y.array)
else:
return x.array.__lt__(y)
def __le__(x, y):
if isinstance(y, PArray):
if not x._on_same_device(y):
raise ValueError("Arrays are not on the same device")
return x.array.__le__(y.array)
else:
return x.array.__le__(y)
def __eq__(x, y):
if isinstance(y, PArray):
if not x._on_same_device(y):
raise ValueError("Arrays are not on the same device")
return x.array.__eq__(y.array)
else:
return x.array.__eq__(y)
def __ne__(x, y):
if isinstance(y, PArray):
if not x._on_same_device(y):
raise ValueError("Arrays are not on the same device")
return x.array.__ne__(y.array)
else:
return x.array.__ne__(y)
def __gt__(x, y):
if isinstance(y, PArray):
if not x._on_same_device(y):
raise ValueError("Arrays are not on the same device")
return x.array.__gt__(y.array)
else:
return x.array.__gt__(y)
def __ge__(x, y):
if isinstance(y, PArray):
if not x._on_same_device(y):
raise ValueError("Arrays are not on the same device")
return x.array.__ge__(y.array)
else:
return x.array.__ge__(y)
# Truth value of an array (bool):
def __nonzero__(self):
return PArray(self.array.__nonzero__())
# Unary operations:
def __neg__(self):
return PArray(self.array.__neg__())
def __pos__(self):
return PArray(self.array.__pos__())
def __abs__(self):
return PArray(self.array.__abs__())
def __invert__(self):
return PArray(self.array.__invert__())
# Arithmetic:
def __add__(x, y):
if isinstance(y, PArray):
if not x._on_same_device(y):
raise ValueError("Arrays are not on the same device")
return PArray(x.array + y.array)
else:
return PArray(x.array + y)
def __sub__(x, y):
if isinstance(y, PArray):
if not x._on_same_device(y):
raise ValueError("Arrays are not on the same device")
return PArray(x.array - y.array)
else:
return PArray(x.array - y)
def __mul__(x, y):
if isinstance(y, PArray):
if not x._on_same_device(y):
raise ValueError("Arrays are not on the same device")
return PArray(x.array * y.array)
else:
return PArray(x.array * y)
def __matmul__(x, y):
if isinstance(y, PArray):
if not x._on_same_device(y):
raise ValueError("Arrays are not on the same device")
return PArray(x.array @ y.array)
else:
return PArray(x.array @ y)
def __div__(x, y):
if isinstance(y, PArray):
if not x._on_same_device(y):
raise ValueError("Arrays are not on the same device")
return PArray(x.array / y.array)
else:
return PArray(x.array / y)
def __truediv__(x, y):
if isinstance(y, PArray):
if not x._on_same_device(y):
raise ValueError("Arrays are not on the same device")
return PArray(x.array / y.array)
else:
return PArray(x.array / y)
def __floordiv__(x, y):
if isinstance(y, PArray):
if not x._on_same_device(y):
raise ValueError("Arrays are not on the same device")
return PArray(x.array.__floordiv__(y.array))
else:
return PArray(x.array.__floordiv__(y))
def __mod__(x, y):
if isinstance(y, PArray):
if not x._on_same_device(y):
raise ValueError("Arrays are not on the same device")
return PArray(x.array.__mod__(y.array))
else:
return PArray(x.array.__mod__(y))
def __divmod__(x, y):
if isinstance(y, PArray):
if not x._on_same_device(y):
raise ValueError("Arrays are not on the same device")
return PArray(x.array.__divmod__(y.array))
else:
return PArray(x.array.__divmod__(y))
def __pow__(x, y, modulo):
if isinstance(y, PArray):
if not x._on_same_device(y):
raise ValueError("Arrays are not on the same device")
return PArray(x.array.__pow__(y.array))
else:
return PArray(x.array.__pow__(y))
def __lshift__(x, y):
if isinstance(y, PArray):
if not x._on_same_device(y):
raise ValueError("Arrays are not on the same device")
return PArray(x.array.__lshift__(y.array))
else:
return PArray(x.array.__lshift__(y))
def __rshift__(x, y):
if isinstance(y, PArray):
if not x._on_same_device(y):
raise ValueError("Arrays are not on the same device")
return PArray(x.array.__rshift__(y.array))
else:
return PArray(x.array.__rshift__(y))
def __and__(x, y):
if isinstance(y, PArray):
if not x._on_same_device(y):
raise ValueError("Arrays are not on the same device")
return PArray(x.array.__and__(y.array))
else:
return PArray(x.array.__and__(y))
def __or__(x, y):
if isinstance(y, PArray):
if not x._on_same_device(y):
raise ValueError("Arrays are not on the same device")
return PArray(x.array.__or__(y.array))
else:
return PArray(x.array.__or__(y))
def __xor__(x, y):
if isinstance(y, PArray):
if not x._on_same_device(y):
raise ValueError("Arrays are not on the same device")
return PArray(x.array.__xor__(y.array))
else:
return PArray(x.array.__xor__(y))
# Arithmetic, in-place:
def __iadd__(self, other):
if isinstance(other, PArray):
if not self._on_same_device(other):
raise ValueError("Arrays are not on the same device")
self.array.__iadd__(other.array)
else:
self.array.__iadd__(other)
return self
def __isub__(self, other):
if isinstance(other, PArray):
if not self._on_same_device(other):
raise ValueError("Arrays are not on the same device")
self.array.__isub__(other.array)
else:
self.array.__isub__(other)
return self
def __imul__(self, other):
if isinstance(other, PArray):
if not self._on_same_device(other):
raise ValueError("Arrays are not on the same device")
self.array.__imul__(other.array)
else:
self.array.__imul__(other)
return self
def __idiv__(self, other):
if isinstance(other, PArray):
if not self._on_same_device(other):
raise ValueError("Arrays are not on the same device")
self.array.__idiv__(other.array)
else:
self.array.__idiv__(other)
return self
def __itruediv__(self, other):
if isinstance(other, PArray):
if not self._on_same_device(other):
raise ValueError("Arrays are not on the same device")
self.array.__itruediv__(other.array)
else:
self.array.__itruediv__(other)
return self
def __ifloordiv__(self, other):
if isinstance(other, PArray):
if not self._on_same_device(other):
raise ValueError("Arrays are not on the same device")
self.array.__ifloordiv__(other.array)
else:
self.array.__ifloordiv__(other)
return self
def __imod__(self, other):
if isinstance(other, PArray):
if not self._on_same_device(other):
raise ValueError("Arrays are not on the same device")
self.array.__imod__(other.array)
else:
self.array.__imod__(other)
return self
def __ipow__(self, other):
if isinstance(other, PArray):
if not self._on_same_device(other):
raise ValueError("Arrays are not on the same device")
self.array.__ipow__(other.array)
else:
self.array.__ipow__(other)
return self
def __ilshift__(self, other):
if isinstance(other, PArray):
if not self._on_same_device(other):
raise ValueError("Arrays are not on the same device")
self.array.__ilshift__(other.array)
else:
self.array.__ilshift__(other)
return self
def __irshift__(self, other):
if isinstance(other, PArray):
if not self._on_same_device(other):
raise ValueError("Arrays are not on the same device")
self.array.__irshift__(other.array)
else:
self.array.__irshift__(other)
return self
def __iand__(self, other):
if isinstance(other, PArray):
if not self._on_same_device(other):
raise ValueError("Arrays are not on the same device")
self.array.__iand__(other.array)
else:
self.array.__iand__(other)
return self
def __ior__(self, other):
if isinstance(other, PArray):
if not self._on_same_device(other):
raise ValueError("Arrays are not on the same device")
self.array.__ior__(other.array)
else:
self.array.__ior__(other)
return self
def __ixor__(self, other):
if isinstance(other, PArray):
if not self._on_same_device(other):
raise ValueError("Arrays are not on the same device")
self.array.__ixor__(other.array)
else:
self.array.__ixor__(other)
return self
# Container customization:
def __iter__(self):
return self.array.__iter__()
def __len__(self):
return self.array.__len__()
def __getitem__(self, slices):
ret = self.array.__getitem__(slices)
# ndarray.__getitem__() may return a ndarray
if isinstance(ret, numpy.ndarray):
return PArray(ret)
elif isinstance(ret, cupy.ndarray):
if ret.shape == ():
return ret.item()
else:
return PArray(ret)
else:
return ret
def __setitem__(self, slices, value):
if isinstance(value, PArray):
self.array.__setitem__(slices, value.array)
else:
self.array.__setitem__(slices, value)
# Conversion:
def __int__(self):
return PArray(int(self.array.get()))
def __float__(self):
return PArray(float(self.array.get()))
def __complex__(self):
return PArray(complex(self.array.get()))
def __oct__(self):
return PArray(oct(self.array.get()))
def __hex__(self):
return PArray(hex(self.array.get()))
def __bytes__(self):
return PArray(bytes(self.array.get()))
# String representations:
def __repr__(self):
return repr(self._array)
def __str__(self):
return str(self._array)
def __format__(self, format_spec):
return self._array.__format__(format_spec)
| [
"cupy.asnumpy",
"cupy.empty_like",
"threading.Lock",
"parla.task_runtime.get_current_devices",
"parla.task_runtime.get_scheduler_context",
"cupy.cuda.runtime.getDeviceCount",
"cupy.cuda.stream.get_current_stream",
"cupy.cuda.get_current_stream",
"cupy.asarray"
] | [((333, 367), 'cupy.cuda.runtime.getDeviceCount', 'cupy.cuda.runtime.getDeviceCount', ([], {}), '()\n', (365, 367), False, 'import cupy\n'), ((1528, 1544), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (1542, 1544), False, 'import threading\n'), ((6110, 6140), 'cupy.cuda.get_current_stream', 'cupy.cuda.get_current_stream', ([], {}), '()\n', (6138, 6140), False, 'import cupy\n'), ((9960, 9981), 'parla.task_runtime.get_current_devices', 'get_current_devices', ([], {}), '()\n', (9979, 9981), False, 'from parla.task_runtime import get_current_devices, get_scheduler_context\n'), ((3478, 3497), 'cupy.asarray', 'cupy.asarray', (['array'], {}), '(array)\n', (3490, 3497), False, 'import cupy\n'), ((3698, 3717), 'cupy.asnumpy', 'cupy.asnumpy', (['array'], {}), '(array)\n', (3710, 3717), False, 'import cupy\n'), ((9283, 9313), 'cupy.asarray', 'cupy.asarray', (['self._array[src]'], {}), '(self._array[src])\n', (9295, 9313), False, 'import cupy\n'), ((3952, 3974), 'cupy.empty_like', 'cupy.empty_like', (['array'], {}), '(array)\n', (3967, 3974), False, 'import cupy\n'), ((9431, 9456), 'cupy.empty_like', 'cupy.empty_like', (['src_data'], {}), '(src_data)\n', (9446, 9456), False, 'import cupy\n'), ((9716, 9746), 'cupy.asnumpy', 'cupy.asnumpy', (['self._array[src]'], {}), '(self._array[src])\n', (9728, 9746), False, 'import cupy\n'), ((1724, 1747), 'parla.task_runtime.get_scheduler_context', 'get_scheduler_context', ([], {}), '()\n', (1745, 1747), False, 'from parla.task_runtime import get_current_devices, get_scheduler_context\n'), ((4078, 4108), 'cupy.cuda.get_current_stream', 'cupy.cuda.get_current_stream', ([], {}), '()\n', (4106, 4108), False, 'import cupy\n'), ((9550, 9587), 'cupy.cuda.stream.get_current_stream', 'cupy.cuda.stream.get_current_stream', ([], {}), '()\n', (9585, 9587), False, 'import cupy\n')] |
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.applications.inception_resnet_v2 import InceptionResNetV2
from tensorflow.keras.applications.inception_resnet_v2 import preprocess_input
from tensorflow.keras.optimizers import Adam
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
class TrainingPlot(keras.callbacks.Callback):
#source: https://github.com/kapil-varshney/utilities/blob/master/training_plot/trainingplot.py
def __init__(self, filename='/nfs/home/xwang/Keras_Transfer_Learning_June/output/training_plot_keras.png'):
self.filename = filename
# This function is called when the training begins
def on_train_begin(self, logs={}):
# Initialize the lists for holding the logs, losses and accuracies
self.losses = []
self.acc = []
self.val_losses = []
self.val_acc = []
self.logs = []
# This function is called at the end of each epoch
def on_epoch_end(self, epoch, logs={}):
# Append the logs, losses and accuracies to the lists
self.logs.append(logs)
self.losses.append(logs.get('loss'))
self.acc.append(logs.get('accuracy'))
self.val_losses.append(logs.get('val_loss'))
self.val_acc.append(logs.get('val_accuracy'))
#loss: 7.6934 - accuracy: 0.7840 - val_loss: 7.6934 - val_accuracy: 0.7837
# Before plotting ensure at least 2 epochs have passed
if len(self.losses) > 1:
N = np.arange(0, len(self.losses))
# You can chose the style of your preference
# print(plt.style.available) to see the available options
plt.style.use("seaborn")
# Plot train loss, train acc, val loss and val acc against epochs passed
plt.figure()
plt.plot(N, self.losses, label = "train_loss")
plt.plot(N, self.acc, label = "train_acc")
plt.plot(N, self.val_losses, label = "val_loss")
plt.plot(N, self.val_acc, label = "val_acc")
plt.title("Training Loss and Accuracy [Epoch {}]".format(epoch))
plt.xlabel("Epoch #")
plt.ylabel("Loss/Accuracy")
plt.legend()
# Make sure there exists a folder called output in the current directory
# or replace 'output' with whatever direcory you want to put in the plots
plt.savefig(self.filename)
plt.close()
if __name__ == "__main__":
# Data loading
dataset_Keras_PATH = "/nfs/home/xwang/Keras_Transfer_Learning_June/Dataset_Keras_Folder/"
kras_class_folder_path = "/nfs/home/xwang/Keras_Transfer_Learning_June/Dataset_Keras_Folder/class_kras/"
nokras_class_folder_path = "/nfs/home/xwang/Keras_Transfer_Learning_June/Dataset_Keras_Folder/class_nokras/"
# Create trainning dataset.
train_dataset = tf.keras.preprocessing.image_dataset_from_directory(dataset_Keras_PATH, validation_split=0.3, subset="training", seed=2020, batch_size=200, image_size=(512, 512))
# create validation dataset.
validation_dataset = tf.keras.preprocessing.image_dataset_from_directory(dataset_Keras_PATH, validation_split=0.3, subset="validation", seed=2020, batch_size=200,image_size=(512, 512))
# Instantiate a base model and load pre-trained weights into it
base_model = InceptionResNetV2(
include_top=False,
weights='imagenet',
input_shape=(512, 512, 3)
)
# Freeze base model
base_model.trainable = False
# - Create a new model on top of the output of one (or several) layers from the base model.
inputs = keras.Input(shape=(512, 512, 3))
x = base_model(inputs, training=False)
x = keras.layers.GlobalAveragePooling2D()(x)
x = keras.layers.Dropout(0.5)(x)
outputs = keras.layers.Dense(2, activation='softmax', name='softmax')(x)
current_model = keras.Model(inputs, outputs)
print(current_model.summary())
#Cross-entropy is the default loss function to use for binary classification problems.
#It is intended for use with binary classification where the target values are in the set {0, 1}.
#loss_fn = keras.losses.BinaryCrossentropy()
optimizer_adam = keras.optimizers.Adam(1e-3)#learning rate is default to 0.001
# Create an instance of the TrainingPlot class with the filename.
plot_losses = TrainingPlot()
epochs = 50
callbacks_plotloss = [
plot_losses
#keras.callbacks.ModelCheckpoint("save_at_{epoch}.h5"),
]
current_model.compile(
optimizer=optimizer_adam,
loss="binary_crossentropy",
metrics=["accuracy"],
)
#Configure the dataset for performance
train_dataset = train_dataset.prefetch(buffer_size=200)
validation_dataset = validation_dataset.prefetch(buffer_size=200)
#Train the model using callback to the TrainingPlot class object
current_model.fit(
train_dataset, epochs=epochs, callbacks=callbacks_plotloss, validation_data=validation_dataset,
) | [
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.ylabel",
"matplotlib.use",
"matplotlib.pyplot.xlabel",
"tensorflow.keras.layers.Dropout",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.style.use",
"tensorflow.keras.optimizers.Adam",
"matplotlib.pyplot.close",
"matplotlib.pyplot.figure",
"tensorflo... | [((294, 315), 'matplotlib.use', 'matplotlib.use', (['"""agg"""'], {}), "('agg')\n", (308, 315), False, 'import matplotlib\n'), ((2894, 3064), 'tensorflow.keras.preprocessing.image_dataset_from_directory', 'tf.keras.preprocessing.image_dataset_from_directory', (['dataset_Keras_PATH'], {'validation_split': '(0.3)', 'subset': '"""training"""', 'seed': '(2020)', 'batch_size': '(200)', 'image_size': '(512, 512)'}), "(dataset_Keras_PATH,\n validation_split=0.3, subset='training', seed=2020, batch_size=200,\n image_size=(512, 512))\n", (2945, 3064), True, 'import tensorflow as tf\n'), ((3116, 3288), 'tensorflow.keras.preprocessing.image_dataset_from_directory', 'tf.keras.preprocessing.image_dataset_from_directory', (['dataset_Keras_PATH'], {'validation_split': '(0.3)', 'subset': '"""validation"""', 'seed': '(2020)', 'batch_size': '(200)', 'image_size': '(512, 512)'}), "(dataset_Keras_PATH,\n validation_split=0.3, subset='validation', seed=2020, batch_size=200,\n image_size=(512, 512))\n", (3167, 3288), True, 'import tensorflow as tf\n'), ((3366, 3454), 'tensorflow.keras.applications.inception_resnet_v2.InceptionResNetV2', 'InceptionResNetV2', ([], {'include_top': '(False)', 'weights': '"""imagenet"""', 'input_shape': '(512, 512, 3)'}), "(include_top=False, weights='imagenet', input_shape=(512, \n 512, 3))\n", (3383, 3454), False, 'from tensorflow.keras.applications.inception_resnet_v2 import InceptionResNetV2\n'), ((3657, 3689), 'tensorflow.keras.Input', 'keras.Input', ([], {'shape': '(512, 512, 3)'}), '(shape=(512, 512, 3))\n', (3668, 3689), False, 'from tensorflow import keras\n'), ((3926, 3954), 'tensorflow.keras.Model', 'keras.Model', (['inputs', 'outputs'], {}), '(inputs, outputs)\n', (3937, 3954), False, 'from tensorflow import keras\n'), ((4254, 4282), 'tensorflow.keras.optimizers.Adam', 'keras.optimizers.Adam', (['(0.001)'], {}), '(0.001)\n', (4275, 4282), False, 'from tensorflow import keras\n'), ((3746, 3783), 'tensorflow.keras.layers.GlobalAveragePooling2D', 'keras.layers.GlobalAveragePooling2D', ([], {}), '()\n', (3781, 3783), False, 'from tensorflow import keras\n'), ((3795, 3820), 'tensorflow.keras.layers.Dropout', 'keras.layers.Dropout', (['(0.5)'], {}), '(0.5)\n', (3815, 3820), False, 'from tensorflow import keras\n'), ((3843, 3902), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['(2)'], {'activation': '"""softmax"""', 'name': '"""softmax"""'}), "(2, activation='softmax', name='softmax')\n", (3861, 3902), False, 'from tensorflow import keras\n'), ((1694, 1718), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""seaborn"""'], {}), "('seaborn')\n", (1707, 1718), True, 'import matplotlib.pyplot as plt\n'), ((1817, 1829), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1827, 1829), True, 'import matplotlib.pyplot as plt\n'), ((1842, 1886), 'matplotlib.pyplot.plot', 'plt.plot', (['N', 'self.losses'], {'label': '"""train_loss"""'}), "(N, self.losses, label='train_loss')\n", (1850, 1886), True, 'import matplotlib.pyplot as plt\n'), ((1901, 1941), 'matplotlib.pyplot.plot', 'plt.plot', (['N', 'self.acc'], {'label': '"""train_acc"""'}), "(N, self.acc, label='train_acc')\n", (1909, 1941), True, 'import matplotlib.pyplot as plt\n'), ((1956, 2002), 'matplotlib.pyplot.plot', 'plt.plot', (['N', 'self.val_losses'], {'label': '"""val_loss"""'}), "(N, self.val_losses, label='val_loss')\n", (1964, 2002), True, 'import matplotlib.pyplot as plt\n'), ((2017, 2059), 'matplotlib.pyplot.plot', 'plt.plot', (['N', 'self.val_acc'], {'label': '"""val_acc"""'}), "(N, self.val_acc, label='val_acc')\n", (2025, 2059), True, 'import matplotlib.pyplot as plt\n'), ((2151, 2172), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epoch #"""'], {}), "('Epoch #')\n", (2161, 2172), True, 'import matplotlib.pyplot as plt\n'), ((2185, 2212), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Loss/Accuracy"""'], {}), "('Loss/Accuracy')\n", (2195, 2212), True, 'import matplotlib.pyplot as plt\n'), ((2225, 2237), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2235, 2237), True, 'import matplotlib.pyplot as plt\n'), ((2421, 2447), 'matplotlib.pyplot.savefig', 'plt.savefig', (['self.filename'], {}), '(self.filename)\n', (2432, 2447), True, 'import matplotlib.pyplot as plt\n'), ((2460, 2471), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (2469, 2471), True, 'import matplotlib.pyplot as plt\n')] |
"""
File: bsd_patches.py
Author: Nrupatunga
Email: <EMAIL>
Github: https://github.com/nrupatunga
Description: BSDS500 patches
"""
import time
from pathlib import Path
import h5py
import numpy as np
from tqdm import tqdm
mode = 'train'
mat_root_dir = f'/media/nthere/datasets/DIV_superres/patches/train/'
out_root_dir = f'/home/nthere/2020/pytorch-deaf/data/train/'
read = True
if read:
root_dir = '/home/nthere/2020/pytorch-deaf/data/DIV_superres/hdf5/train/'
hdf5_files = Path(root_dir).rglob('*.hdf5')
images = []
means = []
stds = []
for i, f in tqdm(enumerate(hdf5_files)):
with h5py.File(f) as fout:
for j in range(10000):
image = fout['images_{}'.format(j)][()]
images.append(image)
if ((i + 1) % 10) == 0:
images = np.asarray(images)
means.append(np.mean(images, 0))
stds.append(np.std(images, 0))
del images
images = []
if (i == 90):
break
means = np.asarray(means)
stds = np.asarray(stds)
mean = np.mean(means, 1)
std = np.std(stds, 1)
else:
for i, mat_file in tqdm(enumerate(Path(mat_root_dir).glob('*.mat'))):
out_hdf5 = Path(out_root_dir).joinpath('{}.hdf5'.format(i))
with h5py.File(mat_file, 'r') as f, h5py.File(out_hdf5, 'w') as fout:
samples_data = np.asarray(list(f['samples']))
labels_data = np.asarray(list(f['labels']))
for i, data in enumerate(samples_data):
fout.create_dataset('images_{}'.format(i),
data=samples_data[i],
compression='gzip')
fout.create_dataset('labels_{}'.format(i),
data=labels_data[i],
compression='gzip')
| [
"numpy.mean",
"pathlib.Path",
"numpy.asarray",
"h5py.File",
"numpy.std"
] | [((1031, 1048), 'numpy.asarray', 'np.asarray', (['means'], {}), '(means)\n', (1041, 1048), True, 'import numpy as np\n'), ((1060, 1076), 'numpy.asarray', 'np.asarray', (['stds'], {}), '(stds)\n', (1070, 1076), True, 'import numpy as np\n'), ((1088, 1105), 'numpy.mean', 'np.mean', (['means', '(1)'], {}), '(means, 1)\n', (1095, 1105), True, 'import numpy as np\n'), ((1116, 1131), 'numpy.std', 'np.std', (['stds', '(1)'], {}), '(stds, 1)\n', (1122, 1131), True, 'import numpy as np\n'), ((485, 499), 'pathlib.Path', 'Path', (['root_dir'], {}), '(root_dir)\n', (489, 499), False, 'from pathlib import Path\n'), ((619, 631), 'h5py.File', 'h5py.File', (['f'], {}), '(f)\n', (628, 631), False, 'import h5py\n'), ((823, 841), 'numpy.asarray', 'np.asarray', (['images'], {}), '(images)\n', (833, 841), True, 'import numpy as np\n'), ((1294, 1318), 'h5py.File', 'h5py.File', (['mat_file', '"""r"""'], {}), "(mat_file, 'r')\n", (1303, 1318), False, 'import h5py\n'), ((1325, 1349), 'h5py.File', 'h5py.File', (['out_hdf5', '"""w"""'], {}), "(out_hdf5, 'w')\n", (1334, 1349), False, 'import h5py\n'), ((867, 885), 'numpy.mean', 'np.mean', (['images', '(0)'], {}), '(images, 0)\n', (874, 885), True, 'import numpy as np\n'), ((911, 928), 'numpy.std', 'np.std', (['images', '(0)'], {}), '(images, 0)\n', (917, 928), True, 'import numpy as np\n'), ((1232, 1250), 'pathlib.Path', 'Path', (['out_root_dir'], {}), '(out_root_dir)\n', (1236, 1250), False, 'from pathlib import Path\n'), ((1177, 1195), 'pathlib.Path', 'Path', (['mat_root_dir'], {}), '(mat_root_dir)\n', (1181, 1195), False, 'from pathlib import Path\n')] |
#
# (c) Copyright 2018 Hewlett Packard Enterprise Development LP
#
# 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.
#
"""Tests for the windlass.testing module"""
import logging
import unittest.mock
import fixtures
import testtools
import windlass.remotes
import windlass.testing
class TestFakeECRConnector(testtools.TestCase):
def test_upload_without_region(self):
# This test should eventually change to ensuring that not setting
# region causes a failure.
self.logger = self.useFixture(fixtures.FakeLogger(level=logging.DEBUG))
c = windlass.testing.FakeECRConnector(
windlass.remotes.AWSCreds('fake_user', 'fake_secret', None)
)
c.upload('fake_image:latest')
self.assertIn(
"Setting AWS region to 'test-region'", self.logger.output
)
def test_upload(self):
c = windlass.testing.FakeECRConnector(
windlass.remotes.AWSCreds(
'fake_user', 'fake_secret', 'fake-region'
)
)
img = 'fake_image:latest'
self.assertIn(img, c.upload(img))
class TestFakeAWSRemote(testtools.TestCase):
def test_windlass_upload(self):
"""Test multiprocessed windlass upload on FakeAWSRemote"""
artifacts = [
windlass.images.Image(
dict(name='some/image', version='1.0.0')
),
windlass.charts.Chart(
dict(name='some/chart', version='1.0.0')
),
windlass.generic.Generic(
dict(
name='some/generic', version='1.0.0',
filename='generic.bin'
)
),
]
windlass_obj = windlass.api.Windlass(
artifacts=windlass.api.Artifacts(artifacts=artifacts)
)
r = windlass.testing.FakeAWSRemote(
'fake_user', 'fake_secret', 'fake-region'
)
r.setup_docker()
r.setup_charts('fake_charts_bucket')
r.setup_generic('fake_generic_bucket')
# Patch the upload methods for charts & generics, at as low a level as
# possible.
# Note - using a custom None-returning patch function since the usual
# Mock object returned by patch() is not pickleable.
def pf(*args, **kwargs):
return None
with unittest.mock.patch(
'windlass.charts.Chart.export_stream', new=pf):
with unittest.mock.patch(
'windlass.generic.Generic.upload', new=pf):
windlass_obj.upload(
remote=r, charts_url='None', docker_image_registry='None',
generic_url='None',
)
| [
"fixtures.FakeLogger"
] | [((1014, 1054), 'fixtures.FakeLogger', 'fixtures.FakeLogger', ([], {'level': 'logging.DEBUG'}), '(level=logging.DEBUG)\n', (1033, 1054), False, 'import fixtures\n')] |
import asyncio
import copy
import discord
import feedparser
import sys
import time
import datetime
import traceback
import os
import json
from discord.ext import commands
from urllib.parse import urlparse, parse_qs
class Loop:
"""
Loop events.
"""
def __init__(self, bot):
self.bot = bot
bot.loop.create_task(self.start_update_loop())
print('Addon "{}" loaded'.format(self.__class__.__name__))
def __unload(self):
self.is_active = False
is_active = True
last_hour = datetime.datetime.now().hour
warning_time_period_ban = datetime.timedelta(minutes=30)
warning_time_period_mute = datetime.timedelta(minutes=10)
async def start_update_loop(self):
# thanks Luc#5653
await self.bot.wait_until_all_ready()
while self.is_active:
try:
timestamp = datetime.datetime.now()
timebans = copy.copy(self.bot.timebans)
timemutes = copy.copy(self.bot.timemutes)
for ban in timebans.items():
if timestamp > ban[1][1]:
self.bot.actions.append("tbr:" + ban[0])
await self.bot.unban(self.bot.server, ban[1][0])
msg = "⚠️ **Ban expired**: {} | {}#{}".format(ban[1][0].mention, self.bot.escape_name(ban[1][0].name), ban[1][0].discriminator)
await self.bot.send_message(self.bot.modlogs_channel, msg)
self.bot.timebans.pop(ban[0])
elif not ban[1][2]:
warning_time = ban[1][1] - self.warning_time_period_ban
if timestamp > warning_time:
ban[1][2] = True
await self.bot.send_message(self.bot.mods_channel, "**Note**: {} will be unbanned in {} minutes.".format(self.bot.escape_name(ban[1][0]), ((ban[1][1] - timestamp).seconds // 60) + 1))
for mute in timemutes.items():
if timestamp > mute[1][0]:
msg = "🔈 **Mute expired**: <@{}>".format(mute[0])
await self.bot.send_message(self.bot.modlogs_channel, msg)
self.bot.timemutes.pop(mute[0])
member = discord.utils.get(self.bot.server.members, id=mute[0])
if member:
await self.bot.remove_roles(member, self.bot.muted_role)
with open("data/timemutes.json", "r") as f:
timemutes_j = json.load(f)
try:
timemutes_j.pop(mute[0])
with open("data/timemutes.json", "w") as f:
json.dump(timemutes_j, f)
except KeyError:
pass
elif not mute[1][1]:
warning_time = mute[1][0] - self.warning_time_period_mute
if timestamp > warning_time:
mute[1][1] = True
await self.bot.send_message(self.bot.mods_channel, "**Note**: <@{}> will be unmuted in {} minutes.".format(mute[0], ((mute[1][0] - timestamp).seconds // 60) + 1))
if timestamp.minute == 0 and timestamp.hour != self.last_hour:
await self.bot.send_message(self.bot.helpers_channel, "{} has {:,} members at this hour!".format(self.bot.server.name, self.bot.server.member_count))
self.last_hour = timestamp.hour
if (timestamp.minute - 1) % 5 == 0 and timestamp.second == 0:
# ugly but it works
ninupdates_feed = feedparser.parse('https://yls8.mtheall.com/ninupdates/feed.php')
# ninupdates_feed = feedparser.parse('./feed.rss')
reported_systems = []
for entry in ninupdates_feed['entries']:
system, ver = entry['title'].split()
if system in reported_systems:
continue
reported_systems.append(system)
reporturl = entry['link']
reporturl_date = parse_qs(urlparse(reporturl).query)['date'][0]
reportpath = 'data/ninupdates/{}.json'.format(system)
to_write = {'reportdate': reporturl_date}
if not os.path.isfile(reportpath):
to_write['ver'] = ver
with open(reportpath, 'w') as f:
json.dump(to_write, f)
else:
with open(reportpath, 'r') as f:
oldver = json.load(f)
if oldver['reportdate'] != reporturl_date:
# "Reminder to not update until confirmed safe or known broken features are fixed."
if reporturl_date == ver:
await self.bot.send_message(self.bot.announcements_channel, '⏬ System updated detected for {}\n<{}>'.format(system, reporturl))
to_write['ver'] = reporturl_date
else:
await self.bot.send_message(self.bot.announcements_channel, '⏬ System updated detected for {}: {}\n<{}>'.format(system, ver, reporturl))
to_write['ver'] = ver
with open(reportpath, 'w') as f:
json.dump(to_write, f)
elif oldver['reportdate'] == oldver['ver'] and len(ver) != 17:
# lazy method of seeing if an update + vernumber was found before the bot caught the update in the first place
await self.bot.send_message(self.bot.announcements_channel, 'ℹ️ New update version for {}: {} ({})'.format(system, ver, reporturl_date))
to_write['ver'] = ver
with open(reportpath, 'w') as f:
json.dump(to_write, f)
except Exception as e:
print('Ignoring exception in start_update_loop', file=sys.stderr)
traceback.print_tb(e.__traceback__)
print('{0.__class__.__name__}: {0}'.format(e), file=sys.stderr)
finally:
await asyncio.sleep(1)
def setup(bot):
bot.add_cog(Loop(bot))
| [
"urllib.parse.urlparse",
"feedparser.parse",
"discord.utils.get",
"traceback.print_tb",
"copy.copy",
"os.path.isfile",
"datetime.datetime.now",
"asyncio.sleep",
"json.load",
"datetime.timedelta",
"json.dump"
] | [((590, 620), 'datetime.timedelta', 'datetime.timedelta', ([], {'minutes': '(30)'}), '(minutes=30)\n', (608, 620), False, 'import datetime\n'), ((652, 682), 'datetime.timedelta', 'datetime.timedelta', ([], {'minutes': '(10)'}), '(minutes=10)\n', (670, 682), False, 'import datetime\n'), ((530, 553), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (551, 553), False, 'import datetime\n'), ((870, 893), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (891, 893), False, 'import datetime\n'), ((921, 949), 'copy.copy', 'copy.copy', (['self.bot.timebans'], {}), '(self.bot.timebans)\n', (930, 949), False, 'import copy\n'), ((978, 1007), 'copy.copy', 'copy.copy', (['self.bot.timemutes'], {}), '(self.bot.timemutes)\n', (987, 1007), False, 'import copy\n'), ((3753, 3817), 'feedparser.parse', 'feedparser.parse', (['"""https://yls8.mtheall.com/ninupdates/feed.php"""'], {}), "('https://yls8.mtheall.com/ninupdates/feed.php')\n", (3769, 3817), False, 'import feedparser\n'), ((6439, 6474), 'traceback.print_tb', 'traceback.print_tb', (['e.__traceback__'], {}), '(e.__traceback__)\n', (6457, 6474), False, 'import traceback\n'), ((6598, 6614), 'asyncio.sleep', 'asyncio.sleep', (['(1)'], {}), '(1)\n', (6611, 6614), False, 'import asyncio\n'), ((2297, 2351), 'discord.utils.get', 'discord.utils.get', (['self.bot.server.members'], {'id': 'mute[0]'}), '(self.bot.server.members, id=mute[0])\n', (2314, 2351), False, 'import discord\n'), ((2582, 2594), 'json.load', 'json.load', (['f'], {}), '(f)\n', (2591, 2594), False, 'import json\n'), ((4514, 4540), 'os.path.isfile', 'os.path.isfile', (['reportpath'], {}), '(reportpath)\n', (4528, 4540), False, 'import os\n'), ((2781, 2806), 'json.dump', 'json.dump', (['timemutes_j', 'f'], {}), '(timemutes_j, f)\n', (2790, 2806), False, 'import json\n'), ((4685, 4707), 'json.dump', 'json.dump', (['to_write', 'f'], {}), '(to_write, f)\n', (4694, 4707), False, 'import json\n'), ((4840, 4852), 'json.load', 'json.load', (['f'], {}), '(f)\n', (4849, 4852), False, 'import json\n'), ((5701, 5723), 'json.dump', 'json.dump', (['to_write', 'f'], {}), '(to_write, f)\n', (5710, 5723), False, 'import json\n'), ((4301, 4320), 'urllib.parse.urlparse', 'urlparse', (['reporturl'], {}), '(reporturl)\n', (4309, 4320), False, 'from urllib.parse import urlparse, parse_qs\n'), ((6282, 6304), 'json.dump', 'json.dump', (['to_write', 'f'], {}), '(to_write, f)\n', (6291, 6304), False, 'import json\n')] |
from unittest.mock import Mock, patch
import pandas as pd
import pytest
from faker import Faker
from faker.config import DEFAULT_LOCALE
from rdt.transformers.numerical import NumericalTransformer
from sdv.constraints.base import Constraint
from sdv.constraints.errors import MissingConstraintColumnError
from sdv.errors import ConstraintsNotMetError
from sdv.metadata import Table
class TestTable:
def test__get_faker_default_locale(self):
"""Test that ``_get_faker`` without locales parameter has default locale.
The ``_get_faker`` should return a Faker object localized to the default locale.
When no locales are specified explicitly.
Input:
- Field metadata from metadata dict.
Output:
- Faker object with default localization.
"""
# Setup
metadata_dict = {
'fields': {
'foo': {
'type': 'categorical',
'pii': True,
'pii_category': 'company'
}
}
}
# Run
faker = Table.from_dict(metadata_dict)._get_faker(metadata_dict['fields']['foo'])
# Assert
assert isinstance(faker, Faker)
assert faker.locales == [DEFAULT_LOCALE]
def test__get_faker_specified_locales_string(self):
"""Test that ``_get_faker`` with locales parameter sets localization correctly.
The ``_get_faker`` should return a Faker object localized to the specified locale.
Input:
- Field metadata from metadata dict.
Output:
- Faker object with specified localization string.
"""
# Setup
metadata_dict = {
'fields': {
'foo': {
'type': 'categorical',
'pii': True,
'pii_category': 'company',
'pii_locales': 'sv_SE'
}
}
}
# Run
faker = Table.from_dict(metadata_dict)._get_faker(metadata_dict['fields']['foo'])
# Assert
assert isinstance(faker, Faker)
assert faker.locales == ['sv_SE']
def test__get_faker_specified_locales_list(self):
"""Test that ``_get_faker`` with locales parameter sets localization correctly.
The ``_get_faker`` should return a Faker object localized to the specified locales.
Input:
- Field metadata from metadata dict.
Output:
- Faker object with specified list of localizations.
"""
# Setup
metadata_dict = {
'fields': {
'foo': {
'type': 'categorical',
'pii': True,
'pii_category': 'company',
'pii_locales': ['en_US', 'sv_SE']
}
}
}
# Run
faker = Table.from_dict(metadata_dict)._get_faker(metadata_dict['fields']['foo'])
# Assert
assert isinstance(faker, Faker)
assert faker.locales == ['en_US', 'sv_SE']
def test__get_faker_method_pass_args(self):
"""Test that ``_get_faker_method`` method utilizes parameters passed in category argument.
The ``_get_faker_method`` method uses the parameters passed to it in the category argument.
Input:
- Faker object to create faked values with.
- Category tuple of category name and parameters passed to the method creating fake values.
Output:
- Fake values created with the specified method from the Faker object.
Utilizing the arguments given to it.
"""
# Setup
metadata_dict = {
'fields': {
'foo': {
'type': 'categorical',
'pii': True,
'pii_category': 'ean'
}
}
}
metadata = Table.from_dict(metadata_dict)
# Run
fake_8_ean = metadata._get_faker_method(Faker(), ('ean', 8))
ean_8 = fake_8_ean()
fake_13_ean = metadata._get_faker_method(Faker(), ('ean', 13))
ean_13 = fake_13_ean()
# Assert
assert len(ean_8) == 8
assert len(ean_13) == 13
@patch('sdv.metadata.Table')
def test__make_anonymization_mappings(self, mock_table):
"""Test that ``_make_anonymization_mappings`` creates the expected mappings.
The ``_make_anonymization_mappings`` method should map values in the original
data to fake values for non-id fields that are labeled pii.
Setup:
- Create a Table that has metadata about three fields (one pii field, one id field,
and one non-pii field).
Input:
- Data that contains a pii field, an id field, and a non-pii field.
Side Effects:
- Expect ``_get_fake_values`` to be called with the number of unique values of the
pii field.
- Expect the resulting `_ANONYMIZATION_MAPPINGS` field to contain the pii field, with
the correct number of mappings and keys.
"""
# Setup
metadata = Mock()
metadata._ANONYMIZATION_MAPPINGS = {}
foo_metadata = {
'type': 'categorical',
'pii': True,
'pii_category': 'email',
}
metadata._fields_metadata = {
'foo': foo_metadata,
'bar': {
'type': 'categorical',
},
'baz': {
'type': 'id',
}
}
foo_values = ['<EMAIL>', '<EMAIL>', '<EMAIL>']
data = pd.DataFrame({
'foo': foo_values,
'bar': ['a', 'b', 'c'],
'baz': [1, 2, 3],
})
# Run
Table._make_anonymization_mappings(metadata, data)
# Assert
assert mock_table._get_fake_values.called_once_with(foo_metadata, 3)
mappings = metadata._ANONYMIZATION_MAPPINGS[id(metadata)]
assert len(mappings) == 1
foo_mappings = mappings['foo']
assert len(foo_mappings) == 3
assert list(foo_mappings.keys()) == foo_values
@patch('sdv.metadata.Table')
def test__make_anonymization_mappings_unique_faked_value_in_field(self, mock_table):
"""Test that ``_make_anonymization_mappings`` method creates mappings for anonymized values.
The ``_make_anonymization_mappings`` method should map equal values in the original data
to the same faked value.
Input:
- DataFrame with a field that should be anonymized based on the metadata description.
Side Effect:
- Mappings are created from the original values to faked values.
"""
# Setup
metadata = Mock()
metadata._ANONYMIZATION_MAPPINGS = {}
foo_metadata = {
'type': 'categorical',
'pii': True,
'pii_category': 'email'
}
metadata._fields_metadata = {
'foo': foo_metadata
}
data = pd.DataFrame({
'foo': ['<EMAIL>', '<EMAIL>', '<EMAIL>']
})
# Run
Table._make_anonymization_mappings(metadata, data)
# Assert
assert mock_table._get_fake_values.called_once_with(foo_metadata, 2)
mappings = metadata._ANONYMIZATION_MAPPINGS[id(metadata)]
assert len(mappings) == 1
foo_mappings = mappings['foo']
assert len(foo_mappings) == 2
assert list(foo_mappings.keys()) == ['<EMAIL>', '<EMAIL>']
@patch.object(Constraint, 'from_dict')
def test__prepare_constraints_sorts_constraints(self, from_dict_mock):
"""Test that ``_prepare_constraints`` method sorts constraints.
The ``_prepare_constraints`` method should sort constraints by putting
constraints with ``rebuild_columns`` before the ones without them.
Input:
- list of constraints with some having ``rebuild_columns``
before constraints without them.
Output:
- List of constraints sorted properly.
"""
# Setup
constraint1 = Constraint(handling_strategy='transform')
constraint2 = Constraint(handling_strategy='transform')
constraint3 = Constraint(handling_strategy='reject_sampling')
constraints = [constraint1, constraint2, constraint3]
constraint1.rebuild_columns = ['a']
constraint2.rebuild_columns = ['b']
constraint3.rebuild_columns = []
from_dict_mock.side_effect = [constraint1, constraint2, constraint3]
# Run
sorted_constraints = Table._prepare_constraints(constraints)
# Asserts
assert sorted_constraints == [constraint3, constraint1, constraint2]
@patch.object(Constraint, 'from_dict')
def test__prepare_constraints_sorts_constraints_none_rebuild_columns(self, from_dict_mock):
"""Test that ``_prepare_constraints`` method sorts constraints.
The ``_prepare_constraints`` method should sort constraints with None as
``rebuild_columns`` before those that have them.
Input:
- list of constraints with some having None as ``rebuild_columns``
listed after those with ``rebuild_columns``.
Output:
- List of constraints sorted properly.
"""
# Setup
constraint1 = Constraint(handling_strategy='transform')
constraint2 = Constraint(handling_strategy='transform')
constraint3 = Constraint(handling_strategy='reject_sampling')
constraints = [constraint1, constraint2, constraint3]
constraint1.rebuild_columns = ['a']
constraint2.rebuild_columns = ['b']
constraint3.rebuild_columns = None
from_dict_mock.side_effect = [constraint1, constraint2, constraint3]
# Run
sorted_constraints = Table._prepare_constraints(constraints)
# Asserts
assert sorted_constraints == [constraint3, constraint1, constraint2]
@patch.object(Constraint, 'from_dict')
def test__prepare_constraints_validates_constraint_order(self, from_dict_mock):
"""Test the ``_prepare_constraints`` method validates the constraint order.
If no constraint has ``rebuild_columns`` that are in a later
constraint's ``constraint_columns``, no exception should be raised.
Input:
- List of constraints with none having ``rebuild_columns``
that are in a later constraint's ``constraint_columns``.
Output:
- Sorted list of constraints.
"""
# Setup
constraint1 = Constraint(handling_strategy='reject_sampling')
constraint2 = Constraint(handling_strategy='reject_sampling')
constraint3 = Constraint(handling_strategy='transform')
constraint4 = Constraint(handling_strategy='transform')
constraints = [constraint1, constraint2, constraint3, constraint4]
constraint3.rebuild_columns = ['e', 'd']
constraint4.constraint_columns = ['a', 'b', 'c']
constraint4.rebuild_columns = ['a']
from_dict_mock.side_effect = [constraint1, constraint2, constraint3, constraint4]
# Run
sorted_constraints = Table._prepare_constraints(constraints)
# Assert
assert sorted_constraints == constraints
@patch.object(Constraint, 'from_dict')
def test__prepare_constraints_invalid_order_raises_exception(self, from_dict_mock):
"""Test the ``_prepare_constraints`` method validates the constraint order.
If one constraint has ``rebuild_columns`` that are in a later
constraint's ``constraint_columns``, an exception should be raised.
Input:
- List of constraints with some having ``rebuild_columns``
that are in a later constraint's ``constraint_columns``.
Side Effect:
- Exception should be raised.
"""
# Setup
constraint1 = Constraint(handling_strategy='reject_sampling')
constraint2 = Constraint(handling_strategy='reject_sampling')
constraint3 = Constraint(handling_strategy='transform')
constraint4 = Constraint(handling_strategy='transform')
constraints = [constraint1, constraint2, constraint3, constraint4]
constraint3.rebuild_columns = ['a', 'd']
constraint4.constraint_columns = ['a', 'b', 'c']
constraint4.rebuild_columns = ['a']
from_dict_mock.side_effect = [constraint1, constraint2, constraint3, constraint4]
# Run
with pytest.raises(Exception):
Table._prepare_constraints(constraints)
@patch('sdv.metadata.table.rdt.transformers.NumericalTransformer',
spec_set=NumericalTransformer)
def test___init__(self, transformer_mock):
"""Test that ``__init__`` method passes parameters.
The ``__init__`` method should pass the custom parameters
to the ``NumericalTransformer``.
Input:
- rounding set to an int
- max_value set to an int
- min_value set to an int
Side Effects:
- ``NumericalTransformer`` should receive the correct parameters
"""
# Run
Table(rounding=-1, max_value=100, min_value=-50)
# Asserts
assert len(transformer_mock.mock_calls) == 2
transformer_mock.assert_any_call(
dtype=int, rounding=-1, max_value=100, min_value=-50)
transformer_mock.assert_any_call(
dtype=float, rounding=-1, max_value=100, min_value=-50)
@patch.object(Table, '_prepare_constraints')
def test___init__calls_prepare_constraints(self, _prepare_constraints_mock):
"""Test that ``__init__`` method calls ``_prepare_constraints"""
# Run
Table(constraints=[])
# Assert
_prepare_constraints_mock.called_once_with([])
def test__make_ids(self):
"""Test whether regex is correctly generating expressions."""
metadata = {'subtype': 'string', 'regex': '[a-d]'}
keys = Table._make_ids(metadata, 3)
assert (keys == pd.Series(['a', 'b', 'c'])).all()
def test__make_ids_fail(self):
"""Test if regex fails with more requested ids than available unique values."""
metadata = {'subtype': 'string', 'regex': '[a-d]'}
with pytest.raises(ValueError):
Table._make_ids(metadata, 20)
def test__make_ids_unique_field_not_unique(self):
"""Test that id column is replaced with all unique values if not already unique."""
metadata_dict = {
'fields': {
'item 0': {'type': 'id', 'subtype': 'integer'},
'item 1': {'type': 'boolean'}
},
'primary_key': 'item 0'
}
metadata = Table.from_dict(metadata_dict)
data = pd.DataFrame({
'item 0': [0, 1, 1, 2, 3, 5, 5, 6],
'item 1': [True, True, False, False, True, False, False, True]
})
new_data = metadata.make_ids_unique(data)
assert new_data['item 1'].equals(data['item 1'])
assert new_data['item 0'].is_unique
def test__make_ids_unique_field_already_unique(self):
"""Test that id column is kept if already unique."""
metadata_dict = {
'fields': {
'item 0': {'type': 'id', 'subtype': 'integer'},
'item 1': {'type': 'boolean'}
},
'primary_key': 'item 0'
}
metadata = Table.from_dict(metadata_dict)
data = pd.DataFrame({
'item 0': [9, 1, 8, 2, 3, 7, 5, 6],
'item 1': [True, True, False, False, True, False, False, True]
})
new_data = metadata.make_ids_unique(data)
assert new_data['item 1'].equals(data['item 1'])
assert new_data['item 0'].equals(data['item 0'])
def test__make_ids_unique_field_index_out_of_order(self):
"""Test that updated id column is unique even if index is out of order."""
metadata_dict = {
'fields': {
'item 0': {'type': 'id', 'subtype': 'integer'},
'item 1': {'type': 'boolean'}
},
'primary_key': 'item 0'
}
metadata = Table.from_dict(metadata_dict)
data = pd.DataFrame({
'item 0': [0, 1, 1, 2, 3, 5, 5, 6],
'item 1': [True, True, False, False, True, False, False, True]
}, index=[0, 1, 1, 2, 3, 5, 5, 6])
new_data = metadata.make_ids_unique(data)
assert new_data['item 1'].equals(data['item 1'])
assert new_data['item 0'].is_unique
def test_transform_calls__transform_constraints(self):
"""Test that the `transform` method calls `_transform_constraints` with right parameters
The ``transform`` method is expected to call the ``_transform_constraints`` method
with the data and correct value for ``on_missing_column``.
Input:
- Table data
Side Effects:
- Calls _transform_constraints
"""
# Setup
data = pd.DataFrame({
'item 0': [0, 1, 2],
'item 1': [True, True, False]
}, index=[0, 1, 2])
dtypes = {'item 0': 'int', 'item 1': 'bool'}
table_mock = Mock()
table_mock.get_dtypes.return_value = dtypes
table_mock._transform_constraints.return_value = data
table_mock._anonymize.return_value = data
table_mock._hyper_transformer.transform.return_value = data
# Run
Table.transform(table_mock, data, 'error')
# Assert
expected_data = pd.DataFrame({
'item 0': [0, 1, 2],
'item 1': [True, True, False]
}, index=[0, 1, 2])
mock_calls = table_mock._transform_constraints.mock_calls
args = mock_calls[0][1]
assert len(mock_calls) == 1
assert args[0].equals(expected_data)
assert args[1] == 'error'
def test__transform_constraints(self):
"""Test that method correctly transforms data based on constraints
The ``_transform_constraints`` method is expected to loop through constraints
and call each constraint's ``transform`` method on the data.
Input:
- Table data
Output:
- Transformed data
"""
# Setup
data = pd.DataFrame({
'item 0': [0, 1, 2],
'item 1': [3, 4, 5]
}, index=[0, 1, 2])
transformed_data = pd.DataFrame({
'item 0': [0, 0.5, 1],
'item 1': [6, 8, 10]
}, index=[0, 1, 2])
first_constraint_mock = Mock()
second_constraint_mock = Mock()
first_constraint_mock.transform.return_value = transformed_data
second_constraint_mock.return_value = transformed_data
table_mock = Mock()
table_mock._constraints = [first_constraint_mock, second_constraint_mock]
# Run
result = Table._transform_constraints(table_mock, data)
# Assert
assert result.equals(transformed_data)
first_constraint_mock.transform.assert_called_once_with(data)
second_constraint_mock.transform.assert_called_once_with(transformed_data)
def test__transform_constraints_raises_error(self):
"""Test that method raises error when specified.
The ``_transform_constraints`` method is expected to raise ``MissingConstraintColumnError``
if the constraint transform raises one and ``on_missing_column`` is set to error.
Input:
- Table data
Side Effects:
- MissingConstraintColumnError
"""
# Setup
data = pd.DataFrame({
'item 0': [0, 1, 2],
'item 1': [3, 4, 5]
}, index=[0, 1, 2])
constraint_mock = Mock()
constraint_mock.transform.side_effect = MissingConstraintColumnError
table_mock = Mock()
table_mock._constraints = [constraint_mock]
# Run/Assert
with pytest.raises(MissingConstraintColumnError):
Table._transform_constraints(table_mock, data, 'error')
def test__transform_constraints_drops_columns(self):
"""Test that method drops columns when specified.
The ``_transform_constraints`` method is expected to drop columns associated with
a constraint its transform raises a MissingConstraintColumnError and ``on_missing_column``
is set to drop.
Input:
- Table data
Output:
- Table with dropped columns
"""
# Setup
data = pd.DataFrame({
'item 0': [0, 1, 2],
'item 1': [3, 4, 5]
}, index=[0, 1, 2])
constraint_mock = Mock()
constraint_mock.transform.side_effect = MissingConstraintColumnError
constraint_mock.constraint_columns = ['item 0']
table_mock = Mock()
table_mock._constraints = [constraint_mock]
# Run
result = Table._transform_constraints(table_mock, data, 'drop')
# Assert
expected_result = pd.DataFrame({
'item 1': [3, 4, 5]
}, index=[0, 1, 2])
assert result.equals(expected_result)
def test__validate_data_on_constraints(self):
"""Test the ``Table._validate_data_on_constraints`` method.
Expect that the method returns True when the constraint columns are in the given data,
and the constraint.is_valid method returns True.
Input:
- Table data
Output:
- None
Side Effects:
- No error
"""
# Setup
data = pd.DataFrame({
'a': [0, 1, 2],
'b': [3, 4, 5]
}, index=[0, 1, 2])
constraint_mock = Mock()
constraint_mock.is_valid.return_value = pd.Series([True, True, True])
constraint_mock.constraint_columns = ['a', 'b']
table_mock = Mock()
table_mock._constraints = [constraint_mock]
# Run
result = Table._validate_data_on_constraints(table_mock, data)
# Assert
assert result is None
def test__validate_data_on_constraints_invalid_input(self):
"""Test the ``Table._validate_data_on_constraints`` method.
Expect that the method returns False when the constraint columns are in the given data,
and the constraint.is_valid method returns False for any row.
Input:
- Table data contains an invalid row
Output:
- None
Side Effects:
- A ConstraintsNotMetError is thrown
"""
# Setup
data = pd.DataFrame({
'a': [0, 1, 2],
'b': [3, 4, 5]
}, index=[0, 1, 2])
constraint_mock = Mock()
constraint_mock.is_valid.return_value = pd.Series([True, False, True])
constraint_mock.constraint_columns = ['a', 'b']
table_mock = Mock()
table_mock._constraints = [constraint_mock]
# Run and assert
with pytest.raises(ConstraintsNotMetError):
Table._validate_data_on_constraints(table_mock, data)
def test__validate_data_on_constraints_missing_cols(self):
"""Test the ``Table._validate_data_on_constraints`` method.
Expect that the method returns True when the constraint columns are not
in the given data.
Input:
- Table data that is missing a constraint column
Output:
- None
Side Effects:
- No error
"""
# Setup
data = pd.DataFrame({
'a': [0, 1, 2],
'b': [3, 4, 5]
}, index=[0, 1, 2])
constraint_mock = Mock()
constraint_mock.constraint_columns = ['a', 'b', 'c']
table_mock = Mock()
table_mock._constraints = [constraint_mock]
# Run
result = Table._validate_data_on_constraints(table_mock, data)
# Assert
assert result is None
def test_from_dict_min_max(self):
"""Test the ``Table.from_dict`` method.
Expect that when min_value and max_value are not provided,
they are set to 'auto'.
Input:
- A dictionary representing a table's metadata
Output:
- A Table object
"""
# Setup
metadata_dict = {
'fields': {
'item 0': {'type': 'id', 'subtype': 'integer'},
'item 1': {'type': 'boolean'}
},
'primary_key': 'item 0'
}
# Run
metadata = Table.from_dict(metadata_dict)
# Assert
assert metadata._transformer_templates['integer'].max_value == 'auto'
assert metadata._transformer_templates['integer'].min_value == 'auto'
assert metadata._transformer_templates['integer'].rounding == 'auto'
assert metadata._transformer_templates['float'].max_value == 'auto'
assert metadata._transformer_templates['float'].min_value == 'auto'
assert metadata._transformer_templates['float'].rounding == 'auto'
| [
"sdv.constraints.base.Constraint",
"pandas.Series",
"unittest.mock.Mock",
"sdv.metadata.Table.from_dict",
"sdv.metadata.Table._make_anonymization_mappings",
"sdv.metadata.Table._validate_data_on_constraints",
"sdv.metadata.Table",
"faker.Faker",
"sdv.metadata.Table._transform_constraints",
"sdv.me... | [((4250, 4277), 'unittest.mock.patch', 'patch', (['"""sdv.metadata.Table"""'], {}), "('sdv.metadata.Table')\n", (4255, 4277), False, 'from unittest.mock import Mock, patch\n'), ((6146, 6173), 'unittest.mock.patch', 'patch', (['"""sdv.metadata.Table"""'], {}), "('sdv.metadata.Table')\n", (6151, 6173), False, 'from unittest.mock import Mock, patch\n'), ((7525, 7562), 'unittest.mock.patch.object', 'patch.object', (['Constraint', '"""from_dict"""'], {}), "(Constraint, 'from_dict')\n", (7537, 7562), False, 'from unittest.mock import Mock, patch\n'), ((8732, 8769), 'unittest.mock.patch.object', 'patch.object', (['Constraint', '"""from_dict"""'], {}), "(Constraint, 'from_dict')\n", (8744, 8769), False, 'from unittest.mock import Mock, patch\n'), ((9966, 10003), 'unittest.mock.patch.object', 'patch.object', (['Constraint', '"""from_dict"""'], {}), "(Constraint, 'from_dict')\n", (9978, 10003), False, 'from unittest.mock import Mock, patch\n'), ((11288, 11325), 'unittest.mock.patch.object', 'patch.object', (['Constraint', '"""from_dict"""'], {}), "(Constraint, 'from_dict')\n", (11300, 11325), False, 'from unittest.mock import Mock, patch\n'), ((12575, 12676), 'unittest.mock.patch', 'patch', (['"""sdv.metadata.table.rdt.transformers.NumericalTransformer"""'], {'spec_set': 'NumericalTransformer'}), "('sdv.metadata.table.rdt.transformers.NumericalTransformer', spec_set=\n NumericalTransformer)\n", (12580, 12676), False, 'from unittest.mock import Mock, patch\n'), ((13489, 13532), 'unittest.mock.patch.object', 'patch.object', (['Table', '"""_prepare_constraints"""'], {}), "(Table, '_prepare_constraints')\n", (13501, 13532), False, 'from unittest.mock import Mock, patch\n'), ((3915, 3945), 'sdv.metadata.Table.from_dict', 'Table.from_dict', (['metadata_dict'], {}), '(metadata_dict)\n', (3930, 3945), False, 'from sdv.metadata import Table\n'), ((5138, 5144), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (5142, 5144), False, 'from unittest.mock import Mock, patch\n'), ((5614, 5689), 'pandas.DataFrame', 'pd.DataFrame', (["{'foo': foo_values, 'bar': ['a', 'b', 'c'], 'baz': [1, 2, 3]}"], {}), "({'foo': foo_values, 'bar': ['a', 'b', 'c'], 'baz': [1, 2, 3]})\n", (5626, 5689), True, 'import pandas as pd\n'), ((5760, 5810), 'sdv.metadata.Table._make_anonymization_mappings', 'Table._make_anonymization_mappings', (['metadata', 'data'], {}), '(metadata, data)\n', (5794, 5810), False, 'from sdv.metadata import Table\n'), ((6746, 6752), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (6750, 6752), False, 'from unittest.mock import Mock, patch\n'), ((7025, 7081), 'pandas.DataFrame', 'pd.DataFrame', (["{'foo': ['<EMAIL>', '<EMAIL>', '<EMAIL>']}"], {}), "({'foo': ['<EMAIL>', '<EMAIL>', '<EMAIL>']})\n", (7037, 7081), True, 'import pandas as pd\n'), ((7127, 7177), 'sdv.metadata.Table._make_anonymization_mappings', 'Table._make_anonymization_mappings', (['metadata', 'data'], {}), '(metadata, data)\n', (7161, 7177), False, 'from sdv.metadata import Table\n'), ((8102, 8143), 'sdv.constraints.base.Constraint', 'Constraint', ([], {'handling_strategy': '"""transform"""'}), "(handling_strategy='transform')\n", (8112, 8143), False, 'from sdv.constraints.base import Constraint\n'), ((8166, 8207), 'sdv.constraints.base.Constraint', 'Constraint', ([], {'handling_strategy': '"""transform"""'}), "(handling_strategy='transform')\n", (8176, 8207), False, 'from sdv.constraints.base import Constraint\n'), ((8230, 8277), 'sdv.constraints.base.Constraint', 'Constraint', ([], {'handling_strategy': '"""reject_sampling"""'}), "(handling_strategy='reject_sampling')\n", (8240, 8277), False, 'from sdv.constraints.base import Constraint\n'), ((8590, 8629), 'sdv.metadata.Table._prepare_constraints', 'Table._prepare_constraints', (['constraints'], {}), '(constraints)\n', (8616, 8629), False, 'from sdv.metadata import Table\n'), ((9334, 9375), 'sdv.constraints.base.Constraint', 'Constraint', ([], {'handling_strategy': '"""transform"""'}), "(handling_strategy='transform')\n", (9344, 9375), False, 'from sdv.constraints.base import Constraint\n'), ((9398, 9439), 'sdv.constraints.base.Constraint', 'Constraint', ([], {'handling_strategy': '"""transform"""'}), "(handling_strategy='transform')\n", (9408, 9439), False, 'from sdv.constraints.base import Constraint\n'), ((9462, 9509), 'sdv.constraints.base.Constraint', 'Constraint', ([], {'handling_strategy': '"""reject_sampling"""'}), "(handling_strategy='reject_sampling')\n", (9472, 9509), False, 'from sdv.constraints.base import Constraint\n'), ((9824, 9863), 'sdv.metadata.Table._prepare_constraints', 'Table._prepare_constraints', (['constraints'], {}), '(constraints)\n', (9850, 9863), False, 'from sdv.metadata import Table\n'), ((10570, 10617), 'sdv.constraints.base.Constraint', 'Constraint', ([], {'handling_strategy': '"""reject_sampling"""'}), "(handling_strategy='reject_sampling')\n", (10580, 10617), False, 'from sdv.constraints.base import Constraint\n'), ((10640, 10687), 'sdv.constraints.base.Constraint', 'Constraint', ([], {'handling_strategy': '"""reject_sampling"""'}), "(handling_strategy='reject_sampling')\n", (10650, 10687), False, 'from sdv.constraints.base import Constraint\n'), ((10710, 10751), 'sdv.constraints.base.Constraint', 'Constraint', ([], {'handling_strategy': '"""transform"""'}), "(handling_strategy='transform')\n", (10720, 10751), False, 'from sdv.constraints.base import Constraint\n'), ((10774, 10815), 'sdv.constraints.base.Constraint', 'Constraint', ([], {'handling_strategy': '"""transform"""'}), "(handling_strategy='transform')\n", (10784, 10815), False, 'from sdv.constraints.base import Constraint\n'), ((11175, 11214), 'sdv.metadata.Table._prepare_constraints', 'Table._prepare_constraints', (['constraints'], {}), '(constraints)\n', (11201, 11214), False, 'from sdv.metadata import Table\n'), ((11902, 11949), 'sdv.constraints.base.Constraint', 'Constraint', ([], {'handling_strategy': '"""reject_sampling"""'}), "(handling_strategy='reject_sampling')\n", (11912, 11949), False, 'from sdv.constraints.base import Constraint\n'), ((11972, 12019), 'sdv.constraints.base.Constraint', 'Constraint', ([], {'handling_strategy': '"""reject_sampling"""'}), "(handling_strategy='reject_sampling')\n", (11982, 12019), False, 'from sdv.constraints.base import Constraint\n'), ((12042, 12083), 'sdv.constraints.base.Constraint', 'Constraint', ([], {'handling_strategy': '"""transform"""'}), "(handling_strategy='transform')\n", (12052, 12083), False, 'from sdv.constraints.base import Constraint\n'), ((12106, 12147), 'sdv.constraints.base.Constraint', 'Constraint', ([], {'handling_strategy': '"""transform"""'}), "(handling_strategy='transform')\n", (12116, 12147), False, 'from sdv.constraints.base import Constraint\n'), ((13144, 13192), 'sdv.metadata.Table', 'Table', ([], {'rounding': '(-1)', 'max_value': '(100)', 'min_value': '(-50)'}), '(rounding=-1, max_value=100, min_value=-50)\n', (13149, 13192), False, 'from sdv.metadata import Table\n'), ((13709, 13730), 'sdv.metadata.Table', 'Table', ([], {'constraints': '[]'}), '(constraints=[])\n', (13714, 13730), False, 'from sdv.metadata import Table\n'), ((13979, 14007), 'sdv.metadata.Table._make_ids', 'Table._make_ids', (['metadata', '(3)'], {}), '(metadata, 3)\n', (13994, 14007), False, 'from sdv.metadata import Table\n'), ((14718, 14748), 'sdv.metadata.Table.from_dict', 'Table.from_dict', (['metadata_dict'], {}), '(metadata_dict)\n', (14733, 14748), False, 'from sdv.metadata import Table\n'), ((14764, 14883), 'pandas.DataFrame', 'pd.DataFrame', (["{'item 0': [0, 1, 1, 2, 3, 5, 5, 6], 'item 1': [True, True, False, False, \n True, False, False, True]}"], {}), "({'item 0': [0, 1, 1, 2, 3, 5, 5, 6], 'item 1': [True, True, \n False, False, True, False, False, True]})\n", (14776, 14883), True, 'import pandas as pd\n'), ((15426, 15456), 'sdv.metadata.Table.from_dict', 'Table.from_dict', (['metadata_dict'], {}), '(metadata_dict)\n', (15441, 15456), False, 'from sdv.metadata import Table\n'), ((15472, 15591), 'pandas.DataFrame', 'pd.DataFrame', (["{'item 0': [9, 1, 8, 2, 3, 7, 5, 6], 'item 1': [True, True, False, False, \n True, False, False, True]}"], {}), "({'item 0': [9, 1, 8, 2, 3, 7, 5, 6], 'item 1': [True, True, \n False, False, True, False, False, True]})\n", (15484, 15591), True, 'import pandas as pd\n'), ((16173, 16203), 'sdv.metadata.Table.from_dict', 'Table.from_dict', (['metadata_dict'], {}), '(metadata_dict)\n', (16188, 16203), False, 'from sdv.metadata import Table\n'), ((16219, 16370), 'pandas.DataFrame', 'pd.DataFrame', (["{'item 0': [0, 1, 1, 2, 3, 5, 5, 6], 'item 1': [True, True, False, False, \n True, False, False, True]}"], {'index': '[0, 1, 1, 2, 3, 5, 5, 6]'}), "({'item 0': [0, 1, 1, 2, 3, 5, 5, 6], 'item 1': [True, True, \n False, False, True, False, False, True]}, index=[0, 1, 1, 2, 3, 5, 5, 6])\n", (16231, 16370), True, 'import pandas as pd\n'), ((17010, 17097), 'pandas.DataFrame', 'pd.DataFrame', (["{'item 0': [0, 1, 2], 'item 1': [True, True, False]}"], {'index': '[0, 1, 2]'}), "({'item 0': [0, 1, 2], 'item 1': [True, True, False]}, index=[0,\n 1, 2])\n", (17022, 17097), True, 'import pandas as pd\n'), ((17202, 17208), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (17206, 17208), False, 'from unittest.mock import Mock, patch\n'), ((17464, 17506), 'sdv.metadata.Table.transform', 'Table.transform', (['table_mock', 'data', '"""error"""'], {}), "(table_mock, data, 'error')\n", (17479, 17506), False, 'from sdv.metadata import Table\n'), ((17549, 17636), 'pandas.DataFrame', 'pd.DataFrame', (["{'item 0': [0, 1, 2], 'item 1': [True, True, False]}"], {'index': '[0, 1, 2]'}), "({'item 0': [0, 1, 2], 'item 1': [True, True, False]}, index=[0,\n 1, 2])\n", (17561, 17636), True, 'import pandas as pd\n'), ((18278, 18351), 'pandas.DataFrame', 'pd.DataFrame', (["{'item 0': [0, 1, 2], 'item 1': [3, 4, 5]}"], {'index': '[0, 1, 2]'}), "({'item 0': [0, 1, 2], 'item 1': [3, 4, 5]}, index=[0, 1, 2])\n", (18290, 18351), True, 'import pandas as pd\n'), ((18413, 18489), 'pandas.DataFrame', 'pd.DataFrame', (["{'item 0': [0, 0.5, 1], 'item 1': [6, 8, 10]}"], {'index': '[0, 1, 2]'}), "({'item 0': [0, 0.5, 1], 'item 1': [6, 8, 10]}, index=[0, 1, 2])\n", (18425, 18489), True, 'import pandas as pd\n'), ((18556, 18562), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (18560, 18562), False, 'from unittest.mock import Mock, patch\n'), ((18596, 18602), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (18600, 18602), False, 'from unittest.mock import Mock, patch\n'), ((18759, 18765), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (18763, 18765), False, 'from unittest.mock import Mock, patch\n'), ((18880, 18926), 'sdv.metadata.Table._transform_constraints', 'Table._transform_constraints', (['table_mock', 'data'], {}), '(table_mock, data)\n', (18908, 18926), False, 'from sdv.metadata import Table\n'), ((19591, 19664), 'pandas.DataFrame', 'pd.DataFrame', (["{'item 0': [0, 1, 2], 'item 1': [3, 4, 5]}"], {'index': '[0, 1, 2]'}), "({'item 0': [0, 1, 2], 'item 1': [3, 4, 5]}, index=[0, 1, 2])\n", (19603, 19664), True, 'import pandas as pd\n'), ((19725, 19731), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (19729, 19731), False, 'from unittest.mock import Mock, patch\n'), ((19830, 19836), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (19834, 19836), False, 'from unittest.mock import Mock, patch\n'), ((20500, 20573), 'pandas.DataFrame', 'pd.DataFrame', (["{'item 0': [0, 1, 2], 'item 1': [3, 4, 5]}"], {'index': '[0, 1, 2]'}), "({'item 0': [0, 1, 2], 'item 1': [3, 4, 5]}, index=[0, 1, 2])\n", (20512, 20573), True, 'import pandas as pd\n'), ((20634, 20640), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (20638, 20640), False, 'from unittest.mock import Mock, patch\n'), ((20795, 20801), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (20799, 20801), False, 'from unittest.mock import Mock, patch\n'), ((20886, 20940), 'sdv.metadata.Table._transform_constraints', 'Table._transform_constraints', (['table_mock', 'data', '"""drop"""'], {}), "(table_mock, data, 'drop')\n", (20914, 20940), False, 'from sdv.metadata import Table\n'), ((20985, 21037), 'pandas.DataFrame', 'pd.DataFrame', (["{'item 1': [3, 4, 5]}"], {'index': '[0, 1, 2]'}), "({'item 1': [3, 4, 5]}, index=[0, 1, 2])\n", (20997, 21037), True, 'import pandas as pd\n'), ((21530, 21593), 'pandas.DataFrame', 'pd.DataFrame', (["{'a': [0, 1, 2], 'b': [3, 4, 5]}"], {'index': '[0, 1, 2]'}), "({'a': [0, 1, 2], 'b': [3, 4, 5]}, index=[0, 1, 2])\n", (21542, 21593), True, 'import pandas as pd\n'), ((21654, 21660), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (21658, 21660), False, 'from unittest.mock import Mock, patch\n'), ((21709, 21738), 'pandas.Series', 'pd.Series', (['[True, True, True]'], {}), '([True, True, True])\n', (21718, 21738), True, 'import pandas as pd\n'), ((21816, 21822), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (21820, 21822), False, 'from unittest.mock import Mock, patch\n'), ((21907, 21960), 'sdv.metadata.Table._validate_data_on_constraints', 'Table._validate_data_on_constraints', (['table_mock', 'data'], {}), '(table_mock, data)\n', (21942, 21960), False, 'from sdv.metadata import Table\n'), ((22511, 22574), 'pandas.DataFrame', 'pd.DataFrame', (["{'a': [0, 1, 2], 'b': [3, 4, 5]}"], {'index': '[0, 1, 2]'}), "({'a': [0, 1, 2], 'b': [3, 4, 5]}, index=[0, 1, 2])\n", (22523, 22574), True, 'import pandas as pd\n'), ((22635, 22641), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (22639, 22641), False, 'from unittest.mock import Mock, patch\n'), ((22690, 22720), 'pandas.Series', 'pd.Series', (['[True, False, True]'], {}), '([True, False, True])\n', (22699, 22720), True, 'import pandas as pd\n'), ((22798, 22804), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (22802, 22804), False, 'from unittest.mock import Mock, patch\n'), ((23429, 23492), 'pandas.DataFrame', 'pd.DataFrame', (["{'a': [0, 1, 2], 'b': [3, 4, 5]}"], {'index': '[0, 1, 2]'}), "({'a': [0, 1, 2], 'b': [3, 4, 5]}, index=[0, 1, 2])\n", (23441, 23492), True, 'import pandas as pd\n'), ((23553, 23559), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (23557, 23559), False, 'from unittest.mock import Mock, patch\n'), ((23642, 23648), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (23646, 23648), False, 'from unittest.mock import Mock, patch\n'), ((23733, 23786), 'sdv.metadata.Table._validate_data_on_constraints', 'Table._validate_data_on_constraints', (['table_mock', 'data'], {}), '(table_mock, data)\n', (23768, 23786), False, 'from sdv.metadata import Table\n'), ((24417, 24447), 'sdv.metadata.Table.from_dict', 'Table.from_dict', (['metadata_dict'], {}), '(metadata_dict)\n', (24432, 24447), False, 'from sdv.metadata import Table\n'), ((4009, 4016), 'faker.Faker', 'Faker', ([], {}), '()\n', (4014, 4016), False, 'from faker import Faker\n'), ((4109, 4116), 'faker.Faker', 'Faker', ([], {}), '()\n', (4114, 4116), False, 'from faker import Faker\n'), ((12491, 12515), 'pytest.raises', 'pytest.raises', (['Exception'], {}), '(Exception)\n', (12504, 12515), False, 'import pytest\n'), ((12529, 12568), 'sdv.metadata.Table._prepare_constraints', 'Table._prepare_constraints', (['constraints'], {}), '(constraints)\n', (12555, 12568), False, 'from sdv.metadata import Table\n'), ((14262, 14287), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (14275, 14287), False, 'import pytest\n'), ((14301, 14330), 'sdv.metadata.Table._make_ids', 'Table._make_ids', (['metadata', '(20)'], {}), '(metadata, 20)\n', (14316, 14330), False, 'from sdv.metadata import Table\n'), ((19924, 19967), 'pytest.raises', 'pytest.raises', (['MissingConstraintColumnError'], {}), '(MissingConstraintColumnError)\n', (19937, 19967), False, 'import pytest\n'), ((19981, 20036), 'sdv.metadata.Table._transform_constraints', 'Table._transform_constraints', (['table_mock', 'data', '"""error"""'], {}), "(table_mock, data, 'error')\n", (20009, 20036), False, 'from sdv.metadata import Table\n'), ((22896, 22933), 'pytest.raises', 'pytest.raises', (['ConstraintsNotMetError'], {}), '(ConstraintsNotMetError)\n', (22909, 22933), False, 'import pytest\n'), ((22947, 23000), 'sdv.metadata.Table._validate_data_on_constraints', 'Table._validate_data_on_constraints', (['table_mock', 'data'], {}), '(table_mock, data)\n', (22982, 23000), False, 'from sdv.metadata import Table\n'), ((1096, 1126), 'sdv.metadata.Table.from_dict', 'Table.from_dict', (['metadata_dict'], {}), '(metadata_dict)\n', (1111, 1126), False, 'from sdv.metadata import Table\n'), ((1992, 2022), 'sdv.metadata.Table.from_dict', 'Table.from_dict', (['metadata_dict'], {}), '(metadata_dict)\n', (2007, 2022), False, 'from sdv.metadata import Table\n'), ((2893, 2923), 'sdv.metadata.Table.from_dict', 'Table.from_dict', (['metadata_dict'], {}), '(metadata_dict)\n', (2908, 2923), False, 'from sdv.metadata import Table\n'), ((14032, 14058), 'pandas.Series', 'pd.Series', (["['a', 'b', 'c']"], {}), "(['a', 'b', 'c'])\n", (14041, 14058), True, 'import pandas as pd\n')] |
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import os
from pymatgen import Composition
class TransformReadingPeriodicTable():
def __init__(self, formula=None, rel_cif_file_path='write cif file path', data_dir='../data'):
self.formula = formula
self.allowed_elements_list = ['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl', 'Ar', 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr', 'Rb', 'Sr', 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'In', 'Sn', 'Sb', 'Te', 'I', 'Xe', 'Cs', 'Ba', 'La',
'Ce', 'Pr', 'Nd', 'Pm', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', 'Lu', 'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg', 'Tl', 'Pb', 'Bi', 'Po', 'At', 'Rn', 'Fr', 'Ra', 'Ac', 'Th', 'Pa', 'U', 'Np', 'Pu', 'Am', 'Cm', 'Bk', 'Cf', 'Es', 'Fm', 'Md', 'No', 'Lr', 'Rf', 'Db', 'Sg', 'Bh', 'Hs', 'Mt', 'Ds', 'Rg', 'Cn', 'Nh', 'Fl', 'Mc', 'Lv', 'Ts', 'Og']
def formula_to_periodic_table(self):
def channel(x, y):
'''
x: horizontal
y: vertical
'''
# f 14, d 10, p 6
x, y = x+1, y+1 # changing to start from 1. 1 is the origin
if y == 1 or x <= 2:
channel = 0 # s
elif 27 <= x:
channel = 1 # p
elif x == 3 or (3 + 14+1 <= x and x <= 17 + 9):
channel = 2 # d
elif 4 <= x and x <= 17:
channel = 3 # f
else:
print("error in making channel in period_table_as_img")
return channel
dict_formula = Composition(self.formula).as_dict()
coordinate = np.zeros([4, 7, 18 + 14], dtype=np.float32)
for key, value in dict_formula.items():
i = self.allowed_elements_list.index(key)
# print(key)
num = i+1 # which is element number as H of num is 1
# 18+14=32 # channel mens s,p,d, and f
if num == 1: # H
coordinate[channel(0, 0), 0, 0] = value
elif num == 2: # He
coordinate[channel(0, 32-1), 0, 32-1] = value
elif num <= 18:
# if q, mod=divmod(10,3) then q=3, mod=1
y, x = divmod(num-2, 8)
if x == 1 or x == 2:
coordinate[channel(y+1, x-1), y+1, x-1] = value
else:
if x == 0:
x = 8
y -= 1
x = x+10+14
coordinate[channel(y+1, x-1), y + 1, x - 1] = value
elif num <= 54: # from K to Xe, which are from 4th and 5th period
y, x = divmod(num-18, 18)
if x == 0:
x = 18
y -= 1
if x == 1 or x == 2 or x == 3:
coordinate[channel(y+3, x-1), y+3, x-1] = value
else:
x = x+14
coordinate[channel(y+3, x-1), y + 3, x - 1] = value
elif num <= 118:
y, x = divmod(num-54, 32)
if x == 0:
x = 32
y -= 1
coordinate[channel(y+5, x-1), y+5, x-1] = value
else:
raise ValueError('error in period to image-like')
# dict[key] = coordinate
# if 'Tl' in dict.keys():
# dict['TI'] = dict['Tl']
# if 'Li' in dict.keys():
# dict['LI'] = dict['Li']
return coordinate
def from_periodic_table_form_to_dict_form(self, periodic_table_form):
''' input: periodic_table_form, basically [4,7,32] the first is for 4 channels s,p,d, and f. but the channel number can be arbitrary if we have more orbitals
'''
periodic_table_form = np.sum(periodic_table_form, axis=0)
dict_form = {}
element_num = 0 # it is like H is 0,He is 1
vertical_len, horizontal_len = periodic_table_form.shape
def add_element_to_dict(y, x, element_num, dic_form, decimal_num=4):
if periodic_table_form[y, x] > 0:
key = self.allowed_elements_list[element_num]
val = periodic_table_form[y, x]
dict_form[key] = np.round(val, decimal_num)
return dict_form
for y in range(vertical_len):
for x in range(horizontal_len):
if y == 0 and (x == 0 or x == 31): # 2 first row
dict_form = add_element_to_dict(
y, x, element_num, dict_form)
element_num += 1
elif (y == 1 or y == 2) and (x <= 1 or 26 <= x): # 2+6=8 (16) 2nd and 3rd row
dict_form = add_element_to_dict(
y, x, element_num, dict_form)
element_num += 1
elif (y == 3 or y == 4) and (x <= 2 or 17 <= x): # 2+16=18 (36)
dict_form = add_element_to_dict(
y, x, element_num, dict_form)
element_num += 1
elif (y == 5 or y == 6): # 32 (64)
dict_form = add_element_to_dict(
y, x, element_num, dict_form)
element_num += 1
if element_num != 118:
print('error1090okc')
exit()
return dict_form
def dict_form_to_chemical_formula(self, dict_form):
return Composition.from_dict(dict_form).reduced_formula
def periodic_table_form_to_chemical_formula(self, periodic_table_form):
dict_form = self.from_periodic_table_form_to_dict_form(
periodic_table_form)
return self.dict_form_to_chemical_formula(dict_form)
'''here is an example'''
"""
test_formula = 'H2He5'
reading_periodic_table = TransformReadingPeriodicTable(formula=test_formula)
reading_periodic_table_form_data = reading_periodic_table.formula_to_periodic_table()
print(reading_periodic_table_form_data)
formula_dict_form = reading_periodic_table.from_periodic_table_form_to_dict_form(reading_periodic_table_form_data)
print(formula_dict_form)
"""
| [
"pymatgen.Composition.from_dict",
"numpy.sum",
"numpy.zeros",
"pymatgen.Composition",
"numpy.round"
] | [((1828, 1871), 'numpy.zeros', 'np.zeros', (['[4, 7, 18 + 14]'], {'dtype': 'np.float32'}), '([4, 7, 18 + 14], dtype=np.float32)\n', (1836, 1871), True, 'import numpy as np\n'), ((3981, 4016), 'numpy.sum', 'np.sum', (['periodic_table_form'], {'axis': '(0)'}), '(periodic_table_form, axis=0)\n', (3987, 4016), True, 'import numpy as np\n'), ((5615, 5647), 'pymatgen.Composition.from_dict', 'Composition.from_dict', (['dict_form'], {}), '(dict_form)\n', (5636, 5647), False, 'from pymatgen import Composition\n'), ((1771, 1796), 'pymatgen.Composition', 'Composition', (['self.formula'], {}), '(self.formula)\n', (1782, 1796), False, 'from pymatgen import Composition\n'), ((4425, 4451), 'numpy.round', 'np.round', (['val', 'decimal_num'], {}), '(val, decimal_num)\n', (4433, 4451), True, 'import numpy as np\n')] |
# [h] import ufo into layer
import hTools2.dialogs.font.layer_import
reload(hTools2.dialogs.font.layer_import)
from hTools2.dialogs.font.layer_import import importUFOIntoLayerDialog
importUFOIntoLayerDialog()
| [
"hTools2.dialogs.font.layer_import.importUFOIntoLayerDialog"
] | [((185, 211), 'hTools2.dialogs.font.layer_import.importUFOIntoLayerDialog', 'importUFOIntoLayerDialog', ([], {}), '()\n', (209, 211), False, 'from hTools2.dialogs.font.layer_import import importUFOIntoLayerDialog\n')] |
# -*- coding: utf-8 -*-
import json
import requests
from django.utils.translation import ugettext as _
from django.utils import translation
from django.core.cache import cache
from common.log import logger
from conf.default import APP_ID, APP_TOKEN, BK_PAAS_HOST
from constants import (HEADERS)
def get_data_by_api(url, request_data, method='GET', headers=True):
"""
@summary:组装接口
"""
language_header = {
'blueking-language': translation.get_language()
}
request_info = "url: {url}: request_data: {request_data}".format(
url=url, request_data=str(request_data)
)
logger.info(request_info)
try:
if method == 'POST':
request_data = json.loads(request_data)
request_data.update({'app_code': APP_ID, 'app_secret': APP_TOKEN})
request_data = json.dumps(request_data)
if headers:
HEADERS.update(language_header)
data = requests.post(url, request_data, headers=HEADERS, timeout=300)
else:
data = requests.post(url, request_data, headers=language_header)
logger.info("url: {url}, request_data: {request_data}, response: {response}".format(
url=url, request_data=str(request_data), response=json.loads(data.text)
))
cache.set(request_info, data, 30)
return data
else:
# GET 请求缓存数据
request_cache = cache.get(request_info)
if request_cache:
return request_cache
url = BK_PAAS_HOST + url
request_data.update({'app_code': APP_ID, 'app_secret': APP_TOKEN})
result = requests.get(url, request_data, headers=language_header, timeout=300)
data = json.loads(result.text)['data']
logger.info("url: {url}, request_data: {request_data}, response: {response}".format(
url=url, request_data=str(request_data), response=json.loads(result.text)
))
if data is None:
data = []
cache.set(request_info, data, 30)
return data
except Exception as e:
logger.error(
_(u'获取API{url}信息失败:{request_data}, 异常:{exception} ').format(
url=url, request_data=request_data, exception=e)
)
return []
def get_app_by_user(bk_token):
"""
@summary:查询用户有权限的业务
"""
cache_name = "%s_apps" % bk_token
data = cache.get(cache_name)
if not data:
data = get_data_by_api('/api/c/compapi/cc/get_app_by_user/',
{'bk_token': bk_token})
cache.set(cache_name, data, 60)
app_list = []
for app in data:
try:
app_list.append({
"app_name": app['ApplicationName'],
"app_id": app['ApplicationID'],
"time_zone": app['TimeZone']
})
except KeyError:
app_list.append({
"app_name": app['ApplicationName'],
"app_id": app['ApplicationID'],
"time_zone": 'Asia/Shanghai'
})
return app_list
| [
"json.loads",
"requests.post",
"common.log.logger.info",
"json.dumps",
"requests.get",
"constants.HEADERS.update",
"django.utils.translation.get_language",
"django.utils.translation.ugettext",
"django.core.cache.cache.set",
"django.core.cache.cache.get"
] | [((616, 641), 'common.log.logger.info', 'logger.info', (['request_info'], {}), '(request_info)\n', (627, 641), False, 'from common.log import logger\n'), ((2471, 2492), 'django.core.cache.cache.get', 'cache.get', (['cache_name'], {}), '(cache_name)\n', (2480, 2492), False, 'from django.core.cache import cache\n'), ((455, 481), 'django.utils.translation.get_language', 'translation.get_language', ([], {}), '()\n', (479, 481), False, 'from django.utils import translation\n'), ((2643, 2674), 'django.core.cache.cache.set', 'cache.set', (['cache_name', 'data', '(60)'], {}), '(cache_name, data, 60)\n', (2652, 2674), False, 'from django.core.cache import cache\n'), ((707, 731), 'json.loads', 'json.loads', (['request_data'], {}), '(request_data)\n', (717, 731), False, 'import json\n'), ((838, 862), 'json.dumps', 'json.dumps', (['request_data'], {}), '(request_data)\n', (848, 862), False, 'import json\n'), ((1332, 1365), 'django.core.cache.cache.set', 'cache.set', (['request_info', 'data', '(30)'], {}), '(request_info, data, 30)\n', (1341, 1365), False, 'from django.core.cache import cache\n'), ((1457, 1480), 'django.core.cache.cache.get', 'cache.get', (['request_info'], {}), '(request_info)\n', (1466, 1480), False, 'from django.core.cache import cache\n'), ((1686, 1755), 'requests.get', 'requests.get', (['url', 'request_data'], {'headers': 'language_header', 'timeout': '(300)'}), '(url, request_data, headers=language_header, timeout=300)\n', (1698, 1755), False, 'import requests\n'), ((2076, 2109), 'django.core.cache.cache.set', 'cache.set', (['request_info', 'data', '(30)'], {}), '(request_info, data, 30)\n', (2085, 2109), False, 'from django.core.cache import cache\n'), ((903, 934), 'constants.HEADERS.update', 'HEADERS.update', (['language_header'], {}), '(language_header)\n', (917, 934), False, 'from constants import HEADERS\n'), ((958, 1020), 'requests.post', 'requests.post', (['url', 'request_data'], {'headers': 'HEADERS', 'timeout': '(300)'}), '(url, request_data, headers=HEADERS, timeout=300)\n', (971, 1020), False, 'import requests\n'), ((1062, 1119), 'requests.post', 'requests.post', (['url', 'request_data'], {'headers': 'language_header'}), '(url, request_data, headers=language_header)\n', (1075, 1119), False, 'import requests\n'), ((1775, 1798), 'json.loads', 'json.loads', (['result.text'], {}), '(result.text)\n', (1785, 1798), False, 'import json\n'), ((1283, 1304), 'json.loads', 'json.loads', (['data.text'], {}), '(data.text)\n', (1293, 1304), False, 'import json\n'), ((1970, 1993), 'json.loads', 'json.loads', (['result.text'], {}), '(result.text)\n', (1980, 1993), False, 'import json\n'), ((2195, 2247), 'django.utils.translation.ugettext', '_', (['u"""获取API{url}信息失败:{request_data}, 异常:{exception} """'], {}), "(u'获取API{url}信息失败:{request_data}, 异常:{exception} ')\n", (2196, 2247), True, 'from django.utils.translation import ugettext as _\n')] |
import random
from kaggle_environments.envs.rps.utils import get_score
last_counter_action = None
def counter_reactionary(observation, configuration):
global last_counter_action
if observation.step == 0:
last_counter_action = random.randrange(0, configuration.signs)
elif get_score(last_counter_action, observation.lastOpponentAction) == 1:
last_counter_action = (last_counter_action + 2) % configuration.signs
else:
last_counter_action = (observation.lastOpponentAction + 1) % configuration.signs
return last_counter_action
| [
"kaggle_environments.envs.rps.utils.get_score",
"random.randrange"
] | [((246, 286), 'random.randrange', 'random.randrange', (['(0)', 'configuration.signs'], {}), '(0, configuration.signs)\n', (262, 286), False, 'import random\n'), ((296, 358), 'kaggle_environments.envs.rps.utils.get_score', 'get_score', (['last_counter_action', 'observation.lastOpponentAction'], {}), '(last_counter_action, observation.lastOpponentAction)\n', (305, 358), False, 'from kaggle_environments.envs.rps.utils import get_score\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ======================================================================================================================
# Imports
# ======================================================================================================================
import json
import yaml
import moleculerize
import pytest
from os import getenv
from click.testing import CliRunner
# ======================================================================================================================
# Globals
# ======================================================================================================================
SKIP_EVERYTHING = False if getenv('SKIP_EVERYTHING') is None else True
# ======================================================================================================================
# Test Suites
# ======================================================================================================================
class TestMoleculerize(object):
"""Tests for moleculerize"""
@pytest.mark.skipif(SKIP_EVERYTHING, reason='Skip if we are creating/modifying tests!')
def test_load_parse_json_inventory(self, groups, json_inventory):
"""Verify that moleculerize can successfully load a JSON Ansible inventory file."""
# Setup
hosts_inventory = moleculerize.generate_hosts_inventory(json_inventory)
# Test
for host in groups.keys():
assert hosts_inventory[host] == set(groups[host])
@pytest.mark.skipif(SKIP_EVERYTHING, reason='Skip if we are creating/modifying tests!')
def test_render_template(self, groups, json_inventory):
"""Verify that moleculerize can create a YAML template with correct syntax."""
# Setup
hosts_inventory = moleculerize.generate_hosts_inventory(json_inventory)
scenario = 'groovy'
render_yaml = yaml.load(moleculerize.render_molecule_template(scenario, hosts_inventory,
moleculerize.TEMPLATE))
# Expectations
platforms_exp = [{'name': host, 'groups': groups[host]} for host in groups.keys() if host != 'host6']
platforms_exp.append({'name': 'host6'})
observed = render_yaml['platforms']
# Test
for platform in platforms_exp:
assert platform in observed
assert scenario == render_yaml['scenario']['name']
@pytest.mark.skipif(SKIP_EVERYTHING, reason='Skip if we are creating/modifying tests!')
def test_missing_required_keys(self):
"""Verify that moleculerize will reject JSON Ansible inventory files missing required keys."""
# Setup
json_inventory_missing_meta = json.loads('{ "invalid": {} }')
json_inventory_missing_hostvars = json.loads('{ "_meta": { "invalid": {} } }')
# Test
with pytest.raises(RuntimeError):
moleculerize.generate_hosts_inventory(json_inventory_missing_meta)
with pytest.raises(RuntimeError):
moleculerize.generate_hosts_inventory(json_inventory_missing_hostvars)
@pytest.mark.skipif(SKIP_EVERYTHING, reason='Skip if we are creating/modifying tests!')
def test_invalid_template_path(self, json_inventory):
"""Verify that moleculerize will fail gracefully if the template file cannot be found."""
# Setup
hosts_inventory = moleculerize.generate_hosts_inventory(json_inventory)
scenario = 'default'
# Test
with pytest.raises(RuntimeError):
moleculerize.render_molecule_template(scenario, hosts_inventory, 'MISSING_TEMPLATE')
@pytest.mark.skipif(SKIP_EVERYTHING, reason='Skip if we are creating/modifying tests!')
def test_invalid_inventory_path(self):
"""Verify that moleculerize will fail gracefully if the inventory file cannot be found."""
# Test
with pytest.raises(RuntimeError):
moleculerize._load_input_file('invalid_path')
@pytest.mark.skipif(SKIP_EVERYTHING, reason='Skip if we are creating/modifying tests!')
def test_invalid_config_path(self, mocker):
"""Verify that moleculerize will fail gracefully if the Molecule config file cannot be written."""
runner = CliRunner()
cli_arguments = ['/path/does/not/exist']
mocker.patch('moleculerize._load_input_file', return_value=None)
mocker.patch('moleculerize._load_input_file', return_value={})
mocker.patch('moleculerize.generate_hosts_inventory', return_value={})
# Expectations
exit_code_exp = 2
# Test
result = runner.invoke(moleculerize.main, args=cli_arguments)
assert exit_code_exp == result.exit_code
| [
"moleculerize.generate_hosts_inventory",
"json.loads",
"os.getenv",
"click.testing.CliRunner",
"pytest.raises",
"moleculerize._load_input_file",
"pytest.mark.skipif",
"moleculerize.render_molecule_template"
] | [((1069, 1160), 'pytest.mark.skipif', 'pytest.mark.skipif', (['SKIP_EVERYTHING'], {'reason': '"""Skip if we are creating/modifying tests!"""'}), "(SKIP_EVERYTHING, reason=\n 'Skip if we are creating/modifying tests!')\n", (1087, 1160), False, 'import pytest\n'), ((1534, 1625), 'pytest.mark.skipif', 'pytest.mark.skipif', (['SKIP_EVERYTHING'], {'reason': '"""Skip if we are creating/modifying tests!"""'}), "(SKIP_EVERYTHING, reason=\n 'Skip if we are creating/modifying tests!')\n", (1552, 1625), False, 'import pytest\n'), ((2471, 2562), 'pytest.mark.skipif', 'pytest.mark.skipif', (['SKIP_EVERYTHING'], {'reason': '"""Skip if we are creating/modifying tests!"""'}), "(SKIP_EVERYTHING, reason=\n 'Skip if we are creating/modifying tests!')\n", (2489, 2562), False, 'import pytest\n'), ((3146, 3237), 'pytest.mark.skipif', 'pytest.mark.skipif', (['SKIP_EVERYTHING'], {'reason': '"""Skip if we are creating/modifying tests!"""'}), "(SKIP_EVERYTHING, reason=\n 'Skip if we are creating/modifying tests!')\n", (3164, 3237), False, 'import pytest\n'), ((3676, 3767), 'pytest.mark.skipif', 'pytest.mark.skipif', (['SKIP_EVERYTHING'], {'reason': '"""Skip if we are creating/modifying tests!"""'}), "(SKIP_EVERYTHING, reason=\n 'Skip if we are creating/modifying tests!')\n", (3694, 3767), False, 'import pytest\n'), ((4027, 4118), 'pytest.mark.skipif', 'pytest.mark.skipif', (['SKIP_EVERYTHING'], {'reason': '"""Skip if we are creating/modifying tests!"""'}), "(SKIP_EVERYTHING, reason=\n 'Skip if we are creating/modifying tests!')\n", (4045, 4118), False, 'import pytest\n'), ((696, 721), 'os.getenv', 'getenv', (['"""SKIP_EVERYTHING"""'], {}), "('SKIP_EVERYTHING')\n", (702, 721), False, 'from os import getenv\n'), ((1361, 1414), 'moleculerize.generate_hosts_inventory', 'moleculerize.generate_hosts_inventory', (['json_inventory'], {}), '(json_inventory)\n', (1398, 1414), False, 'import moleculerize\n'), ((1811, 1864), 'moleculerize.generate_hosts_inventory', 'moleculerize.generate_hosts_inventory', (['json_inventory'], {}), '(json_inventory)\n', (1848, 1864), False, 'import moleculerize\n'), ((2758, 2789), 'json.loads', 'json.loads', (['"""{ "invalid": {} }"""'], {}), '(\'{ "invalid": {} }\')\n', (2768, 2789), False, 'import json\n'), ((2832, 2876), 'json.loads', 'json.loads', (['"""{ "_meta": { "invalid": {} } }"""'], {}), '(\'{ "_meta": { "invalid": {} } }\')\n', (2842, 2876), False, 'import json\n'), ((3432, 3485), 'moleculerize.generate_hosts_inventory', 'moleculerize.generate_hosts_inventory', (['json_inventory'], {}), '(json_inventory)\n', (3469, 3485), False, 'import moleculerize\n'), ((4287, 4298), 'click.testing.CliRunner', 'CliRunner', ([], {}), '()\n', (4296, 4298), False, 'from click.testing import CliRunner\n'), ((1925, 2016), 'moleculerize.render_molecule_template', 'moleculerize.render_molecule_template', (['scenario', 'hosts_inventory', 'moleculerize.TEMPLATE'], {}), '(scenario, hosts_inventory,\n moleculerize.TEMPLATE)\n', (1962, 2016), False, 'import moleculerize\n'), ((2906, 2933), 'pytest.raises', 'pytest.raises', (['RuntimeError'], {}), '(RuntimeError)\n', (2919, 2933), False, 'import pytest\n'), ((2947, 3013), 'moleculerize.generate_hosts_inventory', 'moleculerize.generate_hosts_inventory', (['json_inventory_missing_meta'], {}), '(json_inventory_missing_meta)\n', (2984, 3013), False, 'import moleculerize\n'), ((3028, 3055), 'pytest.raises', 'pytest.raises', (['RuntimeError'], {}), '(RuntimeError)\n', (3041, 3055), False, 'import pytest\n'), ((3069, 3139), 'moleculerize.generate_hosts_inventory', 'moleculerize.generate_hosts_inventory', (['json_inventory_missing_hostvars'], {}), '(json_inventory_missing_hostvars)\n', (3106, 3139), False, 'import moleculerize\n'), ((3544, 3571), 'pytest.raises', 'pytest.raises', (['RuntimeError'], {}), '(RuntimeError)\n', (3557, 3571), False, 'import pytest\n'), ((3585, 3673), 'moleculerize.render_molecule_template', 'moleculerize.render_molecule_template', (['scenario', 'hosts_inventory', '"""MISSING_TEMPLATE"""'], {}), "(scenario, hosts_inventory,\n 'MISSING_TEMPLATE')\n", (3622, 3673), False, 'import moleculerize\n'), ((3934, 3961), 'pytest.raises', 'pytest.raises', (['RuntimeError'], {}), '(RuntimeError)\n', (3947, 3961), False, 'import pytest\n'), ((3975, 4020), 'moleculerize._load_input_file', 'moleculerize._load_input_file', (['"""invalid_path"""'], {}), "('invalid_path')\n", (4004, 4020), False, 'import moleculerize\n')] |
from archive.groups import Group
from archive.teams import Team
from logging import Logging
from itertools import cycle
import datetime
from copy import deepcopy
from sys import exit
import collections
from os import path, getcwd
class Tournament:
"""
Store (and initialise) dictionary and storage structures
Contains dictionaries for teams, groups, pitches which in turn
contain values which are Team, Group and Pitch object respectively.
"""
def __init__(self, team_list, name="tournament"):
self.name = name
self.log_file = path.join(getcwd(), self.name + ".log")
self.groups = {}
self.teams = {}
self.pitches = {}
self.schedule = []
self.group_size = 0
self.total_groups = 0
self.total_teams = 0
self.total_pitches = 0
self.max_placement_game_slots = 0
self.max_concurrent_games = 0
self.req_group_games = 0
# Timings
self.timings = Timings
self.current_time_slot = datetime.datetime
# Populate teams with Team objects
for pos, team in enumerate(team_list):
self.teams[pos + 1] = Team(team, pos + 1)
self.total_teams = len(team_list)
Logging.write_log_event(self.log_file,
'Tournament object initialisation',
'Populated dict teams',
'Total teams: {}'.format(self.total_teams))
def create_groups(self, group_size=4):
self.group_size = group_size
self.total_groups = self.total_teams // self.group_size
print("{} groups of {} teams".format(self.total_groups, group_size))
self.req_group_games = self.total_groups * (self.group_size * (self.group_size - 1)) // 2
print("Total group games: {}".format(self.req_group_games))
# Create group objects within dictionary
for i in range(self.total_groups):
self.groups[i] = Group(i, self.group_size)
# Assign teams in initial self.groups by seed
temp_seed_list = list(range(1, self.total_teams + 1))
for i in cycle(range(self.total_groups)):
try:
team = self.teams[temp_seed_list.pop(0)]
self.groups[i].addTeam(team)
team = self.teams[temp_seed_list.pop(-1)]
self.groups[i].addTeam(team)
except IndexError:
# Run out of teams to place into self.groups
break
def create_pitches(self, total_pitches=2):
self.total_pitches = total_pitches
for id in range(total_pitches):
self.pitches[id] = Pitch(id)
def set_timings(self, timings):
self.timings = timings
length_day1 = self.timings.day1_end - self.timings.day1_start
length_day2 = self.timings.day2_end - self.timings.day2_start
available_time = length_day1 + length_day2
adj_group_game_length = self.timings.group_game_length + self.timings.game_break
adj_game_length = self.timings.game_length + self.timings.game_break
self.max_placement_game_slots = self.total_pitches * (available_time -
adj_group_game_length * (
self.req_group_games // self.total_pitches)
) // adj_game_length
total_group_game_time = (self.req_group_games * adj_group_game_length) / self.total_pitches
print("Total Tournament Time: {}".format(available_time))
if total_group_game_time / available_time > 0.6:
print("{} group games lasting {} ({}% of available time!)".format(self.req_group_games,
total_group_game_time,
100 * total_group_game_time / available_time))
if self.max_placement_game_slots < self.total_teams:
print("Only {} game slots available for placement games!".format(self.max_placement_game_slots))
print("Consider lengthening tournament hours, adding more pitches or removing teams")
self.current_time_slot = self.timings.day1_start
def create_group_stage(self):
"""
create match_ups dictionary of Fixture objects
assign_fixtures_to_schedule()
get_match_priority()
"""
self.max_concurrent_games = min([self.total_pitches, self.group_size // 2])
Logging.write_log_event(self.log_file,
"create_group_stage",
"",
'max concurrent games: {}'.format(self.max_concurrent_games))
# Create dictionary of group game match ups (as fixtures)
match_ups = {}
for group in self.groups.values():
match_ups[group.index] = self.create_group_fixtures(group)
self.assign_fixtures_to_schedule(self.groups.keys(), match_ups, group_game=True, log_stage="create_group_stage")
@staticmethod
def get_group_match_up_indices(group_size):
"""
Create a list of tuples for possible team1 and team2 index
combinations. When a team is chosen as t1, it is removed from t2
to stop double counting
:rtype: tuple array
:param group_size: number of teams in a group
"""
match_ups = []
team_ones = list(range(0, group_size))
team_twos = list(range(0, group_size))
for t1 in team_ones:
for t2 in team_twos:
if t1 != t2:
match_ups.append((t1, t2))
team_twos.pop(team_twos.index(t1))
return match_ups
def assign_fixtures_to_schedule(self, group_keys, fixtures, group_game, log_stage="-"):
"""
:param group_keys: list of groups, made into a cycled iterable
:param fixtures: dictionary of fixtures with pitch, time emitted, containing only the teams involved
:param group_game: True/False
:param log_stage: information for logging
:return: None
"""
groups_it = cycle(iter(group_keys))
pitches = cycle(range(self.total_pitches))
pitch = next(pitches)
group = next(groups_it)
i_concurrent = 0
assigned_fixtures = 0
match_to_append = Fixture(None, None, None, None, None)
Logging.write_log_event(self.log_file,
log_stage,
'assign_fixtures_to_schedule',
'Begin assigning {} games to schedule'.format(
sum(len(matches) for matches in fixtures.values())))
while True:
# Get match priorities
match_priority = self.return_match_priorities(fixtures)
try:
prio_i_match = match_priority[group].index(max(match_priority[group]))
except ValueError:
print("Assigned {} fixtures to the schedule".format(assigned_fixtures))
break
match_to_append = fixtures[group].pop(prio_i_match)
# Assign Time and Pitch to match before adding to schedule
match_to_append.game_start = self.current_time_slot
match_to_append.pitch = pitch
# Log chosen fixture to append
Logging.write_log_event(path.join(getcwd(), 'create_group_stage.log'),
log_stage,
'highest priority match chosen',
'T:{} P:{} T1:{} T2:{} Priority:{:5.0f}'
.format(match_to_append.game_start.strftime('%H:%M'),
match_to_append.pitch,
match_to_append.team1.name,
match_to_append.team2.name,
match_priority[group][prio_i_match]))
self.schedule.append(match_to_append)
assigned_fixtures += 1
i_concurrent += 1
# Increment pitch for next game
pitch = next(pitches)
if pitch == 0:
# Pitch choice has has just cycled around: must move to next time slot
self.current_time_slot = self.increment_current_time(self.current_time_slot, group_game=group_game)
# Increment group if max concurrent games has been reached
if i_concurrent == self.max_concurrent_games:
i_concurrent = 0
group = next(groups_it)
return None
def create_bracket(self):
"""
top x, the rest decided by group stage
Match ups:
Top8/bottom 8
1-8,2-7,3-6,4-5
"""
top_half = self.total_teams // 2
if top_half % 2 != 0:
if top_half <= 7:
top_half += 1
else:
top_half -= 1
grouped_seeds = {'top': list(range(1, top_half + 1)), 'bottom': list(range(top_half + 1, self.total_teams + 1))}
if len(grouped_seeds['bottom']) % 2 != 0:
print("Must have even number of teams in bottom half of bracket")
print(len(grouped_seeds['bottom']))
exit(1)
# Create dictionary of lists of level 1 bracket match ups
# todo dictionary creation should be in a method to avoid repetition for both group and bracket stages
seed_combos = {}
match_ups = {}
for g in ['top', 'bottom']:
seed_combos[g] = []
while len(grouped_seeds[g]) > 0:
t1 = grouped_seeds[g].pop(0)
t2 = grouped_seeds[g].pop(-1)
seed_combos[g].append((t1, t2))
# Turn match up seed combinations to a dict of fixtures
match_ups[g] = []
for t1, t2 in seed_combos[g]:
match_ups[g].append(deepcopy(Fixture(self.teams[t1],
self.teams[t2],
-1,
None,
None,
None)))
# Assign match ups to schedule
self.assign_fixtures_to_schedule(['top', 'bottom'], match_ups, group_game=False, log_stage="create_bracket")
def create_group_fixtures(self, group):
# Generate list of (t1, t2) tuples for a generic group
matchup_indices = self.get_group_match_up_indices(self.group_size)
group_fixtures = []
for t1, t2 in matchup_indices:
group_fixtures.append(deepcopy(Fixture(group.get_team_by_index(t1),
group.get_team_by_index(t2),
-1,
None,
None,
group.index)))
return group_fixtures
def assign_timings_to_schedule(self):
"""
Iterate through schedule, assigning timings to the fixture list
"""
# Iterate over schedule items and iterate timings
current_time = {}
for pitch in self.pitches.keys():
current_time[pitch] = self.timings.day1_start
for fixture in self.schedule:
if fixture.group is not None:
game_length = self.timings.group_game_length
else:
game_length = self.timings.game_length
# Move to 'next day' if required
if self.timings.day2_start > current_time[fixture.pitch] > self.timings.day1_end:
current_time[fixture.pitch] = self.timings.day2_start
if fixture.game_start is None:
fixture.game_start = current_time[fixture.pitch]
fixture.game_length = game_length
current_time[fixture.pitch] += game_length + self.timings.game_break
else:
# Fixture already has a time assigned, skip
current_time[fixture.pitch] += (fixture.game_length + self.timings.game_break)
def print_schedule(self):
"""Output schedule in easy to read format"""
fixtures_by_pitch = []
for pitch in range(self.total_pitches):
fixtures_by_pitch.append([])
assert len(fixtures_by_pitch) == self.total_pitches, "incorrect fixtures_by_pitch initialisation"
for fixture in self.schedule:
fixtures_by_pitch[fixture.pitch].append(fixture)
# Find longest dimension list
longest_length = len(max(fixtures_by_pitch, key=lambda col: len(col)))
# Time for printing to screen
header = "{:<16}".format("Game Time")
for pitch in range(self.total_pitches):
header += "Pitch {:<20}".format(pitch)
print("longest_length", longest_length)
print(header)
for i in range(longest_length):
fixture_info = [
" {} ".format(datetime.datetime.strftime(fixtures_by_pitch[0][i].game_start, '%d/%m %H:%M'))]
for pitch in range(self.total_pitches):
try:
fixture = fixtures_by_pitch[pitch][i]
fixture_info.append("{:<10s} vs {:<10s}".format(fixture.team1.name,
fixture.team2.name))
except IndexError:
fixture_info.append("{:^10s} vs {:^10s}".format("-", "-", "-", "-"))
print(" | ".join(fixture_info))
def return_match_priorities(self, remaining_matches):
"""
:return index linked match priority dictionary of lists
Prioritise a match according to:
Slots since last match
Already playing in current slot?
Games already played(?)
:parameter remaining_matches - dictionary of lists
"""
# Iterate through list, assessing current priority of match
# relative to current fixture list
priorities = {}
for g_key, group in remaining_matches.items():
priorities[g_key] = []
for match_up in group:
# Assess match priority
# Slots since last match
# Games already played
# Work backwards through schedule
t1_games_played = 0
t1_last_game_time = self.timings.day1_start
t2_games_played = 0
t2_last_game_time = self.timings.day1_start
for fixture in self.schedule:
if fixture.team1.id == match_up.team1.id or fixture.team2.id == match_up.team2.id:
t1_games_played += 1
t1_last_game_time = fixture.game_start
if fixture.team1.id == match_up.team1.id or fixture.team2.id == match_up.team2.id:
t2_last_game_time = fixture.game_start
t2_games_played += 1
# lowest_games_played = min([t1_games_played, t2_games_played])
total_games_played = t1_games_played + t2_games_played
time_since_last_game = min([self.current_time_slot - t1_last_game_time,
self.current_time_slot - t2_last_game_time])
priority = (24.0 - time_since_last_game.seconds / 3600.0) + (10 - total_games_played) * 10
if time_since_last_game < (
min([self.timings.game_length, self.timings.group_game_length]) + self.timings.game_break):
if t1_games_played == 0 and t2_games_played == 0:
pass
else:
priority = -1000
priorities[g_key].append(priority)
return priorities
def increment_current_time(self, current_time, group_game):
"""
:param current_time: datetime object
:param group_game: bool
:return: incremented time
"""
if group_game:
g_length = self.timings.group_game_length
else:
g_length = self.timings.game_length
current_time += (g_length + self.timings.game_break)
if current_time >= self.timings.day1_end:
current_time = self.timings.day2_end
return current_time
class Pitch:
def __init__(self, identifier):
self.id = identifier
self.fixtures = []
class Fixture:
def __init__(self, team1, team2, pitch, game_start, game_length, group=None):
self.team1 = team1 # Team Object
self.team2 = team2 # Team Object
self.pitch = pitch #
self.group = group # Group ID
self.game_start = game_start
if self.game_start is None:
self.game_start = datetime.datetime.now()
self.game_length = game_length
def __str__(self):
if self.group is None:
group = "-"
else:
group = self.group
return "{} | pitch {:3} | group {:3} |{:<10} v {:>10}".format(
datetime.datetime.strftime(self.game_start, '%H:%M'), self.pitch, group, self.team1.name, self.team2.name)
Timings = collections.namedtuple('Timings', ['group_game_length',
'game_length',
'game_break',
'day1_start',
'day2_start',
'day1_end',
'day2_end'])
| [
"archive.teams.Team",
"collections.namedtuple",
"os.getcwd",
"archive.groups.Group",
"datetime.datetime.now",
"sys.exit",
"datetime.datetime.strftime"
] | [((17594, 17735), 'collections.namedtuple', 'collections.namedtuple', (['"""Timings"""', "['group_game_length', 'game_length', 'game_break', 'day1_start',\n 'day2_start', 'day1_end', 'day2_end']"], {}), "('Timings', ['group_game_length', 'game_length',\n 'game_break', 'day1_start', 'day2_start', 'day1_end', 'day2_end'])\n", (17616, 17735), False, 'import collections\n'), ((580, 588), 'os.getcwd', 'getcwd', ([], {}), '()\n', (586, 588), False, 'from os import path, getcwd\n'), ((1171, 1190), 'archive.teams.Team', 'Team', (['team', '(pos + 1)'], {}), '(team, pos + 1)\n', (1175, 1190), False, 'from archive.teams import Team\n'), ((1992, 2017), 'archive.groups.Group', 'Group', (['i', 'self.group_size'], {}), '(i, self.group_size)\n', (1997, 2017), False, 'from archive.groups import Group\n'), ((9484, 9491), 'sys.exit', 'exit', (['(1)'], {}), '(1)\n', (9488, 9491), False, 'from sys import exit\n'), ((17205, 17228), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (17226, 17228), False, 'import datetime\n'), ((17475, 17527), 'datetime.datetime.strftime', 'datetime.datetime.strftime', (['self.game_start', '"""%H:%M"""'], {}), "(self.game_start, '%H:%M')\n", (17501, 17527), False, 'import datetime\n'), ((7566, 7574), 'os.getcwd', 'getcwd', ([], {}), '()\n', (7572, 7574), False, 'from os import path, getcwd\n'), ((13361, 13438), 'datetime.datetime.strftime', 'datetime.datetime.strftime', (['fixtures_by_pitch[0][i].game_start', '"""%d/%m %H:%M"""'], {}), "(fixtures_by_pitch[0][i].game_start, '%d/%m %H:%M')\n", (13387, 13438), False, 'import datetime\n')] |
# Generated by Django 2.1.4 on 2019-07-19 00:50
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='post',
old_name='data_published',
new_name='date_published',
),
]
| [
"django.db.migrations.RenameField"
] | [((213, 312), 'django.db.migrations.RenameField', 'migrations.RenameField', ([], {'model_name': '"""post"""', 'old_name': '"""data_published"""', 'new_name': '"""date_published"""'}), "(model_name='post', old_name='data_published',\n new_name='date_published')\n", (235, 312), False, 'from django.db import migrations\n')] |
from .base import ConfigMNISTBase
from pipeline.models.classification import ClassificationModuleLinear
from pipeline.models.image_classification import Resnet18Model
import torch.nn as nn
class Config(ConfigMNISTBase):
def __init__(self):
model = nn.Sequential(
Resnet18Model(),
ClassificationModuleLinear(Resnet18Model.NUM_FEATURES, 10)
)
super().__init__(model=model)
| [
"pipeline.models.image_classification.Resnet18Model",
"pipeline.models.classification.ClassificationModuleLinear"
] | [((291, 306), 'pipeline.models.image_classification.Resnet18Model', 'Resnet18Model', ([], {}), '()\n', (304, 306), False, 'from pipeline.models.image_classification import Resnet18Model\n'), ((320, 378), 'pipeline.models.classification.ClassificationModuleLinear', 'ClassificationModuleLinear', (['Resnet18Model.NUM_FEATURES', '(10)'], {}), '(Resnet18Model.NUM_FEATURES, 10)\n', (346, 378), False, 'from pipeline.models.classification import ClassificationModuleLinear\n')] |