Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line after this snippet: <|code_start|>#-----------------------------------------------------------------------------
# Copyright (c) 2014, HFTools Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
basepath = os.path.split(__file__)[0]
def make_array(a):
dims = (aobj.DimSweep("f", len(a)),
aobj.DimMatrix_i("i", 2),
aobj.DimMatrix_j("j", 2))
return aobj.hfarray(a, dims=dims)
<|code_end|>
using the current file's imports:
import os
import numpy as np
import hftools.dataset.arrayobj as aobj
import hftools.networks.spar_functions as spfun
from hftools.testing import TestCase
and any relevant context from other files:
# Path: hftools/testing/common.py
# class TestCase(unittest.TestCase):
# def assertAllclose(self, a, b, rtol=1e-05, atol=1e-08, msg=None):
# a = np.asanyarray(a)
# b = np.asanyarray(b)
# if msg is None:
# msg = "a (%s) not close to b (%s)" % (a, b)
# self.assertTrue(np.allclose(a, b, rtol, atol), msg)
#
# def assertIsNotInstance(self, obj, cls):
# self.assertFalse(isinstance(obj, cls))
#
# def assertIsInstance(self, obj, cls, msg=None):
# """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
# default message."""
# if not isinstance(obj, cls):
# arg = (unittest.case.safe_repr(obj), cls)
# standardMsg = '%s is not an instance of %r' % arg
# self.fail(self._formatMessage(msg, standardMsg))
#
# def assertHFToolsWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsWarning)
# self.assertRaises(HFToolsWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsWarning)
#
# def assertHFToolsDeprecationWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsDeprecationWarning)
# self.assertRaises(HFToolsDeprecationWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsDeprecationWarning)
. Output only the next line. | class Test_cascade(TestCase): |
Continue the code snippet: <|code_start|> dim_data = list(dim_data)
self._data = tuple(flatten(dim_data))
self._name = dim_name
self._unit = dim_unit
self._outputformat = dim_outputformat
@property
def data(self):
if len(self._data) == 0:
d = np.array([])
elif isinstance(self._data[0], (np.datetime64, datetime.datetime)):
d = np.asarray(self._data, np.dtype("datetime64[us]"))
else:
d = np.asarray(self._data)
return d
@property
def name(self):
return self._name
@property
def unit(self):
return self._unit
@property
def outputformat(self):
if self._outputformat is None:
if is_integer(self._data[0]):
return "%d"
<|code_end|>
. Use current file imports:
import datetime
import numpy as np
import six
from hftools.utils import is_numlike, is_integer, deprecate
from hftools.py3compat import integer_types
and context (classes, functions, or code) from other files:
# Path: hftools/utils.py
# def is_numlike(a):
# if isinstance(a, np.ndarray):
# return np.issubdtype(a.dtype, np.number)
# else:
# return np.issubdtype(np.array(a).dtype, np.number)
#
# def is_integer(a):
# if isinstance(a, np.ndarray):
# return a.dtype.kind == "i"
# else:
# return isinstance(a, int)
#
# def deprecate(msg):
# warnings.warn(msg, HFToolsDeprecationWarning)
#
# Path: hftools/py3compat.py
# DEFAULT_ENCODING = "cp1252"
# PY3 = True
# PY3 = False
# def no_code(x, encoding=None):
# def decode(s, encoding=None):
# def encode(u, encoding=None):
# def cast_unicode(s, encoding=None):
# def cast_bytes(s, encoding=None):
# def reraise(tp, value, tb=None):
# def popen(command):
# def popen(command):
# def print(*k, **kw):
# def cast_str(s, encoding=None):
. Output only the next line. | elif is_numlike(self._data[0]): |
Given the following code snippet before the placeholder: <|code_start|> dim_data = [dim_data.tolist()]
if not isinstance(dim_data, (list, tuple)):
dim_data = list(dim_data)
self._data = tuple(flatten(dim_data))
self._name = dim_name
self._unit = dim_unit
self._outputformat = dim_outputformat
@property
def data(self):
if len(self._data) == 0:
d = np.array([])
elif isinstance(self._data[0], (np.datetime64, datetime.datetime)):
d = np.asarray(self._data, np.dtype("datetime64[us]"))
else:
d = np.asarray(self._data)
return d
@property
def name(self):
return self._name
@property
def unit(self):
return self._unit
@property
def outputformat(self):
if self._outputformat is None:
<|code_end|>
, predict the next line using imports from the current file:
import datetime
import numpy as np
import six
from hftools.utils import is_numlike, is_integer, deprecate
from hftools.py3compat import integer_types
and context including class names, function names, and sometimes code from other files:
# Path: hftools/utils.py
# def is_numlike(a):
# if isinstance(a, np.ndarray):
# return np.issubdtype(a.dtype, np.number)
# else:
# return np.issubdtype(np.array(a).dtype, np.number)
#
# def is_integer(a):
# if isinstance(a, np.ndarray):
# return a.dtype.kind == "i"
# else:
# return isinstance(a, int)
#
# def deprecate(msg):
# warnings.warn(msg, HFToolsDeprecationWarning)
#
# Path: hftools/py3compat.py
# DEFAULT_ENCODING = "cp1252"
# PY3 = True
# PY3 = False
# def no_code(x, encoding=None):
# def decode(s, encoding=None):
# def encode(u, encoding=None):
# def cast_unicode(s, encoding=None):
# def cast_bytes(s, encoding=None):
# def reraise(tp, value, tb=None):
# def popen(command):
# def popen(command):
# def print(*k, **kw):
# def cast_str(s, encoding=None):
. Output only the next line. | if is_integer(self._data[0]): |
Predict the next line after this snippet: <|code_start|># -*- coding: ISO-8859-1 -*-
#-----------------------------------------------------------------------------
# Copyright (c) 2014, HFTools Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
u"""
dim
========
.. autoclass:: DimBase
"""
def dims_has_complex(dims):
for dim in reversed(dims):
dims = (ComplexDerivAxis, ComplexIndepAxis, ComplexDiagAxis)
if isinstance(dim, dims):
return True
return False
def info_has_complex(info):
<|code_end|>
using the current file's imports:
import datetime
import numpy as np
import six
from hftools.utils import is_numlike, is_integer, deprecate
from hftools.py3compat import integer_types
and any relevant context from other files:
# Path: hftools/utils.py
# def is_numlike(a):
# if isinstance(a, np.ndarray):
# return np.issubdtype(a.dtype, np.number)
# else:
# return np.issubdtype(np.array(a).dtype, np.number)
#
# def is_integer(a):
# if isinstance(a, np.ndarray):
# return a.dtype.kind == "i"
# else:
# return isinstance(a, int)
#
# def deprecate(msg):
# warnings.warn(msg, HFToolsDeprecationWarning)
#
# Path: hftools/py3compat.py
# DEFAULT_ENCODING = "cp1252"
# PY3 = True
# PY3 = False
# def no_code(x, encoding=None):
# def decode(s, encoding=None):
# def encode(u, encoding=None):
# def cast_unicode(s, encoding=None):
# def cast_bytes(s, encoding=None):
# def reraise(tp, value, tb=None):
# def popen(command):
# def popen(command):
# def print(*k, **kw):
# def cast_str(s, encoding=None):
. Output only the next line. | deprecate("info_has_complex is deprecated") |
Given the following code snippet before the placeholder: <|code_start|> yield subitem
else:
yield item
class DimBase(object):
sortprio = 0
def __init__(self, Name, data=None, unit=None, name=None,
outputformat=None):
if isinstance(Name, DimBase):
dim_data = Name.data
dim_name = Name.name
dim_unit = Name.unit
dim_outputformat = Name.outputformat
else:
dim_data = data
dim_name = Name
dim_unit = unit
dim_outputformat = outputformat
if data is not None:
dim_data = data
if unit is not None:
dim_unit = unit
if name is not None:
dim_name = name
if outputformat is not None:
dim_outputformat = outputformat
<|code_end|>
, predict the next line using imports from the current file:
import datetime
import numpy as np
import six
from hftools.utils import is_numlike, is_integer, deprecate
from hftools.py3compat import integer_types
and context including class names, function names, and sometimes code from other files:
# Path: hftools/utils.py
# def is_numlike(a):
# if isinstance(a, np.ndarray):
# return np.issubdtype(a.dtype, np.number)
# else:
# return np.issubdtype(np.array(a).dtype, np.number)
#
# def is_integer(a):
# if isinstance(a, np.ndarray):
# return a.dtype.kind == "i"
# else:
# return isinstance(a, int)
#
# def deprecate(msg):
# warnings.warn(msg, HFToolsDeprecationWarning)
#
# Path: hftools/py3compat.py
# DEFAULT_ENCODING = "cp1252"
# PY3 = True
# PY3 = False
# def no_code(x, encoding=None):
# def decode(s, encoding=None):
# def encode(u, encoding=None):
# def cast_unicode(s, encoding=None):
# def cast_bytes(s, encoding=None):
# def reraise(tp, value, tb=None):
# def popen(command):
# def popen(command):
# def print(*k, **kw):
# def cast_str(s, encoding=None):
. Output only the next line. | if isinstance(dim_data, integer_types): |
Given the following code snippet before the placeholder: <|code_start|> The S-parameters of S are scaled such that the highest eigenvalue of S'
becomes |lambda|max < 1 - delta.
"""
eig = np.linalg.eigvals
out = []
for s in S:
lambda_max = max(abs(eig(s)))
if lambda_max > 1:
out.append(s / lambda_max * (1 - delta))
else:
out.append(s)
return S.__class__(out, dims=S.dims)
def make_reciprocal(S):
s12 = S[..., 0, 1]
s21 = S[..., 1, 0]
S12 = np.sqrt(s12 * s21)
A12 = np.where(np.angle(S12 / s12) < 1, S12, -S12)
S[..., 0, 1] = A12
S[..., 1, 0] = A12
return S
def check_passive(S):
eig = np.linalg.eigvals
out = []
for s in S:
lambda_max = max(abs(eig(s)))
out.append(lambda_max)
<|code_end|>
, predict the next line using imports from the current file:
import numpy as np
from hftools.dataset import make_same_dims, _DimMatrix, hfarray
from hftools.math import det, inv, matrix_multiply
and context including class names, function names, and sometimes code from other files:
# Path: hftools/dataset/dim.py
# class _DimMatrix(DiagAxis):
# sortprio = 1000
#
# Path: hftools/dataset/arrayobj.py
# class hfarray(_hfarray):
# def __new__(subtype, data, dims=None, dtype=None, copy=True, order=None,
# subok=False, ndmin=0, unit=None, outputformat=None, info=None):
# if hasattr(data, "__hfarray__"):
# data, dims = data.__hfarray__()
# if unit is None and len(dims) == 1:
# unit = dims[0].unit
# if outputformat is None and len(dims) == 1:
# outputformat = dims[0].outputformat
# return _hfarray.__new__(subtype, data, dims=dims, dtype=dtype,
# copy=copy, order=order, subok=subok,
# ndmin=ndmin, unit=unit,
# outputformat=outputformat, info=info)
#
# def make_same_dims(A, B):
# u"""Anropas med lista med *Arrays*. Returnerar arrayer som har samma *dims*
# dvs vi har anropat change_shape med en *newinfo* som innehaller unionen
# av de Axis objekt som finns i *dims* av *Arrayerna*.
#
# """
# if not isinstance(B, _hfarray):
# B = A.__class__(B.view(), dims=A.dims, copy=False)
# return make_same_dims_list((A, B))
#
# Path: hftools/math.py
# def det(A):
# det = linalg.det
# result = det(A)
# result = hfarray(result, dims=A.dims[:-2])
# return result
#
# def inv(A):
# inv = linalg.inv
# result = inv(A)
# result = hfarray(result, dims=A.dims)
# return result
#
# def matrix_multiply(a, b):
# """Multiply arrays of matrices.
#
# a and b are hfarrays containing dimensions DimMatrix_i and DimMatrix_j.
# Matrix multiplication is done by broadcasting the other dimensions first.
# """
# A, B = make_same_dims(a, b)
# res = np.einsum("...ij,...jk->...ik", A, B)
# return hfarray(res, dims=A.dims)
. Output only the next line. | return hfarray(out, dims=S.dims[:1]) |
Predict the next line for this snippet: <|code_start|># -*- coding: ISO-8859-1 -*-
#-----------------------------------------------------------------------------
# Copyright (c) 2014, HFTools Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
def cascadeS(S1, S2, *rest):
"""Cascade arrays containing S-parameters.
"""
S1, S2 = make_same_dims(S1, S2)
neworder = tuple([x for x in S1.dims if not isinstance(x, _DimMatrix)])
S1 = S1.reorder_dimensions(*neworder)
S2 = S2.reorder_dimensions(*neworder)
denom = (1 - S1[..., 1, 1] * S2[..., 0, 0])
<|code_end|>
with the help of current file imports:
import numpy as np
from hftools.dataset import make_same_dims, _DimMatrix, hfarray
from hftools.math import det, inv, matrix_multiply
and context from other files:
# Path: hftools/dataset/dim.py
# class _DimMatrix(DiagAxis):
# sortprio = 1000
#
# Path: hftools/dataset/arrayobj.py
# class hfarray(_hfarray):
# def __new__(subtype, data, dims=None, dtype=None, copy=True, order=None,
# subok=False, ndmin=0, unit=None, outputformat=None, info=None):
# if hasattr(data, "__hfarray__"):
# data, dims = data.__hfarray__()
# if unit is None and len(dims) == 1:
# unit = dims[0].unit
# if outputformat is None and len(dims) == 1:
# outputformat = dims[0].outputformat
# return _hfarray.__new__(subtype, data, dims=dims, dtype=dtype,
# copy=copy, order=order, subok=subok,
# ndmin=ndmin, unit=unit,
# outputformat=outputformat, info=info)
#
# def make_same_dims(A, B):
# u"""Anropas med lista med *Arrays*. Returnerar arrayer som har samma *dims*
# dvs vi har anropat change_shape med en *newinfo* som innehaller unionen
# av de Axis objekt som finns i *dims* av *Arrayerna*.
#
# """
# if not isinstance(B, _hfarray):
# B = A.__class__(B.view(), dims=A.dims, copy=False)
# return make_same_dims_list((A, B))
#
# Path: hftools/math.py
# def det(A):
# det = linalg.det
# result = det(A)
# result = hfarray(result, dims=A.dims[:-2])
# return result
#
# def inv(A):
# inv = linalg.inv
# result = inv(A)
# result = hfarray(result, dims=A.dims)
# return result
#
# def matrix_multiply(a, b):
# """Multiply arrays of matrices.
#
# a and b are hfarrays containing dimensions DimMatrix_i and DimMatrix_j.
# Matrix multiplication is done by broadcasting the other dimensions first.
# """
# A, B = make_same_dims(a, b)
# res = np.einsum("...ij,...jk->...ik", A, B)
# return hfarray(res, dims=A.dims)
, which may contain function names, class names, or code. Output only the next line. | s1det = det(S1) |
Using the snippet: <|code_start|> neworder = tuple([x for x in X.dims if not isinstance(x, _DimMatrix)])
X = X.reorder_dimensions(*neworder)
e = e.reorder_dimensions(*neworder)
klass, dims = X.__class__, X.dims
# X, e = X.view(type=ndarray), X.view(type=ndarray)
denom = (e[..., 0, 1] * e[..., 1, 0] -
e[..., 0, 0] * e[..., 1, 1] +
e[..., 0, 0] * X[..., 1, 1])
maxshape = tuple(max(x) for x in zip(X.shape, e.shape))
res = X.__class__(np.zeros(maxshape, X.dtype), dims=X.dims)
res[..., 0, 0] = (-X[..., 0, 1] * X[..., 1, 0] * e[..., 0, 0])
res[..., 0, 1] = (X[..., 0, 1] * e[..., 1, 0])
res[..., 1, 0] = (X[..., 1, 0] * e[..., 0, 1])
res[..., 1, 1] = (X[..., 1, 1] - e[..., 1, 1])
res = res / denom
res[..., 0, 0] = res[..., 0, 0] + X[..., 0, 0]
res = klass(res, dims=dims)
return res
def deembed(e1, S, e2):
"""deembeds twoports, e1 and e2, at each port of S using deembed(e1,S,e2)
e1, e2, S should all be on the four-matrix form:
Frequency is first index, measurement sweep is second index and port
indices are third and fourth index. Assuming same shape of all inputs
"""
return deembedright(deembedleft(e1, S), e2)
def switch_correct(b, a):
<|code_end|>
, determine the next line of code. You have imports:
import numpy as np
from hftools.dataset import make_same_dims, _DimMatrix, hfarray
from hftools.math import det, inv, matrix_multiply
and context (class names, function names, or code) available:
# Path: hftools/dataset/dim.py
# class _DimMatrix(DiagAxis):
# sortprio = 1000
#
# Path: hftools/dataset/arrayobj.py
# class hfarray(_hfarray):
# def __new__(subtype, data, dims=None, dtype=None, copy=True, order=None,
# subok=False, ndmin=0, unit=None, outputformat=None, info=None):
# if hasattr(data, "__hfarray__"):
# data, dims = data.__hfarray__()
# if unit is None and len(dims) == 1:
# unit = dims[0].unit
# if outputformat is None and len(dims) == 1:
# outputformat = dims[0].outputformat
# return _hfarray.__new__(subtype, data, dims=dims, dtype=dtype,
# copy=copy, order=order, subok=subok,
# ndmin=ndmin, unit=unit,
# outputformat=outputformat, info=info)
#
# def make_same_dims(A, B):
# u"""Anropas med lista med *Arrays*. Returnerar arrayer som har samma *dims*
# dvs vi har anropat change_shape med en *newinfo* som innehaller unionen
# av de Axis objekt som finns i *dims* av *Arrayerna*.
#
# """
# if not isinstance(B, _hfarray):
# B = A.__class__(B.view(), dims=A.dims, copy=False)
# return make_same_dims_list((A, B))
#
# Path: hftools/math.py
# def det(A):
# det = linalg.det
# result = det(A)
# result = hfarray(result, dims=A.dims[:-2])
# return result
#
# def inv(A):
# inv = linalg.inv
# result = inv(A)
# result = hfarray(result, dims=A.dims)
# return result
#
# def matrix_multiply(a, b):
# """Multiply arrays of matrices.
#
# a and b are hfarrays containing dimensions DimMatrix_i and DimMatrix_j.
# Matrix multiplication is done by broadcasting the other dimensions first.
# """
# A, B = make_same_dims(a, b)
# res = np.einsum("...ij,...jk->...ik", A, B)
# return hfarray(res, dims=A.dims)
. Output only the next line. | Sm = matrix_multiply(b, inv(a)) |
Next line prediction: <|code_start|> neworder = tuple([x for x in X.dims if not isinstance(x, _DimMatrix)])
X = X.reorder_dimensions(*neworder)
e = e.reorder_dimensions(*neworder)
klass, dims = X.__class__, X.dims
# X, e = X.view(type=ndarray), X.view(type=ndarray)
denom = (e[..., 0, 1] * e[..., 1, 0] -
e[..., 0, 0] * e[..., 1, 1] +
e[..., 0, 0] * X[..., 1, 1])
maxshape = tuple(max(x) for x in zip(X.shape, e.shape))
res = X.__class__(np.zeros(maxshape, X.dtype), dims=X.dims)
res[..., 0, 0] = (-X[..., 0, 1] * X[..., 1, 0] * e[..., 0, 0])
res[..., 0, 1] = (X[..., 0, 1] * e[..., 1, 0])
res[..., 1, 0] = (X[..., 1, 0] * e[..., 0, 1])
res[..., 1, 1] = (X[..., 1, 1] - e[..., 1, 1])
res = res / denom
res[..., 0, 0] = res[..., 0, 0] + X[..., 0, 0]
res = klass(res, dims=dims)
return res
def deembed(e1, S, e2):
"""deembeds twoports, e1 and e2, at each port of S using deembed(e1,S,e2)
e1, e2, S should all be on the four-matrix form:
Frequency is first index, measurement sweep is second index and port
indices are third and fourth index. Assuming same shape of all inputs
"""
return deembedright(deembedleft(e1, S), e2)
def switch_correct(b, a):
<|code_end|>
. Use current file imports:
(import numpy as np
from hftools.dataset import make_same_dims, _DimMatrix, hfarray
from hftools.math import det, inv, matrix_multiply)
and context including class names, function names, or small code snippets from other files:
# Path: hftools/dataset/dim.py
# class _DimMatrix(DiagAxis):
# sortprio = 1000
#
# Path: hftools/dataset/arrayobj.py
# class hfarray(_hfarray):
# def __new__(subtype, data, dims=None, dtype=None, copy=True, order=None,
# subok=False, ndmin=0, unit=None, outputformat=None, info=None):
# if hasattr(data, "__hfarray__"):
# data, dims = data.__hfarray__()
# if unit is None and len(dims) == 1:
# unit = dims[0].unit
# if outputformat is None and len(dims) == 1:
# outputformat = dims[0].outputformat
# return _hfarray.__new__(subtype, data, dims=dims, dtype=dtype,
# copy=copy, order=order, subok=subok,
# ndmin=ndmin, unit=unit,
# outputformat=outputformat, info=info)
#
# def make_same_dims(A, B):
# u"""Anropas med lista med *Arrays*. Returnerar arrayer som har samma *dims*
# dvs vi har anropat change_shape med en *newinfo* som innehaller unionen
# av de Axis objekt som finns i *dims* av *Arrayerna*.
#
# """
# if not isinstance(B, _hfarray):
# B = A.__class__(B.view(), dims=A.dims, copy=False)
# return make_same_dims_list((A, B))
#
# Path: hftools/math.py
# def det(A):
# det = linalg.det
# result = det(A)
# result = hfarray(result, dims=A.dims[:-2])
# return result
#
# def inv(A):
# inv = linalg.inv
# result = inv(A)
# result = hfarray(result, dims=A.dims)
# return result
#
# def matrix_multiply(a, b):
# """Multiply arrays of matrices.
#
# a and b are hfarrays containing dimensions DimMatrix_i and DimMatrix_j.
# Matrix multiplication is done by broadcasting the other dimensions first.
# """
# A, B = make_same_dims(a, b)
# res = np.einsum("...ij,...jk->...ik", A, B)
# return hfarray(res, dims=A.dims)
. Output only the next line. | Sm = matrix_multiply(b, inv(a)) |
Continue the code snippet: <|code_start|># -*- coding: ISO-8859-1 -*-
#-----------------------------------------------------------------------------
# Copyright (c) 2014, HFTools Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
load_tests = make_load_tests(utils)
basepath = os.path.split(__file__)[0]
class Test_random_array(TestCase):
def test_float_1(self):
res = testing.random_array(5, 7, 2)
self.assertEqual(res.ndim, 5)
self.assertTrue(np.all([x >= 2 and x <= 7 for x in res.shape]))
self.assertFalse(np.iscomplexobj(res), msg=str(res))
<|code_end|>
. Use current file imports:
import os
import numpy as np
import hftools.utils as utils
import hftools.testing as testing
from hftools.dataset import hfarray
from hftools.testing import TestCase, make_load_tests, expectedFailure
and context (classes, functions, or code) from other files:
# Path: hftools/dataset/arrayobj.py
# class hfarray(_hfarray):
# def __new__(subtype, data, dims=None, dtype=None, copy=True, order=None,
# subok=False, ndmin=0, unit=None, outputformat=None, info=None):
# if hasattr(data, "__hfarray__"):
# data, dims = data.__hfarray__()
# if unit is None and len(dims) == 1:
# unit = dims[0].unit
# if outputformat is None and len(dims) == 1:
# outputformat = dims[0].outputformat
# return _hfarray.__new__(subtype, data, dims=dims, dtype=dtype,
# copy=copy, order=order, subok=subok,
# ndmin=ndmin, unit=unit,
# outputformat=outputformat, info=info)
#
# Path: hftools/testing/common.py
# class TestCase(unittest.TestCase):
# def assertAllclose(self, a, b, rtol=1e-05, atol=1e-08, msg=None):
# def assertIsNotInstance(self, obj, cls):
# def assertIsInstance(self, obj, cls, msg=None):
# def assertHFToolsWarning(self, funk, *k, **kw):
# def assertHFToolsDeprecationWarning(self, funk, *k, **kw):
# def get_label():
# def make_load_tests(module):
# def load_tests(loader, standard_tests, pattern):
# def _random_array(shape):
# def random_array(N, maxsize=6, minsize=1):
# def random_complex_array(N, maxsize=6, minsize=1):
# def random_value_array_from_dims(dims, mean=0, scale=1):
# def random_value_array(N, maxsize, minsize=1):
# def random_complex_value_array(N, maxsize, minsize=1):
# def random_dims(N, maxsize, minsize=1):
# def random_complex_matrix(N, maxsize, minsize=1, Nmatrix=2, Nmatrixj=None):
# def SKIP(self): # pragma: no cover
# _IDX = 1
. Output only the next line. | self.assertIsNotInstance(res, hfarray) |
Given the following code snippet before the placeholder: <|code_start|>
class Test_random_complex_array(TestCase):
def test_float_1(self):
res = testing.random_complex_array(5, 7, 2)
self.assertEqual(res.ndim, 5)
self.assertTrue(np.all([x >= 2 and x <= 7 for x in res.shape]))
self.assertTrue(np.iscomplexobj(res))
self.assertIsNotInstance(res, hfarray)
class Test_random_complex_value_array(TestCase):
def test_float_1(self):
res = testing.random_complex_value_array(5, 7, 2)
self.assertEqual(res.ndim, 5)
self.assertTrue(np.all([x >= 2 and x <= 7 for x in res.shape]))
self.assertTrue(np.iscomplexobj(res))
self.assertIsInstance(res, hfarray)
class Test_random_complex_matrix(TestCase):
def test_float_1(self):
res = testing.random_complex_matrix(5, 7, 2, 2)
self.assertEqual(res.ndim, 5 + 2)
self.assertTrue(np.all([x >= 2 and x <= 7 for x in res.shape[:-2]]))
self.assertTrue(np.iscomplexobj(res))
self.assertIsInstance(res, hfarray)
class Test_testcase(TestCase):
<|code_end|>
, predict the next line using imports from the current file:
import os
import numpy as np
import hftools.utils as utils
import hftools.testing as testing
from hftools.dataset import hfarray
from hftools.testing import TestCase, make_load_tests, expectedFailure
and context including class names, function names, and sometimes code from other files:
# Path: hftools/dataset/arrayobj.py
# class hfarray(_hfarray):
# def __new__(subtype, data, dims=None, dtype=None, copy=True, order=None,
# subok=False, ndmin=0, unit=None, outputformat=None, info=None):
# if hasattr(data, "__hfarray__"):
# data, dims = data.__hfarray__()
# if unit is None and len(dims) == 1:
# unit = dims[0].unit
# if outputformat is None and len(dims) == 1:
# outputformat = dims[0].outputformat
# return _hfarray.__new__(subtype, data, dims=dims, dtype=dtype,
# copy=copy, order=order, subok=subok,
# ndmin=ndmin, unit=unit,
# outputformat=outputformat, info=info)
#
# Path: hftools/testing/common.py
# class TestCase(unittest.TestCase):
# def assertAllclose(self, a, b, rtol=1e-05, atol=1e-08, msg=None):
# def assertIsNotInstance(self, obj, cls):
# def assertIsInstance(self, obj, cls, msg=None):
# def assertHFToolsWarning(self, funk, *k, **kw):
# def assertHFToolsDeprecationWarning(self, funk, *k, **kw):
# def get_label():
# def make_load_tests(module):
# def load_tests(loader, standard_tests, pattern):
# def _random_array(shape):
# def random_array(N, maxsize=6, minsize=1):
# def random_complex_array(N, maxsize=6, minsize=1):
# def random_value_array_from_dims(dims, mean=0, scale=1):
# def random_value_array(N, maxsize, minsize=1):
# def random_complex_value_array(N, maxsize, minsize=1):
# def random_dims(N, maxsize, minsize=1):
# def random_complex_matrix(N, maxsize, minsize=1, Nmatrix=2, Nmatrixj=None):
# def SKIP(self): # pragma: no cover
# _IDX = 1
. Output only the next line. | @expectedFailure |
Given snippet: <|code_start|>
def string_number_with_unit_to_value(string_number):
if isrealnumber(string_number):
return string_number
res = reg_value.match(string_number)
if res:
value = float(res.group())
reg_unit = re.compile(r"\s*[[]?([a-zA-Z%]+)[]]?")
unit_res = reg_unit.match(string_number[res.span()[-1]:])
if unit_res:
unit = unit_res.group()
else:
unit = None
else:
msg = "Could not convert %r to value with unit" % (string_number)
raise ValueError(msg)
return convert_with_unit(unit, value)
def convert_with_unit(unit, value):
if unit is None:
return hftools.dataset.hfarray(value, unit=None)
unit = unit.strip()
if unit:
mul, unit = unit_to_multiplier(unit)
else:
mul = 1
unit = None
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import imp
import re
import numpy as np
import hftools.dataset
from hftools.utils import to_numeric, isrealnumber
and context:
# Path: hftools/utils.py
# def to_numeric(value, error=True):
# """Translate string *value* to numeric type if possible
# """
# try:
# return value + 0
# except TypeError:
# pass
# try:
# return int(value)
# except ValueError:
# try:
# return float(value)
# except ValueError:
# try:
# if dateregexp.match(value):
# return np.datetime64(value)
# else:
# raise ValueError
# except (ValueError, TypeError):
# if error:
# raise
# return value
#
# def isrealnumber(x):
# return isinstance(x, (int, float))
which might include code, classes, or functions. Output only the next line. | return hftools.dataset.hfarray(to_numeric(value, error=True) * mul, |
Given the code snippet: <|code_start|>
for u in siunit_names:
for p, val in siprefixes.items():
setattr(siunits, p + u, val)
def unit_to_multiplier(unit):
"""Convert a unit to multiplier with baseunit
"""
unit = unit.strip()
if len(unit) == 1:
if unit == "%":
return .01, None
if unit == "#":
return 1, None
else:
return 1, unit
elif len(unit) >= 2 and unit[0] in siprefixes:
if unit[1:] in siunit_names:
return siprefixes[unit[0]], unit[1:]
else:
return 1, unit
else:
return 1, unit
reg_value = re.compile(r"[-+0-9.]+[eE]?[-+0-9]?")
reg_unit = re.compile(r"\s*[[]?([a-zA-Z%]+)[]]?")
def string_number_with_unit_to_value(string_number):
<|code_end|>
, generate the next line using the imports in this file:
import imp
import re
import numpy as np
import hftools.dataset
from hftools.utils import to_numeric, isrealnumber
and context (functions, classes, or occasionally code) from other files:
# Path: hftools/utils.py
# def to_numeric(value, error=True):
# """Translate string *value* to numeric type if possible
# """
# try:
# return value + 0
# except TypeError:
# pass
# try:
# return int(value)
# except ValueError:
# try:
# return float(value)
# except ValueError:
# try:
# if dateregexp.match(value):
# return np.datetime64(value)
# else:
# raise ValueError
# except (ValueError, TypeError):
# if error:
# raise
# return value
#
# def isrealnumber(x):
# return isinstance(x, (int, float))
. Output only the next line. | if isrealnumber(string_number): |
Predict the next line for this snippet: <|code_start|>from __future__ import print_function
#-----------------------------------------------------------------------------
# Copyright (c) 2014, HFTools Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
basepath = os.path.split(__file__)[0]
load_tests = make_load_tests(aobj)
<|code_end|>
with the help of current file imports:
import os
import warnings
import numpy as np
import hftools.dataset.arrayobj as aobj
import hftools.dataset.dim as dim
import hftools.dataset as ds
from numpy import newaxis
from hftools.testing import TestCase, make_load_tests
from hftools.testing import random_value_array
from hftools.utils import reset_hftools_warnings, HFToolsDeprecationWarning
and context from other files:
# Path: hftools/testing/common.py
# class TestCase(unittest.TestCase):
# def assertAllclose(self, a, b, rtol=1e-05, atol=1e-08, msg=None):
# a = np.asanyarray(a)
# b = np.asanyarray(b)
# if msg is None:
# msg = "a (%s) not close to b (%s)" % (a, b)
# self.assertTrue(np.allclose(a, b, rtol, atol), msg)
#
# def assertIsNotInstance(self, obj, cls):
# self.assertFalse(isinstance(obj, cls))
#
# def assertIsInstance(self, obj, cls, msg=None):
# """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
# default message."""
# if not isinstance(obj, cls):
# arg = (unittest.case.safe_repr(obj), cls)
# standardMsg = '%s is not an instance of %r' % arg
# self.fail(self._formatMessage(msg, standardMsg))
#
# def assertHFToolsWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsWarning)
# self.assertRaises(HFToolsWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsWarning)
#
# def assertHFToolsDeprecationWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsDeprecationWarning)
# self.assertRaises(HFToolsDeprecationWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsDeprecationWarning)
#
# def make_load_tests(module):
# """Add doctests to tests for module
#
# usage::
# load_tests = make_load_tests(module)
# """
# warnings.simplefilter("error", HFToolsWarning)
# warnings.simplefilter("error", HFToolsDeprecationWarning)
# # warnings.simplefilter("error", DeprecationWarning)
#
# def load_tests(loader, standard_tests, pattern):
# suite = unittest.TestSuite()
# suite.addTests(standard_tests)
# DocTests = doctest.DocTestSuite(module)
# suite.addTests(DocTests)
# return suite
# return load_tests
#
# Path: hftools/testing/common.py
# def random_value_array(N, maxsize, minsize=1):
# dims = random_dims(N, maxsize, minsize)
# return random_value_array_from_dims(dims)
#
# Path: hftools/utils.py
# def reset_hftools_warnings():
# def timestamp(highres=False):
# def warn(msg):
# def deprecate(msg):
# def isnumber(x):
# def isrealnumber(x):
# def isnumber(x):
# def isrealnumber(x):
# def is_numlike(a):
# def is_integer(a):
# def to_numeric(value, error=True):
# def stable_uniq(data):
# def uniq(data):
# def chop(x, rtol=1e-9, atol=1e-15):
# def make_dirs(*pathsegments):
# def split_num(string):
# def lex_order(lista):
# def glob(pat):
# def beep(freq=None, duration=50):
# def beep(freq=None, duration=50):
# def flatten(lista):
, which may contain function names, class names, or code. Output only the next line. | class TestDims(TestCase): |
Given the following code snippet before the placeholder: <|code_start|> self.assertAllclose(w, np.array([[[1, 0], [0, 0]],
[[2, 0], [0, 0]],
[[3, 0], [0, 0]]]))
self.assertEqual(w.dims, (ds.DiagAxis("f", 3),) + ds.CPLX)
def test_5(self):
w = aobj.change_shape(self.ca, (ds.DiagAxis("f", 3),) + ds.CPLX)
self.assertAllclose(w, np.array([[[1, -10], [10, 1]],
[[2, -20], [20, 2]],
[[3, -30], [30, 3]]]))
self.assertEqual(w.dims, (ds.DiagAxis("f", 3),) + ds.CPLX)
def test_error_1(self):
dims = (ds.DiagAxis("f", 3), )
self.assertRaises(ValueError, aobj.change_shape, self.b, dims)
class MakeData(object):
def setUp(self):
self.adims = (aobj.DimSweep("f", 1),
aobj.DimMatrix_i("i", 2),
aobj.DimMatrix_j("j", 2))
self.a = aobj.hfarray([[[0, 0j], [0, 0]]], dims=self.adims)
self.bdims = (aobj.DimSweep("f", 10),
aobj.DimMatrix_i("i", 2),
aobj.DimMatrix_j("j", 2))
self.b = aobj.hfarray(np.array([[[1, 2 + 0j], [3, 4]]]) +
np.arange(10)[:, newaxis, newaxis],
dims=self.bdims)
<|code_end|>
, predict the next line using imports from the current file:
import os
import warnings
import numpy as np
import hftools.dataset.arrayobj as aobj
import hftools.dataset.dim as dim
import hftools.dataset as ds
from numpy import newaxis
from hftools.testing import TestCase, make_load_tests
from hftools.testing import random_value_array
from hftools.utils import reset_hftools_warnings, HFToolsDeprecationWarning
and context including class names, function names, and sometimes code from other files:
# Path: hftools/testing/common.py
# class TestCase(unittest.TestCase):
# def assertAllclose(self, a, b, rtol=1e-05, atol=1e-08, msg=None):
# a = np.asanyarray(a)
# b = np.asanyarray(b)
# if msg is None:
# msg = "a (%s) not close to b (%s)" % (a, b)
# self.assertTrue(np.allclose(a, b, rtol, atol), msg)
#
# def assertIsNotInstance(self, obj, cls):
# self.assertFalse(isinstance(obj, cls))
#
# def assertIsInstance(self, obj, cls, msg=None):
# """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
# default message."""
# if not isinstance(obj, cls):
# arg = (unittest.case.safe_repr(obj), cls)
# standardMsg = '%s is not an instance of %r' % arg
# self.fail(self._formatMessage(msg, standardMsg))
#
# def assertHFToolsWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsWarning)
# self.assertRaises(HFToolsWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsWarning)
#
# def assertHFToolsDeprecationWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsDeprecationWarning)
# self.assertRaises(HFToolsDeprecationWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsDeprecationWarning)
#
# def make_load_tests(module):
# """Add doctests to tests for module
#
# usage::
# load_tests = make_load_tests(module)
# """
# warnings.simplefilter("error", HFToolsWarning)
# warnings.simplefilter("error", HFToolsDeprecationWarning)
# # warnings.simplefilter("error", DeprecationWarning)
#
# def load_tests(loader, standard_tests, pattern):
# suite = unittest.TestSuite()
# suite.addTests(standard_tests)
# DocTests = doctest.DocTestSuite(module)
# suite.addTests(DocTests)
# return suite
# return load_tests
#
# Path: hftools/testing/common.py
# def random_value_array(N, maxsize, minsize=1):
# dims = random_dims(N, maxsize, minsize)
# return random_value_array_from_dims(dims)
#
# Path: hftools/utils.py
# def reset_hftools_warnings():
# def timestamp(highres=False):
# def warn(msg):
# def deprecate(msg):
# def isnumber(x):
# def isrealnumber(x):
# def isnumber(x):
# def isrealnumber(x):
# def is_numlike(a):
# def is_integer(a):
# def to_numeric(value, error=True):
# def stable_uniq(data):
# def uniq(data):
# def chop(x, rtol=1e-9, atol=1e-15):
# def make_dirs(*pathsegments):
# def split_num(string):
# def lex_order(lista):
# def glob(pat):
# def beep(freq=None, duration=50):
# def beep(freq=None, duration=50):
# def flatten(lista):
. Output only the next line. | self.c, = aobj.make_same_dims_list([random_value_array(4, 5)]) |
Using the snippet: <|code_start|> def test_init_error_1(self):
a = np.array([[[1, 2, 3]] * 3] * 2)
self.assertRaises(aobj.DimensionMismatchError, aobj.hfarray, a)
def test_indexing_1(self):
self.assertAllclose(self.b[0], np.array([[1, 2 + 0j], [3, 4]]))
def test_indexing_2(self):
facit = (np.array([[[1, 2 + 0j], [3, 4]]]) +
np.arange(2)[:, newaxis, newaxis])
self.assertAllclose(self.b[:2], facit)
def test_indexing_3(self):
facit = (np.array([[[1, 2 + 0j], [3, 4]]]) +
np.arange(0, 10, 2)[:, newaxis, newaxis])
self.assertAllclose(self.b[::2], facit)
def test_verify_dimension_1(self):
self.assertIsNone(self.a.verify_dimension())
def test_verify_dimension_2(self):
self.assertIsNone(self.b.verify_dimension())
def test_verify_dimension_error_1(self):
self.a.dims = self.a.dims[:-1]
self.assertRaises(aobj.HFArrayShapeDimsMismatchError,
self.a.verify_dimension)
def test_info_deprecation_1(self):
a = aobj.hfarray(1)
<|code_end|>
, determine the next line of code. You have imports:
import os
import warnings
import numpy as np
import hftools.dataset.arrayobj as aobj
import hftools.dataset.dim as dim
import hftools.dataset as ds
from numpy import newaxis
from hftools.testing import TestCase, make_load_tests
from hftools.testing import random_value_array
from hftools.utils import reset_hftools_warnings, HFToolsDeprecationWarning
and context (class names, function names, or code) available:
# Path: hftools/testing/common.py
# class TestCase(unittest.TestCase):
# def assertAllclose(self, a, b, rtol=1e-05, atol=1e-08, msg=None):
# a = np.asanyarray(a)
# b = np.asanyarray(b)
# if msg is None:
# msg = "a (%s) not close to b (%s)" % (a, b)
# self.assertTrue(np.allclose(a, b, rtol, atol), msg)
#
# def assertIsNotInstance(self, obj, cls):
# self.assertFalse(isinstance(obj, cls))
#
# def assertIsInstance(self, obj, cls, msg=None):
# """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
# default message."""
# if not isinstance(obj, cls):
# arg = (unittest.case.safe_repr(obj), cls)
# standardMsg = '%s is not an instance of %r' % arg
# self.fail(self._formatMessage(msg, standardMsg))
#
# def assertHFToolsWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsWarning)
# self.assertRaises(HFToolsWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsWarning)
#
# def assertHFToolsDeprecationWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsDeprecationWarning)
# self.assertRaises(HFToolsDeprecationWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsDeprecationWarning)
#
# def make_load_tests(module):
# """Add doctests to tests for module
#
# usage::
# load_tests = make_load_tests(module)
# """
# warnings.simplefilter("error", HFToolsWarning)
# warnings.simplefilter("error", HFToolsDeprecationWarning)
# # warnings.simplefilter("error", DeprecationWarning)
#
# def load_tests(loader, standard_tests, pattern):
# suite = unittest.TestSuite()
# suite.addTests(standard_tests)
# DocTests = doctest.DocTestSuite(module)
# suite.addTests(DocTests)
# return suite
# return load_tests
#
# Path: hftools/testing/common.py
# def random_value_array(N, maxsize, minsize=1):
# dims = random_dims(N, maxsize, minsize)
# return random_value_array_from_dims(dims)
#
# Path: hftools/utils.py
# def reset_hftools_warnings():
# def timestamp(highres=False):
# def warn(msg):
# def deprecate(msg):
# def isnumber(x):
# def isrealnumber(x):
# def isnumber(x):
# def isrealnumber(x):
# def is_numlike(a):
# def is_integer(a):
# def to_numeric(value, error=True):
# def stable_uniq(data):
# def uniq(data):
# def chop(x, rtol=1e-9, atol=1e-15):
# def make_dirs(*pathsegments):
# def split_num(string):
# def lex_order(lista):
# def glob(pat):
# def beep(freq=None, duration=50):
# def beep(freq=None, duration=50):
# def flatten(lista):
. Output only the next line. | reset_hftools_warnings() |
Continue the code snippet: <|code_start|> def test_indexing_1(self):
self.assertAllclose(self.b[0], np.array([[1, 2 + 0j], [3, 4]]))
def test_indexing_2(self):
facit = (np.array([[[1, 2 + 0j], [3, 4]]]) +
np.arange(2)[:, newaxis, newaxis])
self.assertAllclose(self.b[:2], facit)
def test_indexing_3(self):
facit = (np.array([[[1, 2 + 0j], [3, 4]]]) +
np.arange(0, 10, 2)[:, newaxis, newaxis])
self.assertAllclose(self.b[::2], facit)
def test_verify_dimension_1(self):
self.assertIsNone(self.a.verify_dimension())
def test_verify_dimension_2(self):
self.assertIsNone(self.b.verify_dimension())
def test_verify_dimension_error_1(self):
self.a.dims = self.a.dims[:-1]
self.assertRaises(aobj.HFArrayShapeDimsMismatchError,
self.a.verify_dimension)
def test_info_deprecation_1(self):
a = aobj.hfarray(1)
reset_hftools_warnings()
self.assertHFToolsDeprecationWarning(lambda x: x.info, a)
with warnings.catch_warnings():
warnings.resetwarnings()
<|code_end|>
. Use current file imports:
import os
import warnings
import numpy as np
import hftools.dataset.arrayobj as aobj
import hftools.dataset.dim as dim
import hftools.dataset as ds
from numpy import newaxis
from hftools.testing import TestCase, make_load_tests
from hftools.testing import random_value_array
from hftools.utils import reset_hftools_warnings, HFToolsDeprecationWarning
and context (classes, functions, or code) from other files:
# Path: hftools/testing/common.py
# class TestCase(unittest.TestCase):
# def assertAllclose(self, a, b, rtol=1e-05, atol=1e-08, msg=None):
# a = np.asanyarray(a)
# b = np.asanyarray(b)
# if msg is None:
# msg = "a (%s) not close to b (%s)" % (a, b)
# self.assertTrue(np.allclose(a, b, rtol, atol), msg)
#
# def assertIsNotInstance(self, obj, cls):
# self.assertFalse(isinstance(obj, cls))
#
# def assertIsInstance(self, obj, cls, msg=None):
# """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
# default message."""
# if not isinstance(obj, cls):
# arg = (unittest.case.safe_repr(obj), cls)
# standardMsg = '%s is not an instance of %r' % arg
# self.fail(self._formatMessage(msg, standardMsg))
#
# def assertHFToolsWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsWarning)
# self.assertRaises(HFToolsWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsWarning)
#
# def assertHFToolsDeprecationWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsDeprecationWarning)
# self.assertRaises(HFToolsDeprecationWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsDeprecationWarning)
#
# def make_load_tests(module):
# """Add doctests to tests for module
#
# usage::
# load_tests = make_load_tests(module)
# """
# warnings.simplefilter("error", HFToolsWarning)
# warnings.simplefilter("error", HFToolsDeprecationWarning)
# # warnings.simplefilter("error", DeprecationWarning)
#
# def load_tests(loader, standard_tests, pattern):
# suite = unittest.TestSuite()
# suite.addTests(standard_tests)
# DocTests = doctest.DocTestSuite(module)
# suite.addTests(DocTests)
# return suite
# return load_tests
#
# Path: hftools/testing/common.py
# def random_value_array(N, maxsize, minsize=1):
# dims = random_dims(N, maxsize, minsize)
# return random_value_array_from_dims(dims)
#
# Path: hftools/utils.py
# def reset_hftools_warnings():
# def timestamp(highres=False):
# def warn(msg):
# def deprecate(msg):
# def isnumber(x):
# def isrealnumber(x):
# def isnumber(x):
# def isrealnumber(x):
# def is_numlike(a):
# def is_integer(a):
# def to_numeric(value, error=True):
# def stable_uniq(data):
# def uniq(data):
# def chop(x, rtol=1e-9, atol=1e-15):
# def make_dirs(*pathsegments):
# def split_num(string):
# def lex_order(lista):
# def glob(pat):
# def beep(freq=None, duration=50):
# def beep(freq=None, duration=50):
# def flatten(lista):
. Output only the next line. | warnings.simplefilter("ignore", HFToolsDeprecationWarning) |
Based on the snippet: <|code_start|>#-----------------------------------------------------------------------------
# Copyright (c) 2014, HFTools Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
basepath = os.path.split(__file__)[0]
class TestComment1(TestCase):
def setUp(self):
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import pdb
import numpy as np
import hftools.dataset.comments as comments
import hftools.dataset.arrayobj as aobj
from hftools.dataset.comments import Comments
from hftools.testing import TestCase
and context (classes, functions, sometimes code) from other files:
# Path: hftools/dataset/comments.py
# class Comments(object):
# comment_reg = re.compile(r"([^:]+)[ \t]*[:][ \t]*(.*)")
# spacing_reg = re.compile(r"[ \t]+")
# width = 76
#
# def __init__(self, fullcomments=None, **kw):
# self.fullcomments = []
# self.property = {}
# self.property.update(kw)
# if fullcomments is not None:
# self.add_from_comments(fullcomments)
#
# def add_from_comment(self, comment):
# comment = comment.lstrip("!").strip()
# if comment:
# for key, v in process_comment(comment).items():
# self.property[key] = v
# self.fullcomments.append(comment)
#
# def add_from_comments(self, comments):
# for comment in comments:
# self.add_from_comment(comment)
#
# def extend(self, comment):
# self.fullcomments.extend(comment.fullcomments)
# for k, v in comment.property.items():
# self.property[k] = v
#
# def copy(self):
# out = Comments()
# out.fullcomments = self.fullcomments[:]
# out.property = self.property.copy()
# return out
#
# def table(self):
# if not self.property:
# return []
# keycolwid = max([len(x) for x in self.property.keys()])
# valuecolwid = self.width - keycolwid
# keyfmt = "%%-%ds" % keycolwid
# valuefmt = "%%-%ds" % (valuecolwid)
# table = [(" Comments ".center(self.width + 1, "-"),),
# (keyfmt % ("Key".center(keycolwid, " ")),
# valuefmt % ("Value".center(valuecolwid, " "))),
# ("-" * keycolwid,
# "-" * valuecolwid)]
# for key, value in sorted(self.property.items()):
# if hasattr(value, "strip"):
# value = value.strip()[:valuecolwid]
# table.append((keyfmt % key, valuefmt % (value)))
# key = ""
# return [" ".join(x) for x in table]
#
# def __repr__(self):
# return "\n".join(self.table())
#
# Path: hftools/testing/common.py
# class TestCase(unittest.TestCase):
# def assertAllclose(self, a, b, rtol=1e-05, atol=1e-08, msg=None):
# a = np.asanyarray(a)
# b = np.asanyarray(b)
# if msg is None:
# msg = "a (%s) not close to b (%s)" % (a, b)
# self.assertTrue(np.allclose(a, b, rtol, atol), msg)
#
# def assertIsNotInstance(self, obj, cls):
# self.assertFalse(isinstance(obj, cls))
#
# def assertIsInstance(self, obj, cls, msg=None):
# """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
# default message."""
# if not isinstance(obj, cls):
# arg = (unittest.case.safe_repr(obj), cls)
# standardMsg = '%s is not an instance of %r' % arg
# self.fail(self._formatMessage(msg, standardMsg))
#
# def assertHFToolsWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsWarning)
# self.assertRaises(HFToolsWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsWarning)
#
# def assertHFToolsDeprecationWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsDeprecationWarning)
# self.assertRaises(HFToolsDeprecationWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsDeprecationWarning)
. Output only the next line. | self.comment = Comments(["V1:10", "V2[V]:13", "V3 [V] : 14"]) |
Next line prediction: <|code_start|>#-----------------------------------------------------------------------------
# Copyright (c) 2014, HFTools Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
basepath = os.path.split(__file__)[0]
load_tests = make_load_tests(ddim)
class Test_Dim_init(TestCase):
def setUp(self):
<|code_end|>
. Use current file imports:
(import os
import warnings
import numpy as np
import hftools.dataset.dim as ddim
from hftools.dataset.dim import DimSweep, ComplexDiagAxis, ComplexIndepAxis,\
ComplexDerivAxis, dims_has_complex, info_has_complex
from hftools.testing import TestCase, make_load_tests
from hftools.dataset import hfarray
from hftools.utils import reset_hftools_warnings, HFToolsDeprecationWarning)
and context including class names, function names, or small code snippets from other files:
# Path: hftools/dataset/dim.py
# class DimSweep(DiagAxis):
# pass
#
# class ComplexDiagAxis(_DiagAxis):
# sortprio = 2000
# _indep_axis = ComplexIndepAxis
# _deriv_axis = ComplexDerivAxis
#
# class ComplexIndepAxis(_IndepAxis):
# sortprio = 2001
# pass
#
# class ComplexDerivAxis(_DerivAxis):
# sortprio = 2002
# pass
#
# def dims_has_complex(dims):
# for dim in reversed(dims):
# dims = (ComplexDerivAxis, ComplexIndepAxis, ComplexDiagAxis)
# if isinstance(dim, dims):
# return True
# return False
#
# def info_has_complex(info):
# deprecate("info_has_complex is deprecated")
# return dims_has_complex(info)
#
# Path: hftools/testing/common.py
# class TestCase(unittest.TestCase):
# def assertAllclose(self, a, b, rtol=1e-05, atol=1e-08, msg=None):
# a = np.asanyarray(a)
# b = np.asanyarray(b)
# if msg is None:
# msg = "a (%s) not close to b (%s)" % (a, b)
# self.assertTrue(np.allclose(a, b, rtol, atol), msg)
#
# def assertIsNotInstance(self, obj, cls):
# self.assertFalse(isinstance(obj, cls))
#
# def assertIsInstance(self, obj, cls, msg=None):
# """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
# default message."""
# if not isinstance(obj, cls):
# arg = (unittest.case.safe_repr(obj), cls)
# standardMsg = '%s is not an instance of %r' % arg
# self.fail(self._formatMessage(msg, standardMsg))
#
# def assertHFToolsWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsWarning)
# self.assertRaises(HFToolsWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsWarning)
#
# def assertHFToolsDeprecationWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsDeprecationWarning)
# self.assertRaises(HFToolsDeprecationWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsDeprecationWarning)
#
# def make_load_tests(module):
# """Add doctests to tests for module
#
# usage::
# load_tests = make_load_tests(module)
# """
# warnings.simplefilter("error", HFToolsWarning)
# warnings.simplefilter("error", HFToolsDeprecationWarning)
# # warnings.simplefilter("error", DeprecationWarning)
#
# def load_tests(loader, standard_tests, pattern):
# suite = unittest.TestSuite()
# suite.addTests(standard_tests)
# DocTests = doctest.DocTestSuite(module)
# suite.addTests(DocTests)
# return suite
# return load_tests
#
# Path: hftools/dataset/arrayobj.py
# class hfarray(_hfarray):
# def __new__(subtype, data, dims=None, dtype=None, copy=True, order=None,
# subok=False, ndmin=0, unit=None, outputformat=None, info=None):
# if hasattr(data, "__hfarray__"):
# data, dims = data.__hfarray__()
# if unit is None and len(dims) == 1:
# unit = dims[0].unit
# if outputformat is None and len(dims) == 1:
# outputformat = dims[0].outputformat
# return _hfarray.__new__(subtype, data, dims=dims, dtype=dtype,
# copy=copy, order=order, subok=subok,
# ndmin=ndmin, unit=unit,
# outputformat=outputformat, info=info)
#
# Path: hftools/utils.py
# def reset_hftools_warnings():
# def timestamp(highres=False):
# def warn(msg):
# def deprecate(msg):
# def isnumber(x):
# def isrealnumber(x):
# def isnumber(x):
# def isrealnumber(x):
# def is_numlike(a):
# def is_integer(a):
# def to_numeric(value, error=True):
# def stable_uniq(data):
# def uniq(data):
# def chop(x, rtol=1e-9, atol=1e-15):
# def make_dirs(*pathsegments):
# def split_num(string):
# def lex_order(lista):
# def glob(pat):
# def beep(freq=None, duration=50):
# def beep(freq=None, duration=50):
# def flatten(lista):
. Output only the next line. | self.dim = DimSweep("a", 10, unit="Hz") |
Predict the next line after this snippet: <|code_start|> deriv = ddim.DimMatrix_Deriv_j
class Test_dims_has_complex(TestCase):
def _helper(self, dims):
self.assertTrue(dims_has_complex(dims))
def _helper_false(self, dims):
self.assertFalse(dims_has_complex(dims))
def test_1(self):
self._helper_false((DimSweep("d", 3),))
def test_2(self):
self._helper((DimSweep("d", 3), ComplexDiagAxis("cplx", 2)))
def test_3(self):
self._helper((DimSweep("d", 3), ComplexIndepAxis("cplx", 2)))
def test_4(self):
self._helper((DimSweep("d", 3), ComplexDerivAxis("cplx", 2)))
def test_5(self):
self._helper((DimSweep("d", 3), ComplexIndepAxis("cplx", 2),
ComplexDerivAxis("cplx", 2)))
class Test_info_has_complex(Test_dims_has_complex):
def _helper(self, dims):
reset_hftools_warnings()
<|code_end|>
using the current file's imports:
import os
import warnings
import numpy as np
import hftools.dataset.dim as ddim
from hftools.dataset.dim import DimSweep, ComplexDiagAxis, ComplexIndepAxis,\
ComplexDerivAxis, dims_has_complex, info_has_complex
from hftools.testing import TestCase, make_load_tests
from hftools.dataset import hfarray
from hftools.utils import reset_hftools_warnings, HFToolsDeprecationWarning
and any relevant context from other files:
# Path: hftools/dataset/dim.py
# class DimSweep(DiagAxis):
# pass
#
# class ComplexDiagAxis(_DiagAxis):
# sortprio = 2000
# _indep_axis = ComplexIndepAxis
# _deriv_axis = ComplexDerivAxis
#
# class ComplexIndepAxis(_IndepAxis):
# sortprio = 2001
# pass
#
# class ComplexDerivAxis(_DerivAxis):
# sortprio = 2002
# pass
#
# def dims_has_complex(dims):
# for dim in reversed(dims):
# dims = (ComplexDerivAxis, ComplexIndepAxis, ComplexDiagAxis)
# if isinstance(dim, dims):
# return True
# return False
#
# def info_has_complex(info):
# deprecate("info_has_complex is deprecated")
# return dims_has_complex(info)
#
# Path: hftools/testing/common.py
# class TestCase(unittest.TestCase):
# def assertAllclose(self, a, b, rtol=1e-05, atol=1e-08, msg=None):
# a = np.asanyarray(a)
# b = np.asanyarray(b)
# if msg is None:
# msg = "a (%s) not close to b (%s)" % (a, b)
# self.assertTrue(np.allclose(a, b, rtol, atol), msg)
#
# def assertIsNotInstance(self, obj, cls):
# self.assertFalse(isinstance(obj, cls))
#
# def assertIsInstance(self, obj, cls, msg=None):
# """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
# default message."""
# if not isinstance(obj, cls):
# arg = (unittest.case.safe_repr(obj), cls)
# standardMsg = '%s is not an instance of %r' % arg
# self.fail(self._formatMessage(msg, standardMsg))
#
# def assertHFToolsWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsWarning)
# self.assertRaises(HFToolsWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsWarning)
#
# def assertHFToolsDeprecationWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsDeprecationWarning)
# self.assertRaises(HFToolsDeprecationWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsDeprecationWarning)
#
# def make_load_tests(module):
# """Add doctests to tests for module
#
# usage::
# load_tests = make_load_tests(module)
# """
# warnings.simplefilter("error", HFToolsWarning)
# warnings.simplefilter("error", HFToolsDeprecationWarning)
# # warnings.simplefilter("error", DeprecationWarning)
#
# def load_tests(loader, standard_tests, pattern):
# suite = unittest.TestSuite()
# suite.addTests(standard_tests)
# DocTests = doctest.DocTestSuite(module)
# suite.addTests(DocTests)
# return suite
# return load_tests
#
# Path: hftools/dataset/arrayobj.py
# class hfarray(_hfarray):
# def __new__(subtype, data, dims=None, dtype=None, copy=True, order=None,
# subok=False, ndmin=0, unit=None, outputformat=None, info=None):
# if hasattr(data, "__hfarray__"):
# data, dims = data.__hfarray__()
# if unit is None and len(dims) == 1:
# unit = dims[0].unit
# if outputformat is None and len(dims) == 1:
# outputformat = dims[0].outputformat
# return _hfarray.__new__(subtype, data, dims=dims, dtype=dtype,
# copy=copy, order=order, subok=subok,
# ndmin=ndmin, unit=unit,
# outputformat=outputformat, info=info)
#
# Path: hftools/utils.py
# def reset_hftools_warnings():
# def timestamp(highres=False):
# def warn(msg):
# def deprecate(msg):
# def isnumber(x):
# def isrealnumber(x):
# def isnumber(x):
# def isrealnumber(x):
# def is_numlike(a):
# def is_integer(a):
# def to_numeric(value, error=True):
# def stable_uniq(data):
# def uniq(data):
# def chop(x, rtol=1e-9, atol=1e-15):
# def make_dirs(*pathsegments):
# def split_num(string):
# def lex_order(lista):
# def glob(pat):
# def beep(freq=None, duration=50):
# def beep(freq=None, duration=50):
# def flatten(lista):
. Output only the next line. | self.assertHFToolsDeprecationWarning(info_has_complex, dims) |
Given the following code snippet before the placeholder: <|code_start|> indep = ddim.DimMatrix_Indep_j
deriv = ddim.DimMatrix_Deriv_j
class Test_dims_has_complex(TestCase):
def _helper(self, dims):
self.assertTrue(dims_has_complex(dims))
def _helper_false(self, dims):
self.assertFalse(dims_has_complex(dims))
def test_1(self):
self._helper_false((DimSweep("d", 3),))
def test_2(self):
self._helper((DimSweep("d", 3), ComplexDiagAxis("cplx", 2)))
def test_3(self):
self._helper((DimSweep("d", 3), ComplexIndepAxis("cplx", 2)))
def test_4(self):
self._helper((DimSweep("d", 3), ComplexDerivAxis("cplx", 2)))
def test_5(self):
self._helper((DimSweep("d", 3), ComplexIndepAxis("cplx", 2),
ComplexDerivAxis("cplx", 2)))
class Test_info_has_complex(Test_dims_has_complex):
def _helper(self, dims):
<|code_end|>
, predict the next line using imports from the current file:
import os
import warnings
import numpy as np
import hftools.dataset.dim as ddim
from hftools.dataset.dim import DimSweep, ComplexDiagAxis, ComplexIndepAxis,\
ComplexDerivAxis, dims_has_complex, info_has_complex
from hftools.testing import TestCase, make_load_tests
from hftools.dataset import hfarray
from hftools.utils import reset_hftools_warnings, HFToolsDeprecationWarning
and context including class names, function names, and sometimes code from other files:
# Path: hftools/dataset/dim.py
# class DimSweep(DiagAxis):
# pass
#
# class ComplexDiagAxis(_DiagAxis):
# sortprio = 2000
# _indep_axis = ComplexIndepAxis
# _deriv_axis = ComplexDerivAxis
#
# class ComplexIndepAxis(_IndepAxis):
# sortprio = 2001
# pass
#
# class ComplexDerivAxis(_DerivAxis):
# sortprio = 2002
# pass
#
# def dims_has_complex(dims):
# for dim in reversed(dims):
# dims = (ComplexDerivAxis, ComplexIndepAxis, ComplexDiagAxis)
# if isinstance(dim, dims):
# return True
# return False
#
# def info_has_complex(info):
# deprecate("info_has_complex is deprecated")
# return dims_has_complex(info)
#
# Path: hftools/testing/common.py
# class TestCase(unittest.TestCase):
# def assertAllclose(self, a, b, rtol=1e-05, atol=1e-08, msg=None):
# a = np.asanyarray(a)
# b = np.asanyarray(b)
# if msg is None:
# msg = "a (%s) not close to b (%s)" % (a, b)
# self.assertTrue(np.allclose(a, b, rtol, atol), msg)
#
# def assertIsNotInstance(self, obj, cls):
# self.assertFalse(isinstance(obj, cls))
#
# def assertIsInstance(self, obj, cls, msg=None):
# """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
# default message."""
# if not isinstance(obj, cls):
# arg = (unittest.case.safe_repr(obj), cls)
# standardMsg = '%s is not an instance of %r' % arg
# self.fail(self._formatMessage(msg, standardMsg))
#
# def assertHFToolsWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsWarning)
# self.assertRaises(HFToolsWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsWarning)
#
# def assertHFToolsDeprecationWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsDeprecationWarning)
# self.assertRaises(HFToolsDeprecationWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsDeprecationWarning)
#
# def make_load_tests(module):
# """Add doctests to tests for module
#
# usage::
# load_tests = make_load_tests(module)
# """
# warnings.simplefilter("error", HFToolsWarning)
# warnings.simplefilter("error", HFToolsDeprecationWarning)
# # warnings.simplefilter("error", DeprecationWarning)
#
# def load_tests(loader, standard_tests, pattern):
# suite = unittest.TestSuite()
# suite.addTests(standard_tests)
# DocTests = doctest.DocTestSuite(module)
# suite.addTests(DocTests)
# return suite
# return load_tests
#
# Path: hftools/dataset/arrayobj.py
# class hfarray(_hfarray):
# def __new__(subtype, data, dims=None, dtype=None, copy=True, order=None,
# subok=False, ndmin=0, unit=None, outputformat=None, info=None):
# if hasattr(data, "__hfarray__"):
# data, dims = data.__hfarray__()
# if unit is None and len(dims) == 1:
# unit = dims[0].unit
# if outputformat is None and len(dims) == 1:
# outputformat = dims[0].outputformat
# return _hfarray.__new__(subtype, data, dims=dims, dtype=dtype,
# copy=copy, order=order, subok=subok,
# ndmin=ndmin, unit=unit,
# outputformat=outputformat, info=info)
#
# Path: hftools/utils.py
# def reset_hftools_warnings():
# def timestamp(highres=False):
# def warn(msg):
# def deprecate(msg):
# def isnumber(x):
# def isrealnumber(x):
# def isnumber(x):
# def isrealnumber(x):
# def is_numlike(a):
# def is_integer(a):
# def to_numeric(value, error=True):
# def stable_uniq(data):
# def uniq(data):
# def chop(x, rtol=1e-9, atol=1e-15):
# def make_dirs(*pathsegments):
# def split_num(string):
# def lex_order(lista):
# def glob(pat):
# def beep(freq=None, duration=50):
# def beep(freq=None, duration=50):
# def flatten(lista):
. Output only the next line. | reset_hftools_warnings() |
Predict the next line after this snippet: <|code_start|># Copyright (c) 2014, HFTools Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
def reset_hftools_warnings():
try:
__warningregistry__.clear()
except NameError:
pass
def timestamp(highres=False):
"""Return time stamp string for current time
Example: "20121026T080312"
"""
if highres:
return datetime.datetime.now().strftime("%Y%m%dT%H%M%S.%f")[:-3]
else:
return datetime.datetime.now().strftime("%Y%m%dT%H%M%S")
def warn(msg):
<|code_end|>
using the current file's imports:
import abc
import datetime
import glob as glob_module
import os
import re
import warnings
import numpy as np
import winsound
from hftools.core.exceptions import HFToolsWarning, HFToolsDeprecationWarning
from hftools.py3compat import PY3
and any relevant context from other files:
# Path: hftools/core/exceptions.py
# class HFToolsWarning(Warning):
# pass
#
# class HFToolsDeprecationWarning(DeprecationWarning):
# pass
#
# Path: hftools/py3compat.py
# PY3 = True
. Output only the next line. | warnings.warn(msg, HFToolsWarning) |
Here is a snippet: <|code_start|># The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
def reset_hftools_warnings():
try:
__warningregistry__.clear()
except NameError:
pass
def timestamp(highres=False):
"""Return time stamp string for current time
Example: "20121026T080312"
"""
if highres:
return datetime.datetime.now().strftime("%Y%m%dT%H%M%S.%f")[:-3]
else:
return datetime.datetime.now().strftime("%Y%m%dT%H%M%S")
def warn(msg):
warnings.warn(msg, HFToolsWarning)
def deprecate(msg):
<|code_end|>
. Write the next line using the current file imports:
import abc
import datetime
import glob as glob_module
import os
import re
import warnings
import numpy as np
import winsound
from hftools.core.exceptions import HFToolsWarning, HFToolsDeprecationWarning
from hftools.py3compat import PY3
and context from other files:
# Path: hftools/core/exceptions.py
# class HFToolsWarning(Warning):
# pass
#
# class HFToolsDeprecationWarning(DeprecationWarning):
# pass
#
# Path: hftools/py3compat.py
# PY3 = True
, which may include functions, classes, or code. Output only the next line. | warnings.warn(msg, HFToolsDeprecationWarning) |
Here is a snippet: <|code_start|>
def reset_hftools_warnings():
try:
__warningregistry__.clear()
except NameError:
pass
def timestamp(highres=False):
"""Return time stamp string for current time
Example: "20121026T080312"
"""
if highres:
return datetime.datetime.now().strftime("%Y%m%dT%H%M%S.%f")[:-3]
else:
return datetime.datetime.now().strftime("%Y%m%dT%H%M%S")
def warn(msg):
warnings.warn(msg, HFToolsWarning)
def deprecate(msg):
warnings.warn(msg, HFToolsDeprecationWarning)
<|code_end|>
. Write the next line using the current file imports:
import abc
import datetime
import glob as glob_module
import os
import re
import warnings
import numpy as np
import winsound
from hftools.core.exceptions import HFToolsWarning, HFToolsDeprecationWarning
from hftools.py3compat import PY3
and context from other files:
# Path: hftools/core/exceptions.py
# class HFToolsWarning(Warning):
# pass
#
# class HFToolsDeprecationWarning(DeprecationWarning):
# pass
#
# Path: hftools/py3compat.py
# PY3 = True
, which may include functions, classes, or code. Output only the next line. | if PY3: |
Next line prediction: <|code_start|>WR340 WG9A R26 2.20 3.30 1.736 3.471 3.400 1.700
WR284 WG10 R32 2.60 3.95 2.078 4.156 2.840 1.340
WR229 WG11A R40 3.30 4.90 2.577 5.154 2.290 1.145
WR187 WG12 R48 3.95 5.85 3.153 6.305 1.872 0.872
WR159 WG13 R58 4.90 7.05 3.712 7.423 1.590 0.795
WR137 WG14 R70 5.85 8.20 4.301 8.603 1.372 0.622
WR112 WG15 R84 7.05 10.00 5.26 10.52 1.122 0.497
WR90 WG16 R100 8.20 12.40 6.557 13.114 0.900 0.400
WR75 WG17 R120 10.00 15.00 7.869 15.737 0.750 0.375
WR62 WG18 R140 12.40 18.00 9.488 18.976 0.622 0.311
WR51 WG19 R180 15.00 22.00 11.572 23.143 0.510 0.255
WR42 WG20 R220 18.00 26.50 14.051 28.102 0.420 0.170
WR34 WG21 R260 22.00 33.00 17.357 34.715 0.340 0.170
WR28 WG22 R320 26.50 40.00 21.077 42.154 0.280 0.140
WR22 WG23 R400 33.00 50.00 26.346 52.692 0.224 0.112
WR19 WG24 R500 40.00 60.00 31.391 62.782 0.188 0.094
WR15 WG25 R620 50.00 75.00 39.875 79.75 0.148 0.074
WR12 WG26 R740 60.00 90.00 48.373 96.746 0.122 0.061
WR10 WG27 R900 75.00 110.00 59.015 118.03 0.100 0.050
WR8 WG28 R1200 90.00 140.00 73.768 147.536 0.080 0.040
WR7 WG29 R1400 112.00 172.00 90.791 181.583 0.0650 0.0325
WR5 WG30 R1800 140.00 220.00 115.714 231.429 0.0510 0.0255
WR4 WG31 R2200 172.00 260.00 137.243 274.485 0.0430 0.0215
WR3 WG32 R2600 220.00 330.00 173.571 347.143 0.0340 0.0170"""
WaveGuide = namedtuple("WaveGuide", "EIA RCSC IEC f0 f1 fcl fcu a b")
WR = dict()
for rad in waveguides.strip().split("\n")[1:]:
<|code_end|>
. Use current file imports:
(from collections import namedtuple
from hftools.utils import to_numeric)
and context including class names, function names, or small code snippets from other files:
# Path: hftools/utils.py
# def to_numeric(value, error=True):
# """Translate string *value* to numeric type if possible
# """
# try:
# return value + 0
# except TypeError:
# pass
# try:
# return int(value)
# except ValueError:
# try:
# return float(value)
# except ValueError:
# try:
# if dateregexp.match(value):
# return np.datetime64(value)
# else:
# raise ValueError
# except (ValueError, TypeError):
# if error:
# raise
# return value
. Output only the next line. | x = [to_numeric(x, False) for x in rad.split()] |
Predict the next line after this snippet: <|code_start|># -*- coding: ISO-8859-1 -*-
#-----------------------------------------------------------------------------
# Copyright (c) 2014, HFTools Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
basepath = os.path.split(__file__)[0]
network_classes = [v for k, v in mp.__dict__.items()
if (isinstance(v, type) and
issubclass(v, mp._MultiPortArray) and
v is not mp._MultiPortArray and
v is not mp._TwoPortArray)]
<|code_end|>
using the current file's imports:
import os
import warnings
import numpy as np
import hftools.dataset.arrayobj as aobj
import hftools.networks.multiports as mp
from hftools.testing import TestCase, random_complex_matrix
from hftools.utils import HFToolsWarning
and any relevant context from other files:
# Path: hftools/testing/common.py
# class TestCase(unittest.TestCase):
# def assertAllclose(self, a, b, rtol=1e-05, atol=1e-08, msg=None):
# a = np.asanyarray(a)
# b = np.asanyarray(b)
# if msg is None:
# msg = "a (%s) not close to b (%s)" % (a, b)
# self.assertTrue(np.allclose(a, b, rtol, atol), msg)
#
# def assertIsNotInstance(self, obj, cls):
# self.assertFalse(isinstance(obj, cls))
#
# def assertIsInstance(self, obj, cls, msg=None):
# """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
# default message."""
# if not isinstance(obj, cls):
# arg = (unittest.case.safe_repr(obj), cls)
# standardMsg = '%s is not an instance of %r' % arg
# self.fail(self._formatMessage(msg, standardMsg))
#
# def assertHFToolsWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsWarning)
# self.assertRaises(HFToolsWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsWarning)
#
# def assertHFToolsDeprecationWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsDeprecationWarning)
# self.assertRaises(HFToolsDeprecationWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsDeprecationWarning)
#
# def random_complex_matrix(N, maxsize, minsize=1, Nmatrix=2, Nmatrixj=None):
# if Nmatrixj is None: # pragma: no cover
# Nmatrixj = Nmatrix
# dims = (random_dims(N, maxsize, minsize) +
# (DimMatrix_i("i", Nmatrix), DimMatrix_j("j", Nmatrixj)))
# return (random_value_array_from_dims(dims) +
# random_value_array_from_dims(dims) * 1j)
#
# Path: hftools/utils.py
# def reset_hftools_warnings():
# def timestamp(highres=False):
# def warn(msg):
# def deprecate(msg):
# def isnumber(x):
# def isrealnumber(x):
# def isnumber(x):
# def isrealnumber(x):
# def is_numlike(a):
# def is_integer(a):
# def to_numeric(value, error=True):
# def stable_uniq(data):
# def uniq(data):
# def chop(x, rtol=1e-9, atol=1e-15):
# def make_dirs(*pathsegments):
# def split_num(string):
# def lex_order(lista):
# def glob(pat):
# def beep(freq=None, duration=50):
# def beep(freq=None, duration=50):
# def flatten(lista):
. Output only the next line. | class _Test_hfarray(TestCase): |
Using the snippet: <|code_start|>
class Test_TArray_1(Test_TwoPortArray):
cls = mp.TArray
class Test_TPArray_1(Test_TwoPortArray):
cls = mp.TpArray
class Test_unit_matrices(TestCase):
def test_unit_matrix(self):
m = mp.unit_matrix()
self.assertEqual(m.shape, (2, 2))
self.assertIsInstance(m, mp.SArray)
self.assertAllclose(m, [[1, 0], [0, 1]])
def test_unit_smatrix(self):
m = mp.unit_smatrix()
self.assertEqual(m.shape, (2, 2))
self.assertIsInstance(m, mp.SArray)
self.assertAllclose(m, [[0, 1], [1, 0]])
class TestConversions(TestCase):
"""test conversions by generating a random matrix of type startcls
and then for all networkclasses (stopclass) convert from startcls
to stopclass and back to startcls which should yield the same result.
"""
def setUp(self):
<|code_end|>
, determine the next line of code. You have imports:
import os
import warnings
import numpy as np
import hftools.dataset.arrayobj as aobj
import hftools.networks.multiports as mp
from hftools.testing import TestCase, random_complex_matrix
from hftools.utils import HFToolsWarning
and context (class names, function names, or code) available:
# Path: hftools/testing/common.py
# class TestCase(unittest.TestCase):
# def assertAllclose(self, a, b, rtol=1e-05, atol=1e-08, msg=None):
# a = np.asanyarray(a)
# b = np.asanyarray(b)
# if msg is None:
# msg = "a (%s) not close to b (%s)" % (a, b)
# self.assertTrue(np.allclose(a, b, rtol, atol), msg)
#
# def assertIsNotInstance(self, obj, cls):
# self.assertFalse(isinstance(obj, cls))
#
# def assertIsInstance(self, obj, cls, msg=None):
# """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
# default message."""
# if not isinstance(obj, cls):
# arg = (unittest.case.safe_repr(obj), cls)
# standardMsg = '%s is not an instance of %r' % arg
# self.fail(self._formatMessage(msg, standardMsg))
#
# def assertHFToolsWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsWarning)
# self.assertRaises(HFToolsWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsWarning)
#
# def assertHFToolsDeprecationWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsDeprecationWarning)
# self.assertRaises(HFToolsDeprecationWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsDeprecationWarning)
#
# def random_complex_matrix(N, maxsize, minsize=1, Nmatrix=2, Nmatrixj=None):
# if Nmatrixj is None: # pragma: no cover
# Nmatrixj = Nmatrix
# dims = (random_dims(N, maxsize, minsize) +
# (DimMatrix_i("i", Nmatrix), DimMatrix_j("j", Nmatrixj)))
# return (random_value_array_from_dims(dims) +
# random_value_array_from_dims(dims) * 1j)
#
# Path: hftools/utils.py
# def reset_hftools_warnings():
# def timestamp(highres=False):
# def warn(msg):
# def deprecate(msg):
# def isnumber(x):
# def isrealnumber(x):
# def isnumber(x):
# def isrealnumber(x):
# def is_numlike(a):
# def is_integer(a):
# def to_numeric(value, error=True):
# def stable_uniq(data):
# def uniq(data):
# def chop(x, rtol=1e-9, atol=1e-15):
# def make_dirs(*pathsegments):
# def split_num(string):
# def lex_order(lista):
# def glob(pat):
# def beep(freq=None, duration=50):
# def beep(freq=None, duration=50):
# def flatten(lista):
. Output only the next line. | self.a = random_complex_matrix(3, 4, 1, 2) |
Continue the code snippet: <|code_start|>basepath = os.path.split(__file__)[0]
network_classes = [v for k, v in mp.__dict__.items()
if (isinstance(v, type) and
issubclass(v, mp._MultiPortArray) and
v is not mp._MultiPortArray and
v is not mp._TwoPortArray)]
class _Test_hfarray(TestCase):
def setUp(self):
adims = (aobj.DimSweep("f", 1),
aobj.DimMatrix_i("i", 2),
aobj.DimMatrix_j("j", 2))
self.a = aobj.hfarray([[[1, 2 + 0j], [3, 4]]], dims=adims)
bdims = (aobj.DimSweep("f", 1),
aobj.DimMatrix_i("i", 3),
aobj.DimMatrix_j("j", 3))
self.b = aobj.hfarray([[[1, 2 + 0j, 3],
[4, 5, 6],
[7, 8, 9]]], dims=bdims)
self.adims = adims
self.bdims = bdims
class Test_info_deprecate(_Test_hfarray):
def test1(self):
self.assertHFToolsWarning(mp.SArray, self.a, info=self.adims)
with warnings.catch_warnings():
warnings.resetwarnings()
<|code_end|>
. Use current file imports:
import os
import warnings
import numpy as np
import hftools.dataset.arrayobj as aobj
import hftools.networks.multiports as mp
from hftools.testing import TestCase, random_complex_matrix
from hftools.utils import HFToolsWarning
and context (classes, functions, or code) from other files:
# Path: hftools/testing/common.py
# class TestCase(unittest.TestCase):
# def assertAllclose(self, a, b, rtol=1e-05, atol=1e-08, msg=None):
# a = np.asanyarray(a)
# b = np.asanyarray(b)
# if msg is None:
# msg = "a (%s) not close to b (%s)" % (a, b)
# self.assertTrue(np.allclose(a, b, rtol, atol), msg)
#
# def assertIsNotInstance(self, obj, cls):
# self.assertFalse(isinstance(obj, cls))
#
# def assertIsInstance(self, obj, cls, msg=None):
# """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
# default message."""
# if not isinstance(obj, cls):
# arg = (unittest.case.safe_repr(obj), cls)
# standardMsg = '%s is not an instance of %r' % arg
# self.fail(self._formatMessage(msg, standardMsg))
#
# def assertHFToolsWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsWarning)
# self.assertRaises(HFToolsWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsWarning)
#
# def assertHFToolsDeprecationWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsDeprecationWarning)
# self.assertRaises(HFToolsDeprecationWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsDeprecationWarning)
#
# def random_complex_matrix(N, maxsize, minsize=1, Nmatrix=2, Nmatrixj=None):
# if Nmatrixj is None: # pragma: no cover
# Nmatrixj = Nmatrix
# dims = (random_dims(N, maxsize, minsize) +
# (DimMatrix_i("i", Nmatrix), DimMatrix_j("j", Nmatrixj)))
# return (random_value_array_from_dims(dims) +
# random_value_array_from_dims(dims) * 1j)
#
# Path: hftools/utils.py
# def reset_hftools_warnings():
# def timestamp(highres=False):
# def warn(msg):
# def deprecate(msg):
# def isnumber(x):
# def isrealnumber(x):
# def isnumber(x):
# def isrealnumber(x):
# def is_numlike(a):
# def is_integer(a):
# def to_numeric(value, error=True):
# def stable_uniq(data):
# def uniq(data):
# def chop(x, rtol=1e-9, atol=1e-15):
# def make_dirs(*pathsegments):
# def split_num(string):
# def lex_order(lista):
# def glob(pat):
# def beep(freq=None, duration=50):
# def beep(freq=None, duration=50):
# def flatten(lista):
. Output only the next line. | warnings.simplefilter("ignore", HFToolsWarning) |
Predict the next line after this snippet: <|code_start|> return _random_array(shape)
def random_complex_array(N, maxsize=6, minsize=1):
shape = tuple(x.data.shape[0] for x in random_dims(N, maxsize, minsize))
return _random_array(shape) + _random_array(shape) * 1j
def random_value_array_from_dims(dims, mean=0, scale=1):
shape = tuple(dim.data.shape[0] for dim in dims)
return hfarray(normal(size=shape) * scale + mean, dims)
##
## Random hfarrays
def random_value_array(N, maxsize, minsize=1):
dims = random_dims(N, maxsize, minsize)
return random_value_array_from_dims(dims)
def random_complex_value_array(N, maxsize, minsize=1):
dims = random_dims(N, maxsize, minsize)
return (random_value_array_from_dims(dims) +
random_value_array_from_dims(dims) * 1j)
def random_dims(N, maxsize, minsize=1):
shape = tuple(randint(minsize, maxsize, size=N))
label = get_label()
<|code_end|>
using the current file's imports:
import doctest
import random
import warnings
import unittest
import numpy as np
from hftools.py3compat import PY3
from unittest import skip, expectedFailure
from numpy.random import randint, normal
from hftools.dataset import hfarray, DimSweep, DimRep, DimMatrix_i,\
DimMatrix_j
from hftools.utils import HFToolsWarning, HFToolsDeprecationWarning
and any relevant context from other files:
# Path: hftools/py3compat.py
# PY3 = True
#
# Path: hftools/dataset/dim.py
# class DimSweep(DiagAxis):
# pass
#
# class DimRep(DiagAxis):
# sortprio = 1
#
# class DimMatrix_i(_DimMatrix):
# _indep_axis = DimMatrix_Indep_i
# _deriv_axis = DimMatrix_Deriv_i
# sortprio = 1000
#
# class DimMatrix_j(_DimMatrix):
# _indep_axis = DimMatrix_Indep_j
# _deriv_axis = DimMatrix_Deriv_j
# sortprio = 1001
#
# Path: hftools/dataset/arrayobj.py
# class hfarray(_hfarray):
# def __new__(subtype, data, dims=None, dtype=None, copy=True, order=None,
# subok=False, ndmin=0, unit=None, outputformat=None, info=None):
# if hasattr(data, "__hfarray__"):
# data, dims = data.__hfarray__()
# if unit is None and len(dims) == 1:
# unit = dims[0].unit
# if outputformat is None and len(dims) == 1:
# outputformat = dims[0].outputformat
# return _hfarray.__new__(subtype, data, dims=dims, dtype=dtype,
# copy=copy, order=order, subok=subok,
# ndmin=ndmin, unit=unit,
# outputformat=outputformat, info=info)
#
# Path: hftools/utils.py
# def reset_hftools_warnings():
# def timestamp(highres=False):
# def warn(msg):
# def deprecate(msg):
# def isnumber(x):
# def isrealnumber(x):
# def isnumber(x):
# def isrealnumber(x):
# def is_numlike(a):
# def is_integer(a):
# def to_numeric(value, error=True):
# def stable_uniq(data):
# def uniq(data):
# def chop(x, rtol=1e-9, atol=1e-15):
# def make_dirs(*pathsegments):
# def split_num(string):
# def lex_order(lista):
# def glob(pat):
# def beep(freq=None, duration=50):
# def beep(freq=None, duration=50):
# def flatten(lista):
. Output only the next line. | basedims = [DimSweep, DimRep] |
Given the following code snippet before the placeholder: <|code_start|> return _random_array(shape)
def random_complex_array(N, maxsize=6, minsize=1):
shape = tuple(x.data.shape[0] for x in random_dims(N, maxsize, minsize))
return _random_array(shape) + _random_array(shape) * 1j
def random_value_array_from_dims(dims, mean=0, scale=1):
shape = tuple(dim.data.shape[0] for dim in dims)
return hfarray(normal(size=shape) * scale + mean, dims)
##
## Random hfarrays
def random_value_array(N, maxsize, minsize=1):
dims = random_dims(N, maxsize, minsize)
return random_value_array_from_dims(dims)
def random_complex_value_array(N, maxsize, minsize=1):
dims = random_dims(N, maxsize, minsize)
return (random_value_array_from_dims(dims) +
random_value_array_from_dims(dims) * 1j)
def random_dims(N, maxsize, minsize=1):
shape = tuple(randint(minsize, maxsize, size=N))
label = get_label()
<|code_end|>
, predict the next line using imports from the current file:
import doctest
import random
import warnings
import unittest
import numpy as np
from hftools.py3compat import PY3
from unittest import skip, expectedFailure
from numpy.random import randint, normal
from hftools.dataset import hfarray, DimSweep, DimRep, DimMatrix_i,\
DimMatrix_j
from hftools.utils import HFToolsWarning, HFToolsDeprecationWarning
and context including class names, function names, and sometimes code from other files:
# Path: hftools/py3compat.py
# PY3 = True
#
# Path: hftools/dataset/dim.py
# class DimSweep(DiagAxis):
# pass
#
# class DimRep(DiagAxis):
# sortprio = 1
#
# class DimMatrix_i(_DimMatrix):
# _indep_axis = DimMatrix_Indep_i
# _deriv_axis = DimMatrix_Deriv_i
# sortprio = 1000
#
# class DimMatrix_j(_DimMatrix):
# _indep_axis = DimMatrix_Indep_j
# _deriv_axis = DimMatrix_Deriv_j
# sortprio = 1001
#
# Path: hftools/dataset/arrayobj.py
# class hfarray(_hfarray):
# def __new__(subtype, data, dims=None, dtype=None, copy=True, order=None,
# subok=False, ndmin=0, unit=None, outputformat=None, info=None):
# if hasattr(data, "__hfarray__"):
# data, dims = data.__hfarray__()
# if unit is None and len(dims) == 1:
# unit = dims[0].unit
# if outputformat is None and len(dims) == 1:
# outputformat = dims[0].outputformat
# return _hfarray.__new__(subtype, data, dims=dims, dtype=dtype,
# copy=copy, order=order, subok=subok,
# ndmin=ndmin, unit=unit,
# outputformat=outputformat, info=info)
#
# Path: hftools/utils.py
# def reset_hftools_warnings():
# def timestamp(highres=False):
# def warn(msg):
# def deprecate(msg):
# def isnumber(x):
# def isrealnumber(x):
# def isnumber(x):
# def isrealnumber(x):
# def is_numlike(a):
# def is_integer(a):
# def to_numeric(value, error=True):
# def stable_uniq(data):
# def uniq(data):
# def chop(x, rtol=1e-9, atol=1e-15):
# def make_dirs(*pathsegments):
# def split_num(string):
# def lex_order(lista):
# def glob(pat):
# def beep(freq=None, duration=50):
# def beep(freq=None, duration=50):
# def flatten(lista):
. Output only the next line. | basedims = [DimSweep, DimRep] |
Given the following code snippet before the placeholder: <|code_start|>
##
## Random hfarrays
def random_value_array(N, maxsize, minsize=1):
dims = random_dims(N, maxsize, minsize)
return random_value_array_from_dims(dims)
def random_complex_value_array(N, maxsize, minsize=1):
dims = random_dims(N, maxsize, minsize)
return (random_value_array_from_dims(dims) +
random_value_array_from_dims(dims) * 1j)
def random_dims(N, maxsize, minsize=1):
shape = tuple(randint(minsize, maxsize, size=N))
label = get_label()
basedims = [DimSweep, DimRep]
choice = random.choice
dims = tuple(choice(basedims)(label + str(idx), x)
for idx, x in enumerate(shape))
return dims
def random_complex_matrix(N, maxsize, minsize=1, Nmatrix=2, Nmatrixj=None):
if Nmatrixj is None: # pragma: no cover
Nmatrixj = Nmatrix
dims = (random_dims(N, maxsize, minsize) +
<|code_end|>
, predict the next line using imports from the current file:
import doctest
import random
import warnings
import unittest
import numpy as np
from hftools.py3compat import PY3
from unittest import skip, expectedFailure
from numpy.random import randint, normal
from hftools.dataset import hfarray, DimSweep, DimRep, DimMatrix_i,\
DimMatrix_j
from hftools.utils import HFToolsWarning, HFToolsDeprecationWarning
and context including class names, function names, and sometimes code from other files:
# Path: hftools/py3compat.py
# PY3 = True
#
# Path: hftools/dataset/dim.py
# class DimSweep(DiagAxis):
# pass
#
# class DimRep(DiagAxis):
# sortprio = 1
#
# class DimMatrix_i(_DimMatrix):
# _indep_axis = DimMatrix_Indep_i
# _deriv_axis = DimMatrix_Deriv_i
# sortprio = 1000
#
# class DimMatrix_j(_DimMatrix):
# _indep_axis = DimMatrix_Indep_j
# _deriv_axis = DimMatrix_Deriv_j
# sortprio = 1001
#
# Path: hftools/dataset/arrayobj.py
# class hfarray(_hfarray):
# def __new__(subtype, data, dims=None, dtype=None, copy=True, order=None,
# subok=False, ndmin=0, unit=None, outputformat=None, info=None):
# if hasattr(data, "__hfarray__"):
# data, dims = data.__hfarray__()
# if unit is None and len(dims) == 1:
# unit = dims[0].unit
# if outputformat is None and len(dims) == 1:
# outputformat = dims[0].outputformat
# return _hfarray.__new__(subtype, data, dims=dims, dtype=dtype,
# copy=copy, order=order, subok=subok,
# ndmin=ndmin, unit=unit,
# outputformat=outputformat, info=info)
#
# Path: hftools/utils.py
# def reset_hftools_warnings():
# def timestamp(highres=False):
# def warn(msg):
# def deprecate(msg):
# def isnumber(x):
# def isrealnumber(x):
# def isnumber(x):
# def isrealnumber(x):
# def is_numlike(a):
# def is_integer(a):
# def to_numeric(value, error=True):
# def stable_uniq(data):
# def uniq(data):
# def chop(x, rtol=1e-9, atol=1e-15):
# def make_dirs(*pathsegments):
# def split_num(string):
# def lex_order(lista):
# def glob(pat):
# def beep(freq=None, duration=50):
# def beep(freq=None, duration=50):
# def flatten(lista):
. Output only the next line. | (DimMatrix_i("i", Nmatrix), DimMatrix_j("j", Nmatrixj))) |
Here is a snippet: <|code_start|>
##
## Random hfarrays
def random_value_array(N, maxsize, minsize=1):
dims = random_dims(N, maxsize, minsize)
return random_value_array_from_dims(dims)
def random_complex_value_array(N, maxsize, minsize=1):
dims = random_dims(N, maxsize, minsize)
return (random_value_array_from_dims(dims) +
random_value_array_from_dims(dims) * 1j)
def random_dims(N, maxsize, minsize=1):
shape = tuple(randint(minsize, maxsize, size=N))
label = get_label()
basedims = [DimSweep, DimRep]
choice = random.choice
dims = tuple(choice(basedims)(label + str(idx), x)
for idx, x in enumerate(shape))
return dims
def random_complex_matrix(N, maxsize, minsize=1, Nmatrix=2, Nmatrixj=None):
if Nmatrixj is None: # pragma: no cover
Nmatrixj = Nmatrix
dims = (random_dims(N, maxsize, minsize) +
<|code_end|>
. Write the next line using the current file imports:
import doctest
import random
import warnings
import unittest
import numpy as np
from hftools.py3compat import PY3
from unittest import skip, expectedFailure
from numpy.random import randint, normal
from hftools.dataset import hfarray, DimSweep, DimRep, DimMatrix_i,\
DimMatrix_j
from hftools.utils import HFToolsWarning, HFToolsDeprecationWarning
and context from other files:
# Path: hftools/py3compat.py
# PY3 = True
#
# Path: hftools/dataset/dim.py
# class DimSweep(DiagAxis):
# pass
#
# class DimRep(DiagAxis):
# sortprio = 1
#
# class DimMatrix_i(_DimMatrix):
# _indep_axis = DimMatrix_Indep_i
# _deriv_axis = DimMatrix_Deriv_i
# sortprio = 1000
#
# class DimMatrix_j(_DimMatrix):
# _indep_axis = DimMatrix_Indep_j
# _deriv_axis = DimMatrix_Deriv_j
# sortprio = 1001
#
# Path: hftools/dataset/arrayobj.py
# class hfarray(_hfarray):
# def __new__(subtype, data, dims=None, dtype=None, copy=True, order=None,
# subok=False, ndmin=0, unit=None, outputformat=None, info=None):
# if hasattr(data, "__hfarray__"):
# data, dims = data.__hfarray__()
# if unit is None and len(dims) == 1:
# unit = dims[0].unit
# if outputformat is None and len(dims) == 1:
# outputformat = dims[0].outputformat
# return _hfarray.__new__(subtype, data, dims=dims, dtype=dtype,
# copy=copy, order=order, subok=subok,
# ndmin=ndmin, unit=unit,
# outputformat=outputformat, info=info)
#
# Path: hftools/utils.py
# def reset_hftools_warnings():
# def timestamp(highres=False):
# def warn(msg):
# def deprecate(msg):
# def isnumber(x):
# def isrealnumber(x):
# def isnumber(x):
# def isrealnumber(x):
# def is_numlike(a):
# def is_integer(a):
# def to_numeric(value, error=True):
# def stable_uniq(data):
# def uniq(data):
# def chop(x, rtol=1e-9, atol=1e-15):
# def make_dirs(*pathsegments):
# def split_num(string):
# def lex_order(lista):
# def glob(pat):
# def beep(freq=None, duration=50):
# def beep(freq=None, duration=50):
# def flatten(lista):
, which may include functions, classes, or code. Output only the next line. | (DimMatrix_i("i", Nmatrix), DimMatrix_j("j", Nmatrixj))) |
Given snippet: <|code_start|># warnings.simplefilter("error", DeprecationWarning)
def load_tests(loader, standard_tests, pattern):
suite = unittest.TestSuite()
suite.addTests(standard_tests)
DocTests = doctest.DocTestSuite(module)
suite.addTests(DocTests)
return suite
return load_tests
##
## Random numpy arrays
def _random_array(shape):
return normal(size=shape)
def random_array(N, maxsize=6, minsize=1):
shape = tuple(x.data.shape[0] for x in random_dims(N, maxsize, minsize))
return _random_array(shape)
def random_complex_array(N, maxsize=6, minsize=1):
shape = tuple(x.data.shape[0] for x in random_dims(N, maxsize, minsize))
return _random_array(shape) + _random_array(shape) * 1j
def random_value_array_from_dims(dims, mean=0, scale=1):
shape = tuple(dim.data.shape[0] for dim in dims)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import doctest
import random
import warnings
import unittest
import numpy as np
from hftools.py3compat import PY3
from unittest import skip, expectedFailure
from numpy.random import randint, normal
from hftools.dataset import hfarray, DimSweep, DimRep, DimMatrix_i,\
DimMatrix_j
from hftools.utils import HFToolsWarning, HFToolsDeprecationWarning
and context:
# Path: hftools/py3compat.py
# PY3 = True
#
# Path: hftools/dataset/dim.py
# class DimSweep(DiagAxis):
# pass
#
# class DimRep(DiagAxis):
# sortprio = 1
#
# class DimMatrix_i(_DimMatrix):
# _indep_axis = DimMatrix_Indep_i
# _deriv_axis = DimMatrix_Deriv_i
# sortprio = 1000
#
# class DimMatrix_j(_DimMatrix):
# _indep_axis = DimMatrix_Indep_j
# _deriv_axis = DimMatrix_Deriv_j
# sortprio = 1001
#
# Path: hftools/dataset/arrayobj.py
# class hfarray(_hfarray):
# def __new__(subtype, data, dims=None, dtype=None, copy=True, order=None,
# subok=False, ndmin=0, unit=None, outputformat=None, info=None):
# if hasattr(data, "__hfarray__"):
# data, dims = data.__hfarray__()
# if unit is None and len(dims) == 1:
# unit = dims[0].unit
# if outputformat is None and len(dims) == 1:
# outputformat = dims[0].outputformat
# return _hfarray.__new__(subtype, data, dims=dims, dtype=dtype,
# copy=copy, order=order, subok=subok,
# ndmin=ndmin, unit=unit,
# outputformat=outputformat, info=info)
#
# Path: hftools/utils.py
# def reset_hftools_warnings():
# def timestamp(highres=False):
# def warn(msg):
# def deprecate(msg):
# def isnumber(x):
# def isrealnumber(x):
# def isnumber(x):
# def isrealnumber(x):
# def is_numlike(a):
# def is_integer(a):
# def to_numeric(value, error=True):
# def stable_uniq(data):
# def uniq(data):
# def chop(x, rtol=1e-9, atol=1e-15):
# def make_dirs(*pathsegments):
# def split_num(string):
# def lex_order(lista):
# def glob(pat):
# def beep(freq=None, duration=50):
# def beep(freq=None, duration=50):
# def flatten(lista):
which might include code, classes, or functions. Output only the next line. | return hfarray(normal(size=shape) * scale + mean, dims) |
Given the code snippet: <|code_start|># The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
class TestCase(unittest.TestCase):
def assertAllclose(self, a, b, rtol=1e-05, atol=1e-08, msg=None):
a = np.asanyarray(a)
b = np.asanyarray(b)
if msg is None:
msg = "a (%s) not close to b (%s)" % (a, b)
self.assertTrue(np.allclose(a, b, rtol, atol), msg)
def assertIsNotInstance(self, obj, cls):
self.assertFalse(isinstance(obj, cls))
def assertIsInstance(self, obj, cls, msg=None):
"""Same as self.assertTrue(isinstance(obj, cls)), with a nicer
default message."""
if not isinstance(obj, cls):
arg = (unittest.case.safe_repr(obj), cls)
standardMsg = '%s is not an instance of %r' % arg
self.fail(self._formatMessage(msg, standardMsg))
def assertHFToolsWarning(self, funk, *k, **kw):
warnings.resetwarnings()
<|code_end|>
, generate the next line using the imports in this file:
import doctest
import random
import warnings
import unittest
import numpy as np
from hftools.py3compat import PY3
from unittest import skip, expectedFailure
from numpy.random import randint, normal
from hftools.dataset import hfarray, DimSweep, DimRep, DimMatrix_i,\
DimMatrix_j
from hftools.utils import HFToolsWarning, HFToolsDeprecationWarning
and context (functions, classes, or occasionally code) from other files:
# Path: hftools/py3compat.py
# PY3 = True
#
# Path: hftools/dataset/dim.py
# class DimSweep(DiagAxis):
# pass
#
# class DimRep(DiagAxis):
# sortprio = 1
#
# class DimMatrix_i(_DimMatrix):
# _indep_axis = DimMatrix_Indep_i
# _deriv_axis = DimMatrix_Deriv_i
# sortprio = 1000
#
# class DimMatrix_j(_DimMatrix):
# _indep_axis = DimMatrix_Indep_j
# _deriv_axis = DimMatrix_Deriv_j
# sortprio = 1001
#
# Path: hftools/dataset/arrayobj.py
# class hfarray(_hfarray):
# def __new__(subtype, data, dims=None, dtype=None, copy=True, order=None,
# subok=False, ndmin=0, unit=None, outputformat=None, info=None):
# if hasattr(data, "__hfarray__"):
# data, dims = data.__hfarray__()
# if unit is None and len(dims) == 1:
# unit = dims[0].unit
# if outputformat is None and len(dims) == 1:
# outputformat = dims[0].outputformat
# return _hfarray.__new__(subtype, data, dims=dims, dtype=dtype,
# copy=copy, order=order, subok=subok,
# ndmin=ndmin, unit=unit,
# outputformat=outputformat, info=info)
#
# Path: hftools/utils.py
# def reset_hftools_warnings():
# def timestamp(highres=False):
# def warn(msg):
# def deprecate(msg):
# def isnumber(x):
# def isrealnumber(x):
# def isnumber(x):
# def isrealnumber(x):
# def is_numlike(a):
# def is_integer(a):
# def to_numeric(value, error=True):
# def stable_uniq(data):
# def uniq(data):
# def chop(x, rtol=1e-9, atol=1e-15):
# def make_dirs(*pathsegments):
# def split_num(string):
# def lex_order(lista):
# def glob(pat):
# def beep(freq=None, duration=50):
# def beep(freq=None, duration=50):
# def flatten(lista):
. Output only the next line. | warnings.simplefilter("error", HFToolsWarning) |
Based on the snippet: <|code_start|>
class TestCase(unittest.TestCase):
def assertAllclose(self, a, b, rtol=1e-05, atol=1e-08, msg=None):
a = np.asanyarray(a)
b = np.asanyarray(b)
if msg is None:
msg = "a (%s) not close to b (%s)" % (a, b)
self.assertTrue(np.allclose(a, b, rtol, atol), msg)
def assertIsNotInstance(self, obj, cls):
self.assertFalse(isinstance(obj, cls))
def assertIsInstance(self, obj, cls, msg=None):
"""Same as self.assertTrue(isinstance(obj, cls)), with a nicer
default message."""
if not isinstance(obj, cls):
arg = (unittest.case.safe_repr(obj), cls)
standardMsg = '%s is not an instance of %r' % arg
self.fail(self._formatMessage(msg, standardMsg))
def assertHFToolsWarning(self, funk, *k, **kw):
warnings.resetwarnings()
warnings.simplefilter("error", HFToolsWarning)
self.assertRaises(HFToolsWarning, funk, *k, **kw)
warnings.simplefilter("ignore", HFToolsWarning)
def assertHFToolsDeprecationWarning(self, funk, *k, **kw):
warnings.resetwarnings()
<|code_end|>
, predict the immediate next line with the help of imports:
import doctest
import random
import warnings
import unittest
import numpy as np
from hftools.py3compat import PY3
from unittest import skip, expectedFailure
from numpy.random import randint, normal
from hftools.dataset import hfarray, DimSweep, DimRep, DimMatrix_i,\
DimMatrix_j
from hftools.utils import HFToolsWarning, HFToolsDeprecationWarning
and context (classes, functions, sometimes code) from other files:
# Path: hftools/py3compat.py
# PY3 = True
#
# Path: hftools/dataset/dim.py
# class DimSweep(DiagAxis):
# pass
#
# class DimRep(DiagAxis):
# sortprio = 1
#
# class DimMatrix_i(_DimMatrix):
# _indep_axis = DimMatrix_Indep_i
# _deriv_axis = DimMatrix_Deriv_i
# sortprio = 1000
#
# class DimMatrix_j(_DimMatrix):
# _indep_axis = DimMatrix_Indep_j
# _deriv_axis = DimMatrix_Deriv_j
# sortprio = 1001
#
# Path: hftools/dataset/arrayobj.py
# class hfarray(_hfarray):
# def __new__(subtype, data, dims=None, dtype=None, copy=True, order=None,
# subok=False, ndmin=0, unit=None, outputformat=None, info=None):
# if hasattr(data, "__hfarray__"):
# data, dims = data.__hfarray__()
# if unit is None and len(dims) == 1:
# unit = dims[0].unit
# if outputformat is None and len(dims) == 1:
# outputformat = dims[0].outputformat
# return _hfarray.__new__(subtype, data, dims=dims, dtype=dtype,
# copy=copy, order=order, subok=subok,
# ndmin=ndmin, unit=unit,
# outputformat=outputformat, info=info)
#
# Path: hftools/utils.py
# def reset_hftools_warnings():
# def timestamp(highres=False):
# def warn(msg):
# def deprecate(msg):
# def isnumber(x):
# def isrealnumber(x):
# def isnumber(x):
# def isrealnumber(x):
# def is_numlike(a):
# def is_integer(a):
# def to_numeric(value, error=True):
# def stable_uniq(data):
# def uniq(data):
# def chop(x, rtol=1e-9, atol=1e-15):
# def make_dirs(*pathsegments):
# def split_num(string):
# def lex_order(lista):
# def glob(pat):
# def beep(freq=None, duration=50):
# def beep(freq=None, duration=50):
# def flatten(lista):
. Output only the next line. | warnings.simplefilter("error", HFToolsDeprecationWarning) |
Based on the snippet: <|code_start|>
def test_branch_2(self):
z = np.exp(1j * np.linspace(0, 2 * np.pi, 721))
res = hfmath.angle(z, deg=True)
assert np.all((res > -180) & (res <= 180))
def test_branch_3(self):
z = np.exp(1j * np.linspace(0, 2 * np.pi, 721))
res = hfmath.angle(z, deg=True, branch=0)
assert np.all((res >= 0) & (res <= 360))
def test_branch_4(self):
z = np.exp(1j * np.linspace(0, 2 * np.pi, 721))
res = hfmath.angle(z, deg=False)
assert np.all((res > -np.pi) & (res <= np.pi))
def test_branch_5(self):
z = np.exp(1j * np.linspace(0, 2 * np.pi, 721))
res = hfmath.angle(z, deg=False, branch=0)
assert np.all((res >= 0) & (res <= 2 * np.pi))
class Test_make_matrix(TestCase):
def test_make_matrix_1(self):
a = hfarray([1, 10])
b = hfarray([2, 20])
c = hfarray([3, 30])
d = hfarray([4, 40])
i = DimMatrix_i("i", 2)
j = DimMatrix_j("j", 2)
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import numpy as np
import hftools.math as hfmath
from hftools.dataset import hfarray, DimSweep, DimMatrix_i, DimMatrix_j
from hftools.testing import TestCase, make_load_tests
and context (classes, functions, sometimes code) from other files:
# Path: hftools/dataset/dim.py
# class DimSweep(DiagAxis):
# pass
#
# class DimMatrix_i(_DimMatrix):
# _indep_axis = DimMatrix_Indep_i
# _deriv_axis = DimMatrix_Deriv_i
# sortprio = 1000
#
# class DimMatrix_j(_DimMatrix):
# _indep_axis = DimMatrix_Indep_j
# _deriv_axis = DimMatrix_Deriv_j
# sortprio = 1001
#
# Path: hftools/dataset/arrayobj.py
# class hfarray(_hfarray):
# def __new__(subtype, data, dims=None, dtype=None, copy=True, order=None,
# subok=False, ndmin=0, unit=None, outputformat=None, info=None):
# if hasattr(data, "__hfarray__"):
# data, dims = data.__hfarray__()
# if unit is None and len(dims) == 1:
# unit = dims[0].unit
# if outputformat is None and len(dims) == 1:
# outputformat = dims[0].outputformat
# return _hfarray.__new__(subtype, data, dims=dims, dtype=dtype,
# copy=copy, order=order, subok=subok,
# ndmin=ndmin, unit=unit,
# outputformat=outputformat, info=info)
#
# Path: hftools/testing/common.py
# class TestCase(unittest.TestCase):
# def assertAllclose(self, a, b, rtol=1e-05, atol=1e-08, msg=None):
# a = np.asanyarray(a)
# b = np.asanyarray(b)
# if msg is None:
# msg = "a (%s) not close to b (%s)" % (a, b)
# self.assertTrue(np.allclose(a, b, rtol, atol), msg)
#
# def assertIsNotInstance(self, obj, cls):
# self.assertFalse(isinstance(obj, cls))
#
# def assertIsInstance(self, obj, cls, msg=None):
# """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
# default message."""
# if not isinstance(obj, cls):
# arg = (unittest.case.safe_repr(obj), cls)
# standardMsg = '%s is not an instance of %r' % arg
# self.fail(self._formatMessage(msg, standardMsg))
#
# def assertHFToolsWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsWarning)
# self.assertRaises(HFToolsWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsWarning)
#
# def assertHFToolsDeprecationWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsDeprecationWarning)
# self.assertRaises(HFToolsDeprecationWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsDeprecationWarning)
#
# def make_load_tests(module):
# """Add doctests to tests for module
#
# usage::
# load_tests = make_load_tests(module)
# """
# warnings.simplefilter("error", HFToolsWarning)
# warnings.simplefilter("error", HFToolsDeprecationWarning)
# # warnings.simplefilter("error", DeprecationWarning)
#
# def load_tests(loader, standard_tests, pattern):
# suite = unittest.TestSuite()
# suite.addTests(standard_tests)
# DocTests = doctest.DocTestSuite(module)
# suite.addTests(DocTests)
# return suite
# return load_tests
. Output only the next line. | fi = DimSweep("freq", [0, 1]) |
Based on the snippet: <|code_start|> res = hfmath.angle(self.a, deg=True, branch=0)
self.assertAllclose(res, np.array([0, 90, 180, 270]))
def test_branch_2(self):
z = np.exp(1j * np.linspace(0, 2 * np.pi, 721))
res = hfmath.angle(z, deg=True)
assert np.all((res > -180) & (res <= 180))
def test_branch_3(self):
z = np.exp(1j * np.linspace(0, 2 * np.pi, 721))
res = hfmath.angle(z, deg=True, branch=0)
assert np.all((res >= 0) & (res <= 360))
def test_branch_4(self):
z = np.exp(1j * np.linspace(0, 2 * np.pi, 721))
res = hfmath.angle(z, deg=False)
assert np.all((res > -np.pi) & (res <= np.pi))
def test_branch_5(self):
z = np.exp(1j * np.linspace(0, 2 * np.pi, 721))
res = hfmath.angle(z, deg=False, branch=0)
assert np.all((res >= 0) & (res <= 2 * np.pi))
class Test_make_matrix(TestCase):
def test_make_matrix_1(self):
a = hfarray([1, 10])
b = hfarray([2, 20])
c = hfarray([3, 30])
d = hfarray([4, 40])
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import numpy as np
import hftools.math as hfmath
from hftools.dataset import hfarray, DimSweep, DimMatrix_i, DimMatrix_j
from hftools.testing import TestCase, make_load_tests
and context (classes, functions, sometimes code) from other files:
# Path: hftools/dataset/dim.py
# class DimSweep(DiagAxis):
# pass
#
# class DimMatrix_i(_DimMatrix):
# _indep_axis = DimMatrix_Indep_i
# _deriv_axis = DimMatrix_Deriv_i
# sortprio = 1000
#
# class DimMatrix_j(_DimMatrix):
# _indep_axis = DimMatrix_Indep_j
# _deriv_axis = DimMatrix_Deriv_j
# sortprio = 1001
#
# Path: hftools/dataset/arrayobj.py
# class hfarray(_hfarray):
# def __new__(subtype, data, dims=None, dtype=None, copy=True, order=None,
# subok=False, ndmin=0, unit=None, outputformat=None, info=None):
# if hasattr(data, "__hfarray__"):
# data, dims = data.__hfarray__()
# if unit is None and len(dims) == 1:
# unit = dims[0].unit
# if outputformat is None and len(dims) == 1:
# outputformat = dims[0].outputformat
# return _hfarray.__new__(subtype, data, dims=dims, dtype=dtype,
# copy=copy, order=order, subok=subok,
# ndmin=ndmin, unit=unit,
# outputformat=outputformat, info=info)
#
# Path: hftools/testing/common.py
# class TestCase(unittest.TestCase):
# def assertAllclose(self, a, b, rtol=1e-05, atol=1e-08, msg=None):
# a = np.asanyarray(a)
# b = np.asanyarray(b)
# if msg is None:
# msg = "a (%s) not close to b (%s)" % (a, b)
# self.assertTrue(np.allclose(a, b, rtol, atol), msg)
#
# def assertIsNotInstance(self, obj, cls):
# self.assertFalse(isinstance(obj, cls))
#
# def assertIsInstance(self, obj, cls, msg=None):
# """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
# default message."""
# if not isinstance(obj, cls):
# arg = (unittest.case.safe_repr(obj), cls)
# standardMsg = '%s is not an instance of %r' % arg
# self.fail(self._formatMessage(msg, standardMsg))
#
# def assertHFToolsWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsWarning)
# self.assertRaises(HFToolsWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsWarning)
#
# def assertHFToolsDeprecationWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsDeprecationWarning)
# self.assertRaises(HFToolsDeprecationWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsDeprecationWarning)
#
# def make_load_tests(module):
# """Add doctests to tests for module
#
# usage::
# load_tests = make_load_tests(module)
# """
# warnings.simplefilter("error", HFToolsWarning)
# warnings.simplefilter("error", HFToolsDeprecationWarning)
# # warnings.simplefilter("error", DeprecationWarning)
#
# def load_tests(loader, standard_tests, pattern):
# suite = unittest.TestSuite()
# suite.addTests(standard_tests)
# DocTests = doctest.DocTestSuite(module)
# suite.addTests(DocTests)
# return suite
# return load_tests
. Output only the next line. | i = DimMatrix_i("i", 2) |
Here is a snippet: <|code_start|> self.assertAllclose(res, np.array([0, 90, 180, 270]))
def test_branch_2(self):
z = np.exp(1j * np.linspace(0, 2 * np.pi, 721))
res = hfmath.angle(z, deg=True)
assert np.all((res > -180) & (res <= 180))
def test_branch_3(self):
z = np.exp(1j * np.linspace(0, 2 * np.pi, 721))
res = hfmath.angle(z, deg=True, branch=0)
assert np.all((res >= 0) & (res <= 360))
def test_branch_4(self):
z = np.exp(1j * np.linspace(0, 2 * np.pi, 721))
res = hfmath.angle(z, deg=False)
assert np.all((res > -np.pi) & (res <= np.pi))
def test_branch_5(self):
z = np.exp(1j * np.linspace(0, 2 * np.pi, 721))
res = hfmath.angle(z, deg=False, branch=0)
assert np.all((res >= 0) & (res <= 2 * np.pi))
class Test_make_matrix(TestCase):
def test_make_matrix_1(self):
a = hfarray([1, 10])
b = hfarray([2, 20])
c = hfarray([3, 30])
d = hfarray([4, 40])
i = DimMatrix_i("i", 2)
<|code_end|>
. Write the next line using the current file imports:
import os
import numpy as np
import hftools.math as hfmath
from hftools.dataset import hfarray, DimSweep, DimMatrix_i, DimMatrix_j
from hftools.testing import TestCase, make_load_tests
and context from other files:
# Path: hftools/dataset/dim.py
# class DimSweep(DiagAxis):
# pass
#
# class DimMatrix_i(_DimMatrix):
# _indep_axis = DimMatrix_Indep_i
# _deriv_axis = DimMatrix_Deriv_i
# sortprio = 1000
#
# class DimMatrix_j(_DimMatrix):
# _indep_axis = DimMatrix_Indep_j
# _deriv_axis = DimMatrix_Deriv_j
# sortprio = 1001
#
# Path: hftools/dataset/arrayobj.py
# class hfarray(_hfarray):
# def __new__(subtype, data, dims=None, dtype=None, copy=True, order=None,
# subok=False, ndmin=0, unit=None, outputformat=None, info=None):
# if hasattr(data, "__hfarray__"):
# data, dims = data.__hfarray__()
# if unit is None and len(dims) == 1:
# unit = dims[0].unit
# if outputformat is None and len(dims) == 1:
# outputformat = dims[0].outputformat
# return _hfarray.__new__(subtype, data, dims=dims, dtype=dtype,
# copy=copy, order=order, subok=subok,
# ndmin=ndmin, unit=unit,
# outputformat=outputformat, info=info)
#
# Path: hftools/testing/common.py
# class TestCase(unittest.TestCase):
# def assertAllclose(self, a, b, rtol=1e-05, atol=1e-08, msg=None):
# a = np.asanyarray(a)
# b = np.asanyarray(b)
# if msg is None:
# msg = "a (%s) not close to b (%s)" % (a, b)
# self.assertTrue(np.allclose(a, b, rtol, atol), msg)
#
# def assertIsNotInstance(self, obj, cls):
# self.assertFalse(isinstance(obj, cls))
#
# def assertIsInstance(self, obj, cls, msg=None):
# """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
# default message."""
# if not isinstance(obj, cls):
# arg = (unittest.case.safe_repr(obj), cls)
# standardMsg = '%s is not an instance of %r' % arg
# self.fail(self._formatMessage(msg, standardMsg))
#
# def assertHFToolsWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsWarning)
# self.assertRaises(HFToolsWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsWarning)
#
# def assertHFToolsDeprecationWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsDeprecationWarning)
# self.assertRaises(HFToolsDeprecationWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsDeprecationWarning)
#
# def make_load_tests(module):
# """Add doctests to tests for module
#
# usage::
# load_tests = make_load_tests(module)
# """
# warnings.simplefilter("error", HFToolsWarning)
# warnings.simplefilter("error", HFToolsDeprecationWarning)
# # warnings.simplefilter("error", DeprecationWarning)
#
# def load_tests(loader, standard_tests, pattern):
# suite = unittest.TestSuite()
# suite.addTests(standard_tests)
# DocTests = doctest.DocTestSuite(module)
# suite.addTests(DocTests)
# return suite
# return load_tests
, which may include functions, classes, or code. Output only the next line. | j = DimMatrix_j("j", 2) |
Given snippet: <|code_start|>#-----------------------------------------------------------------------------
# Copyright (c) 2014, HFTools Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
basepath = os.path.split(__file__)[0]
load_tests = make_load_tests(hfmath)
class Test_angle(TestCase):
def setUp(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import numpy as np
import hftools.math as hfmath
from hftools.dataset import hfarray, DimSweep, DimMatrix_i, DimMatrix_j
from hftools.testing import TestCase, make_load_tests
and context:
# Path: hftools/dataset/dim.py
# class DimSweep(DiagAxis):
# pass
#
# class DimMatrix_i(_DimMatrix):
# _indep_axis = DimMatrix_Indep_i
# _deriv_axis = DimMatrix_Deriv_i
# sortprio = 1000
#
# class DimMatrix_j(_DimMatrix):
# _indep_axis = DimMatrix_Indep_j
# _deriv_axis = DimMatrix_Deriv_j
# sortprio = 1001
#
# Path: hftools/dataset/arrayobj.py
# class hfarray(_hfarray):
# def __new__(subtype, data, dims=None, dtype=None, copy=True, order=None,
# subok=False, ndmin=0, unit=None, outputformat=None, info=None):
# if hasattr(data, "__hfarray__"):
# data, dims = data.__hfarray__()
# if unit is None and len(dims) == 1:
# unit = dims[0].unit
# if outputformat is None and len(dims) == 1:
# outputformat = dims[0].outputformat
# return _hfarray.__new__(subtype, data, dims=dims, dtype=dtype,
# copy=copy, order=order, subok=subok,
# ndmin=ndmin, unit=unit,
# outputformat=outputformat, info=info)
#
# Path: hftools/testing/common.py
# class TestCase(unittest.TestCase):
# def assertAllclose(self, a, b, rtol=1e-05, atol=1e-08, msg=None):
# a = np.asanyarray(a)
# b = np.asanyarray(b)
# if msg is None:
# msg = "a (%s) not close to b (%s)" % (a, b)
# self.assertTrue(np.allclose(a, b, rtol, atol), msg)
#
# def assertIsNotInstance(self, obj, cls):
# self.assertFalse(isinstance(obj, cls))
#
# def assertIsInstance(self, obj, cls, msg=None):
# """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
# default message."""
# if not isinstance(obj, cls):
# arg = (unittest.case.safe_repr(obj), cls)
# standardMsg = '%s is not an instance of %r' % arg
# self.fail(self._formatMessage(msg, standardMsg))
#
# def assertHFToolsWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsWarning)
# self.assertRaises(HFToolsWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsWarning)
#
# def assertHFToolsDeprecationWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsDeprecationWarning)
# self.assertRaises(HFToolsDeprecationWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsDeprecationWarning)
#
# def make_load_tests(module):
# """Add doctests to tests for module
#
# usage::
# load_tests = make_load_tests(module)
# """
# warnings.simplefilter("error", HFToolsWarning)
# warnings.simplefilter("error", HFToolsDeprecationWarning)
# # warnings.simplefilter("error", DeprecationWarning)
#
# def load_tests(loader, standard_tests, pattern):
# suite = unittest.TestSuite()
# suite.addTests(standard_tests)
# DocTests = doctest.DocTestSuite(module)
# suite.addTests(DocTests)
# return suite
# return load_tests
which might include code, classes, or functions. Output only the next line. | self.A = hfarray([1, 1j, -1, -1j]) |
Given snippet: <|code_start|>Date: 9 Mar 2007
"""
# TODO
# - Tree-walking functions don't avoid symlink loops. Matt Harrison
# sent me a patch for this.
# - Bug in write_text(). It doesn't support Universal newline mode.
# - Better error message in listdir() when self isn't a
# directory. (On Windows, the error message really sucks.)
# - Make sure everything has a good docstring.
# - Add methods for regex find and replace.
# - guess_content_type() method?
# - Perhaps support arguments to touch().
from __future__ import generators
__version__ = '2.2'
__all__ = ['path']
# Platform-specific support for path.owner
if os.name == 'nt':
try:
except ImportError:
win32security = None
else:
try:
except ImportError:
pwd = None
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from hftools.py3compat import PY3, getcwdu
import sys, warnings, os, fnmatch, glob, shutil, codecs, six
import win32security
import pwd
and context:
# Path: hftools/py3compat.py
# DEFAULT_ENCODING = "cp1252"
# PY3 = True
# PY3 = False
# def no_code(x, encoding=None):
# def decode(s, encoding=None):
# def encode(u, encoding=None):
# def cast_unicode(s, encoding=None):
# def cast_bytes(s, encoding=None):
# def reraise(tp, value, tb=None):
# def popen(command):
# def popen(command):
# def print(*k, **kw):
# def cast_str(s, encoding=None):
which might include code, classes, or functions. Output only the next line. | if six.PY3: |
Predict the next line for this snippet: <|code_start|># - Tree-walking functions don't avoid symlink loops. Matt Harrison
# sent me a patch for this.
# - Bug in write_text(). It doesn't support Universal newline mode.
# - Better error message in listdir() when self isn't a
# directory. (On Windows, the error message really sucks.)
# - Make sure everything has a good docstring.
# - Add methods for regex find and replace.
# - guess_content_type() method?
# - Perhaps support arguments to touch().
from __future__ import generators
__version__ = '2.2'
__all__ = ['path']
# Platform-specific support for path.owner
if os.name == 'nt':
try:
except ImportError:
win32security = None
else:
try:
except ImportError:
pwd = None
if six.PY3:
_base = str
_getcwd = os.getcwd
else:
_base = unicode
<|code_end|>
with the help of current file imports:
from hftools.py3compat import PY3, getcwdu
import sys, warnings, os, fnmatch, glob, shutil, codecs, six
import win32security
import pwd
and context from other files:
# Path: hftools/py3compat.py
# DEFAULT_ENCODING = "cp1252"
# PY3 = True
# PY3 = False
# def no_code(x, encoding=None):
# def decode(s, encoding=None):
# def encode(u, encoding=None):
# def cast_unicode(s, encoding=None):
# def cast_bytes(s, encoding=None):
# def reraise(tp, value, tb=None):
# def popen(command):
# def popen(command):
# def print(*k, **kw):
# def cast_str(s, encoding=None):
, which may contain function names, class names, or code. Output only the next line. | _getcwd = os.getcwdu |
Here is a snippet: <|code_start|>#-----------------------------------------------------------------------------
# Copyright (c) 2014, HFTools Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
basepath = os.path.split(__file__)[0]
class VArray(aobj.hfarray):
__array_priority__ = 10
<|code_end|>
. Write the next line using the current file imports:
import operator
import os
import numpy as np
import hftools.dataset.arrayobj as aobj
from numpy import newaxis
from hftools.testing import TestCase
from hftools.testing import random_value_array_from_dims
from hftools.py3compat import PY3
and context from other files:
# Path: hftools/testing/common.py
# class TestCase(unittest.TestCase):
# def assertAllclose(self, a, b, rtol=1e-05, atol=1e-08, msg=None):
# a = np.asanyarray(a)
# b = np.asanyarray(b)
# if msg is None:
# msg = "a (%s) not close to b (%s)" % (a, b)
# self.assertTrue(np.allclose(a, b, rtol, atol), msg)
#
# def assertIsNotInstance(self, obj, cls):
# self.assertFalse(isinstance(obj, cls))
#
# def assertIsInstance(self, obj, cls, msg=None):
# """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
# default message."""
# if not isinstance(obj, cls):
# arg = (unittest.case.safe_repr(obj), cls)
# standardMsg = '%s is not an instance of %r' % arg
# self.fail(self._formatMessage(msg, standardMsg))
#
# def assertHFToolsWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsWarning)
# self.assertRaises(HFToolsWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsWarning)
#
# def assertHFToolsDeprecationWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsDeprecationWarning)
# self.assertRaises(HFToolsDeprecationWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsDeprecationWarning)
#
# Path: hftools/testing/common.py
# def random_value_array_from_dims(dims, mean=0, scale=1):
# shape = tuple(dim.data.shape[0] for dim in dims)
# return hfarray(normal(size=shape) * scale + mean, dims)
#
# Path: hftools/py3compat.py
# PY3 = True
, which may include functions, classes, or code. Output only the next line. | class Test_binary_ops(TestCase): |
Continue the code snippet: <|code_start|>#-----------------------------------------------------------------------------
# Copyright (c) 2014, HFTools Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
basepath = os.path.split(__file__)[0]
class VArray(aobj.hfarray):
__array_priority__ = 10
class Test_binary_ops(TestCase):
op = operator.add
<|code_end|>
. Use current file imports:
import operator
import os
import numpy as np
import hftools.dataset.arrayobj as aobj
from numpy import newaxis
from hftools.testing import TestCase
from hftools.testing import random_value_array_from_dims
from hftools.py3compat import PY3
and context (classes, functions, or code) from other files:
# Path: hftools/testing/common.py
# class TestCase(unittest.TestCase):
# def assertAllclose(self, a, b, rtol=1e-05, atol=1e-08, msg=None):
# a = np.asanyarray(a)
# b = np.asanyarray(b)
# if msg is None:
# msg = "a (%s) not close to b (%s)" % (a, b)
# self.assertTrue(np.allclose(a, b, rtol, atol), msg)
#
# def assertIsNotInstance(self, obj, cls):
# self.assertFalse(isinstance(obj, cls))
#
# def assertIsInstance(self, obj, cls, msg=None):
# """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
# default message."""
# if not isinstance(obj, cls):
# arg = (unittest.case.safe_repr(obj), cls)
# standardMsg = '%s is not an instance of %r' % arg
# self.fail(self._formatMessage(msg, standardMsg))
#
# def assertHFToolsWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsWarning)
# self.assertRaises(HFToolsWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsWarning)
#
# def assertHFToolsDeprecationWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsDeprecationWarning)
# self.assertRaises(HFToolsDeprecationWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsDeprecationWarning)
#
# Path: hftools/testing/common.py
# def random_value_array_from_dims(dims, mean=0, scale=1):
# shape = tuple(dim.data.shape[0] for dim in dims)
# return hfarray(normal(size=shape) * scale + mean, dims)
#
# Path: hftools/py3compat.py
# PY3 = True
. Output only the next line. | randfunc = [random_value_array_from_dims] |
Given the code snippet: <|code_start|>
def test_5(self):
v1 = (self.randfunc[0]((self.fi, self.gi, self.ri), mean=10))
v2 = VArray(self.randfunc[0]((self.gi,), mean=10))
a1 = np.array(v1).transpose(1, 0, 2)
a2 = np.array(v2)[:, newaxis, newaxis]
self._check(v1, v2, a1, a2)
def test_6(self):
v1 = (self.randfunc[0]((self.fi, self.ri, self.gi), mean=10))
v2 = VArray(self.randfunc[0]((self.ri, self.fi), mean=10))
a1 = np.array(v1).transpose(0, 2, 1)
a2 = np.array(v2).transpose()[:, newaxis]
self._check(v1, v2, a1, a2)
def test_7(self):
v1 = VArray(self.randfunc[0]((self.fi, self.gi, self.ri), mean=10))
v2 = 5.
a1 = np.array(v1)
self._check(v1, v2, a1, v2)
class Test_binary_ops_sub(Test_binary_ops):
op = operator.sub
class Test_binary_ops_mul(Test_binary_ops):
op = operator.mul
<|code_end|>
, generate the next line using the imports in this file:
import operator
import os
import numpy as np
import hftools.dataset.arrayobj as aobj
from numpy import newaxis
from hftools.testing import TestCase
from hftools.testing import random_value_array_from_dims
from hftools.py3compat import PY3
and context (functions, classes, or occasionally code) from other files:
# Path: hftools/testing/common.py
# class TestCase(unittest.TestCase):
# def assertAllclose(self, a, b, rtol=1e-05, atol=1e-08, msg=None):
# a = np.asanyarray(a)
# b = np.asanyarray(b)
# if msg is None:
# msg = "a (%s) not close to b (%s)" % (a, b)
# self.assertTrue(np.allclose(a, b, rtol, atol), msg)
#
# def assertIsNotInstance(self, obj, cls):
# self.assertFalse(isinstance(obj, cls))
#
# def assertIsInstance(self, obj, cls, msg=None):
# """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
# default message."""
# if not isinstance(obj, cls):
# arg = (unittest.case.safe_repr(obj), cls)
# standardMsg = '%s is not an instance of %r' % arg
# self.fail(self._formatMessage(msg, standardMsg))
#
# def assertHFToolsWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsWarning)
# self.assertRaises(HFToolsWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsWarning)
#
# def assertHFToolsDeprecationWarning(self, funk, *k, **kw):
# warnings.resetwarnings()
# warnings.simplefilter("error", HFToolsDeprecationWarning)
# self.assertRaises(HFToolsDeprecationWarning, funk, *k, **kw)
# warnings.simplefilter("ignore", HFToolsDeprecationWarning)
#
# Path: hftools/testing/common.py
# def random_value_array_from_dims(dims, mean=0, scale=1):
# shape = tuple(dim.data.shape[0] for dim in dims)
# return hfarray(normal(size=shape) * scale + mean, dims)
#
# Path: hftools/py3compat.py
# PY3 = True
. Output only the next line. | if not PY3: |
Given snippet: <|code_start|> rank_list = list(cls)
return abs(rank_list.index(first) - rank_list.index(second))
FACE_RANKS = Rank("J"), Rank("Q"), Rank("K")
BROADWAY_RANKS = Rank("T"), Rank("J"), Rank("Q"), Rank("K"), Rank("A")
class _CardMeta(type):
def __new__(metacls, clsname, bases, classdict):
"""Cache all possible Card instances on the class itself."""
cls = super(_CardMeta, metacls).__new__(metacls, clsname, bases, classdict)
cls._all_cards = list(
cls(f"{rank}{suit}") for rank, suit in itertools.product(Rank, Suit)
)
return cls
def make_random(cls):
"""Returns a random Card instance."""
self = object.__new__(cls)
self.rank = Rank.make_random()
self.suit = Suit.make_random()
return self
def __iter__(cls):
return iter(cls._all_cards)
@total_ordering
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import itertools
from functools import total_ordering
from ._common import PokerEnum, _ReprMixin
and context:
# Path: poker/_common.py
# class PokerEnum(_OrderableMixin, enum.Enum, metaclass=_PokerEnumMeta):
# def __str__(self):
# return str(self._value_[0])
#
# def __repr__(self):
# val = self._value_[0]
# apostrophe = "'" if isinstance(val, str) else ""
# return f"{self.__class__.__name__}({apostrophe}{val}{apostrophe})"
#
# def __format__(self, format_spec):
# return str(self._value_[0])
#
# @property
# def val(self):
# """The first value of the Enum member."""
# return self._value_[0]
#
# class _ReprMixin:
# def __repr__(self):
# return f"{self.__class__.__name__}('{self}')"
which might include code, classes, or functions. Output only the next line. | class Card(_ReprMixin, metaclass=_CardMeta): |
Predict the next line for this snippet: <|code_start|> assert Card("Ts").rank == Card("Ts").rank
assert Card("2d").rank == Card("2h").rank
def test_rank_inequality():
assert Card("Ad").rank != Card("Ks").rank
assert Card("Ts").rank != Card("5h").rank
def test_rank_comparisons():
assert Card("Ac").rank > Card("Kh").rank
assert Card("Ks").rank > Card("Qd").rank
assert Card("Qs").rank > Card("Js").rank
assert Card("Jd").rank > Card("Th").rank
assert Card("Ac").rank > Card("2s").rank
def test_rank_comparisons_reverse():
assert Card("Kh").rank < Card("Ac").rank
assert Card("Qd").rank < Card("Ks").rank
assert Card("Js").rank < Card("Qs").rank
assert Card("Th").rank < Card("Jd").rank
assert Card("2s").rank < Card("Ac").rank
def test_suit():
assert Card("Ac").suit == Suit("c")
def test_rank():
<|code_end|>
with the help of current file imports:
import pytest
from poker.card import Card, Rank, Suit
and context from other files:
# Path: poker/card.py
# class Card(_ReprMixin, metaclass=_CardMeta):
# """Represents a Card, which consists a Rank and a Suit."""
#
# __slots__ = ("rank", "suit")
#
# def __new__(cls, card):
# if isinstance(card, cls):
# return card
#
# if len(card) != 2:
# raise ValueError("length should be two in %r" % card)
#
# self = object.__new__(cls)
# self.rank = Rank(card[0])
# self.suit = Suit(card[1])
# return self
#
# def __hash__(self):
# return hash(self.rank) + hash(self.suit)
#
# def __eq__(self, other):
# if self.__class__ is other.__class__:
# return self.rank == other.rank and self.suit == other.suit
# return NotImplemented
#
# def __lt__(self, other):
# if self.__class__ is not other.__class__:
# return NotImplemented
#
# # with same ranks, suit counts
# if self.rank == other.rank:
# return self.suit < other.suit
# return self.rank < other.rank
#
# def __str__(self):
# return f"{self.rank}{self.suit}"
#
# @property
# def is_face(self):
# return self.rank in FACE_RANKS
#
# @property
# def is_broadway(self):
# return self.rank in BROADWAY_RANKS
#
# class Rank(PokerEnum):
# DEUCE = "2", 2
# THREE = "3", 3
# FOUR = "4", 4
# FIVE = "5", 5
# SIX = "6", 6
# SEVEN = "7", 7
# EIGHT = "8", 8
# NINE = "9", 9
# TEN = "T", 10
# JACK = ("J",)
# QUEEN = ("Q",)
# KING = ("K",)
# ACE = "A", 1
#
# @classmethod
# def difference(cls, first, second):
# """Tells the numerical difference between two ranks."""
#
# # so we always get a Rank instance even if string were passed in
# first, second = cls(first), cls(second)
# rank_list = list(cls)
# return abs(rank_list.index(first) - rank_list.index(second))
#
# class Suit(PokerEnum):
# CLUBS = "♣", "c", "clubs"
# DIAMONDS = "♦", "d", "diamonds"
# HEARTS = "♥", "h", "hearts"
# SPADES = "♠", "s", "spades"
# # Can't make alias with redefined value property
# # because of a bug in stdlib enum module (line 162)
# # C = '♣', 'c', 'C', 'clubs'
, which may contain function names, class names, or code. Output only the next line. | assert Card("Ah").rank == Rank("A") |
Based on the snippet: <|code_start|>
def test_comparisons():
assert Card("Ac") > Card("Kh")
assert Card("Ks") > Card("Qd")
assert Card("Qs") > Card("Js")
assert Card("Jd") > Card("Th")
assert Card("Ac") > Card("2s")
def test_comparisons_reverse():
assert Card("Kh") < Card("Ac")
assert Card("Qd") < Card("Ks")
assert Card("Js") < Card("Qs")
assert Card("Th") < Card("Jd")
assert Card("2s") < Card("Ac")
def test_better_suits_are_bigger_with_same_ranks():
assert Card("Ac") < Card("Ad")
assert Card("Ac") < Card("Ah")
assert Card("Ac") < Card("As")
assert Card("Ad") < Card("Ah")
assert Card("Ad") < Card("As")
assert Card("Ah") < Card("As")
def test_unicode_suits():
assert Card("A♠") > Card("Kd")
assert Card("K♥") > Card("Kc")
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
from poker.card import Card, Rank, Suit
and context (classes, functions, sometimes code) from other files:
# Path: poker/card.py
# class Card(_ReprMixin, metaclass=_CardMeta):
# """Represents a Card, which consists a Rank and a Suit."""
#
# __slots__ = ("rank", "suit")
#
# def __new__(cls, card):
# if isinstance(card, cls):
# return card
#
# if len(card) != 2:
# raise ValueError("length should be two in %r" % card)
#
# self = object.__new__(cls)
# self.rank = Rank(card[0])
# self.suit = Suit(card[1])
# return self
#
# def __hash__(self):
# return hash(self.rank) + hash(self.suit)
#
# def __eq__(self, other):
# if self.__class__ is other.__class__:
# return self.rank == other.rank and self.suit == other.suit
# return NotImplemented
#
# def __lt__(self, other):
# if self.__class__ is not other.__class__:
# return NotImplemented
#
# # with same ranks, suit counts
# if self.rank == other.rank:
# return self.suit < other.suit
# return self.rank < other.rank
#
# def __str__(self):
# return f"{self.rank}{self.suit}"
#
# @property
# def is_face(self):
# return self.rank in FACE_RANKS
#
# @property
# def is_broadway(self):
# return self.rank in BROADWAY_RANKS
#
# class Rank(PokerEnum):
# DEUCE = "2", 2
# THREE = "3", 3
# FOUR = "4", 4
# FIVE = "5", 5
# SIX = "6", 6
# SEVEN = "7", 7
# EIGHT = "8", 8
# NINE = "9", 9
# TEN = "T", 10
# JACK = ("J",)
# QUEEN = ("Q",)
# KING = ("K",)
# ACE = "A", 1
#
# @classmethod
# def difference(cls, first, second):
# """Tells the numerical difference between two ranks."""
#
# # so we always get a Rank instance even if string were passed in
# first, second = cls(first), cls(second)
# rank_list = list(cls)
# return abs(rank_list.index(first) - rank_list.index(second))
#
# class Suit(PokerEnum):
# CLUBS = "♣", "c", "clubs"
# DIAMONDS = "♦", "d", "diamonds"
# HEARTS = "♥", "h", "hearts"
# SPADES = "♠", "s", "spades"
# # Can't make alias with redefined value property
# # because of a bug in stdlib enum module (line 162)
# # C = '♣', 'c', 'C', 'clubs'
. Output only the next line. | assert Card("aH").suit == Suit("♥") |
Given the following code snippet before the placeholder: <|code_start|>
__all__ = ["get_ranked_players", "WEBSITE_URL", "RANKINGS_URL"]
WEBSITE_URL = "http://www.pocketfives.com"
RANKINGS_URL = WEBSITE_URL + "/rankings/"
@attr.s(slots=True)
class _Player:
"""Pocketfives player data."""
name = attr.ib()
country = attr.ib()
triple_crowns = attr.ib(convert=int)
monthly_win = attr.ib(convert=int)
biggest_cash = attr.ib()
<|code_end|>
, predict the next line using imports from the current file:
import attr
import requests
from lxml import etree
from .._common import _make_float
and context including class names, function names, and sometimes code from other files:
# Path: poker/_common.py
# def _make_float(string):
# return float(string.strip().replace(",", ""))
. Output only the next line. | plb_score = attr.ib(convert=_make_float) |
Predict the next line for this snippet: <|code_start|> try:
found_name = root[0].text
except IndexError:
raise UserNotFoundError(username)
# The request is basically a search, can return multiple userids
# for users starting with username. Make sure we got the right one!
if found_name.upper() != username.upper():
exc = AmbiguousUserNameError(username)
# attach the extra users to the exception
exc.users = tuple(
_ExtraUser(name=child.text, id=child.attrib["userid"]) for child in root
) # noqa
raise exc
return root[0].attrib["userid"]
class ForumMember:
"""Download and store a member data from the Two Plus Two forum."""
_tz_re = re.compile("GMT (.*?)\.")
_attributes = (
("username", '//td[@id="username_box"]/h1/text()', str),
("rank", '//td[@id="username_box"]/h2/text()', str),
("profile_picture", '//td[@id="profilepic_cell"]/img/@src', str),
("location", '//div[@id="collapseobj_aboutme"]/div/ul/li/dl/dd[1]/text()', str),
(
"total_posts",
'//div[@id="collapseobj_stats"]/div/fieldset[1]/ul/li[1]/text()',
<|code_end|>
with the help of current file imports:
import re
import attr
import requests
import parsedatetime
from datetime import datetime
from lxml import etree
from dateutil.tz import tzoffset
from pytz import UTC
from .._common import _make_int
and context from other files:
# Path: poker/_common.py
# def _make_int(string):
# return int(string.strip().replace(",", ""))
, which may contain function names, class names, or code. Output only the next line. | _make_int, |
Using the snippet: <|code_start|>__all__ = [
"Shape",
"Hand",
"Combo",
"Range",
"PAIR_HANDS",
"OFFSUIT_HANDS",
"SUITED_HANDS",
]
# pregenerated all the possible suit combinations, so we don't have to count them all the time
_PAIR_SUIT_COMBINATIONS = ("cd", "ch", "cs", "dh", "ds", "hs")
_OFFSUIT_SUIT_COMBINATIONS = (
"cd",
"ch",
"cs",
"dc",
"dh",
"ds",
"hc",
"hd",
"hs",
"sc",
"sd",
"sh",
)
_SUITED_SUIT_COMBINATIONS = ("cc", "dd", "hh", "ss")
<|code_end|>
, determine the next line of code. You have imports:
import re
import random
import itertools
import functools
import cProfile
from decimal import Decimal
from pathlib import Path
from cached_property import cached_property
from ._common import PokerEnum, _ReprMixin
from .card import Rank, Card, BROADWAY_RANKS
and context (class names, function names, or code) available:
# Path: poker/_common.py
# class PokerEnum(_OrderableMixin, enum.Enum, metaclass=_PokerEnumMeta):
# def __str__(self):
# return str(self._value_[0])
#
# def __repr__(self):
# val = self._value_[0]
# apostrophe = "'" if isinstance(val, str) else ""
# return f"{self.__class__.__name__}({apostrophe}{val}{apostrophe})"
#
# def __format__(self, format_spec):
# return str(self._value_[0])
#
# @property
# def val(self):
# """The first value of the Enum member."""
# return self._value_[0]
#
# class _ReprMixin:
# def __repr__(self):
# return f"{self.__class__.__name__}('{self}')"
#
# Path: poker/card.py
# class Rank(PokerEnum):
# DEUCE = "2", 2
# THREE = "3", 3
# FOUR = "4", 4
# FIVE = "5", 5
# SIX = "6", 6
# SEVEN = "7", 7
# EIGHT = "8", 8
# NINE = "9", 9
# TEN = "T", 10
# JACK = ("J",)
# QUEEN = ("Q",)
# KING = ("K",)
# ACE = "A", 1
#
# @classmethod
# def difference(cls, first, second):
# """Tells the numerical difference between two ranks."""
#
# # so we always get a Rank instance even if string were passed in
# first, second = cls(first), cls(second)
# rank_list = list(cls)
# return abs(rank_list.index(first) - rank_list.index(second))
#
# class Card(_ReprMixin, metaclass=_CardMeta):
# """Represents a Card, which consists a Rank and a Suit."""
#
# __slots__ = ("rank", "suit")
#
# def __new__(cls, card):
# if isinstance(card, cls):
# return card
#
# if len(card) != 2:
# raise ValueError("length should be two in %r" % card)
#
# self = object.__new__(cls)
# self.rank = Rank(card[0])
# self.suit = Suit(card[1])
# return self
#
# def __hash__(self):
# return hash(self.rank) + hash(self.suit)
#
# def __eq__(self, other):
# if self.__class__ is other.__class__:
# return self.rank == other.rank and self.suit == other.suit
# return NotImplemented
#
# def __lt__(self, other):
# if self.__class__ is not other.__class__:
# return NotImplemented
#
# # with same ranks, suit counts
# if self.rank == other.rank:
# return self.suit < other.suit
# return self.rank < other.rank
#
# def __str__(self):
# return f"{self.rank}{self.suit}"
#
# @property
# def is_face(self):
# return self.rank in FACE_RANKS
#
# @property
# def is_broadway(self):
# return self.rank in BROADWAY_RANKS
#
# BROADWAY_RANKS = Rank("T"), Rank("J"), Rank("Q"), Rank("K"), Rank("A")
. Output only the next line. | class Shape(PokerEnum): |
Predict the next line for this snippet: <|code_start|> cls = super(_HandMeta, metacls).__new__(metacls, clsname, bases, classdict)
cls._all_hands = tuple(cls._get_non_pairs()) + tuple(cls._get_pairs())
return cls
def _get_non_pairs(cls):
for rank1 in Rank:
for rank2 in (r for r in Rank if r < rank1):
yield cls(f"{rank1}{rank2}o")
yield cls(f"{rank1}{rank2}s")
def _get_pairs(cls):
for rank in Rank:
yield cls(rank.val * 2)
def __iter__(cls):
return iter(cls._all_hands)
def make_random(cls):
obj = object.__new__(cls)
first = Rank.make_random()
second = Rank.make_random()
obj._set_ranks_in_order(first, second)
if first == second:
obj._shape = ""
else:
obj._shape = random.choice(["s", "o"])
return obj
@functools.total_ordering
<|code_end|>
with the help of current file imports:
import re
import random
import itertools
import functools
import cProfile
from decimal import Decimal
from pathlib import Path
from cached_property import cached_property
from ._common import PokerEnum, _ReprMixin
from .card import Rank, Card, BROADWAY_RANKS
and context from other files:
# Path: poker/_common.py
# class PokerEnum(_OrderableMixin, enum.Enum, metaclass=_PokerEnumMeta):
# def __str__(self):
# return str(self._value_[0])
#
# def __repr__(self):
# val = self._value_[0]
# apostrophe = "'" if isinstance(val, str) else ""
# return f"{self.__class__.__name__}({apostrophe}{val}{apostrophe})"
#
# def __format__(self, format_spec):
# return str(self._value_[0])
#
# @property
# def val(self):
# """The first value of the Enum member."""
# return self._value_[0]
#
# class _ReprMixin:
# def __repr__(self):
# return f"{self.__class__.__name__}('{self}')"
#
# Path: poker/card.py
# class Rank(PokerEnum):
# DEUCE = "2", 2
# THREE = "3", 3
# FOUR = "4", 4
# FIVE = "5", 5
# SIX = "6", 6
# SEVEN = "7", 7
# EIGHT = "8", 8
# NINE = "9", 9
# TEN = "T", 10
# JACK = ("J",)
# QUEEN = ("Q",)
# KING = ("K",)
# ACE = "A", 1
#
# @classmethod
# def difference(cls, first, second):
# """Tells the numerical difference between two ranks."""
#
# # so we always get a Rank instance even if string were passed in
# first, second = cls(first), cls(second)
# rank_list = list(cls)
# return abs(rank_list.index(first) - rank_list.index(second))
#
# class Card(_ReprMixin, metaclass=_CardMeta):
# """Represents a Card, which consists a Rank and a Suit."""
#
# __slots__ = ("rank", "suit")
#
# def __new__(cls, card):
# if isinstance(card, cls):
# return card
#
# if len(card) != 2:
# raise ValueError("length should be two in %r" % card)
#
# self = object.__new__(cls)
# self.rank = Rank(card[0])
# self.suit = Suit(card[1])
# return self
#
# def __hash__(self):
# return hash(self.rank) + hash(self.suit)
#
# def __eq__(self, other):
# if self.__class__ is other.__class__:
# return self.rank == other.rank and self.suit == other.suit
# return NotImplemented
#
# def __lt__(self, other):
# if self.__class__ is not other.__class__:
# return NotImplemented
#
# # with same ranks, suit counts
# if self.rank == other.rank:
# return self.suit < other.suit
# return self.rank < other.rank
#
# def __str__(self):
# return f"{self.rank}{self.suit}"
#
# @property
# def is_face(self):
# return self.rank in FACE_RANKS
#
# @property
# def is_broadway(self):
# return self.rank in BROADWAY_RANKS
#
# BROADWAY_RANKS = Rank("T"), Rank("J"), Rank("Q"), Rank("K"), Rank("A")
, which may contain function names, class names, or code. Output only the next line. | class Hand(_ReprMixin, metaclass=_HandMeta): |
Predict the next line after this snippet: <|code_start|> "cs",
"dc",
"dh",
"ds",
"hc",
"hd",
"hs",
"sc",
"sd",
"sh",
)
_SUITED_SUIT_COMBINATIONS = ("cc", "dd", "hh", "ss")
class Shape(PokerEnum):
OFFSUIT = "o", "offsuit", "off"
SUITED = "s", "suited"
PAIR = ("",)
class _HandMeta(type):
"""Makes Hand class iterable. __iter__ goes through all hands in ascending order."""
def __new__(metacls, clsname, bases, classdict):
"""Cache all possible Hand instances on the class itself."""
cls = super(_HandMeta, metacls).__new__(metacls, clsname, bases, classdict)
cls._all_hands = tuple(cls._get_non_pairs()) + tuple(cls._get_pairs())
return cls
def _get_non_pairs(cls):
<|code_end|>
using the current file's imports:
import re
import random
import itertools
import functools
import cProfile
from decimal import Decimal
from pathlib import Path
from cached_property import cached_property
from ._common import PokerEnum, _ReprMixin
from .card import Rank, Card, BROADWAY_RANKS
and any relevant context from other files:
# Path: poker/_common.py
# class PokerEnum(_OrderableMixin, enum.Enum, metaclass=_PokerEnumMeta):
# def __str__(self):
# return str(self._value_[0])
#
# def __repr__(self):
# val = self._value_[0]
# apostrophe = "'" if isinstance(val, str) else ""
# return f"{self.__class__.__name__}({apostrophe}{val}{apostrophe})"
#
# def __format__(self, format_spec):
# return str(self._value_[0])
#
# @property
# def val(self):
# """The first value of the Enum member."""
# return self._value_[0]
#
# class _ReprMixin:
# def __repr__(self):
# return f"{self.__class__.__name__}('{self}')"
#
# Path: poker/card.py
# class Rank(PokerEnum):
# DEUCE = "2", 2
# THREE = "3", 3
# FOUR = "4", 4
# FIVE = "5", 5
# SIX = "6", 6
# SEVEN = "7", 7
# EIGHT = "8", 8
# NINE = "9", 9
# TEN = "T", 10
# JACK = ("J",)
# QUEEN = ("Q",)
# KING = ("K",)
# ACE = "A", 1
#
# @classmethod
# def difference(cls, first, second):
# """Tells the numerical difference between two ranks."""
#
# # so we always get a Rank instance even if string were passed in
# first, second = cls(first), cls(second)
# rank_list = list(cls)
# return abs(rank_list.index(first) - rank_list.index(second))
#
# class Card(_ReprMixin, metaclass=_CardMeta):
# """Represents a Card, which consists a Rank and a Suit."""
#
# __slots__ = ("rank", "suit")
#
# def __new__(cls, card):
# if isinstance(card, cls):
# return card
#
# if len(card) != 2:
# raise ValueError("length should be two in %r" % card)
#
# self = object.__new__(cls)
# self.rank = Rank(card[0])
# self.suit = Suit(card[1])
# return self
#
# def __hash__(self):
# return hash(self.rank) + hash(self.suit)
#
# def __eq__(self, other):
# if self.__class__ is other.__class__:
# return self.rank == other.rank and self.suit == other.suit
# return NotImplemented
#
# def __lt__(self, other):
# if self.__class__ is not other.__class__:
# return NotImplemented
#
# # with same ranks, suit counts
# if self.rank == other.rank:
# return self.suit < other.suit
# return self.rank < other.rank
#
# def __str__(self):
# return f"{self.rank}{self.suit}"
#
# @property
# def is_face(self):
# return self.rank in FACE_RANKS
#
# @property
# def is_broadway(self):
# return self.rank in BROADWAY_RANKS
#
# BROADWAY_RANKS = Rank("T"), Rank("J"), Rank("Q"), Rank("K"), Rank("A")
. Output only the next line. | for rank1 in Rank: |
Here is a snippet: <|code_start|>
def __lt__(self, other):
if self.__class__ is not other.__class__:
return NotImplemented
# lookup optimization
self_is_pair, other_is_pair = self.is_pair, other.is_pair
self_first, other_first = self.first, other.first
if self_is_pair and other_is_pair:
if self_first == other_first:
return self.second < other.second
return self_first < other_first
elif self_is_pair or other_is_pair:
# Pairs are better than non-pairs
return self_is_pair < other_is_pair
else:
if self_first.rank == other_first.rank:
if self.second.rank == other.second.rank:
# same ranks, suited go first in order by Suit rank
if self.is_suited or other.is_suited:
return self.is_suited < other.is_suited
# both are suited
return self_first.suit < other_first.suit
return self.second < other.second
return self_first < other_first
def _set_cards_in_order(self, first, second):
<|code_end|>
. Write the next line using the current file imports:
import re
import random
import itertools
import functools
import cProfile
from decimal import Decimal
from pathlib import Path
from cached_property import cached_property
from ._common import PokerEnum, _ReprMixin
from .card import Rank, Card, BROADWAY_RANKS
and context from other files:
# Path: poker/_common.py
# class PokerEnum(_OrderableMixin, enum.Enum, metaclass=_PokerEnumMeta):
# def __str__(self):
# return str(self._value_[0])
#
# def __repr__(self):
# val = self._value_[0]
# apostrophe = "'" if isinstance(val, str) else ""
# return f"{self.__class__.__name__}({apostrophe}{val}{apostrophe})"
#
# def __format__(self, format_spec):
# return str(self._value_[0])
#
# @property
# def val(self):
# """The first value of the Enum member."""
# return self._value_[0]
#
# class _ReprMixin:
# def __repr__(self):
# return f"{self.__class__.__name__}('{self}')"
#
# Path: poker/card.py
# class Rank(PokerEnum):
# DEUCE = "2", 2
# THREE = "3", 3
# FOUR = "4", 4
# FIVE = "5", 5
# SIX = "6", 6
# SEVEN = "7", 7
# EIGHT = "8", 8
# NINE = "9", 9
# TEN = "T", 10
# JACK = ("J",)
# QUEEN = ("Q",)
# KING = ("K",)
# ACE = "A", 1
#
# @classmethod
# def difference(cls, first, second):
# """Tells the numerical difference between two ranks."""
#
# # so we always get a Rank instance even if string were passed in
# first, second = cls(first), cls(second)
# rank_list = list(cls)
# return abs(rank_list.index(first) - rank_list.index(second))
#
# class Card(_ReprMixin, metaclass=_CardMeta):
# """Represents a Card, which consists a Rank and a Suit."""
#
# __slots__ = ("rank", "suit")
#
# def __new__(cls, card):
# if isinstance(card, cls):
# return card
#
# if len(card) != 2:
# raise ValueError("length should be two in %r" % card)
#
# self = object.__new__(cls)
# self.rank = Rank(card[0])
# self.suit = Suit(card[1])
# return self
#
# def __hash__(self):
# return hash(self.rank) + hash(self.suit)
#
# def __eq__(self, other):
# if self.__class__ is other.__class__:
# return self.rank == other.rank and self.suit == other.suit
# return NotImplemented
#
# def __lt__(self, other):
# if self.__class__ is not other.__class__:
# return NotImplemented
#
# # with same ranks, suit counts
# if self.rank == other.rank:
# return self.suit < other.suit
# return self.rank < other.rank
#
# def __str__(self):
# return f"{self.rank}{self.suit}"
#
# @property
# def is_face(self):
# return self.rank in FACE_RANKS
#
# @property
# def is_broadway(self):
# return self.rank in BROADWAY_RANKS
#
# BROADWAY_RANKS = Rank("T"), Rank("J"), Rank("Q"), Rank("K"), Rank("A")
, which may include functions, classes, or code. Output only the next line. | self.first, self.second = Card(first), Card(second) |
Based on the snippet: <|code_start|>
@property
def is_suited(self):
return self._shape == "s"
@property
def is_offsuit(self):
return self._shape == "o"
@property
def is_connector(self):
return self.rank_difference == 1
@property
def is_one_gapper(self):
return self.rank_difference == 2
@property
def is_two_gapper(self):
return self.rank_difference == 3
@property
def rank_difference(self):
"""The difference between the first and second rank of the Hand."""
# self.first >= self.second
return Rank.difference(self.first, self.second)
@property
def is_broadway(self):
<|code_end|>
, predict the immediate next line with the help of imports:
import re
import random
import itertools
import functools
import cProfile
from decimal import Decimal
from pathlib import Path
from cached_property import cached_property
from ._common import PokerEnum, _ReprMixin
from .card import Rank, Card, BROADWAY_RANKS
and context (classes, functions, sometimes code) from other files:
# Path: poker/_common.py
# class PokerEnum(_OrderableMixin, enum.Enum, metaclass=_PokerEnumMeta):
# def __str__(self):
# return str(self._value_[0])
#
# def __repr__(self):
# val = self._value_[0]
# apostrophe = "'" if isinstance(val, str) else ""
# return f"{self.__class__.__name__}({apostrophe}{val}{apostrophe})"
#
# def __format__(self, format_spec):
# return str(self._value_[0])
#
# @property
# def val(self):
# """The first value of the Enum member."""
# return self._value_[0]
#
# class _ReprMixin:
# def __repr__(self):
# return f"{self.__class__.__name__}('{self}')"
#
# Path: poker/card.py
# class Rank(PokerEnum):
# DEUCE = "2", 2
# THREE = "3", 3
# FOUR = "4", 4
# FIVE = "5", 5
# SIX = "6", 6
# SEVEN = "7", 7
# EIGHT = "8", 8
# NINE = "9", 9
# TEN = "T", 10
# JACK = ("J",)
# QUEEN = ("Q",)
# KING = ("K",)
# ACE = "A", 1
#
# @classmethod
# def difference(cls, first, second):
# """Tells the numerical difference between two ranks."""
#
# # so we always get a Rank instance even if string were passed in
# first, second = cls(first), cls(second)
# rank_list = list(cls)
# return abs(rank_list.index(first) - rank_list.index(second))
#
# class Card(_ReprMixin, metaclass=_CardMeta):
# """Represents a Card, which consists a Rank and a Suit."""
#
# __slots__ = ("rank", "suit")
#
# def __new__(cls, card):
# if isinstance(card, cls):
# return card
#
# if len(card) != 2:
# raise ValueError("length should be two in %r" % card)
#
# self = object.__new__(cls)
# self.rank = Rank(card[0])
# self.suit = Suit(card[1])
# return self
#
# def __hash__(self):
# return hash(self.rank) + hash(self.suit)
#
# def __eq__(self, other):
# if self.__class__ is other.__class__:
# return self.rank == other.rank and self.suit == other.suit
# return NotImplemented
#
# def __lt__(self, other):
# if self.__class__ is not other.__class__:
# return NotImplemented
#
# # with same ranks, suit counts
# if self.rank == other.rank:
# return self.suit < other.suit
# return self.rank < other.rank
#
# def __str__(self):
# return f"{self.rank}{self.suit}"
#
# @property
# def is_face(self):
# return self.rank in FACE_RANKS
#
# @property
# def is_broadway(self):
# return self.rank in BROADWAY_RANKS
#
# BROADWAY_RANKS = Rank("T"), Rank("J"), Rank("Q"), Rank("K"), Rank("A")
. Output only the next line. | return self.first in BROADWAY_RANKS and self.second in BROADWAY_RANKS |
Given the following code snippet before the placeholder: <|code_start|> first.rank == second.rank for first, second in self._all_combinations
)
@cached_property
def has_straightdraw(self):
return any(1 <= diff <= 3 for diff in self._get_differences())
@cached_property
def has_gutshot(self):
return any(1 <= diff <= 4 for diff in self._get_differences())
@cached_property
def has_flushdraw(self):
return any(
first.suit == second.suit for first, second in self._all_combinations
)
@cached_property
def players(self):
if not self.actions:
return None
player_names = []
for action in self.actions:
player_name = action.name
if player_name not in player_names:
player_names.append(player_name)
return tuple(player_names)
def _get_differences(self):
return (
<|code_end|>
, predict the next line using imports from the current file:
import io
import itertools
import attr
import pytz
from datetime import datetime
from zope.interface import Interface, Attribute
from cached_property import cached_property
from .card import Rank
and context including class names, function names, and sometimes code from other files:
# Path: poker/card.py
# class Rank(PokerEnum):
# DEUCE = "2", 2
# THREE = "3", 3
# FOUR = "4", 4
# FIVE = "5", 5
# SIX = "6", 6
# SEVEN = "7", 7
# EIGHT = "8", 8
# NINE = "9", 9
# TEN = "T", 10
# JACK = ("J",)
# QUEEN = ("Q",)
# KING = ("K",)
# ACE = "A", 1
#
# @classmethod
# def difference(cls, first, second):
# """Tells the numerical difference between two ranks."""
#
# # so we always get a Rank instance even if string were passed in
# first, second = cls(first), cls(second)
# rank_list = list(cls)
# return abs(rank_list.index(first) - rank_list.index(second))
. Output only the next line. | Rank.difference(first.rank, second.rank) |
Continue the code snippet: <|code_start|>
class SmartLoader(FileSystemLoader):
"""A smart template loader"""
available_extension = ['.html', '.xml']
def get_source(self, environment, template):
if template is None:
raise TemplateNotFound(template)
if '.' in template:
return super(SmartLoader, self).get_source(environment, template)
for extension in SmartLoader.available_extension:
try:
filename = template + extension
return super(SmartLoader, self).get_source(environment, filename)
except TemplateNotFound:
pass
raise TemplateNotFound(template)
class Template(object):
"""Template"""
def __init__(self, path, filters=None, **kwargs):
loader = ChoiceLoader([
SmartLoader(path),
<|code_end|>
. Use current file imports:
from os import path
from jinja2 import FileSystemLoader, ChoiceLoader
from jinja2.exceptions import TemplateNotFound
from peanut.utils import get_resource
import jinja2
import peanut
and context (classes, functions, or code) from other files:
# Path: peanut/utils.py
# def get_resource(relative_path):
# package_path = os.path.abspath(os.path.split(__file__)[0])
# return os.path.join(package_path, relative_path)
. Output only the next line. | SmartLoader(get_resource('themes/default')), |
Predict the next line for this snippet: <|code_start|>Options:
-c --config Config file path.
-v Visiable.
-d Show Debug.
-h --help Show help.
--version Show version.
"""
def main():
"""Read command line arguments and generate site
"""
args = docopt(__doc__, version='Peanut '+peanut.version)
directory = args.get('<directory>', './') or './'
config_path = args.get('<config_file_path>', None)
visiable = args.get('-v', False)
debug = args.get('-d', False)
if debug:
init_logger(logging.DEBUG)
elif visiable:
init_logger(logging.VISIABLE)
else:
init_logger(logging.INFO)
if args['init']:
logging.info('Init peanut environments')
<|code_end|>
with the help of current file imports:
import logging
import peanut
from docopt import docopt
from peanut import site
from peanut.logger import init_logger
and context from other files:
# Path: peanut/site.py
# class Site(object):
# def __init__(self, directory='.'):
# def init(directory='./'):
# def load_config(self, config_path):
# def load_drafts(self):
# def parse_draft(self, draft_file):
# def push(self, url, username, password):
# def generate(self):
#
# Path: peanut/logger.py
# def init_logger(level):
# logging.basicConfig(format='%(message)s', level=level)
, which may contain function names, class names, or code. Output only the next line. | site.Site.init(directory) |
Given the code snippet: <|code_start|>
Usage:
peanut init [(-v|-d)] [<directory>]
peanut ghost <url> <username> <password>
peanut [(-v|-d)] [-c | --config <config_file_path>] [<directory>]
peanut (-h | --help)
peanut --version
Options:
-c --config Config file path.
-v Visiable.
-d Show Debug.
-h --help Show help.
--version Show version.
"""
def main():
"""Read command line arguments and generate site
"""
args = docopt(__doc__, version='Peanut '+peanut.version)
directory = args.get('<directory>', './') or './'
config_path = args.get('<config_file_path>', None)
visiable = args.get('-v', False)
debug = args.get('-d', False)
if debug:
<|code_end|>
, generate the next line using the imports in this file:
import logging
import peanut
from docopt import docopt
from peanut import site
from peanut.logger import init_logger
and context (functions, classes, or occasionally code) from other files:
# Path: peanut/site.py
# class Site(object):
# def __init__(self, directory='.'):
# def init(directory='./'):
# def load_config(self, config_path):
# def load_drafts(self):
# def parse_draft(self, draft_file):
# def push(self, url, username, password):
# def generate(self):
#
# Path: peanut/logger.py
# def init_logger(level):
# logging.basicConfig(format='%(message)s', level=level)
. Output only the next line. | init_logger(logging.DEBUG) |
Here is a snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Post, Tag and Category
"""
from __future__ import unicode_literals
class BaseModel(object):
"""Base model class
"""
layout = None
@property
def file_path(self):
template = configs.path.get(self.__class__.layout, '').lstrip('/')
return url_safe(template.format(**self.__dict__))
@property
def url(self):
<|code_end|>
. Write the next line using the current file imports:
import re
import os
from datetime import datetime
from peanut.utils import path_to_url, url_safe, real_url
from peanut.options import configs, env
and context from other files:
# Path: peanut/utils.py
# def path_to_url(path):
# if six.PY2:
# path = path.encode('utf-8')
# return pathname2url(path)
#
# def url_safe(string):
# new_str = re.sub(
# r'[<>,~!#&\{\}\(\)\[\]\*\^\$\?]', ' ', string
# )
#
# return '-'.join(new_str.strip().split())
#
# def real_url(base, url):
# path = urlsplit(base).path
# if not path.endswith('/'):
# path = path + '/'
# url = url.lstrip('/')
# return urljoin(path, url)
#
# Path: peanut/options.py
# class ValidationError(Exception):
# class LoadingError(ValidationError):
# class Option(dict):
# def __init__(self, msg=None):
# def __init__(self, *args, **kwargs):
# def __setitem__(self, key, value):
# def __getitem__(self, name):
# def __delitem__(self, name):
# def __real_update(self, key, value):
# def update(self, *args, **kwargs):
# def verify_path():
# def verify_theme():
# def verify_configs():
# def load_yaml(path):
# def load_configs(path):
, which may include functions, classes, or code. Output only the next line. | relative_url = path_to_url(self.file_path) |
Given snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Post, Tag and Category
"""
from __future__ import unicode_literals
class BaseModel(object):
"""Base model class
"""
layout = None
@property
def file_path(self):
template = configs.path.get(self.__class__.layout, '').lstrip('/')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import re
import os
from datetime import datetime
from peanut.utils import path_to_url, url_safe, real_url
from peanut.options import configs, env
and context:
# Path: peanut/utils.py
# def path_to_url(path):
# if six.PY2:
# path = path.encode('utf-8')
# return pathname2url(path)
#
# def url_safe(string):
# new_str = re.sub(
# r'[<>,~!#&\{\}\(\)\[\]\*\^\$\?]', ' ', string
# )
#
# return '-'.join(new_str.strip().split())
#
# def real_url(base, url):
# path = urlsplit(base).path
# if not path.endswith('/'):
# path = path + '/'
# url = url.lstrip('/')
# return urljoin(path, url)
#
# Path: peanut/options.py
# class ValidationError(Exception):
# class LoadingError(ValidationError):
# class Option(dict):
# def __init__(self, msg=None):
# def __init__(self, *args, **kwargs):
# def __setitem__(self, key, value):
# def __getitem__(self, name):
# def __delitem__(self, name):
# def __real_update(self, key, value):
# def update(self, *args, **kwargs):
# def verify_path():
# def verify_theme():
# def verify_configs():
# def load_yaml(path):
# def load_configs(path):
which might include code, classes, or functions. Output only the next line. | return url_safe(template.format(**self.__dict__)) |
Here is a snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Post, Tag and Category
"""
from __future__ import unicode_literals
class BaseModel(object):
"""Base model class
"""
layout = None
@property
def file_path(self):
template = configs.path.get(self.__class__.layout, '').lstrip('/')
return url_safe(template.format(**self.__dict__))
@property
def url(self):
relative_url = path_to_url(self.file_path)
if not relative_url.startswith('/'):
relative_url = '/'+relative_url
<|code_end|>
. Write the next line using the current file imports:
import re
import os
from datetime import datetime
from peanut.utils import path_to_url, url_safe, real_url
from peanut.options import configs, env
and context from other files:
# Path: peanut/utils.py
# def path_to_url(path):
# if six.PY2:
# path = path.encode('utf-8')
# return pathname2url(path)
#
# def url_safe(string):
# new_str = re.sub(
# r'[<>,~!#&\{\}\(\)\[\]\*\^\$\?]', ' ', string
# )
#
# return '-'.join(new_str.strip().split())
#
# def real_url(base, url):
# path = urlsplit(base).path
# if not path.endswith('/'):
# path = path + '/'
# url = url.lstrip('/')
# return urljoin(path, url)
#
# Path: peanut/options.py
# class ValidationError(Exception):
# class LoadingError(ValidationError):
# class Option(dict):
# def __init__(self, msg=None):
# def __init__(self, *args, **kwargs):
# def __setitem__(self, key, value):
# def __getitem__(self, name):
# def __delitem__(self, name):
# def __real_update(self, key, value):
# def update(self, *args, **kwargs):
# def verify_path():
# def verify_theme():
# def verify_configs():
# def load_yaml(path):
# def load_configs(path):
, which may include functions, classes, or code. Output only the next line. | return real_url(configs.site.url, relative_url) |
Next line prediction: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Post, Tag and Category
"""
from __future__ import unicode_literals
class BaseModel(object):
"""Base model class
"""
layout = None
@property
def file_path(self):
<|code_end|>
. Use current file imports:
(import re
import os
from datetime import datetime
from peanut.utils import path_to_url, url_safe, real_url
from peanut.options import configs, env)
and context including class names, function names, or small code snippets from other files:
# Path: peanut/utils.py
# def path_to_url(path):
# if six.PY2:
# path = path.encode('utf-8')
# return pathname2url(path)
#
# def url_safe(string):
# new_str = re.sub(
# r'[<>,~!#&\{\}\(\)\[\]\*\^\$\?]', ' ', string
# )
#
# return '-'.join(new_str.strip().split())
#
# def real_url(base, url):
# path = urlsplit(base).path
# if not path.endswith('/'):
# path = path + '/'
# url = url.lstrip('/')
# return urljoin(path, url)
#
# Path: peanut/options.py
# class ValidationError(Exception):
# class LoadingError(ValidationError):
# class Option(dict):
# def __init__(self, msg=None):
# def __init__(self, *args, **kwargs):
# def __setitem__(self, key, value):
# def __getitem__(self, name):
# def __delitem__(self, name):
# def __real_update(self, key, value):
# def update(self, *args, **kwargs):
# def verify_path():
# def verify_theme():
# def verify_configs():
# def load_yaml(path):
# def load_configs(path):
. Output only the next line. | template = configs.path.get(self.__class__.layout, '').lstrip('/') |
Using the snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
def init_logger(level):
logging.basicConfig(format='%(message)s', level=level)
_FORMAT = '\033[{}m\033[{};{}m{}\033[0m'
colors = ['black', 'red', 'green', 'yellow', 'blue',
'magenta', 'cyan', 'white']
attributes = ['blod', 'underscore', 'blink', 'reverse', 'concealed']
_FOREGROUND = dict(zip(colors, list(range(30, 38))))
_BACKGROUND = dict(zip(colors, list(range(40, 48))))
_attributes = dict(zip(attributes, [1, 4, 5, 7, 8]))
def color(msg, fg, bg=None, attr=None):
fg_code = _FOREGROUND.get(fg, 39)
bg_code = _BACKGROUND.get(bg, 49)
att_code = _attributes.get(attr, 0)
return _FORMAT.format(att_code, bg_code, fg_code, msg)
def pretty(func, prefix=None, fg=None, bg=None, attr=None):
def wrapper(msg, *args, **kwargs):
<|code_end|>
, determine the next line of code. You have imports:
import six
import logging
from functools import partial
from peanut.utils import to_s, to_u
and context (class names, function names, or code) available:
# Path: peanut/utils.py
# def to_s(value):
# return str(value)
#
# def to_u(value):
# return str(value)
. Output only the next line. | log = to_s(msg % args) |
Here is a snippet: <|code_start|>class MarkdownReader(with_metaclass(Singleton, Reader)):
"""Markdown reader
"""
regex = re.compile(r'([^/]+)\.(MD|md|[mM]arkdown)')
# Meta data parser
_meta_parser = {
'tags': parser_list,
'category': parser_single,
'date': parser_date,
'publish': parser_bool,
'top': parser_bool,
'image': parser_single,
}
def __init__(self):
self.md_parser = MarkdownReader.__create_md_reader()
@classmethod
def __create_md_reader(cls):
"""Create markdown parser
"""
extensions = [
'markdown.extensions.fenced_code', # Fenced Code Blocks
'markdown.extensions.codehilite', # CodeHilite
'markdown.extensions.footnotes', # Footnotes
'markdown.extensions.tables', # Tables
'markdown.extensions.toc', # Table of Contents
<|code_end|>
. Write the next line using the current file imports:
import os
import six
import re
import markdown
import datetime
import logging
from six import with_metaclass
from peanut.meta_yaml import MetaYamlExtension
and context from other files:
# Path: peanut/meta_yaml.py
# class MetaYamlExtension (Extension):
# """Extension for parsing YAML-Metadata with Python-Markdown."""
#
# def extendMarkdown(self, md, md_globals):
# """Add MetaYamlPreprocessor to Markdown instance."""
# md.preprocessors.add("meta_yaml", MetaYamlPreprocessor(md), "_begin")
, which may include functions, classes, or code. Output only the next line. | MetaYamlExtension(), # Meta-YAML |
Here is a snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Config unittest
"""
PWD = os.path.abspath(os.path.dirname(__file__))
class TestConfig(unittest.TestCase):
def test_load(self):
<|code_end|>
. Write the next line using the current file imports:
import os
import unittest
from peanut.options import configs, load_configs
and context from other files:
# Path: peanut/options.py
# class ValidationError(Exception):
# class LoadingError(ValidationError):
# class Option(dict):
# def __init__(self, msg=None):
# def __init__(self, *args, **kwargs):
# def __setitem__(self, key, value):
# def __getitem__(self, name):
# def __delitem__(self, name):
# def __real_update(self, key, value):
# def update(self, *args, **kwargs):
# def verify_path():
# def verify_theme():
# def verify_configs():
# def load_yaml(path):
# def load_configs(path):
, which may include functions, classes, or code. Output only the next line. | configs.pwd = os.path.join(PWD, 'test_site') |
Given snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Config unittest
"""
PWD = os.path.abspath(os.path.dirname(__file__))
class TestConfig(unittest.TestCase):
def test_load(self):
configs.pwd = os.path.join(PWD, 'test_site')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import unittest
from peanut.options import configs, load_configs
and context:
# Path: peanut/options.py
# class ValidationError(Exception):
# class LoadingError(ValidationError):
# class Option(dict):
# def __init__(self, msg=None):
# def __init__(self, *args, **kwargs):
# def __setitem__(self, key, value):
# def __getitem__(self, name):
# def __delitem__(self, name):
# def __real_update(self, key, value):
# def update(self, *args, **kwargs):
# def verify_path():
# def verify_theme():
# def verify_configs():
# def load_yaml(path):
# def load_configs(path):
which might include code, classes, or functions. Output only the next line. | load_configs('config.yml') |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Model unittest
"""
from __future__ import unicode_literals
class TestPost(unittest.TestCase):
def test_post(self):
meta = {
'date': None,
'tags': ['hello', 'world'],
'layout': 'post',
'top': True,
'publish': False,
'author': 'zqqf16',
'image' : 'http://test.com/test.png',
'test' : 'test'
}
<|code_end|>
with the help of current file imports:
import unittest
from datetime import datetime
from peanut.model import Post, Tag, Pagination
from peanut.options import configs, env
and context from other files:
# Path: peanut/model.py
# class Post(BaseModel):
# """Post model
# """
#
# layout = 'post'
#
# def __init__(self, title, slug, raw=None, content=None, meta=None):
# self.title = title
# self.slug = url_safe(slug)
# self.content = content
# self.raw = raw
#
# meta = meta or {}
# self.date = meta.pop('date', None) or datetime.now()
# self.publish = meta.pop('publish', True)
# self.layout = meta.pop('layout', Post.layout)
# self.top = meta.pop('top', False)
# self.tag_titles = meta.pop('tags', [])
#
# image = meta.pop('image', None)
# if isinstance(image, dict):
# self.image = image.get('feature', None)
# else:
# self.image = image
#
# self.meta = meta
#
# @property
# def tags(self):
# return [Tag(t) for t in self.tag_titles]
#
# def __getattr__(self, key):
# try:
# return super(Post, self).__getattr__(key)
# except:
# pass
# return self.meta.get(key)
#
# def __lt__(self, other):
# return self.date < other.date
#
# class Tag(BaseModel):
# """Tag model
# """
#
# layout = 'tag'
#
# def __init__(self, title):
# self.title = title
# self.slug = url_safe(title)
#
# def __eq__(self, other):
# return self.title == other.title
#
# def __hash__(self):
# return hash(self.title)
#
# class Pagination(object):
# """Pagination"""
#
# def __init__(self, posts, page=1, base_url=None, posts_per_page = 5):
# self._posts = posts
# # page number starts from 1
# self.page = page
# self.base_url = base_url
# if posts_per_page == 0:
# posts_per_page = len(self._posts)
# self.posts_per_page = posts_per_page
#
# self.path = None
# self.url = None
# self.parse_path_and_url()
#
# def parse_path_and_url(self):
# template = configs.path.pagination
# relative_path = template.format(
# number=self.page,
# num=self.page,
# n=self.page
# )
#
# if self.page == 1:
# relative_path = ''
#
# file_path = None
# url = None
# if re.search(r'index.html?$', self.base_url):
# # If base_url ends with index.html or index.htm,
# # insert page path before the index.*
# parent, index = os.path.split(self.base_url)
# url = file_path = os.path.join(parent, relative_path, index)
# else:
# if not self.base_url.endswith('/'):
# self.base_url = self.base_url + '/'
# else:
# if relative_path != '' and not relative_path.endswith('/'):
# relative_path = relative_path + '/'
# url = os.path.join(self.base_url, relative_path)
# file_path = os.path.join(url, 'index.html')
#
# if not url.startswith('/'):
# url = '/' + url
# if file_path.startswith('/'):
# file_path = file_path[1:]
#
# self.file_path = url_safe(file_path)
# self.url = url_safe(url)
#
# @property
# def posts(self):
# start = (self.page - 1) * self.posts_per_page
# end = start + self.posts_per_page
# return self._posts[start:end]
#
# @property
# def total(self):
# if self.posts_per_page == 0:
# return 1
# else:
# return int((len(self._posts)-1)/self.posts_per_page) + 1
#
# @property
# def next(self):
# if self.page == self.total:
# return None
# return Pagination(self._posts, self.page+1,
# self.base_url, self.posts_per_page)
#
# @property
# def prev(self):
# if self.page == 1:
# return None
# return Pagination(self._posts, self.page-1,
# self.base_url, self.posts_per_page)
#
# def iterate(self):
# curr = self
# for i in range(curr.page-1, self.total):
# yield curr
# curr = curr.next
#
# Path: peanut/options.py
# class ValidationError(Exception):
# class LoadingError(ValidationError):
# class Option(dict):
# def __init__(self, msg=None):
# def __init__(self, *args, **kwargs):
# def __setitem__(self, key, value):
# def __getitem__(self, name):
# def __delitem__(self, name):
# def __real_update(self, key, value):
# def update(self, *args, **kwargs):
# def verify_path():
# def verify_theme():
# def verify_configs():
# def load_yaml(path):
# def load_configs(path):
, which may contain function names, class names, or code. Output only the next line. | post = Post('Hello world', 'hello_world', 'Hello world', meta=meta) |
Given the code snippet: <|code_start|>from __future__ import unicode_literals
class TestPost(unittest.TestCase):
def test_post(self):
meta = {
'date': None,
'tags': ['hello', 'world'],
'layout': 'post',
'top': True,
'publish': False,
'author': 'zqqf16',
'image' : 'http://test.com/test.png',
'test' : 'test'
}
post = Post('Hello world', 'hello_world', 'Hello world', meta=meta)
now = datetime.now()
self.assertEqual(post.title, 'Hello world')
self.assertEqual(post.slug, 'hello_world')
self.assertEqual(post.author, 'zqqf16')
self.assertEqual(post.layout, 'post')
self.assertEqual(post.test, 'test')
self.assertEqual(post.image, 'http://test.com/test.png')
self.assertEqual(post.date.year, now.year)
self.assertTrue(post.top)
self.assertFalse(post.publish)
<|code_end|>
, generate the next line using the imports in this file:
import unittest
from datetime import datetime
from peanut.model import Post, Tag, Pagination
from peanut.options import configs, env
and context (functions, classes, or occasionally code) from other files:
# Path: peanut/model.py
# class Post(BaseModel):
# """Post model
# """
#
# layout = 'post'
#
# def __init__(self, title, slug, raw=None, content=None, meta=None):
# self.title = title
# self.slug = url_safe(slug)
# self.content = content
# self.raw = raw
#
# meta = meta or {}
# self.date = meta.pop('date', None) or datetime.now()
# self.publish = meta.pop('publish', True)
# self.layout = meta.pop('layout', Post.layout)
# self.top = meta.pop('top', False)
# self.tag_titles = meta.pop('tags', [])
#
# image = meta.pop('image', None)
# if isinstance(image, dict):
# self.image = image.get('feature', None)
# else:
# self.image = image
#
# self.meta = meta
#
# @property
# def tags(self):
# return [Tag(t) for t in self.tag_titles]
#
# def __getattr__(self, key):
# try:
# return super(Post, self).__getattr__(key)
# except:
# pass
# return self.meta.get(key)
#
# def __lt__(self, other):
# return self.date < other.date
#
# class Tag(BaseModel):
# """Tag model
# """
#
# layout = 'tag'
#
# def __init__(self, title):
# self.title = title
# self.slug = url_safe(title)
#
# def __eq__(self, other):
# return self.title == other.title
#
# def __hash__(self):
# return hash(self.title)
#
# class Pagination(object):
# """Pagination"""
#
# def __init__(self, posts, page=1, base_url=None, posts_per_page = 5):
# self._posts = posts
# # page number starts from 1
# self.page = page
# self.base_url = base_url
# if posts_per_page == 0:
# posts_per_page = len(self._posts)
# self.posts_per_page = posts_per_page
#
# self.path = None
# self.url = None
# self.parse_path_and_url()
#
# def parse_path_and_url(self):
# template = configs.path.pagination
# relative_path = template.format(
# number=self.page,
# num=self.page,
# n=self.page
# )
#
# if self.page == 1:
# relative_path = ''
#
# file_path = None
# url = None
# if re.search(r'index.html?$', self.base_url):
# # If base_url ends with index.html or index.htm,
# # insert page path before the index.*
# parent, index = os.path.split(self.base_url)
# url = file_path = os.path.join(parent, relative_path, index)
# else:
# if not self.base_url.endswith('/'):
# self.base_url = self.base_url + '/'
# else:
# if relative_path != '' and not relative_path.endswith('/'):
# relative_path = relative_path + '/'
# url = os.path.join(self.base_url, relative_path)
# file_path = os.path.join(url, 'index.html')
#
# if not url.startswith('/'):
# url = '/' + url
# if file_path.startswith('/'):
# file_path = file_path[1:]
#
# self.file_path = url_safe(file_path)
# self.url = url_safe(url)
#
# @property
# def posts(self):
# start = (self.page - 1) * self.posts_per_page
# end = start + self.posts_per_page
# return self._posts[start:end]
#
# @property
# def total(self):
# if self.posts_per_page == 0:
# return 1
# else:
# return int((len(self._posts)-1)/self.posts_per_page) + 1
#
# @property
# def next(self):
# if self.page == self.total:
# return None
# return Pagination(self._posts, self.page+1,
# self.base_url, self.posts_per_page)
#
# @property
# def prev(self):
# if self.page == 1:
# return None
# return Pagination(self._posts, self.page-1,
# self.base_url, self.posts_per_page)
#
# def iterate(self):
# curr = self
# for i in range(curr.page-1, self.total):
# yield curr
# curr = curr.next
#
# Path: peanut/options.py
# class ValidationError(Exception):
# class LoadingError(ValidationError):
# class Option(dict):
# def __init__(self, msg=None):
# def __init__(self, *args, **kwargs):
# def __setitem__(self, key, value):
# def __getitem__(self, name):
# def __delitem__(self, name):
# def __real_update(self, key, value):
# def update(self, *args, **kwargs):
# def verify_path():
# def verify_theme():
# def verify_configs():
# def load_yaml(path):
# def load_configs(path):
. Output only the next line. | configs.path.post = 'posts/{slug}.html' |
Based on the snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Context for template rendering"""
# Filters
def asset(config, value):
"""Get asset file url"""
asset_path = config.path['asset']
rel = urljoin(asset_path, value)
<|code_end|>
, predict the immediate next line with the help of imports:
from functools import partial
from datetime import datetime
from peanut.utils import urljoin, real_url
and context (classes, functions, sometimes code) from other files:
# Path: peanut/utils.py
# def to_s(value):
# def to_u(value):
# def path_to_url(path):
# def url_to_path(url):
# def url_safe(string):
# def real_url(base, url):
# def package_resource(path):
# def neighborhood(alist):
# def list_dir(path):
# def get_resource(relative_path):
. Output only the next line. | return real_url(config.site.url, rel) |
Predict the next line for this snippet: <|code_start|>
handlers = Blueprint('handlers', __name__)
@handlers.route("/")
@varsnap
def index() -> Any:
return render_template("index.htm")
@handlers.route("/resume")
def resume() -> Any:
return render_template("resume.htm")
@handlers.route("/projects")
def projects() -> Any:
<|code_end|>
with the help of current file imports:
from typing import Any
from urllib.parse import urljoin
from feedgen.feed import FeedGenerator
from flask import (
Blueprint,
Response,
abort,
redirect,
render_template,
request,
url_for,
)
from varsnap import varsnap
from app import data, note_util
and context from other files:
# Path: app/data.py
# class Projects():
# class Language():
# class Project():
# class Shelf():
# class Section():
# class Item():
# def __init__(self) -> None:
# def load_from_file() -> 'Projects':
# def load(data: Dict[str, Dict[str, Dict[str, str]]]) -> 'Projects':
# def __init__(self) -> None:
# def load(key: str, data: Dict[str, Dict[str, str]]) -> 'Language':
# def __init__(self) -> None:
# def load(key: str, data: Dict[str, str]) -> 'Project':
# def links(self) -> Dict[str, str]:
# def get_projects() -> Projects:
# def __init__(self) -> None:
# def load_from_file() -> 'Shelf':
# def load(shelf_data: Dict[str, List[Dict[str, str]]]) -> 'Shelf':
# def __init__(self) -> None:
# def load(name: str, data: List[Dict[str, str]]) -> 'Section':
# def __init__(self) -> None:
# def load(data: Dict[str, str]) -> 'Item':
# def get_shelf() -> Shelf:
#
# Path: app/note_util.py
# MARKDOWN_EXTRAS = [
# 'code-friendly',
# 'fenced-code-blocks',
# 'smarty-pants',
# 'tables',
# ]
# TIMEZONE = ZoneInfo(os.environ['DISPLAY_TIMEZONE'])
# NOTES_DIRECTORY = 'notes'
# REFERENCE_DIRECTORY = 'reference'
# class Note(object):
# def __init__(self) -> None:
# def __eq__(self, other: Any) -> bool:
# def __repr__(self) -> str:
# def get_note_file_data(note_file: str) -> Optional["Note"]:
# def parse_time(timestamp_str: str) -> datetime.datetime:
# def parse_markdown(markdown: str) -> str:
# def write_note(self) -> None:
# def prune_note_files(note_files: List[str]) -> List[str]:
# def is_valid_note(note_file: str) -> bool:
# def get_note_files(directory: str) -> List[str]:
# def get_notes(directory: str) -> List[Note]:
# def get_note_from_slug(directory: str, slug: str) -> Optional[Note]:
, which may contain function names, class names, or code. Output only the next line. | projects = data.get_projects() |
Based on the snippet: <|code_start|>
handlers = Blueprint('handlers', __name__)
@handlers.route("/")
@varsnap
def index() -> Any:
return render_template("index.htm")
@handlers.route("/resume")
def resume() -> Any:
return render_template("resume.htm")
@handlers.route("/projects")
def projects() -> Any:
projects = data.get_projects()
return render_template("projects.htm", projects=projects)
@handlers.route("/notes")
def notes() -> Any:
<|code_end|>
, predict the immediate next line with the help of imports:
from typing import Any
from urllib.parse import urljoin
from feedgen.feed import FeedGenerator
from flask import (
Blueprint,
Response,
abort,
redirect,
render_template,
request,
url_for,
)
from varsnap import varsnap
from app import data, note_util
and context (classes, functions, sometimes code) from other files:
# Path: app/data.py
# class Projects():
# class Language():
# class Project():
# class Shelf():
# class Section():
# class Item():
# def __init__(self) -> None:
# def load_from_file() -> 'Projects':
# def load(data: Dict[str, Dict[str, Dict[str, str]]]) -> 'Projects':
# def __init__(self) -> None:
# def load(key: str, data: Dict[str, Dict[str, str]]) -> 'Language':
# def __init__(self) -> None:
# def load(key: str, data: Dict[str, str]) -> 'Project':
# def links(self) -> Dict[str, str]:
# def get_projects() -> Projects:
# def __init__(self) -> None:
# def load_from_file() -> 'Shelf':
# def load(shelf_data: Dict[str, List[Dict[str, str]]]) -> 'Shelf':
# def __init__(self) -> None:
# def load(name: str, data: List[Dict[str, str]]) -> 'Section':
# def __init__(self) -> None:
# def load(data: Dict[str, str]) -> 'Item':
# def get_shelf() -> Shelf:
#
# Path: app/note_util.py
# MARKDOWN_EXTRAS = [
# 'code-friendly',
# 'fenced-code-blocks',
# 'smarty-pants',
# 'tables',
# ]
# TIMEZONE = ZoneInfo(os.environ['DISPLAY_TIMEZONE'])
# NOTES_DIRECTORY = 'notes'
# REFERENCE_DIRECTORY = 'reference'
# class Note(object):
# def __init__(self) -> None:
# def __eq__(self, other: Any) -> bool:
# def __repr__(self) -> str:
# def get_note_file_data(note_file: str) -> Optional["Note"]:
# def parse_time(timestamp_str: str) -> datetime.datetime:
# def parse_markdown(markdown: str) -> str:
# def write_note(self) -> None:
# def prune_note_files(note_files: List[str]) -> List[str]:
# def is_valid_note(note_file: str) -> bool:
# def get_note_files(directory: str) -> List[str]:
# def get_notes(directory: str) -> List[Note]:
# def get_note_from_slug(directory: str, slug: str) -> Optional[Note]:
. Output only the next line. | posts = note_util.get_notes(note_util.NOTES_DIRECTORY) |
Given the following code snippet before the placeholder: <|code_start|> self.github: str = ''
self.rubygems: str = ''
self.pypi: str = ''
self.npm: str = ''
self.web: str = ''
@staticmethod
def load(key: str, data: Dict[str, str]) -> 'Project':
project = Project()
project.name = key
project.description = data.get('description', '')
project.github = data.get('github', '')
project.rubygems = data.get('rubygems', '')
project.pypi = data.get('pypi', '')
project.npm = data.get('npm', '')
project.web = data.get('web', '')
return project
def links(self) -> Dict[str, str]:
links: Dict[str, str] = {
'github': self.github,
'rubygems': self.rubygems,
'pypi': self.pypi,
'npm': self.npm,
'web': self.web,
}
links = dict([(k, v) for k, v in links.items() if v])
return links
<|code_end|>
, predict the next line using imports from the current file:
import json
import os
from typing import Dict, List
from app.util import cached_function
and context including class names, function names, and sometimes code from other files:
# Path: app/util.py
# def cached_function(func: Callable[..., Any]) -> Callable[..., Any]:
# data = {}
#
# def wrapper(*args: Any) -> Any:
# if not SHOULD_CACHE:
# return func(*args)
# cache_key = ' '.join([str(x) for x in args])
# if cache_key not in data:
# data[cache_key] = func(*args)
# return data[cache_key]
#
# wrapper.__qualname__ = func.__qualname__
# wrapper.__signature__ = inspect.signature(func) # type: ignore
# return wrapper
. Output only the next line. | @cached_function |
Given the following code snippet before the placeholder: <|code_start|>
class TestProjects(unittest.TestCase):
def setUp(self) -> None:
self.original_cache = util.SHOULD_CACHE
util.SHOULD_CACHE = True
def tearDown(self) -> None:
util.SHOULD_CACHE = self.original_cache
def test_load_from_file(self) -> None:
<|code_end|>
, predict the next line using imports from the current file:
import unittest
from app import data, util
and context including class names, function names, and sometimes code from other files:
# Path: app/data.py
# class Projects():
# class Language():
# class Project():
# class Shelf():
# class Section():
# class Item():
# def __init__(self) -> None:
# def load_from_file() -> 'Projects':
# def load(data: Dict[str, Dict[str, Dict[str, str]]]) -> 'Projects':
# def __init__(self) -> None:
# def load(key: str, data: Dict[str, Dict[str, str]]) -> 'Language':
# def __init__(self) -> None:
# def load(key: str, data: Dict[str, str]) -> 'Project':
# def links(self) -> Dict[str, str]:
# def get_projects() -> Projects:
# def __init__(self) -> None:
# def load_from_file() -> 'Shelf':
# def load(shelf_data: Dict[str, List[Dict[str, str]]]) -> 'Shelf':
# def __init__(self) -> None:
# def load(name: str, data: List[Dict[str, str]]) -> 'Section':
# def __init__(self) -> None:
# def load(data: Dict[str, str]) -> 'Item':
# def get_shelf() -> Shelf:
#
# Path: app/util.py
# SHOULD_CACHE = os.environ.get('ENV', 'development') == 'production'
# def cached_function(func: Callable[..., Any]) -> Callable[..., Any]:
# def wrapper(*args: Any) -> Any:
. Output only the next line. | projects = data.Projects.load_from_file() |
Next line prediction: <|code_start|> }
data = {
'api_key': os.environ.get('GRAMMARBOT_TOKEN'),
'language': 'en-US',
'text': text,
}
response = requests.get(url, cast(Any, data), headers=headers)
content = json.loads(response.content)
matches = content['matches']
matches = [
m for m in matches
if m['rule']['id'] not in TestGrammar.IGNORED
]
matches = [
m for m in matches
if not any([
i in m['message'] for i in TestGrammar.IGNORED_KEYWORDS
])
]
self.assertEqual(len(matches), 0, json.dumps(matches, indent=4))
class TestStyle(unittest.TestCase):
def check_title_case(self, note: note_util.Note) -> None:
title = re.sub('".*"', '', note.title)
self.assertEqual(title, titlecase(title), note.note_file)
class TestPage(unittest.TestCase):
def setUp(self) -> None:
<|code_end|>
. Use current file imports:
(import datetime
import json
import os
import re
import tempfile
import unittest
import requests
from typing import Any, Callable, cast
from titlecase import titlecase
from varsnap import test
from app import note_util, serve)
and context including class names, function names, or small code snippets from other files:
# Path: app/note_util.py
# MARKDOWN_EXTRAS = [
# 'code-friendly',
# 'fenced-code-blocks',
# 'smarty-pants',
# 'tables',
# ]
# TIMEZONE = ZoneInfo(os.environ['DISPLAY_TIMEZONE'])
# NOTES_DIRECTORY = 'notes'
# REFERENCE_DIRECTORY = 'reference'
# class Note(object):
# def __init__(self) -> None:
# def __eq__(self, other: Any) -> bool:
# def __repr__(self) -> str:
# def get_note_file_data(note_file: str) -> Optional["Note"]:
# def parse_time(timestamp_str: str) -> datetime.datetime:
# def parse_markdown(markdown: str) -> str:
# def write_note(self) -> None:
# def prune_note_files(note_files: List[str]) -> List[str]:
# def is_valid_note(note_file: str) -> bool:
# def get_note_files(directory: str) -> List[str]:
# def get_notes(directory: str) -> List[Note]:
# def get_note_from_slug(directory: str, slug: str) -> Optional[Note]:
#
# Path: app/serve.py
# def init_rollbar() -> None:
# def inject_envs() -> Dict[str, Any]:
# def robots() -> Any:
# def health() -> Any:
# def page_not_found(e: Exception) -> Any:
. Output only the next line. | serve.app.config['TESTING'] = True |
Predict the next line for this snippet: <|code_start|>ext = Sitemap(app=app)
ext.register_generator(sitemap_urls)
if os.environ['ENV'] == 'production':
@app.before_first_request
def init_rollbar() -> None:
"""init rollbar module"""
rollbar.init(
os.environ['ROLLBAR_SERVER_TOKEN'],
# environment name
os.environ['ENV'],
# server root directory, makes tracebacks prettier
root=os.path.dirname(os.path.realpath(__file__)),
# flask already sets up logging
allow_logging_basic_config=False)
# send exceptions from `app` to rollbar, using flask's signal system.
got_request_exception.connect(
rollbar.contrib.flask.report_exception, app)
@app.context_processor
def inject_envs() -> Dict[str, Any]:
envs = {}
envs['SEGMENT_TOKEN'] = os.environ['SEGMENT_TOKEN']
return {'ENV': envs}
<|code_end|>
with the help of current file imports:
import os
import dotenv
import rollbar
import rollbar.contrib.flask
from typing import Any, Dict
from flask import (
Flask,
Response,
got_request_exception,
render_template,
)
from flask_sitemap import Sitemap
from syspath import git_root
from varsnap import varsnap
from app.routes import handlers, sitemap_urls # noqa: E402
and context from other files:
# Path: app/routes.py
# def index() -> Any:
# def resume() -> Any:
# def projects() -> Any:
# def notes() -> Any:
# def shelf() -> Any:
# def note(slug: str = '') -> Any:
# def references() -> Any:
# def reference(slug: str = '') -> Any:
# def about() -> Any:
# def atom_feed() -> Any:
# def sitemap_urls() -> Any:
, which may contain function names, class names, or code. Output only the next line. | app.register_blueprint(handlers) |
Using the snippet: <|code_start|>
dotenv.load_dotenv(git_root.path / '.env')
app = Flask(
__name__,
static_url_path='/static',
static_folder=git_root.path / 'static',
)
app.debug = os.environ['DEBUG'] == 'true'
if os.environ.get('SERVER_NAME', ''): # pragma: no cover
app.config['SERVER_NAME'] = os.environ['SERVER_NAME']
app.config['SITEMAP_INCLUDE_RULES_WITHOUT_PARAMS'] = True
app.config['SITEMAP_URL_SCHEME'] = 'https'
ext = Sitemap(app=app)
<|code_end|>
, determine the next line of code. You have imports:
import os
import dotenv
import rollbar
import rollbar.contrib.flask
from typing import Any, Dict
from flask import (
Flask,
Response,
got_request_exception,
render_template,
)
from flask_sitemap import Sitemap
from syspath import git_root
from varsnap import varsnap
from app.routes import handlers, sitemap_urls # noqa: E402
and context (class names, function names, or code) available:
# Path: app/routes.py
# def index() -> Any:
# def resume() -> Any:
# def projects() -> Any:
# def notes() -> Any:
# def shelf() -> Any:
# def note(slug: str = '') -> Any:
# def references() -> Any:
# def reference(slug: str = '') -> Any:
# def about() -> Any:
# def atom_feed() -> Any:
# def sitemap_urls() -> Any:
. Output only the next line. | ext.register_generator(sitemap_urls) |
Next line prediction: <|code_start|> with open(self.note_file, 'w') as handle:
handle.write(self.title + "\n\n")
handle.write(self.slug + "\n\n")
handle.write(str(int(self.time.timestamp())) + "\n\n")
handle.write(self.markdown + "\n")
@varsnap
def prune_note_files(note_files: List[str]) -> List[str]:
def is_valid_note(note_file: str) -> bool:
if '~' in note_file:
return False
if note_file[0] == '.':
return False
return True
files = [note_file for note_file in note_files if is_valid_note(note_file)]
return files
def get_note_files(directory: str) -> List[str]:
current_directory = os.path.dirname(os.path.realpath(__file__))
notes_directory = os.path.join(current_directory, directory)
files = os.listdir(notes_directory)
files.sort(reverse=True)
files = prune_note_files(files)
files = [os.path.join(notes_directory, note_file) for note_file in files]
return files
# @varsnap
<|code_end|>
. Use current file imports:
(import datetime
import os
import markdown2
from typing import Any, List, Optional, cast
from zoneinfo import ZoneInfo
from varsnap import varsnap
from app.util import cached_function)
and context including class names, function names, or small code snippets from other files:
# Path: app/util.py
# def cached_function(func: Callable[..., Any]) -> Callable[..., Any]:
# data = {}
#
# def wrapper(*args: Any) -> Any:
# if not SHOULD_CACHE:
# return func(*args)
# cache_key = ' '.join([str(x) for x in args])
# if cache_key not in data:
# data[cache_key] = func(*args)
# return data[cache_key]
#
# wrapper.__qualname__ = func.__qualname__
# wrapper.__signature__ = inspect.signature(func) # type: ignore
# return wrapper
. Output only the next line. | @cached_function |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Created on Mon Dec 7 13:46:13 2015
@author: ebachelet
"""
def test_orbital_motion_shifts():
model = ['2D', 2458000]
pyLIMA_parameters = collections.namedtuple('params', ['dsdt', 'dalphadt'])
pyLIMA_parameters.dsdt = 0.0001
pyLIMA_parameters.dalphadt = 0.0001
time = np.arange(2457950., 2458050., 10)
<|code_end|>
, predict the immediate next line with the help of imports:
import numpy as np
import unittest.mock as mock
import collections
from pyLIMA import microlorbitalmotion
and context (classes, functions, sometimes code) from other files:
# Path: pyLIMA/microlorbitalmotion.py
# def orbital_motion_shifts(orbital_motion_model, time, pyLIMA_parameters):
# def orbital_motion_2D_trajectory_shift(to_om, time, dalpha_dt):
# def orbital_motion_2D_separation_shift(to_om, time, ds_dt):
# def orbital_motion_circular(to_om, v_para, v_perp, v_radial, separation_0, time):
# def orbital_motion_keplerian(to_om, v_para, v_perp, v_radial, separation_0, separation_z, mass, rE, time):
# def orbital_motion_keplerian_direct(to_om, a_true,period,eccentricity,inclination,omega_node,omega_periastron,t_periastron,
# rE, time):
# def eccentric_anomaly_function(time, ellipticity, t_periastron, speed):
# def mean_to_eccentric_anomaly(params, mean_anomaly, ellipticity):
# def mean_to_eccentric_anomaly_prime(params, mean_anomaly, ellipticity):
# def mean_to_eccentric_anomaly_prime2(params, mean_anomaly, ellipticity):
# N = 2 * np.pi / period * 1 / 365.25
# N = 2*np.pi/period/365.25
. Output only the next line. | ds, dalpha = microlorbitalmotion.orbital_motion_shifts(model, time, pyLIMA_parameters) |
Using the snippet: <|code_start|>
def test_chichi():
magic_residuals = mock.MagicMock()
parameters = []
magic_residuals.residuals_fn.return_value = np.array([0, 1, 50])
parameters2 = [0, 6, 5]
<|code_end|>
, determine the next line of code. You have imports:
import os.path
import numpy as np
import unittest.mock as mock
from pyLIMA import microltoolbox, microlmodels
from pyLIMA import event
and context (class names, function names, or code) available:
# Path: pyLIMA/microltoolbox.py
# MAGNITUDE_CONSTANT = 27.4
# def chichi(residuals_fn, fit_process_parameters):
# def magnitude_to_flux(magnitude):
# def flux_to_magnitude(flux):
# def error_magnitude_to_error_flux(error_magnitude, flux):
# def error_flux_to_error_magnitude(error_flux, flux):
# def MCMC_compute_fs_g(fit, mcmc_chains):
# def align_the_data_to_the_reference_telescope(fit, telescope_index = 0, parameters = None) :
#
# Path: pyLIMA/microlmodels.py
# class ModelException(Exception):
# class MLModel(object):
# class ModelPSPL(MLModel):
# class ModelFSPL(MLModel):
# class ModelFSPLee(MLModel):
# class ModelFSPLarge(MLModel):
# class ModelDSPL(MLModel):
# class ModelDFSPL(MLModel):
# class ModelFSBL(MLModel):
# class ModelUSBL(ModelFSBL):
# class ModelPSBL(ModelFSBL):
# class ModelVariablePL(MLModel):
# def create_model(model_type, event, model_arguments=[], parallax=['None', 0.0], xallarap=['None'],
# orbital_motion=['None', 0.0], source_spots='None', blend_flux_ratio=True):
# def __init__(self, event, model_arguments=[], parallax=['None', 0.0], xallarap=['None'],
# orbital_motion=['None', 0.0], source_spots='None', blend_flux_ratio=True):
# def model_type(self):
# def paczynski_model_parameters(self):
# def model_magnification(self, telescope, pyLIMA_parameters):
# def define_pyLIMA_standard_parameters(self):
# def define_model_parameters(self):
# def print_model_parameters(self):
# def compute_the_microlensing_model(self, telescope, pyLIMA_parameters):
# def _default_microlensing_model(self, telescope, pyLIMA_parameters, amplification):
# def derive_telescope_flux(self, telescope, pyLIMA_parameters, amplification):
# def compute_pyLIMA_parameters(self, fancy_parameters):
# def find_origin(self, pyLIMA_parameters):
# def uo_to_from_uc_tc(self, pyLIMA_parameters):
# def uc_tc_from_uo_to(selfself,pyLIMA_parameters):
# def fancy_parameters_to_pyLIMA_standard_parameters(self, fancy_parameters):
# def pyLIMA_standard_parameters_to_fancy_parameters(self, pyLIMA_parameters):
# def source_trajectory(self, telescope, to, uo, tE, pyLIMA_parameters):
# def model_type(self):
# def paczynski_model_parameters(self):
# def model_magnification(self, telescope, pyLIMA_parameters):
# def Jacobian_model_magnification(self, telescope, pyLIMA_parameters):
# def model_Jacobian(self, telescope, pyLIMA_parameters):
# def model_type(self):
# def paczynski_model_parameters(self):
# def model_magnification(self, telescope, pyLIMA_parameters):
# def Jacobian_model_magnification(self, telescope, pyLIMA_parameters):
# def model_Jacobian(self, telescope, pyLIMA_parameters):
# def model_type(self):
# def paczynski_model_parameters(self):
# def model_magnification(self, telescope, pyLIMA_parameters):
# def model_type(self):
# def paczynski_model_parameters(self):
# def model_magnification(self, telescope, pyLIMA_parameters):
# def model_type(self):
# def paczynski_model_parameters(self):
# def model_magnification(self, telescope, pyLIMA_parameters):
# def model_type(self):
# def paczynski_model_parameters(self):
# def model_magnification(self, telescope, pyLIMA_parameters):
# def model_type(self):
# def paczynski_model_parameters(self):
# def model_magnification(self, telescope, pyLIMA_parameters):
# def find_caustics(self, separation, mass_ratio):
# def find_origin(self, pyLIMA_parameters):
# def uo_to_from_uc_tc(self, pyLIMA_parameters):
# def uc_tc_from_uo_to(self, pyLIMA_parameters, to, uo):
# def find_binary_regime(self, pyLIMA_parameters):
# def model_type(self):
# def paczynski_model_parameters(self):
# def model_magnification(self, telescope, pyLIMA_parameters):
# def model_type(self):
# def paczynski_model_parameters(self):
# def model_magnification(self, telescope, pyLIMA_parameters):
# def model_type(self):
# def paczynski_model_parameters(self):
# def model_magnification(self, telescope, pyLIMA_parameters):
# def compute_the_microlensing_model(self, telescope, pyLIMA_parameters):
# def derive_telescope_flux(self, telescope, pyLIMA_parameters, amplification, pulsations):
# def compute_pulsations(self, time, filter, pyLIMA_parameters):
#
# Path: pyLIMA/event.py
# class EventException(Exception):
# class Event(object):
# def __init__(self):
# def fit(self, model, method, DE_population_size=10, flux_estimation_MCMC='MCMC', fix_parameters_dictionnary=None,
# grid_resolution=10, computational_pool=None, binary_regime=None):
# def telescopes_names(self):
# def check_event(self):
# def find_survey(self, choice=None):
# def lightcurves_in_flux(self, choice='Yes'):
# def compute_parallax_all_telescopes(self, parallax_model):
# def total_number_of_data_points(self):
. Output only the next line. | chichi = microltoolbox.chichi(magic_residuals.residuals_fn, parameters2) |
Given the code snippet: <|code_start|> available_methods parameter:
'LM' : Levenberg-Marquardt algorithm
'DE' : Differential Evolution algorithm
'MCMC' : Monte-Carlo Markov Chain algorithm
More details in the microlfits module
A microlfits object is added in the event.fits list. For example, if you request two fits,
you will obtain :
event.fits=[fit1,fit2]
More details in the microlfits module.
"""
available_kind = ['Microlensing']
available_methods = ['LM', 'DE', 'MCMC', 'GRIDS', 'TRF']
if self.kind not in available_kind:
print('ERROR : No possible fit yet for a non microlensing event, sorry :(')
raise EventException('Can not fit this event kind')
if method not in available_methods:
print('ERROR : Wrong method request, has to be a string selected between ' + \
' or '.join(available_methods) + '')
raise EventException('Wrong fit method request')
<|code_end|>
, generate the next line using the imports in this file:
import sys
import numpy as np
from pyLIMA import microlfits
and context (functions, classes, or occasionally code) from other files:
# Path: pyLIMA/microlfits.py
# class FitException(Exception):
# class MLFits(object):
# def __init__(self, event):
# def mlfit(self, model, method, DE_population_size=10, flux_estimation_MCMC='MCMC', fix_parameters_dictionnary=None,
# grid_resolution=10, computational_pool=None, binary_regime=None):
# def check_parameters_boundaries(self):
# def check_fit(self):
# def initial_guess(self):
# def MCMC(self,pool):
# def chichi_MCMC(self, fit_process_parameters):
# def differential_evolution(self,pool):
# def chichi_differential_evolution(self, fit_process_parameters):
# def lmarquardt(self):
# def residuals_LM(self, fit_process_parameters):
# def LM_Jacobian(self, fit_process_parameters):
# def trust_region_reflective(self):
# def chichi_telescopes(self, fit_process_parameters):
# def model_residuals(self, telescope, pyLIMA_parameters):
# def all_telescope_residuals(self, pyLIMA_parameters):
# def find_fluxes(self, fit_process_parameters, model):
# def grids(self):
# def optimization_on_grid_pixel(self, grid_pixel_parameters):
# def chichi_grids(self, moving_parameters, *fix_parameters):
# def reconstruct_fit_process_parameters(self, moving_parameters, fix_parameters):
# def redefine_parameters_boundaries(self):
# def construct_the_hyper_grid(self, parameters):
# def produce_outputs(self):
# def produce_fit_statistics(self):
# def produce_pdf(self, output_directory='./'):
# def produce_latex_table_results(self, output_directory='./'):
. Output only the next line. | fit = microlfits.MLFits(self) |
Given snippet: <|code_start|>
def test_poisson_noise():
flux = np.array([150, 10 ** 5.2, 0.1])
error = flux ** 0.5
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import collections
import unittest.mock as mock
import numpy as np
import pytest
from pyLIMA import microlsimulator
and context:
# Path: pyLIMA/microlsimulator.py
# RED_NOISE = 'Yes'
# SOURCE_MAGNITUDE = [14, 22]
# BLEND_LIMITS = [0, 1]
# EXPOSURE_TIME = 50 #seconds
# def moon_illumination(sun, moon):
# def poisson_noise(flux):
# def noisy_observations(flux, error_flux):
# def time_simulation(time_start, time_end, sampling, bad_weather_percentage):
# def red_noise(time):
# def simulate_a_microlensing_event(name='Microlensing pyLIMA simulation', ra=270, dec=-30):
# def simulate_a_telescope(name, event, time_start, time_end, sampling, location, filter, uniform_sampling=False,
# altitude=0, longitude=0, latitude=0, spacecraft_name=None, bad_weather_percentage=0.0,
# minimum_alt=20, moon_windows_avoidance=20, maximum_moon_illumination=100.0):
# def simulate_a_microlensing_model(event, model='PSPL', args=(), parallax=['None', 0.0], xallarap=['None'],
# orbital_motion=['None', 0.0], source_spots='None'):
# def simulate_microlensing_model_parameters(model):
# def simulate_fluxes_parameters(list_of_telescopes):
# def simulate_lightcurve_flux(model, pyLIMA_parameters, red_noise_apply='Yes'):
which might include code, classes, or functions. Output only the next line. | assert np.allclose(microlsimulator.poisson_noise(flux), error) |
Given snippet: <|code_start|> This assumes no blending.
:param object event: the event object on which you perform the fit on. More details on the
event module.
:return: the PSPL guess for this event. A list of parameters associated to the PSPL model + the source flux of
:return: the PSPL guess for this event. A list of parameters associated to the PSPL model + the source flux of
the survey telescope.
:rtype: list,float
"""
# to estimation
to_estimations = []
maximum_flux_estimations = []
errors_magnitude = []
for telescope in event.telescopes:
# Lot of process here, if one fails, just skip
lightcurve_magnitude = telescope.lightcurve_magnitude
mean_error_magnitude = np.mean(lightcurve_magnitude[:, 2])
try:
# only the best photometry
good_photometry_indexes = np.where((lightcurve_magnitude[:, 2] <
max(0.1, mean_error_magnitude)))[0]
lightcurve_bis = lightcurve_magnitude[good_photometry_indexes]
lightcurve_bis = lightcurve_bis[lightcurve_bis[:, 0].argsort(), :]
mag = lightcurve_bis[:, 1]
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
import scipy.signal as ss
from pyLIMA import microltoolbox
and context:
# Path: pyLIMA/microltoolbox.py
# MAGNITUDE_CONSTANT = 27.4
# def chichi(residuals_fn, fit_process_parameters):
# def magnitude_to_flux(magnitude):
# def flux_to_magnitude(flux):
# def error_magnitude_to_error_flux(error_magnitude, flux):
# def error_flux_to_error_magnitude(error_flux, flux):
# def MCMC_compute_fs_g(fit, mcmc_chains):
# def align_the_data_to_the_reference_telescope(fit, telescope_index = 0, parameters = None) :
which might include code, classes, or functions. Output only the next line. | flux = microltoolbox.magnitude_to_flux(mag) |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Created on Tue Jun 14 15:49:26 2016
@author: ebachelet
"""
def priors_on_models(pyLIMA_parameters, model, binary_regime = None):
prior = 0
keys = pyLIMA_parameters._fields
for index,bounds in enumerate(model.parameters_boundaries):
parameter = getattr(pyLIMA_parameters, keys[index])
if (parameter < bounds[0]) or (parameter>bounds[1]):
return np.inf
if binary_regime:
<|code_end|>
, determine the next line of code. You have imports:
import numpy as np
from pyLIMA import microlcaustics
and context (class names, function names, or code) available:
# Path: pyLIMA/microlcaustics.py
# def find_2_lenses_caustics_and_critical_curves(separation, mass_ratio, resolution=1000):
# def sort_2lenses_resonant_caustic(caustic_points, critical_curves_points):
# def sort_2lenses_close_caustics(caustic_points, critical_curves_points):
# def sort_2lenses_wide_caustics(caustic_points, critical_curves_points):
# def compute_2_lenses_caustics_points(separation, mass_ratio, resolution=1000):
# def find_area_of_interest_around_caustics(caustics, secure_factor=0.1):
# def find_2_lenses_caustic_regime(separation, mass_ratio):
# def change_source_trajectory_center_to_central_caustics_center(separation, mass_ratio):
# def change_source_trajectory_center_to_planetary_caustics_center(separation, mass_ratio):
# def dx(function, x, args):
# def newtons_method(function, jaco, x0, args=None, e=10 ** -10):
# def foo(x, pp1, pp2, pp3, pp4, pp5):
# def foo2(X, pp1, pp2, pp3, pp4, pp5):
# def jaco(x, pp1, pp2, pp3, pp4, pp5):
# def hessian(x, pp1, pp2, pp3, pp4, pp5):
# def Jacobian(zi, mtot, deltam, z1):
# def find_slices(slice_1, slice_2, points):
. Output only the next line. | regime = microlcaustics.find_2_lenses_caustic_regime(10**pyLIMA_parameters.logs, 10**pyLIMA_parameters.logq) |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Created on Thu May 19 17:02:33 2016
@author: ebachelet
"""
def test_impact_parameter():
tau = np.array([1])
uo = np.array([2])
<|code_end|>
, predict the immediate next line with the help of imports:
import numpy as np
from pyLIMA import microlmagnification
from pyLIMA import microlmodels
and context (classes, functions, sometimes code) from other files:
# Path: pyLIMA/microlmagnification.py
# VBB = VBBinaryLensing.VBBinaryLensing()
# def impact_parameter(tau, uo):
# def amplification_PSPL(tau, uo):
# def Jacobian_amplification_PSPL(tau, uo):
# def amplification_FSPLarge(tau, uo, rho, limb_darkening_coefficient):
# def amplification_FSPLee(tau, uo, rho, gamma):
# def amplification_FSPL(tau, uo, rho, gamma, yoo_table):
# def Jacobian_amplification_FSPL(tau, uo, rho, gamma, yoo_table):
# def amplification_USBL(separation, mass_ratio, x_source, y_source, rho):
# def amplification_FSBL(separation, mass_ratio, x_source, y_source, rho, limb_darkening_coefficient):
# def amplification_PSBL(separation, mass_ratio, x_source, y_source):
# def amplification_FSPL_for_Lyrae(tau, uo, rho, gamma, yoo_table):
# def jit_integrand_function(integrand_function):
# def wrapped(n, xx):
# def Lee_limits(x,u,rho,gamma) :
# def Lee_US( x,u,rho,gamma ):
# def Lee_FS(args) :
#
# Path: pyLIMA/microlmodels.py
# class ModelException(Exception):
# class MLModel(object):
# class ModelPSPL(MLModel):
# class ModelFSPL(MLModel):
# class ModelFSPLee(MLModel):
# class ModelFSPLarge(MLModel):
# class ModelDSPL(MLModel):
# class ModelDFSPL(MLModel):
# class ModelFSBL(MLModel):
# class ModelUSBL(ModelFSBL):
# class ModelPSBL(ModelFSBL):
# class ModelVariablePL(MLModel):
# def create_model(model_type, event, model_arguments=[], parallax=['None', 0.0], xallarap=['None'],
# orbital_motion=['None', 0.0], source_spots='None', blend_flux_ratio=True):
# def __init__(self, event, model_arguments=[], parallax=['None', 0.0], xallarap=['None'],
# orbital_motion=['None', 0.0], source_spots='None', blend_flux_ratio=True):
# def model_type(self):
# def paczynski_model_parameters(self):
# def model_magnification(self, telescope, pyLIMA_parameters):
# def define_pyLIMA_standard_parameters(self):
# def define_model_parameters(self):
# def print_model_parameters(self):
# def compute_the_microlensing_model(self, telescope, pyLIMA_parameters):
# def _default_microlensing_model(self, telescope, pyLIMA_parameters, amplification):
# def derive_telescope_flux(self, telescope, pyLIMA_parameters, amplification):
# def compute_pyLIMA_parameters(self, fancy_parameters):
# def find_origin(self, pyLIMA_parameters):
# def uo_to_from_uc_tc(self, pyLIMA_parameters):
# def uc_tc_from_uo_to(selfself,pyLIMA_parameters):
# def fancy_parameters_to_pyLIMA_standard_parameters(self, fancy_parameters):
# def pyLIMA_standard_parameters_to_fancy_parameters(self, pyLIMA_parameters):
# def source_trajectory(self, telescope, to, uo, tE, pyLIMA_parameters):
# def model_type(self):
# def paczynski_model_parameters(self):
# def model_magnification(self, telescope, pyLIMA_parameters):
# def Jacobian_model_magnification(self, telescope, pyLIMA_parameters):
# def model_Jacobian(self, telescope, pyLIMA_parameters):
# def model_type(self):
# def paczynski_model_parameters(self):
# def model_magnification(self, telescope, pyLIMA_parameters):
# def Jacobian_model_magnification(self, telescope, pyLIMA_parameters):
# def model_Jacobian(self, telescope, pyLIMA_parameters):
# def model_type(self):
# def paczynski_model_parameters(self):
# def model_magnification(self, telescope, pyLIMA_parameters):
# def model_type(self):
# def paczynski_model_parameters(self):
# def model_magnification(self, telescope, pyLIMA_parameters):
# def model_type(self):
# def paczynski_model_parameters(self):
# def model_magnification(self, telescope, pyLIMA_parameters):
# def model_type(self):
# def paczynski_model_parameters(self):
# def model_magnification(self, telescope, pyLIMA_parameters):
# def model_type(self):
# def paczynski_model_parameters(self):
# def model_magnification(self, telescope, pyLIMA_parameters):
# def find_caustics(self, separation, mass_ratio):
# def find_origin(self, pyLIMA_parameters):
# def uo_to_from_uc_tc(self, pyLIMA_parameters):
# def uc_tc_from_uo_to(self, pyLIMA_parameters, to, uo):
# def find_binary_regime(self, pyLIMA_parameters):
# def model_type(self):
# def paczynski_model_parameters(self):
# def model_magnification(self, telescope, pyLIMA_parameters):
# def model_type(self):
# def paczynski_model_parameters(self):
# def model_magnification(self, telescope, pyLIMA_parameters):
# def model_type(self):
# def paczynski_model_parameters(self):
# def model_magnification(self, telescope, pyLIMA_parameters):
# def compute_the_microlensing_model(self, telescope, pyLIMA_parameters):
# def derive_telescope_flux(self, telescope, pyLIMA_parameters, amplification, pulsations):
# def compute_pulsations(self, time, filter, pyLIMA_parameters):
. Output only the next line. | impact_param = microlmagnification.impact_parameter(tau, uo) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
"""
Created on Wed May 18 15:19:27 2016
@author: ebachelet
"""
def test_check_event_bad_name():
<|code_end|>
, predict the next line using imports from the current file:
import numpy as np
import unittest.mock as mock
import pytest
from pyLIMA import event
and context including class names, function names, and sometimes code from other files:
# Path: pyLIMA/event.py
# class EventException(Exception):
# class Event(object):
# def __init__(self):
# def fit(self, model, method, DE_population_size=10, flux_estimation_MCMC='MCMC', fix_parameters_dictionnary=None,
# grid_resolution=10, computational_pool=None, binary_regime=None):
# def telescopes_names(self):
# def check_event(self):
# def find_survey(self, choice=None):
# def lightcurves_in_flux(self, choice='Yes'):
# def compute_parallax_all_telescopes(self, parallax_model):
# def total_number_of_data_points(self):
. Output only the next line. | current_event = event.Event() |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Created on Mon Dec 7 13:46:13 2015
@author: ebachelet
"""
def _create_event():
event = mock.MagicMock()
event.telescopes = [mock.MagicMock()]
event.telescopes[0].name = 'Test'
event.telescopes[0].lightcurve_flux = np.array([[0, 1, 1], [42, 6, 6]])
event.telescopes[0].filter = 'I'
event.telescopes[0].gamma = 0.5
event.ra = 180
event.dec = 360
return event
def test_create_parallax():
event = _create_event()
parallax_model = ['None', 1664.51]
<|code_end|>
with the help of current file imports:
from astropy.time import Time
from astropy.coordinates import solar_system_ephemeris, EarthLocation
from astropy.coordinates import get_body_barycentric, get_body, get_moon
from pyLIMA import microlparallax
import numpy as np
import unittest.mock as mock
and context from other files:
# Path: pyLIMA/microlparallax.py
# TIMEOUT_JPL = 120 # seconds. The time you allow telnetlib to discuss with JPL, see space_parallax.
# JPL_TYPICAL_REQUEST_TIME_PER_LINE = 0.002 # seconds.
# JPL_HORIZONS_ID = {
# 'Geocentric': '500',
# 'Kepler': '-227',
# 'Spitzer': '-79',
# 'HST': '-48',
# 'Gaia': '-139479',
# 'New Horizons': '-98'
# }
# OBSERVATORY_ID = observatory
# OBSERVATORY_ID = JPL_HORIZONS_ID.get(observatory, 'V37')
# AU = self.AU
# JD = time_to_transform + np.array(time_correction)
# X = satellite_positions[:, 1].astype(float)
# Y = satellite_positions[:, 2].astype(float)
# Z = satellite_positions[:, 3].astype(float)
# OBSERVATORY_ID = horizons_obscodes(observatory)
# def EN_trajectory_angle(piEN,piEE):
# def horizons_obscodes(observatory):
# def optcallback(socket, command, option):
# def compute_parallax_curvature(piE, delta_positions):
# def __init__(self, event, parallax_model):
# def North_East_vectors_target(self):
# def HJD_to_JD(self, time_to_transform):
# def parallax_combination(self, telescope):
# def annual_parallax(self, time_to_treat):
# def terrestrial_parallax(self, time_to_treat, altitude, longitude, latitude):
# def space_parallax(self, time_to_treat, satellite_name, telescope):
# def lonely_satellite(self, time_to_treat, telescope):
# def produce_horizons_ephem(body, start_time, end_time, observatory='ELP', step_size='60m',
# verbose=False):
# class MLParallaxes(object):
, which may contain function names, class names, or code. Output only the next line. | parallax = microlparallax.MLParallaxes(event, parallax_model) |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Created on Wed May 18 15:25:12 2016
@author: ebachelet
"""
def test_init():
<|code_end|>
, determine the next line of code. You have imports:
import os.path
import numpy as np
from pyLIMA import telescopes
from pyLIMA import stars
and context (class names, function names, or code) available:
# Path: pyLIMA/telescopes.py
# PYLIMA_LIGHTCURVE_MAGNITUDE_CONVENTION = ['time', 'mag', 'err_mag']
# PYLIMA_LIGHTCURVE_FLUX_CONVENTION = ['time', 'flux', 'err_flux']
# class Telescope(object):
# def __init__(self, name='NDG', camera_filter='I', light_curve_magnitude=None,
# light_curve_magnitude_dictionnary=None,
# light_curve_flux=None, light_curve_flux_dictionnary=None,
# reference_flux=0.0, clean_the_lightcurve='Yes',
# location = 'Earth', spacecraft_name=None):
# def arrange_the_lightcurve_columns(self, choice):
# def n_data(self, choice='magnitude'):
# def find_gamma(self, star):
# def compute_parallax(self, event, parallax):
# def clean_data_magnitude(self):
# def clean_data_flux(self):
# def lightcurve_in_flux(self):
# def lightcurve_in_magnitude(self):
# def hidden(self):
#
# Path: pyLIMA/stars.py
# CLARET_PATH = template
# class Star(object):
# def __init__(self):
# def define_claret_filter_tables(self):
# def find_gamma(self, filter):
. Output only the next line. | telescope = telescopes.Telescope() |
Using the snippet: <|code_start|> light_curve_magnitude=np.array([[0, 1, 0.1], [3, 4, 0.1], [5, 6, 0.1]]))
clean_lightcurve = telescope.clean_data_magnitude()
assert np.allclose(clean_lightcurve, np.array([[0, 1, 0.1], [3, 4, 0.1], [5, 6, 0.1]]))
def test_clean_data_not_clean():
telescope = telescopes.Telescope(light_curve_magnitude=np.array(
[[0, 1, 0.1], [3, np.nan, 0.1], [5, 6, 0.1], [7, np.nan, np.nan], [8, 1, 27.0],
[9, 2, 0.03]]))
clean_lightcurve = telescope.clean_data_magnitude()
assert np.allclose(clean_lightcurve, np.array([[0, 1, 0.1], [5, 6, 0.1], [9, 2, 0.03]]))
def test_lightcurve_in_flux():
telescope = telescopes.Telescope(
light_curve_magnitude=np.array([[0, 1, 0.1], [3, 4, 0.1], [5, 6, 0.1]]))
telescope.lightcurve_flux = telescope.lightcurve_in_flux()
assert np.allclose(telescope.lightcurve_flux,
np.array([[0.00000000e+00, 3.63078055e+10, 3.34407247e+09],
[3.00000000e+00, 2.29086765e+09, 2.10996708e+08],
[5.00000000e+00, 3.63078055e+08, 3.34407247e+07]]))
def test_find_gamma():
telescope = telescopes.Telescope(camera_filter="z'")
<|code_end|>
, determine the next line of code. You have imports:
import os.path
import numpy as np
from pyLIMA import telescopes
from pyLIMA import stars
and context (class names, function names, or code) available:
# Path: pyLIMA/telescopes.py
# PYLIMA_LIGHTCURVE_MAGNITUDE_CONVENTION = ['time', 'mag', 'err_mag']
# PYLIMA_LIGHTCURVE_FLUX_CONVENTION = ['time', 'flux', 'err_flux']
# class Telescope(object):
# def __init__(self, name='NDG', camera_filter='I', light_curve_magnitude=None,
# light_curve_magnitude_dictionnary=None,
# light_curve_flux=None, light_curve_flux_dictionnary=None,
# reference_flux=0.0, clean_the_lightcurve='Yes',
# location = 'Earth', spacecraft_name=None):
# def arrange_the_lightcurve_columns(self, choice):
# def n_data(self, choice='magnitude'):
# def find_gamma(self, star):
# def compute_parallax(self, event, parallax):
# def clean_data_magnitude(self):
# def clean_data_flux(self):
# def lightcurve_in_flux(self):
# def lightcurve_in_magnitude(self):
# def hidden(self):
#
# Path: pyLIMA/stars.py
# CLARET_PATH = template
# class Star(object):
# def __init__(self):
# def define_claret_filter_tables(self):
# def find_gamma(self, filter):
. Output only the next line. | star = stars.Star() |
Given the code snippet: <|code_start|>"""
Created on Thu Aug 27 16:39:32 2015
@author: ebachelet
"""
DATA = """ 0.00 3500. -5.0 2.0 0.6278 Kp L ATLAS
0.50 3500. -5.0 2.0 0.6161 Kp L ATLAS
1.00 3500. -5.0 2.0 0.5889 Kp L ATLAS
1.50 3500. -5.0 2.0 0.5627 Kp L ATLAS
2.00 3500. -5.0 2.0 0.5512 Kp L ATLAS
2.50 3500. -5.0 2.0 0.5526 Kp L ATLAS
3.00 3500. -5.0 2.0 0.5629 Kp L ATLAS
0.00 3750. -5.0 2.0 0.6270 Kp L ATLAS
0.50 3750. -5.0 2.0 0.6190 Kp L ATLAS
1.00 3750. -5.0 2.0 0.6019 Kp L ATLAS
4.50 32000. 1.0 2.0 0.1512 z' F PHOENIX
5.00 32000. 1.0 2.0 0.1419 z' F PHOENIX
4.50 33000. 1.0 2.0 0.1486 z' F PHOENIX
5.00 33000. 1.0 2.0 0.1397 z' F PHOENIX
4.50 34000. 1.0 2.0 0.1450 z' F PHOENIX
5.00 34000. 1.0 2.0 0.1369 z' F PHOENIX
4.50 35000. 1.0 2.0 0.1407 z' F PHOENIX
5.00 35000. 1.0 2.0 0.1334 z' F PHOENIX
5.00 37500. 1.0 2.0 0.1226 z' F PHOENIX
5.00 40000. 1.0 2.0 0.1150 z' F PHOENIX
"""
def test_reading_file():
<|code_end|>
, generate the next line using the imports in this file:
from pyLIMA import microllimb_darkening
and context (functions, classes, or occasionally code) from other files:
# Path: pyLIMA/microllimb_darkening.py
# _CLARET_COLUMNS = 'log_g, Teff, metallicity, microturbulent_velocity, linear_limb_darkening, ' \
# 'filter, method, model'
# def read_claret_data(file_name, camera_filter):
# def _convert_datum(datum):
. Output only the next line. | data = list(microllimb_darkening.read_claret_data(DATA, camera_filter='all')) |
Here is a snippet: <|code_start|>
def test_find_2_lenses_caustics_and_critical_curves():
separation = 1
mass_ratio = 1
<|code_end|>
. Write the next line using the current file imports:
import numpy as np
import unittest.mock
import pytest
from pyLIMA import microlcaustics
and context from other files:
# Path: pyLIMA/microlcaustics.py
# def find_2_lenses_caustics_and_critical_curves(separation, mass_ratio, resolution=1000):
# def sort_2lenses_resonant_caustic(caustic_points, critical_curves_points):
# def sort_2lenses_close_caustics(caustic_points, critical_curves_points):
# def sort_2lenses_wide_caustics(caustic_points, critical_curves_points):
# def compute_2_lenses_caustics_points(separation, mass_ratio, resolution=1000):
# def find_area_of_interest_around_caustics(caustics, secure_factor=0.1):
# def find_2_lenses_caustic_regime(separation, mass_ratio):
# def change_source_trajectory_center_to_central_caustics_center(separation, mass_ratio):
# def change_source_trajectory_center_to_planetary_caustics_center(separation, mass_ratio):
# def dx(function, x, args):
# def newtons_method(function, jaco, x0, args=None, e=10 ** -10):
# def foo(x, pp1, pp2, pp3, pp4, pp5):
# def foo2(X, pp1, pp2, pp3, pp4, pp5):
# def jaco(x, pp1, pp2, pp3, pp4, pp5):
# def hessian(x, pp1, pp2, pp3, pp4, pp5):
# def Jacobian(zi, mtot, deltam, z1):
# def find_slices(slice_1, slice_2, points):
, which may include functions, classes, or code. Output only the next line. | caustic_regime, caustics, critical_curves = microlcaustics.find_2_lenses_caustics_and_critical_curves(separation, |
Given snippet: <|code_start|> error_flux = self.lightcurve_flux[:, 2]
index = np.where(
(~np.isnan(self.lightcurve_flux).any(axis=1)) & (np.abs(error_flux / flux) <= maximum_accepted_precision) & (flux>0))[
0]
lightcurve = self.lightcurve_flux[index]
index = np.where(
(np.isnan(self.lightcurve_flux).any(axis=1)) | (np.abs(error_flux / flux) > maximum_accepted_precision) | (flux<=0))[0]
if len(index) != 0:
self.bad_points_flux = index
print('pyLIMA found some bad points in the telescope ' + self.name + ', you can found these in the ' \
'bad_points_flux attribute.')
return lightcurve
def lightcurve_in_flux(self):
"""
Transform magnitude to flux using m=27.4-2.5*log10(flux) convention. Transform error bar
accordingly. More details in microltoolbox module.
:return: the lightcurve in flux, lightcurve_flux.
:rtype: array_like
"""
lightcurve = self.lightcurve_magnitude
time = lightcurve[:, 0]
mag = lightcurve[:, 1]
err_mag = lightcurve[:, 2]
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
import astropy.io.fits as fits
import webbrowser
from pyLIMA import microltoolbox
from pyLIMA import microlparallax
and context:
# Path: pyLIMA/microltoolbox.py
# MAGNITUDE_CONSTANT = 27.4
# def chichi(residuals_fn, fit_process_parameters):
# def magnitude_to_flux(magnitude):
# def flux_to_magnitude(flux):
# def error_magnitude_to_error_flux(error_magnitude, flux):
# def error_flux_to_error_magnitude(error_flux, flux):
# def MCMC_compute_fs_g(fit, mcmc_chains):
# def align_the_data_to_the_reference_telescope(fit, telescope_index = 0, parameters = None) :
#
# Path: pyLIMA/microlparallax.py
# TIMEOUT_JPL = 120 # seconds. The time you allow telnetlib to discuss with JPL, see space_parallax.
# JPL_TYPICAL_REQUEST_TIME_PER_LINE = 0.002 # seconds.
# JPL_HORIZONS_ID = {
# 'Geocentric': '500',
# 'Kepler': '-227',
# 'Spitzer': '-79',
# 'HST': '-48',
# 'Gaia': '-139479',
# 'New Horizons': '-98'
# }
# OBSERVATORY_ID = observatory
# OBSERVATORY_ID = JPL_HORIZONS_ID.get(observatory, 'V37')
# AU = self.AU
# JD = time_to_transform + np.array(time_correction)
# X = satellite_positions[:, 1].astype(float)
# Y = satellite_positions[:, 2].astype(float)
# Z = satellite_positions[:, 3].astype(float)
# OBSERVATORY_ID = horizons_obscodes(observatory)
# def EN_trajectory_angle(piEN,piEE):
# def horizons_obscodes(observatory):
# def optcallback(socket, command, option):
# def compute_parallax_curvature(piE, delta_positions):
# def __init__(self, event, parallax_model):
# def North_East_vectors_target(self):
# def HJD_to_JD(self, time_to_transform):
# def parallax_combination(self, telescope):
# def annual_parallax(self, time_to_treat):
# def terrestrial_parallax(self, time_to_treat, altitude, longitude, latitude):
# def space_parallax(self, time_to_treat, satellite_name, telescope):
# def lonely_satellite(self, time_to_treat, telescope):
# def produce_horizons_ephem(body, start_time, end_time, observatory='ELP', step_size='60m',
# verbose=False):
# class MLParallaxes(object):
which might include code, classes, or functions. Output only the next line. | flux = microltoolbox.magnitude_to_flux(mag) |
Next line prediction: <|code_start|>
:param string choice: 'magnitude' (default) or 'flux' The unit you want to check data for.
:return: the size of the corresponding lightcurve
:rtype: int
"""
if choice == 'flux':
return len(self.lightcurve_flux[:, 0])
if choice == 'magnitude':
return len(self.lightcurve_magnitude[:, 0])
def find_gamma(self, star):
"""
Set the associated :math:`\\Gamma` linear limb-darkening coefficient associated to the filter.
:param object star: a stars object.
"""
self.gamma = star.find_gamma(self.filter)
def compute_parallax(self, event, parallax):
""" Compute and set the deltas_positions attribute due to the parallax.
:param object event: a event object. More details in the event module.
:param list parallax: a list containing the parallax model and to_par. More details in microlparallax module.
"""
<|code_end|>
. Use current file imports:
(import numpy as np
import astropy.io.fits as fits
import webbrowser
from pyLIMA import microltoolbox
from pyLIMA import microlparallax)
and context including class names, function names, or small code snippets from other files:
# Path: pyLIMA/microltoolbox.py
# MAGNITUDE_CONSTANT = 27.4
# def chichi(residuals_fn, fit_process_parameters):
# def magnitude_to_flux(magnitude):
# def flux_to_magnitude(flux):
# def error_magnitude_to_error_flux(error_magnitude, flux):
# def error_flux_to_error_magnitude(error_flux, flux):
# def MCMC_compute_fs_g(fit, mcmc_chains):
# def align_the_data_to_the_reference_telescope(fit, telescope_index = 0, parameters = None) :
#
# Path: pyLIMA/microlparallax.py
# TIMEOUT_JPL = 120 # seconds. The time you allow telnetlib to discuss with JPL, see space_parallax.
# JPL_TYPICAL_REQUEST_TIME_PER_LINE = 0.002 # seconds.
# JPL_HORIZONS_ID = {
# 'Geocentric': '500',
# 'Kepler': '-227',
# 'Spitzer': '-79',
# 'HST': '-48',
# 'Gaia': '-139479',
# 'New Horizons': '-98'
# }
# OBSERVATORY_ID = observatory
# OBSERVATORY_ID = JPL_HORIZONS_ID.get(observatory, 'V37')
# AU = self.AU
# JD = time_to_transform + np.array(time_correction)
# X = satellite_positions[:, 1].astype(float)
# Y = satellite_positions[:, 2].astype(float)
# Z = satellite_positions[:, 3].astype(float)
# OBSERVATORY_ID = horizons_obscodes(observatory)
# def EN_trajectory_angle(piEN,piEE):
# def horizons_obscodes(observatory):
# def optcallback(socket, command, option):
# def compute_parallax_curvature(piE, delta_positions):
# def __init__(self, event, parallax_model):
# def North_East_vectors_target(self):
# def HJD_to_JD(self, time_to_transform):
# def parallax_combination(self, telescope):
# def annual_parallax(self, time_to_treat):
# def terrestrial_parallax(self, time_to_treat, altitude, longitude, latitude):
# def space_parallax(self, time_to_treat, satellite_name, telescope):
# def lonely_satellite(self, time_to_treat, telescope):
# def produce_horizons_ephem(body, start_time, end_time, observatory='ELP', step_size='60m',
# verbose=False):
# class MLParallaxes(object):
. Output only the next line. | para = microlparallax.MLParallaxes(event, parallax) |
Based on the snippet: <|code_start|>
def _create_event():
event = mock.MagicMock()
event.telescopes = [mock.MagicMock()]
event.telescopes[0].name = 'Test'
event.telescopes[0].lightcurve_magnitude = np.array([[0, 1, 1], [42, 6, 6],[43, 5, 1], [54, 8, 6]])
event.telescopes[0].lightcurve_flux = np.array([[0, 1, 1], [42, 6, 6], [43, 5, 1], [54, 8, 6]])
event.telescopes[0].gamma = 0.5
event.telescopes[0].filter = 'I'
return event
def test_initial_guess_PSPL():
event = _create_event()
<|code_end|>
, predict the immediate next line with the help of imports:
import numpy as np
import unittest.mock as mock
from pyLIMA import microlguess
and context (classes, functions, sometimes code) from other files:
# Path: pyLIMA/microlguess.py
# def initial_guess_PSPL(event):
# def initial_guess_FSPL(event):
# def initial_guess_DSPL(event):
# def differential_evolution_parameters_boundaries(model):
# def MCMC_parameters_initialization(parameter_key, parameters_dictionnary, parameters):
. Output only the next line. | guesses = microlguess.initial_guess_PSPL(event) |
Predict the next line for this snippet: <|code_start|>
# import pygame
# from pygame import movie
try:
OpenCV_avail = True
except ImportError:
OpenCV_avail = False
# Global reference; use AnimationCacheManager.shared_manager() to create and reference.
shared_cache_manager = None
warned_cache_disabled = False
class AnimationCacheManager(object):
def __init__(self, path):
self.path = os.path.expanduser(path)
if not os.path.exists(self.path):
os.makedirs(self.path)
self.load()
# TODO: Check cache for deleted files?
def __del__(self):
self.conn.close()
del self.conn
def shared_manager():
"""Returns a reference to the global, shared manager, if configured by the
``dmd_cache_path`` in :mod:`procgame.config`."""
global shared_cache_manager
if not shared_cache_manager:
<|code_end|>
with the help of current file imports:
import os
import struct
import yaml
import sqlite3
import bz2
import time
import dmd
import logging
import re
import colorsys
import zipfile
import cv2
import cv2.cv as cv
import pdb; pdb.set_trace()
import animgif
from cStringIO import StringIO
from StringIO import StringIO
from PIL import Image
from dmd import Frame
from sdl2_displaymanager import sdl2_DisplayManager
from procgame import config
and context from other files:
# Path: procgame/config.py
# def value_for_key_path(keypath, default=None):
# def load():
, which may contain function names, class names, or code. Output only the next line. | path = config.value_for_key_path('dmd_cache_path') |
Predict the next line after this snippet: <|code_start|>CH_MUSIC_2 = 3 # as above; note: these are useful if you want to pause music, start
# another song playing (other channel) and later resume that first track
# NOTE: using these channels will cause your music to be treated like _sounds_
# and that means they will be fully loaded into memory instead of streamed
# from the disk. Unlike sounds pre-loaded with the assetManager, so unless they
# are registered as non-streaming, they will be loaded at playback time,
# which will introduce a delay
# this refers to all music channels which provides a default for
CH_ALL_MUSIC_CHANNELS = -2 # pause_music, unpause_music, stop_music, fadeout_music
# IF you add your own reserved channels, use numbers > 3 and < 8
# (num channels == 8 unless you change mixer.set_num_channels(8))
# example : CH_SPINNER = 4 # doing this would ensure that your spinner doesn't
# eat all of your sound channels you would also need to add a
# mixer.set_reserved(CH_SPINNER) in the __init__() below, and be sure that
# whenever you play() the spinner effect, you do so on this CH_SPINNER channel
# PLAYBACK "Priorities" for VOICE playback
# PLAY_SIMULTANEOUS = 1 # STANDARD METHOD USING SHARED CHANNEL (CH_SFX)
PLAY_QUEUED = 2 # ADD TO QUEUED CHANNEL (CH_VOICE)
PLAY_FORCE = 3 # STOP ANY SOUNDS PLAYING AND PLAY THIS
PLAY_NOTBUSY= 4 # only play or queue if nothing is currently playing
DUCKED_MUSIC_PERCENT = 0.5 # drops the music volume to this percentage when ducking for voice lines
# it not enabled by default for asset_manager loadeds sounds
# (because the way the pygame queue works, it has to be enabled for all voice calls or no voice calls).
# enable (from game code) via:
# self.sound.enable_music_ducking(True)
<|code_end|>
using the current file's imports:
import random
import time
import logging
import os.path
import procgame
import procgame.game.skeletongame
import traceback
from procgame.game import mode
from collections import deque
from math import ceil
from pygame import mixer # This call takes a while.
and any relevant context from other files:
# Path: procgame/game/mode.py
# class Mode(object):
# class AcceptedSwitch:
# class Delayed:
# class ModeQueue(object):
# def __init__(self, game, priority):
# def __scan_switch_handlers(self):
# def add_switch_handler(self, name, event_type, delay, handler):
# def status_str(self):
# def delay(self, name=None, event_type=None, delay=0, handler=None, param=None):
# def cancel_delayed(self, name):
# def delay_info(self,name):
# def extend_delay_by(self,name,delay):
# def reset_delay_to(self,name,delay):
# def is_delayed(self,name):
# def handle_event(self, event):
# def mode_started(self):
# def mode_stopped(self):
# def mode_topmost(self):
# def mode_tick(self):
# def dispatch_delayed(self):
# def is_started(self):
# def add_child_mode(self, mode):
# def remove_child_mode(self, mode):
# def __str__(self):
# def update_lamps(self):
# def __init__(self, name, event_type, delay, handler, param):
# def __eq__(self, other):
# def __str__(self):
# def __init__(self, name, time, handler, event_type, param):
# def __str__(self):
# def __init__(self, game):
# def add(self, mode):
# def remove(self, mode):
# def __iter__(self):
# def __len__(self):
# def __contains__(self, mode):
# def __getitem__(self, v):
# def handle_event(self, event):
# def tick(self):
# def log_queue(self, log_level=logging.INFO):
# def tabularize(rows, col_spacing=2):
. Output only the next line. | class SoundController(mode.Mode): #made this a mode since I want to use delay feature for audio queuing |
Given the following code snippet before the placeholder: <|code_start|> return self.nframe
class SolidLayer(Layer):
def __init__(self, width, height, color, opaque=True):
super(SolidLayer, self).__init__(opaque)
self.frame = Frame(width,height)
self.frame.fill_rect(0,0,width,height,color)#.append(255))
def next_frame(self):
return self.frame
class AnimatedLayer(Layer):
"""Collection of frames displayed sequentially, as an animation. Optionally holds the last frame on-screen."""
hold = True
"""``True`` if the last frame of the animation should be held on-screen indefinitely."""
repeat = False
"""``True`` if the animation should be repeated indefinitely."""
frame_time = 1
"""Number of frame times each frame should be shown on screen before advancing to the next frame. The default is 1."""
frame_pointer = 0
"""Index of the next frame to display. Incremented by :meth:`next_frame`."""
def __init__(self, opaque=False, hold=True, repeat=False, frame_time=1, frames=None):
super(AnimatedLayer, self).__init__(opaque)
self.hold = hold
self.repeat = repeat
<|code_end|>
, predict the next line using imports from the current file:
from dmd import *
from procgame import config
from random import randrange
from movie import capPropId, getColorProp
from movie import Movie
from procgame.dmd import font, AnimFont, layers
import hdfont
import logging
import cv2
import cv2 as cv
import time
import dmd
import sdl2
import procgame
and context including class names, function names, and sometimes code from other files:
# Path: procgame/config.py
# def value_for_key_path(keypath, default=None):
# def load():
. Output only the next line. | self.fps = config.value_for_key_path('dmd_framerate', None) |
Using the snippet: <|code_start|>
class FakePinPROC(object):
"""Stand-in class for :class:`pinproc.PinPROC`. Generates DMD events."""
last_dmd_event = 0
frames_per_second = 30
drivers = gameitems.AttrCollection("drivers")
switch_events = []
switch_rules = [{'notifyHost':False, 'drivers':[]}] * 1024
"""List of events"""
"""Frames per second at which to dispatch :attr:`pinproc.EventTypeDMDFrameDisplayed` events."""
def __init__(self, machine_type):
# this short circuits the generation of 'extra' DMD events if the virtual/color DMD is used
<|code_end|>
, determine the next line of code. You have imports:
import time
import pinproc
import Queue
from game import gameitems
from procgame import config
and context (class names, function names, or code) available:
# Path: procgame/config.py
# def value_for_key_path(keypath, default=None):
# def load():
. Output only the next line. | use_virtual_dmd_only = config.value_for_key_path('use_virtual_dmd_only', False) |
Continue the code snippet: <|code_start|>
distance_place_sum = models.IntegerField(blank=True, null=True)
@property
def results(self):
ctype = ContentType.objects.get_for_model(self.__class__)
return Result.objects.filter(standings_content_type__pk=ctype.id, standings_object_id=self.id)
@property
def stages_participated(self):
stages = [1, 2, 3, 4, 5, 6, 7, 8]
stages_participated = 0
for stage in stages:
if getattr(self, "distance_points%i" % stage, 0) and getattr(self, "distance_points%i" % stage, 0) > 0:
stages_participated += 1
return stages_participated
def set_points(self):
stages = [1, 2, 3, 4, 5, 6, 7, 8]
mapping = {obj.id: index for index, obj in enumerate(self.competition.get_children(), start=1)}
results = self.results
for result in results:
setattr(self, "group_points%i" % mapping.get(result.competition_id), result.points_group)
setattr(self, "distance_points%i" % mapping.get(result.competition_id), result.points_distance)
setattr(self, "distance_place%i" % mapping.get(result.competition_id), result.result_distance)
try:
stages.remove(mapping.get(result.competition_id))
except:
<|code_end|>
. Use current file imports:
from django.db import models, transaction
from django.db.models import signals
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.utils.translation import ugettext_lazy as _
from django_celery_beat.models import PeriodicTask, PeriodicTasks, CrontabSchedule
from easy_thumbnails.fields import ThumbnailerImageField
from slugify import slugify
from velo.core.models import Log
from velo.core.utils import restart_celerybeat
from velo.results.helper import time_to_seconds
from velo.velo.mixins.models import TimestampMixin
from velo.velo.utils import load_class
import os
import time
import datetime
import uuid
and context (classes, functions, or code) from other files:
# Path: velo/core/models.py
# class Log(models.Model):
# content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True, blank=True)
# object_id = models.PositiveIntegerField(null=True, blank=True)
# content_object = GenericForeignKey('content_type', 'object_id')
#
# user = models.ForeignKey(User, null=True, blank=True)
# action = models.CharField(max_length=50, blank=True)
# message = models.CharField(max_length=255, blank=True)
# params = JSONField(blank=True, null=True)
#
# created = models.DateTimeField(auto_now_add=True)
# modified = models.DateTimeField(auto_now=True)
#
# def set_message(self, message, commit=True):
# self.message = message
# if commit:
# self.save()
#
# def set_object(self, obj, commit=True):
# self.content_object = obj
# if commit:
# self.save()
#
# Path: velo/velo/utils.py
# def load_class(full_class_string):
# """
# dynamically load a class from a string
# """
#
# class_data = full_class_string.split(".")
# module_path = ".".join(class_data[:-1])
# class_str = class_data[-1]
#
# module = importlib.import_module(module_path)
# # Finally, we retrieve the Class
# return getattr(module, class_str)
. Output only the next line. | Log.objects.create(content_object=self, message="Multiple results in stage %s" % result.competition) |
Here is a snippet: <|code_start|> # r = Result.objects.filter(competition=self.competition, number__distance=self.number.distance).order_by('time')
# if r:
# zero_time = datetime.datetime.combine(datetime.date.today(), datetime.time(0, 0, 0, 0))
# delta = datetime.datetime.combine(datetime.date.today(), r[0].time) - zero_time
# self.loses_distance = datetime.datetime.combine(datetime.date.today(), self.time) - delta
# else:
# self.loses_distance = '00:00:00'
#
# def set_loses_group(self):
# r = Result.objects.filter(competition=self.competition, number__distance=self.number.distance, participant__group=self.participant.group).order_by('time')
# if r:
# zero_time = datetime.datetime.combine(datetime.date.today(), datetime.time(0, 0, 0, 0))
# delta = datetime.datetime.combine(datetime.date.today(), r[0].time) - zero_time
# self.loses_group = datetime.datetime.combine(datetime.date.today(), self.time) - delta
# else:
# self.loses_group = '00:00:00'
def set_avg_speed(self):
avg_speed = self.avg_speed
if self.time:
admin = DistanceAdmin.objects.get(competition=self.competition, distance=self.participant.distance)
seconds = datetime.timedelta(hours=self.time.hour, minutes=self.time.minute, seconds=self.time.second).seconds
if admin.distance_actual:
self.avg_speed = round((float(admin.distance_actual) / float(seconds))*3.6, 1)
if avg_speed != self.avg_speed:
return True
return False
def get_competition_class(self):
if not self._competition_class:
<|code_end|>
. Write the next line using the current file imports:
from django.db import models, transaction
from django.db.models import signals
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.utils.translation import ugettext_lazy as _
from django_celery_beat.models import PeriodicTask, PeriodicTasks, CrontabSchedule
from easy_thumbnails.fields import ThumbnailerImageField
from slugify import slugify
from velo.core.models import Log
from velo.core.utils import restart_celerybeat
from velo.results.helper import time_to_seconds
from velo.velo.mixins.models import TimestampMixin
from velo.velo.utils import load_class
import os
import time
import datetime
import uuid
and context from other files:
# Path: velo/core/models.py
# class Log(models.Model):
# content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True, blank=True)
# object_id = models.PositiveIntegerField(null=True, blank=True)
# content_object = GenericForeignKey('content_type', 'object_id')
#
# user = models.ForeignKey(User, null=True, blank=True)
# action = models.CharField(max_length=50, blank=True)
# message = models.CharField(max_length=255, blank=True)
# params = JSONField(blank=True, null=True)
#
# created = models.DateTimeField(auto_now_add=True)
# modified = models.DateTimeField(auto_now=True)
#
# def set_message(self, message, commit=True):
# self.message = message
# if commit:
# self.save()
#
# def set_object(self, obj, commit=True):
# self.content_object = obj
# if commit:
# self.save()
#
# Path: velo/velo/utils.py
# def load_class(full_class_string):
# """
# dynamically load a class from a string
# """
#
# class_data = full_class_string.split(".")
# module_path = ".".join(class_data[:-1])
# class_str = class_data[-1]
#
# module = importlib.import_module(module_path)
# # Finally, we retrieve the Class
# return getattr(module, class_str)
, which may include functions, classes, or code. Output only the next line. | class_ = load_class(self.competition.processing_class) |
Using the snippet: <|code_start|> [code128.Code128("*%s*%s*" % (self.invoice.get('name'), str(final_amount)), humanReadable=1),
'Vēlam veiksmīgu un pozitīvām emocijām bagātu sezonu!']
]
bottom_table = Table(data, colWidths=(self.doc.width*0.3, self.doc.width*0.7))
bottom_table.setStyle(
TableStyle([
('FONT', (0, 0), (-1, -1), 'UbuntuB'),
('SIZE', (0, 0), (-1, -1), 14),
]))
self.elements.append(bottom_table)
def _build_footer(self):
# pass
# if self.competition.id in (89, 90, 91, 92, 93, 94, 95, 96, 97):
adv = os.path.join(settings.MEDIA_ROOT, "adverts", "2020_lvm.jpg")
im = Image(adv, 567, 91)
self.elements.append(im)
def build(self):
self._build_top()
self._build_sender_top()
self._build_receiver_top()
self._build_info_top()
self._build_items()
self.elements.append(Spacer(10 * mm, 10 * mm))
# self.elements.append(Paragraph("", normal))
self._build_footer()
<|code_end|>
, determine the next line of code. You have imports:
import os
from django.conf import settings
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4
from reportlab.platypus import SimpleDocTemplate, Paragraph, TableStyle, Spacer, Image
from reportlab.lib.units import mm
from reportlab.lib.colors import HexColor
from reportlab.platypus import Table
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.enums import TA_CENTER
from reportlab.graphics.barcode import code128
from io import BytesIO
from velo.core.pdf import InvoiceCanvas
from velo.payment.pdf_utils import BreakingParagraph
from velo.payment.skaitlis import num_to_text
and context (class names, function names, or code) available:
# Path: velo/core/pdf.py
# class InvoiceCanvas(canvas.Canvas):
# def __init__(self, *args, **kwargs):
# canvas.Canvas.__init__(self, *args, **kwargs)
# self.pages = []
#
# def showPage(self):
# """
# On a page break, add information to the list
# """
# self.pages.append(dict(self.__dict__))
# self._startPage()
#
# def save(self):
# """
# Add the page number to each page (page x of y)
# """
# for page in self.pages:
# self.__dict__.update(page)
# # self.draw_header()
# self.draw_footer()
# canvas.Canvas.showPage(self)
#
# canvas.Canvas.save(self)
#
# # def draw_header(self):
# # img = os.path.join(settings.MEDIA_ROOT, "adverts", "2018_invoice_header.jpg")
# # self.drawImage(img, 0.5*cm, 24 * cm, width=self._pagesize[0]-cm, height=153, preserveAspectRatio=True)
#
# def draw_footer(self):
# pass
# # img = os.path.join(settings.MEDIA_ROOT, "adverts", "2019_invoice_footer.jpg")
# # img = "velo/test_media/2019_invoice_footer.jpg"
# # self.drawImage(img, 0.5*cm, 0.5*cm, width=self._pagesize[0]-cm, height=86, preserveAspectRatio=True)
. Output only the next line. | self.doc.build(self.elements, canvasmaker=InvoiceCanvas) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.