text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def vertical(x, ymin=0, ymax=1, color=None, width=None, dash=None, opacity=None):
"""Draws a vertical line from `ymin` to `ymax`. Parameters xmin : int, optional... |
lineattr = {}
if color:
lineattr['color'] = color
if width:
lineattr['width'] = width
if dash:
lineattr['dash'] = dash
layout = dict(
shapes=[dict(type='line', x0=x, x1=x, y0=ymin, y1=ymax, opacity=opacity, line=lineattr)]
)
return Chart(layout=layout) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def horizontal(y, xmin=0, xmax=1, color=None, width=None, dash=None, opacity=None):
"""Draws a horizontal line from `xmin` to `xmax`. Parameters xmin : int, opti... |
lineattr = {}
if color:
lineattr['color'] = color
if width:
lineattr['width'] = width
if dash:
lineattr['dash'] = dash
layout = dict(
shapes=[dict(type='line', x0=xmin, x1=xmax, y0=y, y1=y, opacity=opacity, line=lineattr)]
)
return Chart(layout=layout) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def line3d( x, y, z, label=None, color=None, width=None, dash=None, opacity=None, mode='lines+markers' ):
"""Create a 3d line chart.""" |
x = np.atleast_1d(x)
y = np.atleast_1d(y)
z = np.atleast_1d(z)
assert x.shape == y.shape
assert y.shape == z.shape
lineattr = {}
if color:
lineattr['color'] = color
if width:
lineattr['width'] = width
if dash:
lineattr['dash'] = dash
if y.ndim == 2:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scatter( x=None, y=None, label=None, color=None, width=None, dash=None, opacity=None, markersize=6, yaxis=1, fill=None, text="", mode='markers', ):
"""Draws ... |
return line(
x=x,
y=y,
label=label,
color=color,
width=width,
dash=dash,
opacity=opacity,
mode=mode,
yaxis=yaxis,
fill=fill,
text=text,
markersize=markersize,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bar(x=None, y=None, label=None, mode='group', yaxis=1, opacity=None):
"""Create a bar chart. Parameters x : array-like, optional y : TODO, optional label : T... |
assert x is not None or y is not None, "x or y must be something"
yn = 'y' + str(yaxis)
if y is None:
y = x
x = None
if x is None:
x = np.arange(len(y))
else:
x = _try_pydatetime(x)
x = np.atleast_1d(x)
y = np.atleast_1d(y)
if y.ndim == 2:
if not ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def heatmap(z, x=None, y=None, colorscale='Viridis'):
"""Create a heatmap. Parameters z : TODO x : TODO, optional y : TODO, optional colorscale : TODO, optional ... |
z = np.atleast_1d(z)
data = [go.Heatmap(z=z, x=x, y=y, colorscale=colorscale)]
return Chart(data=data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fill_zero( x=None, y=None, label=None, color=None, width=None, dash=None, opacity=None, mode='lines+markers', **kargs ):
"""Fill to zero. Parameters x : arra... |
return line(
x=x,
y=y,
label=label,
color=color,
width=width,
dash=dash,
opacity=opacity,
mode=mode,
fill='tozeroy',
**kargs
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fill_between( x=None, ylow=None, yhigh=None, label=None, color=None, width=None, dash=None, opacity=None, mode='lines+markers', **kargs ):
"""Fill between `y... |
plot = line(
x=x,
y=ylow,
label=label,
color=color,
width=width,
dash=dash,
opacity=opacity,
mode=mode,
fill=None,
**kargs
)
plot += line(
x=x,
y=yhigh,
label=label,
color=color,
width=wi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rug(x, label=None, opacity=None):
"""Rug chart. Parameters x : array-like, optional label : TODO, optional opacity : TODO, optional Returns ------- Chart """ |
x = _try_pydatetime(x)
x = np.atleast_1d(x)
data = [
go.Scatter(
x=x,
y=np.ones_like(x),
name=label,
opacity=opacity,
mode='markers',
marker=dict(symbol='line-ns-open'),
)
]
layout = dict(
barmode='overl... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def surface(x, y, z):
"""Surface plot. Parameters x : array-like, optional y : array-like, optional z : array-like, optional Returns ------- Chart """ |
data = [go.Surface(x=x, y=y, z=z)]
return Chart(data=data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hist2d(x, y, label=None, opacity=None):
"""2D Histogram. Parameters x : array-like, optional y : array-like, optional label : TODO, optional opacity : float,... |
x = np.atleast_1d(x)
y = np.atleast_1d(y)
data = [go.Histogram2d(x=x, y=y, opacity=opacity, name=label)]
return Chart(data=data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ytickangle(self, angle, index=1):
"""Set the angle of the y-axis tick labels. Parameters value : int Angle in degrees index : int, optional Y-axis index Retu... |
self.layout['yaxis' + str(index)]['tickangle'] = angle
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ylabelsize(self, size, index=1):
"""Set the size of the label. Parameters size : int Returns ------- Chart """ |
self.layout['yaxis' + str(index)]['titlefont']['size'] = size
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def yticksize(self, size, index=1):
"""Set the tick font size. Parameters size : int Returns ------- Chart """ |
self.layout['yaxis' + str(index)]['tickfont']['size'] = size
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ytickvals(self, values, index=1):
"""Set the tick values. Parameters values : array-like Returns ------- Chart """ |
self.layout['yaxis' + str(index)]['tickvals'] = values
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def yticktext(self, labels, index=1):
"""Set the tick labels. Parameters labels : array-like Returns ------- Chart """ |
self.layout['yaxis' + str(index)]['ticktext'] = labels
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ylim(self, low, high, index=1):
"""Set yaxis limits. Parameters low : number high : number index : int, optional Returns ------- Chart """ |
self.layout['yaxis' + str(index)]['range'] = [low, high]
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ydtick(self, dtick, index=1):
"""Set the tick distance.""" |
self.layout['yaxis' + str(index)]['dtick'] = dtick
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ynticks(self, nticks, index=1):
"""Set the number of ticks.""" |
self.layout['yaxis' + str(index)]['nticks'] = nticks
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show( self, filename: Optional[str] = None, show_link: bool = True, auto_open: bool = True, detect_notebook: bool = True, ) -> None: """Display the chart. Par... |
kargs = {}
if detect_notebook and _detect_notebook():
py.init_notebook_mode()
plot = py.iplot
else:
plot = py.plot
if filename is None:
filename = NamedTemporaryFile(prefix='plotly', suffix='.html', delete=False).name
k... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save( self, filename: Optional[str] = None, show_link: bool = True, auto_open: bool = False, output: str = 'file', plotlyjs: bool = True, ) -> str: """Save th... |
if filename is None:
filename = NamedTemporaryFile(prefix='plotly', suffix='.html', delete=False).name
# NOTE: this doesn't work for output 'div'
py.plot(
self,
show_link=show_link,
filename=filename,
auto_open=auto_open,
o... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_method_sig(method):
""" Given a function, it returns a string that pretty much looks how the function signature_ would be written in python. :param metho... |
# The return value of ArgSpec is a bit weird, as the list of arguments and
# list of defaults are returned in separate array.
# eg: ArgSpec(args=['first_arg', 'second_arg', 'third_arg'],
# varargs=None, keywords=None, defaults=(42, 'something'))
argspec = inspect.getargspec(method)
arg_index=0... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ThenAt(self, n, f, *_args, **kwargs):
""" `ThenAt` enables you to create a partially apply many arguments to a function, the returned partial expects a singl... |
_return_type = None
n_args = n - 1
if '_return_type' in kwargs:
_return_type = kwargs['_return_type']
del kwargs['_return_type']
@utils.lift
def g(x):
new_args = _args[0:n_args] + (x,) + _args[n_args:] if n_args >= 0 else _args
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Seq(self, *sequence, **kwargs):
""" `Seq` is used to express function composition. The expression Seq(f, g) be equivalent to lambda x: g(f(x)) As you see, it... |
fs = [ _parse(elem)._f for elem in sequence ]
def g(x, state):
return functools.reduce(lambda args, f: f(*args), fs, (x, state))
return self.__then__(g, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Write(self, *state_args, **state_dict):
"""See `phi.dsl.Expression.Read`""" |
if len(state_dict) + len(state_args) < 1:
raise Exception("Please include at-least 1 state variable, got {0} and {1}".format(state_args, state_dict))
if len(state_dict) > 1:
raise Exception("Please include at-most 1 keyword argument expression, got {0}".format(state_dict))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Else(self, *Else, **kwargs):
"""See `phi.dsl.Expression.If`""" |
root = self._root
ast = self._ast
next_else = E.Seq(*Else)._f
ast = _add_else(ast, next_else)
g = _compile_if(ast)
return root.__then__(g, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def length(string, until=None):
""" Returns the number of graphemes in the string. Note that this functions needs to traverse the full string to calculate the le... |
if until is None:
return sum(1 for _ in GraphemeIterator(string))
iterator = graphemes(string)
count = 0
while True:
try:
if count >= until:
break
next(iterator)
except StopIteration:
break
else:
count += 1... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def slice(string, start=None, end=None):
""" Returns a substring of the given string, counting graphemes instead of codepoints. Negative indices is currently not... |
if start is None:
start = 0
if end is not None and start >= end:
return ""
if start < 0:
raise NotImplementedError("Negative indexing is currently not supported.")
sum_ = 0
start_index = None
for grapheme_index, grapheme_length in enumerate(grapheme_lengths(string)):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def contains(string, substring):
""" Returns true if the sequence of graphemes in substring is also present in string. This differs from the normal python `in` o... |
if substring not in string:
return False
substr_graphemes = list(graphemes(substring))
if len(substr_graphemes) == 0:
return True
elif len(substr_graphemes) == 1:
return substr_graphemes[0] in graphemes(string)
else:
str_iter = graphemes(string)
str_sub_par... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def startswith(string, prefix):
""" Like str.startswith, but also checks that the string starts with the given prefixes sequence of graphemes. str.startswith may... |
return string.startswith(prefix) and safe_split_index(string, len(prefix)) == len(prefix) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def endswith(string, suffix):
""" Like str.endswith, but also checks that the string ends with the given prefixes sequence of graphemes. str.endswith may return ... |
expected_index = len(string) - len(suffix)
return string.endswith(suffix) and safe_split_index(string, expected_index) == expected_index |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def safe_split_index(string, max_len):
""" Returns the highest index up to `max_len` at which the given string can be sliced, without breaking a grapheme. This i... |
last_index = get_last_certain_break_index(string, max_len)
for l in grapheme_lengths(string[last_index:]):
if last_index + l > max_len:
break
last_index += l
return last_index |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def writeB1logfile(filename, data):
"""Write a header structure into a B1 logfile. Inputs: filename: name of the file. data: header dictionary Notes: exceptions ... |
allkeys = list(data.keys())
f = open(filename, 'wt', encoding='utf-8')
for ld in _logfile_data: # process each line
linebegin = ld[0]
fieldnames = ld[1]
# set the default formatter if it is not given
if len(ld) < 3:
formatter = str
elif ld[2] is None:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _readedf_extractline(left, right):
"""Helper function to interpret lines in an EDF file header. """ |
functions = [int, float, lambda l:float(l.split(None, 1)[0]),
lambda l:int(l.split(None, 1)[0]),
dateutil.parser.parse, lambda x:str(x)]
for f in functions:
try:
right = f(right)
break
except ValueError:
continue
return r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def readmarheader(filename):
"""Read a header from a MarResearch .image file.""" |
with open(filename, 'rb') as f:
intheader = np.fromstring(f.read(10 * 4), np.int32)
floatheader = np.fromstring(f.read(15 * 4), '<f4')
strheader = f.read(24)
f.read(4)
otherstrings = [f.read(16) for i in range(29)]
return {'Xsize': intheader[0], 'Ysize': intheader[1], 'M... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Square(x, a, b, c):
"""Second order polynomial Inputs: ------- ``x``: independent variable ``a``: coefficient of the second-order term ``b``: coefficient of ... |
return a * x ** 2 + b * x + c |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Cube(x, a, b, c, d):
"""Third order polynomial Inputs: ------- ``x``: independent variable ``a``: coefficient of the third-order term ``b``: coefficient of t... |
return a * x ** 3 + b * x ** 2 + c * x + d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def LogNormal(x, a, mu, sigma):
"""PDF of a log-normal distribution Inputs: ------- ``x``: independent variable ``a``: amplitude ``mu``: center parameter ``sigma... |
return a / np.sqrt(2 * np.pi * sigma ** 2 * x ** 2) *\
np.exp(-(np.log(x) - mu) ** 2 / (2 * sigma ** 2)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_subdirs(startdir='.', recursion_depth=None):
"""Find all subdirectory of a directory. Inputs: startdir: directory to start with. Defaults to the current... |
startdir = os.path.expanduser(startdir)
direct_subdirs = [os.path.join(startdir, x) for x in os.listdir(
startdir) if os.path.isdir(os.path.join(startdir, x))]
if recursion_depth is None:
next_recursion_depth = None
else:
next_recursion_depth = recursion_depth - 1
if (recurs... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def findpeak_multi(x, y, dy, N, Ntolerance, Nfit=None, curve='Lorentz', return_xfit=False, return_stat=False):
"""Find multiple peaks in the dataset given by vec... |
if Nfit is None:
Nfit = N
# find points where the curve grows for N points before them and
# decreases for N points after them. To accomplish this, we create
# an indicator array of the sign of the first derivative.
sgndiff = np.sign(np.diff(y))
xdiff = x[:-1] # associate difference va... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def readspec(filename, read_scan=None):
"""Open a SPEC file and read its content Inputs: filename: string the file to open read_scan: None, 'all' or integer the ... |
with open(filename, 'rt') as f:
sf = {'motors': [], 'maxscannumber': 0}
sf['originalfilename'] = filename
lastscannumber = None
while True:
l = f.readline()
if l.startswith('#F'):
sf['filename'] = l[2:].strip()
elif l.startswith('#... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def energy(self) -> ErrorValue: """X-ray energy""" |
return (ErrorValue(*(scipy.constants.physical_constants['speed of light in vacuum'][0::2])) *
ErrorValue(*(scipy.constants.physical_constants['Planck constant in eV s'][0::2])) /
scipy.constants.nano /
self.wavelength) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def findbeam_gravity(data, mask):
"""Find beam center with the "gravity" method Inputs: data: scattering image mask: mask matrix Output: a vector of length 2 wit... |
# for each row and column find the center of gravity
data1 = data.copy() # take a copy, because elements will be tampered with
data1[mask == 0] = 0 # set masked elements to zero
# vector of x (row) coordinates
x = np.arange(data1.shape[0])
# vector of y (column) coordinates
y = np.arange(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def findbeam_slices(data, orig_initial, mask=None, maxiter=0, epsfcn=0.001, dmin=0, dmax=np.inf, sector_width=np.pi / 9.0, extent=10, callback=None):
"""Find bea... |
if mask is None:
mask = np.ones(data.shape)
data = data.astype(np.double)
def targetfunc(orig, data, mask, orig_orig, callback):
# integrate four sectors
I = [None] * 4
p, Ints, A = radint_nsector(data, None, -1, -1, -1, orig[0] + orig_orig[0], orig[1] + orig_orig[1], mask=... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def findbeam_azimuthal(data, orig_initial, mask=None, maxiter=100, Ntheta=50, dmin=0, dmax=np.inf, extent=10, callback=None):
"""Find beam center using azimuthal... |
if mask is None:
mask = np.ones(data.shape)
data = data.astype(np.double)
def targetfunc(orig, data, mask, orig_orig, callback):
def sinfun(p, x, y):
return (y - np.sin(x + p[1]) * p[0] - p[2]) / np.sqrt(len(x))
t, I, a = azimintpix(data, None, orig[
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def findbeam_azimuthal_fold(data, orig_initial, mask=None, maxiter=100, Ntheta=50, dmin=0, dmax=np.inf, extent=10, callback=None):
"""Find beam center using azim... |
if Ntheta % 2:
raise ValueError('Ntheta should be even!')
if mask is None:
mask = np.ones_like(data).astype(np.uint8)
data = data.astype(np.double)
# the function to minimize is the sum of squared difference of two halves of
# the azimuthal integral.
def targetfunc(orig, data, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def findbeam_semitransparent(data, pri, threshold=0.05):
"""Find beam with 2D weighting of semitransparent beamstop area Inputs: data: scattering matrix pri: lis... |
rowmin = np.floor(min(pri[2:]))
rowmax = np.ceil(max(pri[2:]))
colmin = np.floor(min(pri[:2]))
colmax = np.ceil(max(pri[:2]))
if threshold is not None:
# beam area on the scattering image
B = data[rowmin:rowmax, colmin:colmax]
# print B.shape
# row and column indice... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def findbeam_radialpeak(data, orig_initial, mask, rmin, rmax, maxiter=100, drive_by='amplitude', extent=10, callback=None):
"""Find the beam by minimizing the wi... |
orig_initial = np.array(orig_initial)
mask = 1 - mask.astype(np.uint8)
data = data.astype(np.double)
pix = np.arange(rmin * 1.0, rmax * 1.0, 1)
if drive_by.lower() == 'hwhm':
def targetfunc(orig, data, mask, orig_orig, callback):
I = radintpix(
data, None, orig[0... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scalefactor(self, other, qmin=None, qmax=None, Npoints=None):
"""Calculate a scaling factor, by which this curve is to be multiplied to best fit the other on... |
if qmin is None:
qmin = max(self.q.min(), other.q.min())
if qmax is None:
xmax = min(self.q.max(), other.q.max())
data1 = self.trim(qmin, qmax)
data2 = other.trim(qmin, qmax)
if Npoints is None:
Npoints = min(len(data1), len(data2))
co... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _substitute_fixed_parameters_covar(self, covar):
"""Insert fixed parameters in a covariance matrix""" |
covar_resolved = np.empty((len(self._fixed_parameters), len(self._fixed_parameters)))
indices_of_fixed_parameters = [i for i in range(len(self.parameters())) if
self._fixed_parameters[i] is not None]
indices_of_free_parameters = [i for i in range(len(self.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loadmask(self, filename: str) -> np.ndarray: """Load a mask file.""" |
mask = scipy.io.loadmat(self.find_file(filename, what='mask'))
maskkey = [k for k in mask.keys() if not (k.startswith('_') or k.endswith('_'))][0]
return mask[maskkey].astype(np.bool) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loadcurve(self, fsn: int) -> classes2.Curve: """Load a radial scattering curve""" |
return classes2.Curve.new_from_file(self.find_file(self._exposureclass + '_%05d.txt' % fsn)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def writeint2dnorm(filename, Intensity, Error=None):
"""Save the intensity and error matrices to a file Inputs ------ filename: string the name of the file Inten... |
whattosave = {'Intensity': Intensity}
if Error is not None:
whattosave['Error'] = Error
if filename.upper().endswith('.NPZ'):
np.savez(filename, **whattosave)
elif filename.upper().endswith('.MAT'):
scipy.io.savemat(filename, whattosave)
else: # text file
np.savetxt... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def readbdfv2(filename, bdfext='.bdf', bhfext='.bhf'):
"""Read a version 2 Bessy Data File Inputs ------ filename: string the name of the input file. One can giv... |
datas = header.readbhfv2(filename, True, bdfext, bhfext)
return datas |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def readmar(filename):
"""Read a two-dimensional scattering pattern from a MarResearch .image file. """ |
hed = header.readmarheader(filename)
with open(filename, 'rb') as f:
h = f.read(hed['recordlength'])
data = np.fromstring(
f.read(2 * hed['Xsize'] * hed['Ysize']), '<u2').astype(np.float64)
if hed['highintensitypixels'] > 0:
raise NotImplementedError(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def writebdfv2(filename, bdf, bdfext='.bdf', bhfext='.bhf'):
"""Write a version 2 Bessy Data File Inputs ------ filename: string the name of the output file. One... |
if filename.endswith(bdfext):
basename = filename[:-len(bdfext)]
elif filename.endswith(bhfext):
basename = filename[:-len(bhfext)]
else:
basename = filename
header.writebhfv2(basename + '.bhf', bdf)
f = open(basename + '.bdf', 'wb')
keys = ['RAWDATA', 'RAWERROR', 'CORRD... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fill_padding(padded_string):
# type: (bytes) -> bytes """ Fill up missing padding in a string. This function makes sure that the string has length which is m... |
length = len(padded_string)
reminder = len(padded_string) % 4
if reminder:
return padded_string.ljust(length + 4 - reminder, b'.')
return padded_string |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decode(encoded):
# type: (bytes) -> bytes """ Decode the result of querystringsafe_base64_encode or a regular base64. .. note :: As a regular base64 string d... |
padded_string = fill_padding(encoded)
return urlsafe_b64decode(padded_string.replace(b'.', b'=')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flatten_hierarchical_dict(original_dict, separator='.', max_recursion_depth=None):
"""Flatten a dict. Inputs ------ original_dict: dict the dictionary to fla... |
if max_recursion_depth is not None and max_recursion_depth <= 0:
# we reached the maximum recursion depth, refuse to go further
return original_dict
if max_recursion_depth is None:
next_recursion_depth = None
else:
next_recursion_depth = max_recursion_depth - 1
dict1 = {... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fit_shullroess(q, Intensity, Error, R0=None, r=None):
"""Do a Shull-Roess fitting on the scattering data. Inputs: q: np.ndarray[ndim=1] vector of the q value... |
q = np.array(q)
Intensity = np.array(Intensity)
Error = np.array(Error)
if R0 is None:
r0s = np.linspace(1, 2 * np.pi / q.min(), 1000)
def naive_fit_chi2(q, Intensity, r0):
p = np.polyfit(np.log(q ** 2 + 3 / r0 ** 2), np.log(Intensity), 1)
return ((np.polyval(p, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def findfileindirs(filename, dirs=None, use_pythonpath=True, use_searchpath=True, notfound_is_fatal=True, notfound_val=None):
"""Find file in multiple directorie... |
if os.path.isabs(filename):
if os.path.exists(filename):
return filename
elif notfound_is_fatal:
raise IOError('File ' + filename + ' not found.')
else:
return notfound_val
if dirs is None:
dirs = []
dirs = normalize_listargument(dirs)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def twotheta(matrix, bcx, bcy, pixsizeperdist):
"""Calculate the two-theta matrix for a scattering matrix Inputs: matrix: only the shape of it is needed bcx, bcy... |
col, row = np.meshgrid(list(range(matrix.shape[1])), list(range(matrix.shape[0])))
return np.arctan(np.sqrt((row - bcx) ** 2 + (col - bcy) ** 2) * pixsizeperdist) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def solidangle(twotheta, sampletodetectordistance, pixelsize=None):
"""Solid-angle correction for two-dimensional SAS images Inputs: twotheta: matrix of two-thet... |
if pixelsize is None:
pixelsize = 1
return sampletodetectordistance ** 2 / np.cos(twotheta) ** 3 / pixelsize ** 2 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def solidangle_errorprop(twotheta, dtwotheta, sampletodetectordistance, dsampletodetectordistance, pixelsize=None):
"""Solid-angle correction for two-dimensional... |
SAC = solidangle(twotheta, sampletodetectordistance, pixelsize)
if pixelsize is None:
pixelsize = 1
return (SAC,
(sampletodetectordistance * (4 * dsampletodetectordistance ** 2 * np.cos(twotheta) ** 2 +
9 * dtwotheta ** 2 * sampletodetectordistanc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def angledependentabsorption(twotheta, transmission):
"""Correction for angle-dependent absorption of the sample Inputs: twotheta: matrix of two-theta values tra... |
cor = np.ones(twotheta.shape)
if transmission == 1:
return cor
mud = -np.log(transmission)
cor[twotheta > 0] = transmission * mud * (1 - 1 / np.cos(twotheta[twotheta > 0])) / (np.exp(-mud / np.cos(twotheta[twotheta > 0])) - np.exp(-mud))
return cor |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def angledependentabsorption_errorprop(twotheta, dtwotheta, transmission, dtransmission):
"""Correction for angle-dependent absorption of the sample with error p... |
# error propagation formula calculated using sympy
return (angledependentabsorption(twotheta, transmission),
_calc_angledependentabsorption_error(twotheta, dtwotheta, transmission, dtransmission)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def angledependentairtransmission(twotheta, mu_air, sampletodetectordistance):
"""Correction for the angle dependent absorption of air in the scattered beam path... |
return np.exp(mu_air * sampletodetectordistance / np.cos(twotheta)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def angledependentairtransmission_errorprop(twotheta, dtwotheta, mu_air, dmu_air, sampletodetectordistance, dsampletodetectordistance):
"""Correction for the ang... |
return (np.exp(mu_air * sampletodetectordistance / np.cos(twotheta)),
np.sqrt(dmu_air ** 2 * sampletodetectordistance ** 2 *
np.exp(2 * mu_air * sampletodetectordistance / np.cos(twotheta))
/ np.cos(twotheta) ** 2 + dsampletodetectordistance ** 2 *
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_file(self, filename: str, strip_path: bool = True, what='exposure') -> str: """Find file in the path""" |
if what == 'exposure':
path = self._path
elif what == 'header':
path = self._headerpath
elif what == 'mask':
path = self._maskpath
else:
path = self._path
tried = []
if strip_path:
filename = os.path.split(filen... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_subpath(self, subpath: str):
"""Search a file or directory relative to the base path""" |
for d in self._path:
if os.path.exists(os.path.join(d, subpath)):
return os.path.join(d, subpath)
raise FileNotFoundError |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sum(self, only_valid=True) -> ErrorValue: """Calculate the sum of pixels, not counting the masked ones if only_valid is True.""" |
if not only_valid:
mask = 1
else:
mask = self.mask
return ErrorValue((self.intensity * mask).sum(),
((self.error * mask) ** 2).sum() ** 0.5) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mean(self, only_valid=True) -> ErrorValue: """Calculate the mean of the pixels, not counting the masked ones if only_valid is True.""" |
if not only_valid:
intensity = self.intensity
error = self.error
else:
intensity = self.intensity[self.mask]
error = self.error[self.mask]
return ErrorValue(intensity.mean(),
(error ** 2).mean() ** 0.5) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def twotheta(self) -> ErrorValue: """Calculate the two-theta array""" |
row, column = np.ogrid[0:self.shape[0], 0:self.shape[1]]
rho = (((self.header.beamcentery - row) * self.header.pixelsizey) ** 2 +
((self.header.beamcenterx - column) * self.header.pixelsizex) ** 2) ** 0.5
assert isinstance(self.header.pixelsizex, ErrorValue)
assert isinst... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pixel_to_q(self, row: float, column: float):
"""Return the q coordinates of a given pixel. Inputs: row: float the row (vertical) coordinate of the pixel colu... |
qrow = 4 * np.pi * np.sin(
0.5 * np.arctan(
(row - float(self.header.beamcentery)) *
float(self.header.pixelsizey) /
float(self.header.distance))) / float(self.header.wavelength)
qcol = 4 * np.pi * np.sin(0.5 * np.arctan(
(colu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def radial_average(self, qrange=None, pixel=False, returnmask=False, errorpropagation=3, abscissa_errorpropagation=3, raw_result=False) -> Curve: """Do a radial a... |
retmask = None
if isinstance(qrange, str):
if qrange == 'linear':
qrange = None
autoqrange_linear = True
elif qrange == 'log':
qrange = None
autoqrange_linear = False
else:
raise ValueErr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mask_negative(self):
"""Extend the mask with the image elements where the intensity is negative.""" |
self.mask = np.logical_and(self.mask, ~(self.intensity < 0)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def distance(self) -> ErrorValue: """Sample-to-detector distance""" |
if 'DistCalibrated' in self._data:
dist = self._data['DistCalibrated']
else:
dist = self._data["Dist"]
if 'DistCalibratedError' in self._data:
disterr = self._data['DistCalibratedError']
elif 'DistError' in self._data:
disterr = self._data... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def simultaneous_nonlinear_leastsquares(xs, ys, dys, func, params_inits, verbose=False, **kwargs):
"""Do a simultaneous nonlinear least-squares fit and return th... |
p, dp, statdict = simultaneous_nlsq_fit(xs, ys, dys, func, params_inits,
verbose, **kwargs)
params = [[ErrorValue(p_, dp_) for (p_, dp_) in zip(pcurrent, dpcurrent)]
for (pcurrent, dpcurrent) in zip(p, dp)]
return tuple(params + [statdict]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tostring(self: 'ErrorValue', extra_digits: int = 0, plusminus: str = ' +/- ', fmt: str = None) -> str: """Make a string representation of the value and its un... |
if isinstance(fmt, str) and fmt.lower().endswith('tex'):
return re.subn('(\d*)(\.(\d)*)?[eE]([+-]?\d+)',
lambda m: (r'$%s%s\cdot 10^{%s}$' % (m.group(1), m.group(2), m.group(4))).replace('None',
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def evalfunc(cls, func, *args, **kwargs):
"""Evaluate a function with error propagation. Inputs: ------- ``func``: callable this is the function to be evaluated.... |
def do_random(x):
if isinstance(x, cls):
return x.random()
else:
return x
if 'NMC' not in kwargs:
kwargs['NMC'] = 1000
if 'exceptions_to_skip' not in kwargs:
kwargs['exceptions_to_skip'] = []
if 'exception... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GeneralGuinier(q, G, Rg, s):
"""Generalized Guinier scattering Inputs: ------- ``q``: independent variable ``G``: factor ``Rg``: radius of gyration ``s``: di... |
return G / q ** (3 - s) * np.exp(-(q * Rg) ** 2 / s) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GuinierPorod(q, G, Rg, alpha):
"""Empirical Guinier-Porod scattering Inputs: ------- ``q``: independent variable ``G``: factor of the Guinier-branch ``Rg``: ... |
return GuinierPorodMulti(q, G, Rg, alpha) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def PorodGuinier(q, a, alpha, Rg):
"""Empirical Porod-Guinier scattering Inputs: ------- ``q``: independent variable ``a``: factor of the power-law branch ``alph... |
return PorodGuinierMulti(q, a, alpha, Rg) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def PorodGuinierPorod(q, a, alpha, Rg, beta):
"""Empirical Porod-Guinier-Porod scattering Inputs: ------- ``q``: independent variable ``a``: factor of the first ... |
return PorodGuinierMulti(q, a, alpha, Rg, beta) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GuinierPorodGuinier(q, G, Rg1, alpha, Rg2):
"""Empirical Guinier-Porod-Guinier scattering Inputs: ------- ``q``: independent variable ``G``: factor for the f... |
return GuinierPorodMulti(q, G, Rg1, alpha, Rg2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def DampedPowerlaw(q, a, alpha, sigma):
"""Damped power-law Inputs: ------- ``q``: independent variable ``a``: factor ``alpha``: exponent ``sigma``: hwhm of the ... |
return a * q ** alpha * np.exp(-q ** 2 / (2 * sigma ** 2)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def PowerlawGuinierPorodConst(q, A, alpha, G, Rg, beta, C):
"""Sum of a Power-law, a Guinier-Porod curve and a constant. Inputs: ------- ``q``: independent varia... |
return PowerlawPlusConstant(q, A, alpha, C) + GuinierPorod(q, G, Rg, beta) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GuinierPorodMulti(q, G, *Rgsalphas):
"""Empirical multi-part Guinier-Porod scattering Inputs: ------- ``q``: independent variable ``G``: factor for the first... |
scalefactor = G
funcs = [lambda q: Guinier(q, G, Rgsalphas[0])]
indices = np.ones_like(q, dtype=np.bool)
constraints = []
for i in range(1, len(Rgsalphas)):
if i % 2:
# Rgsalphas[i] is an exponent, Rgsalphas[i-1] is a radius of gyration
qsep = _PGgen_qsep(Rgsalphas[i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def PorodGuinierMulti(q, A, *alphasRgs):
"""Empirical multi-part Porod-Guinier scattering Inputs: ------- ``q``: independent variable ``A``: factor for the first... |
scalefactor = A
funcs = [lambda q: Powerlaw(q, A, alphasRgs[0])]
indices = np.ones_like(q, dtype=np.bool)
constraints = []
for i in range(1, len(alphasRgs)):
if i % 2:
# alphasRgs[i] is a radius of gyration, alphasRgs[i-1] is a power-law exponent
qsep = _PGgen_qsep(a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GeneralGuinierPorod(q, factor, *args, **kwargs):
"""Empirical generalized multi-part Guinier-Porod scattering Inputs: ------- ``q``: independent variable ``f... |
if kwargs.get('startswithguinier', True):
funcs = [lambda q, A = factor:GeneralGuinier(q, A, args[0], args[1])]
i = 2
guiniernext = False
else:
funcs = [lambda q, A = factor: Powerlaw(q, A, args[0])]
i = 1
guiniernext = True
indices = np.ones_like(q, dtype=np... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ExcludedVolumeChain(q, Rg, nu):
"""Scattering intensity of a generalized excluded-volume Gaussian chain Inputs: ------- ``q``: independent variable ``Rg``: r... |
u = (q * Rg) ** 2 * (2 * nu + 1) * (2 * nu + 2) / 6.
return (u ** (0.5 / nu) * gamma(0.5 / nu) * gammainc(0.5 / nu, u) -
gamma(1. / nu) * gammainc(1. / nu, u)) / (nu * u ** (1. / nu)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def BorueErukhimovich(q, C, r0, s, t):
"""Borue-Erukhimovich model of microphase separation in polyelectrolytes Inputs: ------- ``q``: independent variable ``C``... |
x = q * r0
return C * (x ** 2 + s) / ((x ** 2 + s) * (x ** 2 + t) + 1) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def BorueErukhimovich_Powerlaw(q, C, r0, s, t, nu):
"""Borue-Erukhimovich model ending in a power-law. Inputs: ------- ``q``: independent variable ``C``: scaling... |
def get_xsep(alpha, s, t):
A = alpha + 2
B = 2 * s * alpha + t * alpha + 4 * s
C = s * t * alpha + alpha + alpha * s ** 2 + alpha * s * t - 2 + 2 * s ** 2
D = alpha * s ** 2 * t + alpha * s
r = np.roots([A, B, C, D])
#print "get_xsep: ", alpha, s, t, r
return... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def sample(self, data, interval):
'''Sample a patch from the data object
Parameters
----------
data : dict
A data dict as produced by pumpp.Pump.transform
interval : slice
The time interval to sample
Returns
-------
data_slice : ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def indices(self, data):
'''Generate patch start indices
Parameters
----------
data : dict of np.ndarray
As produced by pumpp.transform
Yields
------
start : int >= 0
The start index of a sample patch
'''
duration = self.d... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def scope(self, key):
'''Apply the name scope to a key
Parameters
----------
key : string
Returns
-------
`name/key` if `name` is not `None`;
otherwise, `key`.
'''
if self.name is None:
return key
return '{:s}/{:s}'.fo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def register(self, field, shape, dtype):
'''Register a field as a tensor with specified shape and type.
A `Tensor` of the given shape and type will be registered in this
object's `fields` dict.
Parameters
----------
field : str
The name of the field
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def merge(self, data):
'''Merge an array of output dictionaries into a single dictionary
with properly scoped names.
Parameters
----------
data : list of dict
Output dicts as produced by `pumpp.task.BaseTaskTransformer.transform`
or `pumpp.feature.Feature... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def add(self, operator):
'''Add an operator to the Slicer
Parameters
----------
operator : Scope (TaskTransformer or FeatureExtractor)
The new operator to add
'''
if not isinstance(operator, Scope):
raise ParameterError('Operator {} must be a Task... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def data_duration(self, data):
'''Compute the valid data duration of a dict
Parameters
----------
data : dict
As produced by pumpp.transform
Returns
-------
length : int
The minimum temporal extent of a dynamic observation in data
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.