code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
'''
Author: <NAME>
Description:
Autocolorization
'''
import cv2
image = cv2.imread('data/original.png')
cv2.imshow('original',image)
cv2.waitKey(0)
cv2.destroyAllWindows()
image = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)
cv2.imshow('lab',image)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imshow('lab2bgr',cv2.cvtColor(image, cv2.COLOR_LAB2BGR))
cv2.waitKey(0)
cv2.destroyAllWindows() | [
"cv2.imshow",
"cv2.destroyAllWindows",
"cv2.cvtColor",
"cv2.waitKey",
"cv2.imread"
] | [((91, 122), 'cv2.imread', 'cv2.imread', (['"""data/original.png"""'], {}), "('data/original.png')\n", (101, 122), False, 'import cv2\n'), ((123, 152), 'cv2.imshow', 'cv2.imshow', (['"""original"""', 'image'], {}), "('original', image)\n", (133, 152), False, 'import cv2\n'), ((152, 166), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (163, 166), False, 'import cv2\n'), ((167, 190), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (188, 190), False, 'import cv2\n'), ((200, 238), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2LAB'], {}), '(image, cv2.COLOR_BGR2LAB)\n', (212, 238), False, 'import cv2\n'), ((239, 263), 'cv2.imshow', 'cv2.imshow', (['"""lab"""', 'image'], {}), "('lab', image)\n", (249, 263), False, 'import cv2\n'), ((263, 277), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (274, 277), False, 'import cv2\n'), ((278, 301), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (299, 301), False, 'import cv2\n'), ((364, 378), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (375, 378), False, 'import cv2\n'), ((379, 402), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (400, 402), False, 'import cv2\n'), ((324, 362), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_LAB2BGR'], {}), '(image, cv2.COLOR_LAB2BGR)\n', (336, 362), False, 'import cv2\n')] |
'''
Create a list of tables with different features such as:
- number of columns
- number of rows
- number of words per cell
- contains a specific word
- ...
A column 'is_table' is computed from the features to predict if a table is an actual table.
Majority of extracted tables are not actual and table, but simple text, hence the importance to filter them out.
The input is a directory containing the tables extracted from pdf documents using the 'extract-tables.jar' command line tool.
'''
import pandas as pd
import glob
import os
import re
import collections
import tqdm
import logging
def get_table_parts(file):
items = file.split(os.sep)
article = items[-3]
_, page, _, table_num, _ = items[-1].split('.')
return (article, int(page), int(table_num))
def get_table_file(dir_, article, page, table):
return os.path.join(dir_, article, 'tables', 'page.{:03d}.table.{:02d}.csv'.format(page, table))
def read_csv(file):
return pd.read_csv(file, encoding='utf-8', header=None, dtype=str).fillna('')
def is_word_in(word, cells, case_sensitive, match_end):
pattern = r'\b{}{}'.format(word, r'\b' if match_end else '')
flags = re.IGNORECASE if not case_sensitive else 0
pattern = re.compile(pattern, flags)
for c in cells:
for _ in pattern.finditer(c):
return True
return False
def predict_is_table(s):
return s['digits_perc'] > 0.1 and s['cell_words_mean'] < 5
def get_table_features(df):
cells = [c for _, col in df.items() for c in col]
words_count_by_cell = pd.Series([len(c.split()) for c in cells])
features = collections.OrderedDict(
columns = len(df.columns),
rows = len(df),
cell_words_min = words_count_by_cell.min(),
cell_words_mean = words_count_by_cell.mean(),
cell_words_max = words_count_by_cell.max(),
empty_cells = sum(1 for c in cells if c.strip() == ''),
total_words = sum(1 for c in cells for w in c.split()),
total_chars = sum(1 for c in cells for char in c),
total_digits = sum(1 for c in cells for char in c if char in '0123456789')
)
features['digits_perc'] = features['total_digits'] / features['total_chars']
# words features
words = [
('age', False, True),
('date', False, True),
('year', False, False),
('BP', True, True),
('BC', True, True),
('AD', False, True),
('Ka', True, True),
('CAL', False, True),
('painting', False, False),
('drawing', False, False),
('engraving', False, False),
('pictograph', False, False),
('petroglyph', False, False),
('AMS', True, True),
(r'Uranium\sserie', False, False),
('Radiocarbon', False, True),
('RC14', False, True),
('charcoal', False, True),
('pigment', False, False),
('calcite', False, False),
('beeswax', False, True),
('varnish', False, True),
('bone', False, False),
('cave', False, False),
('site', False, False),
]
for word, case_sensitive, match_end in words:
word_name = word if case_sensitive else word.lower()
word_name = re.sub(r'\\.', '_', word_name)
feature_name = 'w_{}_{}_{}'.format('cs' if case_sensitive else 'ci', 'e' if match_end else 'ne', word_name)
features[feature_name] = is_word_in(word, cells, case_sensitive, match_end)
# digit featues
digit_word_len_count = collections.Counter(len(d) for c in cells for d in re.findall(r'\d+', c))
for length in range(2, 5 + 1):
feature_name = 'digit_of_len_{}'.format(length)
features[feature_name] = digit_word_len_count.get(length, 0)
# is an actual table
features['is_table'] = predict_is_table(features)
features.move_to_end('is_table', last=False)
return features
# params
pdf_extraction_dir = r'<input dir>'
output_dir = 'output'
def output(name):
f = os.path.join(output_dir, name)
os.makedirs(os.path.split(f)[0], exist_ok=True)
return f
logging.basicConfig(filename=output('extract_features.log'), level=logging.INFO)
files = glob.glob(os.path.join(pdf_extraction_dir, '*', 'tables', '*.table.*.csv'))
tables = pd.DataFrame([get_table_parts(f) for f in files], columns=['article', 'page', 'table'])
# extract features
feature_list = []
for table in tqdm.tqdm(tables.itertuples(), desc='extracting features', total=len(tables)):
try:
file = get_table_file(pdf_extraction_dir, table.article, table.page, table.table)
df = read_csv(file)
features = get_table_features(df)
feature_list.append(features)
except:
logging.exception('Failed to extract features for table {} p.{} t.{}'.format(table.article, table.page, table.table))
features_df = pd.DataFrame(feature_list)
tables = pd.concat([tables, features_df], axis=1)
tables.to_pickle(output('tables.pkl'))
tables.to_csv(output('tables.csv'))
| [
"pandas.read_csv",
"re.compile",
"os.path.join",
"os.path.split",
"pandas.DataFrame",
"re.sub",
"re.findall",
"pandas.concat"
] | [((4813, 4839), 'pandas.DataFrame', 'pd.DataFrame', (['feature_list'], {}), '(feature_list)\n', (4825, 4839), True, 'import pandas as pd\n'), ((4849, 4889), 'pandas.concat', 'pd.concat', (['[tables, features_df]'], {'axis': '(1)'}), '([tables, features_df], axis=1)\n', (4858, 4889), True, 'import pandas as pd\n'), ((1225, 1251), 're.compile', 're.compile', (['pattern', 'flags'], {}), '(pattern, flags)\n', (1235, 1251), False, 'import re\n'), ((3963, 3993), 'os.path.join', 'os.path.join', (['output_dir', 'name'], {}), '(output_dir, name)\n', (3975, 3993), False, 'import os\n'), ((4160, 4224), 'os.path.join', 'os.path.join', (['pdf_extraction_dir', '"""*"""', '"""tables"""', '"""*.table.*.csv"""'], {}), "(pdf_extraction_dir, '*', 'tables', '*.table.*.csv')\n", (4172, 4224), False, 'import os\n'), ((3208, 3239), 're.sub', 're.sub', (['"""\\\\\\\\."""', '"""_"""', 'word_name'], {}), "('\\\\\\\\.', '_', word_name)\n", (3214, 3239), False, 'import re\n'), ((963, 1022), 'pandas.read_csv', 'pd.read_csv', (['file'], {'encoding': '"""utf-8"""', 'header': 'None', 'dtype': 'str'}), "(file, encoding='utf-8', header=None, dtype=str)\n", (974, 1022), True, 'import pandas as pd\n'), ((4010, 4026), 'os.path.split', 'os.path.split', (['f'], {}), '(f)\n', (4023, 4026), False, 'import os\n'), ((3537, 3558), 're.findall', 're.findall', (['"""\\\\d+"""', 'c'], {}), "('\\\\d+', c)\n", (3547, 3558), False, 'import re\n')] |
"""Computation of quadrature points and weights for different schemes.
Attributes
----------
DEFAULT_COLLOCATION_POINTS_MAX : int
Constant default limitation on the maximum number of collocation points
per mesh section that a user can specify. The value of 20 has been chosen
as above this the algorithms that are used for evaluating the orthogonal
polynomials become numerically unstable and raise a warning.
DEFAULT_COLLOCATION_POINTS_MIN : int
Constant default limitation on the minimum number of collocation points
per mesh section that a user can specify. The value of 2 has been chosen
as this is the smallest possible value that still makes logical sense (i.e.
a mesh section cannot have fewer than two nodes).
GAUSS : str
Keyword identifier for Legendre-Gauss quadrature method.
LOBATTO : str
Keyword identifier for Legendre-Gauss-Lobatto quadrature method.
RADAU : str
Keyword identifier for Legendre-Gauss-Radau quadrature method.
"""
__all__ = []
import numpy as np
import scipy.interpolate as interpolate
from pyproprop import Options
GAUSS = "gauss"
LOBATTO = "lobatto"
RADAU = "radau"
QUADRATURES = Options((GAUSS, LOBATTO, RADAU), default=LOBATTO,
unsupported=GAUSS)
DEFAULT_COLLOCATION_POINTS_MIN = 4
DEFAULT_COLLOCATION_POINTS_MAX = 10
class Quadrature:
"""Class for quadrature schemes including weights and points."""
def __init__(self, backend):
self.backend = backend
self._polynomials = {}
self._quadrature_points = {}
self._quadrature_weights = {}
self._butcher_arrays = {}
self._D_matrices = {}
self._A_matrices = {}
self._W_matrices = {}
self._D_index_arrays = {}
self._A_index_arrays = {}
@property
def settings(self):
return self.backend.ocp.settings
@property
def backend(self):
return self._backend
@backend.setter
def backend(self, backend):
self._backend = backend
self.order_range = list(range(
self.settings.collocation_points_min, self.settings.collocation_points_max))
if self.settings.quadrature_method == LOBATTO:
self.quadrature_generator = self.lobatto_generator
elif self.settings.quadrature_method == RADAU:
self.quadrature_generator = self.radau_generator
elif self.settings.quadrature_method == GAUSS:
self.quadrature_generator = self.gauss_generator
def _retrive_or_generate_dict_value(self, quad_dict, order):
try:
quad_dict[order]
except KeyError:
self.quadrature_generator(order)
return quad_dict[order]
def polynomials(self, order):
return self._retrive_or_generate_dict_value(self._polynomials, order)
def quadrature_point(self, order, *, domain=None):
points = self._retrive_or_generate_dict_value(
self._quadrature_points, order)
if domain:
stretch = 0.5 * (domain[1] - domain[0])
scale = 0.5 * (domain[0] + domain[1])
return stretch * points + scale
else:
return points
def quadrature_weight(self, order):
return self._retrive_or_generate_dict_value(self._quadrature_weights, order)
def butcher_array(self, order):
return self._retrive_or_generate_dict_value(self._butcher_arrays, order)
def D_matrix(self, order):
return self._retrive_or_generate_dict_value(self._D_matrices, order)
def A_matrix(self, order):
return self._retrive_or_generate_dict_value(self._A_matrices, order)
def W_matrix(self, order):
return self._retrive_or_generate_dict_value(self._W_matrices, order)
def D_index_array(self, order):
return self._retrive_or_generate_dict_value(self._D_index_arrays, order)
def A_index_array(self, order):
return self._retrive_or_generate_dict_value(self._A_index_arrays, order)
def radau_generator(self, order):
coefficients = [0] * (order - 2)
coefficients.extend([1, 1])
legendre_polynomial = np.polynomial.legendre.Legendre(coefficients)
self._polynomials.update({order: legendre_polynomial})
radau_points = legendre_polynomial.roots()
radau_points = np.concatenate([radau_points, np.array([0])])
self._quadrature_points.update({order: radau_points})
coefficients = [0] * (order - 2)
coefficients.extend([1])
legendre_polynomial = np.polynomial.legendre.Legendre(coefficients)
radau_weights = [2 / (order - 1)**2]
radau_weights = np.array(
radau_weights + [(1 - x) / ((order - 1)**2 * (legendre_polynomial(x)**2))
for x in radau_points[1:-1]])
radau_weights = np.concatenate([radau_weights, np.array([0])])
self._quadrature_weights.update({order: radau_weights})
butcher_points = self.quadrature_point(order, domain=[0, 1])
butcher_array = np.zeros((order, order))
butcher_array[-1, :] = radau_weights / 2
if order > 2:
A_row = (order + 1) * (order - 2)
A_col = order * (order - 2)
A = np.zeros((A_row, A_col))
b = np.zeros(A_row)
for k in range(order - 2):
for j in range(order):
row = j + k * order
for i in range(order - 2):
col = i + j * (order - 2)
A[row, col] = radau_weights[i + 1] * \
butcher_points[i + 1]**k
b[row] = (radau_weights[j] / (k + 1)) * (1 - butcher_points[j]
** (k + 1)) - radau_weights[-1] * radau_weights[j]
del_row = []
for i, row in enumerate(A):
if np.count_nonzero(row) == 0:
del_row.append(i)
A = np.delete(A, del_row, axis=0)
b = np.delete(b, del_row, axis=0)
a = np.linalg.solve(A, b)
butcher_array[1:-1, :] = a.reshape(order - 2, -1, order='F')
self._butcher_arrays.update({order: butcher_array})
D_left = np.ones((order - 1, 1), dtype=int)
D_right = np.diag(-1 * np.ones((order - 1, ), dtype=int))
D_matrix = np.hstack([D_left, D_right])
self._D_matrices.update({order: D_matrix})
A_matrix = self.butcher_array(order)[1:, :]
self._A_matrices.update({order: A_matrix})
A_index_array = np.array(range(A_matrix.size), dtype=int)
self._A_index_arrays.update({order: A_index_array})
D_num_row, D_num_col = D_matrix.shape
D_rows = np.array(range(D_num_row), dtype=int)
D_left = D_rows * D_num_col
D_right = D_rows * (D_num_col + 1) + 1
D_index_array = np.concatenate((D_left, D_right))
D_index_array.sort()
self._D_index_arrays.update({order: D_index_array})
# print(f'x: {radau_points}')
# print(f'w: {radau_weights}, {sum(radau_weights)}')
# print(f"a: {butcher_array}")
# print(f"A: {D_matrix}")
# print(f"I: {A_matrix}")
# input()
def lobatto_generator(self, order):
num_interior_points = order - 1
coefficients = [0] * (num_interior_points)
coefficients.append(1)
legendre_polynomial = np.polynomial.legendre.Legendre(coefficients)
self._polynomials.update({order: legendre_polynomial})
lobatto_points = legendre_polynomial.deriv().roots()
lobatto_points = np.insert(lobatto_points, 0, -1, axis=0)
lobatto_points = np.append(lobatto_points, 1)
self._quadrature_points.update({order: lobatto_points})
lobatto_weights = np.array(
[1 / (order * (order - 1) * (legendre_polynomial(x)**2)) for x in lobatto_points])
self._quadrature_weights.update({order: lobatto_weights})
butcher_points = self.quadrature_point(order, domain=[0, 1])
# print(f'x\': {butcher_points}')
butcher_array = np.zeros((order, order))
butcher_array[-1, :] = lobatto_weights
if order > 2:
A_row = (order + 1) * (order - 2)
A_col = order * (order - 2)
A = np.zeros((A_row, A_col))
b = np.zeros(A_row)
for k in range(order - 2):
# print(f'k: {k}')
for j in range(order):
# print(f'j: {j}')
row = j + k * order
# print(f'row: {row}')
for i in range(order - 2):
# print(f'i: {i}')
col = i + j * (order - 2)
# print(f'col: {col}')
A[row, col] = lobatto_weights[i + 1] * \
butcher_points[i + 1]**k
# print(f'A: {lobatto_weights[i+1] * butcher_points[i+1]**k}')
b[row] = (lobatto_weights[j] / (k + 1)) * (1 - butcher_points[j]
** (k + 1)) - lobatto_weights[-1] * lobatto_weights[j]
# print(f'b: {(lobatto_weights[j]/(k+1))*(1 - butcher_points[j]**(k+1)) - lobatto_weights[-1]*lobatto_weights[j]}\n')
del_row = []
for i, row in enumerate(A):
if np.count_nonzero(row) == 0:
del_row.append(i)
A = np.delete(A, del_row, axis=0)
b = np.delete(b, del_row, axis=0)
a = np.linalg.solve(A, b)
# print(f'A: {A}')
# print(f'b: {b}')
# print(f'a: {a}')
butcher_array[1:-1, :] = a.reshape(order - 2, -1, order='F')
self._butcher_arrays.update({order: butcher_array})
D_left = np.ones((num_interior_points, 1), dtype=int)
D_right = np.diag(-1 * np.ones((num_interior_points, ), dtype=int))
D_matrix = np.hstack([D_left, D_right])
self._D_matrices.update({order: D_matrix})
A_matrix = self.butcher_array(order)[1:, :]
self._A_matrices.update({order: A_matrix})
A_index_array = np.array(range(A_matrix.size), dtype=int)
self._A_index_arrays.update({order: A_index_array})
D_num_row, D_num_col = D_matrix.shape
D_rows = np.array(range(D_num_row), dtype=int)
D_left = D_rows * D_num_col
D_right = D_rows * (D_num_col + 1) + 1
D_index_array = np.concatenate((D_left, D_right))
D_index_array.sort()
self._D_index_arrays.update({order: D_index_array})
# print(f'x: {lobatto_points}')
# print(f'w: {lobatto_weights}, {sum(lobatto_weights)}')
# print(f"a: {butcher_array}")
# print(f"A: {D_matrix}")
# print(f"I: {A_matrix}")
# input()
| [
"numpy.insert",
"numpy.linalg.solve",
"numpy.ones",
"numpy.hstack",
"numpy.delete",
"numpy.append",
"numpy.array",
"numpy.zeros",
"numpy.count_nonzero",
"numpy.concatenate",
"numpy.polynomial.legendre.Legendre",
"pyproprop.Options"
] | [((1165, 1233), 'pyproprop.Options', 'Options', (['(GAUSS, LOBATTO, RADAU)'], {'default': 'LOBATTO', 'unsupported': 'GAUSS'}), '((GAUSS, LOBATTO, RADAU), default=LOBATTO, unsupported=GAUSS)\n', (1172, 1233), False, 'from pyproprop import Options\n'), ((4125, 4170), 'numpy.polynomial.legendre.Legendre', 'np.polynomial.legendre.Legendre', (['coefficients'], {}), '(coefficients)\n', (4156, 4170), True, 'import numpy as np\n'), ((4522, 4567), 'numpy.polynomial.legendre.Legendre', 'np.polynomial.legendre.Legendre', (['coefficients'], {}), '(coefficients)\n', (4553, 4567), True, 'import numpy as np\n'), ((5021, 5045), 'numpy.zeros', 'np.zeros', (['(order, order)'], {}), '((order, order))\n', (5029, 5045), True, 'import numpy as np\n'), ((6233, 6267), 'numpy.ones', 'np.ones', (['(order - 1, 1)'], {'dtype': 'int'}), '((order - 1, 1), dtype=int)\n', (6240, 6267), True, 'import numpy as np\n'), ((6353, 6381), 'numpy.hstack', 'np.hstack', (['[D_left, D_right]'], {}), '([D_left, D_right])\n', (6362, 6381), True, 'import numpy as np\n'), ((6873, 6906), 'numpy.concatenate', 'np.concatenate', (['(D_left, D_right)'], {}), '((D_left, D_right))\n', (6887, 6906), True, 'import numpy as np\n'), ((7414, 7459), 'numpy.polynomial.legendre.Legendre', 'np.polynomial.legendre.Legendre', (['coefficients'], {}), '(coefficients)\n', (7445, 7459), True, 'import numpy as np\n'), ((7610, 7650), 'numpy.insert', 'np.insert', (['lobatto_points', '(0)', '(-1)'], {'axis': '(0)'}), '(lobatto_points, 0, -1, axis=0)\n', (7619, 7650), True, 'import numpy as np\n'), ((7676, 7704), 'numpy.append', 'np.append', (['lobatto_points', '(1)'], {}), '(lobatto_points, 1)\n', (7685, 7704), True, 'import numpy as np\n'), ((8103, 8127), 'numpy.zeros', 'np.zeros', (['(order, order)'], {}), '((order, order))\n', (8111, 8127), True, 'import numpy as np\n'), ((9849, 9893), 'numpy.ones', 'np.ones', (['(num_interior_points, 1)'], {'dtype': 'int'}), '((num_interior_points, 1), dtype=int)\n', (9856, 9893), True, 'import numpy as np\n'), ((9989, 10017), 'numpy.hstack', 'np.hstack', (['[D_left, D_right]'], {}), '([D_left, D_right])\n', (9998, 10017), True, 'import numpy as np\n'), ((10509, 10542), 'numpy.concatenate', 'np.concatenate', (['(D_left, D_right)'], {}), '((D_left, D_right))\n', (10523, 10542), True, 'import numpy as np\n'), ((5219, 5243), 'numpy.zeros', 'np.zeros', (['(A_row, A_col)'], {}), '((A_row, A_col))\n', (5227, 5243), True, 'import numpy as np\n'), ((5260, 5275), 'numpy.zeros', 'np.zeros', (['A_row'], {}), '(A_row)\n', (5268, 5275), True, 'import numpy as np\n'), ((5968, 5997), 'numpy.delete', 'np.delete', (['A', 'del_row'], {'axis': '(0)'}), '(A, del_row, axis=0)\n', (5977, 5997), True, 'import numpy as np\n'), ((6014, 6043), 'numpy.delete', 'np.delete', (['b', 'del_row'], {'axis': '(0)'}), '(b, del_row, axis=0)\n', (6023, 6043), True, 'import numpy as np\n'), ((6060, 6081), 'numpy.linalg.solve', 'np.linalg.solve', (['A', 'b'], {}), '(A, b)\n', (6075, 6081), True, 'import numpy as np\n'), ((8299, 8323), 'numpy.zeros', 'np.zeros', (['(A_row, A_col)'], {}), '((A_row, A_col))\n', (8307, 8323), True, 'import numpy as np\n'), ((8340, 8355), 'numpy.zeros', 'np.zeros', (['A_row'], {}), '(A_row)\n', (8348, 8355), True, 'import numpy as np\n'), ((9491, 9520), 'numpy.delete', 'np.delete', (['A', 'del_row'], {'axis': '(0)'}), '(A, del_row, axis=0)\n', (9500, 9520), True, 'import numpy as np\n'), ((9537, 9566), 'numpy.delete', 'np.delete', (['b', 'del_row'], {'axis': '(0)'}), '(b, del_row, axis=0)\n', (9546, 9566), True, 'import numpy as np\n'), ((9583, 9604), 'numpy.linalg.solve', 'np.linalg.solve', (['A', 'b'], {}), '(A, b)\n', (9598, 9604), True, 'import numpy as np\n'), ((4339, 4352), 'numpy.array', 'np.array', (['[0]'], {}), '([0])\n', (4347, 4352), True, 'import numpy as np\n'), ((4847, 4860), 'numpy.array', 'np.array', (['[0]'], {}), '([0])\n', (4855, 4860), True, 'import numpy as np\n'), ((6299, 6331), 'numpy.ones', 'np.ones', (['(order - 1,)'], {'dtype': 'int'}), '((order - 1,), dtype=int)\n', (6306, 6331), True, 'import numpy as np\n'), ((9925, 9967), 'numpy.ones', 'np.ones', (['(num_interior_points,)'], {'dtype': 'int'}), '((num_interior_points,), dtype=int)\n', (9932, 9967), True, 'import numpy as np\n'), ((5886, 5907), 'numpy.count_nonzero', 'np.count_nonzero', (['row'], {}), '(row)\n', (5902, 5907), True, 'import numpy as np\n'), ((9409, 9430), 'numpy.count_nonzero', 'np.count_nonzero', (['row'], {}), '(row)\n', (9425, 9430), True, 'import numpy as np\n')] |
"""Provides utilities for creating and working with Databases in ESPEI
"""
import logging
from typing import Dict, Union
import sympy
from pycalphad import Database, variables as v
import espei.refdata
from espei.utils import extract_aliases
_log = logging.getLogger(__name__)
def _get_ser_data(element, ref_state, fallback_ref_state="SGTE91") -> Dict[str, Union[str, float]]:
"""Return a dictionary of the stable element reference (SER) data.
If no SER data is found, returns an empty dictionary.
"""
ser_ref_state = ref_state + "SER"
# Return an empty dict for backwards compatibility, since the SER data may not exist
ser_dict = getattr(espei.refdata, ser_ref_state, {})
fallback_ser_ref_state = fallback_ref_state + "SER"
fallback_ser_dict = getattr(espei.refdata, fallback_ser_ref_state)
el_ser_data = ser_dict.get(element)
if el_ser_data is None and ref_state == fallback_ref_state:
# No data found, no fallback alternative
_log.warning("%s has no entry in the %s reference data. Fitting formation energies will not be possible.", element, ser_ref_state)
elif el_ser_data is None:
# No data found, try the fallback
el_ser_data = fallback_ser_dict.get(element)
if el_ser_data is None:
# No data found in the fallback
_log.warning("%s has no entry in the %s reference data nor in the %s fallback reference data. Fitting formation energies will not be possible.", element, ser_ref_state + "SER", fallback_ser_ref_state)
return {}
else:
# Data found in the fallback
_log.trace("%s has no entry in the %s reference data, but was available in the %s fallback reference data.", element, ser_ref_state + "SER", fallback_ser_ref_state)
if el_ser_data is not None:
return el_ser_data
else:
return {}
def initialize_database(phase_models, ref_state, dbf=None, fallback_ref_state="SGTE91"):
"""Return a Database boostraped with elements, species, phases and unary lattice stabilities.
Parameters
----------
phase_models : Dict[str, Any]
Dictionary of components and phases to fit.
ref_state : str
String of the reference data to use, e.g. 'SGTE91' or 'SR2016'
dbf : Optional[Database]
Initial pycalphad Database that can have parameters that would not be fit by ESPEI
fallback_ref_state : str
String of the reference data to use for SER data, defaults to 'SGTE91'
Returns
-------
Database
A new pycalphad Database object, or a modified one if it was given.
"""
if dbf is None:
dbf = Database()
lattice_stabilities = getattr(espei.refdata, ref_state)
ser_stability = getattr(espei.refdata, ref_state + "Stable")
aliases = extract_aliases(phase_models)
phases = sorted({ph.upper() for ph in phase_models["phases"].keys()})
elements = {el.upper() for el in phase_models["components"]}
dbf.elements.update(elements)
dbf.species.update({v.Species(el, {el: 1}, 0) for el in elements})
# Add SER reference data for this element
for element in dbf.elements:
if element in dbf.refstates:
continue # Do not clobber user reference states
el_ser_data = _get_ser_data(element, ref_state, fallback_ref_state=fallback_ref_state)
# Try to look up the alias that we are using in this fitting
el_ser_data["phase"] = aliases.get(el_ser_data["phase"], el_ser_data["phase"])
# Don't warn if the element is a species with no atoms because per-atom
# formation energies are not possible (e.g. VA (VACUUM) or /- (ELECTRON_GAS))
if el_ser_data["phase"] not in phases and v.Species(element).number_of_atoms != 0:
# We have the Gibbs energy expression that we need in the reference
# data, but this phase is not a candidate in the phase models. The
# phase won't be added to the database, so looking up the phases's
# energy won't work.
_log.warning(
"The reference phase for %s, %s, is not in the supplied phase models "
"and won't be added to the Database phases. Fitting formation "
"energies will not be possible.", element, el_ser_data["phase"]
)
dbf.refstates[element] = el_ser_data
# Add the phases
for phase_name, phase_data in phase_models['phases'].items():
if phase_name not in dbf.phases.keys(): # Do not clobber user phases
# TODO: Need to support model hints for: magnetic, order-disorder, etc.
site_ratios = phase_data['sublattice_site_ratios']
subl_model = phase_data['sublattice_model']
# Only generate the sublattice model for active components
subl_model = [sorted(set(subl).intersection(dbf.elements)) for subl in subl_model]
if all(len(subl) > 0 for subl in subl_model):
dbf.add_phase(phase_name, dict(), site_ratios)
dbf.add_phase_constituents(phase_name, subl_model)
# Add the GHSER functions to the Database
for element in dbf.elements:
# Use setdefault here to not clobber user-provided functions
if element == "VA":
dbf.symbols.setdefault("GHSERVA", 0)
else:
# note that `c.upper()*2)[:2]` returns "AL" for "Al" and "BB" for "B"
# Using this ensures that GHSER functions will be unique, e.g.
# GHSERC would be an abbreviation for GHSERCA.
sym_name = "GHSER" + (element.upper()*2)[:2]
dbf.symbols.setdefault(sym_name, ser_stability[element])
return dbf
| [
"logging.getLogger",
"pycalphad.variables.Species",
"espei.utils.extract_aliases",
"pycalphad.Database"
] | [((251, 278), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (268, 278), False, 'import logging\n'), ((2808, 2837), 'espei.utils.extract_aliases', 'extract_aliases', (['phase_models'], {}), '(phase_models)\n', (2823, 2837), False, 'from espei.utils import extract_aliases\n'), ((2658, 2668), 'pycalphad.Database', 'Database', ([], {}), '()\n', (2666, 2668), False, 'from pycalphad import Database, variables as v\n'), ((3035, 3060), 'pycalphad.variables.Species', 'v.Species', (['el', '{el: 1}', '(0)'], {}), '(el, {el: 1}, 0)\n', (3044, 3060), True, 'from pycalphad import Database, variables as v\n'), ((3727, 3745), 'pycalphad.variables.Species', 'v.Species', (['element'], {}), '(element)\n', (3736, 3745), True, 'from pycalphad import Database, variables as v\n')] |
#!/usr/bin/python3
'''
NAME:
lf_json_test.py
PURPOSE:
EXAMPLE:
./lf_json_test.py -
NOTES:
TO DO NOTES:
'''
import os
import sys
if sys.version_info[0] != 3:
print("This script requires Python3")
exit()
from time import sleep
import argparse
import json
#if 'py-json' not in sys.path:
# sys.path.append(os.path.join(os.path.abspath('..'), 'py-json'))
# print("path: {}".format(os.path.join(os.path.abspath('..'))))
if 'py-json' not in sys.path:
sys.path.append(os.path.join(os.path.abspath('..'), 'py-json'))
from LANforge import lf_json_autogen
class lf_read_json():
def __init__(self):
self.timeout = 10
def preprocess_data(self):
pass
def main():
# arguments
parser = argparse.ArgumentParser(
prog='lf_json_test.py',
formatter_class=argparse.RawTextHelpFormatter,
epilog='''\
lf_json_test.py : lf json test
''',
description='''\
lf_json_test.py
-----------
Summary :
---------
./lf_dataplane_json.py --mgr 192.168.0.101 --port 8080 --lf_user lanforge --lf_password <PASSWORD> --instance_name dataplane-instance --config_name test_con --upstream 1.1.eth1 --dut asus_5g --duration 15s --station 1.1.13.sta0002 --download_speed 85% --upload_speed 0 --raw_line 'pkts: Custom;60;MTU' --raw_line 'cust_pkt_sz: 88 1200' --raw_line 'directions: DUT Transmit' --raw_line 'traffic_types: UDP' --raw_line 'bandw_options: 20' --raw_line 'spatial_streams: 1
''')
#parser.add_argument('--json', help="--json <config.json> json input file", default="config.json")
parser.add_argument('--cmd', help="--cmd <json_cmd> json command", default="")
args = parser.parse_args()
json_cmd = args.cmd
print("json cmd {}".format(json_cmd))
#with open(config_json, 'r') as config_file:
# config_data = json.load(config_file)
#print(config_data)
lf_get = lf_json_autogen.LFJsonGet(lfclient_host='192.168.0.101',
lfclient_port=8080,
debug_=True,
)
duts = lf_get.get_chamber(fields = [lf_get.duts])
print("duts {}".format(duts))
print("END lf_read_json.py")
if __name__ == "__main__":
main() | [
"os.path.abspath",
"argparse.ArgumentParser",
"LANforge.lf_json_autogen.LFJsonGet"
] | [((754, 1494), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'prog': '"""lf_json_test.py"""', 'formatter_class': 'argparse.RawTextHelpFormatter', 'epilog': '""" lf_json_test.py : lf json test\n """', 'description': '"""lf_json_test.py\n-----------\n\nSummary :\n---------\n\n\n./lf_dataplane_json.py --mgr 192.168.0.101 --port 8080 --lf_user lanforge --lf_password <PASSWORD> --instance_name dataplane-instance --config_name test_con --upstream 1.1.eth1 --dut asus_5g --duration 15s --station 1.1.13.sta0002 --download_speed 85% --upload_speed 0 --raw_line \'pkts: Custom;60;MTU\' --raw_line \'cust_pkt_sz: 88 1200\' --raw_line \'directions: DUT Transmit\' --raw_line \'traffic_types: UDP\' --raw_line \'bandw_options: 20\' --raw_line \'spatial_streams: 1\n\n """'}), '(prog=\'lf_json_test.py\', formatter_class=argparse.\n RawTextHelpFormatter, epilog=\n """ lf_json_test.py : lf json test\n """,\n description=\n """lf_json_test.py\n-----------\n\nSummary :\n---------\n\n\n./lf_dataplane_json.py --mgr 192.168.0.101 --port 8080 --lf_user lanforge --lf_password <PASSWORD> --instance_name dataplane-instance --config_name test_con --upstream 1.1.eth1 --dut asus_5g --duration 15s --station 1.1.13.sta0002 --download_speed 85% --upload_speed 0 --raw_line \'pkts: Custom;60;MTU\' --raw_line \'cust_pkt_sz: 88 1200\' --raw_line \'directions: DUT Transmit\' --raw_line \'traffic_types: UDP\' --raw_line \'bandw_options: 20\' --raw_line \'spatial_streams: 1\n\n """\n )\n', (777, 1494), False, 'import argparse\n'), ((1936, 2029), 'LANforge.lf_json_autogen.LFJsonGet', 'lf_json_autogen.LFJsonGet', ([], {'lfclient_host': '"""192.168.0.101"""', 'lfclient_port': '(8080)', 'debug_': '(True)'}), "(lfclient_host='192.168.0.101', lfclient_port=8080,\n debug_=True)\n", (1961, 2029), False, 'from LANforge import lf_json_autogen\n'), ((504, 525), 'os.path.abspath', 'os.path.abspath', (['""".."""'], {}), "('..')\n", (519, 525), False, 'import os\n')] |
from django.shortcuts import render,redirect
# Create your views here.
from django.http import HttpResponse
from django.http import JsonResponse
import requests
import json
def getResponseProducts(request):
try:
getResponse = requests.get('https://testbankapi.firebaseio.com/products.json')
arrayJson = list(getResponse.json().items())
sumvalue = sum([o[1]['value'] for o in arrayJson ])
except:
return JsonResponse({"Ocurrio un error"},safe=False)
return render(request,'index.html',{'arrayJson':arrayJson, 'sumvalue': sumvalue})
def postResponseProducts(request):
data = {
"category": request.POST['category'],
"description": request.POST['description'],
"identification": request.POST['identification'],
"initdate": request.POST['initdate'],
"productname": request.POST['productname'],
"value":int(request.POST['value'])
}
getResponse = requests.post('https://testbankapi.firebaseio.com/products.json',data=json.dumps(data))
try:
getResponse.raise_for_status()
return redirect('/')
except requests.exceptions.HTTPError as err:
return JsonResponse({'Status':'ERROR','message':'Error al guardar'})
raise SystemExit(err)
def putProducts (request):
data = {
"category": request.POST['category'],
"description": request.POST['description'],
"identification": request.POST['identification'],
"initdate": request.POST['initdate'],
"productname": request.POST['productname'],
"value":int(request.POST['value'])
}
url = 'https://testbankapi.firebaseio.com/products/'+request.POST['id']+".json"
putResponse = requests.put(url, data=json.dumps(data))
try:
putResponse.raise_for_status()
print(putResponse.raise_for_status())
return redirect('/')
except requests.exceptions.HTTPError as err:
return JsonResponse({'status':'Error','message':'Error al actualizar el producto'})
print(putResponse)
def deleteProducts (request):
url = 'https://testbankapi.firebaseio.com/products/'+request.POST['id']+".json"
deleteResponse = requests.delete(url)
try:
deleteResponse.raise_for_status()
print(deleteResponse.raise_for_status())
return redirect('/')
except requests.exceptions.HTTPError as err:
return JsonResponse({'status':'Error','message':'Error al eliminar el producto'})
print(deleteResponse) | [
"django.shortcuts.render",
"django.http.JsonResponse",
"json.dumps",
"requests.get",
"requests.delete",
"django.shortcuts.redirect"
] | [((486, 563), 'django.shortcuts.render', 'render', (['request', '"""index.html"""', "{'arrayJson': arrayJson, 'sumvalue': sumvalue}"], {}), "(request, 'index.html', {'arrayJson': arrayJson, 'sumvalue': sumvalue})\n", (492, 563), False, 'from django.shortcuts import render, redirect\n'), ((2062, 2082), 'requests.delete', 'requests.delete', (['url'], {}), '(url)\n', (2077, 2082), False, 'import requests\n'), ((235, 299), 'requests.get', 'requests.get', (['"""https://testbankapi.firebaseio.com/products.json"""'], {}), "('https://testbankapi.firebaseio.com/products.json')\n", (247, 299), False, 'import requests\n'), ((1042, 1055), 'django.shortcuts.redirect', 'redirect', (['"""/"""'], {}), "('/')\n", (1050, 1055), False, 'from django.shortcuts import render, redirect\n'), ((1759, 1772), 'django.shortcuts.redirect', 'redirect', (['"""/"""'], {}), "('/')\n", (1767, 1772), False, 'from django.shortcuts import render, redirect\n'), ((2184, 2197), 'django.shortcuts.redirect', 'redirect', (['"""/"""'], {}), "('/')\n", (2192, 2197), False, 'from django.shortcuts import render, redirect\n'), ((426, 472), 'django.http.JsonResponse', 'JsonResponse', (["{'Ocurrio un error'}"], {'safe': '(False)'}), "({'Ocurrio un error'}, safe=False)\n", (438, 472), False, 'from django.http import JsonResponse\n'), ((971, 987), 'json.dumps', 'json.dumps', (['data'], {}), '(data)\n', (981, 987), False, 'import json\n'), ((1115, 1179), 'django.http.JsonResponse', 'JsonResponse', (["{'Status': 'ERROR', 'message': 'Error al guardar'}"], {}), "({'Status': 'ERROR', 'message': 'Error al guardar'})\n", (1127, 1179), False, 'from django.http import JsonResponse\n'), ((1646, 1662), 'json.dumps', 'json.dumps', (['data'], {}), '(data)\n', (1656, 1662), False, 'import json\n'), ((1831, 1910), 'django.http.JsonResponse', 'JsonResponse', (["{'status': 'Error', 'message': 'Error al actualizar el producto'}"], {}), "({'status': 'Error', 'message': 'Error al actualizar el producto'})\n", (1843, 1910), False, 'from django.http import JsonResponse\n'), ((2256, 2333), 'django.http.JsonResponse', 'JsonResponse', (["{'status': 'Error', 'message': 'Error al eliminar el producto'}"], {}), "({'status': 'Error', 'message': 'Error al eliminar el producto'})\n", (2268, 2333), False, 'from django.http import JsonResponse\n')] |
"""
Certificate service
"""
import logging
from django.core.exceptions import ObjectDoesNotExist
from opaque_keys.edx.keys import CourseKey
from lms.djangoapps.certificates.generation_handler import is_on_certificate_allowlist
from lms.djangoapps.certificates.models import GeneratedCertificate
from lms.djangoapps.utils import _get_key
log = logging.getLogger(__name__)
class CertificateService:
"""
User Certificate service
"""
def invalidate_certificate(self, user_id, course_key_or_id):
"""
Invalidate the user certificate in a given course if it exists and the user is not on the allowlist for this
course run.
"""
course_key = _get_key(course_key_or_id, CourseKey)
if is_on_certificate_allowlist(user_id, course_key):
log.info(f'User {user_id} is on the allowlist for {course_key}. The certificate will not be invalidated.')
return False
try:
generated_certificate = GeneratedCertificate.objects.get(
user=user_id,
course_id=course_key
)
generated_certificate.invalidate(source='certificate_service')
except ObjectDoesNotExist:
log.warning(
'Invalidation failed because a certificate for user %d in course %s does not exist.',
user_id,
course_key
)
return False
return True
| [
"logging.getLogger",
"lms.djangoapps.utils._get_key",
"lms.djangoapps.certificates.models.GeneratedCertificate.objects.get",
"lms.djangoapps.certificates.generation_handler.is_on_certificate_allowlist"
] | [((348, 375), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (365, 375), False, 'import logging\n'), ((697, 734), 'lms.djangoapps.utils._get_key', '_get_key', (['course_key_or_id', 'CourseKey'], {}), '(course_key_or_id, CourseKey)\n', (705, 734), False, 'from lms.djangoapps.utils import _get_key\n'), ((746, 794), 'lms.djangoapps.certificates.generation_handler.is_on_certificate_allowlist', 'is_on_certificate_allowlist', (['user_id', 'course_key'], {}), '(user_id, course_key)\n', (773, 794), False, 'from lms.djangoapps.certificates.generation_handler import is_on_certificate_allowlist\n'), ((990, 1058), 'lms.djangoapps.certificates.models.GeneratedCertificate.objects.get', 'GeneratedCertificate.objects.get', ([], {'user': 'user_id', 'course_id': 'course_key'}), '(user=user_id, course_id=course_key)\n', (1022, 1058), False, 'from lms.djangoapps.certificates.models import GeneratedCertificate\n')] |
import marshmallow
import pytest
from marshmallow import fields
from queue_messaging.data import structures
class FancyModelSchema(marshmallow.Schema):
uuid_field = fields.UUID(required=True)
string_field = fields.String(required=False)
class FancyModel(structures.Model):
class Meta:
schema = FancyModelSchema
def test_creating_model():
model = FancyModel(
uuid_field=1,
string_field='123456789',
)
assert model.uuid_field == 1
assert model.string_field == '123456789'
def test_if_creating_model_with_missing_optional_field_is_ok():
model = FancyModel(
uuid_field=1,
)
assert model.uuid_field == 1
assert model.string_field is None
def test_if_creating_model_with_invalid_fields_raises_exception():
with pytest.raises(TypeError) as excinfo:
FancyModel(
uuid_field=1,
string_field='123456789',
not_existing_field='abc'
)
assert str(excinfo.value) == "Got unexpected fields '{'not_existing_field'}'"
def test_if_creating_model_with_missing_required_field_raises_exception():
with pytest.raises(TypeError) as excinfo:
FancyModel(
string_field='aaa',
)
assert str(excinfo.value) == "Missing required fields '{'uuid_field'}'"
| [
"pytest.raises",
"marshmallow.fields.String",
"marshmallow.fields.UUID"
] | [((172, 198), 'marshmallow.fields.UUID', 'fields.UUID', ([], {'required': '(True)'}), '(required=True)\n', (183, 198), False, 'from marshmallow import fields\n'), ((218, 247), 'marshmallow.fields.String', 'fields.String', ([], {'required': '(False)'}), '(required=False)\n', (231, 247), False, 'from marshmallow import fields\n'), ((796, 820), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (809, 820), False, 'import pytest\n'), ((1132, 1156), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (1145, 1156), False, 'import pytest\n')] |
from line import Line
from matrix import Matrix
def str_to_point(str):
p = str.split(',')
point = (int(p[0]),int(p[1]))
return point
def process_file():
lines = open('input','r').readlines()
rects = []
for line in lines:
parts = line.split("->")
p1 = str_to_point(parts[0])
p2 = str_to_point(parts[1])
rects.append(Line(p1,p2))
return (rects)
lines = process_file()
matrix = Matrix()
#print(matrix)
#print(lines[0].calc_points())
for line in lines:
matrix.add_line(line)
print(matrix.get_num_inter()) | [
"line.Line",
"matrix.Matrix"
] | [((443, 451), 'matrix.Matrix', 'Matrix', ([], {}), '()\n', (449, 451), False, 'from matrix import Matrix\n'), ((377, 389), 'line.Line', 'Line', (['p1', 'p2'], {}), '(p1, p2)\n', (381, 389), False, 'from line import Line\n')] |
import visa
import numpy as np
class Agilent54845A:
def __init__(self,instrument,chan_num=1):
"""
Default constructor only requires direct access to the underlyign visa
handler. See the method fromResourceManager for a more user-friendly way
of constructing the class.
"""
self.channel_num = chan_num
self.instrument = instrument
@classmethod
def fromResourceManager(cls,resource_manager,device_type="GPIB"):
"""
Parameters:
-----------
resource_manager Resource manager from the visa module.
See pyvisa documentation.
device_type Specifies the type of device to
communicate with.
"""
resources = resource_manager.list_resources()
gpib_resources = list(filter(lambda resource_id :
device_type in resource_id, resources))
# need to handle if no GPIB devices found
if len(gpib_resources) == 0: raise Exception("No GPIB devices found.")
# need to handle if more than one GPIB resource connected.
# TODO: this will be necessary when we add AWG or another GPIB device.
if len(gpib_resources) > 1: raise Exception("More than one device found")
instrument = resource_manager.open_resource(gpib_resources[0])
instrument.timeout = 6000
#instrument.write("*RST")
return cls(instrument)
def get_xrange(self):
return self.instrument.query_ascii_values("WAV:XRAN?")[0]
def get_xunits(self):
return self.instrument.query("WAV:XUN?").rstrip('\n')
def get_yrange(self):
return self.instrument.query_ascii_values("WAV:YRAN?")[0]
def get_yunits(self):
return self.instrument.query("WAV:YUN?").rstrip('\n')
def get_offset(self):
return self.instrument.query_ascii_values("CHAN%d:OFFS?" % self.channel_num)[0]
def get_bottom_bound(self):
""" Gets the voltage at the bottom of the scope window. """
return self.get_offset() - 0.5*self.get_yrange()
def get_top_bound(self):
""" Gets the voltage at the top of the scope window. """
return self.get_offset() + 0.5*self.get_yrange()
def set_offset(self,value):
""" Sets the center of the window of the scope. """
offset_command = "CHAN%d:OFFS " % self.channel_num
self.instrument.write(offset_command + str(value))
def set_range(self,value):
""" Sets the total vertical range of the scope. """
range_command = "CHAN%d:RANG " % self.channel_num
self.instrument.write(range_command + str(value))
def recenter(self):
v_average = self.instrument.query_ascii_values("MEAS:VAV?")[0]
self.instrument.write("CHAN" + str(self.channel_num) + ":OFFS " + str(v_average))
def scope_autoscale(self):
"""
Instructs the oscilloscope to autoscale the axes. Returns the
values of the ranges after doing the autoscale.
"""
self.instrument.write("AUT")
# return range of x,y values after doing auto scale
return {'x' : [self.get_xrange(), self.get_xunits()],
'y': [self.get_yrange(), self.get_yunits()]}
def reset_window(self):
"""
Resets the window to full scale (16 V), then brings the signal to center.
"""
self.set_range(16)
self.recenter()
self.recenter() # twice needed in case signal was out of range the first time.
def autoscale(self):
"""
Auto scaling function to find the optimal window for a given signal.
"""
self.reset_window()
self.rescale(True)
def rescale(self,quick_scale=True):
"""
Rescales the window based on measurements on signal iteratively as best it
can to fill a noisy signal + 5sigma of fluctauations to the entire window.
By setting quick_scale=True, it will first attempt a rough guess of the final
window config before starting an iterative procedure. If this is used just after
reset_window(), this should speed up the scaling.
Usage:
self.reset_window()
self.rescale(False)
Parameters:
-----------
quick_scale Boolean to to decide whether or not
to 'one-shot' the window config. Use
only if used a reset_window() before.
"""
self.instrument.write("MEAS:CLE") # clear current measurements.
self.instrument.write("MEAS:STAT ON") # turn on statistics tracking
# measurements to perform.
self.instrument.write("MEAS:VMAX")
self.instrument.write("MEAS:VMIN")
self.instrument.write("MEAS:VAV")
time.sleep(8)
# contains results of all three measurements.
query = self.instrument.query("MEAS:RES?").split(",")
# maximum voltage of signal
vmax = np.array(query[1:7],dtype=float)
if query[0].upper() != "V MAX(1)":
raise Exception(query[0] + " is not measuring maximum voltage.")
# minimum voltage of signal
vmin = np.array(query[8:14],dtype=float)
if query[7].upper() != "V MIN(1)":
raise Exception(query[7] + " is not measuring minimum voltage.")
# average signal of signal
vav = np.array(query[15:21],dtype=float)
if query[14].upper() != "V AVG(1)":
raise Exception(query[14] + " is not measuring minimum voltage.")
num_samples = vmax[-1]
if num_samples < 5:
raise Warning("Only collected " + str(num_samples) + " samples.")
# if signal goes outside of current window bounds, zoom out before continuing.
if vmin[1] < self.get_bottom_bound() or vmax[2] > self.get_top_bound():
self.set_offset((vav[2] + vav[1])/2)
self.set_range(self.get_yrange()*2)
self.rescale(False)
return
# find the maximum deviation of the signal from its average while accounting
# for 5 sigma of fluctuations.
v_amp = vmax if np.abs(vmax[2] - vav[2]) > np.abs(vmin[2] - vav[2] ) else vmin
v_amp_max = np.abs(v_amp[2] - vav[2]) + 5*np.sqrt(2)*v_amp[4]
# if high voltage signal, oscilloscope is not capable of performing high
# resolution zooms. If this is the case, attempt zoom beyond scope capabilities.
# Additionally, turn off 'one-shot' attempt as this is not accurate for
# high voltages.
rmin = 0.064
if vav[2] > 1.0:
rmin = 0.8
quick_scale = False
# ESCAPE CONDITION
range = self.get_yrange()
if range/2 < v_amp_max or range/2 < rmin:
self.set_offset((vav[2] + vav[1])/2)
return
# one-shot attempt
if quick_scale:
self.set_range(v_amp_max)
self.recenter()
self.rescale(False)
return
# iterative attempts
self.set_range(range/2)
self.set_offset((vav[2] + vav[1])/2)
self.rescale(False)
def id(self):
return self.instrument.query('*IDN?')
def set_waveform_source(self,channel_num):
"""
Parameters
----------
channel_num Sets the source for the WAVEFORM operation
the channel given by channel_num.
"""
self.channel_num = channel_num
self.instrument.write("WAV:SOUR CHAN %d" % channel_num)
def enable_header_data(self):
self.instrument.write("SYST:HEAD ON")
def disable_header_data(self):
self.instrument.write("SYST:HEAD OFF")
def get_waveform(self):
"""
Main data-taking function. Grabs the waveform currently measured by
oscilloscope while checking that the waveform is currently within window
bounds. If not, will automatically autoscale.
"""
num_attempts = 0
while True:
wave = self.instrument.query_ascii_values("WAV:DATA?",container = np.array)
within_bounds = (wave < self.get_top_bound()).all() and (wave > self.get_bottom_bound()).all()
if within_bounds:
return wave
else:
self.autoscale()
num_attempts += 1
def get_num_points(self):
"""
Returns the number of points measured by the scope for the waveform function.
"""
return int(self.instrument.query_ascii_values("WAV:POIN?")[0])
def close(self):
self.instrument.close()
| [
"numpy.array",
"numpy.sqrt",
"numpy.abs"
] | [((5140, 5173), 'numpy.array', 'np.array', (['query[1:7]'], {'dtype': 'float'}), '(query[1:7], dtype=float)\n', (5148, 5173), True, 'import numpy as np\n'), ((5345, 5379), 'numpy.array', 'np.array', (['query[8:14]'], {'dtype': 'float'}), '(query[8:14], dtype=float)\n', (5353, 5379), True, 'import numpy as np\n'), ((5549, 5584), 'numpy.array', 'np.array', (['query[15:21]'], {'dtype': 'float'}), '(query[15:21], dtype=float)\n', (5557, 5584), True, 'import numpy as np\n'), ((6392, 6417), 'numpy.abs', 'np.abs', (['(v_amp[2] - vav[2])'], {}), '(v_amp[2] - vav[2])\n', (6398, 6417), True, 'import numpy as np\n'), ((6309, 6333), 'numpy.abs', 'np.abs', (['(vmax[2] - vav[2])'], {}), '(vmax[2] - vav[2])\n', (6315, 6333), True, 'import numpy as np\n'), ((6336, 6360), 'numpy.abs', 'np.abs', (['(vmin[2] - vav[2])'], {}), '(vmin[2] - vav[2])\n', (6342, 6360), True, 'import numpy as np\n'), ((6422, 6432), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (6429, 6432), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
import unittest
test_records = [
dict(doctype='Item', item_code='Food Item 1',
item_group='Products', is_stock_item=0),
dict(doctype='Item', item_code='Food Item 2',
item_group='Products', is_stock_item=0),
dict(doctype='Item', item_code='Food Item 3',
item_group='Products', is_stock_item=0),
dict(doctype='Item', item_code='Food Item 4',
item_group='Products', is_stock_item=0),
dict(doctype='Restaurant Menu', restaurant='Test Restaurant 1', name='Test Restaurant 1 Menu 1',
items = [
dict(item='Food Item 1', rate=400),
dict(item='Food Item 2', rate=300),
dict(item='Food Item 3', rate=200),
dict(item='Food Item 4', rate=100),
]),
dict(doctype='Restaurant Menu', restaurant='Test Restaurant 1', name='Test Restaurant 1 Menu 2',
items = [
dict(item='Food Item 1', rate=450),
dict(item='Food Item 2', rate=350),
])
]
class TestRestaurantMenu(unittest.TestCase):
def test_price_list_creation_and_editing(self):
menu1 = frappe.get_doc('Restaurant Menu', 'Test Restaurant 1 Menu 1')
menu1.save()
menu2 = frappe.get_doc('Restaurant Menu', 'Test Restaurant 1 Menu 2')
menu2.save()
self.assertTrue(frappe.db.get_value('Price List', 'Test Restaurant 1 Menu 1'))
self.assertEqual(frappe.db.get_value('Item Price',
dict(price_list = 'Test Restaurant 1 Menu 1', item_code='Food Item 1'), 'price_list_rate'), 400)
self.assertEqual(frappe.db.get_value('Item Price',
dict(price_list = 'Test Restaurant 1 Menu 2', item_code='Food Item 1'), 'price_list_rate'), 450)
menu1.items[0].rate = 401
menu1.save()
self.assertEqual(frappe.db.get_value('Item Price',
dict(price_list = 'Test Restaurant 1 Menu 1', item_code='Food Item 1'), 'price_list_rate'), 401)
menu1.items[0].rate = 400
menu1.save()
| [
"frappe.get_doc",
"frappe.db.get_value"
] | [((1132, 1193), 'frappe.get_doc', 'frappe.get_doc', (['"""Restaurant Menu"""', '"""Test Restaurant 1 Menu 1"""'], {}), "('Restaurant Menu', 'Test Restaurant 1 Menu 1')\n", (1146, 1193), False, 'import frappe\n'), ((1220, 1281), 'frappe.get_doc', 'frappe.get_doc', (['"""Restaurant Menu"""', '"""Test Restaurant 1 Menu 2"""'], {}), "('Restaurant Menu', 'Test Restaurant 1 Menu 2')\n", (1234, 1281), False, 'import frappe\n'), ((1316, 1377), 'frappe.db.get_value', 'frappe.db.get_value', (['"""Price List"""', '"""Test Restaurant 1 Menu 1"""'], {}), "('Price List', 'Test Restaurant 1 Menu 1')\n", (1335, 1377), False, 'import frappe\n')] |
# Generated by Django 3.1.4 on 2021-01-09 17:51
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('beers', '0034_matchfiltercollab'),
]
operations = [
migrations.DeleteModel(
name='MatchFilterCollab',
),
]
| [
"django.db.migrations.DeleteModel"
] | [((236, 284), 'django.db.migrations.DeleteModel', 'migrations.DeleteModel', ([], {'name': '"""MatchFilterCollab"""'}), "(name='MatchFilterCollab')\n", (258, 284), False, 'from django.db import migrations\n')] |
#!/usr/bin/env python3
import argparse
import pickle
import numpy as np
import os.path
from tqdm import tqdm
from props import getNode
from lib import matcher
from lib import match_cleanup
from lib import project
# Reset all match point locations to their original direct
# georeferenced locations based on estimated camera pose and
# projection onto DEM earth surface
parser = argparse.ArgumentParser(description='Keypoint projection.')
parser.add_argument('project', help='project directory')
args = parser.parse_args()
m = matcher.Matcher()
proj = project.ProjectMgr(args.project)
proj.load_images_info()
proj.load_features(descriptors=False)
#proj.undistort_keypoints()
proj.load_match_pairs()
match_cleanup.merge_duplicates(proj)
# enable the following code to visualize the matches after collapsing
# identical uv coordinates
if False:
for i, i1 in enumerate(proj.image_list):
for j, i2 in enumerate(proj.image_list):
if i >= j:
# don't repeat reciprocal matches
continue
if len(i1.match_list[j]):
print("Showing %s vs %s" % (i1.name, i2.name))
status = m.showMatchOrient(i1, i2, i1.match_list[j])
match_cleanup.check_for_pair_dups(proj)
# enable the following code to visualize the matches after eliminating
# duplicates (duplicates can happen after collapsing uv coordinates.)
if False:
for i, i1 in enumerate(proj.image_list):
for j, i2 in enumerate(proj.image_list):
if i >= j:
# don't repeat reciprocal matches
continue
if len(i1.match_list[j]):
print("Showing %s vs %s" % (i1.name, i2.name))
status = m.showMatchOrient(i1, i2, i1.match_list[j])
match_cleanup.check_for_1vn_dups(proj)
matches_direct = match_cleanup.make_match_structure(proj)
# Note to self: I don't think we need the matches_direct file any more
# (except for debugging possibly in the future.)
#
#print("Writing matches_direct file ...")
#direct_file = os.path.join(proj.analysis_dir, "matches_direct")
#pickle.dump(matches_direct, open(direct_file, "wb"))
matches_grouped = match_cleanup.link_matches(proj, matches_direct)
print("Writing full group chain matches_grouped file ...")
pickle.dump(matches_grouped, open(os.path.join(proj.analysis_dir, "matches_grouped"), "wb"))
| [
"lib.match_cleanup.link_matches",
"lib.match_cleanup.check_for_pair_dups",
"argparse.ArgumentParser",
"lib.matcher.Matcher",
"lib.match_cleanup.make_match_structure",
"lib.project.ProjectMgr",
"lib.match_cleanup.merge_duplicates",
"lib.match_cleanup.check_for_1vn_dups"
] | [((383, 442), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Keypoint projection."""'}), "(description='Keypoint projection.')\n", (406, 442), False, 'import argparse\n'), ((532, 549), 'lib.matcher.Matcher', 'matcher.Matcher', ([], {}), '()\n', (547, 549), False, 'from lib import matcher\n'), ((558, 590), 'lib.project.ProjectMgr', 'project.ProjectMgr', (['args.project'], {}), '(args.project)\n', (576, 590), False, 'from lib import project\n'), ((706, 742), 'lib.match_cleanup.merge_duplicates', 'match_cleanup.merge_duplicates', (['proj'], {}), '(proj)\n', (736, 742), False, 'from lib import match_cleanup\n'), ((1214, 1253), 'lib.match_cleanup.check_for_pair_dups', 'match_cleanup.check_for_pair_dups', (['proj'], {}), '(proj)\n', (1247, 1253), False, 'from lib import match_cleanup\n'), ((1777, 1815), 'lib.match_cleanup.check_for_1vn_dups', 'match_cleanup.check_for_1vn_dups', (['proj'], {}), '(proj)\n', (1809, 1815), False, 'from lib import match_cleanup\n'), ((1834, 1874), 'lib.match_cleanup.make_match_structure', 'match_cleanup.make_match_structure', (['proj'], {}), '(proj)\n', (1868, 1874), False, 'from lib import match_cleanup\n'), ((2178, 2226), 'lib.match_cleanup.link_matches', 'match_cleanup.link_matches', (['proj', 'matches_direct'], {}), '(proj, matches_direct)\n', (2204, 2226), False, 'from lib import match_cleanup\n')] |
import torch
import torch.nn as nn
import physics_aware_training.digital_twin_utils
class SplitInputParameterNet(nn.Module):
def __init__(self,
input_dim,
nparams,
output_dim,
parameterNunits = [100,100,100],
internalNunits = [10,10,10]):
'''
Defines network that splits inputs x into physical system input and parameters.
Inputs are propagated through a "main" neural network whose weights are predicted by an
auxiliary neural network whose inputs are the parameters.
Args:
inputDim (int): dimension of physical system inputs
outputDim (int): dimension of physical system outputs
parameterDim (int): dimension of all physical system parameters combined
parameterNunits (list of int): defines the number of hidden units per layer in the
auxiliary parameter network.
internalDim (int): number of hidden units per layer of the main neural network that
propagates physical system inputs
inputNlayers (int): number of hidden layers of main neural network
'''
super(SplitInputParameterNet, self).__init__()
self.input_dim = input_dim
self.nparams = nparams
self.output_dim = output_dim
self.internalNunits = internalNunits
self.inputNlayers = len(internalNunits)
nparameters = 0
for i in range(len(internalNunits)-1):
nparameters += internalNunits[i]*internalNunits[i+1]
nparameters += internalNunits[i+1]
# parameterNet is a submodel that predicts a matrix of dimensions
self.parameterNet = torch.nn.Sequential()
self.parameterNet.add_module("fcIn", torch.nn.Linear(nparams, parameterNunits[0]))
for i in range(len(parameterNunits)):
if i<len(parameterNunits)-1:
self.parameterNet.add_module(f"relu{i}", torch.nn.ReLU())
self.parameterNet.add_module(f"fc{i}", torch.nn.Linear(parameterNunits[i], parameterNunits[i+1]))
else:
self.parameterNet.add_module(f"relu{i}", torch.nn.ReLU())
self.parameterNet.add_module(f"fcOut", torch.nn.Linear(parameterNunits[i], nparameters))
# two fully connected input and output layers adjust the input and output dimenstion to
# the internal dimension
self.fcIn = nn.Linear(input_dim, internalNunits[0])
self.fcOut = nn.Linear(internalNunits[-1], output_dim)
def forward(self, x):
batch_size, _ = x.shape
# initialize matrices for inputNet
inputNetMatrices = []
inputNetBiases = []
for i in range(len(self.internalNunits)-1):
inputNetMatrices.append([torch.zeros(batch_size, self.internalNunits[i], self.internalNunits[i+1])])
inputNetBiases.append([torch.zeros(batch_size, self.internalNunits[i+1], 1)])
# split x into physical system inputs and parameters
inputs = x[:, :self.input_dim]
parameters = x[:, self.input_dim:]
# AUXILIARY PARAMETER NETWORK
parameters = self.parameterNet(parameters)
# fill inputNetMatrices with outputs from parameterNet
index = 0
for i in range(len(self.internalNunits)-1):
index_temp = index
index += self.internalNunits[i] * self.internalNunits[i+1]
inputNetMatrices[i] = parameters[:, index_temp:index].reshape(batch_size, self.internalNunits[i+1], self.internalNunits[i])
# fill inputNetBiases with outputs from parameterNet
for i in range(len(self.internalNunits)-1):
index_temp = index
index += self.internalNunits[i+1]
inputNetBiases[i] = parameters[:, index_temp:index].reshape(batch_size, self.internalNunits[i+1], 1)
# MAIN INPUT NETWORK
inputs = self.fcIn(inputs).unsqueeze(-1)
# MAIN INPUT NETWORK
for i in range(len(self.internalNunits)-1):
# apply matrices and biases just filled with outputs from parameterNet
inputs = torch.bmm(inputNetMatrices[i], inputs)
inputs += inputNetBiases[i]
inputs = torch.relu(inputs)
return self.fcOut(inputs.squeeze(-1))
class SplitInputParameterObjective(object):
# define class to smuggle additional arguments into objective function
def __init__(self, train_loader, test_loader, dt_path, input_dim, nparams, output_dim, **modelargs):
self.modelargs = modelargs
self.dt_path = dt_path
self.train_loader = train_loader
self.test_loader = test_loader
self.input_dim = input_dim
self.nparams = nparams
self.output_dim = output_dim
def __call__(self, trial):
lr = trial.suggest_loguniform("lr", 1e-4, 1e-1)
parameterNlayers = trial.suggest_categorical("parameterNlayers", [1, 2, 3, 4, 5])
parameterNunits = []
if parameterNlayers == 1:
parameterNunits.append(int(trial.suggest_loguniform("Nunits1", 50, 1000)))
if parameterNlayers == 2:
parameterNunits.append(int(trial.suggest_loguniform("Nunits1", 50, 1000)))
parameterNunits.append(int(trial.suggest_loguniform("Nunits2", 50, 1000)))
if parameterNlayers == 3:
parameterNunits.append(int(trial.suggest_loguniform("Nunits1", 50, 1000)))
parameterNunits.append(int(trial.suggest_loguniform("Nunits2", 50, 1000)))
parameterNunits.append(int(trial.suggest_loguniform("Nunits3", 50, 1000)))
if parameterNlayers == 4:
parameterNunits.append(int(trial.suggest_loguniform("Nunits1", 50, 1000)))
parameterNunits.append(int(trial.suggest_loguniform("Nunits2", 50, 1000)))
parameterNunits.append(int(trial.suggest_loguniform("Nunits3", 50, 1000)))
parameterNunits.append(int(trial.suggest_loguniform("Nunits4", 50, 1000)))
if parameterNlayers == 5:
parameterNunits.append(int(trial.suggest_loguniform("Nunits1", 50, 1000)))
parameterNunits.append(int(trial.suggest_loguniform("Nunits2", 50, 1000)))
parameterNunits.append(int(trial.suggest_loguniform("Nunits3", 50, 1000)))
parameterNunits.append(int(trial.suggest_loguniform("Nunits4", 50, 1000)))
parameterNunits.append(int(trial.suggest_loguniform("Nunits5", 50, 1000)))
internalNlayers = trial.suggest_categorical("internalNlayers", [1, 2, 3, 4, 5])
internalNunits = []
if parameterNlayers == 1:
internalNunits.append(int(trial.suggest_loguniform("iNunits1", 10, 100)))
if parameterNlayers == 2:
internalNunits.append(int(trial.suggest_loguniform("iNunits1", 10, 100)))
internalNunits.append(int(trial.suggest_loguniform("iNunits2", 10, 100)))
if parameterNlayers == 3:
internalNunits.append(int(trial.suggest_loguniform("iNunits1", 10, 100)))
internalNunits.append(int(trial.suggest_loguniform("iNunits2", 10, 100)))
internalNunits.append(int(trial.suggest_loguniform("iNunits3", 10, 100)))
if parameterNlayers == 4:
internalNunits.append(int(trial.suggest_loguniform("iNunits1", 10, 100)))
internalNunits.append(int(trial.suggest_loguniform("iNunits2", 10, 100)))
internalNunits.append(int(trial.suggest_loguniform("iNunits3", 10, 100)))
internalNunits.append(int(trial.suggest_loguniform("iNunits4", 10, 100)))
if parameterNlayers == 5:
internalNunits.append(int(trial.suggest_loguniform("iNunits1", 10, 100)))
internalNunits.append(int(trial.suggest_loguniform("iNunits2", 10, 100)))
internalNunits.append(int(trial.suggest_loguniform("iNunits3", 10, 100)))
internalNunits.append(int(trial.suggest_loguniform("iNunits4", 10, 100)))
internalNunits.append(int(trial.suggest_loguniform("iNunits5", 10, 100)))
name = f"{self.dt_path}_v{trial.number}" #create name with trial index
value, model_path = physics_aware_training.digital_twin_utils.train_loop_reg_model(
self.train_loader,
self.test_loader,
name,
self.input_dim,
self.nparams,
self.output_dim,
Model = SplitInputParameterNet,
parameterNunits = parameterNunits,
internalNunits = internalNunits,
lr = lr,
**self.modelargs)
trial.set_user_attr('model_path', model_path) #save the model path string in NAS study
return value | [
"torch.nn.ReLU",
"torch.nn.Sequential",
"torch.relu",
"torch.nn.Linear",
"torch.bmm",
"torch.zeros"
] | [((1782, 1803), 'torch.nn.Sequential', 'torch.nn.Sequential', ([], {}), '()\n', (1801, 1803), False, 'import torch\n'), ((2533, 2572), 'torch.nn.Linear', 'nn.Linear', (['input_dim', 'internalNunits[0]'], {}), '(input_dim, internalNunits[0])\n', (2542, 2572), True, 'import torch.nn as nn\n'), ((2594, 2635), 'torch.nn.Linear', 'nn.Linear', (['internalNunits[-1]', 'output_dim'], {}), '(internalNunits[-1], output_dim)\n', (2603, 2635), True, 'import torch.nn as nn\n'), ((1849, 1893), 'torch.nn.Linear', 'torch.nn.Linear', (['nparams', 'parameterNunits[0]'], {}), '(nparams, parameterNunits[0])\n', (1864, 1893), False, 'import torch\n'), ((4267, 4305), 'torch.bmm', 'torch.bmm', (['inputNetMatrices[i]', 'inputs'], {}), '(inputNetMatrices[i], inputs)\n', (4276, 4305), False, 'import torch\n'), ((4367, 4385), 'torch.relu', 'torch.relu', (['inputs'], {}), '(inputs)\n', (4377, 4385), False, 'import torch\n'), ((2039, 2054), 'torch.nn.ReLU', 'torch.nn.ReLU', ([], {}), '()\n', (2052, 2054), False, 'import torch\n'), ((2111, 2170), 'torch.nn.Linear', 'torch.nn.Linear', (['parameterNunits[i]', 'parameterNunits[i + 1]'], {}), '(parameterNunits[i], parameterNunits[i + 1])\n', (2126, 2170), False, 'import torch\n'), ((2245, 2260), 'torch.nn.ReLU', 'torch.nn.ReLU', ([], {}), '()\n', (2258, 2260), False, 'import torch\n'), ((2317, 2365), 'torch.nn.Linear', 'torch.nn.Linear', (['parameterNunits[i]', 'nparameters'], {}), '(parameterNunits[i], nparameters)\n', (2332, 2365), False, 'import torch\n'), ((2903, 2978), 'torch.zeros', 'torch.zeros', (['batch_size', 'self.internalNunits[i]', 'self.internalNunits[i + 1]'], {}), '(batch_size, self.internalNunits[i], self.internalNunits[i + 1])\n', (2914, 2978), False, 'import torch\n'), ((3014, 3068), 'torch.zeros', 'torch.zeros', (['batch_size', 'self.internalNunits[i + 1]', '(1)'], {}), '(batch_size, self.internalNunits[i + 1], 1)\n', (3025, 3068), False, 'import torch\n')] |
'''
Provider for dataset
'''
import os
import os.path
import numpy as np
import time
class SceneflowDataset():
def __init__(self, root='/tmp/FlyingThings3D_subset_processed_35m', npoints=8192, mode = 'train_ft3d'):
self.npoints = npoints
self.mode = mode
self.root = root
if self.mode == 'eval_kitti':
self.samples = self.make_dataset()
self.datapath = root
self.file_list = os.listdir(self.datapath)
self.npoints = 16384
elif self.mode == 'train_ft3d':
self.datapath = os.path.join(self.root, 'train')
self.file_list = os.listdir(self.datapath)
elif self.mode == 'eval_ft3d':
self.datapath = os.path.join(self.root, 'val')
self.file_list = os.listdir(self.datapath)
def __getitem__(self, index):
np.random.seed(0)
if self.mode == 'eval_kitti':
fn = self.samples[index]
else:
fn = self.file_list[index]
fn = os.path.join(self.datapath, fn)
pc1 = os.path.join(fn,'pc1.npy')
pc2 = os.path.join(fn,'pc2.npy')
with open(pc1, 'rb') as fp:
pos1 = np.load(fp)
with open(pc2, 'rb') as fp2:
pos2 = np.load(fp2)
flow = pos2[:, :3] - pos1[:, :3]
if self.mode == 'eval_kitti':
is_ground = np.logical_or(pos1[:,1] < -1.35, pos2[:,1] < -1.35)
not_ground = np.logical_not(is_ground)
near_mask = np.logical_and(pos1[:, 2] < 35, pos2[:, 2] < 35)
near_mask = np.logical_and(not_ground, near_mask)
indices = np.where(near_mask)[0]
else:
near_mask = np.logical_and(pos1[:, 2] < 35, pos2[:, 2] < 35)
indices = np.where(near_mask)[0]
if len(indices) >= self.npoints:
sample_idx1 = np.random.choice(indices, self.npoints, replace=False)
else:
sample_idx1 = np.concatenate((indices, np.random.choice(indices, self.npoints - len(indices), replace=True)), axis=-1)
if len(indices) >= self.npoints:
sample_idx2 = np.random.choice(indices, self.npoints, replace=False)
else:
sample_idx2 = np.concatenate((indices, np.random.choice(indices, self.npoints - len(indices), replace=True)), axis=-1)
pos1 = pos1[sample_idx1, :]
pos2 = pos2[sample_idx2, :]
flow = flow[sample_idx1, :]
if self.mode == 'eval_kitti':
return pos1, pos2, flow, fn
else:
return pos1, pos2, flow
def __len__(self):
return len(self.file_list)
def make_dataset(self):
do_mapping = True
root = os.path.realpath(os.path.expanduser(self.root))
all_paths = sorted(os.walk(root))
useful_paths = [item[0] for item in all_paths if len(item[1]) == 0]
try:
assert (len(useful_paths) == 200)
except AssertionError:
print('assert (len(useful_paths) == 200) failed!', len(useful_paths))
if do_mapping:
mapping_path = os.path.join(os.path.dirname(__file__), 'KITTI_mapping.txt')
print('mapping_path', mapping_path)
with open(mapping_path) as fd:
lines = fd.readlines()
lines = [line.strip() for line in lines]
useful_paths = [path for path in useful_paths if lines[int(os.path.split(path)[-1])] != '']
res_paths = useful_paths
return res_paths
| [
"os.listdir",
"numpy.logical_and",
"numpy.random.choice",
"numpy.where",
"numpy.logical_not",
"os.path.join",
"numpy.logical_or",
"os.walk",
"os.path.split",
"os.path.dirname",
"numpy.random.seed",
"numpy.load",
"os.path.expanduser"
] | [((895, 912), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (909, 912), True, 'import numpy as np\n'), ((1120, 1147), 'os.path.join', 'os.path.join', (['fn', '"""pc1.npy"""'], {}), "(fn, 'pc1.npy')\n", (1132, 1147), False, 'import os\n'), ((1161, 1188), 'os.path.join', 'os.path.join', (['fn', '"""pc2.npy"""'], {}), "(fn, 'pc2.npy')\n", (1173, 1188), False, 'import os\n'), ((463, 488), 'os.listdir', 'os.listdir', (['self.datapath'], {}), '(self.datapath)\n', (473, 488), False, 'import os\n'), ((1061, 1092), 'os.path.join', 'os.path.join', (['self.datapath', 'fn'], {}), '(self.datapath, fn)\n', (1073, 1092), False, 'import os\n'), ((1244, 1255), 'numpy.load', 'np.load', (['fp'], {}), '(fp)\n', (1251, 1255), True, 'import numpy as np\n'), ((1313, 1325), 'numpy.load', 'np.load', (['fp2'], {}), '(fp2)\n', (1320, 1325), True, 'import numpy as np\n'), ((1448, 1501), 'numpy.logical_or', 'np.logical_or', (['(pos1[:, 1] < -1.35)', '(pos2[:, 1] < -1.35)'], {}), '(pos1[:, 1] < -1.35, pos2[:, 1] < -1.35)\n', (1461, 1501), True, 'import numpy as np\n'), ((1526, 1551), 'numpy.logical_not', 'np.logical_not', (['is_ground'], {}), '(is_ground)\n', (1540, 1551), True, 'import numpy as np\n'), ((1577, 1625), 'numpy.logical_and', 'np.logical_and', (['(pos1[:, 2] < 35)', '(pos2[:, 2] < 35)'], {}), '(pos1[:, 2] < 35, pos2[:, 2] < 35)\n', (1591, 1625), True, 'import numpy as np\n'), ((1650, 1687), 'numpy.logical_and', 'np.logical_and', (['not_ground', 'near_mask'], {}), '(not_ground, near_mask)\n', (1664, 1687), True, 'import numpy as np\n'), ((1781, 1829), 'numpy.logical_and', 'np.logical_and', (['(pos1[:, 2] < 35)', '(pos2[:, 2] < 35)'], {}), '(pos1[:, 2] < 35, pos2[:, 2] < 35)\n', (1795, 1829), True, 'import numpy as np\n'), ((1956, 2010), 'numpy.random.choice', 'np.random.choice', (['indices', 'self.npoints'], {'replace': '(False)'}), '(indices, self.npoints, replace=False)\n', (1972, 2010), True, 'import numpy as np\n'), ((2232, 2286), 'numpy.random.choice', 'np.random.choice', (['indices', 'self.npoints'], {'replace': '(False)'}), '(indices, self.npoints, replace=False)\n', (2248, 2286), True, 'import numpy as np\n'), ((2830, 2859), 'os.path.expanduser', 'os.path.expanduser', (['self.root'], {}), '(self.root)\n', (2848, 2859), False, 'import os\n'), ((2889, 2902), 'os.walk', 'os.walk', (['root'], {}), '(root)\n', (2896, 2902), False, 'import os\n'), ((591, 623), 'os.path.join', 'os.path.join', (['self.root', '"""train"""'], {}), "(self.root, 'train')\n", (603, 623), False, 'import os\n'), ((653, 678), 'os.listdir', 'os.listdir', (['self.datapath'], {}), '(self.datapath)\n', (663, 678), False, 'import os\n'), ((1711, 1730), 'numpy.where', 'np.where', (['near_mask'], {}), '(near_mask)\n', (1719, 1730), True, 'import numpy as np\n'), ((1852, 1871), 'numpy.where', 'np.where', (['near_mask'], {}), '(near_mask)\n', (1860, 1871), True, 'import numpy as np\n'), ((3216, 3241), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (3231, 3241), False, 'import os\n'), ((755, 785), 'os.path.join', 'os.path.join', (['self.root', '"""val"""'], {}), "(self.root, 'val')\n", (767, 785), False, 'import os\n'), ((815, 840), 'os.listdir', 'os.listdir', (['self.datapath'], {}), '(self.datapath)\n', (825, 840), False, 'import os\n'), ((3523, 3542), 'os.path.split', 'os.path.split', (['path'], {}), '(path)\n', (3536, 3542), False, 'import os\n')] |
import numpy as np
import pandas as pd
import torch
import torchvision
from am_utils.utils import walk_dir
from torch.utils.data import DataLoader
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
from tqdm import tqdm
from ..dataset.dataset_object_inference import DatasetObjectInference, DatasetObjectInferenceMosaic
from ..transforms.bbox import get_test_transform
from ..utils.utils import collate_fn
from ..utils.utils import remove_overlapping_boxes, get_boxes_above_threshold
def get_df_of_file_list(input_dir, id_name='image_id'):
"""
List files in given folder and generate a dataframe for the data loader.
Parameters
----------
input_dir : str
Input directory
id_name : str, optional
Column name to specify image ID.
Default is 'image_id'
Returns
-------
pd.DataFrame
Dataframe with a list of input files.
"""
files = walk_dir(input_dir)
files = [fn[len(input_dir) + 1:] for fn in files]
df = pd.DataFrame({id_name: files})
return df
def load_detection_model(model_fn, num_classes=2, device=None):
"""
Load the object detection model from a given file.
Parameters
----------
model_fn : str
Model filename with the full path.
num_classes : int, optional
Number of classes in the object detection model.
Default is 2 (one class + background).
device : torch.device
Device to send the model to ('cpu' or 'cuda').
If None, the device will be detected automatically.
Default is None.
Returns
-------
model:
Torch model with loaded weights.
"""
model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=False, pretrained_backbone=False)
in_features = model.roi_heads.box_predictor.cls_score.in_features
model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)
# Load the trained weights
model.load_state_dict(torch.load(model_fn))
model.eval()
if device is None:
device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
model.to(device)
return model
def detect_bboxes(input_dir, model_fn, batch_size=2, maxsize=None,
detection_threshold=0.5, overlap_threshold=0.1, id_name='image_id'):
"""
Detect object bounding boxes in all image in give directory and return dataframe with the results.
Parameters
----------
input_dir : str
Input directory.
model_fn : str
Model filename with the full path.
batch_size : int, optional
Batch size for predictions.
Default is 2.
maxsize : int, optional
Pad the input image to a square with this size.
Default is None.
detection_threshold : float, optional
Threshold (between 0 and 1) for the confidence of the bounding boxes.
Bounding boxes with a confidence score lower than `detection_threshold` will not be included.
Default is 0.5.
overlap_threshold : float, optional
Maximum allowed intersection-over-union (IOU) score for two bounding boxes.
If two boxes overlap with a higher score, the box with a lower confidence score will be removed
id_name : str, optional
Column name to specify image ID.
Default is 'image_id'
Returns
-------
pd.DataFrame
Dataframe with detected bounding box coordinates.
"""
device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
model = load_detection_model(model_fn, device=device)
loader_kwargs = dict(batch_size=batch_size,
shuffle=False,
num_workers=batch_size,
drop_last=False)
df = get_df_of_file_list(input_dir)
ds = DatasetObjectInference(df, input_dir,
get_test_transform(),
maxsize=maxsize)
dl = DataLoader(ds, collate_fn=collate_fn, **loader_kwargs)
results = pd.DataFrame()
for images, image_ids in tqdm(dl):
images = list(image.to(device) for image in images)
outputs = model(images)
for i in range(len(outputs)):
bboxes, scores = get_boxes_above_threshold(outputs[i], detection_threshold)
bboxes, scores = remove_overlapping_boxes(bboxes, scores,
overlap_threshold, return_full=True)
bboxes = bboxes[scores > 0].data.cpu().numpy()
scores = scores[scores > 0].data.cpu().numpy()
results = __append_detections(bboxes, scores, results, image_ids[i], id_name)
return results
def __append_detections(bboxes, scores, results, image_id, id_name):
cur_results = pd.DataFrame(np.int_(np.round_(bboxes)), columns=['x1', 'y1', 'x2', 'y2'])
cur_results['scores'] = scores
cur_results[id_name] = image_id
results = pd.concat([results, cur_results], ignore_index=True)
return results
def __get_mosaic_df(df, imgshape, maxsize):
step = int(maxsize / 2)
ind_i = np.arange(int(imgshape[0] / step + 1)) * step if imgshape[0] > maxsize else [0]
ind_j = np.arange(int(imgshape[1] / step + 1)) * step if imgshape[1] > maxsize else [0]
boxes = []
for i in ind_i:
for j in ind_j:
boxes.append([j, i, j + maxsize, i + maxsize])
df_new = pd.DataFrame()
for i in range(len(df)):
cur_df = pd.DataFrame(boxes, columns=['x1', 'y1', 'x2', 'y2'])
cur_df['image_id'] = df.iloc[i]['image_id']
df_new = pd.concat([df_new, cur_df], ignore_index=True)
return df_new
def __add_shift(boxes, shift):
boxes[:, 0] += shift[0]
boxes[:, 2] += shift[0]
boxes[:, 1] += shift[1]
boxes[:, 3] += shift[1]
return boxes
def detect_bboxes_mosaic(input_dir, model_fn, maxsize, imgshape, batch_size=2,
detection_threshold=0.5, overlap_threshold=0.1, id_name='image_id'):
"""
Detect object bounding boxes in all image in give directory and return dataframe with the results.
Parameters
----------
input_dir : str
Input directory.
model_fn : str
Model filename with the full path.
maxsize : int
Pad the input image to a square with this size.
imgshape : tuple
Shape of the input image.
If greater than `maxsize`, the mosaic option will be used to crop ROI of `maxsize`.
batch_size : int, optional
Batch size for predictions.
Default is 2.
detection_threshold : float, optional
Threshold (between 0 and 1) for the confidence of the bounding boxes.
Bounding boxes with a confidence score lower than `detection_threshold` will not be included.
Default is 0.5.
overlap_threshold : float, optional
Maximum allowed intersection-over-union (IOU) score for two bounding boxes.
If two boxes overlap with a higher score, the box with a lower confidence score will be removed
id_name : str, optional
Column name to specify image ID.
Default is 'image_id'
Returns
-------
pd.DataFrame
Dataframe with detected bounding box coordinates.
"""
device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
model = load_detection_model(model_fn, device=device)
loader_kwargs = dict(batch_size=batch_size,
shuffle=False,
num_workers=batch_size,
drop_last=False)
df = __get_mosaic_df(get_df_of_file_list(input_dir), imgshape, maxsize)
ds = DatasetObjectInferenceMosaic(df, input_dir,
get_test_transform(),
maxsize=maxsize)
dl = DataLoader(ds, collate_fn=collate_fn, **loader_kwargs)
results = pd.DataFrame()
for images, image_ids, start_coord in tqdm(dl):
images = list(image.to(device) for image in images)
outputs = model(images)
for i in range(len(outputs)):
bboxes, scores = get_boxes_above_threshold(outputs[i], detection_threshold)
bboxes = bboxes.data.cpu().numpy()
scores = scores.data.cpu().numpy()
bboxes = __add_shift(bboxes, start_coord[i])
results = __append_detections(bboxes, scores, results, image_ids[i], id_name)
results2 = pd.DataFrame()
for image_id in results['image_id'].unique():
cur_df = results[results['image_id'] == image_id]
bboxes = torch.tensor(cur_df[['x1', 'y1', 'x2', 'y2']].values).to(device)
scores = torch.tensor(cur_df['scores'].values).to(device)
bboxes, scores = remove_overlapping_boxes(bboxes, scores,
overlap_threshold, return_full=True)
bboxes = bboxes[scores > 0].data.cpu().numpy()
scores = scores[scores > 0].data.cpu().numpy()
results2 = __append_detections(bboxes, scores, results2, image_id, id_name)
return results2
| [
"numpy.round_",
"torch.load",
"tqdm.tqdm",
"torchvision.models.detection.faster_rcnn.FastRCNNPredictor",
"am_utils.utils.walk_dir",
"torch.tensor",
"torchvision.models.detection.fasterrcnn_resnet50_fpn",
"torch.cuda.is_available",
"torch.utils.data.DataLoader",
"pandas.DataFrame",
"pandas.concat... | [((931, 950), 'am_utils.utils.walk_dir', 'walk_dir', (['input_dir'], {}), '(input_dir)\n', (939, 950), False, 'from am_utils.utils import walk_dir\n'), ((1014, 1044), 'pandas.DataFrame', 'pd.DataFrame', (['{id_name: files}'], {}), '({id_name: files})\n', (1026, 1044), True, 'import pandas as pd\n'), ((1681, 1782), 'torchvision.models.detection.fasterrcnn_resnet50_fpn', 'torchvision.models.detection.fasterrcnn_resnet50_fpn', ([], {'pretrained': '(False)', 'pretrained_backbone': '(False)'}), '(pretrained=False,\n pretrained_backbone=False)\n', (1733, 1782), False, 'import torchvision\n'), ((1885, 1928), 'torchvision.models.detection.faster_rcnn.FastRCNNPredictor', 'FastRCNNPredictor', (['in_features', 'num_classes'], {}), '(in_features, num_classes)\n', (1902, 1928), False, 'from torchvision.models.detection.faster_rcnn import FastRCNNPredictor\n'), ((3990, 4044), 'torch.utils.data.DataLoader', 'DataLoader', (['ds'], {'collate_fn': 'collate_fn'}), '(ds, collate_fn=collate_fn, **loader_kwargs)\n', (4000, 4044), False, 'from torch.utils.data import DataLoader\n'), ((4059, 4073), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (4071, 4073), True, 'import pandas as pd\n'), ((4103, 4111), 'tqdm.tqdm', 'tqdm', (['dl'], {}), '(dl)\n', (4107, 4111), False, 'from tqdm import tqdm\n'), ((4971, 5023), 'pandas.concat', 'pd.concat', (['[results, cur_results]'], {'ignore_index': '(True)'}), '([results, cur_results], ignore_index=True)\n', (4980, 5023), True, 'import pandas as pd\n'), ((5432, 5446), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (5444, 5446), True, 'import pandas as pd\n'), ((7838, 7892), 'torch.utils.data.DataLoader', 'DataLoader', (['ds'], {'collate_fn': 'collate_fn'}), '(ds, collate_fn=collate_fn, **loader_kwargs)\n', (7848, 7892), False, 'from torch.utils.data import DataLoader\n'), ((7907, 7921), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (7919, 7921), True, 'import pandas as pd\n'), ((7964, 7972), 'tqdm.tqdm', 'tqdm', (['dl'], {}), '(dl)\n', (7968, 7972), False, 'from tqdm import tqdm\n'), ((8450, 8464), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (8462, 8464), True, 'import pandas as pd\n'), ((1987, 2007), 'torch.load', 'torch.load', (['model_fn'], {}), '(model_fn)\n', (1997, 2007), False, 'import torch\n'), ((3502, 3527), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (3525, 3527), False, 'import torch\n'), ((3478, 3498), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (3490, 3498), False, 'import torch\n'), ((3533, 3552), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (3545, 3552), False, 'import torch\n'), ((5493, 5546), 'pandas.DataFrame', 'pd.DataFrame', (['boxes'], {'columns': "['x1', 'y1', 'x2', 'y2']"}), "(boxes, columns=['x1', 'y1', 'x2', 'y2'])\n", (5505, 5546), True, 'import pandas as pd\n'), ((5616, 5662), 'pandas.concat', 'pd.concat', (['[df_new, cur_df]'], {'ignore_index': '(True)'}), '([df_new, cur_df], ignore_index=True)\n', (5625, 5662), True, 'import pandas as pd\n'), ((7296, 7321), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (7319, 7321), False, 'import torch\n'), ((7272, 7292), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (7284, 7292), False, 'import torch\n'), ((7327, 7346), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (7339, 7346), False, 'import torch\n'), ((2091, 2116), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (2114, 2116), False, 'import torch\n'), ((2067, 2087), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (2079, 2087), False, 'import torch\n'), ((2122, 2141), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (2134, 2141), False, 'import torch\n'), ((4832, 4849), 'numpy.round_', 'np.round_', (['bboxes'], {}), '(bboxes)\n', (4841, 4849), True, 'import numpy as np\n'), ((8590, 8643), 'torch.tensor', 'torch.tensor', (["cur_df[['x1', 'y1', 'x2', 'y2']].values"], {}), "(cur_df[['x1', 'y1', 'x2', 'y2']].values)\n", (8602, 8643), False, 'import torch\n'), ((8672, 8709), 'torch.tensor', 'torch.tensor', (["cur_df['scores'].values"], {}), "(cur_df['scores'].values)\n", (8684, 8709), False, 'import torch\n')] |
# coding: utf-8
import os
from unittest import TestCase
class TestCsvFormatter(TestCase):
filename = '/tmp/test_csv_formatter_write.txt'
def setUp(self):
if os.path.exists(self.filename):
os.remove(self.filename)
tearDown = setUp
def _get_class(self, *args, **kwargs):
from datafactory.formatters.csv import CsvFormatter
return CsvFormatter(*args, **kwargs)
def test_stringify_list_fields_csv(self):
sf = self._get_class([
(1, 2, 3),
(4, 5, 6),
])
self.assertEqual(
sf.stringify(),
(
"1,2,3\r\n"
"4,5,6\r\n"
)
)
def test_stringify_dict_fields_tsv(self):
sf = self._get_class([
{'a': 1, 'b': 2, 'c': 3},
{'a': 4, 'b': 5, 'c': 6},
], fields=['a', 'b', 'c'], delimiter='\t', lineterminator='\n')
self.assertEqual(
sf.stringify(),
(
"1\t2\t3\n"
"4\t5\t6\n"
)
)
def test_write_list_fields_tsv(self):
from datafactory.exceptions import OutputFileAlreadyExists
sf = self._get_class(
[
{'a': 1, 'b': 2, 'c': 3},
{'a': 4, 'b': 5, 'c': 6},
],
fields=['a', 'b', 'c'],
header=['a', 'b', 'c'],
delimiter='\t',
lineterminator='\n'
)
sf.write(self.filename)
self.assertEqual(
open(self.filename).read(),
(
"a\tb\tc\n"
"1\t2\t3\n"
"4\t5\t6\n"
)
)
with self.assertRaises(OutputFileAlreadyExists):
sf.write(self.filename)
| [
"os.path.exists",
"datafactory.formatters.csv.CsvFormatter",
"os.remove"
] | [((176, 205), 'os.path.exists', 'os.path.exists', (['self.filename'], {}), '(self.filename)\n', (190, 205), False, 'import os\n'), ((385, 414), 'datafactory.formatters.csv.CsvFormatter', 'CsvFormatter', (['*args'], {}), '(*args, **kwargs)\n', (397, 414), False, 'from datafactory.formatters.csv import CsvFormatter\n'), ((219, 243), 'os.remove', 'os.remove', (['self.filename'], {}), '(self.filename)\n', (228, 243), False, 'import os\n')] |
# pylint: disable=wrong-import-position, wrong-import-order, invalid-name
"""
Invoke build script.
Show all tasks with::
invoke -l
.. seealso::
* http://pyinvoke.org
* https://github.com/pyinvoke/invoke
"""
###############################################################################
# Catch exceptions and go into ipython/ipdb
# import sys
# from IPython.core.debugger import Tracer # noqa
# from IPython.core import ultratb
# sys.excepthook = ultratb.FormattedTB(
# mode="Verbose", color_scheme="Linux", call_pdb=True, ostream=sys.__stdout__
# )
###############################################################################
import logging
from invoke import Collection, Context, Config
from invoke import task
from .constants import ROOT_DIR, PROJECT_BIN_DIR, DATA_DIR, SCRIPT_DIR
from . import local
from . import ci
LOGGER = logging.getLogger()
ns = Collection()
ns.add_collection(local)
ns.add_collection(ci)
# https://github.com/imbrra/logowanie/blob/38a1a38ea9f5b2494e5bc986df651ff9d713fda5/tasks/__init__.py
# TODO: THINK ABOUT USING THESE MODULES https://medium.com/hultner/how-to-write-bash-scripts-in-python-10c34a5c2df1
# TODO: THINK ABOUT USING THESE MODULES https://medium.com/hultner/how-to-write-bash-scripts-in-python-10c34a5c2df1
# TODO: THINK ABOUT USING THESE MODULES https://medium.com/hultner/how-to-write-bash-scripts-in-python-10c34a5c2df1
| [
"logging.getLogger",
"invoke.Collection"
] | [((857, 876), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (874, 876), False, 'import logging\n'), ((883, 895), 'invoke.Collection', 'Collection', ([], {}), '()\n', (893, 895), False, 'from invoke import Collection, Context, Config\n')] |
from random import randint
from cowait.worker.worker_node import WorkerNode
from .html_logger import HTMLLogger
class NotebookNode(WorkerNode):
"""
The Notebook Node is a variant of the standard worker node meant to run in a notebook.
It simulates a running task by connecting upstream and forwarding events from tasks
created from within the notebook.
NotebookNodes use random ports for their web servers to allow multiple nodes on a single host.
Output is disabled to prevent event spam into the notebook.
"""
def __init__(self, taskdef):
self.taskdef = taskdef
super().__init__(
id=taskdef.id,
upstream=taskdef.upstream,
port=randint(10000, 60000),
logger=HTMLLogger(),
)
async def start(self, token: str) -> None:
"""
Starts the node by connecting upstream, sending initialization
events and starting the local web server.
"""
await self.connect(token)
await self.parent.send_init(self.taskdef)
await self.parent.send_run()
await self.parent.send_log(data='Kernel ready.', file='stdout')
self.serve()
async def stop(self):
await self.parent.send_log(data='Kernel stopped!', file='stdout')
await self.parent.send_stop()
await self.parent.close()
async def connect(self, token: str) -> None:
await self.parent.connect(self.upstream, token)
| [
"random.randint"
] | [((717, 738), 'random.randint', 'randint', (['(10000)', '(60000)'], {}), '(10000, 60000)\n', (724, 738), False, 'from random import randint\n')] |
"""
Pure Python implementation of the kernel functions
"""
import numpy as np
from scipy.special import erf
from utils import numpy_trans, numpy_trans_idx
s2pi = np.sqrt(2.0 * np.pi)
s2 = np.sqrt(2.0)
@numpy_trans
def norm1d_pdf(z, out):
"""
Full-python implementation of :py:func:`normal_kernel1d.pdf`
"""
z = np.atleast_1d(z)
if out is None:
out = np.empty(z.shape, dtype=z.dtype)
np.multiply(z, z, out)
out *= -0.5
np.exp(out, out)
out /= s2pi
return out
@numpy_trans
def norm1d_cdf(z, out):
"""
Full-python implementation of :py:func:`normal_kernel1d.cdf`
"""
np.divide(z, s2, out)
erf(out, out)
out *= 0.5
out += 0.5
return out
@numpy_trans
def norm1d_pm1(z, out):
"""
Full-python implementation of :py:func:`normal_kernel1d.pm1`
"""
np.multiply(z, z, out)
out *= -0.5
np.exp(out, out)
out /= -s2pi
return out
@numpy_trans_idx
def norm1d_pm2(z, out):
"""
Full-python implementation of :py:func:`normal_kernel1d.pm2`
"""
np.divide(z, s2, out)
erf(out, out)
out /= 2
if z.shape:
zz = np.isfinite(z)
sz = z[zz]
out[zz] -= sz * np.exp(-0.5 * sz * sz) / s2pi
elif np.isfinite(z):
out -= z * np.exp(-0.5 * z * z) / s2pi
out += 0.5
return out
tricube_width = np.sqrt(35. / 243)
@numpy_trans_idx
def tricube_pdf(z, out=None):
np.multiply(z, tricube_width, out)
sel = (out > -1) & (out < 1)
out[~sel] = 0
out[sel] = 70. / 81 * (1 - abs(out[sel]) ** 3.) ** 3. * tricube_width
return out
@numpy_trans_idx
def tricube_cdf(z, out=None):
np.multiply(z, tricube_width, out)
sel_down = out <= -1
sel_up = out >= 1
sel_neg = (out < 0) & (~sel_down)
sel_pos = (out >= 0) & (~sel_up)
out[sel_up] = 1
out[sel_down] = 0
out[sel_pos] = 1. / 162 * \
(60 * (out[sel_pos] ** 7) - 7. *
(2 * (out[sel_pos] ** 10) + 15 * (out[sel_pos] ** 4)) +
140 * out[sel_pos] + 81)
out[sel_neg] = 1. / 162 * \
(60 * (out[sel_neg] ** 7) + 7. *
(2 * (out[sel_neg] ** 10) + 15 * (out[sel_neg] ** 4)) +
140 * out[sel_neg] + 81)
return out
@numpy_trans_idx
def tricube_pm1(z, out=None):
np.multiply(z, tricube_width, out)
out[out < 0] = -out[out < 0]
sel = out < 1
out[~sel] = 0
out[sel] = 7 / (3564 * tricube_width) * \
(165 * out[sel] ** 8 - 8 * (5 * out[sel] ** 11 + 33 * out[sel] ** 5) +
220 * out[sel] ** 2 - 81)
return out
@numpy_trans_idx
def tricube_pm2(z, out=None):
np.multiply(z, tricube_width, out)
sel_down = out <= -1
sel_up = out >= 1
sel_neg = (out < 0) & ~sel_down
sel_pos = (out >= 0) & ~sel_up
out[sel_down] = 0
out[sel_up] = 1
out[sel_pos] = 35. / (tricube_width * tricube_width * 486) * \
(4 * out[sel_pos] ** 9 - (out[sel_pos] ** 12 + 6 * out[sel_pos] ** 6) +
4 * out[sel_pos] ** 3 + 1)
out[sel_neg] = 35. / (tricube_width * tricube_width * 486) * \
(4 * out[sel_neg] ** 9 + (out[sel_neg] ** 12 + 6 * out[sel_neg] ** 6) +
4 * out[sel_neg] ** 3 + 1)
return out
epanechnikov_width = 1. / np.sqrt(5.)
@numpy_trans_idx
def epanechnikov_pdf(z, out=None):
np.multiply(z, epanechnikov_width, out)
sel = (out > -1) & (out < 1)
out[~sel] = 0
out[sel] = (.75 * epanechnikov_width) * (1 - out[sel] ** 2)
return out
@numpy_trans_idx
def epanechnikov_cdf(z, out=None):
np.multiply(z, epanechnikov_width, out)
sel_up = out >= 1
sel_down = out <= -1
out[sel_up] = 1
out[sel_down] = 0
sel = ~(sel_up | sel_down)
out[sel] = .25 * (2 + 3 * out[sel] - out[sel] ** 3)
return out
@numpy_trans_idx
def epanechnikov_pm1(z, out=None):
np.multiply(z, epanechnikov_width, out)
sel = (out > -1) & (out < 1)
out[~sel] = 0
out[sel] = -3 / (16 * epanechnikov_width) * \
(1 - 2 * out[sel] ** 2 + out[sel] ** 4)
return out
@numpy_trans_idx
def epanechnikov_pm2(z, out=None):
np.multiply(z, epanechnikov_width, out)
sel_up = out >= 1
sel_down = out <= -1
out[sel_up] = 1
out[sel_down] = 0
sel = ~(sel_up | sel_down)
out[sel] = .25 * (2 + 5 * out[sel] ** 3 - 3 * out[sel] ** 5)
return out
@numpy_trans
def normal_o4_pdf(z, out=None):
norm1d_pdf(z, out)
out *= (3 - z ** 2) / 2
return out
@numpy_trans_idx
def normal_o4_cdf(z, out=None):
norm1d_cdf(z, out)
sel = np.isfinite(z)
out[sel] += z[sel] * norm1d_pdf(z[sel]) / 2
return out
@numpy_trans_idx
def normal_o4_pm1(z, out=None):
norm1d_pdf(z, out)
out -= normal_o4_pdf(z)
out[~np.isfinite(z)] = 0
return out
@numpy_trans_idx
def normal_o4_pm2(z, out=None):
np.power(z, 3, out)
out *= norm1d_pdf(z) / 2
out[~np.isfinite(z)] = 0
return out
@numpy_trans_idx
def epanechnikov_o4_pdf(z, out=None):
np.power(z, 2., out)
out *= -15 / 8.
out += 9. / 8.
out[(z < -1) | (z > 1)] = 0
return out
@numpy_trans_idx
def epanechnikov_o4_cdf(z, out=None):
np.power(z, 3, out)
out *= -5. / 8.
out += (4 + 9 * z) / 8.
out[z > 1] = 1
out[z < -1] = 0
return out
@numpy_trans_idx
def epanechnikov_o4_pm1(z, out=None):
out = np.power(z, 4, out)
out *= -15. / 32.
out += 1. / 32. * (18 * z ** 2 - 3)
out[(z < -1) | (z > 1)] = 0
return out
@numpy_trans_idx
def epanechnikov_o4_pm2(z, out=None):
out = np.power(z, 3, out)
out *= .375
out -= .375 * np.power(z, 5)
out[(z < -1) | (z > 1)] = 0
return out
| [
"numpy.multiply",
"numpy.sqrt",
"numpy.power",
"numpy.exp",
"scipy.special.erf",
"numpy.isfinite",
"numpy.empty",
"numpy.divide",
"numpy.atleast_1d"
] | [((165, 185), 'numpy.sqrt', 'np.sqrt', (['(2.0 * np.pi)'], {}), '(2.0 * np.pi)\n', (172, 185), True, 'import numpy as np\n'), ((191, 203), 'numpy.sqrt', 'np.sqrt', (['(2.0)'], {}), '(2.0)\n', (198, 203), True, 'import numpy as np\n'), ((1354, 1373), 'numpy.sqrt', 'np.sqrt', (['(35.0 / 243)'], {}), '(35.0 / 243)\n', (1361, 1373), True, 'import numpy as np\n'), ((332, 348), 'numpy.atleast_1d', 'np.atleast_1d', (['z'], {}), '(z)\n', (345, 348), True, 'import numpy as np\n'), ((420, 442), 'numpy.multiply', 'np.multiply', (['z', 'z', 'out'], {}), '(z, z, out)\n', (431, 442), True, 'import numpy as np\n'), ((463, 479), 'numpy.exp', 'np.exp', (['out', 'out'], {}), '(out, out)\n', (469, 479), True, 'import numpy as np\n'), ((635, 656), 'numpy.divide', 'np.divide', (['z', 's2', 'out'], {}), '(z, s2, out)\n', (644, 656), True, 'import numpy as np\n'), ((661, 674), 'scipy.special.erf', 'erf', (['out', 'out'], {}), '(out, out)\n', (664, 674), False, 'from scipy.special import erf\n'), ((844, 866), 'numpy.multiply', 'np.multiply', (['z', 'z', 'out'], {}), '(z, z, out)\n', (855, 866), True, 'import numpy as np\n'), ((887, 903), 'numpy.exp', 'np.exp', (['out', 'out'], {}), '(out, out)\n', (893, 903), True, 'import numpy as np\n'), ((1064, 1085), 'numpy.divide', 'np.divide', (['z', 's2', 'out'], {}), '(z, s2, out)\n', (1073, 1085), True, 'import numpy as np\n'), ((1090, 1103), 'scipy.special.erf', 'erf', (['out', 'out'], {}), '(out, out)\n', (1093, 1103), False, 'from scipy.special import erf\n'), ((1426, 1460), 'numpy.multiply', 'np.multiply', (['z', 'tricube_width', 'out'], {}), '(z, tricube_width, out)\n', (1437, 1460), True, 'import numpy as np\n'), ((1654, 1688), 'numpy.multiply', 'np.multiply', (['z', 'tricube_width', 'out'], {}), '(z, tricube_width, out)\n', (1665, 1688), True, 'import numpy as np\n'), ((2265, 2299), 'numpy.multiply', 'np.multiply', (['z', 'tricube_width', 'out'], {}), '(z, tricube_width, out)\n', (2276, 2299), True, 'import numpy as np\n'), ((2597, 2631), 'numpy.multiply', 'np.multiply', (['z', 'tricube_width', 'out'], {}), '(z, tricube_width, out)\n', (2608, 2631), True, 'import numpy as np\n'), ((3200, 3212), 'numpy.sqrt', 'np.sqrt', (['(5.0)'], {}), '(5.0)\n', (3207, 3212), True, 'import numpy as np\n'), ((3269, 3308), 'numpy.multiply', 'np.multiply', (['z', 'epanechnikov_width', 'out'], {}), '(z, epanechnikov_width, out)\n', (3280, 3308), True, 'import numpy as np\n'), ((3497, 3536), 'numpy.multiply', 'np.multiply', (['z', 'epanechnikov_width', 'out'], {}), '(z, epanechnikov_width, out)\n', (3508, 3536), True, 'import numpy as np\n'), ((3786, 3825), 'numpy.multiply', 'np.multiply', (['z', 'epanechnikov_width', 'out'], {}), '(z, epanechnikov_width, out)\n', (3797, 3825), True, 'import numpy as np\n'), ((4048, 4087), 'numpy.multiply', 'np.multiply', (['z', 'epanechnikov_width', 'out'], {}), '(z, epanechnikov_width, out)\n', (4059, 4087), True, 'import numpy as np\n'), ((4485, 4499), 'numpy.isfinite', 'np.isfinite', (['z'], {}), '(z)\n', (4496, 4499), True, 'import numpy as np\n'), ((4764, 4783), 'numpy.power', 'np.power', (['z', '(3)', 'out'], {}), '(z, 3, out)\n', (4772, 4783), True, 'import numpy as np\n'), ((4918, 4939), 'numpy.power', 'np.power', (['z', '(2.0)', 'out'], {}), '(z, 2.0, out)\n', (4926, 4939), True, 'import numpy as np\n'), ((5086, 5105), 'numpy.power', 'np.power', (['z', '(3)', 'out'], {}), '(z, 3, out)\n', (5094, 5105), True, 'import numpy as np\n'), ((5275, 5294), 'numpy.power', 'np.power', (['z', '(4)', 'out'], {}), '(z, 4, out)\n', (5283, 5294), True, 'import numpy as np\n'), ((5471, 5490), 'numpy.power', 'np.power', (['z', '(3)', 'out'], {}), '(z, 3, out)\n', (5479, 5490), True, 'import numpy as np\n'), ((383, 415), 'numpy.empty', 'np.empty', (['z.shape'], {'dtype': 'z.dtype'}), '(z.shape, dtype=z.dtype)\n', (391, 415), True, 'import numpy as np\n'), ((1146, 1160), 'numpy.isfinite', 'np.isfinite', (['z'], {}), '(z)\n', (1157, 1160), True, 'import numpy as np\n'), ((1243, 1257), 'numpy.isfinite', 'np.isfinite', (['z'], {}), '(z)\n', (1254, 1257), True, 'import numpy as np\n'), ((5525, 5539), 'numpy.power', 'np.power', (['z', '(5)'], {}), '(z, 5)\n', (5533, 5539), True, 'import numpy as np\n'), ((4674, 4688), 'numpy.isfinite', 'np.isfinite', (['z'], {}), '(z)\n', (4685, 4688), True, 'import numpy as np\n'), ((4822, 4836), 'numpy.isfinite', 'np.isfinite', (['z'], {}), '(z)\n', (4833, 4836), True, 'import numpy as np\n'), ((1204, 1226), 'numpy.exp', 'np.exp', (['(-0.5 * sz * sz)'], {}), '(-0.5 * sz * sz)\n', (1210, 1226), True, 'import numpy as np\n'), ((1278, 1298), 'numpy.exp', 'np.exp', (['(-0.5 * z * z)'], {}), '(-0.5 * z * z)\n', (1284, 1298), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
import gym
import ptan
import argparse
import random
import numpy as np
import torch
import torch.optim as optim
import torch.nn.functional as F
from ignite.engine import Engine
from lib import common, dqn_extra
NAME = "07_distrib"
def calc_loss(batch, net, tgt_net, gamma, device="cpu"):
states, actions, rewards, dones, next_states = \
common.unpack_batch(batch)
batch_size = len(batch)
states_v = torch.tensor(states).to(device)
actions_v = torch.tensor(actions).to(device)
next_states_v = torch.tensor(next_states).to(device)
# next state distribution
next_distr_v, next_qvals_v = tgt_net.both(next_states_v)
next_acts = next_qvals_v.max(1)[1].data.cpu().numpy()
next_distr = tgt_net.apply_softmax(next_distr_v)
next_distr = next_distr.data.cpu().numpy()
next_best_distr = next_distr[range(batch_size), next_acts]
dones = dones.astype(np.bool)
proj_distr = dqn_extra.distr_projection(
next_best_distr, rewards, dones, gamma)
distr_v = net(states_v)
sa_vals = distr_v[range(batch_size), actions_v.data]
state_log_sm_v = F.log_softmax(sa_vals, dim=1)
proj_distr_v = torch.tensor(proj_distr).to(device)
loss_v = -state_log_sm_v * proj_distr_v
return loss_v.sum(dim=1).mean()
if __name__ == "__main__":
random.seed(common.SEED)
torch.manual_seed(common.SEED)
params = common.HYPERPARAMS['pong']
parser = argparse.ArgumentParser()
parser.add_argument("--cuda", default=False, action="store_true", help="Enable cuda")
args = parser.parse_args()
device = torch.device("cuda" if args.cuda else "cpu")
env = gym.make(params.env_name)
env = ptan.common.wrappers.wrap_dqn(env)
env.seed(common.SEED)
net = dqn_extra.DistributionalDQN(env.observation_space.shape, env.action_space.n).to(device)
print(net)
tgt_net = ptan.agent.TargetNet(net)
selector = ptan.actions.EpsilonGreedyActionSelector(epsilon=params.epsilon_start)
epsilon_tracker = common.EpsilonTracker(selector, params)
agent = ptan.agent.DQNAgent(lambda x: net.qvals(x), selector, device=device)
exp_source = ptan.experience.ExperienceSourceFirstLast(
env, agent, gamma=params.gamma)
buffer = ptan.experience.ExperienceReplayBuffer(
exp_source, buffer_size=params.replay_size)
optimizer = optim.Adam(net.parameters(), lr=params.learning_rate)
def process_batch(engine, batch):
optimizer.zero_grad()
loss_v = calc_loss(batch, net, tgt_net.target_model,
gamma=params.gamma, device=device)
loss_v.backward()
optimizer.step()
epsilon_tracker.frame(engine.state.iteration)
if engine.state.iteration % params.target_net_sync == 0:
tgt_net.sync()
return {
"loss": loss_v.item(),
"epsilon": selector.epsilon,
}
engine = Engine(process_batch)
common.setup_ignite(engine, params, exp_source, NAME)
engine.run(common.batch_generator(buffer, params.replay_initial, params.batch_size))
| [
"ignite.engine.Engine",
"gym.make",
"ptan.actions.EpsilonGreedyActionSelector",
"argparse.ArgumentParser",
"lib.dqn_extra.distr_projection",
"lib.dqn_extra.DistributionalDQN",
"lib.common.EpsilonTracker",
"ptan.agent.TargetNet",
"lib.common.batch_generator",
"torch.nn.functional.log_softmax",
"p... | [((379, 405), 'lib.common.unpack_batch', 'common.unpack_batch', (['batch'], {}), '(batch)\n', (398, 405), False, 'from lib import common, dqn_extra\n'), ((954, 1020), 'lib.dqn_extra.distr_projection', 'dqn_extra.distr_projection', (['next_best_distr', 'rewards', 'dones', 'gamma'], {}), '(next_best_distr, rewards, dones, gamma)\n', (980, 1020), False, 'from lib import common, dqn_extra\n'), ((1137, 1166), 'torch.nn.functional.log_softmax', 'F.log_softmax', (['sa_vals'], {'dim': '(1)'}), '(sa_vals, dim=1)\n', (1150, 1166), True, 'import torch.nn.functional as F\n'), ((1336, 1360), 'random.seed', 'random.seed', (['common.SEED'], {}), '(common.SEED)\n', (1347, 1360), False, 'import random\n'), ((1365, 1395), 'torch.manual_seed', 'torch.manual_seed', (['common.SEED'], {}), '(common.SEED)\n', (1382, 1395), False, 'import torch\n'), ((1449, 1474), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1472, 1474), False, 'import argparse\n'), ((1609, 1653), 'torch.device', 'torch.device', (["('cuda' if args.cuda else 'cpu')"], {}), "('cuda' if args.cuda else 'cpu')\n", (1621, 1653), False, 'import torch\n'), ((1665, 1690), 'gym.make', 'gym.make', (['params.env_name'], {}), '(params.env_name)\n', (1673, 1690), False, 'import gym\n'), ((1701, 1735), 'ptan.common.wrappers.wrap_dqn', 'ptan.common.wrappers.wrap_dqn', (['env'], {}), '(env)\n', (1730, 1735), False, 'import ptan\n'), ((1890, 1915), 'ptan.agent.TargetNet', 'ptan.agent.TargetNet', (['net'], {}), '(net)\n', (1910, 1915), False, 'import ptan\n'), ((1931, 2001), 'ptan.actions.EpsilonGreedyActionSelector', 'ptan.actions.EpsilonGreedyActionSelector', ([], {'epsilon': 'params.epsilon_start'}), '(epsilon=params.epsilon_start)\n', (1971, 2001), False, 'import ptan\n'), ((2024, 2063), 'lib.common.EpsilonTracker', 'common.EpsilonTracker', (['selector', 'params'], {}), '(selector, params)\n', (2045, 2063), False, 'from lib import common, dqn_extra\n'), ((2163, 2236), 'ptan.experience.ExperienceSourceFirstLast', 'ptan.experience.ExperienceSourceFirstLast', (['env', 'agent'], {'gamma': 'params.gamma'}), '(env, agent, gamma=params.gamma)\n', (2204, 2236), False, 'import ptan\n'), ((2259, 2346), 'ptan.experience.ExperienceReplayBuffer', 'ptan.experience.ExperienceReplayBuffer', (['exp_source'], {'buffer_size': 'params.replay_size'}), '(exp_source, buffer_size=params.\n replay_size)\n', (2297, 2346), False, 'import ptan\n'), ((2928, 2949), 'ignite.engine.Engine', 'Engine', (['process_batch'], {}), '(process_batch)\n', (2934, 2949), False, 'from ignite.engine import Engine\n'), ((2954, 3007), 'lib.common.setup_ignite', 'common.setup_ignite', (['engine', 'params', 'exp_source', 'NAME'], {}), '(engine, params, exp_source, NAME)\n', (2973, 3007), False, 'from lib import common, dqn_extra\n'), ((3023, 3095), 'lib.common.batch_generator', 'common.batch_generator', (['buffer', 'params.replay_initial', 'params.batch_size'], {}), '(buffer, params.replay_initial, params.batch_size)\n', (3045, 3095), False, 'from lib import common, dqn_extra\n'), ((450, 470), 'torch.tensor', 'torch.tensor', (['states'], {}), '(states)\n', (462, 470), False, 'import torch\n'), ((498, 519), 'torch.tensor', 'torch.tensor', (['actions'], {}), '(actions)\n', (510, 519), False, 'import torch\n'), ((551, 576), 'torch.tensor', 'torch.tensor', (['next_states'], {}), '(next_states)\n', (563, 576), False, 'import torch\n'), ((1186, 1210), 'torch.tensor', 'torch.tensor', (['proj_distr'], {}), '(proj_distr)\n', (1198, 1210), False, 'import torch\n'), ((1773, 1849), 'lib.dqn_extra.DistributionalDQN', 'dqn_extra.DistributionalDQN', (['env.observation_space.shape', 'env.action_space.n'], {}), '(env.observation_space.shape, env.action_space.n)\n', (1800, 1849), False, 'from lib import common, dqn_extra\n')] |
# coding: utf-8
"""
Scubawhere API Documentation
This is the documentation for scubawhere's RMS API. This API is only to be used by authorized parties with valid auth tokens. [Learn about scubawhere](http://www.scubawhere.com) to become an authorized consumer of our API
OpenAPI spec version: 1.0.0
Contact: <EMAIL>
Generated by: https://github.com/swagger-api/swagger-codegen.git
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 absolute_import
import sys
import os
import re
# python 2 and python 3 compatibility library
from six import iteritems
from ..configuration import Configuration
from ..api_client import ApiClient
class BookingApi(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
config = Configuration()
if api_client:
self.api_client = api_client
else:
if not config.api_client:
config.api_client = ApiClient()
self.api_client = config.api_client
def add_booking_detail(self, booking_id, customer_id, **kwargs):
"""
Add a package / course / ticket with its session to the booking
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.add_booking_detail(booking_id, customer_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id: (required)
:param int customer_id: (required)
:param int ticket_id:
:param int session_id:
:param int boatroom_id:
:param int training_session_id:
:param bool temporary:
:param int package_id:
:param int packagefacade_id:
:param int course_id:
:return: InlineResponse20010
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.add_booking_detail_with_http_info(booking_id, customer_id, **kwargs)
else:
(data) = self.add_booking_detail_with_http_info(booking_id, customer_id, **kwargs)
return data
def add_booking_detail_with_http_info(self, booking_id, customer_id, **kwargs):
"""
Add a package / course / ticket with its session to the booking
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.add_booking_detail_with_http_info(booking_id, customer_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id: (required)
:param int customer_id: (required)
:param int ticket_id:
:param int session_id:
:param int boatroom_id:
:param int training_session_id:
:param bool temporary:
:param int package_id:
:param int packagefacade_id:
:param int course_id:
:return: InlineResponse20010
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['booking_id', 'customer_id', 'ticket_id', 'session_id', 'boatroom_id', 'training_session_id', 'temporary', 'package_id', 'packagefacade_id', 'course_id']
all_params.append('callback')
all_params.append('_return_http_data_only')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method add_booking_detail" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'booking_id' is set
if ('booking_id' not in params) or (params['booking_id'] is None):
raise ValueError("Missing the required parameter `booking_id` when calling `add_booking_detail`")
# verify the required parameter 'customer_id' is set
if ('customer_id' not in params) or (params['customer_id'] is None):
raise ValueError("Missing the required parameter `customer_id` when calling `add_booking_detail`")
resource_path = '/booking/add-detail'.replace('{format}', 'json')
path_params = {}
query_params = {}
if 'booking_id' in params:
query_params['booking_id'] = params['booking_id']
if 'customer_id' in params:
query_params['customer_id'] = params['customer_id']
if 'ticket_id' in params:
query_params['ticket_id'] = params['ticket_id']
if 'session_id' in params:
query_params['session_id'] = params['session_id']
if 'boatroom_id' in params:
query_params['boatroom_id'] = params['boatroom_id']
if 'training_session_id' in params:
query_params['training_session_id'] = params['training_session_id']
if 'temporary' in params:
query_params['temporary'] = params['temporary']
if 'package_id' in params:
query_params['package_id'] = params['package_id']
if 'packagefacade_id' in params:
query_params['packagefacade_id'] = params['packagefacade_id']
if 'course_id' in params:
query_params['course_id'] = params['course_id']
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = []
return self.api_client.call_api(resource_path, 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='InlineResponse20010',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'))
def attach_accommodation(self, booking_id, accommodation_id, customer_id, **kwargs):
"""
Attach an accommodation booking to a booking
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.attach_accommodation(booking_id, accommodation_id, customer_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id: (required)
:param int accommodation_id: (required)
:param int customer_id: (required)
:param date start:
:param date end:
:return: InlineResponse2008
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.attach_accommodation_with_http_info(booking_id, accommodation_id, customer_id, **kwargs)
else:
(data) = self.attach_accommodation_with_http_info(booking_id, accommodation_id, customer_id, **kwargs)
return data
def attach_accommodation_with_http_info(self, booking_id, accommodation_id, customer_id, **kwargs):
"""
Attach an accommodation booking to a booking
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.attach_accommodation_with_http_info(booking_id, accommodation_id, customer_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id: (required)
:param int accommodation_id: (required)
:param int customer_id: (required)
:param date start:
:param date end:
:return: InlineResponse2008
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['booking_id', 'accommodation_id', 'customer_id', 'start', 'end']
all_params.append('callback')
all_params.append('_return_http_data_only')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method attach_accommodation" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'booking_id' is set
if ('booking_id' not in params) or (params['booking_id'] is None):
raise ValueError("Missing the required parameter `booking_id` when calling `attach_accommodation`")
# verify the required parameter 'accommodation_id' is set
if ('accommodation_id' not in params) or (params['accommodation_id'] is None):
raise ValueError("Missing the required parameter `accommodation_id` when calling `attach_accommodation`")
# verify the required parameter 'customer_id' is set
if ('customer_id' not in params) or (params['customer_id'] is None):
raise ValueError("Missing the required parameter `customer_id` when calling `attach_accommodation`")
resource_path = '/booking/add-accommodation'.replace('{format}', 'json')
path_params = {}
query_params = {}
if 'booking_id' in params:
query_params['booking_id'] = params['booking_id']
if 'accommodation_id' in params:
query_params['accommodation_id'] = params['accommodation_id']
if 'customer_id' in params:
query_params['customer_id'] = params['customer_id']
if 'start' in params:
query_params['start'] = params['start']
if 'end' in params:
query_params['end'] = params['end']
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = []
return self.api_client.call_api(resource_path, 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='InlineResponse2008',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'))
def attach_addon(self, booking_id, bookingdetail_id, addon_id, **kwargs):
"""
Attach an addon to a trip of a booking
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.attach_addon(booking_id, bookingdetail_id, addon_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id: (required)
:param int bookingdetail_id: (required)
:param int addon_id: (required)
:param int quantity:
:param int packagefacade_id:
:return: InlineResponse2009
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.attach_addon_with_http_info(booking_id, bookingdetail_id, addon_id, **kwargs)
else:
(data) = self.attach_addon_with_http_info(booking_id, bookingdetail_id, addon_id, **kwargs)
return data
def attach_addon_with_http_info(self, booking_id, bookingdetail_id, addon_id, **kwargs):
"""
Attach an addon to a trip of a booking
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.attach_addon_with_http_info(booking_id, bookingdetail_id, addon_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id: (required)
:param int bookingdetail_id: (required)
:param int addon_id: (required)
:param int quantity:
:param int packagefacade_id:
:return: InlineResponse2009
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['booking_id', 'bookingdetail_id', 'addon_id', 'quantity', 'packagefacade_id']
all_params.append('callback')
all_params.append('_return_http_data_only')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method attach_addon" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'booking_id' is set
if ('booking_id' not in params) or (params['booking_id'] is None):
raise ValueError("Missing the required parameter `booking_id` when calling `attach_addon`")
# verify the required parameter 'bookingdetail_id' is set
if ('bookingdetail_id' not in params) or (params['bookingdetail_id'] is None):
raise ValueError("Missing the required parameter `bookingdetail_id` when calling `attach_addon`")
# verify the required parameter 'addon_id' is set
if ('addon_id' not in params) or (params['addon_id'] is None):
raise ValueError("Missing the required parameter `addon_id` when calling `attach_addon`")
resource_path = '/booking/add-addon'.replace('{format}', 'json')
path_params = {}
query_params = {}
if 'booking_id' in params:
query_params['booking_id'] = params['booking_id']
if 'bookingdetail_id' in params:
query_params['bookingdetail_id'] = params['bookingdetail_id']
if 'addon_id' in params:
query_params['addon_id'] = params['addon_id']
if 'quantity' in params:
query_params['quantity'] = params['quantity']
if 'packagefacade_id' in params:
query_params['packagefacade_id'] = params['packagefacade_id']
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = []
return self.api_client.call_api(resource_path, 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='InlineResponse2009',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'))
def attach_pickup(self, booking_id, location, date, time, **kwargs):
"""
Attach a pickup location for a booking
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.attach_pickup(booking_id, location, date, time, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id: (required)
:param str location: (required)
:param date date: (required)
:param str time: (required)
:return: InlineResponse20011
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.attach_pickup_with_http_info(booking_id, location, date, time, **kwargs)
else:
(data) = self.attach_pickup_with_http_info(booking_id, location, date, time, **kwargs)
return data
def attach_pickup_with_http_info(self, booking_id, location, date, time, **kwargs):
"""
Attach a pickup location for a booking
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.attach_pickup_with_http_info(booking_id, location, date, time, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id: (required)
:param str location: (required)
:param date date: (required)
:param str time: (required)
:return: InlineResponse20011
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['booking_id', 'location', 'date', 'time']
all_params.append('callback')
all_params.append('_return_http_data_only')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method attach_pickup" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'booking_id' is set
if ('booking_id' not in params) or (params['booking_id'] is None):
raise ValueError("Missing the required parameter `booking_id` when calling `attach_pickup`")
# verify the required parameter 'location' is set
if ('location' not in params) or (params['location'] is None):
raise ValueError("Missing the required parameter `location` when calling `attach_pickup`")
# verify the required parameter 'date' is set
if ('date' not in params) or (params['date'] is None):
raise ValueError("Missing the required parameter `date` when calling `attach_pickup`")
# verify the required parameter 'time' is set
if ('time' not in params) or (params['time'] is None):
raise ValueError("Missing the required parameter `time` when calling `attach_pickup`")
resource_path = '/booking/add-pickup'.replace('{format}', 'json')
path_params = {}
query_params = {}
if 'booking_id' in params:
query_params['booking_id'] = params['booking_id']
if 'location' in params:
query_params['location'] = params['location']
if 'date' in params:
query_params['date'] = params['date']
if 'time' in params:
query_params['time'] = params['time']
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = []
return self.api_client.call_api(resource_path, 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='InlineResponse20011',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'))
def cancel_booking(self, booking_id, **kwargs):
"""
Cancel a booking
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.cancel_booking(booking_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id: (required)
:return: InlineResponse2003
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.cancel_booking_with_http_info(booking_id, **kwargs)
else:
(data) = self.cancel_booking_with_http_info(booking_id, **kwargs)
return data
def cancel_booking_with_http_info(self, booking_id, **kwargs):
"""
Cancel a booking
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.cancel_booking_with_http_info(booking_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id: (required)
:return: InlineResponse2003
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['booking_id']
all_params.append('callback')
all_params.append('_return_http_data_only')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method cancel_booking" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'booking_id' is set
if ('booking_id' not in params) or (params['booking_id'] is None):
raise ValueError("Missing the required parameter `booking_id` when calling `cancel_booking`")
resource_path = '/booking/cancel'.replace('{format}', 'json')
path_params = {}
query_params = {}
if 'booking_id' in params:
query_params['booking_id'] = params['booking_id']
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = []
return self.api_client.call_api(resource_path, 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='InlineResponse2003',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'))
def confirm_booking(self, booking_id, **kwargs):
"""
Confirm a booking and all of its sessions and notify the lead customer
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.confirm_booking(booking_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id: (required)
:return: InlineResponse20012
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.confirm_booking_with_http_info(booking_id, **kwargs)
else:
(data) = self.confirm_booking_with_http_info(booking_id, **kwargs)
return data
def confirm_booking_with_http_info(self, booking_id, **kwargs):
"""
Confirm a booking and all of its sessions and notify the lead customer
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.confirm_booking_with_http_info(booking_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id: (required)
:return: InlineResponse20012
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['booking_id']
all_params.append('callback')
all_params.append('_return_http_data_only')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method confirm_booking" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'booking_id' is set
if ('booking_id' not in params) or (params['booking_id'] is None):
raise ValueError("Missing the required parameter `booking_id` when calling `confirm_booking`")
resource_path = '/booking/confirm'.replace('{format}', 'json')
path_params = {}
query_params = {}
if 'booking_id' in params:
query_params['booking_id'] = params['booking_id']
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = []
return self.api_client.call_api(resource_path, 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='InlineResponse20012',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'))
def delete_booking(self, id, **kwargs):
"""
Delete a booking by ID
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.delete_booking(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: (required)
:return: InlineResponse2003
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.delete_booking_with_http_info(id, **kwargs)
else:
(data) = self.delete_booking_with_http_info(id, **kwargs)
return data
def delete_booking_with_http_info(self, id, **kwargs):
"""
Delete a booking by ID
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.delete_booking_with_http_info(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: (required)
:return: InlineResponse2003
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['id']
all_params.append('callback')
all_params.append('_return_http_data_only')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_booking" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'id' is set
if ('id' not in params) or (params['id'] is None):
raise ValueError("Missing the required parameter `id` when calling `delete_booking`")
resource_path = '/booking/delete'.replace('{format}', 'json')
path_params = {}
query_params = {}
if 'id' in params:
query_params['id'] = params['id']
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = []
return self.api_client.call_api(resource_path, 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='InlineResponse2003',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'))
def dettach_accommodation(self, booking_id, accommodation_id, customer_id, **kwargs):
"""
Dettach an accommodation booking to a booking
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.dettach_accommodation(booking_id, accommodation_id, customer_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id: (required)
:param int accommodation_id: (required)
:param int customer_id: (required)
:param date start:
:return: InlineResponse20017
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.dettach_accommodation_with_http_info(booking_id, accommodation_id, customer_id, **kwargs)
else:
(data) = self.dettach_accommodation_with_http_info(booking_id, accommodation_id, customer_id, **kwargs)
return data
def dettach_accommodation_with_http_info(self, booking_id, accommodation_id, customer_id, **kwargs):
"""
Dettach an accommodation booking to a booking
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.dettach_accommodation_with_http_info(booking_id, accommodation_id, customer_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id: (required)
:param int accommodation_id: (required)
:param int customer_id: (required)
:param date start:
:return: InlineResponse20017
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['booking_id', 'accommodation_id', 'customer_id', 'start']
all_params.append('callback')
all_params.append('_return_http_data_only')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method dettach_accommodation" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'booking_id' is set
if ('booking_id' not in params) or (params['booking_id'] is None):
raise ValueError("Missing the required parameter `booking_id` when calling `dettach_accommodation`")
# verify the required parameter 'accommodation_id' is set
if ('accommodation_id' not in params) or (params['accommodation_id'] is None):
raise ValueError("Missing the required parameter `accommodation_id` when calling `dettach_accommodation`")
# verify the required parameter 'customer_id' is set
if ('customer_id' not in params) or (params['customer_id'] is None):
raise ValueError("Missing the required parameter `customer_id` when calling `dettach_accommodation`")
resource_path = '/booking/remove-accommodation'.replace('{format}', 'json')
path_params = {}
query_params = {}
if 'booking_id' in params:
query_params['booking_id'] = params['booking_id']
if 'accommodation_id' in params:
query_params['accommodation_id'] = params['accommodation_id']
if 'customer_id' in params:
query_params['customer_id'] = params['customer_id']
if 'start' in params:
query_params['start'] = params['start']
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = []
return self.api_client.call_api(resource_path, 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='InlineResponse20017',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'))
def dettach_addon(self, booking_id, bookingdetail_id, addon_id, **kwargs):
"""
Dettach an addon to a trip of a booking
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.dettach_addon(booking_id, bookingdetail_id, addon_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id: (required)
:param int bookingdetail_id: (required)
:param int addon_id: (required)
:param int packagefacade_id:
:return: InlineResponse20017
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.dettach_addon_with_http_info(booking_id, bookingdetail_id, addon_id, **kwargs)
else:
(data) = self.dettach_addon_with_http_info(booking_id, bookingdetail_id, addon_id, **kwargs)
return data
def dettach_addon_with_http_info(self, booking_id, bookingdetail_id, addon_id, **kwargs):
"""
Dettach an addon to a trip of a booking
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.dettach_addon_with_http_info(booking_id, bookingdetail_id, addon_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id: (required)
:param int bookingdetail_id: (required)
:param int addon_id: (required)
:param int packagefacade_id:
:return: InlineResponse20017
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['booking_id', 'bookingdetail_id', 'addon_id', 'packagefacade_id']
all_params.append('callback')
all_params.append('_return_http_data_only')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method dettach_addon" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'booking_id' is set
if ('booking_id' not in params) or (params['booking_id'] is None):
raise ValueError("Missing the required parameter `booking_id` when calling `dettach_addon`")
# verify the required parameter 'bookingdetail_id' is set
if ('bookingdetail_id' not in params) or (params['bookingdetail_id'] is None):
raise ValueError("Missing the required parameter `bookingdetail_id` when calling `dettach_addon`")
# verify the required parameter 'addon_id' is set
if ('addon_id' not in params) or (params['addon_id'] is None):
raise ValueError("Missing the required parameter `addon_id` when calling `dettach_addon`")
resource_path = '/booking/remove-addon'.replace('{format}', 'json')
path_params = {}
query_params = {}
if 'booking_id' in params:
query_params['booking_id'] = params['booking_id']
if 'bookingdetail_id' in params:
query_params['bookingdetail_id'] = params['bookingdetail_id']
if 'addon_id' in params:
query_params['addon_id'] = params['addon_id']
if 'packagefacade_id' in params:
query_params['packagefacade_id'] = params['packagefacade_id']
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = []
return self.api_client.call_api(resource_path, 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='InlineResponse20017',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'))
def dettach_pickup(self, booking_id, **kwargs):
"""
Dettach a pickup location for a booking
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.dettach_pickup(booking_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id: (required)
:param int id:
:return: InlineResponse2003
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.dettach_pickup_with_http_info(booking_id, **kwargs)
else:
(data) = self.dettach_pickup_with_http_info(booking_id, **kwargs)
return data
def dettach_pickup_with_http_info(self, booking_id, **kwargs):
"""
Dettach a pickup location for a booking
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.dettach_pickup_with_http_info(booking_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id: (required)
:param int id:
:return: InlineResponse2003
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['booking_id', 'id']
all_params.append('callback')
all_params.append('_return_http_data_only')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method dettach_pickup" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'booking_id' is set
if ('booking_id' not in params) or (params['booking_id'] is None):
raise ValueError("Missing the required parameter `booking_id` when calling `dettach_pickup`")
resource_path = '/booking/remove-pickup'.replace('{format}', 'json')
path_params = {}
query_params = {}
if 'booking_id' in params:
query_params['booking_id'] = params['booking_id']
if 'id' in params:
query_params['id'] = params['id']
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = []
return self.api_client.call_api(resource_path, 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='InlineResponse2003',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'))
def edit_booking_info(self, **kwargs):
"""
Edit the information related to a booking
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.edit_booking_info(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id:
:param float discount:
:param str comment:
:return: InlineResponse20014
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.edit_booking_info_with_http_info(**kwargs)
else:
(data) = self.edit_booking_info_with_http_info(**kwargs)
return data
def edit_booking_info_with_http_info(self, **kwargs):
"""
Edit the information related to a booking
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.edit_booking_info_with_http_info(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id:
:param float discount:
:param str comment:
:return: InlineResponse20014
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['booking_id', 'discount', 'comment']
all_params.append('callback')
all_params.append('_return_http_data_only')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method edit_booking_info" % key
)
params[key] = val
del params['kwargs']
resource_path = '/booking/edit-info'.replace('{format}', 'json')
path_params = {}
query_params = {}
if 'booking_id' in params:
query_params['booking_id'] = params['booking_id']
if 'discount' in params:
query_params['discount'] = params['discount']
if 'comment' in params:
query_params['comment'] = params['comment']
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = []
return self.api_client.call_api(resource_path, 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='InlineResponse20014',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'))
def filter_bookings(self, **kwargs):
"""
Get all bookings matching a filter
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.filter_bookings(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str reference:
:param date date:
:param str lastname:
:return: InlineResponse20013
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.filter_bookings_with_http_info(**kwargs)
else:
(data) = self.filter_bookings_with_http_info(**kwargs)
return data
def filter_bookings_with_http_info(self, **kwargs):
"""
Get all bookings matching a filter
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.filter_bookings_with_http_info(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str reference:
:param date date:
:param str lastname:
:return: InlineResponse20013
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['reference', 'date', 'lastname']
all_params.append('callback')
all_params.append('_return_http_data_only')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method filter_bookings" % key
)
params[key] = val
del params['kwargs']
resource_path = '/booking/filter'.replace('{format}', 'json')
path_params = {}
query_params = {}
if 'reference' in params:
query_params['reference'] = params['reference']
if 'date' in params:
query_params['date'] = params['date']
if 'lastname' in params:
query_params['lastname'] = params['lastname']
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = []
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='InlineResponse20013',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'))
def get_all_bookings(self, **kwargs):
"""
Retrieve all bookings
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_all_bookings(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: list[Booking]
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_all_bookings_with_http_info(**kwargs)
else:
(data) = self.get_all_bookings_with_http_info(**kwargs)
return data
def get_all_bookings_with_http_info(self, **kwargs):
"""
Retrieve all bookings
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_all_bookings_with_http_info(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: list[Booking]
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('callback')
all_params.append('_return_http_data_only')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_all_bookings" % key
)
params[key] = val
del params['kwargs']
resource_path = '/booking/all'.replace('{format}', 'json')
path_params = {}
query_params = {}
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = []
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='list[Booking]',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'))
def get_all_with_trashed_bookings(self, **kwargs):
"""
Retrieve all bookings including any deleted models
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_all_with_trashed_bookings(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: list[Booking]
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_all_with_trashed_bookings_with_http_info(**kwargs)
else:
(data) = self.get_all_with_trashed_bookings_with_http_info(**kwargs)
return data
def get_all_with_trashed_bookings_with_http_info(self, **kwargs):
"""
Retrieve all bookings including any deleted models
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_all_with_trashed_bookings_with_http_info(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: list[Booking]
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('callback')
all_params.append('_return_http_data_only')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_all_with_trashed_bookings" % key
)
params[key] = val
del params['kwargs']
resource_path = '/booking/all-with-trashed'.replace('{format}', 'json')
path_params = {}
query_params = {}
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = []
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='list[Booking]',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'))
def get_booking(self, id, **kwargs):
"""
Retrieve a booking by ID
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_booking(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: (required)
:return: InlineResponse2007
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_booking_with_http_info(id, **kwargs)
else:
(data) = self.get_booking_with_http_info(id, **kwargs)
return data
def get_booking_with_http_info(self, id, **kwargs):
"""
Retrieve a booking by ID
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_booking_with_http_info(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: (required)
:return: InlineResponse2007
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['id']
all_params.append('callback')
all_params.append('_return_http_data_only')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_booking" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'id' is set
if ('id' not in params) or (params['id'] is None):
raise ValueError("Missing the required parameter `id` when calling `get_booking`")
resource_path = '/booking'.replace('{format}', 'json')
path_params = {}
query_params = {}
if 'id' in params:
query_params['id'] = params['id']
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = []
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='InlineResponse2007',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'))
def get_customer_bookings(self, customer_id, **kwargs):
"""
Get all bookings for a customer
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_customer_bookings(customer_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int customer_id: (required)
:return: InlineResponse20013
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_customer_bookings_with_http_info(customer_id, **kwargs)
else:
(data) = self.get_customer_bookings_with_http_info(customer_id, **kwargs)
return data
def get_customer_bookings_with_http_info(self, customer_id, **kwargs):
"""
Get all bookings for a customer
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_customer_bookings_with_http_info(customer_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int customer_id: (required)
:return: InlineResponse20013
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['customer_id']
all_params.append('callback')
all_params.append('_return_http_data_only')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_customer_bookings" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'customer_id' is set
if ('customer_id' not in params) or (params['customer_id'] is None):
raise ValueError("Missing the required parameter `customer_id` when calling `get_customer_bookings`")
resource_path = '/booking/customer'.replace('{format}', 'json')
path_params = {}
query_params = {}
if 'customer_id' in params:
query_params['customer_id'] = params['customer_id']
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = []
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='InlineResponse20013',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'))
def get_payments(self, **kwargs):
"""
Retrieve all payments made for a booking
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_payments(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id:
:return: InlineResponse20015
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_payments_with_http_info(**kwargs)
else:
(data) = self.get_payments_with_http_info(**kwargs)
return data
def get_payments_with_http_info(self, **kwargs):
"""
Retrieve all payments made for a booking
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_payments_with_http_info(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id:
:return: InlineResponse20015
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['booking_id']
all_params.append('callback')
all_params.append('_return_http_data_only')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_payments" % key
)
params[key] = val
del params['kwargs']
resource_path = '/booking/payments'.replace('{format}', 'json')
path_params = {}
query_params = {}
if 'booking_id' in params:
query_params['booking_id'] = params['booking_id']
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = []
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='InlineResponse20015',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'))
def get_refunds(self, **kwargs):
"""
Retrieve all refunds for a booking
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_refunds(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id:
:return: InlineResponse20016
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_refunds_with_http_info(**kwargs)
else:
(data) = self.get_refunds_with_http_info(**kwargs)
return data
def get_refunds_with_http_info(self, **kwargs):
"""
Retrieve all refunds for a booking
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_refunds_with_http_info(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id:
:return: InlineResponse20016
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['booking_id']
all_params.append('callback')
all_params.append('_return_http_data_only')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_refunds" % key
)
params[key] = val
del params['kwargs']
resource_path = '/booking/refunds'.replace('{format}', 'json')
path_params = {}
query_params = {}
if 'booking_id' in params:
query_params['booking_id'] = params['booking_id']
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = []
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='InlineResponse20016',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'))
def get_todays_bookings(self, **kwargs):
"""
Get all bookings made today
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_todays_bookings(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: InlineResponse20013
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_todays_bookings_with_http_info(**kwargs)
else:
(data) = self.get_todays_bookings_with_http_info(**kwargs)
return data
def get_todays_bookings_with_http_info(self, **kwargs):
"""
Get all bookings made today
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_todays_bookings_with_http_info(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: InlineResponse20013
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('callback')
all_params.append('_return_http_data_only')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_todays_bookings" % key
)
params[key] = val
del params['kwargs']
resource_path = '/booking/today'.replace('{format}', 'json')
path_params = {}
query_params = {}
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = []
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='InlineResponse20013',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'))
def get_tommorows_bookings(self, **kwargs):
"""
Get all bookings made today
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_tommorows_bookings(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: InlineResponse20013
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_tommorows_bookings_with_http_info(**kwargs)
else:
(data) = self.get_tommorows_bookings_with_http_info(**kwargs)
return data
def get_tommorows_bookings_with_http_info(self, **kwargs):
"""
Get all bookings made today
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_tommorows_bookings_with_http_info(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: InlineResponse20013
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('callback')
all_params.append('_return_http_data_only')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_tommorows_bookings" % key
)
params[key] = val
del params['kwargs']
resource_path = '/booking/tommorow'.replace('{format}', 'json')
path_params = {}
query_params = {}
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = []
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='InlineResponse20013',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'))
def init_booking(self, source, **kwargs):
"""
Create a new empty booking
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.init_booking(source, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str source: (required)
:param int agent_id:
:param str agent_reference:
:return: InlineResponse201
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.init_booking_with_http_info(source, **kwargs)
else:
(data) = self.init_booking_with_http_info(source, **kwargs)
return data
def init_booking_with_http_info(self, source, **kwargs):
"""
Create a new empty booking
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.init_booking_with_http_info(source, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str source: (required)
:param int agent_id:
:param str agent_reference:
:return: InlineResponse201
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['source', 'agent_id', 'agent_reference']
all_params.append('callback')
all_params.append('_return_http_data_only')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method init_booking" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'source' is set
if ('source' not in params) or (params['source'] is None):
raise ValueError("Missing the required parameter `source` when calling `init_booking`")
resource_path = '/booking/init'.replace('{format}', 'json')
path_params = {}
query_params = {}
if 'source' in params:
query_params['source'] = params['source']
if 'agent_id' in params:
query_params['agent_id'] = params['agent_id']
if 'agent_reference' in params:
query_params['agent_reference'] = params['agent_reference']
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = []
return self.api_client.call_api(resource_path, 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='InlineResponse201',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'))
def remove_booking_detail(self, booking_id, bookingdetail_id, **kwargs):
"""
Remove a detail from a booking
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.remove_booking_detail(booking_id, bookingdetail_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id: (required)
:param int bookingdetail_id: (required)
:return: InlineResponse20017
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.remove_booking_detail_with_http_info(booking_id, bookingdetail_id, **kwargs)
else:
(data) = self.remove_booking_detail_with_http_info(booking_id, bookingdetail_id, **kwargs)
return data
def remove_booking_detail_with_http_info(self, booking_id, bookingdetail_id, **kwargs):
"""
Remove a detail from a booking
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.remove_booking_detail_with_http_info(booking_id, bookingdetail_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id: (required)
:param int bookingdetail_id: (required)
:return: InlineResponse20017
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['booking_id', 'bookingdetail_id']
all_params.append('callback')
all_params.append('_return_http_data_only')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method remove_booking_detail" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'booking_id' is set
if ('booking_id' not in params) or (params['booking_id'] is None):
raise ValueError("Missing the required parameter `booking_id` when calling `remove_booking_detail`")
# verify the required parameter 'bookingdetail_id' is set
if ('bookingdetail_id' not in params) or (params['bookingdetail_id'] is None):
raise ValueError("Missing the required parameter `bookingdetail_id` when calling `remove_booking_detail`")
resource_path = '/booking/remove-detail'.replace('{format}', 'json')
path_params = {}
query_params = {}
if 'booking_id' in params:
query_params['booking_id'] = params['booking_id']
if 'bookingdetail_id' in params:
query_params['bookingdetail_id'] = params['bookingdetail_id']
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = []
return self.api_client.call_api(resource_path, 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='InlineResponse20017',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'))
def resend_confirmation(self, booking_id, **kwargs):
"""
Resend the confirmation email to the lead customer
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.resend_confirmation(booking_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id: (required)
:return: InlineResponse2003
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.resend_confirmation_with_http_info(booking_id, **kwargs)
else:
(data) = self.resend_confirmation_with_http_info(booking_id, **kwargs)
return data
def resend_confirmation_with_http_info(self, booking_id, **kwargs):
"""
Resend the confirmation email to the lead customer
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.resend_confirmation_with_http_info(booking_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id: (required)
:return: InlineResponse2003
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['booking_id']
all_params.append('callback')
all_params.append('_return_http_data_only')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method resend_confirmation" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'booking_id' is set
if ('booking_id' not in params) or (params['booking_id'] is None):
raise ValueError("Missing the required parameter `booking_id` when calling `resend_confirmation`")
resource_path = '/booking/resend-confirmation'.replace('{format}', 'json')
path_params = {}
query_params = {}
if 'booking_id' in params:
query_params['booking_id'] = params['booking_id']
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = []
return self.api_client.call_api(resource_path, 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='InlineResponse2003',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'))
def reserve_booking(self, booking_id, **kwargs):
"""
Reserve a booking and its sessions capcity until a set date
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.reserve_booking(booking_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id: (required)
:param date reserved_until:
:return: InlineResponse20018
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.reserve_booking_with_http_info(booking_id, **kwargs)
else:
(data) = self.reserve_booking_with_http_info(booking_id, **kwargs)
return data
def reserve_booking_with_http_info(self, booking_id, **kwargs):
"""
Reserve a booking and its sessions capcity until a set date
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.reserve_booking_with_http_info(booking_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id: (required)
:param date reserved_until:
:return: InlineResponse20018
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['booking_id', 'reserved_until']
all_params.append('callback')
all_params.append('_return_http_data_only')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method reserve_booking" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'booking_id' is set
if ('booking_id' not in params) or (params['booking_id'] is None):
raise ValueError("Missing the required parameter `booking_id` when calling `reserve_booking`")
resource_path = '/booking/reserve'.replace('{format}', 'json')
path_params = {}
query_params = {}
if 'booking_id' in params:
query_params['booking_id'] = params['booking_id']
if 'reserved_until' in params:
query_params['reserved_until'] = params['reserved_until']
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = []
return self.api_client.call_api(resource_path, 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='InlineResponse20018',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'))
def save_booking(self, booking_id, **kwargs):
"""
Save a booking as a quote and release all capacity of sessions
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.save_booking(booking_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id: (required)
:return: InlineResponse2003
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.save_booking_with_http_info(booking_id, **kwargs)
else:
(data) = self.save_booking_with_http_info(booking_id, **kwargs)
return data
def save_booking_with_http_info(self, booking_id, **kwargs):
"""
Save a booking as a quote and release all capacity of sessions
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.save_booking_with_http_info(booking_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id: (required)
:return: InlineResponse2003
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['booking_id']
all_params.append('callback')
all_params.append('_return_http_data_only')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method save_booking" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'booking_id' is set
if ('booking_id' not in params) or (params['booking_id'] is None):
raise ValueError("Missing the required parameter `booking_id` when calling `save_booking`")
resource_path = '/booking/save'.replace('{format}', 'json')
path_params = {}
query_params = {}
if 'booking_id' in params:
query_params['booking_id'] = params['booking_id']
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = []
return self.api_client.call_api(resource_path, 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='InlineResponse2003',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'))
def set_lead_customer(self, booking_id, customer_id, **kwargs):
"""
Set the lead customer for a booking
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.set_lead_customer(booking_id, customer_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id: (required)
:param int customer_id: (required)
:return: InlineResponse2003
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.set_lead_customer_with_http_info(booking_id, customer_id, **kwargs)
else:
(data) = self.set_lead_customer_with_http_info(booking_id, customer_id, **kwargs)
return data
def set_lead_customer_with_http_info(self, booking_id, customer_id, **kwargs):
"""
Set the lead customer for a booking
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.set_lead_customer_with_http_info(booking_id, customer_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id: (required)
:param int customer_id: (required)
:return: InlineResponse2003
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['booking_id', 'customer_id']
all_params.append('callback')
all_params.append('_return_http_data_only')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method set_lead_customer" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'booking_id' is set
if ('booking_id' not in params) or (params['booking_id'] is None):
raise ValueError("Missing the required parameter `booking_id` when calling `set_lead_customer`")
# verify the required parameter 'customer_id' is set
if ('customer_id' not in params) or (params['customer_id'] is None):
raise ValueError("Missing the required parameter `customer_id` when calling `set_lead_customer`")
resource_path = '/booking/set-lead'.replace('{format}', 'json')
path_params = {}
query_params = {}
if 'booking_id' in params:
query_params['booking_id'] = params['booking_id']
if 'customer_id' in params:
query_params['customer_id'] = params['customer_id']
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = []
return self.api_client.call_api(resource_path, 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='InlineResponse2003',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'))
| [
"six.iteritems"
] | [((4678, 4705), 'six.iteritems', 'iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (4687, 4705), False, 'from six import iteritems\n'), ((10568, 10595), 'six.iteritems', 'iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (10577, 10595), False, 'from six import iteritems\n'), ((16156, 16183), 'six.iteritems', 'iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (16165, 16183), False, 'from six import iteritems\n'), ((21583, 21610), 'six.iteritems', 'iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (21592, 21610), False, 'from six import iteritems\n'), ((26589, 26616), 'six.iteritems', 'iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (26598, 26616), False, 'from six import iteritems\n'), ((30795, 30822), 'six.iteritems', 'iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (30804, 30822), False, 'from six import iteritems\n'), ((34829, 34856), 'six.iteritems', 'iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (34838, 34856), False, 'from six import iteritems\n'), ((39439, 39466), 'six.iteritems', 'iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (39448, 39466), False, 'from six import iteritems\n'), ((44897, 44924), 'six.iteritems', 'iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (44906, 44924), False, 'from six import iteritems\n'), ((49909, 49936), 'six.iteritems', 'iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (49918, 49936), False, 'from six import iteritems\n'), ((54200, 54227), 'six.iteritems', 'iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (54209, 54227), False, 'from six import iteritems\n'), ((58316, 58343), 'six.iteritems', 'iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (58325, 58343), False, 'from six import iteritems\n'), ((62175, 62202), 'six.iteritems', 'iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (62184, 62202), False, 'from six import iteritems\n'), ((65898, 65925), 'six.iteritems', 'iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (65907, 65925), False, 'from six import iteritems\n'), ((69595, 69622), 'six.iteritems', 'iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (69604, 69622), False, 'from six import iteritems\n'), ((73698, 73725), 'six.iteritems', 'iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (73707, 73725), False, 'from six import iteritems\n'), ((77755, 77782), 'six.iteritems', 'iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (77764, 77782), False, 'from six import iteritems\n'), ((81530, 81557), 'six.iteritems', 'iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (81539, 81557), False, 'from six import iteritems\n'), ((85261, 85288), 'six.iteritems', 'iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (85270, 85288), False, 'from six import iteritems\n'), ((88919, 88946), 'six.iteritems', 'iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (88928, 88946), False, 'from six import iteritems\n'), ((92816, 92843), 'six.iteritems', 'iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (92825, 92843), False, 'from six import iteritems\n'), ((97372, 97399), 'six.iteritems', 'iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (97381, 97399), False, 'from six import iteritems\n'), ((101969, 101996), 'six.iteritems', 'iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (101978, 101996), False, 'from six import iteritems\n'), ((106268, 106295), 'six.iteritems', 'iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (106277, 106295), False, 'from six import iteritems\n'), ((110551, 110578), 'six.iteritems', 'iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (110560, 110578), False, 'from six import iteritems\n'), ((114872, 114899), 'six.iteritems', 'iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (114881, 114899), False, 'from six import iteritems\n')] |
import os
target_path = 'groundtruths'
mirror_path = 'detections'
files = []
for (dirpath, dirnames, filenames) in os.walk(target_path):
if len(dirnames) == 0:
files.extend([f_name for f_name in filenames])
# print(files[:10])
for filename in files:
mirror = os.path.join(mirror_path, filename)
if os.path.exists(mirror) is False:
target = os.path.join(target_path, filename)
if os.path.exists(target):
os.remove(target)
| [
"os.path.exists",
"os.path.join",
"os.walk",
"os.remove"
] | [((117, 137), 'os.walk', 'os.walk', (['target_path'], {}), '(target_path)\n', (124, 137), False, 'import os\n'), ((278, 313), 'os.path.join', 'os.path.join', (['mirror_path', 'filename'], {}), '(mirror_path, filename)\n', (290, 313), False, 'import os\n'), ((321, 343), 'os.path.exists', 'os.path.exists', (['mirror'], {}), '(mirror)\n', (335, 343), False, 'import os\n'), ((371, 406), 'os.path.join', 'os.path.join', (['target_path', 'filename'], {}), '(target_path, filename)\n', (383, 406), False, 'import os\n'), ((418, 440), 'os.path.exists', 'os.path.exists', (['target'], {}), '(target)\n', (432, 440), False, 'import os\n'), ((454, 471), 'os.remove', 'os.remove', (['target'], {}), '(target)\n', (463, 471), False, 'import os\n')] |
# Generated by Django 3.1 on 2021-07-30 07:00
from django.conf import settings
import django.contrib.auth.models
import django.contrib.auth.validators
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import sunnysouth.lib.models
class Migration(migrations.Migration):
initial = True
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')),
('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('uuid', models.CharField(default=sunnysouth.lib.models.generate_uuid, max_length=300, unique=True)),
('created', models.DateTimeField(auto_now_add=True, help_text='Date time on which the object was created.', verbose_name='created at')),
('modified', models.DateTimeField(auto_now=True, help_text='Date time on which the object was last modified.', verbose_name='modified at')),
('email', models.EmailField(error_messages={'unique': 'A user with that email already exists.'}, max_length=254, unique=True, verbose_name='email address')),
('is_verified', models.BooleanField(default=False, help_text='Set to true when the user have verified its email address.', verbose_name='verified')),
('phone_number', models.CharField(blank=True, max_length=15, validators=[django.core.validators.RegexValidator(message='Phone number must be entered in the format: +999999999. Up to 15 digits allowed.', regex='\\+?1?\\d{9,15}$')])),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'ordering': ['-created', '-modified'],
'get_latest_by': 'created',
'abstract': False,
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
migrations.CreateModel(
name='Category',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('uuid', models.CharField(default=sunnysouth.lib.models.generate_uuid, max_length=300, unique=True)),
('created', models.DateTimeField(auto_now_add=True, help_text='Date time on which the object was created.', verbose_name='created at')),
('modified', models.DateTimeField(auto_now=True, help_text='Date time on which the object was last modified.', verbose_name='modified at')),
('name', models.CharField(max_length=100)),
('description', models.CharField(max_length=500)),
('picture', models.ImageField(blank=True, null=True, upload_to='categories/pictures/', verbose_name='category picture')),
],
options={
'verbose_name': 'category',
'verbose_name_plural': 'categories',
},
),
migrations.CreateModel(
name='Product',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('uuid', models.CharField(default=sunnysouth.lib.models.generate_uuid, max_length=300, unique=True)),
('created', models.DateTimeField(auto_now_add=True, help_text='Date time on which the object was created.', verbose_name='created at')),
('modified', models.DateTimeField(auto_now=True, help_text='Date time on which the object was last modified.', verbose_name='modified at')),
('name', models.CharField(max_length=100)),
('slug', models.CharField(max_length=200, null=True)),
('description', models.CharField(max_length=500)),
('price', models.FloatField()),
('stock', models.PositiveIntegerField(default=1)),
('custom_features', models.JSONField(null=True)),
('code', models.CharField(max_length=50, null=True)),
('is_active', models.BooleanField(default=True, verbose_name='active')),
('is_hidden', models.BooleanField(default=False, verbose_name='hidden')),
('home_service_enabled', models.BooleanField(default=True)),
('category', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='marketplace.category')),
],
options={
'ordering': ['-created', '-modified'],
'get_latest_by': 'created',
'abstract': False,
},
),
migrations.CreateModel(
name='Purchase',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('uuid', models.CharField(default=sunnysouth.lib.models.generate_uuid, max_length=300, unique=True)),
('created', models.DateTimeField(auto_now_add=True, help_text='Date time on which the object was created.', verbose_name='created at')),
('modified', models.DateTimeField(auto_now=True, help_text='Date time on which the object was last modified.', verbose_name='modified at')),
('total_amount', models.FloatField()),
('address', models.JSONField()),
('paid_at', models.DateTimeField(null=True)),
('canceled_at', models.DateTimeField(null=True)),
('status', models.CharField(choices=[('pending', 'Pending'), ('canceled', 'Canceled'), ('paid', 'Paid')], default='pending', max_length=100)),
('client_ranking', models.FloatField(default=5.0)),
('supplier_ranking', models.FloatField(default=5.0)),
('client', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ['-created', '-modified'],
'get_latest_by': 'created',
'abstract': False,
},
),
migrations.CreateModel(
name='Supplier',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('uuid', models.CharField(default=sunnysouth.lib.models.generate_uuid, max_length=300, unique=True)),
('created', models.DateTimeField(auto_now_add=True, help_text='Date time on which the object was created.', verbose_name='created at')),
('modified', models.DateTimeField(auto_now=True, help_text='Date time on which the object was last modified.', verbose_name='modified at')),
('name', models.CharField(max_length=300)),
('biography', models.TextField(blank=True, max_length=500)),
('status', models.CharField(choices=[('pending', 'Pending'), ('rejected', 'Rejected'), ('approved', 'Approved')], default='pending', max_length=100)),
('is_active', models.BooleanField(default=True, verbose_name='active')),
('reputation', models.FloatField(default=5.0)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='supplier', to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ['-created', '-modified'],
'get_latest_by': 'created',
'abstract': False,
},
),
migrations.CreateModel(
name='PurchaseProduct',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('uuid', models.CharField(default=sunnysouth.lib.models.generate_uuid, max_length=300, unique=True)),
('created', models.DateTimeField(auto_now_add=True, help_text='Date time on which the object was created.', verbose_name='created at')),
('modified', models.DateTimeField(auto_now=True, help_text='Date time on which the object was last modified.', verbose_name='modified at')),
('quantity', models.IntegerField()),
('price', models.FloatField()),
('product', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='marketplace.product')),
('purchase', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='marketplace.purchase')),
],
options={
'ordering': ['-created', '-modified'],
'get_latest_by': 'created',
'abstract': False,
},
),
migrations.AddField(
model_name='purchase',
name='products',
field=models.ManyToManyField(through='marketplace.PurchaseProduct', to='marketplace.Product'),
),
migrations.CreateModel(
name='Profile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('uuid', models.CharField(default=sunnysouth.lib.models.generate_uuid, max_length=300, unique=True)),
('created', models.DateTimeField(auto_now_add=True, help_text='Date time on which the object was created.', verbose_name='created at')),
('modified', models.DateTimeField(auto_now=True, help_text='Date time on which the object was last modified.', verbose_name='modified at')),
('slug_name', models.CharField(max_length=300, null=True)),
('biography', models.TextField(blank=True, max_length=500)),
('is_active', models.BooleanField(default=True, verbose_name='active')),
('reputation', models.FloatField(default=5.0)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='profile', to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ['-created', '-modified'],
'get_latest_by': 'created',
'abstract': False,
},
),
migrations.AddField(
model_name='product',
name='supplier',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='products', to='marketplace.supplier'),
),
migrations.CreateModel(
name='Address',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('uuid', models.CharField(default=sunnysouth.lib.models.generate_uuid, max_length=300, unique=True)),
('created', models.DateTimeField(auto_now_add=True, help_text='Date time on which the object was created.', verbose_name='created at')),
('modified', models.DateTimeField(auto_now=True, help_text='Date time on which the object was last modified.', verbose_name='modified at')),
('name', models.CharField(max_length=300)),
('city', models.CharField(max_length=300)),
('state', models.CharField(max_length=300)),
('country', models.CharField(max_length=300)),
('latitude', models.CharField(max_length=100)),
('longitude', models.CharField(max_length=100)),
('reference', models.CharField(max_length=300)),
('custom_address', models.CharField(max_length=500)),
('is_primary', models.BooleanField(default=False, verbose_name='primary')),
('addressable_object_id', models.IntegerField()),
('addressable_content_type', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='contenttypes.contenttype')),
],
options={
'ordering': ['-created', '-modified'],
'get_latest_by': 'created',
'abstract': False,
},
),
]
| [
"django.db.models.EmailField",
"django.db.models.OneToOneField",
"django.db.models.FloatField",
"django.db.models.TextField",
"django.db.models.ForeignKey",
"django.db.models.IntegerField",
"django.db.models.ManyToManyField",
"django.db.models.JSONField",
"django.db.models.BooleanField",
"django.d... | [((10857, 10949), 'django.db.models.ManyToManyField', 'models.ManyToManyField', ([], {'through': '"""marketplace.PurchaseProduct"""', 'to': '"""marketplace.Product"""'}), "(through='marketplace.PurchaseProduct', to=\n 'marketplace.Product')\n", (10879, 10949), False, 'from django.db import migrations, models\n'), ((12340, 12459), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.CASCADE', 'related_name': '"""products"""', 'to': '"""marketplace.supplier"""'}), "(on_delete=django.db.models.deletion.CASCADE, related_name\n ='products', to='marketplace.supplier')\n", (12357, 12459), False, 'from django.db import migrations, models\n'), ((642, 735), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (658, 735), False, 'from django.db import migrations, models\n'), ((763, 820), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(128)', 'verbose_name': '"""password"""'}), "(max_length=128, verbose_name='password')\n", (779, 820), False, 'from django.db import migrations, models\n'), ((854, 924), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'blank': '(True)', 'null': '(True)', 'verbose_name': '"""last login"""'}), "(blank=True, null=True, verbose_name='last login')\n", (874, 924), False, 'from django.db import migrations, models\n'), ((960, 1131), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)', 'help_text': '"""Designates that this user has all permissions without explicitly assigning them."""', 'verbose_name': '"""superuser status"""'}), "(default=False, help_text=\n 'Designates that this user has all permissions without explicitly assigning them.'\n , verbose_name='superuser status')\n", (979, 1131), False, 'from django.db import migrations, models\n'), ((1485, 1556), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(150)', 'verbose_name': '"""first name"""'}), "(blank=True, max_length=150, verbose_name='first name')\n", (1501, 1556), False, 'from django.db import migrations, models\n'), ((1589, 1659), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(150)', 'verbose_name': '"""last name"""'}), "(blank=True, max_length=150, verbose_name='last name')\n", (1605, 1659), False, 'from django.db import migrations, models\n'), ((1691, 1834), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)', 'help_text': '"""Designates whether the user can log into this admin site."""', 'verbose_name': '"""staff status"""'}), "(default=False, help_text=\n 'Designates whether the user can log into this admin site.',\n verbose_name='staff status')\n", (1710, 1834), False, 'from django.db import migrations, models\n'), ((1858, 2039), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(True)', 'help_text': '"""Designates whether this user should be treated as active. Unselect this instead of deleting accounts."""', 'verbose_name': '"""active"""'}), "(default=True, help_text=\n 'Designates whether this user should be treated as active. Unselect this instead of deleting accounts.'\n , verbose_name='active')\n", (1877, 2039), False, 'from django.db import migrations, models\n'), ((2064, 2152), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'default': 'django.utils.timezone.now', 'verbose_name': '"""date joined"""'}), "(default=django.utils.timezone.now, verbose_name=\n 'date joined')\n", (2084, 2152), False, 'from django.db import migrations, models\n'), ((2175, 2270), 'django.db.models.CharField', 'models.CharField', ([], {'default': 'sunnysouth.lib.models.generate_uuid', 'max_length': '(300)', 'unique': '(True)'}), '(default=sunnysouth.lib.models.generate_uuid, max_length=\n 300, unique=True)\n', (2191, 2270), False, 'from django.db import migrations, models\n'), ((2296, 2423), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)', 'help_text': '"""Date time on which the object was created."""', 'verbose_name': '"""created at"""'}), "(auto_now_add=True, help_text=\n 'Date time on which the object was created.', verbose_name='created at')\n", (2316, 2423), False, 'from django.db import migrations, models\n'), ((2450, 2585), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now': '(True)', 'help_text': '"""Date time on which the object was last modified."""', 'verbose_name': '"""modified at"""'}), "(auto_now=True, help_text=\n 'Date time on which the object was last modified.', verbose_name=\n 'modified at')\n", (2470, 2585), False, 'from django.db import migrations, models\n'), ((2604, 2757), 'django.db.models.EmailField', 'models.EmailField', ([], {'error_messages': "{'unique': 'A user with that email already exists.'}", 'max_length': '(254)', 'unique': '(True)', 'verbose_name': '"""email address"""'}), "(error_messages={'unique':\n 'A user with that email already exists.'}, max_length=254, unique=True,\n verbose_name='email address')\n", (2621, 2757), False, 'from django.db import migrations, models\n'), ((2784, 2924), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)', 'help_text': '"""Set to true when the user have verified its email address."""', 'verbose_name': '"""verified"""'}), "(default=False, help_text=\n 'Set to true when the user have verified its email address.',\n verbose_name='verified')\n", (2803, 2924), False, 'from django.db import migrations, models\n'), ((3194, 3445), 'django.db.models.ManyToManyField', 'models.ManyToManyField', ([], {'blank': '(True)', 'help_text': '"""The groups this user belongs to. A user will get all permissions granted to each of their groups."""', 'related_name': '"""user_set"""', 'related_query_name': '"""user"""', 'to': '"""auth.Group"""', 'verbose_name': '"""groups"""'}), "(blank=True, help_text=\n 'The groups this user belongs to. A user will get all permissions granted to each of their groups.'\n , related_name='user_set', related_query_name='user', to='auth.Group',\n verbose_name='groups')\n", (3216, 3445), False, 'from django.db import migrations, models\n'), ((3471, 3675), 'django.db.models.ManyToManyField', 'models.ManyToManyField', ([], {'blank': '(True)', 'help_text': '"""Specific permissions for this user."""', 'related_name': '"""user_set"""', 'related_query_name': '"""user"""', 'to': '"""auth.Permission"""', 'verbose_name': '"""user permissions"""'}), "(blank=True, help_text=\n 'Specific permissions for this user.', related_name='user_set',\n related_query_name='user', to='auth.Permission', verbose_name=\n 'user permissions')\n", (3493, 3675), False, 'from django.db import migrations, models\n'), ((4075, 4168), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (4091, 4168), False, 'from django.db import migrations, models\n'), ((4192, 4287), 'django.db.models.CharField', 'models.CharField', ([], {'default': 'sunnysouth.lib.models.generate_uuid', 'max_length': '(300)', 'unique': '(True)'}), '(default=sunnysouth.lib.models.generate_uuid, max_length=\n 300, unique=True)\n', (4208, 4287), False, 'from django.db import migrations, models\n'), ((4313, 4440), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)', 'help_text': '"""Date time on which the object was created."""', 'verbose_name': '"""created at"""'}), "(auto_now_add=True, help_text=\n 'Date time on which the object was created.', verbose_name='created at')\n", (4333, 4440), False, 'from django.db import migrations, models\n'), ((4467, 4602), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now': '(True)', 'help_text': '"""Date time on which the object was last modified."""', 'verbose_name': '"""modified at"""'}), "(auto_now=True, help_text=\n 'Date time on which the object was last modified.', verbose_name=\n 'modified at')\n", (4487, 4602), False, 'from django.db import migrations, models\n'), ((4620, 4652), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)'}), '(max_length=100)\n', (4636, 4652), False, 'from django.db import migrations, models\n'), ((4687, 4719), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(500)'}), '(max_length=500)\n', (4703, 4719), False, 'from django.db import migrations, models\n'), ((4750, 4861), 'django.db.models.ImageField', 'models.ImageField', ([], {'blank': '(True)', 'null': '(True)', 'upload_to': '"""categories/pictures/"""', 'verbose_name': '"""category picture"""'}), "(blank=True, null=True, upload_to='categories/pictures/',\n verbose_name='category picture')\n", (4767, 4861), False, 'from django.db import migrations, models\n'), ((5124, 5217), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (5140, 5217), False, 'from django.db import migrations, models\n'), ((5241, 5336), 'django.db.models.CharField', 'models.CharField', ([], {'default': 'sunnysouth.lib.models.generate_uuid', 'max_length': '(300)', 'unique': '(True)'}), '(default=sunnysouth.lib.models.generate_uuid, max_length=\n 300, unique=True)\n', (5257, 5336), False, 'from django.db import migrations, models\n'), ((5362, 5489), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)', 'help_text': '"""Date time on which the object was created."""', 'verbose_name': '"""created at"""'}), "(auto_now_add=True, help_text=\n 'Date time on which the object was created.', verbose_name='created at')\n", (5382, 5489), False, 'from django.db import migrations, models\n'), ((5516, 5651), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now': '(True)', 'help_text': '"""Date time on which the object was last modified."""', 'verbose_name': '"""modified at"""'}), "(auto_now=True, help_text=\n 'Date time on which the object was last modified.', verbose_name=\n 'modified at')\n", (5536, 5651), False, 'from django.db import migrations, models\n'), ((5669, 5701), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)'}), '(max_length=100)\n', (5685, 5701), False, 'from django.db import migrations, models\n'), ((5729, 5772), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(200)', 'null': '(True)'}), '(max_length=200, null=True)\n', (5745, 5772), False, 'from django.db import migrations, models\n'), ((5807, 5839), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(500)'}), '(max_length=500)\n', (5823, 5839), False, 'from django.db import migrations, models\n'), ((5868, 5887), 'django.db.models.FloatField', 'models.FloatField', ([], {}), '()\n', (5885, 5887), False, 'from django.db import migrations, models\n'), ((5916, 5954), 'django.db.models.PositiveIntegerField', 'models.PositiveIntegerField', ([], {'default': '(1)'}), '(default=1)\n', (5943, 5954), False, 'from django.db import migrations, models\n'), ((5993, 6020), 'django.db.models.JSONField', 'models.JSONField', ([], {'null': '(True)'}), '(null=True)\n', (6009, 6020), False, 'from django.db import migrations, models\n'), ((6048, 6090), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)', 'null': '(True)'}), '(max_length=50, null=True)\n', (6064, 6090), False, 'from django.db import migrations, models\n'), ((6123, 6179), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(True)', 'verbose_name': '"""active"""'}), "(default=True, verbose_name='active')\n", (6142, 6179), False, 'from django.db import migrations, models\n'), ((6212, 6269), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)', 'verbose_name': '"""hidden"""'}), "(default=False, verbose_name='hidden')\n", (6231, 6269), False, 'from django.db import migrations, models\n'), ((6313, 6346), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(True)'}), '(default=True)\n', (6332, 6346), False, 'from django.db import migrations, models\n'), ((6378, 6482), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'null': '(True)', 'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""marketplace.category"""'}), "(null=True, on_delete=django.db.models.deletion.CASCADE,\n to='marketplace.category')\n", (6395, 6482), False, 'from django.db import migrations, models\n'), ((6783, 6876), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (6799, 6876), False, 'from django.db import migrations, models\n'), ((6900, 6995), 'django.db.models.CharField', 'models.CharField', ([], {'default': 'sunnysouth.lib.models.generate_uuid', 'max_length': '(300)', 'unique': '(True)'}), '(default=sunnysouth.lib.models.generate_uuid, max_length=\n 300, unique=True)\n', (6916, 6995), False, 'from django.db import migrations, models\n'), ((7021, 7148), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)', 'help_text': '"""Date time on which the object was created."""', 'verbose_name': '"""created at"""'}), "(auto_now_add=True, help_text=\n 'Date time on which the object was created.', verbose_name='created at')\n", (7041, 7148), False, 'from django.db import migrations, models\n'), ((7175, 7310), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now': '(True)', 'help_text': '"""Date time on which the object was last modified."""', 'verbose_name': '"""modified at"""'}), "(auto_now=True, help_text=\n 'Date time on which the object was last modified.', verbose_name=\n 'modified at')\n", (7195, 7310), False, 'from django.db import migrations, models\n'), ((7336, 7355), 'django.db.models.FloatField', 'models.FloatField', ([], {}), '()\n', (7353, 7355), False, 'from django.db import migrations, models\n'), ((7386, 7404), 'django.db.models.JSONField', 'models.JSONField', ([], {}), '()\n', (7402, 7404), False, 'from django.db import migrations, models\n'), ((7435, 7466), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'null': '(True)'}), '(null=True)\n', (7455, 7466), False, 'from django.db import migrations, models\n'), ((7501, 7532), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'null': '(True)'}), '(null=True)\n', (7521, 7532), False, 'from django.db import migrations, models\n'), ((7562, 7695), 'django.db.models.CharField', 'models.CharField', ([], {'choices': "[('pending', 'Pending'), ('canceled', 'Canceled'), ('paid', 'Paid')]", 'default': '"""pending"""', 'max_length': '(100)'}), "(choices=[('pending', 'Pending'), ('canceled', 'Canceled'),\n ('paid', 'Paid')], default='pending', max_length=100)\n", (7578, 7695), False, 'from django.db import migrations, models\n'), ((7729, 7759), 'django.db.models.FloatField', 'models.FloatField', ([], {'default': '(5.0)'}), '(default=5.0)\n', (7746, 7759), False, 'from django.db import migrations, models\n'), ((7799, 7829), 'django.db.models.FloatField', 'models.FloatField', ([], {'default': '(5.0)'}), '(default=5.0)\n', (7816, 7829), False, 'from django.db import migrations, models\n'), ((7859, 7955), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.CASCADE', 'to': 'settings.AUTH_USER_MODEL'}), '(on_delete=django.db.models.deletion.CASCADE, to=settings.\n AUTH_USER_MODEL)\n', (7876, 7955), False, 'from django.db import migrations, models\n'), ((8255, 8348), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (8271, 8348), False, 'from django.db import migrations, models\n'), ((8372, 8467), 'django.db.models.CharField', 'models.CharField', ([], {'default': 'sunnysouth.lib.models.generate_uuid', 'max_length': '(300)', 'unique': '(True)'}), '(default=sunnysouth.lib.models.generate_uuid, max_length=\n 300, unique=True)\n', (8388, 8467), False, 'from django.db import migrations, models\n'), ((8493, 8620), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)', 'help_text': '"""Date time on which the object was created."""', 'verbose_name': '"""created at"""'}), "(auto_now_add=True, help_text=\n 'Date time on which the object was created.', verbose_name='created at')\n", (8513, 8620), False, 'from django.db import migrations, models\n'), ((8647, 8782), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now': '(True)', 'help_text': '"""Date time on which the object was last modified."""', 'verbose_name': '"""modified at"""'}), "(auto_now=True, help_text=\n 'Date time on which the object was last modified.', verbose_name=\n 'modified at')\n", (8667, 8782), False, 'from django.db import migrations, models\n'), ((8800, 8832), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(300)'}), '(max_length=300)\n', (8816, 8832), False, 'from django.db import migrations, models\n'), ((8865, 8909), 'django.db.models.TextField', 'models.TextField', ([], {'blank': '(True)', 'max_length': '(500)'}), '(blank=True, max_length=500)\n', (8881, 8909), False, 'from django.db import migrations, models\n'), ((8939, 9080), 'django.db.models.CharField', 'models.CharField', ([], {'choices': "[('pending', 'Pending'), ('rejected', 'Rejected'), ('approved', 'Approved')]", 'default': '"""pending"""', 'max_length': '(100)'}), "(choices=[('pending', 'Pending'), ('rejected', 'Rejected'),\n ('approved', 'Approved')], default='pending', max_length=100)\n", (8955, 9080), False, 'from django.db import migrations, models\n'), ((9109, 9165), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(True)', 'verbose_name': '"""active"""'}), "(default=True, verbose_name='active')\n", (9128, 9165), False, 'from django.db import migrations, models\n'), ((9199, 9229), 'django.db.models.FloatField', 'models.FloatField', ([], {'default': '(5.0)'}), '(default=5.0)\n', (9216, 9229), False, 'from django.db import migrations, models\n'), ((9257, 9380), 'django.db.models.OneToOneField', 'models.OneToOneField', ([], {'on_delete': 'django.db.models.deletion.CASCADE', 'related_name': '"""supplier"""', 'to': 'settings.AUTH_USER_MODEL'}), "(on_delete=django.db.models.deletion.CASCADE,\n related_name='supplier', to=settings.AUTH_USER_MODEL)\n", (9277, 9380), False, 'from django.db import migrations, models\n'), ((9688, 9781), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (9704, 9781), False, 'from django.db import migrations, models\n'), ((9805, 9900), 'django.db.models.CharField', 'models.CharField', ([], {'default': 'sunnysouth.lib.models.generate_uuid', 'max_length': '(300)', 'unique': '(True)'}), '(default=sunnysouth.lib.models.generate_uuid, max_length=\n 300, unique=True)\n', (9821, 9900), False, 'from django.db import migrations, models\n'), ((9926, 10053), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)', 'help_text': '"""Date time on which the object was created."""', 'verbose_name': '"""created at"""'}), "(auto_now_add=True, help_text=\n 'Date time on which the object was created.', verbose_name='created at')\n", (9946, 10053), False, 'from django.db import migrations, models\n'), ((10080, 10215), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now': '(True)', 'help_text': '"""Date time on which the object was last modified."""', 'verbose_name': '"""modified at"""'}), "(auto_now=True, help_text=\n 'Date time on which the object was last modified.', verbose_name=\n 'modified at')\n", (10100, 10215), False, 'from django.db import migrations, models\n'), ((10237, 10258), 'django.db.models.IntegerField', 'models.IntegerField', ([], {}), '()\n', (10256, 10258), False, 'from django.db import migrations, models\n'), ((10287, 10306), 'django.db.models.FloatField', 'models.FloatField', ([], {}), '()\n', (10304, 10306), False, 'from django.db import migrations, models\n'), ((10337, 10430), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""marketplace.product"""'}), "(on_delete=django.db.models.deletion.CASCADE, to=\n 'marketplace.product')\n", (10354, 10430), False, 'from django.db import migrations, models\n'), ((10457, 10551), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""marketplace.purchase"""'}), "(on_delete=django.db.models.deletion.CASCADE, to=\n 'marketplace.purchase')\n", (10474, 10551), False, 'from django.db import migrations, models\n'), ((11061, 11154), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (11077, 11154), False, 'from django.db import migrations, models\n'), ((11178, 11273), 'django.db.models.CharField', 'models.CharField', ([], {'default': 'sunnysouth.lib.models.generate_uuid', 'max_length': '(300)', 'unique': '(True)'}), '(default=sunnysouth.lib.models.generate_uuid, max_length=\n 300, unique=True)\n', (11194, 11273), False, 'from django.db import migrations, models\n'), ((11299, 11426), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)', 'help_text': '"""Date time on which the object was created."""', 'verbose_name': '"""created at"""'}), "(auto_now_add=True, help_text=\n 'Date time on which the object was created.', verbose_name='created at')\n", (11319, 11426), False, 'from django.db import migrations, models\n'), ((11453, 11588), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now': '(True)', 'help_text': '"""Date time on which the object was last modified."""', 'verbose_name': '"""modified at"""'}), "(auto_now=True, help_text=\n 'Date time on which the object was last modified.', verbose_name=\n 'modified at')\n", (11473, 11588), False, 'from django.db import migrations, models\n'), ((11611, 11654), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(300)', 'null': '(True)'}), '(max_length=300, null=True)\n', (11627, 11654), False, 'from django.db import migrations, models\n'), ((11687, 11731), 'django.db.models.TextField', 'models.TextField', ([], {'blank': '(True)', 'max_length': '(500)'}), '(blank=True, max_length=500)\n', (11703, 11731), False, 'from django.db import migrations, models\n'), ((11764, 11820), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(True)', 'verbose_name': '"""active"""'}), "(default=True, verbose_name='active')\n", (11783, 11820), False, 'from django.db import migrations, models\n'), ((11854, 11884), 'django.db.models.FloatField', 'models.FloatField', ([], {'default': '(5.0)'}), '(default=5.0)\n', (11871, 11884), False, 'from django.db import migrations, models\n'), ((11912, 12034), 'django.db.models.OneToOneField', 'models.OneToOneField', ([], {'on_delete': 'django.db.models.deletion.CASCADE', 'related_name': '"""profile"""', 'to': 'settings.AUTH_USER_MODEL'}), "(on_delete=django.db.models.deletion.CASCADE,\n related_name='profile', to=settings.AUTH_USER_MODEL)\n", (11932, 12034), False, 'from django.db import migrations, models\n'), ((12571, 12664), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (12587, 12664), False, 'from django.db import migrations, models\n'), ((12688, 12783), 'django.db.models.CharField', 'models.CharField', ([], {'default': 'sunnysouth.lib.models.generate_uuid', 'max_length': '(300)', 'unique': '(True)'}), '(default=sunnysouth.lib.models.generate_uuid, max_length=\n 300, unique=True)\n', (12704, 12783), False, 'from django.db import migrations, models\n'), ((12809, 12936), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)', 'help_text': '"""Date time on which the object was created."""', 'verbose_name': '"""created at"""'}), "(auto_now_add=True, help_text=\n 'Date time on which the object was created.', verbose_name='created at')\n", (12829, 12936), False, 'from django.db import migrations, models\n'), ((12963, 13098), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now': '(True)', 'help_text': '"""Date time on which the object was last modified."""', 'verbose_name': '"""modified at"""'}), "(auto_now=True, help_text=\n 'Date time on which the object was last modified.', verbose_name=\n 'modified at')\n", (12983, 13098), False, 'from django.db import migrations, models\n'), ((13116, 13148), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(300)'}), '(max_length=300)\n', (13132, 13148), False, 'from django.db import migrations, models\n'), ((13176, 13208), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(300)'}), '(max_length=300)\n', (13192, 13208), False, 'from django.db import migrations, models\n'), ((13237, 13269), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(300)'}), '(max_length=300)\n', (13253, 13269), False, 'from django.db import migrations, models\n'), ((13300, 13332), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(300)'}), '(max_length=300)\n', (13316, 13332), False, 'from django.db import migrations, models\n'), ((13364, 13396), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)'}), '(max_length=100)\n', (13380, 13396), False, 'from django.db import migrations, models\n'), ((13429, 13461), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)'}), '(max_length=100)\n', (13445, 13461), False, 'from django.db import migrations, models\n'), ((13494, 13526), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(300)'}), '(max_length=300)\n', (13510, 13526), False, 'from django.db import migrations, models\n'), ((13564, 13596), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(500)'}), '(max_length=500)\n', (13580, 13596), False, 'from django.db import migrations, models\n'), ((13630, 13688), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)', 'verbose_name': '"""primary"""'}), "(default=False, verbose_name='primary')\n", (13649, 13688), False, 'from django.db import migrations, models\n'), ((13733, 13754), 'django.db.models.IntegerField', 'models.IntegerField', ([], {}), '()\n', (13752, 13754), False, 'from django.db import migrations, models\n'), ((13802, 13900), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.PROTECT', 'to': '"""contenttypes.contenttype"""'}), "(on_delete=django.db.models.deletion.PROTECT, to=\n 'contenttypes.contenttype')\n", (13819, 13900), False, 'from django.db import migrations, models\n')] |
from django.db import models
from django.utils import timezone
from pymongo import MongoClient
from django.core.validators import MaxValueValidator, MinValueValidator
from decimal import Decimal
client = MongoClient()
db = client.test # base de datos
restaurantes = db.restaurants # colección
class Plato(models.Model):
ITALIANA = 'italiana'
VEGETARIANA = 'vegetariana'
ESPANOA = 'Española'
TIPOS_COCINAS = (
(ITALIANA, 'italiana'),
(VEGETARIANA, 'vegetariana'),
(ESPANOA, 'Española'),
)
ALERGENOS = (())
nombre = models.TextField(max_length = 200, blank = False)
precio = models.DecimalField(max_digits = 5,decimal_places=2, validators=[MinValueValidator(Decimal('0.00'))], blank = False)
tiposCocinas = models.CharField(choices=TIPOS_COCINAS, default=ESPANOA,max_length=100)
alergenos = models.CharField(choices=ALERGENOS, default=ESPANOA,max_length=100)
descripcion = models.TextField(max_length = 500)
def insertar(self):
self.precio = 0
self.save()
def eliminar(self):
self.precio = 0
def modificar(self):
self.precio = 0
def __str__(self):
return self.nombre
from django.db import models
| [
"pymongo.MongoClient",
"django.db.models.TextField",
"decimal.Decimal",
"django.db.models.CharField"
] | [((205, 218), 'pymongo.MongoClient', 'MongoClient', ([], {}), '()\n', (216, 218), False, 'from pymongo import MongoClient\n'), ((590, 635), 'django.db.models.TextField', 'models.TextField', ([], {'max_length': '(200)', 'blank': '(False)'}), '(max_length=200, blank=False)\n', (606, 635), False, 'from django.db import models\n'), ((790, 862), 'django.db.models.CharField', 'models.CharField', ([], {'choices': 'TIPOS_COCINAS', 'default': 'ESPANOA', 'max_length': '(100)'}), '(choices=TIPOS_COCINAS, default=ESPANOA, max_length=100)\n', (806, 862), False, 'from django.db import models\n'), ((878, 946), 'django.db.models.CharField', 'models.CharField', ([], {'choices': 'ALERGENOS', 'default': 'ESPANOA', 'max_length': '(100)'}), '(choices=ALERGENOS, default=ESPANOA, max_length=100)\n', (894, 946), False, 'from django.db import models\n'), ((964, 996), 'django.db.models.TextField', 'models.TextField', ([], {'max_length': '(500)'}), '(max_length=500)\n', (980, 996), False, 'from django.db import models\n'), ((737, 752), 'decimal.Decimal', 'Decimal', (['"""0.00"""'], {}), "('0.00')\n", (744, 752), False, 'from decimal import Decimal\n')] |
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='192.168.13.201'))
channel = connection.channel()
channel.exchange_declare(exchange='logs',
exchange_type='fanout')
result = channel.queue_declare(exclusive=True, queue='')
queue_name = result.method.queue
channel.queue_bind(exchange='logs',
queue=queue_name)
print('[*] Waiting for logs. To exit press CTRL+C')
def callback(ch, method, properties, body):
print("[x] %r" % body)
channel.basic_consume(on_message_callback=callback,
queue=queue_name)
channel.start_consuming()
| [
"pika.ConnectionParameters"
] | [((50, 98), 'pika.ConnectionParameters', 'pika.ConnectionParameters', ([], {'host': '"""192.168.13.201"""'}), "(host='192.168.13.201')\n", (75, 98), False, 'import pika\n')] |
#!/usr/bin/env python3
# _*_ coding:utf-8 _*_
# author:CT
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from torch.utils.data import Dataset, DataLoader
class MNIST(nn.Module):
"""
main block
"""
def __init__(self):
super().__init__()
self.layer1 = nn.Sequential(nn.Conv2d(1, 32, kernel_size=5, padding=2),
nn.BatchNorm2d(32),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2))
self.init_weight(self.layer1[0])
self.layer2 = nn.Sequential(nn.Conv2d(32, 64, kernel_size=5, padding=2),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2))
self.init_weight(self.layer2[0])
self.layer3 = nn.Sequential(nn.Linear(7*7*64, 1024),
nn.ReLU())
self.init_weight(self.layer3[0])
self.layer4 = nn.Sequential(nn.Linear(1024, 10),
# nn.Dropout(p=0.2),
nn.Softmax())
def __len__(self):
return len(self.layer1)+len(self.layer2)+len(self.layer3)+len(self.layer4)
def init_weight(self, layer):
init.kaiming_normal_(layer.weight)
init.constant_(layer.bias, 0.01)
def view_feature(self, input):
out1 = self.layer1(input)
out2 = self.layer2(out1)
return out1[0, 0], out2[0, 0]
def forward(self, input):
out1 = self.layer1(input)
out2 = self.layer2(out1)
out3 = out2.view(out2.size(0), -1)
out4 = self.layer3(out3)
out5 = self.layer4(out4)
return out5
if __name__ == '__main__':
model = MNIST()
data = torch.randn(3, 1, 28, 28)
out = model(data)
print(out.sum(1))
print(model)
print(model.view_feature(data))
print(len(model))
| [
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"torch.nn.init.constant_",
"torch.nn.Softmax",
"torch.nn.init.kaiming_normal_",
"torch.nn.Conv2d",
"torch.nn.MaxPool2d",
"torch.nn.Linear",
"torch.randn"
] | [((1880, 1905), 'torch.randn', 'torch.randn', (['(3)', '(1)', '(28)', '(28)'], {}), '(3, 1, 28, 28)\n', (1891, 1905), False, 'import torch\n'), ((1375, 1409), 'torch.nn.init.kaiming_normal_', 'init.kaiming_normal_', (['layer.weight'], {}), '(layer.weight)\n', (1395, 1409), True, 'import torch.nn.init as init\n'), ((1418, 1450), 'torch.nn.init.constant_', 'init.constant_', (['layer.bias', '(0.01)'], {}), '(layer.bias, 0.01)\n', (1432, 1450), True, 'import torch.nn.init as init\n'), ((349, 391), 'torch.nn.Conv2d', 'nn.Conv2d', (['(1)', '(32)'], {'kernel_size': '(5)', 'padding': '(2)'}), '(1, 32, kernel_size=5, padding=2)\n', (358, 391), True, 'import torch.nn as nn\n'), ((429, 447), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['(32)'], {}), '(32)\n', (443, 447), True, 'import torch.nn as nn\n'), ((485, 494), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (492, 494), True, 'import torch.nn as nn\n'), ((532, 569), 'torch.nn.MaxPool2d', 'nn.MaxPool2d', ([], {'kernel_size': '(2)', 'stride': '(2)'}), '(kernel_size=2, stride=2)\n', (544, 569), True, 'import torch.nn as nn\n'), ((648, 691), 'torch.nn.Conv2d', 'nn.Conv2d', (['(32)', '(64)'], {'kernel_size': '(5)', 'padding': '(2)'}), '(32, 64, kernel_size=5, padding=2)\n', (657, 691), True, 'import torch.nn as nn\n'), ((729, 747), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['(64)'], {}), '(64)\n', (743, 747), True, 'import torch.nn as nn\n'), ((785, 794), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (792, 794), True, 'import torch.nn as nn\n'), ((832, 869), 'torch.nn.MaxPool2d', 'nn.MaxPool2d', ([], {'kernel_size': '(2)', 'stride': '(2)'}), '(kernel_size=2, stride=2)\n', (844, 869), True, 'import torch.nn as nn\n'), ((948, 975), 'torch.nn.Linear', 'nn.Linear', (['(7 * 7 * 64)', '(1024)'], {}), '(7 * 7 * 64, 1024)\n', (957, 975), True, 'import torch.nn as nn\n'), ((1009, 1018), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (1016, 1018), True, 'import torch.nn as nn\n'), ((1097, 1116), 'torch.nn.Linear', 'nn.Linear', (['(1024)', '(10)'], {}), '(1024, 10)\n', (1106, 1116), True, 'import torch.nn as nn\n'), ((1211, 1223), 'torch.nn.Softmax', 'nn.Softmax', ([], {}), '()\n', (1221, 1223), True, 'import torch.nn as nn\n')] |
#!/usr/bin/env python3
#return classes the student is enrolled in,
#return the current assignments for each of those classes
import StudentData
import CourseData
class WebData:
def __init__(self, studentID):
self._studentID=studentID
self._student_data=StudentData.StudentData()
self._course_data=CourseData.CourseData()
def getCurrentAssignmentData(self):
_data={}
_courses=self._student_data.getCourses(self._studentID)
for _coursename in _courses:
_data[_coursename]=self._course_data.getCurrentCourseAssignments(_coursename)
return _data
if __name__ == '__main__':
_wd=WebData('154317')
print(_wd.getCurrentAssignmentData())
| [
"StudentData.StudentData",
"CourseData.CourseData"
] | [((271, 296), 'StudentData.StudentData', 'StudentData.StudentData', ([], {}), '()\n', (294, 296), False, 'import StudentData\n'), ((321, 344), 'CourseData.CourseData', 'CourseData.CourseData', ([], {}), '()\n', (342, 344), False, 'import CourseData\n')] |
# encoding: utf-8
import logging
log = logging.getLogger(__name__)
def metadata_standard_show(context, data_dict):
return {'success': True}
def metadata_schema_show(context, data_dict):
return {'success': True}
def infrastructure_show(context, data_dict):
return {'success': True}
def metadata_collection_show(context, data_dict):
return {'success': True}
def metadata_record_show(context, data_dict):
return {'success': True}
def metadata_standard_list(context, data_dict):
return {'success': True}
def metadata_schema_list(context, data_dict):
return {'success': True}
def metadata_schema_dependent_record_list(context, data_dict):
return {'success': True}
def infrastructure_list(context, data_dict):
return {'success': True}
def metadata_collection_list(context, data_dict):
return {'success': True}
def metadata_record_list(context, data_dict):
return {'success': True}
def metadata_record_validation_schema_list(context, data_dict):
return {'success': True}
def metadata_record_validation_activity_show(context, data_dict):
return {'success': True}
def metadata_validity_check(context, data_dict):
return {'success': True}
def metadata_record_workflow_rules_check(context, data_dict):
return {'success': True}
def metadata_record_workflow_activity_show(context, data_dict):
return {'success': True}
def metadata_record_workflow_annotation_show(context, data_dict):
return {'success': True}
def metadata_record_workflow_annotation_list(context, data_dict):
return {'success': True}
def metadata_record_workflow_augmented_show(context, data_dict):
return {'success': True}
def workflow_state_show(context, data_dict):
return {'success': True}
def workflow_state_list(context, data_dict):
return {'success': True}
def workflow_transition_show(context, data_dict):
return {'success': True}
def workflow_transition_list(context, data_dict):
return {'success': True}
def workflow_annotation_show(context, data_dict):
return {'success': True}
def workflow_annotation_list(context, data_dict):
return {'success': True}
def metadata_json_attr_map_show(context, data_dict):
return {'success': True}
def metadata_json_attr_map_list(context, data_dict):
return {'success': True}
def metadata_json_attr_map_apply(context, data_dict):
return {'success': True}
def metadata_record_attr_match(context, data_dict):
return {'success': True}
def metadata_record_exact_match(context, data_dict):
return {'success': True}
def metadata_standard_index_show(context, data_dict):
return {'success': True}
def metadata_record_index_show(context, data_dict):
return {'success': True}
| [
"logging.getLogger"
] | [((41, 68), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (58, 68), False, 'import logging\n')] |
from django.shortcuts import render, redirect
from django.http import HttpResponse
# Create your views here.
from .models import GuessNumbers
from .forms import PostForm
def index(request):
lottos = GuessNumbers.objects.all()
return render(request, "lotto/default.html", {"lottos": lottos})
def post(request):
if request.method == "POST":
# save data
form = PostForm(request.POST)
if form.is_valid():
lotto = form.save(commit = False)
lotto.generate()
return redirect('lotto:index')
else:
form = PostForm()
return render(request, 'lotto/form.html', {"form": form})
def detail(request, lottokey):
lotto = GuessNumbers.objects.get(pk = lottokey)
return render(request, "lotto/detail.html", {"lotto": lotto})
| [
"django.shortcuts.render",
"django.shortcuts.redirect"
] | [((243, 300), 'django.shortcuts.render', 'render', (['request', '"""lotto/default.html"""', "{'lottos': lottos}"], {}), "(request, 'lotto/default.html', {'lottos': lottos})\n", (249, 300), False, 'from django.shortcuts import render, redirect\n'), ((755, 809), 'django.shortcuts.render', 'render', (['request', '"""lotto/detail.html"""', "{'lotto': lotto}"], {}), "(request, 'lotto/detail.html', {'lotto': lotto})\n", (761, 809), False, 'from django.shortcuts import render, redirect\n'), ((609, 659), 'django.shortcuts.render', 'render', (['request', '"""lotto/form.html"""', "{'form': form}"], {}), "(request, 'lotto/form.html', {'form': form})\n", (615, 659), False, 'from django.shortcuts import render, redirect\n'), ((534, 557), 'django.shortcuts.redirect', 'redirect', (['"""lotto:index"""'], {}), "('lotto:index')\n", (542, 557), False, 'from django.shortcuts import render, redirect\n')] |
import os
import shutil
import ntpath
import csv
import itertools as IT
def check_if_directory_exists(dir_path):
return os.path.isdir(dir_path)
def check_if_file_exists(file_path):
return os.path.isfile(file_path)
def make_directory(directory_path):
is_successful = True
try:
os.mkdir(directory_path)
except OSError:
is_successful = False
return is_successful
def delete_directory(directory_path):
is_successful = True
try:
shutil.rmtree(directory_path)
except OSError:
is_successful = False
return is_successful
def get_list_of_subdirectory_paths(root_dir):
paths = []
if check_if_directory_exists(root_dir):
for subdir_path in os.scandir(root_dir):
#subdir_path = subdir_path.name
#subdir_path = subdir_path.replace("\\", "/")
paths.append(subdir_path)
return paths
def get_list_of_file_paths_in_directory(root_dir):
paths = [os.path.join(root_dir, f) for f in os.listdir(root_dir) if check_if_file_exists(os.path.join(root_dir, f))]
return paths
def get_name_from_path(path):
head, tail = ntpath.split(path)
return tail or ntpath.basename(head)
def get_file_name_without_extension(file_name):
return os.path.splitext(file_name)[0]
def merge_multiple_csv_files(filepaths, filelabels, destination_filepath):
dest_rows = []
for i in range(len(filepaths)):
filepath = filepaths[i]
file_label = filelabels[i]
with open(filepath) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
src_csv_rows = [["", "", file_label , ""]]
for row in csv_reader:
src_csv_rows.append(row)
if len(dest_rows) == 0:
dest_rows = src_csv_rows
else:
for index in range(len(dest_rows)):
dest_rows[index].extend(src_csv_rows[index][1:])
with open(destination_filepath, 'w', newline='') as dest_csv_path:
dest_csv_writer = csv.writer(dest_csv_path, delimiter=',')
for row in dest_rows:
dest_csv_writer.writerow(row)
| [
"ntpath.basename",
"os.listdir",
"os.scandir",
"os.path.join",
"os.path.splitext",
"csv.writer",
"os.path.isfile",
"os.path.isdir",
"os.mkdir",
"shutil.rmtree",
"csv.reader",
"ntpath.split"
] | [((125, 148), 'os.path.isdir', 'os.path.isdir', (['dir_path'], {}), '(dir_path)\n', (138, 148), False, 'import os\n'), ((199, 224), 'os.path.isfile', 'os.path.isfile', (['file_path'], {}), '(file_path)\n', (213, 224), False, 'import os\n'), ((1148, 1166), 'ntpath.split', 'ntpath.split', (['path'], {}), '(path)\n', (1160, 1166), False, 'import ntpath\n'), ((305, 329), 'os.mkdir', 'os.mkdir', (['directory_path'], {}), '(directory_path)\n', (313, 329), False, 'import os\n'), ((488, 517), 'shutil.rmtree', 'shutil.rmtree', (['directory_path'], {}), '(directory_path)\n', (501, 517), False, 'import shutil\n'), ((728, 748), 'os.scandir', 'os.scandir', (['root_dir'], {}), '(root_dir)\n', (738, 748), False, 'import os\n'), ((974, 999), 'os.path.join', 'os.path.join', (['root_dir', 'f'], {}), '(root_dir, f)\n', (986, 999), False, 'import os\n'), ((1186, 1207), 'ntpath.basename', 'ntpath.basename', (['head'], {}), '(head)\n', (1201, 1207), False, 'import ntpath\n'), ((1269, 1296), 'os.path.splitext', 'os.path.splitext', (['file_name'], {}), '(file_name)\n', (1285, 1296), False, 'import os\n'), ((2047, 2087), 'csv.writer', 'csv.writer', (['dest_csv_path'], {'delimiter': '""","""'}), "(dest_csv_path, delimiter=',')\n", (2057, 2087), False, 'import csv\n'), ((1009, 1029), 'os.listdir', 'os.listdir', (['root_dir'], {}), '(root_dir)\n', (1019, 1029), False, 'import os\n'), ((1565, 1600), 'csv.reader', 'csv.reader', (['csv_file'], {'delimiter': '""","""'}), "(csv_file, delimiter=',')\n", (1575, 1600), False, 'import csv\n'), ((1054, 1079), 'os.path.join', 'os.path.join', (['root_dir', 'f'], {}), '(root_dir, f)\n', (1066, 1079), False, 'import os\n')] |
from app import Application
if __name__ == '__main__':
Application.run()
| [
"app.Application.run"
] | [((62, 79), 'app.Application.run', 'Application.run', ([], {}), '()\n', (77, 79), False, 'from app import Application\n')] |
"""Generate constants files from the Unicorn headers.
This is heavily borrowed from the script in the Unicorn source repo, except modified to
work with an installed library rather than from the source code. The headers must be
present, but that's all that's required.
"""
import ast
import collections
import datetime
import logging
import os
import re
import sys
GENERATED_FILE_TEMPLATE = """\
/** Autogenerated from installed Unicorn header files. DO NOT EDIT.
*
* Source: {header_file}
* Generated: {now:%Y-%m-%d %I:%M %p}
*
* @file {slug}_const.cpp
*/
#include <unicorn/unicorn.h>
#include "unicornlua/lua.h"
#include "unicornlua/utils.h"
static const struct NamedIntConst kConstants[] {{
{values},
{{nullptr, 0}}
}};
extern "C" UNICORN_EXPORT int luaopen_unicorn_{slug}_const(lua_State *L) {{
lua_createtable(L, 0, {n_values});
load_int_constants(L, kConstants);
return 1;
}}
"""
def clean_line(line):
"""Strip whitespace off a line and separate out the comment, if any."""
if "//" in line:
line, _sep, comment = line.partition("//")
if "/*" in line:
line, _sep, comment = line.partition("/*")
comment, _sep, _trash = comment.partition("*/")
else:
comment = ""
return line.strip(), comment.strip()
def parse_header_file(header_file):
"""Parse a single header file to get all defined constants out of it."""
resolved_values = collections.OrderedDict()
raw_matches = {}
with open(header_file, "r") as fd:
all_file_lines = collections.OrderedDict(
[
(lineno, line.strip())
for lineno, line in enumerate(fd, start=1)
if not line.isspace()
]
)
line_iterator = iter(all_file_lines.items())
for lineno, line in line_iterator:
line, _comment = clean_line(line)
# First check to see if this is a #define statement
match = re.match(r"^#define\s+UC_(?P<id>\w+)\s+(?P<value>.*)$", line)
if match:
name = "UC_" + match.group("id")
raw_value = match.group("value")
try:
resolved_values[name] = ast.literal_eval(raw_value)
except (NameError, SyntaxError, ValueError):
raw_matches[name] = raw_value
continue
# Not a #define; see if it's an enum.
if "enum uc_" not in line.lower():
continue
# This is the beginning of an enum. Subsequent lines until the closing `}` are
# part of it. We need to keep track because enums without an explicitly defined
# value are incremented by one from the previous enum value.
next_enum_value = 0
enum_start_line = lineno
while True:
lineno, line = next(line_iterator, (None, None))
if line is None:
# Hit EOF before we hit the end of the enum. That's odd.
logging.warning(
"Hit EOF before end of enum beginning on line %d.", enum_start_line
)
break
elif "}" in line:
# Hit the end of the enum.
break
line, _comment = clean_line(line)
# Sometimes we have multiple enum definitions on one line. We need to handle
# these one at a time. Splitting the line by commas should be enough to
# separate out multiple expressions.
for expression in line.strip(",").split(","):
expression = expression.strip()
if not expression:
continue
# See if this enum value is being assigned rather than implicit.
match = re.match(r"^UC_(?P<id>\w+)\s*=\s*(?P<expr>.+)$", expression)
if match:
# Enum value is assigned. Whatever's on the right-hand side, any
# names it references must already be defined.
name = "UC_" + match.group("id")
raw_value = match.group("expr")
try:
processed_value = eval(raw_value, resolved_values)
except NameError as nerr:
logging.error(
"Failed to resolve %r on line %d: %s", name, lineno, nerr
)
continue
resolved_values[name] = processed_value
next_enum_value = processed_value + 1
else:
# Not an explicit assignment. Expect this expression to be just a
# single identifier.
match = re.match(r"^UC_(\w+)$", expression)
if match:
name = match.group(1)
resolved_values["UC_" + name] = next_enum_value
next_enum_value += 1
else:
raise SyntaxError(
"Couldn't match any expression type to: %r" % expression
)
for name, raw_value in raw_matches.items():
# Convert any remaining values that are still unresolved. This usually only
# applies to #define macros that reference other constants.
if name not in resolved_values:
resolved_values[name] = eval(raw_value, resolved_values)
return resolved_values
def generate_constants_for_file(header_file, output_file):
"""Generate a constants file from a Unicorn header.
Arguments:
header_file (str):
The path to the source file header where the constants are defined. Ideally
this is an absolute path.
output_file (str):
The path to the Lua file to create that'll contain these defined constants.
"""
header_file = os.path.abspath(header_file)
logging.info("Processing file: %s", header_file)
all_value_pairs = parse_header_file(header_file)
if not all_value_pairs:
logging.error("No constants found in header, refusing to write to output file.")
return
with open(output_file, "w") as out_fd:
out_fd.write(
GENERATED_FILE_TEMPLATE.format(
header_file=header_file,
now=datetime.datetime.now(),
n_values=len(all_value_pairs),
slug=os.path.splitext(os.path.basename(header_file))[0].lower(),
values=",\n".join(
' {"%s", %s}' % kv for kv in sorted(all_value_pairs.items())
),
)
)
logging.info("Finished. Found %d constant(s) in file.", len(all_value_pairs))
def main():
logging.basicConfig(level=logging.INFO, format="[%(levelname)-5s] %(message)s")
if len(sys.argv) != 3:
logging.error(
"Script takes two arguments, the path to a header file and the path to the"
" C++ file to generate."
)
return sys.exit(1)
logging.info("Generating `%s`...", sys.argv[2])
generate_constants_for_file(os.path.abspath(sys.argv[1]), sys.argv[2])
return sys.exit(0)
if __name__ == "__main__":
main()
| [
"logging.basicConfig",
"collections.OrderedDict",
"re.match",
"logging.warning",
"ast.literal_eval",
"datetime.datetime.now",
"os.path.basename",
"sys.exit",
"os.path.abspath",
"logging.info",
"logging.error"
] | [((1425, 1450), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (1448, 1450), False, 'import collections\n'), ((5869, 5897), 'os.path.abspath', 'os.path.abspath', (['header_file'], {}), '(header_file)\n', (5884, 5897), False, 'import os\n'), ((5902, 5950), 'logging.info', 'logging.info', (['"""Processing file: %s"""', 'header_file'], {}), "('Processing file: %s', header_file)\n", (5914, 5950), False, 'import logging\n'), ((6724, 6803), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'format': '"""[%(levelname)-5s] %(message)s"""'}), "(level=logging.INFO, format='[%(levelname)-5s] %(message)s')\n", (6743, 6803), False, 'import logging\n'), ((7021, 7068), 'logging.info', 'logging.info', (['"""Generating `%s`..."""', 'sys.argv[2]'], {}), "('Generating `%s`...', sys.argv[2])\n", (7033, 7068), False, 'import logging\n'), ((7155, 7166), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (7163, 7166), False, 'import sys\n'), ((1945, 2008), 're.match', 're.match', (['"""^#define\\\\s+UC_(?P<id>\\\\w+)\\\\s+(?P<value>.*)$"""', 'line'], {}), "('^#define\\\\s+UC_(?P<id>\\\\w+)\\\\s+(?P<value>.*)$', line)\n", (1953, 2008), False, 'import re\n'), ((6041, 6126), 'logging.error', 'logging.error', (['"""No constants found in header, refusing to write to output file."""'], {}), "('No constants found in header, refusing to write to output file.'\n )\n", (6054, 6126), False, 'import logging\n'), ((6839, 6961), 'logging.error', 'logging.error', (['"""Script takes two arguments, the path to a header file and the path to the C++ file to generate."""'], {}), "(\n 'Script takes two arguments, the path to a header file and the path to the C++ file to generate.'\n )\n", (6852, 6961), False, 'import logging\n'), ((7004, 7015), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (7012, 7015), False, 'import sys\n'), ((7101, 7129), 'os.path.abspath', 'os.path.abspath', (['sys.argv[1]'], {}), '(sys.argv[1])\n', (7116, 7129), False, 'import os\n'), ((2172, 2199), 'ast.literal_eval', 'ast.literal_eval', (['raw_value'], {}), '(raw_value)\n', (2188, 2199), False, 'import ast\n'), ((2940, 3028), 'logging.warning', 'logging.warning', (['"""Hit EOF before end of enum beginning on line %d."""', 'enum_start_line'], {}), "('Hit EOF before end of enum beginning on line %d.',\n enum_start_line)\n", (2955, 3028), False, 'import logging\n'), ((3726, 3788), 're.match', 're.match', (['"""^UC_(?P<id>\\\\w+)\\\\s*=\\\\s*(?P<expr>.+)$"""', 'expression'], {}), "('^UC_(?P<id>\\\\w+)\\\\s*=\\\\s*(?P<expr>.+)$', expression)\n", (3734, 3788), False, 'import re\n'), ((4695, 4730), 're.match', 're.match', (['"""^UC_(\\\\w+)$"""', 'expression'], {}), "('^UC_(\\\\w+)$', expression)\n", (4703, 4730), False, 'import re\n'), ((6308, 6331), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (6329, 6331), False, 'import datetime\n'), ((4240, 4312), 'logging.error', 'logging.error', (['"""Failed to resolve %r on line %d: %s"""', 'name', 'lineno', 'nerr'], {}), "('Failed to resolve %r on line %d: %s', name, lineno, nerr)\n", (4253, 4312), False, 'import logging\n'), ((6418, 6447), 'os.path.basename', 'os.path.basename', (['header_file'], {}), '(header_file)\n', (6434, 6447), False, 'import os\n')] |
import secrets
import os
# Values in this file are loaded into the flask app instance, `demo.APP` in this
# demo. This file sources values from the environment if they exist, otherwise a
# set of defaults are used. This is useful for keeping secrets secret, as well
# as facilitating configuration in a container. Defaults may be overriden either
# by defining the environment variables, or by creating a `config.py` file that
# contains locally set secrets or config values.
# Defaults for flask configuration
IP = os.environ.get('IP', default='127.0.0.1')
PORT = os.environ.get('PORT', default=5000)
SERVER_NAME = os.environ.get('SERVER_NAME', default='localhost:5000')
SECRET_KEY = os.environ.get('SESSION_KEY', default=''.join(secrets.token_hex(16)))
# OAuth2 settings
GOOGLE_CLIENT_ID = os.environ.get('GOOGLE_CLIENT_ID', default='')
GOOGLE_CLIENT_SECRET = os.environ.get('GOOGLE_CLIENT_SECRET', default='')
| [
"secrets.token_hex",
"os.environ.get"
] | [((519, 560), 'os.environ.get', 'os.environ.get', (['"""IP"""'], {'default': '"""127.0.0.1"""'}), "('IP', default='127.0.0.1')\n", (533, 560), False, 'import os\n'), ((568, 604), 'os.environ.get', 'os.environ.get', (['"""PORT"""'], {'default': '(5000)'}), "('PORT', default=5000)\n", (582, 604), False, 'import os\n'), ((619, 674), 'os.environ.get', 'os.environ.get', (['"""SERVER_NAME"""'], {'default': '"""localhost:5000"""'}), "('SERVER_NAME', default='localhost:5000')\n", (633, 674), False, 'import os\n'), ((796, 842), 'os.environ.get', 'os.environ.get', (['"""GOOGLE_CLIENT_ID"""'], {'default': '""""""'}), "('GOOGLE_CLIENT_ID', default='')\n", (810, 842), False, 'import os\n'), ((866, 916), 'os.environ.get', 'os.environ.get', (['"""GOOGLE_CLIENT_SECRET"""'], {'default': '""""""'}), "('GOOGLE_CLIENT_SECRET', default='')\n", (880, 916), False, 'import os\n'), ((734, 755), 'secrets.token_hex', 'secrets.token_hex', (['(16)'], {}), '(16)\n', (751, 755), False, 'import secrets\n')] |
#!/usr/bin/env python3
# Copyright (c) 2014-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test logic for skipping signature validation on old blocks.
Test logic for skipping signature validation on blocks which we've assumed
valid (https://github.com/bitcoin/bitcoin/pull/9484)
We build a chain that includes and invalid signature for one of the
transactions:
0: genesis block
1: block 1 with coinbase transaction output.
2-101: bury that block with 100 blocks so the coinbase transaction
output can be spent
102: a block containing a transaction spending the coinbase
transaction output. The transaction has an invalid signature.
103-2202: bury the bad block with just over two weeks' worth of blocks
(2100 blocks)
Start three nodes:
- node0 has no -assumevalid parameter. Try to sync to block 2202. It will
reject block 102 and only sync as far as block 101
- node1 has -assumevalid set to the hash of block 102. Try to sync to
block 2202. node1 will sync all the way to block 2202.
- node2 has -assumevalid set to the hash of block 102. Try to sync to
block 200. node2 will reject block 102 since it's assumed valid, but it
isn't buried by at least two weeks' work.
"""
import time
from test_framework.blocktools import (create_block, create_coinbase)
from test_framework.key import CECKey
from test_framework.mininode import (CBlockHeader,
COutPoint,
CTransaction,
CTxIn,
CTxOut,
network_thread_join,
network_thread_start,
P2PInterface,
msg_block,
msg_headers)
from test_framework.script import (CScript, OP_TRUE)
from test_framework.test_framework import SafeCashTestFramework
from test_framework.util import assert_equal
class BaseNode(P2PInterface):
def send_header_for_blocks(self, new_blocks):
headers_message = msg_headers()
headers_message.headers = [CBlockHeader(b) for b in new_blocks]
self.send_message(headers_message)
class AssumeValidTest(SafeCashTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 3
def setup_network(self):
self.add_nodes(3)
# Start node0. We don't start the other nodes yet since
# we need to pre-mine a block with an invalid transaction
# signature so we can pass in the block hash as assumevalid.
self.start_node(0)
def send_blocks_until_disconnected(self, p2p_conn):
"""Keep sending blocks to the node until we're disconnected."""
for i in range(len(self.blocks)):
if p2p_conn.state != "connected":
break
try:
p2p_conn.send_message(msg_block(self.blocks[i]))
except IOError as e:
assert str(e) == 'Not connected, no pushbuf'
break
def assert_blockchain_height(self, node, height):
"""Wait until the blockchain is no longer advancing and verify it's reached the expected height."""
last_height = node.getblock(node.getbestblockhash())['height']
timeout = 10
while True:
time.sleep(0.25)
current_height = node.getblock(node.getbestblockhash())['height']
if current_height != last_height:
last_height = current_height
if timeout < 0:
assert False, "blockchain too short after timeout: %d" % current_height
timeout - 0.25
continue
elif current_height > height:
assert False, "blockchain too long: %d" % current_height
elif current_height == height:
break
def run_test(self):
# Connect to node0
p2p0 = self.nodes[0].add_p2p_connection(BaseNode())
network_thread_start()
self.nodes[0].p2p.wait_for_verack()
# Build the blockchain
self.tip = int(self.nodes[0].getbestblockhash(), 16)
self.block_time = self.nodes[0].getblock(self.nodes[0].getbestblockhash())['time'] + 1
self.blocks = []
# Get a pubkey for the coinbase TXO
coinbase_key = CECKey()
coinbase_key.set_secretbytes(b"horsebattery")
coinbase_pubkey = coinbase_key.get_pubkey()
# Create the first block with a coinbase output to our key
height = 1
block = create_block(self.tip, create_coinbase(height, coinbase_pubkey), self.block_time)
self.blocks.append(block)
self.block_time += 1
block.solve()
# Save the coinbase for later
self.block1 = block
self.tip = block.sha256
height += 1
# Bury the block 100 deep so the coinbase output is spendable
for i in range(100):
block = create_block(self.tip, create_coinbase(height), self.block_time)
block.solve()
self.blocks.append(block)
self.tip = block.sha256
self.block_time += 1
height += 1
# Create a transaction spending the coinbase output with an invalid (null) signature
tx = CTransaction()
tx.vin.append(CTxIn(COutPoint(self.block1.vtx[0].sha256, 0), scriptSig=b""))
tx.vout.append(CTxOut(49 * 100000000, CScript([OP_TRUE])))
tx.calc_sha256()
block102 = create_block(self.tip, create_coinbase(height), self.block_time)
self.block_time += 1
block102.vtx.extend([tx])
block102.hashMerkleRoot = block102.calc_merkle_root()
block102.rehash()
block102.solve()
self.blocks.append(block102)
self.tip = block102.sha256
self.block_time += 1
height += 1
# Bury the assumed valid block 2100 deep
for i in range(2100):
block = create_block(self.tip, create_coinbase(height), self.block_time)
block.nVersion = 4
block.solve()
self.blocks.append(block)
self.tip = block.sha256
self.block_time += 1
height += 1
# We're adding new connections so terminate the network thread
self.nodes[0].disconnect_p2ps()
network_thread_join()
# Start node1 and node2 with assumevalid so they accept a block with a bad signature.
self.start_node(1, extra_args=["-assumevalid=" + hex(block102.sha256)])
self.start_node(2, extra_args=["-assumevalid=" + hex(block102.sha256)])
p2p0 = self.nodes[0].add_p2p_connection(BaseNode())
p2p1 = self.nodes[1].add_p2p_connection(BaseNode())
p2p2 = self.nodes[2].add_p2p_connection(BaseNode())
network_thread_start()
p2p0.wait_for_verack()
p2p1.wait_for_verack()
p2p2.wait_for_verack()
# send header lists to all three nodes
p2p0.send_header_for_blocks(self.blocks[0:2000])
p2p0.send_header_for_blocks(self.blocks[2000:])
p2p1.send_header_for_blocks(self.blocks[0:2000])
p2p1.send_header_for_blocks(self.blocks[2000:])
p2p2.send_header_for_blocks(self.blocks[0:200])
# Send blocks to node0. Block 102 will be rejected.
self.send_blocks_until_disconnected(p2p0)
self.assert_blockchain_height(self.nodes[0], 101)
# Send all blocks to node1. All blocks will be accepted.
for i in range(2202):
p2p1.send_message(msg_block(self.blocks[i]))
# Syncing 2200 blocks can take a while on slow systems. Give it plenty of time to sync.
p2p1.sync_with_ping(120)
assert_equal(self.nodes[1].getblock(self.nodes[1].getbestblockhash())['height'], 2202)
# Send blocks to node2. Block 102 will be rejected.
self.send_blocks_until_disconnected(p2p2)
self.assert_blockchain_height(self.nodes[2], 101)
if __name__ == '__main__':
AssumeValidTest().main()
| [
"test_framework.script.CScript",
"test_framework.mininode.network_thread_join",
"test_framework.mininode.CTransaction",
"test_framework.mininode.msg_block",
"test_framework.mininode.CBlockHeader",
"test_framework.mininode.msg_headers",
"time.sleep",
"test_framework.key.CECKey",
"test_framework.minin... | [((2320, 2333), 'test_framework.mininode.msg_headers', 'msg_headers', ([], {}), '()\n', (2331, 2333), False, 'from test_framework.mininode import CBlockHeader, COutPoint, CTransaction, CTxIn, CTxOut, network_thread_join, network_thread_start, P2PInterface, msg_block, msg_headers\n'), ((4266, 4288), 'test_framework.mininode.network_thread_start', 'network_thread_start', ([], {}), '()\n', (4286, 4288), False, 'from test_framework.mininode import CBlockHeader, COutPoint, CTransaction, CTxIn, CTxOut, network_thread_join, network_thread_start, P2PInterface, msg_block, msg_headers\n'), ((4615, 4623), 'test_framework.key.CECKey', 'CECKey', ([], {}), '()\n', (4621, 4623), False, 'from test_framework.key import CECKey\n'), ((5567, 5581), 'test_framework.mininode.CTransaction', 'CTransaction', ([], {}), '()\n', (5579, 5581), False, 'from test_framework.mininode import CBlockHeader, COutPoint, CTransaction, CTxIn, CTxOut, network_thread_join, network_thread_start, P2PInterface, msg_block, msg_headers\n'), ((6614, 6635), 'test_framework.mininode.network_thread_join', 'network_thread_join', ([], {}), '()\n', (6633, 6635), False, 'from test_framework.mininode import CBlockHeader, COutPoint, CTransaction, CTxIn, CTxOut, network_thread_join, network_thread_start, P2PInterface, msg_block, msg_headers\n'), ((7081, 7103), 'test_framework.mininode.network_thread_start', 'network_thread_start', ([], {}), '()\n', (7101, 7103), False, 'from test_framework.mininode import CBlockHeader, COutPoint, CTransaction, CTxIn, CTxOut, network_thread_join, network_thread_start, P2PInterface, msg_block, msg_headers\n'), ((2369, 2384), 'test_framework.mininode.CBlockHeader', 'CBlockHeader', (['b'], {}), '(b)\n', (2381, 2384), False, 'from test_framework.mininode import CBlockHeader, COutPoint, CTransaction, CTxIn, CTxOut, network_thread_join, network_thread_start, P2PInterface, msg_block, msg_headers\n'), ((3598, 3614), 'time.sleep', 'time.sleep', (['(0.25)'], {}), '(0.25)\n', (3608, 3614), False, 'import time\n'), ((4856, 4896), 'test_framework.blocktools.create_coinbase', 'create_coinbase', (['height', 'coinbase_pubkey'], {}), '(height, coinbase_pubkey)\n', (4871, 4896), False, 'from test_framework.blocktools import create_block, create_coinbase\n'), ((5802, 5825), 'test_framework.blocktools.create_coinbase', 'create_coinbase', (['height'], {}), '(height)\n', (5817, 5825), False, 'from test_framework.blocktools import create_block, create_coinbase\n'), ((5261, 5284), 'test_framework.blocktools.create_coinbase', 'create_coinbase', (['height'], {}), '(height)\n', (5276, 5284), False, 'from test_framework.blocktools import create_block, create_coinbase\n'), ((5610, 5649), 'test_framework.mininode.COutPoint', 'COutPoint', (['self.block1.vtx[0].sha256', '(0)'], {}), '(self.block1.vtx[0].sha256, 0)\n', (5619, 5649), False, 'from test_framework.mininode import CBlockHeader, COutPoint, CTransaction, CTxIn, CTxOut, network_thread_join, network_thread_start, P2PInterface, msg_block, msg_headers\n'), ((5713, 5731), 'test_framework.script.CScript', 'CScript', (['[OP_TRUE]'], {}), '([OP_TRUE])\n', (5720, 5731), False, 'from test_framework.script import CScript, OP_TRUE\n'), ((6264, 6287), 'test_framework.blocktools.create_coinbase', 'create_coinbase', (['height'], {}), '(height)\n', (6279, 6287), False, 'from test_framework.blocktools import create_block, create_coinbase\n'), ((7823, 7848), 'test_framework.mininode.msg_block', 'msg_block', (['self.blocks[i]'], {}), '(self.blocks[i])\n', (7832, 7848), False, 'from test_framework.mininode import CBlockHeader, COutPoint, CTransaction, CTxIn, CTxOut, network_thread_join, network_thread_start, P2PInterface, msg_block, msg_headers\n'), ((3168, 3193), 'test_framework.mininode.msg_block', 'msg_block', (['self.blocks[i]'], {}), '(self.blocks[i])\n', (3177, 3193), False, 'from test_framework.mininode import CBlockHeader, COutPoint, CTransaction, CTxIn, CTxOut, network_thread_join, network_thread_start, P2PInterface, msg_block, msg_headers\n')] |
# -*- coding: utf-8 -*-
import unittest
from nose.tools import raises
import torch
from kraken.lib import layers
class TestLayers(unittest.TestCase):
"""
Testing custom layer implementations.
"""
def setUp(self):
torch.set_grad_enabled(False)
def test_maxpool(self):
"""
Test maximum pooling layer.
"""
mp = layers.MaxPool((3, 3), (2, 2))
o = mp(torch.randn(1, 2, 32, 64))
self.assertEqual(o[0].shape, (1, 2, 15, 31))
def test_1d_dropout(self):
"""
Test 1d dropout layer.
"""
do = layers.Dropout(0.2, 1)
o = do(torch.randn(1, 2, 32, 64))
self.assertEqual(o[0].shape, (1, 2, 32, 64))
def test_2d_dropout(self):
"""
Test 2d dropout layer.
"""
do = layers.Dropout(0.2, 2)
o = do(torch.randn(1, 2, 32, 64))
self.assertEqual(o[0].shape, (1, 2, 32, 64))
def test_forward_rnn_layer_x(self):
"""
Test unidirectional RNN layer in x-dimension.
"""
rnn = layers.TransposedSummarizingRNN(10, 2, 'f', False, False)
o = rnn(torch.randn(1, 10, 32, 64))
self.assertEqual(o[0].shape, (1, 2, 32, 64))
def test_forward_rnn_layer_y(self):
"""
Test unidirectional RNN layer in y-dimension.
"""
rnn = layers.TransposedSummarizingRNN(10, 2, 'f', True, False)
o = rnn(torch.randn(1, 10, 32, 64))
self.assertEqual(o[0].shape, (1, 2, 32, 64))
def test_forward_rnn_layer_x_summarize(self):
"""
Test unidirectional summarizing RNN layer in x-dimension.
"""
rnn = layers.TransposedSummarizingRNN(10, 2, 'f', False, True)
o = rnn(torch.randn(1, 10, 32, 64))
self.assertEqual(o[0].shape, (1, 2, 32, 1))
def test_forward_rnn_layer_y_summarize(self):
"""
Test unidirectional summarizing RNN layer in y-dimension.
"""
rnn = layers.TransposedSummarizingRNN(10, 2, 'f', True, True)
o = rnn(torch.randn(1, 10, 32, 64))
self.assertEqual(o[0].shape, (1, 2, 1, 64))
def test_bidi_rnn_layer_x(self):
"""
Test bidirectional RNN layer in x-dimension.
"""
rnn = layers.TransposedSummarizingRNN(10, 2, 'b', False, False)
o = rnn(torch.randn(1, 10, 32, 64))
self.assertEqual(o[0].shape, (1, 4, 32, 64))
def test_bidi_rnn_layer_y(self):
"""
Test bidirectional RNN layer in y-dimension.
"""
rnn = layers.TransposedSummarizingRNN(10, 2, 'b', True, False)
o = rnn(torch.randn(1, 10, 32, 64))
self.assertEqual(o[0].shape, (1, 4, 32, 64))
def test_bidi_rnn_layer_x_summarize(self):
"""
Test bidirectional summarizing RNN layer in x-dimension.
"""
rnn = layers.TransposedSummarizingRNN(10, 2, 'b', False, True)
o = rnn(torch.randn(1, 10, 32, 64))
self.assertEqual(o[0].shape, (1, 4, 32, 1))
def test_bidi_rnn_layer_y_summarize(self):
"""
Test bidirectional summarizing RNN layer in y-dimension.
"""
rnn = layers.TransposedSummarizingRNN(10, 2, 'b', True, True)
o = rnn(torch.randn(1, 10, 32, 64))
self.assertEqual(o[0].shape, (1, 4, 1, 64))
def test_linsoftmax(self):
"""
Test basic function of linear layer.
"""
lin = layers.LinSoftmax(20, 10)
o = lin(torch.randn(1, 20, 12, 24))
self.assertEqual(o[0].shape, (1, 10, 12, 24))
def test_linsoftmax_train(self):
"""
Test function of linear layer in training mode (log_softmax)
"""
lin = layers.LinSoftmax(20, 10).train()
o = lin(torch.randn(1, 20, 12, 24))
self.assertLess(o[0].max(), 0)
def test_linsoftmax_test(self):
"""
Test function of linear layer in eval mode (softmax)
"""
lin = layers.LinSoftmax(20, 10).eval()
o = lin(torch.randn(1, 20, 12, 24))
self.assertGreaterEqual(o[0].min(), 0)
def test_linsoftmax_aug(self):
"""
Test basic function of linear layer with 1-augmentation.
"""
lin = layers.LinSoftmax(20, 10, True)
o = lin(torch.randn(1, 20, 12, 24))
self.assertEqual(o[0].shape, (1, 10, 12, 24))
def test_linsoftmax_aug_train(self):
"""
Test function of linear layer in training mode (log_softmax) with 1-augmentation
"""
lin = layers.LinSoftmax(20, 10, True).train()
o = lin(torch.randn(1, 20, 12, 24))
self.assertLess(o[0].max(), 0)
def test_linsoftmax_aug_test(self):
"""
Test function of linear layer in eval mode (softmax) with 1-augmentation
"""
lin = layers.LinSoftmax(20, 10, True).eval()
o = lin(torch.randn(1, 20, 12, 24))
self.assertGreaterEqual(o[0].min(), 0)
def test_actconv2d_lin(self):
"""
Test convolutional layer without activation.
"""
conv = layers.ActConv2D(5, 12, (3, 3), (1, 1), 'l')
o = conv(torch.randn(1, 5, 24, 12))
self.assertEqual(o[0].shape, (1, 12, 24, 12))
def test_actconv2d_sigmoid(self):
"""
Test convolutional layer with sigmoid activation.
"""
conv = layers.ActConv2D(5, 12, (3, 3), (1, 1), 's')
o = conv(torch.randn(1, 5, 24, 12))
self.assertTrue(0 <= o[0].min() <= 1)
self.assertTrue(0 <= o[0].max() <= 1)
def test_actconv2d_tanh(self):
"""
Test convolutional layer with tanh activation.
"""
conv = layers.ActConv2D(5, 12, (3, 3), (1, 1), 't')
o = conv(torch.randn(1, 5, 24, 12))
self.assertTrue(-1 <= o[0].min() <= 1)
self.assertTrue(-1 <= o[0].max() <= 1)
def test_actconv2d_softmax(self):
"""
Test convolutional layer with softmax activation.
"""
conv = layers.ActConv2D(5, 12, (3, 3), (1, 1), 'm')
o = conv(torch.randn(1, 5, 24, 12))
self.assertTrue(0 <= o[0].min() <= 1)
self.assertTrue(0 <= o[0].max() <= 1)
def test_actconv2d_relu(self):
"""
Test convolutional layer with relu activation.
"""
conv = layers.ActConv2D(5, 12, (3, 3), (1, 1), 'r')
o = conv(torch.randn(1, 5, 24, 12))
self.assertLessEqual(0, o[0].min())
self.assertLessEqual(0, o[0].max())
| [
"kraken.lib.layers.TransposedSummarizingRNN",
"kraken.lib.layers.Dropout",
"kraken.lib.layers.LinSoftmax",
"kraken.lib.layers.MaxPool",
"torch.set_grad_enabled",
"kraken.lib.layers.ActConv2D",
"torch.randn"
] | [((242, 271), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(False)'], {}), '(False)\n', (264, 271), False, 'import torch\n'), ((374, 404), 'kraken.lib.layers.MaxPool', 'layers.MaxPool', (['(3, 3)', '(2, 2)'], {}), '((3, 3), (2, 2))\n', (388, 404), False, 'from kraken.lib import layers\n'), ((600, 622), 'kraken.lib.layers.Dropout', 'layers.Dropout', (['(0.2)', '(1)'], {}), '(0.2, 1)\n', (614, 622), False, 'from kraken.lib import layers\n'), ((818, 840), 'kraken.lib.layers.Dropout', 'layers.Dropout', (['(0.2)', '(2)'], {}), '(0.2, 2)\n', (832, 840), False, 'from kraken.lib import layers\n'), ((1069, 1126), 'kraken.lib.layers.TransposedSummarizingRNN', 'layers.TransposedSummarizingRNN', (['(10)', '(2)', '"""f"""', '(False)', '(False)'], {}), "(10, 2, 'f', False, False)\n", (1100, 1126), False, 'from kraken.lib import layers\n'), ((1357, 1413), 'kraken.lib.layers.TransposedSummarizingRNN', 'layers.TransposedSummarizingRNN', (['(10)', '(2)', '"""f"""', '(True)', '(False)'], {}), "(10, 2, 'f', True, False)\n", (1388, 1413), False, 'from kraken.lib import layers\n'), ((1666, 1722), 'kraken.lib.layers.TransposedSummarizingRNN', 'layers.TransposedSummarizingRNN', (['(10)', '(2)', '"""f"""', '(False)', '(True)'], {}), "(10, 2, 'f', False, True)\n", (1697, 1722), False, 'from kraken.lib import layers\n'), ((1974, 2029), 'kraken.lib.layers.TransposedSummarizingRNN', 'layers.TransposedSummarizingRNN', (['(10)', '(2)', '"""f"""', '(True)', '(True)'], {}), "(10, 2, 'f', True, True)\n", (2005, 2029), False, 'from kraken.lib import layers\n'), ((2255, 2312), 'kraken.lib.layers.TransposedSummarizingRNN', 'layers.TransposedSummarizingRNN', (['(10)', '(2)', '"""b"""', '(False)', '(False)'], {}), "(10, 2, 'b', False, False)\n", (2286, 2312), False, 'from kraken.lib import layers\n'), ((2539, 2595), 'kraken.lib.layers.TransposedSummarizingRNN', 'layers.TransposedSummarizingRNN', (['(10)', '(2)', '"""b"""', '(True)', '(False)'], {}), "(10, 2, 'b', True, False)\n", (2570, 2595), False, 'from kraken.lib import layers\n'), ((2844, 2900), 'kraken.lib.layers.TransposedSummarizingRNN', 'layers.TransposedSummarizingRNN', (['(10)', '(2)', '"""b"""', '(False)', '(True)'], {}), "(10, 2, 'b', False, True)\n", (2875, 2900), False, 'from kraken.lib import layers\n'), ((3148, 3203), 'kraken.lib.layers.TransposedSummarizingRNN', 'layers.TransposedSummarizingRNN', (['(10)', '(2)', '"""b"""', '(True)', '(True)'], {}), "(10, 2, 'b', True, True)\n", (3179, 3203), False, 'from kraken.lib import layers\n'), ((3415, 3440), 'kraken.lib.layers.LinSoftmax', 'layers.LinSoftmax', (['(20)', '(10)'], {}), '(20, 10)\n', (3432, 3440), False, 'from kraken.lib import layers\n'), ((4200, 4231), 'kraken.lib.layers.LinSoftmax', 'layers.LinSoftmax', (['(20)', '(10)', '(True)'], {}), '(20, 10, True)\n', (4217, 4231), False, 'from kraken.lib import layers\n'), ((5039, 5083), 'kraken.lib.layers.ActConv2D', 'layers.ActConv2D', (['(5)', '(12)', '(3, 3)', '(1, 1)', '"""l"""'], {}), "(5, 12, (3, 3), (1, 1), 'l')\n", (5055, 5083), False, 'from kraken.lib import layers\n'), ((5318, 5362), 'kraken.lib.layers.ActConv2D', 'layers.ActConv2D', (['(5)', '(12)', '(3, 3)', '(1, 1)', '"""s"""'], {}), "(5, 12, (3, 3), (1, 1), 's')\n", (5334, 5362), False, 'from kraken.lib import layers\n'), ((5629, 5673), 'kraken.lib.layers.ActConv2D', 'layers.ActConv2D', (['(5)', '(12)', '(3, 3)', '(1, 1)', '"""t"""'], {}), "(5, 12, (3, 3), (1, 1), 't')\n", (5645, 5673), False, 'from kraken.lib import layers\n'), ((5948, 5992), 'kraken.lib.layers.ActConv2D', 'layers.ActConv2D', (['(5)', '(12)', '(3, 3)', '(1, 1)', '"""m"""'], {}), "(5, 12, (3, 3), (1, 1), 'm')\n", (5964, 5992), False, 'from kraken.lib import layers\n'), ((6259, 6303), 'kraken.lib.layers.ActConv2D', 'layers.ActConv2D', (['(5)', '(12)', '(3, 3)', '(1, 1)', '"""r"""'], {}), "(5, 12, (3, 3), (1, 1), 'r')\n", (6275, 6303), False, 'from kraken.lib import layers\n'), ((420, 445), 'torch.randn', 'torch.randn', (['(1)', '(2)', '(32)', '(64)'], {}), '(1, 2, 32, 64)\n', (431, 445), False, 'import torch\n'), ((638, 663), 'torch.randn', 'torch.randn', (['(1)', '(2)', '(32)', '(64)'], {}), '(1, 2, 32, 64)\n', (649, 663), False, 'import torch\n'), ((856, 881), 'torch.randn', 'torch.randn', (['(1)', '(2)', '(32)', '(64)'], {}), '(1, 2, 32, 64)\n', (867, 881), False, 'import torch\n'), ((1143, 1169), 'torch.randn', 'torch.randn', (['(1)', '(10)', '(32)', '(64)'], {}), '(1, 10, 32, 64)\n', (1154, 1169), False, 'import torch\n'), ((1430, 1456), 'torch.randn', 'torch.randn', (['(1)', '(10)', '(32)', '(64)'], {}), '(1, 10, 32, 64)\n', (1441, 1456), False, 'import torch\n'), ((1739, 1765), 'torch.randn', 'torch.randn', (['(1)', '(10)', '(32)', '(64)'], {}), '(1, 10, 32, 64)\n', (1750, 1765), False, 'import torch\n'), ((2046, 2072), 'torch.randn', 'torch.randn', (['(1)', '(10)', '(32)', '(64)'], {}), '(1, 10, 32, 64)\n', (2057, 2072), False, 'import torch\n'), ((2329, 2355), 'torch.randn', 'torch.randn', (['(1)', '(10)', '(32)', '(64)'], {}), '(1, 10, 32, 64)\n', (2340, 2355), False, 'import torch\n'), ((2612, 2638), 'torch.randn', 'torch.randn', (['(1)', '(10)', '(32)', '(64)'], {}), '(1, 10, 32, 64)\n', (2623, 2638), False, 'import torch\n'), ((2917, 2943), 'torch.randn', 'torch.randn', (['(1)', '(10)', '(32)', '(64)'], {}), '(1, 10, 32, 64)\n', (2928, 2943), False, 'import torch\n'), ((3220, 3246), 'torch.randn', 'torch.randn', (['(1)', '(10)', '(32)', '(64)'], {}), '(1, 10, 32, 64)\n', (3231, 3246), False, 'import torch\n'), ((3457, 3483), 'torch.randn', 'torch.randn', (['(1)', '(20)', '(12)', '(24)'], {}), '(1, 20, 12, 24)\n', (3468, 3483), False, 'import torch\n'), ((3734, 3760), 'torch.randn', 'torch.randn', (['(1)', '(20)', '(12)', '(24)'], {}), '(1, 20, 12, 24)\n', (3745, 3760), False, 'import torch\n'), ((3986, 4012), 'torch.randn', 'torch.randn', (['(1)', '(20)', '(12)', '(24)'], {}), '(1, 20, 12, 24)\n', (3997, 4012), False, 'import torch\n'), ((4248, 4274), 'torch.randn', 'torch.randn', (['(1)', '(20)', '(12)', '(24)'], {}), '(1, 20, 12, 24)\n', (4259, 4274), False, 'import torch\n'), ((4555, 4581), 'torch.randn', 'torch.randn', (['(1)', '(20)', '(12)', '(24)'], {}), '(1, 20, 12, 24)\n', (4566, 4581), False, 'import torch\n'), ((4837, 4863), 'torch.randn', 'torch.randn', (['(1)', '(20)', '(12)', '(24)'], {}), '(1, 20, 12, 24)\n', (4848, 4863), False, 'import torch\n'), ((5101, 5126), 'torch.randn', 'torch.randn', (['(1)', '(5)', '(24)', '(12)'], {}), '(1, 5, 24, 12)\n', (5112, 5126), False, 'import torch\n'), ((5380, 5405), 'torch.randn', 'torch.randn', (['(1)', '(5)', '(24)', '(12)'], {}), '(1, 5, 24, 12)\n', (5391, 5405), False, 'import torch\n'), ((5691, 5716), 'torch.randn', 'torch.randn', (['(1)', '(5)', '(24)', '(12)'], {}), '(1, 5, 24, 12)\n', (5702, 5716), False, 'import torch\n'), ((6010, 6035), 'torch.randn', 'torch.randn', (['(1)', '(5)', '(24)', '(12)'], {}), '(1, 5, 24, 12)\n', (6021, 6035), False, 'import torch\n'), ((6321, 6346), 'torch.randn', 'torch.randn', (['(1)', '(5)', '(24)', '(12)'], {}), '(1, 5, 24, 12)\n', (6332, 6346), False, 'import torch\n'), ((3684, 3709), 'kraken.lib.layers.LinSoftmax', 'layers.LinSoftmax', (['(20)', '(10)'], {}), '(20, 10)\n', (3701, 3709), False, 'from kraken.lib import layers\n'), ((3937, 3962), 'kraken.lib.layers.LinSoftmax', 'layers.LinSoftmax', (['(20)', '(10)'], {}), '(20, 10)\n', (3954, 3962), False, 'from kraken.lib import layers\n'), ((4499, 4530), 'kraken.lib.layers.LinSoftmax', 'layers.LinSoftmax', (['(20)', '(10)', '(True)'], {}), '(20, 10, True)\n', (4516, 4530), False, 'from kraken.lib import layers\n'), ((4782, 4813), 'kraken.lib.layers.LinSoftmax', 'layers.LinSoftmax', (['(20)', '(10)', '(True)'], {}), '(20, 10, True)\n', (4799, 4813), False, 'from kraken.lib import layers\n')] |
#
# Copyright (c) 2016, SUSE LLC All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of ceph-auto-aws nor the names of its contributors may be
# used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
import logging
from handson.myyaml import stanza
log = logging.getLogger(__name__)
class ClusterOptions(object):
def validate_delegate_list(self):
dl = self.args.delegate_list
if dl is None or len(dl) == 0:
return True
max_delegates = stanza('delegates')
log.debug("Maximum number of delegates is {!r}".format(max_delegates))
assert (
max_delegates is not None and
max_delegates > 0 and
max_delegates <= 100
), "Bad delegates stanza in YAML: {!r}".format(max_delegates)
assert dl[-1] <= max_delegates, (
("Delegate list exceeds {!r} (maximum number of " +
"delegates in YAML)").format(max_delegates)
)
def process_delegate_list(self):
max_d = stanza('delegates')
if self.args.delegate_list is None:
self.args.delegate_list = list()
if self.args.all:
self.args.delegate_list = list(range(1, max_d + 1))
if self.args.master:
self.args.delegate_list.insert(0, 0)
self.validate_delegate_list()
log.info("Delegate list is {!r}".format(self.args.delegate_list))
| [
"logging.getLogger",
"handson.myyaml.stanza"
] | [((1580, 1607), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1597, 1607), False, 'import logging\n'), ((1803, 1822), 'handson.myyaml.stanza', 'stanza', (['"""delegates"""'], {}), "('delegates')\n", (1809, 1822), False, 'from handson.myyaml import stanza\n'), ((2337, 2356), 'handson.myyaml.stanza', 'stanza', (['"""delegates"""'], {}), "('delegates')\n", (2343, 2356), False, 'from handson.myyaml import stanza\n')] |
"""
Cirrus
======
Handle Cirrus data.
"""
import csv
import io
import re
import pandas as pd
def read_csv_cirrus(filename): # pylint: disable=too-many-locals
"""Read a Cirrus CSV file. Currently exists support for some types of
CSV files extracted with NoiseTools. There is no support for CSVs related
with occupational noise.
If there are NC and NR values in the csv file, they will be stored in the
returned object with attributes ``nc`` and ``nr``. If the CSV file contains
time history, you can access to date and time with the ``time`` attribute.
Also, it is possible to know the integration time with the
``integration_time`` attribute.
:param filename: CSV file name.
:returns: Pandas dataframe with all data extracted from the CSV file.
:rtype: Pandas dataframe.
"""
with open(filename, "r") as csvfile:
csvreader = csvfile.read()
csvreader = re.sub(r" dB", "", csvreader) # Clean " dB" from data
dialect = csv.Sniffer().sniff(csvreader, delimiters=",;")
separator = dialect.delimiter
# Guess decimal separator
decimal_sep = re.search(
r"\"\d{2,3}"
r"(\.|,)" # Decimal separator
r"\d{1,2}\"",
csvreader,
).group(1)
n_cols = re.search("(.+)\n", csvreader).group(1).count(separator) + 1
if n_cols < 5:
unsorted_data = []
pdindex = ["Z"]
for i, c in enumerate(csvreader.splitlines()):
if c[:4] == '"NR"':
nr = int(re.search(r"\d{2}", c).group(0))
continue
elif c[:4] == '"NC"':
nc = int(re.search(r"\d{2}", c).group(0))
continue
if i != 0:
unsorted_data.append(c.split(separator))
else:
if n_cols == 3:
pdindex.append(c[-2:-1])
elif n_cols == 4:
pdindex.append("A")
pdindex.append("C")
# Create a sorted temporary csv-like file
csv_data = list(zip(*unsorted_data))
temp_csv = ""
for row in csv_data:
temp_csv += separator.join(row) + "\n"
# Then, read it with pandas
data = pd.read_csv(
io.StringIO(temp_csv),
sep=separator,
decimal=decimal_sep,
)
# Assign NC and NR data if they are present
try:
data.nc = nc
data.nr = nr
# TODO specify exception type:
except: # pylint: disable=bare-except
pass
# If the csv file contains global data from the "Details" tab in
# NoiseTools, skip row names
if n_cols != 2:
data.index = pdindex
else:
data = pd.read_csv(
filename,
parse_dates=[[0, 1]],
sep=separator,
decimal=decimal_sep,
)
# Fix time name column
en_columns = data.columns.values
en_columns[0] = "time"
data.columns = en_columns
# Guess integration time with statistical mode because the csv could
# have been cleaned from unwanted noise
data["time"] = pd.to_datetime(data.time)
delta = data.time.diff().fillna(0.0)
# Mode and change from ns to s
int_time = int(delta.mode().astype(int) * 1e-9)
if round(int_time, 2) == 0.06: # Fix for 1/16 s
int_time = 0.0625
data.integration_time = int_time
return data
| [
"pandas.read_csv",
"csv.Sniffer",
"re.sub",
"io.StringIO",
"pandas.to_datetime",
"re.search"
] | [((928, 956), 're.sub', 're.sub', (['""" dB"""', '""""""', 'csvreader'], {}), "(' dB', '', csvreader)\n", (934, 956), False, 'import re\n'), ((2790, 2869), 'pandas.read_csv', 'pd.read_csv', (['filename'], {'parse_dates': '[[0, 1]]', 'sep': 'separator', 'decimal': 'decimal_sep'}), '(filename, parse_dates=[[0, 1]], sep=separator, decimal=decimal_sep)\n', (2801, 2869), True, 'import pandas as pd\n'), ((3216, 3241), 'pandas.to_datetime', 'pd.to_datetime', (['data.time'], {}), '(data.time)\n', (3230, 3241), True, 'import pandas as pd\n'), ((2284, 2305), 'io.StringIO', 'io.StringIO', (['temp_csv'], {}), '(temp_csv)\n', (2295, 2305), False, 'import io\n'), ((1001, 1014), 'csv.Sniffer', 'csv.Sniffer', ([], {}), '()\n', (1012, 1014), False, 'import csv\n'), ((1143, 1196), 're.search', 're.search', (['"""\\\\"\\\\d{2,3}(\\\\.|,)\\\\d{1,2}\\\\\\""""', 'csvreader'], {}), '(\'\\\\"\\\\d{2,3}(\\\\.|,)\\\\d{1,2}\\\\"\', csvreader)\n', (1152, 1196), False, 'import re\n'), ((1303, 1333), 're.search', 're.search', (['"""(.+)\n"""', 'csvreader'], {}), "('(.+)\\n', csvreader)\n", (1312, 1333), False, 'import re\n'), ((1546, 1568), 're.search', 're.search', (['"""\\\\d{2}"""', 'c'], {}), "('\\\\d{2}', c)\n", (1555, 1568), False, 'import re\n'), ((1663, 1685), 're.search', 're.search', (['"""\\\\d{2}"""', 'c'], {}), "('\\\\d{2}', c)\n", (1672, 1685), False, 'import re\n')] |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Configuration file (powered by YACS)."""
import os
from pycls.core.io import pathmgr
from yacs.config import CfgNode
# Global config object (example usage: from core.config import cfg)
_C = CfgNode()
cfg = _C
# ---------------------------------- Model options ----------------------------------- #
_C.MODEL = CfgNode()
# Model type
_C.MODEL.TYPE = ""
# Number of weight layers
_C.MODEL.DEPTH = 0
# Number of classes
_C.MODEL.NUM_CLASSES = 10
# Loss function (see pycls/models/loss.py for options)
_C.MODEL.LOSS_FUN = "cross_entropy"
# Activation function (relu or silu/swish)
_C.MODEL.ACTIVATION_FUN = "relu"
# Perform activation inplace if implemented
_C.MODEL.ACTIVATION_INPLACE = True
# Model scaling parameters, see models/scaler.py (has no effect unless scaler is used)
_C.MODEL.SCALING_TYPE = ""
_C.MODEL.SCALING_FACTOR = 1.0
# ---------------------------------- ResNet options ---------------------------------- #
_C.RESNET = CfgNode()
# Transformation function (see pycls/models/resnet.py for options)
_C.RESNET.TRANS_FUN = "basic_transform"
# Number of groups to use (1 -> ResNet; > 1 -> ResNeXt)
_C.RESNET.NUM_GROUPS = 1
# Width of each group (64 -> ResNet; 4 -> ResNeXt)
_C.RESNET.WIDTH_PER_GROUP = 64
# Apply stride to 1x1 conv (True -> MSRA; False -> fb.torch)
_C.RESNET.STRIDE_1X1 = True
# ---------------------------------- AnyNet options ---------------------------------- #
_C.ANYNET = CfgNode()
# Stem type
_C.ANYNET.STEM_TYPE = "simple_stem_in"
# Stem width
_C.ANYNET.STEM_W = 32
# Block type
_C.ANYNET.BLOCK_TYPE = "res_bottleneck_block"
# Depth for each stage (number of blocks in the stage)
_C.ANYNET.DEPTHS = []
# Width for each stage (width of each block in the stage)
_C.ANYNET.WIDTHS = []
# Strides for each stage (applies to the first block of each stage)
_C.ANYNET.STRIDES = []
# Bottleneck multipliers for each stage (applies to bottleneck block)
_C.ANYNET.BOT_MULS = []
# Group widths for each stage (applies to bottleneck block)
_C.ANYNET.GROUP_WS = []
# Head width for first conv in head (if 0 conv is omitted, as is the default)
_C.ANYNET.HEAD_W = 0
# Whether SE is enabled for res_bottleneck_block
_C.ANYNET.SE_ON = False
# SE ratio
_C.ANYNET.SE_R = 0.25
# ---------------------------------- RegNet options ---------------------------------- #
_C.REGNET = CfgNode()
# Stem type
_C.REGNET.STEM_TYPE = "simple_stem_in"
# Stem width
_C.REGNET.STEM_W = 32
# Block type
_C.REGNET.BLOCK_TYPE = "res_bottleneck_block"
# Stride of each stage
_C.REGNET.STRIDE = 2
# Squeeze-and-Excitation (RegNetY)
_C.REGNET.SE_ON = False
_C.REGNET.SE_R = 0.25
# Depth
_C.REGNET.DEPTH = 10
# Initial width
_C.REGNET.W0 = 32
# Slope
_C.REGNET.WA = 5.0
# Quantization
_C.REGNET.WM = 2.5
# Group width
_C.REGNET.GROUP_W = 16
# Bottleneck multiplier (bm = 1 / b from the paper)
_C.REGNET.BOT_MUL = 1.0
# Head width for first conv in head (if 0 conv is omitted, as is the default)
_C.REGNET.HEAD_W = 0
# ------------------------------- EfficientNet options ------------------------------- #
_C.EN = CfgNode()
# Stem width
_C.EN.STEM_W = 32
# Depth for each stage (number of blocks in the stage)
_C.EN.DEPTHS = []
# Width for each stage (width of each block in the stage)
_C.EN.WIDTHS = []
# Expansion ratios for MBConv blocks in each stage
_C.EN.EXP_RATIOS = []
# Squeeze-and-Excitation (SE) ratio
_C.EN.SE_R = 0.25
# Strides for each stage (applies to the first block of each stage)
_C.EN.STRIDES = []
# Kernel sizes for each stage
_C.EN.KERNELS = []
# Head width
_C.EN.HEAD_W = 1280
# Drop connect ratio
_C.EN.DC_RATIO = 0.0
# Dropout ratio
_C.EN.DROPOUT_RATIO = 0.0
# ---------------------------- Vision Transformer options ---------------------------- #
_C.VIT = CfgNode()
# Patch Size (TRAIN.IM_SIZE must be divisible by PATCH_SIZE)
_C.VIT.PATCH_SIZE = 16
# Type of stem select from {'patchify', 'conv'}
_C.VIT.STEM_TYPE = "patchify"
# C-stem conv kernel sizes (https://arxiv.org/abs/2106.14881)
_C.VIT.C_STEM_KERNELS = []
# C-stem conv strides (the product of which must equal PATCH_SIZE)
_C.VIT.C_STEM_STRIDES = []
# C-stem conv output dims (last dim must equal HIDDEN_DIM)
_C.VIT.C_STEM_DIMS = []
# Number of layers in the encoder
_C.VIT.NUM_LAYERS = 12
# Number of self attention heads
_C.VIT.NUM_HEADS = 12
# Hidden dimension
_C.VIT.HIDDEN_DIM = 768
# Dimension of the MLP in the encoder
_C.VIT.MLP_DIM = 3072
# Type of classifier select from {'token', 'pooled'}
_C.VIT.CLASSIFIER_TYPE = "token"
# -------------------------------- Batch norm options -------------------------------- #
_C.BN = CfgNode()
# BN epsilon
_C.BN.EPS = 1e-5
# BN momentum (BN momentum in PyTorch = 1 - BN momentum in Caffe2)
_C.BN.MOM = 0.1
# Precise BN stats
_C.BN.USE_PRECISE_STATS = True
_C.BN.NUM_SAMPLES_PRECISE = 8192
# Initialize the gamma of the final BN of each block to zero
_C.BN.ZERO_INIT_FINAL_GAMMA = False
# Use a different weight decay for BN layers
_C.BN.USE_CUSTOM_WEIGHT_DECAY = False
_C.BN.CUSTOM_WEIGHT_DECAY = 0.0
# -------------------------------- Layer norm options -------------------------------- #
_C.LN = CfgNode()
# LN epsilon
_C.LN.EPS = 1e-5
# Use a different weight decay for LN layers
_C.LN.USE_CUSTOM_WEIGHT_DECAY = False
_C.LN.CUSTOM_WEIGHT_DECAY = 0.0
# -------------------------------- Optimizer options --------------------------------- #
_C.OPTIM = CfgNode()
# Type of optimizer select from {'sgd', 'adam', 'adamw'}
_C.OPTIM.OPTIMIZER = "sgd"
# Learning rate ranges from BASE_LR to MIN_LR*BASE_LR according to the LR_POLICY
_C.OPTIM.BASE_LR = 0.1
_C.OPTIM.MIN_LR = 0.0
# Learning rate policy select from {'cos', 'exp', 'lin', 'steps'}
_C.OPTIM.LR_POLICY = "cos"
# Steps for 'steps' policy (in epochs)
_C.OPTIM.STEPS = []
# Learning rate multiplier for 'steps' policy
_C.OPTIM.LR_MULT = 0.1
# Maximal number of epochs
_C.OPTIM.MAX_EPOCH = 200
# Momentum
_C.OPTIM.MOMENTUM = 0.9
# Momentum dampening
_C.OPTIM.DAMPENING = 0.0
# Nesterov momentum
_C.OPTIM.NESTEROV = True
# Betas (for Adam/AdamW optimizer)
_C.OPTIM.BETA1 = 0.9
_C.OPTIM.BETA2 = 0.999
# L2 regularization
_C.OPTIM.WEIGHT_DECAY = 5e-4
# Use a different weight decay for all biases (excluding those in BN/LN layers)
_C.OPTIM.BIAS_USE_CUSTOM_WEIGHT_DECAY = False
_C.OPTIM.BIAS_CUSTOM_WEIGHT_DECAY = 0.0
# Start the warm up from OPTIM.BASE_LR * OPTIM.WARMUP_FACTOR
_C.OPTIM.WARMUP_FACTOR = 0.1
# Gradually warm up the OPTIM.BASE_LR over this number of epochs
_C.OPTIM.WARMUP_EPOCHS = 0.0
# Exponential Moving Average (EMA) update value
_C.OPTIM.EMA_ALPHA = 1e-5
# Iteration frequency with which to update EMA weights
_C.OPTIM.EMA_UPDATE_PERIOD = 32
# WARM-UP Iter
_C.OPTIM.WARMUP_ITER = False
# --------------------------------- Training options --------------------------------- #
_C.TRAIN = CfgNode()
# Dataset and split
_C.TRAIN.DATASET = ""
_C.TRAIN.SPLIT = "train"
# Total mini-batch size
_C.TRAIN.BATCH_SIZE = 128
# Image size
_C.TRAIN.IM_SIZE = 224
# Resume training from the latest checkpoint in the output directory
_C.TRAIN.AUTO_RESUME = True
# Weights to start training from
_C.TRAIN.WEIGHTS = ""
# If True train using mixed precision
_C.TRAIN.MIXED_PRECISION = False
# Label smoothing value in 0 to 1 where (0 gives no smoothing)
_C.TRAIN.LABEL_SMOOTHING = 0.0
# Batch mixup regularization value in 0 to 1 (0 gives no mixup)
_C.TRAIN.MIXUP_ALPHA = 0.0
# Batch cutmix regularization value in 0 to 1 (0 gives no cutmix)
_C.TRAIN.CUTMIX_ALPHA = 0.0
# Standard deviation for AlexNet-style PCA jitter (0 gives no PCA jitter)
_C.TRAIN.PCA_STD = 0.1
# Data augmentation to use ("", "AutoAugment", "RandAugment_N2_M0.5", etc.)
_C.TRAIN.AUGMENT = ""
# --------------------------------- Testing options ---------------------------------- #
_C.TEST = CfgNode()
# Dataset and split
_C.TEST.DATASET = ""
_C.TEST.SPLIT = "val"
# Total mini-batch size
_C.TEST.BATCH_SIZE = 200
# Image size
_C.TEST.IM_SIZE = 256
# Weights to use for testing
_C.TEST.WEIGHTS = ""
# ------------------------------- Data loader options -------------------------------- #
_C.DATA_LOADER = CfgNode()
# Number of data loader workers per process
_C.DATA_LOADER.NUM_WORKERS = 8
# Load data to pinned host memory
_C.DATA_LOADER.PIN_MEMORY = True
# ---------------------------------- CUDNN options ----------------------------------- #
_C.CUDNN = CfgNode()
# Perform benchmarking to select fastest CUDNN algorithms (best for fixed input sizes)
_C.CUDNN.BENCHMARK = True
# ------------------------------- Precise time options ------------------------------- #
_C.PREC_TIME = CfgNode()
# Number of iterations to warm up the caches
_C.PREC_TIME.WARMUP_ITER = 3
# Number of iterations to compute avg time
_C.PREC_TIME.NUM_ITER = 30
# ---------------------------------- Launch options ---------------------------------- #
_C.LAUNCH = CfgNode()
# The launch mode, may be 'local' or 'slurm' (or 'submitit_local' for debugging)
# The 'local' mode uses a multi-GPU setup via torch.multiprocessing.run_processes.
# The 'slurm' mode uses submitit to launch a job on a SLURM cluster and provides
# support for MULTI-NODE jobs (and is the only way to launch MULTI-NODE jobs).
# In 'slurm' mode, the LAUNCH options below can be used to control the SLURM options.
# Note that NUM_GPUS (not part of LAUNCH options) determines total GPUs requested.
_C.LAUNCH.MODE = "local"
# Launch options that are only used if LAUNCH.MODE is 'slurm'
_C.LAUNCH.MAX_RETRY = 3
_C.LAUNCH.NAME = "pycls_job"
_C.LAUNCH.COMMENT = ""
_C.LAUNCH.CPUS_PER_GPU = 10
_C.LAUNCH.MEM_PER_GPU = 60
_C.LAUNCH.PARTITION = "devlab"
_C.LAUNCH.GPU_TYPE = "volta"
_C.LAUNCH.TIME_LIMIT = 4200
_C.LAUNCH.EMAIL = ""
# ----------------------------------- Misc options ----------------------------------- #
# Optional description of a config
_C.DESC = ""
# If True output additional info to log
_C.VERBOSE = True
# Number of GPUs to use (applies to both training and testing)
_C.NUM_GPUS = 1
# Maximum number of GPUs available per node (unlikely to need to be changed)
_C.MAX_GPUS_PER_NODE = 8
# Output directory
_C.OUT_DIR = "/tmp"
# Config destination (in OUT_DIR)
_C.CFG_DEST = "config.yaml"
# Note that non-determinism is still be present due to non-deterministic GPU ops
_C.RNG_SEED = 1
# Log destination ('stdout' or 'file')
_C.LOG_DEST = "stdout"
# Log period in iters
_C.LOG_PERIOD = 10
# Distributed backend
_C.DIST_BACKEND = "nccl"
# Hostname and port range for multi-process groups (actual port selected randomly)
_C.HOST = "localhost"
_C.PORT_RANGE = [10000, 65000]
# Models weights referred to by URL are downloaded to this local cache
_C.DOWNLOAD_CACHE = "/tmp/pycls-download-cache"
# ---------------------------------- Default config ---------------------------------- #
_CFG_DEFAULT = _C.clone()
_CFG_DEFAULT.freeze()
# --------------------------------- Deprecated keys ---------------------------------- #
_C.register_deprecated_key("MEM")
_C.register_deprecated_key("MEM.RELU_INPLACE")
_C.register_deprecated_key("OPTIM.GAMMA")
_C.register_deprecated_key("PREC_TIME.BATCH_SIZE")
_C.register_deprecated_key("PREC_TIME.ENABLED")
_C.register_deprecated_key("PORT")
_C.register_deprecated_key("TRAIN.EVAL_PERIOD")
_C.register_deprecated_key("TRAIN.CHECKPOINT_PERIOD")
def assert_cfg():
"""Checks config values invariants."""
err_str = "The first lr step must start at 0"
assert not _C.OPTIM.STEPS or _C.OPTIM.STEPS[0] == 0, err_str
data_splits = ["train", "val", "test"]
err_str = "Data split '{}' not supported"
assert _C.TRAIN.SPLIT in data_splits, err_str.format(_C.TRAIN.SPLIT)
assert _C.TEST.SPLIT in data_splits, err_str.format(_C.TEST.SPLIT)
err_str = "Mini-batch size should be a multiple of NUM_GPUS."
assert _C.TRAIN.BATCH_SIZE % _C.NUM_GPUS == 0, err_str
assert _C.TEST.BATCH_SIZE % _C.NUM_GPUS == 0, err_str
err_str = "Log destination '{}' not supported"
assert _C.LOG_DEST in ["stdout", "file"], err_str.format(_C.LOG_DEST)
err_str = "NUM_GPUS must be divisible by or less than MAX_GPUS_PER_NODE"
num_gpus, max_gpus_per_node = _C.NUM_GPUS, _C.MAX_GPUS_PER_NODE
assert num_gpus <= max_gpus_per_node or num_gpus % max_gpus_per_node == 0, err_str
err_str = "Invalid mode {}".format(_C.LAUNCH.MODE)
assert _C.LAUNCH.MODE in ["local", "submitit_local", "slurm"], err_str
def dump_cfg():
"""Dumps the config to the output directory."""
cfg_file = os.path.join(_C.OUT_DIR, _C.CFG_DEST)
with pathmgr.open(cfg_file, "w") as f:
_C.dump(stream=f)
return cfg_file
def load_cfg(cfg_file):
"""Loads config from specified file."""
with pathmgr.open(cfg_file, "r") as f:
_C.merge_from_other_cfg(_C.load_cfg(f))
def reset_cfg():
"""Reset config to initial state."""
_C.merge_from_other_cfg(_CFG_DEFAULT)
| [
"pycls.core.io.pathmgr.open",
"os.path.join",
"yacs.config.CfgNode"
] | [((399, 408), 'yacs.config.CfgNode', 'CfgNode', ([], {}), '()\n', (406, 408), False, 'from yacs.config import CfgNode\n'), ((520, 529), 'yacs.config.CfgNode', 'CfgNode', ([], {}), '()\n', (527, 529), False, 'from yacs.config import CfgNode\n'), ((1153, 1162), 'yacs.config.CfgNode', 'CfgNode', ([], {}), '()\n', (1160, 1162), False, 'from yacs.config import CfgNode\n'), ((1629, 1638), 'yacs.config.CfgNode', 'CfgNode', ([], {}), '()\n', (1636, 1638), False, 'from yacs.config import CfgNode\n'), ((2529, 2538), 'yacs.config.CfgNode', 'CfgNode', ([], {}), '()\n', (2536, 2538), False, 'from yacs.config import CfgNode\n'), ((3256, 3265), 'yacs.config.CfgNode', 'CfgNode', ([], {}), '()\n', (3263, 3265), False, 'from yacs.config import CfgNode\n'), ((3936, 3945), 'yacs.config.CfgNode', 'CfgNode', ([], {}), '()\n', (3943, 3945), False, 'from yacs.config import CfgNode\n'), ((4784, 4793), 'yacs.config.CfgNode', 'CfgNode', ([], {}), '()\n', (4791, 4793), False, 'from yacs.config import CfgNode\n'), ((5306, 5315), 'yacs.config.CfgNode', 'CfgNode', ([], {}), '()\n', (5313, 5315), False, 'from yacs.config import CfgNode\n'), ((5565, 5574), 'yacs.config.CfgNode', 'CfgNode', ([], {}), '()\n', (5572, 5574), False, 'from yacs.config import CfgNode\n'), ((6985, 6994), 'yacs.config.CfgNode', 'CfgNode', ([], {}), '()\n', (6992, 6994), False, 'from yacs.config import CfgNode\n'), ((7957, 7966), 'yacs.config.CfgNode', 'CfgNode', ([], {}), '()\n', (7964, 7966), False, 'from yacs.config import CfgNode\n'), ((8276, 8285), 'yacs.config.CfgNode', 'CfgNode', ([], {}), '()\n', (8283, 8285), False, 'from yacs.config import CfgNode\n'), ((8532, 8541), 'yacs.config.CfgNode', 'CfgNode', ([], {}), '()\n', (8539, 8541), False, 'from yacs.config import CfgNode\n'), ((8762, 8771), 'yacs.config.CfgNode', 'CfgNode', ([], {}), '()\n', (8769, 8771), False, 'from yacs.config import CfgNode\n'), ((9021, 9030), 'yacs.config.CfgNode', 'CfgNode', ([], {}), '()\n', (9028, 9030), False, 'from yacs.config import CfgNode\n'), ((12600, 12637), 'os.path.join', 'os.path.join', (['_C.OUT_DIR', '_C.CFG_DEST'], {}), '(_C.OUT_DIR, _C.CFG_DEST)\n', (12612, 12637), False, 'import os\n'), ((12647, 12674), 'pycls.core.io.pathmgr.open', 'pathmgr.open', (['cfg_file', '"""w"""'], {}), "(cfg_file, 'w')\n", (12659, 12674), False, 'from pycls.core.io import pathmgr\n'), ((12806, 12833), 'pycls.core.io.pathmgr.open', 'pathmgr.open', (['cfg_file', '"""r"""'], {}), "(cfg_file, 'r')\n", (12818, 12833), False, 'from pycls.core.io import pathmgr\n')] |
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import os
import threading
from parl.remote import Master, Worker
def main(args):
"""Start a master or a worker through:
1. xparl start --port 1234
2. xparl connect --address localhost:1234 --cpu_num 8
"""
if args.name == 'master':
port = args.port
master = Master(port)
master.run()
elif args.name == 'worker':
address = args.address
cpu_num = int(args.cpu_num) if args.cpu_num else None
worker = Worker(address, cpu_num)
worker.run()
else:
raise NotImplementedError
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
'--name', default='master', type=str, help='master/worker')
parser.add_argument('--port', default='1234', type=str)
parser.add_argument('--address', default='localhost:1234', type=str)
parser.add_argument('--cpu_num', default='', type=str)
args = parser.parse_args()
main(args)
| [
"parl.remote.Master",
"parl.remote.Worker",
"argparse.ArgumentParser"
] | [((1238, 1263), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1261, 1263), False, 'import argparse\n'), ((928, 940), 'parl.remote.Master', 'Master', (['port'], {}), '(port)\n', (934, 940), False, 'from parl.remote import Master, Worker\n'), ((1105, 1129), 'parl.remote.Worker', 'Worker', (['address', 'cpu_num'], {}), '(address, cpu_num)\n', (1111, 1129), False, 'from parl.remote import Master, Worker\n')] |
"""
Combat Manager. This is where the magic happens. And by magic,
we mean characters dying, most likely due to vile sorcery.
The Combat Manager is invoked by a character starting combat
with the +fight command. Anyone set up as a defender of either
of those two characters is pulled into combat automatically.
Otherwise, players can enter into combat that is in progress
with the appropriate defend command, or by a +fight command
to attack one of the belligerent parties.
Turn based combat has the obvious drawback that someone who
is AFK or deliberately not taking their turn completely halts
the action. There isn't an easy solution to this. GMs will
have tools to skip someone's turn or remove them from combat,
and a majority vote by all parties can cause a turn to proceed
even when someone has not taken their turn.
Phase 1 is the setup phase. This phase is designed to have a
pause before deciding actions so that other people can join
combat. Characters who join in later phases will not receive
a combat turn, and will be added to the fight in the following
turn. Phase 1 is also when players can vote to end the combat.
Every player MUST enter a command to continue for combat to
proceed. There will never be a case where a character can be
AFK and in combat. It is possible to vote a character out of
combat due to AFK in order for things to proceed. Immediately
after every current combatant selects to continue, the participants
are locked in and we go to phase 2.
Phase 2 is the action phase. Initiative is rolled, and then
each player must take an action when it is their turn. 'pass'
is a valid action. Each combat action is resolved during the
character's turn. Characters who are incapacitated lose their
action. Characters who join combat during Phase 2 must wait
for the following turn to be allowed a legal action.
"""
import time
from operator import attrgetter
from evennia.utils.utils import fill, dedent
from server.utils.prettytable import PrettyTable
from server.utils.arx_utils import list_to_string
from typeclasses.scripts.combat import combat_settings
from typeclasses.scripts.combat.state_handler import CombatantStateHandler
from typeclasses.scripts.scripts import Script as BaseScript
COMBAT_INTRO = combat_settings.COMBAT_INTRO
PHASE1_INTRO = combat_settings.PHASE1_INTRO
PHASE2_INTRO = combat_settings.PHASE2_INTRO
MAX_AFK = combat_settings.MAX_AFK
ROUND_DELAY = combat_settings.ROUND_DELAY
class CombatManager(BaseScript):
"""
Players are added via add_combatant or add_observer. These are invoked
by commands in normal commandsets. Characters added receive the combat
commandset, which give commands that invoke the other methods.
Turns proceed based on every combatant submitting an action, which is a
dictionary of combatant IDs to their actions. Dead characters are moved
to observer status, incapacitated characters are moved to a special
list to denote that they're still in combat but can take no action.
Attribute references to the combat manager script are stored in the room
location under room.ndb.combat_manager, and inside each character in the
combat under character.ndb.combat_manager.
Note that all the data for the combat manager is stored inside non-database
attributes, since it is designed to be non-persistent. If there's a server
reset, combat will end.
Non-database attributes:
self.ndb.combatants - list of everyone active in the fight. If it's empty, combat ends
self.ndb.observers - People passively watching the fight
self.ndb.incapacitated - People who are too injured to act, but still can be attacked
self.ndb.fighter_data - CharacterCombatData for each combatant. dict with character.id as keys
self.ndb.combat_location - room where script happens
self.ndb.initiative_list - CharacterCombatData for each fighter. incapacitated chars aren't in it
self.ndb.active_character - Current turn of player in phase 2. Not used in phase 1
self.ndb.phase - Phase 1 or 2. 1 is setup, 2 is resolution
self.ndb.afk_check - anyone we're checking to see if they're afk
self.ndb.votes_to_end - anyone voting to end combat
self.ndb.flee_success - Those who can run this turn
self.ndb.fleeing - Those intending to try to run
Admin Methods:
self.msg() - Message to all combatants/observers.
self.end_combat() - shut down the fight
self.next_character_turn() - move to next character in initiative list in phase 2
self.add_observer(character)
self.add_combatant(character)
self.remove_combatant(character)
self.move_to_observer(character)
"""
# noinspection PyAttributeOutsideInit
def at_script_creation(self):
"""
Setup the script
"""
self.key = "CombatManager"
self.desc = "Manages the combat state for a group of combatants"
# Not persistent because if someone goes LD, we don't want them reconnecting
# in combat a week later with no way to leave it. Intentionally quitting out
# to avoid combat will just need to be corrected with rules enforcement.
self.persistent = False
self.interval = ROUND_DELAY
self.start_delay = True
self.ndb.combatants = [] # those actively involved in fight
self.ndb.observers = [] # sent combat data, but cannot act
self.ndb.combat_location = self.obj # room of the fight
self.ndb.initiative_list = [] # CharacterCombatData of characters in order of initiative
self.ndb.active_character = None # who is currently acting during phase 2
self.ndb.phase = 1
self.ndb.afk_check = [] # characters who are flagged afk until they take an action
self.ndb.votes_to_end = [] # if all characters vote yes, combat ends
self.ndb.flee_success = [] # if we're here, the character is allowed to flee on their turn
self.ndb.fleeing = [] # if we're here, they're attempting to flee but haven't rolled yet
self.ndb.ready = [] # those ready for phase 2
self.ndb.not_ready = [] # not ready for phase 2
self.ndb.surrender_list = [] # peoeple trying to surrender
self.ndb.affect_real_dmg = not self.obj.tags.get("nonlethal_combat")
self.ndb.random_deaths = not self.obj.tags.get("no_random_deaths")
self.ndb.max_rounds = 250
self.ndb.rounds = 0
# to ensure proper shutdown, prevent some timing errors
self.ndb.shutting_down = False
self.ndb.status_table = None
self.ndb.initializing = True
if self.obj.event:
self.ndb.risk = self.obj.event.risk
else:
self.ndb.risk = 4
self.ndb.special_actions = []
self.ndb.gm_afk_counter = 0
@property
def status_table(self):
"""text table of the combat"""
if not self.ndb.status_table:
self.build_status_table()
return self.ndb.status_table
def at_repeat(self):
"""Called at the script timer interval"""
if self.check_if_combat_should_end():
return
# reset the script timers
if self.ndb.shutting_down:
return
# proceed to combat
if self.ndb.phase == 1:
self.ready_check()
self.msg("Use {w+cs{n to see the current combat status.")
self.remove_surrendering_characters()
def is_valid(self):
"""
Check if still has combatants. Incapacitated characters are still
combatants, just with very limited options - they can either pass
turn or vote to end the fight. The fight ends when all combatants
either pass they turn or choose to end. Players can be forced out
of active combat if they are AFK, moved to observer status.
"""
if self.ndb.shutting_down:
return False
if self.ndb.combatants:
return True
if self.ndb.initializing:
return True
return False
# ----Methods for passing messages to characters-------------
@staticmethod
def send_intro_message(character, combatant=True):
"""
Displays intro message of combat to character
"""
if not combatant:
msg = fill("{mYou are now in observer mode for a fight. {n" +
"Most combat commands will not function. To " +
"join the fight, use the {w+fight{n command.")
else:
msg = "{rEntering combat mode.{n\n"
msg += "\n\n" + fill(COMBAT_INTRO)
character.msg(msg)
return
def display_phase_status(self, character, disp_intro=True):
"""
Gives message based on the current combat phase to character.cmdset
In phase 1, just list combatants and observers, anyone marked AFK,
dead, whatever, and any votes to end.
In phase 2, list initiative order and who has the current action.
"""
if self.ndb.shutting_down:
return
msg = ""
if self.ndb.phase == 1:
if disp_intro:
msg += PHASE1_INTRO + "\n"
msg += str(self.status_table) + "\n"
vote_str = self.vote_string
if vote_str:
msg += vote_str + "\n"
elif self.ndb.phase == 2:
if disp_intro:
msg += PHASE2_INTRO + "\n"
msg += str(self.status_table) + "\n"
msg += self.get_initiative_list() + "\n"
msg += "{wCurrent Round:{n %d" % self.ndb.rounds
character.msg(msg)
def build_status_table(self):
"""Builds a table of the status of combatants"""
combatants = sorted(self.ndb.combatants)
table = PrettyTable(["{wCombatant{n", "{wDamage{n", "{wFatigue{n", "{wAction{n", "{wReady?{n"])
for state in combatants:
name = state.combat_handler.name
dmg = state.character.get_wound_descriptor(state.character.dmg)
fatigue = str(state.fatigue_penalty)
action = "None" if not state.queued_action else state.queued_action.table_str
rdy = "yes" if state.ready else "{rno{n"
table.add_row([name, dmg, fatigue, action, rdy])
self.ndb.status_table = table
def display_phase_status_to_all(self, intro=False):
"""Sends status to all characters in or watching the fight"""
msglist = set([ob.character for ob in self.ndb.combatants] + self.ndb.observers)
self.build_status_table()
self.ready_check()
for ob in msglist:
self.display_phase_status(ob, disp_intro=intro)
def msg(self, message, exclude=None, options=None):
"""
Sends a message to all objects in combat/observers except for
individuals in the exclude list.
"""
# those in incapacitated list should still be in combatants also
msglist = [ob.character for ob in self.ndb.combatants] + self.ndb.observers
if not exclude:
exclude = []
msglist = [ob for ob in msglist if ob not in exclude]
for ob in msglist:
mymsg = message
ob.msg(mymsg, options)
# ---------------------------------------------------------------------
# -----Admin Methods for OOC character status: adding, removing, etc----
def check_character_is_combatant(self, character):
"""Returns True if the character is one of our combatants."""
try:
state = character.combat.state
return state and state in self.ndb.combatants
except AttributeError:
return False
def add_combatant(self, character, adder=None, reset=False):
"""
Adds a character to combat. The adder is the character that started
the process, and the return message is sent to them. We return None
if they're already fighting, since then it's likely a state change
in defending or so on, and messages will be sent from elsewhere.
"""
# if we're already fighting, nothing happens
cdata = character.combat
if adder:
adder_state = adder.combat.state
else:
adder_state = None
if self.check_character_is_combatant(character):
if character == adder:
return "You are already in the fight."
if cdata.state and adder:
cdata.state.add_foe(adder)
if adder_state:
adder_state.add_foe(character)
return "%s is already fighting." % character.key
# check if attackable
if not character.attackable:
return "%s is not attackable." % character.key
if character.location != self.obj:
return "%s is not in the same room as the fight." % character.key
# if we were in observer list, we stop since we're participant now
self.remove_observer(character)
self.send_intro_message(character)
# add combat state to list of combatants
if character not in self.characters_in_combat:
CombatantStateHandler(character, self, reset=reset)
if character == adder:
return "{rYou have entered combat.{n"
# if we have an adder, they're fighting one another. set targets
elif self.check_character_is_combatant(adder):
# make sure adder is a combatant, not a GM
cdata.state.add_foe(adder)
cdata.state.prev_targ = adder
adder_state.add_foe(character)
adder_state.prev_targ = character
adder_state.setup_attacks()
cdata.state.setup_attacks()
return "You have added %s to a fight." % character.name
@property
def characters_in_combat(self):
"""Returns characters from our combat states"""
return [ob.character for ob in self.ndb.combatants]
def register_state(self, state):
"""
Stores reference to a CombatantStateHandler in self.ndb.combatants. Called by CombatantStateHandler's init,
done this way to avoid possible infinite recursion
"""
if state not in self.ndb.combatants:
self.ndb.combatants.append(state)
def finish_initialization(self):
"""
Finish the initial setup of combatants we add
"""
self.ndb.initializing = False
self.reset_combatants()
self.display_phase_status_to_all(intro=True)
def reset_combatants(self):
"""Resets all our combatants for the next round, displaying prep message to them"""
for state in self.ndb.combatants:
state.reset()
for state in self.ndb.combatants:
state.setup_phase_prep()
def check_if_combat_should_end(self):
"""Checks if combat should be over"""
if not self or not self.pk or self.ndb.shutting_down:
self.end_combat()
return True
if not self.ndb.combatants and not self.ndb.initializing and self.managed_mode_permits_ending():
self.msg("No combatants found. Exiting.")
self.end_combat()
return True
active_combatants = [ob for ob in self.ndb.combatants if ob.conscious]
active_fighters = [ob for ob in active_combatants if not (ob.automated and ob.queued_action and
ob.queued_action.qtype == "Pass")]
if not active_fighters and not self.ndb.initializing:
if self.managed_mode_permits_ending():
self.msg("All combatants are incapacitated or automated npcs who are passing their turn. Exiting.")
self.end_combat()
return True
def managed_mode_permits_ending(self):
"""If we're in managed mode, increment a counter of how many checks before we decide it's idle and end"""
if not self.managed_mode:
return True
if self.ndb.gm_afk_counter > 3:
return True
self.ndb.gm_afk_counter += 1
return False
def ready_check(self, checker=None):
"""
Check all combatants. If all ready, move to phase 2. If checker is
set, it's a character who is already ready but is using the command
to see a list of who might not be, so the message is only sent to them.
"""
self.ndb.ready = []
self.ndb.not_ready = []
if self.ndb.phase == 2:
# already in phase 2, do nothing
return
for state in self.ndb.combatants:
if state.ready:
self.ndb.ready.append(state.character)
elif not state.conscious:
self.ndb.ready.append(state.character)
else:
self.ndb.not_ready.append(state.character)
if self.ndb.not_ready: # not ready for phase 2, tell them why
if checker:
self.display_phase_status(checker, disp_intro=False)
else:
try:
self.start_phase_2()
except ValueError:
import traceback
traceback.print_exc()
self.end_combat()
def afk_check(self, checking_char, char_to_check):
"""
Prods a character to make a response. If the character is not in the
afk_check list, we add them and send them a warning message, then update
their combat data with the AFK timer. Subsequent checks are votes to
kick the player if they have been AFK longer than a given idle timer.
Any action removes them from AFK timer and resets the AFK timer in their
combat data as well as removes all votes there.
"""
# No, they can't vote themselves AFK as a way to escape combat
if checking_char == char_to_check:
checking_char.msg("You cannot vote yourself AFK to leave combat.")
return
if self.ndb.phase == 1 and char_to_check.combat.state.ready:
checking_char.msg("That character is ready to proceed " +
"with combat. They are not holding up the fight.")
return
if self.ndb.phase == 2 and not self.ndb.active_character == char_to_check:
checking_char.msg("It is not their turn to act. You may only " +
"vote them AFK if they are holding up the fight.")
return
if char_to_check not in self.ndb.afk_check:
msg = "{w%s is checking if you are AFK. Please take" % checking_char.name
msg += " an action within a few minutes.{n"
char_to_check.msg(msg)
checking_char.msg("You have nudged %s to take an action." % char_to_check.name)
self.ndb.afk_check.append(char_to_check)
char_to_check.combat.state.afk_timer = time.time() # current time
return
# character is in the AFK list. Check if they've been gone long enough to vote against
elapsed_time = time.time() - char_to_check.combat.state.afk_timer
if elapsed_time < MAX_AFK:
msg = "It has been %s since %s was first checked for " % (elapsed_time, char_to_check.name)
msg += "AFK. They have %s seconds to respond before " % (MAX_AFK - elapsed_time)
msg += "votes can be lodged against them to remove them from combat."
checking_char.msg(msg)
return
# record votes. if we have enough votes, boot 'em.
votes = char_to_check.combat.state.votes_to_kick
if checking_char in votes:
checking_char.msg("You have already voted for their removal. Every other player " +
"except for %s must vote for their removal." % char_to_check.name)
return
votes.append(checking_char)
if votes >= len(self.ndb.combatants) - 1:
self.msg("Removing %s from combat due to inactivity." % char_to_check.name)
self.move_to_observer(char_to_check)
return
char_to_check.msg("A vote has been lodged for your removal from combat due to inactivity.")
def remove_afk(self, character):
"""
Removes a character from the afk_check list after taking a combat
action. Resets relevant fields in combat data
"""
if character in self.ndb.afk_check:
self.ndb.afk_check.remove(character)
character.combat.state.afk_timer = None
character.combat.state.votes_to_kick = []
character.msg("You are no longer being checked for AFK.")
return
def move_to_observer(self, character):
"""
If a character is marked AFK or dies, they are moved from the
combatant list to the observer list.
"""
self.remove_combatant(character)
self.add_observer(character)
def remove_combatant(self, character, in_shutdown=False):
"""
Remove a character from combat altogether. Do a ready check if
we're in phase one.
"""
state = character.combat.state
self.clear_lists_of_character(character)
if state in self.ndb.combatants:
self.ndb.combatants.remove(state)
if state:
state.leave_combat()
# if we're already shutting down, avoid redundant messages
if len(self.ndb.combatants) < 2 and not in_shutdown:
# We weren't shutting down and don't have enough fighters to continue. end the fight.
self.end_combat()
return
if self.ndb.phase == 1 and not in_shutdown:
self.ready_check()
return
if self.ndb.phase == 2 and not in_shutdown:
if state in self.ndb.initiative_list:
self.ndb.initiative_list.remove(state)
return
if self.ndb.active_character == character:
self.next_character_turn()
def clear_lists_of_character(self, character):
"""Removes a character from any of the lists they might be in"""
if character in self.ndb.fleeing:
self.ndb.fleeing.remove(character)
if character in self.ndb.afk_check:
self.ndb.afk_check.remove(character)
if character in self.ndb.surrender_list:
self.ndb.surrender_list.remove(character)
def add_observer(self, character):
"""
Character becomes a non-participating observer. This is usually
for GMs who are watching combat, but other players may be moved
to this - dead characters are no longer combatants, nor are
characters who have been marked as AFK.
"""
# first make sure that any other combat they're watching removes them as a spectator
currently_spectating = character.combat.spectated_combat
if currently_spectating and currently_spectating != self:
currently_spectating.remove_observer(character)
# now we start them spectating
character.combat.spectated_combat = self
self.send_intro_message(character, combatant=False)
self.display_phase_status(character, disp_intro=False)
if character not in self.ndb.observers:
self.ndb.observers.append(character)
return
def remove_observer(self, character, quiet=True):
"""
Leave observer list, either due to stop observing or due to
joining the fight
"""
character.combat.spectated_combat = None
if character in self.ndb.observers:
character.msg("You stop spectating the fight.")
self.ndb.observers.remove(character)
return
if not quiet:
character.msg("You were not an observer, but stop anyway.")
def build_initiative_list(self):
"""
Rolls initiative for each combatant, resolves ties, adds them
to list in order from first to last. Sets current character
to first character in list.
"""
fighter_states = self.ndb.combatants
for fighter in fighter_states:
fighter.roll_initiative()
self.ndb.initiative_list = sorted([data for data in fighter_states
if data.can_act],
key=attrgetter('initiative', 'tiebreaker'),
reverse=True)
def get_initiative_list(self):
"""Displays who the acting character is and the remaining order"""
acting_char = self.ndb.active_character
msg = ""
if acting_char:
msg += "{wIt is {c%s's {wturn.{n " % acting_char.name
if self.ndb.initiative_list:
msg += "{wTurn order for remaining characters:{n %s" % list_to_string(self.ndb.initiative_list)
return msg
def next_character_turn(self):
"""
It is now a character's turn in the iniative list. They will
be prompted to take an action. If there is no more characters,
end the turn when this is called and start over at Phase 1.
"""
if self.ndb.shutting_down:
return
if self.ndb.phase != 2:
return
self.ndb.initiative_list = [ob for ob in self.ndb.initiative_list if ob.can_act and ob.remaining_attacks > 0]
if not self.ndb.initiative_list:
self.start_phase_1()
self.display_phase_status_to_all()
return
character_state = self.ndb.initiative_list.pop(0)
acting_char = character_state.character
self.ndb.active_character = acting_char
# check if they went LD, teleported, or something
if acting_char.location != self.ndb.combat_location:
self.msg("%s is no longer here. Removing them from combat." % acting_char.name)
self.remove_combatant(acting_char)
return self.next_character_turn()
# For when we put in subdue/hostage code
elif not character_state.can_act:
acting_char.msg("It would be your turn, but you cannot act. Passing your turn.")
self.msg("%s cannot act." % acting_char.name, exclude=[acting_char])
return self.next_character_turn()
# turns lost from botches or other effects
elif character_state.lost_turn_counter > 0:
character_state.remaining_attacks -= 1
character_state.lost_turn_counter -= 1
if character_state.remaining_attacks == 0:
acting_char.msg("It would be your turn, but you are recovering from a botch. Passing.")
self.msg("%s is recovering from a botch and loses their turn." % acting_char.name,
exclude=[acting_char])
return self.next_character_turn()
self.msg("{wIt is now{n {c%s's{n {wturn.{n" % acting_char.name, exclude=[acting_char])
if self.managed_mode:
return self.send_managed_mode_prompt()
result = character_state.do_turn_actions()
if not result and self.ndb.phase == 2:
mssg = dedent("""
It is now {wyour turn{n to act in combat. Please give a little time to make
sure other players have finished their poses or emits before you select
an action. For your character's action, you may either pass your turn
with the {wpass{n command, or execute a command like {wattack{n. Once you
have executed your command, control will pass to the next character, but
please describe the results of your action with appropriate poses.
""")
acting_char.msg(mssg)
def start_phase_1(self):
"""
Setup for phase 1, the 'setup' phase. We'll mark all current
combatants as being non-ready. Characters will need to hit the
'continue' command to be marked as ready. Once all combatants
have done so, we move to phase 2. Alternately, everyone can
vote to end the fight, and then we're done.
"""
if self.ndb.shutting_down:
return
self.remove_surrendering_characters()
self.ndb.phase = 1
self.ndb.active_character = None
self.ndb.votes_to_end = []
allchars = self.ndb.combatants + self.ndb.observers
if not allchars:
return
self.reset_combatants()
self.ndb.rounds += 1
if self.ndb.rounds >= self.ndb.max_rounds:
self.end_combat()
self.msg("{ySetup Phase{n")
def start_phase_2(self):
"""
Setup for phase 2, the 'resolution' phase. We build the list
for initiative, which will be a list of CombatCharacterData
objects from self.ndb.fighter_data.values(). Whenever it comes
to a character's turn, they're popped from the front of the
list, and it remains their turn until they take an action.
Any action they take will call the next_character_turn() to
proceed, and when there are no more characters, we go back
to phase 1.
"""
if self.ndb.shutting_down:
return
self.ndb.phase = 2
# determine who can flee this turn
self.ndb.flee_success = []
# if they were attempting to flee last turn, roll for them
for char in self.ndb.fleeing:
c_fite = char.combat
if c_fite.state.roll_flee_success(): # they can now flee
self.ndb.flee_success.append(char)
self.remove_fled_characters()
if self.ndb.shutting_down:
return
self.msg("{yResolution Phase{n")
self.build_initiative_list()
self.next_character_turn()
def remove_fled_characters(self):
"""Checks characters who fled and removes them"""
for char in self.all_combatant_characters:
if char.location != self.ndb.combat_location:
self.remove_combatant(char)
continue
def vote_to_end(self, character):
"""
Allows characters to vote to bring the fight to a conclusion.
"""
mess = ""
try:
self.register_vote_to_end(character)
mess = "%s has voted to end the fight.\n" % character.name
except combat_settings.CombatError as err:
character.msg(err)
if self.check_sufficient_votes_to_end():
return
mess += self.vote_string
if mess:
self.msg(mess)
def register_vote_to_end(self, character):
"""
If eligible to vote for an end to combat, appends our state to a tally.
"""
state = character.combat.state
if state not in self.ndb.combatants:
raise combat_settings.CombatError("Only participants in the fight may vote to end it.")
elif state in self.ndb.votes_to_end:
raise combat_settings.CombatError("You have already voted to end the fight.")
else:
self.ndb.votes_to_end.append(state)
def check_sufficient_votes_to_end(self):
"""
Messages and ends combat if everyone has voted to do so.
"""
if not self.not_voted:
self.msg("All participants have voted to end combat.")
self.end_combat()
return True
@property
def not_voted(self):
"""List of combat states who voted to end"""
not_voted = [ob for ob in self.ndb.combatants if ob and ob not in self.ndb.votes_to_end]
# only let conscious people vote
not_voted = [ob for ob in not_voted if ob.can_fight and not ob.wants_to_end]
return not_voted
@property
def vote_string(self):
"""Get string of any who have voted to end, and who still has to vote for combat to end"""
mess = ""
if self.ndb.votes_to_end:
mess += "{wCurrently voting to end combat:{n %s\n" % list_to_string(self.ndb.votes_to_end)
mess += "{wFor the fight to end, the following characters must also use +end_combat:{n "
mess += "%s" % list_to_string(self.not_voted)
return mess
# noinspection PyBroadException
def end_combat(self):
"""
Shut down combat.
"""
self.msg("Ending combat.")
self.ndb.shutting_down = True
for char in self.all_combatant_characters:
self.remove_combatant(char, in_shutdown=True)
for char in self.ndb.observers[:]:
self.remove_observer(char)
self.obj.ndb.combat_manager = None
try:
self.stop() # delete script
except Exception:
import traceback
traceback.print_exc()
@property
def all_combatant_characters(self):
"""All characters from the states saved in combatants"""
return [ob.character for ob in self.ndb.combatants]
def register_surrendering_character(self, character):
"""
Adds a character to the surrender list.
Args:
character: Character who wants to surrender
Returns:
True if successfully added, False otherwise
"""
if self.check_surrender_prevent(character):
return
self.ndb.surrender_list.append(character)
return True
def check_surrender_prevent(self, character):
"""
Checks if character is prevented from surrendering
Args:
character: Character who is trying to surrender
Returns:
True if character is prevented, False otherwise
"""
for state in self.ndb.combatants:
if character in state.prevent_surrender_list:
return True
return False
def remove_surrendering_characters(self):
"""
Check our surrendering characters, remove them from combat if not prevented
"""
for character in self.ndb.surrender_list[:]:
if self.check_surrender_prevent(character):
self.ndb.surrender_list.remove(character)
return
self.remove_combatant(character)
@property
def special_actions(self):
"""GM defined actions that players can take"""
return self.ndb.special_actions
def add_special_action(self, name, stat="", skill="", difficulty=15):
"""Adds a new special action recognized by the combat that players can choose to do"""
from .special_actions import ActionByGM
self.special_actions.append(ActionByGM(combat=self, name=name, stat=stat, skill=skill,
difficulty=difficulty))
def list_special_actions(self):
"""Gets string display of GM-defined special actions"""
msg = "Current Actions:\n"
table = PrettyTable(["#", "Name", "Stat", "Skill", "Difficulty"])
for num, action in enumerate(self.special_actions, 1):
table.add_row([num, action.name, action.stat, action.skill, action.difficulty])
return msg + str(table)
def list_rolls_for_special_actions(self):
"""Gets string display of all rolls players have made for GM-defined special actions"""
actions = self.get_current_and_queued_actions()
actions = [ob for ob in actions if ob.special_action in self.special_actions]
table = PrettyTable(["Name", "Action", "Roll"])
for action in actions:
table.add_row([str(action.character), str(action.special_action), action.display_roll()])
return str(table)
def get_current_and_queued_actions(self):
"""Returns list of current actions for each combatant"""
actions = []
for state in self.ndb.combatants:
actions.extend(state.get_current_and_queued_actions())
return actions
def make_all_checks_for_special_action(self, special_action):
"""Given a special action, make checks for all corresponding queued actions"""
pc_actions = [ob for ob in self.get_current_and_queued_actions() if ob.special_action == special_action]
special_action.make_checks(pc_actions)
@property
def managed_mode(self):
"""Whether or not a GM controls combat pacing"""
return self.ndb.managed_mode
@managed_mode.setter
def managed_mode(self, value):
self.ndb.managed_mode = value
def send_managed_mode_prompt(self):
"""Notifies GMs that we're waiting on them to evaluate the character's turn."""
character = self.ndb.active_character
msg = "%s's current action: %s\n" % (character, character.combat.state.get_action_description())
msg += "Use @admin_combat/roll to make a check, /execute to perform their action, and /next to mark resolved."
self.msg_gms(msg)
def msg_gms(self, message):
"""Sends a message to current GMs for this combat."""
for gm in self.gms:
gm.msg(message)
def add_gm(self, character):
"""Adds a character to our list of gms."""
if character not in self.gms:
self.gms.append(character)
@property
def gms(self):
"""Characters who have admin powers for this combat."""
if self.ndb.gms is None:
self.ndb.gms = []
return self.ndb.gms
| [
"operator.attrgetter",
"evennia.utils.utils.fill",
"typeclasses.scripts.combat.state_handler.CombatantStateHandler",
"typeclasses.scripts.combat.combat_settings.CombatError",
"server.utils.arx_utils.list_to_string",
"server.utils.prettytable.PrettyTable",
"traceback.print_exc",
"time.time",
"evennia... | [((9754, 9845), 'server.utils.prettytable.PrettyTable', 'PrettyTable', (["['{wCombatant{n', '{wDamage{n', '{wFatigue{n', '{wAction{n', '{wReady?{n']"], {}), "(['{wCombatant{n', '{wDamage{n', '{wFatigue{n', '{wAction{n',\n '{wReady?{n'])\n", (9765, 9845), False, 'from server.utils.prettytable import PrettyTable\n'), ((34817, 34874), 'server.utils.prettytable.PrettyTable', 'PrettyTable', (["['#', 'Name', 'Stat', 'Skill', 'Difficulty']"], {}), "(['#', 'Name', 'Stat', 'Skill', 'Difficulty'])\n", (34828, 34874), False, 'from server.utils.prettytable import PrettyTable\n'), ((35363, 35402), 'server.utils.prettytable.PrettyTable', 'PrettyTable', (["['Name', 'Action', 'Roll']"], {}), "(['Name', 'Action', 'Roll'])\n", (35374, 35402), False, 'from server.utils.prettytable import PrettyTable\n'), ((8273, 8431), 'evennia.utils.utils.fill', 'fill', (["('{mYou are now in observer mode for a fight. {n' +\n 'Most combat commands will not function. To ' +\n 'join the fight, use the {w+fight{n command.')"], {}), "('{mYou are now in observer mode for a fight. {n' +\n 'Most combat commands will not function. To ' +\n 'join the fight, use the {w+fight{n command.')\n", (8277, 8431), False, 'from evennia.utils.utils import fill, dedent\n'), ((13127, 13178), 'typeclasses.scripts.combat.state_handler.CombatantStateHandler', 'CombatantStateHandler', (['character', 'self'], {'reset': 'reset'}), '(character, self, reset=reset)\n', (13148, 13178), False, 'from typeclasses.scripts.combat.state_handler import CombatantStateHandler\n'), ((18876, 18887), 'time.time', 'time.time', ([], {}), '()\n', (18885, 18887), False, 'import time\n'), ((19041, 19052), 'time.time', 'time.time', ([], {}), '()\n', (19050, 19052), False, 'import time\n'), ((27124, 27665), 'evennia.utils.utils.dedent', 'dedent', (['"""\n It is now {wyour turn{n to act in combat. Please give a little time to make\n sure other players have finished their poses or emits before you select\n an action. For your character\'s action, you may either pass your turn\n with the {wpass{n command, or execute a command like {wattack{n. Once you\n have executed your command, control will pass to the next character, but\n please describe the results of your action with appropriate poses.\n """'], {}), '(\n """\n It is now {wyour turn{n to act in combat. Please give a little time to make\n sure other players have finished their poses or emits before you select\n an action. For your character\'s action, you may either pass your turn\n with the {wpass{n command, or execute a command like {wattack{n. Once you\n have executed your command, control will pass to the next character, but\n please describe the results of your action with appropriate poses.\n """\n )\n', (27130, 27665), False, 'from evennia.utils.utils import fill, dedent\n'), ((30774, 30860), 'typeclasses.scripts.combat.combat_settings.CombatError', 'combat_settings.CombatError', (['"""Only participants in the fight may vote to end it."""'], {}), "(\n 'Only participants in the fight may vote to end it.')\n", (30801, 30860), False, 'from typeclasses.scripts.combat import combat_settings\n'), ((8560, 8578), 'evennia.utils.utils.fill', 'fill', (['COMBAT_INTRO'], {}), '(COMBAT_INTRO)\n', (8564, 8578), False, 'from evennia.utils.utils import fill, dedent\n'), ((24344, 24382), 'operator.attrgetter', 'attrgetter', (['"""initiative"""', '"""tiebreaker"""'], {}), "('initiative', 'tiebreaker')\n", (24354, 24382), False, 'from operator import attrgetter\n'), ((24810, 24850), 'server.utils.arx_utils.list_to_string', 'list_to_string', (['self.ndb.initiative_list'], {}), '(self.ndb.initiative_list)\n', (24824, 24850), False, 'from server.utils.arx_utils import list_to_string\n'), ((30919, 30990), 'typeclasses.scripts.combat.combat_settings.CombatError', 'combat_settings.CombatError', (['"""You have already voted to end the fight."""'], {}), "('You have already voted to end the fight.')\n", (30946, 30990), False, 'from typeclasses.scripts.combat import combat_settings\n'), ((31939, 31976), 'server.utils.arx_utils.list_to_string', 'list_to_string', (['self.ndb.votes_to_end'], {}), '(self.ndb.votes_to_end)\n', (31953, 31976), False, 'from server.utils.arx_utils import list_to_string\n'), ((32105, 32135), 'server.utils.arx_utils.list_to_string', 'list_to_string', (['self.not_voted'], {}), '(self.not_voted)\n', (32119, 32135), False, 'from server.utils.arx_utils import list_to_string\n'), ((32697, 32718), 'traceback.print_exc', 'traceback.print_exc', ([], {}), '()\n', (32716, 32718), False, 'import traceback\n'), ((17154, 17175), 'traceback.print_exc', 'traceback.print_exc', ([], {}), '()\n', (17173, 17175), False, 'import traceback\n')] |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 22 23:31:26 2018
@author: <NAME>
@title: MNIST Image classification using RNN - LSTM
Developed as part of Cognitive Class - Deep Learning with Tensorflow class
"""
import warnings
warnings.filterwarnings('ignore')
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets(".", one_hot=True)
# Train Test Split
trainimgs = mnist.train.images
trainlabels = mnist.train.labels
testimgs = mnist.test.images
testlabels = mnist.test.labels
ntrain = trainimgs.shape[0]
ntest = testimgs.shape[0]
dim = trainimgs.shape[1]
nclasses = trainlabels.shape[1]
print("Train Images: ", trainimgs.shape)
print("Train Labels ", trainlabels.shape)
print()
print("Test Images: " , testimgs.shape)
print("Test Labels: ", testlabels.shape)
# Sample Viewing
#samplesIdx = [100, 101, 102] #<-- You can change these numbers here to see other samples
#
#from mpl_toolkits.mplot3d import Axes3D
#fig = plt.figure()
#
#ax1 = fig.add_subplot(121)
#ax1.imshow(testimgs[samplesIdx[0]].reshape([28,28]), cmap='gray')
#
#
#xx, yy = np.meshgrid(np.linspace(0,28,28), np.linspace(0,28,28))
#X = xx ; Y = yy
#Z = 100*np.ones(X.shape)
#
#img = testimgs[77].reshape([28,28])
#ax = fig.add_subplot(122, projection='3d')
#ax.set_zlim((0,200))
#
#
#offset=200
#for i in samplesIdx:
# img = testimgs[i].reshape([28,28]).transpose()
# ax.contourf(X, Y, img, 200, zdir='z', offset=offset, cmap="gray")
# offset -= 100
#
# ax.set_xticks([])
#ax.set_yticks([])
#ax.set_zticks([])
#
#plt.show()
#
#
#for i in samplesIdx:
# print("Sample: {0} - Class: {1} - Label Vector: {2} ".format(i, np.nonzero(testlabels[i])[0], testlabels[i]))
# Parameter Declaration - RNN
n_input = 28 # MNIST data input (img shape: 28*28)
n_steps = 28 # timesteps
n_hidden = 128 # hidden layer num of features
n_classes = 10 # MNIST total classes (0-9 digits)
# Count Declaration
learning_rate = 0.001
training_iters = 100000
batch_size = 100
display_step = 10
# Input and Output Layer
x = tf.placeholder(dtype="float", shape=[None, n_steps, n_input], name="x") # Current data input shape: (batch_size, n_steps, n_input) [100x28x28]
y = tf.placeholder(dtype="float", shape=[None, n_classes], name="y")
# Weights and Biases
weights = {
'out': tf.Variable(tf.random_normal([n_hidden, n_classes]))
}
biases = {
'out': tf.Variable(tf.random_normal([n_classes]))
}
# LSTM Cell
lstm_cell = tf.contrib.rnn.BasicLSTMCell(n_hidden, forget_bias=1.0)
# RNN
outputs, states = tf.nn.dynamic_rnn(lstm_cell, inputs=x, dtype=tf.float32)
output = tf.reshape(tf.split(outputs, 28, axis=1, num=None, name='split')[-1],[-1,128])
pred = tf.matmul(output, weights['out']) + biases['out']
#pred
# Cost Function and Optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=pred ))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
# Accuracy
correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
init = tf.global_variables_initializer()
# Training and Testing
with tf.Session() as sess:
sess.run(init)
step = 1
# Keep training until reach max iterations
while step * batch_size < training_iters:
# We will read a batch of 100 images [100 x 784] as batch_x
# batch_y is a matrix of [100x10]
batch_x, batch_y = mnist.train.next_batch(batch_size)
# We consider each row of the image as one sequence
# Reshape data to get 28 seq of 28 elements, so that, batxh_x is [100x28x28]
batch_x = batch_x.reshape((batch_size, n_steps, n_input))
# Run optimization op (backprop)
sess.run(optimizer, feed_dict={x: batch_x, y: batch_y})
if step % display_step == 0:
# Calculate batch accuracy
acc = sess.run(accuracy, feed_dict={x: batch_x, y: batch_y})
# Calculate batch loss
loss = sess.run(cost, feed_dict={x: batch_x, y: batch_y})
print("Iter " + str(step*batch_size) + ", Minibatch Loss= " + \
"{:.6f}".format(loss) + ", Training Accuracy= " + \
"{:.5f}".format(acc))
step += 1
print("Optimization Finished!")
# Calculate accuracy for 128 mnist test images
test_len = 128
test_data = mnist.test.images[:test_len].reshape((-1, n_steps, n_input))
test_label = mnist.test.labels[:test_len]
print("Testing Accuracy:", \
sess.run(accuracy, feed_dict={x: test_data, y: test_label}))
sess.close() | [
"tensorflow.train.AdamOptimizer",
"tensorflow.random_normal",
"tensorflow.placeholder",
"tensorflow.Session",
"tensorflow.split",
"tensorflow.nn.dynamic_rnn",
"tensorflow.global_variables_initializer",
"tensorflow.examples.tutorials.mnist.input_data.read_data_sets",
"tensorflow.argmax",
"tensorflo... | [((232, 265), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (255, 265), False, 'import warnings\n'), ((410, 454), 'tensorflow.examples.tutorials.mnist.input_data.read_data_sets', 'input_data.read_data_sets', (['"""."""'], {'one_hot': '(True)'}), "('.', one_hot=True)\n", (435, 454), False, 'from tensorflow.examples.tutorials.mnist import input_data\n'), ((2125, 2196), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': '"""float"""', 'shape': '[None, n_steps, n_input]', 'name': '"""x"""'}), "(dtype='float', shape=[None, n_steps, n_input], name='x')\n", (2139, 2196), True, 'import tensorflow as tf\n'), ((2272, 2336), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': '"""float"""', 'shape': '[None, n_classes]', 'name': '"""y"""'}), "(dtype='float', shape=[None, n_classes], name='y')\n", (2286, 2336), True, 'import tensorflow as tf\n'), ((2529, 2584), 'tensorflow.contrib.rnn.BasicLSTMCell', 'tf.contrib.rnn.BasicLSTMCell', (['n_hidden'], {'forget_bias': '(1.0)'}), '(n_hidden, forget_bias=1.0)\n', (2557, 2584), True, 'import tensorflow as tf\n'), ((2611, 2667), 'tensorflow.nn.dynamic_rnn', 'tf.nn.dynamic_rnn', (['lstm_cell'], {'inputs': 'x', 'dtype': 'tf.float32'}), '(lstm_cell, inputs=x, dtype=tf.float32)\n', (2628, 2667), True, 'import tensorflow as tf\n'), ((3169, 3202), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (3200, 3202), True, 'import tensorflow as tf\n'), ((2765, 2798), 'tensorflow.matmul', 'tf.matmul', (['output', "weights['out']"], {}), "(output, weights['out'])\n", (2774, 2798), True, 'import tensorflow as tf\n'), ((2881, 2943), 'tensorflow.nn.softmax_cross_entropy_with_logits', 'tf.nn.softmax_cross_entropy_with_logits', ([], {'labels': 'y', 'logits': 'pred'}), '(labels=y, logits=pred)\n', (2920, 2943), True, 'import tensorflow as tf\n'), ((3061, 3079), 'tensorflow.argmax', 'tf.argmax', (['pred', '(1)'], {}), '(pred, 1)\n', (3070, 3079), True, 'import tensorflow as tf\n'), ((3080, 3095), 'tensorflow.argmax', 'tf.argmax', (['y', '(1)'], {}), '(y, 1)\n', (3089, 3095), True, 'import tensorflow as tf\n'), ((3122, 3155), 'tensorflow.cast', 'tf.cast', (['correct_pred', 'tf.float32'], {}), '(correct_pred, tf.float32)\n', (3129, 3155), True, 'import tensorflow as tf\n'), ((3233, 3245), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (3243, 3245), True, 'import tensorflow as tf\n'), ((2394, 2433), 'tensorflow.random_normal', 'tf.random_normal', (['[n_hidden, n_classes]'], {}), '([n_hidden, n_classes])\n', (2410, 2433), True, 'import tensorflow as tf\n'), ((2471, 2500), 'tensorflow.random_normal', 'tf.random_normal', (['[n_classes]'], {}), '([n_classes])\n', (2487, 2500), True, 'import tensorflow as tf\n'), ((2690, 2743), 'tensorflow.split', 'tf.split', (['outputs', '(28)'], {'axis': '(1)', 'num': 'None', 'name': '"""split"""'}), "(outputs, 28, axis=1, num=None, name='split')\n", (2698, 2743), True, 'import tensorflow as tf\n'), ((2958, 3009), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'learning_rate'}), '(learning_rate=learning_rate)\n', (2980, 3009), True, 'import tensorflow as tf\n')] |
# -*- coding: utf-8 -*-
# Copyright (c) The python-semanticversion project
# This code is distributed under the two-clause BSD License.
from __future__ import unicode_literals
import unittest
import sys
import semantic_version
from .setup_django import django_loaded
if django_loaded: # pragma: no cover
from semantic_version import django_fields
from .django_test_app import models
import django
from django.conf import settings
from django.core import serializers
from django.core.management import call_command
from django.db import connection
from django.test import TestCase as DjangoTestCase
from django.test import TransactionTestCase
from django.test import runner as django_test_runner
from django.test import utils as django_test_utils
else:
DjangoTestCase = unittest.TestCase
TransactionTestCase = unittest.TestCase
test_state = {}
def setUpModule():
if not django_loaded: # pragma: no cover
raise unittest.SkipTest("Django not installed")
django_test_utils.setup_test_environment()
runner = django_test_runner.DiscoverRunner()
runner_state = runner.setup_databases()
test_state.update({
'runner': runner,
'runner_state': runner_state,
})
def tearDownModule():
if not django_loaded: # pragma: no cover
return
runner = test_state['runner']
runner_state = test_state['runner_state']
runner.teardown_databases(runner_state)
django_test_utils.teardown_test_environment()
# the refresh_from_db method only came in with 1.8, so in order to make this
# work will all supported versions we have our own function.
def save_and_refresh(obj):
"""Saves an object, and refreshes from the database."""
obj.save()
obj = obj.__class__.objects.get(id=obj.id)
Version = semantic_version.Version
Spec = semantic_version.Spec
@unittest.skipIf(not django_loaded, "Django not installed")
class DjangoFieldTestCase(unittest.TestCase):
def test_version(self):
obj = models.VersionModel(version=Version('0.1.1'), spec=Spec('==0.1.1,!=0.1.1-alpha'))
self.assertEqual(Version('0.1.1'), obj.version)
self.assertEqual(Spec('==0.1.1,!=0.1.1-alpha'), obj.spec)
alt_obj = models.VersionModel(version=obj.version, spec=obj.spec)
self.assertEqual(Version('0.1.1'), alt_obj.version)
self.assertEqual(Spec('==0.1.1,!=0.1.1-alpha'), alt_obj.spec)
self.assertEqual(obj.spec, alt_obj.spec)
self.assertEqual(obj.version, alt_obj.version)
def test_version_clean(self):
"""Calling .full_clean() should convert str to Version/Spec objects."""
obj = models.VersionModel(version='0.1.1', spec='==0.1.1,!=0.1.1-alpha')
obj.full_clean()
self.assertEqual(Version('0.1.1'), obj.version)
self.assertEqual(Spec('==0.1.1,!=0.1.1-alpha'), obj.spec)
def test_version_save(self):
"""Test saving object with a VersionField."""
# first test with a null value
obj = models.PartialVersionModel()
self.assertIsNone(obj.id)
self.assertIsNone(obj.optional)
save_and_refresh(obj)
self.assertIsNotNone(obj.id)
self.assertIsNone(obj.optional_spec)
# now set to something that is not null
spec = Spec('==0,!=0.2')
obj.optional_spec = spec
save_and_refresh(obj)
self.assertEqual(obj.optional_spec, spec)
def test_spec_save(self):
"""Test saving object with a SpecField."""
# first test with a null value
obj = models.PartialVersionModel()
self.assertIsNone(obj.id)
self.assertIsNone(obj.optional_spec)
save_and_refresh(obj)
self.assertIsNotNone(obj.id)
self.assertIsNone(obj.optional_spec)
# now set to something that is not null
spec = Spec('==0,!=0.2')
obj.optional_spec = spec
save_and_refresh(obj)
self.assertEqual(obj.optional_spec, spec)
def test_partial_spec_clean(self):
obj = models.VersionModel(version='0.1.1', spec='==0,!=0.2')
obj.full_clean()
self.assertEqual(Version('0.1.1'), obj.version)
self.assertEqual(Spec('==0,!=0.2'), obj.spec)
def test_coerce_clean(self):
obj = models.CoerceVersionModel(version='0.1.1a+2', partial='23')
obj.full_clean()
self.assertEqual(Version('0.1.1-a+2'), obj.version)
self.assertEqual(Version('23', partial=True), obj.partial)
obj2 = models.CoerceVersionModel(version='23', partial='0.1.2.3.4.5/6')
obj2.full_clean()
self.assertEqual(Version('23.0.0'), obj2.version)
self.assertEqual(Version('0.1.2+3.4.5-6', partial=True), obj2.partial)
def test_invalid_input(self):
v = models.VersionModel(version='0.1.1', spec='blah')
self.assertRaises(ValueError, v.full_clean)
v2 = models.VersionModel(version='0.1', spec='==0.1.1,!=0.1.1-alpha')
self.assertRaises(ValueError, v2.full_clean)
def test_partial(self):
obj = models.PartialVersionModel(partial=Version('0.1.0'))
self.assertEqual(Version('0.1.0', partial=True), obj.partial)
self.assertIsNone(obj.optional)
self.assertIsNone(obj.optional_spec)
# Copy values to another model
alt_obj = models.PartialVersionModel(
partial=obj.partial,
optional=obj.optional,
optional_spec=obj.optional_spec,
)
self.assertEqual(Version('0.1.0', partial=True), alt_obj.partial)
self.assertEqual(obj.partial, alt_obj.partial)
self.assertIsNone(obj.optional)
self.assertIsNone(obj.optional_spec)
# Validation should be fine
obj.full_clean()
def test_serialization(self):
o1 = models.VersionModel(version=Version('0.1.1'), spec=Spec('==0.1.1,!=0.1.1-alpha'))
o2 = models.VersionModel(version=Version('0.4.3-rc3+build3'),
spec=Spec('<=0.1.1-rc2,!=0.1.1-rc1'))
data = serializers.serialize('json', [o1, o2])
obj1, obj2 = serializers.deserialize('json', data)
self.assertEqual(o1.version, obj1.object.version)
self.assertEqual(o1.spec, obj1.object.spec)
self.assertEqual(o2.version, obj2.object.version)
self.assertEqual(o2.spec, obj2.object.spec)
def test_serialization_partial(self):
o1 = models.PartialVersionModel(
partial=Version('0.1.1', partial=True),
optional=Version('0.2.4-rc42', partial=True),
optional_spec=None,
)
o2 = models.PartialVersionModel(
partial=Version('0.4.3-rc3+build3', partial=True),
optional='',
optional_spec=Spec('==0.1.1,!=0.1.1-alpha'),
)
data = serializers.serialize('json', [o1, o2])
obj1, obj2 = serializers.deserialize('json', data)
self.assertEqual(o1.partial, obj1.object.partial)
self.assertEqual(o1.optional, obj1.object.optional)
self.assertEqual(o2.partial, obj2.object.partial)
self.assertEqual(o2.optional, obj2.object.optional)
@unittest.skipIf(not django_loaded, "Django not installed")
class FieldMigrationTests(DjangoTestCase):
def test_version_field(self):
field = django_fields.VersionField(
partial=True,
coerce=True,
)
expected = {
'coerce': True,
'partial': True,
'max_length': 200,
}
self.assertEqual(field.deconstruct()[3], expected)
def test_spec_field(self):
field = django_fields.SpecField()
expected = {'max_length': 200}
self.assertEqual(field.deconstruct()[3], expected)
@unittest.skipIf(not django_loaded, "Django not installed")
class FullMigrateTests(TransactionTestCase):
def test_migrate(self):
# Let's check that this does not crash
call_command('makemigrations', verbosity=0)
call_command('migrate', verbosity=0)
with connection.cursor() as cursor:
table_list = connection.introspection.get_table_list(cursor)
table_list = [t.name for t in connection.introspection.get_table_list(cursor)]
self.assertIn('django_test_app_versionmodel', table_list)
@unittest.skipIf(not django_loaded, "Django not installed")
class DbInteractingTestCase(DjangoTestCase):
def test_db_interaction(self):
o1 = models.VersionModel(version=Version('0.1.1'), spec=Spec('<0.2.4-rc42'))
o2 = models.VersionModel(version=Version('0.4.3-rc3+build3'), spec=Spec('==0.4.3'))
o1.save()
o2.save()
obj1 = models.VersionModel.objects.get(pk=o1.pk)
self.assertEqual(o1.version, obj1.version)
obj2 = models.VersionModel.objects.get(pk=o2.pk)
self.assertEqual(o2.version, obj2.version)
| [
"semantic_version.django_fields.SpecField",
"django.core.serializers.deserialize",
"django.core.management.call_command",
"unittest.skipIf",
"django.test.runner.DiscoverRunner",
"django.db.connection.cursor",
"unittest.SkipTest",
"django.db.connection.introspection.get_table_list",
"django.test.util... | [((1881, 1939), 'unittest.skipIf', 'unittest.skipIf', (['(not django_loaded)', '"""Django not installed"""'], {}), "(not django_loaded, 'Django not installed')\n", (1896, 1939), False, 'import unittest\n'), ((7128, 7186), 'unittest.skipIf', 'unittest.skipIf', (['(not django_loaded)', '"""Django not installed"""'], {}), "(not django_loaded, 'Django not installed')\n", (7143, 7186), False, 'import unittest\n'), ((7722, 7780), 'unittest.skipIf', 'unittest.skipIf', (['(not django_loaded)', '"""Django not installed"""'], {}), "(not django_loaded, 'Django not installed')\n", (7737, 7780), False, 'import unittest\n'), ((8279, 8337), 'unittest.skipIf', 'unittest.skipIf', (['(not django_loaded)', '"""Django not installed"""'], {}), "(not django_loaded, 'Django not installed')\n", (8294, 8337), False, 'import unittest\n'), ((1033, 1075), 'django.test.utils.setup_test_environment', 'django_test_utils.setup_test_environment', ([], {}), '()\n', (1073, 1075), True, 'from django.test import utils as django_test_utils\n'), ((1089, 1124), 'django.test.runner.DiscoverRunner', 'django_test_runner.DiscoverRunner', ([], {}), '()\n', (1122, 1124), True, 'from django.test import runner as django_test_runner\n'), ((1477, 1522), 'django.test.utils.teardown_test_environment', 'django_test_utils.teardown_test_environment', ([], {}), '()\n', (1520, 1522), True, 'from django.test import utils as django_test_utils\n'), ((987, 1028), 'unittest.SkipTest', 'unittest.SkipTest', (['"""Django not installed"""'], {}), "('Django not installed')\n", (1004, 1028), False, 'import unittest\n'), ((6021, 6060), 'django.core.serializers.serialize', 'serializers.serialize', (['"""json"""', '[o1, o2]'], {}), "('json', [o1, o2])\n", (6042, 6060), False, 'from django.core import serializers\n'), ((6083, 6120), 'django.core.serializers.deserialize', 'serializers.deserialize', (['"""json"""', 'data'], {}), "('json', data)\n", (6106, 6120), False, 'from django.core import serializers\n'), ((6789, 6828), 'django.core.serializers.serialize', 'serializers.serialize', (['"""json"""', '[o1, o2]'], {}), "('json', [o1, o2])\n", (6810, 6828), False, 'from django.core import serializers\n'), ((6851, 6888), 'django.core.serializers.deserialize', 'serializers.deserialize', (['"""json"""', 'data'], {}), "('json', data)\n", (6874, 6888), False, 'from django.core import serializers\n'), ((7280, 7333), 'semantic_version.django_fields.VersionField', 'django_fields.VersionField', ([], {'partial': '(True)', 'coerce': '(True)'}), '(partial=True, coerce=True)\n', (7306, 7333), False, 'from semantic_version import django_fields\n'), ((7595, 7620), 'semantic_version.django_fields.SpecField', 'django_fields.SpecField', ([], {}), '()\n', (7618, 7620), False, 'from semantic_version import django_fields\n'), ((7909, 7952), 'django.core.management.call_command', 'call_command', (['"""makemigrations"""'], {'verbosity': '(0)'}), "('makemigrations', verbosity=0)\n", (7921, 7952), False, 'from django.core.management import call_command\n'), ((7961, 7997), 'django.core.management.call_command', 'call_command', (['"""migrate"""'], {'verbosity': '(0)'}), "('migrate', verbosity=0)\n", (7973, 7997), False, 'from django.core.management import call_command\n'), ((8011, 8030), 'django.db.connection.cursor', 'connection.cursor', ([], {}), '()\n', (8028, 8030), False, 'from django.db import connection\n'), ((8067, 8114), 'django.db.connection.introspection.get_table_list', 'connection.introspection.get_table_list', (['cursor'], {}), '(cursor)\n', (8106, 8114), False, 'from django.db import connection\n'), ((8157, 8204), 'django.db.connection.introspection.get_table_list', 'connection.introspection.get_table_list', (['cursor'], {}), '(cursor)\n', (8196, 8204), False, 'from django.db import connection\n')] |
#!/usr/bin/env python3
from include import QtPorting as QP
from qtpy import QtWidgets as QW
from qtpy import QtCore as QC
import locale
try: locale.setlocale( locale.LC_ALL, '' )
except: pass
from include import HydrusConstants as HC
from include import HydrusData
from include import HydrusGlobals as HG
from include import TestController
import sys
import threading
import traceback
from twisted.internet import reactor
if __name__ == '__main__':
args = sys.argv[1:]
if len( args ) > 0:
only_run = args[0]
else:
only_run = None
try:
threading.Thread( target = reactor.run, kwargs = { 'installSignalHandlers' : 0 } ).start()
QP.MonkeyPatchMissingMethods()
app = QW.QApplication( sys.argv )
app.call_after_catcher = QP.CallAfterEventCatcher( app )
try:
# we run the tests on the Qt thread atm
# keep a window alive the whole time so the app doesn't finish its mainloop
win = QW.QWidget( None )
win.setWindowTitle( 'Running tests...' )
controller = TestController.Controller( win, only_run )
def do_it():
controller.Run( win )
QP.CallAfter( do_it )
app.exec_()
except:
HydrusData.DebugPrint( traceback.format_exc() )
finally:
HG.view_shutdown = True
controller.pubimmediate( 'wake_daemons' )
HG.model_shutdown = True
controller.pubimmediate( 'wake_daemons' )
controller.TidyUp()
except:
HydrusData.DebugPrint( traceback.format_exc() )
finally:
reactor.callFromThread( reactor.stop )
print( 'This was version ' + str( HC.SOFTWARE_VERSION ) )
input()
| [
"include.TestController.Controller",
"include.QtPorting.CallAfter",
"qtpy.QtWidgets.QApplication",
"traceback.format_exc",
"locale.setlocale",
"include.QtPorting.MonkeyPatchMissingMethods",
"twisted.internet.reactor.callFromThread",
"qtpy.QtWidgets.QWidget",
"threading.Thread",
"include.QtPorting.... | [((143, 178), 'locale.setlocale', 'locale.setlocale', (['locale.LC_ALL', '""""""'], {}), "(locale.LC_ALL, '')\n", (159, 178), False, 'import locale\n'), ((747, 777), 'include.QtPorting.MonkeyPatchMissingMethods', 'QP.MonkeyPatchMissingMethods', ([], {}), '()\n', (775, 777), True, 'from include import QtPorting as QP\n'), ((792, 817), 'qtpy.QtWidgets.QApplication', 'QW.QApplication', (['sys.argv'], {}), '(sys.argv)\n', (807, 817), True, 'from qtpy import QtWidgets as QW\n'), ((862, 891), 'include.QtPorting.CallAfterEventCatcher', 'QP.CallAfterEventCatcher', (['app'], {}), '(app)\n', (886, 891), True, 'from include import QtPorting as QP\n'), ((1995, 2031), 'twisted.internet.reactor.callFromThread', 'reactor.callFromThread', (['reactor.stop'], {}), '(reactor.stop)\n', (2017, 2031), False, 'from twisted.internet import reactor\n'), ((1100, 1116), 'qtpy.QtWidgets.QWidget', 'QW.QWidget', (['None'], {}), '(None)\n', (1110, 1116), True, 'from qtpy import QtWidgets as QW\n'), ((1210, 1250), 'include.TestController.Controller', 'TestController.Controller', (['win', 'only_run'], {}), '(win, only_run)\n', (1235, 1250), False, 'from include import TestController\n'), ((1388, 1407), 'include.QtPorting.CallAfter', 'QP.CallAfter', (['do_it'], {}), '(do_it)\n', (1400, 1407), True, 'from include import QtPorting as QP\n'), ((639, 712), 'threading.Thread', 'threading.Thread', ([], {'target': 'reactor.run', 'kwargs': "{'installSignalHandlers': 0}"}), "(target=reactor.run, kwargs={'installSignalHandlers': 0})\n", (655, 712), False, 'import threading\n'), ((1931, 1953), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (1951, 1953), False, 'import traceback\n'), ((1524, 1546), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (1544, 1546), False, 'import traceback\n')] |
import re
import sys
class BColors:
def __init__(self):
pass
# FOREGROUND
BLACK = '\033[30m'
RED = '\033[31m'
GREEN = '\033[32m'
YELLOW = '\033[33m'
BLUE = '\033[34m'
MAGENTA = '\033[35m'
CYAN = '\033[36m'
WHITE = '\033[37m'
RESET = '\033[39m'
# SPECIAL
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
# !/usr/bin/env python
#
# http://en.wikipedia.org/wiki/Ford-Fulkerson_algorithm
# Ford-Fulkerson algorithm computes max flow in a flow network.
# prevzato z: https://github.com/bigbighd604/Python/blob/master/graph/Ford-Fulkerson.py
# upraveno pro nas priklad, ale princip algoritmu zachovan
#
graph = []
list_of_keys = []
list_of_lastkeys = []
list_of_flowkeys = []
list_of_doors = []
list_of_rooms = []
start = []
def entry():
for i in sys.stdin:
entry_split = re.split('\W+', i)
if entry_split[len(entry_split) - 1] == '':
del entry_split[len(entry_split) - 1]
if entry_split[0].startswith('M', 0, 2):
start.append(entry_split[0])
start.append(entry_split[1])
# print 'start', start
for index in range(len(entry_split)):
if str(entry_split[index]).startswith('D', 0, 2):
graph.append(str(entry_split[index + 1]) + ' > ' + str(entry_split[index + 2]) + ' ' + str(
entry_split[index + 3]))
for index in range(len(entry_split)):
if str(entry_split[index]).startswith('D', 0, 2):
list_of_doors.append(str(entry_split[index]))
for index in range(len(entry_split)):
if str(entry_split[index]).startswith('M', 0, 2):
if str(entry_split[index]) not in list_of_rooms:
list_of_rooms.append(str(entry_split[index]))
for index in range(len(entry_split)):
if str(entry_split[index]).startswith('E', 0, 3):
if str(entry_split[index]) not in list_of_rooms:
list_of_rooms.append(str(entry_split[index]))
class Edge(object):
def __init__(self, u, v, w):
self.source = u
self.target = v
self.capacity = w
def __repr__(self):
return "%s > %s %s" % (self.source, self.target, self.capacity)
class FlowNetwork(object):
def __init__(self):
self.adj = {}
self.flow = {}
def addvertex(self, vertex):
self.adj[vertex] = []
def getedges(self, v):
return self.adj[v]
def addedge(self, u, v, w=0):
if u == v:
raise ValueError("u == v")
edge = Edge(u, v, w)
redge = Edge(v, u, 0)
edge.redge = redge
redge.redge = edge
self.adj[u].append(edge)
self.adj[v].append(redge)
# Intialize all flows to zero
self.flow[edge] = 0
self.flow[redge] = 0
def findpath(self, source, target, path):
if source == target:
return path
for edge in self.getedges(source):
residual = edge.capacity - self.flow[edge]
if residual > 0 and not (edge, residual) in path:
result = self.findpath(edge.target, target, path + [(edge, residual)])
if result != None:
return result
def maxflow(self, source, target):
path = self.findpath(source, target, [])
while path != None:
flow = min(res for edge, res in path)
for edge, res in path:
self.flow[edge] += flow
self.flow[edge.redge] -= flow
for key in self.flow:
continue
path = self.findpath(source, target, [])
for key in self.flow:
if self.flow[key] >= 0:
list_of_keys.append(str(key))
list_of_flowkeys.append(str(self.flow[key]))
if str(key)[len(str(key)) - 2] == ' ':
list_of_lastkeys.append(str(key)[-1:])
else:
list_of_lastkeys.append(str(key)[-2:])
return sum(self.flow[edge] for edge in self.getedges(source))
if __name__ == "__main__":
exit_count = 0
entry()
g = FlowNetwork()
for i in range(len(list_of_rooms)):
g.addvertex(list_of_rooms[i])
for j in range(len(graph)):
length = len(graph[j])
temp = graph[j]
m1 = temp[:3]
if temp[6] == 'E':
m2 = temp[6:10]
exit_count += 1
else:
m2 = temp[6:9]
if str(temp)[len(temp) - 2] == ' ':
t = temp[-1:]
else:
t = temp[-2:]
g.addedge(str(m1), str(m2), int(t))
result = g.maxflow(start[0], 'EXIT')
sys.stdout.write(BColors.GREEN)
sys.stdout.write('Group size: ' + str(result) + '\n')
for i in range(len(graph)):
if graph[i] in list_of_keys:
if list_of_lastkeys[list_of_keys.index(graph[i])] == list_of_flowkeys[list_of_keys.index(graph[i])]:
sys.stdout.write(
str(list_of_doors[i]) + ': ' + str(list_of_flowkeys[list_of_keys.index(graph[i])]) + ' !\n')
else:
sys.stdout.write(
str(list_of_doors[i]) + ': ' + str(list_of_flowkeys[list_of_keys.index(graph[i])]) + '\n')
time = int(start[1]) / result * exit_count
sys.stdout.write('Time: ' + str(time) + '\n')
sys.stdout.write(BColors.RESET)
| [
"re.split",
"sys.stdout.write"
] | [((4493, 4524), 'sys.stdout.write', 'sys.stdout.write', (['BColors.GREEN'], {}), '(BColors.GREEN)\n', (4509, 4524), False, 'import sys\n'), ((5132, 5163), 'sys.stdout.write', 'sys.stdout.write', (['BColors.RESET'], {}), '(BColors.RESET)\n', (5148, 5163), False, 'import sys\n'), ((962, 981), 're.split', 're.split', (['"""\\\\W+"""', 'i'], {}), "('\\\\W+', i)\n", (970, 981), False, 'import re\n')] |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import os
import numpy as np
__all__ = ['raises', 'assert_equal', 'assert_almost_equal',
'assert_true', 'setup_function', 'teardown_function',
'has_isnan']
CWD = os.getcwd()
TEST_DIR = os.path.dirname(__file__)
has_isnan = True
try:
from math import isnan # noqa
except ImportError:
try:
from numpy import isnan # noqa
except ImportError:
has_isnan = False
print('Tests requiring isnan will fail')
def setup_function(function):
os.chdir(TEST_DIR)
def teardown_function(function):
os.chdir(CWD)
# Compatibility functions to convert from nose to py.test
def assert_equal(a, b):
assert a == b
def assert_almost_equal(a, b, **kwargs):
assert np.allclose(a, b, **kwargs)
def assert_true(a):
assert a
def make_decorator(func):
"""
Wraps a test decorator so as to properly replicate metadata
of the decorated function, including nose's additional stuff
(namely, setup and teardown).
"""
def decorate(newfunc):
if hasattr(func, 'compat_func_name'):
name = func.compat_func_name
else:
name = func.__name__
newfunc.__dict__ = func.__dict__
newfunc.__doc__ = func.__doc__
newfunc.__module__ = func.__module__
if not hasattr(newfunc, 'compat_co_firstlineno'):
try:
newfunc.compat_co_firstlineno = func.func_code.co_firstlineno
except AttributeError:
newfunc.compat_co_firstlineno = func.__code__.co_firstlineno
try:
newfunc.__name__ = name
except TypeError:
# can't set func name in 2.3
newfunc.compat_func_name = name
return newfunc
return decorate
def raises(*exceptions):
"""Test must raise one of expected exceptions to pass.
Example use::
@raises(TypeError, ValueError)
def test_raises_type_error():
raise TypeError("This test passes")
@raises(Exception)
def test_that_fails_by_passing():
pass
If you want to test many assertions about exceptions in a single test,
you may want to use `assert_raises` instead.
"""
valid = ' or '.join([e.__name__ for e in exceptions])
def decorate(func):
name = func.__name__
def newfunc(*arg, **kw):
try:
func(*arg, **kw)
except exceptions:
pass
else:
message = f"{name}() did not raise {valid}"
raise AssertionError(message)
newfunc = make_decorator(func)(newfunc)
return newfunc
return decorate
| [
"os.chdir",
"os.path.dirname",
"numpy.allclose",
"os.getcwd"
] | [((255, 266), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (264, 266), False, 'import os\n'), ((278, 303), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (293, 303), False, 'import os\n'), ((566, 584), 'os.chdir', 'os.chdir', (['TEST_DIR'], {}), '(TEST_DIR)\n', (574, 584), False, 'import os\n'), ((624, 637), 'os.chdir', 'os.chdir', (['CWD'], {}), '(CWD)\n', (632, 637), False, 'import os\n'), ((794, 821), 'numpy.allclose', 'np.allclose', (['a', 'b'], {}), '(a, b, **kwargs)\n', (805, 821), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
import asyncio
import logging
import os
import pathlib
import subprocess
import sys
import tempfile
from typing import Optional
from fbpcp.entity.container_instance import ContainerInstanceStatus, ContainerInstance
from fbpcp.service.onedocker import OneDockerService
from fbpcp.service.storage import PathType, StorageService
from fbpcs.data_processing.pid_preparer.preparer import UnionPIDDataPreparerService
from fbpcs.onedocker_binary_names import OneDockerBinaryNames
from fbpcs.private_computation.service.run_binary_base_service import (
RunBinaryBaseService,
)
CPP_UNION_PID_PREPARER_PATH = pathlib.Path(
os.environ.get("CPP_UNION_PID_PREPARER_PATH", "cpp_bin/union_pid_data_preparer")
)
# 10800 s = 3 hrs
DEFAULT_CONTAINER_TIMEOUT_IN_SEC = 10800
class CppUnionPIDDataPreparerService(UnionPIDDataPreparerService):
def prepare(
self,
input_path: str,
output_path: str,
log_path: Optional[pathlib.Path] = None,
log_level: int = logging.INFO,
storage_svc: Optional[StorageService] = None,
) -> None:
if log_path is not None:
logging.basicConfig(filename=log_path, level=log_level)
else:
logging.basicConfig(level=log_level)
logger = logging.getLogger(__name__)
# First check if we need to copy the files from the StorageService
local_inpath = input_path
local_outpath = output_path
# If the path isn't local, assume the passed storage_svc can handle it
if storage_svc and StorageService.path_type(input_path) != PathType.Local:
with tempfile.NamedTemporaryFile(delete=False) as f:
local_inpath = f.name
storage_svc.copy(input_path, local_inpath)
if storage_svc and StorageService.path_type(output_path) != PathType.Local:
with tempfile.NamedTemporaryFile(delete=False) as f:
local_outpath = f.name
cmd = [
f"{CPP_UNION_PID_PREPARER_PATH.absolute()}",
f"--input_path={local_inpath}",
f"--output_path={local_outpath}",
]
try:
logger.info("Starting new process for C++ Preparer")
logger.info(f"Running command: {cmd}")
operating_dir = pathlib.Path(os.getcwd())
proc = subprocess.Popen(
cmd, cwd=operating_dir, stdout=subprocess.PIPE, stderr=sys.stderr
)
out, err = proc.communicate()
except Exception as e:
logger.warning("Encountered error while calling C++ preparer")
raise e
# Remember to copy the file back to the real output path
if storage_svc and StorageService.path_type(output_path) != PathType.Local:
storage_svc.copy(local_outpath, output_path)
logger.info(f"C++ Preparer returned status code {proc.returncode}")
if proc.returncode != 0:
logger.warning(f"C++ preparer returned nonzero status [{proc.returncode}]")
raise Exception(f"{cmd} failed with return code {proc.returncode}")
def prepare_on_container(
self,
input_path: str,
output_path: str,
onedocker_svc: OneDockerService,
binary_version: str,
tmp_directory: str = "/tmp/",
container_timeout: Optional[int] = None,
wait_for_container: bool = True,
) -> ContainerInstance:
return asyncio.run(
self.prepare_on_container_async(
input_path,
output_path,
onedocker_svc,
binary_version,
tmp_directory,
container_timeout,
wait_for_container,
)
)
async def prepare_on_container_async(
self,
input_path: str,
output_path: str,
# TODO: Support custom log path
onedocker_svc: OneDockerService,
binary_version: str,
tmp_directory: str = "/tmp/",
container_timeout: Optional[int] = None,
wait_for_container: bool = True,
) -> ContainerInstance:
logger = logging.getLogger(__name__)
timeout = container_timeout or DEFAULT_CONTAINER_TIMEOUT_IN_SEC
# TODO: Probably put exe in an env variable?
# Try to align with existing paths
cmd_args = " ".join(
[
f"--input_path={input_path}",
f"--output_path={output_path}",
f"--tmp_directory={tmp_directory}",
]
)
current_retry = 0
status = ContainerInstanceStatus.UNKNOWN
exe = OneDockerBinaryNames.UNION_PID_PREPARER.value
container = None
while status is not ContainerInstanceStatus.COMPLETED:
logger.info(
f"Starting container: <{onedocker_svc.task_definition}, {exe} {cmd_args}>"
)
# TODO: The ContainerService API for async instance creation only
# applies to a list of cmds, so we have to immediately dereference
# to take the first element
pending_containers = onedocker_svc.start_containers(
package_name=exe,
version=binary_version,
cmd_args_list=[cmd_args],
timeout=timeout,
)
container = (
await onedocker_svc.wait_for_pending_containers(
[container.instance_id for container in pending_containers]
)
)[0]
# Busy wait until the container is finished
if wait_for_container:
container = (
await RunBinaryBaseService.wait_for_containers_async(
onedocker_svc, [container]
)
)[0]
status = container.status
else:
return container
if container is None:
raise RuntimeError(
f"Failed to start any containers after {1 + current_retry} attempts"
)
logger.info(f"Process finished with status: {container.status}")
return container
| [
"logging.getLogger",
"logging.basicConfig",
"subprocess.Popen",
"os.environ.get",
"fbpcp.service.storage.StorageService.path_type",
"os.getcwd",
"tempfile.NamedTemporaryFile",
"fbpcs.private_computation.service.run_binary_base_service.RunBinaryBaseService.wait_for_containers_async"
] | [((842, 927), 'os.environ.get', 'os.environ.get', (['"""CPP_UNION_PID_PREPARER_PATH"""', '"""cpp_bin/union_pid_data_preparer"""'], {}), "('CPP_UNION_PID_PREPARER_PATH', 'cpp_bin/union_pid_data_preparer'\n )\n", (856, 927), False, 'import os\n'), ((1474, 1501), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1491, 1501), False, 'import logging\n'), ((4333, 4360), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (4350, 4360), False, 'import logging\n'), ((1338, 1393), 'logging.basicConfig', 'logging.basicConfig', ([], {'filename': 'log_path', 'level': 'log_level'}), '(filename=log_path, level=log_level)\n', (1357, 1393), False, 'import logging\n'), ((1420, 1456), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'log_level'}), '(level=log_level)\n', (1439, 1456), False, 'import logging\n'), ((2534, 2622), 'subprocess.Popen', 'subprocess.Popen', (['cmd'], {'cwd': 'operating_dir', 'stdout': 'subprocess.PIPE', 'stderr': 'sys.stderr'}), '(cmd, cwd=operating_dir, stdout=subprocess.PIPE, stderr=sys\n .stderr)\n', (2550, 2622), False, 'import subprocess\n'), ((1754, 1790), 'fbpcp.service.storage.StorageService.path_type', 'StorageService.path_type', (['input_path'], {}), '(input_path)\n', (1778, 1790), False, 'from fbpcp.service.storage import PathType, StorageService\n'), ((1827, 1868), 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', ([], {'delete': '(False)'}), '(delete=False)\n', (1854, 1868), False, 'import tempfile\n'), ((1996, 2033), 'fbpcp.service.storage.StorageService.path_type', 'StorageService.path_type', (['output_path'], {}), '(output_path)\n', (2020, 2033), False, 'from fbpcp.service.storage import PathType, StorageService\n'), ((2070, 2111), 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', ([], {'delete': '(False)'}), '(delete=False)\n', (2097, 2111), False, 'import tempfile\n'), ((2502, 2513), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (2511, 2513), False, 'import os\n'), ((2909, 2946), 'fbpcp.service.storage.StorageService.path_type', 'StorageService.path_type', (['output_path'], {}), '(output_path)\n', (2933, 2946), False, 'from fbpcp.service.storage import PathType, StorageService\n'), ((5876, 5950), 'fbpcs.private_computation.service.run_binary_base_service.RunBinaryBaseService.wait_for_containers_async', 'RunBinaryBaseService.wait_for_containers_async', (['onedocker_svc', '[container]'], {}), '(onedocker_svc, [container])\n', (5922, 5950), False, 'from fbpcs.private_computation.service.run_binary_base_service import RunBinaryBaseService\n')] |
import heapq
import itertools as itt
import operator as op
from collections import OrderedDict, UserDict, defaultdict
from .array import Array
from .optional import Nothing, Some
from .repr import short_repr
from .row import KeyValue, Row
from .stream import Stream
def identity(_): return _
class Map(OrderedDict):
'''A mutable dictionary enhanced with a bulk of useful methods.
'''
def items(self):
return Stream(super().items()).starmap(KeyValue)
def values(self):
return Stream(super().values())
def keys(self):
return Stream(super().keys())
def update(self, *args, **kwds):
'''Update Map from dict/iterable and ``return self``
>>> m = Map(a=3, b=4)
>>> m2 = m.update(a=5, c=3).update({'d': 2})
>>> m is m2
True
>>> m
Map({'a': 5, 'b': 4, 'c': 3, 'd': 2})
'''
super().update(*args, **kwds)
return self
def updated(self, *args, **kwds):
'''Create a new Map instance that is updated from dict/iterable.
This method is the same as ``m.copy().update(...)``
>>> m = Map(a=3, b=4)
>>> m2 = m.updated(a=5, c=3).update({'d': 2})
>>> m2
Map({'a': 5, 'b': 4, 'c': 3, 'd': 2})
>>> m
Map({'a': 3, 'b': 4})
'''
m = self.copy()
return m.update(*args, **kwds)
def join(self, *others, fillvalue=None, agg=None):
"""Create a new Map instance with keys merged and values joined.
>>> m1 = Map(a=1, b=2)
>>> m2 = m1.join(dict(a=3, b=4, c=5))
>>> m2 is m1
False
>>> m2
Map({'a': Row(f0=1, f1=3), 'b': Row(f0=2, f1=4), 'c': Row(f0=None, f1=5)})
>>> m1 = Map(a=1, b=2)
>>> m2 = m1.join(dict(a=3, b=4, c=5), agg=sum, fillvalue=0)
>>> m2
Map({'a': 4, 'b': 6, 'c': 5})
"""
return Map(self.iter_joined(*others, fillvalue=fillvalue, agg=agg))
def iter_joined(self, *others, fillvalue=None, agg=None):
"""Create a ``Row(key, Row(v0, v1, ...))`` iterator with keys from
all Maps and value joined.
>>> m = Map(a=1, b=2)
>>> l = list(m.iter_joined(
... Map(a=3, b=4, c=5),
... Map(a=6, c=7),
... fillvalue=0))
>>> l[0]
Row(key='a', values=Row(f0=1, f1=3, f2=6))
>>> l[1]
Row(key='b', values=Row(f0=2, f1=4, f2=0))
>>> l[2]
Row(key='c', values=Row(f0=0, f1=5, f2=7))
"""
if agg is None:
agg = identity
keys = list(self.keys())
keys_set = set(keys)
for other in others:
for key in other.keys():
if key not in keys_set:
keys_set.add(key)
keys.append(key)
dicts = (self,) + others
for key in keys:
yield Row(key=key,
values=agg(Row.from_values(
d.get(key, fillvalue)
for d in dicts)))
def __repr__(self):
return f'Map({self.make_string()})'
def map(self, func):
'''Create a new Map instance that each key, value pair is derived by
applying function to original key, value.
>>> Map(a=3, b=4).map(lambda k, v: (v, k))
Map({3: 'a', 4: 'b'})
Parameters
----------
func : ``pred(key, value) -> (key, value)``
function for computing new key/value pair
'''
return Map(func(key, value) for key, value in self.items())
def map_keys(self, func):
'''Create a new Map instance that all values remains the same,
while each corresponding key is updated by applying function to
original key, value.
>>> Map(a=3, b=4).map_keys(lambda k, v: k + '_1')
Map({'a_1': 3, 'b_1': 4})
Parameters
----------
func : ``pred(key, value) -> key``
function for computing new keys
'''
return Map((func(key, value), value) for key, value in self.items())
def map_values(self, func):
'''Create a new Map instance that all keys remains the same,
while each corresponding value is updated by applying function to
original key, value.
>>> Map(a=3, b=4).map_values(lambda k, v: v * 2)
Map({'a': 6, 'b': 8})
Parameters
----------
func : ``pred(key, value) -> value``
function for computing new values
'''
return Map((key, func(key, value)) for key, value in self.items())
def revamp_values(self, func):
'''Update values of current Map and return self.
Each value is derived by computing the function using
both key and value.
>>> m = Map(a=3, b=4)
>>> m.revamp_values(lambda k, v: v * 2)
Map({'a': 6, 'b': 8})
>>> m
Map({'a': 6, 'b': 8})
Parameters
----------
func : ``pred(key, value) -> value``
function for computing new values
Returns
-------
self
'''
for key, value in self.items():
self[key] = func(key, value)
return self
def keep(self, *keys):
'''Delete keys not specified and return self
>>> m = Map(a=3, b=4, c=5)
>>> m.keep('a', 'c')
Map({'a': 3, 'c': 5})
>>> m
Map({'a': 3, 'c': 5})
Returns
-------
self
'''
keys = set(keys)
current_keys = set(self.keys())
keys_to_delete = current_keys - keys
for key, in keys_to_delete:
del self[key]
return self
def project(self, *keys):
'''Create a new Map instance contains only specified keys.
>>> m = Map(a=3, b=4, c=5)
>>> m.project('a', 'c')
Map({'a': 3, 'c': 5})
>>> m
Map({'a': 3, 'b': 4, 'c': 5})
Returns
-------
Map[key, value]
'''
return Map((k, self[k]) for k in keys)
def get_opt(self, key):
'''Get the value of specified key as Optional type.
Return Some(value) if key exists, otherwise return Nothing.
>>> m = Map(a=3, b=4)
>>> m.get_opt('a')
Some(3)
>>> m.get_opt('c')
Nothing
>>> m.get_opt('a').map(lambda v: v * 2)
Some(6)
>>> m.get_opt('c').map(lambda v: v * 2)
Nothing
Returns
-------
Optional[value]
'''
if key in self:
return Some(self[key])
return Nothing
def remove(self, *keys):
'''Delete keys and return self
>>> m = Map(a=3, b=4, c=5)
>>> m.remove('a', 'c')
Map({'b': 4})
>>> m
Map({'b': 4})
Returns
-------
self
'''
for key in keys:
del self[key]
return self
def without(self, *keys):
'''Create a new Map instance with those keys
>>> m = Map(a=3, b=4, c=6)
>>> m.without('a', 'c')
Map({'b': 4})
>>> m
Map({'a': 3, 'b': 4, 'c': 6})
Returns
-------
Map[key, value]
'''
return Map((key, value)
for key, value in self.items()
if key not in keys)
def retain(self, pred):
'''Delete key/value pairs not satisfying the predicate and return self
>>> m = Map(a=3, b=4, c=5)
>>> m.retain(lambda k, v: k == 'b' or v == 5)
Map({'b': 4, 'c': 5})
>>> m
Map({'b': 4, 'c': 5})
Parameters
----------
pred : ``(k, v) -> bool``
Returns
-------
self
'''
keys_to_delete = []
for key, value in self.items():
if not pred(key, value):
keys_to_delete.append(key)
return self.remove(*keys_to_delete)
def retain_false(self, pred):
'''Delete key/value pairs satisfying the predicate and return self
>>> m = Map(a=3, b=4, c=5)
>>> m.retain_false(lambda k, v: k == 'b' or v == 5)
Map({'a': 3})
>>> m
Map({'a': 3})
Parameters
----------
pred : ``(k, v) -> bool``
Returns
-------
self
'''
keys_to_delete = []
for key, value in self.items():
if pred(key, value):
keys_to_delete.append(key)
return self.remove(*keys_to_delete)
def retain_by_key(self, pred):
'''Delete key/value pairs not satisfying the predicate and return self
>>> m = Map(a=3, b=4, c=5)
>>> m.retain_by_key(lambda k: k == 'b')
Map({'b': 4})
>>> m
Map({'b': 4})
Parameters
----------
pred : ``(k) -> bool``
Returns
-------
self
'''
keys_to_delete = []
for key, value in self.items():
if not pred(key):
keys_to_delete.append(key)
return self.remove(*keys_to_delete)
def retain_by_value(self, pred):
'''Delete key/value pairs not satisfying the predicate and return self
>>> m = Map(a=3, b=4, c=5)
>>> m.retain_by_value(lambda v: v == 4)
Map({'b': 4})
>>> m
Map({'b': 4})
Parameters
----------
pred : ``(k) -> bool``
Returns
-------
self
'''
keys_to_delete = []
for key, value in self.items():
if not pred(value):
keys_to_delete.append(key)
return self.remove(*keys_to_delete)
def filter(self, pred):
'''Create a new Map with key/value pairs satisfying the predicate
>>> m = Map({1: 2, 2: 4, 3: 6})
>>> m2 = m.filter(lambda k, v: (v-k) % 3 == 0)
>>> m2
Map({3: 6})
Parameters
----------
pred : ``(k, v) -> bool``
predicate
Returns
-------
Map[key, value]
'''
return Map((k, v) for k, v in self.items() if pred(k, v))
def filter_false(self, pred):
'''Create a new Map with key/value pairs not satisfying the predicate
>>> m = Map({1: 2, 2: 4, 3: 6})
>>> m2 = m.filter_false(lambda k, v: (v-k) % 3 == 0)
>>> m2
Map({1: 2, 2: 4})
Parameters
----------
pred : ``(k, v) -> bool``
predicate
Returns
-------
Map[key, value]
'''
return Map((k, v) for k, v in self.items() if not pred(k, v))
def filter_by_key(self, pred):
'''Create a new Map with keys satisfying the predicate
>>> m = Map({1: 2, 2: 4, 3: 6})
>>> m2 = m.filter_by_key(lambda k: k % 3 == 0)
>>> m2
Map({3: 6})
Parameters
----------
pred : ``(k, v) -> bool``
predicate
Returns
-------
Map[key, value]
'''
return Map((k, v) for k, v in self.items() if pred(k))
def filter_by_value(self, pred):
'''Create a new Map with values satisfying the predicate
>>> m = Map({1: 2, 2: 4, 3: 6})
>>> m2 = m.filter_by_value(lambda v: v % 3 == 0)
>>> m2
Map({3: 6})
Parameters
----------
pred : ``(k, v) -> bool``
predicate
Returns
-------
Map[key, value]
'''
return Map((k, v) for k, v in self.items() if pred(v))
def group_by(self, key_func):
'''Group key/value pairs into nested Maps.
>>> Map(a=3, b=4, c=5).group_by(lambda k, v: v % 2)
Map({1: Map({'a': 3, 'c': 5}), 0: Map({'b': 4})})
Parameters
----------
key_func : ``(key, value) -> group_key``
predicate
Returns
-------
Map[key_func(key), Map[key, value]]
'''
grouped_d = defaultdict(Map)
for key, value in self.items():
grouped_d[key_func(key, value)][key] = value
return Map(grouped_d)
def reduce(self, key):
pass
def make_string(self,
key_value_format='{key!r}: {value!r}',
start='{', item_sep=', ', end='}'):
'''Construct a string from key/values.
>>> m = Map(a=3, b=4, c=5)
>>> m.make_string()
"{'a': 3, 'b': 4, 'c': 5}"
>>> m.make_string(start='(', key_value_format='{key}={value!r}',
... item_sep=', ', end=')')
'(a=3, b=4, c=5)'
Parameters
----------
key_value_format : str
string template using builtin ``str.format()`` for formatting
key/value pairs. Default to ``'{key!r}: {value!r}'``.
Available named placeholders: ``{key}``, ``{value}``
start : str
Default to ``'{'``.
item_sep : str
Default to ``', '``
end : str
Default to ``}``
Returns
-------
str
'''
items_str = item_sep.join(
key_value_format.format(key=key, value=value)
for key, value in self.items())
return start + items_str + end
def take(self, n):
'''create a Stream instance of first ``n`` ``Row(key, value)`` elements.
>>> m = Map(a=4, b=5, c=6, d=7)
>>> m.take(2).to_list()
[Row(key='a', value=4), Row(key='b', value=5)]
Returns
-------
Stream[Row[key, value]]
'''
return self.to_stream().take(n)
def first(self):
'''Get the first item in ``Row(key, value)`` type
>>> m = Map(a=4, b=5, c=6, d=7)
>>> m.first()
Row(key='a', value=4)
>>> m.first().key
'a'
>>> m.first().value
4
>>> m = Map()
>>> m.first()
Traceback (most recent call last):
...
IndexError: index out of range.
Returns
-------
Row[key, value]
'''
return self.nth(0)
def first_opt(self):
'''Optionally get the first item.
Return Some(Row(key, value)) if first item exists,
otherwise return Nothing
>>> m = Map(a=4, b=5, c=6, d=7)
>>> m.first_opt().map(lambda kv: kv.transform(value=lambda v: v * 2))
Some(Row(key='a', value=8))
>>> m.first_opt().map(lambda kv: kv.value)
Some(4)
>>> m = Map()
>>> m.first_opt()
Nothing
Returns
-------
Optional[Row[key, value]]
'''
return self.nth_opt(0)
def nth(self, index):
'''Get the nth item in ``Row(key, value)`` type.
>>> m = Map(a=4, b=5, c=6, d=7)
>>> m.nth(2)
Row(key='c', value=6)
>>> m = Map(a=4, b=5)
>>> m.nth(2)
Traceback (most recent call last):
...
IndexError: index out of range.
Returns
-------
Row[key, value]
'''
try:
key, value = next(itt.islice(self.items(), index, None))
return KeyValue(key, value)
except StopIteration:
raise IndexError('index out of range.')
def nth_opt(self, index):
'''Optionally get the nth item.
Return ``Some(Row(key, value))`` if first item exists,
otherwise return Nothing.
>>> m = Map(a=4, b=5, c=6, d=7)
>>> m.first_opt().map(lambda kv: kv.transform(value=lambda v: v * 2))
Some(Row(key='a', value=8))
>>> m = Map()
>>> m.first_opt()
Nothing
Returns
-------
Optional[Row[key, value]]
'''
try:
return Some(self.nth(index))
except IndexError:
return Nothing
def len(self):
'''Get the length of this Map
>>> m = Map(a=4, b=5, c=6, d=7)
>>> m.len()
4
Returns
-------
int
'''
return len(self)
def to_stream(self, key_field='key', value_field='value'):
'''Convert to a Stream instance of ``Row(key, value)`` iterable.
>>> m = Map(a=4, b=5, c=6, d=7)
>>> m.to_stream().take(2).to_list()
[Row(key='a', value=4), Row(key='b', value=5)]
Returns
-------
Stream[Row[key, value]]
'''
return (Stream(super().items())
.starmap(lambda key, value:
Row(**{key_field: key, value_field: value})))
def to_array(self):
'''Convert to an Array instance of ``Row(key, value)`` iterable.
>>> m = Map(a=4, b=5, c=6, d=7)
>>> m.to_array().take(2)
Array([Row(key='a', value=4), Row(key='b', value=5)])
Returns
-------
Array[Row[key, value]]
'''
return self.to_stream().to_array()
def to_list(self):
'''Convert to an list instance of ``Row(key, value)`` iterable.
>>> m = Map(a=4, b=5)
>>> m.to_list()
[Row(key='a', value=4), Row(key='b', value=5)]
Returns
-------
Array[Row[key, value]]
'''
return self.to_stream().to_list()
def to_dict(self):
'''Convert to dict'''
return dict(self)
def flip(self):
'''Create a new Map which key/value pairs are fliped
>>> m = Map(a=4, b=5, c=6)
>>> m.flip()
Map({4: 'a', 5: 'b', 6: 'c'})
'''
return Map((value, key) for key, value in self.items())
def for_each(self, func):
'''Call func for each key/value pair
>>> m = Map(a=[], b=[], c=[])
>>> m.for_each(lambda k, v: v.append(k))
>>> m
Map({'a': ['a'], 'b': ['b'], 'c': ['c']})
'''
for k, v in self.items():
func(k, v)
def for_each_key(self, func):
'''Call func for each key
>>> m = Map(a=[], b=[], c=[])
>>> keys = []
>>> m.for_each_key(lambda k: keys.append(k))
>>> keys
['a', 'b', 'c']
'''
for k in self.keys():
func(k)
def for_each_value(self, func):
'''Call func for each value
>>> m = Map(a=[], b=[], c=[])
>>> m.for_each_value(lambda v: v.append(3))
>>> m
Map({'a': [3], 'b': [3], 'c': [3]})
'''
for v in self.values():
func(v)
def nlargest_value_items(self, n=None):
'''Get top n largest values
>>> m = Map(a=6, b=2, c=10, d=9)
>>> m.nlargest_value_items(n=2)
Array([Row(key='c', value=10), Row(key='d', value=9)])
Returns
-------
Array[Row[key, value]]
'''
if n is None:
vs = sorted(self.items(), key=op.itemgetter(1), reverse=True)
vs = heapq.nlargest(n, self.items(), key=op.itemgetter(1))
return Array(vs)
def nsmallest_value_items(self, n=None):
'''Get top n smallest values
>>> m = Map(a=6, b=2, c=10, d=9)
>>> m.nsmallest_value_items(n=2)
Array([Row(key='b', value=2), Row(key='a', value=6)])
Returns
-------
Array[Row[key, value]]
'''
if n is None:
vs = sorted(self.items(), key=op.itemgetter(1), reverse=False)
vs = heapq.nsmallest(n, self.items(), key=op.itemgetter(1))
return Array(vs)
| [
"operator.itemgetter",
"collections.defaultdict"
] | [((11997, 12013), 'collections.defaultdict', 'defaultdict', (['Map'], {}), '(Map)\n', (12008, 12013), False, 'from collections import OrderedDict, UserDict, defaultdict\n'), ((18899, 18915), 'operator.itemgetter', 'op.itemgetter', (['(1)'], {}), '(1)\n', (18912, 18915), True, 'import operator as op\n'), ((19394, 19410), 'operator.itemgetter', 'op.itemgetter', (['(1)'], {}), '(1)\n', (19407, 19410), True, 'import operator as op\n'), ((18818, 18834), 'operator.itemgetter', 'op.itemgetter', (['(1)'], {}), '(1)\n', (18831, 18834), True, 'import operator as op\n'), ((19311, 19327), 'operator.itemgetter', 'op.itemgetter', (['(1)'], {}), '(1)\n', (19324, 19327), True, 'import operator as op\n')] |
#!/usr/bin/python
#
# SPDX-License-Identifier: Apache-2.0
#
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ..module_utils.dict_utils import equal_dicts, merge_dicts, copy_dict
from ..module_utils.module import BlockchainModule
from ..module_utils.proto_utils import proto_to_json, json_to_proto
from ansible.module_utils._text import to_native
import json
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: channel_policy
short_description: Manage a policy for a Hyperledger Fabric channel
description:
- Add, update, and remove policies for a Hyperledger Fabric channel by using the IBM Blockchain Platform.
- This module works with the IBM Blockchain Platform managed service running in IBM Cloud, or the IBM Blockchain
Platform software running in a Red Hat OpenShift or Kubernetes cluster.
author: <NAME> (@sstone1)
options:
state:
description:
- C(absent) - An policy matching the specified name will be removed from the channel.
- C(present) - Asserts that an policy matching the specified name and configuration exists
in the channel. If no policy matches the specified name, the policy will be added
to the channel. If an policy matches the specified name but the configuration does not
match, then the policy in the channel will be updated.
type: str
default: present
choices:
- absent
- present
path:
description:
- Path to current the channel configuration file.
- This file can be fetched by using the M(channel_config) module.
- This file will be updated in place. You will need to keep a copy of the original file for computing the configuration
update.
type: str
required: true
name:
description:
- The name of the policy to add, update, or remove from the channel.
type: str
required: true
policy:
description:
- The policy to add, update, or remove from the channel.
- You can pass a string, which is a path to a JSON file containing a policy
in the Hyperledger Fabric format (common.Policy).
- You can also pass a dict, which must correspond to a parsed policy in the
Hyperledger Fabric format (common.Policy).
- Only required when I(state) is C(present).
type: raw
required: true
notes: []
requirements: []
'''
EXAMPLES = '''
- name: Add the policy to the channel
ibm.blockchain_platform.channel_policy:
state: present
api_endpoint: https://ibp-console.example.org:32000
api_authtype: basic
api_key: xxxxxxxx
api_secret: <KEY>
name: Admins
policy: admins-policy.json
path: channel_config.bin
- name: Remove the policy to the channel
ibm.blockchain_platform.channel_policy:
state: absent
api_endpoint: https://ibp-console.example.org:32000
api_authtype: basic
api_key: xxxxxxxx
api_secret: <KEY>
name: Admins
path: channel_config.bin
'''
RETURN = '''
---
{}
'''
def main():
# Create the module.
argument_spec = dict(
state=dict(type='str', default='present', choices=['present', 'absent']),
path=dict(type='str', required=True),
name=dict(type='str', required=True),
policy=dict(type='raw', required=True)
)
required_if = [
]
module = BlockchainModule(argument_spec=argument_spec, supports_check_mode=True, required_if=required_if)
# Ensure all exceptions are caught.
try:
# Get the target path, policy name and policy.
path = module.params['path']
name = module.params['name']
policy = module.params['policy']
if isinstance(policy, str):
with open(policy, 'r') as file:
policy = json.load(file)
elif isinstance(policy, dict):
pass
else:
raise Exception(f'The policy {name} is invalid')
# Read the config.
with open(path, 'rb') as file:
config_json = proto_to_json('common.Config', file.read())
# Check to see if the channel member exists.
application_policies = config_json['channel_group']['groups']['Application']['policies']
policy_wrapper = application_policies.get(name, None)
# Handle the desired state appropriately.
state = module.params['state']
if state == 'present' and policy_wrapper is None:
# Add the channel policy.
application_policies[name] = dict(
mod_policy='Admins',
policy=policy
)
elif state == 'present' and policy_wrapper is not None:
# Update the channel policy.
updated_policy_wrapper = copy_dict(policy_wrapper)
merge_dicts(updated_policy_wrapper['policy'], policy)
if equal_dicts(policy_wrapper, updated_policy_wrapper):
return module.exit_json(changed=False)
application_policies[name] = updated_policy_wrapper
elif state == 'absent' and policy_wrapper is None:
# Nothing to do.
return module.exit_json(changed=False)
elif state == 'absent' and policy_wrapper is not None:
# Delete the channel member.
del application_policies[name]
# Save the config.
config_proto = json_to_proto('common.Config', config_json)
with open(path, 'wb') as file:
file.write(config_proto)
module.exit_json(changed=True)
# Notify Ansible of the exception.
except Exception as e:
module.fail_json(msg=to_native(e))
if __name__ == '__main__':
main()
| [
"json.load",
"ansible.module_utils._text.to_native"
] | [((4034, 4049), 'json.load', 'json.load', (['file'], {}), '(file)\n', (4043, 4049), False, 'import json\n'), ((5865, 5877), 'ansible.module_utils._text.to_native', 'to_native', (['e'], {}), '(e)\n', (5874, 5877), False, 'from ansible.module_utils._text import to_native\n')] |
#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2012 <EMAIL>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import socket
import time
from enum import IntEnum
from typing import Tuple
from PyQt5.QtCore import Qt, pyqtSignal, QThread
from PyQt5.QtWidgets import (QTreeWidget, QTreeWidgetItem, QMenu, QGridLayout, QComboBox,
QLineEdit, QDialog, QVBoxLayout, QHeaderView, QCheckBox,
QTabWidget, QWidget, QLabel)
from PyQt5.QtGui import QFontMetrics
from electrum_trc.i18n import _
from electrum_trc import constants, blockchain
from electrum_trc.interface import serialize_server, deserialize_server
from electrum_trc.network import Network
from electrum_trc.logging import get_logger
from .util import Buttons, CloseButton, HelpButton, read_QIcon, char_width_in_lineedit
_logger = get_logger(__name__)
protocol_names = ['TCP', 'SSL']
protocol_letters = 'ts'
class NetworkDialog(QDialog):
def __init__(self, network, config, network_updated_signal_obj):
QDialog.__init__(self)
self.setWindowTitle(_('Electrum Network'))
self.setMinimumSize(500, 300)
self.nlayout = NetworkChoiceLayout(network, config)
self.network_updated_signal_obj = network_updated_signal_obj
vbox = QVBoxLayout(self)
vbox.addLayout(self.nlayout.layout())
vbox.addLayout(Buttons(CloseButton(self)))
self.network_updated_signal_obj.network_updated_signal.connect(
self.on_update)
network.register_callback(self.on_network, ['network_updated'])
def on_network(self, event, *args):
self.network_updated_signal_obj.network_updated_signal.emit(event, args)
def on_update(self):
self.nlayout.update()
class NodesListWidget(QTreeWidget):
def __init__(self, parent):
QTreeWidget.__init__(self)
self.parent = parent
self.setHeaderLabels([_('Connected node'), _('Height')])
self.setContextMenuPolicy(Qt.CustomContextMenu)
self.customContextMenuRequested.connect(self.create_menu)
def create_menu(self, position):
item = self.currentItem()
if not item:
return
is_server = not bool(item.data(0, Qt.UserRole))
menu = QMenu()
if is_server:
server = item.data(1, Qt.UserRole)
menu.addAction(_("Use as server"), lambda: self.parent.follow_server(server))
else:
chain_id = item.data(1, Qt.UserRole)
menu.addAction(_("Follow this branch"), lambda: self.parent.follow_branch(chain_id))
menu.exec_(self.viewport().mapToGlobal(position))
def keyPressEvent(self, event):
if event.key() in [ Qt.Key_F2, Qt.Key_Return ]:
self.on_activated(self.currentItem(), self.currentColumn())
else:
QTreeWidget.keyPressEvent(self, event)
def on_activated(self, item, column):
# on 'enter' we show the menu
pt = self.visualItemRect(item).bottomLeft()
pt.setX(50)
self.customContextMenuRequested.emit(pt)
def update(self, network: Network):
self.clear()
self.addChild = self.addTopLevelItem
chains = network.get_blockchains()
n_chains = len(chains)
for chain_id, interfaces in chains.items():
b = blockchain.blockchains.get(chain_id)
if b is None: continue
name = b.get_name()
if n_chains > 1:
x = QTreeWidgetItem([name + '@%d'%b.get_max_forkpoint(), '%d'%b.height()])
x.setData(0, Qt.UserRole, 1)
x.setData(1, Qt.UserRole, b.get_id())
else:
x = self
for i in interfaces:
star = ' *' if i == network.interface else ''
item = QTreeWidgetItem([i.host + star, '%d'%i.tip])
item.setData(0, Qt.UserRole, 0)
item.setData(1, Qt.UserRole, i.server)
x.addChild(item)
if n_chains > 1:
self.addTopLevelItem(x)
x.setExpanded(True)
h = self.header()
h.setStretchLastSection(False)
h.setSectionResizeMode(0, QHeaderView.Stretch)
h.setSectionResizeMode(1, QHeaderView.ResizeToContents)
super().update()
class ServerListWidget(QTreeWidget):
class Columns(IntEnum):
HOST = 0
PORT = 1
SERVER_STR_ROLE = Qt.UserRole + 100
def __init__(self, parent):
QTreeWidget.__init__(self)
self.parent = parent
self.setHeaderLabels([_('Host'), _('Port')])
self.setContextMenuPolicy(Qt.CustomContextMenu)
self.customContextMenuRequested.connect(self.create_menu)
def create_menu(self, position):
item = self.currentItem()
if not item:
return
menu = QMenu()
server = item.data(self.Columns.HOST, self.SERVER_STR_ROLE)
menu.addAction(_("Use as server"), lambda: self.set_server(server))
menu.exec_(self.viewport().mapToGlobal(position))
def set_server(self, s):
host, port, protocol = deserialize_server(s)
self.parent.server_host.setText(host)
self.parent.server_port.setText(port)
self.parent.set_server()
def keyPressEvent(self, event):
if event.key() in [ Qt.Key_F2, Qt.Key_Return ]:
self.on_activated(self.currentItem(), self.currentColumn())
else:
QTreeWidget.keyPressEvent(self, event)
def on_activated(self, item, column):
# on 'enter' we show the menu
pt = self.visualItemRect(item).bottomLeft()
pt.setX(50)
self.customContextMenuRequested.emit(pt)
def update(self, servers, protocol, use_tor):
self.clear()
for _host, d in sorted(servers.items()):
if _host.endswith('.onion') and not use_tor:
continue
port = d.get(protocol)
if port:
x = QTreeWidgetItem([_host, port])
server = serialize_server(_host, port, protocol)
x.setData(self.Columns.HOST, self.SERVER_STR_ROLE, server)
self.addTopLevelItem(x)
h = self.header()
h.setStretchLastSection(False)
h.setSectionResizeMode(self.Columns.HOST, QHeaderView.Stretch)
h.setSectionResizeMode(self.Columns.PORT, QHeaderView.ResizeToContents)
super().update()
class NetworkChoiceLayout(object):
def __init__(self, network: Network, config, wizard=False):
self.network = network
self.config = config
self.protocol = None
self.tor_proxy = None
self.tabs = tabs = QTabWidget()
server_tab = QWidget()
proxy_tab = QWidget()
blockchain_tab = QWidget()
tabs.addTab(blockchain_tab, _('Overview'))
tabs.addTab(server_tab, _('Server'))
tabs.addTab(proxy_tab, _('Proxy'))
fixed_width_hostname = 24 * char_width_in_lineedit()
fixed_width_port = 6 * char_width_in_lineedit()
# server tab
grid = QGridLayout(server_tab)
grid.setSpacing(8)
self.server_host = QLineEdit()
self.server_host.setFixedWidth(fixed_width_hostname)
self.server_port = QLineEdit()
self.server_port.setFixedWidth(fixed_width_port)
self.autoconnect_cb = QCheckBox(_('Select server automatically'))
self.autoconnect_cb.setEnabled(self.config.is_modifiable('auto_connect'))
self.server_host.editingFinished.connect(self.set_server)
self.server_port.editingFinished.connect(self.set_server)
self.autoconnect_cb.clicked.connect(self.set_server)
self.autoconnect_cb.clicked.connect(self.update)
msg = ' '.join([
_("If auto-connect is enabled, Terracoin Electrum will always use a server that is on the longest blockchain."),
_("If it is disabled, you have to choose a server you want to use. Terracoin Electrum will warn you if your server is lagging.")
])
grid.addWidget(self.autoconnect_cb, 0, 0, 1, 3)
grid.addWidget(HelpButton(msg), 0, 4)
grid.addWidget(QLabel(_('Server') + ':'), 1, 0)
grid.addWidget(self.server_host, 1, 1, 1, 2)
grid.addWidget(self.server_port, 1, 3)
label = _('Server peers') if network.is_connected() else _('Default Servers')
grid.addWidget(QLabel(label), 2, 0, 1, 5)
self.servers_list = ServerListWidget(self)
grid.addWidget(self.servers_list, 3, 0, 1, 5)
# Proxy tab
grid = QGridLayout(proxy_tab)
grid.setSpacing(8)
# proxy setting
self.proxy_cb = QCheckBox(_('Use proxy'))
self.proxy_cb.clicked.connect(self.check_disable_proxy)
self.proxy_cb.clicked.connect(self.set_proxy)
self.proxy_mode = QComboBox()
self.proxy_mode.addItems(['SOCKS4', 'SOCKS5'])
self.proxy_host = QLineEdit()
self.proxy_host.setFixedWidth(fixed_width_hostname)
self.proxy_port = QLineEdit()
self.proxy_port.setFixedWidth(fixed_width_port)
self.proxy_user = QLineEdit()
self.proxy_user.setPlaceholderText(_("Proxy user"))
self.proxy_password = QLineEdit()
self.proxy_password.setPlaceholderText(_("Password"))
self.proxy_password.setEchoMode(QLineEdit.Password)
self.proxy_password.setFixedWidth(fixed_width_port)
self.proxy_mode.currentIndexChanged.connect(self.set_proxy)
self.proxy_host.editingFinished.connect(self.set_proxy)
self.proxy_port.editingFinished.connect(self.set_proxy)
self.proxy_user.editingFinished.connect(self.set_proxy)
self.proxy_password.editingFinished.connect(self.set_proxy)
self.proxy_mode.currentIndexChanged.connect(self.proxy_settings_changed)
self.proxy_host.textEdited.connect(self.proxy_settings_changed)
self.proxy_port.textEdited.connect(self.proxy_settings_changed)
self.proxy_user.textEdited.connect(self.proxy_settings_changed)
self.proxy_password.textEdited.connect(self.proxy_settings_changed)
self.tor_cb = QCheckBox(_("Use Tor Proxy"))
self.tor_cb.setIcon(read_QIcon("tor_logo.png"))
self.tor_cb.hide()
self.tor_cb.clicked.connect(self.use_tor_proxy)
self.tor_auto_on = QCheckBox(_("Use Tor Proxy on startup"))
self.tor_auto_on.setIcon(read_QIcon("tor_logo.png"))
self.tor_auto_on.setChecked(self.config.get('tor_auto_on', True))
self.tor_auto_on.clicked.connect(self.use_tor_auto_on)
grid.addWidget(self.tor_cb, 1, 0, 1, 3)
grid.addWidget(self.proxy_cb, 2, 0, 1, 3)
grid.addWidget(HelpButton(_('Proxy settings apply to all connections: with Terracoin Electrum servers, but also with third-party services.')), 2, 4)
grid.addWidget(self.proxy_mode, 4, 1)
grid.addWidget(self.proxy_host, 4, 2)
grid.addWidget(self.proxy_port, 4, 3)
grid.addWidget(self.proxy_user, 5, 2)
grid.addWidget(self.proxy_password, 5, 3)
grid.addWidget(self.tor_auto_on, 6, 0, 1, 3)
grid.addWidget(HelpButton(_('During wallet startup try to detect and use Tor Proxy.')), 6, 4)
grid.setRowStretch(7, 1)
# Blockchain Tab
grid = QGridLayout(blockchain_tab)
msg = ' '.join([
_("Terracoin Electrum connects to several nodes in order to download block headers and find out the longest blockchain."),
_("This blockchain is used to verify the transactions sent by your transaction server.")
])
self.status_label = QLabel('')
grid.addWidget(QLabel(_('Status') + ':'), 0, 0)
grid.addWidget(self.status_label, 0, 1, 1, 3)
grid.addWidget(HelpButton(msg), 0, 4)
self.server_label = QLabel('')
msg = _("Terracoin Electrum sends your wallet addresses to a single server, in order to receive your transaction history.")
grid.addWidget(QLabel(_('Server') + ':'), 1, 0)
grid.addWidget(self.server_label, 1, 1, 1, 3)
grid.addWidget(HelpButton(msg), 1, 4)
self.height_label = QLabel('')
msg = _('This is the height of your local copy of the blockchain.')
grid.addWidget(QLabel(_('Blockchain') + ':'), 2, 0)
grid.addWidget(self.height_label, 2, 1)
grid.addWidget(HelpButton(msg), 2, 4)
self.split_label = QLabel('')
grid.addWidget(self.split_label, 3, 0, 1, 3)
self.nodes_list_widget = NodesListWidget(self)
grid.addWidget(self.nodes_list_widget, 5, 0, 1, 5)
vbox = QVBoxLayout()
vbox.addWidget(tabs)
self.layout_ = vbox
# tor detector
self.td = td = TorDetector()
td.found_proxy.connect(self.suggest_proxy)
td.start()
self.fill_in_proxy_settings()
self.update()
def check_disable_proxy(self, b):
if not self.config.is_modifiable('proxy'):
b = False
for w in [self.proxy_mode, self.proxy_host, self.proxy_port, self.proxy_user, self.proxy_password]:
w.setEnabled(b)
def enable_set_server(self):
if self.config.is_modifiable('server'):
enabled = not self.autoconnect_cb.isChecked()
self.server_host.setEnabled(enabled)
self.server_port.setEnabled(enabled)
self.servers_list.setEnabled(enabled)
else:
for w in [self.autoconnect_cb, self.server_host, self.server_port, self.servers_list]:
w.setEnabled(False)
def update(self):
net_params = self.network.get_parameters()
host, port, protocol = net_params.host, net_params.port, net_params.protocol
proxy_config, auto_connect = net_params.proxy, net_params.auto_connect
if not self.server_host.hasFocus() and not self.server_port.hasFocus():
self.server_host.setText(host)
self.server_port.setText(str(port))
self.autoconnect_cb.setChecked(auto_connect)
interface = self.network.interface
host = interface.host if interface else _('None')
self.server_label.setText(host)
self.set_protocol(protocol)
self.servers = self.network.get_servers()
self.servers_list.update(self.servers, self.protocol, self.tor_cb.isChecked())
self.enable_set_server()
height_str = "%d "%(self.network.get_local_height()) + _('blocks')
self.height_label.setText(height_str)
n = len(self.network.get_interfaces())
status = _("Connected to {0} nodes.").format(n) if n else _("Not connected")
self.status_label.setText(status)
chains = self.network.get_blockchains()
if len(chains) > 1:
chain = self.network.blockchain()
forkpoint = chain.get_max_forkpoint()
name = chain.get_name()
msg = _('Chain split detected at block {0}').format(forkpoint) + '\n'
msg += (_('You are following branch') if auto_connect else _('Your server is on branch'))+ ' ' + name
msg += ' (%d %s)' % (chain.get_branch_size(), _('blocks'))
else:
msg = ''
self.split_label.setText(msg)
self.nodes_list_widget.update(self.network)
def fill_in_proxy_settings(self):
proxy_config = self.network.get_parameters().proxy
if not proxy_config:
proxy_config = {"mode": "none", "host": "localhost", "port": "9050"}
b = proxy_config.get('mode') != "none"
self.check_disable_proxy(b)
if b:
self.proxy_cb.setChecked(True)
self.proxy_mode.setCurrentIndex(
self.proxy_mode.findText(str(proxy_config.get("mode").upper())))
self.proxy_host.setText(proxy_config.get("host"))
self.proxy_port.setText(proxy_config.get("port"))
self.proxy_user.setText(proxy_config.get("user", ""))
self.proxy_password.setText(proxy_config.get("password", ""))
def layout(self):
return self.layout_
def set_protocol(self, protocol):
if protocol != self.protocol:
self.protocol = protocol
def change_protocol(self, use_ssl):
p = 's' if use_ssl else 't'
host = self.server_host.text()
pp = self.servers.get(host, constants.net.DEFAULT_PORTS)
if p not in pp.keys():
p = list(pp.keys())[0]
port = pp[p]
self.server_host.setText(host)
self.server_port.setText(port)
self.set_protocol(p)
self.set_server()
def follow_branch(self, chain_id):
self.network.run_from_another_thread(self.network.follow_chain_given_id(chain_id))
self.update()
def follow_server(self, server):
self.network.run_from_another_thread(self.network.follow_chain_given_server(server))
self.update()
def server_changed(self, x):
if x:
self.change_server(str(x.text(0)), self.protocol)
def change_server(self, host, protocol):
pp = self.servers.get(host, constants.net.DEFAULT_PORTS)
if protocol and protocol not in protocol_letters:
protocol = None
if protocol:
port = pp.get(protocol)
if port is None:
protocol = None
if not protocol:
if 's' in pp.keys():
protocol = 's'
port = pp.get(protocol)
else:
protocol = list(pp.keys())[0]
port = pp.get(protocol)
self.server_host.setText(host)
self.server_port.setText(port)
def accept(self):
pass
def set_server(self):
net_params = self.network.get_parameters()
net_params = net_params._replace(host=str(self.server_host.text()),
port=str(self.server_port.text()),
auto_connect=self.autoconnect_cb.isChecked())
self.network.run_from_another_thread(self.network.set_parameters(net_params))
def set_proxy(self):
net_params = self.network.get_parameters()
if self.proxy_cb.isChecked():
proxy = { 'mode':str(self.proxy_mode.currentText()).lower(),
'host':str(self.proxy_host.text()),
'port':str(self.proxy_port.text()),
'user':str(self.proxy_user.text()),
'password':str(self.proxy_password.text())}
else:
proxy = None
self.tor_cb.setChecked(False)
net_params = net_params._replace(proxy=proxy)
self.network.run_from_another_thread(self.network.set_parameters(net_params))
def suggest_proxy(self, found_proxy):
if found_proxy is None:
self.tor_cb.hide()
return
self.tor_proxy = found_proxy
self.tor_cb.setText("Use Tor proxy at port " + str(found_proxy[1]))
if (self.proxy_cb.isChecked()
and self.proxy_mode.currentIndex() == self.proxy_mode.findText('SOCKS5')
and self.proxy_host.text() == "127.0.0.1"
and self.proxy_port.text() == str(found_proxy[1])):
self.tor_cb.setChecked(True)
self.tor_cb.show()
def use_tor_proxy(self, use_it):
if not use_it:
self.proxy_cb.setChecked(False)
else:
socks5_mode_index = self.proxy_mode.findText('SOCKS5')
if socks5_mode_index == -1:
_logger.info("can't find proxy_mode 'SOCKS5'")
return
self.proxy_mode.setCurrentIndex(socks5_mode_index)
self.proxy_host.setText("127.0.0.1")
self.proxy_port.setText(str(self.tor_proxy[1]))
self.proxy_user.setText("")
self.proxy_password.setText("")
self.tor_cb.setChecked(True)
self.proxy_cb.setChecked(True)
self.check_disable_proxy(use_it)
self.set_proxy()
def proxy_settings_changed(self):
self.tor_cb.setChecked(False)
def use_tor_auto_on(self, use_it):
self.config.set_key('tor_auto_on', use_it, True)
class TorDetector(QThread):
found_proxy = pyqtSignal(object)
def __init__(self):
QThread.__init__(self)
def run(self):
# Probable ports for Tor to listen at
ports = [9050, 9150]
while True:
for p in ports:
net_addr = ("127.0.0.1", p)
if TorDetector.is_tor_port(net_addr):
self.found_proxy.emit(net_addr)
break
else:
self.found_proxy.emit(None)
time.sleep(10)
@staticmethod
def is_tor_port(net_addr: Tuple[str, int]) -> bool:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(0.1)
s.connect(net_addr)
# Tor responds uniquely to HTTP-like requests
s.send(b"GET\n")
if b"Tor is not an HTTP Proxy" in s.recv(1024):
return True
except socket.error:
pass
return False
| [
"time.sleep",
"PyQt5.QtWidgets.QTreeWidget.__init__",
"PyQt5.QtWidgets.QVBoxLayout",
"PyQt5.QtCore.QThread.__init__",
"PyQt5.QtWidgets.QComboBox",
"PyQt5.QtWidgets.QTreeWidget.keyPressEvent",
"electrum_trc.logging.get_logger",
"PyQt5.QtWidgets.QLabel",
"PyQt5.QtWidgets.QLineEdit",
"PyQt5.QtWidgets... | [((1889, 1909), 'electrum_trc.logging.get_logger', 'get_logger', (['__name__'], {}), '(__name__)\n', (1899, 1909), False, 'from electrum_trc.logging import get_logger\n'), ((21242, 21260), 'PyQt5.QtCore.pyqtSignal', 'pyqtSignal', (['object'], {}), '(object)\n', (21252, 21260), False, 'from PyQt5.QtCore import Qt, pyqtSignal, QThread\n'), ((2075, 2097), 'PyQt5.QtWidgets.QDialog.__init__', 'QDialog.__init__', (['self'], {}), '(self)\n', (2091, 2097), False, 'from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QMenu, QGridLayout, QComboBox, QLineEdit, QDialog, QVBoxLayout, QHeaderView, QCheckBox, QTabWidget, QWidget, QLabel\n'), ((2331, 2348), 'PyQt5.QtWidgets.QVBoxLayout', 'QVBoxLayout', (['self'], {}), '(self)\n', (2342, 2348), False, 'from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QMenu, QGridLayout, QComboBox, QLineEdit, QDialog, QVBoxLayout, QHeaderView, QCheckBox, QTabWidget, QWidget, QLabel\n'), ((2876, 2902), 'PyQt5.QtWidgets.QTreeWidget.__init__', 'QTreeWidget.__init__', (['self'], {}), '(self)\n', (2896, 2902), False, 'from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QMenu, QGridLayout, QComboBox, QLineEdit, QDialog, QVBoxLayout, QHeaderView, QCheckBox, QTabWidget, QWidget, QLabel\n'), ((3302, 3309), 'PyQt5.QtWidgets.QMenu', 'QMenu', ([], {}), '()\n', (3307, 3309), False, 'from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QMenu, QGridLayout, QComboBox, QLineEdit, QDialog, QVBoxLayout, QHeaderView, QCheckBox, QTabWidget, QWidget, QLabel\n'), ((5532, 5558), 'PyQt5.QtWidgets.QTreeWidget.__init__', 'QTreeWidget.__init__', (['self'], {}), '(self)\n', (5552, 5558), False, 'from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QMenu, QGridLayout, QComboBox, QLineEdit, QDialog, QVBoxLayout, QHeaderView, QCheckBox, QTabWidget, QWidget, QLabel\n'), ((5890, 5897), 'PyQt5.QtWidgets.QMenu', 'QMenu', ([], {}), '()\n', (5895, 5897), False, 'from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QMenu, QGridLayout, QComboBox, QLineEdit, QDialog, QVBoxLayout, QHeaderView, QCheckBox, QTabWidget, QWidget, QLabel\n'), ((6161, 6182), 'electrum_trc.interface.deserialize_server', 'deserialize_server', (['s'], {}), '(s)\n', (6179, 6182), False, 'from electrum_trc.interface import serialize_server, deserialize_server\n'), ((7722, 7734), 'PyQt5.QtWidgets.QTabWidget', 'QTabWidget', ([], {}), '()\n', (7732, 7734), False, 'from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QMenu, QGridLayout, QComboBox, QLineEdit, QDialog, QVBoxLayout, QHeaderView, QCheckBox, QTabWidget, QWidget, QLabel\n'), ((7756, 7765), 'PyQt5.QtWidgets.QWidget', 'QWidget', ([], {}), '()\n', (7763, 7765), False, 'from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QMenu, QGridLayout, QComboBox, QLineEdit, QDialog, QVBoxLayout, QHeaderView, QCheckBox, QTabWidget, QWidget, QLabel\n'), ((7786, 7795), 'PyQt5.QtWidgets.QWidget', 'QWidget', ([], {}), '()\n', (7793, 7795), False, 'from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QMenu, QGridLayout, QComboBox, QLineEdit, QDialog, QVBoxLayout, QHeaderView, QCheckBox, QTabWidget, QWidget, QLabel\n'), ((7821, 7830), 'PyQt5.QtWidgets.QWidget', 'QWidget', ([], {}), '()\n', (7828, 7830), False, 'from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QMenu, QGridLayout, QComboBox, QLineEdit, QDialog, QVBoxLayout, QHeaderView, QCheckBox, QTabWidget, QWidget, QLabel\n'), ((8125, 8148), 'PyQt5.QtWidgets.QGridLayout', 'QGridLayout', (['server_tab'], {}), '(server_tab)\n', (8136, 8148), False, 'from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QMenu, QGridLayout, QComboBox, QLineEdit, QDialog, QVBoxLayout, QHeaderView, QCheckBox, QTabWidget, QWidget, QLabel\n'), ((8204, 8215), 'PyQt5.QtWidgets.QLineEdit', 'QLineEdit', ([], {}), '()\n', (8213, 8215), False, 'from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QMenu, QGridLayout, QComboBox, QLineEdit, QDialog, QVBoxLayout, QHeaderView, QCheckBox, QTabWidget, QWidget, QLabel\n'), ((8304, 8315), 'PyQt5.QtWidgets.QLineEdit', 'QLineEdit', ([], {}), '()\n', (8313, 8315), False, 'from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QMenu, QGridLayout, QComboBox, QLineEdit, QDialog, QVBoxLayout, QHeaderView, QCheckBox, QTabWidget, QWidget, QLabel\n'), ((9620, 9642), 'PyQt5.QtWidgets.QGridLayout', 'QGridLayout', (['proxy_tab'], {}), '(proxy_tab)\n', (9631, 9642), False, 'from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QMenu, QGridLayout, QComboBox, QLineEdit, QDialog, QVBoxLayout, QHeaderView, QCheckBox, QTabWidget, QWidget, QLabel\n'), ((9890, 9901), 'PyQt5.QtWidgets.QComboBox', 'QComboBox', ([], {}), '()\n', (9899, 9901), False, 'from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QMenu, QGridLayout, QComboBox, QLineEdit, QDialog, QVBoxLayout, QHeaderView, QCheckBox, QTabWidget, QWidget, QLabel\n'), ((9983, 9994), 'PyQt5.QtWidgets.QLineEdit', 'QLineEdit', ([], {}), '()\n', (9992, 9994), False, 'from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QMenu, QGridLayout, QComboBox, QLineEdit, QDialog, QVBoxLayout, QHeaderView, QCheckBox, QTabWidget, QWidget, QLabel\n'), ((10081, 10092), 'PyQt5.QtWidgets.QLineEdit', 'QLineEdit', ([], {}), '()\n', (10090, 10092), False, 'from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QMenu, QGridLayout, QComboBox, QLineEdit, QDialog, QVBoxLayout, QHeaderView, QCheckBox, QTabWidget, QWidget, QLabel\n'), ((10175, 10186), 'PyQt5.QtWidgets.QLineEdit', 'QLineEdit', ([], {}), '()\n', (10184, 10186), False, 'from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QMenu, QGridLayout, QComboBox, QLineEdit, QDialog, QVBoxLayout, QHeaderView, QCheckBox, QTabWidget, QWidget, QLabel\n'), ((10277, 10288), 'PyQt5.QtWidgets.QLineEdit', 'QLineEdit', ([], {}), '()\n', (10286, 10288), False, 'from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QMenu, QGridLayout, QComboBox, QLineEdit, QDialog, QVBoxLayout, QHeaderView, QCheckBox, QTabWidget, QWidget, QLabel\n'), ((12352, 12379), 'PyQt5.QtWidgets.QGridLayout', 'QGridLayout', (['blockchain_tab'], {}), '(blockchain_tab)\n', (12363, 12379), False, 'from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QMenu, QGridLayout, QComboBox, QLineEdit, QDialog, QVBoxLayout, QHeaderView, QCheckBox, QTabWidget, QWidget, QLabel\n'), ((12681, 12691), 'PyQt5.QtWidgets.QLabel', 'QLabel', (['""""""'], {}), "('')\n", (12687, 12691), False, 'from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QMenu, QGridLayout, QComboBox, QLineEdit, QDialog, QVBoxLayout, QHeaderView, QCheckBox, QTabWidget, QWidget, QLabel\n'), ((12877, 12887), 'PyQt5.QtWidgets.QLabel', 'QLabel', (['""""""'], {}), "('')\n", (12883, 12887), False, 'from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QMenu, QGridLayout, QComboBox, QLineEdit, QDialog, QVBoxLayout, QHeaderView, QCheckBox, QTabWidget, QWidget, QLabel\n'), ((12902, 13024), 'electrum_trc.i18n._', '_', (['"""Terracoin Electrum sends your wallet addresses to a single server, in order to receive your transaction history."""'], {}), "('Terracoin Electrum sends your wallet addresses to a single server, in order to receive your transaction history.'\n )\n", (12903, 13024), False, 'from electrum_trc.i18n import _\n'), ((13205, 13215), 'PyQt5.QtWidgets.QLabel', 'QLabel', (['""""""'], {}), "('')\n", (13211, 13215), False, 'from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QMenu, QGridLayout, QComboBox, QLineEdit, QDialog, QVBoxLayout, QHeaderView, QCheckBox, QTabWidget, QWidget, QLabel\n'), ((13230, 13291), 'electrum_trc.i18n._', '_', (['"""This is the height of your local copy of the blockchain."""'], {}), "('This is the height of your local copy of the blockchain.')\n", (13231, 13291), False, 'from electrum_trc.i18n import _\n'), ((13474, 13484), 'PyQt5.QtWidgets.QLabel', 'QLabel', (['""""""'], {}), "('')\n", (13480, 13484), False, 'from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QMenu, QGridLayout, QComboBox, QLineEdit, QDialog, QVBoxLayout, QHeaderView, QCheckBox, QTabWidget, QWidget, QLabel\n'), ((13669, 13682), 'PyQt5.QtWidgets.QVBoxLayout', 'QVBoxLayout', ([], {}), '()\n', (13680, 13682), False, 'from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QMenu, QGridLayout, QComboBox, QLineEdit, QDialog, QVBoxLayout, QHeaderView, QCheckBox, QTabWidget, QWidget, QLabel\n'), ((21294, 21316), 'PyQt5.QtCore.QThread.__init__', 'QThread.__init__', (['self'], {}), '(self)\n', (21310, 21316), False, 'from PyQt5.QtCore import Qt, pyqtSignal, QThread\n'), ((2126, 2147), 'electrum_trc.i18n._', '_', (['"""Electrum Network"""'], {}), "('Electrum Network')\n", (2127, 2147), False, 'from electrum_trc.i18n import _\n'), ((3878, 3916), 'PyQt5.QtWidgets.QTreeWidget.keyPressEvent', 'QTreeWidget.keyPressEvent', (['self', 'event'], {}), '(self, event)\n', (3903, 3916), False, 'from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QMenu, QGridLayout, QComboBox, QLineEdit, QDialog, QVBoxLayout, QHeaderView, QCheckBox, QTabWidget, QWidget, QLabel\n'), ((4368, 4404), 'electrum_trc.blockchain.blockchains.get', 'blockchain.blockchains.get', (['chain_id'], {}), '(chain_id)\n', (4394, 4404), False, 'from electrum_trc import constants, blockchain\n'), ((5989, 6007), 'electrum_trc.i18n._', '_', (['"""Use as server"""'], {}), "('Use as server')\n", (5990, 6007), False, 'from electrum_trc.i18n import _\n'), ((6499, 6537), 'PyQt5.QtWidgets.QTreeWidget.keyPressEvent', 'QTreeWidget.keyPressEvent', (['self', 'event'], {}), '(self, event)\n', (6524, 6537), False, 'from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QMenu, QGridLayout, QComboBox, QLineEdit, QDialog, QVBoxLayout, QHeaderView, QCheckBox, QTabWidget, QWidget, QLabel\n'), ((7867, 7880), 'electrum_trc.i18n._', '_', (['"""Overview"""'], {}), "('Overview')\n", (7868, 7880), False, 'from electrum_trc.i18n import _\n'), ((7914, 7925), 'electrum_trc.i18n._', '_', (['"""Server"""'], {}), "('Server')\n", (7915, 7925), False, 'from electrum_trc.i18n import _\n'), ((7958, 7968), 'electrum_trc.i18n._', '_', (['"""Proxy"""'], {}), "('Proxy')\n", (7959, 7968), False, 'from electrum_trc.i18n import _\n'), ((8413, 8445), 'electrum_trc.i18n._', '_', (['"""Select server automatically"""'], {}), "('Select server automatically')\n", (8414, 8445), False, 'from electrum_trc.i18n import _\n'), ((9359, 9376), 'electrum_trc.i18n._', '_', (['"""Server peers"""'], {}), "('Server peers')\n", (9360, 9376), False, 'from electrum_trc.i18n import _\n'), ((9408, 9428), 'electrum_trc.i18n._', '_', (['"""Default Servers"""'], {}), "('Default Servers')\n", (9409, 9428), False, 'from electrum_trc.i18n import _\n'), ((9452, 9465), 'PyQt5.QtWidgets.QLabel', 'QLabel', (['label'], {}), '(label)\n', (9458, 9465), False, 'from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QMenu, QGridLayout, QComboBox, QLineEdit, QDialog, QVBoxLayout, QHeaderView, QCheckBox, QTabWidget, QWidget, QLabel\n'), ((9729, 9743), 'electrum_trc.i18n._', '_', (['"""Use proxy"""'], {}), "('Use proxy')\n", (9730, 9743), False, 'from electrum_trc.i18n import _\n'), ((10230, 10245), 'electrum_trc.i18n._', '_', (['"""Proxy user"""'], {}), "('Proxy user')\n", (10231, 10245), False, 'from electrum_trc.i18n import _\n'), ((10336, 10349), 'electrum_trc.i18n._', '_', (['"""Password"""'], {}), "('Password')\n", (10337, 10349), False, 'from electrum_trc.i18n import _\n'), ((11207, 11225), 'electrum_trc.i18n._', '_', (['"""Use Tor Proxy"""'], {}), "('Use Tor Proxy')\n", (11208, 11225), False, 'from electrum_trc.i18n import _\n'), ((11404, 11433), 'electrum_trc.i18n._', '_', (['"""Use Tor Proxy on startup"""'], {}), "('Use Tor Proxy on startup')\n", (11405, 11433), False, 'from electrum_trc.i18n import _\n'), ((15170, 15179), 'electrum_trc.i18n._', '_', (['"""None"""'], {}), "('None')\n", (15171, 15179), False, 'from electrum_trc.i18n import _\n'), ((15491, 15502), 'electrum_trc.i18n._', '_', (['"""blocks"""'], {}), "('blocks')\n", (15492, 15502), False, 'from electrum_trc.i18n import _\n'), ((15662, 15680), 'electrum_trc.i18n._', '_', (['"""Not connected"""'], {}), "('Not connected')\n", (15663, 15680), False, 'from electrum_trc.i18n import _\n'), ((21710, 21724), 'time.sleep', 'time.sleep', (['(10)'], {}), '(10)\n', (21720, 21724), False, 'import time\n'), ((21829, 21878), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (21842, 21878), False, 'import socket\n'), ((2962, 2981), 'electrum_trc.i18n._', '_', (['"""Connected node"""'], {}), "('Connected node')\n", (2963, 2981), False, 'from electrum_trc.i18n import _\n'), ((2983, 2994), 'electrum_trc.i18n._', '_', (['"""Height"""'], {}), "('Height')\n", (2984, 2994), False, 'from electrum_trc.i18n import _\n'), ((3406, 3424), 'electrum_trc.i18n._', '_', (['"""Use as server"""'], {}), "('Use as server')\n", (3407, 3424), False, 'from electrum_trc.i18n import _\n'), ((3559, 3582), 'electrum_trc.i18n._', '_', (['"""Follow this branch"""'], {}), "('Follow this branch')\n", (3560, 3582), False, 'from electrum_trc.i18n import _\n'), ((4852, 4898), 'PyQt5.QtWidgets.QTreeWidgetItem', 'QTreeWidgetItem', (["[i.host + star, '%d' % i.tip]"], {}), "([i.host + star, '%d' % i.tip])\n", (4867, 4898), False, 'from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QMenu, QGridLayout, QComboBox, QLineEdit, QDialog, QVBoxLayout, QHeaderView, QCheckBox, QTabWidget, QWidget, QLabel\n'), ((5618, 5627), 'electrum_trc.i18n._', '_', (['"""Host"""'], {}), "('Host')\n", (5619, 5627), False, 'from electrum_trc.i18n import _\n'), ((5629, 5638), 'electrum_trc.i18n._', '_', (['"""Port"""'], {}), "('Port')\n", (5630, 5638), False, 'from electrum_trc.i18n import _\n'), ((7019, 7049), 'PyQt5.QtWidgets.QTreeWidgetItem', 'QTreeWidgetItem', (['[_host, port]'], {}), '([_host, port])\n', (7034, 7049), False, 'from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QMenu, QGridLayout, QComboBox, QLineEdit, QDialog, QVBoxLayout, QHeaderView, QCheckBox, QTabWidget, QWidget, QLabel\n'), ((7075, 7114), 'electrum_trc.interface.serialize_server', 'serialize_server', (['_host', 'port', 'protocol'], {}), '(_host, port, protocol)\n', (7091, 7114), False, 'from electrum_trc.interface import serialize_server, deserialize_server\n'), ((8818, 8934), 'electrum_trc.i18n._', '_', (['"""If auto-connect is enabled, Terracoin Electrum will always use a server that is on the longest blockchain."""'], {}), "('If auto-connect is enabled, Terracoin Electrum will always use a server that is on the longest blockchain.'\n )\n", (8819, 8934), False, 'from electrum_trc.i18n import _\n'), ((8943, 9076), 'electrum_trc.i18n._', '_', (['"""If it is disabled, you have to choose a server you want to use. Terracoin Electrum will warn you if your server is lagging."""'], {}), "('If it is disabled, you have to choose a server you want to use. Terracoin Electrum will warn you if your server is lagging.'\n )\n", (8944, 9076), False, 'from electrum_trc.i18n import _\n'), ((11766, 11885), 'electrum_trc.i18n._', '_', (['"""Proxy settings apply to all connections: with Terracoin Electrum servers, but also with third-party services."""'], {}), "('Proxy settings apply to all connections: with Terracoin Electrum servers, but also with third-party services.'\n )\n", (11767, 11885), False, 'from electrum_trc.i18n import _\n'), ((12210, 12269), 'electrum_trc.i18n._', '_', (['"""During wallet startup try to detect and use Tor Proxy."""'], {}), "('During wallet startup try to detect and use Tor Proxy.')\n", (12211, 12269), False, 'from electrum_trc.i18n import _\n'), ((12418, 12544), 'electrum_trc.i18n._', '_', (['"""Terracoin Electrum connects to several nodes in order to download block headers and find out the longest blockchain."""'], {}), "('Terracoin Electrum connects to several nodes in order to download block headers and find out the longest blockchain.'\n )\n", (12419, 12544), False, 'from electrum_trc.i18n import _\n'), ((12553, 12646), 'electrum_trc.i18n._', '_', (['"""This blockchain is used to verify the transactions sent by your transaction server."""'], {}), "('This blockchain is used to verify the transactions sent by your transaction server.'\n )\n", (12554, 12646), False, 'from electrum_trc.i18n import _\n'), ((9216, 9227), 'electrum_trc.i18n._', '_', (['"""Server"""'], {}), "('Server')\n", (9217, 9227), False, 'from electrum_trc.i18n import _\n'), ((12722, 12733), 'electrum_trc.i18n._', '_', (['"""Status"""'], {}), "('Status')\n", (12723, 12733), False, 'from electrum_trc.i18n import _\n'), ((13050, 13061), 'electrum_trc.i18n._', '_', (['"""Server"""'], {}), "('Server')\n", (13051, 13061), False, 'from electrum_trc.i18n import _\n'), ((13322, 13337), 'electrum_trc.i18n._', '_', (['"""Blockchain"""'], {}), "('Blockchain')\n", (13323, 13337), False, 'from electrum_trc.i18n import _\n'), ((15613, 15641), 'electrum_trc.i18n._', '_', (['"""Connected to {0} nodes."""'], {}), "('Connected to {0} nodes.')\n", (15614, 15641), False, 'from electrum_trc.i18n import _\n'), ((16185, 16196), 'electrum_trc.i18n._', '_', (['"""blocks"""'], {}), "('blocks')\n", (16186, 16196), False, 'from electrum_trc.i18n import _\n'), ((15949, 15987), 'electrum_trc.i18n._', '_', (['"""Chain split detected at block {0}"""'], {}), "('Chain split detected at block {0}')\n", (15950, 15987), False, 'from electrum_trc.i18n import _\n'), ((16033, 16062), 'electrum_trc.i18n._', '_', (['"""You are following branch"""'], {}), "('You are following branch')\n", (16034, 16062), False, 'from electrum_trc.i18n import _\n'), ((16084, 16113), 'electrum_trc.i18n._', '_', (['"""Your server is on branch"""'], {}), "('Your server is on branch')\n", (16085, 16113), False, 'from electrum_trc.i18n import _\n')] |
"""bootcamp URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf import settings
from django.contrib import admin
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib.auth import views as auth_views
from .core import views as core_views
from .search import views as search_views
from .authentication import views as authentication_views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^i18n/', include('django.conf.urls.i18n', namespace='i18n')),
url(r'^$', core_views.home, name='home'),
url(r'^login', auth_views.login,
{'template_name': 'core/cover.html'}, name='login'),
url(r'^logout', auth_views.logout, {'next_page': '/'}, name='logout'),
url(r'^signup/$', authentication_views.signup, name='signup'),
url(r'^feeds/', include('bootcamp.feeds.urls')),
url(r'^settings/', include('bootcamp.core.urls')),
url(r'^articles/', include('bootcamp.articles.urls')),
url(r'^messages/', include('bootcamp.messenger.urls')),
url(r'^questions/', include('bootcamp.questions.urls')),
url(r'^notifications/', include('bootcamp.activities.urls')),
url(r'^search/$', search_views.search, name='search'),
url(r'^network/$', core_views.network, name='network'),
url(r'^(?P<username>[^/]+)/$', core_views.profile, name='profile'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
| [
"django.conf.urls.static.static",
"django.conf.urls.include",
"django.conf.urls.url"
] | [((1007, 1038), 'django.conf.urls.url', 'url', (['"""^admin/"""', 'admin.site.urls'], {}), "('^admin/', admin.site.urls)\n", (1010, 1038), False, 'from django.conf.urls import include, url\n'), ((1118, 1157), 'django.conf.urls.url', 'url', (['"""^$"""', 'core_views.home'], {'name': '"""home"""'}), "('^$', core_views.home, name='home')\n", (1121, 1157), False, 'from django.conf.urls import include, url\n'), ((1164, 1252), 'django.conf.urls.url', 'url', (['"""^login"""', 'auth_views.login', "{'template_name': 'core/cover.html'}"], {'name': '"""login"""'}), "('^login', auth_views.login, {'template_name': 'core/cover.html'}, name=\n 'login')\n", (1167, 1252), False, 'from django.conf.urls import include, url\n'), ((1262, 1330), 'django.conf.urls.url', 'url', (['"""^logout"""', 'auth_views.logout', "{'next_page': '/'}"], {'name': '"""logout"""'}), "('^logout', auth_views.logout, {'next_page': '/'}, name='logout')\n", (1265, 1330), False, 'from django.conf.urls import include, url\n'), ((1337, 1397), 'django.conf.urls.url', 'url', (['"""^signup/$"""', 'authentication_views.signup'], {'name': '"""signup"""'}), "('^signup/$', authentication_views.signup, name='signup')\n", (1340, 1397), False, 'from django.conf.urls import include, url\n'), ((1760, 1812), 'django.conf.urls.url', 'url', (['"""^search/$"""', 'search_views.search'], {'name': '"""search"""'}), "('^search/$', search_views.search, name='search')\n", (1763, 1812), False, 'from django.conf.urls import include, url\n'), ((1819, 1872), 'django.conf.urls.url', 'url', (['"""^network/$"""', 'core_views.network'], {'name': '"""network"""'}), "('^network/$', core_views.network, name='network')\n", (1822, 1872), False, 'from django.conf.urls import include, url\n'), ((1879, 1944), 'django.conf.urls.url', 'url', (['"""^(?P<username>[^/]+)/$"""', 'core_views.profile'], {'name': '"""profile"""'}), "('^(?P<username>[^/]+)/$', core_views.profile, name='profile')\n", (1882, 1944), False, 'from django.conf.urls import include, url\n'), ((1988, 2049), 'django.conf.urls.static.static', 'static', (['settings.MEDIA_URL'], {'document_root': 'settings.MEDIA_ROOT'}), '(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n', (1994, 2049), False, 'from django.conf.urls.static import static\n'), ((1060, 1110), 'django.conf.urls.include', 'include', (['"""django.conf.urls.i18n"""'], {'namespace': '"""i18n"""'}), "('django.conf.urls.i18n', namespace='i18n')\n", (1067, 1110), False, 'from django.conf.urls import include, url\n'), ((1421, 1451), 'django.conf.urls.include', 'include', (['"""bootcamp.feeds.urls"""'], {}), "('bootcamp.feeds.urls')\n", (1428, 1451), False, 'from django.conf.urls import include, url\n'), ((1477, 1506), 'django.conf.urls.include', 'include', (['"""bootcamp.core.urls"""'], {}), "('bootcamp.core.urls')\n", (1484, 1506), False, 'from django.conf.urls import include, url\n'), ((1532, 1565), 'django.conf.urls.include', 'include', (['"""bootcamp.articles.urls"""'], {}), "('bootcamp.articles.urls')\n", (1539, 1565), False, 'from django.conf.urls import include, url\n'), ((1591, 1625), 'django.conf.urls.include', 'include', (['"""bootcamp.messenger.urls"""'], {}), "('bootcamp.messenger.urls')\n", (1598, 1625), False, 'from django.conf.urls import include, url\n'), ((1652, 1686), 'django.conf.urls.include', 'include', (['"""bootcamp.questions.urls"""'], {}), "('bootcamp.questions.urls')\n", (1659, 1686), False, 'from django.conf.urls import include, url\n'), ((1717, 1752), 'django.conf.urls.include', 'include', (['"""bootcamp.activities.urls"""'], {}), "('bootcamp.activities.urls')\n", (1724, 1752), False, 'from django.conf.urls import include, url\n')] |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from typing import Iterable
import torch
from ._base_schedule import BaseSchedule
from colossalai.utils import conditional_context
class NonPipelineSchedule(BaseSchedule):
"""A helper schedule class for no pipeline parallelism running environment.
During one process, it loads a batch of dataset and feeds it to the model.
After getting the output and calculating the loss, it will use :meth:`step`
to update the parameters if it is in training mode.
Args:
batch_data_process_func (Callable, optional): The preprocessing function which receives a batch of data,
and it will be executed in load_batch.
"""
def forward_backward_step(self,
engine,
data_iter: Iterable,
forward_only: bool = False,
return_loss: bool = True,
return_output_label: bool = True):
"""The process function that loads a batch of dataset and feeds it to the model.
The returned labels and loss will None if :attr:`return_loss` is False.
Args:
engine (colossalai.engine.Engine): Colossalai engine for training and inference.
data_iter (Iterable): Dataloader as the form of an iterator, obtained by calling iter(dataloader).
forward_only (bool, optional):
If True, the model is run for the forward pass, else back propagation will be executed.
return_loss (bool, optional): Loss will be returned if True.
return_output_label (bool, optional): Output and label will be returned if True.
Returns:
Tuple[:class:`torch.Tensor`]: A tuple of (output, label, loss), loss and label could be None.
"""
assert forward_only or return_loss, \
"The argument 'return_loss' has to be True when 'forward_only' is False, but got False."
data, label = self.load_batch(data_iter)
# forward
with conditional_context(torch.no_grad(), enable=forward_only):
output = self._call_engine(engine, data)
if return_loss:
loss = self._call_engine_criterion(engine, output, label)
if not forward_only:
engine.backward(loss)
if return_output_label:
if return_loss:
return output, label, loss
else:
return output, label, None
else:
if return_loss:
return None, None, loss
else:
return None, None, None
| [
"torch.no_grad"
] | [((2089, 2104), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2102, 2104), False, 'import torch\n')] |
from __future__ import unicode_literals
import os
import sys
import urllib
import datetime
import logging
import subprocess
import eeUtil
import time
import requests
import json
# url for bleaching alert data
SOURCE_URL = 'ftp://ftp.star.nesdis.noaa.gov/pub/sod/mecb/crw/data/5km/v3.1/nc/v1.0/daily/baa-max-7d/{year}/ct5km_baa-max-7d_v3.1_{date}.nc'
# subdataset to be converted to tif
# should be of the format 'NETCDF:"filename.nc":variable'
SDS_NAME = 'NETCDF:"{fname}":bleaching_alert_area'
# filename format for GEE
FILENAME = 'bio_005_{date}'
# nodata value for netcdf
# this netcdf has a nodata value of -5
# GEE can't accept a negative no data value, set to 251 for Byte type?
NODATA_VALUE = 251
# name of data directory in Docker container
DATA_DIR = 'data'
# name of folder to store data in Google Cloud Storage
GS_FOLDER = 'bio_005_bleaching_alerts'
# name of collection in GEE where we will upload the final data
EE_COLLECTION = 'bio_005_bleaching_alerts'
# do you want to delete everything currently in the GEE collection when you run this script?
CLEAR_COLLECTION_FIRST = False
# how many assets can be stored in the GEE collection before the oldest ones are deleted?
MAX_ASSETS = 61
# format of date (used in both the source data files and GEE)
DATE_FORMAT = '%Y%m%d'
# Resource Watch dataset API ID
# Important! Before testing this script:
# Please change this ID OR comment out the getLayerIDs(DATASET_ID) function in the script below
# Failing to do so will overwrite the last update date on a different dataset on Resource Watch
DATASET_ID = 'e2a2d074-8428-410e-920c-325bbe363a2e'
'''
FUNCTIONS FOR ALL DATASETS
The functions below must go in every near real-time script.
Their format should not need to be changed.
'''
def lastUpdateDate(dataset, date):
'''
Given a Resource Watch dataset's API ID and a datetime,
this function will update the dataset's 'last update date' on the API with the given datetime
INPUT dataset: Resource Watch API dataset ID (string)
date: date to set as the 'last update date' for the input dataset (datetime)
'''
# generate the API url for this dataset
apiUrl = f'http://api.resourcewatch.org/v1/dataset/{dataset}'
# create headers to send with the request to update the 'last update date'
headers = {
'Content-Type': 'application/json',
'Authorization': os.getenv('apiToken')
}
# create the json data to send in the request
body = {
"dataLastUpdated": date.isoformat() # date should be a string in the format 'YYYY-MM-DDTHH:MM:SS'
}
# send the request
try:
r = requests.patch(url = apiUrl, json = body, headers = headers)
logging.info('[lastUpdated]: SUCCESS, '+ date.isoformat() +' status code '+str(r.status_code))
return 0
except Exception as e:
logging.error('[lastUpdated]: '+str(e))
'''
FUNCTIONS FOR RASTER DATASETS
The functions below must go in every near real-time script for a RASTER dataset.
Their format should not need to be changed.
'''
def getLastUpdate(dataset):
'''
Given a Resource Watch dataset's API ID,
this function will get the current 'last update date' from the API
and return it as a datetime
INPUT dataset: Resource Watch API dataset ID (string)
RETURN lastUpdateDT: current 'last update date' for the input dataset (datetime)
'''
# generate the API url for this dataset
apiUrl = f'http://api.resourcewatch.org/v1/dataset/{dataset}'
# pull the dataset from the API
r = requests.get(apiUrl)
# find the 'last update date'
lastUpdateString=r.json()['data']['attributes']['dataLastUpdated']
# split this date into two pieces at the seconds decimal so that the datetime module can read it:
# ex: '2020-03-11T00:00:00.000Z' will become '2020-03-11T00:00:00' (nofrag) and '000Z' (frag)
nofrag, frag = lastUpdateString.split('.')
# generate a datetime object
nofrag_dt = datetime.datetime.strptime(nofrag, "%Y-%m-%dT%H:%M:%S")
# add back the microseconds to the datetime
lastUpdateDT = nofrag_dt.replace(microsecond=int(frag[:-1])*1000)
return lastUpdateDT
def getLayerIDs(dataset):
'''
Given a Resource Watch dataset's API ID,
this function will return a list of all the layer IDs associated with it
INPUT dataset: Resource Watch API dataset ID (string)
RETURN layerIDs: Resource Watch API layer IDs for the input dataset (list of strings)
'''
# generate the API url for this dataset - this must include the layers
apiUrl = f'http://api.resourcewatch.org/v1/dataset/{dataset}?includes=layer'
# pull the dataset from the API
r = requests.get(apiUrl)
#get a list of all the layers
layers = r.json()['data']['attributes']['layer']
# create an empty list to store the layer IDs
layerIDs =[]
# go through each layer and add its ID to the list
for layer in layers:
# only add layers that have Resource Watch listed as its application
if layer['attributes']['application']==['rw']:
layerIDs.append(layer['id'])
return layerIDs
def flushTileCache(layer_id):
"""
Given the API ID for a GEE layer on Resource Watch,
this function will clear the layer cache.
If the cache is not cleared, when you view the dataset on Resource Watch, old and new tiles will be mixed together.
INPUT layer_id: Resource Watch API layer ID (string)
"""
# generate the API url for this layer's cache
apiUrl = f'http://api.resourcewatch.org/v1/layer/{layer_id}/expire-cache'
# create headers to send with the request to clear the cache
headers = {
'Content-Type': 'application/json',
'Authorization': os.getenv('apiToken')
}
# clear the cache for the layer
# sometimetimes this fails, so we will try multiple times, if it does
# specify that we are on the first try
try_num=1
tries = 4
while try_num<tries:
try:
# try to delete the cache
r = requests.delete(url = apiUrl, headers = headers, timeout=1000)
# if we get a 200, the cache has been deleted
# if we get a 504 (gateway timeout) - the tiles are still being deleted, but it worked
if r.ok or r.status_code==504:
logging.info('[Cache tiles deleted] for {}: status code {}'.format(layer_id, r.status_code))
return r.status_code
# if we don't get a 200 or 504:
else:
# if we are not on our last try, wait 60 seconds and try to clear the cache again
if try_num < (tries-1):
logging.info('Cache failed to flush: status code {}'.format(r.status_code))
time.sleep(60)
logging.info('Trying again.')
# if we are on our last try, log that the cache flush failed
else:
logging.error('Cache failed to flush: status code {}'.format(r.status_code))
logging.error('Aborting.')
try_num += 1
except Exception as e:
logging.error('Failed: {}'.format(e))
'''
FUNCTIONS FOR THIS DATASET
The functions below have been tailored to this specific dataset.
They should all be checked because their format likely will need to be changed.
'''
def getUrl(date):
'''
format source url with date
INPUT date: date in the format YYYYMMDD (string)
RETURN source url to download data, formatted for the input date (string)
'''
return SOURCE_URL.format(year=date[:4], date=date)
def getAssetName(date):
'''
get asset name
INPUT date: date in the format of the DATE_FORMAT variable (string)
RETURN GEE asset name for input date (string)
'''
return os.path.join(EE_COLLECTION, FILENAME.format(date=date))
def getFilename(date):
'''
get netcdf filename to save source file as
INPUT date: date in the format of the DATE_FORMAT variable (string)
RETURN file name to save netcdf from source under (string)
'''
return os.path.join(DATA_DIR, '{}.nc'.format(FILENAME.format(date=date)))
def getDate(filename):
'''
get date from filename (last 8 characters of filename after removing extension)
INPUT filename: file name that ends in a date of the format YYYYMMDD (string)
RETURN date in the format YYYYMMDD (string)
'''
return os.path.splitext(os.path.basename(filename))[0][-8:]
def getNewDates(exclude_dates):
'''
Get new dates we want to try to fetch data for
INPUT exclude_dates: list of dates that we already have in GEE, in the format of the DATE_FORMAT variable (list of strings)
RETURN new_dates: list of new dates we want to try to get, in the format of the DATE_FORMAT variable (list of strings)
'''
# create empty list to store dates we want to fetch
new_dates = []
# start with today's date
date = datetime.date.today()
for i in range(MAX_ASSETS):
# go back one day at a time
date -= datetime.timedelta(days=1)
# generate a string from the date
datestr = date.strftime(DATE_FORMAT)
# if the date string is not the list of dates we already have, add it to the list of new dates to try and fetch
if datestr not in exclude_dates:
new_dates.append(datestr)
return new_dates
def convert(files):
'''
Convert netcdf files to tifs
INPUT files: list of file names for netcdfs that have already been downloaded (list of strings)
RETURN tifs: list of file names for tifs that have been generated (list of strings)
'''
# create an empty list to store the names of the tifs we generate
tifs = []
#go through each netcdf file and translate
for f in files:
# generate the subdatset name for current netcdf file
sds_path = SDS_NAME.format(fname=f)
# generate a name to save the tif file we will translate the netcdf file into
tif = '{}.tif'.format(os.path.splitext(f)[0])
# translate the netcdf into a tif
cmd = ['gdal_translate', '-q', '-a_nodata', str(NODATA_VALUE), sds_path, tif]
logging.debug('Converting {} to {}'.format(f, tif))
subprocess.call(cmd)
# add the new tif files to the list of tifs
tifs.append(tif)
return tifs
def fetch(dates):
'''
Fetch files by datestamp
INPUT dates: list of dates we want to try to fetch, in the format YYYYMMDD (list of strings)
RETURN files: list of file names for netcdfs that have been downloaded (list of strings)
'''
# make an empty list to store names of the files we downloaded
files = []
# go through each input date
for date in dates:
# get the url to download the file from the source for the given date
url = getUrl(date)
# get the filename we want to save the file under locally
f = getFilename(date)
logging.debug('Fetching {}'.format(url))
try:
# try to download the data
urllib.request.urlretrieve(url, f)
# if successful, add the file to the list of files we have downloaded
files.append(f)
except Exception as e:
# if unsuccessful, log that the file was not downloaded
# (could be because we are attempting to download a file that is not available yet)
logging.warning('Could not fetch {}'.format(url))
logging.debug(e)
return files
def processNewData(existing_dates):
'''
fetch, process, upload, and clean new data
INPUT existing_dates: list of dates we already have in GEE, in the format of the DATE_FORMAT variable (list of strings)
RETURN assets: list of file names for netcdfs that have been downloaded (list of strings)
'''
# Get list of new dates we want to try to fetch data for
new_dates = getNewDates(existing_dates)
# Fetch new files
logging.info('Fetching files')
files = fetch(new_dates)
# If we have successfully been able to fetch new data files
if files:
# Convert new files from netcdf to tif files
logging.info('Converting files to tifs')
tifs = convert(files)
logging.info('Uploading files')
# Get a list of the dates we have to upload from the tif file names
dates = [getDate(tif) for tif in tifs]
# Get a list of datetimes from these dates for each of the dates we are uploading
datestamps = [datetime.datetime.strptime(date, DATE_FORMAT) for date in dates]
# Get a list of the names we want to use for the assets once we upload the files to GEE
assets = [getAssetName(date) for date in dates]
# Upload new files (tifs) to GEE
eeUtil.uploadAssets(tifs, assets, GS_FOLDER, datestamps)
# Delete local files
logging.info('Cleaning local files')
for tif in tifs:
os.remove(tif)
for f in files:
os.remove(f)
return assets
return []
def checkCreateCollection(collection):
'''
List assests in collection if it exists, else create new collection
INPUT collection: GEE collection to check or create (string)
RETURN list of assets in collection (list of strings)
'''
# if collection exists, return list of assets in collection
if eeUtil.exists(collection):
return eeUtil.ls(collection)
# if collection does not exist, create it and return an empty list (because no assets are in the collection)
else:
logging.info('{} does not exist, creating'.format(collection))
eeUtil.createFolder(collection, True, public=True)
return []
def deleteExcessAssets(dates, max_assets):
'''
Delete oldest assets, if more than specified in max_assets variable
INPUT dates: dates for all the assets currently in the GEE collection; dates should be in the format specified
in DATE_FORMAT variable (list of strings)
max_assets: maximum number of assets allowed in the collection (int)
'''
# sort the list of dates so that the oldest is first
dates.sort()
# if we have more dates of data than allowed,
if len(dates) > max_assets:
# go through each date, starting with the oldest, and delete until we only have the max number of assets left
for date in dates[:-max_assets]:
eeUtil.removeAsset(getAssetName(date))
def get_most_recent_date(collection):
'''
Get most recent data we have assets for
INPUT collection: GEE collection to check dates for (string)
RETURN most_recent_date: most recent date in GEE collection (datetime)
'''
# get list of assets in collection
existing_assets = checkCreateCollection(collection)
# get a list of strings of dates in the collection
existing_dates = [getDate(a) for a in existing_assets]
# sort these dates oldest to newest
existing_dates.sort()
# get the most recent date (last in the list) and turn it into a datetime
most_recent_date = datetime.datetime.strptime(existing_dates[-1], DATE_FORMAT)
return most_recent_date
def create_headers():
'''
Create headers to perform authorized actions on API
'''
return {
'Content-Type': "application/json",
'Authorization': "{}".format(os.getenv('apiToken')),
}
def pull_layers_from_API(dataset_id):
'''
Pull dictionary of current layers from API
INPUT dataset_id: Resource Watch API dataset ID (string)
RETURN layer_dict: dictionary of layers (dictionary of strings)
'''
# generate url to access layer configs for this dataset in back office
rw_api_url = 'https://api.resourcewatch.org/v1/dataset/{}/layer?page[size]=100'.format(dataset_id)
# request data
r = requests.get(rw_api_url)
# convert response into json and make dictionary of layers
layer_dict = json.loads(r.content.decode('utf-8'))['data']
return layer_dict
def update_layer(layer, new_date):
'''
Update layers in Resource Watch back office.
INPUT layer: layer that will be updated (string)
new_date: date of asset to be shown in this layer (datetime)
'''
# get current layer titile
cur_title = layer['attributes']['name']
# get current end date being used from title by string manupulation
old_date = cur_title.split()[0:7]
# join each time variable to construct text of current date
old_date_text = ' '.join(old_date)
# latest data is for one day ago, so subtracting a day
new_date_end = (new_date - datetime.timedelta(days=1))
# get text for new date
new_date_end = datetime.datetime.strftime(new_date_end, "%B %d, %Y")
# get most recent starting date, 8 day ago
new_date_start = (new_date - datetime.timedelta(days=7))
new_date_start = datetime.datetime.strftime(new_date_start, "%B %d, %Y")
# construct new date range by joining new start date and new end date
new_date_text = new_date_start + ' - ' + new_date_end
# replace date in layer's title with new date
layer['attributes']['name'] = layer['attributes']['name'].replace(old_date_text, new_date_text)
# send patch to API to replace layers
# generate url to patch layer
rw_api_url_layer = "https://api.resourcewatch.org/v1/dataset/{dataset_id}/layer/{layer_id}".format(
dataset_id=layer['attributes']['dataset'], layer_id=layer['id'])
# create payload with new title and layer configuration
payload = {
'application': ['rw'],
'name': layer['attributes']['name']
}
# patch API with updates
r = requests.request('PATCH', rw_api_url_layer, data=json.dumps(payload), headers=create_headers())
# check response
# if we get a 200, the layers have been replaced
# if we get a 504 (gateway timeout) - the layers are still being replaced, but it worked
if r.ok or r.status_code==504:
logging.info('Layer replaced: {}'.format(layer['id']))
else:
logging.error('Error replacing layer: {} ({})'.format(layer['id'], r.status_code))
def updateResourceWatch():
'''
This function should update Resource Watch to reflect the new data.
This may include updating the 'last update date', flushing the tile cache, and updating any dates on layers
'''
# Get the most recent date from the data in the GEE collection
most_recent_date = get_most_recent_date(EE_COLLECTION)
# Get the current 'last update date' from the dataset on Resource Watch
current_date = getLastUpdate(DATASET_ID)
# Update the dates on layer legends
logging.info('Updating {}'.format(EE_COLLECTION))
# pull dictionary of current layers from API
layer_dict = pull_layers_from_API(DATASET_ID)
# go through each layer, pull the definition and update
for layer in layer_dict:
# replace layer title with new dates
update_layer(layer, most_recent_date)
# If the most recent date from the GEE collection does not match the 'last update date' on the RW API, update it
if current_date != most_recent_date:
logging.info('Updating last update date and flushing cache.')
# Update dataset's last update date on Resource Watch
lastUpdateDate(DATASET_ID, most_recent_date)
# get layer ids and flush tile cache for each
layer_ids = getLayerIDs(DATASET_ID)
for layer_id in layer_ids:
flushTileCache(layer_id)
def main():
logging.basicConfig(stream=sys.stderr, level=logging.INFO)
logging.info('STARTING')
# Initialize eeUtil
eeUtil.initJson()
# Clear the GEE collection, if specified above
if CLEAR_COLLECTION_FIRST:
if eeUtil.exists(EE_COLLECTION):
eeUtil.removeAsset(EE_COLLECTION, recursive=True)
# Check if collection exists, create it if it does not
# If it exists return the list of assets currently in the collection
existing_assets = checkCreateCollection(EE_COLLECTION)
# Get a list of the dates of data we already have in the collection
existing_dates = [getDate(a) for a in existing_assets]
# Fetch, process, and upload the new data
new_assets = processNewData(existing_dates)
# Get the dates of the new data we have added
new_dates = [getDate(a) for a in new_assets]
logging.info('Previous assets: {}, new: {}, max: {}'.format(
len(existing_dates), len(new_dates), MAX_ASSETS))
# Delete excess assets
deleteExcessAssets(existing_dates+new_dates, MAX_ASSETS)
# Update Resource Watch
updateResourceWatch()
logging.info('SUCCESS')
| [
"logging.debug",
"requests.patch",
"time.sleep",
"datetime.timedelta",
"logging.info",
"eeUtil.uploadAssets",
"logging.error",
"os.remove",
"eeUtil.exists",
"urllib.request.urlretrieve",
"json.dumps",
"subprocess.call",
"eeUtil.removeAsset",
"eeUtil.ls",
"os.path.splitext",
"requests.g... | [((3538, 3558), 'requests.get', 'requests.get', (['apiUrl'], {}), '(apiUrl)\n', (3550, 3558), False, 'import requests\n'), ((3960, 4015), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['nofrag', '"""%Y-%m-%dT%H:%M:%S"""'], {}), "(nofrag, '%Y-%m-%dT%H:%M:%S')\n", (3986, 4015), False, 'import datetime\n'), ((4674, 4694), 'requests.get', 'requests.get', (['apiUrl'], {}), '(apiUrl)\n', (4686, 4694), False, 'import requests\n'), ((8950, 8971), 'datetime.date.today', 'datetime.date.today', ([], {}), '()\n', (8969, 8971), False, 'import datetime\n'), ((11973, 12003), 'logging.info', 'logging.info', (['"""Fetching files"""'], {}), "('Fetching files')\n", (11985, 12003), False, 'import logging\n'), ((13382, 13407), 'eeUtil.exists', 'eeUtil.exists', (['collection'], {}), '(collection)\n', (13395, 13407), False, 'import eeUtil\n'), ((15093, 15152), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['existing_dates[-1]', 'DATE_FORMAT'], {}), '(existing_dates[-1], DATE_FORMAT)\n', (15119, 15152), False, 'import datetime\n'), ((15840, 15864), 'requests.get', 'requests.get', (['rw_api_url'], {}), '(rw_api_url)\n', (15852, 15864), False, 'import requests\n'), ((16701, 16754), 'datetime.datetime.strftime', 'datetime.datetime.strftime', (['new_date_end', '"""%B %d, %Y"""'], {}), "(new_date_end, '%B %d, %Y')\n", (16727, 16754), False, 'import datetime\n'), ((16884, 16939), 'datetime.datetime.strftime', 'datetime.datetime.strftime', (['new_date_start', '"""%B %d, %Y"""'], {}), "(new_date_start, '%B %d, %Y')\n", (16910, 16939), False, 'import datetime\n'), ((19519, 19577), 'logging.basicConfig', 'logging.basicConfig', ([], {'stream': 'sys.stderr', 'level': 'logging.INFO'}), '(stream=sys.stderr, level=logging.INFO)\n', (19538, 19577), False, 'import logging\n'), ((19582, 19606), 'logging.info', 'logging.info', (['"""STARTING"""'], {}), "('STARTING')\n", (19594, 19606), False, 'import logging\n'), ((19636, 19653), 'eeUtil.initJson', 'eeUtil.initJson', ([], {}), '()\n', (19651, 19653), False, 'import eeUtil\n'), ((20630, 20653), 'logging.info', 'logging.info', (['"""SUCCESS"""'], {}), "('SUCCESS')\n", (20642, 20653), False, 'import logging\n'), ((2377, 2398), 'os.getenv', 'os.getenv', (['"""apiToken"""'], {}), "('apiToken')\n", (2386, 2398), False, 'import os\n'), ((2624, 2678), 'requests.patch', 'requests.patch', ([], {'url': 'apiUrl', 'json': 'body', 'headers': 'headers'}), '(url=apiUrl, json=body, headers=headers)\n', (2638, 2678), False, 'import requests\n'), ((5720, 5741), 'os.getenv', 'os.getenv', (['"""apiToken"""'], {}), "('apiToken')\n", (5729, 5741), False, 'import os\n'), ((9056, 9082), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(1)'}), '(days=1)\n', (9074, 9082), False, 'import datetime\n'), ((10247, 10267), 'subprocess.call', 'subprocess.call', (['cmd'], {}), '(cmd)\n', (10262, 10267), False, 'import subprocess\n'), ((12173, 12213), 'logging.info', 'logging.info', (['"""Converting files to tifs"""'], {}), "('Converting files to tifs')\n", (12185, 12213), False, 'import logging\n'), ((12253, 12284), 'logging.info', 'logging.info', (['"""Uploading files"""'], {}), "('Uploading files')\n", (12265, 12284), False, 'import logging\n'), ((12786, 12842), 'eeUtil.uploadAssets', 'eeUtil.uploadAssets', (['tifs', 'assets', 'GS_FOLDER', 'datestamps'], {}), '(tifs, assets, GS_FOLDER, datestamps)\n', (12805, 12842), False, 'import eeUtil\n'), ((12881, 12917), 'logging.info', 'logging.info', (['"""Cleaning local files"""'], {}), "('Cleaning local files')\n", (12893, 12917), False, 'import logging\n'), ((13424, 13445), 'eeUtil.ls', 'eeUtil.ls', (['collection'], {}), '(collection)\n', (13433, 13445), False, 'import eeUtil\n'), ((13648, 13698), 'eeUtil.createFolder', 'eeUtil.createFolder', (['collection', '(True)'], {'public': '(True)'}), '(collection, True, public=True)\n', (13667, 13698), False, 'import eeUtil\n'), ((16626, 16652), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(1)'}), '(days=1)\n', (16644, 16652), False, 'import datetime\n'), ((16835, 16861), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(7)'}), '(days=7)\n', (16853, 16861), False, 'import datetime\n'), ((19155, 19216), 'logging.info', 'logging.info', (['"""Updating last update date and flushing cache."""'], {}), "('Updating last update date and flushing cache.')\n", (19167, 19216), False, 'import logging\n'), ((19748, 19776), 'eeUtil.exists', 'eeUtil.exists', (['EE_COLLECTION'], {}), '(EE_COLLECTION)\n', (19761, 19776), False, 'import eeUtil\n'), ((6023, 6081), 'requests.delete', 'requests.delete', ([], {'url': 'apiUrl', 'headers': 'headers', 'timeout': '(1000)'}), '(url=apiUrl, headers=headers, timeout=1000)\n', (6038, 6081), False, 'import requests\n'), ((11071, 11105), 'urllib.request.urlretrieve', 'urllib.request.urlretrieve', (['url', 'f'], {}), '(url, f)\n', (11097, 11105), False, 'import urllib\n'), ((12520, 12565), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['date', 'DATE_FORMAT'], {}), '(date, DATE_FORMAT)\n', (12546, 12565), False, 'import datetime\n'), ((12955, 12969), 'os.remove', 'os.remove', (['tif'], {}), '(tif)\n', (12964, 12969), False, 'import os\n'), ((13006, 13018), 'os.remove', 'os.remove', (['f'], {}), '(f)\n', (13015, 13018), False, 'import os\n'), ((15371, 15392), 'os.getenv', 'os.getenv', (['"""apiToken"""'], {}), "('apiToken')\n", (15380, 15392), False, 'import os\n'), ((17720, 17739), 'json.dumps', 'json.dumps', (['payload'], {}), '(payload)\n', (17730, 17739), False, 'import json\n'), ((19790, 19839), 'eeUtil.removeAsset', 'eeUtil.removeAsset', (['EE_COLLECTION'], {'recursive': '(True)'}), '(EE_COLLECTION, recursive=True)\n', (19808, 19839), False, 'import eeUtil\n'), ((8443, 8469), 'os.path.basename', 'os.path.basename', (['filename'], {}), '(filename)\n', (8459, 8469), False, 'import os\n'), ((10027, 10046), 'os.path.splitext', 'os.path.splitext', (['f'], {}), '(f)\n', (10043, 10046), False, 'import os\n'), ((11485, 11501), 'logging.debug', 'logging.debug', (['e'], {}), '(e)\n', (11498, 11501), False, 'import logging\n'), ((6748, 6762), 'time.sleep', 'time.sleep', (['(60)'], {}), '(60)\n', (6758, 6762), False, 'import time\n'), ((6783, 6812), 'logging.info', 'logging.info', (['"""Trying again."""'], {}), "('Trying again.')\n", (6795, 6812), False, 'import logging\n'), ((7029, 7055), 'logging.error', 'logging.error', (['"""Aborting."""'], {}), "('Aborting.')\n", (7042, 7055), False, 'import logging\n')] |
import argparse
import os
import pydub
def convert_file(file_path, _format, start=None, end=None, out=None):
filename, file_extension = os.path.splitext(file_path)
audio = pydub.audio_segment.AudioSegment.from_file(file_path)
start = int(start) if start is not None else 0
end = int(end) if end is not None else len(audio)
audio = audio[start:end]
if _format == "wav":
audio = audio.set_sample_width(2) # pygame only supports a sample format of 16 bit (2 byte)
if out is not None:
head, tail = os.path.split(file_path)
audio.export(os.path.join(head, f"{out}.{_format}"), format=_format)
else:
audio.export(f"{filename}.{_format}", format=_format)
if __name__ == "__main__":
"""
Converts a file (e.g., mp3) to a different format (e.g., wav, ogg). The converted file will be in the same
directory as the original file. Can convert a single file or every file in a directory.
Run this script as follows:
`python convert_file.py filename-or-directory format`
Example:
`python convert_file.py my_sound.wav ogg`
This script supports additional arguments, type `python convert_file.py --help` for more information.
"""
parser = argparse.ArgumentParser(description="Perform a file conversion")
parser.add_argument("source", metavar="S", help="path to the source (file or directory)")
parser.add_argument("format", metavar="F", help="new file format")
parser.add_argument("--start", required=False, help="start file at time in milliseconds")
parser.add_argument("--end", required=False, help="end file at time in milliseconds")
parser.add_argument("--out", required=False, help="output name (excluding extension)")
args = parser.parse_args()
if os.path.isdir(args.source):
for file in os.listdir(args.source):
full_file_path = os.path.join(args.source, file)
if os.path.isfile(full_file_path):
convert_file(file_path=full_file_path, _format=args.format)
else:
convert_file(file_path=args.source, _format=args.format, start=args.start, end=args.end, out=args.out)
| [
"os.listdir",
"argparse.ArgumentParser",
"pydub.audio_segment.AudioSegment.from_file",
"os.path.splitext",
"os.path.join",
"os.path.split",
"os.path.isfile",
"os.path.isdir"
] | [((143, 170), 'os.path.splitext', 'os.path.splitext', (['file_path'], {}), '(file_path)\n', (159, 170), False, 'import os\n'), ((183, 236), 'pydub.audio_segment.AudioSegment.from_file', 'pydub.audio_segment.AudioSegment.from_file', (['file_path'], {}), '(file_path)\n', (225, 236), False, 'import pydub\n'), ((1235, 1299), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Perform a file conversion"""'}), "(description='Perform a file conversion')\n", (1258, 1299), False, 'import argparse\n'), ((1779, 1805), 'os.path.isdir', 'os.path.isdir', (['args.source'], {}), '(args.source)\n', (1792, 1805), False, 'import os\n'), ((542, 566), 'os.path.split', 'os.path.split', (['file_path'], {}), '(file_path)\n', (555, 566), False, 'import os\n'), ((1827, 1850), 'os.listdir', 'os.listdir', (['args.source'], {}), '(args.source)\n', (1837, 1850), False, 'import os\n'), ((588, 626), 'os.path.join', 'os.path.join', (['head', 'f"""{out}.{_format}"""'], {}), "(head, f'{out}.{_format}')\n", (600, 626), False, 'import os\n'), ((1881, 1912), 'os.path.join', 'os.path.join', (['args.source', 'file'], {}), '(args.source, file)\n', (1893, 1912), False, 'import os\n'), ((1928, 1958), 'os.path.isfile', 'os.path.isfile', (['full_file_path'], {}), '(full_file_path)\n', (1942, 1958), False, 'import os\n')] |
#!/usr/bin/python
"""
ZetCode PyQt6 tutorial
In the example, we draw randomly 1000 red points
on the window.
Author: <NAME>
Website: zetcode.com
"""
from PyQt6.QtWidgets import QWidget, QApplication
from PyQt6.QtGui import QPainter
from PyQt6.QtCore import Qt
import sys, random
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setMinimumSize(50, 50)
self.setGeometry(300, 300, 350, 300)
self.setWindowTitle('Points')
self.show()
def paintEvent(self, e):
qp = QPainter()
qp.begin(self)
self.drawPoints(qp)
qp.end()
def drawPoints(self, qp):
qp.setPen(Qt.GlobalColor.red)
size = self.size()
for i in range(1000):
x = random.randint(1, size.width() - 1)
y = random.randint(1, size.height() - 1)
qp.drawPoint(x, y)
def main():
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec())
if __name__ == '__main__':
main()
| [
"PyQt6.QtGui.QPainter",
"PyQt6.QtWidgets.QApplication"
] | [((963, 985), 'PyQt6.QtWidgets.QApplication', 'QApplication', (['sys.argv'], {}), '(sys.argv)\n', (975, 985), False, 'from PyQt6.QtWidgets import QWidget, QApplication\n'), ((593, 603), 'PyQt6.QtGui.QPainter', 'QPainter', ([], {}), '()\n', (601, 603), False, 'from PyQt6.QtGui import QPainter\n')] |
# -*- coding: utf-8 -*-
'''
Created on 2016年2月19日
一些json的处理方法
@author: hzwangzhiwei
'''
from datetime import date
from datetime import datetime
import json
class CJsonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(obj, date):
return obj.strftime('%Y-%m-%d')
else:
return json.JSONEncoder.default(self, obj)
def object_2_json(obj):
'''
py字典、数据转成json字符转
'''
if obj is None:
return {}
return json.dumps(obj, cls=CJsonEncoder)
def json_2_dict(json_str):
'''
json字符串转成dict,list数据结构
'''
try:
return json.loads(json_str)
except Exception:
return None
| [
"json.loads",
"json.dumps",
"json.JSONEncoder.default"
] | [((577, 610), 'json.dumps', 'json.dumps', (['obj'], {'cls': 'CJsonEncoder'}), '(obj, cls=CJsonEncoder)\n', (587, 610), False, 'import json\n'), ((707, 727), 'json.loads', 'json.loads', (['json_str'], {}), '(json_str)\n', (717, 727), False, 'import json\n'), ((429, 464), 'json.JSONEncoder.default', 'json.JSONEncoder.default', (['self', 'obj'], {}), '(self, obj)\n', (453, 464), False, 'import json\n')] |
# encoding: utf-8
import os
import csv
from pylab import *
from numpy import *
def loadData(name):
# DATADIR='sav/'
DATADIR='/home/zhenfeng/Research/GroupEvolution/src/code201611-MZ/sav/'
if name == 'allGroups':
G={}
fpath=DATADIR+'gids-all.csv'
csvfile=open(fpath, 'rb')
data = csv.reader(csvfile, delimiter=',')
i=0
for row in data:
for j in row:
G[j]=i
i+=1
del data
csvfile.close()
del csvfile
return G
if name == 'joinGroups':
G={}
fpath=DATADIR+'gids-join.csv'
csvfile=open(fpath, 'rb')
data = csv.reader(csvfile, delimiter=',')
i=0
for row in data:
for j in row:
G[j]=i
i+=1
del data
csvfile.close()
del csvfile
return G
if name == 'groupStates':
GS={}
fpath=DATADIR+'GroupState.txt'
csvfile=open(fpath, 'rb')
data = csv.reader(csvfile, delimiter=',')
for row in data:
GS[row[0]]=int(row[1])
del data
csvfile.close()
del csvfile
return GS
if name == 'avgGroupSizes':
S={}
fpath=DATADIR+'avgGroupSizes.txt'
csvfile=open(fpath, 'rb')
data = csv.reader(csvfile, delimiter=',')
for row in data:
S[row[0]]=float(row[1])
del data
csvfile.close()
del csvfile
return S
if name == 'allUsers':
U={}
fpath=DATADIR+'uids-all.csv'
csvfile=open(fpath, 'rb')
data = csv.reader(csvfile, delimiter=',')
i=0
for row in data:
for j in row:
U[j]=i
i+=1
del data
csvfile.close()
del csvfile
return U
if name == 'joinUsers':
U={}
fpath=DATADIR+'uids-join.csv'
csvfile=open(fpath, 'rb')
data = csv.reader(csvfile, delimiter=',')
i=0
for row in data:
for j in row:
U[j]=i
i+=1
del data
csvfile.close()
del csvfile
return U
if name == 'userStates':
UI={}
csvfile=open(DATADIR+'UserState.txt', 'rb')
data = csv.reader(csvfile, delimiter=',')
for row in data:
UI[row[0]]=int(row[1])
del data
csvfile.close()
del csvfile
return UI
if name == 'groupsByDay':
GBD={}
fpath=DATADIR+'GroupsByDay.txt'
csvfile=open(fpath, 'rb')
data = csv.reader(csvfile, delimiter=',')
for row in data:
GBD[int(row[0])]=row[1:]
del data
csvfile.close()
del csvfile
return GBD
if name == 'NJoinsByDay':
JBD={}
fpath=DATADIR+'NJoinsByDay.txt'
csvfile=open(fpath, 'rb')
data = csv.reader(csvfile, delimiter=',')
for row in data:
JBD[row[0]]=map(int,row[1:])
del data
csvfile.close()
del csvfile
return JBD
print('dataNotFound!')
| [
"csv.reader"
] | [((324, 358), 'csv.reader', 'csv.reader', (['csvfile'], {'delimiter': '""","""'}), "(csvfile, delimiter=',')\n", (334, 358), False, 'import csv\n'), ((673, 707), 'csv.reader', 'csv.reader', (['csvfile'], {'delimiter': '""","""'}), "(csvfile, delimiter=',')\n", (683, 707), False, 'import csv\n'), ((1025, 1059), 'csv.reader', 'csv.reader', (['csvfile'], {'delimiter': '""","""'}), "(csvfile, delimiter=',')\n", (1035, 1059), False, 'import csv\n'), ((1335, 1369), 'csv.reader', 'csv.reader', (['csvfile'], {'delimiter': '""","""'}), "(csvfile, delimiter=',')\n", (1345, 1369), False, 'import csv\n'), ((1635, 1669), 'csv.reader', 'csv.reader', (['csvfile'], {'delimiter': '""","""'}), "(csvfile, delimiter=',')\n", (1645, 1669), False, 'import csv\n'), ((1983, 2017), 'csv.reader', 'csv.reader', (['csvfile'], {'delimiter': '""","""'}), "(csvfile, delimiter=',')\n", (1993, 2017), False, 'import csv\n'), ((2314, 2348), 'csv.reader', 'csv.reader', (['csvfile'], {'delimiter': '""","""'}), "(csvfile, delimiter=',')\n", (2324, 2348), False, 'import csv\n'), ((2623, 2657), 'csv.reader', 'csv.reader', (['csvfile'], {'delimiter': '""","""'}), "(csvfile, delimiter=',')\n", (2633, 2657), False, 'import csv\n'), ((2935, 2969), 'csv.reader', 'csv.reader', (['csvfile'], {'delimiter': '""","""'}), "(csvfile, delimiter=',')\n", (2945, 2969), False, 'import csv\n')] |
from torchvision import transforms
import torch
import torchvision.transforms.functional as TF
class RandomHorizontalFlip:
def __init__(self, p):
self.p = p
def __call__(self, sample):
image, target = sample
if torch.rand(1) < self.p:
image = transforms.RandomHorizontalFlip(1)(image)
target[[3, 5]] = target[[5, 3]]
return image, target
class RandomVerticalFlip:
def __init__(self, p):
self.p = p
def __call__(self, sample):
image, target = sample
if torch.rand(1) < self.p:
image = transforms.RandomVerticalFlip(1)(image)
target[[2, 4]] = target[[4, 2]]
return image, target
class RandomRightRotation:
def __init__(self, p):
self.p = p
def __call__(self, sample):
image, target = sample
if torch.rand(1) < self.p:
image = TF.rotate(image, -90)
target[[3, 4, 5, 2]] = target[[2, 3, 4, 5]]
return image, target
| [
"torchvision.transforms.RandomVerticalFlip",
"torchvision.transforms.functional.rotate",
"torchvision.transforms.RandomHorizontalFlip",
"torch.rand"
] | [((249, 262), 'torch.rand', 'torch.rand', (['(1)'], {}), '(1)\n', (259, 262), False, 'import torch\n'), ((560, 573), 'torch.rand', 'torch.rand', (['(1)'], {}), '(1)\n', (570, 573), False, 'import torch\n'), ((870, 883), 'torch.rand', 'torch.rand', (['(1)'], {}), '(1)\n', (880, 883), False, 'import torch\n'), ((914, 935), 'torchvision.transforms.functional.rotate', 'TF.rotate', (['image', '(-90)'], {}), '(image, -90)\n', (923, 935), True, 'import torchvision.transforms.functional as TF\n'), ((293, 327), 'torchvision.transforms.RandomHorizontalFlip', 'transforms.RandomHorizontalFlip', (['(1)'], {}), '(1)\n', (324, 327), False, 'from torchvision import transforms\n'), ((604, 636), 'torchvision.transforms.RandomVerticalFlip', 'transforms.RandomVerticalFlip', (['(1)'], {}), '(1)\n', (633, 636), False, 'from torchvision import transforms\n')] |
import platform
import scipy
import numpy as np
import math
from scipy import integrate
from scipy import optimize as opt
from scipy.stats import gamma
from colorama import init, Fore, Back, Style
from cell import Cell
class PopSimulator:
def __init__(self, ncells, gr, sb, steps, CV2div = 0, CV2gr = 0, lamb=1, V0array=None, nu=1):
"""
:param ncells: int
:param gr: float
:param sb: float
:param steps: float
:param CV2div: float
:param CV2gr: float
:param lamb: float
:param V0array: list
"""
#self.__title()
self.__check_errors(ncells, gr, sb, steps, CV2div, CV2gr, lamb, nu)
self.n = ncells # Number of cells to study
self.smplt = 0 # Sampling time
self.gr = gr # Growth rate
self.total_steps = steps # Division steps
self.sb = sb #Initial size
self.l = lamb
self.nu=nu
if lamb ==1:
self.K = self.total_steps *self.gr/(self.sb)
else:
self.K = self.total_steps*self.getk()
self.CV2div = CV2div
self.CV2gr = CV2gr
self.output = "" # string to export data in dynamic simulation
self.output_size = "" # string to export data in divison strategy
self.num_steps = 0 # Initial steps
self.V = self.sb # Cell size
self.time = 0 # Simulation time
self.cells = [] # Array of cells
if hasattr(V0array, "__len__"):
self.V0arr = V0array
else:
self.V0arr = []
self.initialize_cells(V0array=self.V0arr) #Initialize cells
self.DivFile=''
def __title(self):
"""
Initial title with the name of the project
:return: None
"""
if platform.system() == "Windows":
print(" ___ __ __ _______ ______ _____ __ ___ _____")
print("| _ \ \ \ | | | _____| / ____| / ___ \ | | | | | __ \\")
print("| | \ | \ \ | | | | | / | / \ | | | |___| | | \ |")
print("| |_/ / \ \| | | |___ | | | | | | | | ___ | |__/ /")
print("| __/ \__ | | ___| | | | | | | | | | | | __ \\")
print("| | / / | | | | | | | | | | | | | | \ |")
print("| | ___/ / | |_____ | \_____ | \___/ | | |___ | | | |__/ |")
print("|_| |_____/ |_______| \______| \_____/ |______| |___| |______/")
else:
print("\x1b[1,32m"+" ___ __ __ _______ ______ _____ __ ___ _____"+'\033[0m')
print("\x1b[1,32m"+"| _ \ \ \ | | | _____| / ____| / ___ \ | | | | | __ \\"+'\033[0m')
print("\x1b[1,32m"+"| | \ | \ \ | | | | | / | / \ | | | |___| | | \ |"+'\033[0m')
print("\x1b[1,32m"+"| |_/ / \ \| | | |___ | | | | | | | | ___ | |__/ /"+'\033[0m')
print("\x1b[1,32m"+"| __/ \__ | | ___| | | | | | | | | | | | __ \\"+'\033[0m')
print("\x1b[1,32m"+"| | / / | | | | | | | | | | | | | | \ |"+'\033[0m')
print("\x1b[1,32m"+"| | ___/ / | |_____ | \_____ | \___/ | | |___ | | | |__/ |"+'\033[0m')
print("\x1b[1,32m"+"|_| |_____/ |_______| \______| \_____/ |______| |___| |______/"+'\033[0m')
def __check_errors(self, ncells, gr, sb, steps, CV2div, CV2gr, lamb,nu):
"""
it generate an error if some param does not comply with the established
:param ncells: int
:param gr: float
:param sb: float
:param steps: int
:param CV2div: float
:param CV2gr: float
:param lamb: float
:return: None
"""
if not(nu in [1,2]):
raise NameError('nu must be in [1,2]')
elif ncells <= 0:
raise NameError('ncells must be positive')
elif gr < 0:
raise NameError('gr must be positive')
elif sb < 0:
raise NameError('sb must be positive or zero')
elif steps < 0:
raise NameError('steps must be positive or zero')
elif CV2div < 0:
raise NameError('CV2div must be positive or zero')
elif CV2gr < 0:
raise NameError('CV2gr must be positive or zero')
elif lamb < 0.5 or lamb > 2:
raise NameError('lamb must be higher than 0.5 and less than 2')
def newgr(self,CV2):
"""
Give a new growth rate
:param CV2: float
:return: float
"""
if CV2 ==0:
return 1.
else:
return np.random.gamma(shape=1/CV2,scale=CV2)
def newdivpar(self,CV2):
"""
*
:param CV2: float
:return: None
"""
if CV2 ==0:
return 0.5
else:
beta = 0.5*((1/CV2)-1)
return np.random.beta(a=beta,b=beta)
def getsb(self,k):
"""
*
:param k: float
:return: None
"""
def root(tt):
return self.multimean(tt,k)-2*tt
def meansb():
return opt.bisect(root,0.00001,100000)
sb = meansb()
return sb
def multimean(self,s,k):
"""
*
:param s: float
:param k: float
:return: None
"""
sb=s
def moment(sd):
return self.rhomulti(sb,sd,k)*sd
v=integrate.quad(moment, sb, np.inf)[0]
return v
def rhomulti(self,sb,sd,k):
"""
*
:param sb: float
:param sd: float
:param k: float
:return: None
"""
n=self.total_steps
lamb=self.l
gr=self.gr
c=n*k/gr
x=c*((sd**lamb-sb**lamb)/lamb)
return gamma.pdf(x, n)*c*sd**(lamb-1)
def opti(self,k):
"""
*
:param k: float
:return: float
"""
return self.getsb(k)-self.sb
def getk(self):
"""
return k when it cannot be calculate with the equation gr/sb
:return: float
"""
return opt.bisect(self.opti,0.001,1.5)
def initialize_cells(self, V0array):
"""
Give the initial params to the cells
:param V0array: list
:return: None
"""
self.cells=[]
if len(V0array)!=0:
idx = 0
for v in V0array:
gr = self.newgr(self.CV2gr)
divpar = self.newdivpar(self.CV2div)
cell = Cell(idx, v, num_steps=self.total_steps, gr=gr, divpar=divpar, k = gr)
cell.nextt = self.nextt(v,cell.rv,cell)
self.cells.append(cell)
idx += 1
else:
for i in range(self.n):
gr = self.newgr(self.CV2gr)
divpar = self.newdivpar(self.CV2div)
cell = Cell(i, self.sb, num_steps=self.total_steps, gr = gr, divpar = divpar, k = gr)
cell.nextt = self.nextt(self.sb,cell.rv,cell)
self.cells.append(cell)
def open_file(self, FileName="./DataSz.csv",DivEventsFile=None):
"""
Here open the file to write the .csv outputs
:param nameCRM: string
:return: None
"""
if hasattr(DivEventsFile, "__len__"):
self.DivFile = open(DivEventsFile, "w")
output="Sample,Cell,Mother,MotherSize,BirthTime,Sb,GrowthRate,DivPar\n"
for m in range(len(self.cells)):
output+=str(m)+','+str(m)+','+str(m)+','+str(np.nan)+',0.000,'+str(np.round(self.cells[m].V,8))\
+','+str(np.round(self.cells[m].gr*self.gr,8))+','+str(self.cells[m].dp)+'\n'
self.DivFile.write(output)
self.output = ""
self.file = open(FileName, "w")
self.output += "Time,Sample,Cell,Size,DivSteps\n"
self.file.write(self.output)
kk=0
for cell in self.cells:
self.output = ""
self.output += "0.00,"+str(kk)+","+str(kk)+","
self.output += str(np.round(cell.get_size(), 4) )+",0\n"
self.file.write(self.output)
kk+=1
def nextt (self,s0,r,cell):
"""
*
:param s0: float
:param r: float
:param cell: Cell
:return: None
"""
mu= (self.gr*cell.gr)
k= self.K*cell.k
l=self.l
return (1/(l*mu))*np.log(1-(l*mu*np.log(r)/(k*s0**l)))
def simulate(self,tmax):
"""
This function do all operations
:param tmax: int
:return: None
"""
if self.nu==2:
raise NameError('This function was designed for nu=1.')
else:
for cell in self.cells:
t=0
while t<tmax:
tt = cell.nextt
if ((t+tt) <= tmax):
cell.num_steps += 1
Vn=cell.V*np.exp(self.gr*cell.gr*tt)
if cell.num_steps >= cell.total_steps:
dp = self.newdivpar(self.CV2div)
gr = self.newgr(self.CV2gr)
cell.division(Vn,dp,gr,k=gr)
else:
cell.change(Vn)
cell.rv=np.random.rand()
cell.nextt = self.nextt(cell.V,cell.rv,cell)
else:
Vn = cell.V*np.exp(self.gr*cell.gr*(tmax-t))
cell.change(Vn)
cell.nextt = cell.nextt - (tmax-t)
t += tt
def szdyn(self, tmax, sample_time, FileName = "./DataSz.csv", DivEventsFile=None):
self.initialize_cells(self.V0arr) #Initialize cells
if hasattr(DivEventsFile, "__len__"):
self.open_file(FileName = FileName, DivEventsFile=DivEventsFile)
else:
self.open_file(FileName = FileName)
"""
*
:param tmax: int
:param sample_time: int
:param nameCRM: string
:return: None
"""
if self.nu==2:
if tmax>9*np.log(2)/self.gr:
raise NameError('Please select tmax<9*doublingtime')
elif self.n>=2000:
raise NameError('Please select ncells<=2000')
self.smplt = sample_time
self.time = 0
nextarray=np.empty(len(self.cells))
for m in range(len(self.cells)):
nextarray[m]=self.cells[m].nextt
self.cells[m].idx=m
tref=self.smplt
while self.time<tmax:
nexttm=np.min(nextarray)
if nexttm>tref-self.time:
tt=tref-self.time
self.time+=tt
self.output = ""
for ll in range(len(self.cells)):
cell=self.cells[ll]
cell.nextt+=-tt
nextarray[ll]+=-tt
g=cell.gr*self.gr
cell.V=cell.V*np.exp(g*tt)
"Time,Sample,Cell,Size,DivSteps\n"
self.output += str(self.time)+","+str(cell.popidx)+","+str(cell.idx)+","\
+str(np.round(cell.V,8))+","+str(cell.num_steps)+"\n"
self.file.write(self.output)
tref+=self.smplt
else:
m = np.argmin(nextarray)
cell = self.cells[m]
cell.num_steps+=1
for ll in range(len(self.cells)):
self.cells[ll].nextt+=-nexttm
nextarray[ll]+=-nexttm
g=self.cells[ll].gr*self.gr
self.cells[ll].V=self.cells[ll].V*np.exp(g*nexttm)
if cell.num_steps>=self.total_steps:
momsz=cell.V
sz=cell.V*cell.dp
sz2=cell.V*(1-cell.dp)
cell.V=sz
cell.num_steps=0
cell.dp = self.newdivpar(self.CV2div)
cell.gr = self.newgr(self.CV2gr)
gr=cell.gr
dp=cell.dp
cell.nextt = self.nextt(sz,np.random.rand(),cell)
nextarray[m]=cell.nextt
if self.nu==2:
gr2 = self.newgr(self.CV2gr)
dp2 = self.newdivpar(self.CV2div)
idx=len(self.cells)
cell2 = Cell(idx, V0=sz2, num_steps=self.total_steps, gr=gr2, divpar=dp2, k = gr2)
cell2.popidx=cell.popidx
cell2.nextt = self.nextt(sz2,np.random.rand(),cell2)
nextarray=np.concatenate((nextarray, [cell2.nextt]), axis=None)
self.cells.append(cell2)
if hasattr(DivEventsFile, "__len__"):
self.DivFile.write(str(cell.popidx)+","+str(int(cell.idx))+","+str(int(cell.idx))+","+str(momsz)\
+","+str(nexttm+self.time)+","+str(np.round(sz,8))\
+","+str(np.round(gr*self.gr,8))+","+str(dp)+"\n")
if self.nu==2:
self.DivFile.write(str(cell.popidx)+","+str(int(cell2.idx))+","+str(int(cell.idx))+","+str(momsz)\
+","+str(nexttm+self.time)+","+str(np.round(sz2,8))\
+","+str(np.round(gr2*self.gr,8))+","+str(dp2)+"\n")
else:
cell.rv=np.random.rand()
cell.nextt = self.nextt(cell.V, cell.rv, cell)
nextarray[m]=cell.nextt
self.time+=nexttm
self.file.close()
if hasattr(DivEventsFile, "__len__"):
self.DivFile.close()
def divstrat(self, tmax, sample_time, nameDSM = "./dataDSM.csv"):
"""
*
:param tmax: int
:param sample_time: int
:param nameDSM: string
:return: None
"""
if self.nu==2:
raise NameError('This function was designed for nu==1.')
else:
self.initialize_cells(self.V0arr) #Initialize cells
self.file_size = open(nameDSM, "w")
self.file_size.write("S_b,S_d,time\n")
self.smplt = sample_time
self.time = 0
self.open_file()
self.time = 0
divarray = np.array([])
tgt = (tmax/10)
cnt = 0
for i in range(len(self.cells)):
divarray = np.concatenate((divarray,[self.get_ndiv(i)]),axis=0)
while self.time<tmax:
self.simulate(self.smplt)
cnt2 = 0
self.time += self.smplt
line = ""
for cell in self.cells:
if self.get_ndiv(i) > divarray[cnt2]:
line+=str(self.truncate(cell.Vb, 4))+","+str(self.truncate(cell.Vd, 4))+","+str(self.truncate(self.time, 4))+"\n "
divarray[cnt2] = self.get_ndiv(i)
cnt2+=1
self.file_size.write(line)
cnt +=self.smplt
if cnt >= tgt:
print(str(np.int(100*self.time/tmax))+"%")
cnt = 0
self.file_size.close()
def du(self,u,sb,t,dt):
"""
*
:param u: array
:param sb: float
:param t: int
:param dt: float
:return: array
"""
mu=self.gr
lamb=self.l
k=self.K
v=np.zeros_like(u)
s=sb*np.exp(mu*t)
for l in range(len(u)):
if l==0:
v[0]=(-k*(s**lamb)*u[0])*dt
elif l==len(u)-1:
v[len(u)-1]=(k*(s**lamb)*u[len(u)-2])*dt
elif l==len(u)-2:
v[len(u)-2]=(-k*(s**lamb)*u[len(u)-2]+k*(s**lamb)*u[len(u)-3])*dt
else:
v[l]=(-k*(s**lamb)*u[l]+k*(s**lamb)*u[l-1])*dt
return v
def SdStat(self,sb):
"""
*
:param sb: float
:return: float, float
"""
mu=self.gr
tmax=5/self.gr
dt=0.001/self.gr
u=np.zeros(self.total_steps+1)
t=0
count=10
plim=[]
tarrayfsp=[]
u[0]=1
while t<tmax:
u+=self.du(u,sb,t,dt)
t+=dt
count+=1
if count>9:
plim.append(u[-1])
tarrayfsp.append(t)
count=0
tt=np.array(tarrayfsp)
h=tt[1]-tt[0]
rhot=np.diff(plim)/h
trho=0.5*(tt[1:] + tt[:-1])
sarray=sb*np.exp(mu*tt)
ds=np.diff(sarray)
ss=0.5*(sarray[1:] + sarray[:-1])
rhos=rhot=np.diff(plim)/ds
mn=np.trapz(rhos*ss,x=ss)
var=np.trapz(rhos*(ss)**2,x=ss)
CV2=(var-mn**2)/(mn-sb)**2
return mn-sb,CV2
def szdynFSP(self, tmax, CV2sz = 0, nameFSP = "./dataFSP.csv"):
"""
*
:param tmax: int
:param CV2sz: float
:param nameFSP: string
:return: None
"""
if self.nu==2:
raise NameError('This function was designed for nu==1.')
else:
file = open(nameFSP, "w")
output = "time,Meansize,VarSize\n"
nsteps=self.total_steps
gr=self.gr
k=self.K
lamb=self.l
tmax=tmax
ndivs=int(1.5*tmax*self.gr/np.log(2))
dt=0.0001*np.log(2)/self.gr
if CV2sz==0:
s0arr=[self.V]
else:
s0arr = np.linspace(gamma.ppf(0.001,a=1/CV2sz,scale=self.V*CV2sz),
gamma.ppf(0.999, a=1/CV2sz,scale=self.V*CV2sz), 30)
dx=(s0arr[1]-s0arr[0])
wgs=[]
for l in s0arr:
wgs.append((gamma.cdf(l+dx/2,a=1/CV2sz,scale=self.V*CV2sz)-gamma.cdf(l-dx/2,a=1/CV2sz,scale=self.V*CV2sz))/dx)
allp=np.zeros([ndivs,len(s0arr),1000])
obj=0
countv0=0
for v0 in s0arr:
if obj%3==2:
print(str(np.int(100*obj/30))+"%")
obj+=1
t=0
steps=int(np.floor(tmax/dt))
u=np.zeros([ndivs,nsteps])#(DIVS,STEPS)
u[0]=np.zeros(nsteps)
u[0][0]=1#P_00
time=[]#time array
count=int(np.floor(tmax/(dt*1000)))-1
count2=0
for l in range(steps):
utemp=u
for n in range(len(utemp)):#n=divs,
for m in range(len(utemp[n])):#m=steps
arg=lamb*(gr*t-n*np.log(2))
if (m==0):#m=steps
if(n==0):#n=divs
dun=-k*v0**lamb*np.exp(lamb*gr*t)*(utemp[0][0])
u[n][m]+=dun*dt
else:
dun=k*v0**lamb*np.exp(arg)*(2**lamb*utemp[n-1][len(utemp[n])-1]-utemp[n][0])
u[n][m]+=dun*dt
elif(m==len(utemp[n])-1):
if(n==len(utemp)-1):
dun=k*v0**lamb*np.exp(arg)*(utemp[n][len(utemp[n])-2])
u[n][m]+=dun*dt
else:
dun=k*v0**lamb*np.exp(arg)*(utemp[n][m-1]-utemp[n][m])
u[n][m]+=dun*dt
else:
dun=k*v0**lamb*np.exp(arg)*(utemp[n][m-1]-utemp[n][m])
u[n][m]+=dun*dt
t+=dt
count=count+1
if count==int(np.floor(tmax/(dt*1000))):
time.append(t)
mean=0
for ii in range(len(allp)):
allp[ii][countv0][count2]=np.sum(u[ii])
count=0
count2+=1
countv0=countv0+1
if CV2sz==0:
fullmeansz=[]
fullvarsz=[]
fulltime=[]
t=0
dt=tmax/1000
for ll in range(len(allp[0][0])):
ms=0
for ctv0 in range(len(s0arr)):
tempms=0
for ii in range(ndivs):
arg=gr*t-np.log(2)*ii
tempms+=np.exp(arg)*allp[ii][ctv0][ll]
ms+=s0arr[ctv0]*tempms
fullmeansz.append(ms)
mvar=0
for ctv0 in range(len(s0arr)):
tempms=0
for ii in range(ndivs):
arg=gr*t-np.log(2)*ii
tempms+=(ms-s0arr[ctv0]*np.exp(arg))**2*allp[ii][ctv0][ll]
mvar+=tempms
fullvarsz.append(mvar)
fulltime.append(t)
t+=dt
else:
fullmeansz=[]
fullvarsz=[]
fulltime=[]
t=0
dt=tmax/1000
for ll in range(len(allp[0][0])):
ms=0
for ctv0 in range(len(s0arr)):
tempms=0
for ii in range(ndivs):
arg=gr*t-np.log(2)*ii
tempms+=np.exp(arg)*allp[ii][ctv0][ll]
ms+=s0arr[ctv0]*tempms*wgs[ctv0]*dx
fullmeansz.append(ms)
mvar=0
for ctv0 in range(len(s0arr)):
tempms=0
for ii in range(ndivs):
arg=gr*t-np.log(2)*ii
tempms+=(ms-s0arr[ctv0]*np.exp(arg))**2*allp[ii][ctv0][ll]
mvar+=tempms*wgs[ctv0]*dx
fullvarsz.append(mvar)
fulltime.append(t)
t+=dt
for m in range(len(fullmeansz)):
output += str(fulltime[m])+","+str(fullmeansz[m])+","+str(fullvarsz[m])+"\n"
file.write(output)
def get_sz(self, n, cells=[]):
"""
Give the size of a cell
:param n: int
:param cells: list
:return: float
"""
if len(cells) > 0:
return cells[n].V
else:
return self.cells[n].V
def get_ndiv(self, n, cells=[]):
if len(cells) > 0:
return cells[n].ndiv
else:
return self.cells[n].ndiv
def get_gr(self, n, cells=[]):
"""
Give the growth rate of a given index cell
:param n: int
:param cells: list
:return: float
"""
if len(cells) > 0:
return cells[n].gr
else:
return self.cells[n].gr
def get_dp(self, n, cells=[]):
"""
*
:param n: int
:param cells: array
:return: float
"""
if len(cells) > 0:
return cells[n].dp
else:
return self.cells[n].dp
def get_next_t(self, n, cells=[]):
"""
Get the next time
:param n: int
:param cells: array
:return: int
"""
if len(cells) > 0:
return cells[n].nextt
else:
return self.cells[n].nextt
def truncate(self, num, ciphers):
"""
This functions return a number with the n number of ciphers
:param num: float
:param ciphers: int
:return: float
"""
pos = pow(10.0, ciphers)
return math.trunc(pos * num)/pos
def __str__(self):
out = "Initial Params: {\n tmax: "+str(self.total_time)+", \n sample time: "+str(self.smplt)+", \n ncells: "+str(self.n)+", \n dt: "+str(self.dt)+", \n alpha: "+str(self.alpha)+", \n k: "+str(self.K)+"\n}"
for cell in self.cells:
out+= str(cell)+"\n"
return out
| [
"numpy.random.rand",
"numpy.log",
"numpy.array",
"math.trunc",
"scipy.stats.gamma.pdf",
"numpy.diff",
"numpy.exp",
"platform.system",
"numpy.random.gamma",
"cell.Cell",
"numpy.concatenate",
"numpy.min",
"numpy.argmin",
"numpy.round",
"scipy.stats.gamma.cdf",
"numpy.trapz",
"numpy.ran... | [((6301, 6334), 'scipy.optimize.bisect', 'opt.bisect', (['self.opti', '(0.001)', '(1.5)'], {}), '(self.opti, 0.001, 1.5)\n', (6311, 6334), True, 'from scipy import optimize as opt\n'), ((15927, 15943), 'numpy.zeros_like', 'np.zeros_like', (['u'], {}), '(u)\n', (15940, 15943), True, 'import numpy as np\n'), ((16557, 16587), 'numpy.zeros', 'np.zeros', (['(self.total_steps + 1)'], {}), '(self.total_steps + 1)\n', (16565, 16587), True, 'import numpy as np\n'), ((16892, 16911), 'numpy.array', 'np.array', (['tarrayfsp'], {}), '(tarrayfsp)\n', (16900, 16911), True, 'import numpy as np\n'), ((17042, 17057), 'numpy.diff', 'np.diff', (['sarray'], {}), '(sarray)\n', (17049, 17057), True, 'import numpy as np\n'), ((17146, 17171), 'numpy.trapz', 'np.trapz', (['(rhos * ss)'], {'x': 'ss'}), '(rhos * ss, x=ss)\n', (17154, 17171), True, 'import numpy as np\n'), ((17181, 17211), 'numpy.trapz', 'np.trapz', (['(rhos * ss ** 2)'], {'x': 'ss'}), '(rhos * ss ** 2, x=ss)\n', (17189, 17211), True, 'import numpy as np\n'), ((1783, 1800), 'platform.system', 'platform.system', ([], {}), '()\n', (1798, 1800), False, 'import platform\n'), ((4813, 4854), 'numpy.random.gamma', 'np.random.gamma', ([], {'shape': '(1 / CV2)', 'scale': 'CV2'}), '(shape=1 / CV2, scale=CV2)\n', (4828, 4854), True, 'import numpy as np\n'), ((5075, 5105), 'numpy.random.beta', 'np.random.beta', ([], {'a': 'beta', 'b': 'beta'}), '(a=beta, b=beta)\n', (5089, 5105), True, 'import numpy as np\n'), ((5320, 5351), 'scipy.optimize.bisect', 'opt.bisect', (['root', '(1e-05)', '(100000)'], {}), '(root, 1e-05, 100000)\n', (5330, 5351), True, 'from scipy import optimize as opt\n'), ((5620, 5654), 'scipy.integrate.quad', 'integrate.quad', (['moment', 'sb', 'np.inf'], {}), '(moment, sb, np.inf)\n', (5634, 5654), False, 'from scipy import integrate\n'), ((10865, 10882), 'numpy.min', 'np.min', (['nextarray'], {}), '(nextarray)\n', (10871, 10882), True, 'import numpy as np\n'), ((14761, 14773), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (14769, 14773), True, 'import numpy as np\n'), ((15957, 15971), 'numpy.exp', 'np.exp', (['(mu * t)'], {}), '(mu * t)\n', (15963, 15971), True, 'import numpy as np\n'), ((16947, 16960), 'numpy.diff', 'np.diff', (['plim'], {}), '(plim)\n', (16954, 16960), True, 'import numpy as np\n'), ((17017, 17032), 'numpy.exp', 'np.exp', (['(mu * tt)'], {}), '(mu * tt)\n', (17023, 17032), True, 'import numpy as np\n'), ((17118, 17131), 'numpy.diff', 'np.diff', (['plim'], {}), '(plim)\n', (17125, 17131), True, 'import numpy as np\n'), ((24288, 24309), 'math.trunc', 'math.trunc', (['(pos * num)'], {}), '(pos * num)\n', (24298, 24309), False, 'import math\n'), ((5976, 5991), 'scipy.stats.gamma.pdf', 'gamma.pdf', (['x', 'n'], {}), '(x, n)\n', (5985, 5991), False, 'from scipy.stats import gamma\n'), ((6719, 6787), 'cell.Cell', 'Cell', (['idx', 'v'], {'num_steps': 'self.total_steps', 'gr': 'gr', 'divpar': 'divpar', 'k': 'gr'}), '(idx, v, num_steps=self.total_steps, gr=gr, divpar=divpar, k=gr)\n', (6723, 6787), False, 'from cell import Cell\n'), ((7081, 7153), 'cell.Cell', 'Cell', (['i', 'self.sb'], {'num_steps': 'self.total_steps', 'gr': 'gr', 'divpar': 'divpar', 'k': 'gr'}), '(i, self.sb, num_steps=self.total_steps, gr=gr, divpar=divpar, k=gr)\n', (7085, 7153), False, 'from cell import Cell\n'), ((11607, 11627), 'numpy.argmin', 'np.argmin', (['nextarray'], {}), '(nextarray)\n', (11616, 11627), True, 'import numpy as np\n'), ((18651, 18676), 'numpy.zeros', 'np.zeros', (['[ndivs, nsteps]'], {}), '([ndivs, nsteps])\n', (18659, 18676), True, 'import numpy as np\n'), ((18710, 18726), 'numpy.zeros', 'np.zeros', (['nsteps'], {}), '(nsteps)\n', (18718, 18726), True, 'import numpy as np\n'), ((13859, 13875), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (13873, 13875), True, 'import numpy as np\n'), ((17835, 17844), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (17841, 17844), True, 'import numpy as np\n'), ((17868, 17877), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (17874, 17877), True, 'import numpy as np\n'), ((17996, 18047), 'scipy.stats.gamma.ppf', 'gamma.ppf', (['(0.001)'], {'a': '(1 / CV2sz)', 'scale': '(self.V * CV2sz)'}), '(0.001, a=1 / CV2sz, scale=self.V * CV2sz)\n', (18005, 18047), False, 'from scipy.stats import gamma\n'), ((18063, 18114), 'scipy.stats.gamma.ppf', 'gamma.ppf', (['(0.999)'], {'a': '(1 / CV2sz)', 'scale': '(self.V * CV2sz)'}), '(0.999, a=1 / CV2sz, scale=self.V * CV2sz)\n', (18072, 18114), False, 'from scipy.stats import gamma\n'), ((18614, 18633), 'numpy.floor', 'np.floor', (['(tmax / dt)'], {}), '(tmax / dt)\n', (18622, 18633), True, 'import numpy as np\n'), ((10394, 10403), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (10400, 10403), True, 'import numpy as np\n'), ((11255, 11269), 'numpy.exp', 'np.exp', (['(g * tt)'], {}), '(g * tt)\n', (11261, 11269), True, 'import numpy as np\n'), ((11944, 11962), 'numpy.exp', 'np.exp', (['(g * nexttm)'], {}), '(g * nexttm)\n', (11950, 11962), True, 'import numpy as np\n'), ((12415, 12431), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (12429, 12431), True, 'import numpy as np\n'), ((12704, 12776), 'cell.Cell', 'Cell', (['idx'], {'V0': 'sz2', 'num_steps': 'self.total_steps', 'gr': 'gr2', 'divpar': 'dp2', 'k': 'gr2'}), '(idx, V0=sz2, num_steps=self.total_steps, gr=gr2, divpar=dp2, k=gr2)\n', (12708, 12776), False, 'from cell import Cell\n'), ((12939, 12992), 'numpy.concatenate', 'np.concatenate', (['(nextarray, [cell2.nextt])'], {'axis': 'None'}), '((nextarray, [cell2.nextt]), axis=None)\n', (12953, 12992), True, 'import numpy as np\n'), ((18819, 18847), 'numpy.floor', 'np.floor', (['(tmax / (dt * 1000))'], {}), '(tmax / (dt * 1000))\n', (18827, 18847), True, 'import numpy as np\n'), ((8643, 8652), 'numpy.log', 'np.log', (['r'], {}), '(r)\n', (8649, 8652), True, 'import numpy as np\n'), ((9162, 9192), 'numpy.exp', 'np.exp', (['(self.gr * cell.gr * tt)'], {}), '(self.gr * cell.gr * tt)\n', (9168, 9192), True, 'import numpy as np\n'), ((9536, 9552), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (9550, 9552), True, 'import numpy as np\n'), ((9684, 9722), 'numpy.exp', 'np.exp', (['(self.gr * cell.gr * (tmax - t))'], {}), '(self.gr * cell.gr * (tmax - t))\n', (9690, 9722), True, 'import numpy as np\n'), ((12881, 12897), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (12895, 12897), True, 'import numpy as np\n'), ((20243, 20271), 'numpy.floor', 'np.floor', (['(tmax / (dt * 1000))'], {}), '(tmax / (dt * 1000))\n', (20251, 20271), True, 'import numpy as np\n'), ((20446, 20459), 'numpy.sum', 'np.sum', (['u[ii]'], {}), '(u[ii])\n', (20452, 20459), True, 'import numpy as np\n'), ((15574, 15604), 'numpy.int', 'np.int', (['(100 * self.time / tmax)'], {}), '(100 * self.time / tmax)\n', (15580, 15604), True, 'import numpy as np\n'), ((18241, 18297), 'scipy.stats.gamma.cdf', 'gamma.cdf', (['(l + dx / 2)'], {'a': '(1 / CV2sz)', 'scale': '(self.V * CV2sz)'}), '(l + dx / 2, a=1 / CV2sz, scale=self.V * CV2sz)\n', (18250, 18297), False, 'from scipy.stats import gamma\n'), ((18288, 18344), 'scipy.stats.gamma.cdf', 'gamma.cdf', (['(l - dx / 2)'], {'a': '(1 / CV2sz)', 'scale': '(self.V * CV2sz)'}), '(l - dx / 2, a=1 / CV2sz, scale=self.V * CV2sz)\n', (18297, 18344), False, 'from scipy.stats import gamma\n'), ((18520, 18542), 'numpy.int', 'np.int', (['(100 * obj / 30)'], {}), '(100 * obj / 30)\n', (18526, 18542), True, 'import numpy as np\n'), ((21014, 21025), 'numpy.exp', 'np.exp', (['arg'], {}), '(arg)\n', (21020, 21025), True, 'import numpy as np\n'), ((22022, 22033), 'numpy.exp', 'np.exp', (['arg'], {}), '(arg)\n', (22028, 22033), True, 'import numpy as np\n'), ((7836, 7875), 'numpy.round', 'np.round', (['(self.cells[m].gr * self.gr)', '(8)'], {}), '(self.cells[m].gr * self.gr, 8)\n', (7844, 7875), True, 'import numpy as np\n'), ((20965, 20974), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (20971, 20974), True, 'import numpy as np\n'), ((21330, 21339), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (21336, 21339), True, 'import numpy as np\n'), ((21973, 21982), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (21979, 21982), True, 'import numpy as np\n'), ((22351, 22360), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (22357, 22360), True, 'import numpy as np\n'), ((11442, 11461), 'numpy.round', 'np.round', (['cell.V', '(8)'], {}), '(cell.V, 8)\n', (11450, 11461), True, 'import numpy as np\n'), ((19103, 19112), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (19109, 19112), True, 'import numpy as np\n'), ((7781, 7809), 'numpy.round', 'np.round', (['self.cells[m].V', '(8)'], {}), '(self.cells[m].V, 8)\n', (7789, 7809), True, 'import numpy as np\n'), ((19262, 19283), 'numpy.exp', 'np.exp', (['(lamb * gr * t)'], {}), '(lamb * gr * t)\n', (19268, 19283), True, 'import numpy as np\n'), ((19435, 19446), 'numpy.exp', 'np.exp', (['arg'], {}), '(arg)\n', (19441, 19446), True, 'import numpy as np\n'), ((20061, 20072), 'numpy.exp', 'np.exp', (['arg'], {}), '(arg)\n', (20067, 20072), True, 'import numpy as np\n'), ((21395, 21406), 'numpy.exp', 'np.exp', (['arg'], {}), '(arg)\n', (21401, 21406), True, 'import numpy as np\n'), ((22416, 22427), 'numpy.exp', 'np.exp', (['arg'], {}), '(arg)\n', (22422, 22427), True, 'import numpy as np\n'), ((13389, 13414), 'numpy.round', 'np.round', (['(gr * self.gr)', '(8)'], {}), '(gr * self.gr, 8)\n', (13397, 13414), True, 'import numpy as np\n'), ((19707, 19718), 'numpy.exp', 'np.exp', (['arg'], {}), '(arg)\n', (19713, 19718), True, 'import numpy as np\n'), ((19888, 19899), 'numpy.exp', 'np.exp', (['arg'], {}), '(arg)\n', (19894, 19899), True, 'import numpy as np\n'), ((13765, 13791), 'numpy.round', 'np.round', (['(gr2 * self.gr)', '(8)'], {}), '(gr2 * self.gr, 8)\n', (13773, 13791), True, 'import numpy as np\n'), ((13320, 13335), 'numpy.round', 'np.round', (['sz', '(8)'], {}), '(sz, 8)\n', (13328, 13335), True, 'import numpy as np\n'), ((13695, 13711), 'numpy.round', 'np.round', (['sz2', '(8)'], {}), '(sz2, 8)\n', (13703, 13711), True, 'import numpy as np\n')] |
"""
file: simple_gen.py
author: <NAME>
date: 17 May 2020
notes: a most basic implementation of genetic cross breeding and mutation to attempt to improve
a neural network. Assumes the standard Keras model from Donkeycar project.
Lower score means less loss = better.
"""
import argparse
import json
import os
import time
import warnings
import numpy as np
from PIL import Image
# noisy, noisy tensorflow. we love you.
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=FutureWarning)
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.ERROR)
class IAgent:
def begin(self):
pass
def wait(self):
pass
def get_score(self):
pass
def make_new(self, parent1, parent2):
return IAgent()
class GeneticAlg:
def __init__(self, population, conf={}):
self.population = population
self.conf = conf
def finished(self):
return False
def process(self, num_iter):
iIter = 0
while not self.finished() and iIter < num_iter:
print("starting epoch", iIter)
s = time.time()
self.evaluate_agents()
self.on_agents_finished()
e = time.time() - s
self.breed_agents()
iIter += 1
d = time.time() - s
# Time per iteration getting worse?!
print("finish epoch", iIter)
print("Iter %d eval time: %f total time: %f" % (iIter, e, d))
def on_agents_finished(self):
pass
def evaluate_agents(self):
for agent in self.population:
agent.begin()
for agent in self.population:
agent.wait()
self.sort_agents()
# progress
print("scores:", [a.score for a in self.population])
def how_many_to_keep(self):
return round(len(self.population) / 4) + 1
def breed_agents(self):
"""
keep the best N of our population and replace the rest
with versions cross bred from other agents.
"""
keep = self.how_many_to_keep()
num_new = len(self.population) - keep
pop_to_keep = self.population[0:keep]
new_population = []
for _ in range(num_new):
p1, p2 = self.select_parents()
new_agent = p1.make_new(p1, p2)
new_agent.mutate()
new_population.append(new_agent)
self.population = pop_to_keep + new_population
def sort_agents(self):
self.population.sort(key=lambda x: x.get_score(), reverse=False)
def select_pop_index(self):
r = np.random.uniform(low=0.0, high=1.0)
N = len(self.population)
iP = round(r * N) % N
return iP
def select_parents(self):
iP1 = self.select_pop_index()
iP2 = self.select_pop_index()
# hack, always select the best 2
# iP1 = 0
# iP2 = 1
# lets make sure parents are not the same
while iP2 == iP1:
iP2 = self.select_pop_index()
return self.population[iP1], self.population[iP2]
class NNAgent(IAgent):
def __init__(self, model, conf):
self.model = model
self.score = 0.0
self.conf = conf
def begin(self):
self.score = 0.0
def wait(self):
pass
def get_score(self):
return self.score
def mutate(self):
pass
def breed(self, agent1, agent2):
return agent1.model
def make_new(self, parent1, parent2):
new_model = self.breed(parent1, parent2)
agent = NNAgent(new_model, self.conf)
agent.mutate()
return agent
class KerasNNAgent(NNAgent):
def __init__(self, model, conf):
super().__init__(model, conf)
self.mutation_rate = conf["mutation_rate"]
def mutate(self):
layers_to_mutate = self.conf["layers_to_mutate"]
for iLayer in layers_to_mutate:
layer = self.model.get_layer(index=iLayer)
w = layer.get_weights()
self.modify_weights(w)
layer.set_weights(w)
self.decay_mutations()
def rand_float(self, mn, mx):
return float(np.random.uniform(mn, mx, 1)[0])
def modify_weights(self, w):
mx = self.conf["mutation_max"]
mn = self.conf["mutation_min"]
mag = self.rand_float(mn, mx)
for iArr, arr in enumerate(w):
val = self.rand_float(0.0, 1.0)
if val > self.mutation_rate:
continue
random_values = np.random.uniform(-mag, mag, arr.shape)
arr = arr + random_values
w[iArr] = arr
return w
def decay_mutations(self):
self.conf["mutation_max"] *= self.conf["mutation_decay"]
def breed(self, agent1, agent2):
model1, model2 = agent1.model, agent2.model
jsm = model1.to_json()
new_model = tf.keras.models.model_from_json(jsm)
new_model.set_weights(model1.get_weights())
iLayers = self.conf["layers_to_combine"]
for iLayer in iLayers:
layer1 = model1.get_layer(index=iLayer)
layer2 = model2.get_layer(index=iLayer)
final_layer = new_model.get_layer(index=iLayer)
self.merge_layers(final_layer, layer1, layer2)
return new_model
def merge_layers(self, dest_layer, src1_layer, src2_layer):
w1 = src1_layer.get_weights()
w2 = src2_layer.get_weights()
res = w1.copy()
if type(w1) is list:
half = round(len(w1) / 2)
res[half:-1] = w2[half:-1]
else:
l_indices = np.tril_indices_from(w2)
res[l_indices] = w2[l_indices]
dest_layer.set_weights(res)
class KerasNNImageAgent(KerasNNAgent):
"""
Given an image and a target prediction, make an agent that will
optimize for score of target.
"""
def __init__(self, model, conf):
super().__init__(model, conf)
self.image = conf["image"]
self.target = conf["target"]
def begin(self):
pred = self.model.predict(self.image)
self.score = np.sum(np.absolute(pred - self.target))
def make_new(self, parent1, parent2):
new_model = self.breed(parent1, parent2)
agent = KerasNNImageAgent(new_model, self.conf)
agent.mutate()
return agent
def test_image_agent(model_filename, record_filename, num_agents, num_iter):
with open(os.path.expanduser(record_filename), "r") as fp:
record = json.load(fp)
img_filename = os.path.join(os.path.dirname(record_filename), record["cam/image_array"])
img = Image.open(os.path.expanduser(img_filename))
img_arr = np.array(img)
# Our model was trained with this normalization scale on data.
one_byte_scale = 1.0 / 255.0
img_arr = img_arr.astype(np.float32) * one_byte_scale
img_arr = img_arr.reshape((1,) + img_arr.shape)
steering = record["user/angle"]
throttle = record["user/throttle"]
target = np.array([np.array([[steering]]), np.array([[throttle]])])
# These are the final two dense layers we will mutate. We will use the same two layers we breeding.
to_mutate = [14, 16]
conf = {"layers_to_mutate": to_mutate}
conf["layers_to_combine"] = to_mutate
conf["mutation_rate"] = 1.0
conf["mutation_max"] = 0.3
conf["mutation_min"] = 0.0
conf["mutation_decay"] = 1.0
conf["image"] = img_arr
conf["target"] = target
population = []
for i in range(num_agents):
model = tf.keras.models.load_model(os.path.expanduser(model_filename))
agent = KerasNNImageAgent(model, conf)
if i > 0:
agent.mutate()
population.append(agent)
# Some initial state
print("target: steering: %f throttle: %f" % (target[0][0][0], target[1][0][0]))
agent = population[0]
agent.begin()
print("initial score:", agent.score)
pred = agent.model.predict(img_arr)
print("initial pred", pred[0][0], pred[1][0])
# Try to improve
alg = GeneticAlg(population)
alg.process(num_iter=num_iter)
# Our best agent
agent = alg.population[0]
print("final score:", agent.score)
pred = agent.model.predict(img_arr)
print("final pred", pred[0][0], pred[1][0])
if __name__ == "__main__":
# Example: python ~\projects\gym-donkeycar\examples\genetic_alg\simple_gen.py
# --model models\lane_keeper.h5 --record data\tub_6_20-05-16\record_2000.json
parser = argparse.ArgumentParser(description="simple_gen")
parser.add_argument("--model", type=str, help=".h5 model produced by donkeycar. expects the default linear model type.")
parser.add_argument("--record", type=str, help="donkey json record to use for training")
parser.add_argument("--num_agents", type=int, default=8, help="how many agents in our population")
parser.add_argument("--num_iter", type=int, default=8, help="how many generations before we stop")
args = parser.parse_args()
# only needed if TF==1.13.1
# config = tf.ConfigProto()
# config.gpu_options.allow_growth = True
# sess = tf.Session(config=config)
# K.set_session(sess)
test_image_agent(
model_filename=args.model, record_filename=args.record, num_agents=args.num_agents, num_iter=args.num_iter
)
| [
"numpy.tril_indices_from",
"argparse.ArgumentParser",
"tensorflow.keras.models.model_from_json",
"numpy.absolute",
"warnings.catch_warnings",
"tensorflow.logging.set_verbosity",
"numpy.array",
"os.path.dirname",
"numpy.random.uniform",
"json.load",
"time.time",
"warnings.filterwarnings",
"os... | [((600, 642), 'tensorflow.logging.set_verbosity', 'tf.logging.set_verbosity', (['tf.logging.ERROR'], {}), '(tf.logging.ERROR)\n', (624, 642), True, 'import tensorflow as tf\n'), ((482, 507), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (505, 507), False, 'import warnings\n'), ((513, 570), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'FutureWarning'}), "('ignore', category=FutureWarning)\n", (536, 570), False, 'import warnings\n'), ((6748, 6761), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (6756, 6761), True, 'import numpy as np\n'), ((8536, 8585), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""simple_gen"""'}), "(description='simple_gen')\n", (8559, 8585), False, 'import argparse\n'), ((2670, 2706), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(0.0)', 'high': '(1.0)'}), '(low=0.0, high=1.0)\n', (2687, 2706), True, 'import numpy as np\n'), ((4953, 4989), 'tensorflow.keras.models.model_from_json', 'tf.keras.models.model_from_json', (['jsm'], {}), '(jsm)\n', (4984, 4989), True, 'import tensorflow as tf\n'), ((6572, 6585), 'json.load', 'json.load', (['fp'], {}), '(fp)\n', (6581, 6585), False, 'import json\n'), ((6618, 6650), 'os.path.dirname', 'os.path.dirname', (['record_filename'], {}), '(record_filename)\n', (6633, 6650), False, 'import os\n'), ((6700, 6732), 'os.path.expanduser', 'os.path.expanduser', (['img_filename'], {}), '(img_filename)\n', (6718, 6732), False, 'import os\n'), ((1173, 1184), 'time.time', 'time.time', ([], {}), '()\n', (1182, 1184), False, 'import time\n'), ((4594, 4633), 'numpy.random.uniform', 'np.random.uniform', (['(-mag)', 'mag', 'arr.shape'], {}), '(-mag, mag, arr.shape)\n', (4611, 4633), True, 'import numpy as np\n'), ((5681, 5705), 'numpy.tril_indices_from', 'np.tril_indices_from', (['w2'], {}), '(w2)\n', (5701, 5705), True, 'import numpy as np\n'), ((6188, 6219), 'numpy.absolute', 'np.absolute', (['(pred - self.target)'], {}), '(pred - self.target)\n', (6199, 6219), True, 'import numpy as np\n'), ((6506, 6541), 'os.path.expanduser', 'os.path.expanduser', (['record_filename'], {}), '(record_filename)\n', (6524, 6541), False, 'import os\n'), ((7071, 7093), 'numpy.array', 'np.array', (['[[steering]]'], {}), '([[steering]])\n', (7079, 7093), True, 'import numpy as np\n'), ((7095, 7117), 'numpy.array', 'np.array', (['[[throttle]]'], {}), '([[throttle]])\n', (7103, 7117), True, 'import numpy as np\n'), ((7615, 7649), 'os.path.expanduser', 'os.path.expanduser', (['model_filename'], {}), '(model_filename)\n', (7633, 7649), False, 'import os\n'), ((1275, 1286), 'time.time', 'time.time', ([], {}), '()\n', (1284, 1286), False, 'import time\n'), ((1362, 1373), 'time.time', 'time.time', ([], {}), '()\n', (1371, 1373), False, 'import time\n'), ((4232, 4260), 'numpy.random.uniform', 'np.random.uniform', (['mn', 'mx', '(1)'], {}), '(mn, mx, 1)\n', (4249, 4260), True, 'import numpy as np\n')] |
import nexussdk as nexus
prod = "https://bbp.epfl.ch/nexus/v1/"
staging = 'https://bbp-nexus.epfl.ch/staging/v1'
token = open('token.txt', 'r').read().strip()
nexus.config.set_token(token)
nexus.config.set_environment(staging)
# DEV with Github token
# token = open('token-gh.txt', 'r').read().strip()
# nexus.config.set_token(token)
# nexus.config.set_environment('http://dev.nexus.ocp.bbp.epfl.ch/v1')
# DEV with Github token
# token = open('token-gh.txt', 'r').read().strip()
# nexus.config.set_token(token)
# nexus.config.set_environment('http://dev.nexus.ocp.bbp.epfl.ch/v1')
# WORKS
# Fetch a view
# payload = nexus.views.fetch("bbp", "example", "http://example.comthe_id_of_this")
# payload = nexus.views.fetch("bbp", "example", "http://example.comthe_id_of_this", tag="some_tag")
# nexus.tools.pretty_print(payload)
# WORKS
# Create a ES view
# view_data = """
# {
# "mapping": {
# "dynamic": false,
# "properties": {
# "@id": {
# "type": "keyword"
# },
# "@type": {
# "type": "keyword"
# },
# "firstname": {
# "type": "keyword"
# },
# "lastname": {
# "type": "keyword"
# }
# }
# },
# "includeMetadata": false,
# "sourceAsText": false,
# "resourceSchemas": "nxs:myschema"
# }
# """
# payload = nexus.views.create_es("bbp", "example", view_data, id="name_view")
# nexus.tools.pretty_print(payload)
# WORKS
# List the views (all kinds)
# payload = nexus.views.list("bbp", "example")
# nexus.tools.pretty_print(payload)
# Listing but keeping only the ElasticSearch view from the list
# list_of_es_views = nexus.views.list_keep_only_es( nexus.views.list("bbp", "example") )
# nexus.tools.pretty_print(list_of_es_views)
# WORKS
# Update a view
# payload["mapping"]["dynamic"] = True
# payload = nexus.views.update_es(payload)
# nexus.tools.pretty_print(payload)
# WORKS
# Deprecate a view
# payload = nexus.views.deprecate_es(payload)
# nexus.tools.pretty_print(payload)
# Tag a view
# payload = nexus.views.tag_es(payload, "some_tag")
# nexus.tools.pretty_print(payload)
# # Aggregate some views
# # 1- make a list of their ids
# view_ids_to_aggregate = [
# "http://example.comthe_id_of_this",
# "nxv:myview1"
# ]
# # 2- gotta fetch'em all!
# views_to_aggregate = []
# for id in view_ids_to_aggregate:
# views_to_aggregate.append( nexus.views.fetch("bbp", "example", id) )
#
# # 3- make the call to Aggregate them
# payload = nexus.views.aggregate_es("bbp", "example", views_to_aggregate, id="some_fancy_aggregation")
# nexus.tools.pretty_print(payload)
# # # Perform a ES query
# query = """
# {
# "query": {
# "term": {
# "firstname": "Johnny6"
# }
# }
# }
# """
# payload_view = nexus.views.fetch("bbp", "example", "name_view")
# payload = nexus.views.query_es(payload_view, query)
# nexus.tools.pretty_print(payload)
# SparQL query
query = "SELECT ?s where {?s ?p ?o} LIMIT 2"
payload = nexus.views.query_sparql("bbp", "example", query)
nexus.tools.pretty_print(payload)
| [
"nexussdk.tools.pretty_print",
"nexussdk.config.set_environment",
"nexussdk.config.set_token",
"nexussdk.views.query_sparql"
] | [((162, 191), 'nexussdk.config.set_token', 'nexus.config.set_token', (['token'], {}), '(token)\n', (184, 191), True, 'import nexussdk as nexus\n'), ((192, 229), 'nexussdk.config.set_environment', 'nexus.config.set_environment', (['staging'], {}), '(staging)\n', (220, 229), True, 'import nexussdk as nexus\n'), ((2949, 2998), 'nexussdk.views.query_sparql', 'nexus.views.query_sparql', (['"""bbp"""', '"""example"""', 'query'], {}), "('bbp', 'example', query)\n", (2973, 2998), True, 'import nexussdk as nexus\n'), ((2999, 3032), 'nexussdk.tools.pretty_print', 'nexus.tools.pretty_print', (['payload'], {}), '(payload)\n', (3023, 3032), True, 'import nexussdk as nexus\n')] |
#!/usr/bin/env python3
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test node responses to invalid blocks.
In this test we connect to one node over p2p, and test block requests:
1) Valid blocks should be requested and become chain tip.
2) Invalid block with duplicated transaction should be re-requested.
3) Invalid block with bad coinbase value should be rejected and not
re-requested.
"""
import copy
from test_framework.blocktools import (
create_block,
create_coinbase,
create_transaction,
)
from test_framework.messages import COIN
from test_framework.mininode import network_thread_start, P2PDataStore
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal
class InvalidBlockRequestTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 1
self.setup_clean_chain = True
self.extra_args = [["-whitelist=127.0.0.1"]]
def run_test(self):
# Add p2p connection to node0
node = self.nodes[0] # convenience reference to the node
node.add_p2p_connection(P2PDataStore())
network_thread_start()
node.p2p.wait_for_verack()
best_block = node.getblock(node.getbestblockhash())
tip = int(node.getbestblockhash(), 16)
height = best_block["height"] + 1
block_time = best_block["time"] + 1
self.log.info("Create a new block with an anyone-can-spend coinbase")
height = 1
block = create_block(tip, create_coinbase(height), block_time)
block.solve()
# Save the coinbase for later
block1 = block
tip = block.sha256
node.p2p.send_blocks_and_test([block1], node, True)
self.log.info("Mature the block.")
node.generate(100)
best_block = node.getblock(node.getbestblockhash())
tip = int(node.getbestblockhash(), 16)
height = best_block["height"] + 1
block_time = best_block["time"] + 1
# Use merkle-root malleability to generate an invalid block with
# same blockheader.
# Manufacture a block with 3 transactions (coinbase, spend of prior
# coinbase, spend of that spend). Duplicate the 3rd transaction to
# leave merkle root and blockheader unchanged but invalidate the block.
self.log.info("Test merkle root malleability.")
block2 = create_block(tip, create_coinbase(height), block_time)
block_time += 1
# b'0x51' is OP_TRUE
tx1 = create_transaction(block1.vtx[0], 0, b'', 50 * COIN)
tx2 = create_transaction(tx1, 0, b'\x51', 50 * COIN)
block2.vtx.extend([tx1, tx2])
block2.vtx = [block2.vtx[0]] + \
sorted(block2.vtx[1:], key=lambda tx: tx.get_id())
block2.hashMerkleRoot = block2.calc_merkle_root()
block2.rehash()
block2.solve()
orig_hash = block2.sha256
block2_orig = copy.deepcopy(block2)
# Mutate block 2
block2.vtx.append(block2.vtx[2])
assert_equal(block2.hashMerkleRoot, block2.calc_merkle_root())
assert_equal(orig_hash, block2.rehash())
assert(block2_orig.vtx != block2.vtx)
node.p2p.send_blocks_and_test(
[block2], node, False, False, 16, b'bad-txns-duplicate')
# Check transactions for duplicate inputs
self.log.info("Test duplicate input block.")
block2_orig.vtx[2].vin.append(block2_orig.vtx[2].vin[0])
block2.vtx = [block2.vtx[0]] + \
sorted(block2.vtx[1:], key=lambda tx: tx.get_id())
block2_orig.vtx[2].rehash()
block2_orig.hashMerkleRoot = block2_orig.calc_merkle_root()
block2_orig.rehash()
block2_orig.solve()
node.p2p.send_blocks_and_test(
[block2_orig], node, False, False, 16, b'bad-txns-inputs-duplicate')
self.log.info("Test very broken block.")
block3 = create_block(tip, create_coinbase(height), block_time)
block_time += 1
block3.vtx[0].vout[0].nValue = 100 * COIN # Too high!
block3.vtx[0].sha256 = None
block3.vtx[0].calc_sha256()
block3.hashMerkleRoot = block3.calc_merkle_root()
block3.rehash()
block3.solve()
node.p2p.send_blocks_and_test(
[block3], node, False, False, 16, b'bad-cb-amount')
if __name__ == '__main__':
InvalidBlockRequestTest().main()
| [
"test_framework.blocktools.create_transaction",
"copy.deepcopy",
"test_framework.mininode.network_thread_start",
"test_framework.blocktools.create_coinbase",
"test_framework.mininode.P2PDataStore"
] | [((1270, 1292), 'test_framework.mininode.network_thread_start', 'network_thread_start', ([], {}), '()\n', (1290, 1292), False, 'from test_framework.mininode import network_thread_start, P2PDataStore\n'), ((2658, 2710), 'test_framework.blocktools.create_transaction', 'create_transaction', (['block1.vtx[0]', '(0)', "b''", '(50 * COIN)'], {}), "(block1.vtx[0], 0, b'', 50 * COIN)\n", (2676, 2710), False, 'from test_framework.blocktools import create_block, create_coinbase, create_transaction\n'), ((2725, 2768), 'test_framework.blocktools.create_transaction', 'create_transaction', (['tx1', '(0)', "b'Q'", '(50 * COIN)'], {}), "(tx1, 0, b'Q', 50 * COIN)\n", (2743, 2768), False, 'from test_framework.blocktools import create_block, create_coinbase, create_transaction\n'), ((3076, 3097), 'copy.deepcopy', 'copy.deepcopy', (['block2'], {}), '(block2)\n', (3089, 3097), False, 'import copy\n'), ((1245, 1259), 'test_framework.mininode.P2PDataStore', 'P2PDataStore', ([], {}), '()\n', (1257, 1259), False, 'from test_framework.mininode import network_thread_start, P2PDataStore\n'), ((1655, 1678), 'test_framework.blocktools.create_coinbase', 'create_coinbase', (['height'], {}), '(height)\n', (1670, 1678), False, 'from test_framework.blocktools import create_block, create_coinbase, create_transaction\n'), ((2553, 2576), 'test_framework.blocktools.create_coinbase', 'create_coinbase', (['height'], {}), '(height)\n', (2568, 2576), False, 'from test_framework.blocktools import create_block, create_coinbase, create_transaction\n'), ((4081, 4104), 'test_framework.blocktools.create_coinbase', 'create_coinbase', (['height'], {}), '(height)\n', (4096, 4104), False, 'from test_framework.blocktools import create_block, create_coinbase, create_transaction\n')] |
"""
Support for covers which integrate with other components.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/cover.template/
"""
import logging
import voluptuous as vol
from homeassistant.core import callback
from homeassistant.components.cover import (
ENTITY_ID_FORMAT, CoverDevice, PLATFORM_SCHEMA,
SUPPORT_OPEN_TILT, SUPPORT_CLOSE_TILT, SUPPORT_STOP_TILT,
SUPPORT_SET_TILT_POSITION, SUPPORT_OPEN, SUPPORT_CLOSE, SUPPORT_STOP,
SUPPORT_SET_POSITION, ATTR_POSITION, ATTR_TILT_POSITION)
from homeassistant.const import (
CONF_FRIENDLY_NAME, CONF_ENTITY_ID,
EVENT_HOMEASSISTANT_START, MATCH_ALL,
CONF_VALUE_TEMPLATE, CONF_ICON_TEMPLATE,
CONF_ENTITY_PICTURE_TEMPLATE, CONF_OPTIMISTIC,
STATE_OPEN, STATE_CLOSED)
from homeassistant.exceptions import TemplateError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import async_generate_entity_id
from homeassistant.helpers.event import async_track_state_change
from homeassistant.helpers.script import Script
_LOGGER = logging.getLogger(__name__)
_VALID_STATES = [STATE_OPEN, STATE_CLOSED, 'true', 'false']
CONF_COVERS = 'covers'
CONF_POSITION_TEMPLATE = 'position_template'
CONF_TILT_TEMPLATE = 'tilt_template'
OPEN_ACTION = 'open_cover'
CLOSE_ACTION = 'close_cover'
STOP_ACTION = 'stop_cover'
POSITION_ACTION = 'set_cover_position'
TILT_ACTION = 'set_cover_tilt_position'
CONF_TILT_OPTIMISTIC = 'tilt_optimistic'
CONF_VALUE_OR_POSITION_TEMPLATE = 'value_or_position'
CONF_OPEN_OR_CLOSE = 'open_or_close'
TILT_FEATURES = (SUPPORT_OPEN_TILT | SUPPORT_CLOSE_TILT | SUPPORT_STOP_TILT |
SUPPORT_SET_TILT_POSITION)
COVER_SCHEMA = vol.Schema({
vol.Inclusive(OPEN_ACTION, CONF_OPEN_OR_CLOSE): cv.SCRIPT_SCHEMA,
vol.Inclusive(CLOSE_ACTION, CONF_OPEN_OR_CLOSE): cv.SCRIPT_SCHEMA,
vol.Optional(STOP_ACTION): cv.SCRIPT_SCHEMA,
vol.Exclusive(CONF_POSITION_TEMPLATE,
CONF_VALUE_OR_POSITION_TEMPLATE): cv.template,
vol.Exclusive(CONF_VALUE_TEMPLATE,
CONF_VALUE_OR_POSITION_TEMPLATE): cv.template,
vol.Optional(CONF_POSITION_TEMPLATE): cv.template,
vol.Optional(CONF_TILT_TEMPLATE): cv.template,
vol.Optional(CONF_ICON_TEMPLATE): cv.template,
vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template,
vol.Optional(CONF_OPTIMISTIC): cv.boolean,
vol.Optional(CONF_TILT_OPTIMISTIC): cv.boolean,
vol.Optional(POSITION_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(TILT_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(CONF_FRIENDLY_NAME): cv.string,
vol.Optional(CONF_ENTITY_ID): cv.entity_ids
})
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_COVERS): vol.Schema({cv.slug: COVER_SCHEMA}),
})
async def async_setup_platform(hass, config, async_add_devices,
discovery_info=None):
"""Set up the Template cover."""
covers = []
for device, device_config in config[CONF_COVERS].items():
friendly_name = device_config.get(CONF_FRIENDLY_NAME, device)
state_template = device_config.get(CONF_VALUE_TEMPLATE)
position_template = device_config.get(CONF_POSITION_TEMPLATE)
tilt_template = device_config.get(CONF_TILT_TEMPLATE)
icon_template = device_config.get(CONF_ICON_TEMPLATE)
entity_picture_template = device_config.get(
CONF_ENTITY_PICTURE_TEMPLATE)
open_action = device_config.get(OPEN_ACTION)
close_action = device_config.get(CLOSE_ACTION)
stop_action = device_config.get(STOP_ACTION)
position_action = device_config.get(POSITION_ACTION)
tilt_action = device_config.get(TILT_ACTION)
optimistic = device_config.get(CONF_OPTIMISTIC)
tilt_optimistic = device_config.get(CONF_TILT_OPTIMISTIC)
if position_action is None and open_action is None:
_LOGGER.error('Must specify at least one of %s' or '%s',
OPEN_ACTION, POSITION_ACTION)
continue
template_entity_ids = set()
if state_template is not None:
temp_ids = state_template.extract_entities()
if str(temp_ids) != MATCH_ALL:
template_entity_ids |= set(temp_ids)
if position_template is not None:
temp_ids = position_template.extract_entities()
if str(temp_ids) != MATCH_ALL:
template_entity_ids |= set(temp_ids)
if tilt_template is not None:
temp_ids = tilt_template.extract_entities()
if str(temp_ids) != MATCH_ALL:
template_entity_ids |= set(temp_ids)
if icon_template is not None:
temp_ids = icon_template.extract_entities()
if str(temp_ids) != MATCH_ALL:
template_entity_ids |= set(temp_ids)
if entity_picture_template is not None:
temp_ids = entity_picture_template.extract_entities()
if str(temp_ids) != MATCH_ALL:
template_entity_ids |= set(temp_ids)
if not template_entity_ids:
template_entity_ids = MATCH_ALL
entity_ids = device_config.get(CONF_ENTITY_ID, template_entity_ids)
covers.append(
CoverTemplate(
hass,
device, friendly_name, state_template,
position_template, tilt_template, icon_template,
entity_picture_template, open_action, close_action,
stop_action, position_action, tilt_action,
optimistic, tilt_optimistic, entity_ids
)
)
if not covers:
_LOGGER.error("No covers added")
return False
async_add_devices(covers)
return True
class CoverTemplate(CoverDevice):
"""Representation of a Template cover."""
def __init__(self, hass, device_id, friendly_name, state_template,
position_template, tilt_template, icon_template,
entity_picture_template, open_action, close_action,
stop_action, position_action, tilt_action,
optimistic, tilt_optimistic, entity_ids):
"""Initialize the Template cover."""
self.hass = hass
self.entity_id = async_generate_entity_id(
ENTITY_ID_FORMAT, device_id, hass=hass)
self._name = friendly_name
self._template = state_template
self._position_template = position_template
self._tilt_template = tilt_template
self._icon_template = icon_template
self._entity_picture_template = entity_picture_template
self._open_script = None
if open_action is not None:
self._open_script = Script(hass, open_action)
self._close_script = None
if close_action is not None:
self._close_script = Script(hass, close_action)
self._stop_script = None
if stop_action is not None:
self._stop_script = Script(hass, stop_action)
self._position_script = None
if position_action is not None:
self._position_script = Script(hass, position_action)
self._tilt_script = None
if tilt_action is not None:
self._tilt_script = Script(hass, tilt_action)
self._optimistic = (optimistic or
(not state_template and not position_template))
self._tilt_optimistic = tilt_optimistic or not tilt_template
self._icon = None
self._entity_picture = None
self._position = None
self._tilt_value = None
self._entities = entity_ids
if self._template is not None:
self._template.hass = self.hass
if self._position_template is not None:
self._position_template.hass = self.hass
if self._tilt_template is not None:
self._tilt_template.hass = self.hass
if self._icon_template is not None:
self._icon_template.hass = self.hass
if self._entity_picture_template is not None:
self._entity_picture_template.hass = self.hass
async def async_added_to_hass(self):
"""Register callbacks."""
@callback
def template_cover_state_listener(entity, old_state, new_state):
"""Handle target device state changes."""
self.async_schedule_update_ha_state(True)
@callback
def template_cover_startup(event):
"""Update template on startup."""
async_track_state_change(
self.hass, self._entities, template_cover_state_listener)
self.async_schedule_update_ha_state(True)
self.hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_START, template_cover_startup)
@property
def name(self):
"""Return the name of the cover."""
return self._name
@property
def is_closed(self):
"""Return if the cover is closed."""
return self._position == 0
@property
def current_cover_position(self):
"""Return current position of cover.
None is unknown, 0 is closed, 100 is fully open.
"""
if self._position_template or self._position_script:
return self._position
return None
@property
def current_cover_tilt_position(self):
"""Return current position of cover tilt.
None is unknown, 0 is closed, 100 is fully open.
"""
return self._tilt_value
@property
def icon(self):
"""Return the icon to use in the frontend, if any."""
return self._icon
@property
def entity_picture(self):
"""Return the entity picture to use in the frontend, if any."""
return self._entity_picture
@property
def supported_features(self):
"""Flag supported features."""
supported_features = SUPPORT_OPEN | SUPPORT_CLOSE
if self._stop_script is not None:
supported_features |= SUPPORT_STOP
if self._position_script is not None:
supported_features |= SUPPORT_SET_POSITION
if self.current_cover_tilt_position is not None:
supported_features |= TILT_FEATURES
return supported_features
@property
def should_poll(self):
"""Return the polling state."""
return False
async def async_open_cover(self, **kwargs):
"""Move the cover up."""
if self._open_script:
await self._open_script.async_run()
elif self._position_script:
await self._position_script.async_run({"position": 100})
if self._optimistic:
self._position = 100
self.async_schedule_update_ha_state()
async def async_close_cover(self, **kwargs):
"""Move the cover down."""
if self._close_script:
await self._close_script.async_run()
elif self._position_script:
await self._position_script.async_run({"position": 0})
if self._optimistic:
self._position = 0
self.async_schedule_update_ha_state()
async def async_stop_cover(self, **kwargs):
"""Fire the stop action."""
if self._stop_script:
await self._stop_script.async_run()
async def async_set_cover_position(self, **kwargs):
"""Set cover position."""
self._position = kwargs[ATTR_POSITION]
await self._position_script.async_run(
{"position": self._position})
if self._optimistic:
self.async_schedule_update_ha_state()
async def async_open_cover_tilt(self, **kwargs):
"""Tilt the cover open."""
self._tilt_value = 100
await self._tilt_script.async_run({"tilt": self._tilt_value})
if self._tilt_optimistic:
self.async_schedule_update_ha_state()
async def async_close_cover_tilt(self, **kwargs):
"""Tilt the cover closed."""
self._tilt_value = 0
await self._tilt_script.async_run(
{"tilt": self._tilt_value})
if self._tilt_optimistic:
self.async_schedule_update_ha_state()
async def async_set_cover_tilt_position(self, **kwargs):
"""Move the cover tilt to a specific position."""
self._tilt_value = kwargs[ATTR_TILT_POSITION]
await self._tilt_script.async_run({"tilt": self._tilt_value})
if self._tilt_optimistic:
self.async_schedule_update_ha_state()
async def async_update(self):
"""Update the state from the template."""
if self._template is not None:
try:
state = self._template.async_render().lower()
if state in _VALID_STATES:
if state in ('true', STATE_OPEN):
self._position = 100
else:
self._position = 0
else:
_LOGGER.error(
'Received invalid cover is_on state: %s. Expected: %s',
state, ', '.join(_VALID_STATES))
self._position = None
except TemplateError as ex:
_LOGGER.error(ex)
self._position = None
if self._position_template is not None:
try:
state = float(self._position_template.async_render())
if state < 0 or state > 100:
self._position = None
_LOGGER.error("Cover position value must be"
" between 0 and 100."
" Value was: %.2f", state)
else:
self._position = state
except TemplateError as ex:
_LOGGER.error(ex)
self._position = None
except ValueError as ex:
_LOGGER.error(ex)
self._position = None
if self._tilt_template is not None:
try:
state = float(self._tilt_template.async_render())
if state < 0 or state > 100:
self._tilt_value = None
_LOGGER.error("Tilt value must be between 0 and 100."
" Value was: %.2f", state)
else:
self._tilt_value = state
except TemplateError as ex:
_LOGGER.error(ex)
self._tilt_value = None
except ValueError as ex:
_LOGGER.error(ex)
self._tilt_value = None
for property_name, template in (
('_icon', self._icon_template),
('_entity_picture', self._entity_picture_template)):
if template is None:
continue
try:
setattr(self, property_name, template.async_render())
except TemplateError as ex:
friendly_property_name = property_name[1:].replace('_', ' ')
if ex.args and ex.args[0].startswith(
"UndefinedError: 'None' has no attribute"):
# Common during HA startup - so just a warning
_LOGGER.warning('Could not render %s template %s,'
' the state is unknown.',
friendly_property_name, self._name)
return
try:
setattr(self, property_name,
getattr(super(), property_name))
except AttributeError:
_LOGGER.error('Could not render %s template %s: %s',
friendly_property_name, self._name, ex)
| [
"logging.getLogger",
"voluptuous.Inclusive",
"voluptuous.Required",
"voluptuous.Exclusive",
"homeassistant.helpers.event.async_track_state_change",
"voluptuous.Schema",
"homeassistant.helpers.script.Script",
"homeassistant.helpers.entity.async_generate_entity_id",
"voluptuous.Optional"
] | [((1107, 1134), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1124, 1134), False, 'import logging\n'), ((1753, 1799), 'voluptuous.Inclusive', 'vol.Inclusive', (['OPEN_ACTION', 'CONF_OPEN_OR_CLOSE'], {}), '(OPEN_ACTION, CONF_OPEN_OR_CLOSE)\n', (1766, 1799), True, 'import voluptuous as vol\n'), ((1823, 1870), 'voluptuous.Inclusive', 'vol.Inclusive', (['CLOSE_ACTION', 'CONF_OPEN_OR_CLOSE'], {}), '(CLOSE_ACTION, CONF_OPEN_OR_CLOSE)\n', (1836, 1870), True, 'import voluptuous as vol\n'), ((1894, 1919), 'voluptuous.Optional', 'vol.Optional', (['STOP_ACTION'], {}), '(STOP_ACTION)\n', (1906, 1919), True, 'import voluptuous as vol\n'), ((1943, 2013), 'voluptuous.Exclusive', 'vol.Exclusive', (['CONF_POSITION_TEMPLATE', 'CONF_VALUE_OR_POSITION_TEMPLATE'], {}), '(CONF_POSITION_TEMPLATE, CONF_VALUE_OR_POSITION_TEMPLATE)\n', (1956, 2013), True, 'import voluptuous as vol\n'), ((2050, 2117), 'voluptuous.Exclusive', 'vol.Exclusive', (['CONF_VALUE_TEMPLATE', 'CONF_VALUE_OR_POSITION_TEMPLATE'], {}), '(CONF_VALUE_TEMPLATE, CONF_VALUE_OR_POSITION_TEMPLATE)\n', (2063, 2117), True, 'import voluptuous as vol\n'), ((2154, 2190), 'voluptuous.Optional', 'vol.Optional', (['CONF_POSITION_TEMPLATE'], {}), '(CONF_POSITION_TEMPLATE)\n', (2166, 2190), True, 'import voluptuous as vol\n'), ((2209, 2241), 'voluptuous.Optional', 'vol.Optional', (['CONF_TILT_TEMPLATE'], {}), '(CONF_TILT_TEMPLATE)\n', (2221, 2241), True, 'import voluptuous as vol\n'), ((2260, 2292), 'voluptuous.Optional', 'vol.Optional', (['CONF_ICON_TEMPLATE'], {}), '(CONF_ICON_TEMPLATE)\n', (2272, 2292), True, 'import voluptuous as vol\n'), ((2311, 2353), 'voluptuous.Optional', 'vol.Optional', (['CONF_ENTITY_PICTURE_TEMPLATE'], {}), '(CONF_ENTITY_PICTURE_TEMPLATE)\n', (2323, 2353), True, 'import voluptuous as vol\n'), ((2372, 2401), 'voluptuous.Optional', 'vol.Optional', (['CONF_OPTIMISTIC'], {}), '(CONF_OPTIMISTIC)\n', (2384, 2401), True, 'import voluptuous as vol\n'), ((2419, 2453), 'voluptuous.Optional', 'vol.Optional', (['CONF_TILT_OPTIMISTIC'], {}), '(CONF_TILT_OPTIMISTIC)\n', (2431, 2453), True, 'import voluptuous as vol\n'), ((2471, 2500), 'voluptuous.Optional', 'vol.Optional', (['POSITION_ACTION'], {}), '(POSITION_ACTION)\n', (2483, 2500), True, 'import voluptuous as vol\n'), ((2524, 2549), 'voluptuous.Optional', 'vol.Optional', (['TILT_ACTION'], {}), '(TILT_ACTION)\n', (2536, 2549), True, 'import voluptuous as vol\n'), ((2573, 2605), 'voluptuous.Optional', 'vol.Optional', (['CONF_FRIENDLY_NAME'], {}), '(CONF_FRIENDLY_NAME)\n', (2585, 2605), True, 'import voluptuous as vol\n'), ((2622, 2650), 'voluptuous.Optional', 'vol.Optional', (['CONF_ENTITY_ID'], {}), '(CONF_ENTITY_ID)\n', (2634, 2650), True, 'import voluptuous as vol\n'), ((2717, 2742), 'voluptuous.Required', 'vol.Required', (['CONF_COVERS'], {}), '(CONF_COVERS)\n', (2729, 2742), True, 'import voluptuous as vol\n'), ((2744, 2779), 'voluptuous.Schema', 'vol.Schema', (['{cv.slug: COVER_SCHEMA}'], {}), '({cv.slug: COVER_SCHEMA})\n', (2754, 2779), True, 'import voluptuous as vol\n'), ((6255, 6319), 'homeassistant.helpers.entity.async_generate_entity_id', 'async_generate_entity_id', (['ENTITY_ID_FORMAT', 'device_id'], {'hass': 'hass'}), '(ENTITY_ID_FORMAT, device_id, hass=hass)\n', (6279, 6319), False, 'from homeassistant.helpers.entity import async_generate_entity_id\n'), ((6713, 6738), 'homeassistant.helpers.script.Script', 'Script', (['hass', 'open_action'], {}), '(hass, open_action)\n', (6719, 6738), False, 'from homeassistant.helpers.script import Script\n'), ((6843, 6869), 'homeassistant.helpers.script.Script', 'Script', (['hass', 'close_action'], {}), '(hass, close_action)\n', (6849, 6869), False, 'from homeassistant.helpers.script import Script\n'), ((6971, 6996), 'homeassistant.helpers.script.Script', 'Script', (['hass', 'stop_action'], {}), '(hass, stop_action)\n', (6977, 6996), False, 'from homeassistant.helpers.script import Script\n'), ((7110, 7139), 'homeassistant.helpers.script.Script', 'Script', (['hass', 'position_action'], {}), '(hass, position_action)\n', (7116, 7139), False, 'from homeassistant.helpers.script import Script\n'), ((7241, 7266), 'homeassistant.helpers.script.Script', 'Script', (['hass', 'tilt_action'], {}), '(hass, tilt_action)\n', (7247, 7266), False, 'from homeassistant.helpers.script import Script\n'), ((8493, 8579), 'homeassistant.helpers.event.async_track_state_change', 'async_track_state_change', (['self.hass', 'self._entities', 'template_cover_state_listener'], {}), '(self.hass, self._entities,\n template_cover_state_listener)\n', (8517, 8579), False, 'from homeassistant.helpers.event import async_track_state_change\n')] |
# Copyright (C) 2020 THL A29 Limited, a Tencent company.
# All rights reserved.
# Licensed under the BSD 3-Clause License (the "License"); you may
# not use this file except in compliance with the License. You may
# obtain a copy of the License at
# https://opensource.org/licenses/BSD-3-Clause
# 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.
# See the AUTHORS file for names of contributors.
import turbo_transformers
import unittest
import io
import torch
from transformers.modeling_bert import BertConfig, BertOutput
import sys
import os
sys.path.append(os.path.dirname(__file__))
import test_helper
def create_shape_test(batch_size: int, seq_length: int):
class TestBertOut(unittest.TestCase):
def init_data(self, use_cuda) -> None:
test_device = torch.device('cuda:0') if use_cuda else \
torch.device('cpu:0')
if not use_cuda:
torch.set_num_threads(1)
torch.set_grad_enabled(False)
self.cfg = BertConfig()
self.intermediate_size = self.cfg.intermediate_size # 3072;
self.hidden_size = self.cfg.hidden_size # 768
self.torch_bertout = BertOutput(self.cfg)
self.torch_bertout.eval()
if use_cuda:
self.torch_bertout.to(test_device)
self.turbo_bertout = turbo_transformers.BertOutput.from_torch(
self.torch_bertout)
self.intermediate_output = torch.rand(
size=(batch_size, seq_length, self.intermediate_size),
dtype=torch.float32,
device=test_device)
self.attention_output = torch.rand(size=(batch_size, seq_length,
self.hidden_size),
dtype=torch.float32,
device=test_device)
def check_torch_and_turbo(self, use_cuda):
self.init_data(use_cuda)
sio = io.StringIO()
num_iter = 2
device = "GPU" if use_cuda else "CPU"
torch_model = lambda: self.torch_bertout(self.intermediate_output,
self.attention_output)
torch_result, torch_qps, torch_time = \
test_helper.run_model(torch_model, use_cuda, num_iter)
print(f'Bert Output Plain PyTorch({device}) QPS {torch_qps}',
file=sio)
turbo_model = lambda: self.turbo_bertout(self.intermediate_output,
self.attention_output)
turbo_result, turbo_qps, turbo_time = \
test_helper.run_model(turbo_model, use_cuda, num_iter)
print(
f'Bert Output Plain TurboTransformer({device}) QPS {turbo_qps}',
file=sio)
# cuda version precision is lower due to tensor-core
self.assertTrue(
torch.max(torch.abs(torch_result - turbo_result)) < 1e-2
if use_cuda else 1e-4)
sio.seek(0)
with open(f"gpu_bert_output_qps_{batch_size}_{seq_length:03}.txt",
"w") as of:
for line in sio:
print(line.strip(), file=of)
def test_bertout(self):
self.check_torch_and_turbo(use_cuda=False)
if torch.cuda.is_available() and \
turbo_transformers.config.is_compiled_with_cuda():
self.check_torch_and_turbo(use_cuda=True)
TestBertOut.__name__ = f"TestBertOut_BatchSize_{batch_size}_SeqLen_{seq_length}"
globals()[TestBertOut.__name__] = TestBertOut
for seq_length in (20, 40, 60, 80, 100, 120):
for batch_size in (1, 2):
create_shape_test(batch_size=batch_size, seq_length=seq_length)
if __name__ == '__main__':
unittest.main()
| [
"turbo_transformers.BertOutput.from_torch",
"torch.abs",
"transformers.modeling_bert.BertOutput",
"turbo_transformers.config.is_compiled_with_cuda",
"transformers.modeling_bert.BertConfig",
"torch.set_num_threads",
"os.path.dirname",
"torch.cuda.is_available",
"test_helper.run_model",
"unittest.ma... | [((828, 853), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (843, 853), False, 'import os\n'), ((4160, 4175), 'unittest.main', 'unittest.main', ([], {}), '()\n', (4173, 4175), False, 'import unittest\n'), ((1215, 1244), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(False)'], {}), '(False)\n', (1237, 1244), False, 'import torch\n'), ((1268, 1280), 'transformers.modeling_bert.BertConfig', 'BertConfig', ([], {}), '()\n', (1278, 1280), False, 'from transformers.modeling_bert import BertConfig, BertOutput\n'), ((1446, 1466), 'transformers.modeling_bert.BertOutput', 'BertOutput', (['self.cfg'], {}), '(self.cfg)\n', (1456, 1466), False, 'from transformers.modeling_bert import BertConfig, BertOutput\n'), ((1615, 1675), 'turbo_transformers.BertOutput.from_torch', 'turbo_transformers.BertOutput.from_torch', (['self.torch_bertout'], {}), '(self.torch_bertout)\n', (1655, 1675), False, 'import turbo_transformers\n'), ((1733, 1844), 'torch.rand', 'torch.rand', ([], {'size': '(batch_size, seq_length, self.intermediate_size)', 'dtype': 'torch.float32', 'device': 'test_device'}), '(size=(batch_size, seq_length, self.intermediate_size), dtype=\n torch.float32, device=test_device)\n', (1743, 1844), False, 'import torch\n'), ((1925, 2030), 'torch.rand', 'torch.rand', ([], {'size': '(batch_size, seq_length, self.hidden_size)', 'dtype': 'torch.float32', 'device': 'test_device'}), '(size=(batch_size, seq_length, self.hidden_size), dtype=torch.\n float32, device=test_device)\n', (1935, 2030), False, 'import torch\n'), ((2280, 2293), 'io.StringIO', 'io.StringIO', ([], {}), '()\n', (2291, 2293), False, 'import io\n'), ((2593, 2647), 'test_helper.run_model', 'test_helper.run_model', (['torch_model', 'use_cuda', 'num_iter'], {}), '(torch_model, use_cuda, num_iter)\n', (2614, 2647), False, 'import test_helper\n'), ((2974, 3028), 'test_helper.run_model', 'test_helper.run_model', (['turbo_model', 'use_cuda', 'num_iter'], {}), '(turbo_model, use_cuda, num_iter)\n', (2995, 3028), False, 'import test_helper\n'), ((1048, 1070), 'torch.device', 'torch.device', (['"""cuda:0"""'], {}), "('cuda:0')\n", (1060, 1070), False, 'import torch\n'), ((1110, 1131), 'torch.device', 'torch.device', (['"""cpu:0"""'], {}), "('cpu:0')\n", (1122, 1131), False, 'import torch\n'), ((1177, 1201), 'torch.set_num_threads', 'torch.set_num_threads', (['(1)'], {}), '(1)\n', (1198, 1201), False, 'import torch\n'), ((3685, 3710), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (3708, 3710), False, 'import torch\n'), ((3733, 3782), 'turbo_transformers.config.is_compiled_with_cuda', 'turbo_transformers.config.is_compiled_with_cuda', ([], {}), '()\n', (3780, 3782), False, 'import turbo_transformers\n'), ((3276, 3314), 'torch.abs', 'torch.abs', (['(torch_result - turbo_result)'], {}), '(torch_result - turbo_result)\n', (3285, 3314), False, 'import torch\n')] |
import os
import glob
import pickle
import pcl
import torch
import torch.utils.data
import torch.nn as nn
import numpy as np
# global configurations:
from autolab_core import YamlConfig
from dexnet.grasping import GpgGraspSampler
from dexnet.grasping import RobotGripper
home_dir = os.environ['HOME']
yaml_config = YamlConfig(home_dir + "/Projects/PointNetGPD/dex-net/test/config.yaml")
gripper_name = 'robotiq_85'
gripper = RobotGripper.load(gripper_name, home_dir + "/Projects/PointNetGPD/dex-net/data/grippers")
ags = GpgGraspSampler(gripper, yaml_config)
class PointGraspDataset(torch.utils.data.Dataset):
def __init__(self, obj_points_num, grasp_points_num, pc_file_used_num, grasp_amount_per_file, thresh_good,
thresh_bad, path, tag, with_obj=False, projection=False, project_chann=3, project_size=60):
self.obj_points_num = obj_points_num
self.grasp_points_num = grasp_points_num
self.pc_file_used_num = pc_file_used_num
self.grasp_amount_per_file = grasp_amount_per_file
self.path = path
self.tag = tag
self.thresh_good = thresh_good
self.thresh_bad = thresh_bad
self.with_obj = with_obj
self.min_point_limit = 50
# projection related
self.projection = projection
self.project_chann = project_chann
if self.project_chann not in [3, 12]:
raise NotImplementedError
self.project_size = project_size
if self.project_size != 60:
raise NotImplementedError
self.normal_K = 10
self.voxel_point_num = 50
self.projection_margin = 1
self.transform = pickle.load(open(os.path.join(self.path, 'google2cloud.pkl'), 'rb'))
fl_grasp = glob.glob(os.path.join(path, 'ycb_grasp', self.tag, '*.npy'))
fl_pc = glob.glob(os.path.join(path, 'ycb_rgbd', '*', 'clouds', '*.npy'))
self.d_pc, self.d_grasp = {}, {}
for i in fl_pc:
k = i.split('/')[-3]
if k in self.d_pc.keys():
self.d_pc[k].append(i)
else:
self.d_pc[k] = [i]
for i in fl_grasp:
k = i.split('/')[-1].split('.')[0]
self.d_grasp[k] = i
object1 = set(self.d_grasp.keys())
object2 = set(self.transform.keys())
self.object = list(object1.intersection(object2))
self.amount = len(self.object) * self.grasp_amount_per_file
def collect_pc(self, grasp, pc, transform):
center = grasp[0:3]
axis = grasp[3:6] # binormal
width = grasp[6]
angle = grasp[7]
axis = axis/np.linalg.norm(axis)
binormal = axis
# cal approach
cos_t = np.cos(angle)
sin_t = np.sin(angle)
R1 = np.c_[[cos_t, 0, sin_t],[0, 1, 0],[-sin_t, 0, cos_t]]
axis_y = axis
axis_x = np.array([axis_y[1], -axis_y[0], 0])
if np.linalg.norm(axis_x) == 0:
axis_x = np.array([1, 0, 0])
axis_x = axis_x / np.linalg.norm(axis_x)
axis_y = axis_y / np.linalg.norm(axis_y)
axis_z = np.cross(axis_x, axis_y)
R2 = np.c_[axis_x, np.c_[axis_y, axis_z]]
approach = R2.dot(R1)[:, 0]
approach = approach / np.linalg.norm(approach)
minor_normal = np.cross(axis, approach)
left = center - width*axis/2
right = center + width*axis/2
# bottom = center - width*approach
left = (np.dot(transform, np.array([left[0], left[1], left[2], 1])))[:3]
right = (np.dot(transform, np.array([right[0], right[1], right[2], 1])))[:3]
# bottom = (transform @ np.array([bottom[0], bottom[1], bottom[2], 1]))[:3]
center = (np.dot(transform, np.array([center[0], center[1], center[2], 1])))[:3]
binormal = (np.dot(transform, np.array([binormal[0], binormal[1], binormal[2], 1])))[:3].reshape(3, 1)
approach = (np.dot(transform, np.array([approach[0], approach[1], approach[2], 1])))[:3].reshape(3, 1)
minor_normal = (np.dot(transform, np.array([minor_normal[0], minor_normal[1], minor_normal[2], 1])))[:3].reshape(3, 1)
matrix = np.hstack([approach, binormal, minor_normal]).T
# pc_p2c/left_t/right_t is in local coordinate(with center as origin)
# other(include pc) are in pc coordinate
pc_p2c = (np.dot(matrix, (pc-center).T)).T
left_t = (-width * np.array([0,1,0]) / 2).squeeze()
right_t = (width * np.array([0,1,0]) / 2).squeeze()
x_limit = width/4
z_limit = width/4
y_limit = width/2
x1 = pc_p2c[:, 0] > -x_limit
x2 = pc_p2c[:, 0] < x_limit
y1 = pc_p2c[:, 1] > -y_limit
y2 = pc_p2c[:, 1] < y_limit
z1 = pc_p2c[:, 2] > -z_limit
z2 = pc_p2c[:, 2] < z_limit
a = np.vstack([x1, x2, y1, y2, z1, z2])
self.in_ind = np.where(np.sum(a, axis=0) == len(a))[0]
if len(self.in_ind) < self.min_point_limit:
return None
if self.projection:
return self.project_pc(pc_p2c, width)
else:
return pc_p2c[self.in_ind]
def check_square(self, point, points_g):
dirs = np.array([[-1, 1, 1], [1, 1, 1], [-1, -1, 1], [1, -1, 1],
[-1, 1, -1], [1, 1, -1], [-1, -1, -1], [1, -1, -1]])
p = dirs * 0.5 + point # here res * 0.5 means get half of a pixel width
a1 = p[2][1] < points_g[:, 1]
a2 = p[0][1] > points_g[:, 1]
a3 = p[0][2] > points_g[:, 2]
a4 = p[4][2] < points_g[:, 2]
a5 = p[1][0] > points_g[:, 0]
a6 = p[0][0] < points_g[:, 0]
a = np.vstack([a1, a2, a3, a4, a5, a6])
points_in_area = np.where(np.sum(a, axis=0) == len(a))[0]
if len(points_in_area) == 0:
has_p = False
else:
has_p = True
return points_in_area
def cal_projection(self, point_cloud_voxel, m_width_of_pic, margin, surface_normal, order, gripper_width):
occupy_pic = np.zeros([m_width_of_pic, m_width_of_pic, 1])
norm_pic = np.zeros([m_width_of_pic, m_width_of_pic, 3])
norm_pic_num = np.zeros([m_width_of_pic, m_width_of_pic, 1])
max_x = point_cloud_voxel[:, order[0]].max()
min_x = point_cloud_voxel[:, order[0]].min()
max_y = point_cloud_voxel[:, order[1]].max()
min_y = point_cloud_voxel[:, order[1]].min()
min_z = point_cloud_voxel[:, order[2]].min()
tmp = max((max_x - min_x), (max_y - min_y))
if tmp == 0:
print("WARNING : the num of input points seems only have one, no possilbe to do learning on"
"such data, please throw it away. -- Hongzhuo")
return occupy_pic, norm_pic
# Here, we use the gripper width to cal the res:
res = gripper_width / (m_width_of_pic-margin)
voxel_points_square_norm = []
x_coord_r = ((point_cloud_voxel[:, order[0]]) / res + m_width_of_pic / 2)
y_coord_r = ((point_cloud_voxel[:, order[1]]) / res + m_width_of_pic / 2)
z_coord_r = ((point_cloud_voxel[:, order[2]]) / res + m_width_of_pic / 2)
x_coord_r = np.floor(x_coord_r).astype(int)
y_coord_r = np.floor(y_coord_r).astype(int)
z_coord_r = np.floor(z_coord_r).astype(int)
voxel_index = np.array([x_coord_r, y_coord_r, z_coord_r]).T # all point in grid
coordinate_buffer = np.unique(voxel_index, axis=0) # get a list of points without duplication
K = len(coordinate_buffer)
# [K, 1] store number of points in each voxel grid
number_buffer = np.zeros(shape=K, dtype=np.int64)
feature_buffer = np.zeros(shape=(K, self.voxel_point_num, 6), dtype=np.float32)
index_buffer = {}
for i in range(K):
index_buffer[tuple(coordinate_buffer[i])] = i # got index of coordinate
for voxel, point, normal in zip(voxel_index, point_cloud_voxel, surface_normal):
index = index_buffer[tuple(voxel)]
number = number_buffer[index]
if number < self.voxel_point_num:
feature_buffer[index, number, :3] = point
feature_buffer[index, number, 3:6] = normal
number_buffer[index] += 1
voxel_points_square_norm = np.sum(feature_buffer[..., -3:], axis=1)/number_buffer[:, np.newaxis]
voxel_points_square = coordinate_buffer
if len(voxel_points_square) == 0:
return occupy_pic, norm_pic
x_coord_square = voxel_points_square[:, 0]
y_coord_square = voxel_points_square[:, 1]
norm_pic[x_coord_square, y_coord_square, :] = voxel_points_square_norm
occupy_pic[x_coord_square, y_coord_square] = number_buffer[:, np.newaxis]
occupy_max = occupy_pic.max()
assert(occupy_max > 0)
occupy_pic = occupy_pic / occupy_max
return occupy_pic, norm_pic
def project_pc(self, pc, gripper_width):
"""
for gpd baseline, only support input_chann == [3, 12]
"""
pc = pc.astype(np.float32)
pc = pcl.PointCloud(pc)
norm = pc.make_NormalEstimation()
norm.set_KSearch(self.normal_K)
normals = norm.compute()
surface_normal = normals.to_array()
surface_normal = surface_normal[:, 0:3]
pc = pc.to_array()
grasp_pc = pc[self.in_ind]
grasp_pc_norm = surface_normal[self.in_ind]
bad_check = (grasp_pc_norm != grasp_pc_norm)
if np.sum(bad_check)!=0:
bad_ind = np.where(bad_check == True)
grasp_pc = np.delete(grasp_pc, bad_ind[0], axis=0)
grasp_pc_norm = np.delete(grasp_pc_norm, bad_ind[0], axis=0)
assert(np.sum(grasp_pc_norm != grasp_pc_norm) == 0)
m_width_of_pic = self.project_size
margin = self.projection_margin
order = np.array([0, 1, 2])
occupy_pic1, norm_pic1 = self.cal_projection(grasp_pc, m_width_of_pic, margin, grasp_pc_norm,
order, gripper_width)
if self.project_chann == 3:
output = norm_pic1
elif self.project_chann == 12:
order = np.array([1, 2, 0])
occupy_pic2, norm_pic2 = self.cal_projection(grasp_pc, m_width_of_pic, margin, grasp_pc_norm,
order, gripper_width)
order = np.array([0, 2, 1])
occupy_pic3, norm_pic3 = self.cal_projection(grasp_pc, m_width_of_pic, margin, grasp_pc_norm,
order, gripper_width)
output = np.dstack([occupy_pic1, norm_pic1, occupy_pic2, norm_pic2, occupy_pic3, norm_pic3])
else:
raise NotImplementedError
return output
def __getitem__(self, index):
# try:
obj_ind, grasp_ind = np.unravel_index(index, (len(self.object), self.grasp_amount_per_file))
obj_grasp = self.object[obj_ind]
obj_pc = self.transform[obj_grasp][0]
f_grasp = self.d_grasp[obj_grasp]
fl_pc = np.array(self.d_pc[obj_pc])
fl_pc = fl_pc[np.random.choice(len(fl_pc), size=self.pc_file_used_num)]
grasp = np.load(f_grasp)[grasp_ind]
pc = np.vstack([np.load(i) for i in fl_pc])
pc = pc[np.random.choice(len(pc), size=self.obj_points_num)]
t = self.transform[obj_grasp][1]
grasp_pc = self.collect_pc(grasp, pc, t)
if grasp_pc is None:
return None
level_score, refine_score = grasp[-2:]
if not self.projection:
if len(grasp_pc) > self.grasp_points_num:
grasp_pc = grasp_pc[np.random.choice(len(grasp_pc), size=self.grasp_points_num,
replace=False)].T
else:
grasp_pc = grasp_pc[np.random.choice(len(grasp_pc), size=self.grasp_points_num,
replace=True)].T
else:
grasp_pc = grasp_pc.transpose((2, 1, 0))
score = level_score + refine_score*0.01
if score >= self.thresh_bad:
label = 0
elif score <= self.thresh_good:
label = 1
else:
return None
if self.with_obj:
return grasp_pc, label, obj_grasp
else:
return grasp_pc, label
def __len__(self):
return self.amount
class PointGraspMultiClassDataset(torch.utils.data.Dataset):
def __init__(self, obj_points_num, grasp_points_num, pc_file_used_num, grasp_amount_per_file, thresh_good,
thresh_bad, path, tag, with_obj=False, projection=False, project_chann=3, project_size=60):
self.obj_points_num = obj_points_num
self.grasp_points_num = grasp_points_num
self.pc_file_used_num = pc_file_used_num
self.grasp_amount_per_file = grasp_amount_per_file
self.path = path
self.tag = tag
self.thresh_good = thresh_good
self.thresh_bad = thresh_bad
self.with_obj = with_obj
self.min_point_limit = 50
# projection related
self.projection = projection
self.project_chann = project_chann
if self.project_chann not in [3, 12]:
raise NotImplementedError
self.project_size = project_size
if self.project_size != 60:
raise NotImplementedError
self.normal_K = 10
self.voxel_point_num = 50
self.projection_margin = 1
self.transform = pickle.load(open(os.path.join(self.path, 'google2cloud.pkl'), 'rb'))
fl_grasp = glob.glob(os.path.join(path, 'ycb_grasp', self.tag, '*.npy'))
fl_pc = glob.glob(os.path.join(path, 'ycb_rgbd', '*', 'clouds', '*.npy'))
self.d_pc, self.d_grasp = {}, {}
for i in fl_pc:
k = i.split('/')[-3]
if k in self.d_pc.keys():
self.d_pc[k].append(i)
else:
self.d_pc[k] = [i]
for i in fl_grasp:
k = i.split('/')[-1].split('.')[0]
self.d_grasp[k] = i
object1 = set(self.d_grasp.keys())
object2 = set(self.transform.keys())
self.object = list(object1.intersection(object2))
self.amount = len(self.object) * self.grasp_amount_per_file
def collect_pc(self, grasp, pc, transform):
center = grasp[0:3]
axis = grasp[3:6] # binormal
width = grasp[6]
angle = grasp[7]
axis = axis/np.linalg.norm(axis)
binormal = axis
# cal approach
cos_t = np.cos(angle)
sin_t = np.sin(angle)
R1 = np.c_[[cos_t, 0, sin_t],[0, 1, 0],[-sin_t, 0, cos_t]]
axis_y = axis
axis_x = np.array([axis_y[1], -axis_y[0], 0])
if np.linalg.norm(axis_x) == 0:
axis_x = np.array([1, 0, 0])
axis_x = axis_x / np.linalg.norm(axis_x)
axis_y = axis_y / np.linalg.norm(axis_y)
axis_z = np.cross(axis_x, axis_y)
R2 = np.c_[axis_x, np.c_[axis_y, axis_z]]
approach = R2.dot(R1)[:, 0]
approach = approach / np.linalg.norm(approach)
minor_normal = np.cross(axis, approach)
left = center - width*axis/2
right = center + width*axis/2
# bottom = center - width*approach
left = (np.dot(transform, np.array([left[0], left[1], left[2], 1])))[:3]
right = (np.dot(transform, np.array([right[0], right[1], right[2], 1])))[:3]
# bottom = (transform @ np.array([bottom[0], bottom[1], bottom[2], 1]))[:3]
center = (np.dot(transform, np.array([center[0], center[1], center[2], 1])))[:3]
binormal = (np.dot(transform, np.array([binormal[0], binormal[1], binormal[2], 1])))[:3].reshape(3, 1)
approach = (np.dot(transform, np.array([approach[0], approach[1], approach[2], 1])))[:3].reshape(3, 1)
minor_normal = (np.dot(transform, np.array([minor_normal[0], minor_normal[1], minor_normal[2], 1])))[:3].reshape(3, 1)
matrix = np.hstack([approach, binormal, minor_normal]).T
# pc_p2c/left_t/right_t is in local coordinate(with center as origin)
# other(include pc) are in pc coordinate
pc_p2c = (np.dot(matrix, (pc-center).T)).T
left_t = (-width * np.array([0,1,0]) / 2).squeeze()
right_t = (width * np.array([0,1,0]) / 2).squeeze()
x_limit = width/4
z_limit = width/4
y_limit = width/2
x1 = pc_p2c[:, 0] > -x_limit
x2 = pc_p2c[:, 0] < x_limit
y1 = pc_p2c[:, 1] > -y_limit
y2 = pc_p2c[:, 1] < y_limit
z1 = pc_p2c[:, 2] > -z_limit
z2 = pc_p2c[:, 2] < z_limit
a = np.vstack([x1, x2, y1, y2, z1, z2])
self.in_ind = np.where(np.sum(a, axis=0) == len(a))[0]
if len(self.in_ind) < self.min_point_limit:
return None
if self.projection:
return self.project_pc(pc_p2c, width)
else:
return pc_p2c[self.in_ind]
def check_square(self, point, points_g):
dirs = np.array([[-1, 1, 1], [1, 1, 1], [-1, -1, 1], [1, -1, 1],
[-1, 1, -1], [1, 1, -1], [-1, -1, -1], [1, -1, -1]])
p = dirs * 0.5 + point # here res * 0.5 means get half of a pixel width
a1 = p[2][1] < points_g[:, 1]
a2 = p[0][1] > points_g[:, 1]
a3 = p[0][2] > points_g[:, 2]
a4 = p[4][2] < points_g[:, 2]
a5 = p[1][0] > points_g[:, 0]
a6 = p[0][0] < points_g[:, 0]
a = np.vstack([a1, a2, a3, a4, a5, a6])
points_in_area = np.where(np.sum(a, axis=0) == len(a))[0]
if len(points_in_area) == 0:
has_p = False
else:
has_p = True
return points_in_area
def cal_projection(self, point_cloud_voxel, m_width_of_pic, margin, surface_normal, order, gripper_width):
occupy_pic = np.zeros([m_width_of_pic, m_width_of_pic, 1])
norm_pic = np.zeros([m_width_of_pic, m_width_of_pic, 3])
norm_pic_num = np.zeros([m_width_of_pic, m_width_of_pic, 1])
max_x = point_cloud_voxel[:, order[0]].max()
min_x = point_cloud_voxel[:, order[0]].min()
max_y = point_cloud_voxel[:, order[1]].max()
min_y = point_cloud_voxel[:, order[1]].min()
min_z = point_cloud_voxel[:, order[2]].min()
tmp = max((max_x - min_x), (max_y - min_y))
if tmp == 0:
print("WARNING : the num of input points seems only have one, no possilbe to do learning on"
"such data, please throw it away. -- Hongzhuo")
return occupy_pic, norm_pic
# Here, we use the gripper width to cal the res:
res = gripper_width / (m_width_of_pic-margin)
voxel_points_square_norm = []
x_coord_r = ((point_cloud_voxel[:, order[0]]) / res + m_width_of_pic / 2)
y_coord_r = ((point_cloud_voxel[:, order[1]]) / res + m_width_of_pic / 2)
z_coord_r = ((point_cloud_voxel[:, order[2]]) / res + m_width_of_pic / 2)
x_coord_r = np.floor(x_coord_r).astype(int)
y_coord_r = np.floor(y_coord_r).astype(int)
z_coord_r = np.floor(z_coord_r).astype(int)
voxel_index = np.array([x_coord_r, y_coord_r, z_coord_r]).T # all point in grid
coordinate_buffer = np.unique(voxel_index, axis=0) # get a list of points without duplication
K = len(coordinate_buffer)
# [K, 1] store number of points in each voxel grid
number_buffer = np.zeros(shape=K, dtype=np.int64)
feature_buffer = np.zeros(shape=(K, self.voxel_point_num, 6), dtype=np.float32)
index_buffer = {}
for i in range(K):
index_buffer[tuple(coordinate_buffer[i])] = i # got index of coordinate
for voxel, point, normal in zip(voxel_index, point_cloud_voxel, surface_normal):
index = index_buffer[tuple(voxel)]
number = number_buffer[index]
if number < self.voxel_point_num:
feature_buffer[index, number, :3] = point
feature_buffer[index, number, 3:6] = normal
number_buffer[index] += 1
voxel_points_square_norm = np.sum(feature_buffer[..., -3:], axis=1)/number_buffer[:, np.newaxis]
voxel_points_square = coordinate_buffer
if len(voxel_points_square) == 0:
return occupy_pic, norm_pic
x_coord_square = voxel_points_square[:, 0]
y_coord_square = voxel_points_square[:, 1]
norm_pic[x_coord_square, y_coord_square, :] = voxel_points_square_norm
occupy_pic[x_coord_square, y_coord_square] = number_buffer[:, np.newaxis]
occupy_max = occupy_pic.max()
assert(occupy_max > 0)
occupy_pic = occupy_pic / occupy_max
return occupy_pic, norm_pic
def project_pc(self, pc, gripper_width):
"""
for gpd baseline, only support input_chann == [3, 12]
"""
pc = pc.astype(np.float32)
pc = pcl.PointCloud(pc)
norm = pc.make_NormalEstimation()
norm.set_KSearch(self.normal_K)
normals = norm.compute()
surface_normal = normals.to_array()
surface_normal = surface_normal[:, 0:3]
pc = pc.to_array()
grasp_pc = pc[self.in_ind]
grasp_pc_norm = surface_normal[self.in_ind]
bad_check = (grasp_pc_norm != grasp_pc_norm)
if np.sum(bad_check)!=0:
bad_ind = np.where(bad_check == True)
grasp_pc = np.delete(grasp_pc, bad_ind[0], axis=0)
grasp_pc_norm = np.delete(grasp_pc_norm, bad_ind[0], axis=0)
assert(np.sum(grasp_pc_norm != grasp_pc_norm) == 0)
m_width_of_pic = self.project_size
margin = self.projection_margin
order = np.array([0, 1, 2])
occupy_pic1, norm_pic1 = self.cal_projection(grasp_pc, m_width_of_pic, margin, grasp_pc_norm,
order, gripper_width)
if self.project_chann == 3:
output = norm_pic1
elif self.project_chann == 12:
order = np.array([1, 2, 0])
occupy_pic2, norm_pic2 = self.cal_projection(grasp_pc, m_width_of_pic, margin, grasp_pc_norm,
order, gripper_width)
order = np.array([0, 2, 1])
occupy_pic3, norm_pic3 = self.cal_projection(grasp_pc, m_width_of_pic, margin, grasp_pc_norm,
order, gripper_width)
output = np.dstack([occupy_pic1, norm_pic1, occupy_pic2, norm_pic2, occupy_pic3, norm_pic3])
else:
raise NotImplementedError
return output
def __getitem__(self, index):
# try:
obj_ind, grasp_ind = np.unravel_index(index, (len(self.object), self.grasp_amount_per_file))
obj_grasp = self.object[obj_ind]
obj_pc = self.transform[obj_grasp][0]
f_grasp = self.d_grasp[obj_grasp]
fl_pc = np.array(self.d_pc[obj_pc])
fl_pc = fl_pc[np.random.choice(len(fl_pc), size=self.pc_file_used_num)]
grasp = np.load(f_grasp)[grasp_ind]
pc = np.vstack([np.load(i) for i in fl_pc])
pc = pc[np.random.choice(len(pc), size=self.obj_points_num)]
t = self.transform[obj_grasp][1]
grasp_pc = self.collect_pc(grasp, pc, t)
if grasp_pc is None:
return None
level_score, refine_score = grasp[-2:]
if not self.projection:
if len(grasp_pc) > self.grasp_points_num:
grasp_pc = grasp_pc[np.random.choice(len(grasp_pc), size=self.grasp_points_num,
replace=False)].T
else:
grasp_pc = grasp_pc[np.random.choice(len(grasp_pc), size=self.grasp_points_num,
replace=True)].T
else:
grasp_pc = grasp_pc.transpose((2, 1, 0))
score = level_score + refine_score*0.01
if score >= self.thresh_bad:
label = 0
elif score <= self.thresh_good:
label = 2
else:
label = 1
if self.with_obj:
return grasp_pc, label, obj_grasp
else:
return grasp_pc, label
def __len__(self):
return self.amount
class PointGraspOneViewDataset(torch.utils.data.Dataset):
def __init__(self, grasp_points_num, grasp_amount_per_file, thresh_good,
thresh_bad, path, tag, with_obj=False, projection=False, project_chann=3, project_size=60):
self.grasp_points_num = grasp_points_num
self.grasp_amount_per_file = grasp_amount_per_file
self.path = path
self.tag = tag
self.thresh_good = thresh_good
self.thresh_bad = thresh_bad
self.with_obj = with_obj
self.min_point_limit = 150 # 最低点数限制
# projection related 投影相关参数
self.projection = projection
self.project_chann = project_chann
if self.project_chann not in [3, 12]:
raise NotImplementedError
self.project_size = project_size
if self.project_size != 60:
raise NotImplementedError
self.normal_K = 10
self.voxel_point_num = 50
self.projection_margin = 1
self.minimum_point_amount = 150
# google扫描仪到点云的转换矩阵
self.transform = pickle.load(open(os.path.join(self.path, 'google2cloud.pkl'), 'rb'))
fl_grasp = glob.glob(os.path.join(path, 'ycb_grasp', self.tag, '*.npy')) # grasp pose file
# 仅获取相机NP3采集的点云
fl_pc = glob.glob(os.path.join(path, 'ycb_rgbd', '*', 'clouds', 'pc_NP3_NP5*.npy')) # point cloud file
self.d_pc, self.d_grasp = {}, {}
for i in fl_pc: # 获取点云文件列表
k = i.split('/')[-3]
if k in self.d_pc.keys():
self.d_pc[k].append(i)
else:
self.d_pc[k] = [i]
for k in self.d_pc.keys():
self.d_pc[k].sort()
for i in fl_grasp: # 获取已生成的抓取姿态列表
grasp_fl_name = i.split('/')[-1].split('.')[0] # grasp文件名
cnt = grasp_fl_name.split('_')[-1] # grasp文件尾
head = grasp_fl_name.split('_')[0] # grasp文件头
k = grasp_fl_name[len(head)+1:-(len(cnt)+1)] # 标准物品名称
self.d_grasp[k] = i
object1 = set(self.d_grasp.keys()) # objects to deal with
# print("object1", object1)
object2 = set(self.transform.keys()) # all ycb objects name
# print("object2", object2)
self.object = list(object1)
# self.object = list(object1.intersection(object2)) # 取交集
print("objects to deal with", self.object)
self.amount = len(self.object) * self.grasp_amount_per_file
def collect_pc(self, grasp, pc, transform):
"""
获取手抓闭合区域中的点云
:param grasp: 扫描仪获取的mesh坐标系下抓取姿态 (grasp_center, grasp_axis, grasp_angle, grasp_width, jaw_width)
:param pc: 点云
:param transform: 扫描仪mesh到点云的转换矩阵
:param vis: 可视化选项
:return: 手抓闭合区域中的点云, 或其投影
"""
# 轴角表示
center = grasp[0:3] # 抓取姿态中心点
axis = grasp[3:6] # binormal 副法线
width = grasp[6] # 抓取姿态宽度
angle = grasp[7] # 旋转角
axis = axis/np.linalg.norm(axis) # (3,)
binormal = axis
# cal approach
cos_t = np.cos(angle)
sin_t = np.sin(angle)
R1 = np.c_[[cos_t, 0, sin_t], [0, 1, 0], [-sin_t, 0, cos_t]] # 旋转矩阵
axis_y = axis
axis_x = np.array([axis_y[1], -axis_y[0], 0])
if np.linalg.norm(axis_x) == 0:
axis_x = np.array([1, 0, 0])
# 各轴单位方向向量
axis_x = axis_x / np.linalg.norm(axis_x)
axis_y = axis_y / np.linalg.norm(axis_y)
axis_z = np.cross(axis_x, axis_y)
R2 = np.c_[axis_x, np.c_[axis_y, axis_z]] # 旋转矩阵
approach = R2.dot(R1)[:, 0]
approach = approach / np.linalg.norm(approach) # 手抓朝向
minor_normal = -np.cross(axis, approach) # 次曲率方向 NOTE: 添加了负号调整为右手坐标系
# 碰撞检测
# grasp_bottom_center = -ags.gripper.hand_depth * approach + center
# hand_points = ags.get_hand_points(grasp_bottom_center, approach, binormal)
# local_hand_points = ags.get_hand_points(np.array([0, 0, 0]), np.array([1, 0, 0]), np.array([0, 1, 0]))
# if_collide = ags.check_collide(grasp_bottom_center, approach,
# binormal, minor_normal, graspable, local_hand_points)
vis = False
if vis: # NOTE:此处获得的抓取姿态可能与点云存在碰撞(影响不是很大)!!! TODO:碰撞检查
mlab.figure(bgcolor=(1, 1, 1), size=(1000, 800))
mlab.pipeline.surface(mlab.pipeline.open("/home/sdhm/Projects/PointNetGPD/PointNetGPD/data/"
"ycb_meshes_google/003_cracker_box/google_512k/nontextured.ply"))
# ---扫描仪坐标系下---:
# 世界坐标系
show_line([0, 0, 0], [0.1, 0, 0], color='r', scale_factor=.0015)
show_line([0, 0, 0], [0, 0.1, 0], color='g', scale_factor=.0015)
show_line([0, 0, 0], [0, 0, 0.1], color='b', scale_factor=.0015)
show_points(pc, color='b', scale_factor=.002) # 原始点云
show_points(center, color='r', scale_factor=.008)
# 显示手抓坐标系
show_line(center, (center + binormal * 0.05).reshape(3), color='g', scale_factor=.0015)
show_line(center, (center + approach * 0.05).reshape(3), color='r', scale_factor=.0015)
show_line(center, (center + minor_normal * 0.05).reshape(3), color='b', scale_factor=.0015)
grasp_bottom_center = -ags.gripper.hand_depth * approach + center
hand_points = ags.get_hand_points(grasp_bottom_center, approach, binormal)
ags.show_grasp_3d(hand_points, color=(0.4, 0.6, 0.0))
mlab.title("google", size=0.3, color=(0, 0, 0))
mlab.show()
left = center - width*axis/2 # 手抓最左侧点
right = center + width*axis/2 # 手抓最右侧点
# bottom = center - width*approach
left = (np.dot(transform, np.array([left[0], left[1], left[2], 1])))[:3]
right = (np.dot(transform, np.array([right[0], right[1], right[2], 1])))[:3]
# bottom = (transform @ np.array([bottom[0], bottom[1], bottom[2], 1]))[:3]
# NOTE: m:mesh c:center p:point cloud
matrix_m2c = np.array([approach, binormal, minor_normal]) # 旋转矩阵: 扫描仪坐标系->中心点坐标系
matrix_p2m = transform[:3, :3] # 旋转矩阵: 点云坐标系->扫描仪坐标系
trans_p2m = transform[:, 3:][:3].reshape(3,) # 平移矩阵: 点云坐标系->扫描仪坐标系
trans_p2m = np.array([trans_p2m[0], trans_p2m[1], trans_p2m[2] + 0.02]) # 微调
pc_p2m = np.dot(matrix_p2m.T, (pc - trans_p2m).T).T # 配准到扫描仪坐标系下的点云
pc_m2c = (np.dot(matrix_m2c, (pc_p2m-center).T)).T # 扫描仪坐标系下点云转换到中心点坐标系下
# pc_c2m = (np.dot(matrix_m2c.T, pc_m2c.T)).T + center # 中心点坐标系下点云转换到扫描仪坐标系下
left_t = (-width * np.array([0, 1, 0]) / 2).squeeze()
right_t = (width * np.array([0, 1, 0]) / 2).squeeze()
# 获取手抓闭合区域中的点
x_limit = ags.gripper.hand_depth
z_limit = ags.gripper.hand_height
y_limit = width
x1 = pc_m2c[:, 0] > -x_limit
x2 = pc_m2c[:, 0] < 0
y1 = pc_m2c[:, 1] > -y_limit/2
y2 = pc_m2c[:, 1] < y_limit/2
z1 = pc_m2c[:, 2] > -z_limit/2
z2 = pc_m2c[:, 2] < z_limit/2
a = np.vstack([x1, x2, y1, y2, z1, z2])
self.in_ind = np.where(np.sum(a, axis=0) == len(a))[0] # 手抓闭合区域中点的索引
if len(self.in_ind) < self.min_point_limit: # 手抓闭合区域内点数太少
# print("\033[0;32m%s\033[0m" % "[INFO] points num", len(self.in_ind))
return None
vis = False
if vis: # 显示手抓闭合区域内点云
mlab.figure(bgcolor=(1, 1, 1), size=(1000, 800))
mlab.pipeline.surface(mlab.pipeline.open("/home/sdhm/Projects/PointNetGPD/PointNetGPD/data/"
"ycb_meshes_google/003_cracker_box/google_512k/nontextured.ply"))
# 世界坐标系
show_line([0, 0, 0], [0.1, 0, 0], color='r', scale_factor=.0015)
show_line([0, 0, 0], [0, 0.1, 0], color='g', scale_factor=.0015)
show_line([0, 0, 0], [0, 0, 0.1], color='b', scale_factor=.0015)
# show_points(pc, color='b', scale_factor=.002) # 原始点云
show_points(pc_p2m, color='g', scale_factor=.002) # 配准到扫描仪坐标系下点云
show_points(pc_m2c, color='b', scale_factor=.002) # 手抓中心坐标系下点云
# show_points(pc_c2m, color='r', scale_factor=.002) # 手抓中心坐标系转换到扫描仪坐标系下点云
# 显示扫描仪坐标系下手抓
grasp_bottom_center = -ags.gripper.hand_depth * approach + center
hand_points = ags.get_hand_points(grasp_bottom_center, approach, binormal)
ags.show_grasp_3d(hand_points, color=(0.0, 1.0, 0.0))
# 中心点坐标系下手抓(应在世界坐标系原点)
hand_points = (np.dot(matrix_m2c, (hand_points - center).T)).T # 手抓关键点转换到中心点坐标系
ags.show_grasp_3d(hand_points, color=(0.5, 0.5, 0.5)) # 显示手抓
# 扫描仪坐标系下抓取坐标系
show_points(center, color='r', scale_factor=.008) # 扫描仪坐标系下中心点
show_line(center, (center + binormal * 0.05).reshape(3), color='g', scale_factor=.0015)
show_line(center, (center + approach * 0.05).reshape(3), color='r', scale_factor=.0015)
show_line(center, (center + minor_normal * 0.05).reshape(3), color='b', scale_factor=.0015)
show_points(pc_m2c, color='c', scale_factor=.002) # 手抓中心坐标系下点云
show_points(pc_m2c[self.in_ind], color='b', scale_factor=.002) # 中心点坐标系下手抓闭合区域中的点云
pc_c2m_region = (np.dot(matrix_m2c.T, pc_m2c[self.in_ind].T)).T + center # 扫描仪坐标系下手抓闭合区域中的点云
show_points(pc_c2m_region, color='r', scale_factor=.002)
# 显示手抓闭合区域
# x = (np.array([[-1, 1, 1, -1, -1], [-1, 1, 1, -1, -1]]) - 1) * x_limit/2
# y = np.array([[-1, -1, -1, -1, -1], [1, 1, 1, 1, 1]]) * y_limit
# z = np.array([[1, 1, -1, -1, 1], [1, 1, -1, -1, 1]]) * z_limit
# mlab.mesh(x, y, z, color=(1, 0, 0), opacity=0.4)
# 体积为1的正方体的八个顶点
x_arr = np.array([-1, 1, 1, -1, -1, 1, 1, -1])/2
y_arr = np.array([-1, -1, 1, 1, -1, -1, 1, 1])/2
z_arr = np.array([-1, -1, -1, -1, 1, 1, 1, 1])/2
x = (x_arr - 0.5) * ags.gripper.hand_depth # 平移半个单位
y = y_arr * (ags.gripper.hand_outer_diameter-2*ags.gripper.finger_width)
z = z_arr * ags.gripper.hand_height
triangles = [(0, 1, 2), (0, 2, 3), (4, 5, 6), (4, 6, 7), (1, 5, 6), (1, 2, 6),
(0, 4, 7), (0, 3, 7), (2, 3, 6), (3, 6, 7), (0, 1, 5), (0, 4, 5)]
mlab.triangular_mesh(x, y, z, triangles, color=(1, 0, 1), opacity=0.2)
mlab.title("cloud", size=0.3, color=(0, 0, 0))
mlab.show()
if self.projection:
return self.project_pc(pc_m2c, width) # 返回投影后的点云
else:
return pc_m2c[self.in_ind] # 返回手抓闭合区域中的点云
def check_square(self, point, points_g):
dirs = np.array([[-1, 1, 1], [1, 1, 1], [-1, -1, 1], [1, -1, 1],
[-1, 1, -1], [1, 1, -1], [-1, -1, -1], [1, -1, -1]])
p = dirs * 0.5 + point # here res * 0.5 means get half of a pixel width
a1 = p[2][1] < points_g[:, 1]
a2 = p[0][1] > points_g[:, 1]
a3 = p[0][2] > points_g[:, 2]
a4 = p[4][2] < points_g[:, 2]
a5 = p[1][0] > points_g[:, 0]
a6 = p[0][0] < points_g[:, 0]
a = np.vstack([a1, a2, a3, a4, a5, a6])
points_in_area = np.where(np.sum(a, axis=0) == len(a))[0]
if len(points_in_area) == 0:
has_p = False
else:
has_p = True
return points_in_area
def cal_projection(self, point_cloud_voxel, m_width_of_pic, margin, surface_normal, order, gripper_width):
"""
计算点云投影
:param point_cloud_voxel:
:param m_width_of_pic:
:param margin:
:param surface_normal:
:param order:
:param gripper_width:
:return:
"""
occupy_pic = np.zeros([m_width_of_pic, m_width_of_pic, 1])
norm_pic = np.zeros([m_width_of_pic, m_width_of_pic, 3])
norm_pic_num = np.zeros([m_width_of_pic, m_width_of_pic, 1])
max_x = point_cloud_voxel[:, order[0]].max()
min_x = point_cloud_voxel[:, order[0]].min()
max_y = point_cloud_voxel[:, order[1]].max()
min_y = point_cloud_voxel[:, order[1]].min()
min_z = point_cloud_voxel[:, order[2]].min()
tmp = max((max_x - min_x), (max_y - min_y))
if tmp == 0:
print("WARNING : the num of input points seems only have one, no possilbe to do learning on"
"such data, please throw it away. -- Hongzhuo")
return occupy_pic, norm_pic
# Here, we use the gripper width to cal the res:
res = gripper_width / (m_width_of_pic-margin)
voxel_points_square_norm = []
x_coord_r = ((point_cloud_voxel[:, order[0]]) / res + m_width_of_pic / 2)
y_coord_r = ((point_cloud_voxel[:, order[1]]) / res + m_width_of_pic / 2)
z_coord_r = ((point_cloud_voxel[:, order[2]]) / res + m_width_of_pic / 2)
x_coord_r = np.floor(x_coord_r).astype(int)
y_coord_r = np.floor(y_coord_r).astype(int)
z_coord_r = np.floor(z_coord_r).astype(int)
voxel_index = np.array([x_coord_r, y_coord_r, z_coord_r]).T # all point in grid
coordinate_buffer = np.unique(voxel_index, axis=0) # get a list of points without duplication
K = len(coordinate_buffer)
# [K, 1] store number of points in each voxel grid
number_buffer = np.zeros(shape=K, dtype=np.int64)
feature_buffer = np.zeros(shape=(K, self.voxel_point_num, 6), dtype=np.float32)
index_buffer = {}
for i in range(K):
index_buffer[tuple(coordinate_buffer[i])] = i # got index of coordinate
for voxel, point, normal in zip(voxel_index, point_cloud_voxel, surface_normal):
index = index_buffer[tuple(voxel)]
number = number_buffer[index]
if number < self.voxel_point_num:
feature_buffer[index, number, :3] = point
feature_buffer[index, number, 3:6] = normal
number_buffer[index] += 1
voxel_points_square_norm = np.sum(feature_buffer[..., -3:], axis=1)/number_buffer[:, np.newaxis]
voxel_points_square = coordinate_buffer
if len(voxel_points_square) == 0:
return occupy_pic, norm_pic
x_coord_square = voxel_points_square[:, 0]
y_coord_square = voxel_points_square[:, 1]
norm_pic[x_coord_square, y_coord_square, :] = voxel_points_square_norm
occupy_pic[x_coord_square, y_coord_square] = number_buffer[:, np.newaxis]
occupy_max = occupy_pic.max()
assert(occupy_max > 0)
occupy_pic = occupy_pic / occupy_max
return occupy_pic, norm_pic
def project_pc(self, pc, gripper_width):
"""
获取手抓闭合区域中点云的投影
for gpd baseline, only support input_chann == [3, 12]
"""
pc = pc.astype(np.float32)
pc = pcl.PointCloud(pc)
norm = pc.make_NormalEstimation()
norm.set_KSearch(self.normal_K)
normals = norm.compute()
surface_normal = normals.to_array()
surface_normal = surface_normal[:, 0:3]
pc = pc.to_array()
grasp_pc = pc[self.in_ind]
grasp_pc_norm = surface_normal[self.in_ind]
bad_check = (grasp_pc_norm != grasp_pc_norm)
if np.sum(bad_check) != 0:
bad_ind = np.where(bad_check == True)
grasp_pc = np.delete(grasp_pc, bad_ind[0], axis=0)
grasp_pc_norm = np.delete(grasp_pc_norm, bad_ind[0], axis=0)
assert(np.sum(grasp_pc_norm != grasp_pc_norm) == 0)
m_width_of_pic = self.project_size
margin = self.projection_margin
order = np.array([0, 1, 2])
occupy_pic1, norm_pic1 = self.cal_projection(grasp_pc, m_width_of_pic, margin, grasp_pc_norm, # 计算点云投影
order, gripper_width)
if self.project_chann == 3:
output = norm_pic1
elif self.project_chann == 12:
order = np.array([1, 2, 0])
occupy_pic2, norm_pic2 = self.cal_projection(grasp_pc, m_width_of_pic, margin, grasp_pc_norm, # 计算点云投影
order, gripper_width)
order = np.array([0, 2, 1])
occupy_pic3, norm_pic3 = self.cal_projection(grasp_pc, m_width_of_pic, margin, grasp_pc_norm, # 计算点云投影
order, gripper_width)
output = np.dstack([occupy_pic1, norm_pic1, occupy_pic2, norm_pic2, occupy_pic3, norm_pic3])
else:
raise NotImplementedError
return output
def __getitem__(self, index):
# 获取物体和抓取姿态索引
obj_ind, grasp_ind = np.unravel_index(index, (len(self.object), self.grasp_amount_per_file))
obj_grasp = self.object[obj_ind] # 物体名称, 用于获取抓取姿态
obj_pc = self.transform[obj_grasp][0] # 物体名称, 用于获取点云
f_grasp = self.d_grasp[obj_grasp] # 抓取姿态文件名
fl_pc = np.array(self.d_pc[obj_pc]) # 各视角点云文件名
np.random.shuffle(fl_pc) # 打乱文件
grasp = np.load(f_grasp)[grasp_ind] # 获取抓取姿态
pc = np.load(fl_pc[-1]) # 随机获取点云
t = self.transform[obj_grasp][1] # 获取扫描仪到点云的转换矩阵, 抓取姿态在扫描仪采集的mesh文件上获取, 须转换到
# debug
# level_score_, refine_score_ = grasp[-2:]
# score_ = level_score_ + refine_score_ * 0.01
# if score_ >= self.thresh_bad:
# print("label: 0")
# elif score_ <= self.thresh_good:
# print("label: 1")
grasp_pc = self.collect_pc(grasp, pc, t) # 获取手抓闭合区域中的点云
if grasp_pc is None:
return None
level_score, refine_score = grasp[-2:]
if not self.projection:
# 点数不够则有放回采样, 点数太多则随机采样
if len(grasp_pc) > self.grasp_points_num:
grasp_pc = grasp_pc[np.random.choice(len(grasp_pc), size=self.grasp_points_num,
replace=False)].T
else:
grasp_pc = grasp_pc[np.random.choice(len(grasp_pc), size=self.grasp_points_num,
replace=True)].T
else:
grasp_pc = grasp_pc.transpose((2, 1, 0)) # 调整通道顺序
# 根据score分类
score = level_score + refine_score*0.01
if score >= self.thresh_bad:
label = 0
elif score <= self.thresh_good:
label = 1
else:
return None
if self.with_obj:
return grasp_pc, label, obj_grasp
else:
# print("grasp_pc", grasp_pc, grasp_pc.shape, label) # (3, 750)
return grasp_pc, label
def __len__(self):
return self.amount
class PointGraspOneViewMultiClassDataset(torch.utils.data.Dataset):
def __init__(self, grasp_points_num, grasp_amount_per_file, thresh_good,
thresh_bad, path, tag, with_obj=False, projection=False, project_chann=3, project_size=60):
self.grasp_points_num = grasp_points_num
self.grasp_amount_per_file = grasp_amount_per_file
self.path = path
self.tag = tag
self.thresh_good = thresh_good
self.thresh_bad = thresh_bad
self.with_obj = with_obj
self.min_point_limit = 50
# projection related
self.projection = projection
self.project_chann = project_chann
if self.project_chann not in [3, 12]:
raise NotImplementedError
self.project_size = project_size
if self.project_size != 60:
raise NotImplementedError
self.normal_K = 10
self.voxel_point_num = 50
self.projection_margin = 1
self.minimum_point_amount = 150
self.transform = pickle.load(open(os.path.join(self.path, 'google2cloud.pkl'), 'rb'))
fl_grasp = glob.glob(os.path.join(path, 'ycb_grasp', self.tag, '*.npy'))
fl_pc = glob.glob(os.path.join(path, 'ycb_rgbd', '*', 'clouds', 'pc_NP3_NP5*.npy'))
self.d_pc, self.d_grasp = {}, {}
for i in fl_pc:
k = i.split('/')[-3]
if k in self.d_pc.keys():
self.d_pc[k].append(i)
else:
self.d_pc[k] = [i]
for k in self.d_pc.keys():
self.d_pc[k].sort()
for i in fl_grasp:
k = i.split('/')[-1].split('.')[0]
self.d_grasp[k] = i
object1 = set(self.d_grasp.keys())
object2 = set(self.transform.keys())
self.object = list(object1.intersection(object2))
self.amount = len(self.object) * self.grasp_amount_per_file
def collect_pc(self, grasp, pc, transform):
center = grasp[0:3]
axis = grasp[3:6] # binormal
width = grasp[6]
angle = grasp[7]
axis = axis/np.linalg.norm(axis)
binormal = axis
# cal approach
cos_t = np.cos(angle)
sin_t = np.sin(angle)
R1 = np.c_[[cos_t, 0, sin_t],[0, 1, 0],[-sin_t, 0, cos_t]]
axis_y = axis
axis_x = np.array([axis_y[1], -axis_y[0], 0])
if np.linalg.norm(axis_x) == 0:
axis_x = np.array([1, 0, 0])
axis_x = axis_x / np.linalg.norm(axis_x)
axis_y = axis_y / np.linalg.norm(axis_y)
axis_z = np.cross(axis_x, axis_y)
R2 = np.c_[axis_x, np.c_[axis_y, axis_z]]
approach = R2.dot(R1)[:, 0]
approach = approach / np.linalg.norm(approach)
minor_normal = np.cross(axis, approach)
left = center - width*axis/2
right = center + width*axis/2
left = (np.dot(transform, np.array([left[0], left[1], left[2], 1])))[:3]
right = (np.dot(transform, np.array([right[0], right[1], right[2], 1])))[:3]
center = (np.dot(transform, np.array([center[0], center[1], center[2], 1])))[:3]
binormal = (np.dot(transform, np.array([binormal[0], binormal[1], binormal[2], 1])))[:3].reshape(3, 1)
approach = (np.dot(transform, np.array([approach[0], approach[1], approach[2], 1])))[:3].reshape(3, 1)
minor_normal = (np.dot(transform, np.array([minor_normal[0], minor_normal[1], minor_normal[2], 1])))[:3].reshape(3, 1)
matrix = np.hstack([approach, binormal, minor_normal]).T
pc_p2c = (np.dot(matrix, (pc-center).T)).T
left_t = (-width * np.array([0,1,0]) / 2).squeeze()
right_t = (width * np.array([0,1,0]) / 2).squeeze()
x_limit = width/4
z_limit = width/4
y_limit = width/2
x1 = pc_p2c[:, 0] > -x_limit
x2 = pc_p2c[:, 0] < x_limit
y1 = pc_p2c[:, 1] > -y_limit
y2 = pc_p2c[:, 1] < y_limit
z1 = pc_p2c[:, 2] > -z_limit
z2 = pc_p2c[:, 2] < z_limit
a = np.vstack([x1, x2, y1, y2, z1, z2])
self.in_ind = np.where(np.sum(a, axis=0) == len(a))[0]
if len(self.in_ind) < self.min_point_limit:
return None
if self.projection:
return self.project_pc(pc_p2c, width)
else:
return pc_p2c[self.in_ind]
def check_square(self, point, points_g):
dirs = np.array([[-1, 1, 1], [1, 1, 1], [-1, -1, 1], [1, -1, 1],
[-1, 1, -1], [1, 1, -1], [-1, -1, -1], [1, -1, -1]])
p = dirs * 0.5 + point # here res * 0.5 means get half of a pixel width
a1 = p[2][1] < points_g[:, 1]
a2 = p[0][1] > points_g[:, 1]
a3 = p[0][2] > points_g[:, 2]
a4 = p[4][2] < points_g[:, 2]
a5 = p[1][0] > points_g[:, 0]
a6 = p[0][0] < points_g[:, 0]
a = np.vstack([a1, a2, a3, a4, a5, a6])
points_in_area = np.where(np.sum(a, axis=0) == len(a))[0]
if len(points_in_area) == 0:
has_p = False
else:
has_p = True
return points_in_area
def cal_projection(self, point_cloud_voxel, m_width_of_pic, margin, surface_normal, order, gripper_width):
occupy_pic = np.zeros([m_width_of_pic, m_width_of_pic, 1])
norm_pic = np.zeros([m_width_of_pic, m_width_of_pic, 3])
norm_pic_num = np.zeros([m_width_of_pic, m_width_of_pic, 1])
max_x = point_cloud_voxel[:, order[0]].max()
min_x = point_cloud_voxel[:, order[0]].min()
max_y = point_cloud_voxel[:, order[1]].max()
min_y = point_cloud_voxel[:, order[1]].min()
min_z = point_cloud_voxel[:, order[2]].min()
tmp = max((max_x - min_x), (max_y - min_y))
if tmp == 0:
print("WARNING : the num of input points seems only have one, no possilbe to do learning on"
"such data, please throw it away. -- Hongzhuo")
return occupy_pic, norm_pic
# Here, we use the gripper width to cal the res:
res = gripper_width / (m_width_of_pic-margin)
voxel_points_square_norm = []
x_coord_r = ((point_cloud_voxel[:, order[0]]) / res + m_width_of_pic / 2)
y_coord_r = ((point_cloud_voxel[:, order[1]]) / res + m_width_of_pic / 2)
z_coord_r = ((point_cloud_voxel[:, order[2]]) / res + m_width_of_pic / 2)
x_coord_r = np.floor(x_coord_r).astype(int)
y_coord_r = np.floor(y_coord_r).astype(int)
z_coord_r = np.floor(z_coord_r).astype(int)
voxel_index = np.array([x_coord_r, y_coord_r, z_coord_r]).T # all point in grid
coordinate_buffer = np.unique(voxel_index, axis=0) # get a list of points without duplication
K = len(coordinate_buffer)
# [K, 1] store number of points in each voxel grid
number_buffer = np.zeros(shape=K, dtype=np.int64)
feature_buffer = np.zeros(shape=(K, self.voxel_point_num, 6), dtype=np.float32)
index_buffer = {}
for i in range(K):
index_buffer[tuple(coordinate_buffer[i])] = i # got index of coordinate
for voxel, point, normal in zip(voxel_index, point_cloud_voxel, surface_normal):
index = index_buffer[tuple(voxel)]
number = number_buffer[index]
if number < self.voxel_point_num:
feature_buffer[index, number, :3] = point
feature_buffer[index, number, 3:6] = normal
number_buffer[index] += 1
voxel_points_square_norm = np.sum(feature_buffer[..., -3:], axis=1)/number_buffer[:, np.newaxis]
voxel_points_square = coordinate_buffer
if len(voxel_points_square) == 0:
return occupy_pic, norm_pic
x_coord_square = voxel_points_square[:, 0]
y_coord_square = voxel_points_square[:, 1]
norm_pic[x_coord_square, y_coord_square, :] = voxel_points_square_norm
occupy_pic[x_coord_square, y_coord_square] = number_buffer[:, np.newaxis]
occupy_max = occupy_pic.max()
assert(occupy_max > 0)
occupy_pic = occupy_pic / occupy_max
return occupy_pic, norm_pic
def project_pc(self, pc, gripper_width):
"""
for gpd baseline, only support input_chann == [3, 12]
"""
pc = pc.astype(np.float32)
pc = pcl.PointCloud(pc)
norm = pc.make_NormalEstimation()
norm.set_KSearch(self.normal_K)
normals = norm.compute()
surface_normal = normals.to_array()
surface_normal = surface_normal[:, 0:3]
pc = pc.to_array()
grasp_pc = pc[self.in_ind]
grasp_pc_norm = surface_normal[self.in_ind]
bad_check = (grasp_pc_norm != grasp_pc_norm)
if np.sum(bad_check)!=0:
bad_ind = np.where(bad_check == True)
grasp_pc = np.delete(grasp_pc, bad_ind[0], axis=0)
grasp_pc_norm = np.delete(grasp_pc_norm, bad_ind[0], axis=0)
assert(np.sum(grasp_pc_norm != grasp_pc_norm) == 0)
m_width_of_pic = self.project_size
margin = self.projection_margin
order = np.array([0, 1, 2])
occupy_pic1, norm_pic1 = self.cal_projection(grasp_pc, m_width_of_pic, margin, grasp_pc_norm,
order, gripper_width)
if self.project_chann == 3:
output = norm_pic1
elif self.project_chann == 12:
order = np.array([1, 2, 0])
occupy_pic2, norm_pic2 = self.cal_projection(grasp_pc, m_width_of_pic, margin, grasp_pc_norm,
order, gripper_width)
order = np.array([0, 2, 1])
occupy_pic3, norm_pic3 = self.cal_projection(grasp_pc, m_width_of_pic, margin, grasp_pc_norm,
order, gripper_width)
output = np.dstack([occupy_pic1, norm_pic1, occupy_pic2, norm_pic2, occupy_pic3, norm_pic3])
else:
raise NotImplementedError
return output
def __getitem__(self, index):
obj_ind, grasp_ind = np.unravel_index(index, (len(self.object), self.grasp_amount_per_file))
obj_grasp = self.object[obj_ind] # 抓取姿态
obj_pc = self.transform[obj_grasp][0] # 物体点云
f_grasp = self.d_grasp[obj_grasp]
fl_pc = np.array(self.d_pc[obj_pc])
np.random.shuffle(fl_pc)
grasp = np.load(f_grasp)[grasp_ind]
pc = np.load(fl_pc[-1])
t = self.transform[obj_grasp][1]
grasp_pc = self.collect_pc(grasp, pc, t)
if grasp_pc is None:
return None
level_score, refine_score = grasp[-2:]
if not self.projection:
if len(grasp_pc) > self.grasp_points_num:
grasp_pc = grasp_pc[np.random.choice(len(grasp_pc), size=self.grasp_points_num,
replace=False)].T
else:
grasp_pc = grasp_pc[np.random.choice(len(grasp_pc), size=self.grasp_points_num,
replace=True)].T
else:
grasp_pc = grasp_pc.transpose((2, 1, 0))
score = level_score + refine_score*0.01
if score >= self.thresh_bad:
label = 0
elif score <= self.thresh_good:
label = 2
else:
label = 1
if self.with_obj:
return grasp_pc, label, obj_grasp
else:
return grasp_pc, label
def __len__(self):
return self.amount
if __name__ == '__main__':
try:
from mayavi import mlab
except ImportError:
print("Can not import mayavi")
mlab = None
def worker_init_fn(pid): # After creating the workers, each worker has an independent seed
np.random.seed(torch.initial_seed() % (2 ** 31 - 1))
def my_collate(batch):
batch = list(filter(lambda x: x is not None, batch))
return torch.utils.data.dataloader.default_collate(batch)
def show_points(point, color='lb', scale_factor=.0005):
if color == 'b':
color_f = (0, 0, 1)
elif color == 'r':
color_f = (1, 0, 0)
elif color == 'g':
color_f = (0, 1, 0)
elif color == 'lb': # light blue
color_f = (0.22, 1, 1)
else:
color_f = (1, 1, 1)
if point.size == 3: # vis for only one point, shape must be (3,), for shape (1, 3) is not work
point = point.reshape(3, )
mlab.points3d(point[0], point[1], point[2], color=color_f, scale_factor=scale_factor)
else: # vis for multiple points
mlab.points3d(point[:, 0], point[:, 1], point[:, 2], color=color_f, scale_factor=scale_factor)
def show_line(un1, un2, color='g', scale_factor=0.0005):
if color == 'b':
color_f = (0, 0, 1)
elif color == 'r':
color_f = (1, 0, 0)
elif color == 'g':
color_f = (0, 1, 0)
else:
color_f = (1, 1, 1)
mlab.plot3d([un1[0], un2[0]], [un1[1], un2[1]], [un1[2], un2[2]], color=color_f, tube_radius=scale_factor)
grasp_points_num = 1000
obj_points_num = 50000
pc_file_used_num = 20
thresh_good = 0.6
thresh_bad = 0.6
input_size = 60
input_chann = 12 # 12
# a = PointGraspDataset(
# obj_points_num=obj_points_num,
# grasp_points_num=grasp_points_num,
# pc_file_used_num=pc_file_used_num,
# path="../data",
# tag='train',
# grasp_amount_per_file=2000,
# thresh_good=thresh_good,
# thresh_bad=thresh_bad,
# projection=True,
# project_chann=input_chann,
# project_size=input_size,
# )
# c, d = a.__getitem__(0)
b = PointGraspOneViewDataset(
grasp_points_num=grasp_points_num,
path="../data",
tag='train',
grasp_amount_per_file=2100, # 6500
thresh_good=thresh_good,
thresh_bad=thresh_bad,
)
cnt = 0
for i in range(b.__len__()):
try:
grasp_pc, label = b.__getitem__(i)
cnt += 1
except (RuntimeError, TypeError, NameError):
print("[INFO] don't have valid points!")
else:
print("[INFO] get points success!")
# print("grasp_pc:", grasp_pc[0], grasp_pc[0].shape, grasp_pc.shape, "\nlable:", label)
# break
# pass
print("[INFO] have {} valid grasp in the dataset.".format(cnt))
# train_loader = torch.utils.data.DataLoader(
# PointGraspOneViewDataset(
# grasp_points_num=grasp_points_num,
# path="../data",
# tag='train',
# grasp_amount_per_file=2100, # 6500
# thresh_good=thresh_good,
# thresh_bad=thresh_bad,
# ),
# batch_size=64,
# num_workers=32,
# pin_memory=True,
# shuffle=True,
# worker_init_fn=worker_init_fn,
# collate_fn=my_collate,
# drop_last=True, # fix bug: ValueError: Expected more than 1 value per channel when training
# )
#
# for batch_idx, (data, target) in enumerate(train_loader):
# # print("data", data, data.shape, "target", target)
# pass | [
"dexnet.grasping.GpgGraspSampler",
"numpy.hstack",
"torch.initial_seed",
"numpy.array",
"numpy.linalg.norm",
"numpy.sin",
"pcl.PointCloud",
"autolab_core.YamlConfig",
"mayavi.mlab.points3d",
"mayavi.mlab.pipeline.open",
"numpy.cross",
"numpy.where",
"numpy.delete",
"numpy.dot",
"numpy.vs... | [((318, 389), 'autolab_core.YamlConfig', 'YamlConfig', (["(home_dir + '/Projects/PointNetGPD/dex-net/test/config.yaml')"], {}), "(home_dir + '/Projects/PointNetGPD/dex-net/test/config.yaml')\n", (328, 389), False, 'from autolab_core import YamlConfig\n'), ((428, 521), 'dexnet.grasping.RobotGripper.load', 'RobotGripper.load', (['gripper_name', "(home_dir + '/Projects/PointNetGPD/dex-net/data/grippers')"], {}), "(gripper_name, home_dir +\n '/Projects/PointNetGPD/dex-net/data/grippers')\n", (445, 521), False, 'from dexnet.grasping import RobotGripper\n'), ((524, 561), 'dexnet.grasping.GpgGraspSampler', 'GpgGraspSampler', (['gripper', 'yaml_config'], {}), '(gripper, yaml_config)\n', (539, 561), False, 'from dexnet.grasping import GpgGraspSampler\n'), ((2711, 2724), 'numpy.cos', 'np.cos', (['angle'], {}), '(angle)\n', (2717, 2724), True, 'import numpy as np\n'), ((2741, 2754), 'numpy.sin', 'np.sin', (['angle'], {}), '(angle)\n', (2747, 2754), True, 'import numpy as np\n'), ((2861, 2897), 'numpy.array', 'np.array', (['[axis_y[1], -axis_y[0], 0]'], {}), '([axis_y[1], -axis_y[0], 0])\n', (2869, 2897), True, 'import numpy as np\n'), ((3094, 3118), 'numpy.cross', 'np.cross', (['axis_x', 'axis_y'], {}), '(axis_x, axis_y)\n', (3102, 3118), True, 'import numpy as np\n'), ((3283, 3307), 'numpy.cross', 'np.cross', (['axis', 'approach'], {}), '(axis, approach)\n', (3291, 3307), True, 'import numpy as np\n'), ((4790, 4825), 'numpy.vstack', 'np.vstack', (['[x1, x2, y1, y2, z1, z2]'], {}), '([x1, x2, y1, y2, z1, z2])\n', (4799, 4825), True, 'import numpy as np\n'), ((5158, 5273), 'numpy.array', 'np.array', (['[[-1, 1, 1], [1, 1, 1], [-1, -1, 1], [1, -1, 1], [-1, 1, -1], [1, 1, -1], [\n -1, -1, -1], [1, -1, -1]]'], {}), '([[-1, 1, 1], [1, 1, 1], [-1, -1, 1], [1, -1, 1], [-1, 1, -1], [1, \n 1, -1], [-1, -1, -1], [1, -1, -1]])\n', (5166, 5273), True, 'import numpy as np\n'), ((5615, 5650), 'numpy.vstack', 'np.vstack', (['[a1, a2, a3, a4, a5, a6]'], {}), '([a1, a2, a3, a4, a5, a6])\n', (5624, 5650), True, 'import numpy as np\n'), ((5983, 6028), 'numpy.zeros', 'np.zeros', (['[m_width_of_pic, m_width_of_pic, 1]'], {}), '([m_width_of_pic, m_width_of_pic, 1])\n', (5991, 6028), True, 'import numpy as np\n'), ((6048, 6093), 'numpy.zeros', 'np.zeros', (['[m_width_of_pic, m_width_of_pic, 3]'], {}), '([m_width_of_pic, m_width_of_pic, 3])\n', (6056, 6093), True, 'import numpy as np\n'), ((6117, 6162), 'numpy.zeros', 'np.zeros', (['[m_width_of_pic, m_width_of_pic, 1]'], {}), '([m_width_of_pic, m_width_of_pic, 1])\n', (6125, 6162), True, 'import numpy as np\n'), ((7384, 7414), 'numpy.unique', 'np.unique', (['voxel_index'], {'axis': '(0)'}), '(voxel_index, axis=0)\n', (7393, 7414), True, 'import numpy as np\n'), ((7577, 7610), 'numpy.zeros', 'np.zeros', ([], {'shape': 'K', 'dtype': 'np.int64'}), '(shape=K, dtype=np.int64)\n', (7585, 7610), True, 'import numpy as np\n'), ((7636, 7698), 'numpy.zeros', 'np.zeros', ([], {'shape': '(K, self.voxel_point_num, 6)', 'dtype': 'np.float32'}), '(shape=(K, self.voxel_point_num, 6), dtype=np.float32)\n', (7644, 7698), True, 'import numpy as np\n'), ((9052, 9070), 'pcl.PointCloud', 'pcl.PointCloud', (['pc'], {}), '(pc)\n', (9066, 9070), False, 'import pcl\n'), ((9823, 9842), 'numpy.array', 'np.array', (['[0, 1, 2]'], {}), '([0, 1, 2])\n', (9831, 9842), True, 'import numpy as np\n'), ((11048, 11075), 'numpy.array', 'np.array', (['self.d_pc[obj_pc]'], {}), '(self.d_pc[obj_pc])\n', (11056, 11075), True, 'import numpy as np\n'), ((14557, 14570), 'numpy.cos', 'np.cos', (['angle'], {}), '(angle)\n', (14563, 14570), True, 'import numpy as np\n'), ((14587, 14600), 'numpy.sin', 'np.sin', (['angle'], {}), '(angle)\n', (14593, 14600), True, 'import numpy as np\n'), ((14707, 14743), 'numpy.array', 'np.array', (['[axis_y[1], -axis_y[0], 0]'], {}), '([axis_y[1], -axis_y[0], 0])\n', (14715, 14743), True, 'import numpy as np\n'), ((14940, 14964), 'numpy.cross', 'np.cross', (['axis_x', 'axis_y'], {}), '(axis_x, axis_y)\n', (14948, 14964), True, 'import numpy as np\n'), ((15129, 15153), 'numpy.cross', 'np.cross', (['axis', 'approach'], {}), '(axis, approach)\n', (15137, 15153), True, 'import numpy as np\n'), ((16636, 16671), 'numpy.vstack', 'np.vstack', (['[x1, x2, y1, y2, z1, z2]'], {}), '([x1, x2, y1, y2, z1, z2])\n', (16645, 16671), True, 'import numpy as np\n'), ((17004, 17119), 'numpy.array', 'np.array', (['[[-1, 1, 1], [1, 1, 1], [-1, -1, 1], [1, -1, 1], [-1, 1, -1], [1, 1, -1], [\n -1, -1, -1], [1, -1, -1]]'], {}), '([[-1, 1, 1], [1, 1, 1], [-1, -1, 1], [1, -1, 1], [-1, 1, -1], [1, \n 1, -1], [-1, -1, -1], [1, -1, -1]])\n', (17012, 17119), True, 'import numpy as np\n'), ((17461, 17496), 'numpy.vstack', 'np.vstack', (['[a1, a2, a3, a4, a5, a6]'], {}), '([a1, a2, a3, a4, a5, a6])\n', (17470, 17496), True, 'import numpy as np\n'), ((17829, 17874), 'numpy.zeros', 'np.zeros', (['[m_width_of_pic, m_width_of_pic, 1]'], {}), '([m_width_of_pic, m_width_of_pic, 1])\n', (17837, 17874), True, 'import numpy as np\n'), ((17894, 17939), 'numpy.zeros', 'np.zeros', (['[m_width_of_pic, m_width_of_pic, 3]'], {}), '([m_width_of_pic, m_width_of_pic, 3])\n', (17902, 17939), True, 'import numpy as np\n'), ((17963, 18008), 'numpy.zeros', 'np.zeros', (['[m_width_of_pic, m_width_of_pic, 1]'], {}), '([m_width_of_pic, m_width_of_pic, 1])\n', (17971, 18008), True, 'import numpy as np\n'), ((19230, 19260), 'numpy.unique', 'np.unique', (['voxel_index'], {'axis': '(0)'}), '(voxel_index, axis=0)\n', (19239, 19260), True, 'import numpy as np\n'), ((19423, 19456), 'numpy.zeros', 'np.zeros', ([], {'shape': 'K', 'dtype': 'np.int64'}), '(shape=K, dtype=np.int64)\n', (19431, 19456), True, 'import numpy as np\n'), ((19482, 19544), 'numpy.zeros', 'np.zeros', ([], {'shape': '(K, self.voxel_point_num, 6)', 'dtype': 'np.float32'}), '(shape=(K, self.voxel_point_num, 6), dtype=np.float32)\n', (19490, 19544), True, 'import numpy as np\n'), ((20898, 20916), 'pcl.PointCloud', 'pcl.PointCloud', (['pc'], {}), '(pc)\n', (20912, 20916), False, 'import pcl\n'), ((21669, 21688), 'numpy.array', 'np.array', (['[0, 1, 2]'], {}), '([0, 1, 2])\n', (21677, 21688), True, 'import numpy as np\n'), ((22894, 22921), 'numpy.array', 'np.array', (['self.d_pc[obj_pc]'], {}), '(self.d_pc[obj_pc])\n', (22902, 22921), True, 'import numpy as np\n'), ((27295, 27308), 'numpy.cos', 'np.cos', (['angle'], {}), '(angle)\n', (27301, 27308), True, 'import numpy as np\n'), ((27325, 27338), 'numpy.sin', 'np.sin', (['angle'], {}), '(angle)\n', (27331, 27338), True, 'import numpy as np\n'), ((27455, 27491), 'numpy.array', 'np.array', (['[axis_y[1], -axis_y[0], 0]'], {}), '([axis_y[1], -axis_y[0], 0])\n', (27463, 27491), True, 'import numpy as np\n'), ((27708, 27732), 'numpy.cross', 'np.cross', (['axis_x', 'axis_y'], {}), '(axis_x, axis_y)\n', (27716, 27732), True, 'import numpy as np\n'), ((30303, 30347), 'numpy.array', 'np.array', (['[approach, binormal, minor_normal]'], {}), '([approach, binormal, minor_normal])\n', (30311, 30347), True, 'import numpy as np\n'), ((30539, 30598), 'numpy.array', 'np.array', (['[trans_p2m[0], trans_p2m[1], trans_p2m[2] + 0.02]'], {}), '([trans_p2m[0], trans_p2m[1], trans_p2m[2] + 0.02])\n', (30547, 30598), True, 'import numpy as np\n'), ((31341, 31376), 'numpy.vstack', 'np.vstack', (['[x1, x2, y1, y2, z1, z2]'], {}), '([x1, x2, y1, y2, z1, z2])\n', (31350, 31376), True, 'import numpy as np\n'), ((35055, 35170), 'numpy.array', 'np.array', (['[[-1, 1, 1], [1, 1, 1], [-1, -1, 1], [1, -1, 1], [-1, 1, -1], [1, 1, -1], [\n -1, -1, -1], [1, -1, -1]]'], {}), '([[-1, 1, 1], [1, 1, 1], [-1, -1, 1], [1, -1, 1], [-1, 1, -1], [1, \n 1, -1], [-1, -1, -1], [1, -1, -1]])\n', (35063, 35170), True, 'import numpy as np\n'), ((35512, 35547), 'numpy.vstack', 'np.vstack', (['[a1, a2, a3, a4, a5, a6]'], {}), '([a1, a2, a3, a4, a5, a6])\n', (35521, 35547), True, 'import numpy as np\n'), ((36107, 36152), 'numpy.zeros', 'np.zeros', (['[m_width_of_pic, m_width_of_pic, 1]'], {}), '([m_width_of_pic, m_width_of_pic, 1])\n', (36115, 36152), True, 'import numpy as np\n'), ((36172, 36217), 'numpy.zeros', 'np.zeros', (['[m_width_of_pic, m_width_of_pic, 3]'], {}), '([m_width_of_pic, m_width_of_pic, 3])\n', (36180, 36217), True, 'import numpy as np\n'), ((36241, 36286), 'numpy.zeros', 'np.zeros', (['[m_width_of_pic, m_width_of_pic, 1]'], {}), '([m_width_of_pic, m_width_of_pic, 1])\n', (36249, 36286), True, 'import numpy as np\n'), ((37508, 37538), 'numpy.unique', 'np.unique', (['voxel_index'], {'axis': '(0)'}), '(voxel_index, axis=0)\n', (37517, 37538), True, 'import numpy as np\n'), ((37701, 37734), 'numpy.zeros', 'np.zeros', ([], {'shape': 'K', 'dtype': 'np.int64'}), '(shape=K, dtype=np.int64)\n', (37709, 37734), True, 'import numpy as np\n'), ((37760, 37822), 'numpy.zeros', 'np.zeros', ([], {'shape': '(K, self.voxel_point_num, 6)', 'dtype': 'np.float32'}), '(shape=(K, self.voxel_point_num, 6), dtype=np.float32)\n', (37768, 37822), True, 'import numpy as np\n'), ((39199, 39217), 'pcl.PointCloud', 'pcl.PointCloud', (['pc'], {}), '(pc)\n', (39213, 39217), False, 'import pcl\n'), ((39972, 39991), 'numpy.array', 'np.array', (['[0, 1, 2]'], {}), '([0, 1, 2])\n', (39980, 39991), True, 'import numpy as np\n'), ((41285, 41312), 'numpy.array', 'np.array', (['self.d_pc[obj_pc]'], {}), '(self.d_pc[obj_pc])\n', (41293, 41312), True, 'import numpy as np\n'), ((41333, 41357), 'numpy.random.shuffle', 'np.random.shuffle', (['fl_pc'], {}), '(fl_pc)\n', (41350, 41357), True, 'import numpy as np\n'), ((41434, 41452), 'numpy.load', 'np.load', (['fl_pc[-1]'], {}), '(fl_pc[-1])\n', (41441, 41452), True, 'import numpy as np\n'), ((45170, 45183), 'numpy.cos', 'np.cos', (['angle'], {}), '(angle)\n', (45176, 45183), True, 'import numpy as np\n'), ((45200, 45213), 'numpy.sin', 'np.sin', (['angle'], {}), '(angle)\n', (45206, 45213), True, 'import numpy as np\n'), ((45320, 45356), 'numpy.array', 'np.array', (['[axis_y[1], -axis_y[0], 0]'], {}), '([axis_y[1], -axis_y[0], 0])\n', (45328, 45356), True, 'import numpy as np\n'), ((45553, 45577), 'numpy.cross', 'np.cross', (['axis_x', 'axis_y'], {}), '(axis_x, axis_y)\n', (45561, 45577), True, 'import numpy as np\n'), ((45742, 45766), 'numpy.cross', 'np.cross', (['axis', 'approach'], {}), '(axis, approach)\n', (45750, 45766), True, 'import numpy as np\n'), ((46995, 47030), 'numpy.vstack', 'np.vstack', (['[x1, x2, y1, y2, z1, z2]'], {}), '([x1, x2, y1, y2, z1, z2])\n', (47004, 47030), True, 'import numpy as np\n'), ((47363, 47478), 'numpy.array', 'np.array', (['[[-1, 1, 1], [1, 1, 1], [-1, -1, 1], [1, -1, 1], [-1, 1, -1], [1, 1, -1], [\n -1, -1, -1], [1, -1, -1]]'], {}), '([[-1, 1, 1], [1, 1, 1], [-1, -1, 1], [1, -1, 1], [-1, 1, -1], [1, \n 1, -1], [-1, -1, -1], [1, -1, -1]])\n', (47371, 47478), True, 'import numpy as np\n'), ((47820, 47855), 'numpy.vstack', 'np.vstack', (['[a1, a2, a3, a4, a5, a6]'], {}), '([a1, a2, a3, a4, a5, a6])\n', (47829, 47855), True, 'import numpy as np\n'), ((48188, 48233), 'numpy.zeros', 'np.zeros', (['[m_width_of_pic, m_width_of_pic, 1]'], {}), '([m_width_of_pic, m_width_of_pic, 1])\n', (48196, 48233), True, 'import numpy as np\n'), ((48253, 48298), 'numpy.zeros', 'np.zeros', (['[m_width_of_pic, m_width_of_pic, 3]'], {}), '([m_width_of_pic, m_width_of_pic, 3])\n', (48261, 48298), True, 'import numpy as np\n'), ((48322, 48367), 'numpy.zeros', 'np.zeros', (['[m_width_of_pic, m_width_of_pic, 1]'], {}), '([m_width_of_pic, m_width_of_pic, 1])\n', (48330, 48367), True, 'import numpy as np\n'), ((49589, 49619), 'numpy.unique', 'np.unique', (['voxel_index'], {'axis': '(0)'}), '(voxel_index, axis=0)\n', (49598, 49619), True, 'import numpy as np\n'), ((49782, 49815), 'numpy.zeros', 'np.zeros', ([], {'shape': 'K', 'dtype': 'np.int64'}), '(shape=K, dtype=np.int64)\n', (49790, 49815), True, 'import numpy as np\n'), ((49841, 49903), 'numpy.zeros', 'np.zeros', ([], {'shape': '(K, self.voxel_point_num, 6)', 'dtype': 'np.float32'}), '(shape=(K, self.voxel_point_num, 6), dtype=np.float32)\n', (49849, 49903), True, 'import numpy as np\n'), ((51257, 51275), 'pcl.PointCloud', 'pcl.PointCloud', (['pc'], {}), '(pc)\n', (51271, 51275), False, 'import pcl\n'), ((52028, 52047), 'numpy.array', 'np.array', (['[0, 1, 2]'], {}), '([0, 1, 2])\n', (52036, 52047), True, 'import numpy as np\n'), ((53255, 53282), 'numpy.array', 'np.array', (['self.d_pc[obj_pc]'], {}), '(self.d_pc[obj_pc])\n', (53263, 53282), True, 'import numpy as np\n'), ((53291, 53315), 'numpy.random.shuffle', 'np.random.shuffle', (['fl_pc'], {}), '(fl_pc)\n', (53308, 53315), True, 'import numpy as np\n'), ((53374, 53392), 'numpy.load', 'np.load', (['fl_pc[-1]'], {}), '(fl_pc[-1])\n', (53381, 53392), True, 'import numpy as np\n'), ((54884, 54934), 'torch.utils.data.dataloader.default_collate', 'torch.utils.data.dataloader.default_collate', (['batch'], {}), '(batch)\n', (54927, 54934), False, 'import torch\n'), ((55976, 56087), 'mayavi.mlab.plot3d', 'mlab.plot3d', (['[un1[0], un2[0]]', '[un1[1], un2[1]]', '[un1[2], un2[2]]'], {'color': 'color_f', 'tube_radius': 'scale_factor'}), '([un1[0], un2[0]], [un1[1], un2[1]], [un1[2], un2[2]], color=\n color_f, tube_radius=scale_factor)\n', (55987, 56087), False, 'from mayavi import mlab\n'), ((1758, 1808), 'os.path.join', 'os.path.join', (['path', '"""ycb_grasp"""', 'self.tag', '"""*.npy"""'], {}), "(path, 'ycb_grasp', self.tag, '*.npy')\n", (1770, 1808), False, 'import os\n'), ((1836, 1890), 'os.path.join', 'os.path.join', (['path', '"""ycb_rgbd"""', '"""*"""', '"""clouds"""', '"""*.npy"""'], {}), "(path, 'ycb_rgbd', '*', 'clouds', '*.npy')\n", (1848, 1890), False, 'import os\n'), ((2627, 2647), 'numpy.linalg.norm', 'np.linalg.norm', (['axis'], {}), '(axis)\n', (2641, 2647), True, 'import numpy as np\n'), ((2909, 2931), 'numpy.linalg.norm', 'np.linalg.norm', (['axis_x'], {}), '(axis_x)\n', (2923, 2931), True, 'import numpy as np\n'), ((2959, 2978), 'numpy.array', 'np.array', (['[1, 0, 0]'], {}), '([1, 0, 0])\n', (2967, 2978), True, 'import numpy as np\n'), ((3005, 3027), 'numpy.linalg.norm', 'np.linalg.norm', (['axis_x'], {}), '(axis_x)\n', (3019, 3027), True, 'import numpy as np\n'), ((3054, 3076), 'numpy.linalg.norm', 'np.linalg.norm', (['axis_y'], {}), '(axis_y)\n', (3068, 3076), True, 'import numpy as np\n'), ((3235, 3259), 'numpy.linalg.norm', 'np.linalg.norm', (['approach'], {}), '(approach)\n', (3249, 3259), True, 'import numpy as np\n'), ((4132, 4177), 'numpy.hstack', 'np.hstack', (['[approach, binormal, minor_normal]'], {}), '([approach, binormal, minor_normal])\n', (4141, 4177), True, 'import numpy as np\n'), ((4325, 4356), 'numpy.dot', 'np.dot', (['matrix', '(pc - center).T'], {}), '(matrix, (pc - center).T)\n', (4331, 4356), True, 'import numpy as np\n'), ((7289, 7332), 'numpy.array', 'np.array', (['[x_coord_r, y_coord_r, z_coord_r]'], {}), '([x_coord_r, y_coord_r, z_coord_r])\n', (7297, 7332), True, 'import numpy as np\n'), ((8258, 8298), 'numpy.sum', 'np.sum', (['feature_buffer[..., -3:]'], {'axis': '(1)'}), '(feature_buffer[..., -3:], axis=1)\n', (8264, 8298), True, 'import numpy as np\n'), ((9456, 9473), 'numpy.sum', 'np.sum', (['bad_check'], {}), '(bad_check)\n', (9462, 9473), True, 'import numpy as np\n'), ((9500, 9527), 'numpy.where', 'np.where', (['(bad_check == True)'], {}), '(bad_check == True)\n', (9508, 9527), True, 'import numpy as np\n'), ((9551, 9590), 'numpy.delete', 'np.delete', (['grasp_pc', 'bad_ind[0]'], {'axis': '(0)'}), '(grasp_pc, bad_ind[0], axis=0)\n', (9560, 9590), True, 'import numpy as np\n'), ((9619, 9663), 'numpy.delete', 'np.delete', (['grasp_pc_norm', 'bad_ind[0]'], {'axis': '(0)'}), '(grasp_pc_norm, bad_ind[0], axis=0)\n', (9628, 9663), True, 'import numpy as np\n'), ((9679, 9717), 'numpy.sum', 'np.sum', (['(grasp_pc_norm != grasp_pc_norm)'], {}), '(grasp_pc_norm != grasp_pc_norm)\n', (9685, 9717), True, 'import numpy as np\n'), ((11173, 11189), 'numpy.load', 'np.load', (['f_grasp'], {}), '(f_grasp)\n', (11180, 11189), True, 'import numpy as np\n'), ((13604, 13654), 'os.path.join', 'os.path.join', (['path', '"""ycb_grasp"""', 'self.tag', '"""*.npy"""'], {}), "(path, 'ycb_grasp', self.tag, '*.npy')\n", (13616, 13654), False, 'import os\n'), ((13682, 13736), 'os.path.join', 'os.path.join', (['path', '"""ycb_rgbd"""', '"""*"""', '"""clouds"""', '"""*.npy"""'], {}), "(path, 'ycb_rgbd', '*', 'clouds', '*.npy')\n", (13694, 13736), False, 'import os\n'), ((14473, 14493), 'numpy.linalg.norm', 'np.linalg.norm', (['axis'], {}), '(axis)\n', (14487, 14493), True, 'import numpy as np\n'), ((14755, 14777), 'numpy.linalg.norm', 'np.linalg.norm', (['axis_x'], {}), '(axis_x)\n', (14769, 14777), True, 'import numpy as np\n'), ((14805, 14824), 'numpy.array', 'np.array', (['[1, 0, 0]'], {}), '([1, 0, 0])\n', (14813, 14824), True, 'import numpy as np\n'), ((14851, 14873), 'numpy.linalg.norm', 'np.linalg.norm', (['axis_x'], {}), '(axis_x)\n', (14865, 14873), True, 'import numpy as np\n'), ((14900, 14922), 'numpy.linalg.norm', 'np.linalg.norm', (['axis_y'], {}), '(axis_y)\n', (14914, 14922), True, 'import numpy as np\n'), ((15081, 15105), 'numpy.linalg.norm', 'np.linalg.norm', (['approach'], {}), '(approach)\n', (15095, 15105), True, 'import numpy as np\n'), ((15978, 16023), 'numpy.hstack', 'np.hstack', (['[approach, binormal, minor_normal]'], {}), '([approach, binormal, minor_normal])\n', (15987, 16023), True, 'import numpy as np\n'), ((16171, 16202), 'numpy.dot', 'np.dot', (['matrix', '(pc - center).T'], {}), '(matrix, (pc - center).T)\n', (16177, 16202), True, 'import numpy as np\n'), ((19135, 19178), 'numpy.array', 'np.array', (['[x_coord_r, y_coord_r, z_coord_r]'], {}), '([x_coord_r, y_coord_r, z_coord_r])\n', (19143, 19178), True, 'import numpy as np\n'), ((20104, 20144), 'numpy.sum', 'np.sum', (['feature_buffer[..., -3:]'], {'axis': '(1)'}), '(feature_buffer[..., -3:], axis=1)\n', (20110, 20144), True, 'import numpy as np\n'), ((21302, 21319), 'numpy.sum', 'np.sum', (['bad_check'], {}), '(bad_check)\n', (21308, 21319), True, 'import numpy as np\n'), ((21346, 21373), 'numpy.where', 'np.where', (['(bad_check == True)'], {}), '(bad_check == True)\n', (21354, 21373), True, 'import numpy as np\n'), ((21397, 21436), 'numpy.delete', 'np.delete', (['grasp_pc', 'bad_ind[0]'], {'axis': '(0)'}), '(grasp_pc, bad_ind[0], axis=0)\n', (21406, 21436), True, 'import numpy as np\n'), ((21465, 21509), 'numpy.delete', 'np.delete', (['grasp_pc_norm', 'bad_ind[0]'], {'axis': '(0)'}), '(grasp_pc_norm, bad_ind[0], axis=0)\n', (21474, 21509), True, 'import numpy as np\n'), ((21525, 21563), 'numpy.sum', 'np.sum', (['(grasp_pc_norm != grasp_pc_norm)'], {}), '(grasp_pc_norm != grasp_pc_norm)\n', (21531, 21563), True, 'import numpy as np\n'), ((23019, 23035), 'numpy.load', 'np.load', (['f_grasp'], {}), '(f_grasp)\n', (23026, 23035), True, 'import numpy as np\n'), ((25402, 25452), 'os.path.join', 'os.path.join', (['path', '"""ycb_grasp"""', 'self.tag', '"""*.npy"""'], {}), "(path, 'ycb_grasp', self.tag, '*.npy')\n", (25414, 25452), False, 'import os\n'), ((25534, 25598), 'os.path.join', 'os.path.join', (['path', '"""ycb_rgbd"""', '"""*"""', '"""clouds"""', '"""pc_NP3_NP5*.npy"""'], {}), "(path, 'ycb_rgbd', '*', 'clouds', 'pc_NP3_NP5*.npy')\n", (25546, 25598), False, 'import os\n'), ((27203, 27223), 'numpy.linalg.norm', 'np.linalg.norm', (['axis'], {}), '(axis)\n', (27217, 27223), True, 'import numpy as np\n'), ((27503, 27525), 'numpy.linalg.norm', 'np.linalg.norm', (['axis_x'], {}), '(axis_x)\n', (27517, 27525), True, 'import numpy as np\n'), ((27553, 27572), 'numpy.array', 'np.array', (['[1, 0, 0]'], {}), '([1, 0, 0])\n', (27561, 27572), True, 'import numpy as np\n'), ((27619, 27641), 'numpy.linalg.norm', 'np.linalg.norm', (['axis_x'], {}), '(axis_x)\n', (27633, 27641), True, 'import numpy as np\n'), ((27668, 27690), 'numpy.linalg.norm', 'np.linalg.norm', (['axis_y'], {}), '(axis_y)\n', (27682, 27690), True, 'import numpy as np\n'), ((27857, 27881), 'numpy.linalg.norm', 'np.linalg.norm', (['approach'], {}), '(approach)\n', (27871, 27881), True, 'import numpy as np\n'), ((27914, 27938), 'numpy.cross', 'np.cross', (['axis', 'approach'], {}), '(axis, approach)\n', (27922, 27938), True, 'import numpy as np\n'), ((28522, 28570), 'mayavi.mlab.figure', 'mlab.figure', ([], {'bgcolor': '(1, 1, 1)', 'size': '(1000, 800)'}), '(bgcolor=(1, 1, 1), size=(1000, 800))\n', (28533, 28570), False, 'from mayavi import mlab\n'), ((29774, 29821), 'mayavi.mlab.title', 'mlab.title', (['"""google"""'], {'size': '(0.3)', 'color': '(0, 0, 0)'}), "('google', size=0.3, color=(0, 0, 0))\n", (29784, 29821), False, 'from mayavi import mlab\n'), ((29834, 29845), 'mayavi.mlab.show', 'mlab.show', ([], {}), '()\n', (29843, 29845), False, 'from mayavi import mlab\n'), ((30623, 30663), 'numpy.dot', 'np.dot', (['matrix_p2m.T', '(pc - trans_p2m).T'], {}), '(matrix_p2m.T, (pc - trans_p2m).T)\n', (30629, 30663), True, 'import numpy as np\n'), ((30701, 30740), 'numpy.dot', 'np.dot', (['matrix_m2c', '(pc_p2m - center).T'], {}), '(matrix_m2c, (pc_p2m - center).T)\n', (30707, 30740), True, 'import numpy as np\n'), ((31694, 31742), 'mayavi.mlab.figure', 'mlab.figure', ([], {'bgcolor': '(1, 1, 1)', 'size': '(1000, 800)'}), '(bgcolor=(1, 1, 1), size=(1000, 800))\n', (31705, 31742), False, 'from mayavi import mlab\n'), ((34679, 34749), 'mayavi.mlab.triangular_mesh', 'mlab.triangular_mesh', (['x', 'y', 'z', 'triangles'], {'color': '(1, 0, 1)', 'opacity': '(0.2)'}), '(x, y, z, triangles, color=(1, 0, 1), opacity=0.2)\n', (34699, 34749), False, 'from mayavi import mlab\n'), ((34763, 34809), 'mayavi.mlab.title', 'mlab.title', (['"""cloud"""'], {'size': '(0.3)', 'color': '(0, 0, 0)'}), "('cloud', size=0.3, color=(0, 0, 0))\n", (34773, 34809), False, 'from mayavi import mlab\n'), ((34822, 34833), 'mayavi.mlab.show', 'mlab.show', ([], {}), '()\n', (34831, 34833), False, 'from mayavi import mlab\n'), ((37413, 37456), 'numpy.array', 'np.array', (['[x_coord_r, y_coord_r, z_coord_r]'], {}), '([x_coord_r, y_coord_r, z_coord_r])\n', (37421, 37456), True, 'import numpy as np\n'), ((38382, 38422), 'numpy.sum', 'np.sum', (['feature_buffer[..., -3:]'], {'axis': '(1)'}), '(feature_buffer[..., -3:], axis=1)\n', (38388, 38422), True, 'import numpy as np\n'), ((39603, 39620), 'numpy.sum', 'np.sum', (['bad_check'], {}), '(bad_check)\n', (39609, 39620), True, 'import numpy as np\n'), ((39649, 39676), 'numpy.where', 'np.where', (['(bad_check == True)'], {}), '(bad_check == True)\n', (39657, 39676), True, 'import numpy as np\n'), ((39700, 39739), 'numpy.delete', 'np.delete', (['grasp_pc', 'bad_ind[0]'], {'axis': '(0)'}), '(grasp_pc, bad_ind[0], axis=0)\n', (39709, 39739), True, 'import numpy as np\n'), ((39768, 39812), 'numpy.delete', 'np.delete', (['grasp_pc_norm', 'bad_ind[0]'], {'axis': '(0)'}), '(grasp_pc_norm, bad_ind[0], axis=0)\n', (39777, 39812), True, 'import numpy as np\n'), ((39828, 39866), 'numpy.sum', 'np.sum', (['(grasp_pc_norm != grasp_pc_norm)'], {}), '(grasp_pc_norm != grasp_pc_norm)\n', (39834, 39866), True, 'import numpy as np\n'), ((41383, 41399), 'numpy.load', 'np.load', (['f_grasp'], {}), '(f_grasp)\n', (41390, 41399), True, 'import numpy as np\n'), ((44140, 44190), 'os.path.join', 'os.path.join', (['path', '"""ycb_grasp"""', 'self.tag', '"""*.npy"""'], {}), "(path, 'ycb_grasp', self.tag, '*.npy')\n", (44152, 44190), False, 'import os\n'), ((44218, 44282), 'os.path.join', 'os.path.join', (['path', '"""ycb_rgbd"""', '"""*"""', '"""clouds"""', '"""pc_NP3_NP5*.npy"""'], {}), "(path, 'ycb_rgbd', '*', 'clouds', 'pc_NP3_NP5*.npy')\n", (44230, 44282), False, 'import os\n'), ((45086, 45106), 'numpy.linalg.norm', 'np.linalg.norm', (['axis'], {}), '(axis)\n', (45100, 45106), True, 'import numpy as np\n'), ((45368, 45390), 'numpy.linalg.norm', 'np.linalg.norm', (['axis_x'], {}), '(axis_x)\n', (45382, 45390), True, 'import numpy as np\n'), ((45418, 45437), 'numpy.array', 'np.array', (['[1, 0, 0]'], {}), '([1, 0, 0])\n', (45426, 45437), True, 'import numpy as np\n'), ((45464, 45486), 'numpy.linalg.norm', 'np.linalg.norm', (['axis_x'], {}), '(axis_x)\n', (45478, 45486), True, 'import numpy as np\n'), ((45513, 45535), 'numpy.linalg.norm', 'np.linalg.norm', (['axis_y'], {}), '(axis_y)\n', (45527, 45535), True, 'import numpy as np\n'), ((45694, 45718), 'numpy.linalg.norm', 'np.linalg.norm', (['approach'], {}), '(approach)\n', (45708, 45718), True, 'import numpy as np\n'), ((46464, 46509), 'numpy.hstack', 'np.hstack', (['[approach, binormal, minor_normal]'], {}), '([approach, binormal, minor_normal])\n', (46473, 46509), True, 'import numpy as np\n'), ((46530, 46561), 'numpy.dot', 'np.dot', (['matrix', '(pc - center).T'], {}), '(matrix, (pc - center).T)\n', (46536, 46561), True, 'import numpy as np\n'), ((49494, 49537), 'numpy.array', 'np.array', (['[x_coord_r, y_coord_r, z_coord_r]'], {}), '([x_coord_r, y_coord_r, z_coord_r])\n', (49502, 49537), True, 'import numpy as np\n'), ((50463, 50503), 'numpy.sum', 'np.sum', (['feature_buffer[..., -3:]'], {'axis': '(1)'}), '(feature_buffer[..., -3:], axis=1)\n', (50469, 50503), True, 'import numpy as np\n'), ((51661, 51678), 'numpy.sum', 'np.sum', (['bad_check'], {}), '(bad_check)\n', (51667, 51678), True, 'import numpy as np\n'), ((51705, 51732), 'numpy.where', 'np.where', (['(bad_check == True)'], {}), '(bad_check == True)\n', (51713, 51732), True, 'import numpy as np\n'), ((51756, 51795), 'numpy.delete', 'np.delete', (['grasp_pc', 'bad_ind[0]'], {'axis': '(0)'}), '(grasp_pc, bad_ind[0], axis=0)\n', (51765, 51795), True, 'import numpy as np\n'), ((51824, 51868), 'numpy.delete', 'np.delete', (['grasp_pc_norm', 'bad_ind[0]'], {'axis': '(0)'}), '(grasp_pc_norm, bad_ind[0], axis=0)\n', (51833, 51868), True, 'import numpy as np\n'), ((51884, 51922), 'numpy.sum', 'np.sum', (['(grasp_pc_norm != grasp_pc_norm)'], {}), '(grasp_pc_norm != grasp_pc_norm)\n', (51890, 51922), True, 'import numpy as np\n'), ((53333, 53349), 'numpy.load', 'np.load', (['f_grasp'], {}), '(f_grasp)\n', (53340, 53349), True, 'import numpy as np\n'), ((55450, 55540), 'mayavi.mlab.points3d', 'mlab.points3d', (['point[0]', 'point[1]', 'point[2]'], {'color': 'color_f', 'scale_factor': 'scale_factor'}), '(point[0], point[1], point[2], color=color_f, scale_factor=\n scale_factor)\n', (55463, 55540), False, 'from mayavi import mlab\n'), ((55589, 55687), 'mayavi.mlab.points3d', 'mlab.points3d', (['point[:, 0]', 'point[:, 1]', 'point[:, 2]'], {'color': 'color_f', 'scale_factor': 'scale_factor'}), '(point[:, 0], point[:, 1], point[:, 2], color=color_f,\n scale_factor=scale_factor)\n', (55602, 55687), False, 'from mayavi import mlab\n'), ((1677, 1720), 'os.path.join', 'os.path.join', (['self.path', '"""google2cloud.pkl"""'], {}), "(self.path, 'google2cloud.pkl')\n", (1689, 1720), False, 'import os\n'), ((3461, 3501), 'numpy.array', 'np.array', (['[left[0], left[1], left[2], 1]'], {}), '([left[0], left[1], left[2], 1])\n', (3469, 3501), True, 'import numpy as np\n'), ((3543, 3586), 'numpy.array', 'np.array', (['[right[0], right[1], right[2], 1]'], {}), '([right[0], right[1], right[2], 1])\n', (3551, 3586), True, 'import numpy as np\n'), ((3713, 3759), 'numpy.array', 'np.array', (['[center[0], center[1], center[2], 1]'], {}), '([center[0], center[1], center[2], 1])\n', (3721, 3759), True, 'import numpy as np\n'), ((7131, 7150), 'numpy.floor', 'np.floor', (['x_coord_r'], {}), '(x_coord_r)\n', (7139, 7150), True, 'import numpy as np\n'), ((7183, 7202), 'numpy.floor', 'np.floor', (['y_coord_r'], {}), '(y_coord_r)\n', (7191, 7202), True, 'import numpy as np\n'), ((7235, 7254), 'numpy.floor', 'np.floor', (['z_coord_r'], {}), '(z_coord_r)\n', (7243, 7254), True, 'import numpy as np\n'), ((10146, 10165), 'numpy.array', 'np.array', (['[1, 2, 0]'], {}), '([1, 2, 0])\n', (10154, 10165), True, 'import numpy as np\n'), ((10371, 10390), 'numpy.array', 'np.array', (['[0, 2, 1]'], {}), '([0, 2, 1])\n', (10379, 10390), True, 'import numpy as np\n'), ((10593, 10680), 'numpy.dstack', 'np.dstack', (['[occupy_pic1, norm_pic1, occupy_pic2, norm_pic2, occupy_pic3, norm_pic3]'], {}), '([occupy_pic1, norm_pic1, occupy_pic2, norm_pic2, occupy_pic3,\n norm_pic3])\n', (10602, 10680), True, 'import numpy as np\n'), ((11225, 11235), 'numpy.load', 'np.load', (['i'], {}), '(i)\n', (11232, 11235), True, 'import numpy as np\n'), ((13523, 13566), 'os.path.join', 'os.path.join', (['self.path', '"""google2cloud.pkl"""'], {}), "(self.path, 'google2cloud.pkl')\n", (13535, 13566), False, 'import os\n'), ((15307, 15347), 'numpy.array', 'np.array', (['[left[0], left[1], left[2], 1]'], {}), '([left[0], left[1], left[2], 1])\n', (15315, 15347), True, 'import numpy as np\n'), ((15389, 15432), 'numpy.array', 'np.array', (['[right[0], right[1], right[2], 1]'], {}), '([right[0], right[1], right[2], 1])\n', (15397, 15432), True, 'import numpy as np\n'), ((15559, 15605), 'numpy.array', 'np.array', (['[center[0], center[1], center[2], 1]'], {}), '([center[0], center[1], center[2], 1])\n', (15567, 15605), True, 'import numpy as np\n'), ((18977, 18996), 'numpy.floor', 'np.floor', (['x_coord_r'], {}), '(x_coord_r)\n', (18985, 18996), True, 'import numpy as np\n'), ((19029, 19048), 'numpy.floor', 'np.floor', (['y_coord_r'], {}), '(y_coord_r)\n', (19037, 19048), True, 'import numpy as np\n'), ((19081, 19100), 'numpy.floor', 'np.floor', (['z_coord_r'], {}), '(z_coord_r)\n', (19089, 19100), True, 'import numpy as np\n'), ((21992, 22011), 'numpy.array', 'np.array', (['[1, 2, 0]'], {}), '([1, 2, 0])\n', (22000, 22011), True, 'import numpy as np\n'), ((22217, 22236), 'numpy.array', 'np.array', (['[0, 2, 1]'], {}), '([0, 2, 1])\n', (22225, 22236), True, 'import numpy as np\n'), ((22439, 22526), 'numpy.dstack', 'np.dstack', (['[occupy_pic1, norm_pic1, occupy_pic2, norm_pic2, occupy_pic3, norm_pic3]'], {}), '([occupy_pic1, norm_pic1, occupy_pic2, norm_pic2, occupy_pic3,\n norm_pic3])\n', (22448, 22526), True, 'import numpy as np\n'), ((23071, 23081), 'numpy.load', 'np.load', (['i'], {}), '(i)\n', (23078, 23081), True, 'import numpy as np\n'), ((25321, 25364), 'os.path.join', 'os.path.join', (['self.path', '"""google2cloud.pkl"""'], {}), "(self.path, 'google2cloud.pkl')\n", (25333, 25364), False, 'import os\n'), ((28605, 28747), 'mayavi.mlab.pipeline.open', 'mlab.pipeline.open', (['"""/home/sdhm/Projects/PointNetGPD/PointNetGPD/data/ycb_meshes_google/003_cracker_box/google_512k/nontextured.ply"""'], {}), "(\n '/home/sdhm/Projects/PointNetGPD/PointNetGPD/data/ycb_meshes_google/003_cracker_box/google_512k/nontextured.ply'\n )\n", (28623, 28747), False, 'from mayavi import mlab\n'), ((30019, 30059), 'numpy.array', 'np.array', (['[left[0], left[1], left[2], 1]'], {}), '([left[0], left[1], left[2], 1])\n', (30027, 30059), True, 'import numpy as np\n'), ((30101, 30144), 'numpy.array', 'np.array', (['[right[0], right[1], right[2], 1]'], {}), '([right[0], right[1], right[2], 1])\n', (30109, 30144), True, 'import numpy as np\n'), ((31777, 31919), 'mayavi.mlab.pipeline.open', 'mlab.pipeline.open', (['"""/home/sdhm/Projects/PointNetGPD/PointNetGPD/data/ycb_meshes_google/003_cracker_box/google_512k/nontextured.ply"""'], {}), "(\n '/home/sdhm/Projects/PointNetGPD/PointNetGPD/data/ycb_meshes_google/003_cracker_box/google_512k/nontextured.ply'\n )\n", (31795, 31919), False, 'from mayavi import mlab\n'), ((32849, 32893), 'numpy.dot', 'np.dot', (['matrix_m2c', '(hand_points - center).T'], {}), '(matrix_m2c, (hand_points - center).T)\n', (32855, 32893), True, 'import numpy as np\n'), ((34124, 34162), 'numpy.array', 'np.array', (['[-1, 1, 1, -1, -1, 1, 1, -1]'], {}), '([-1, 1, 1, -1, -1, 1, 1, -1])\n', (34132, 34162), True, 'import numpy as np\n'), ((34185, 34223), 'numpy.array', 'np.array', (['[-1, -1, 1, 1, -1, -1, 1, 1]'], {}), '([-1, -1, 1, 1, -1, -1, 1, 1])\n', (34193, 34223), True, 'import numpy as np\n'), ((34246, 34284), 'numpy.array', 'np.array', (['[-1, -1, -1, -1, 1, 1, 1, 1]'], {}), '([-1, -1, -1, -1, 1, 1, 1, 1])\n', (34254, 34284), True, 'import numpy as np\n'), ((37255, 37274), 'numpy.floor', 'np.floor', (['x_coord_r'], {}), '(x_coord_r)\n', (37263, 37274), True, 'import numpy as np\n'), ((37307, 37326), 'numpy.floor', 'np.floor', (['y_coord_r'], {}), '(y_coord_r)\n', (37315, 37326), True, 'import numpy as np\n'), ((37359, 37378), 'numpy.floor', 'np.floor', (['z_coord_r'], {}), '(z_coord_r)\n', (37367, 37378), True, 'import numpy as np\n'), ((40309, 40328), 'numpy.array', 'np.array', (['[1, 2, 0]'], {}), '([1, 2, 0])\n', (40317, 40328), True, 'import numpy as np\n'), ((40544, 40563), 'numpy.array', 'np.array', (['[0, 2, 1]'], {}), '([0, 2, 1])\n', (40552, 40563), True, 'import numpy as np\n'), ((40776, 40863), 'numpy.dstack', 'np.dstack', (['[occupy_pic1, norm_pic1, occupy_pic2, norm_pic2, occupy_pic3, norm_pic3]'], {}), '([occupy_pic1, norm_pic1, occupy_pic2, norm_pic2, occupy_pic3,\n norm_pic3])\n', (40785, 40863), True, 'import numpy as np\n'), ((44059, 44102), 'os.path.join', 'os.path.join', (['self.path', '"""google2cloud.pkl"""'], {}), "(self.path, 'google2cloud.pkl')\n", (44071, 44102), False, 'import os\n'), ((45877, 45917), 'numpy.array', 'np.array', (['[left[0], left[1], left[2], 1]'], {}), '([left[0], left[1], left[2], 1])\n', (45885, 45917), True, 'import numpy as np\n'), ((45959, 46002), 'numpy.array', 'np.array', (['[right[0], right[1], right[2], 1]'], {}), '([right[0], right[1], right[2], 1])\n', (45967, 46002), True, 'import numpy as np\n'), ((46045, 46091), 'numpy.array', 'np.array', (['[center[0], center[1], center[2], 1]'], {}), '([center[0], center[1], center[2], 1])\n', (46053, 46091), True, 'import numpy as np\n'), ((49336, 49355), 'numpy.floor', 'np.floor', (['x_coord_r'], {}), '(x_coord_r)\n', (49344, 49355), True, 'import numpy as np\n'), ((49388, 49407), 'numpy.floor', 'np.floor', (['y_coord_r'], {}), '(y_coord_r)\n', (49396, 49407), True, 'import numpy as np\n'), ((49440, 49459), 'numpy.floor', 'np.floor', (['z_coord_r'], {}), '(z_coord_r)\n', (49448, 49459), True, 'import numpy as np\n'), ((52351, 52370), 'numpy.array', 'np.array', (['[1, 2, 0]'], {}), '([1, 2, 0])\n', (52359, 52370), True, 'import numpy as np\n'), ((52576, 52595), 'numpy.array', 'np.array', (['[0, 2, 1]'], {}), '([0, 2, 1])\n', (52584, 52595), True, 'import numpy as np\n'), ((52798, 52885), 'numpy.dstack', 'np.dstack', (['[occupy_pic1, norm_pic1, occupy_pic2, norm_pic2, occupy_pic3, norm_pic3]'], {}), '([occupy_pic1, norm_pic1, occupy_pic2, norm_pic2, occupy_pic3,\n norm_pic3])\n', (52807, 52885), True, 'import numpy as np\n'), ((54741, 54761), 'torch.initial_seed', 'torch.initial_seed', ([], {}), '()\n', (54759, 54761), False, 'import torch\n'), ((4857, 4874), 'numpy.sum', 'np.sum', (['a'], {'axis': '(0)'}), '(a, axis=0)\n', (4863, 4874), True, 'import numpy as np\n'), ((5685, 5702), 'numpy.sum', 'np.sum', (['a'], {'axis': '(0)'}), '(a, axis=0)\n', (5691, 5702), True, 'import numpy as np\n'), ((16703, 16720), 'numpy.sum', 'np.sum', (['a'], {'axis': '(0)'}), '(a, axis=0)\n', (16709, 16720), True, 'import numpy as np\n'), ((17531, 17548), 'numpy.sum', 'np.sum', (['a'], {'axis': '(0)'}), '(a, axis=0)\n', (17537, 17548), True, 'import numpy as np\n'), ((31408, 31425), 'numpy.sum', 'np.sum', (['a'], {'axis': '(0)'}), '(a, axis=0)\n', (31414, 31425), True, 'import numpy as np\n'), ((33600, 33643), 'numpy.dot', 'np.dot', (['matrix_m2c.T', 'pc_m2c[self.in_ind].T'], {}), '(matrix_m2c.T, pc_m2c[self.in_ind].T)\n', (33606, 33643), True, 'import numpy as np\n'), ((35582, 35599), 'numpy.sum', 'np.sum', (['a'], {'axis': '(0)'}), '(a, axis=0)\n', (35588, 35599), True, 'import numpy as np\n'), ((47062, 47079), 'numpy.sum', 'np.sum', (['a'], {'axis': '(0)'}), '(a, axis=0)\n', (47068, 47079), True, 'import numpy as np\n'), ((47890, 47907), 'numpy.sum', 'np.sum', (['a'], {'axis': '(0)'}), '(a, axis=0)\n', (47896, 47907), True, 'import numpy as np\n'), ((3804, 3856), 'numpy.array', 'np.array', (['[binormal[0], binormal[1], binormal[2], 1]'], {}), '([binormal[0], binormal[1], binormal[2], 1])\n', (3812, 3856), True, 'import numpy as np\n'), ((3915, 3967), 'numpy.array', 'np.array', (['[approach[0], approach[1], approach[2], 1]'], {}), '([approach[0], approach[1], approach[2], 1])\n', (3923, 3967), True, 'import numpy as np\n'), ((4030, 4094), 'numpy.array', 'np.array', (['[minor_normal[0], minor_normal[1], minor_normal[2], 1]'], {}), '([minor_normal[0], minor_normal[1], minor_normal[2], 1])\n', (4038, 4094), True, 'import numpy as np\n'), ((4385, 4404), 'numpy.array', 'np.array', (['[0, 1, 0]'], {}), '([0, 1, 0])\n', (4393, 4404), True, 'import numpy as np\n'), ((4445, 4464), 'numpy.array', 'np.array', (['[0, 1, 0]'], {}), '([0, 1, 0])\n', (4453, 4464), True, 'import numpy as np\n'), ((15650, 15702), 'numpy.array', 'np.array', (['[binormal[0], binormal[1], binormal[2], 1]'], {}), '([binormal[0], binormal[1], binormal[2], 1])\n', (15658, 15702), True, 'import numpy as np\n'), ((15761, 15813), 'numpy.array', 'np.array', (['[approach[0], approach[1], approach[2], 1]'], {}), '([approach[0], approach[1], approach[2], 1])\n', (15769, 15813), True, 'import numpy as np\n'), ((15876, 15940), 'numpy.array', 'np.array', (['[minor_normal[0], minor_normal[1], minor_normal[2], 1]'], {}), '([minor_normal[0], minor_normal[1], minor_normal[2], 1])\n', (15884, 15940), True, 'import numpy as np\n'), ((16231, 16250), 'numpy.array', 'np.array', (['[0, 1, 0]'], {}), '([0, 1, 0])\n', (16239, 16250), True, 'import numpy as np\n'), ((16291, 16310), 'numpy.array', 'np.array', (['[0, 1, 0]'], {}), '([0, 1, 0])\n', (16299, 16310), True, 'import numpy as np\n'), ((30879, 30898), 'numpy.array', 'np.array', (['[0, 1, 0]'], {}), '([0, 1, 0])\n', (30887, 30898), True, 'import numpy as np\n'), ((30941, 30960), 'numpy.array', 'np.array', (['[0, 1, 0]'], {}), '([0, 1, 0])\n', (30949, 30960), True, 'import numpy as np\n'), ((46136, 46188), 'numpy.array', 'np.array', (['[binormal[0], binormal[1], binormal[2], 1]'], {}), '([binormal[0], binormal[1], binormal[2], 1])\n', (46144, 46188), True, 'import numpy as np\n'), ((46247, 46299), 'numpy.array', 'np.array', (['[approach[0], approach[1], approach[2], 1]'], {}), '([approach[0], approach[1], approach[2], 1])\n', (46255, 46299), True, 'import numpy as np\n'), ((46362, 46426), 'numpy.array', 'np.array', (['[minor_normal[0], minor_normal[1], minor_normal[2], 1]'], {}), '([minor_normal[0], minor_normal[1], minor_normal[2], 1])\n', (46370, 46426), True, 'import numpy as np\n'), ((46590, 46609), 'numpy.array', 'np.array', (['[0, 1, 0]'], {}), '([0, 1, 0])\n', (46598, 46609), True, 'import numpy as np\n'), ((46650, 46669), 'numpy.array', 'np.array', (['[0, 1, 0]'], {}), '([0, 1, 0])\n', (46658, 46669), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
import pytest
from django.core.urlresolvers import reverse
from pontoon.administration.forms import (
ProjectForm,
)
from pontoon.administration.views import _create_or_update_translated_resources
from pontoon.base.models import (
Entity,
Locale,
Project,
ProjectLocale,
Resource,
TranslatedResource,
)
from pontoon.test.factories import (
EntityFactory,
LocaleFactory,
ProjectFactory,
ResourceFactory,
TranslationFactory,
UserFactory,
)
@pytest.mark.django_db
def test_manage_project_strings(client):
project = ProjectFactory.create(data_source='database', repositories=[])
url = reverse('pontoon.admin.project.strings', args=(project.slug,))
# Test with anonymous user.
response = client.get(url)
assert response.status_code == 403
# Test with a user that is not a superuser.
user = UserFactory.create()
client.force_login(user)
response = client.get(url)
assert response.status_code == 403
# Test with a superuser.
user.is_superuser = True
user.save()
response = client.get(url)
assert response.status_code == 200
@pytest.mark.django_db
def test_manage_project(client_superuser):
url = reverse('pontoon.admin.project.new')
response = client_superuser.get(url)
assert response.status_code == 200
@pytest.mark.django_db
def test_manage_project_strings_bad_request(client_superuser):
# Tets an unknown project returns a 404 error.
url = reverse('pontoon.admin.project.strings', args=('unknown',))
response = client_superuser.get(url)
assert response.status_code == 404
@pytest.mark.django_db
def test_manage_project_strings_new(client_superuser, locale_a):
project = ProjectFactory.create(
data_source='database',
repositories=[],
locales=[locale_a],
)
url = reverse('pontoon.admin.project.strings', args=(project.slug,))
# Test sending a well-formatted batch of strings.
new_strings = """Hey, I just met you
And this is crazy
But here's my number
So call me maybe?
"""
response = client_superuser.post(url, {'new_strings': new_strings})
assert response.status_code == 200
# Verify a resource has been created.
resources = list(Resource.objects.filter(project=project))
assert len(resources) == 1
assert resources[0].path == 'database'
# Verify all strings have been created as entities.
entities = Entity.for_project_locale(project, locale_a)
assert len(entities) == 4
expected_strings = [
'Hey, I just met you',
'And this is crazy',
'But here\'s my number',
'So call me maybe?',
]
assert expected_strings == [x.string for x in entities]
# Verify strings have the correct order.
for index, entity in enumerate(entities):
assert entity.order == index
# Verify new strings appear on the page.
assert 'Hey, I just met you' in response.content
@pytest.mark.django_db
def test_manage_project_strings_translated_resource(client_superuser):
"""Test that adding new strings to a project enables translation of that
project on all enabled locales.
"""
locales = [
LocaleFactory.create(code='kl', name='Klingon'),
LocaleFactory.create(code='gs', name='Geonosian'),
]
project = ProjectFactory.create(
data_source='database',
locales=locales,
repositories=[]
)
locales_count = len(locales)
_create_or_update_translated_resources(project, locales)
url = reverse('pontoon.admin.project.strings', args=(project.slug,))
new_strings = """
Morty, do you know what "Wubba lubba dub dub" means?
Oh that's just Rick's stupid non-sense catch phrase.
It's not.
In my people's tongue, it means "I am in great pain, please help me".
"""
strings_count = 4
response = client_superuser.post(url, {'new_strings': new_strings})
assert response.status_code == 200
# Verify no strings have been created as entities.
entities = list(Entity.objects.filter(resource__project=project))
assert len(entities) == strings_count
# Verify the resource has the right stats.
resources = Resource.objects.filter(project=project)
assert len(resources) == 1
resource = resources[0]
assert resource.total_strings == strings_count
# Verify the correct TranslatedResource objects have been created.
translated_resources = TranslatedResource.objects.filter(resource__project=project)
assert len(translated_resources) == locales_count
# Verify stats have been correctly updated on locale, project and resource.
for tr in translated_resources:
assert tr.total_strings == strings_count
project = Project.objects.get(id=project.id)
assert project.total_strings == strings_count * locales_count
for l in locales:
locale = Locale.objects.get(id=l.id)
assert locale.total_strings == strings_count
@pytest.mark.django_db
def test_manage_project_strings_new_all_empty(client_superuser):
"""Test that sending empty data doesn't create empty strings in the database.
"""
project = ProjectFactory.create(data_source='database', repositories=[])
url = reverse('pontoon.admin.project.strings', args=(project.slug,))
# Test sending an empty batch of strings.
new_strings = " \n \n\n"
response = client_superuser.post(url, {'new_strings': new_strings})
assert response.status_code == 200
# Verify no strings have been created as entities.
entities = list(Entity.objects.filter(resource__project=project))
assert len(entities) == 0
@pytest.mark.django_db
def test_manage_project_strings_list(client_superuser):
project = ProjectFactory.create(data_source='database', repositories=[])
resource = ResourceFactory.create(project=project)
nb_entities = 2
entities = EntityFactory.create_batch(nb_entities, resource=resource)
url = reverse('pontoon.admin.project.strings', args=(project.slug,))
response = client_superuser.get(url)
assert response.status_code == 200
for i in range(nb_entities):
assert 'string %s' % i in response.content
# Test editing strings and comments.
form_data = {
'form-TOTAL_FORMS': nb_entities,
'form-INITIAL_FORMS': nb_entities,
'form-MIN_NUM_FORMS': 0,
'form-MAX_NUM_FORMS': 1000,
'form-0-id': entities[0].id,
'form-0-string': 'changed 0',
'form-0-comment': 'Wubba lubba dub dub',
'form-1-id': entities[1].id,
'form-1-string': 'string 1',
'form-1-obsolete': 'on', # Remove this one.
}
response = client_superuser.post(url, form_data)
assert response.status_code == 200
assert 'changed 0' in response.content
assert 'Wubba lubba dub dub' in response.content
assert 'string 0' not in response.content
assert 'string 1' not in response.content # It's been removed.
total = Entity.objects.filter(
resource=resource, obsolete=False,
).count()
assert total == nb_entities - 1
# Test adding a new string.
form_data = {
'form-TOTAL_FORMS': nb_entities,
'form-INITIAL_FORMS': nb_entities - 1,
'form-MIN_NUM_FORMS': 0,
'form-MAX_NUM_FORMS': 1000,
'form-0-id': entities[0].id,
'form-0-string': 'changed 0',
'form-0-comment': 'Wubba lubba dub dub',
'form-1-id': '',
'form-1-string': 'new string',
'form-1-comment': 'adding this entity now',
}
response = client_superuser.post(url, form_data)
assert response.status_code == 200
assert 'changed 0' in response.content
assert 'new string' in response.content
assert 'adding this entity now' in response.content
total = Entity.objects.filter(
resource=resource, obsolete=False,
).count()
assert total == nb_entities
# Verify the new string has the correct order.
new_string = Entity.objects.filter(
resource=resource, obsolete=False, string='new string',
).first()
# The highest order before adding new string was 0,
# so the order of that new one should be 1.
assert new_string.order == 1
@pytest.mark.django_db
def test_manage_project_strings_download_csv(client_superuser):
locale_kl = LocaleFactory.create(code='kl', name='Klingon')
locale_gs = LocaleFactory.create(code='gs', name='Geonosian')
project = ProjectFactory.create(
data_source='database',
locales=[locale_kl, locale_gs],
repositories=[]
)
url = reverse('pontoon.admin.project.strings', args=(project.slug,))
new_strings = """
And on the pedestal these words appear:
'My name is Ozymandias, king of kings:
Look on my works, ye Mighty, and despair!'
"""
response = client_superuser.post(url, {'new_strings': new_strings})
assert response.status_code == 200
# Test downloading the data.
response = client_superuser.get(url, {'format': 'csv'})
assert response.status_code == 200
assert response._headers['content-type'] == ('Content-Type', 'text/csv')
# Verify the original content is here.
assert 'pedestal' in response.content
assert 'Ozymandias' in response.content
assert 'Mighty' in response.content
# Verify we have the locale columns.
assert 'kl' in response.content
assert 'gs' in response.content
# Now add some translations.
entity = Entity.objects.filter(string='And on the pedestal these words appear:')[0]
TranslationFactory.create(
string='Et sur le piédestal il y a ces mots :',
entity=entity,
locale=locale_kl,
approved=True,
)
TranslationFactory.create(
string='Und auf dem Sockel steht die Schrift: ‚Mein Name',
entity=entity,
locale=locale_gs,
approved=True,
)
entity = Entity.objects.filter(string='\'My name is Ozymandias, king of kings:')[0]
TranslationFactory.create(
string='"Mon nom est Ozymandias, Roi des Rois.',
entity=entity,
locale=locale_kl,
approved=True,
)
TranslationFactory.create(
string='Ist Osymandias, aller Kön’ge König: –',
entity=entity,
locale=locale_gs,
approved=True,
)
entity = Entity.objects.filter(string='Look on my works, ye Mighty, and despair!\'')[0]
TranslationFactory.create(
string='Voyez mon œuvre, vous puissants, et désespérez !"',
entity=entity,
locale=locale_kl,
approved=True,
)
TranslationFactory.create(
string='Seht meine Werke, Mächt’ge, und erbebt!‘',
entity=entity,
locale=locale_gs,
approved=True,
)
response = client_superuser.get(url, {'format': 'csv'})
# Verify the translated content is here.
assert 'pedestal' in response.content
assert 'piédestal' in response.content
assert 'Sockel' in response.content
assert 'Mighty' in response.content
assert 'puissants' in response.content
assert 'Mächt’ge' in response.content
@pytest.mark.django_db
def test_project_add_locale(client_superuser):
locale_kl = LocaleFactory.create(code='kl', name='Klingon')
locale_gs = LocaleFactory.create(code='gs', name='Geonosian')
project = ProjectFactory.create(
data_source='database',
locales=[locale_kl],
repositories=[],
)
_create_or_update_translated_resources(project, [locale_kl])
url = reverse('pontoon.admin.project', args=(project.slug,))
# Boring data creation for FormSets. Django is painful with that,
# or I don't know how to handle that more gracefully.
form = ProjectForm(instance=project)
form_data = dict(form.initial)
del form_data['width']
del form_data['deadline']
del form_data['contact']
form_data.update({
'subpage_set-INITIAL_FORMS': '0',
'subpage_set-TOTAL_FORMS': '1',
'subpage_set-MIN_NUM_FORMS': '0',
'subpage_set-MAX_NUM_FORMS': '1000',
'externalresource_set-TOTAL_FORMS': '1',
'externalresource_set-MAX_NUM_FORMS': '1000',
'externalresource_set-MIN_NUM_FORMS': '0',
'externalresource_set-INITIAL_FORMS': '0',
'tag_set-TOTAL_FORMS': '1',
'tag_set-INITIAL_FORMS': '0',
'tag_set-MAX_NUM_FORMS': '1000',
'tag_set-MIN_NUM_FORMS': '0',
'repositories-INITIAL_FORMS': '0',
'repositories-MIN_NUM_FORMS': '0',
'repositories-MAX_NUM_FORMS': '1000',
'repositories-TOTAL_FORMS': '0',
# These are the values that actually matter.
'pk': project.pk,
'locales': [locale_kl.id, locale_gs.id],
})
response = client_superuser.post(url, form_data)
assert response.status_code == 200
assert '. Error.' not in response.content
# Verify we have the right ProjectLocale objects.
pl = ProjectLocale.objects.filter(project=project)
assert len(pl) == 2
# Verify that TranslatedResource objects have been created.
resource = Resource.objects.get(project=project, path='database')
tr = TranslatedResource.objects.filter(resource=resource)
assert len(tr) == 2
| [
"pontoon.test.factories.LocaleFactory.create",
"pontoon.test.factories.TranslationFactory.create",
"pontoon.administration.views._create_or_update_translated_resources",
"pontoon.base.models.Project.objects.get",
"pontoon.test.factories.UserFactory.create",
"pontoon.base.models.Entity.for_project_locale",... | [((597, 659), 'pontoon.test.factories.ProjectFactory.create', 'ProjectFactory.create', ([], {'data_source': '"""database"""', 'repositories': '[]'}), "(data_source='database', repositories=[])\n", (618, 659), False, 'from pontoon.test.factories import EntityFactory, LocaleFactory, ProjectFactory, ResourceFactory, TranslationFactory, UserFactory\n'), ((670, 732), 'django.core.urlresolvers.reverse', 'reverse', (['"""pontoon.admin.project.strings"""'], {'args': '(project.slug,)'}), "('pontoon.admin.project.strings', args=(project.slug,))\n", (677, 732), False, 'from django.core.urlresolvers import reverse\n'), ((896, 916), 'pontoon.test.factories.UserFactory.create', 'UserFactory.create', ([], {}), '()\n', (914, 916), False, 'from pontoon.test.factories import EntityFactory, LocaleFactory, ProjectFactory, ResourceFactory, TranslationFactory, UserFactory\n'), ((1241, 1277), 'django.core.urlresolvers.reverse', 'reverse', (['"""pontoon.admin.project.new"""'], {}), "('pontoon.admin.project.new')\n", (1248, 1277), False, 'from django.core.urlresolvers import reverse\n'), ((1507, 1566), 'django.core.urlresolvers.reverse', 'reverse', (['"""pontoon.admin.project.strings"""'], {'args': "('unknown',)"}), "('pontoon.admin.project.strings', args=('unknown',))\n", (1514, 1566), False, 'from django.core.urlresolvers import reverse\n'), ((1751, 1838), 'pontoon.test.factories.ProjectFactory.create', 'ProjectFactory.create', ([], {'data_source': '"""database"""', 'repositories': '[]', 'locales': '[locale_a]'}), "(data_source='database', repositories=[], locales=[\n locale_a])\n", (1772, 1838), False, 'from pontoon.test.factories import EntityFactory, LocaleFactory, ProjectFactory, ResourceFactory, TranslationFactory, UserFactory\n'), ((1875, 1937), 'django.core.urlresolvers.reverse', 'reverse', (['"""pontoon.admin.project.strings"""'], {'args': '(project.slug,)'}), "('pontoon.admin.project.strings', args=(project.slug,))\n", (1882, 1937), False, 'from django.core.urlresolvers import reverse\n'), ((2487, 2531), 'pontoon.base.models.Entity.for_project_locale', 'Entity.for_project_locale', (['project', 'locale_a'], {}), '(project, locale_a)\n', (2512, 2531), False, 'from pontoon.base.models import Entity, Locale, Project, ProjectLocale, Resource, TranslatedResource\n'), ((3374, 3453), 'pontoon.test.factories.ProjectFactory.create', 'ProjectFactory.create', ([], {'data_source': '"""database"""', 'locales': 'locales', 'repositories': '[]'}), "(data_source='database', locales=locales, repositories=[])\n", (3395, 3453), False, 'from pontoon.test.factories import EntityFactory, LocaleFactory, ProjectFactory, ResourceFactory, TranslationFactory, UserFactory\n'), ((3521, 3577), 'pontoon.administration.views._create_or_update_translated_resources', '_create_or_update_translated_resources', (['project', 'locales'], {}), '(project, locales)\n', (3559, 3577), False, 'from pontoon.administration.views import _create_or_update_translated_resources\n'), ((3589, 3651), 'django.core.urlresolvers.reverse', 'reverse', (['"""pontoon.admin.project.strings"""'], {'args': '(project.slug,)'}), "('pontoon.admin.project.strings', args=(project.slug,))\n", (3596, 3651), False, 'from django.core.urlresolvers import reverse\n'), ((4266, 4306), 'pontoon.base.models.Resource.objects.filter', 'Resource.objects.filter', ([], {'project': 'project'}), '(project=project)\n', (4289, 4306), False, 'from pontoon.base.models import Entity, Locale, Project, ProjectLocale, Resource, TranslatedResource\n'), ((4516, 4576), 'pontoon.base.models.TranslatedResource.objects.filter', 'TranslatedResource.objects.filter', ([], {'resource__project': 'project'}), '(resource__project=project)\n', (4549, 4576), False, 'from pontoon.base.models import Entity, Locale, Project, ProjectLocale, Resource, TranslatedResource\n'), ((4812, 4846), 'pontoon.base.models.Project.objects.get', 'Project.objects.get', ([], {'id': 'project.id'}), '(id=project.id)\n', (4831, 4846), False, 'from pontoon.base.models import Entity, Locale, Project, ProjectLocale, Resource, TranslatedResource\n'), ((5228, 5290), 'pontoon.test.factories.ProjectFactory.create', 'ProjectFactory.create', ([], {'data_source': '"""database"""', 'repositories': '[]'}), "(data_source='database', repositories=[])\n", (5249, 5290), False, 'from pontoon.test.factories import EntityFactory, LocaleFactory, ProjectFactory, ResourceFactory, TranslationFactory, UserFactory\n'), ((5301, 5363), 'django.core.urlresolvers.reverse', 'reverse', (['"""pontoon.admin.project.strings"""'], {'args': '(project.slug,)'}), "('pontoon.admin.project.strings', args=(project.slug,))\n", (5308, 5363), False, 'from django.core.urlresolvers import reverse\n'), ((5805, 5867), 'pontoon.test.factories.ProjectFactory.create', 'ProjectFactory.create', ([], {'data_source': '"""database"""', 'repositories': '[]'}), "(data_source='database', repositories=[])\n", (5826, 5867), False, 'from pontoon.test.factories import EntityFactory, LocaleFactory, ProjectFactory, ResourceFactory, TranslationFactory, UserFactory\n'), ((5883, 5922), 'pontoon.test.factories.ResourceFactory.create', 'ResourceFactory.create', ([], {'project': 'project'}), '(project=project)\n', (5905, 5922), False, 'from pontoon.test.factories import EntityFactory, LocaleFactory, ProjectFactory, ResourceFactory, TranslationFactory, UserFactory\n'), ((5958, 6016), 'pontoon.test.factories.EntityFactory.create_batch', 'EntityFactory.create_batch', (['nb_entities'], {'resource': 'resource'}), '(nb_entities, resource=resource)\n', (5984, 6016), False, 'from pontoon.test.factories import EntityFactory, LocaleFactory, ProjectFactory, ResourceFactory, TranslationFactory, UserFactory\n'), ((6028, 6090), 'django.core.urlresolvers.reverse', 'reverse', (['"""pontoon.admin.project.strings"""'], {'args': '(project.slug,)'}), "('pontoon.admin.project.strings', args=(project.slug,))\n", (6035, 6090), False, 'from django.core.urlresolvers import reverse\n'), ((8385, 8432), 'pontoon.test.factories.LocaleFactory.create', 'LocaleFactory.create', ([], {'code': '"""kl"""', 'name': '"""Klingon"""'}), "(code='kl', name='Klingon')\n", (8405, 8432), False, 'from pontoon.test.factories import EntityFactory, LocaleFactory, ProjectFactory, ResourceFactory, TranslationFactory, UserFactory\n'), ((8449, 8498), 'pontoon.test.factories.LocaleFactory.create', 'LocaleFactory.create', ([], {'code': '"""gs"""', 'name': '"""Geonosian"""'}), "(code='gs', name='Geonosian')\n", (8469, 8498), False, 'from pontoon.test.factories import EntityFactory, LocaleFactory, ProjectFactory, ResourceFactory, TranslationFactory, UserFactory\n'), ((8513, 8612), 'pontoon.test.factories.ProjectFactory.create', 'ProjectFactory.create', ([], {'data_source': '"""database"""', 'locales': '[locale_kl, locale_gs]', 'repositories': '[]'}), "(data_source='database', locales=[locale_kl, locale_gs\n ], repositories=[])\n", (8534, 8612), False, 'from pontoon.test.factories import EntityFactory, LocaleFactory, ProjectFactory, ResourceFactory, TranslationFactory, UserFactory\n'), ((8649, 8711), 'django.core.urlresolvers.reverse', 'reverse', (['"""pontoon.admin.project.strings"""'], {'args': '(project.slug,)'}), "('pontoon.admin.project.strings', args=(project.slug,))\n", (8656, 8711), False, 'from django.core.urlresolvers import reverse\n'), ((9620, 9745), 'pontoon.test.factories.TranslationFactory.create', 'TranslationFactory.create', ([], {'string': '"""Et sur le piédestal il y a ces mots :"""', 'entity': 'entity', 'locale': 'locale_kl', 'approved': '(True)'}), "(string='Et sur le piédestal il y a ces mots :',\n entity=entity, locale=locale_kl, approved=True)\n", (9645, 9745), False, 'from pontoon.test.factories import EntityFactory, LocaleFactory, ProjectFactory, ResourceFactory, TranslationFactory, UserFactory\n'), ((9785, 9926), 'pontoon.test.factories.TranslationFactory.create', 'TranslationFactory.create', ([], {'string': '"""Und auf dem Sockel steht die Schrift: ‚Mein Name"""', 'entity': 'entity', 'locale': 'locale_gs', 'approved': '(True)'}), "(string=\n 'Und auf dem Sockel steht die Schrift: ‚Mein Name', entity=entity,\n locale=locale_gs, approved=True)\n", (9810, 9926), False, 'from pontoon.test.factories import EntityFactory, LocaleFactory, ProjectFactory, ResourceFactory, TranslationFactory, UserFactory\n'), ((10050, 10176), 'pontoon.test.factories.TranslationFactory.create', 'TranslationFactory.create', ([], {'string': '""""Mon nom est Ozymandias, Roi des Rois."""', 'entity': 'entity', 'locale': 'locale_kl', 'approved': '(True)'}), '(string=\'"Mon nom est Ozymandias, Roi des Rois.\',\n entity=entity, locale=locale_kl, approved=True)\n', (10075, 10176), False, 'from pontoon.test.factories import EntityFactory, LocaleFactory, ProjectFactory, ResourceFactory, TranslationFactory, UserFactory\n'), ((10216, 10341), 'pontoon.test.factories.TranslationFactory.create', 'TranslationFactory.create', ([], {'string': '"""Ist Osymandias, aller Kön’ge König: –"""', 'entity': 'entity', 'locale': 'locale_gs', 'approved': '(True)'}), "(string='Ist Osymandias, aller Kön’ge König: –',\n entity=entity, locale=locale_gs, approved=True)\n", (10241, 10341), False, 'from pontoon.test.factories import EntityFactory, LocaleFactory, ProjectFactory, ResourceFactory, TranslationFactory, UserFactory\n'), ((10474, 10616), 'pontoon.test.factories.TranslationFactory.create', 'TranslationFactory.create', ([], {'string': '"""Voyez mon œuvre, vous puissants, et désespérez !\\""""', 'entity': 'entity', 'locale': 'locale_kl', 'approved': '(True)'}), '(string=\n \'Voyez mon œuvre, vous puissants, et désespérez !"\', entity=entity,\n locale=locale_kl, approved=True)\n', (10499, 10616), False, 'from pontoon.test.factories import EntityFactory, LocaleFactory, ProjectFactory, ResourceFactory, TranslationFactory, UserFactory\n'), ((10651, 10779), 'pontoon.test.factories.TranslationFactory.create', 'TranslationFactory.create', ([], {'string': '"""Seht meine Werke, Mächt’ge, und erbebt!‘"""', 'entity': 'entity', 'locale': 'locale_gs', 'approved': '(True)'}), "(string='Seht meine Werke, Mächt’ge, und erbebt!‘',\n entity=entity, locale=locale_gs, approved=True)\n", (10676, 10779), False, 'from pontoon.test.factories import EntityFactory, LocaleFactory, ProjectFactory, ResourceFactory, TranslationFactory, UserFactory\n'), ((11261, 11308), 'pontoon.test.factories.LocaleFactory.create', 'LocaleFactory.create', ([], {'code': '"""kl"""', 'name': '"""Klingon"""'}), "(code='kl', name='Klingon')\n", (11281, 11308), False, 'from pontoon.test.factories import EntityFactory, LocaleFactory, ProjectFactory, ResourceFactory, TranslationFactory, UserFactory\n'), ((11325, 11374), 'pontoon.test.factories.LocaleFactory.create', 'LocaleFactory.create', ([], {'code': '"""gs"""', 'name': '"""Geonosian"""'}), "(code='gs', name='Geonosian')\n", (11345, 11374), False, 'from pontoon.test.factories import EntityFactory, LocaleFactory, ProjectFactory, ResourceFactory, TranslationFactory, UserFactory\n'), ((11389, 11476), 'pontoon.test.factories.ProjectFactory.create', 'ProjectFactory.create', ([], {'data_source': '"""database"""', 'locales': '[locale_kl]', 'repositories': '[]'}), "(data_source='database', locales=[locale_kl],\n repositories=[])\n", (11410, 11476), False, 'from pontoon.test.factories import EntityFactory, LocaleFactory, ProjectFactory, ResourceFactory, TranslationFactory, UserFactory\n'), ((11508, 11568), 'pontoon.administration.views._create_or_update_translated_resources', '_create_or_update_translated_resources', (['project', '[locale_kl]'], {}), '(project, [locale_kl])\n', (11546, 11568), False, 'from pontoon.administration.views import _create_or_update_translated_resources\n'), ((11580, 11634), 'django.core.urlresolvers.reverse', 'reverse', (['"""pontoon.admin.project"""'], {'args': '(project.slug,)'}), "('pontoon.admin.project', args=(project.slug,))\n", (11587, 11634), False, 'from django.core.urlresolvers import reverse\n'), ((11775, 11804), 'pontoon.administration.forms.ProjectForm', 'ProjectForm', ([], {'instance': 'project'}), '(instance=project)\n', (11786, 11804), False, 'from pontoon.administration.forms import ProjectForm\n'), ((12987, 13032), 'pontoon.base.models.ProjectLocale.objects.filter', 'ProjectLocale.objects.filter', ([], {'project': 'project'}), '(project=project)\n', (13015, 13032), False, 'from pontoon.base.models import Entity, Locale, Project, ProjectLocale, Resource, TranslatedResource\n'), ((13137, 13191), 'pontoon.base.models.Resource.objects.get', 'Resource.objects.get', ([], {'project': 'project', 'path': '"""database"""'}), "(project=project, path='database')\n", (13157, 13191), False, 'from pontoon.base.models import Entity, Locale, Project, ProjectLocale, Resource, TranslatedResource\n'), ((13201, 13253), 'pontoon.base.models.TranslatedResource.objects.filter', 'TranslatedResource.objects.filter', ([], {'resource': 'resource'}), '(resource=resource)\n', (13234, 13253), False, 'from pontoon.base.models import Entity, Locale, Project, ProjectLocale, Resource, TranslatedResource\n'), ((2298, 2338), 'pontoon.base.models.Resource.objects.filter', 'Resource.objects.filter', ([], {'project': 'project'}), '(project=project)\n', (2321, 2338), False, 'from pontoon.base.models import Entity, Locale, Project, ProjectLocale, Resource, TranslatedResource\n'), ((3246, 3293), 'pontoon.test.factories.LocaleFactory.create', 'LocaleFactory.create', ([], {'code': '"""kl"""', 'name': '"""Klingon"""'}), "(code='kl', name='Klingon')\n", (3266, 3293), False, 'from pontoon.test.factories import EntityFactory, LocaleFactory, ProjectFactory, ResourceFactory, TranslationFactory, UserFactory\n'), ((3303, 3352), 'pontoon.test.factories.LocaleFactory.create', 'LocaleFactory.create', ([], {'code': '"""gs"""', 'name': '"""Geonosian"""'}), "(code='gs', name='Geonosian')\n", (3323, 3352), False, 'from pontoon.test.factories import EntityFactory, LocaleFactory, ProjectFactory, ResourceFactory, TranslationFactory, UserFactory\n'), ((4110, 4158), 'pontoon.base.models.Entity.objects.filter', 'Entity.objects.filter', ([], {'resource__project': 'project'}), '(resource__project=project)\n', (4131, 4158), False, 'from pontoon.base.models import Entity, Locale, Project, ProjectLocale, Resource, TranslatedResource\n'), ((4953, 4980), 'pontoon.base.models.Locale.objects.get', 'Locale.objects.get', ([], {'id': 'l.id'}), '(id=l.id)\n', (4971, 4980), False, 'from pontoon.base.models import Entity, Locale, Project, ProjectLocale, Resource, TranslatedResource\n'), ((5630, 5678), 'pontoon.base.models.Entity.objects.filter', 'Entity.objects.filter', ([], {'resource__project': 'project'}), '(resource__project=project)\n', (5651, 5678), False, 'from pontoon.base.models import Entity, Locale, Project, ProjectLocale, Resource, TranslatedResource\n'), ((9541, 9612), 'pontoon.base.models.Entity.objects.filter', 'Entity.objects.filter', ([], {'string': '"""And on the pedestal these words appear:"""'}), "(string='And on the pedestal these words appear:')\n", (9562, 9612), False, 'from pontoon.base.models import Entity, Locale, Project, ProjectLocale, Resource, TranslatedResource\n'), ((9971, 10041), 'pontoon.base.models.Entity.objects.filter', 'Entity.objects.filter', ([], {'string': '"""\'My name is Ozymandias, king of kings:"""'}), '(string="\'My name is Ozymandias, king of kings:")\n', (9992, 10041), False, 'from pontoon.base.models import Entity, Locale, Project, ProjectLocale, Resource, TranslatedResource\n'), ((10391, 10465), 'pontoon.base.models.Entity.objects.filter', 'Entity.objects.filter', ([], {'string': '"""Look on my works, ye Mighty, and despair!\'"""'}), '(string="Look on my works, ye Mighty, and despair!\'")\n', (10412, 10465), False, 'from pontoon.base.models import Entity, Locale, Project, ProjectLocale, Resource, TranslatedResource\n'), ((7042, 7098), 'pontoon.base.models.Entity.objects.filter', 'Entity.objects.filter', ([], {'resource': 'resource', 'obsolete': '(False)'}), '(resource=resource, obsolete=False)\n', (7063, 7098), False, 'from pontoon.base.models import Entity, Locale, Project, ProjectLocale, Resource, TranslatedResource\n'), ((7861, 7917), 'pontoon.base.models.Entity.objects.filter', 'Entity.objects.filter', ([], {'resource': 'resource', 'obsolete': '(False)'}), '(resource=resource, obsolete=False)\n', (7882, 7917), False, 'from pontoon.base.models import Entity, Locale, Project, ProjectLocale, Resource, TranslatedResource\n'), ((8042, 8119), 'pontoon.base.models.Entity.objects.filter', 'Entity.objects.filter', ([], {'resource': 'resource', 'obsolete': '(False)', 'string': '"""new string"""'}), "(resource=resource, obsolete=False, string='new string')\n", (8063, 8119), False, 'from pontoon.base.models import Entity, Locale, Project, ProjectLocale, Resource, TranslatedResource\n')] |
# -*- coding: utf-8 -*-
#
# This file is part of the python-chess library.
# Copyright (C) 2012-2019 <NAME> <<EMAIL>>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import collections
import math
import mmap
import os
import re
import struct
import threading
import typing
import chess
from types import TracebackType
from typing import Dict, Iterator, List, Mapping, MutableMapping, Optional, Tuple, Type, Union
PathLike = Union[str, bytes]
UINT64_BE = struct.Struct(">Q")
UINT32 = struct.Struct("<I")
UINT32_BE = struct.Struct(">I")
UINT16 = struct.Struct("<H")
TBPIECES = 7
TRIANGLE = [
6, 0, 1, 2, 2, 1, 0, 6,
0, 7, 3, 4, 4, 3, 7, 0,
1, 3, 8, 5, 5, 8, 3, 1,
2, 4, 5, 9, 9, 5, 4, 2,
2, 4, 5, 9, 9, 5, 4, 2,
1, 3, 8, 5, 5, 8, 3, 1,
0, 7, 3, 4, 4, 3, 7, 0,
6, 0, 1, 2, 2, 1, 0, 6,
]
INVTRIANGLE = [1, 2, 3, 10, 11, 19, 0, 9, 18, 27]
def offdiag(square: chess.Square) -> int:
return chess.square_rank(square) - chess.square_file(square)
def flipdiag(square: chess.Square) -> chess.Square:
return ((square >> 3) | (square << 3)) & 63
LOWER = [
28, 0, 1, 2, 3, 4, 5, 6,
0, 29, 7, 8, 9, 10, 11, 12,
1, 7, 30, 13, 14, 15, 16, 17,
2, 8, 13, 31, 18, 19, 20, 21,
3, 9, 14, 18, 32, 22, 23, 24,
4, 10, 15, 19, 22, 33, 25, 26,
5, 11, 16, 20, 23, 25, 34, 27,
6, 12, 17, 21, 24, 26, 27, 35,
]
DIAG = [
0, 0, 0, 0, 0, 0, 0, 8,
0, 1, 0, 0, 0, 0, 9, 0,
0, 0, 2, 0, 0, 10, 0, 0,
0, 0, 0, 3, 11, 0, 0, 0,
0, 0, 0, 12, 4, 0, 0, 0,
0, 0, 13, 0, 0, 5, 0, 0,
0, 14, 0, 0, 0, 0, 6, 0,
15, 0, 0, 0, 0, 0, 0, 7,
]
FLAP = [
0, 0, 0, 0, 0, 0, 0, 0,
0, 6, 12, 18, 18, 12, 6, 0,
1, 7, 13, 19, 19, 13, 7, 1,
2, 8, 14, 20, 20, 14, 8, 2,
3, 9, 15, 21, 21, 15, 9, 3,
4, 10, 16, 22, 22, 16, 10, 4,
5, 11, 17, 23, 23, 17, 11, 5,
0, 0, 0, 0, 0, 0, 0, 0,
]
PTWIST = [
0, 0, 0, 0, 0, 0, 0, 0,
47, 35, 23, 11, 10, 22, 34, 46,
45, 33, 21, 9, 8, 20, 32, 44,
43, 31, 19, 7, 6, 18, 30, 42,
41, 29, 17, 5, 4, 16, 28, 40,
39, 27, 15, 3, 2, 14, 26, 38,
37, 25, 13, 1, 0, 12, 24, 36,
0, 0, 0, 0, 0, 0, 0, 0,
]
INVFLAP = [
8, 16, 24, 32, 40, 48,
9, 17, 25, 33, 41, 49,
10, 18, 26, 34, 42, 50,
11, 19, 27, 35, 43, 51,
]
FILE_TO_FILE = [0, 1, 2, 3, 3, 2, 1, 0]
KK_IDX = [[
-1, -1, -1, 0, 1, 2, 3, 4,
-1, -1, -1, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33,
34, 35, 36, 37, 38, 39, 40, 41,
42, 43, 44, 45, 46, 47, 48, 49,
50, 51, 52, 53, 54, 55, 56, 57,
], [
58, -1, -1, -1, 59, 60, 61, 62,
63, -1, -1, -1, 64, 65, 66, 67,
68, 69, 70, 71, 72, 73, 74, 75,
76, 77, 78, 79, 80, 81, 82, 83,
84, 85, 86, 87, 88, 89, 90, 91,
92, 93, 94, 95, 96, 97, 98, 99,
100, 101, 102, 103, 104, 105, 106, 107,
108, 109, 110, 111, 112, 113, 114, 115,
], [
116, 117, -1, -1, -1, 118, 119, 120,
121, 122, -1, -1, -1, 123, 124, 125,
126, 127, 128, 129, 130, 131, 132, 133,
134, 135, 136, 137, 138, 139, 140, 141,
142, 143, 144, 145, 146, 147, 148, 149,
150, 151, 152, 153, 154, 155, 156, 157,
158, 159, 160, 161, 162, 163, 164, 165,
166, 167, 168, 169, 170, 171, 172, 173,
], [
174, -1, -1, -1, 175, 176, 177, 178,
179, -1, -1, -1, 180, 181, 182, 183,
184, -1, -1, -1, 185, 186, 187, 188,
189, 190, 191, 192, 193, 194, 195, 196,
197, 198, 199, 200, 201, 202, 203, 204,
205, 206, 207, 208, 209, 210, 211, 212,
213, 214, 215, 216, 217, 218, 219, 220,
221, 222, 223, 224, 225, 226, 227, 228,
], [
229, 230, -1, -1, -1, 231, 232, 233,
234, 235, -1, -1, -1, 236, 237, 238,
239, 240, -1, -1, -1, 241, 242, 243,
244, 245, 246, 247, 248, 249, 250, 251,
252, 253, 254, 255, 256, 257, 258, 259,
260, 261, 262, 263, 264, 265, 266, 267,
268, 269, 270, 271, 272, 273, 274, 275,
276, 277, 278, 279, 280, 281, 282, 283,
], [
284, 285, 286, 287, 288, 289, 290, 291,
292, 293, -1, -1, -1, 294, 295, 296,
297, 298, -1, -1, -1, 299, 300, 301,
302, 303, -1, -1, -1, 304, 305, 306,
307, 308, 309, 310, 311, 312, 313, 314,
315, 316, 317, 318, 319, 320, 321, 322,
323, 324, 325, 326, 327, 328, 329, 330,
331, 332, 333, 334, 335, 336, 337, 338,
], [
-1, -1, 339, 340, 341, 342, 343, 344,
-1, -1, 345, 346, 347, 348, 349, 350,
-1, -1, 441, 351, 352, 353, 354, 355,
-1, -1, -1, 442, 356, 357, 358, 359,
-1, -1, -1, -1, 443, 360, 361, 362,
-1, -1, -1, -1, -1, 444, 363, 364,
-1, -1, -1, -1, -1, -1, 445, 365,
-1, -1, -1, -1, -1, -1, -1, 446,
], [
-1, -1, -1, 366, 367, 368, 369, 370,
-1, -1, -1, 371, 372, 373, 374, 375,
-1, -1, -1, 376, 377, 378, 379, 380,
-1, -1, -1, 447, 381, 382, 383, 384,
-1, -1, -1, -1, 448, 385, 386, 387,
-1, -1, -1, -1, -1, 449, 388, 389,
-1, -1, -1, -1, -1, -1, 450, 390,
-1, -1, -1, -1, -1, -1, -1, 451,
], [
452, 391, 392, 393, 394, 395, 396, 397,
-1, -1, -1, -1, 398, 399, 400, 401,
-1, -1, -1, -1, 402, 403, 404, 405,
-1, -1, -1, -1, 406, 407, 408, 409,
-1, -1, -1, -1, 453, 410, 411, 412,
-1, -1, -1, -1, -1, 454, 413, 414,
-1, -1, -1, -1, -1, -1, 455, 415,
-1, -1, -1, -1, -1, -1, -1, 456,
], [
457, 416, 417, 418, 419, 420, 421, 422,
-1, 458, 423, 424, 425, 426, 427, 428,
-1, -1, -1, -1, -1, 429, 430, 431,
-1, -1, -1, -1, -1, 432, 433, 434,
-1, -1, -1, -1, -1, 435, 436, 437,
-1, -1, -1, -1, -1, 459, 438, 439,
-1, -1, -1, -1, -1, -1, 460, 440,
-1, -1, -1, -1, -1, -1, -1, 461,
]]
PP_IDX = [[
0, -1, 1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, 26, 27, 28, 29, 30,
31, 32, 33, 34, 35, 36, 37, 38,
39, 40, 41, 42, 43, 44, 45, 46,
-1, 47, 48, 49, 50, 51, 52, 53,
54, 55, 56, 57, 58, 59, 60, 61,
], [
62, -1, -1, 63, 64, 65, -1, 66,
-1, 67, 68, 69, 70, 71, 72, -1,
73, 74, 75, 76, 77, 78, 79, 80,
81, 82, 83, 84, 85, 86, 87, 88,
89, 90, 91, 92, 93, 94, 95, 96,
-1, 97, 98, 99, 100, 101, 102, 103,
-1, 104, 105, 106, 107, 108, 109, -1,
110, -1, 111, 112, 113, 114, -1, 115,
], [
116, -1, -1, -1, 117, -1, -1, 118,
-1, 119, 120, 121, 122, 123, 124, -1,
-1, 125, 126, 127, 128, 129, 130, -1,
131, 132, 133, 134, 135, 136, 137, 138,
-1, 139, 140, 141, 142, 143, 144, 145,
-1, 146, 147, 148, 149, 150, 151, -1,
-1, 152, 153, 154, 155, 156, 157, -1,
158, -1, -1, 159, 160, -1, -1, 161,
], [
162, -1, -1, -1, -1, -1, -1, 163,
-1, 164, -1, 165, 166, 167, 168, -1,
-1, 169, 170, 171, 172, 173, 174, -1,
-1, 175, 176, 177, 178, 179, 180, -1,
-1, 181, 182, 183, 184, 185, 186, -1,
-1, -1, 187, 188, 189, 190, 191, -1,
-1, 192, 193, 194, 195, 196, 197, -1,
198, -1, -1, -1, -1, -1, -1, 199,
], [
200, -1, -1, -1, -1, -1, -1, 201,
-1, 202, -1, -1, 203, -1, 204, -1,
-1, -1, 205, 206, 207, 208, -1, -1,
-1, 209, 210, 211, 212, 213, 214, -1,
-1, -1, 215, 216, 217, 218, 219, -1,
-1, -1, 220, 221, 222, 223, -1, -1,
-1, 224, -1, 225, 226, -1, 227, -1,
228, -1, -1, -1, -1, -1, -1, 229,
], [
230, -1, -1, -1, -1, -1, -1, 231,
-1, 232, -1, -1, -1, -1, 233, -1,
-1, -1, 234, -1, 235, 236, -1, -1,
-1, -1, 237, 238, 239, 240, -1, -1,
-1, -1, -1, 241, 242, 243, -1, -1,
-1, -1, 244, 245, 246, 247, -1, -1,
-1, 248, -1, -1, -1, -1, 249, -1,
250, -1, -1, -1, -1, -1, -1, 251,
], [
-1, -1, -1, -1, -1, -1, -1, 259,
-1, 252, -1, -1, -1, -1, 260, -1,
-1, -1, 253, -1, -1, 261, -1, -1,
-1, -1, -1, 254, 262, -1, -1, -1,
-1, -1, -1, -1, 255, -1, -1, -1,
-1, -1, -1, -1, -1, 256, -1, -1,
-1, -1, -1, -1, -1, -1, 257, -1,
-1, -1, -1, -1, -1, -1, -1, 258,
], [
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, 268, -1,
-1, -1, 263, -1, -1, 269, -1, -1,
-1, -1, -1, 264, 270, -1, -1, -1,
-1, -1, -1, -1, 265, -1, -1, -1,
-1, -1, -1, -1, -1, 266, -1, -1,
-1, -1, -1, -1, -1, -1, 267, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
], [
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 274, -1, -1,
-1, -1, -1, 271, 275, -1, -1, -1,
-1, -1, -1, -1, 272, -1, -1, -1,
-1, -1, -1, -1, -1, 273, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
], [
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, 277, -1, -1, -1,
-1, -1, -1, -1, 276, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1
]]
def test45(sq: chess.Square) -> bool:
return bool(chess.BB_SQUARES[sq] & (chess.BB_A5 | chess.BB_A6 | chess.BB_A7 |
chess.BB_B5 | chess.BB_B6 |
chess.BB_C5))
MTWIST = [
15, 63, 55, 47, 40, 48, 56, 12,
62, 11, 39, 31, 24, 32, 8, 57,
54, 38, 7, 23, 16, 4, 33, 49,
46, 30, 22, 3, 0, 17, 25, 41,
45, 29, 21, 2, 1, 18, 26, 42,
53, 37, 6, 20, 19, 5, 34, 50,
61, 10, 36, 28, 27, 35, 9, 58,
14, 60, 52, 44, 43, 51, 59, 13,
]
def binom(x: int, y: int) -> int:
try:
return math.factorial(x) // math.factorial(y) // math.factorial(x - y)
except ValueError:
return 0
PAWNIDX = [[0 for _ in range(24)] for _ in range(5)]
PFACTOR = [[0 for _ in range(4)] for _ in range(5)]
for i in range(5):
j = 0
s = 0
while j < 6:
PAWNIDX[i][j] = s
s += 1 if i == 0 else binom(PTWIST[INVFLAP[j]], i)
j += 1
PFACTOR[i][0] = s
s = 0
while j < 12:
PAWNIDX[i][j] = s
s += 1 if i == 0 else binom(PTWIST[INVFLAP[j]], i)
j += 1
PFACTOR[i][1] = s
s = 0
while j < 18:
PAWNIDX[i][j] = s
s += 1 if i == 0 else binom(PTWIST[INVFLAP[j]], i)
j += 1
PFACTOR[i][2] = s
s = 0
while j < 24:
PAWNIDX[i][j] = s
s += 1 if i == 0 else binom(PTWIST[INVFLAP[j]], i)
j += 1
PFACTOR[i][3] = s
MULTIDX = [[0 for _ in range(10)] for _ in range(5)]
MFACTOR = [0 for _ in range(5)]
for i in range(5):
s = 0
for j in range(10):
MULTIDX[i][j] = s
s += 1 if i == 0 else binom(MTWIST[INVTRIANGLE[j]], i)
MFACTOR[i] = s
WDL_TO_MAP = [1, 3, 0, 2, 0]
PA_FLAGS = [8, 0, 0, 0, 4]
WDL_TO_DTZ = [-1, -101, 0, 101, 1]
PCHR = ["K", "Q", "R", "B", "N", "P"]
TABLENAME_REGEX = re.compile(r"^[KQRBNP]+v[KQRBNP]+\Z")
def is_table_name(name: str) -> bool:
return len(name) <= 7 + 1 and bool(TABLENAME_REGEX.match(name)) and normalize_tablename(name) == name
def tablenames(*, one_king: bool = True, piece_count: int = 6) -> Iterator[str]:
first = "K" if one_king else "P"
targets = []
white_pieces = piece_count - 2
black_pieces = 0
while white_pieces >= black_pieces:
targets.append(first + "P" * white_pieces + "v" + first + "P" * black_pieces)
white_pieces -= 1
black_pieces += 1
return all_dependencies(targets, one_king=one_king)
def normalize_tablename(name: str, *, mirror: bool = False) -> str:
w, b = name.split("v", 1)
w = "".join(sorted(w, key=PCHR.index))
b = "".join(sorted(b, key=PCHR.index))
if mirror ^ ((len(w), [PCHR.index(c) for c in b]) < (len(b), [PCHR.index(c) for c in w])):
return b + "v" + w
else:
return w + "v" + b
def _dependencies(target: str, *, one_king: bool = True) -> Iterator[str]:
w, b = target.split("v", 1)
for p in PCHR:
if p == "K" and one_king:
continue
# Promotions.
if p != "P" and "P" in w:
yield normalize_tablename(w.replace("P", p, 1) + "v" + b)
if p != "P" and "P" in b:
yield normalize_tablename(w + "v" + b.replace("P", p, 1))
# Captures.
if p in w and len(w) > 1:
yield normalize_tablename(w.replace(p, "", 1) + "v" + b)
if p in b and len(b) > 1:
yield normalize_tablename(w + "v" + b.replace(p, "", 1))
def dependencies(target: str, *, one_king: bool = True) -> Iterator[str]:
closed = set()
if one_king:
closed.add("KvK")
for dependency in _dependencies(target, one_king=one_king):
if dependency not in closed and len(dependency) > 2:
yield dependency
closed.add(dependency)
def all_dependencies(targets: str, *, one_king: bool = True) -> Iterator[str]:
closed = set()
if one_king:
closed.add("KvK")
open_list = [normalize_tablename(target) for target in targets]
while open_list:
name = open_list.pop()
if name in closed:
continue
yield name
closed.add(name)
open_list.extend(_dependencies(name, one_king=one_king))
def calc_key(board: chess.BaseBoard, *, mirror: bool = False) -> str:
w = board.occupied_co[chess.WHITE ^ mirror]
b = board.occupied_co[chess.BLACK ^ mirror]
return "".join([
"K" * chess.popcount(board.kings & w),
"Q" * chess.popcount(board.queens & w),
"R" * chess.popcount(board.rooks & w),
"B" * chess.popcount(board.bishops & w),
"N" * chess.popcount(board.knights & w),
"P" * chess.popcount(board.pawns & w),
"v",
"K" * chess.popcount(board.kings & b),
"Q" * chess.popcount(board.queens & b),
"R" * chess.popcount(board.rooks & b),
"B" * chess.popcount(board.bishops & b),
"N" * chess.popcount(board.knights & b),
"P" * chess.popcount(board.pawns & b),
])
def recalc_key(pieces: List[chess.PieceType], *, mirror: bool = False) -> str:
# Some endgames are stored with a different key than their filename
# indicates: http://talkchess.com/forum/viewtopic.php?p=695509#695509
w = 8 if mirror else 0
b = 0 if mirror else 8
return "".join([
"K" * pieces.count(6 ^ w),
"Q" * pieces.count(5 ^ w),
"R" * pieces.count(4 ^ w),
"B" * pieces.count(3 ^ w),
"N" * pieces.count(2 ^ w),
"P" * pieces.count(1 ^ w),
"v",
"K" * pieces.count(6 ^ b),
"Q" * pieces.count(5 ^ b),
"R" * pieces.count(4 ^ b),
"B" * pieces.count(3 ^ b),
"N" * pieces.count(2 ^ b),
"P" * pieces.count(1 ^ b),
])
def subfactor(k: int, n: int) -> int:
f = n
l = 1
for i in range(1, k):
f *= n - i
l *= i + 1
return f // l
def dtz_before_zeroing(wdl: int) -> int:
return ((wdl > 0) - (wdl < 0)) * (1 if abs(wdl) == 2 else 101)
class MissingTableError(KeyError):
"""Can not probe position because a required table is missing."""
pass
class PairsData:
def __init__(self) -> None:
self.indextable = None
self.sizetable = None
self.data = None
self.offset = None
self.symlen = None
self.sympat = None # type: int
self.blocksize = None
self.idxbits = None
self.min_len = None
self.base = None
class PawnFileData:
def __init__(self) -> None:
self.precomp = {}
self.factor = {}
self.pieces = {}
self.norm = {}
class PawnFileDataDtz:
def __init__(self) -> None:
self.precomp = None
self.factor = None
self.pieces = None
self.norm = None
class Table:
def __init__(self, path: PathLike, *, variant: Type[chess.Board] = chess.Board) -> None:
self.path = path
self.variant = variant
self.write_lock = threading.RLock()
self.initialized = False
self.fd = None
self.data = None
self.read_condition = threading.Condition()
self.read_count = 0
tablename, _ = os.path.splitext(os.path.basename(path))
self.key = normalize_tablename(tablename)
self.mirrored_key = normalize_tablename(tablename, mirror=True)
self.symmetric = self.key == self.mirrored_key
# Leave the v out of the tablename to get the number of pieces.
self.num = len(tablename) - 1
self.has_pawns = "P" in tablename
black_part, white_part = tablename.split("v")
if self.has_pawns:
self.pawns = {0: white_part.count("P"),
1: black_part.count("P")}
if self.pawns[1] > 0 and (self.pawns[0] == 0 or self.pawns[1] < self.pawns[0]):
self.pawns[0], self.pawns[1] = self.pawns[1], self.pawns[0]
else:
j = 0
for piece_type in PCHR:
if black_part.count(piece_type) == 1:
j += 1
if white_part.count(piece_type) == 1:
j += 1
if j >= 3:
self.enc_type = 0
elif j == 2:
self.enc_type = 2
else: # only for suicide
j = 16
for _ in range(16):
for piece_type in PCHR:
if 1 < black_part.count(piece_type) < j:
j = black_part.count(piece_type)
if 1 < white_part.count(piece_type) < j:
j = white_part.count(piece_type)
self.enc_type = 1 + j
def init_mmap(self) -> None:
with self.write_lock:
# Open fd.
if self.fd is None:
self.fd = os.open(self.path, os.O_RDONLY | os.O_BINARY if hasattr(os, "O_BINARY") else os.O_RDONLY)
# Open mmap.
if self.data is None:
self.data = mmap.mmap(self.fd, 0, access=mmap.ACCESS_READ)
def check_magic(self, magic: Optional[bytes], pawnless_magic: Optional[bytes]) -> bool:
valid_magics = [magic, self.has_pawns and pawnless_magic]
if self.data[:min(4, len(self.data))] not in valid_magics:
raise IOError("invalid magic header: ensure {!r} is a valid syzygy tablebase file".format(self.path))
def setup_pairs(self, data_ptr: int, tb_size: int, size_idx: int, wdl: int) -> PairsData:
d = PairsData()
self._flags = self.data[data_ptr]
if self.data[data_ptr] & 0x80:
d.idxbits = 0
if wdl:
d.min_len = self.data[data_ptr + 1]
else:
# http://www.talkchess.com/forum/viewtopic.php?p=698093#698093
d.min_len = 1 if self.variant.captures_compulsory else 0
self._next = data_ptr + 2
self.size[size_idx + 0] = 0
self.size[size_idx + 1] = 0
self.size[size_idx + 2] = 0
return d
d.blocksize = self.data[data_ptr + 1]
d.idxbits = self.data[data_ptr + 2]
real_num_blocks = self.read_uint32(data_ptr + 4)
num_blocks = real_num_blocks + self.data[data_ptr + 3]
max_len = self.data[data_ptr + 8]
min_len = self.data[data_ptr + 9]
h = max_len - min_len + 1
num_syms = self.read_uint16(data_ptr + 10 + 2 * h)
d.offset = data_ptr + 10
d.symlen = [0 for _ in range(h * 8 + num_syms)]
d.sympat = data_ptr + 12 + 2 * h
d.min_len = min_len
self._next = data_ptr + 12 + 2 * h + 3 * num_syms + (num_syms & 1)
num_indices = (tb_size + (1 << d.idxbits) - 1) >> d.idxbits
self.size[size_idx + 0] = 6 * num_indices
self.size[size_idx + 1] = 2 * num_blocks
self.size[size_idx + 2] = (1 << d.blocksize) * real_num_blocks
tmp = [0 for _ in range(num_syms)]
for i in range(num_syms):
if not tmp[i]:
self.calc_symlen(d, i, tmp)
d.base = [0 for _ in range(h)]
d.base[h - 1] = 0
for i in range(h - 2, -1, -1):
d.base[i] = (d.base[i + 1] + self.read_uint16(d.offset + i * 2) - self.read_uint16(d.offset + i * 2 + 2)) // 2
for i in range(h):
d.base[i] <<= 64 - (min_len + i)
d.offset -= 2 * d.min_len
return d
def set_norm_piece(self, norm: List[int], pieces) -> None:
if self.enc_type == 0:
norm[0] = 3
elif self.enc_type == 2:
norm[0] = 2
else:
norm[0] = self.enc_type - 1
i = norm[0]
while i < self.num:
j = i
while j < self.num and pieces[j] == pieces[i]:
norm[i] += 1
j += 1
i += norm[i]
def calc_factors_piece(self, factor: List[int], order: int, norm: List[int]) -> int:
if not self.variant.connected_kings:
PIVFAC = [31332, 28056, 462]
else:
PIVFAC = [31332, 0, 518, 278]
n = 64 - norm[0]
f = 1
i = norm[0]
k = 0
while i < self.num or k == order:
if k == order:
factor[0] = f
if self.enc_type < 4:
f *= PIVFAC[self.enc_type]
else:
f *= MFACTOR[self.enc_type - 2]
else:
factor[i] = f
f *= subfactor(norm[i], n)
n -= norm[i]
i += norm[i]
k += 1
return f
def calc_factors_pawn(self, factor: int, order: int, order2: int, norm: List[int], f: int) -> int:
i = norm[0]
if order2 < 0x0f:
i += norm[i]
n = 64 - i
fac = 1
k = 0
while i < self.num or k in [order, order2]:
if k == order:
factor[0] = fac
fac *= PFACTOR[norm[0] - 1][f]
elif k == order2:
factor[norm[0]] = fac
fac *= subfactor(norm[norm[0]], 48 - norm[0])
else:
factor[i] = fac
fac *= subfactor(norm[i], n)
n -= norm[i]
i += norm[i]
k += 1
return fac
def set_norm_pawn(self, norm: List[int], pieces) -> None:
norm[0] = self.pawns[0]
if self.pawns[1]:
norm[self.pawns[0]] = self.pawns[1]
i = self.pawns[0] + self.pawns[1]
while i < self.num:
j = i
while j < self.num and pieces[j] == pieces[i]:
norm[i] += 1
j += 1
i += norm[i]
def calc_symlen(self, d: PairsData, s: int, tmp: List[int]) -> None:
w = d.sympat + 3 * s
s2 = (self.data[w + 2] << 4) | (self.data[w + 1] >> 4)
if s2 == 0x0fff:
d.symlen[s] = 0
else:
s1 = ((self.data[w + 1] & 0xf) << 8) | self.data[w]
if not tmp[s1]:
self.calc_symlen(d, s1, tmp)
if not tmp[s2]:
self.calc_symlen(d, s2, tmp)
d.symlen[s] = d.symlen[s1] + d.symlen[s2] + 1
tmp[s] = 1
def pawn_file(self, pos: chess.Square) -> int:
for i in range(1, self.pawns[0]):
if FLAP[pos[0]] > FLAP[pos[i]]:
pos[0], pos[i] = pos[i], pos[0]
return FILE_TO_FILE[pos[0] & 0x07]
def encode_piece(self, norm: List[int], pos: List[chess.Square], factor: int) -> int:
n = self.num
if self.enc_type < 3:
if pos[0] & 0x04:
for i in range(n):
pos[i] ^= 0x07
if pos[0] & 0x20:
for i in range(n):
pos[i] ^= 0x38
for i in range(n):
if offdiag(pos[i]):
break
if i < (3 if self.enc_type == 0 else 2) and offdiag(pos[i]) > 0:
for i in range(n):
pos[i] = flipdiag(pos[i])
if self.enc_type == 0: # 111
i = int(pos[1] > pos[0])
j = int(pos[2] > pos[0]) + int(pos[2] > pos[1])
if offdiag(pos[0]):
idx = TRIANGLE[pos[0]] * 63 * 62 + (pos[1] - i) * 62 + (pos[2] - j)
elif offdiag(pos[1]):
idx = 6 * 63 * 62 + DIAG[pos[0]] * 28 * 62 + LOWER[pos[1]] * 62 + pos[2] - j
elif offdiag(pos[2]):
idx = 6 * 63 * 62 + 4 * 28 * 62 + (DIAG[pos[0]]) * 7 * 28 + (DIAG[pos[1]] - i) * 28 + LOWER[pos[2]]
else:
idx = 6 * 63 * 62 + 4 * 28 * 62 + 4 * 7 * 28 + (DIAG[pos[0]] * 7 * 6) + (DIAG[pos[1]] - i) * 6 + (DIAG[pos[2]] - j)
i = 3
elif self.enc_type == 2: # K2
if not self.variant.connected_kings:
idx = KK_IDX[TRIANGLE[pos[0]]][pos[1]]
else:
i = pos[1] > pos[0]
if offdiag(pos[0]):
idx = TRIANGLE[pos[0]] * 63 + (pos[1] - i)
elif offdiag(pos[1]):
idx = 6 * 63 + DIAG[pos[0]] * 28 + LOWER[pos[1]]
else:
idx = 6 * 63 + 4 * 28 + (DIAG[pos[0]]) * 7 + (DIAG[pos[1]] - i)
i = 2
elif self.enc_type == 3: # 2, e.g. KKvK
if TRIANGLE[pos[0]] > TRIANGLE[pos[1]]:
pos[0], pos[1] = pos[1], pos[0]
if pos[0] & 0x04:
for i in range(n):
pos[i] ^= 0x07
if pos[0] & 0x20:
for i in range(n):
pos[i] ^= 0x38
if offdiag(pos[0]) > 0 or (offdiag(pos[0]) == 0 and offdiag(pos[1]) > 0):
for i in range(n):
pos[i] = flipdiag(pos[i])
if test45(pos[1]) and TRIANGLE[pos[0]] == TRIANGLE[pos[1]]:
pos[0], pos[1] = pos[1], pos[0]
for i in range(n):
pos[i] = flipdiag(pos[i] ^ 0x38)
idx = PP_IDX[TRIANGLE[pos[0]]][pos[1]]
i = 2
else: # 3 and higher, e.g. KKKvK and KKKKvK
for i in range(1, norm[0]):
if TRIANGLE[pos[0]] > TRIANGLE[pos[i]]:
pos[0], pos[i] = pos[i], pos[0]
if pos[0] & 0x04:
for i in range(n):
pos[i] ^= 0x07
if pos[0] & 0x20:
for i in range(n):
pos[i] ^= 0x38
if offdiag(pos[0]) > 0:
for i in range(n):
pos[i] = flipdiag(pos[i])
for i in range(1, norm[0]):
for j in range(i + 1, norm[0]):
if MTWIST[pos[i]] > MTWIST[pos[j]]:
pos[i], pos[j] = pos[j], pos[i]
idx = MULTIDX[norm[0] - 1][TRIANGLE[pos[0]]]
i = 1
while i < norm[0]:
idx += binom(MTWIST[pos[i]], i)
i += 1
idx *= factor[0]
while i < n:
t = norm[i]
for j in range(i, i + t):
for k in range(j + 1, i + t):
# Swap.
if pos[j] > pos[k]:
pos[j], pos[k] = pos[k], pos[j]
s = 0
for m in range(i, i + t):
p = pos[m]
j = 0
for l in range(i):
j += int(p > pos[l])
s += binom(p - j, m - i + 1)
idx += s * factor[i]
i += t
return idx
def encode_pawn(self, norm: List[int], pos: chess.Square, factor: int) -> int:
n = self.num
if pos[0] & 0x04:
for i in range(n):
pos[i] ^= 0x07
for i in range(1, self.pawns[0]):
for j in range(i + 1, self.pawns[0]):
if PTWIST[pos[i]] < PTWIST[pos[j]]:
pos[i], pos[j] = pos[j], pos[i]
t = self.pawns[0] - 1
idx = PAWNIDX[t][FLAP[pos[0]]]
for i in range(t, 0, -1):
idx += binom(PTWIST[pos[i]], t - i + 1)
idx *= factor[0]
# Remaining pawns.
i = self.pawns[0]
t = i + self.pawns[1]
if t > i:
for j in range(i, t):
for k in range(j + 1, t):
if pos[j] > pos[k]:
pos[j], pos[k] = pos[k], pos[j]
s = 0
for m in range(i, t):
p = pos[m]
j = 0
for k in range(i):
j += int(p > pos[k])
s += binom(p - j - 8, m - i + 1)
idx += s * factor[i]
i = t
while i < n:
t = norm[i]
for j in range(i, i + t):
for k in range(j + 1, i + t):
if pos[j] > pos[k]:
pos[j], pos[k] = pos[k], pos[j]
s = 0
for m in range(i, i + t):
p = pos[m]
j = 0
for k in range(i):
j += int(p > pos[k])
s += binom(p - j, m - i + 1)
idx += s * factor[i]
i += t
return idx
def decompress_pairs(self, d: PairsData, idx: int) -> int:
if not d.idxbits:
return d.min_len
mainidx = idx >> d.idxbits
litidx = (idx & (1 << d.idxbits) - 1) - (1 << (d.idxbits - 1))
block = self.read_uint32(d.indextable + 6 * mainidx)
idx_offset = self.read_uint16(d.indextable + 6 * mainidx + 4)
litidx += idx_offset
if litidx < 0:
while litidx < 0:
block -= 1
litidx += self.read_uint16(d.sizetable + 2 * block) + 1
else:
while litidx > self.read_uint16(d.sizetable + 2 * block):
litidx -= self.read_uint16(d.sizetable + 2 * block) + 1
block += 1
ptr = d.data + (block << d.blocksize)
m = d.min_len
base_idx = -m
symlen_idx = 0
code = self.read_uint64_be(ptr)
ptr += 2 * 4
bitcnt = 0 # Number of empty bits in code
while True:
l = m
while code < d.base[base_idx + l]:
l += 1
sym = self.read_uint16(d.offset + l * 2)
sym += (code - d.base[base_idx + l]) >> (64 - l)
if litidx < d.symlen[symlen_idx + sym] + 1:
break
litidx -= d.symlen[symlen_idx + sym] + 1
code <<= l
bitcnt += l
if bitcnt >= 32:
bitcnt -= 32
code |= self.read_uint32_be(ptr) << bitcnt
ptr += 4
# Cut off at 64bit.
code &= 0xffffffffffffffff
sympat = d.sympat
while d.symlen[symlen_idx + sym]:
w = sympat + 3 * sym
s1 = ((self.data[w + 1] & 0xf) << 8) | self.data[w]
if litidx < d.symlen[symlen_idx + s1] + 1:
sym = s1
else:
litidx -= d.symlen[symlen_idx + s1] + 1
sym = (self.data[w + 2] << 4) | (self.data[w + 1] >> 4)
w = sympat + 3 * sym
if isinstance(self, DtzTable):
return ((self.data[w + 1] & 0x0f) << 8) | self.data[w]
else:
return self.data[w]
def read_uint64_be(self, data_ptr: int) -> int:
return UINT64_BE.unpack_from(self.data, data_ptr)[0]
def read_uint32(self, data_ptr: int) -> int:
return UINT32.unpack_from(self.data, data_ptr)[0]
def read_uint32_be(self, data_ptr: int) -> int:
return UINT32_BE.unpack_from(self.data, data_ptr)[0]
def read_uint16(self, data_ptr: int) -> int:
return UINT16.unpack_from(self.data, data_ptr)[0]
def close(self) -> None:
with self.write_lock:
with self.read_condition:
while self.read_count > 0:
self.read_condition.wait()
if self.data is not None:
self.data.close()
self.data = None
if self.fd is not None:
os.close(self.fd)
self.fd = None
def __enter__(self) -> None:
return self
def __exit__(self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType]) -> None:
self.close()
class WdlTable(Table):
def init_table_wdl(self) -> None:
with self.write_lock:
self.init_mmap()
if self.initialized:
return
self.check_magic(self.variant.tbw_magic, self.variant.pawnless_tbw_magic)
self.tb_size = [0 for _ in range(8)]
self.size = [0 for _ in range(8 * 3)]
# Used if there are only pieces.
self.precomp = {}
self.pieces = {}
self.factor = {0: [0 for _ in range(TBPIECES)],
1: [0 for _ in range(TBPIECES)]}
self.norm = {0: [0 for _ in range(self.num)],
1: [0 for _ in range(self.num)]}
# Used if there are pawns.
self.files = [PawnFileData() for _ in range(4)]
self._next = None
self._flags = None
self.flags = None
split = self.data[4] & 0x01
files = 4 if self.data[4] & 0x02 else 1
data_ptr = 5
if not self.has_pawns:
self.setup_pieces_piece(data_ptr)
data_ptr += self.num + 1
data_ptr += data_ptr & 0x01
self.precomp[0] = self.setup_pairs(data_ptr, self.tb_size[0], 0, True)
data_ptr = self._next
if split:
self.precomp[1] = self.setup_pairs(data_ptr, self.tb_size[1], 3, True)
data_ptr = self._next
else:
self.precomp[1] = None
self.precomp[0].indextable = data_ptr
data_ptr += self.size[0]
if split:
self.precomp[1].indextable = data_ptr
data_ptr += self.size[3]
self.precomp[0].sizetable = data_ptr
data_ptr += self.size[1]
if split:
self.precomp[1].sizetable = data_ptr
data_ptr += self.size[4]
data_ptr = (data_ptr + 0x3f) & ~0x3f
self.precomp[0].data = data_ptr
data_ptr += self.size[2]
if split:
data_ptr = (data_ptr + 0x3f) & ~0x3f
self.precomp[1].data = data_ptr
self.key = recalc_key(self.pieces[0])
self.mirrored_key = recalc_key(self.pieces[0], mirror=True)
else:
s = 1 + int(self.pawns[1] > 0)
for f in range(4):
self.setup_pieces_pawn(data_ptr, 2 * f, f)
data_ptr += self.num + s
data_ptr += data_ptr & 0x01
for f in range(files):
self.files[f].precomp[0] = self.setup_pairs(data_ptr, self.tb_size[2 * f], 6 * f, True)
data_ptr = self._next
if split:
self.files[f].precomp[1] = self.setup_pairs(data_ptr, self.tb_size[2 * f + 1], 6 * f + 3, True)
data_ptr = self._next
else:
self.files[f].precomp[1] = None
for f in range(files):
self.files[f].precomp[0].indextable = data_ptr
data_ptr += self.size[6 * f]
if split:
self.files[f].precomp[1].indextable = data_ptr
data_ptr += self.size[6 * f + 3]
for f in range(files):
self.files[f].precomp[0].sizetable = data_ptr
data_ptr += self.size[6 * f + 1]
if split:
self.files[f].precomp[1].sizetable = data_ptr
data_ptr += self.size[6 * f + 4]
for f in range(files):
data_ptr = (data_ptr + 0x3f) & ~0x3f
self.files[f].precomp[0].data = data_ptr
data_ptr += self.size[6 * f + 2]
if split:
data_ptr = (data_ptr + 0x3f) & ~0x3f
self.files[f].precomp[1].data = data_ptr
data_ptr += self.size[6 * f + 5]
self.initialized = True
def setup_pieces_pawn(self, p_data: int, p_tb_size: int, f: int) -> None:
j = 1 + int(self.pawns[1] > 0)
order = self.data[p_data] & 0x0f
order2 = self.data[p_data + 1] & 0x0f if self.pawns[1] else 0x0f
self.files[f].pieces[0] = [self.data[p_data + i + j] & 0x0f for i in range(self.num)]
self.files[f].norm[0] = [0 for _ in range(self.num)]
self.set_norm_pawn(self.files[f].norm[0], self.files[f].pieces[0])
self.files[f].factor[0] = [0 for _ in range(TBPIECES)]
self.tb_size[p_tb_size] = self.calc_factors_pawn(self.files[f].factor[0], order, order2, self.files[f].norm[0], f)
order = self.data[p_data] >> 4
order2 = self.data[p_data + 1] >> 4 if self.pawns[1] else 0x0f
self.files[f].pieces[1] = [self.data[p_data + i + j] >> 4 for i in range(self.num)]
self.files[f].norm[1] = [0 for _ in range(self.num)]
self.set_norm_pawn(self.files[f].norm[1], self.files[f].pieces[1])
self.files[f].factor[1] = [0 for _ in range(TBPIECES)]
self.tb_size[p_tb_size + 1] = self.calc_factors_pawn(self.files[f].factor[1], order, order2, self.files[f].norm[1], f)
def setup_pieces_piece(self, p_data: int) -> None:
self.pieces[0] = [self.data[p_data + i + 1] & 0x0f for i in range(self.num)]
order = self.data[p_data] & 0x0f
self.set_norm_piece(self.norm[0], self.pieces[0])
self.tb_size[0] = self.calc_factors_piece(self.factor[0], order, self.norm[0])
self.pieces[1] = [self.data[p_data + i + 1] >> 4 for i in range(self.num)]
order = self.data[p_data] >> 4
self.set_norm_piece(self.norm[1], self.pieces[1])
self.tb_size[1] = self.calc_factors_piece(self.factor[1], order, self.norm[1])
def probe_wdl_table(self, board: chess.Board) -> int:
try:
with self.read_condition:
self.read_count += 1
return self._probe_wdl_table(board)
finally:
with self.read_condition:
self.read_count -= 1
self.read_condition.notify()
def _probe_wdl_table(self, board: chess.Board) -> int:
self.init_table_wdl()
key = calc_key(board)
if not self.symmetric:
if key != self.key:
cmirror = 8
mirror = 0x38
bside = int(board.turn == chess.WHITE)
else:
cmirror = mirror = 0
bside = int(board.turn != chess.WHITE)
else:
cmirror = 0 if board.turn == chess.WHITE else 8
mirror = 0 if board.turn == chess.WHITE else 0x38
bside = 0
if not self.has_pawns:
p = [0 for _ in range(TBPIECES)]
i = 0
while i < self.num:
piece_type = self.pieces[bside][i] & 0x07
color = (self.pieces[bside][i] ^ cmirror) >> 3
bb = board.pieces_mask(piece_type, chess.WHITE if color == 0 else chess.BLACK)
for square in chess.scan_forward(bb):
p[i] = square
i += 1
idx = self.encode_piece(self.norm[bside], p, self.factor[bside])
res = self.decompress_pairs(self.precomp[bside], idx)
else:
p = [0 for _ in range(TBPIECES)]
i = 0
k = self.files[0].pieces[0][0] ^ cmirror
color = k >> 3
piece_type = k & 0x07
bb = board.pieces_mask(piece_type, chess.WHITE if color == 0 else chess.BLACK)
for square in chess.scan_forward(bb):
p[i] = square ^ mirror
i += 1
f = self.pawn_file(p)
pc = self.files[f].pieces[bside]
while i < self.num:
color = (pc[i] ^ cmirror) >> 3
piece_type = pc[i] & 0x07
bb = board.pieces_mask(piece_type, chess.WHITE if color == 0 else chess.BLACK)
for square in chess.scan_forward(bb):
p[i] = square ^ mirror
i += 1
idx = self.encode_pawn(self.files[f].norm[bside], p, self.files[f].factor[bside])
res = self.decompress_pairs(self.files[f].precomp[bside], idx)
return res - 2
class DtzTable(Table):
def init_table_dtz(self) -> None:
with self.write_lock:
self.init_mmap()
if self.initialized:
return
self.check_magic(self.variant.tbz_magic, self.variant.pawnless_tbz_magic)
self.factor = [0 for _ in range(TBPIECES)]
self.norm = [0 for _ in range(self.num)]
self.tb_size = [0, 0, 0, 0]
self.size = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
self.files = [PawnFileDataDtz() for f in range(4)]
files = 4 if self.data[4] & 0x02 else 1
p_data = 5
if not self.has_pawns:
self.map_idx = [0, 0, 0, 0]
self.setup_pieces_piece_dtz(p_data, 0)
p_data += self.num + 1
p_data += p_data & 0x01
self.precomp = self.setup_pairs(p_data, self.tb_size[0], 0, False)
self.flags = self._flags
p_data = self._next
self.p_map = p_data
if self.flags & 2:
if not self.flags & 16:
for i in range(4):
self.map_idx[i] = p_data + 1 - self.p_map
p_data += 1 + self.data[p_data]
else:
for i in range(4):
self.map_idx[i] = (p_data + 2 - self.p_map) // 2
p_data += 2 + 2 * self.read_uint16(p_data)
p_data += p_data & 0x01
self.precomp.indextable = p_data
p_data += self.size[0]
self.precomp.sizetable = p_data
p_data += self.size[1]
p_data = (p_data + 0x3f) & ~0x3f
self.precomp.data = p_data
p_data += self.size[2]
self.key = recalc_key(self.pieces)
self.mirrored_key = recalc_key(self.pieces, mirror=True)
else:
s = 1 + int(self.pawns[1] > 0)
for f in range(4):
self.setup_pieces_pawn_dtz(p_data, f, f)
p_data += self.num + s
p_data += p_data & 0x01
self.flags = []
for f in range(files):
self.files[f].precomp = self.setup_pairs(p_data, self.tb_size[f], 3 * f, False)
p_data = self._next
self.flags.append(self._flags)
self.map_idx = []
self.p_map = p_data
for f in range(files):
self.map_idx.append([])
if self.flags[f] & 2:
if not self.flags[f] & 16:
for _ in range(4):
self.map_idx[-1].append(p_data + 1 - self.p_map)
p_data += 1 + self.data[p_data]
else:
p_data += p_data & 0x01
for _ in range(4):
self.map_idx[-1].append((p_data + 2 - self.p_map) // 2)
p_data += 2 + 2 * self.read_uint16(p_data)
p_data += p_data & 0x01
for f in range(files):
self.files[f].precomp.indextable = p_data
p_data += self.size[3 * f]
for f in range(files):
self.files[f].precomp.sizetable = p_data
p_data += self.size[3 * f + 1]
for f in range(files):
p_data = (p_data + 0x3f) & ~0x3f
self.files[f].precomp.data = p_data
p_data += self.size[3 * f + 2]
self.initialized = True
def probe_dtz_table(self, board: chess.Board, wdl: int) -> Tuple[int, int]:
try:
with self.read_condition:
self.read_count += 1
return self._probe_dtz_table(board, wdl)
finally:
with self.read_condition:
self.read_count -= 1
self.read_condition.notify()
def _probe_dtz_table(self, board: chess.Board, wdl: int) -> Tuple[int, int]:
self.init_table_dtz()
key = calc_key(board)
if not self.symmetric:
if key != self.key:
cmirror = 8
mirror = 0x38
bside = int(board.turn == chess.WHITE)
else:
cmirror = mirror = 0
bside = int(board.turn != chess.WHITE)
else:
cmirror = 0 if board.turn == chess.WHITE else 8
mirror = 0 if board.turn == chess.WHITE else 0x38
bside = 0
if not self.has_pawns:
if (self.flags & 1) != bside and not self.symmetric:
return 0, -1
pc = self.pieces
p = [0 for _ in range(TBPIECES)]
i = 0
while i < self.num:
piece_type = pc[i] & 0x07
color = (pc[i] ^ cmirror) >> 3
bb = board.pieces_mask(piece_type, chess.WHITE if color == 0 else chess.BLACK)
for square in chess.scan_forward(bb):
p[i] = square
i += 1
idx = self.encode_piece(self.norm, p, self.factor)
res = self.decompress_pairs(self.precomp, idx)
if self.flags & 2:
if not self.flags & 16:
res = self.data[self.p_map + self.map_idx[WDL_TO_MAP[wdl + 2]] + res]
else:
res = self.read_uint16(self.p_map + 2 * (self.map_idx[WDL_TO_MAP[wdl + 2]] + res))
if (not (self.flags & PA_FLAGS[wdl + 2])) or (wdl & 1):
res *= 2
else:
k = self.files[0].pieces[0] ^ cmirror
piece_type = k & 0x07
color = k >> 3
bb = board.pieces_mask(piece_type, chess.WHITE if color == 0 else chess.BLACK)
i = 0
p = [0 for _ in range(TBPIECES)]
for square in chess.scan_forward(bb):
p[i] = square ^ mirror
i += 1
f = self.pawn_file(p)
if self.flags[f] & 1 != bside:
return 0, -1
pc = self.files[f].pieces
while i < self.num:
piece_type = pc[i] & 0x07
color = (pc[i] ^ cmirror) >> 3
bb = board.pieces_mask(piece_type, chess.WHITE if color == 0 else chess.BLACK)
for square in chess.scan_forward(bb):
p[i] = square ^ mirror
i += 1
idx = self.encode_pawn(self.files[f].norm, p, self.files[f].factor)
res = self.decompress_pairs(self.files[f].precomp, idx)
if self.flags[f] & 2:
if not self.flags[f] & 16:
res = self.data[self.p_map + self.map_idx[f][WDL_TO_MAP[wdl + 2]] + res]
else:
res = self.read_uint16(self.p_map + 2 * (self.map_idx[f][WDL_TO_MAP[wdl + 2]] + res))
if (not (self.flags[f] & PA_FLAGS[wdl + 2])) or (wdl & 1):
res *= 2
return res, 1
def setup_pieces_piece_dtz(self, p_data: int, p_tb_size: int) -> None:
self.pieces = [self.data[p_data + i + 1] & 0x0f for i in range(self.num)]
order = self.data[p_data] & 0x0f
self.set_norm_piece(self.norm, self.pieces)
self.tb_size[p_tb_size] = self.calc_factors_piece(self.factor, order, self.norm)
def setup_pieces_pawn_dtz(self, p_data: int, p_tb_size: int, f: int) -> None:
j = 1 + int(self.pawns[1] > 0)
order = self.data[p_data] & 0x0f
order2 = self.data[p_data + 1] & 0x0f if self.pawns[1] else 0x0f
self.files[f].pieces = [self.data[p_data + i + j] & 0x0f for i in range(self.num)]
self.files[f].norm = [0 for _ in range(self.num)]
self.set_norm_pawn(self.files[f].norm, self.files[f].pieces)
self.files[f].factor = [0 for _ in range(TBPIECES)]
self.tb_size[p_tb_size] = self.calc_factors_pawn(self.files[f].factor, order, order2, self.files[f].norm, f)
class Tablebase:
"""
Manages a collection of tablebase files for probing.
If *max_fds* is not ``None``, will at most use *max_fds* open file
descriptors at any given time. The least recently used tables are closed,
if nescessary.
"""
def __init__(self, *, max_fds: Optional[int] = 128, VariantBoard: Type[chess.Board] = chess.Board) -> None:
self.variant = VariantBoard
self.max_fds = max_fds
self.lru = collections.deque() # type: typing.Deque[Table]
self.lru_lock = threading.Lock()
self.wdl = {} # type: MutableMapping[str, WdlTable]
self.dtz = {} # type: MutableMapping[str, DtzTable]
def _bump_lru(self, table: Table) -> None:
if self.max_fds is None:
return
with self.lru_lock:
try:
self.lru.remove(table)
self.lru.appendleft(table)
except ValueError:
self.lru.appendleft(table)
if len(self.lru) > self.max_fds:
self.lru.pop().close()
def _open_table(self, hashtable: MutableMapping[str, Table], Table: Type[Table], path: PathLike) -> int:
table = Table(path, variant=self.variant)
if table.key in hashtable:
hashtable[table.key].close()
hashtable[table.key] = table
hashtable[table.mirrored_key] = table
return 1
def add_directory(self, directory: PathLike, *, load_wdl: bool = True, load_dtz: bool = True) -> int:
"""
Adds tables from a directory.
By default all available tables with the correct file names
(e.g. WDL files like ``KQvKN.rtbw`` and DTZ files like ``KRBvK.rtbz``)
are added.
The relevant files are lazily opened when the tablebase is actually
probed.
Returns the number of table files that were found.
"""
num = 0
directory = os.path.abspath(directory)
for filename in os.listdir(directory):
path = os.path.join(directory, filename)
tablename, ext = os.path.splitext(filename)
if is_table_name(tablename) and os.path.isfile(path):
if load_wdl:
if ext == self.variant.tbw_suffix:
num += self._open_table(self.wdl, WdlTable, path)
elif "P" not in tablename and ext == self.variant.pawnless_tbw_suffix:
num += self._open_table(self.wdl, WdlTable, path)
if load_dtz:
if ext == self.variant.tbz_suffix:
num += self._open_table(self.dtz, DtzTable, path)
elif "P" not in tablename and ext == self.variant.pawnless_tbz_suffix:
num += self._open_table(self.dtz, DtzTable, path)
return num
def probe_wdl_table(self, board: chess.Board) -> int:
# Test for variant end.
if board.is_variant_win():
return 2
elif board.is_variant_draw():
return 0
elif board.is_variant_loss():
return -2
# Test for KvK.
if self.variant.one_king and board.kings == board.occupied:
return 0
key = calc_key(board)
try:
table = self.wdl[key]
except KeyError:
raise MissingTableError("did not find wdl table {}".format(key))
self._bump_lru(table)
return table.probe_wdl_table(board)
def probe_ab(self, board: chess.Board, alpha: int, beta: int, threats: bool = False) -> Tuple[int, int]:
if self.variant.captures_compulsory:
if board.is_variant_win():
return 2, 2
elif board.is_variant_loss():
return -2, 2
elif board.is_variant_draw():
return 0, 2
return self.sprobe_ab(board, alpha, beta, threats)
# Generate non-ep captures.
for move in board.generate_legal_moves(to_mask=board.occupied_co[not board.turn]):
board.push(move)
try:
v_plus, _ = self.probe_ab(board, -beta, -alpha)
v = -v_plus
finally:
board.pop()
if v > alpha:
if v >= beta:
return v, 2
alpha = v
v = self.probe_wdl_table(board)
if alpha >= v:
return alpha, 1 + int(alpha > 0)
else:
return v, 1
def sprobe_ab(self, board: chess.Board, alpha: int, beta: int, threats: bool = False) -> Tuple[int, int]:
if chess.popcount(board.occupied_co[not board.turn]) > 1:
v, captures_found = self.sprobe_capts(board, alpha, beta)
if captures_found:
return v, 2
else:
if any(board.generate_legal_captures()):
return -2, 2
threats_found = False
if threats or chess.popcount(board.occupied) >= 6:
for threat in board.generate_legal_moves(~board.pawns):
board.push(threat)
try:
v_plus, captures_found = self.sprobe_capts(board, -beta, -alpha)
v = -v_plus
finally:
board.pop()
if captures_found and v > alpha:
threats_found = True
alpha = v
if alpha >= beta:
return v, 3
v = self.probe_wdl_table(board)
if v > alpha:
return v, 1
else:
return alpha, 3 if threats_found else 1
def sprobe_capts(self, board: chess.Board, alpha: int, beta: int) -> Tuple[int, int]:
captures_found = False
for move in board.generate_legal_captures():
captures_found = True
board.push(move)
try:
v_plus, _ = self.sprobe_ab(board, -beta, -alpha)
v = -v_plus
finally:
board.pop()
alpha = max(v, alpha)
if alpha >= beta:
break
return alpha, captures_found
def probe_wdl(self, board: chess.Board) -> int:
"""
Probes WDL tables for win/draw/loss-information.
Probing is thread-safe when done with different *board* objects and
if *board* objects are not modified during probing.
Returns ``2`` if the side to move is winning, ``0`` if the position is
a draw and ``-2`` if the side to move is losing.
Returns ``1`` in case of a cursed win and ``-1`` in case of a blessed
loss. Mate can be forced but the position can be drawn due to the
fifty-move rule.
>>> import chess
>>> import chess.syzygy
>>>
>>> with chess.syzygy.open_tablebase("data/syzygy/regular") as tablebase:
... board = chess.Board("8/2K5/4B3/3N4/8/8/4k3/8 b - - 0 1")
... print(tablebase.probe_wdl(board))
...
-2
:raises: :exc:`KeyError` (or specifically
:exc:`chess.syzygy.MissingTableError`) if the position could not
be found in the tablebase. Use
:func:`~chess.syzygy.Tablebase.get_wdl()` if you prefer to get
``None`` instead of an exception.
Note that probing corrupted table files is undefined behavior.
"""
# Positions with castling rights are not in the tablebase.
if board.castling_rights:
raise KeyError("syzygy tables do not contain positions with castling rights: {}".format(board.fen()))
# Validate piece count.
if chess.popcount(board.occupied) > 7:
raise KeyError("syzygy tables support up to 6 (and experimentally 7) pieces, not {}: {}".format(chess.popcount(board.occupied), board.fen()))
# Probe.
v, _ = self.probe_ab(board, -2, 2)
# If en passant is not possible, we are done.
if not board.ep_square or self.variant.captures_compulsory:
return v
# Now handle en passant.
v1 = -3
# Look at all legal en passant captures.
for move in board.generate_legal_ep():
board.push(move)
try:
v0_plus, _ = self.probe_ab(board, -2, 2)
v0 = -v0_plus
finally:
board.pop()
if v0 > v1:
v1 = v0
if v1 > -3:
if v1 >= v:
v = v1
elif v == 0:
# If there is not at least one legal non-en-passant move we are
# forced to play the losing en passant cature.
if all(board.is_en_passant(move) for move in board.generate_legal_moves()):
v = v1
return v
def get_wdl(self, board: chess.Board, default: Optional[int] = None) -> Optional[int]:
try:
return self.probe_wdl(board)
except KeyError:
return default
def probe_dtz_table(self, board: chess.Board, wdl: int) -> Tuple[int, int]:
key = calc_key(board)
try:
table = self.dtz[key]
except KeyError:
raise MissingTableError("did not find dtz table {}".format(key))
self._bump_lru(table)
return table.probe_dtz_table(board, wdl)
def probe_dtz_no_ep(self, board: chess.Board) -> int:
wdl, success = self.probe_ab(board, -2, 2, threats=True)
if wdl == 0:
return 0
if success == 2 or not board.occupied_co[board.turn] & ~board.pawns:
return dtz_before_zeroing(wdl)
if wdl > 0:
# The position is a win or a cursed win by a threat move.
if success == 3:
return 2 if wdl == 2 else 102
# Generate all legal non-capturing pawn moves.
for move in board.generate_legal_moves(board.pawns, ~board.occupied):
if board.is_capture(move):
# En passant.
continue
board.push(move)
try:
v = -self.probe_wdl(board)
finally:
board.pop()
if v == wdl:
return 1 if v == 2 else 101
dtz, success = self.probe_dtz_table(board, wdl)
if success >= 0:
return dtz_before_zeroing(wdl) + (dtz if wdl > 0 else -dtz)
if wdl > 0:
best = 0xffff
for move in board.generate_legal_moves(~board.pawns, ~board.occupied):
board.push(move)
try:
v = -self.probe_dtz(board)
if v == 1 and board.is_checkmate():
best = 1
elif v > 0 and v + 1 < best:
best = v + 1
finally:
board.pop()
return best
else:
best = -1
for move in board.generate_legal_moves():
board.push(move)
try:
if board.halfmove_clock == 0:
if wdl == -2:
v = -1
else:
v, success = self.probe_ab(board, 1, 2, threats=True)
v = 0 if v == 2 else -101
else:
v = -self.probe_dtz(board) - 1
finally:
board.pop()
if v < best:
best = v
return best
def probe_dtz(self, board: chess.Board) -> int:
"""
Probes DTZ tables for distance to zero information.
Both DTZ and WDL tables are required in order to probe for DTZ.
Returns a positive value if the side to move is winning, ``0`` if the
position is a draw and a negative value if the side to move is losing.
More precisely:
+-----+------------------+--------------------------------------------+
| WDL | DTZ | |
+=====+==================+============================================+
| -2 | -100 <= n <= -1 | Unconditional loss (assuming 50-move |
| | | counter is zero), where a zeroing move can |
| | | be forced in -n plies. |
+-----+------------------+--------------------------------------------+
| -1 | n < -100 | Loss, but draw under the 50-move rule. |
| | | A zeroing move can be forced in -n plies |
| | | or -n - 100 plies (if a later phase is |
| | | responsible for the blessed loss). |
+-----+------------------+--------------------------------------------+
| 0 | 0 | Draw. |
+-----+------------------+--------------------------------------------+
| 1 | 100 < n | Win, but draw under the 50-move rule. |
| | | A zeroing move can be forced in n plies or |
| | | n - 100 plies (if a later phase is |
| | | responsible for the cursed win). |
+-----+------------------+--------------------------------------------+
| 2 | 1 <= n <= 100 | Unconditional win (assuming 50-move |
| | | counter is zero), where a zeroing move can |
| | | be forced in n plies. |
+-----+------------------+--------------------------------------------+
The return value can be off by one: a return value -n can mean a
losing zeroing move in in n + 1 plies and a return value +n can mean a
winning zeroing move in n + 1 plies.
This is guaranteed not to happen for positions exactly on the edge of
the 50-move rule, so that (with some care) this never impacts the
result of practical play.
Minmaxing the DTZ values guarantees winning a won position (and drawing
a drawn position), because it makes progress keeping the win in hand.
However the lines are not always the most straightforward ways to win.
Engines like Stockfish calculate themselves, checking with DTZ, but
only play according to DTZ if they can not manage on their own.
>>> import chess
>>> import chess.syzygy
>>>
>>> with chess.syzygy.open_tablebase("data/syzygy/regular") as tablebase:
... board = chess.Board("8/2K5/4B3/3N4/8/8/4k3/8 b - - 0 1")
... print(tablebase.probe_dtz(board))
...
-53
Probing is thread-safe when done with different *board* objects and
if *board* objects are not modified during probing.
:raises: :exc:`KeyError` (or specifically
:exc:`chess.syzygy.MissingTableError`) if the position could not
be found in the tablebase. Use
:func:`~chess.syzygy.Tablebase.get_dtz()` if you prefer to get
``None`` instead of an exception.
Note that probing corrupted table files is undefined behavior.
"""
v = self.probe_dtz_no_ep(board)
if not board.ep_square or self.variant.captures_compulsory:
return v
v1 = -3
# Generate all en-passant moves.
for move in board.generate_legal_ep():
board.push(move)
try:
v0_plus, _ = self.probe_ab(board, -2, 2)
v0 = -v0_plus
finally:
board.pop()
if v0 > v1:
v1 = v0
if v1 > -3:
v1 = WDL_TO_DTZ[v1 + 2]
if v < -100:
if v1 >= 0:
v = v1
elif v < 0:
if v1 >= 0 or v1 < -100:
v = v1
elif v > 100:
if v1 > 0:
v = v1
elif v > 0:
if v1 == 1:
v = v1
elif v1 >= 0:
v = v1
else:
if all(board.is_en_passant(move) for move in board.generate_legal_moves()):
v = v1
return v
def get_dtz(self, board: chess.Board, default: Optional[int] = None) -> Optional[int]:
try:
return self.probe_dtz(board)
except KeyError:
return default
def close(self) -> None:
"""Closes all loaded tables."""
while self.wdl:
_, wdl = self.wdl.popitem()
wdl.close()
while self.dtz:
_, dtz = self.dtz.popitem()
dtz.close()
self.lru.clear()
def __enter__(self) -> "Tablebase":
return self
def __exit__(self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType]) -> None:
self.close()
def open_tablebase(directory: PathLike, *, load_wdl: bool = True, load_dtz: bool = True, max_fds: Optional[int] = 128, VariantBoard: Type[chess.Board] = chess.Board) -> Tablebase:
"""
Opens a collection of tables for probing. See
:class:`~chess.syzygy.Tablebase`.
.. note::
Generally probing requires tablebase files for the specific
material composition, **as well as** tablebase files with less pieces.
This is important because 6-piece and 5-piece files are often
distributed seperately, but are both required for 6-piece positions.
Use :func:`~chess.syzygy.Tablebase.add_directory()` to load
tables from additional directories.
"""
tables = Tablebase(max_fds=max_fds, VariantBoard=VariantBoard)
tables.add_directory(directory, load_wdl=load_wdl, load_dtz=load_dtz)
return tables
| [
"mmap.mmap",
"re.compile",
"chess.square_file",
"chess.popcount",
"os.listdir",
"collections.deque",
"chess.scan_forward",
"threading.Lock",
"threading.RLock",
"threading.Condition",
"math.factorial",
"os.close",
"os.path.splitext",
"os.path.isfile",
"struct.Struct",
"chess.square_rank... | [((1048, 1067), 'struct.Struct', 'struct.Struct', (['""">Q"""'], {}), "('>Q')\n", (1061, 1067), False, 'import struct\n'), ((1077, 1096), 'struct.Struct', 'struct.Struct', (['"""<I"""'], {}), "('<I')\n", (1090, 1096), False, 'import struct\n'), ((1109, 1128), 'struct.Struct', 'struct.Struct', (['""">I"""'], {}), "('>I')\n", (1122, 1128), False, 'import struct\n'), ((1138, 1157), 'struct.Struct', 'struct.Struct', (['"""<H"""'], {}), "('<H')\n", (1151, 1157), False, 'import struct\n'), ((12037, 12074), 're.compile', 're.compile', (['"""^[KQRBNP]+v[KQRBNP]+\\\\Z"""'], {}), "('^[KQRBNP]+v[KQRBNP]+\\\\Z')\n", (12047, 12074), False, 'import re\n'), ((1517, 1542), 'chess.square_rank', 'chess.square_rank', (['square'], {}), '(square)\n', (1534, 1542), False, 'import chess\n'), ((1545, 1570), 'chess.square_file', 'chess.square_file', (['square'], {}), '(square)\n', (1562, 1570), False, 'import chess\n'), ((17139, 17156), 'threading.RLock', 'threading.RLock', ([], {}), '()\n', (17154, 17156), False, 'import threading\n'), ((17269, 17290), 'threading.Condition', 'threading.Condition', ([], {}), '()\n', (17288, 17290), False, 'import threading\n'), ((50740, 50759), 'collections.deque', 'collections.deque', ([], {}), '()\n', (50757, 50759), False, 'import collections\n'), ((50813, 50829), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (50827, 50829), False, 'import threading\n'), ((52211, 52237), 'os.path.abspath', 'os.path.abspath', (['directory'], {}), '(directory)\n', (52226, 52237), False, 'import os\n'), ((52263, 52284), 'os.listdir', 'os.listdir', (['directory'], {}), '(directory)\n', (52273, 52284), False, 'import os\n'), ((10834, 10855), 'math.factorial', 'math.factorial', (['(x - y)'], {}), '(x - y)\n', (10848, 10855), False, 'import math\n'), ((17360, 17382), 'os.path.basename', 'os.path.basename', (['path'], {}), '(path)\n', (17376, 17382), False, 'import os\n'), ((41370, 41392), 'chess.scan_forward', 'chess.scan_forward', (['bb'], {}), '(bb)\n', (41388, 41392), False, 'import chess\n'), ((48167, 48189), 'chess.scan_forward', 'chess.scan_forward', (['bb'], {}), '(bb)\n', (48185, 48189), False, 'import chess\n'), ((52305, 52338), 'os.path.join', 'os.path.join', (['directory', 'filename'], {}), '(directory, filename)\n', (52317, 52338), False, 'import os\n'), ((52368, 52394), 'os.path.splitext', 'os.path.splitext', (['filename'], {}), '(filename)\n', (52384, 52394), False, 'import os\n'), ((54892, 54941), 'chess.popcount', 'chess.popcount', (['board.occupied_co[not board.turn]'], {}), '(board.occupied_co[not board.turn])\n', (54906, 54941), False, 'import chess\n'), ((57945, 57975), 'chess.popcount', 'chess.popcount', (['board.occupied'], {}), '(board.occupied)\n', (57959, 57975), False, 'import chess\n'), ((10792, 10809), 'math.factorial', 'math.factorial', (['x'], {}), '(x)\n', (10806, 10809), False, 'import math\n'), ((10813, 10830), 'math.factorial', 'math.factorial', (['y'], {}), '(y)\n', (10827, 10830), False, 'import math\n'), ((14594, 14625), 'chess.popcount', 'chess.popcount', (['(board.kings & w)'], {}), '(board.kings & w)\n', (14608, 14625), False, 'import chess\n'), ((14641, 14673), 'chess.popcount', 'chess.popcount', (['(board.queens & w)'], {}), '(board.queens & w)\n', (14655, 14673), False, 'import chess\n'), ((14689, 14720), 'chess.popcount', 'chess.popcount', (['(board.rooks & w)'], {}), '(board.rooks & w)\n', (14703, 14720), False, 'import chess\n'), ((14736, 14769), 'chess.popcount', 'chess.popcount', (['(board.bishops & w)'], {}), '(board.bishops & w)\n', (14750, 14769), False, 'import chess\n'), ((14785, 14818), 'chess.popcount', 'chess.popcount', (['(board.knights & w)'], {}), '(board.knights & w)\n', (14799, 14818), False, 'import chess\n'), ((14834, 14865), 'chess.popcount', 'chess.popcount', (['(board.pawns & w)'], {}), '(board.pawns & w)\n', (14848, 14865), False, 'import chess\n'), ((14894, 14925), 'chess.popcount', 'chess.popcount', (['(board.kings & b)'], {}), '(board.kings & b)\n', (14908, 14925), False, 'import chess\n'), ((14941, 14973), 'chess.popcount', 'chess.popcount', (['(board.queens & b)'], {}), '(board.queens & b)\n', (14955, 14973), False, 'import chess\n'), ((14989, 15020), 'chess.popcount', 'chess.popcount', (['(board.rooks & b)'], {}), '(board.rooks & b)\n', (15003, 15020), False, 'import chess\n'), ((15036, 15069), 'chess.popcount', 'chess.popcount', (['(board.bishops & b)'], {}), '(board.bishops & b)\n', (15050, 15069), False, 'import chess\n'), ((15085, 15118), 'chess.popcount', 'chess.popcount', (['(board.knights & b)'], {}), '(board.knights & b)\n', (15099, 15118), False, 'import chess\n'), ((15134, 15165), 'chess.popcount', 'chess.popcount', (['(board.pawns & b)'], {}), '(board.pawns & b)\n', (15148, 15165), False, 'import chess\n'), ((19177, 19223), 'mmap.mmap', 'mmap.mmap', (['self.fd', '(0)'], {'access': 'mmap.ACCESS_READ'}), '(self.fd, 0, access=mmap.ACCESS_READ)\n', (19186, 19223), False, 'import mmap\n'), ((40832, 40854), 'chess.scan_forward', 'chess.scan_forward', (['bb'], {}), '(bb)\n', (40850, 40854), False, 'import chess\n'), ((41783, 41805), 'chess.scan_forward', 'chess.scan_forward', (['bb'], {}), '(bb)\n', (41801, 41805), False, 'import chess\n'), ((47272, 47294), 'chess.scan_forward', 'chess.scan_forward', (['bb'], {}), '(bb)\n', (47290, 47294), False, 'import chess\n'), ((48645, 48667), 'chess.scan_forward', 'chess.scan_forward', (['bb'], {}), '(bb)\n', (48663, 48667), False, 'import chess\n'), ((52440, 52460), 'os.path.isfile', 'os.path.isfile', (['path'], {}), '(path)\n', (52454, 52460), False, 'import os\n'), ((55226, 55256), 'chess.popcount', 'chess.popcount', (['board.occupied'], {}), '(board.occupied)\n', (55240, 55256), False, 'import chess\n'), ((33304, 33321), 'os.close', 'os.close', (['self.fd'], {}), '(self.fd)\n', (33312, 33321), False, 'import os\n'), ((58089, 58119), 'chess.popcount', 'chess.popcount', (['board.occupied'], {}), '(board.occupied)\n', (58103, 58119), False, 'import chess\n')] |
from materializationengine.models import AnalysisTable, AnalysisVersion
from flask_marshmallow import Marshmallow
from marshmallow import fields, ValidationError, Schema
from marshmallow_sqlalchemy import SQLAlchemyAutoSchema
ma = Marshmallow()
class AnalysisVersionSchema(SQLAlchemyAutoSchema):
class Meta:
model = AnalysisVersion
load_instance = True
class AnalysisTableSchema(SQLAlchemyAutoSchema):
class Meta:
model = AnalysisTable
load_instance = True
class CronField(fields.Field):
def _deserialize(self, value, attr, data, **kwargs):
if isinstance(value, (str, int, list)):
return value
else:
raise ValidationError("Field should be str, int or list")
class CeleryBeatSchema(Schema):
name = fields.Str(required=True)
minute = CronField(default="*")
hour = CronField(default="*")
day_of_week = CronField(default="*")
day_of_month = CronField(default="*")
month_of_year = CronField(default="*")
task = fields.Str(required=True)
| [
"flask_marshmallow.Marshmallow",
"marshmallow.fields.Str",
"marshmallow.ValidationError"
] | [((232, 245), 'flask_marshmallow.Marshmallow', 'Marshmallow', ([], {}), '()\n', (243, 245), False, 'from flask_marshmallow import Marshmallow\n'), ((794, 819), 'marshmallow.fields.Str', 'fields.Str', ([], {'required': '(True)'}), '(required=True)\n', (804, 819), False, 'from marshmallow import fields, ValidationError, Schema\n'), ((1027, 1052), 'marshmallow.fields.Str', 'fields.Str', ([], {'required': '(True)'}), '(required=True)\n', (1037, 1052), False, 'from marshmallow import fields, ValidationError, Schema\n'), ((697, 748), 'marshmallow.ValidationError', 'ValidationError', (['"""Field should be str, int or list"""'], {}), "('Field should be str, int or list')\n", (712, 748), False, 'from marshmallow import fields, ValidationError, Schema\n')] |
import os
import jwt
import time
import unittest
from django.conf import settings
from django.test import RequestFactory
from sparrow_cloud.middleware.acl_middleware import ACLMiddleware
from django.http import JsonResponse
os.environ["DJANGO_SETTINGS_MODULE"] = "tests.mock_settings"
def token():
private_key = settings.PRIVATE_KEY
payload = {
"service_name": 'test',
"ALL": 1,
"permission": [],
"exp": int(time.time() + 60*60),
"iat": int(time.time()),
"iss": "ACL"
}
acl_token = jwt.encode(payload, private_key, algorithm='RS256')
return acl_token
class TestACLMiddleware(unittest.TestCase):
rf = RequestFactory()
TOKEN = token()
def setUp(self):
os.environ["DJANGO_SETTINGS_MODULE"] = "tests.mock_settings"
def test_acl(self):
"""测试 没有remote_user 和错误的 acl token """
request = self.rf.get('/acl', {'acl_token': '<KEY>'})
self.assertEqual(ACLMiddleware().process_request(request).status_code,
JsonResponse({"message": "ACL验证未通过"}, status=403).status_code)
def test_acl1(self):
"""测试 没有remote_user 和正确的 acl token """
request = self.rf.get('/acl', {'acl_token': self.TOKEN})
self.assertEqual(ACLMiddleware().process_request(request), None)
def test_acl2(self):
"""测试 有remote_user 和正确的 acl token """
rf1 = RequestFactory(REMOTE_USER='sssssssss')
request = rf1.get('/acl', {'acl_token': self.TOKEN})
self.assertEqual(ACLMiddleware().process_request(request), None)
def test_acl3(self):
"""测试 有remote_user 和错误的 acl token """
rf1 = RequestFactory(REMOTE_USER='sssssssss')
request = rf1.get('/acl', {'acl_token': '123dsafsafaq321dsknfdsj358q744'})
self.assertEqual(ACLMiddleware().process_request(request).status_code,
JsonResponse({"message": "ACL验证未通过"}, status=403).status_code)
def test_acl4(self):
"""测试 没有 acl token """
request = self.rf.get('/acl')
self.assertEqual(ACLMiddleware().process_request(request), None)
def tearDown(self):
del os.environ["DJANGO_SETTINGS_MODULE"]
if __name__ == '__main__':
unittest.main()
| [
"django.test.RequestFactory",
"django.http.JsonResponse",
"unittest.main",
"sparrow_cloud.middleware.acl_middleware.ACLMiddleware",
"time.time",
"jwt.encode"
] | [((550, 601), 'jwt.encode', 'jwt.encode', (['payload', 'private_key'], {'algorithm': '"""RS256"""'}), "(payload, private_key, algorithm='RS256')\n", (560, 601), False, 'import jwt\n'), ((678, 694), 'django.test.RequestFactory', 'RequestFactory', ([], {}), '()\n', (692, 694), False, 'from django.test import RequestFactory\n'), ((2229, 2244), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2242, 2244), False, 'import unittest\n'), ((1404, 1443), 'django.test.RequestFactory', 'RequestFactory', ([], {'REMOTE_USER': '"""sssssssss"""'}), "(REMOTE_USER='sssssssss')\n", (1418, 1443), False, 'from django.test import RequestFactory\n'), ((1664, 1703), 'django.test.RequestFactory', 'RequestFactory', ([], {'REMOTE_USER': '"""sssssssss"""'}), "(REMOTE_USER='sssssssss')\n", (1678, 1703), False, 'from django.test import RequestFactory\n'), ((493, 504), 'time.time', 'time.time', ([], {}), '()\n', (502, 504), False, 'import time\n'), ((452, 463), 'time.time', 'time.time', ([], {}), '()\n', (461, 463), False, 'import time\n'), ((1044, 1093), 'django.http.JsonResponse', 'JsonResponse', (["{'message': 'ACL验证未通过'}"], {'status': '(403)'}), "({'message': 'ACL验证未通过'}, status=403)\n", (1056, 1093), False, 'from django.http import JsonResponse\n'), ((1891, 1940), 'django.http.JsonResponse', 'JsonResponse', (["{'message': 'ACL验证未通过'}"], {'status': '(403)'}), "({'message': 'ACL验证未通过'}, status=403)\n", (1903, 1940), False, 'from django.http import JsonResponse\n'), ((1270, 1285), 'sparrow_cloud.middleware.acl_middleware.ACLMiddleware', 'ACLMiddleware', ([], {}), '()\n', (1283, 1285), False, 'from sparrow_cloud.middleware.acl_middleware import ACLMiddleware\n'), ((1530, 1545), 'sparrow_cloud.middleware.acl_middleware.ACLMiddleware', 'ACLMiddleware', ([], {}), '()\n', (1543, 1545), False, 'from sparrow_cloud.middleware.acl_middleware import ACLMiddleware\n'), ((2074, 2089), 'sparrow_cloud.middleware.acl_middleware.ACLMiddleware', 'ACLMiddleware', ([], {}), '()\n', (2087, 2089), False, 'from sparrow_cloud.middleware.acl_middleware import ACLMiddleware\n'), ((965, 980), 'sparrow_cloud.middleware.acl_middleware.ACLMiddleware', 'ACLMiddleware', ([], {}), '()\n', (978, 980), False, 'from sparrow_cloud.middleware.acl_middleware import ACLMiddleware\n'), ((1812, 1827), 'sparrow_cloud.middleware.acl_middleware.ACLMiddleware', 'ACLMiddleware', ([], {}), '()\n', (1825, 1827), False, 'from sparrow_cloud.middleware.acl_middleware import ACLMiddleware\n')] |
# Adafruit PN532 NFC/RFID control library.
# Author: <NAME>
#
# The MIT License (MIT)
#
# Copyright (c) 2015-2018 Adafruit Industries
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
``adafruit_pn532.spi``
====================================================
This module will let you communicate with a PN532 RFID/NFC shield or breakout
using SPI.
* Author(s): Original Raspberry Pi code by <NAME>, CircuitPython by ladyada,
refactor by <NAME>
"""
__version__ = "0.0.0-auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_PN532.git"
import time
import adafruit_bus_device.spi_device as spi_device
from micropython import const
from adafruit_pn532HCE.adafruit_pn532HCE import PN532
# pylint: disable=bad-whitespace
_SPI_STATREAD = const(0x02)
_SPI_DATAWRITE = const(0x01)
_SPI_DATAREAD = const(0x03)
_SPI_READY = const(0x01)
def reverse_bit(num):
"""Turn an LSB byte to an MSB byte, and vice versa. Used for SPI as
it is LSB for the PN532, but 99% of SPI implementations are MSB only!"""
result = 0
for _ in range(8):
result <<= 1
result += (num & 1)
num >>= 1
return result
class PN532_SPI(PN532):
"""Driver for the PN532 connected over SPI. Pass in a hardware or bitbang
SPI device & chip select digitalInOut pin. Optional IRQ pin (not used),
reset pin and debugging output."""
def __init__(self, spi, cs_pin, *, irq=None, reset=None, debug=False):
"""Create an instance of the PN532 class using SPI"""
self.debug = debug
self._irq = irq
self._spi = spi_device.SPIDevice(spi, cs_pin)
super().__init__(debug=debug, reset=reset)
def _wakeup(self):
"""Send any special commands/data to wake up PN532"""
with self._spi as spi:
time.sleep(1)
spi.write(bytearray([0x00])) #pylint: disable=no-member
time.sleep(1)
def _wait_ready(self, timeout=1):
"""Poll PN532 if status byte is ready, up to `timeout` seconds"""
status = bytearray([reverse_bit(_SPI_STATREAD), 0])
timestamp = time.monotonic()
while (time.monotonic() - timestamp) < timeout:
with self._spi as spi:
time.sleep(0.02) # required
spi.write_readinto(status, status) #pylint: disable=no-member
if reverse_bit(status[1]) == 0x01: # LSB data is read in MSB
return True # Not busy anymore!
else:
time.sleep(0.01) # pause a bit till we ask again
# We timed out!
return False
def _read_data(self, count):
"""Read a specified count of bytes from the PN532."""
# Build a read request frame.
frame = bytearray(count+1)
# Add the SPI data read signal byte, but LSB'ify it
frame[0] = reverse_bit(_SPI_DATAREAD)
with self._spi as spi:
time.sleep(0.02) # required
spi.write_readinto(frame, frame) #pylint: disable=no-member
for i, val in enumerate(frame):
frame[i] = reverse_bit(val) # turn LSB data to MSB
if self.debug:
print("Reading: ", [hex(i) for i in frame[1:]])
return frame[1:]
def _write_data(self, framebytes):
"""Write a specified count of bytes to the PN532"""
# start by making a frame with data write in front,
# then rest of bytes, and LSBify it
rev_frame = [reverse_bit(x) for x in bytes([_SPI_DATAWRITE]) + framebytes]
if self.debug:
print("Writing: ", [hex(i) for i in rev_frame])
with self._spi as spi:
time.sleep(0.02) # required
spi.write(bytes(rev_frame)) #pylint: disable=no-member
| [
"adafruit_bus_device.spi_device.SPIDevice",
"time.monotonic",
"time.sleep",
"micropython.const"
] | [((1796, 1804), 'micropython.const', 'const', (['(2)'], {}), '(2)\n', (1801, 1804), False, 'from micropython import const\n'), ((1841, 1849), 'micropython.const', 'const', (['(1)'], {}), '(1)\n', (1846, 1849), False, 'from micropython import const\n'), ((1886, 1894), 'micropython.const', 'const', (['(3)'], {}), '(3)\n', (1891, 1894), False, 'from micropython import const\n'), ((1931, 1939), 'micropython.const', 'const', (['(1)'], {}), '(1)\n', (1936, 1939), False, 'from micropython import const\n'), ((2664, 2697), 'adafruit_bus_device.spi_device.SPIDevice', 'spi_device.SPIDevice', (['spi', 'cs_pin'], {}), '(spi, cs_pin)\n', (2684, 2697), True, 'import adafruit_bus_device.spi_device as spi_device\n'), ((3180, 3196), 'time.monotonic', 'time.monotonic', ([], {}), '()\n', (3194, 3196), False, 'import time\n'), ((2878, 2891), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (2888, 2891), False, 'import time\n'), ((2972, 2985), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (2982, 2985), False, 'import time\n'), ((3987, 4003), 'time.sleep', 'time.sleep', (['(0.02)'], {}), '(0.02)\n', (3997, 4003), False, 'import time\n'), ((4713, 4729), 'time.sleep', 'time.sleep', (['(0.02)'], {}), '(0.02)\n', (4723, 4729), False, 'import time\n'), ((3212, 3228), 'time.monotonic', 'time.monotonic', ([], {}), '()\n', (3226, 3228), False, 'import time\n'), ((3304, 3320), 'time.sleep', 'time.sleep', (['(0.02)'], {}), '(0.02)\n', (3314, 3320), False, 'import time\n'), ((3573, 3589), 'time.sleep', 'time.sleep', (['(0.01)'], {}), '(0.01)\n', (3583, 3589), False, 'import time\n')] |
import configargparse
from lxml import etree, objectify
from rich import console
from rich.console import Console
import importlib.metadata
import re
__version__ = importlib.metadata.version('camel-xml2dsl')
ns = {"camel": "http://camel.apache.org/schema/spring"}
console = Console()
class Converter:
def __init__(self):
self.dsl_route = ''
def xml_to_dsl(self):
p = configargparse.ArgParser(
description="Transforms xml routes to dsl routes " + __version__)
p.add_argument('--xml', metavar='xml', type=str,
help='xml camel context file', required=True, env_var='XML_CTX_INPUT')
p.add_argument('--beans', metavar='beans', type=str,
help='use beans instead processors', required=False, env_var='USE_BEANS')
args = p.parse_args()
with open(args.xml, "r") as xml_file:
parser = etree.XMLParser(remove_comments=True)
data = objectify.parse(xml_file, parser=parser)
console.log(" XML 2 DSL Utility ", style="bold red")
root = data.getroot()
for camelContext in root.findall('camel:camelContext', ns):
if 'id' in camelContext.attrib:
console.log("processing camel context", camelContext.attrib['id'])
self.get_namespaces(camelContext)
self.dsl_route = self.analyze_node(camelContext)
print("dsl route:\n", self.dsl_route)
def get_namespaces(self, node):
console.log("namespaces:", node.nsmap)
def analyze_node(self, node):
dslText = ""
for child in node:
node_name = child.tag.partition('}')[2] + "_def"
console.log("procesing node", node_name, child.tag, child.sourceline)
dslText += getattr(self, node_name)(child)
return dslText
def analyze_element(self, node):
node_name = node.tag.partition('}')[2] + "_def"
console.log("procesing node", node_name, node.tag, node.sourceline)
return getattr(self, node_name)(node)
def route_def(self, node):
route_def = self.analyze_node(node)
route_def += "\n.end();\n"
return route_def
def propertyPlaceholder_def(self, node):
return ""
def dataFormats_def(self, node):
return '\n//TODO: define dataformat ' + node[0].tag + '\n'
def endpoint_def(self, node):
return ""
def multicast_def(self, node):
multicast_def = "\n.multicast()"
multicast_def += self.analyze_node(node)
multicast_def += "\n.end() //end multicast"
return multicast_def
def bean_def(self, node):
if 'method' in node.attrib:
return '\n.bean("' + node.attrib['ref'] + '","'+ node.attrib['method'] + '")'
elif 'beanType' in node.attrib:
return '\n.bean("' + node.attrib['ref'] + '","'+ node.attrib['beanType'] + '")'
else:
return '\n.bean("' + node.attrib['ref'] + '")'
def aggregator_def(self, node):
return "//TODO: Aggregator"
def recipientList_def(self, node):
recipient_def = "\n.recipientList()."
recipient_def += self.analyze_node(node)
recipient_def += ".end() // end recipientList"
return recipient_def
def errorHandler_def(self, node):
if node.attrib['type'] == "DefaultErrorHandler":
return "\ndefaultErrorHandler().setRedeliveryPolicy(policy);"
def redeliveryPolicyProfile_def(self, node):
policy_def = "\nRedeliveryPolicy policy = new RedeliveryPolicy()"
if "maximumRedeliveries" in node.attrib:
policy_def += ".maximumRedeliveries("+ node.attrib["maximumRedeliveries"]+")"
if "retryAttemptedLogLevel" in node.attrib:
policy_def += ".retryAttemptedLogLevel(LoggingLevel." + node.attrib["retryAttemptedLogLevel"] +")"
if "redeliveryDelay" in node.attrib:
policy_def += ".redeliveryDelay("+ node.attrib["redeliveryDelay"] +")"
if "logRetryAttempted" in node.attrib:
policy_def += ".logRetryAttempted("+node.attrib["logRetryAttempted"] +")"
if "logRetryStackTrace" in node.attrib:
policy_def += ".logRetryStackTrace("+node.attrib["logRetryStackTrace"]+")"
policy_def += ";"
return policy_def
def onException_def(self, node):
exceptions = []
for exception in node.findall("camel:exception", ns):
exceptions.append(exception.text + ".class")
node.remove(exception)
exceptions = ','.join(exceptions)
onException_def = '\nonException(' + exceptions + ')'
handled = node.find("camel:handled", ns)
if handled is not None:
onException_def += '.handled(' + handled[0].text + ')'
node.remove(handled)
redeliveryPolicy = node.find("camel:redeliveryPolicy", ns)
if redeliveryPolicy is not None:
onException_def += '\n.maximumRedeliveries('+redeliveryPolicy.attrib['maximumRedeliveries'] + \
')' if 'maximumRedeliveries' in redeliveryPolicy.attrib else ""
onException_def += '\n.redeliveryDelay('+redeliveryPolicy.attrib['redeliveryDelay'] + \
')' if 'redeliveryDelay' in redeliveryPolicy.attrib else ""
onException_def += '\n.retryAttemptedLogLevel(LoggingLevel.' + \
redeliveryPolicy.attrib['retryAttemptedLogLevel'] + \
')' if 'retryAttemptedLogLevel' in redeliveryPolicy.attrib else ""
onException_def += '\n.retriesExhaustedLogLevel(LoggingLevel.' + \
redeliveryPolicy.attrib['retriesExhaustedLogLevel'] + \
')' if 'retriesExhaustedLogLevel' in redeliveryPolicy.attrib else ""
node.remove(redeliveryPolicy)
if "redeliveryPolicyRef" in node.attrib:
onException_def += ".redeliveryPolicy(policy)"
onException_def += self.analyze_node(node)
onException_def += "\n.end();\n"
return onException_def
def description_def(self, node):
if node.text:
return "//" + node.text + "\n"
else:
return ""
def from_def(self, node):
routeId = node.getparent().attrib['id']
routeFrom = node.attrib['uri']
from_def = '\nfrom("' + routeFrom+'").routeId("' + routeId + '")'
from_def += self.analyze_node(node)
return from_def
def log_def(self, node):
if 'loggingLevel' in node.attrib and node.attrib['loggingLevel'] != 'INFO' :
return '\n.log(LoggingLevel.' + node.attrib['loggingLevel'] + ', "' + self.deprecatedProcessor(node.attrib['message']) + '")'
else:
return '\n.log("' + self.deprecatedProcessor(node.attrib['message']) + '")'
def choice_def(self, node):
choice_def = '\n.choice() //' + str(node.sourceline)
choice_def += self.analyze_node(node)
parent = node.getparent()
if parent.tag != '{'+ns['camel']+'}route':
choice_def += "\n.endChoice() //" + str(node.sourceline)
else:
choice_def += "\n.end() //end choice " + str(node.sourceline)
return choice_def
def when_def(self, node):
return '\n.when().' + self.analyze_node(node)
def otherwise_def(self, node):
return '\n.otherwise()' + self.analyze_node(node)
def simple_def(self, node):
simple_def = ""
if node.text is not None:
simple_def = 'simple("' + self.deprecatedProcessor(node.text) + '")'
else:
simple_def = 'simple("")'
if "resultType" in node.attrib:
simple_def += ".resultType("+ node.attrib["resultType"]+".class)"
return simple_def
def constant_def(self, node):
if node.text is not None:
return 'constant("' + node.text + '")'
else:
return 'constant("")'
def groovy_def(self, node):
text = node.text.replace('"','\'')
return 'groovy("' + text + '")'
def xpath_def(self, node):
xpath_def = 'xpath("' + node.text + '")'
if 'resultType' in node.attrib:
xpath_def = 'xpath("' + node.text + '",' + \
node.attrib['resultType']+'.class)'
if 'saxon' in node.attrib:
xpath_def += '.saxon()'
return xpath_def
def jsonpath_def(self, node):
jsonpath_def = 'jsonpath("' + node.text + '")'
if 'resultType' in node.attrib:
jsonpath_def = 'jsonpath("' + node.text + '",' + \
node.attrib['resultType']+'.class)'
return jsonpath_def
def to_def(self, node):
if 'pattern' in node.attrib and 'InOnly' in node.attrib['pattern']:
return '\n.inOnly("' + self.componentOptions(node.attrib['uri']) + '")'
else:
return '\n.to("' + self.componentOptions(node.attrib['uri']) + '")'
def setBody_def(self, node):
setBody_predicate = self.analyze_element(node[0])
return '\n.setBody(' + setBody_predicate + ')'
def convertBodyTo_def(self, node):
return '\n.convertBodyTo('+ node.attrib['type'] + '.class)'
def unmarshal_def(self, node):
if 'ref' in node.attrib:
return '\n.unmarshal("' + node.attrib['ref']+ '") //TODO: define dataformat'
else:
return '\n.unmarshal()' + self.analyze_node(node)
def marshal_def(self, node):
if 'ref' in node.attrib:
return '\n.marshal("' + node.attrib['ref']+ '") //TODO: define dataformat'
else:
return '\n.marshal()' + self.analyze_node(node)
def jaxb_def(self, node):
if 'prettyPrint' in node.attrib:
return '.jaxb("' + node.attrib['contextPath']+'")'
else:
return '.jaxb("' + node.attrib['contextPath']+'")'
def setHeader_def(self, node):
setHeader_predicate = self.analyze_element(node[0])
return '\n.setHeader("'+node.attrib['headerName']+'",' + setHeader_predicate+')'
def setProperty_def(self, node):
setProperty_predicate = self.analyze_element(node[0])
return '\n.setProperty("' + node.attrib['propertyName']+'",' + setProperty_predicate + ')'
def process_def(self, node):
return '\n.process("' + node.attrib["ref"]+'")'
def inOnly_def(self, node):
return '\n.inOnly("' + node.attrib["uri"]+'")'
def split_def(self, node):
split_def = '\n.split().'
split_def += self.analyze_element(node[0])
if 'streaming' in node.attrib:
split_def += '.streaming()'
if 'strategyRef' in node.attrib:
split_def += '.aggregationStrategyRef("' + node.attrib["strategyRef"] + '")'
if 'parallelProcessing' in node.attrib:
split_def += '.parallelProcessing()'
node.remove(node[0]) # remove first child as was processed
split_def += self.analyze_node(node)
split_def += '\n.end() //end split'
return split_def
def removeHeaders_def(self, node):
if 'excludePattern' in node.attrib:
return '\n.removeHeaders("' + node.attrib['pattern']+'", "' + node.attrib['excludePattern']+'")'
else:
return '\n.removeHeaders("' + node.attrib['pattern']+'")'
def removeHeader_def(self, node):
return '\n.removeHeaders("' + node.attrib['headerName']+'")'
def xquery_def(self, node):
return 'xquery("'+ node.text +'") //xquery not finished please review'
def doTry_def(self, node):
doTry_def = "\n.doTry()"
doTry_def += self.analyze_node(node)
return doTry_def
def doCatch_def(self, node):
exceptions = []
for exception in node.findall("camel:exception", ns):
exceptions.append(exception.text + ".class")
node.remove(exception)
exceptions = ','.join(exceptions)
doCatch_def = '\n.endDoTry()'
doCatch_def += '\n.doCatch(' + exceptions + ')'
doCatch_def += self.analyze_node(node)
doCatch_def += "\n.end() //end doCatch"
return doCatch_def
def handled_def(self, node):
return '.handled(' + node[0].text + ')'
def transacted_def(self, node):
return ""
def wireTap_def(self, node):
if 'executorServiceRef' in node.attrib:
return '\n.wireTap("'+ node.attrib['uri'] +'").executorServiceRef("profile")'
else:
return '\n.wireTap("'+ node.attrib['uri'] +'")'
def language_def(self, node):
return 'language("'+ node.attrib['language']+'","'+ node.text +'")'
def threads_def(self, node):
threads_def = None
maxPoolSize = node.attrib['maxPoolSize'] if 'maxPoolSize' in node.attrib else None
poolSize = node.attrib['poolSize'] if 'poolSize' in node.attrib else None
if poolSize is None and maxPoolSize is not None:
poolSize = maxPoolSize
if poolSize is not None and maxPoolSize is None:
maxPoolSize = poolSize
if 'threadName' in node.attrib:
threads_def = '\n.threads('+ poolSize+','+ maxPoolSize+',"'+ node.attrib['threadName']+'")'
else:
threads_def = '\n.threads('+ poolSize+','+ maxPoolSize+')'
threads_def += self.analyze_node(node)
threads_def += "\n.end() //end threads"
return threads_def
def delay_def(self, node):
delay_def = '\n.delay().'
delay_def += self.analyze_node(node)
return delay_def
def javaScript_def(self, node):
return 'new JavaScriptExpression("'+ node.text +'")'
def threadPoolProfile_def(self, node):
profileDef = '\nThreadPoolProfile profile = new ThreadPoolProfile();'
if 'defaultProfile' in node.attrib:
profileDef += '\nprofile.setDefaultProfile('+ node.attrib['defaultProfile']+');'
if 'id' in node.attrib:
profileDef += '\nprofile.setId("'+ node.attrib['id']+'");'
if 'keepAliveTime' in node.attrib:
profileDef += '\nprofile.setKeepAliveTime('+ node.attrib['keepAliveTime']+'L);'
if 'maxPoolSize' in node.attrib:
profileDef += '\nprofile.setMaxPoolSize('+ node.attrib['maxPoolSize'] +');'
if 'maxQueueSize' in node.attrib:
profileDef += '\nprofile.setMaxQueueSize('+ node.attrib['maxQueueSize']+');'
if 'poolSize' in node.attrib:
profileDef += '\nprofile.setPoolSize('+ node.attrib['poolSize']+');'
if 'rejectedPolicy' in node.attrib:
if node.attrib['rejectedPolicy'] == 'Abort':
profileDef += '\nprofile.setRejectedPolicy(ThreadPoolRejectedPolicy.Abort);'
return profileDef
def throwException_def(self, node):
throwException_def = ''
if 'ref' in node.attrib:
throwException_def = '\n.throwException(Exception.class, "' + node.attrib['ref']+ '") //TODO: Please review throwException has changed with java DSL'
else:
throwException_def = '\n.throwException(Exception.class, "") //TODO: Please review throwException has changed with java DSL'
throwException_def += self.analyze_node(node)
return throwException_def
def spel_def(self, node):
return 'SpelExpression.spel("' + node.text + '")'
def loop_def(self, node):
loop_def = '\n.loop().'
loop_def += self.analyze_node(node)
loop_def += '\n.end() // end loop'
return loop_def
# Text deprecated processor for camel deprecated endpoints and features
def deprecatedProcessor(self, text):
text = re.sub('\${property\.(\w+\.?\w+)}', r'${exchangeProperty.\1}', text) #exhange property in simple expressions
text = re.sub('"', "'", text) # replace all ocurrences from " to '
text = re.sub('\n', "", text) # remove all endlines
return text
# Text processor for apply custom options in to endpoints
def componentOptions(self, text):
if "velocity:" in text:
text += "?contentCache=true"
return text
if __name__ == "__main__":
converter = Converter()
converter.xml_to_dsl()
def main():
converter = Converter()
converter.xml_to_dsl()
| [
"configargparse.ArgParser",
"rich.console.Console",
"lxml.objectify.parse",
"lxml.etree.XMLParser",
"re.sub",
"rich.console.log"
] | [((275, 284), 'rich.console.Console', 'Console', ([], {}), '()\n', (282, 284), False, 'from rich.console import Console\n'), ((394, 488), 'configargparse.ArgParser', 'configargparse.ArgParser', ([], {'description': "('Transforms xml routes to dsl routes ' + __version__)"}), "(description='Transforms xml routes to dsl routes ' +\n __version__)\n", (418, 488), False, 'import configargparse\n'), ((1522, 1560), 'rich.console.log', 'console.log', (['"""namespaces:"""', 'node.nsmap'], {}), "('namespaces:', node.nsmap)\n", (1533, 1560), False, 'from rich import console\n'), ((1967, 2034), 'rich.console.log', 'console.log', (['"""procesing node"""', 'node_name', 'node.tag', 'node.sourceline'], {}), "('procesing node', node_name, node.tag, node.sourceline)\n", (1978, 2034), False, 'from rich import console\n'), ((15666, 15739), 're.sub', 're.sub', (['"""\\\\${property\\\\.(\\\\w+\\\\.?\\\\w+)}"""', '"""${exchangeProperty.\\\\1}"""', 'text'], {}), "('\\\\${property\\\\.(\\\\w+\\\\.?\\\\w+)}', '${exchangeProperty.\\\\1}', text)\n", (15672, 15739), False, 'import re\n'), ((15790, 15812), 're.sub', 're.sub', (['"""\\""""', '"""\'"""', 'text'], {}), '(\'"\', "\'", text)\n', (15796, 15812), False, 'import re\n'), ((15865, 15887), 're.sub', 're.sub', (['"""\n"""', '""""""', 'text'], {}), "('\\n', '', text)\n", (15871, 15887), False, 'import re\n'), ((904, 941), 'lxml.etree.XMLParser', 'etree.XMLParser', ([], {'remove_comments': '(True)'}), '(remove_comments=True)\n', (919, 941), False, 'from lxml import etree, objectify\n'), ((961, 1001), 'lxml.objectify.parse', 'objectify.parse', (['xml_file'], {'parser': 'parser'}), '(xml_file, parser=parser)\n', (976, 1001), False, 'from lxml import etree, objectify\n'), ((1014, 1066), 'rich.console.log', 'console.log', (['""" XML 2 DSL Utility """'], {'style': '"""bold red"""'}), "(' XML 2 DSL Utility ', style='bold red')\n", (1025, 1066), False, 'from rich import console\n'), ((1717, 1786), 'rich.console.log', 'console.log', (['"""procesing node"""', 'node_name', 'child.tag', 'child.sourceline'], {}), "('procesing node', node_name, child.tag, child.sourceline)\n", (1728, 1786), False, 'from rich import console\n'), ((1241, 1307), 'rich.console.log', 'console.log', (['"""processing camel context"""', "camelContext.attrib['id']"], {}), "('processing camel context', camelContext.attrib['id'])\n", (1252, 1307), False, 'from rich import console\n')] |
# Text Classifiation using NLP
# Importing the libraries
import numpy as np
import re
import pickle
import nltk
from nltk.corpus import stopwords
from sklearn.datasets import load_files
nltk.download('stopwords')
# Importing the dataset
reviews = load_files('txt_sentoken/')
X,y = reviews.data,reviews.target
# Pickling the dataset
with open('X.pickle','wb') as f:
pickle.dump(X,f)
with open('y.pickle','wb') as f:
pickle.dump(y,f)
# Unpickling dataset
X_in = open('X.pickle','rb')
y_in = open('y.pickle','rb')
X = pickle.load(X_in)
y = pickle.load(y_in) | [
"pickle.dump",
"pickle.load",
"sklearn.datasets.load_files",
"nltk.download"
] | [((188, 214), 'nltk.download', 'nltk.download', (['"""stopwords"""'], {}), "('stopwords')\n", (201, 214), False, 'import nltk\n'), ((251, 278), 'sklearn.datasets.load_files', 'load_files', (['"""txt_sentoken/"""'], {}), "('txt_sentoken/')\n", (261, 278), False, 'from sklearn.datasets import load_files\n'), ((535, 552), 'pickle.load', 'pickle.load', (['X_in'], {}), '(X_in)\n', (546, 552), False, 'import pickle\n'), ((557, 574), 'pickle.load', 'pickle.load', (['y_in'], {}), '(y_in)\n', (568, 574), False, 'import pickle\n'), ((375, 392), 'pickle.dump', 'pickle.dump', (['X', 'f'], {}), '(X, f)\n', (386, 392), False, 'import pickle\n'), ((434, 451), 'pickle.dump', 'pickle.dump', (['y', 'f'], {}), '(y, f)\n', (445, 451), False, 'import pickle\n')] |
# This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
from indico.modules.admin.views import WPAdmin
from indico.util.i18n import _
from indico.web.views import WPDecorated, WPJinjaMixin
class WPNews(WPJinjaMixin, WPDecorated):
template_prefix = 'news/'
title = _('News')
def _get_body(self, params):
return self._get_page_content(params)
class WPManageNews(WPAdmin):
template_prefix = 'news/'
| [
"indico.util.i18n._"
] | [((473, 482), 'indico.util.i18n._', '_', (['"""News"""'], {}), "('News')\n", (474, 482), False, 'from indico.util.i18n import _\n')] |
'''
@FileName : data_parser.py
@EditTime : 2021-11-29 13:59:47
@Author : <NAME>
@Email : <EMAIL>
@Description :
'''
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import sys
import os
import os.path as osp
import platform
import json
from collections import namedtuple
import cv2
import numpy as np
import torch
from torch.utils.data import Dataset
Keypoints = namedtuple('Keypoints',
['keypoints', 'gender_gt', 'gender_pd'])
Keypoints.__new__.__defaults__ = (None,) * len(Keypoints._fields)
def read_keypoints(keypoint_fn, num_people, num_joint):
if not os.path.exists(keypoint_fn):
keypoints = [np.zeros((num_joint, 3))] * num_people # keypoints may not exist
flags = np.zeros((num_people,))
valid = 0
return keypoints, flags, valid
with open(keypoint_fn) as keypoint_file:
data = json.load(keypoint_file)
valid = 1
keypoints = []
flags = np.zeros((len(data['people'])))
for idx, person_data in enumerate(data['people']):
if person_data is None:
body_keypoints = np.zeros((num_joint, 3),
dtype=np.float32)
else:
flags[idx] = 1
body_keypoints = np.array(person_data['pose_keypoints_2d'],
dtype=np.float32)
body_keypoints = body_keypoints.reshape([-1, 3])
keypoints.append(body_keypoints)
return keypoints[:num_people], flags[:num_people], valid
def read_joints(keypoint_fn, use_hands=True, use_face=True,
use_face_contour=False):
"""
load 3D annotation
"""
with open(keypoint_fn) as keypoint_file:
data = json.load(keypoint_file)
keypoints = []
gender_pd = []
gender_gt = []
for idx, person_data in enumerate(data['people']):
try:
body_keypoints = np.array(person_data['pose_keypoints_3d'],
dtype=np.float32)
body_keypoints = body_keypoints.reshape([-1, 4])
if use_hands:
left_hand_keyp = np.array(
person_data['hand_left_keypoints_3d'],
dtype=np.float32).reshape([-1, 4])
right_hand_keyp = np.array(
person_data['hand_right_keypoints_3d'],
dtype=np.float32).reshape([-1, 4])
body_keypoints = np.concatenate(
[body_keypoints, left_hand_keyp, right_hand_keyp], axis=0)
if use_face:
# TODO: Make parameters, 17 is the offset for the eye brows,
# etc. 51 is the total number of FLAME compatible landmarks
face_keypoints = np.array(
person_data['face_keypoints_3d'],
dtype=np.float32).reshape([-1, 4])[17: 17 + 51, :]
contour_keyps = np.array(
[], dtype=body_keypoints.dtype).reshape(0, 4)
if use_face_contour:
contour_keyps = np.array(
person_data['face_keypoints_3d'],
dtype=np.float32).reshape([-1, 4])[:17, :]
body_keypoints = np.concatenate(
[body_keypoints, face_keypoints, contour_keyps], axis=0)
keypoints.append(body_keypoints)
except:
keypoints = None
if 'gender_pd' in person_data:
gender_pd.append(person_data['gender_pd'])
if 'gender_gt' in person_data:
gender_gt.append(person_data['gender_gt'])
return Keypoints(keypoints=keypoints, gender_pd=gender_pd,
gender_gt=gender_gt)
def smpl_to_annotation(model_type='smpl', use_hands=False, use_face=False,
use_face_contour=False, pose_format='coco17'):
if pose_format == 'halpe':
if model_type == 'smplhalpe':
# Halpe to SMPL
return np.array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25],
dtype=np.int32)
else:
raise ValueError('Unknown model type: {}'.format(model_type))
class FittingData(Dataset):
NUM_BODY_JOINTS = 17
NUM_HAND_JOINTS = 20
def __init__(self, data_folder, img_folder='images',
keyp_folder='keypoints',
use_hands=False,
use_face=False,
dtype=torch.float32,
model_type='smplx',
joints_to_ign=None,
use_face_contour=False,
pose_format='coco17',
use_3d=False,
use_hip=True,
frames=1,
num_people=1,
**kwargs):
super(FittingData, self).__init__()
self.use_hands = use_hands
self.use_face = use_face
self.model_type = model_type
self.dtype = dtype
self.use_3d = use_3d
self.use_hip = use_hip
self.joints_to_ign = joints_to_ign
self.use_face_contour = use_face_contour
self.pose_format = pose_format
if self.pose_format == 'halpe':
self.NUM_BODY_JOINTS = 26
self.num_joints = (self.NUM_BODY_JOINTS +
2 * self.NUM_HAND_JOINTS * use_hands)
self.data_folder = data_folder
self.img_folder = osp.join(data_folder, img_folder)
self.keyp_folder = osp.join(data_folder, keyp_folder)
img_serials = sorted(os.listdir(self.img_folder))
self.img_paths = []
for i_s in img_serials:
i_s_dir = osp.join(self.img_folder, i_s)
img_cameras = sorted(os.listdir(i_s_dir))
this_serials = []
for i_cam in img_cameras:
i_c_dir = osp.join(i_s_dir, i_cam)
cam_imgs = [osp.join(i_s, i_cam, img_fn)
for img_fn in os.listdir(i_c_dir)
if img_fn.endswith('.png') or
img_fn.endswith('.jpg') and
not img_fn.startswith('.')]
cam_imgs = sorted(cam_imgs)
this_serials.append(cam_imgs)
self.img_paths.append(this_serials)
self.cnt = 0
self.serial_cnt = 0
self.max_frames = frames
self.min_frames = 13
self.num_people = num_people
# if len(cam_imgs) < frames:
# self.frames = len(cam_imgs)
# else:
self.frames = frames
def get_model2data(self):
# Map SMPL to Halpe
return np.array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25],
dtype=np.int32)
def get_left_shoulder(self):
return 2
def get_right_shoulder(self):
return 5
def get_joint_weights(self):
# The weights for the joint terms in the optimization
optim_weights = np.ones(self.num_joints + 2 * self.use_hands +
self.use_face * 51 +
17 * self.use_face_contour,
dtype=np.float32)
# Neck, Left and right hip
# These joints are ignored because SMPL has no neck joint and the
# annotation of the hips is ambiguous.
# if self.joints_to_ign is not None and -1 not in self.joints_to_ign:
# optim_weights[self.joints_to_ign] = 0.
# return torch.tensor(optim_weights, dtype=self.dtype)
if (self.pose_format != 'lsp14' and self.pose_format != 'halpe') or not self.use_hip:
optim_weights[11] = 0.
optim_weights[12] = 0.
return torch.tensor(optim_weights, dtype=self.dtype)
def __len__(self):
return len(self.img_paths)
def __getitem__(self, idx):
img_path = self.img_paths[idx]
return self.read_item(img_path)
def read_item(self, img_paths):
"""Load keypoints according to img name"""
keypoints = []
total_flags = []
count = 0
for imgs in img_paths:
cam_keps = []
cam_flag = []
for img in imgs:
if platform.system() == 'Windows':
seq_name, cam_name, f_name = img.split('\\')
else:
seq_name, cam_name, f_name = img.split('/')
index = f_name.split('.')[0]
keypoint_fn = osp.join(self.keyp_folder, seq_name, cam_name, '%s_keypoints.json' %index)
keypoints_, flags, valid = read_keypoints(keypoint_fn, self.num_people, self.NUM_BODY_JOINTS)
count += valid
cam_flag.append(flags)
cam_keps.append(keypoints_)
keypoints.append(cam_keps)
total_flags.append(cam_flag)
total_flags = np.array(total_flags, dtype=np.int)
total_flags = np.max(total_flags, axis=0)
camparam = os.path.join(self.data_folder, 'camparams', seq_name, 'camparams.txt')
output_dict = { 'camparam': camparam,
'img_path': img_paths,
'keypoints': keypoints,
'flags':total_flags,
'count':count}
return output_dict
def __iter__(self):
return self
def __next__(self):
return self.next()
def next(self):
if self.serial_cnt >= len(self.img_paths):
raise StopIteration
img_path = self.img_paths[self.serial_cnt]
img_paths = []
for cam in img_path:
if self.cnt+self.max_frames > len(cam):
if len(cam) - self.cnt < self.min_frames:
img_paths.append(cam[-self.min_frames:])
else:
img_paths.append(cam[self.cnt:])
else:
img_paths.append(cam[self.cnt:self.cnt+self.max_frames]) #
self.frames = len(img_paths[0])
if self.cnt + self.max_frames >= len(cam):
self.cnt = 0
self.serial_cnt += 1
else:
self.cnt += self.frames
return self.read_item(img_paths)
| [
"os.path.exists",
"collections.namedtuple",
"os.listdir",
"numpy.ones",
"os.path.join",
"numpy.max",
"numpy.array",
"numpy.zeros",
"torch.tensor",
"platform.system",
"numpy.concatenate",
"json.load"
] | [((452, 516), 'collections.namedtuple', 'namedtuple', (['"""Keypoints"""', "['keypoints', 'gender_gt', 'gender_pd']"], {}), "('Keypoints', ['keypoints', 'gender_gt', 'gender_pd'])\n", (462, 516), False, 'from collections import namedtuple\n'), ((676, 703), 'os.path.exists', 'os.path.exists', (['keypoint_fn'], {}), '(keypoint_fn)\n', (690, 703), False, 'import os\n'), ((807, 830), 'numpy.zeros', 'np.zeros', (['(num_people,)'], {}), '((num_people,))\n', (815, 830), True, 'import numpy as np\n'), ((949, 973), 'json.load', 'json.load', (['keypoint_file'], {}), '(keypoint_file)\n', (958, 973), False, 'import json\n'), ((1782, 1806), 'json.load', 'json.load', (['keypoint_file'], {}), '(keypoint_file)\n', (1791, 1806), False, 'import json\n'), ((5495, 5528), 'os.path.join', 'osp.join', (['data_folder', 'img_folder'], {}), '(data_folder, img_folder)\n', (5503, 5528), True, 'import os.path as osp\n'), ((5556, 5590), 'os.path.join', 'osp.join', (['data_folder', 'keyp_folder'], {}), '(data_folder, keyp_folder)\n', (5564, 5590), True, 'import os.path as osp\n'), ((6710, 6834), 'numpy.array', 'np.array', (['[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, \n 21, 22, 23, 24, 25]'], {'dtype': 'np.int32'}), '([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,\n 19, 20, 21, 22, 23, 24, 25], dtype=np.int32)\n', (6718, 6834), True, 'import numpy as np\n'), ((7057, 7174), 'numpy.ones', 'np.ones', (['(self.num_joints + 2 * self.use_hands + self.use_face * 51 + 17 * self.\n use_face_contour)'], {'dtype': 'np.float32'}), '(self.num_joints + 2 * self.use_hands + self.use_face * 51 + 17 *\n self.use_face_contour, dtype=np.float32)\n', (7064, 7174), True, 'import numpy as np\n'), ((7806, 7851), 'torch.tensor', 'torch.tensor', (['optim_weights'], {'dtype': 'self.dtype'}), '(optim_weights, dtype=self.dtype)\n', (7818, 7851), False, 'import torch\n'), ((8976, 9011), 'numpy.array', 'np.array', (['total_flags'], {'dtype': 'np.int'}), '(total_flags, dtype=np.int)\n', (8984, 9011), True, 'import numpy as np\n'), ((9034, 9061), 'numpy.max', 'np.max', (['total_flags'], {'axis': '(0)'}), '(total_flags, axis=0)\n', (9040, 9061), True, 'import numpy as np\n'), ((9082, 9152), 'os.path.join', 'os.path.join', (['self.data_folder', '"""camparams"""', 'seq_name', '"""camparams.txt"""'], {}), "(self.data_folder, 'camparams', seq_name, 'camparams.txt')\n", (9094, 9152), False, 'import os\n'), ((1167, 1209), 'numpy.zeros', 'np.zeros', (['(num_joint, 3)'], {'dtype': 'np.float32'}), '((num_joint, 3), dtype=np.float32)\n', (1175, 1209), True, 'import numpy as np\n'), ((1316, 1376), 'numpy.array', 'np.array', (["person_data['pose_keypoints_2d']"], {'dtype': 'np.float32'}), "(person_data['pose_keypoints_2d'], dtype=np.float32)\n", (1324, 1376), True, 'import numpy as np\n'), ((1963, 2023), 'numpy.array', 'np.array', (["person_data['pose_keypoints_3d']"], {'dtype': 'np.float32'}), "(person_data['pose_keypoints_3d'], dtype=np.float32)\n", (1971, 2023), True, 'import numpy as np\n'), ((4028, 4152), 'numpy.array', 'np.array', (['[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, \n 21, 22, 23, 24, 25]'], {'dtype': 'np.int32'}), '([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,\n 19, 20, 21, 22, 23, 24, 25], dtype=np.int32)\n', (4036, 4152), True, 'import numpy as np\n'), ((5621, 5648), 'os.listdir', 'os.listdir', (['self.img_folder'], {}), '(self.img_folder)\n', (5631, 5648), False, 'import os\n'), ((5732, 5762), 'os.path.join', 'osp.join', (['self.img_folder', 'i_s'], {}), '(self.img_folder, i_s)\n', (5740, 5762), True, 'import os.path as osp\n'), ((726, 750), 'numpy.zeros', 'np.zeros', (['(num_joint, 3)'], {}), '((num_joint, 3))\n', (734, 750), True, 'import numpy as np\n'), ((2497, 2570), 'numpy.concatenate', 'np.concatenate', (['[body_keypoints, left_hand_keyp, right_hand_keyp]'], {'axis': '(0)'}), '([body_keypoints, left_hand_keyp, right_hand_keyp], axis=0)\n', (2511, 2570), True, 'import numpy as np\n'), ((3289, 3360), 'numpy.concatenate', 'np.concatenate', (['[body_keypoints, face_keypoints, contour_keyps]'], {'axis': '(0)'}), '([body_keypoints, face_keypoints, contour_keyps], axis=0)\n', (3303, 3360), True, 'import numpy as np\n'), ((5796, 5815), 'os.listdir', 'os.listdir', (['i_s_dir'], {}), '(i_s_dir)\n', (5806, 5815), False, 'import os\n'), ((5911, 5935), 'os.path.join', 'osp.join', (['i_s_dir', 'i_cam'], {}), '(i_s_dir, i_cam)\n', (5919, 5935), True, 'import os.path as osp\n'), ((8572, 8647), 'os.path.join', 'osp.join', (['self.keyp_folder', 'seq_name', 'cam_name', "('%s_keypoints.json' % index)"], {}), "(self.keyp_folder, seq_name, cam_name, '%s_keypoints.json' % index)\n", (8580, 8647), True, 'import os.path as osp\n'), ((5964, 5992), 'os.path.join', 'osp.join', (['i_s', 'i_cam', 'img_fn'], {}), '(i_s, i_cam, img_fn)\n', (5972, 5992), True, 'import os.path as osp\n'), ((8314, 8331), 'platform.system', 'platform.system', ([], {}), '()\n', (8329, 8331), False, 'import platform\n'), ((2180, 2245), 'numpy.array', 'np.array', (["person_data['hand_left_keypoints_3d']"], {'dtype': 'np.float32'}), "(person_data['hand_left_keypoints_3d'], dtype=np.float32)\n", (2188, 2245), True, 'import numpy as np\n'), ((2338, 2404), 'numpy.array', 'np.array', (["person_data['hand_right_keypoints_3d']"], {'dtype': 'np.float32'}), "(person_data['hand_right_keypoints_3d'], dtype=np.float32)\n", (2346, 2404), True, 'import numpy as np\n'), ((2971, 3011), 'numpy.array', 'np.array', (['[]'], {'dtype': 'body_keypoints.dtype'}), '([], dtype=body_keypoints.dtype)\n', (2979, 3011), True, 'import numpy as np\n'), ((6035, 6054), 'os.listdir', 'os.listdir', (['i_c_dir'], {}), '(i_c_dir)\n', (6045, 6054), False, 'import os\n'), ((2803, 2863), 'numpy.array', 'np.array', (["person_data['face_keypoints_3d']"], {'dtype': 'np.float32'}), "(person_data['face_keypoints_3d'], dtype=np.float32)\n", (2811, 2863), True, 'import numpy as np\n'), ((3120, 3180), 'numpy.array', 'np.array', (["person_data['face_keypoints_3d']"], {'dtype': 'np.float32'}), "(person_data['face_keypoints_3d'], dtype=np.float32)\n", (3128, 3180), True, 'import numpy as np\n')] |
"""View tests for the mailer app"""
# pylint: disable=no-value-for-parameter,invalid-name
from django.http import Http404
from django.test import TestCase, RequestFactory
from django.test.utils import override_settings
from model_mommy import mommy
from mock import Mock, patch
from open_connect.accounts.utils import generate_nologin_hash as hashgen
from open_connect.mailer import views
from open_connect.mailer.models import Unsubscribe
from open_connect.mailer.utils import url_representation_encode
from open_connect.mailer.tests.test_utils import (
OPEN_DATA, OPEN_DATA_ENCODED, OPEN_DATA_HASH
)
@override_settings(EMAIL_SECRET_KEY='abcd')
class TestOpenView(TestCase):
"""Test the Process Tracking middleware"""
def setUp(self):
"""Setup the Create Open Test"""
self.view = views.OpenView.as_view()
self.factory = RequestFactory()
self.request = self.factory.get('/')
self.request.META = Mock()
def test_failed_hash_returns_404(self):
"""Test that a failing hash raises a Http404"""
with self.assertRaises(Http404):
self.view(self.request,
encoded_data=OPEN_DATA_ENCODED,
request_hash='aaaaaaaaaa')
def test_missing_data_returns_404(self):
"""Test that not providing all required fields raises Http404"""
data = {
'e': '<EMAIL>'
}
representation, verification_hash = url_representation_encode(data)
with self.assertRaises(Http404):
self.view(self.request,
encoded_data=representation,
request_hash=verification_hash)
@patch('open_connect.mailer.views.create_open')
def test_process_request(self, mock):
"""Test a valid call to process_request"""
result = self.view(
self.request,
encoded_data=OPEN_DATA_ENCODED,
request_hash=OPEN_DATA_HASH)
mock.assert_called_once_with(OPEN_DATA, self.request.META)
self.assertEqual(result.status_code, 200)
self.assertEqual(result['content-type'], 'image/gif')
class TestUnsubscribeView(TestCase):
"""Tests for the UnsubscribeView"""
def setUp(self):
"""Setup the test"""
self.view = views.UnsubscribeView.as_view()
self.factory = RequestFactory()
self.request = self.factory.get('/')
self.email = '<EMAIL>'
self.code = hashgen(self.email)
def test_valid_get_request(self):
"""Test a valid request returns a valid response"""
self.request.GET = {
'code': self.code,
'email': self.email
}
result = self.view(self.request)
self.assertEqual(result.status_code, 200)
def test_dispatch_no_args(self):
"""
Test that a 404 is returned by the dispatch method if no code is given
"""
with self.assertRaises(Http404):
self.request.GET = {}
self.view(self.request)
def test_dispatch_only_one_arg(self):
"""Test that a 404 is returned when only one arg is given"""
with self.assertRaises(Http404):
self.request.GET = {'email': self.email}
self.view(self.request)
def test_dispatch_non_valid_email(self):
"""Test that a 404 is returned with a non-valid email"""
with self.assertRaises(Http404):
self.request.GET = {
'email': 'notanemail',
'code': hashgen('notanemail')
}
self.view(self.request)
def test_dispatch_non_valid_code(self):
"""Test that a 404 is thrown with a non-valid code"""
with self.assertRaises(Http404):
self.request.GET = {
'email': self.email,
'code': 'notavalidcode'
}
self.view(self.request)
def test_context_contains_user(self):
"""Test that when a user exists the context has that user's account"""
user = mommy.make('accounts.User', email='<EMAIL>')
self.request.GET = {'email': user.email, 'code': user.private_hash}
response = self.view(self.request)
self.assertEqual(response.context_data['email'], user.email)
self.assertEqual(response.context_data['account'], user)
def test_context_contains_email(self):
"""Test that the context contains the email in the GET request"""
self.request.GET = {'email': self.email, 'code': self.code}
response = self.view(self.request)
self.assertEqual(response.context_data['email'], self.email)
def test_post_creates_record(self):
"""Test that a POST request generates a new Unsubscribe record"""
self.assertFalse(Unsubscribe.objects.filter(
address=self.email, source='user').exists())
request = self.factory.post('/')
request.GET = {'email': self.email, 'code': self.code}
response = self.view(request)
self.assertTrue(Unsubscribe.objects.filter(
address=self.email, source='user').exists())
self.assertEqual(response.status_code, 302)
| [
"django.test.RequestFactory",
"model_mommy.mommy.make",
"mock.patch",
"django.test.utils.override_settings",
"open_connect.accounts.utils.generate_nologin_hash",
"mock.Mock",
"open_connect.mailer.views.UnsubscribeView.as_view",
"open_connect.mailer.models.Unsubscribe.objects.filter",
"open_connect.m... | [((611, 653), 'django.test.utils.override_settings', 'override_settings', ([], {'EMAIL_SECRET_KEY': '"""abcd"""'}), "(EMAIL_SECRET_KEY='abcd')\n", (628, 653), False, 'from django.test.utils import override_settings\n'), ((1676, 1722), 'mock.patch', 'patch', (['"""open_connect.mailer.views.create_open"""'], {}), "('open_connect.mailer.views.create_open')\n", (1681, 1722), False, 'from mock import Mock, patch\n'), ((813, 837), 'open_connect.mailer.views.OpenView.as_view', 'views.OpenView.as_view', ([], {}), '()\n', (835, 837), False, 'from open_connect.mailer import views\n'), ((861, 877), 'django.test.RequestFactory', 'RequestFactory', ([], {}), '()\n', (875, 877), False, 'from django.test import TestCase, RequestFactory\n'), ((951, 957), 'mock.Mock', 'Mock', ([], {}), '()\n', (955, 957), False, 'from mock import Mock, patch\n'), ((1456, 1487), 'open_connect.mailer.utils.url_representation_encode', 'url_representation_encode', (['data'], {}), '(data)\n', (1481, 1487), False, 'from open_connect.mailer.utils import url_representation_encode\n'), ((2285, 2316), 'open_connect.mailer.views.UnsubscribeView.as_view', 'views.UnsubscribeView.as_view', ([], {}), '()\n', (2314, 2316), False, 'from open_connect.mailer import views\n'), ((2340, 2356), 'django.test.RequestFactory', 'RequestFactory', ([], {}), '()\n', (2354, 2356), False, 'from django.test import TestCase, RequestFactory\n'), ((2453, 2472), 'open_connect.accounts.utils.generate_nologin_hash', 'hashgen', (['self.email'], {}), '(self.email)\n', (2460, 2472), True, 'from open_connect.accounts.utils import generate_nologin_hash as hashgen\n'), ((4024, 4068), 'model_mommy.mommy.make', 'mommy.make', (['"""accounts.User"""'], {'email': '"""<EMAIL>"""'}), "('accounts.User', email='<EMAIL>')\n", (4034, 4068), False, 'from model_mommy import mommy\n'), ((3507, 3528), 'open_connect.accounts.utils.generate_nologin_hash', 'hashgen', (['"""notanemail"""'], {}), "('notanemail')\n", (3514, 3528), True, 'from open_connect.accounts.utils import generate_nologin_hash as hashgen\n'), ((4760, 4821), 'open_connect.mailer.models.Unsubscribe.objects.filter', 'Unsubscribe.objects.filter', ([], {'address': 'self.email', 'source': '"""user"""'}), "(address=self.email, source='user')\n", (4786, 4821), False, 'from open_connect.mailer.models import Unsubscribe\n'), ((5011, 5072), 'open_connect.mailer.models.Unsubscribe.objects.filter', 'Unsubscribe.objects.filter', ([], {'address': 'self.email', 'source': '"""user"""'}), "(address=self.email, source='user')\n", (5037, 5072), False, 'from open_connect.mailer.models import Unsubscribe\n')] |
#!/usr/bin/env python
"""
Tool for combining and converting paths within catalog files
"""
import sys
import json
import argparse
from glob import glob
from pathlib import Path
def fail(message):
print(message)
sys.exit(1)
def build_catalog():
catalog_paths = []
for source_glob in CLI_ARGS.sources:
catalog_paths.extend(glob(source_glob))
items = []
for catalog_original_path in catalog_paths:
catalog_path = Path(catalog_original_path).absolute()
print('Loading catalog "{}"'.format(str(catalog_original_path)))
if not catalog_path.is_file():
fail('Unable to find catalog file "{}"'.format(str(catalog_path)))
with open(catalog_path, 'r', encoding='utf-8') as catalog_file:
catalog_items = json.load(catalog_file)
base_path = catalog_path.parent.absolute()
for item in catalog_items:
new_item = {}
for entry, entry_original_path in item.items():
entry_path = Path(entry_original_path)
entry_path = entry_path if entry_path.is_absolute() else (base_path / entry_path).absolute()
if ((len(CLI_ARGS.check) == 1 and CLI_ARGS.check[0] == 'all')
or entry in CLI_ARGS.check) and not entry_path.is_file():
note = 'Catalog "{}" - Missing file for "{}" ("{}")'.format(
str(catalog_original_path), entry, str(entry_original_path))
if CLI_ARGS.on_miss == 'fail':
fail(note + ' - aborting')
if CLI_ARGS.on_miss == 'ignore':
print(note + ' - keeping it as it is')
new_item[entry] = str(entry_path)
elif CLI_ARGS.on_miss == 'drop':
print(note + ' - dropping catalog item')
new_item = None
break
else:
print(note + ' - removing entry from item')
else:
new_item[entry] = str(entry_path)
if CLI_ARGS.output is not None and new_item is not None and len(new_item.keys()) > 0:
items.append(new_item)
if CLI_ARGS.output is not None:
catalog_path = Path(CLI_ARGS.output).absolute()
print('Writing catalog "{}"'.format(str(CLI_ARGS.output)))
if CLI_ARGS.make_relative:
base_path = catalog_path.parent
for item in items:
for entry in item.keys():
item[entry] = str(Path(item[entry]).relative_to(base_path))
if CLI_ARGS.order_by is not None:
items.sort(key=lambda i: i[CLI_ARGS.order_by] if CLI_ARGS.order_by in i else '')
with open(catalog_path, 'w', encoding='utf-8') as catalog_file:
json.dump(items, catalog_file, indent=2)
def handle_args():
parser = argparse.ArgumentParser(description='Tool for combining catalog files and/or ordering, checking and '
'converting paths within catalog files')
parser.add_argument('--output', help='Write collected catalog items to this new catalog file')
parser.add_argument('--make-relative', action='store_true',
help='Make all path entries of all items relative to new catalog file\'s parent directory')
parser.add_argument('--check',
help='Comma separated list of path entries to check for existence '
'("all" for checking every entry, default: no checks)')
parser.add_argument('--on-miss', default='fail', choices=['fail', 'drop', 'remove', 'ignore'],
help='What to do if a path is not existing: '
'"fail" (exit program), '
'"drop" (drop catalog item) or '
'"remove" (remove path entry from catalog item) or '
'"ignore" (keep it as it is)')
parser.add_argument('--order-by', help='Path entry used for sorting items in target catalog')
parser.add_argument('sources', nargs='+', help='Source catalog files (supporting wildcards)')
return parser.parse_args()
if __name__ == "__main__":
CLI_ARGS = handle_args()
CLI_ARGS.check = [] if CLI_ARGS.check is None else CLI_ARGS.check.split(',')
build_catalog()
| [
"argparse.ArgumentParser",
"pathlib.Path",
"glob.glob",
"sys.exit",
"json.load",
"json.dump"
] | [((222, 233), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (230, 233), False, 'import sys\n'), ((2927, 3076), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Tool for combining catalog files and/or ordering, checking and converting paths within catalog files"""'}), "(description=\n 'Tool for combining catalog files and/or ordering, checking and converting paths within catalog files'\n )\n", (2950, 3076), False, 'import argparse\n'), ((350, 367), 'glob.glob', 'glob', (['source_glob'], {}), '(source_glob)\n', (354, 367), False, 'from glob import glob\n'), ((785, 808), 'json.load', 'json.load', (['catalog_file'], {}), '(catalog_file)\n', (794, 808), False, 'import json\n'), ((2852, 2892), 'json.dump', 'json.dump', (['items', 'catalog_file'], {'indent': '(2)'}), '(items, catalog_file, indent=2)\n', (2861, 2892), False, 'import json\n'), ((455, 482), 'pathlib.Path', 'Path', (['catalog_original_path'], {}), '(catalog_original_path)\n', (459, 482), False, 'from pathlib import Path\n'), ((1010, 1035), 'pathlib.Path', 'Path', (['entry_original_path'], {}), '(entry_original_path)\n', (1014, 1035), False, 'from pathlib import Path\n'), ((2301, 2322), 'pathlib.Path', 'Path', (['CLI_ARGS.output'], {}), '(CLI_ARGS.output)\n', (2305, 2322), False, 'from pathlib import Path\n'), ((2591, 2608), 'pathlib.Path', 'Path', (['item[entry]'], {}), '(item[entry])\n', (2595, 2608), False, 'from pathlib import Path\n')] |
# Copyright (C) 2016 ycmd contributors
#
# This file is part of ycmd.
#
# ycmd is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ycmd is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ycmd. If not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
# Not installing aliases from python-future; it's unreliable and slow.
from builtins import * # noqa
from contextlib import contextmanager
import functools
import os
from ycmd.tests.test_utils import ( ClearCompletionsCache,
IsolatedApp,
SetUpApp,
StartCompleterServer,
StopCompleterServer,
WaitUntilCompleterServerReady,
YCMD_EXTRA_CONF )
shared_app = None
shared_filepaths = []
def PathToTestFile( *args ):
dir_of_current_script = os.path.dirname( os.path.abspath( __file__ ) )
return os.path.join( dir_of_current_script, 'testdata', *args )
def setUpPackage():
"""Initializes the ycmd server as a WebTest application that will be shared
by all tests using the SharedYcmd decorator in this package. Additional
configuration that is common to these tests, like starting a semantic
subserver, should be done here."""
global shared_app
shared_app = SetUpApp()
shared_app.post_json( '/ignore_extra_conf_file',
{ 'filepath': YCMD_EXTRA_CONF } )
shared_app.post_json( '/ignore_extra_conf_file',
{ 'filepath': PathToTestFile( '.ycm_extra_conf.py' ) } )
def tearDownPackage():
"""Cleans up the tests using the SharedYcmd decorator in this package. It is
executed once after running all the tests in the package."""
global shared_app, shared_filepaths
for filepath in shared_filepaths:
StopCompleterServer( shared_app, 'cs', filepath )
@contextmanager
def WrapOmniSharpServer( app, filepath ):
global shared_filepaths
if filepath not in shared_filepaths:
StartCompleterServer( app, 'cs', filepath )
shared_filepaths.append( filepath )
WaitUntilCompleterServerReady( app, 'cs' )
yield
def SharedYcmd( test ):
"""Defines a decorator to be attached to tests of this package. This decorator
passes the shared ycmd application as a parameter.
Do NOT attach it to test generators but directly to the yielded tests."""
global shared_app
@functools.wraps( test )
def Wrapper( *args, **kwargs ):
ClearCompletionsCache()
return test( shared_app, *args, **kwargs )
return Wrapper
def IsolatedYcmd( custom_options = {} ):
"""Defines a decorator to be attached to tests of this package. This decorator
passes a unique ycmd application as a parameter. It should be used on tests
that change the server state in a irreversible way (ex: a semantic subserver
is stopped or restarted) or expect a clean state (ex: no semantic subserver
started, no .ycm_extra_conf.py loaded, etc). Use the optional parameter
|custom_options| to give additional options and/or override the default ones.
Do NOT attach it to test generators but directly to the yielded tests.
Example usage:
from ycmd.tests.cs import IsolatedYcmd
@IsolatedYcmd( { 'server_keep_logfiles': 1 } )
def CustomServerKeepLogfiles_test( app ):
...
"""
def Decorator( test ):
@functools.wraps( test )
def Wrapper( *args, **kwargs ):
with IsolatedApp( custom_options ) as app:
app.post_json( '/ignore_extra_conf_file',
{ 'filepath': YCMD_EXTRA_CONF } )
app.post_json( '/ignore_extra_conf_file',
{ 'filepath': PathToTestFile( '.ycm_extra_conf.py' ) } )
test( app, *args, **kwargs )
return Wrapper
return Decorator
| [
"ycmd.tests.test_utils.ClearCompletionsCache",
"ycmd.tests.test_utils.StopCompleterServer",
"os.path.join",
"functools.wraps",
"ycmd.tests.test_utils.SetUpApp",
"ycmd.tests.test_utils.StartCompleterServer",
"ycmd.tests.test_utils.IsolatedApp",
"os.path.abspath",
"ycmd.tests.test_utils.WaitUntilCompl... | [((1545, 1599), 'os.path.join', 'os.path.join', (['dir_of_current_script', '"""testdata"""', '*args'], {}), "(dir_of_current_script, 'testdata', *args)\n", (1557, 1599), False, 'import os\n'), ((1921, 1931), 'ycmd.tests.test_utils.SetUpApp', 'SetUpApp', ([], {}), '()\n', (1929, 1931), False, 'from ycmd.tests.test_utils import ClearCompletionsCache, IsolatedApp, SetUpApp, StartCompleterServer, StopCompleterServer, WaitUntilCompleterServerReady, YCMD_EXTRA_CONF\n'), ((2685, 2725), 'ycmd.tests.test_utils.WaitUntilCompleterServerReady', 'WaitUntilCompleterServerReady', (['app', '"""cs"""'], {}), "(app, 'cs')\n", (2714, 2725), False, 'from ycmd.tests.test_utils import ClearCompletionsCache, IsolatedApp, SetUpApp, StartCompleterServer, StopCompleterServer, WaitUntilCompleterServerReady, YCMD_EXTRA_CONF\n'), ((2997, 3018), 'functools.wraps', 'functools.wraps', (['test'], {}), '(test)\n', (3012, 3018), False, 'import functools\n'), ((1506, 1531), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (1521, 1531), False, 'import os\n'), ((2419, 2466), 'ycmd.tests.test_utils.StopCompleterServer', 'StopCompleterServer', (['shared_app', '"""cs"""', 'filepath'], {}), "(shared_app, 'cs', filepath)\n", (2438, 2466), False, 'from ycmd.tests.test_utils import ClearCompletionsCache, IsolatedApp, SetUpApp, StartCompleterServer, StopCompleterServer, WaitUntilCompleterServerReady, YCMD_EXTRA_CONF\n'), ((2599, 2640), 'ycmd.tests.test_utils.StartCompleterServer', 'StartCompleterServer', (['app', '"""cs"""', 'filepath'], {}), "(app, 'cs', filepath)\n", (2619, 2640), False, 'from ycmd.tests.test_utils import ClearCompletionsCache, IsolatedApp, SetUpApp, StartCompleterServer, StopCompleterServer, WaitUntilCompleterServerReady, YCMD_EXTRA_CONF\n'), ((3059, 3082), 'ycmd.tests.test_utils.ClearCompletionsCache', 'ClearCompletionsCache', ([], {}), '()\n', (3080, 3082), False, 'from ycmd.tests.test_utils import ClearCompletionsCache, IsolatedApp, SetUpApp, StartCompleterServer, StopCompleterServer, WaitUntilCompleterServerReady, YCMD_EXTRA_CONF\n'), ((3940, 3961), 'functools.wraps', 'functools.wraps', (['test'], {}), '(test)\n', (3955, 3961), False, 'import functools\n'), ((4011, 4038), 'ycmd.tests.test_utils.IsolatedApp', 'IsolatedApp', (['custom_options'], {}), '(custom_options)\n', (4022, 4038), False, 'from ycmd.tests.test_utils import ClearCompletionsCache, IsolatedApp, SetUpApp, StartCompleterServer, StopCompleterServer, WaitUntilCompleterServerReady, YCMD_EXTRA_CONF\n')] |
from cupy import core
def argmax(a, axis=None, dtype=None, out=None, keepdims=False):
"""Returns the indices of the maximum along an axis.
Args:
a (cupy.ndarray): Array to take argmax.
axis (int): Along which axis to find the maximum. ``a`` is flattened by
default.
dtype: Data type specifier.
out (cupy.ndarray): Output array.
keepdims (bool): If ``True``, the axis ``axis`` is preserved as an axis
of length one.
Returns:
cupy.ndarray: The indices of the maximum of ``a`` along an axis.
.. seealso:: :func:`numpy.argmax`
"""
# TODO(okuta): check type
return a.argmax(axis=axis, dtype=dtype, out=out, keepdims=keepdims)
# TODO(okuta): Implement nanargmax
def argmin(a, axis=None, dtype=None, out=None, keepdims=False):
"""Returns the indices of the minimum along an axis.
Args:
a (cupy.ndarray): Array to take argmin.
axis (int): Along which axis to find the minimum. ``a`` is flattened by
default.
dtype: Data type specifier.
out (cupy.ndarray): Output array.
keepdims (bool): If ``True``, the axis ``axis`` is preserved as an axis
of length one.
Returns:
cupy.ndarray: The indices of the minimum of ``a`` along an axis.
.. seealso:: :func:`numpy.argmin`
"""
# TODO(okuta): check type
return a.argmin(axis=axis, dtype=dtype, out=out, keepdims=keepdims)
# TODO(okuta): Implement nanargmin
# TODO(okuta): Implement argwhere
def nonzero(a):
"""Return the indices of the elements that are non-zero.
Returns a tuple of arrays, one for each dimension of a,
containing the indices of the non-zero elements in that dimension.
Args:
a (cupy.ndarray): array
Returns:
tuple of arrays: Indices of elements that are non-zero.
.. seealso:: :func:`numpy.nonzero`
"""
assert isinstance(a, core.ndarray)
return a.nonzero()
def flatnonzero(a):
"""Return indices that are non-zero in the flattened version of a.
This is equivalent to a.ravel().nonzero()[0].
Args:
a (cupy.ndarray): input array
Returns:
cupy.ndarray: Output array,
containing the indices of the elements of a.ravel() that are non-zero.
.. seealso:: :func:`numpy.flatnonzero`
"""
assert isinstance(a, core.ndarray)
return a.ravel().nonzero()[0]
def where(condition, x=None, y=None):
"""Return elements, either from x or y, depending on condition.
If only condition is given, return ``condition.nonzero()``.
Args:
condition (cupy.ndarray): When True, take x, otherwise take y.
x (cupy.ndarray): Values from which to choose on ``True``.
y (cupy.ndarray): Values from which to choose on ``False``.
Returns:
cupy.ndarray: Each element of output contains elements of ``x`` when
``condition`` is ``True``, otherwise elements of ``y``. If only
``condition`` is given, return the tuple ``condition.nonzero()``,
the indices where ``condition`` is True.
.. seealso:: :func:`numpy.where`
"""
missing = (x is None, y is None).count(True)
if missing == 1:
raise ValueError("Must provide both 'x' and 'y' or neither.")
if missing == 2:
return nonzero(condition)
return _where_ufunc(condition.astype('?'), x, y)
_where_ufunc = core.create_ufunc(
'cupy_where',
('???->?', '?bb->b', '?BB->B', '?hh->h', '?HH->H', '?ii->i', '?II->I',
'?ll->l', '?LL->L', '?qq->q', '?QQ->Q', '?ee->e', '?ff->f',
# On CUDA 6.5 these combinations don't work correctly (on CUDA >=7.0, it
# works).
# See issue #551.
'?hd->d', '?Hd->d',
'?dd->d'),
'out0 = in0 ? in1 : in2')
# TODO(okuta): Implement searchsorted
# TODO(okuta): Implement extract
| [
"cupy.core.create_ufunc"
] | [((3435, 3667), 'cupy.core.create_ufunc', 'core.create_ufunc', (['"""cupy_where"""', "('???->?', '?bb->b', '?BB->B', '?hh->h', '?HH->H', '?ii->i', '?II->I',\n '?ll->l', '?LL->L', '?qq->q', '?QQ->Q', '?ee->e', '?ff->f', '?hd->d',\n '?Hd->d', '?dd->d')", '"""out0 = in0 ? in1 : in2"""'], {}), "('cupy_where', ('???->?', '?bb->b', '?BB->B', '?hh->h',\n '?HH->H', '?ii->i', '?II->I', '?ll->l', '?LL->L', '?qq->q', '?QQ->Q',\n '?ee->e', '?ff->f', '?hd->d', '?Hd->d', '?dd->d'), 'out0 = in0 ? in1 : in2'\n )\n", (3452, 3667), False, 'from cupy import core\n')] |
"""
Credential implementation
"""
from typing import Dict, List, Union
from alteia.apis.provider import ExternalProviderServiceAPI
from alteia.core.resources.resource import ResourcesWithTotal
from alteia.core.utils.typing import Resource, ResourceId
class CredentialsImpl:
def __init__(self,
external_provider_service_api: ExternalProviderServiceAPI,
**kwargs):
self._provider = external_provider_service_api
def search(self, *, name: str = None, filter: Dict = None,
limit: int = None, page: int = None, sort: dict = None,
return_total: bool = False,
**kwargs) -> Union[ResourcesWithTotal, List[Resource]]:
"""Search for a list of credentials.
Args:
name: Credential name.
filter: Search filter dictionary (refer to ``/search-credentials``
definition in the External Providers Service API for a detailed
description of ``filter``).
limit: Maximum number of results to extract.
page: Page number (starting at page 0).
sort: Sort the results on the specified attributes
(``1`` is sorting in ascending order,
``-1`` is sorting in descending order).
return_total: Return the number of results found.
**kwargs: Optional keyword arguments. Those arguments are
passed as is to the API provider.
Returns:
Credentials: A list of credential resources OR a namedtuple
with total number of results and list of credential resources.
"""
data = kwargs
for prop_name, value in [('filter', filter or {}),
('limit', limit),
('page', page),
('sort', sort)]:
if value is not None:
data.update({prop_name: value})
if name is not None:
data['filter']['name'] = {'$eq': name}
search_desc = self._provider.post(
path='search-credentials', data=data, as_json=True)
credentials = search_desc.get('results')
results = [Resource(**credentials) for credentials in credentials]
if return_total is True:
total = search_desc.get('total')
return ResourcesWithTotal(total=total, results=results)
else:
return results
def create(self, *, name: str, credentials: Dict[str, str],
**kwargs) -> Resource:
"""Create a credential entry.
Args:
name: Credential name (must be unique).
credentials: Credential dict.
**kwargs: Optional keyword arguments. Those arguments are
passed as is to the API provider.
Returns:
The created credential description.
Examples:
>>> sdk.credentials.create(name="My Docker registry",
... credentials={
... "type": "docker",
... "login": "my_login",
... "password": "<PASSWORD>",
... "registry": "mydockerregistry.com"
... }
... )
<alteia.core.resources.Resource with id ... (credentials)>
>>> sdk.credentials.create(name="My Docker registry",
... credentials={
... "type": "aws",
... "aws_access_key_id": "key_id",
... "aws_secret_access_key": "password_test",
... "aws_region": "us-east-1",
... "registry": "XXX..dkr.ecr.us-east-1.amazonaws.com"
... }
... )
<alteia.core.resources.Resource with id ... (credentials)>
"""
data = kwargs
data.update({
'name': name,
'credentials': credentials
})
desc = self._provider.post(
path='create-credentials', data=dict(data), as_json=True)
return Resource(**desc)
def delete(self, credential: ResourceId, **kwargs) -> None:
"""Delete a credential entry.
Args:
credential: Credential identifier.
**kwargs: Optional keyword arguments. Those arguments are
passed as is to the API provider.
"""
data = kwargs
data.update({'credentials': credential})
self._provider.post(
path='delete-credentials',
data=data,
as_json=False
)
| [
"alteia.core.utils.typing.Resource",
"alteia.core.resources.resource.ResourcesWithTotal"
] | [((4099, 4115), 'alteia.core.utils.typing.Resource', 'Resource', ([], {}), '(**desc)\n', (4107, 4115), False, 'from alteia.core.utils.typing import Resource, ResourceId\n'), ((2236, 2259), 'alteia.core.utils.typing.Resource', 'Resource', ([], {}), '(**credentials)\n', (2244, 2259), False, 'from alteia.core.utils.typing import Resource, ResourceId\n'), ((2390, 2438), 'alteia.core.resources.resource.ResourcesWithTotal', 'ResourcesWithTotal', ([], {'total': 'total', 'results': 'results'}), '(total=total, results=results)\n', (2408, 2438), False, 'from alteia.core.resources.resource import ResourcesWithTotal\n')] |
from django.test import TestCase, Client
from django.contrib.auth.models import User
from .models import Feed
class FeedViewsTest(TestCase):
def setUp(self):
self.client = Client()
user = User.objects.create_user(
username='test_user',
email='<EMAIL>',
password='<PASSWORD>'
)
self.feed = Feed.objects.create(user=user, post='test feed')
def test_feeds(self):
response = self.client.get('/feeds/')
self.assertEqual(response.status_code, 200)
def test_feed(self):
response = self.client.get('/feeds/123/')
self.assertEqual(response.status_code, 404)
response = self.client.get(f'/feeds/{self.feed.pk}/')
self.assertEqual(response.status_code, 200)
| [
"django.contrib.auth.models.User.objects.create_user",
"django.test.Client"
] | [((187, 195), 'django.test.Client', 'Client', ([], {}), '()\n', (193, 195), False, 'from django.test import TestCase, Client\n'), ((211, 302), 'django.contrib.auth.models.User.objects.create_user', 'User.objects.create_user', ([], {'username': '"""test_user"""', 'email': '"""<EMAIL>"""', 'password': '"""<PASSWORD>"""'}), "(username='test_user', email='<EMAIL>', password=\n '<PASSWORD>')\n", (235, 302), False, 'from django.contrib.auth.models import User\n')] |
import wandb
import torch
import torch.nn as nn
import torch.nn.functional as F
from tqdm import tqdm
from collections import OrderedDict
from transformers import BertModel
from torchmeta.modules import MetaModule, MetaSequential, MetaLinear
from torchmeta.utils.gradient_based import gradient_update_parameters
from ..utils.average_meter import AverageMeter
from ..utils import utils as utils
from .common import WordEmbedding
class FUMI(nn.Module):
def __init__(self,
n_way=5,
im_emb_dim=2048,
im_hid_dim=32,
text_encoder="BERT",
text_emb_dim=300,
text_hid_dim=1024,
dictionary=None,
pooling_strat="mean",
shared_feats=True):
super(FUMI, self).__init__()
self.n_way = n_way
self.im_emb_dim = im_emb_dim
self.im_hid_dim = im_hid_dim
self.text_encoder_type = text_encoder
self.text_emb_dim = text_emb_dim # only applicable if precomputed
self.text_hid_dim = text_hid_dim
self.dictionary = dictionary # for word embeddings
self.pooling_strat = pooling_strat
if self.text_encoder_type == "BERT":
self.text_encoder = BertModel.from_pretrained('bert-base-uncased')
self.text_emb_dim = self.text_encoder.config.hidden_size
elif self.text_encoder_type == "precomputed":
self.text_encoder = nn.Identity()
elif self.text_encoder_type == "w2v" or self.text_encoder_type == "glove":
# load pretrained word embeddings as weights
self.text_encoder = WordEmbedding(self.text_encoder_type,
self.pooling_strat,
self.dictionary)
self.text_emb_dim = self.text_encoder.embedding_dim
elif self.text_encoder_type == "rand":
self.text_encoder = nn.Linear(self.text_emb_dim, self.text_emb_dim)
else:
raise NameError(f"{text_encoder} not allowed as text encoder")
for param in self.text_encoder.parameters():
param.requires_grad = False
self.shared_feats = shared_feats
if self.shared_feats:
# Text embedding to image parameters
self.net = nn.Sequential(
nn.Linear(self.text_emb_dim, self.text_hid_dim),
nn.ReLU(),
nn.Linear(
self.text_hid_dim,
self.im_hid_dim # Weights
+ 1) # Biases
)
# Bit of a hack to copy torch default weight initialisation
self.first = nn.Linear(
1,
self.im_hid_dim * self.im_emb_dim # Weights
+ self.im_hid_dim, # Biases
bias=False)
else:
# Text embedding to image parameters
self.net = nn.Sequential(
nn.Linear(self.text_emb_dim, self.text_hid_dim),
nn.ReLU(),
nn.Linear(
self.text_hid_dim,
self.im_hid_dim * (self.im_emb_dim + 1) # Weights
+ self.im_hid_dim + 1) # Biases
)
def forward(self, text_embed, device):
im_params = self.net(text_embed)
if self.shared_feats:
shared_params = self.first(torch.ones(1).to(device))
bias_len = self.im_hid_dim + 1
out = torch.empty(
len(text_embed),
self.im_hid_dim * (self.im_emb_dim + 1) + self.im_hid_dim +
1).to(device)
out[:, :bias_len - 1] = shared_params[:bias_len - 1]
out[:, bias_len - 1] = im_params[:, 0]
out[:, bias_len:-self.im_hid_dim] = shared_params[bias_len - 1:]
out[:, -self.im_hid_dim:] = im_params[:, 1:]
return out
return im_params
def evaluate(self, args, batch, optimizer, task="train"):
"""
Evaluate batch on model
Returns:
- outer_loss: outer loop loss
- acc: accuracy on query set
"""
if task == "train":
self.train()
self.zero_grad()
else:
self.eval()
# Support set
train_inputs, train_targets = batch['train']
train_inputs = [x.to(args.device) for x in train_inputs]
# train_inputs = train_inputs[3].to(device=args.device)
train_targets = train_targets.to(device=args.device)
# Query set
test_inputs, test_targets = batch['test']
test_inputs = [x.to(args.device) for x in test_inputs]
# test_inputs = test_inputs[3].to(device=args.device)
test_targets = test_targets.to(device=args.device)
test_preds = torch.zeros(test_targets.shape).to(device=args.device)
# Unpack input
if self.text_encoder_type == "BERT":
_, train_texts, train_attn_masks, train_imss = train_inputs
_, test_texts, test_attn_masks, test_imss = test_inputs
else:
_, train_texts, train_imss = train_inputs
_, test_texts, test_imss = test_inputs
outer_loss = torch.tensor(0., device=args.device)
accuracy = torch.tensor(0., device=args.device)
for task_idx, (train_target, test_target) in enumerate(
zip(train_targets, test_targets)):
n_steps = 0
if task == "train":
n_steps = args.num_train_adapt_steps
else:
n_steps = args.num_test_adapt_steps
if self.text_encoder_type == "BERT":
im_params = self.get_im_params(train_texts[task_idx],
train_target, args.device,
train_attn_masks[task_idx])
else:
im_params = self.get_im_params(train_texts[task_idx],
train_target, args.device)
for _ in range(n_steps):
train_logit = self.im_forward(train_imss[task_idx], im_params)
inner_loss = F.cross_entropy(train_logit, train_target)
grads = torch.autograd.grad(inner_loss,
im_params,
create_graph=not args.first_order)
im_params -= args.step_size * grads[0]
test_logit = self.im_forward(test_imss[task_idx], im_params)
_, test_preds[task_idx] = test_logit.max(dim=-1)
outer_loss += F.cross_entropy(test_logit, test_target)
with torch.no_grad():
accuracy += get_accuracy(test_logit, test_target)
outer_loss.div_(train_imss.shape[0])
accuracy.div_(train_imss.shape[0])
if task == "train":
optimizer.zero_grad()
outer_loss.backward()
optimizer.step()
return outer_loss.detach().cpu().numpy(), accuracy.detach().cpu(
).numpy(), test_preds, test_targets
def get_im_params(self, text, targets, device, attn_mask=None):
NK, seq_len = text.shape
if self.text_encoder_type == "BERT":
# Need to reshape batch for BERT input
bert_output = self.text_encoder(text.view(-1, seq_len),
attention_mask=attn_mask.view(
-1, seq_len))
# Get [CLS] token
text_encoding = bert_output[1].view(NK, -1) # (N*K x 768)
elif self.text_encoder_type == "rand":
# Get a random tensor as the encoding
text_encoding = 2 * torch.rand(NK, self.text_emb_dim) - 1
else:
text_encoding = self.text_encoder(text.unsqueeze(0)).squeeze()
# Transform to per-class descriptions
class_text_enc = torch.empty(self.n_way, self.text_emb_dim).to(device)
for i in range(self.n_way):
class_text_enc[i] = text_encoding[(targets == i).nonzero(
as_tuple=True)[0][0]]
return self(class_text_enc, device)
def im_forward(self, im_embeds, im_params):
bias_len = self.im_hid_dim + 1
b_im = torch.unsqueeze(im_params[:, :bias_len], 2)
w_im = im_params[:, bias_len:].view(-1, self.im_emb_dim + 1,
self.im_hid_dim)
a = torch.matmul(im_embeds, w_im[:, :-1])
h = F.relu(torch.transpose(a, 1, 2) + b_im[:, :-1])
a_out = torch.matmul(torch.transpose(h, 1, 2),
torch.unsqueeze(w_im[:, -1], 2))
out = torch.squeeze(a_out) + b_im[:, -1]
return torch.transpose(out, 0, 1)
def training_run(args, model, optimizer, train_loader, val_loader,
max_test_batches):
"""
FUMI training loop
"""
best_loss, best_acc = test_loop(args, model, val_loader, max_test_batches)
print(f"\ninitial loss: {best_loss}, acc: {best_acc}")
best_batch_idx = 0
try:
# Training loop
for batch_idx, batch in enumerate(train_loader):
train_loss, train_acc = model.evaluate(args=args,
batch=batch,
optimizer=optimizer,
task="train")
wandb.log(
{
"train/acc": train_acc,
"train/loss": train_loss,
"num_episodes": (batch_idx + 1) * args.batch_size
},
step=batch_idx)
# Eval on validation set periodically
if batch_idx % args.eval_freq == 0 and batch_idx != 0:
val_loss, val_acc = test_loop(args, model, val_loader,
max_test_batches)
is_best = val_loss < best_loss
if is_best:
best_loss = val_loss
best_batch_idx = batch_idx
wandb.log({
"val/acc": val_acc,
"val/loss": val_loss
},
step=batch_idx)
checkpoint_dict = {
"batch_idx": batch_idx,
"state_dict": model.state_dict(),
"best_loss": best_loss,
"optimizer": optimizer.state_dict(),
"args": vars(args)
}
utils.save_checkpoint(checkpoint_dict, is_best)
print(
f"\nBatch {batch_idx+1}/{args.epochs}: \ntrain/loss: {train_loss}, train/acc: {train_acc}"
f"\nval/loss: {val_loss}, val/acc: {val_acc}")
# break after max iters or early stopping
if (batch_idx > args.epochs - 1) or (
args.patience > 0
and batch_idx - best_batch_idx > args.patience):
break
except KeyboardInterrupt:
pass
return model
def test_loop(args, model, test_loader, max_num_batches):
"""
Evaluate model on val/test set.
Returns:
- avg_test_acc (float): average test accuracy per task
- avg_test_loss (float): average test loss per task
"""
avg_test_acc = AverageMeter()
avg_test_loss = AverageMeter()
test_preds = []
test_targets = []
for batch_idx, batch in enumerate(
tqdm(test_loader, total=max_num_batches, position=0, leave=True)):
test_loss, test_acc, preds, target = model.evaluate(args=args,
batch=batch,
optimizer=None,
task="test")
avg_test_acc.update(test_acc)
avg_test_loss.update(test_loss)
test_preds.append(preds)
test_targets.append(target)
if batch_idx > max_num_batches - 1:
break
return avg_test_loss.avg, avg_test_acc.avg, test_preds, test_targets
def get_accuracy(logits, targets):
_, predictions = torch.max(logits, dim=-1)
return torch.mean(predictions.eq(targets).float())
| [
"torch.nn.ReLU",
"wandb.log",
"torch.max",
"torch.squeeze",
"torch.unsqueeze",
"torch.matmul",
"torch.nn.Identity",
"transformers.BertModel.from_pretrained",
"torch.transpose",
"torch.autograd.grad",
"torch.empty",
"tqdm.tqdm",
"torch.tensor",
"torch.nn.Linear",
"torch.nn.functional.cros... | [((12257, 12282), 'torch.max', 'torch.max', (['logits'], {'dim': '(-1)'}), '(logits, dim=-1)\n', (12266, 12282), False, 'import torch\n'), ((5240, 5277), 'torch.tensor', 'torch.tensor', (['(0.0)'], {'device': 'args.device'}), '(0.0, device=args.device)\n', (5252, 5277), False, 'import torch\n'), ((5296, 5333), 'torch.tensor', 'torch.tensor', (['(0.0)'], {'device': 'args.device'}), '(0.0, device=args.device)\n', (5308, 5333), False, 'import torch\n'), ((8307, 8350), 'torch.unsqueeze', 'torch.unsqueeze', (['im_params[:, :bias_len]', '(2)'], {}), '(im_params[:, :bias_len], 2)\n', (8322, 8350), False, 'import torch\n'), ((8494, 8531), 'torch.matmul', 'torch.matmul', (['im_embeds', 'w_im[:, :-1]'], {}), '(im_embeds, w_im[:, :-1])\n', (8506, 8531), False, 'import torch\n'), ((8774, 8800), 'torch.transpose', 'torch.transpose', (['out', '(0)', '(1)'], {}), '(out, 0, 1)\n', (8789, 8800), False, 'import torch\n'), ((11557, 11621), 'tqdm.tqdm', 'tqdm', (['test_loader'], {'total': 'max_num_batches', 'position': '(0)', 'leave': '(True)'}), '(test_loader, total=max_num_batches, position=0, leave=True)\n', (11561, 11621), False, 'from tqdm import tqdm\n'), ((1270, 1316), 'transformers.BertModel.from_pretrained', 'BertModel.from_pretrained', (['"""bert-base-uncased"""'], {}), "('bert-base-uncased')\n", (1295, 1316), False, 'from transformers import BertModel\n'), ((2709, 2786), 'torch.nn.Linear', 'nn.Linear', (['(1)', '(self.im_hid_dim * self.im_emb_dim + self.im_hid_dim)'], {'bias': '(False)'}), '(1, self.im_hid_dim * self.im_emb_dim + self.im_hid_dim, bias=False)\n', (2718, 2786), True, 'import torch.nn as nn\n'), ((6654, 6694), 'torch.nn.functional.cross_entropy', 'F.cross_entropy', (['test_logit', 'test_target'], {}), '(test_logit, test_target)\n', (6669, 6694), True, 'import torch.nn.functional as F\n'), ((8622, 8646), 'torch.transpose', 'torch.transpose', (['h', '(1)', '(2)'], {}), '(h, 1, 2)\n', (8637, 8646), False, 'import torch\n'), ((8677, 8708), 'torch.unsqueeze', 'torch.unsqueeze', (['w_im[:, -1]', '(2)'], {}), '(w_im[:, -1], 2)\n', (8692, 8708), False, 'import torch\n'), ((8724, 8744), 'torch.squeeze', 'torch.squeeze', (['a_out'], {}), '(a_out)\n', (8737, 8744), False, 'import torch\n'), ((9474, 9606), 'wandb.log', 'wandb.log', (["{'train/acc': train_acc, 'train/loss': train_loss, 'num_episodes': (\n batch_idx + 1) * args.batch_size}"], {'step': 'batch_idx'}), "({'train/acc': train_acc, 'train/loss': train_loss, 'num_episodes':\n (batch_idx + 1) * args.batch_size}, step=batch_idx)\n", (9483, 9606), False, 'import wandb\n'), ((1472, 1485), 'torch.nn.Identity', 'nn.Identity', ([], {}), '()\n', (1483, 1485), True, 'import torch.nn as nn\n'), ((2374, 2421), 'torch.nn.Linear', 'nn.Linear', (['self.text_emb_dim', 'self.text_hid_dim'], {}), '(self.text_emb_dim, self.text_hid_dim)\n', (2383, 2421), True, 'import torch.nn as nn\n'), ((2439, 2448), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (2446, 2448), True, 'import torch.nn as nn\n'), ((2466, 2515), 'torch.nn.Linear', 'nn.Linear', (['self.text_hid_dim', '(self.im_hid_dim + 1)'], {}), '(self.text_hid_dim, self.im_hid_dim + 1)\n', (2475, 2515), True, 'import torch.nn as nn\n'), ((2990, 3037), 'torch.nn.Linear', 'nn.Linear', (['self.text_emb_dim', 'self.text_hid_dim'], {}), '(self.text_emb_dim, self.text_hid_dim)\n', (2999, 3037), True, 'import torch.nn as nn\n'), ((3055, 3064), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (3062, 3064), True, 'import torch.nn as nn\n'), ((3082, 3178), 'torch.nn.Linear', 'nn.Linear', (['self.text_hid_dim', '(self.im_hid_dim * (self.im_emb_dim + 1) + self.im_hid_dim + 1)'], {}), '(self.text_hid_dim, self.im_hid_dim * (self.im_emb_dim + 1) + self\n .im_hid_dim + 1)\n', (3091, 3178), True, 'import torch.nn as nn\n'), ((4835, 4866), 'torch.zeros', 'torch.zeros', (['test_targets.shape'], {}), '(test_targets.shape)\n', (4846, 4866), False, 'import torch\n'), ((6204, 6246), 'torch.nn.functional.cross_entropy', 'F.cross_entropy', (['train_logit', 'train_target'], {}), '(train_logit, train_target)\n', (6219, 6246), True, 'import torch.nn.functional as F\n'), ((6271, 6348), 'torch.autograd.grad', 'torch.autograd.grad', (['inner_loss', 'im_params'], {'create_graph': '(not args.first_order)'}), '(inner_loss, im_params, create_graph=not args.first_order)\n', (6290, 6348), False, 'import torch\n'), ((6713, 6728), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (6726, 6728), False, 'import torch\n'), ((7961, 8003), 'torch.empty', 'torch.empty', (['self.n_way', 'self.text_emb_dim'], {}), '(self.n_way, self.text_emb_dim)\n', (7972, 8003), False, 'import torch\n'), ((8551, 8575), 'torch.transpose', 'torch.transpose', (['a', '(1)', '(2)'], {}), '(a, 1, 2)\n', (8566, 8575), False, 'import torch\n'), ((10146, 10215), 'wandb.log', 'wandb.log', (["{'val/acc': val_acc, 'val/loss': val_loss}"], {'step': 'batch_idx'}), "({'val/acc': val_acc, 'val/loss': val_loss}, step=batch_idx)\n", (10155, 10215), False, 'import wandb\n'), ((1968, 2015), 'torch.nn.Linear', 'nn.Linear', (['self.text_emb_dim', 'self.text_emb_dim'], {}), '(self.text_emb_dim, self.text_emb_dim)\n', (1977, 2015), True, 'import torch.nn as nn\n'), ((3424, 3437), 'torch.ones', 'torch.ones', (['(1)'], {}), '(1)\n', (3434, 3437), False, 'import torch\n'), ((7762, 7795), 'torch.rand', 'torch.rand', (['NK', 'self.text_emb_dim'], {}), '(NK, self.text_emb_dim)\n', (7772, 7795), False, 'import torch\n')] |
#coding: utf-8
from __future__ import print_function
from builtins import str
from builtins import range
from .. import ParallelSampler
import ctypes as ct
import os
import cosmosis
import numpy as np
import sys
loglike_type = ct.CFUNCTYPE(ct.c_double,
ct.POINTER(ct.c_double), #cube
ct.c_int, #ndim
ct.c_int, #npars
ct.c_voidp, #context
)
dumper_type = ct.CFUNCTYPE(None, #void
ct.c_int, #nsamples
ct.c_int, #nlive
ct.c_int, #npars
ct.POINTER(ct.c_double), #physlive
ct.POINTER(ct.c_double), #posterior
ct.POINTER(ct.c_double), #paramConstr
ct.c_double, #maxLogLike
ct.c_double, #logZ
ct.c_double, #INSLogZ
ct.c_double, #logZerr
ct.c_voidp, #Context
)
multinest_args = [
ct.c_bool, #nest_IS nested importance sampling
ct.c_bool, #nest_mmodal mode separation
ct.c_bool, #nest_ceff constant efficiency mode
ct.c_int, #nest_nlive
ct.c_double, #nest_tol
ct.c_double, #nest_ef
ct.c_int, #nest_ndims,
ct.c_int, #nest_totPar,
ct.c_int, #nest_nCdims,
ct.c_int, #maxClst,
ct.c_int, #nest_updInt,
ct.c_double, #nest_Ztol,
ct.c_char_p, #nest_root,
ct.c_int, #seed,
ct.POINTER(ct.c_int), #nest_pWrap,
ct.c_bool, #nest_fb,
ct.c_bool, #nest_resume,
ct.c_bool, #nest_outfile,
ct.c_bool, #initMPI,
ct.c_double, #nest_logZero,
ct.c_int, #nest_maxIter,
loglike_type, #loglike,
dumper_type, #dumper,
ct.c_voidp, #context
]
MULTINEST_SECTION='multinest'
class MultinestSampler(ParallelSampler):
parallel_output = False
sampler_outputs = [("like", float), ("post", float), ("weight", float)]
supports_smp=False
def config(self):
if self.pool:
libname = "libnest3_mpi.so"
else:
libname = "libnest3.so"
dirname = os.path.split(__file__)[0]
libname = os.path.join(dirname, "multinest_src", libname)
try:
libnest3 = ct.cdll.LoadLibrary(libname)
except Exception as error:
sys.stderr.write("Multinest could not be loaded.\n")
sys.stderr.write("This may mean an MPI compiler was not found to compile it,\n")
sys.stderr.write("or that some other error occurred. More info below.\n")
sys.stderr.write(str(error)+'\n')
sys.exit(1)
self._run = libnest3.run
self._run.restype=None
self._run.argtypes = multinest_args
self.converged=False
self.ndim = len(self.pipeline.varied_params)
# We add one to the output to save the posterior as well as the
# likelihood.
self.npar = self.ndim + len(self.pipeline.extra_saves) + 1
#Required options
self.max_iterations = self.read_ini("max_iterations", int)
self.live_points = self.read_ini("live_points", int)
#Output and feedback options
self.feedback = self.read_ini("feedback", bool, True)
self.resume = self.read_ini("resume", bool, False)
self.multinest_outfile_root = self.read_ini("multinest_outfile_root", str, "")
self.update_interval = self.read_ini("update_interval", int, 200)
#General run options
self.random_seed = self.read_ini("random_seed", int, -1)
self.importance = self.read_ini("ins", bool, True)
self.efficiency = self.read_ini("efficiency", float, 1.0)
self.tolerance = self.read_ini("tolerance", float, 0.1)
self.log_zero = self.read_ini("log_zero", float, -1e6)
#Multi-modal options
self.mode_separation = self.read_ini("mode_separation", bool, False)
self.const_efficiency = self.read_ini("constant_efficiency", bool, False)
self.max_modes = self.read_ini("max_modes", int, default=100)
self.cluster_dimensions = self.read_ini("cluster_dimensions", int, default=-1)
self.mode_ztolerance = self.read_ini("mode_ztolerance", float, default=0.5)
#Parameters with wrap-around edges - can help sampling
#of parameters which are relatively flat in likelihood
wrapped_params = self.read_ini("wrapped_params", str, default="")
wrapped_params = wrapped_params.split()
self.wrapping = [0 for i in range(self.ndim)]
if wrapped_params:
print("")
for p in wrapped_params:
try:
P = p.split('--')
except ValueError:
raise ValueError("You included {} in wrapped_params mulitnest option but should be format: section--name".format(p))
if P in self.pipeline.varied_params:
index = self.pipeline.varied_params.index(P)
self.wrapping[index] = 1
print("MULTINEST: Parameter {} ({}) will be wrapped around the edge of its prior".format(index,p))
elif P in self.pipeline.parameters:
print("MULTINEST NOTE: You asked for wrapped sampling on {}. That parameter is not fixed in this pipeline, so this will have no effect.".format(p))
else:
raise ValueError("You asked for an unknown parameter, {} to be wrapped around in the multinest wrapped_params option.".format(p))
if wrapped_params:
print("")
if self.output:
def dumper(nsample, nlive, nparam, live, post, paramConstr, max_log_like, logz, ins_logz, log_z_err, context):
print("Saving %d samples" % nsample)
self.output_params(nsample, live, post, logz, ins_logz, log_z_err)
self.wrapped_output_logger = dumper_type(dumper)
else:
def dumper(nsample, nlive, nparam, live, post, paramConstr, max_log_like, logz, ins_logz, log_z_err, context):
return
self.wrapped_output_logger = dumper_type(dumper)
def likelihood(cube_p, ndim, nparam, context_p):
# The -1 is because we store the likelihood separately.
nextra = nparam-ndim-1
#pull out values from cube
cube_vector = np.array([cube_p[i] for i in range(ndim)])
vector = self.pipeline.denormalize_vector_from_prior(cube_vector)
# For information only
prior = self.pipeline.prior(vector)
try:
like, extra = self.pipeline.likelihood(vector)
except KeyboardInterrupt:
raise sys.exit(1)
for i in range(ndim):
cube_p[i] = vector[i]
for i in range(nextra):
cube_p[ndim+i] = extra[i]
# posterior column
cube_p[ndim+nextra] = prior + like
return like
self.wrapped_likelihood = loglike_type(likelihood)
def worker(self):
self.sample()
def execute(self):
self.log_z = 0.0
self.log_z_err = 0.0
self.sample()
self.output.final("log_z", self.log_z)
self.output.final("log_z_error", self.log_z_err)
def sample(self):
# only master gets dumper function
cluster_dimensions = self.ndim if self.cluster_dimensions==-1 else self.cluster_dimensions
periodic_boundaries = (ct.c_int*self.ndim)()
for i in range(self.ndim):
periodic_boundaries[i] = self.wrapping[i]
context=None
init_mpi=False
self._run(self.importance, self.mode_separation,
self.const_efficiency, self.live_points,
self.tolerance, self.efficiency, self.ndim,
self.npar, cluster_dimensions, self.max_modes,
self.update_interval, self.mode_ztolerance,
self.multinest_outfile_root.encode('ascii'), self.random_seed,
periodic_boundaries, self.feedback, self.resume,
self.multinest_outfile_root!="", init_mpi,
self.log_zero, self.max_iterations,
self.wrapped_likelihood, self.wrapped_output_logger,
context)
self.converged = True
def output_params(self, n, live, posterior, log_z, ins_log_z, log_z_err):
self.log_z = ins_log_z if self.importance else log_z
self.log_z_err = log_z_err
data = np.array([posterior[i] for i in range(n*(self.npar+2))]).reshape((self.npar+2, n))
for row in data.T:
params = row[:self.ndim]
extra_vals = row[self.ndim:self.npar-1]
post = row[self.npar-1]
like = row[self.npar]
importance = row[self.npar+1]
self.output.parameters(params, extra_vals, like, post, importance)
self.output.final("nsample", n)
self.output.flush()
def is_converged(self):
return self.converged
| [
"ctypes.POINTER",
"ctypes.cdll.LoadLibrary",
"os.path.join",
"builtins.str",
"os.path.split",
"sys.stderr.write",
"builtins.range",
"sys.exit"
] | [((259, 282), 'ctypes.POINTER', 'ct.POINTER', (['ct.c_double'], {}), '(ct.c_double)\n', (269, 282), True, 'import ctypes as ct\n'), ((477, 500), 'ctypes.POINTER', 'ct.POINTER', (['ct.c_double'], {}), '(ct.c_double)\n', (487, 500), True, 'import ctypes as ct\n'), ((518, 541), 'ctypes.POINTER', 'ct.POINTER', (['ct.c_double'], {}), '(ct.c_double)\n', (528, 541), True, 'import ctypes as ct\n'), ((560, 583), 'ctypes.POINTER', 'ct.POINTER', (['ct.c_double'], {}), '(ct.c_double)\n', (570, 583), True, 'import ctypes as ct\n'), ((1217, 1237), 'ctypes.POINTER', 'ct.POINTER', (['ct.c_int'], {}), '(ct.c_int)\n', (1227, 1237), True, 'import ctypes as ct\n'), ((1904, 1951), 'os.path.join', 'os.path.join', (['dirname', '"""multinest_src"""', 'libname'], {}), "(dirname, 'multinest_src', libname)\n", (1916, 1951), False, 'import os\n'), ((7293, 7309), 'builtins.range', 'range', (['self.ndim'], {}), '(self.ndim)\n', (7298, 7309), False, 'from builtins import range\n'), ((1859, 1882), 'os.path.split', 'os.path.split', (['__file__'], {}), '(__file__)\n', (1872, 1882), False, 'import os\n'), ((2001, 2029), 'ctypes.cdll.LoadLibrary', 'ct.cdll.LoadLibrary', (['libname'], {}), '(libname)\n', (2020, 2029), True, 'import ctypes as ct\n'), ((6514, 6525), 'builtins.range', 'range', (['ndim'], {}), '(ndim)\n', (6519, 6525), False, 'from builtins import range\n'), ((6587, 6600), 'builtins.range', 'range', (['nextra'], {}), '(nextra)\n', (6592, 6600), False, 'from builtins import range\n'), ((2077, 2129), 'sys.stderr.write', 'sys.stderr.write', (['"""Multinest could not be loaded.\n"""'], {}), "('Multinest could not be loaded.\\n')\n", (2093, 2129), False, 'import sys\n'), ((2142, 2227), 'sys.stderr.write', 'sys.stderr.write', (['"""This may mean an MPI compiler was not found to compile it,\n"""'], {}), "('This may mean an MPI compiler was not found to compile it,\\n'\n )\n", (2158, 2227), False, 'import sys\n'), ((2235, 2309), 'sys.stderr.write', 'sys.stderr.write', (['"""or that some other error occurred. More info below.\n"""'], {}), "('or that some other error occurred. More info below.\\n')\n", (2251, 2309), False, 'import sys\n'), ((2368, 2379), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (2376, 2379), False, 'import sys\n'), ((4335, 4351), 'builtins.range', 'range', (['self.ndim'], {}), '(self.ndim)\n', (4340, 4351), False, 'from builtins import range\n'), ((6480, 6491), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (6488, 6491), False, 'import sys\n'), ((2339, 2349), 'builtins.str', 'str', (['error'], {}), '(error)\n', (2342, 2349), False, 'from builtins import str\n'), ((6164, 6175), 'builtins.range', 'range', (['ndim'], {}), '(ndim)\n', (6169, 6175), False, 'from builtins import range\n'), ((8338, 8364), 'builtins.range', 'range', (['(n * (self.npar + 2))'], {}), '(n * (self.npar + 2))\n', (8343, 8364), False, 'from builtins import range\n')] |
from __future__ import annotations
from collections import OrderedDict
from datetime import datetime
from pathlib import Path
from typing import TYPE_CHECKING, Union, Dict, List
import pandas as pd
from pkg_resources import get_distribution
from .utils import TextBuffer
if TYPE_CHECKING:
from os import PathLike
__version__ = get_distribution("starfile").version
class StarWriter:
def __init__(self, dataframes: Union[pd.DataFrame, Dict[pd.DataFrame], List[pd.DataFrame]],
filename: PathLike, overwrite: bool = False, float_format: str = '%.6f',
sep: str = '\t', na_rep: str = '<NA>', force_loop: bool = False):
self.overwrite = overwrite
self.filename = filename
self.dataframes = dataframes
self.float_format = float_format
self.sep = sep
self.na_rep = na_rep
self.force_loop = force_loop
self.buffer = TextBuffer()
self.write_star_file()
@property
def dataframes(self):
"""
Ordered dictionary of pandas dataframes
df.name defines the data block name
"""
return self._dataframes
@dataframes.setter
def dataframes(self, dataframes: Union[pd.DataFrame, Dict[pd.DataFrame], List[pd.DataFrame]]):
if isinstance(dataframes, pd.DataFrame):
self._dataframes = self.coerce_dataframe(dataframes)
elif isinstance(dataframes, dict):
self._dataframes = self.coerce_dict(dataframes)
elif isinstance(dataframes, list):
self._dataframes = self.coerce_list(dataframes)
else:
raise ValueError(f'Expected a DataFrame, Dict or List object, got {type(dataframes)}')
@staticmethod
def coerce_dataframe(df: pd.DataFrame):
name = getattr(df, 'name', '')
if name != '':
name = 0
return {name: df}
@staticmethod
def coerce_dict(dfs: Dict[str, pd.DataFrame]):
"""
This method ensures that dataframe names are updated based on dict keys
"""
for key, df in dfs.items():
df.name = str(key)
return dfs
def coerce_list(self, dfs: List[pd.DataFrame]):
"""
This method coerces a list of DataFrames into a dict
"""
return self.coerce_dict(OrderedDict([(idx, df) for idx, df in enumerate(dfs)]))
@property
def filename(self):
return self._filename
@filename.setter
def filename(self, filename: Union[Path, str]):
self._filename = Path(filename)
if not self.file_writable:
raise FileExistsError('to overwrite an existing file set overwrite=True')
@property
def file_exists(self):
return self.filename.exists()
@property
def file_writable(self):
if self.overwrite or (not self.file_exists):
return True
else:
return False
def write_package_info(self):
date = datetime.now().strftime('%d/%m/%Y')
time = datetime.now().strftime('%H:%M:%S')
line = f'Created by the starfile Python package (version {__version__}) at {time} on' \
f' {date}'
self.buffer.add_comment(line)
self.buffer.add_blank_lines(1)
self.buffer.write_as_new_file_and_clear(self.filename)
def write_star_file(self, filename: str = None):
self.write_package_info()
for _, df in self.dataframes.items():
self.write_block(df)
self.buffer.add_blank_line()
self.buffer.append_to_file_and_clear(self.filename)
def write_loopheader(self, df: pd.DataFrame):
self.buffer.add_line('loop_')
lines = [f'_{column_name} #{idx}' for idx, column_name in enumerate(df.columns, 1)]
for line in lines:
self.buffer.add_line(line)
self.buffer.append_to_file_and_clear(self.filename)
@staticmethod
def get_block_name(df: pd.DataFrame):
return 'data_' + getattr(df, 'name', '')
def add_block_name_to_buffer(self, df: pd.DataFrame):
self.buffer.add_line(self.get_block_name(df))
self.buffer.add_blank_lines(1)
self.buffer.append_to_file_and_clear(self.filename)
def write_block(self, df: pd.DataFrame):
self.add_block_name_to_buffer(df)
if (df.shape[0] == 1) and not self.force_loop:
self._write_simple_block(df)
elif (df.shape[0] > 1) or self.force_loop:
self._write_loop_block(df)
self.buffer.add_blank_lines(2)
self.buffer.append_to_file_and_clear(self.filename)
def _write_simple_block(self, df: pd.DataFrame):
lines = [f'_{column_name}\t\t\t{df[column_name].iloc[0]}'
for column_name in df.columns]
for line in lines:
self.buffer.add_line(line)
self.buffer.append_to_file_and_clear(self.filename)
def _write_loop_block(self, df: pd.DataFrame):
self.write_loopheader(df)
df.to_csv(self.filename, mode='a', sep=self.sep, header=False, index=False,
float_format=self.float_format, na_rep=self.na_rep)
| [
"datetime.datetime.now",
"pkg_resources.get_distribution",
"pathlib.Path"
] | [((336, 364), 'pkg_resources.get_distribution', 'get_distribution', (['"""starfile"""'], {}), "('starfile')\n", (352, 364), False, 'from pkg_resources import get_distribution\n'), ((2534, 2548), 'pathlib.Path', 'Path', (['filename'], {}), '(filename)\n', (2538, 2548), False, 'from pathlib import Path\n'), ((2960, 2974), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (2972, 2974), False, 'from datetime import datetime\n'), ((3011, 3025), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (3023, 3025), False, 'from datetime import datetime\n')] |
from conan.packager import ConanMultiPackager
import copy
import platform
if __name__ == "__main__":
builder = ConanMultiPackager(clang_versions=["9.0"], gcc_versions=["9.2"])
builder.add_common_builds(shared_option_name="leveldb:shared", pure_c=False)
if platform.system() == "Linux":
filtered_builds = []
for settings, options, _, _, _ in builder.items:
if settings["arch"] != "x86":
filtered_builds.append([settings, options])
if settings["compiler"] == "gcc" and float(settings["compiler.version"]) > 5:
settings["compiler.libcxx"] = "libstdc++11"
builder.builds = filtered_builds
builder.run()
| [
"platform.system",
"conan.packager.ConanMultiPackager"
] | [((116, 180), 'conan.packager.ConanMultiPackager', 'ConanMultiPackager', ([], {'clang_versions': "['9.0']", 'gcc_versions': "['9.2']"}), "(clang_versions=['9.0'], gcc_versions=['9.2'])\n", (134, 180), False, 'from conan.packager import ConanMultiPackager\n'), ((273, 290), 'platform.system', 'platform.system', ([], {}), '()\n', (288, 290), False, 'import platform\n')] |
import numpy as np
import matplotlib.pyplot as plt
import math
def log(list_name):
for i in range(len(list_name)):
list_name[i] = math.log10(list_name[i])
print(list_name[i])
return list_name
size = 4
x = np.arange(size)
video_file = [11132, 21164, 34452, 45208] # 每帧视频文件大小(byte)
video_file = log(video_file)
data_to_cloud = [127, 248, 365, 488] # 每帧所有edge上传的文件大小(byte)(2,2,3,4个摄像头)
data_to_cloud = log(data_to_cloud)
total_width, n = 0.8, 3
width = total_width / n
x = x - (total_width - width) / 2
plt.xlabel('Total Camera Numbers', fontsize=20)
plt.ylabel('Communication Cost (lg(Byte))', fontsize=20)
plt.bar(x-0.45*width, video_file, fc='#036564', width=0.75*width, label='Input Data to Cloud (Cloud)')
# plt.bar(x-0.45*width, data_to_cam, fc='#033649', width=0.75*width, bottom=video_file, label='Feedback (Cloud)')
plt.bar(x+0.45*width, data_to_cloud, fc='#764D39', width=0.75*width, label='Input Data to Cloud (EATP)')
# plt.bar(x+0.45*width, data_to_cam, fc='#250807', width=0.75*width, bottom=data_to_cloud, label='Feedback (EaOT)')
plt.xticks(x, (2, 4, 6, 8), fontsize=18)
plt.yticks(fontsize=18)
plt.legend(loc='center', bbox_to_anchor=(0.62, 0.11), fontsize=17)
plt.show()
| [
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.yticks",
"math.log10",
"numpy.arange",
"matplotlib.pyplot.show"
] | [((232, 247), 'numpy.arange', 'np.arange', (['size'], {}), '(size)\n', (241, 247), True, 'import numpy as np\n'), ((533, 580), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Total Camera Numbers"""'], {'fontsize': '(20)'}), "('Total Camera Numbers', fontsize=20)\n", (543, 580), True, 'import matplotlib.pyplot as plt\n'), ((581, 637), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Communication Cost (lg(Byte))"""'], {'fontsize': '(20)'}), "('Communication Cost (lg(Byte))', fontsize=20)\n", (591, 637), True, 'import matplotlib.pyplot as plt\n'), ((638, 750), 'matplotlib.pyplot.bar', 'plt.bar', (['(x - 0.45 * width)', 'video_file'], {'fc': '"""#036564"""', 'width': '(0.75 * width)', 'label': '"""Input Data to Cloud (Cloud)"""'}), "(x - 0.45 * width, video_file, fc='#036564', width=0.75 * width,\n label='Input Data to Cloud (Cloud)')\n", (645, 750), True, 'import matplotlib.pyplot as plt\n'), ((855, 969), 'matplotlib.pyplot.bar', 'plt.bar', (['(x + 0.45 * width)', 'data_to_cloud'], {'fc': '"""#764D39"""', 'width': '(0.75 * width)', 'label': '"""Input Data to Cloud (EATP)"""'}), "(x + 0.45 * width, data_to_cloud, fc='#764D39', width=0.75 * width,\n label='Input Data to Cloud (EATP)')\n", (862, 969), True, 'import matplotlib.pyplot as plt\n'), ((1076, 1116), 'matplotlib.pyplot.xticks', 'plt.xticks', (['x', '(2, 4, 6, 8)'], {'fontsize': '(18)'}), '(x, (2, 4, 6, 8), fontsize=18)\n', (1086, 1116), True, 'import matplotlib.pyplot as plt\n'), ((1117, 1140), 'matplotlib.pyplot.yticks', 'plt.yticks', ([], {'fontsize': '(18)'}), '(fontsize=18)\n', (1127, 1140), True, 'import matplotlib.pyplot as plt\n'), ((1141, 1207), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""center"""', 'bbox_to_anchor': '(0.62, 0.11)', 'fontsize': '(17)'}), "(loc='center', bbox_to_anchor=(0.62, 0.11), fontsize=17)\n", (1151, 1207), True, 'import matplotlib.pyplot as plt\n'), ((1208, 1218), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1216, 1218), True, 'import matplotlib.pyplot as plt\n'), ((144, 168), 'math.log10', 'math.log10', (['list_name[i]'], {}), '(list_name[i])\n', (154, 168), False, 'import math\n')] |
import numpy
from chainer import cuda
import chainer.serializers as S
import chainer.links as L
from nltk.corpus import stopwords
from context_models import CbowContext, BiLstmContext
from defs import IN_TO_OUT_UNITS_RATIO, NEGATIVE_SAMPLING_NUM
class ModelReader(object):
'''
Reads a pre-trained model using a config file
'''
def __init__(self, config_file):
self.gpu = -1 # todo support gpu
print('Reading config file: ' + config_file)
params = self.read_config_file(config_file)
print('Config: ', params)
self.w, self.word2index, self.index2word, self.model = self.read_model(params)
def read_config_file(self, filename):
params = {}
config_path = filename[:filename.rfind('/')+1]
params['config_path'] = config_path
with open(filename, 'r') as f:
for line in f:
if not line.startswith('#'):
[param, val] = line.strip().split()
params[param] = val
return params
def read_model(self, params, train=False):
if 'model_type' in params:
model_type = params['model_type']
else:
model_type = 'lstm_context'
if model_type == 'lstm_context':
return self.read_lstm_model(params, train)
elif model_type == 'bow_context':
return self.read_bow_model(params)
else:
raise Exception("Unknown model type: " + model_type)
def read_lstm_model(self, params, train):
assert train == False # reading a model to continue training is currently not supported
words_file = params['config_path'] + params['words_file']
model_file = params['config_path'] + params['model_file']
unit = int(params['unit'])
deep = (params['deep'] == 'yes')
drop_ratio = float(params['drop_ratio'])
#read and normalize target word embeddings
w, word2index, index2word = self.read_words(words_file)
s = numpy.sqrt((w * w).sum(1))
s[s==0.] = 1.
w /= s.reshape((s.shape[0], 1)) # normalize
context_word_units = unit
lstm_hidden_units = IN_TO_OUT_UNITS_RATIO*unit
target_word_units = IN_TO_OUT_UNITS_RATIO*unit
cs = [1 for _ in range(len(word2index))] # dummy word counts - not used for eval
loss_func = L.NegativeSampling(target_word_units, cs, NEGATIVE_SAMPLING_NUM) # dummy loss func - not used for eval
model = BiLstmContext(deep, self.gpu, word2index, context_word_units, lstm_hidden_units, target_word_units, loss_func, train, drop_ratio)
S.load_npz(model_file, model,strict=False)
return w, word2index, index2word, model
def read_bow_model(self, params):
words_file = params['config_path'] + params['words_file']
contexts_file = params['config_path'] + params['contexts_file'] if 'contexts_file' in params else None
window_size = int(params['window_size'])
use_stopwords = params['stopwords']
if 'word_counts_file' in params:
word_counts_file = params['config_path'] + params['word_counts_file']
else:
word_counts_file = None
if use_stopwords == 'yes':
stop = set(stopwords.words('english') + ['.',',','(',')','[',']',':','"',"'","'s","-",';','?','!','|','%','/','\\'])
else:
stop = set()
word_counts = self.read_word_counts(word_counts_file) if word_counts_file is not None else None
# read and normalize target words embeddings
w, word2index, index2word = self.read_words(words_file)
s = numpy.sqrt((w * w).sum(1))
s[s==0.] = 1.
w /= s.reshape((s.shape[0], 1)) # normalize
# read and normalize context words embeddings (if using different embeddings for context words)
if contexts_file is not None:
c, _, _ = self.read_words(words_file) # assuming words and contexts vocabs are identical
s = numpy.sqrt((c * c).sum(1))
s[s==0.] = 1.
c /= s.reshape((s.shape[0], 1)) # normalize
else:
c = None
model = CbowContext(w, c, word2index, stop, window_size, word_counts)
return w, word2index, index2word, model
def read_words(self, filename):
with open(filename, 'r') as f:
ss = f.readline().split()
n_vocab, n_units = int(ss[0]), int(ss[1])
word2index = {}
index2word = []
w = numpy.empty((n_vocab, n_units), dtype=numpy.float32)
for i, line in enumerate(f):
ss = line.split()
assert len(ss) == n_units + 1
word = ss[0]
word2index[word] = i
index2word.append(word)
w[i] = numpy.array([float(s) for s in ss[1:]], dtype=numpy.float32)
return w, word2index, index2word
def read_word_counts(self, filename):
counts = {}
with open(filename) as f:
for line in f:
if len(line) > 0:
tokens = line.split('\t')
word = tokens[0].strip()
count = int(tokens[1].strip())
counts[word] = count
return counts
| [
"nltk.corpus.stopwords.words",
"context_models.CbowContext",
"numpy.empty",
"context_models.BiLstmContext",
"chainer.links.NegativeSampling",
"chainer.serializers.load_npz"
] | [((2480, 2544), 'chainer.links.NegativeSampling', 'L.NegativeSampling', (['target_word_units', 'cs', 'NEGATIVE_SAMPLING_NUM'], {}), '(target_word_units, cs, NEGATIVE_SAMPLING_NUM)\n', (2498, 2544), True, 'import chainer.links as L\n'), ((2608, 2741), 'context_models.BiLstmContext', 'BiLstmContext', (['deep', 'self.gpu', 'word2index', 'context_word_units', 'lstm_hidden_units', 'target_word_units', 'loss_func', 'train', 'drop_ratio'], {}), '(deep, self.gpu, word2index, context_word_units,\n lstm_hidden_units, target_word_units, loss_func, train, drop_ratio)\n', (2621, 2741), False, 'from context_models import CbowContext, BiLstmContext\n'), ((2746, 2789), 'chainer.serializers.load_npz', 'S.load_npz', (['model_file', 'model'], {'strict': '(False)'}), '(model_file, model, strict=False)\n', (2756, 2789), True, 'import chainer.serializers as S\n'), ((4353, 4414), 'context_models.CbowContext', 'CbowContext', (['w', 'c', 'word2index', 'stop', 'window_size', 'word_counts'], {}), '(w, c, word2index, stop, window_size, word_counts)\n', (4364, 4414), False, 'from context_models import CbowContext, BiLstmContext\n'), ((4713, 4765), 'numpy.empty', 'numpy.empty', (['(n_vocab, n_units)'], {'dtype': 'numpy.float32'}), '((n_vocab, n_units), dtype=numpy.float32)\n', (4724, 4765), False, 'import numpy\n'), ((3413, 3439), 'nltk.corpus.stopwords.words', 'stopwords.words', (['"""english"""'], {}), "('english')\n", (3428, 3439), False, 'from nltk.corpus import stopwords\n')] |
import requests
from operator import itemgetter
import os
url = 'https://hacker-news.firebaseio.com/v0/topstories.json'
# /Users/ldu020/workspace/github.com/mrdulin/python-codelab/venv/lib/python3.7/site-packages/urllib3/connectionpool.py:1004: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
# InsecureRequestWarning,
r = requests.get(url, verify=False)
print('Status code: ', r.status_code)
submission_ids = r.json()
submission_dicts = []
for submission_id in submission_ids[:30]:
url = 'https://hacker-news.firebaseio.com/v0/item/' + \
str(submission_id) + '.json'
submission_r = requests.get(url, verify=False)
print(submission_r.status_code)
response_dict = submission_r.json()
submission_dict = {
'title': response_dict['title'],
'link': 'https://news.ycombinator.com/item?id=' + str(submission_id),
'comments': response_dict.get('descendants', 0)
}
submission_dicts.append(submission_dict)
submission_dicts = sorted(submission_dicts, key=itemgetter('comments'))
for submission_dict in submission_dicts:
print('\nTitle: ', submission_dict['title'])
print('Discussion Link: ', submission_dict['link'])
print('Comments: ', submission_dict['comments'])
| [
"operator.itemgetter",
"requests.get"
] | [((472, 503), 'requests.get', 'requests.get', (['url'], {'verify': '(False)'}), '(url, verify=False)\n', (484, 503), False, 'import requests\n'), ((750, 781), 'requests.get', 'requests.get', (['url'], {'verify': '(False)'}), '(url, verify=False)\n', (762, 781), False, 'import requests\n'), ((1157, 1179), 'operator.itemgetter', 'itemgetter', (['"""comments"""'], {}), "('comments')\n", (1167, 1179), False, 'from operator import itemgetter\n')] |
#!/usr/bin/env python
#
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import azure.functions as func
from onefuzztypes.enums import ErrorCode, TaskState
from onefuzztypes.models import Error
from onefuzztypes.requests import CanScheduleRequest
from onefuzztypes.responses import CanSchedule
from ..onefuzzlib.endpoint_authorization import call_if_agent
from ..onefuzzlib.request import not_ok, ok, parse_request
from ..onefuzzlib.tasks.main import Task
from ..onefuzzlib.workers.nodes import Node
def post(req: func.HttpRequest) -> func.HttpResponse:
request = parse_request(CanScheduleRequest, req)
if isinstance(request, Error):
return not_ok(request, context="CanScheduleRequest")
node = Node.get_by_machine_id(request.machine_id)
if not node:
return not_ok(
Error(code=ErrorCode.UNABLE_TO_FIND, errors=["unable to find node"]),
context=request.machine_id,
)
allowed = True
work_stopped = False
if not node.can_process_new_work():
allowed = False
task = Task.get_by_task_id(request.task_id)
work_stopped = isinstance(task, Error) or task.state in TaskState.shutting_down()
if work_stopped:
allowed = False
if allowed:
allowed = not isinstance(node.acquire_scale_in_protection(), Error)
return ok(CanSchedule(allowed=allowed, work_stopped=work_stopped))
def main(req: func.HttpRequest) -> func.HttpResponse:
methods = {"POST": post}
method = methods[req.method]
result = call_if_agent(req, method)
return result
| [
"onefuzztypes.models.Error",
"onefuzztypes.enums.TaskState.shutting_down",
"onefuzztypes.responses.CanSchedule"
] | [((1357, 1412), 'onefuzztypes.responses.CanSchedule', 'CanSchedule', ([], {'allowed': 'allowed', 'work_stopped': 'work_stopped'}), '(allowed=allowed, work_stopped=work_stopped)\n', (1368, 1412), False, 'from onefuzztypes.responses import CanSchedule\n'), ((838, 906), 'onefuzztypes.models.Error', 'Error', ([], {'code': 'ErrorCode.UNABLE_TO_FIND', 'errors': "['unable to find node']"}), "(code=ErrorCode.UNABLE_TO_FIND, errors=['unable to find node'])\n", (843, 906), False, 'from onefuzztypes.models import Error\n'), ((1178, 1203), 'onefuzztypes.enums.TaskState.shutting_down', 'TaskState.shutting_down', ([], {}), '()\n', (1201, 1203), False, 'from onefuzztypes.enums import ErrorCode, TaskState\n')] |
from PIL import Image
import os
if not os.path.exists("SortedCharacters"):
os.mkdir("SortedCharacters")
order="123456789abcdefghijklmnpqrstuvwxyz"
for i in range(0,len(order)):
black=0
im1=Image.open("Chars\\"+order[i]+".png")
if not os.path.exists("SortedCharacters\\"+order[i]):
os.mkdir("SortedCharacters\\"+order[i])
im1.save("SortedCharacters\\"+order[i]+"\\First.png")
pix1=im1.load()
for y in range(0,32):
for x in range(0,30):
if pix1[x,y]==(0,0,0):
black+=1
for j in range(1,601):
match=0
im2=Image.open("Characters\\"+str(j)+".png")
pix2=im2.load()
for y in range(0,32):
for x in range(0,30):
if pix1[x,y]==pix2[x,y] and pix2[x,y]==(0,0,0):
match+=1
if float(match)/float(black)>=0.95:
fp="SortedCharacters\\"+order[i]+"\\"+order[i]+"-"+str(4000+j)+".png"
im2.save(fp)
| [
"os.path.exists",
"PIL.Image.open",
"os.mkdir"
] | [((39, 73), 'os.path.exists', 'os.path.exists', (['"""SortedCharacters"""'], {}), "('SortedCharacters')\n", (53, 73), False, 'import os\n'), ((79, 107), 'os.mkdir', 'os.mkdir', (['"""SortedCharacters"""'], {}), "('SortedCharacters')\n", (87, 107), False, 'import os\n'), ((201, 242), 'PIL.Image.open', 'Image.open', (["('Chars\\\\' + order[i] + '.png')"], {}), "('Chars\\\\' + order[i] + '.png')\n", (211, 242), False, 'from PIL import Image\n'), ((250, 297), 'os.path.exists', 'os.path.exists', (["('SortedCharacters\\\\' + order[i])"], {}), "('SortedCharacters\\\\' + order[i])\n", (264, 297), False, 'import os\n'), ((305, 346), 'os.mkdir', 'os.mkdir', (["('SortedCharacters\\\\' + order[i])"], {}), "('SortedCharacters\\\\' + order[i])\n", (313, 346), False, 'import os\n')] |
#!/usr/bin/env python3
#-----------------------------------------------------------------------------
# Title : Root Class For PCIE Express
#-----------------------------------------------------------------------------
# File : CmbPcie.py
# Created : 2019-10-11
#-----------------------------------------------------------------------------
# Description:
# Root class for PCI Express Ethernet
#-----------------------------------------------------------------------------
# This file is part of the AmcCarrier Core. It is subject to
# the license terms in the LICENSE.txt file found in the top-level directory
# of this distribution and at:
# https://confluence.slac.stanford.edu/display/ppareg/LICENSE.html.
# No part of the AmcCarrierCore, including this file, may be
# copied, modified, propagated, or distributed except according to the terms
# contained in the LICENSE.txt file.
#-----------------------------------------------------------------------------
from CryoDet._MicrowaveMuxBpEthGen2 import FpgaTopLevel
import pyrogue
import rogue.hardware.axi
import rogue.protocols.srp
from pysmurf.core.roots.Common import Common
class CmbPcie(Common):
def __init__(self, *,
pcie_rssi_lane = 0,
pcie_dev_rssi = "/dev/datadev_0",
pcie_dev_data = "/dev/datadev_1",
config_file = None,
epics_prefix = "EpicsPrefix",
polling_en = True,
pv_dump_file = "",
disable_bay0 = False,
disable_bay1 = False,
enable_pwri2c = False,
txDevice = None,
configure = False,
VariableGroups = None,
server_port = 0,
**kwargs):
# TDEST 0 routed to streamr0 (SRPv3)
self._srpStream = rogue.hardware.axi.AxiStreamDma(pcie_dev_rssi,(pcie_rssi_lane*0x100 + 0),True)
# Create the SRP Engine
self._srp = rogue.protocols.srp.SrpV3()
pyrogue.streamConnectBiDir(self._srp, self._srpStream)
# Instantiate Fpga top level
# In order to be backwards compatible for now, also support
# FpgaTopLevel which doesn't have the enablePwrI2C argument.
try:
self._fpga = FpgaTopLevel( memBase = self._srp,
disableBay0 = disable_bay0,
disableBay1 = disable_bay1,
enablePwrI2C = enable_pwri2c)
except TypeError as e:
print(f"TypeError calling FpgaTopLevel: {e}")
print("This FpgaTopLevel does not support the option 'enablePwrI2C'.")
print("Please use a pyrogue zip file which is up to date.")
print("Staring the server without using the 'enablePwrI2C' option.")
self._fpga = FpgaTopLevel( memBase = self._srp,
disableBay0 = disable_bay0,
disableBay1 = disable_bay1)
# Create stream interfaces
self._ddr_streams = []
# DDR streams. We are only using the first 2 channel of each AMC daughter card, i.e.
# channels 0, 1, 4, 5.
for i in [0, 1, 4, 5]:
tmp = rogue.hardware.axi.AxiStreamDma(pcie_dev_rssi,(pcie_rssi_lane*0x100 + 0x80 + i), True)
tmp.setZeroCopyEn(False)
self._ddr_streams.append(tmp)
# Streaming interface stream
self._streaming_stream = \
rogue.hardware.axi.AxiStreamDma(pcie_dev_data,(pcie_rssi_lane*0x100 + 0xC1), True)
# Setup base class
Common.__init__(self,
config_file = config_file,
epics_prefix = epics_prefix,
polling_en = polling_en,
pv_dump_file = pv_dump_file,
txDevice = txDevice,
configure = configure,
VariableGroups = VariableGroups,
server_port = server_port,
disable_bay0 = disable_bay0,
disable_bay1 = disable_bay1,
**kwargs)
| [
"pysmurf.core.roots.Common.Common.__init__",
"pyrogue.streamConnectBiDir",
"CryoDet._MicrowaveMuxBpEthGen2.FpgaTopLevel"
] | [((2058, 2112), 'pyrogue.streamConnectBiDir', 'pyrogue.streamConnectBiDir', (['self._srp', 'self._srpStream'], {}), '(self._srp, self._srpStream)\n', (2084, 2112), False, 'import pyrogue\n'), ((3708, 4009), 'pysmurf.core.roots.Common.Common.__init__', 'Common.__init__', (['self'], {'config_file': 'config_file', 'epics_prefix': 'epics_prefix', 'polling_en': 'polling_en', 'pv_dump_file': 'pv_dump_file', 'txDevice': 'txDevice', 'configure': 'configure', 'VariableGroups': 'VariableGroups', 'server_port': 'server_port', 'disable_bay0': 'disable_bay0', 'disable_bay1': 'disable_bay1'}), '(self, config_file=config_file, epics_prefix=epics_prefix,\n polling_en=polling_en, pv_dump_file=pv_dump_file, txDevice=txDevice,\n configure=configure, VariableGroups=VariableGroups, server_port=\n server_port, disable_bay0=disable_bay0, disable_bay1=disable_bay1, **kwargs\n )\n', (3723, 4009), False, 'from pysmurf.core.roots.Common import Common\n'), ((2326, 2442), 'CryoDet._MicrowaveMuxBpEthGen2.FpgaTopLevel', 'FpgaTopLevel', ([], {'memBase': 'self._srp', 'disableBay0': 'disable_bay0', 'disableBay1': 'disable_bay1', 'enablePwrI2C': 'enable_pwri2c'}), '(memBase=self._srp, disableBay0=disable_bay0, disableBay1=\n disable_bay1, enablePwrI2C=enable_pwri2c)\n', (2338, 2442), False, 'from CryoDet._MicrowaveMuxBpEthGen2 import FpgaTopLevel\n'), ((2921, 3009), 'CryoDet._MicrowaveMuxBpEthGen2.FpgaTopLevel', 'FpgaTopLevel', ([], {'memBase': 'self._srp', 'disableBay0': 'disable_bay0', 'disableBay1': 'disable_bay1'}), '(memBase=self._srp, disableBay0=disable_bay0, disableBay1=\n disable_bay1)\n', (2933, 3009), False, 'from CryoDet._MicrowaveMuxBpEthGen2 import FpgaTopLevel\n')] |
import unittest
from pyparsing import ParseException
from media_management_scripts.support.search_parser import parse_and_execute, parse
class ParseTestCase():
def parse(self, query, expected, context={}):
self.assertEqual(parse_and_execute(query, context), expected)
class SimpleTest(unittest.TestCase, ParseTestCase):
def test_basic(self):
self.parse('1+1', 2)
self.parse('1-1', 0)
self.parse('-1-2', -3)
self.parse('3*2', 6)
self.parse('10/2', 5)
def test_whitespace(self):
self.parse(' 1 + 1 ', 2)
self.parse(' 1 + 1 ', 2)
def test_order_of_operations(self):
self.parse('1+2*3', 7)
self.parse('2*3+1', 7)
self.parse('(1+2)*3', 9)
def test_boolean(self):
self.parse('true', True)
self.parse('false', False)
self.parse('true and true', True)
self.parse('true and false', False)
self.parse('True and False', False)
self.parse('true or false', True)
self.parse('not true', False)
self.parse('not false', True)
def test_boolean_order_of_operations(self):
self.parse('true and true or false', True)
self.parse('not false and false', False)
self.parse('not false or false', True)
self.parse('1 in [1] or false', True)
self.parse('1 in [1] and false', False)
def test_comparison(self):
self.parse('1 = 1', True)
self.parse('1 != 1', False)
self.parse('1 != 2', True)
self.parse('1 > 1', False)
self.parse('2 > 1', True)
self.parse('1 < 1', False)
self.parse('1 >= 1', True)
self.parse('1 <= 1', True)
def test_in(self):
self.parse('1 in [1]', True)
self.parse('1 in [1,2]', True)
self.parse('2 in [1]', False)
def test_basic_context(self):
self.parse('a', 2, {'a': 2})
self.parse('a+1', 3, {'a': 2})
self.parse('a.b+1', 3, {'a': {'b': 2}})
def test_reuse(self):
op = parse('a+1')
self.assertEqual(2, op.exec({'a': 1}))
self.assertEqual(3, op.exec({'a': 2}))
def test_invalid(self):
with self.assertRaises(ParseException):
parse('True and')
with self.assertRaises(ParseException):
parse('1+')
def test_isNull(self):
self.parse('isNull(1)', False)
self.parse('isNull(a)', True, {'a': None})
self.parse('not isNull(a)', True, {'a': 1})
def test_all(self):
self.parse('a = 1', True, {'a': [1, 2]})
self.parse('all(a) = 1', True, {'a': [1, 1]})
self.parse('all(a) = 1', False, {'a': [1, 2]})
self.parse('all(a) != 1', True, {'a': [1, 2]})
self.parse('all(a) != 1', False, {'a': [1, 1]})
def test_string(self):
self.parse('"test"', 'test')
self.parse('test', 'test')
self.parse('"test test"', 'test test')
self.parse('"test test"', 'test test')
self.parse('"test test" = "test test"', True)
| [
"media_management_scripts.support.search_parser.parse_and_execute",
"media_management_scripts.support.search_parser.parse"
] | [((2033, 2045), 'media_management_scripts.support.search_parser.parse', 'parse', (['"""a+1"""'], {}), "('a+1')\n", (2038, 2045), False, 'from media_management_scripts.support.search_parser import parse_and_execute, parse\n'), ((238, 271), 'media_management_scripts.support.search_parser.parse_and_execute', 'parse_and_execute', (['query', 'context'], {}), '(query, context)\n', (255, 271), False, 'from media_management_scripts.support.search_parser import parse_and_execute, parse\n'), ((2229, 2246), 'media_management_scripts.support.search_parser.parse', 'parse', (['"""True and"""'], {}), "('True and')\n", (2234, 2246), False, 'from media_management_scripts.support.search_parser import parse_and_execute, parse\n'), ((2307, 2318), 'media_management_scripts.support.search_parser.parse', 'parse', (['"""1+"""'], {}), "('1+')\n", (2312, 2318), False, 'from media_management_scripts.support.search_parser import parse_and_execute, parse\n')] |
"""Completers for Python code"""
import builtins
import collections.abc as cabc
import inspect
import re
import warnings
import xonsh.lazyasd as xl
import xonsh.tools as xt
from xonsh.built_ins import XSH
from xonsh.completers.tools import (
CompleterResult,
RichCompletion,
contextual_completer,
get_filter_function,
)
from xonsh.parsers.completion_context import CompletionContext, PythonContext
@xl.lazyobject
def RE_ATTR():
return re.compile(r"([^\s\(\)]+(\.[^\s\(\)]+)*)\.(\w*)$")
@xl.lazyobject
def XONSH_EXPR_TOKENS():
return {
RichCompletion("and", append_space=True),
"else",
RichCompletion("for", append_space=True),
RichCompletion("if", append_space=True),
RichCompletion("in", append_space=True),
RichCompletion("is", append_space=True),
RichCompletion("lambda", append_space=True),
RichCompletion("not", append_space=True),
RichCompletion("or", append_space=True),
"+",
"-",
"/",
"//",
"%",
"**",
"|",
"&",
"~",
"^",
">>",
"<<",
"<",
"<=",
">",
">=",
"==",
"!=",
RichCompletion(",", append_space=True),
"?",
"??",
"$(",
"${",
"$[",
"...",
"![",
"!(",
"@(",
"@$(",
"@",
}
@xl.lazyobject
def XONSH_STMT_TOKENS():
return {
RichCompletion("as", append_space=True),
RichCompletion("assert", append_space=True),
"break",
RichCompletion("class", append_space=True),
"continue",
RichCompletion("def", append_space=True),
RichCompletion("del", append_space=True),
RichCompletion("elif", append_space=True),
RichCompletion("except", append_space=True),
"finally:",
RichCompletion("from", append_space=True),
RichCompletion("global", append_space=True),
RichCompletion("import", append_space=True),
RichCompletion("nonlocal", append_space=True),
"pass",
RichCompletion("raise", append_space=True),
RichCompletion("return", append_space=True),
"try:",
RichCompletion("while", append_space=True),
RichCompletion("with", append_space=True),
RichCompletion("yield", append_space=True),
"-",
"/",
"//",
"%",
"**",
"|",
"&",
"~",
"^",
">>",
"<<",
"<",
"<=",
"->",
"=",
"+=",
"-=",
"*=",
"/=",
"%=",
"**=",
">>=",
"<<=",
"&=",
"^=",
"|=",
"//=",
";",
":",
"..",
}
@xl.lazyobject
def XONSH_TOKENS():
return set(XONSH_EXPR_TOKENS) | set(XONSH_STMT_TOKENS)
@contextual_completer
def complete_python(context: CompletionContext) -> CompleterResult:
"""
Completes based on the contents of the current Python environment,
the Python built-ins, and xonsh operators.
"""
# If there are no matches, split on common delimiters and try again.
if context.python is None:
return None
if context.command and context.command.arg_index != 0:
# this can be a command (i.e. not a subexpression)
first = context.command.args[0].value
ctx = context.python.ctx or {}
if first in XSH.commands_cache and first not in ctx: # type: ignore
# this is a known command, so it won't be python code
return None
line = context.python.multiline_code
prefix = (line.rsplit(maxsplit=1) or [""])[-1]
rtn = _complete_python(prefix, context.python)
if not rtn:
prefix = (
re.split(r"\(|=|{|\[|,", prefix)[-1]
if not prefix.startswith(",")
else prefix
)
rtn = _complete_python(prefix, context.python)
return rtn, len(prefix)
def _complete_python(prefix, context: PythonContext):
"""
Completes based on the contents of the current Python environment,
the Python built-ins, and xonsh operators.
"""
line = context.multiline_code
end = context.cursor_index
ctx = context.ctx
filt = get_filter_function()
rtn = set()
if ctx is not None:
if "." in prefix:
rtn |= attr_complete(prefix, ctx, filt)
args = python_signature_complete(prefix, line, end, ctx, filt)
rtn |= args
rtn |= {s for s in ctx if filt(s, prefix)}
else:
args = ()
if len(args) == 0:
# not in a function call, so we can add non-expression tokens
rtn |= {s for s in XONSH_TOKENS if filt(s, prefix)}
else:
rtn |= {s for s in XONSH_EXPR_TOKENS if filt(s, prefix)}
rtn |= {s for s in dir(builtins) if filt(s, prefix)}
return rtn
def _turn_off_warning(func):
"""Decorator to turn off warning temporarily."""
def wrapper(*args, **kwargs):
warnings.filterwarnings("ignore")
r = func(*args, **kwargs)
warnings.filterwarnings("once", category=DeprecationWarning)
return r
return wrapper
def _safe_eval(expr, ctx):
"""Safely tries to evaluate an expression. If this fails, it will return
a (None, None) tuple.
"""
_ctx = None
xonsh_safe_eval = XSH.execer.eval
try:
val = xonsh_safe_eval(expr, ctx, ctx, transform=False)
_ctx = ctx
except Exception:
try:
val = xonsh_safe_eval(expr, builtins.__dict__, transform=False)
_ctx = builtins.__dict__
except Exception:
val = _ctx = None
return val, _ctx
@_turn_off_warning
def attr_complete(prefix, ctx, filter_func):
"""Complete attributes of an object."""
attrs = set()
m = RE_ATTR.match(prefix)
if m is None:
return attrs
expr, attr = m.group(1, 3)
expr = xt.subexpr_from_unbalanced(expr, "(", ")")
expr = xt.subexpr_from_unbalanced(expr, "[", "]")
expr = xt.subexpr_from_unbalanced(expr, "{", "}")
val, _ctx = _safe_eval(expr, ctx)
if val is None and _ctx is None:
return attrs
if len(attr) == 0:
opts = [o for o in dir(val) if not o.startswith("_")]
else:
opts = [o for o in dir(val) if filter_func(o, attr)]
prelen = len(prefix)
for opt in opts:
# check whether these options actually work (e.g., disallow 7.imag)
_expr = f"{expr}.{opt}"
_val_, _ctx_ = _safe_eval(_expr, _ctx)
if _val_ is None and _ctx_ is None:
continue
a = getattr(val, opt)
if XSH.env["COMPLETIONS_BRACKETS"]:
if callable(a):
rpl = opt + "("
elif isinstance(a, (cabc.Sequence, cabc.Mapping)):
rpl = opt + "["
else:
rpl = opt
else:
rpl = opt
# note that prefix[:prelen-len(attr)] != prefix[:-len(attr)]
# when len(attr) == 0.
comp = prefix[: prelen - len(attr)] + rpl
attrs.add(comp)
return attrs
@_turn_off_warning
def python_signature_complete(prefix, line, end, ctx, filter_func):
"""Completes a python function (or other callable) call by completing
argument and keyword argument names.
"""
front = line[:end]
if xt.is_balanced(front, "(", ")"):
return set()
funcname = xt.subexpr_before_unbalanced(front, "(", ")")
val, _ctx = _safe_eval(funcname, ctx)
if val is None:
return set()
try:
sig = inspect.signature(val)
except ValueError:
return set()
args = {p + "=" for p in sig.parameters if filter_func(p, prefix)}
return args
| [
"re.split",
"re.compile",
"xonsh.tools.subexpr_from_unbalanced",
"inspect.signature",
"xonsh.tools.subexpr_before_unbalanced",
"xonsh.tools.is_balanced",
"xonsh.completers.tools.RichCompletion",
"xonsh.completers.tools.get_filter_function",
"warnings.filterwarnings"
] | [((458, 516), 're.compile', 're.compile', (['"""([^\\\\s\\\\(\\\\)]+(\\\\.[^\\\\s\\\\(\\\\)]+)*)\\\\.(\\\\w*)$"""'], {}), "('([^\\\\s\\\\(\\\\)]+(\\\\.[^\\\\s\\\\(\\\\)]+)*)\\\\.(\\\\w*)$')\n", (468, 516), False, 'import re\n'), ((4314, 4335), 'xonsh.completers.tools.get_filter_function', 'get_filter_function', ([], {}), '()\n', (4333, 4335), False, 'from xonsh.completers.tools import CompleterResult, RichCompletion, contextual_completer, get_filter_function\n'), ((5974, 6016), 'xonsh.tools.subexpr_from_unbalanced', 'xt.subexpr_from_unbalanced', (['expr', '"""("""', '""")"""'], {}), "(expr, '(', ')')\n", (6000, 6016), True, 'import xonsh.tools as xt\n'), ((6028, 6070), 'xonsh.tools.subexpr_from_unbalanced', 'xt.subexpr_from_unbalanced', (['expr', '"""["""', '"""]"""'], {}), "(expr, '[', ']')\n", (6054, 6070), True, 'import xonsh.tools as xt\n'), ((6082, 6124), 'xonsh.tools.subexpr_from_unbalanced', 'xt.subexpr_from_unbalanced', (['expr', '"""{"""', '"""}"""'], {}), "(expr, '{', '}')\n", (6108, 6124), True, 'import xonsh.tools as xt\n'), ((7385, 7416), 'xonsh.tools.is_balanced', 'xt.is_balanced', (['front', '"""("""', '""")"""'], {}), "(front, '(', ')')\n", (7399, 7416), True, 'import xonsh.tools as xt\n'), ((7454, 7499), 'xonsh.tools.subexpr_before_unbalanced', 'xt.subexpr_before_unbalanced', (['front', '"""("""', '""")"""'], {}), "(front, '(', ')')\n", (7482, 7499), True, 'import xonsh.tools as xt\n'), ((572, 612), 'xonsh.completers.tools.RichCompletion', 'RichCompletion', (['"""and"""'], {'append_space': '(True)'}), "('and', append_space=True)\n", (586, 612), False, 'from xonsh.completers.tools import CompleterResult, RichCompletion, contextual_completer, get_filter_function\n'), ((638, 678), 'xonsh.completers.tools.RichCompletion', 'RichCompletion', (['"""for"""'], {'append_space': '(True)'}), "('for', append_space=True)\n", (652, 678), False, 'from xonsh.completers.tools import CompleterResult, RichCompletion, contextual_completer, get_filter_function\n'), ((688, 727), 'xonsh.completers.tools.RichCompletion', 'RichCompletion', (['"""if"""'], {'append_space': '(True)'}), "('if', append_space=True)\n", (702, 727), False, 'from xonsh.completers.tools import CompleterResult, RichCompletion, contextual_completer, get_filter_function\n'), ((737, 776), 'xonsh.completers.tools.RichCompletion', 'RichCompletion', (['"""in"""'], {'append_space': '(True)'}), "('in', append_space=True)\n", (751, 776), False, 'from xonsh.completers.tools import CompleterResult, RichCompletion, contextual_completer, get_filter_function\n'), ((786, 825), 'xonsh.completers.tools.RichCompletion', 'RichCompletion', (['"""is"""'], {'append_space': '(True)'}), "('is', append_space=True)\n", (800, 825), False, 'from xonsh.completers.tools import CompleterResult, RichCompletion, contextual_completer, get_filter_function\n'), ((835, 878), 'xonsh.completers.tools.RichCompletion', 'RichCompletion', (['"""lambda"""'], {'append_space': '(True)'}), "('lambda', append_space=True)\n", (849, 878), False, 'from xonsh.completers.tools import CompleterResult, RichCompletion, contextual_completer, get_filter_function\n'), ((888, 928), 'xonsh.completers.tools.RichCompletion', 'RichCompletion', (['"""not"""'], {'append_space': '(True)'}), "('not', append_space=True)\n", (902, 928), False, 'from xonsh.completers.tools import CompleterResult, RichCompletion, contextual_completer, get_filter_function\n'), ((938, 977), 'xonsh.completers.tools.RichCompletion', 'RichCompletion', (['"""or"""'], {'append_space': '(True)'}), "('or', append_space=True)\n", (952, 977), False, 'from xonsh.completers.tools import CompleterResult, RichCompletion, contextual_completer, get_filter_function\n'), ((1229, 1267), 'xonsh.completers.tools.RichCompletion', 'RichCompletion', (['""","""'], {'append_space': '(True)'}), "(',', append_space=True)\n", (1243, 1267), False, 'from xonsh.completers.tools import CompleterResult, RichCompletion, contextual_completer, get_filter_function\n'), ((1492, 1531), 'xonsh.completers.tools.RichCompletion', 'RichCompletion', (['"""as"""'], {'append_space': '(True)'}), "('as', append_space=True)\n", (1506, 1531), False, 'from xonsh.completers.tools import CompleterResult, RichCompletion, contextual_completer, get_filter_function\n'), ((1541, 1584), 'xonsh.completers.tools.RichCompletion', 'RichCompletion', (['"""assert"""'], {'append_space': '(True)'}), "('assert', append_space=True)\n", (1555, 1584), False, 'from xonsh.completers.tools import CompleterResult, RichCompletion, contextual_completer, get_filter_function\n'), ((1611, 1653), 'xonsh.completers.tools.RichCompletion', 'RichCompletion', (['"""class"""'], {'append_space': '(True)'}), "('class', append_space=True)\n", (1625, 1653), False, 'from xonsh.completers.tools import CompleterResult, RichCompletion, contextual_completer, get_filter_function\n'), ((1683, 1723), 'xonsh.completers.tools.RichCompletion', 'RichCompletion', (['"""def"""'], {'append_space': '(True)'}), "('def', append_space=True)\n", (1697, 1723), False, 'from xonsh.completers.tools import CompleterResult, RichCompletion, contextual_completer, get_filter_function\n'), ((1733, 1773), 'xonsh.completers.tools.RichCompletion', 'RichCompletion', (['"""del"""'], {'append_space': '(True)'}), "('del', append_space=True)\n", (1747, 1773), False, 'from xonsh.completers.tools import CompleterResult, RichCompletion, contextual_completer, get_filter_function\n'), ((1783, 1824), 'xonsh.completers.tools.RichCompletion', 'RichCompletion', (['"""elif"""'], {'append_space': '(True)'}), "('elif', append_space=True)\n", (1797, 1824), False, 'from xonsh.completers.tools import CompleterResult, RichCompletion, contextual_completer, get_filter_function\n'), ((1834, 1877), 'xonsh.completers.tools.RichCompletion', 'RichCompletion', (['"""except"""'], {'append_space': '(True)'}), "('except', append_space=True)\n", (1848, 1877), False, 'from xonsh.completers.tools import CompleterResult, RichCompletion, contextual_completer, get_filter_function\n'), ((1907, 1948), 'xonsh.completers.tools.RichCompletion', 'RichCompletion', (['"""from"""'], {'append_space': '(True)'}), "('from', append_space=True)\n", (1921, 1948), False, 'from xonsh.completers.tools import CompleterResult, RichCompletion, contextual_completer, get_filter_function\n'), ((1958, 2001), 'xonsh.completers.tools.RichCompletion', 'RichCompletion', (['"""global"""'], {'append_space': '(True)'}), "('global', append_space=True)\n", (1972, 2001), False, 'from xonsh.completers.tools import CompleterResult, RichCompletion, contextual_completer, get_filter_function\n'), ((2011, 2054), 'xonsh.completers.tools.RichCompletion', 'RichCompletion', (['"""import"""'], {'append_space': '(True)'}), "('import', append_space=True)\n", (2025, 2054), False, 'from xonsh.completers.tools import CompleterResult, RichCompletion, contextual_completer, get_filter_function\n'), ((2064, 2109), 'xonsh.completers.tools.RichCompletion', 'RichCompletion', (['"""nonlocal"""'], {'append_space': '(True)'}), "('nonlocal', append_space=True)\n", (2078, 2109), False, 'from xonsh.completers.tools import CompleterResult, RichCompletion, contextual_completer, get_filter_function\n'), ((2135, 2177), 'xonsh.completers.tools.RichCompletion', 'RichCompletion', (['"""raise"""'], {'append_space': '(True)'}), "('raise', append_space=True)\n", (2149, 2177), False, 'from xonsh.completers.tools import CompleterResult, RichCompletion, contextual_completer, get_filter_function\n'), ((2187, 2230), 'xonsh.completers.tools.RichCompletion', 'RichCompletion', (['"""return"""'], {'append_space': '(True)'}), "('return', append_space=True)\n", (2201, 2230), False, 'from xonsh.completers.tools import CompleterResult, RichCompletion, contextual_completer, get_filter_function\n'), ((2256, 2298), 'xonsh.completers.tools.RichCompletion', 'RichCompletion', (['"""while"""'], {'append_space': '(True)'}), "('while', append_space=True)\n", (2270, 2298), False, 'from xonsh.completers.tools import CompleterResult, RichCompletion, contextual_completer, get_filter_function\n'), ((2308, 2349), 'xonsh.completers.tools.RichCompletion', 'RichCompletion', (['"""with"""'], {'append_space': '(True)'}), "('with', append_space=True)\n", (2322, 2349), False, 'from xonsh.completers.tools import CompleterResult, RichCompletion, contextual_completer, get_filter_function\n'), ((2359, 2401), 'xonsh.completers.tools.RichCompletion', 'RichCompletion', (['"""yield"""'], {'append_space': '(True)'}), "('yield', append_space=True)\n", (2373, 2401), False, 'from xonsh.completers.tools import CompleterResult, RichCompletion, contextual_completer, get_filter_function\n'), ((5051, 5084), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (5074, 5084), False, 'import warnings\n'), ((5127, 5187), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""once"""'], {'category': 'DeprecationWarning'}), "('once', category=DeprecationWarning)\n", (5150, 5187), False, 'import warnings\n'), ((7606, 7628), 'inspect.signature', 'inspect.signature', (['val'], {}), '(val)\n', (7623, 7628), False, 'import inspect\n'), ((3830, 3863), 're.split', 're.split', (['"""\\\\(|=|{|\\\\[|,"""', 'prefix'], {}), "('\\\\(|=|{|\\\\[|,', prefix)\n", (3838, 3863), False, 'import re\n')] |
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2012-2016 GEM Foundation
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
"""
Module exports :class:`ZhaoEtAl2006Asc`, :class:`ZhaoEtAl2006SInter`,
:class:`ZhaoEtAl2006SSlab`, :class:`ZhaoEtAl2006SInterNSHMP2008` and
:class:`ZhaoEtAl2006SSlabNSHMP2014`
"""
from __future__ import division
import numpy as np
# standard acceleration of gravity in m/s**2
from scipy.constants import g
import copy
from openquake.hazardlib.gsim.base import GMPE, CoeffsTable
from openquake.hazardlib import const
from openquake.hazardlib.imt import PGA, PGV, SA
class ZhaoEtAl2006Asc(GMPE):
"""
Implements GMPE developed by <NAME> et al. and published as
"Attenuation Relations of Strong Ground Motion in Japan Using Site
Classification Based on Predominant Period" (2006, Bulletin of the
Seismological Society of America, Volume 96, No. 3, pages 898-913).
This class implements the equations for 'Active Shallow Crust'
(that's why the class name ends with 'Asc').
"""
#: Supported tectonic region type is active shallow crust, this means
#: that factors SI, SS and SSL are assumed 0 in equation 1, p. 901.
DEFINED_FOR_TECTONIC_REGION_TYPE = const.TRT.ACTIVE_SHALLOW_CRUST
#: Supported intensity measure types are spectral acceleration,
#: and peak ground acceleration, see paragraph 'Development of Base Model'
#: p. 901.
DEFINED_FOR_INTENSITY_MEASURE_TYPES = set([
PGA,
SA
])
#: Supported intensity measure component is geometric mean
#: of two horizontal components :
#: attr:`~openquake.hazardlib.const.IMC.AVERAGE_HORIZONTAL`, see paragraph
#: 'Development of Base Model', p. 901.
DEFINED_FOR_INTENSITY_MEASURE_COMPONENT = const.IMC.AVERAGE_HORIZONTAL
#: Supported standard deviation types are inter-event, intra-event
#: and total, see equation 3, p. 902.
DEFINED_FOR_STANDARD_DEVIATION_TYPES = set([
const.StdDev.TOTAL,
const.StdDev.INTER_EVENT,
const.StdDev.INTRA_EVENT
])
#: Required site parameters is Vs30.
#: See table 2, p. 901.
REQUIRES_SITES_PARAMETERS = set(('vs30', ))
#: Required rupture parameters are magnitude, rake, and focal depth.
#: See paragraph 'Development of Base Model', p. 901.
REQUIRES_RUPTURE_PARAMETERS = set(('mag', 'rake', 'hypo_depth'))
#: Required distance measure is Rrup.
#: See paragraph 'Development of Base Model', p. 902.
REQUIRES_DISTANCES = set(('rrup', ))
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# extracting dictionary of coefficients specific to required
# intensity measure type.
C = self.COEFFS_ASC[imt]
# mean value as given by equation 1, p. 901, without considering the
# interface and intraslab terms (that is SI, SS, SSL = 0) and the
# inter and intra event terms, plus the magnitude-squared term
# correction factor (equation 5 p. 909).
mean = self._compute_magnitude_term(C, rup.mag) +\
self._compute_distance_term(C, rup.mag, dists.rrup) +\
self._compute_focal_depth_term(C, rup.hypo_depth) +\
self._compute_faulting_style_term(C, rup.rake) +\
self._compute_site_class_term(C, sites.vs30) +\
self._compute_magnitude_squared_term(P=0.0, M=6.3, Q=C['QC'],
W=C['WC'], mag=rup.mag)
# convert from cm/s**2 to g
mean = np.log(np.exp(mean) * 1e-2 / g)
stddevs = self._get_stddevs(C['sigma'], C['tauC'], stddev_types,
num_sites=len(sites.vs30))
return mean, stddevs
def _get_stddevs(self, sigma, tau, stddev_types, num_sites):
"""
Return standard deviations as defined in equation 3 p. 902.
"""
stddevs = []
for stddev_type in stddev_types:
assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
if stddev_type == const.StdDev.TOTAL:
sigma_t = np.sqrt(sigma ** 2 + tau ** 2)
stddevs.append(sigma_t + np.zeros(num_sites))
elif stddev_type == const.StdDev.INTRA_EVENT:
stddevs.append(sigma + np.zeros(num_sites))
elif stddev_type == const.StdDev.INTER_EVENT:
stddevs.append(tau + np.zeros(num_sites))
return stddevs
def _compute_magnitude_term(self, C, mag):
"""
Compute first term in equation 1, p. 901.
"""
return C['a'] * mag
def _compute_distance_term(self, C, mag, rrup):
"""
Compute second and third terms in equation 1, p. 901.
"""
term1 = C['b'] * rrup
term2 = - np.log(rrup + C['c'] * np.exp(C['d'] * mag))
return term1 + term2
def _compute_focal_depth_term(self, C, hypo_depth):
"""
Compute fourth term in equation 1, p. 901.
"""
# p. 901. "(i.e, depth is capped at 125 km)".
focal_depth = hypo_depth
if focal_depth > 125.0:
focal_depth = 125.0
# p. 902. "We used the value of 15 km for the
# depth coefficient hc ...".
hc = 15.0
# p. 901. "When h is larger than hc, the depth terms takes
# effect ...". The next sentence specifies h>=hc.
return float(focal_depth >= hc) * C['e'] * (focal_depth - hc)
def _compute_faulting_style_term(self, C, rake):
"""
Compute fifth term in equation 1, p. 901.
"""
# p. 900. "The differentiation in focal mechanism was
# based on a rake angle criterion, with a rake of +/- 45
# as demarcation between dip-slip and strike-slip."
return float(rake > 45.0 and rake < 135.0) * C['FR']
def _compute_site_class_term(self, C, vs30):
"""
Compute nine-th term in equation 1, p. 901.
"""
# map vs30 value to site class, see table 2, p. 901.
site_term = np.zeros(len(vs30))
# hard rock
site_term[vs30 > 1100.0] = C['CH']
# rock
site_term[(vs30 > 600) & (vs30 <= 1100)] = C['C1']
# hard soil
site_term[(vs30 > 300) & (vs30 <= 600)] = C['C2']
# medium soil
site_term[(vs30 > 200) & (vs30 <= 300)] = C['C3']
# soft soil
site_term[vs30 <= 200] = C['C4']
return site_term
def _compute_magnitude_squared_term(self, P, M, Q, W, mag):
"""
Compute magnitude squared term, equation 5, p. 909.
"""
return P * (mag - M) + Q * (mag - M) ** 2 + W
#: Coefficient table obtained by joining table 4 (except columns for
#: SI, SS, SSL), table 5 (both at p. 903) and table 6 (only columns for
#: QC WC TauC), p. 907.
COEFFS_ASC = CoeffsTable(sa_damping=5, table="""\
IMT a b c d e FR CH C1 C2 C3 C4 sigma QC WC tauC
pga 1.101 -0.00564 0.0055 1.080 0.01412 0.251 0.293 1.111 1.344 1.355 1.420 0.604 0.0 0.0 0.303
0.05 1.076 -0.00671 0.0075 1.060 0.01463 0.251 0.939 1.684 1.793 1.747 1.814 0.640 0.0 0.0 0.326
0.10 1.118 -0.00787 0.0090 1.083 0.01423 0.240 1.499 2.061 2.135 2.031 2.082 0.694 0.0 0.0 0.342
0.15 1.134 -0.00722 0.0100 1.053 0.01509 0.251 1.462 1.916 2.168 2.052 2.113 0.702 0.0 0.0 0.331
0.20 1.147 -0.00659 0.0120 1.014 0.01462 0.260 1.280 1.669 2.085 2.001 2.030 0.692 0.0 0.0 0.312
0.25 1.149 -0.00590 0.0140 0.966 0.01459 0.269 1.121 1.468 1.942 1.941 1.937 0.682 0.0 0.0 0.298
0.30 1.163 -0.00520 0.0150 0.934 0.01458 0.259 0.852 1.172 1.683 1.808 1.770 0.670 0.0 0.0 0.300
0.40 1.200 -0.00422 0.0100 0.959 0.01257 0.248 0.365 0.655 1.127 1.482 1.397 0.659 0.0 0.0 0.346
0.50 1.250 -0.00338 0.0060 1.008 0.01114 0.247 -0.207 0.071 0.515 0.934 0.955 0.653 -0.0126 0.0116 0.338
0.60 1.293 -0.00282 0.0030 1.088 0.01019 0.233 -0.705 -0.429 -0.003 0.394 0.559 0.653 -0.0329 0.0202 0.349
0.70 1.336 -0.00258 0.0025 1.084 0.00979 0.220 -1.144 -0.866 -0.449 -0.111 0.188 0.652 -0.0501 0.0274 0.351
0.80 1.386 -0.00242 0.0022 1.088 0.00944 0.232 -1.609 -1.325 -0.928 -0.620 -0.246 0.647 -0.0650 0.0336 0.356
0.90 1.433 -0.00232 0.0020 1.109 0.00972 0.220 -2.023 -1.732 -1.349 -1.066 -0.643 0.653 -0.0781 0.0391 0.348
1.00 1.479 -0.00220 0.0020 1.115 0.01005 0.211 -2.451 -2.152 -1.776 -1.523 -1.084 0.657 -0.0899 0.0440 0.338
1.25 1.551 -0.00207 0.0020 1.083 0.01003 0.251 -3.243 -2.923 -2.542 -2.327 -1.936 0.660 -0.1148 0.0545 0.313
1.50 1.621 -0.00224 0.0020 1.091 0.00928 0.248 -3.888 -3.548 -3.169 -2.979 -2.661 0.664 -0.1351 0.0630 0.306
2.00 1.694 -0.00201 0.0025 1.055 0.00833 0.263 -4.783 -4.410 -4.039 -3.871 -3.640 0.669 -0.1672 0.0764 0.283
2.50 1.748 -0.00187 0.0028 1.052 0.00776 0.262 -5.444 -5.049 -4.698 -4.496 -4.341 0.671 -0.1921 0.0869 0.287
3.00 1.759 -0.00147 0.0032 1.025 0.00644 0.307 -5.839 -5.431 -5.089 -4.893 -4.758 0.667 -0.2124 0.0954 0.278
4.00 1.826 -0.00195 0.0040 1.044 0.00590 0.353 -6.598 -6.181 -5.882 -5.698 -5.588 0.647 -0.2445 0.1088 0.273
5.00 1.825 -0.00237 0.0050 1.065 0.00510 0.248 -6.752 -6.347 -6.051 -5.873 -5.798 0.643 -0.2694 0.1193 0.275
""")
class ZhaoEtAl2006SInter(ZhaoEtAl2006Asc):
"""
Implements GMPE developed by <NAME> et al and published as
"Attenuation Relations of Strong Ground Motion in Japan Using Site
Classification Based on Predominant Period" (2006, Bulletin of the
Seismological Society of America, Volume 96, No. 3, pages
898-913). This class implements the equations for 'Subduction
Interface' (that's why the class name ends with 'SInter'). This
class extends the
:class:`openquake.hazardlib.gsim.zhao_2006.ZhaoEtAl2006Asc`
because the equation for subduction interface is obtained from the
equation for active shallow crust, by removing the faulting style
term and adding a subduction interface term.
"""
#: Supported tectonic region type is subduction interface, this means
#: that factors FR, SS and SSL are assumed 0 in equation 1, p. 901.
DEFINED_FOR_TECTONIC_REGION_TYPE = const.TRT.SUBDUCTION_INTERFACE
#: Required rupture parameters are magnitude and focal depth.
REQUIRES_RUPTURE_PARAMETERS = set(('mag', 'hypo_depth'))
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# extracting dictionary of coefficients specific to required
# intensity measure type.
C = self.COEFFS_ASC[imt]
C_SINTER = self.COEFFS_SINTER[imt]
# mean value as given by equation 1, p. 901, without considering the
# faulting style and intraslab terms (that is FR, SS, SSL = 0) and the
# inter and intra event terms, plus the magnitude-squared term
# correction factor (equation 5 p. 909)
mean = self._compute_magnitude_term(C, rup.mag) +\
self._compute_distance_term(C, rup.mag, dists.rrup) +\
self._compute_focal_depth_term(C, rup.hypo_depth) +\
self._compute_site_class_term(C, sites.vs30) + \
self._compute_magnitude_squared_term(P=0.0, M=6.3,
Q=C_SINTER['QI'],
W=C_SINTER['WI'],
mag=rup.mag) +\
C_SINTER['SI']
# convert from cm/s**2 to g
mean = np.log(np.exp(mean) * 1e-2 / g)
stddevs = self._get_stddevs(C['sigma'], C_SINTER['tauI'], stddev_types,
num_sites=len(sites.vs30))
return mean, stddevs
#: Coefficient table containing subduction interface coefficients,
#: taken from table 4, p. 903 (only column SI), and table 6, p. 907
#: (only columns QI, WI, TauI)
COEFFS_SINTER = CoeffsTable(sa_damping=5, table="""\
IMT SI QI WI tauI
pga 0.000 0.0 0.0 0.308
0.05 0.000 0.0 0.0 0.343
0.10 0.000 0.0 0.0 0.403
0.15 0.000 -0.0138 0.0286 0.367
0.20 0.000 -0.0256 0.0352 0.328
0.25 0.000 -0.0348 0.0403 0.289
0.30 0.000 -0.0423 0.0445 0.280
0.40 -0.041 -0.0541 0.0511 0.271
0.50 -0.053 -0.0632 0.0562 0.277
0.60 -0.103 -0.0707 0.0604 0.296
0.70 -0.146 -0.0771 0.0639 0.313
0.80 -0.164 -0.0825 0.0670 0.329
0.90 -0.206 -0.0874 0.0697 0.324
1.00 -0.239 -0.0917 0.0721 0.328
1.25 -0.256 -0.1009 0.0772 0.339
1.50 -0.306 -0.1083 0.0814 0.352
2.00 -0.321 -0.1202 0.0880 0.360
2.50 -0.337 -0.1293 0.0931 0.356
3.00 -0.331 -0.1368 0.0972 0.338
4.00 -0.390 -0.1486 0.1038 0.307
5.00 -0.498 -0.1578 0.1090 0.272
""")
class ZhaoEtAl2006SSlab(ZhaoEtAl2006Asc):
"""
Implements GMPE developed by <NAME> et al and published as
"Attenuation Relations of Strong Ground Motion in Japan Using Site
Classification Based on Predominant Period" (2006, Bulletin of the
Seismological Society of America, Volume 96, No. 3, pages
898-913). This class implements the equations for 'Subduction
Slab'. (that's why the class name ends with 'SSlab'). This class
extends the
:class:`openquake.hazardlib.gsim.zhao_2006.ZhaoEtAl2006Asc`
because the equation for subduction slab is obtained from the
equation for active shallow crust, by removing the faulting style
term and adding subduction slab terms.
"""
#: Supported tectonic region type is subduction interface, this means
#: that factors FR, SS and SSL are assumed 0 in equation 1, p. 901.
DEFINED_FOR_TECTONIC_REGION_TYPE = const.TRT.SUBDUCTION_INTRASLAB
#: Required rupture parameters are magnitude and focal depth.
REQUIRES_RUPTURE_PARAMETERS = set(('mag', 'hypo_depth'))
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# extracting dictionary of coefficients specific to required
# intensity measure type.
C = self.COEFFS_ASC[imt]
C_SSLAB = self.COEFFS_SSLAB[imt]
# to avoid singularity at 0.0 (in the calculation of the
# slab correction term), replace 0 values with 0.1
d = dists.rrup
d[d == 0.0] = 0.1
# mean value as given by equation 1, p. 901, without considering the
# faulting style and intraslab terms (that is FR, SS, SSL = 0) and the
# inter and intra event terms, plus the magnitude-squared term
# correction factor (equation 5 p. 909)
mean = self._compute_magnitude_term(C, rup.mag) +\
self._compute_distance_term(C, rup.mag, d) +\
self._compute_focal_depth_term(C, rup.hypo_depth) +\
self._compute_site_class_term(C, sites.vs30) +\
self._compute_magnitude_squared_term(P=C_SSLAB['PS'], M=6.5,
Q=C_SSLAB['QS'],
W=C_SSLAB['WS'],
mag=rup.mag) +\
C_SSLAB['SS'] + self._compute_slab_correction_term(C_SSLAB, d)
# convert from cm/s**2 to g
mean = np.log(np.exp(mean) * 1e-2 / g)
stddevs = self._get_stddevs(C['sigma'], C_SSLAB['tauS'], stddev_types,
num_sites=len(sites.vs30))
return mean, stddevs
def _compute_slab_correction_term(self, C, rrup):
"""
Compute path modification term for slab events, that is
the 8-th term in equation 1, p. 901.
"""
slab_term = C['SSL'] * np.log(rrup)
return slab_term
#: Coefficient table containing subduction slab coefficients taken from
#: table 4, p. 903 (only columns for SS and SSL), and table 6, p. 907
#: (only columns for PS, QS, WS, TauS)
COEFFS_SSLAB = CoeffsTable(sa_damping=5, table="""\
IMT SS SSL PS QS WS tauS
pga 2.607 -0.528 0.1392 0.1584 -0.0529 0.321
0.05 2.764 -0.551 0.1636 0.1932 -0.0841 0.378
0.10 2.156 -0.420 0.1690 0.2057 -0.0877 0.420
0.15 2.161 -0.431 0.1669 0.1984 -0.0773 0.372
0.20 1.901 -0.372 0.1631 0.1856 -0.0644 0.324
0.25 1.814 -0.360 0.1588 0.1714 -0.0515 0.294
0.30 2.181 -0.450 0.1544 0.1573 -0.0395 0.284
0.40 2.432 -0.506 0.1460 0.1309 -0.0183 0.278
0.50 2.629 -0.554 0.1381 0.1078 -0.0008 0.272
0.60 2.702 -0.575 0.1307 0.0878 0.0136 0.285
0.70 2.654 -0.572 0.1239 0.0705 0.0254 0.290
0.80 2.480 -0.540 0.1176 0.0556 0.0352 0.299
0.90 2.332 -0.522 0.1116 0.0426 0.0432 0.289
1.00 2.233 -0.509 0.1060 0.0314 0.0498 0.286
1.25 2.029 -0.469 0.0933 0.0093 0.0612 0.277
1.50 1.589 -0.379 0.0821 -0.0062 0.0674 0.282
2.00 0.966 -0.248 0.0628 -0.0235 0.0692 0.300
2.50 0.789 -0.221 0.0465 -0.0287 0.0622 0.292
3.00 1.037 -0.263 0.0322 -0.0261 0.0496 0.274
4.00 0.561 -0.169 0.0083 -0.0065 0.0150 0.281
5.00 0.225 -0.120 -0.0117 0.0246 -0.0268 0.296
""")
class ZhaoEtAl2006SInterNSHMP2008(ZhaoEtAl2006SInter):
"""
Extend :class:`ZhaoEtAl2006SInter` and fix hypocentral depth at 20 km
as defined the by National Seismic Hazard Mapping Project for the 2008 US
hazard model.
The calculation of the total standard deviation is done considering the
inter-event standard deviation as defined in table 5, page 903 of Zhao's
paper.
The class implement the equation as coded in ``subroutine zhao`` in
``hazSUBXnga.f`` Fotran code available at:
http://earthquake.usgs.gov/hazards/products/conterminous/2008/software/
"""
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
Call super class method with hypocentral depth fixed at 20 km
"""
# create new rupture context to avoid changing the original one
new_rup = copy.deepcopy(rup)
new_rup.hypo_depth = 20.
mean, stddevs = super(ZhaoEtAl2006SInterNSHMP2008, self). \
get_mean_and_stddevs(sites, new_rup, dists, imt, stddev_types)
return mean, stddevs
COEFFS_SINTER = CoeffsTable(sa_damping=5, table="""\
IMT SI QI WI tauI
pga 0.000 0.0 0.0 0.3976
0.05 0.000 0.0 0.0 0.4437
0.10 0.000 0.0 0.0 0.4903
0.15 0.000 -0.0138 0.0286 0.4603
0.20 0.000 -0.0256 0.0352 0.4233
0.25 0.000 -0.0348 0.0403 0.3908
0.30 0.000 -0.0423 0.0445 0.3790
0.40 -0.041 -0.0541 0.0511 0.3897
0.50 -0.053 -0.0632 0.0562 0.3890
0.60 -0.103 -0.0707 0.0604 0.4014
0.70 -0.146 -0.0771 0.0639 0.4079
0.80 -0.164 -0.0825 0.0670 0.4183
0.90 -0.206 -0.0874 0.0697 0.4106
1.00 -0.239 -0.0917 0.0721 0.4101
1.25 -0.256 -0.1009 0.0772 0.4021
1.50 -0.306 -0.1083 0.0814 0.4076
2.00 -0.321 -0.1202 0.0880 0.4138
2.50 -0.337 -0.1293 0.0931 0.4108
3.00 -0.331 -0.1368 0.0972 0.3961
4.00 -0.390 -0.1486 0.1038 0.3821
5.00 -0.498 -0.1578 0.1090 0.3766
""")
class ZhaoEtAl2006SSlabNSHMP2014(ZhaoEtAl2006SSlab):
"""
For the 2014 US National Seismic Hazard Maps the magnitude of Zhao et al.
(2006) for the subduction inslab events is capped at magnitude Mw 7.8
"""
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# extracting dictionary of coefficients specific to required
# intensity measure type.
C = self.COEFFS_ASC[imt]
C_SSLAB = self.COEFFS_SSLAB[imt]
# to avoid singularity at 0.0 (in the calculation of the
# slab correction term), replace 0 values with 0.1
d = dists.rrup
d[d == 0.0] = 0.1
if rup.mag > 7.8:
rup_mag = 7.8
else:
rup_mag = rup.mag
# mean value as given by equation 1, p. 901, without considering the
# faulting style and intraslab terms (that is FR, SS, SSL = 0) and the
# inter and intra event terms, plus the magnitude-squared term
# correction factor (equation 5 p. 909)
mean = self._compute_magnitude_term(C, rup_mag) +\
self._compute_distance_term(C, rup_mag, d) +\
self._compute_focal_depth_term(C, rup.hypo_depth) +\
self._compute_site_class_term(C, sites.vs30) +\
self._compute_magnitude_squared_term(P=C_SSLAB['PS'], M=6.5,
Q=C_SSLAB['QS'],
W=C_SSLAB['WS'],
mag=rup_mag) +\
C_SSLAB['SS'] + self._compute_slab_correction_term(C_SSLAB, d)
# convert from cm/s**2 to g
mean = np.log(np.exp(mean) * 1e-2 / g)
stddevs = self._get_stddevs(C['sigma'], C_SSLAB['tauS'], stddev_types,
num_sites=len(sites.vs30))
return mean, stddevs
# Coefficient table taken from <NAME>'s "White paper on
# Proposed Ground-motion Prediction Equations (GMPEs) for 2015
# National Seismic Hazard Maps" (2012, page 16).
# Values were interpolated to include all listed periods.
# MF is the linear multiplicative factor.
COEFFS_SITE_FACTORS = CoeffsTable(sa_damping=5, table="""\
IMT MF
pga 0.50
pgv 1.00
0.05 0.44
0.10 0.44
0.15 0.53
0.20 0.60
0.25 0.72
0.30 0.81
0.40 1.00
0.50 1.01
0.60 1.02
0.70 1.02
0.80 1.03
0.90 1.04
1.00 1.04
1.25 1.19
1.50 1.31
2.00 1.51
2.50 1.34
3.00 1.21
4.00 1.09
5.00 1.00
""")
class ZhaoEtAl2006SInterCascadia(ZhaoEtAl2006SInter):
"""
Implements the interface GMPE developed by <NAME> et al modified
by the Japan/Cascadia site factors as proposed by <NAME>.
(2012). White paper on proposed ground-motion prediction equations
(GMPEs) for 2015 National Seismic Hazard Maps Final Version,
Nov. 2012, 50 pp. This class extends the
:class:`openquake.hazardlib.gsim.zhao_2006.ZhaoEtAl2006Asc`
because the equation for subduction interface is obtained from the
equation for active shallow crust, by removing the faulting style
term and adding a subduction interface term.
"""
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# extracting dictionary of coefficients specific to required
# intensity measure type.
C = self.COEFFS_ASC[imt]
C_SINTER = self.COEFFS_SINTER[imt]
C_SF = COEFFS_SITE_FACTORS[imt]
# mean value as given by equation 1, p. 901, without considering the
# faulting style and intraslab terms (that is FR, SS, SSL = 0) and the
# inter and intra event terms, plus the magnitude-squared term
# correction factor (equation 5 p. 909)
mean = self._compute_magnitude_term(C, rup.mag) +\
self._compute_distance_term(C, rup.mag, dists.rrup) +\
self._compute_focal_depth_term(C, rup.hypo_depth) +\
self._compute_site_class_term(C, sites.vs30) + \
self._compute_magnitude_squared_term(P=0.0, M=6.3,
Q=C_SINTER['QI'],
W=C_SINTER['WI'],
mag=rup.mag) +\
C_SINTER['SI']
# multiply by site factor to "convert" Japan values to Cascadia values
# then convert from cm/s**2 to g
mean = np.log((np.exp(mean) * C_SF["MF"]) * 1e-2 / g)
stddevs = self._get_stddevs(C['sigma'], C_SINTER['tauI'], stddev_types,
num_sites=len(sites.vs30))
return mean, stddevs
class ZhaoEtAl2006SSlabCascadia(ZhaoEtAl2006SSlab):
"""
Implements GMPE developed by <NAME> et al modified
by the Japan/Cascadia site factors as proposed by <NAME>.
(2012). White paper on proposed ground-motion prediction equations
(GMPEs) for 2015 National Seismic Hazard Maps Final Version,
Nov. 2012, 50 pp. This class extends the
:class:`openquake.hazardlib.gsim.zhao_2006.ZhaoEtAl2006Asc`
because the equation for subduction slab is obtained from the
equation for active shallow crust, by removing the faulting style
term and adding subduction slab terms.
"""
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# extracting dictionary of coefficients specific to required
# intensity measure type.
C = self.COEFFS_ASC[imt]
C_SSLAB = self.COEFFS_SSLAB[imt]
C_SF = COEFFS_SITE_FACTORS[imt]
# to avoid singularity at 0.0 (in the calculation of the
# slab correction term), replace 0 values with 0.1
d = dists.rrup
d[d == 0.0] = 0.1
# mean value as given by equation 1, p. 901, without considering the
# faulting style and intraslab terms (that is FR, SS, SSL = 0) and the
# inter and intra event terms, plus the magnitude-squared term
# correction factor (equation 5 p. 909)
mean = self._compute_magnitude_term(C, rup.mag) +\
self._compute_distance_term(C, rup.mag, d) +\
self._compute_focal_depth_term(C, rup.hypo_depth) +\
self._compute_site_class_term(C, sites.vs30) +\
self._compute_magnitude_squared_term(P=C_SSLAB['PS'], M=6.5,
Q=C_SSLAB['QS'],
W=C_SSLAB['WS'],
mag=rup.mag) +\
C_SSLAB['SS'] + self._compute_slab_correction_term(C_SSLAB, d)
# multiply by site factor to "convert" Japan values to Cascadia values
# then convert from cm/s**2 to g
mean = np.log((np.exp(mean) * C_SF["MF"]) * 1e-2 / g)
stddevs = self._get_stddevs(C['sigma'], C_SSLAB['tauS'], stddev_types,
num_sites=len(sites.vs30))
return mean, stddevs
| [
"numpy.sqrt",
"numpy.log",
"numpy.exp",
"openquake.hazardlib.gsim.base.CoeffsTable",
"numpy.zeros",
"copy.deepcopy"
] | [((23450, 23869), 'openquake.hazardlib.gsim.base.CoeffsTable', 'CoeffsTable', ([], {'sa_damping': '(5)', 'table': '""" IMT MF\n pga 0.50\n pgv 1.00\n 0.05 0.44\n 0.10 0.44\n 0.15 0.53\n 0.20 0.60\n 0.25 0.72\n 0.30 0.81\n 0.40 1.00\n 0.50 1.01\n 0.60 1.02\n 0.70 1.02\n 0.80 1.03\n 0.90 1.04\n 1.00 1.04\n 1.25 1.19\n 1.50 1.31\n 2.00 1.51\n 2.50 1.34\n 3.00 1.21\n 4.00 1.09\n 5.00 1.00\n """'}), '(sa_damping=5, table=\n """ IMT MF\n pga 0.50\n pgv 1.00\n 0.05 0.44\n 0.10 0.44\n 0.15 0.53\n 0.20 0.60\n 0.25 0.72\n 0.30 0.81\n 0.40 1.00\n 0.50 1.01\n 0.60 1.02\n 0.70 1.02\n 0.80 1.03\n 0.90 1.04\n 1.00 1.04\n 1.25 1.19\n 1.50 1.31\n 2.00 1.51\n 2.50 1.34\n 3.00 1.21\n 4.00 1.09\n 5.00 1.00\n """\n )\n', (23461, 23869), False, 'from openquake.hazardlib.gsim.base import GMPE, CoeffsTable\n'), ((7631, 10389), 'openquake.hazardlib.gsim.base.CoeffsTable', 'CoeffsTable', ([], {'sa_damping': '(5)', 'table': '""" IMT a b c d e FR CH C1 C2 C3 C4 sigma QC WC tauC\n pga 1.101 -0.00564 0.0055 1.080 0.01412 0.251 0.293 1.111 1.344 1.355 1.420 0.604 0.0 0.0 0.303\n 0.05 1.076 -0.00671 0.0075 1.060 0.01463 0.251 0.939 1.684 1.793 1.747 1.814 0.640 0.0 0.0 0.326\n 0.10 1.118 -0.00787 0.0090 1.083 0.01423 0.240 1.499 2.061 2.135 2.031 2.082 0.694 0.0 0.0 0.342\n 0.15 1.134 -0.00722 0.0100 1.053 0.01509 0.251 1.462 1.916 2.168 2.052 2.113 0.702 0.0 0.0 0.331\n 0.20 1.147 -0.00659 0.0120 1.014 0.01462 0.260 1.280 1.669 2.085 2.001 2.030 0.692 0.0 0.0 0.312\n 0.25 1.149 -0.00590 0.0140 0.966 0.01459 0.269 1.121 1.468 1.942 1.941 1.937 0.682 0.0 0.0 0.298\n 0.30 1.163 -0.00520 0.0150 0.934 0.01458 0.259 0.852 1.172 1.683 1.808 1.770 0.670 0.0 0.0 0.300\n 0.40 1.200 -0.00422 0.0100 0.959 0.01257 0.248 0.365 0.655 1.127 1.482 1.397 0.659 0.0 0.0 0.346\n 0.50 1.250 -0.00338 0.0060 1.008 0.01114 0.247 -0.207 0.071 0.515 0.934 0.955 0.653 -0.0126 0.0116 0.338\n 0.60 1.293 -0.00282 0.0030 1.088 0.01019 0.233 -0.705 -0.429 -0.003 0.394 0.559 0.653 -0.0329 0.0202 0.349\n 0.70 1.336 -0.00258 0.0025 1.084 0.00979 0.220 -1.144 -0.866 -0.449 -0.111 0.188 0.652 -0.0501 0.0274 0.351\n 0.80 1.386 -0.00242 0.0022 1.088 0.00944 0.232 -1.609 -1.325 -0.928 -0.620 -0.246 0.647 -0.0650 0.0336 0.356\n 0.90 1.433 -0.00232 0.0020 1.109 0.00972 0.220 -2.023 -1.732 -1.349 -1.066 -0.643 0.653 -0.0781 0.0391 0.348\n 1.00 1.479 -0.00220 0.0020 1.115 0.01005 0.211 -2.451 -2.152 -1.776 -1.523 -1.084 0.657 -0.0899 0.0440 0.338\n 1.25 1.551 -0.00207 0.0020 1.083 0.01003 0.251 -3.243 -2.923 -2.542 -2.327 -1.936 0.660 -0.1148 0.0545 0.313\n 1.50 1.621 -0.00224 0.0020 1.091 0.00928 0.248 -3.888 -3.548 -3.169 -2.979 -2.661 0.664 -0.1351 0.0630 0.306\n 2.00 1.694 -0.00201 0.0025 1.055 0.00833 0.263 -4.783 -4.410 -4.039 -3.871 -3.640 0.669 -0.1672 0.0764 0.283\n 2.50 1.748 -0.00187 0.0028 1.052 0.00776 0.262 -5.444 -5.049 -4.698 -4.496 -4.341 0.671 -0.1921 0.0869 0.287\n 3.00 1.759 -0.00147 0.0032 1.025 0.00644 0.307 -5.839 -5.431 -5.089 -4.893 -4.758 0.667 -0.2124 0.0954 0.278\n 4.00 1.826 -0.00195 0.0040 1.044 0.00590 0.353 -6.598 -6.181 -5.882 -5.698 -5.588 0.647 -0.2445 0.1088 0.273\n 5.00 1.825 -0.00237 0.0050 1.065 0.00510 0.248 -6.752 -6.347 -6.051 -5.873 -5.798 0.643 -0.2694 0.1193 0.275\n """'}), '(sa_damping=5, table=\n """ IMT a b c d e FR CH C1 C2 C3 C4 sigma QC WC tauC\n pga 1.101 -0.00564 0.0055 1.080 0.01412 0.251 0.293 1.111 1.344 1.355 1.420 0.604 0.0 0.0 0.303\n 0.05 1.076 -0.00671 0.0075 1.060 0.01463 0.251 0.939 1.684 1.793 1.747 1.814 0.640 0.0 0.0 0.326\n 0.10 1.118 -0.00787 0.0090 1.083 0.01423 0.240 1.499 2.061 2.135 2.031 2.082 0.694 0.0 0.0 0.342\n 0.15 1.134 -0.00722 0.0100 1.053 0.01509 0.251 1.462 1.916 2.168 2.052 2.113 0.702 0.0 0.0 0.331\n 0.20 1.147 -0.00659 0.0120 1.014 0.01462 0.260 1.280 1.669 2.085 2.001 2.030 0.692 0.0 0.0 0.312\n 0.25 1.149 -0.00590 0.0140 0.966 0.01459 0.269 1.121 1.468 1.942 1.941 1.937 0.682 0.0 0.0 0.298\n 0.30 1.163 -0.00520 0.0150 0.934 0.01458 0.259 0.852 1.172 1.683 1.808 1.770 0.670 0.0 0.0 0.300\n 0.40 1.200 -0.00422 0.0100 0.959 0.01257 0.248 0.365 0.655 1.127 1.482 1.397 0.659 0.0 0.0 0.346\n 0.50 1.250 -0.00338 0.0060 1.008 0.01114 0.247 -0.207 0.071 0.515 0.934 0.955 0.653 -0.0126 0.0116 0.338\n 0.60 1.293 -0.00282 0.0030 1.088 0.01019 0.233 -0.705 -0.429 -0.003 0.394 0.559 0.653 -0.0329 0.0202 0.349\n 0.70 1.336 -0.00258 0.0025 1.084 0.00979 0.220 -1.144 -0.866 -0.449 -0.111 0.188 0.652 -0.0501 0.0274 0.351\n 0.80 1.386 -0.00242 0.0022 1.088 0.00944 0.232 -1.609 -1.325 -0.928 -0.620 -0.246 0.647 -0.0650 0.0336 0.356\n 0.90 1.433 -0.00232 0.0020 1.109 0.00972 0.220 -2.023 -1.732 -1.349 -1.066 -0.643 0.653 -0.0781 0.0391 0.348\n 1.00 1.479 -0.00220 0.0020 1.115 0.01005 0.211 -2.451 -2.152 -1.776 -1.523 -1.084 0.657 -0.0899 0.0440 0.338\n 1.25 1.551 -0.00207 0.0020 1.083 0.01003 0.251 -3.243 -2.923 -2.542 -2.327 -1.936 0.660 -0.1148 0.0545 0.313\n 1.50 1.621 -0.00224 0.0020 1.091 0.00928 0.248 -3.888 -3.548 -3.169 -2.979 -2.661 0.664 -0.1351 0.0630 0.306\n 2.00 1.694 -0.00201 0.0025 1.055 0.00833 0.263 -4.783 -4.410 -4.039 -3.871 -3.640 0.669 -0.1672 0.0764 0.283\n 2.50 1.748 -0.00187 0.0028 1.052 0.00776 0.262 -5.444 -5.049 -4.698 -4.496 -4.341 0.671 -0.1921 0.0869 0.287\n 3.00 1.759 -0.00147 0.0032 1.025 0.00644 0.307 -5.839 -5.431 -5.089 -4.893 -4.758 0.667 -0.2124 0.0954 0.278\n 4.00 1.826 -0.00195 0.0040 1.044 0.00590 0.353 -6.598 -6.181 -5.882 -5.698 -5.588 0.647 -0.2445 0.1088 0.273\n 5.00 1.825 -0.00237 0.0050 1.065 0.00510 0.248 -6.752 -6.347 -6.051 -5.873 -5.798 0.643 -0.2694 0.1193 0.275\n """\n )\n', (7642, 10389), False, 'from openquake.hazardlib.gsim.base import GMPE, CoeffsTable\n'), ((13164, 14188), 'openquake.hazardlib.gsim.base.CoeffsTable', 'CoeffsTable', ([], {'sa_damping': '(5)', 'table': '""" IMT SI QI WI tauI\n pga 0.000 0.0 0.0 0.308\n 0.05 0.000 0.0 0.0 0.343\n 0.10 0.000 0.0 0.0 0.403\n 0.15 0.000 -0.0138 0.0286 0.367\n 0.20 0.000 -0.0256 0.0352 0.328\n 0.25 0.000 -0.0348 0.0403 0.289\n 0.30 0.000 -0.0423 0.0445 0.280\n 0.40 -0.041 -0.0541 0.0511 0.271\n 0.50 -0.053 -0.0632 0.0562 0.277\n 0.60 -0.103 -0.0707 0.0604 0.296\n 0.70 -0.146 -0.0771 0.0639 0.313\n 0.80 -0.164 -0.0825 0.0670 0.329\n 0.90 -0.206 -0.0874 0.0697 0.324\n 1.00 -0.239 -0.0917 0.0721 0.328\n 1.25 -0.256 -0.1009 0.0772 0.339\n 1.50 -0.306 -0.1083 0.0814 0.352\n 2.00 -0.321 -0.1202 0.0880 0.360\n 2.50 -0.337 -0.1293 0.0931 0.356\n 3.00 -0.331 -0.1368 0.0972 0.338\n 4.00 -0.390 -0.1486 0.1038 0.307\n 5.00 -0.498 -0.1578 0.1090 0.272\n """'}), '(sa_damping=5, table=\n """ IMT SI QI WI tauI\n pga 0.000 0.0 0.0 0.308\n 0.05 0.000 0.0 0.0 0.343\n 0.10 0.000 0.0 0.0 0.403\n 0.15 0.000 -0.0138 0.0286 0.367\n 0.20 0.000 -0.0256 0.0352 0.328\n 0.25 0.000 -0.0348 0.0403 0.289\n 0.30 0.000 -0.0423 0.0445 0.280\n 0.40 -0.041 -0.0541 0.0511 0.271\n 0.50 -0.053 -0.0632 0.0562 0.277\n 0.60 -0.103 -0.0707 0.0604 0.296\n 0.70 -0.146 -0.0771 0.0639 0.313\n 0.80 -0.164 -0.0825 0.0670 0.329\n 0.90 -0.206 -0.0874 0.0697 0.324\n 1.00 -0.239 -0.0917 0.0721 0.328\n 1.25 -0.256 -0.1009 0.0772 0.339\n 1.50 -0.306 -0.1083 0.0814 0.352\n 2.00 -0.321 -0.1202 0.0880 0.360\n 2.50 -0.337 -0.1293 0.0931 0.356\n 3.00 -0.331 -0.1368 0.0972 0.338\n 4.00 -0.390 -0.1486 0.1038 0.307\n 5.00 -0.498 -0.1578 0.1090 0.272\n """\n )\n', (13175, 14188), False, 'from openquake.hazardlib.gsim.base import GMPE, CoeffsTable\n'), ((17435, 18833), 'openquake.hazardlib.gsim.base.CoeffsTable', 'CoeffsTable', ([], {'sa_damping': '(5)', 'table': '""" IMT SS SSL PS QS WS tauS\n pga 2.607 -0.528 0.1392 0.1584 -0.0529 0.321\n 0.05 2.764 -0.551 0.1636 0.1932 -0.0841 0.378\n 0.10 2.156 -0.420 0.1690 0.2057 -0.0877 0.420\n 0.15 2.161 -0.431 0.1669 0.1984 -0.0773 0.372\n 0.20 1.901 -0.372 0.1631 0.1856 -0.0644 0.324\n 0.25 1.814 -0.360 0.1588 0.1714 -0.0515 0.294\n 0.30 2.181 -0.450 0.1544 0.1573 -0.0395 0.284\n 0.40 2.432 -0.506 0.1460 0.1309 -0.0183 0.278\n 0.50 2.629 -0.554 0.1381 0.1078 -0.0008 0.272\n 0.60 2.702 -0.575 0.1307 0.0878 0.0136 0.285\n 0.70 2.654 -0.572 0.1239 0.0705 0.0254 0.290\n 0.80 2.480 -0.540 0.1176 0.0556 0.0352 0.299\n 0.90 2.332 -0.522 0.1116 0.0426 0.0432 0.289\n 1.00 2.233 -0.509 0.1060 0.0314 0.0498 0.286\n 1.25 2.029 -0.469 0.0933 0.0093 0.0612 0.277\n 1.50 1.589 -0.379 0.0821 -0.0062 0.0674 0.282\n 2.00 0.966 -0.248 0.0628 -0.0235 0.0692 0.300\n 2.50 0.789 -0.221 0.0465 -0.0287 0.0622 0.292\n 3.00 1.037 -0.263 0.0322 -0.0261 0.0496 0.274\n 4.00 0.561 -0.169 0.0083 -0.0065 0.0150 0.281\n 5.00 0.225 -0.120 -0.0117 0.0246 -0.0268 0.296\n """'}), '(sa_damping=5, table=\n """ IMT SS SSL PS QS WS tauS\n pga 2.607 -0.528 0.1392 0.1584 -0.0529 0.321\n 0.05 2.764 -0.551 0.1636 0.1932 -0.0841 0.378\n 0.10 2.156 -0.420 0.1690 0.2057 -0.0877 0.420\n 0.15 2.161 -0.431 0.1669 0.1984 -0.0773 0.372\n 0.20 1.901 -0.372 0.1631 0.1856 -0.0644 0.324\n 0.25 1.814 -0.360 0.1588 0.1714 -0.0515 0.294\n 0.30 2.181 -0.450 0.1544 0.1573 -0.0395 0.284\n 0.40 2.432 -0.506 0.1460 0.1309 -0.0183 0.278\n 0.50 2.629 -0.554 0.1381 0.1078 -0.0008 0.272\n 0.60 2.702 -0.575 0.1307 0.0878 0.0136 0.285\n 0.70 2.654 -0.572 0.1239 0.0705 0.0254 0.290\n 0.80 2.480 -0.540 0.1176 0.0556 0.0352 0.299\n 0.90 2.332 -0.522 0.1116 0.0426 0.0432 0.289\n 1.00 2.233 -0.509 0.1060 0.0314 0.0498 0.286\n 1.25 2.029 -0.469 0.0933 0.0093 0.0612 0.277\n 1.50 1.589 -0.379 0.0821 -0.0062 0.0674 0.282\n 2.00 0.966 -0.248 0.0628 -0.0235 0.0692 0.300\n 2.50 0.789 -0.221 0.0465 -0.0287 0.0622 0.292\n 3.00 1.037 -0.263 0.0322 -0.0261 0.0496 0.274\n 4.00 0.561 -0.169 0.0083 -0.0065 0.0150 0.281\n 5.00 0.225 -0.120 -0.0117 0.0246 -0.0268 0.296\n """\n )\n', (17446, 18833), False, 'from openquake.hazardlib.gsim.base import GMPE, CoeffsTable\n'), ((20084, 21129), 'openquake.hazardlib.gsim.base.CoeffsTable', 'CoeffsTable', ([], {'sa_damping': '(5)', 'table': '""" IMT SI QI WI tauI\n pga 0.000 0.0 0.0 0.3976\n 0.05 0.000 0.0 0.0 0.4437\n 0.10 0.000 0.0 0.0 0.4903\n 0.15 0.000 -0.0138 0.0286 0.4603\n 0.20 0.000 -0.0256 0.0352 0.4233\n 0.25 0.000 -0.0348 0.0403 0.3908\n 0.30 0.000 -0.0423 0.0445 0.3790\n 0.40 -0.041 -0.0541 0.0511 0.3897\n 0.50 -0.053 -0.0632 0.0562 0.3890\n 0.60 -0.103 -0.0707 0.0604 0.4014\n 0.70 -0.146 -0.0771 0.0639 0.4079\n 0.80 -0.164 -0.0825 0.0670 0.4183\n 0.90 -0.206 -0.0874 0.0697 0.4106\n 1.00 -0.239 -0.0917 0.0721 0.4101\n 1.25 -0.256 -0.1009 0.0772 0.4021\n 1.50 -0.306 -0.1083 0.0814 0.4076\n 2.00 -0.321 -0.1202 0.0880 0.4138\n 2.50 -0.337 -0.1293 0.0931 0.4108\n 3.00 -0.331 -0.1368 0.0972 0.3961\n 4.00 -0.390 -0.1486 0.1038 0.3821\n 5.00 -0.498 -0.1578 0.1090 0.3766\n """'}), '(sa_damping=5, table=\n """ IMT SI QI WI tauI\n pga 0.000 0.0 0.0 0.3976\n 0.05 0.000 0.0 0.0 0.4437\n 0.10 0.000 0.0 0.0 0.4903\n 0.15 0.000 -0.0138 0.0286 0.4603\n 0.20 0.000 -0.0256 0.0352 0.4233\n 0.25 0.000 -0.0348 0.0403 0.3908\n 0.30 0.000 -0.0423 0.0445 0.3790\n 0.40 -0.041 -0.0541 0.0511 0.3897\n 0.50 -0.053 -0.0632 0.0562 0.3890\n 0.60 -0.103 -0.0707 0.0604 0.4014\n 0.70 -0.146 -0.0771 0.0639 0.4079\n 0.80 -0.164 -0.0825 0.0670 0.4183\n 0.90 -0.206 -0.0874 0.0697 0.4106\n 1.00 -0.239 -0.0917 0.0721 0.4101\n 1.25 -0.256 -0.1009 0.0772 0.4021\n 1.50 -0.306 -0.1083 0.0814 0.4076\n 2.00 -0.321 -0.1202 0.0880 0.4138\n 2.50 -0.337 -0.1293 0.0931 0.4108\n 3.00 -0.331 -0.1368 0.0972 0.3961\n 4.00 -0.390 -0.1486 0.1038 0.3821\n 5.00 -0.498 -0.1578 0.1090 0.3766\n """\n )\n', (20095, 21129), False, 'from openquake.hazardlib.gsim.base import GMPE, CoeffsTable\n'), ((19837, 19855), 'copy.deepcopy', 'copy.deepcopy', (['rup'], {}), '(rup)\n', (19850, 19855), False, 'import copy\n'), ((17183, 17195), 'numpy.log', 'np.log', (['rrup'], {}), '(rrup)\n', (17189, 17195), True, 'import numpy as np\n'), ((4892, 4922), 'numpy.sqrt', 'np.sqrt', (['(sigma ** 2 + tau ** 2)'], {}), '(sigma ** 2 + tau ** 2)\n', (4899, 4922), True, 'import numpy as np\n'), ((4328, 4340), 'numpy.exp', 'np.exp', (['mean'], {}), '(mean)\n', (4334, 4340), True, 'import numpy as np\n'), ((12766, 12778), 'numpy.exp', 'np.exp', (['mean'], {}), '(mean)\n', (12772, 12778), True, 'import numpy as np\n'), ((16766, 16778), 'numpy.exp', 'np.exp', (['mean'], {}), '(mean)\n', (16772, 16778), True, 'import numpy as np\n'), ((22960, 22972), 'numpy.exp', 'np.exp', (['mean'], {}), '(mean)\n', (22966, 22972), True, 'import numpy as np\n'), ((4964, 4983), 'numpy.zeros', 'np.zeros', (['num_sites'], {}), '(num_sites)\n', (4972, 4983), True, 'import numpy as np\n'), ((5602, 5622), 'numpy.exp', 'np.exp', (["(C['d'] * mag)"], {}), "(C['d'] * mag)\n", (5608, 5622), True, 'import numpy as np\n'), ((25926, 25938), 'numpy.exp', 'np.exp', (['mean'], {}), '(mean)\n', (25932, 25938), True, 'import numpy as np\n'), ((28395, 28407), 'numpy.exp', 'np.exp', (['mean'], {}), '(mean)\n', (28401, 28407), True, 'import numpy as np\n'), ((5082, 5101), 'numpy.zeros', 'np.zeros', (['num_sites'], {}), '(num_sites)\n', (5090, 5101), True, 'import numpy as np\n'), ((5198, 5217), 'numpy.zeros', 'np.zeros', (['num_sites'], {}), '(num_sites)\n', (5206, 5217), True, 'import numpy as np\n')] |
# Lib
from setuptools import setup, find_packages
exec(open('methylprep/version.py').read())
test_requirements = [
'methylcheck', # 'git+https://github.com/FoxoTech/methylcheck.git@feature/v0.7.7#egg=methylcheck',
'pytest',
'pytest_mock',
'matplotlib',
'scikit-learn', # openpyxl uses this, and forcing it to install the best version, not sklearn 0.0
'openpyxl',
'coverage'
]
setup(
name='methylprep',
version=__version__,
description='Python-based Illumina methylation array preprocessing software',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
project_urls = {
"Documentation": "https://life-epigenetics-methylprep.readthedocs-hosted.com/en/latest/",
"Source": "https://github.com/FOXOBioScience/methylprep/",
"Funding": "https://FOXOBioScience.com/"
},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.7',
'Topic :: Scientific/Engineering :: Bio-Informatics',
'Topic :: Scientific/Engineering :: Medical Science Apps.',
'Framework :: Jupyter',
'Intended Audience :: Science/Research',
'Intended Audience :: Financial and Insurance Industry',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX :: Linux',
],
keywords='methylation dna data processing epigenetics illumina',
url='https://github.com/FOXOBioScience/methylprep',
license='MIT',
author='Life Epigenetics',
author_email='<EMAIL>',
packages=find_packages(),
include_package_data=True,
package_data={"":["*.txt.gz"]},
install_requires=[
'pyparsing > 3.0',
'numpy',
'pandas >=1.3.0',
'scipy',
'statsmodels',
'tqdm',
'bs4',
'lxml',
'requests',
],
extras_require={
'dev': test_requirements
},
setup_requires=['pytest-runner'],
tests_require= test_requirements,
entry_points='''
[console_scripts]
methylprep-cli=methylprep.cli:app
''',
)
| [
"setuptools.find_packages"
] | [((1736, 1751), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (1749, 1751), False, 'from setuptools import setup, find_packages\n')] |
import random
class Fluctuation:
def __init__(self, percentage, baseline):
self.percentage = percentage
self.baseline = baseline
def __call__(self, value):
return self.apply(value)
def apply(self, value):
return value + self.generate(self.baseline)
def generate(self, baseline):
relative_value = self.get_relative_value(baseline)
corridor = (-relative_value, relative_value)
return random.randint(corridor[0], corridor[1])
def get_relative_value(self, baseline):
relative_value = float(baseline) / 100.0 * float(self.percentage)
return int(relative_value)
| [
"random.randint"
] | [((460, 500), 'random.randint', 'random.randint', (['corridor[0]', 'corridor[1]'], {}), '(corridor[0], corridor[1])\n', (474, 500), False, 'import random\n')] |
from airflow.models import DAG
from airflow.utils.timezone import datetime as adt
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators.bash_operator import BashOperator
def random_subdag(parent_dag_name, child_dag_name, args):
with DAG(
# subdag의 id는 이와같은 컨벤션으로 쓴답니다.
dag_id='%s.subdag_%s' % (parent_dag_name, child_dag_name),
default_args=args,
start_date=adt(2021, 8, 2, 3),
# schedule_interval=None, # 값을 넣어주어야 합니다.
) as dag_subdag:
union = DummyOperator(
task_id='%s-union' % (child_dag_name),
dag=dag_subdag
)
for i in range(2):
process_a = DummyOperator(
task_id='%s-task_A-%s' % (child_dag_name, i + 1),
dag=dag_subdag,
)
# globals()['process_b'] = BashOperator(
process_b = DummyOperator(
task_id='%s-task_B-%s' % (child_dag_name, i + 1),
dag=dag_subdag,
)
process_a >> process_b >> union
return dag_subdag
| [
"airflow.utils.timezone.datetime",
"airflow.operators.dummy_operator.DummyOperator"
] | [((532, 598), 'airflow.operators.dummy_operator.DummyOperator', 'DummyOperator', ([], {'task_id': "('%s-union' % child_dag_name)", 'dag': 'dag_subdag'}), "(task_id='%s-union' % child_dag_name, dag=dag_subdag)\n", (545, 598), False, 'from airflow.operators.dummy_operator import DummyOperator\n'), ((687, 766), 'airflow.operators.dummy_operator.DummyOperator', 'DummyOperator', ([], {'task_id': "('%s-task_A-%s' % (child_dag_name, i + 1))", 'dag': 'dag_subdag'}), "(task_id='%s-task_A-%s' % (child_dag_name, i + 1), dag=dag_subdag)\n", (700, 766), False, 'from airflow.operators.dummy_operator import DummyOperator\n'), ((891, 970), 'airflow.operators.dummy_operator.DummyOperator', 'DummyOperator', ([], {'task_id': "('%s-task_B-%s' % (child_dag_name, i + 1))", 'dag': 'dag_subdag'}), "(task_id='%s-task_B-%s' % (child_dag_name, i + 1), dag=dag_subdag)\n", (904, 970), False, 'from airflow.operators.dummy_operator import DummyOperator\n'), ((424, 442), 'airflow.utils.timezone.datetime', 'adt', (['(2021)', '(8)', '(2)', '(3)'], {}), '(2021, 8, 2, 3)\n', (427, 442), True, 'from airflow.utils.timezone import datetime as adt\n')] |
import subprocess
subprocess.run("paplay --volume=65536 /home/pi/Kodo.wav", shell=True)
| [
"subprocess.run"
] | [((18, 87), 'subprocess.run', 'subprocess.run', (['"""paplay --volume=65536 /home/pi/Kodo.wav"""'], {'shell': '(True)'}), "('paplay --volume=65536 /home/pi/Kodo.wav', shell=True)\n", (32, 87), False, 'import subprocess\n')] |
# uncompyle6 version 3.2.4
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)]
# Embedded file name: lib.coginvasion.makeatoon.ToonGenerator_ITW
from direct.directnotify.DirectNotifyGlobal import directNotify
from lib.coginvasion.toon import Toon
import random
notify = directNotify.newCategory('ToonGenerator')
class ToonGenerator:
def __init__(self, mat=None):
self.toon = Toon.Toon(base.cr, mat=1)
def generateToon(self, gender, matNARandomToon=0):
genderDNA = self.toon.gender2genderDNA[gender]
self.random_animal = random.randint(0, 8)
shortDNA = '00'
if self.toon.animalDNA2animal['0' + str(self.random_animal)] == 'mouse':
self.random_head = random.randint(0, 1)
else:
if self.toon.animalDNA2animal['0' + str(self.random_animal)] == 'dog':
self.random_head = random.randint(4, 7)
else:
self.random_head = random.randint(0, 3)
if gender == 'girl':
self.random_torso = random.randint(3, 5)
shortDNA = '10'
else:
self.random_torso = random.randint(0, 2)
self.random_legs = random.randint(0, 2)
self.random_color = random.randint(0, 26)
animalDNA = '0' + str(self.random_animal)
headDNA = '0' + str(self.random_head)
torsoDNA = '0' + str(self.random_torso)
legsDNA = '0' + str(self.random_legs)
if self.random_color < 10:
colorDNA = '0' + str(self.random_color)
else:
colorDNA = str(self.random_color)
dnaStrand = '%s/%s/%s/%s/%s/%s/%s/%s/00/00/%s/00/00/00/00' % (
genderDNA, animalDNA, headDNA, colorDNA, torsoDNA,
colorDNA, legsDNA, colorDNA, shortDNA)
self.toon.setDNAStrand(dnaStrand, makeTag=0)
self.currentAnimFrame = 0
if not matNARandomToon:
self.createToon()
def cleanupToon(self):
self.toon.deleteCurrentToon()
self.toon.disable()
self.toon.delete()
def isFinalHead(self, headDna, direction):
if direction == 1:
return headDna == '03' and self.toon.animal != 'mouse' and self.toon.animal != 'dog' or headDna == '01' and self.toon.animal == 'mouse' or headDna == '07' and self.toon.animal == 'dog'
if direction == 0:
return headDna == '00' and self.toon.animal != 'dog' or headDna == '04' and self.toon.animal == 'dog'
def isFinalTorso(self, torsoDna, direction):
if direction == 1:
if self.toon.gender == 'girl':
return torsoDna == '05'
return torsoDna == '02'
else:
if direction == 0:
if self.toon.gender == 'girl':
return torsoDna == '03'
return torsoDna == '00'
def isFinalLeg(self, legDna, direction):
if direction == 1:
return legDna == '02'
if direction == 0:
return legDna == '00'
def isFinalAnimal(self, animalDna, direction):
if direction == 1:
return animalDna == '08'
if direction == 0:
return animalDna == '00'
def isFinalColor(self, colorDna, direction):
if direction == 1:
return colorDna == '26'
if direction == 0:
return colorDna == '00'
def isFinalShorts(self, shortDna, direction):
if direction == 1:
if self.toon.gender == 'girl':
return shortDna == '17'
return shortDna == '09'
else:
if direction == 0:
if self.toon.gender == 'girl':
return shortDna == '10'
return shortDna == '00'
def isFinalShirt(self, shirtDna, direction):
if direction == 1:
return shirtDna == '22'
if direction == 0:
return shirtDna == '00'
def isFinalSleeve(self, sleeveDna, direction):
if direction == 1:
return sleeveDna == '22'
if direction == 0:
return sleeveDna == '00'
def getNextTorso(self):
if self.isFinalTorso(self.toon.torso2torsoDNA[self.toon.torso], 1):
if self.toon.getGender() == 'girl':
return '03'
return '00'
else:
currentTorso = int(self.toon.torso2torsoDNA[self.toon.torso])
return '0' + str(currentTorso + 1)
def getPrevTorso(self):
if self.isFinalTorso(self.toon.torso2torsoDNA[self.toon.torso], 0):
if self.toon.getGender() == 'girl':
return '05'
return '02'
else:
currentTorso = int(self.toon.torso2torsoDNA[self.toon.torso])
return '0' + str(currentTorso - 1)
def getNextLeg(self):
if self.isFinalLeg(self.toon.leg2legDNA[self.toon.legs], 1):
return '00'
currentLeg = int(self.toon.leg2legDNA[self.toon.legs])
return '0' + str(currentLeg + 1)
def getPrevLeg(self):
if self.isFinalLeg(self.toon.leg2legDNA[self.toon.legs], 0):
return '02'
currentLeg = int(self.toon.leg2legDNA[self.toon.legs])
return '0' + str(currentLeg - 1)
def getNextHead(self):
if self.isFinalHead(self.toon.head2headDNA[self.toon.head], 1):
if self.getNextAnimal() == '01':
return '04'
return '00'
else:
currentHead = int(self.toon.head2headDNA[self.toon.head])
return '0' + str(currentHead + 1)
def getNextAnimal(self):
if self.toon.animal == 'duck' and self.isFinalHead(self.toon.head2headDNA[self.toon.head], 1):
return '00'
if not self.isFinalHead(self.toon.head2headDNA[self.toon.head], 1):
return
currentAnimal = int(self.toon.animal2animalDNA[self.toon.animal])
return '0' + str(currentAnimal + 1)
return
def getPrevAnimal(self):
if self.toon.animal == 'cat' and self.isFinalHead(self.toon.head2headDNA[self.toon.head], 0):
return '08'
if not self.isFinalHead(self.toon.head2headDNA[self.toon.head], 0):
return
currentAnimal = int(self.toon.animal2animalDNA[self.toon.animal])
return '0' + str(currentAnimal - 1)
return
def getPrevHead(self):
if self.isFinalHead(self.toon.head2headDNA[self.toon.head], 0):
if self.getPrevAnimal() == '07':
return '01'
if self.getPrevAnimal() == '01':
return '07'
return '03'
else:
currentHead = int(self.toon.head2headDNA[self.toon.head])
return '0' + str(currentHead - 1)
def getNextColor(self, part):
if part == 'torso':
color = self.toon.torsocolor
else:
if part == 'legs':
color = self.toon.legcolor
else:
if part == 'head' or part == 'all':
color = self.toon.headcolor
else:
if part == 'shirt':
color = self.toon.shirtColor
else:
if part == 'shorts':
color = self.toon.shortColor
else:
if part == 'sleeve':
color = self.toon.sleeveColor
else:
if part == 'gloves':
color = self.toon.gloveColor
if part in ('shorts', 'sleeve', 'shirt'):
if self.isFinalColor(self.toon.clothesColor2clothesColorDNA[color], 1):
return '00'
currentColor = int(self.toon.clothesColor2clothesColorDNA[color])
if currentColor < 9:
return '0' + str(currentColor + 1)
return str(currentColor + 1)
if self.isFinalColor(self.toon.color2colorDNA[color], 1):
return '00'
currentColor = int(self.toon.color2colorDNA[color])
if currentColor < 9:
return '0' + str(currentColor + 1)
return str(currentColor + 1)
def getPrevColor(self, part):
if part == 'torso':
color = self.toon.torsocolor
else:
if part == 'legs':
color = self.toon.legcolor
else:
if part == 'head' or part == 'all':
color = self.toon.headcolor
else:
if part == 'shirt':
color = self.toon.shirtColor
else:
if part == 'shorts':
color = self.toon.shortColor
else:
if part == 'sleeve':
color = self.toon.sleeveColor
else:
if part == 'gloves':
color = self.toon.gloveColor
if part in ('shirt', 'shorts', 'sleeve'):
if self.isFinalColor(self.toon.clothesColor2clothesColorDNA[color], 0):
return '26'
currentColor = int(self.toon.clothesColor2clothesColorDNA[color])
if currentColor < 11:
return '0' + str(currentColor - 1)
return str(currentColor - 1)
else:
if self.isFinalColor(self.toon.color2colorDNA[color], 0):
return '26'
currentColor = int(self.toon.color2colorDNA[color])
if currentColor < 11:
return '0' + str(currentColor - 1)
return str(currentColor - 1)
def getNextShirtAndSleeve(self):
return [
self.getNextShirt(), self.getNextSleeve()]
def getPrevShirtAndSleeve(self):
return [
self.getPrevShirt(), self.getPrevSleeve()]
def getNextShirt(self):
if self.getNextColor('shirt') == '00':
if self.isFinalShirt(self.toon.shirt2shirtDNA[self.toon.shirt], 1):
return '00'
currentShirt = int(self.toon.shirt2shirtDNA[self.toon.shirt])
if currentShirt < 9:
return '0' + str(currentShirt + 1)
return str(currentShirt + 1)
else:
return
return
def getPrevShirt(self):
if self.getPrevColor('shirt') == '26':
if self.isFinalShirt(self.toon.shirt2shirtDNA[self.toon.shirt], 0):
return '22'
currentShirt = int(self.toon.shirt2shirtDNA[self.toon.shirt])
if currentShirt < 11:
return '0' + str(currentShirt - 1)
return str(currentShirt - 1)
else:
return
return
def getNextSleeve(self):
if self.getNextColor('sleeve') == '00':
if self.isFinalSleeve(self.toon.sleeve2sleeveDNA[self.toon.sleeve], 1):
return '00'
currentSleeve = int(self.toon.sleeve2sleeveDNA[self.toon.sleeve])
if currentSleeve < 9:
return '0' + str(currentSleeve + 1)
return str(currentSleeve + 1)
else:
return
return
def getPrevSleeve(self):
if self.getPrevColor('sleeve') == '26':
if self.isFinalSleeve(self.toon.sleeve2sleeveDNA[self.toon.sleeve], 0):
return '22'
currentSleeve = int(self.toon.sleeve2sleeveDNA[self.toon.sleeve])
if currentSleeve < 11:
return '0' + str(currentSleeve - 1)
return str(currentSleeve - 1)
else:
return
return
def getNextShorts(self):
if self.getNextColor('shorts') == '00':
if self.isFinalShorts(self.toon.short2shortDNA[self.toon.shorts], 1):
return '00'
currentShorts = int(self.toon.short2shortDNA[self.toon.shorts])
if currentShorts < 9:
return '0' + str(currentShorts + 1)
return str(currentShorts + 1)
else:
return
return
def getPrevShorts(self):
if self.getPrevColor('shorts') == '26':
if self.isFinalShorts(self.toon.short2shortDNA[self.toon.shorts], 0):
return '16'
currentShorts = int(self.toon.short2shortDNA[self.toon.shorts])
if currentShorts < 11:
return '0' + str(currentShorts - 1)
return str(currentShorts - 1)
else:
return
return
def generateDNAStrandWithCurrentStyle(self):
self.currentAnimFrame = self.toon.getCurrentFrame()
self.toon.generateDNAStrandWithCurrentStyle()
self.createToon()
def setToonPosForNameShop(self):
self.toon.setPos(2.29, -3, 0)
self.toon.setHpr(138.01, 0, 0)
def setToonPosForGeneralShop(self):
self.toon.setPos(0, 0, 0)
self.toon.setHpr(180, 0, 0)
def createToon(self):
self.toon.reparentTo(render)
if self.currentAnimFrame == 0:
self.toon.animFSM.request('neutral')
else:
self.toon.loopFromFrameToZero('neutral', fromFrame=self.currentAnimFrame)
self.toon.startBlink()
self.toon.startLookAround()
self.toon.setH(180) | [
"direct.directnotify.DirectNotifyGlobal.directNotify.newCategory",
"random.randint",
"lib.coginvasion.toon.Toon.Toon"
] | [((353, 394), 'direct.directnotify.DirectNotifyGlobal.directNotify.newCategory', 'directNotify.newCategory', (['"""ToonGenerator"""'], {}), "('ToonGenerator')\n", (377, 394), False, 'from direct.directnotify.DirectNotifyGlobal import directNotify\n'), ((472, 497), 'lib.coginvasion.toon.Toon.Toon', 'Toon.Toon', (['base.cr'], {'mat': '(1)'}), '(base.cr, mat=1)\n', (481, 497), False, 'from lib.coginvasion.toon import Toon\n'), ((638, 658), 'random.randint', 'random.randint', (['(0)', '(8)'], {}), '(0, 8)\n', (652, 658), False, 'import random\n'), ((1247, 1267), 'random.randint', 'random.randint', (['(0)', '(2)'], {}), '(0, 2)\n', (1261, 1267), False, 'import random\n'), ((1296, 1317), 'random.randint', 'random.randint', (['(0)', '(26)'], {}), '(0, 26)\n', (1310, 1317), False, 'import random\n'), ((795, 815), 'random.randint', 'random.randint', (['(0)', '(1)'], {}), '(0, 1)\n', (809, 815), False, 'import random\n'), ((1104, 1124), 'random.randint', 'random.randint', (['(3)', '(5)'], {}), '(3, 5)\n', (1118, 1124), False, 'import random\n'), ((1199, 1219), 'random.randint', 'random.randint', (['(0)', '(2)'], {}), '(0, 2)\n', (1213, 1219), False, 'import random\n'), ((948, 968), 'random.randint', 'random.randint', (['(4)', '(7)'], {}), '(4, 7)\n', (962, 968), False, 'import random\n'), ((1022, 1042), 'random.randint', 'random.randint', (['(0)', '(3)'], {}), '(0, 3)\n', (1036, 1042), False, 'import random\n')] |
import time
import pytest
from brownie import PriceExercise, network
from scripts.helpful_scripts import LOCAL_BLOCKCHAIN_ENVIRONMENTS, get_account, get_contract
@pytest.fixture
def deploy_price_exercise(get_job_id, chainlink_fee):
# Arrange / Act
price_exercise = PriceExercise.deploy(
get_contract("oracle").address,
get_job_id,
chainlink_fee,
get_contract("link_token").address,
get_contract("btc_usd_price_feed").address,
{"from": get_account()},
)
# Assert
assert price_exercise is not None
return price_exercise
def test_send_api_request_local(
deploy_price_exercise,
chainlink_fee,
get_data,
):
# Arrange
if network.show_active() not in LOCAL_BLOCKCHAIN_ENVIRONMENTS:
pytest.skip("Only for local testing")
price_exercise = deploy_price_exercise
get_contract("link_token").transfer(
price_exercise.address, chainlink_fee * 2, {"from": get_account()}
)
# Act
transaction_receipt = price_exercise.requestPriceData({"from": get_account()})
requestId = transaction_receipt.events["ChainlinkRequested"]["id"]
# Assert
get_contract("oracle").fulfillOracleRequest(requestId, get_data, {"from": get_account()})
assert isinstance(price_exercise.priceFeedGreater(), bool)
def test_send_api_request_testnet(deploy_price_exercise, chainlink_fee):
# Arrange
if network.show_active() not in ["kovan", "rinkeby", "mainnet"]:
pytest.skip("Only for local testing")
price_exercise = deploy_price_exercise
get_contract("link_token").transfer(
price_exercise.address, chainlink_fee * 2, {"from": get_account()}
)
# Act
transaction = price_exercise.requestPriceData({"from": get_account()})
# Assert
assert transaction is not None
transaction.wait(2)
time.sleep(35)
assert isinstance(price_exercise.priceFeedGreater(), bool)
#assert price_exercise.volume() > 0
def test_can_get_latest_price(get_job_id, chainlink_fee):
# Arrange / Act
price_exercise = PriceExercise.deploy(
get_contract("oracle").address,
get_job_id,
chainlink_fee,
get_contract("link_token").address,
get_contract("btc_usd_price_feed"),
{"from": get_account()},
)
# price_exercise = deploy_price_exercise
# Assert
value = price_exercise.getLatestPrice()
assert isinstance(value, int)
assert value > 0
| [
"scripts.helpful_scripts.get_contract",
"scripts.helpful_scripts.get_account",
"time.sleep",
"brownie.network.show_active",
"pytest.skip"
] | [((1852, 1866), 'time.sleep', 'time.sleep', (['(35)'], {}), '(35)\n', (1862, 1866), False, 'import time\n'), ((715, 736), 'brownie.network.show_active', 'network.show_active', ([], {}), '()\n', (734, 736), False, 'from brownie import PriceExercise, network\n'), ((783, 820), 'pytest.skip', 'pytest.skip', (['"""Only for local testing"""'], {}), "('Only for local testing')\n", (794, 820), False, 'import pytest\n'), ((1418, 1439), 'brownie.network.show_active', 'network.show_active', ([], {}), '()\n', (1437, 1439), False, 'from brownie import PriceExercise, network\n'), ((1488, 1525), 'pytest.skip', 'pytest.skip', (['"""Only for local testing"""'], {}), "('Only for local testing')\n", (1499, 1525), False, 'import pytest\n'), ((2228, 2262), 'scripts.helpful_scripts.get_contract', 'get_contract', (['"""btc_usd_price_feed"""'], {}), "('btc_usd_price_feed')\n", (2240, 2262), False, 'from scripts.helpful_scripts import LOCAL_BLOCKCHAIN_ENVIRONMENTS, get_account, get_contract\n'), ((307, 329), 'scripts.helpful_scripts.get_contract', 'get_contract', (['"""oracle"""'], {}), "('oracle')\n", (319, 329), False, 'from scripts.helpful_scripts import LOCAL_BLOCKCHAIN_ENVIRONMENTS, get_account, get_contract\n'), ((390, 416), 'scripts.helpful_scripts.get_contract', 'get_contract', (['"""link_token"""'], {}), "('link_token')\n", (402, 416), False, 'from scripts.helpful_scripts import LOCAL_BLOCKCHAIN_ENVIRONMENTS, get_account, get_contract\n'), ((434, 468), 'scripts.helpful_scripts.get_contract', 'get_contract', (['"""btc_usd_price_feed"""'], {}), "('btc_usd_price_feed')\n", (446, 468), False, 'from scripts.helpful_scripts import LOCAL_BLOCKCHAIN_ENVIRONMENTS, get_account, get_contract\n'), ((495, 508), 'scripts.helpful_scripts.get_account', 'get_account', ([], {}), '()\n', (506, 508), False, 'from scripts.helpful_scripts import LOCAL_BLOCKCHAIN_ENVIRONMENTS, get_account, get_contract\n'), ((868, 894), 'scripts.helpful_scripts.get_contract', 'get_contract', (['"""link_token"""'], {}), "('link_token')\n", (880, 894), False, 'from scripts.helpful_scripts import LOCAL_BLOCKCHAIN_ENVIRONMENTS, get_account, get_contract\n'), ((965, 978), 'scripts.helpful_scripts.get_account', 'get_account', ([], {}), '()\n', (976, 978), False, 'from scripts.helpful_scripts import LOCAL_BLOCKCHAIN_ENVIRONMENTS, get_account, get_contract\n'), ((1063, 1076), 'scripts.helpful_scripts.get_account', 'get_account', ([], {}), '()\n', (1074, 1076), False, 'from scripts.helpful_scripts import LOCAL_BLOCKCHAIN_ENVIRONMENTS, get_account, get_contract\n'), ((1167, 1189), 'scripts.helpful_scripts.get_contract', 'get_contract', (['"""oracle"""'], {}), "('oracle')\n", (1179, 1189), False, 'from scripts.helpful_scripts import LOCAL_BLOCKCHAIN_ENVIRONMENTS, get_account, get_contract\n'), ((1241, 1254), 'scripts.helpful_scripts.get_account', 'get_account', ([], {}), '()\n', (1252, 1254), False, 'from scripts.helpful_scripts import LOCAL_BLOCKCHAIN_ENVIRONMENTS, get_account, get_contract\n'), ((1573, 1599), 'scripts.helpful_scripts.get_contract', 'get_contract', (['"""link_token"""'], {}), "('link_token')\n", (1585, 1599), False, 'from scripts.helpful_scripts import LOCAL_BLOCKCHAIN_ENVIRONMENTS, get_account, get_contract\n'), ((1670, 1683), 'scripts.helpful_scripts.get_account', 'get_account', ([], {}), '()\n', (1681, 1683), False, 'from scripts.helpful_scripts import LOCAL_BLOCKCHAIN_ENVIRONMENTS, get_account, get_contract\n'), ((1760, 1773), 'scripts.helpful_scripts.get_account', 'get_account', ([], {}), '()\n', (1771, 1773), False, 'from scripts.helpful_scripts import LOCAL_BLOCKCHAIN_ENVIRONMENTS, get_account, get_contract\n'), ((2101, 2123), 'scripts.helpful_scripts.get_contract', 'get_contract', (['"""oracle"""'], {}), "('oracle')\n", (2113, 2123), False, 'from scripts.helpful_scripts import LOCAL_BLOCKCHAIN_ENVIRONMENTS, get_account, get_contract\n'), ((2184, 2210), 'scripts.helpful_scripts.get_contract', 'get_contract', (['"""link_token"""'], {}), "('link_token')\n", (2196, 2210), False, 'from scripts.helpful_scripts import LOCAL_BLOCKCHAIN_ENVIRONMENTS, get_account, get_contract\n'), ((2281, 2294), 'scripts.helpful_scripts.get_account', 'get_account', ([], {}), '()\n', (2292, 2294), False, 'from scripts.helpful_scripts import LOCAL_BLOCKCHAIN_ENVIRONMENTS, get_account, get_contract\n')] |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Cloud SDK default keyboard interrupt handler."""
from __future__ import absolute_import
from __future__ import division
import os
import signal
import sys
from googlecloudsdk.core import log
def HandleInterrupt(signal_number=None, frame=None):
"""Handles keyboard interrupts (aka SIGINT, ^C).
Disables the stack trace when a command is killed by keyboard interrupt.
Args:
signal_number: The interrupt signal number.
frame: The signal stack frame context.
"""
del signal_number, frame # currently unused
message = '\n\nCommand killed by keyboard interrupt\n'
try:
log.err.Print(message)
except NameError:
sys.stderr.write(message)
# Kill ourselves with SIGINT so our parent can detect that we exited because
# of a signal. SIG_DFL disables further KeyboardInterrupt exceptions.
signal.signal(signal.SIGINT, signal.SIG_DFL)
os.kill(os.getpid(), signal.SIGINT)
# Just in case the kill failed ...
sys.exit(1)
def InstallHandler():
"""Installs the default Cloud SDK keyboard interrupt handler."""
try:
signal.signal(signal.SIGINT, HandleInterrupt)
except ValueError:
# Signal cannot be sent from non-main threads. Integration testing will
# run parallel threads for performance reasons, occasionally hitting this
# exception. Should not be reached in production.
pass
| [
"signal.signal",
"sys.stderr.write",
"googlecloudsdk.core.log.err.Print",
"os.getpid",
"sys.exit"
] | [((1421, 1465), 'signal.signal', 'signal.signal', (['signal.SIGINT', 'signal.SIG_DFL'], {}), '(signal.SIGINT, signal.SIG_DFL)\n', (1434, 1465), False, 'import signal\n'), ((1543, 1554), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (1551, 1554), False, 'import sys\n'), ((1195, 1217), 'googlecloudsdk.core.log.err.Print', 'log.err.Print', (['message'], {}), '(message)\n', (1208, 1217), False, 'from googlecloudsdk.core import log\n'), ((1476, 1487), 'os.getpid', 'os.getpid', ([], {}), '()\n', (1485, 1487), False, 'import os\n'), ((1657, 1702), 'signal.signal', 'signal.signal', (['signal.SIGINT', 'HandleInterrupt'], {}), '(signal.SIGINT, HandleInterrupt)\n', (1670, 1702), False, 'import signal\n'), ((1242, 1267), 'sys.stderr.write', 'sys.stderr.write', (['message'], {}), '(message)\n', (1258, 1267), False, 'import sys\n')] |