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 handle_line(self, obj):
"""Handle a line event. This function displays a line of dialogue. It generates a blocking wait for a period of time calculated from ... |
if obj.persona is None:
return obj
name = getattr(obj.persona, "_name", "")
print(
textwrap.indent(
"{t.normal}{name}".format(name=name, t=self.terminal),
" " * 2
),
end="\n",
file=self.terminal.stream
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_memory(self, obj):
"""Handle a memory event. This function accesses the internal database. It writes a record containing state information and an opti... |
if obj.subject is not None:
with self.con as db:
SchemaBase.note(
db,
obj.subject,
obj.state,
obj.object,
text=obj.text,
html=obj.html,
)
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 handle_property(self, obj):
"""Handle a property event. This function will set an attribute on an object if the event requires it. :param obj: A :py:class:`~... |
if obj.object is not None:
try:
setattr(obj.object, obj.attr, obj.val)
except AttributeError as e:
self.log.error(". ".join(getattr(e, "args", e) or e))
try:
print(
"{t.dim}{obj.object._name}.{obj.attr} = {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 handle_scene(self, obj):
"""Handle a scene event. This function applies a blocking wait at the start of a scene. :param obj: A :py:class:`~turberfield.dialog... |
print(
"{t.dim}{scene}{t.normal}".format(
scene=obj.scene.capitalize(), t=self.terminal
),
end="\n" * 3,
file=self.terminal.stream
)
time.sleep(self.pause)
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_shot(self, obj):
"""Handle a shot event. :param obj: A :py:class:`~turberfield.dialogue.model.Model.Shot` object. :return: The supplied object. """ |
print(
"{t.dim}{shot}{t.normal}".format(
shot=obj.name.capitalize(), t=self.terminal
),
end="\n" * 3,
file=self.terminal.stream
)
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_request_thread(self, mainthread):
"""obtain request from queue instead of directly from server socket""" |
life_time = time.time()
nb_requests = 0
while not mainthread.killed():
if self.max_life_time > 0:
if (time.time() - life_time) >= self.max_life_time:
mainthread.add_worker(1)
return
try:
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 build_distribution():
"""Build distributions of the code.""" |
result = invoke.run('python setup.py sdist bdist_egg bdist_wheel',
warn=True, hide=True)
if result.ok:
print("[{}GOOD{}] Distribution built without errors."
.format(GOOD_COLOR, RESET_COLOR))
else:
print('[{}ERROR{}] Something broke trying to package you... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def other_dependencies(ctx, server, environment):
"""Install things that need to be in place before installing the main package.""" |
if 'extra_packages' in ctx.releaser:
server = server.lower()
extra_pkgs = []
if server in ["local"]:
if 'local' in ctx.releaser.extra_packages:
extra_pkgs.extend(ctx.releaser.extra_packages.local)
elif server in ["testpypi", "pypitest"]:
# the... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_local_install(ctx, version, ext, server="local"):
""" Upload and install works? Uploads a distribution to PyPI, and then tests to see if I can download... |
here = Path(ctx.releaser.here).resolve()
dist_dir = here / 'dist'
all_files = list(dist_dir.glob('*.{}'.format(ext)))
the_file = all_files[0]
for f in all_files[1:]:
if f.stat().st_mtime > the_file.stat().st_mtime:
the_file = f
# this is the latest generated file of... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iscm_md_update_dict(self, keypath, data):
""" Update a metadata dictionary entry """ |
current = self.metadata
for k in string.split(keypath, "."):
if not current.has_key(k):
current[k] = {}
current = current[k]
current.update(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 iscm_md_append_array(self, arraypath, member):
""" Append a member to a metadata array entry """ |
array_path = string.split(arraypath, ".")
array_key = array_path.pop()
current = self.metadata
for k in array_path:
if not current.has_key(k):
current[k] = {}
current = current[k]
if not current.has_key(array_key):
current[arra... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def context_lookup(self, vars):
""" Lookup the variables in the provided dictionary, resolve with entries in the context """ |
while isinstance(vars, IscmExpr):
vars = vars.resolve(self.context)
#
for (k,v) in vars.items():
if isinstance(v, IscmExpr):
vars[k] = v.resolve(self.context)
return vars |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply_to(self, launchable):
""" Apply this ISCM configuration into a launchable resource, such as an EC2 instance or an AutoScalingGroup LaunchConfig. """ |
# Update user data
if launchable.get_property("UserData") is not None:
raise NotImplementedError("It's not yet supported to append SCM to existing userdata")
user_data = {
"Fn::Base64" : {
"Fn::Join" : ["", [
"\n".join([
... |
<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_uri_backend(uri_scheme, create_method, module, c14n_uri_method, escape, cast, is_connected):
""" This method is intended to be used by backends only... |
try:
delta_api = __compare_api_level(module.apilevel, any_apilevel)
mod_paramstyle = module.paramstyle
mod_threadsafety = module.threadsafety
except NameError:
raise NotImplementedError("This module does not support registration "
"of non DBAPI... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def setoutputsize(self, size, column = None):
"As in DBAPI2.0"
if column is None:
self.__dbapi2_cursor.setoutputsize(size)
else:
self.__dbapi2_cursor.setoutputsize(size, column) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __connect(self):
""" Connect to the database. """ |
self.__methods = _get_methods_by_uri(self.sqluri)
uri_connect_method = self.__methods[METHOD_CONNECT]
self.__dbapi2_conn = uri_connect_method(self.sqluri) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reconnect(self, query = None, log_reconnect = False):
""" Reconnect to the database. """ |
uri = list(urisup.uri_help_split(self.sqluri))
if uri[1]:
authority = list(uri[1])
if authority[1]:
authority[1] = None
uri[1] = authority
if log_reconnect:
LOG.warning('reconnecting to %r database (query: %r)', urisup.uri_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def perform(self):
""" Performs bulk operation """ |
for request in self._cfg[Integrator._CFG_KEY_REQUESTS]:
request_type = self._cfg[Integrator._CFG_KEY_REQUESTS][request][Integrator._CFG_KEY_REQUEST_TYPE]
request_cfg_file = self._cfg[Integrator._CFG_KEY_REQUESTS][request][Integrator._CFG_KEY_REQUEST_CFG_FILE]
self._logger.de... |
<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_session():
"""Gets a session. If there's no yet, creates one. :returns: a session """ |
if hasattr(g, 'session'):
return g.session
sess = create_session(bind=current_app.config['DATABASE_ENGINE'])
try:
g.session = sess
except RuntimeError:
pass
return sess |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _plugin_get(self, plugin_name):
""" Find plugins in controller :param plugin_name: Name of the plugin to find :type plugin_name: str | None :return: Plugin o... |
if not plugin_name:
return None, u"Plugin name not set"
for plugin in self.controller.plugins:
if not isinstance(plugin, SettablePlugin):
continue
if plugin.name == plugin_name:
return plugin, ""
return None, u"Settable plugin ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _make_builder(config, current_target):
""" Create and return a Builder for a component. Arguments component - The component the builder should be created for... |
tool_key = devpipeline_core.toolsupport.choose_tool_key(
current_target, _BUILD_TOOL_KEYS
)
return devpipeline_core.toolsupport.tool_builder(
config, tool_key, devpipeline_build.BUILDERS, current_target
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_task(current_target):
""" Build a target. Arguments target - The target to build. """ |
target = current_target.config
try:
builder = _make_builder(target, current_target)
build_path = _get_build_path(target, builder)
if not os.path.exists(build_path):
os.makedirs(build_path)
builder.configure(src_dir=target.get("dp.src_dir"), build_dir=build_path)
... |
<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_registry(self, registry_path_or_url):
'''Return a dict with objects mapped by their id from a CSV endpoint'''
if os.path.isfile(registry_path_or_url):
with open(registry_path_or_url, 'r') as f:
reader = compat.csv_dict_reader(f.readlines())
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 _load_json_file_or_url(self, json_path_or_url):
'''Return the JSON at the local path or URL as a dict
This method raises DataPackageRegistryException if there were any
errors.
'''
try:
if os.path.isfile(json_path_or_url):
with open(json_path_or_ur... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def allow(self, comment, content_object, request):
"""Moderates comments.""" |
POST = urlencode({
"blog": settings.AKISMET_BLOG.encode("utf-8"),
"user_ip": comment.ip_address,
"user_agent": request.META.get('HTTP_USER_AGENT', "").
encode("utf-8"),
"referrer": request.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 get_dict_repr(self):
""" Return a dictionary representation of this phase. This will be used for checksumming, in order to uniquely compare instance images a... |
return dict(
phase_name = self.phase_name,
phase_type = self.phase_type,
actions = self.actions
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def discrete_index(self, indices):
"""get elements by discrete indices :param indices: list discrete indices :return: elements """ |
elements = []
for i in indices:
elements.append(self[i])
return elements |
<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_images(im0, im1, *, rmMean=True, correctScale=True):
"""Finds the rotation, scaling and translation of im1 relative to im0 Parameters im0: First ima... |
# sanitize input
im0 = np.asarray(im0, dtype=np.float32)
im1 = np.asarray(im1, dtype=np.float32)
if rmMean:
# remove mean
im0 = im0 - im0.mean()
im1 = im1 - im1.mean()
# Compute DFT (THe images are resized to the same size)
f0, f1 = dft_optsize_same(im0, im1)
# Get 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 find_rotation_scale(im0, im1, isccs=False):
"""Compares the images and return the best guess for the rotation angle, and scale difference. Parameters im0: 2d... |
# sanitize input
im0 = np.asarray(im0, dtype=np.float32)
im1 = np.asarray(im1, dtype=np.float32)
truesize = None
# if ccs, convert to shifted dft before giving to polar_fft
if isccs:
truesize = im0.shape
im0 = centered_mag_sq_ccs(im0)
im1 = centered_mag_sq_ccs(im1)
... |
<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_shift_cc(im0, im1, ylim=None, xlim=None, subpix=True):
"""Finds the best shift between im0 and im1 using cross correlation Parameters im0: 2d array Firs... |
# sanitize input
im0 = np.asarray(im0, dtype=np.float32)
im1 = np.asarray(im1, dtype=np.float32)
# Remove mean
im0 = im0 - np.nanmean(im0)
im1 = im1 - np.nanmean(im1)
# Save shapes as np array
shape0 = np.asarray(im0.shape)
shape1 = np.asarray(im1.shape)
# Compute the offset an... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def combine_images(imgs, register=True):
"""Combine similar images into one to reduce the noise Parameters imgs: list of 2d array Series of images register: Bool... |
imgs = np.asarray(imgs, dtype="float")
if register:
for i in range(1, imgs.shape[0]):
ret = register_images(imgs[0, :, :], imgs[i, :, :])
imgs[i, :, :] = rotate_scale_shift(imgs[i, :, :], *ret[:3], np.nan)
return np.mean(imgs, 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 dft_optsize(im, shape=None):
"""Resize image for optimal DFT and computes it Parameters im: 2d array The image shape: 2 numbers, optional The shape of the ou... |
im = np.asarray(im)
# save shape
initshape = im.shape
# get optimal size
if shape is None:
ys = cv2.getOptimalDFTSize(initshape[0])
xs = cv2.getOptimalDFTSize(initshape[1])
shape = [ys, xs]
# Add zeros to go to optimal size
im = cv2.copyMakeBorder(im, 0, shape[0] - 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 dft_optsize_same(im0, im1):
"""Resize 2 image same size for optimal DFT and computes it Parameters im0: 2d array First image im1: 2d array Second image Retur... |
im0 = np.asarray(im0)
im1 = np.asarray(im1)
# save shape
shape0 = im0.shape
shape1 = im1.shape
# get optimal size
ys = max(cv2.getOptimalDFTSize(shape0[0]),
cv2.getOptimalDFTSize(shape1[0]))
xs = max(cv2.getOptimalDFTSize(shape0[1]),
cv2.getOptimalDFTSize(shape... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rotate_scale(im, angle, scale, borderValue=0, interp=cv2.INTER_CUBIC):
"""Rotates and scales the image Parameters im: 2d array The image angle: number The an... |
im = np.asarray(im, dtype=np.float32)
rows, cols = im.shape
M = cv2.getRotationMatrix2D(
(cols / 2, rows / 2), -angle * 180 / np.pi, 1 / scale)
im = cv2.warpAffine(im, M, (cols, rows),
borderMode=cv2.BORDER_CONSTANT,
flags=interp,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shift_image(im, shift, borderValue=0):
"""shift the image Parameters im: 2d array The image shift: 2 numbers (y,x) the shift in y and x direction borderValue... |
im = np.asarray(im, dtype=np.float32)
rows, cols = im.shape
M = np.asarray([[1, 0, shift[1]], [0, 1, shift[0]]], dtype=np.float32)
return cv2.warpAffine(im, M, (cols, rows),
borderMode=cv2.BORDER_CONSTANT,
flags=cv2.INTER_CUBIC,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ccs_normalize(compIM, ccsnorm):
""" normalize the ccs representation Parameters compIM: 2d array The CCS image in CCS representation ccsnorm: 2d array The no... |
compIM = np.asarray(compIM)
ccsnorm = np.asarray(ccsnorm)
ys = ccsnorm.shape[0]
xs = ccsnorm.shape[1]
# start with first column
ccsnorm[2::2, 0] = ccsnorm[1:ys - 1:2, 0]
# continue with middle columns
ccsnorm[:, 2::2] = ccsnorm[:, 1:xs - 1:2]
# finish whith last row if even
if x... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gauss_fit(X, Y):
""" Fit the function to a gaussian. Parameters X: 1d array X values Y: 1d array Y values Returns ------- (The return from scipy.optimize.cur... |
X = np.asarray(X)
Y = np.asarray(Y)
# Can not have negative values
Y[Y < 0] = 0
# define gauss function
def gauss(x, a, x0, sigma):
return a * np.exp(-(x - x0)**2 / (2 * sigma**2))
# get first estimation for parameter
mean = (X * Y).sum() / Y.sum()
sigma = np.sqrt((Y * ((X ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gauss_fit_log(X, Y):
""" Fit the log of the input to the log of a gaussian. Parameters X: 1d array X values Y: 1d array Y values Returns ------- mean: number... |
X = np.asarray(X)
Y = np.asarray(Y)
# take log data
Data = np.log(Y)
# Get Di and Xi
D = [(Data * X**i).sum() for i in range(3)]
X = [(X**i).sum() for i in range(5)]
# compute numerator and denominator for mean and variance
num = (D[0] * (X[1] * X[4] - X[2] * X[3]) +
D[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 center_of_mass(X, Y):
"""Get center of mass Parameters X: 1d array X values Y: 1d array Y values Returns ------- res: number The position of the center of ma... |
X = np.asarray(X)
Y = np.asarray(Y)
return (X * Y).sum() / Y.sum() |
<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_peak_pos(im, wrap=False):
"""Get the peak position with subpixel precision Parameters im: 2d array The image containing a peak wrap: boolean, defaults Fa... |
im = np.asarray(im)
# remove invalid values (assuming im>0)
im[np.logical_not(np.isfinite(im))] = 0
# remove mean
im = im - im.mean()
# get maximum value
argmax = im.argmax()
dsize = im.size
# get cut value (30% biggest peak)
# TODO: choose less random value
cut = .3 * im[ar... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def centered_mag_sq_ccs(im):
"""return centered squared magnitude Parameters im: 2d array A CCS DFT image Returns ------- im: 2d array A centered image of the ma... |
im = np.asarray(im)
# multiply image by image* to get squared magnitude
im = cv2.mulSpectrums(im, im, flags=0, conjB=True)
ys = im.shape[0]
xs = im.shape[1]
# get correct size return
ret = np.zeros((ys, xs // 2 + 1))
# first column:
# center
ret[ys // 2, 0] = im[0, 0]
# 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 is_overexposed(ims):
"""Simple test to check if image is overexposed Parameters im: 2d array integer the image Returns ------- overexposed: Bool Is the image... |
if len(np.shape(ims)) == 3:
return [is_overexposed(im) for im in ims]
ims = np.array(ims, int)
diffbincount = np.diff(np.bincount(np.ravel(ims)))
overexposed = diffbincount[-1] > np.std(diffbincount)
return overexposed |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_taps_aff(self):
"""Returns True if taps aff for this location""" |
request = requests.get('https://www.taps-aff.co.uk/api/%s' % self.location)
if request.status_code == 200:
try:
taps = request.json()['taps']['status']
if taps == 'aff':
return True
elif taps == 'oan':
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def equal(actual, expected):
'''
Compare actual and expected using ==
>>> expect = Expector([])
>>> expect(1).to_not(equal, 2)
(True, 'equal: expect 1 == 2')
>>> expect(1).to(equal, 1)
(True, 'equal: expect 1 == 1')
'''
is_passing = (actual == expected)
types_to_diff = (str, 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 change(subject, evaluator, by=_NOT_SET, frm=_NOT_SET, to=_NOT_SET):
'''
Calls function `evaluator` before and after a call function `subject`. Output of `evaluator` should change.
>>> expect = Expector([])
>>> a = [1, 2, 3]
>>> expect(a.clear).to(change, lambda: len(a))
(True, 'expect chang... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def stitch_pdfs(pdf_list):
''' Merges a series of single page pdfs into one multi-page doc '''
pdf_merger = PdfFileMerger()
for pdf in pdf_list:
pdf_merger.append(pdf)
with NamedTemporaryFile(prefix='pyglass', suffix='.pdf', delete=False) as tempfileobj:
dest_path = tempfileobj.name
pdf_merger.write... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def split_pdf(pdf_path):
''' Splits a multi-page pdf into a list of single page pdfs '''
pdf = PdfFileReader(pdf_path)
pdf_list = []
for page_num in range(pdf.numPages):
page = pdf.getPage(page_num)
pdf_writer = PdfFileWriter()
pdf_writer.addPage(page)
with NamedTemporaryFile(prefix='pyglass'... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_head(self):
"""Builds response headers and in process renders templates, if any. This method overrides SimpleHTTPRequestHandlet.send_head() """ |
path = self.translate_path(self.path)
f = None
to_render = False
if os.path.isdir(path):
if not self.path.endswith('/'):
# redirect browser - doing basically what apache does
self.send_response(301)
self.send_header("Location",... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pct_decode(s):
""" Return the percent-decoded version of string s. 'Coucou, je suis convivial' '' '%25' """ |
if s is None:
return None
elif not isinstance(s, unicode):
s = str(s)
else:
s = s.encode('utf8')
return PERCENT_CODE_SUB(lambda mo: chr(int(mo.group(0)[1:], 16)), 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 pct_encode(s, encdct):
""" Return a translated version of s where each character is mapped to a string thanks to the encdct dictionary. Use the encdct parame... |
if s is None:
return None
elif not isinstance(s, unicode):
s = str(s)
else:
s = s.encode('utf8')
return ''.join(map(encdct.__getitem__, 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 split_authority(authority):
""" Split authority into component parts. This function supports IP-literal as defined in RFC 3986. ('user', 'passwd', 'host', 'p... |
if '@' in authority:
userinfo, hostport = authority.split('@', 1)
if userinfo and ':' in userinfo:
user, passwd = userinfo.split(':', 1)
else:
user, passwd = userinfo, None
else:
user, passwd, hostport = None, None, authority
if hostport:
if h... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def basic_urisplit(uri):
""" Basic URI Parser according to RFC 3986 ('scheme', 'authority', '/path', 'query', 'fragment') """ |
p = RFC3986_MATCHER(uri).groups()
return (p[1], p[3], p[4], p[6], p[8]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def uri_tree_normalize(uri_tree):
""" Transform an URI tree so that adjacent all-empty fields are coalesced into a single None at parent level. The return value ... |
scheme, authority, path, query, fragment = uri_tree
if authority and (filter(bool, authority) == ()):
authority = None
if query:
query = filter(lambda (x, y): bool(x) or bool(y), query)
return (scheme or None, authority or None, path or None,
query or None, fragment or 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 uri_tree_precode_check(uri_tree, type_host = HOST_REG_NAME):
""" Call this function to validate a raw URI tree before trying to encode it. """ |
scheme, authority, path, query, fragment = uri_tree # pylint: disable-msg=W0612
if scheme:
if not valid_scheme(scheme):
raise InvalidSchemeError, "Invalid scheme %r" % (scheme,)
if authority:
user, passwd, host, port = authority # pylint: disable-msg=W0612
if port and no... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_configuration(ctx, base_key, needed_keys):
""" Confrim a valid configuration. Args: ctx (invoke.context):
base_key (str):
the base configuration key ... |
# check for valid configuration
if base_key not in ctx.keys():
exit("[{}ERROR{}] missing configuration for '{}'"
.format(ERROR_COLOR, RESET_COLOR, base_key))
# TODO: offer to create configuration file
if ctx.releaser is None:
exit("[{}ERROR{}] empty configuration for '... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_existence(to_check, name, config_key=None, relative_to=None, allow_undefined=False, allow_not_existing=False, base_key='releaser'):
"""Determine whethe... |
if allow_undefined and (to_check is None or to_check.lower() == 'none'):
print("{: <14} -> {}UNDEFINED{}".format(name, WARNING_COLOR,
RESET_COLOR))
return
else:
if config_key is None:
config_key = "{}.{}".format(base_key, name)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _determine_dimensions(num_of_pixels):
""" Given a number of pixels, determines the largest width and height that define a rectangle with such an area """ |
for x in xrange(int(math.sqrt(num_of_pixels)) + 1, 1, -1):
if num_of_pixels % x == 0:
return num_of_pixels // x, x
return 1, num_of_pixels |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_image_to_file(img_path, file_path):
""" Expects images created by from_from_file_to_image """ |
img = Image.open(img_path)
data = numpy.array(img)
data = numpy.reshape(data, len(img.getdata()) * 3)
to_remove = data[len(data) - 1]
data = numpy.delete(data, xrange(len(data) - to_remove, len(data)))
data.tofile(file_path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def textFromHTML(html):
""" Cleans and parses text from the given HTML. """ |
cleaner = lxml.html.clean.Cleaner(scripts=True)
cleaned = cleaner.clean_html(html)
return lxml.html.fromstring(cleaned).text_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 evaluate(self, context):
""" Interpolates the HTML source with the context, then returns that HTML and the text extracted from that html. """ |
html = self._source.format(**context)
parts = {"text/html": html, "text/plain": textFromHTML(html)}
return {}, parts |
<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_files(*bases):
""" List all files in a data directory. """ |
for base in bases:
basedir, _ = base.split(".", 1)
base = os.path.join(os.path.dirname(__file__), *base.split("."))
rem = len(os.path.dirname(base)) + len(basedir) + 2
for root, dirs, files in os.walk(base):
for name in files:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def equirectangular_distance(self, other):
""" Return the approximate equirectangular when the location is close to the center of the cluster. For small distance... |
x = math.radians(other.longitude - self.longitude) \
* math.cos(math.radians(other.latitude + self.latitude) / 2);
y = math.radians(other.latitude - self.latitude);
return math.sqrt(x * x + y * y) * GeoPoint.EARTH_RADIUS_METERS; |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_json(payload):
""" Build a ``GeoPoint`` instance from the specified JSON object. @param payload: JSON representation of a geographic location:: { "accur... |
return payload and \
GeoPoint(payload['longitude'],
payload['latitude'],
accuracy=payload.get('accuracy'),
altitude=payload.get('altitude'),
bearing=payload.get('bearing'),
fix_time=payload.get(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def change_keys(obj, convert):
""" Recursively goes through the dictionary obj and replaces keys with the convert function. """ |
if isinstance(obj, (str, int, float)):
return obj
if isinstance(obj, dict):
new = obj.__class__()
for k, v in obj.items():
new[convert(k)] = change_keys(v, convert)
elif isinstance(obj, (list, set, tuple)):
new = obj.__class__(change_keys(v, convert) for v in obj... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _expand_placeholder_value(value):
""" Return the SQL string representation of the specified placeholder's value. @param value: the value of a placeholder suc... |
if isinstance(value, (list, set)) or (isinstance(value, tuple) and len(value) != 1):
sql_value = ','.join( [ RdbmsConnection._to_sql_value(
element if not isinstance(element, tuple) else element[0],
noquote=isinstance(element, tuple))
... |
<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_placeholders(sql_statement, parameters):
""" Retrieve the list of placeholders and their type defined in an SQL statement. @param sql_statement: a param... |
# Find the list of placeholders, and their type, defined in the SQL
# statement.
placeholders = {}
try:
for match in REGEX_PATTERN_SQL_PLACEHOLDERS.findall(sql_statement):
for (i, placeholder_type) in enumerate(PlaceholderType._values):
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 _prepare_statement(sql_statement, parameters):
""" Prepare the specified SQL statement, replacing the placeholders by the value of the given parameters @para... |
placehoolders = RdbmsConnection._get_placeholders(sql_statement, parameters)
for (variable_name, (variable_type, variable_value)) in placehoolders.iteritems():
# Only expand parameters whose value corresponds to a list.
if isinstance(variable_value, (list, set, tuple)):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _replace_placeholder(sql_statement, variable):
""" Return the string obtained by replacing the specified placeholders by its corresponding value. @param sql_... |
(variable_name, variable_type, variable_value) = variable
sql_value = RdbmsConnection._expand_placeholder_value(variable_value) if variable_type == PlaceholderType.simple_list \
else ','.join([ '(%s)' % RdbmsConnection._expand_placeholder_value(v) for v in variable_value ])
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 _to_sql_value(value, noquote=False):
""" Return the SQL string representation of the specified value. @param value: a value to convert into its SQL string re... |
# Convert to string the values that the database adapter can't adapt
# to a SQL type.
# [http://initd.org/psycopg/docs/usage.html#query-parameters]
if not isinstance(value, (types.NoneType, bool, int, long, float, basestring)):
value = obj.stringify(value)
if noquot... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def standalone_from_launchable(cls, launch):
""" Given a launchable resource, create a definition of a standalone instance, which doesn't depend on or contain re... |
attrs = copy.copy(launch.el_attrs)
# Remove attributes we overwrite / don't need
del attrs["Type"]
if attrs.has_key("DependsOn"):
del attrs["DependsOn"]
if attrs["Properties"].has_key("SpotPrice"):
del attrs["Properties"]["SpotPrice"]
if attrs["Pr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filter_data(self, pattern=''):
"""
Filter available varaibles
""" |
filtered_profiles = {}
with open(self.abspath) as fobj:
for idx, line in enumerate(fobj):
if 'TIME SERIES' in line:
break
if pattern in line and (idx-self._attributes['CATALOG']-1) > 0:
filtered_profiles[idx-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 extract(self, variable_idx):
"""
Extract a specific varaible
""" |
branch = self._define_branch(variable_idx)
label = self.profiles[variable_idx].replace("\n", "")
self.label[variable_idx] = label
self.data[variable_idx] = [[], []]
with open(self.abspath) as fobj:
for line in fobj.readlines()[
variable_idx... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def canonicalize(message):
""" Function to convert an email Message to standard format string :param message: email.Message to be converted to standard string :r... |
if message.is_multipart() \
or message.get('Content-Transfer-Encoding') != 'binary':
return mime_to_bytes(message, 0).replace(
b'\r\n', b'\n').replace(b'\r', b'\n').replace(b'\n', b'\r\n')
else:
message_header = ''
message_body = message.get_payload(decode=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 extract_first_part(message, boundary):
""" Function to extract the first part of a multipart message""" |
first_message = message.split(boundary)[1].lstrip()
if first_message.endswith(b'\r\n'):
first_message = first_message[:-2]
else:
first_message = first_message[:-1]
return first_message |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pem_to_der(cert, return_multiple=True):
""" Converts a given certificate or list to PEM format""" |
# initialize the certificate array
cert_list = []
# If certificate is in DER then un-armour it
if pem.detect(cert):
for _, _, der_bytes in pem.unarmor(cert, multiple=True):
cert_list.append(der_bytes)
else:
cert_list.append(cert)
# return multiple if return_multip... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def verify_certificate_chain(cert_str, trusted_certs, ignore_self_signed=True):
""" Verify a given certificate against a trust store""" |
# Load the certificate
certificate = crypto.load_certificate(crypto.FILETYPE_ASN1, cert_str)
# Create a certificate store and add your trusted certs
try:
store = crypto.X509Store()
if ignore_self_signed:
store.add_cert(certificate)
# Assuming the certificates are... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def csrf(request):
""" Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if it has not been provided by either a view decorator or the mi... |
def _get_val():
token = get_token(request)
if token is None:
# In order to be able to provide debugging info in the
# case of misconfiguration, we use a sentinel value
# instead of returning an empty dict.
return 'NOTPROVIDED'
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 api(root_url, service, version, path):
"""Generate URL for path in a Taskcluster service.""" |
root_url = root_url.rstrip('/')
path = path.lstrip('/')
if root_url == OLD_ROOT_URL:
return 'https://{}.taskcluster.net/{}/{}'.format(service, version, path)
else:
return '{}/api/{}/{}/{}'.format(root_url, service, version, path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def api_reference(root_url, service, version):
"""Generate URL for a Taskcluster api reference.""" |
root_url = root_url.rstrip('/')
if root_url == OLD_ROOT_URL:
return 'https://references.taskcluster.net/{}/{}/api.json'.format(service, version)
else:
return '{}/references/{}/{}/api.json'.format(root_url, service, 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 docs(root_url, path):
"""Generate URL for path in the Taskcluster docs.""" |
root_url = root_url.rstrip('/')
path = path.lstrip('/')
if root_url == OLD_ROOT_URL:
return 'https://docs.taskcluster.net/{}'.format(path)
else:
return '{}/docs/{}'.format(root_url, path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exchange_reference(root_url, service, version):
"""Generate URL for a Taskcluster exchange reference.""" |
root_url = root_url.rstrip('/')
if root_url == OLD_ROOT_URL:
return 'https://references.taskcluster.net/{}/{}/exchanges.json'.format(service, version)
else:
return '{}/references/{}/{}/exchanges.json'.format(root_url, service, 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 schema(root_url, service, name):
"""Generate URL for a schema in a Taskcluster service.""" |
root_url = root_url.rstrip('/')
name = name.lstrip('/')
if root_url == OLD_ROOT_URL:
return 'https://schemas.taskcluster.net/{}/{}'.format(service, name)
else:
return '{}/schemas/{}/{}'.format(root_url, service, name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def regex_validation_sealer(fields, defaults, RegexType=type(re.compile(""))):
""" Example sealer that just does regex-based validation. """ |
required = set(fields) - set(defaults)
if required:
raise TypeError(
"regex_validation_sealer doesn't support required arguments. Fields that need fixing: %s" % required)
klass = None
kwarg_validators = dict(
(key, val if isinstance(val, RegexType) else re.compile(val)) for... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def PI_read(server, tag, start=None, end=None, frequency=None):
""" Read function for PI server. It has to be executed by python 32 bit. """ |
pisdk = Dispatch('PISDK.PISDK')
my_server = pisdk.Servers(server)
# Not sure if/when the login is necessary
#con = Dispatch('PISDKDlg.Connections')
#con.Login(my_server, '', '', 1, 0)
time_start = Dispatch('PITimeServer.PITimeFormat')
time_end = Dispatch('PITimeServer.PITimeFormat')
sa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unisim_csv_formatting(path, fname):
""" Remove some useless stuff from the head of a csv file generated by unisim and returns a pandas dataframe """ |
with open(path+fname, 'r') as fobj:
data = fobj.readlines()
header = data[9].split(",")[:-1]
unit_of_measures = data[10].split(",")[:-1]
data = pd.read_csv(path+fname,
skiprows=10,
index_col=0,
usecols=(range(0, len(he... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_stripchart(self, stripchart='overall', expose_data=True):
""" Extract a specific stripchard and exposes the data in the namespace """ |
csv_fname = self.fname.split(os.sep)[-1].replace(".usc", ".csv")
scp_fname = self.fname.split(os.sep)[-1].replace(".usc", ".SCP")
case_details = {'case': self.fname.__repr__()[1:-1],
'stripchart': stripchart,
'target': self.path.__repr__()[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 extract_profiles(self, pipeline_name, expose_data=True):
""" Extract all the profiles of a specific pipeline and exposes the data in the namespace """ |
compas_pipe = self.__profile_definition(pipeline_name)
get_variable = compas_pipe.GEtUserVariable
if os.path.isdir(self.path+'profiles') is not True:
os.mkdir(self.path + 'profiles')
target_dir = self.path + 'profiles'
if expose_data is True:
self.profile... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __profile_definition(self, pipeline_name):
""" Prepare the profiles extraction from a specific profile """ |
pipe = self.flsh.Operations[pipeline_name]
x_st = pipe.GetUserVariable(PROFILE_LENGTH_ST).Variable()
x_non_st = pipe.GetUserVariable(PROFILE_LENGTH_NON_ST).Variable()
timesteps = pipe.GetUserVariable(PROFILE_TIME).Variable()
self.pipes[pipeline_name] = {'grid': x_st,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_until(self, endtime, timeunit='minutes', save=True):
""" Run a case untile the specifiend endtime """ |
integrator = self.case.solver.Integrator
integrator.rununtil(endtime, timeunit)
if save is True:
self.case.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 save(self, fname=''):
""" Save the current case """ |
if fname is '':
self.case.save()
else:
self.case.SaveAs(self.path+os.sep+fname) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tuple_sealer(fields, defaults):
""" This sealer returns an equivalent of a ``namedtuple``. """ |
baseclass_name = 'FieldsBase_for__{0}'.format('__'.join(fields))
global_namespace, local_namespace = make_init_func(
fields, defaults, baseclass_name,
header_name='__new__',
header_start='def {func_name}(cls',
header_end='):\n',
super_call_start='return tuple.__new__(cls... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filter_trends(self, pattern=''):
"""
Filter available trends
""" |
filtered_trends = {}
with open(self.abspath) as fobj:
for idx, line in enumerate(fobj):
variable_idx = idx-self._attributes['CATALOG']-1
if 'TIME SERIES' in line:
break
if pattern in line and variable_idx > 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 extract(self, *args):
"""
Extract a specific variable
""" |
self.time = np.loadtxt(self.abspath,
skiprows=self._attributes['data_idx']+1,
unpack=True, usecols=(0,))
for variable_idx in args:
data = np.loadtxt(self.abspath,
skiprows=self._attributes['dat... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def view_trends(self, pattern=''):
"""
Return a pandas df with the available trends
""" |
d = OrderedDict()
d['Index'] = None
d['Variable'] = []
d['Position'] = []
d['Unit'] = []
d['Description'] = []
raw_d = self.filter_trends(pattern)
d['Index'] = [k for k in raw_d.keys()]
for st in self.filter_trends(pattern).values():
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _tab_type(self):
"""
Private method to define the tab type
""" |
with open(self.abspath) as fobj:
contents = fobj.readlines()
for line in contents:
if 'COMPONENTS' in line:
return 'keyword'
else:
return 'fixed' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _partial_extraction_fixed(self, idx, extra_idx=0):
"""
Private method for a single extraction on a fixed-type tab file
""" |
myarray = np.array([])
with open(self.abspath) as fobj:
contents = fobj.readlines()[idx+extra_idx:]
for line in contents:
try:
vals = re.findall(r' *[\w\-\+\.]*', line)
temp = np.array([float(val) for val in vals
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _export_all_fixed(self):
"""
Exports all the properties for a fixed-type tab file
""" |
array_ts = []
array_ps = []
for array_t, array_p in it.product(self.metadata["t_array"][0],
self.metadata["p_array"][0]):
array_ts.append(array_t)
array_ps.append(array_p/1e5)
array_ts_tot = [array_ts for t in 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 _metadata_keyword(self):
"""
Define the most important tab parameters for a keyword-type tab file
""" |
with open(self.abspath) as fobj:
for line in fobj:
if 'PVTTABLE LABEL' in line:
label = re.findall(r"\=[\w\ \"]*\,", line)[0][1:-1]
self.metadata["fluids"].append(label)
if 'PRESSURE = (' in line:
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 _export_all_keyword(self):
"""
Export method for keyword tab files
""" |
data = {}
for fluid_idx, fluid in enumerate(self.metadata["fluids"]):
data[fluid] = {}
with open(self.abspath) as fobj:
text = fobj.read()
try:
text = text.split("!Phase properties")[1+fluid_idx]
except ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def export_all(self):
"""
It makes all the properties avaiable as data attribute
""" |
if self.tab_type == 'fixed':
self._export_all_fixed()
if self.tab_type == 'keyword':
self._export_all_keyword() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.