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 rdf2dot( g, stream, opts={} ):
""" Convert the RDF graph to DOT Write the dot output to the stream """ |
accept_lang = set( opts.get('lang',[]) )
do_literal = opts.get('literal')
nodes = {}
links = []
def node_id(x):
if x not in nodes:
nodes[x] = "node%d" % len(nodes)
return nodes[x]
def qname(x, g):
try:
q = g.compute_qname(x)
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 draw_graph( g, fmt='svg', prg='dot', options={} ):
""" Draw an RDF graph as an image """ |
# Convert RDF to Graphviz
buf = StringIO()
rdf2dot( g, buf, options )
gv_options = options.get('graphviz',[])
if fmt == 'png':
gv_options += [ '-Gdpi=220', '-Gsize=25,10!' ]
metadata = { "width": 5500, "height": 2200, "unconfined" : True }
#import codecs
#with codecs.open(... |
<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_SZ(self, psd, geometry):
""" Compute the scattering matrices for the given PSD and geometries. Returns: The new amplitude (S) and phase (Z) matrices. """ |
if (self._S_table is None) or (self._Z_table is None):
raise AttributeError(
"Initialize or load the scattering table first.")
if (not isinstance(psd, PSD)) or self._previous_psd != psd:
self._S_dict = {}
self._Z_dict = {}
psd_w = psd(sel... |
<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_scatter_table(self, fn, description=""):
"""Save the scattering lookup tables. Save the state of the scattering lookup tables to a file. This can be loa... |
data = {
"description": description,
"time": datetime.now(),
"psd_scatter": (self.num_points, self.D_max, self._psd_D,
self._S_table, self._Z_table, self._angular_table,
self._m_table, self.geometries),
"version": tmatrix_aux.VERSION... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_scatter_table(self, fn):
"""Load the scattering lookup tables. Load the scattering lookup tables saved with save_scatter_table. Args: fn: The name of th... |
data = pickle.load(file(fn))
if ("version" not in data) or (data["version"]!=tmatrix_aux.VERSION):
warnings.warn("Loading data saved with another version.", Warning)
(self.num_points, self.D_max, self._psd_D, self._S_table,
self._Z_table, self._angular_table, self._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 gaussian_pdf(std=10.0, mean=0.0):
"""Gaussian PDF for orientation averaging. Args: std: The standard deviation in degrees of the Gaussian PDF mean: The mean ... |
norm_const = 1.0
def pdf(x):
return norm_const*np.exp(-0.5 * ((x-mean)/std)**2) * \
np.sin(np.pi/180.0 * x)
norm_dev = quad(pdf, 0.0, 180.0)[0]
# ensure that the integral over the distribution equals 1
norm_const /= norm_dev
return pdf |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def uniform_pdf():
"""Uniform PDF for orientation averaging. Returns: pdf(x), a function that returns the value of the spherical Jacobian- normalized uniform PDF... |
norm_const = 1.0
def pdf(x):
return norm_const * np.sin(np.pi/180.0 * x)
norm_dev = quad(pdf, 0.0, 180.0)[0]
# ensure that the integral over the distribution equals 1
norm_const /= norm_dev
return pdf |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def orient_averaged_adaptive(tm):
"""Compute the T-matrix using variable orientation scatterers. This method uses a very slow adaptive routine and should mainly ... |
S = np.zeros((2,2), dtype=complex)
Z = np.zeros((4,4))
def Sfunc(beta, alpha, i, j, real):
(S_ang, Z_ang) = tm.get_SZ_single(alpha=alpha, beta=beta)
s = S_ang[i,j].real if real else S_ang[i,j].imag
return s * tm.or_pdf(beta)
ind = range(2)
for i in ind:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def orient_averaged_fixed(tm):
"""Compute the T-matrix using variable orientation scatterers. This method uses a fast Gaussian quadrature and is suitable for mos... |
S = np.zeros((2,2), dtype=complex)
Z = np.zeros((4,4))
ap = np.linspace(0, 360, tm.n_alpha+1)[:-1]
aw = 1.0/tm.n_alpha
for alpha in ap:
for (beta, w) in zip(tm.beta_p, tm.beta_w):
(S_ang, Z_ang) = tm.get_SZ_single(alpha=alpha, beta=beta)
S += w * S_ang
Z... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_geometry(self, geom):
"""A convenience function to set the geometry variables. Args: geom: A tuple containing (thet0, thet, phi0, phi, alpha, beta). See ... |
(self.thet0, self.thet, self.phi0, self.phi, self.alpha,
self.beta) = geom |
<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_geometry(self):
"""A convenience function to get the geometry variables. Returns: A tuple containing (thet0, thet, phi0, phi, alpha, beta). See the Scatt... |
return (self.thet0, self.thet, self.phi0, self.phi, self.alpha,
self.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 _init_tmatrix(self):
"""Initialize the T-matrix. """ |
if self.radius_type == Scatterer.RADIUS_MAXIMUM:
# Maximum radius is not directly supported in the original
# so we convert it to equal volume radius
radius_type = Scatterer.RADIUS_EQUAL_VOLUME
radius = self.equal_volume_from_maximum()
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _init_orient(self):
"""Retrieve the quadrature points and weights if needed. """ |
if self.orient == orientation.orient_averaged_fixed:
(self.beta_p, self.beta_w) = quadrature.get_points_and_weights(
self.or_pdf, 0, 180, self.n_beta)
self._set_orient_signature() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _set_scatter_signature(self):
"""Mark the amplitude and scattering matrices as up to date. """ |
self._scatter_signature = (self.thet0, self.thet, self.phi0, self.phi,
self.alpha, self.beta, self.orient) |
<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_SZ_single(self, alpha=None, beta=None):
"""Get the S and Z matrices for a single orientation. """ |
if alpha == None:
alpha = self.alpha
if beta == None:
beta = self.beta
tm_outdated = self._tm_signature != (self.radius, self.radius_type,
self.wavelength, self.m, self.axis_ratio, self.shape, self.ddelt,
self.ndgs)
if tm_outdated:
... |
<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_SZ_orient(self):
"""Get the S and Z matrices using the specified orientation averaging. """ |
tm_outdated = self._tm_signature != (self.radius, self.radius_type,
self.wavelength, self.m, self.axis_ratio, self.shape, self.ddelt,
self.ndgs)
scatter_outdated = self._scatter_signature != (self.thet0, self.thet,
self.phi0, self.phi, self.alpha, self.beta, 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 get_SZ(self):
"""Get the S and Z matrices using the current parameters. """ |
if self.psd_integrator is None:
(self._S, self._Z) = self.get_SZ_orient()
else:
scatter_outdated = self._scatter_signature != (self.thet0,
self.thet, self.phi0, self.phi, self.alpha, self.beta,
self.orient)
psd_outdated =... |
<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_points_and_weights(w_func=lambda x : np.ones(x.shape), left=-1.0, right=1.0, num_points=5, n=4096):
"""Quadratude points and weights for a weighting func... |
dx = (float(right)-left)/n
z = np.hstack(np.linspace(left+0.5*dx, right-0.5*dx, n))
w = dx*w_func(z)
(a, b) = discrete_gautschi(z, w, num_points)
alpha = a
beta = np.sqrt(b)
J = np.diag(alpha)
J += np.diag(beta, k=-1)
J += np.diag(beta, k=1)
(points,v) =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sca_xsect(scatterer, h_pol=True):
"""Scattering cross section for the current setup, with polarization. Args: scatterer: a Scatterer instance. h_pol: If True... |
if scatterer.psd_integrator is not None:
return scatterer.psd_integrator.get_angular_integrated(
scatterer.psd, scatterer.get_geometry(), "sca_xsect")
old_geom = scatterer.get_geometry()
def d_xsect(thet, phi):
(scatterer.phi, scatterer.thet) = (phi*rad_to_deg, thet*rad_t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ext_xsect(scatterer, h_pol=True):
"""Extinction cross section for the current setup, with polarization. Args: scatterer: a Scatterer instance. h_pol: If True... |
if scatterer.psd_integrator is not None:
try:
return scatterer.psd_integrator.get_angular_integrated(
scatterer.psd, scatterer.get_geometry(), "ext_xsect")
except AttributeError:
# Fall back to the usual method of computing this from S
pass
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ssa(scatterer, h_pol=True):
"""Single-scattering albedo for the current setup, with polarization. Args: scatterer: a Scatterer instance. h_pol: If True (defa... |
ext_xs = ext_xsect(scatterer, h_pol=h_pol)
return sca_xsect(scatterer, h_pol=h_pol)/ext_xs if ext_xs > 0.0 else 0.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 asym(scatterer, h_pol=True):
"""Asymmetry parameter for the current setup, with polarization. Args: scatterer: a Scatterer instance. h_pol: If True (default)... |
if scatterer.psd_integrator is not None:
return scatterer.psd_integrator.get_angular_integrated(
scatterer.psd, scatterer.get_geometry(), "asym")
old_geom = scatterer.get_geometry()
cos_t0 = np.cos(scatterer.thet0 * deg_to_rad)
sin_t0 = np.sin(scatterer.thet0 * deg_to_rad)
p0... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def radar_xsect(scatterer, h_pol=True):
"""Radar cross section for the current setup. Args: scatterer: a Scatterer instance. h_pol: If True (default), use horizo... |
Z = scatterer.get_Z()
if h_pol:
return 2 * np.pi * \
(Z[0,0] - Z[0,1] - Z[1,0] + Z[1,1])
else:
return 2 * np.pi * \
(Z[0,0] + Z[0,1] + Z[1,0] + Z[1,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 delta_hv(scatterer):
""" Delta_hv for the current setup. Args: scatterer: a Scatterer instance. Returns: Delta_hv [rad]. """ |
Z = scatterer.get_Z()
return np.arctan2(Z[2,3] - Z[3,2], -Z[2,2] - Z[3,3]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mg_refractive(m, mix):
"""Maxwell-Garnett EMA for the refractive index. Args: m: Tuple of the complex refractive indices of the media. mix: Tuple of the volu... |
if len(m) == 2:
cF = float(mix[1]) / (mix[0]+mix[1]) * \
(m[1]**2-m[0]**2) / (m[1]**2+2*m[0]**2)
er = m[0]**2 * (1.0+2.0*cF) / (1.0-cF)
m = np.sqrt(er)
else:
m_last = mg_refractive(m[-2:], mix[-2:])
mix_last = mix[-2] + mix[-1]
m = mg_refractive(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 bruggeman_refractive(m, mix):
"""Bruggeman EMA for the refractive index. For instructions, see mg_refractive in this module, except this routine only works f... |
f1 = mix[0]/sum(mix)
f2 = mix[1]/sum(mix)
e1 = m[0]**2
e2 = m[1]**2
a = -2*(f1+f2)
b = (2*f1*e1 - f1*e2 + 2*f2*e2 - f2*e1)
c = (f1+f2)*e1*e2
e_eff = (-b - np.sqrt(b**2-4*a*c))/(2*a)
return np.sqrt(e_eff) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ice_refractive(file):
""" Interpolator for the refractive indices of ice. Inputs: File to read the refractive index lookup table from. This is supplied as "i... |
D = np.loadtxt(file)
log_wl = np.log10(D[:,0]/1000)
re = D[:,1]
log_im = np.log10(D[:,2])
iobj_re = interpolate.interp1d(log_wl, re)
iobj_log_im = interpolate.interp1d(log_wl, log_im)
def ref(wl, snow_density):
lwl = np.log10(wl)
try:
len(lwl)
except T... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _group_by(data, criteria):
""" Group objects in data using a function or a key """ |
if isinstance(criteria, str):
criteria_str = criteria
def criteria(x):
return x[criteria_str]
res = defaultdict(list)
for element in data:
key = criteria(element)
res[key].append(element)
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _product(k, v):
""" Perform the product between two objects even if they don't support iteration """ |
if not _can_iterate(k):
k = [k]
if not _can_iterate(v):
v = [v]
return list(product(k, v)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def learning_curve(train_scores, test_scores, train_sizes, ax=None):
"""Plot a learning curve Plot a metric vs number of examples for the training and test set P... |
if ax is None:
ax = plt.gca()
ax.grid()
ax.set_title("Learning Curve")
ax.set_xlabel("Training examples")
ax.set_ylabel("Score mean")
train_scores_mean = np.mean(train_scores, axis=1)
train_scores_std = np.std(train_scores, axis=1)
test_scores_mean = np.mean(test_scores, axis=... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def precision_at(y_true, y_score, proportion, ignore_nas=False):
'''
Calculates precision at a given proportion.
Only supports binary classification.
'''
# Sort scores in descending order
scores_sorted = np.sort(y_score)[::-1]
# Based on the proportion, get the index to split the 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 __precision(y_true, y_pred):
'''
Precision metric tolerant to unlabeled data in y_true,
NA values are ignored for the precision calculation
'''
# make copies of the arrays to avoid modifying the original ones
y_true = np.copy(y_true)
y_pred = np.copy(y_pred)
# precision = tp... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def labels_at(y_true, y_score, proportion, normalize=False):
'''
Return the number of labels encountered in the top X proportion
'''
# Get indexes of scores sorted in descending order
indexes = np.argsort(y_score)[::-1]
# Sort true values in the same order
y_true_sorted = y_true[indexe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validation_curve(train_scores, test_scores, param_range, param_name=None, semilogx=False, ax=None):
"""Plot a validation curve Plot a metric vs hyperpameter ... |
if ax is None:
ax = plt.gca()
if semilogx:
ax.set_xscale('log')
train_scores_mean = np.mean(train_scores, axis=1)
train_scores_std = np.std(train_scores, axis=1)
test_scores_mean = np.mean(test_scores, axis=1)
test_scores_std = np.std(test_scores, axis=1)
ax.set_title("V... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def confusion_matrix(y_true, y_pred, target_names=None, normalize=False, cmap=None, ax=None):
""" Plot confustion matrix. Parameters y_true : array-like, shape =... |
if any((val is None for val in (y_true, y_pred))):
raise ValueError("y_true and y_pred are needed to plot confusion "
"matrix")
# calculate how many names you expect
values = set(y_true).union(set(y_pred))
expected_len = len(values)
if target_names and (expected_l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def precision_at_proportions(y_true, y_score, ax=None):
""" Plot precision values at different proportions. Parameters y_true : array-like Correct target values ... |
if any((val is None for val in (y_true, y_score))):
raise ValueError('y_true and y_score are needed to plot precision at '
'proportions')
if ax is None:
ax = plt.gca()
y_score_is_vector = is_column_vector(y_score) or is_row_vector(y_score)
if not y_score_is_ve... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def grid_search(grid_scores, change, subset=None, kind='line', cmap=None, ax=None):
""" Plot results from a sklearn grid search by changing two parameters at mos... |
if change is None:
raise ValueError(('change can\'t be None, you need to select at least'
' one value to make the plot.'))
if ax is None:
ax = plt.gca()
if cmap is None:
cmap = default_heatmap()
if isinstance(change, string_types) or len(change) == 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 confusion_matrix(self):
"""Confusion matrix plot """ |
return plot.confusion_matrix(self.y_true, self.y_pred,
self.target_names, ax=_gen_ax()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def precision_recall(self):
"""Precision-recall plot """ |
return plot.precision_recall(self.y_true, self.y_score, ax=_gen_ax()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def feature_importances(self):
"""Feature importances plot """ |
return plot.feature_importances(self.estimator,
feature_names=self.feature_names,
ax=_gen_ax()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def feature_importances_table(self):
"""Feature importances table """ |
from . import table
return table.feature_importances(self.estimator,
feature_names=self.feature_names) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def precision_at_proportions(self):
"""Precision at proportions plot """ |
return plot.precision_at_proportions(self.y_true, self.y_score,
ax=_gen_ax()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_report(self, template, path=None, style=None):
""" Generate HTML report Parameters template : markdown-formatted string or path to the template file... |
from .report import generate
return generate(self, template, path, style) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def roc(y_true, y_score, ax=None):
""" Plot ROC curve. Parameters y_true : array-like, shape = [n_samples] Correct target values (ground truth). y_score : array-... |
if any((val is None for val in (y_true, y_score))):
raise ValueError("y_true and y_score are needed to plot ROC")
if ax is None:
ax = plt.gca()
# get the number of classes based on the shape of y_score
y_score_is_vector = is_column_vector(y_score) or is_row_vector(y_score)
if y_sc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _roc(y_true, y_score, ax=None):
""" Plot ROC curve for binary classification. Parameters y_true : array-like, shape = [n_samples] Correct target values (grou... |
# check dimensions
fpr, tpr, _ = roc_curve(y_true, y_score)
roc_auc = auc(fpr, tpr)
ax.plot(fpr, tpr, label=('ROC curve (area = {0:0.2f})'.format(roc_auc)))
_set_ax_settings(ax)
return ax |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _roc_multi(y_true, y_score, ax=None):
""" Plot ROC curve for multi classification. Parameters y_true : array-like, shape = [n_samples, n_classes] Correct tar... |
# Compute micro-average ROC curve and ROC area
fpr, tpr, _ = roc_curve(y_true.ravel(), y_score.ravel())
roc_auc = auc(fpr, tpr)
if ax is None:
ax = plt.gca()
ax.plot(fpr, tpr, label=('micro-average ROC curve (area = {0:0.2f})'
.format(roc_auc)))
_set_ax_se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def reassemble_options(payload):
'''
Reassemble partial options to options, returns a list of dhcp_option
DHCP options are basically `|tag|length|value|` structure. When an
option is longer than 255 bytes, it can be splitted into multiple
structures with the same tag. The splitted structures mu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_option_from_value(tag, value):
""" Set DHCP option with human friendly value """ |
dhcp_option.parser()
fake_opt = dhcp_option(tag = tag)
for c in dhcp_option.subclasses:
if c.criteria(fake_opt):
if hasattr(c, '_parse_from_value'):
return c(tag = tag, value = c._parse_from_value(value))
else:
raise ValueError('Invalid DHCP 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 create_dhcp_options(input_dict, ignoreError = False, generateNone = False):
""" Try best to create dhcp_options from human friendly values, ignoring invalid ... |
retdict = {}
for k,v in dict(input_dict).items():
try:
if generateNone and v is None:
retdict[k] = None
else:
try:
retdict[k] = create_option_from_value(k, v)
except _EmptyOptionException:
if... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def with_indices(*args):
'''
Create indices for an event class. Every event class must be decorated with this decorator.
'''
def decorator(cls):
for c in cls.__bases__:
if hasattr(c, '_indicesNames'):
cls._classnameIndex = c._classnameIndex + 1
for i i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| async def lock(self, container = None):
"Wait for lock acquire"
if container is None:
container = RoutineContainer.get_container(self.scheduler)
if self.locked:
pass
elif self.lockroutine:
await LockedEvent.createMatcher(self)
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def trylock(self):
"Try to acquire lock and return True; if cannot acquire the lock at this moment, return False."
if self.locked:
return True
if self.lockroutine:
return False
waiter = self.scheduler.send(LockEvent(self.context, self.key, self))
if waiter... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def beginlock(self, container):
"Start to acquire lock in another routine. Call trylock or lock later to acquire the lock. Call unlock to cancel the lock routine"
if self.locked:
return True
if self.lockroutine:
return False
self.lockroutine = container.subroutine... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def unlock(self):
"Unlock the key"
if self.lockroutine:
self.lockroutine.close()
self.lockroutine = None
if self.locked:
self.locked = False
self.scheduler.ignore(LockEvent.createMatcher(self.context, self.key, 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 create(self):
""" Create the subqueue to change the default behavior of Lock to semaphore. """ |
self.queue = self.scheduler.queue.addSubQueue(self.priority, LockEvent.createMatcher(self.context, self.key),
maxdefault = self.size, defaultQueueClass = CBQueue.AutoClassQueue.initHelper('locker', subqueuelimit = 1)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def destroy(self, container = None):
""" Destroy the created subqueue to change the behavior back to Lock """ |
if container is None:
container = RoutineContainer(self.scheduler)
if self.queue is not None:
await container.syscall_noreturn(syscall_removequeue(self.scheduler.queue, self.queue))
self.queue = 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 default_start():
""" Use `sys.argv` for starting parameters. This is the entry-point of `vlcp-start` """ |
(config, daemon, pidfile, startup, fork) = parsearg()
if config is None:
if os.path.isfile('/etc/vlcp.conf'):
config = '/etc/vlcp.conf'
else:
print('/etc/vlcp.conf is not found; start without configurations.')
elif not config:
config = None
main(config, 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 close(self):
"Stop the output stream, but further download will still perform"
if self.stream:
self.stream.close(self.scheduler)
self.stream = None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| async def shutdown(self):
"Force stop the output stream, if there are more data to download, shutdown the connection"
if self.stream:
if not self.stream.dataeof and not self.stream.dataerror:
self.stream.close(self.scheduler)
await self.connection.shutdown()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def restart_walk(self):
""" Force a re-walk """ |
if not self._restartwalk:
self._restartwalk = True
await self.wait_for_send(FlowUpdaterNotification(self, FlowUpdaterNotification.STARTWALK)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def _dataobject_update_detect(self, _initialkeys, _savedresult):
""" Coroutine that wait for retrieved value update notification """ |
def expr(newvalues, updatedvalues):
if any(v.getkey() in _initialkeys for v in updatedvalues if v is not None):
return True
else:
return self.shouldupdate(newvalues, updatedvalues)
while True:
updatedvalues, _ = await multiwaitif(_save... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def updateobjects(self, updatedvalues):
""" Force a update notification on specified objects, even if they are not actually updated in ObjectDB """ |
if not self._updatedset:
self.scheduler.emergesend(FlowUpdaterNotification(self, FlowUpdaterNotification.DATAUPDATED))
self._updatedset.update(set(updatedvalues).intersection(self._savedresult)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def syscall_direct(*events):
'''
Directly process these events. This should never be used for normal events.
'''
def _syscall(scheduler, processor):
for e in events:
processor(e)
return _syscall |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def syscall_generator(generator):
'''
Directly process events from a generator function. This should never be used for normal events.
'''
def _syscall(scheduler, processor):
for e in generator():
processor(e)
return _syscall |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def syscall_clearqueue(queue):
'''
Clear a queue
'''
def _syscall(scheduler, processor):
qes, qees = queue.clear()
events = scheduler.queue.unblockqueue(queue)
for e in events:
scheduler.eventtree.remove(e)
for e in qes:
processor(e)
for e ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def unregisterall(self, runnable):
'''
Unregister all matches and detach the runnable. Automatically called when runnable returns StopIteration.
'''
if runnable in self.registerIndex:
for m in self.registerIndex[runnable]:
self.matchtree.remove(m, runnable)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def ignore(self, matcher):
'''
Unblock and ignore the matched events, if any.
'''
events = self.eventtree.findAndRemove(matcher)
for e in events:
self.queue.unblock(e)
e.canignore = True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def quit(self, daemononly = False):
'''
Send quit event to quit the main loop
'''
if not self.quitting:
self.quitting = True
self.queue.append(SystemControlEvent(SystemControlEvent.QUIT, daemononly = daemononly), True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def setDaemon(self, runnable, isdaemon, noregister = False):
'''
If a runnable is a daemon, it will not keep the main loop running. The main loop will end when all alived runnables are daemons.
'''
if not noregister and runnable not in self.registerIndex:
self.register((), ru... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| async def updateconfig(self):
"Reload configurations, remove non-exist servers, add new servers, and leave others unchanged"
exists = {}
for s in self.connections:
exists[(s.protocol.vhost, s.rawurl)] = s
self._createServers(self, '', exists = exists)
for _,v in exist... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getconnections(self, vhost = None):
"Return accepted connections, optionally filtered by vhost"
if vhost is None:
return list(self.managed_connections)
else:
return [c for c in self.managed_connections if c.protocol.vhost == vhost] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def watch_context(keys, result, reqid, container, module = 'objectdb'):
""" DEPRECATED - use request_context for most use cases """ |
try:
keys = [k for k,r in zip(keys, result) if r is not None]
yield result
finally:
if keys:
async def clearup():
try:
await send_api(container, module, 'munwatch', {'keys': keys, 'requestid': reqid})
except QuitException:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def updater(f):
"Decorate a function with named arguments into updater for transact"
@functools.wraps(f)
def wrapped_updater(keys, values):
result = f(*values)
return (keys[:len(result)], result)
return wrapped_updater |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def dump(obj, attributes = True, _refset = None):
"Show full value of a data object"
if _refset is None:
_refset = set()
if obj is None:
return None
elif isinstance(obj, DataObject):
if id(obj) in _refset:
attributes = False
else:
_refset.a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def update_ports(self, ports, ovsdb_ports):
""" Called from main module to update port information """ |
new_port_names = dict((p['name'], _to32bitport(p['ofport'])) for p in ovsdb_ports)
new_port_ids = dict((p['id'], _to32bitport(p['ofport'])) for p in ovsdb_ports if p['id'])
if new_port_names == self._portnames and new_port_ids == self._portids:
return
self._portnames.clear()... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def list_proxy(root_package = 'vlcp'):
'''
Walk through all the sub modules, find subclasses of vlcp.server.module._ProxyModule,
list their default values
'''
proxy_dict = OrderedDict()
pkg = __import__(root_package, fromlist=['_'])
for imp, module, _ in walk_packages(pkg.__path__, root_pack... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def list_modules(root_package = 'vlcp'):
'''
Walk through all the sub modules, find subclasses of vlcp.server.module.Module,
list their apis through apidefs
'''
pkg = __import__(root_package, fromlist=['_'])
module_dict = OrderedDict()
_server = Server()
for imp, module, _ in walk_packag... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def unblock(self, event):
'''
Remove a block
'''
if event not in self.blockEvents:
return
self.blockEvents[event].unblock(event)
del self.blockEvents[event] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def unblockall(self):
'''
Remove all blocks from the queue and all sub-queues
'''
for q in self.queues.values():
q.unblockall()
self.blockEvents.clear() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def notifyBlock(self, queue, blocked):
'''
Internal notify for sub-queues been blocked
'''
if blocked:
if self.prioritySet[-1] == queue.priority:
self.prioritySet.pop()
else:
pindex = bisect_left(self.prioritySet, queue.priority)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def setPriority(self, queue, priority):
'''
Set priority of a sub-queue
'''
q = self.queueindex[queue]
self.queues[q[0]].removeSubQueue(q[1])
newPriority = self.queues.setdefault(priority, CBQueue.MultiQueue(self, priority))
q[0] = priority
newPriority.add... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ensure_keys(walk, *keys):
""" Use walk to try to retrieve all keys """ |
all_retrieved = True
for k in keys:
try:
walk(k)
except WalkKeyNotRetrieved:
all_retrieved = False
return all_retrieved |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def list_config(root_package = 'vlcp'):
'''
Walk through all the sub modules, find subclasses of vlcp.config.Configurable,
list their available configurations through _default_ prefix
'''
pkg = __import__(root_package, fromlist=['_'])
return_dict = OrderedDict()
for imp, module, _ in walk_pa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def http(container = None):
"wrap a WSGI-style class method to a HTTPRequest event handler"
def decorator(func):
@functools.wraps(func)
def handler(self, event):
return _handler(self if container is None else container, event, lambda env: func(self, env))
return handler
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 statichttp(container = None):
"wrap a WSGI-style function to a HTTPRequest event handler"
def decorator(func):
@functools.wraps(func)
def handler(event):
return _handler(container, event, func)
if hasattr(func, '__self__'):
handler.__self__ = func.__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 start_response(self, status = 200, headers = [], clearheaders = True, disabletransferencoding = False):
"Start to send response"
if self._sendHeaders:
raise HttpProtocolException('Cannot modify response, headers already sent')
self.status = status
self.disabledeflate = di... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def header(self, key, value, replace = True):
"Send a new header"
if hasattr(key, 'encode'):
key = key.encode('ascii')
if hasattr(value, 'encode'):
value = value.encode(self.encoding)
if replace:
self.sent_headers = [(k,v) for k,v in self.sent_headers ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setcookie(self, key, value, max_age=None, expires=None, path='/', domain=None, secure=None, httponly=False):
""" Add a new cookie """ |
newcookie = Morsel()
newcookie.key = key
newcookie.value = value
newcookie.coded_value = value
if max_age is not None:
newcookie['max-age'] = max_age
if expires is not None:
newcookie['expires'] = expires
if path is not None:
n... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bufferoutput(self):
""" Buffer the whole output until write EOF or flushed. """ |
new_stream = Stream(writebufferlimit=None)
if self._sendHeaders:
# An extra copy
self.container.subroutine(new_stream.copy_to(self.outputstream, self.container, buffering=False))
self.outputstream = Stream(writebufferlimit=None) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| async def rewrite(self, path, method = None, keepresponse = True):
"Rewrite this request to another processor. Must be called before header sent"
if self._sendHeaders:
raise HttpProtocolException('Cannot modify response, headers already sent')
if getattr(self.event, 'rewritedepth', 0... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def redirect(self, path, status = 302):
""" Redirect this request with 3xx status """ |
location = urljoin(urlunsplit((b'https' if self.https else b'http',
self.host,
quote_from_bytes(self.path).encode('ascii'),
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def escape(self, text, quote = True):
""" Escape special characters in HTML """ |
if isinstance(text, bytes):
return escape_b(text, quote)
else:
return escape(text, quote) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def error(self, status=500, allowredirect = True, close = True, showerror = None, headers = []):
""" Show default error response """ |
if showerror is None:
showerror = self.showerrorinfo
if self._sendHeaders:
if showerror:
typ, exc, tb = sys.exc_info()
if exc:
await self.write('<span style="white-space:pre-wrap">\n', buffering = False)
awa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def write(self, data, eof = False, buffering = True):
""" Write output to current output stream """ |
if not self.outputstream:
self.outputstream = Stream()
self._startResponse()
elif (not buffering or eof) and not self._sendHeaders:
self._startResponse()
if not isinstance(data, bytes):
data = data.encode(self.encoding)
await self.outputst... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def writelines(self, lines, eof = False, buffering = True):
""" Write lines to current output stream """ |
for l in lines:
await self.write(l, False, buffering)
if eof:
await self.write(b'', eof, buffering) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def output(self, stream, disabletransferencoding = None):
""" Set output stream and send response immediately """ |
if self._sendHeaders:
raise HttpProtocolException('Cannot modify response, headers already sent')
self.outputstream = stream
try:
content_length = len(stream)
except Exception:
pass
else:
self.header(b'Content-Length', str(content_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def outputdata(self, data):
""" Send output with fixed length data """ |
if not isinstance(data, bytes):
data = str(data).encode(self.encoding)
self.output(MemoryStream(data)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def close(self):
""" Close this request, send all data. You can still run other operations in the handler. """ |
if not self._sendHeaders:
self._startResponse()
if self.inputstream is not None:
self.inputstream.close(self.connection.scheduler)
if self.outputstream is not None:
await self.flush(True)
if hasattr(self, 'session') and self.session:
self.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| async def sessionstart(self):
"Start session. Must start service.utils.session.Session to use this method"
if not hasattr(self, 'session') or not self.session:
self.session, setcookies = await call_api(self.container, 'session', 'start', {'cookies':self.rawcookie})
for nc in setc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def sessiondestroy(self):
""" Destroy current session. The session object is discarded and can no longer be used in other requests. """ |
if hasattr(self, 'session') and self.session:
setcookies = await call_api(self.container, 'session', 'destroy', {'sessionid':self.session.id})
self.session.unlock()
del self.session
for nc in setcookies:
self.sent_cookies = [c for c in self.sent_c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.