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 _parse_keys(row, line_num):
""" Perform some sanity checks on they keys Each key in the row should not be named None cause (that's an overrun). A key named `... |
link = 'tools.ietf.org/html/rfc4180#section-2'
none_keys = [key for key in row.keys() if key is None]
if none_keys:
fail('You have more fields defined on row number {} '
'than field headers in your CSV data. Please fix '
'your request body.'.form... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_field_headers(reader):
""" Perform some validations on the CSV headers A `type` field header must be present & all field headers must be strings. :... |
link = 'tools.ietf.org/html/rfc4180#section-2'
for field in reader.fieldnames:
if not isinstance(field, str):
fail('All headers in your CSV payload must be '
'strings.', link)
if 'type' not in reader.fieldnames:
fail('A type header... |
<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_xml_request(self, text):
""" make xml content from given text """ |
# create base stucture
soap_root = ET.Element('soap:Envelope', {
'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
'xmlns:xsd': 'http://www.w3.org/2001/XMLSchema',
'xmlns:soap': 'http://schemas.xmlsoap.org/soap/envelope/', })
body = ET.SubElement(soap... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __parse_xml_response(self, response):
""" parse response and get text result """ |
# get xml from response
xml_response = response[response.find('<?xml'):].replace(' encoding=""', '')
xml_content = xml.dom.minidom.parseString(xml_response)
return xml_content.getElementsByTagName('ProcessTextResult')[0].firstChild.nodeValue |
<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_text(self, text):
""" send request with given text and get result """ |
# escape base char
text = text.replace('&', '&').replace('<', '<').replace('>', '>')
# make xml request body
soap_body = self.__create_xml_request(text)
# make total request
length = len(soap_body.encode('UTF-8')) if PY3 else len(soap_body)
soap_request... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def try_process_text(self, text):
""" safe process text if error - return not modifyed text """ |
if not text:
return text
try:
return self.process_text(text)
except (socket.gaierror, socket.timeout, xml.parsers.expat.ExpatError):
return text |
<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_align(self, orientation, value):
'''We define a setter because it's better to diagnose this kind of
programmatic error here than have to work out why alignment is odd when
we sliently fail!
'''
orientation_letter = orientation[0]
possible_alignments = getattr(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _populate_lines(self, block, terminal, styles, default_esc_seq):
'''Takes some lines to draw to the terminal, which may contain
formatting placeholder objects, and inserts the appropriate concrete
escapes sequences by using data from the terminal object and styles
dictionary.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _ascii_find_urls(bytes, mimetype, extra_tokens=True):
""" This function finds URLs inside of ASCII bytes. """ |
tokens = _tokenize(bytes, mimetype, extra_tokens=extra_tokens)
return tokens |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pdf_find_urls(bytes, mimetype):
""" This function finds URLs inside of PDF bytes. """ |
# Start with only the ASCII bytes. Limit it to 12+ character strings.
try:
ascii_bytes = b' '.join(re.compile(b'[\x00\x09\x0A\x0D\x20-\x7E]{12,}').findall(bytes))
ascii_bytes = ascii_bytes.replace(b'\x00', b'')
except:
return []
urls = []
# Find the embedded text sandwich... |
<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_valid(url, fix=True):
""" Returns True if this is what we consider to be a valid URL. A valid URL has: * http OR https scheme * a valid TLD If there is no... |
try:
# Convert the url to a string if we were given it as bytes.
if isinstance(url, bytes):
url = url.decode('ascii', errors='replace')
# Hacky way to deal with URLs that have a username:password notation.
user_pass_url = ''
# Check for no scheme and assume ht... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_to_one(self, value):
""" Check if the to_one should exist & casts properly """ |
if value.rid and self.typeness is int:
validators.validate_int(value)
if value.rid and not self.skip_exists:
if not value.load():
raise ValidationError(self.messages['exists'])
return value |
<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_body(self):
""" Return a HTTPStatus compliant body attribute Be sure to purge any unallowed properties from the object. TIP: At the risk of being a bit s... |
body = copy.deepcopy(self.errors)
for error in body:
for key in error.keys():
if key not in self.ERROR_OBJECT_FIELDS:
del error[key]
return json.dumps({'errors': body}) |
<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_headers(self):
""" Return a HTTPStatus compliant headers attribute FIX: duplicate headers will collide terribly! """ |
headers = {'Content-Type': goldman.JSON_MIMETYPE}
for error in self.errors:
if 'headers' in error:
headers.update(error['headers'])
return 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 get_status(self):
""" Return a HTTPStatus compliant status attribute Per the JSON API spec errors could have different status codes & a generic one should be... |
codes = [error['status'] for error in self.errors]
same = all(code == codes[0] for code in codes)
if not same and codes[0].startswith('4'):
return falcon.HTTP_400
elif not same and codes[0].startswith('5'):
return falcon.HTTP_500
else:
retur... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def normalize(self, parts):
""" Invoke the RFC 2388 spec compliant normalizer :param parts: the already vetted & parsed FieldStorage objects :return: normalized ... |
part = parts.list[0]
return {
'content': part.file.read(),
'content-type': part.type,
'file-ext': extensions.get(part.type),
'file-name': part.filename,
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(self, mimetypes):
""" Invoke the RFC 2388 spec compliant parser """ |
self._parse_top_level_content_type()
link = 'tools.ietf.org/html/rfc2388'
parts = cgi.FieldStorage(
fp=self.req.stream,
environ=self.req.env,
)
if not parts:
self.fail('A payload in the body of your request is required '
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def covered_interval(bin):
""" Given a bin number `bin`, return the interval covered by this bin. :arg int bin: Bin number. :return: Tuple of `start, stop` being... |
if bin < 0 or bin > MAX_BIN:
raise OutOfRangeError(
'Invalid bin number %d (maximum bin number is %d)'
% (bin, MAX_BIN))
shift = SHIFT_FIRST
for offset in BIN_OFFSETS:
if offset <= bin:
return bin - offset << shift, bin + 1 - offset << shift
shif... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stitchModules(module, fallbackModule):
""" complete missing attributes with those in fallbackModule imagine you have 2 modules: a and b a is some kind of an ... |
for name, attr in fallbackModule.__dict__.items():
if name not in module.__dict__:
module.__dict__[name] = attr |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getTarget(self, iid):
'''
Returns a dictionary containing information about a certain target
'''
sql = 'select name, path from {} where _id=?'.format(self.TABLE_ITEMS)
data = self.db.execute(sql, (iid,)).fetchone()
if data:
return {'name': data[0], '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 insertTarget(self, name, path):
'''
Inserts a new target into the vault database
Returns the id of the created target
'''
sql = 'insert into {}(name, path) values (?,?);'.format(self.TABLE_ITEMS)
try:
_id = self.db.execute(sql, (name, path)).lastr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def removeTarget(self, iid):
'''
Removes target information from vault database
'''
sql = 'delete from {} where _id=?'.format(self.TABLE_ITEMS)
cursor = self.db.execute(sql, (iid,))
if cursor.rowcount > 0:
self.db.commit()
return 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 listTargets(self):
'''
Returns a list of all the items secured in the vault
'''
sql = 'select * from {}'.format(self.TABLE_ITEMS)
cursor = self.db.execute(sql)
return [(iid, name, path) for iid, name, path in cursor] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pre_create(sender, model):
""" Callback before creating any new model Identify the creator of the new model & set the created timestamp to now. """ |
model.created = dt.utcnow()
model.creator = goldman.sess.login |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def x509_from_ecdsap256_key_pair(pub_key, priv_key, common_name):
""" Creates a self-signed x509 certificate for a common name and ECDSAP256 key pair. :pub_key: ... |
cert_len = _lib.xtt_x509_certificate_length()
cert = _ffi.new('unsigned char[]', cert_len)
rc = _lib.xtt_x509_from_ecdsap256_keypair(pub_key.native,
priv_key.native,
common_name.native,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def asn1_from_ecdsap256_private_key(priv_key, pub_key):
""" Returns the ASN.1 encoding of a ECDSAP256 private ket. :priv_key: an ECDSAP256PrivateKey instance :re... |
encoded_len = _lib.xtt_asn1_private_key_length()
encoded = _ffi.new('unsigned char[]', encoded_len)
rc = _lib.xtt_asn1_from_ecdsap256_private_key(priv_key.native, pub_key.native, encoded, len(encoded))
if rc == RC.SUCCESS:
return _ffi.buffer(encoded)[:]
else:
raise error_from_code(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 smart_fit(image, fit_to_width, fit_to_height):
""" Proportionally fit the image into the specified width and height. Return the correct width and height. """ |
im_width, im_height = image.size
out_width, out_height = fit_to_width, fit_to_height
if im_width == 0 or im_height == 0:
return (fit_to_width, fit_to_height)
w_scale = float(fit_to_width) / float(im_width)
h_scale = float(fit_to_height) / float(im_height)
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 process(image, size, *args, **kwargs):
""" Automatically crop the image based on image gravity and face detection """ |
from autodetect import smart_crop
box_width, box_height = AutoCrop.parse_size(image, size)
scaled_size, rect = smart_crop(box_width, box_height, image.filename)
return image.resize(scaled_size, Image.ANTIALIAS).crop(tuple(rect)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def version_by_import(self, module_name):
# type: (str) ->Dict[str,str] """ This is slow & if running against random code, dangerous Sometimes apps call exit() i... |
if not module_name:
return {}
try:
module = __import__(module_name)
except ModuleNotFoundError:
# hypothetical module would have to be on python path or execution folder, I think.
return {}
except FileNotFoundError:
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 initrepo(repopath, bare, shared):
""" Initialize an activegit repo. Default makes base shared repo that should be cloned for users """ |
ag = activegit.ActiveGit(repopath, bare=bare, shared=shared) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clonerepo(barerepo, userrepo):
""" Clone a bare base repo to a user """ |
git.clone(barerepo, userrepo)
ag = activegit.ActiveGit(userrepo) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def example(script, explain, contents, requirements, output, outputfmt, details):
"""Prints the example help for the script.""" |
blank()
cprint(script.upper(), "yellow")
cprint(''.join(["=" for i in range(70)]) + '\n', "yellow")
cprint("DETAILS", "blue")
std(explain + '\n')
cprint(requirements, "red")
cprint(output, "green")
blank()
if details != "":
std(details)
blank()
cprint("OUTPUT... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def EntryPoints(registry, **kwargs):
"""Returns an object to use as entry point when calling ``registry.solve_resource``. When calling ``registry.solve_resource`... |
# We convert functions to staticmethod as they will be held by a class and
# we don't want them to expect a ``self`` or ``cls`` argument.
attrs = {k: (staticmethod(v) if isfunction(v) else v) for k, v in kwargs.items()}
klass = type('EntryPoints', (BaseEntryPoints, ), attrs)
registry.register(kla... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register(self, source, attributes=None, allow_class=False, allow_subclasses=True, propagate_attributes=True, inherit_attributes=True):
"""Register a source c... |
if source in self.sources:
raise AlreadyRegistered(self, source)
# Inherit attributes from parent classes
parent_sources = set()
if inherit_attributes:
bases = source.__bases__ if isinstance(source, type) else source.__class__.__bases__
for klass in... |
<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_resource_solvers(self, resource):
"""Returns the resource solvers that can solve the given resource. Arguments --------- resource : dataql.resources.Reso... |
solvers_classes = [s for s in self.resource_solver_classes if s.can_solve(resource)]
if solvers_classes:
solvers = []
for solver_class in solvers_classes:
# Put the solver instance in the cache if not cached yet.
if solver_class not in self._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 get_filter_solvers(self, filter_):
"""Returns the filter solvers that can solve the given filter. Arguments --------- filter : dataql.resources.BaseFilter An... |
solvers_classes = [s for s in self.filter_solver_classes if s.can_solve(filter_)]
if solvers_classes:
solvers = []
for solver_class in solvers_classes:
# Put the solver instance in the cache if not cached yet.
if solver_class not in self._filt... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def solve_resource(self, value, resource):
"""Solve the given resource for the given value. The solving is done by the first resource solver class that returns `... |
for solver in self.get_resource_solvers(resource):
try:
return solver.solve(value, resource)
except CannotSolve:
continue
raise SolveFailure(self, resource, value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def solve_filter(self, value, filter_):
"""Solve the given filter for the given value. The solving is done by the first filter solver class that returns ``True``... |
for solver in self.get_filter_solvers(filter_):
try:
return solver.solve(value, filter_)
except CannotSolve:
continue
raise SolveFailure(self, filter_, value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_or_update(data, item, value):
""" Add or update value in configuration file format used by proftpd. Args: data (str):
Configuration file as string. item... |
data = data.splitlines()
# to list of bytearrays (this is useful, because their reference passed to
# other functions can be changed, and it will change objects in arrays
# unlike strings)
data = map(lambda x: bytearray(x), data)
# search for the item in raw (ucommented) values
conf = fil... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def comment(data, what):
""" Comments line containing `what` in string `data`. Args: data (str):
Configuration file in string. what (str):
Line which will be c... |
data = data.splitlines()
data = map(
lambda x: "#" + x if x.strip().split() == what.split() else x,
data
)
return "\n".join(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 _write_conf_file():
""" Write configuration file as it is defined in settings. """ |
with open(CONF_FILE, "w") as f:
f.write(DEFAULT_PROFTPD_CONF)
logger.debug("'%s' created.", CONF_FILE) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def integerize(self):
"""Convert co-ordinate values to integers.""" |
self.x = int(round(self.x))
self.y = int(round(self.y)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def floatize(self):
"""Convert co-ordinate values to floats.""" |
self.x = float(self.x)
self.y = float(self.y) |
<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(self, rad):
""" Rotate counter-clockwise by rad radians. Positive y goes *up,* as in traditional mathematics. Interestingly, you can use this in y-dow... |
s, c = [f(rad) for f in (math.sin, math.cos)]
x, y = (c * self.x - s * self.y, s * self.x + c * self.y)
return Point(x, y) |
<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_about(self, p, theta):
""" Rotate counter-clockwise around a point, by theta degrees. Positive y goes *up,* as in traditional mathematics. The new pos... |
result = self.clone()
result.translate(-p.x, -p.y)
result.rotate(theta)
result.translate(p.x, p.y)
return result |
<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_points(self, pt1, pt2):
"""Reset the rectangle coordinates.""" |
(x1, y1) = pt1.as_tuple()
(x2, y2) = pt2.as_tuple()
self.left = min(x1, x2)
self.top = min(y1, y2)
self.right = max(x1, x2)
self.bottom = max(y1, y2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def overlaps(self, other):
""" Return true if a rectangle overlaps this rectangle. """ |
return (
self.right > other.left and
self.left < other.right and
self.top < other.bottom and
self.bottom > other.top
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expanded_by(self, n):
"""Return a rectangle with extended borders. Create a new rectangle that is wider and taller than the immediate one. All sides are exte... |
return Rect(self.left - n, self.top - n, self.right + n, self.bottom + 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 save(self, *args, **kwargs):
""" Before saving, get publication's PubMed metadata if publication is not already in database or if 'redo_query' is True. """ |
if self.no_query:
if not self.pk or self.pmid > 0:
try:
pmid_min = Publication.objects.all().aggregate(
models.Min('pmid'))['pmid__min'] - 1
except:
self.pmid = 0
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 perform_bulk_pubmed_query(self):
""" If 'bulk_pubmed_query' contains any content, perform a bulk PubMed query, add the publications to the publication set, a... |
if self.bulk_pubmed_query:
failed_queries = []
pmid_list = re.findall(r'(\d+)(?:[\s,]+|$)', self.bulk_pubmed_query)
for pmid in pmid_list:
try:
p, created = Publication.objects.get_or_create(pmid=pmid)
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 add_backend(self, backend):
"Add a RapidSMS backend to this tenant"
if backend in self.get_backends():
return
backend_link, created = BackendLink.all_tenants.get_or_create(backend=backend)
self.backendlink_set.add(backend_link) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_resources_to_registry():
""" Add resources to the deform registry """ |
from deform.widget import default_resource_registry
default_resource_registry.set_js_resources("jqueryui", None, None)
default_resource_registry.set_js_resources("datetimepicker", None, None)
default_resource_registry.set_js_resources("custom_dates", None, None)
default_resource_registry.set_js_re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def childgroup(self, field):
""" Return children grouped regarding the grid description """ |
cols = getattr(self, "cols", self.default_cols)
width = self.num_cols / cols
for child in field.children:
child.width = width
res = list(grouper(field.children, cols, fillvalue=None))
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 _childgroup(self, children, grid):
""" Stores the children in a list following the grid's structure :param children: list of fields :param grid: a list of li... |
result = []
index = 0
hidden_fields = []
for row in grid:
child_row = []
width_sum = 0
for width, filled in row:
width_sum += width
if width_sum > self.num_cols:
warnings.warn(u"It seems your grid c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _childgroup_by_name(self, children, grid):
""" Group the children ordering them by name """ |
children = self._dict_children(children)
result = []
for row in grid:
child_row = []
row_is_void = True
width_sum = 0
for name, width in row:
width_sum += width
if width_sum > self.num_cols:
war... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def childgroup(self, field):
""" Return a list of fields stored by row regarding the configured grid :param field: The original field this widget is attached to ... |
grid = getattr(self, "grid", None)
named_grid = getattr(self, "named_grid", None)
if grid is not None:
childgroup = self._childgroup(field.children, grid)
elif named_grid is not None:
childgroup = self._childgroup_by_name(field.children, named_grid)
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 summary(self):
'''Compute the execution summary'''
out = {}
for bench in self.runner.runned:
key = self.key(bench)
runs = {}
for method, results in bench.results.items():
mean = results.total / bench.times
name = bench.label... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def end(self):
'''
Dump the report into the output file.
If the file directory does not exists, it will be created.
The open file is then given as parameter to :meth:`~minibench.report.FileReporter.output`.
'''
dirname = os.path.dirname(self.filename)
if dirname ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def line(self, text=''):
'''A simple helper to write line with `\n`'''
self.out.write(text)
self.out.write('\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 with_sizes(self, *headers):
'''Compute the report summary and add the computed column sizes'''
if len(headers) != 5:
raise ValueError('You need to provide this headers: class, method, times, total, average')
summary = self.summary()
for row in summary.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 __telnet_event_listener(self, ip, callback):
"""creates a telnet connection to the lightpad""" |
tn = telnetlib.Telnet(ip, 2708)
self._last_event = ""
self._telnet_running = True
while self._telnet_running:
try:
raw_string = tn.read_until(b'.\n', 5)
if len(raw_string) >= 2 and raw_string[-2:] == b'.\n':
# lightpad 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 find_assign(data, varname):
"""Finds a substring that looks like an assignment. :param data: Source to search in. :param varname: Name of the variable for wh... |
ASSIGN_RE = re.compile(BASE_ASSIGN_PATTERN.format(varname))
if len(ASSIGN_RE.findall(data)) > 1:
raise PluginError('Found multiple {}-strings.'.format(varname))
if len(ASSIGN_RE.findall(data)) < 1:
raise PluginError('No version assignment ("{}") found.'
.format(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 get_instance_id(self, instance):
" Returns instance pk even if multiple instances were passed to RichTextField. "
if type(instance) in [list, tuple]:
core_signals.request_finished.connect(receiver=RichTextField.reset_instance_counter_listener)
if RichTextField.__inst_counter ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clean(self, value):
""" When cleaning field, store original value to SourceText model and return rendered field. @raise ValidationError when something went w... |
super_value = super(RichTextField, self).clean(value)
if super_value in fields.EMPTY_VALUES:
if self.instance:
obj_id = self.get_instance_id(self.instance)
if not obj_id:
SourceText.objects.filter(content_type=self.ct, object_id=obj_id, f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def value_from_datadict(self, data, files, name):
'''Generate a single value from multi-part form data. Constructs a W3C
date based on values that are set, leaving out day and month if they are
not present.
:param data: dictionary of data submitted by the form
:param files: - u... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def render(self, name, value, attrs=None):
'''Render the widget as HTML inputs for display on a form.
:param name: form field base name
:param value: date value
:param attrs: - unused
:returns: HTML text with three inputs for year/month/day
'''
# expects a value... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def describe(self):
'''Provide a dictionary with information describing itself.'''
description = {
'description': self._description,
'type': self.name,
}
description.update(self.extra_params)
return description |
<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_raw_query(self, routine, parameters):
"""Return a query that uses raw string-replacement for parameters. The parameters will still be escaped before ... |
parameter_names = []
replacements = {}
for i, value in enumerate(parameters):
name = 'arg' + str(i)
parameter_names.append(name)
replacements[name] = value
parameter_phrase = ', '.join([('%(' + p + ')s') for p in parameter_names])
query =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call(self, routine, *args):
"""This is a newer, less-verbose interface that calls the old philistine one. This should be used. """ |
(query, replacements) = self.__build_query(routine, args)
return self.__execute_text(query, **replacements) |
<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_resultsets(self, routine, *args):
"""Return a list of lists of dictionaries, for when a query returns more than one resultset. """ |
(query, replacements) = self.__build_raw_query(routine, args)
# Grab a raw connection from the connection-pool.
connection = mm.db.ENGINE.raw_connection()
sets = []
try:
cursor = connection.cursor()
cursor.execute(query, replacements)
wh... |
<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(self, name, namespace=None):
""" Find plugin object Parameters name : string A name of the object entry or full namespace namespace : string, optional A... |
if "." in name:
namespace, name = name.rsplit(".", 1)
caret = self.raw
if namespace:
for term in namespace.split('.'):
if term not in caret:
caret[term] = Bunch()
caret = caret[term]
return caret[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 sign(self, request, authheaders, secret):
"""Returns the signature appropriate for the request. The request is not changed by this function. Keyword argument... |
mac = hmac.HMAC(secret.encode('utf-8'), digestmod=self.digest)
mac.update(self.signable(request, authheaders).encode('utf-8'))
digest = mac.digest()
return base64.b64encode(digest).decode('utf-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 parse_auth_headers(self, authorization):
"""Parses the authorization headers from the authorization header taken from a request. Returns a dict that is accep... |
m = re.match(r'^(?i)Acquia\s+(.*?):(.+)$', authorization)
if m is not None:
return {"id": m.group(1), "signature": m.group(2)}
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 check(self, request, secret):
"""Verifies whether or not the request bears an authorization appropriate and valid for this version of the signature. This ver... |
if request.get_header("Authorization") == "":
return False
ah = self.parse_auth_headers(request.get_header("Authorization"))
if "id" not in ah:
return False
if "signature" not in ah:
return False
return ah["signature"] == self.sign(request, ah... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sign_direct(self, request, authheaders, secret):
"""Signs a request directly with an appropriate signature. The request's Authorization header will change. K... |
sig = self.sign(request, authheaders, secret)
return request.with_header("Authorization", "Acquia {0}:{1}".format(authheaders["id"], sig)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def main(directories):
'''Perform all checks on the API's contained in `directory`.'''
msg = 'Checking module "{}" from directory "{}" for coding errors.'
api_checker = ApiChecker()
resource_checker = ResourceChecker()
errors = []
modules = []
for loader, mname, _ in pkgutil.walk_packages(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 checks(self):
'''Return the list of all check methods.'''
condition = lambda a: a.startswith('check_')
return (getattr(self, a) for a in dir(self) if condition(a)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def check_has_docstring(self, api):
'''An API class must have a docstring.'''
if not api.__doc__:
msg = 'The Api class "{}" lacks a docstring.'
return [msg.format(api.__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 check_has_version(self, api):
'''An API class must have a `version` attribute.'''
if not hasattr(api, 'version'):
msg = 'The Api class "{}" lacks a `version` attribute.'
return [msg.format(api.__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 check_has_path(self, api):
'''An API class must have a `path` attribute.'''
if not hasattr(api, 'path'):
msg = 'The Api class "{}" lacks a `path` attribute.'
return [msg.format(api.__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 check_docstring(self, method):
'''All methods should have a docstring.'''
mn = method.__name__
if method.__doc__ is None:
return ['Missing docstring for method "{}"'.format(mn)] |
<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_return_types(self, method):
'''Return types must be correct, their codes must match actual use.'''
mn = method.__name__
retanno = method.__annotations__.get('return', None)
# Take a look at the syntax
if not retanno:
return ['Missing return types for method ... |
<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_params_types(self, method):
'''Types in argument annotations must be instances, not classes.'''
mn = method.__name__
annos = dict(method.__annotations__)
errors = []
# Take a look at the syntax
msg_tuple = 'Parameter {} in method {} is not annotated with a 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 check_path_consistency(self, resource):
'''Path arguments must be consistent for all methods.'''
msg = ('Method "{}" path variables {}) do not conform with the '
'resource subpath declaration ({}).')
errors = []
# If subpath is not set, it will be detected by another c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def check_no_multiple_handlers(self, resource):
'''The same verb cannot be repeated on several endpoints.'''
seen = []
errors = []
msg = 'HTTP verb "{}" associated to more than one endpoint in "{}".'
for method in resource.callbacks:
for op in getattr(method, 'swagger... |
<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(req, model):
""" Return an array of fields to include. """ |
rels = model.relationships
params = req.get_param_as_list('include') or []
params = [param.lower() for param in params]
for param in params:
_validate_no_nesting(param)
_validate_rels(param, rels)
return params |
<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_endpoint(api_key, query, offset, type):
"""Return endpoint URL for the relevant search type. The base API endpoint only varies by type of search requeste... |
query_type = get_query_type(query)
if query_type not in ('domain', 'email'):
raise ex.InvalidQueryStringException('Invalid query string')
if query_type == 'domain':
return DOMAIN_URL.format(query, api_key, offset, type)
else:
return EMAIL_URL.format(query, api_key) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def incrementName(nameList, name):
""" return a name that is unique in a given nameList through attaching a number to it now we will add 3xfoo 2xbar and one klau... |
if name not in nameList:
return name
newName = name + str(1)
for n in range(1, len(nameList) + 2):
found = False
for b in nameList:
newName = name + str(n)
if b == newName:
found = True
if not found:
break
return newNam... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def provider_factory(factory=_sentinel, scope=NoneScope):
'''
Decorator to create a provider using the given factory, and scope.
Can also be used in a non-decorator manner.
:param scope: Scope key, factory, or instance
:type scope: object or callable
:return: decorator
:rtype: decorator
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _id_for_pc(self, name):
""" Given the name of the PC, return the database identifier. """ |
if not name in self.pc2id_lut:
self.c.execute("INSERT INTO pcs (name) VALUES ( ? )", (name,))
self.pc2id_lut[name] = self.c.lastrowid
self.id2pc_lut[self.c.lastrowid] = name
return self.pc2id_lut[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 _id_for_source(self, name):
""" Given the name of the source, return the database identifier. """ |
if not name in self.source2id_lut:
self.c.execute("INSERT INTO sources (name) VALUES ( ? )", (name,))
self.source2id_lut[name] = self.c.lastrowid
self.id2source_lut[self.c.lastrowid] = name
return self.source2id_lut[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 record_occupation_updates(self, updates, source, version):
""" Records an occupation update """ |
now = int(time.time())
# Put it on the recordQueue and notify the worker thread.
with self.recordCond:
self.recordQueue.append((now, updates, source))
self.recordCond.notify() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def a_urls(html):
'''
return normalized urls found in the 'a' tag
'''
soup = BeautifulSoup(html, 'lxml')
for node in soup.find_all('a'):
try:
href = node['href']
except KeyError:
continue
yield norm_url(href) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def host_names(urls):
'''
Takes a StringCounter of normalized URL and parses their hostnames
N.B. this assumes that absolute URLs will begin with
http://
in order to accurately resolve the host name.
Relative URLs will not have host names.
'''
host_names = StringCounter()
for url ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def path_dirs(urls):
'''
Takes a StringCounter of normalized URL and parses them into
a list of path directories. The file name is
included in the path directory list.
'''
path_dirs = StringCounter()
for url in urls:
for path_dir in filter(None, urlparse(url).path.split('/')):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scan_path(executable="mongod"):
"""Scan the path for a binary. """ |
for path in os.environ.get("PATH", "").split(":"):
path = os.path.abspath(path)
executable_path = os.path.join(path, executable)
if os.path.exists(executable_path):
return executable_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_open_port(host="localhost"):
"""Get an open port on the machine. """ |
temp_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
temp_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
temp_sock.bind((host, 0))
port = temp_sock.getsockname()[1]
temp_sock.close()
del temp_sock
return port |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configure(self, options, conf):
"""Parse the command line options and start an instance of mongodb """ |
# This option has to be specified on the command line, to enable the
# plugin.
if not options.mongoengine or options.mongodb_bin:
return
if not options.mongodb_bin:
self.mongodb_param['mongodb_bin'] = scan_path()
if self.mongodb_param['mongodb_bin'] ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stopContext(self, context):
"""Clear the database if so configured for this """ |
# Use pymongo directly to drop all collections of created db
if ((self.clear_context['module'] and inspect.ismodule(context)) or
(self.clear_context['class'] and inspect.isclass(context))):
self.connection.drop_database(self.database_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 finalize(self, result):
"""Stop the mongodb instance. """ |
if not self._running:
return
# Clear out the env variable.
del os.environ["TEST_MONGODB"]
del os.environ["TEST_MONGODB_DATABASE"]
# Kill the mongod process
if sys.platform == 'darwin':
self.process.kill()
else:
self.process.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.