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 select(self, name):
'''
Returns a new PluginSet that has only the plugins in this that are
named `name`.
'''
return PluginSet(self.group, name, [
plug for plug in self.plugins if plug.name == 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 browse_home_listpage_url(self, state=None, county=None, zipcode=None, street=None, **kwargs):
""" Construct an url of home list page by state, county, zipcod... |
url = self.domain_browse_homes
for item in [state, county, zipcode, street]:
if item:
url = url + "/%s" % item
url = url + "/"
return 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 _render_bundle(bundle_name):
""" Renders the HTML for a bundle in place - one HTML tag or many depending on settings.USE_BUNDLES """ |
try:
bundle = get_bundles()[bundle_name]
except KeyError:
raise ImproperlyConfigured("Bundle '%s' is not defined" % bundle_name)
if bundle.use_bundle:
return _render_file(bundle.bundle_type, bundle.get_url(), attrs=({'media':bundle.media} if bundle.media else {}))
# Render 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 from_string(self, string_representation, resource=None):
""" Extracts resource data from the given string and converts them to a new resource or updates the ... |
stream = NativeIO(string_representation)
return self.from_stream(stream, resource=resource) |
<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_string(self, obj):
""" Converts the given resource to a string representation and returns it. """ |
stream = NativeIO()
self.to_stream(obj, stream)
return text_(stream.getvalue(), encoding=self.encoding) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def data_from_bytes(self, byte_representation):
""" Converts the given bytes representation to resource data. """ |
text = byte_representation.decode(self.encoding)
return self.data_from_string(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 data_to_string(self, data_element):
""" Converts the given data element into a string representation. :param data_element: object implementing :class:`everes... |
stream = NativeIO()
self.data_to_stream(data_element, stream)
return stream.getvalue() |
<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_from_resource_class(cls, resource_class):
""" Creates a new representer for the given resource class. The representer obtains a reference to the (fres... |
mp_reg = get_mapping_registry(cls.content_type)
mp = mp_reg.find_or_create_mapping(resource_class)
return cls(resource_class, mp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def data_from_stream(self, stream):
""" Creates a data element reading a representation from the given stream. :returns: object implementing :class:`everest.repr... |
parser = self._make_representation_parser(stream, self.resource_class,
self._mapping)
return parser.run() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def data_to_stream(self, data_element, stream):
""" Writes the given data element to the given stream. """ |
generator = \
self._make_representation_generator(stream, self.resource_class,
self._mapping)
generator.run(data_element) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resource_from_data(self, data_element, resource=None):
""" Converts the given data element to a resource. :param data_element: object implementing :class:`ev... |
return self._mapping.map_to_resource(data_element, resource=resource) |
<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=None, attribute_options=None):
# pylint: disable=W0221 """ Configures the options and attribute options of the mapping associated wit... |
self._mapping.update(options=options,
attribute_options=attribute_options) |
<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_updated_configuration(self, options=None, attribute_options=None):
""" Returns a context in which this representer is updated with the given options and... |
return self._mapping.with_updated_configuration(options=options,
attribute_options=
attribute_options) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def jsPath(path):
'''Returns a relative path without \, -, and . so that
the string will play nicely with javascript.'''
shortPath=path.replace(
"C:\\Users\\scheinerbock\\Desktop\\"+
"ideogram\\scrapeSource\\test\\","")
noDash = shortPath.replace("-","_dash_")
jsPath=noDash.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def jsName(path,name):
'''Returns a name string without \, -, and . so that
the string will play nicely with javascript.'''
shortPath=path.replace(
"C:\\Users\\scheinerbock\\Desktop\\"+
"ideogram\\scrapeSource\\test\\","")
noDash = shortPath.replace("-","_dash_")
jsPath=noDa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getStartNodes(fdefs,calls):
'''Return a list of nodes in fdefs that have no inbound edges'''
s=[]
for source in fdefs:
for fn in fdefs[source]:
inboundEdges=False
for call in calls:
if call.target==fn:
inboundEdges=True
if 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 getChildren(current,calls,blacklist=[]):
''' Return a list of the children of current that are not in used. '''
return [c.target for c in calls if c.source==current and c.target not in blacklist] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def tagAttributes(fdef_master_list,node,depth=0):
'''recursively tag objects with sizes, depths and path names '''
if type(node)==list:
for i in node:
depth+=1
tagAttributes(fdef_master_list,i,depth)
if type(node)==dict:
for x in fdef_master_list:
if jsNam... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def tagAttributes_while(fdef_master_list,root):
'''Tag each node under root with the appropriate depth. '''
depth = 0
current = root
untagged_nodes = [root]
while untagged_nodes:
current = untagged_nodes.pop()
for x in fdef_master_list:
if jsName(x.path,x.name) == current... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def noEmptyNests(node):
'''recursively make sure that no dictionaries inside node contain empty children lists '''
if type(node)==list:
for i in node:
noEmptyNests(i)
if type(node)==dict:
for i in node.values():
noEmptyNests(i)
if node["children"] == []:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_old_tmp_files(profiles=None, max_lifetime=(7 * 24)):
""" Removes old temp files that is older than expiration_hours. If profiles is None then will be ... |
assert isinstance(profiles, (list, tuple)) or profiles is None
if profiles is None:
profiles = dju_settings.DJU_IMG_UPLOAD_PROFILES.keys()
profiles = set(('default',) + tuple(profiles))
total = removed = 0
old_dt = datetime.datetime.utcnow() - datetime.timedelta(hours=max_lifetime)
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 next_task(self, item, **kwargs):
"""Calls import_batch for the next filename in the queue and "archives" the file. The archive folder is typically the folder... |
filename = os.path.basename(item)
try:
self.tx_importer.import_batch(filename=filename)
except TransactionImporterError as e:
raise TransactionsFileQueueError(e) from e
else:
self.archive(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 get_public_comments_for_model(model):
""" Get visible comments for the model. """ |
if not IS_INSTALLED:
# No local comments, return empty queryset.
# The project might be using DISQUS or Facebook comments instead.
return CommentModelStub.objects.none()
else:
return CommentModel.objects.for_model(model).filter(is_public=True, is_removed=False) |
<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_comments_are_open(instance):
""" Check if comments are open for the instance """ |
if not IS_INSTALLED:
return False
try:
# Get the moderator which is installed for this model.
mod = moderator._registry[instance.__class__]
except KeyError:
# No moderator = no restrictions
return True
# Check the 'enable_field', 'auto_close_field' and 'close_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 get_comments_are_moderated(instance):
""" Check if comments are moderated for the instance """ |
if not IS_INSTALLED:
return False
try:
# Get the moderator which is installed for this model.
mod = moderator._registry[instance.__class__]
except KeyError:
# No moderator = no moderation
return False
# Check the 'auto_moderate_field', 'moderate_after',
# 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 calc_local_indices(shape, num_partitions, coordinate):
""" calculate local indices, return start and stop index per dimension per process for local data fiel... |
dimension = len(shape)
# check matching of cartesian communicator and shape
assert dimension == len(num_partitions)
decomposed_shapes = []
# build shape list for every dimension
for idx in range(dimension):
local_shape = shape[idx] // num_partitions[idx]
temp_shape_list = []
... |
<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_file(self, filename):
"""Read in file contents and set the current string.""" |
with open(filename, 'r') as sourcefile:
self.set_string(sourcefile.read()) |
<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_string(self, string):
"""Set the working string and its length then reset positions.""" |
self.string = string
self.length = len(string)
self.reset_position() |
<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_string(self, string):
"""Add to the working string and its length and reset eos.""" |
self.string += string
self.length += len(string)
self.eos = 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 reset_position(self):
"""Reset all current positions.""" |
self.pos = 0
self.col = 0
self.row = 1
self.eos = 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 has_space(self, length=1, offset=0):
"""Returns boolean if self.pos + length < working string length.""" |
return self.pos + (length + offset) - 1 < self.length |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def eol_distance_next(self, offset=0):
"""Return the amount of characters until the next newline.""" |
distance = 0
for char in self.string[self.pos + offset:]:
if char == '\n':
break
else:
distance += 1
return distance |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def eol_distance_last(self, offset=0):
"""Return the ammount of characters until the last newline.""" |
distance = 0
for char in reversed(self.string[:self.pos + offset]):
if char == '\n':
break
else:
distance += 1
return distance |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def spew_length(self, length):
"""Move current position backwards by length.""" |
pos = self.pos
if not pos or length > pos:
return None
row = self.row
for char in reversed(self.string[pos - length:pos]):
pos -= 1
if char == '\n': # handle a newline char
row -= 1
self.pos = pos
self.col = self.eol... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def eat_length(self, length):
"""Move current position forward by length and sets eos if needed.""" |
pos = self.pos
if self.eos or pos + length > self.length:
return None
col = self.col
row = self.row
for char in self.string[pos:pos + length]:
col += 1
pos += 1
if char == '\n': # handle a newline char
col = 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 eat_string(self, string):
"""Move current position by length of string and count lines by \n.""" |
pos = self.pos
if self.eos or pos + len(string) > self.length:
return None
col = self.col
row = self.row
for char in string:
col += 1
pos += 1
if char == '\n': # handle a newline char
col = 0
row +... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def eat_line(self):
"""Move current position forward until the next line.""" |
if self.eos:
return None
eat_length = self.eat_length
get_char = self.get_char
has_space = self.has_space
while has_space() and get_char() != '\n':
eat_length(1)
eat_length(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 get_char(self, offset=0):
"""Return the current character in the working string.""" |
if not self.has_space(offset=offset):
return ''
return self.string[self.pos + offset] |
<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_length(self, length, trim=0, offset=0):
"""Return string at current position + length. If trim == true then get as much as possible before eos. """ |
if trim and not self.has_space(offset + length):
return self.string[self.pos + offset:]
elif self.has_space(offset + length):
return self.string[self.pos + offset:self.pos + offset + length]
else:
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 get_string(self, offset=0):
"""Return non space chars from current position until a whitespace.""" |
if not self.has_space(offset=offset):
return ''
# Get a char for each char in the current string from pos onward
# solong as the char is not whitespace.
string = self.string
pos = self.pos + offset
for i, char in enumerate(string[pos:]):
if char... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rest_of_string(self, offset=0):
"""A copy of the current position till the end of the source string.""" |
if self.has_space(offset=offset):
return self.string[self.pos + offset:]
else:
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 get_current_line(self):
"""Return a SourceLine of the current line.""" |
if not self.has_space():
return None
pos = self.pos - self.col
string = self.string
end = self.length
output = []
while pos < len(string) and string[pos] != '\n':
output.append(string[pos])
pos += 1
if pos == end:
... |
<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_lines(self, first, last):
"""Return SourceLines for lines between and including first & last.""" |
line = 1
linestring = []
linestrings = []
for char in self.string:
if line >= first and line <= last:
linestring.append(char)
if char == '\n':
linestrings.append((''.join(linestring), line))
linestring =... |
<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_surrounding_lines(self, past=1, future=1):
"""Return the current line and x,y previous and future lines. Returns a list of SourceLine's. """ |
string = self.string
pos = self.pos - self.col
end = self.length
row = self.row
linesback = 0
while linesback > -past:
if pos <= 0:
break
elif string[pos - 2] == '\n':
linesback -= 1
pos -= 1
o... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_all_lines(self):
"""Return all lines of the SourceString as a list of SourceLine's.""" |
output = []
line = []
lineno = 1
for char in self.string:
line.append(char)
if char == '\n':
output.append(SourceLine(''.join(line), lineno))
line = []
lineno += 1
if line:
output.append(SourceLi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def match_string(self, string, word=0, offset=0):
"""Returns 1 if string can be matches against SourceString's current position. If word is >= 1 then it will onl... |
if word:
return self.get_string(offset) == string
return self.get_length(len(string), offset) == string |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def match_any_string(self, strings, word=0, offset=0):
"""Attempts to match each string in strings in order. Will return the string that matches or an empty stri... |
if word:
current = self.get_string(offset)
return current if current in strings else ''
current = ''
currentlength = 0
length = 0
for string in strings:
length = len(string)
if length != currentlength:
current = 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 match_any_char(self, chars, offset=0):
"""Match and return the current SourceString char if its in chars.""" |
if not self.has_space(offset=offset):
return ''
current = self.string[self.pos + offset]
return current if current in chars 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 match_function_pattern(self, first, rest=None, least=1, offset=0):
"""Match each char sequentially from current SourceString position until the pattern doesn... |
if not self.has_space(offset=offset):
return ''
firstchar = self.string[self.pos + offset]
if not first(firstchar):
return ''
output = [firstchar]
pattern = first if rest is None else rest
for char in self.string[self.pos + offset + 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 count_indents_last_line(self, spacecount, tabs=0, back=5):
"""Finds the last meaningful line and returns its indent level. Back specifies the amount of lines... |
if not self.has_space():
return 0
lines = self.get_surrounding_lines(back, 0)
for line in reversed(lines):
if not line.string.isspace():
return line.count_indents(spacecount, tabs)
return 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 count_indents_length_last_line(self, spacecount, tabs=0, back=5):
"""Finds the last meaningful line and returns its indent level and character length. Back s... |
if not self.has_space():
return 0
lines = self.get_surrounding_lines(back, 0)
for line in reversed(lines):
if not line.string.isspace():
return line.count_indents_length(spacecount, tabs)
return (0, 0) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def skip_whitespace(self, newlines=0):
"""Moves the position forwards to the next non newline space character. If newlines >= 1 include newlines as spaces. """ |
if newlines:
while not self.eos:
if self.get_char().isspace():
self.eat_length(1)
else:
break
else:
char = ''
while not self.eos:
char = self.get_char()
if char.is... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pretty_print(self, carrot=False):
"""Return a string of this line including linenumber. If carrot is True then a line is added under the string with a carrot... |
lineno = self.lineno
padding = 0
if lineno < 1000:
padding = 1
if lineno < 100:
padding = 2
if lineno < 10:
padding = 3
string = str(lineno) + (' ' * padding) + '|' + self.string
if carrot:
string += '\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 safe_exit(output):
"""exit without breaking pipes.""" |
try:
sys.stdout.write(output)
sys.stdout.flush()
except IOError:
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def frag2text(endpoint, stype, selector, clean=False, raw=False, verbose=False):
"""returns Markdown text of selected fragment. Args: endpoint: URL, file, or HTM... |
try:
return main(endpoint, stype, selector, clean, raw, verbose)
except StandardError as err:
return err |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read(self, _file):
"""return local file contents as endpoint.""" |
with open(_file) as fh:
data = fh.read()
if self.verbose:
sys.stdout.write("read %d bytes from %s\n"
% (fh.tell(), _file))
return 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 GET(self, url):
"""returns text content of HTTP GET response.""" |
r = requests.get(url)
if self.verbose:
sys.stdout.write("%s %s\n" % (r.status_code, r.encoding))
sys.stdout.write(str(r.headers) + "\n")
self.encoding = r.encoding
return r.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 select(self, html, stype, expression):
"""returns WHATWG spec HTML fragment from selector expression.""" |
etree = html5lib.parse(html,
treebuilder='lxml',
namespaceHTMLElements=False)
if stype == 'css':
selector = lxml.cssselect.CSSSelector(expression)
frag = list(selector(etree))
else:
frag = etree.xp... |
<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, html):
"""removes evil HTML per lxml.html.clean defaults.""" |
return lxml.html.clean.clean_html(unicode(html, self.encoding)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filesystem_repository(_context, name=None, make_default=False, aggregate_class=None, repository_class=None, directory=None, content_type=None):
""" Directive... |
cnf = {}
if not directory is None:
cnf['directory'] = directory
if not content_type is None:
cnf['content_type'] = content_type
_repository(_context, name, make_default,
aggregate_class, repository_class,
REPOSITORY_TYPES.FILE_SYSTEM, 'add_filesystem_repo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rdb_repository(_context, name=None, make_default=False, aggregate_class=None, repository_class=None, db_string=None, metadata_factory=None):
""" Directive fo... |
cnf = {}
if not db_string is None:
cnf['db_string'] = db_string
if not metadata_factory is None:
cnf['metadata_factory'] = metadata_factory
_repository(_context, name, make_default,
aggregate_class, repository_class,
REPOSITORY_TYPES.RDB, 'add_rdb_reposit... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def messaging(_context, repository, reset_on_start=False):
""" Directive for setting up the user message resource in the appropriate repository. :param str repos... |
discriminator = ('messaging', repository)
reg = get_current_registry()
config = Configurator(reg, package=_context.package)
_context.action(discriminator=discriminator, # pylint: disable=E1101
callable=config.setup_system_repository,
args=(repository,),
... |
<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(self, dict, keep):
""" Remove any keys not in 'keep' """ |
if not keep:
return dict
result = {}
for key, value in dict.iteritems():
if key in keep:
result[key] = value
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 main( upload='usbasp', core='arduino', replace_existing=True, ):
"""install custom boards.""" |
def install(mcu, f_cpu, kbyte):
board = AutoBunch()
board.name = TEMPL_NAME.format(mcu=mcu,
f_cpu=format_freq(f_cpu),
upload=upload)
board_id = TEMPL_ID.format(mcu=mcu,
f_cpu=(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 write_county_estimate(self, table, variable, code, datum):
""" Creates new estimate from a census series. Data has following signature from API: { 'B00001_00... |
try:
division = Division.objects.get(
code="{}{}".format(datum["state"], datum["county"]),
level=self.COUNTY_LEVEL,
)
CensusEstimate.objects.update_or_create(
division=division,
variable=variable,
... |
<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_district_estimates_by_state( self, api, table, variable, estimate, state ):
""" Calls API for all districts in a state and a given estimate. """ |
state = Division.objects.get(level=self.STATE_LEVEL, code=state)
district_data = api.get(
("NAME", estimate),
{
"for": "congressional district:*",
"in": "state:{}".format(state.code),
},
year=int(table.year),
)
... |
<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_county_estimates_by_state( self, api, table, variable, estimate, state ):
""" Calls API for all counties in a state and a given estimate. """ |
state = Division.objects.get(level=self.STATE_LEVEL, code=state)
county_data = api.get(
("NAME", estimate),
{"for": "county:*", "in": "state:{}".format(state.code)},
year=int(table.year),
)
for datum in county_data:
self.write_county_estim... |
<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_state_estimates_by_state( self, api, table, variable, estimate, state ):
""" Calls API for a state and a given estimate. """ |
state = Division.objects.get(level=self.STATE_LEVEL, code=state)
state_data = api.get(
("NAME", estimate),
{"for": "state:{}".format(state.code)},
year=int(table.year),
)
for datum in state_data:
self.write_state_estimate(table, variable, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def aggregate_variable(estimate, id):
""" Aggregate census table variables by a custom label. """ |
estimates = [
variable.estimates.get(division__id=id).estimate
for variable in estimate.variable.label.variables.all()
]
method = estimate.variable.label.aggregation
if method == "s":
aggregate = sum(estimates)
elif method == "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 aggregate_national_estimates_by_district(self):
""" Aggregates district-level estimates for each table within the country. Creates data structure designed fo... |
data = {}
fips = "00"
aggregated_labels = []
states = Division.objects.filter(level=self.DISTRICT_LEVEL)
estimates = CensusEstimate.objects.filter(
division__level=self.DISTRICT_LEVEL
)
for estimate in estimates:
series = estimate.variable... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def aggregate_state_estimates_by_county(self, parent):
""" Aggregates county-level estimates for each table within a given state. Creates data structure designed... |
data = {}
for division in tqdm(
Division.objects.filter(level=self.COUNTY_LEVEL, parent=parent)
):
fips = division.code
id = division.id
aggregated_labels = [] # Keep track of already agg'ed variables
for estimate in division.census_e... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def xml(self, fn=None, src='word/document.xml', XMLClass=XML, **params):
"return the src with the given transformation applied, if any."
if src in self.xml_cache: return self.xml_cache[src]
if src not in self.zipfile.namelist(): return
x = XMLClass(
fn=fn or (self.fn and ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def endnotemap(self, cache=True):
"""return the endnotes from the docx, keyed to string id.""" |
if self.__endnotemap is not None and cache==True:
return self.__endnotemap
else:
x = self.xml(src='word/endnotes.xml')
d = Dict()
if x is None: return d
for endnote in x.root.xpath("w:endnote", namespaces=self.NS):
id = endnote... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def footnotemap(self, cache=True):
"""return the footnotes from the docx, keyed to string id.""" |
if self.__footnotemap is not None and cache==True:
return self.__footnotemap
else:
x = self.xml(src='word/footnotes.xml')
d = Dict()
if x is None: return d
for footnote in x.root.xpath("w:footnote", namespaces=self.NS):
id = fo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def commentmap(self, cache=True):
"""return the comments from the docx, keyed to string id.""" |
if self.__commentmap is not None and cache==True:
return self.__commentmap
else:
x = self.xml(src='word/comments.xml')
d = Dict()
if x is None: return d
for comment in x.root.xpath("w:comment", namespaces=self.NS):
id = comment... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def selector(C, style):
"""return the selector for the given stylemap style""" |
clas = C.classname(style.name)
if style.type == 'paragraph':
# heading outline levels are 0..7 internally, indicating h1..h8
outlineLvl = int((style.properties.get('outlineLvl') or {}).get('val') or 8) + 1
if outlineLvl < 9:
tag = 'h%d' % outlineLvl
... |
<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_collection_from_stream(resource, stream, content_type):
""" Creates a new collection for the registered resource and calls `load_into_collection_from_st... |
coll = create_staging_collection(resource)
load_into_collection_from_stream(coll, stream, content_type)
return coll |
<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_into_collection_from_file(collection, filename, content_type=None):
""" Loads resources from the specified file into the given collection resource. If n... |
if content_type is None:
ext = os.path.splitext(filename)[1]
try:
content_type = MimeTypeRegistry.get_type_for_extension(ext)
except KeyError:
raise ValueError('Could not infer MIME type for file extension '
'"%s".' % ext)
load_into_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 load_collection_from_file(resource, filename, content_type=None):
""" Creates a new collection for the registered resource and calls `load_into_collection_fr... |
coll = create_staging_collection(resource)
load_into_collection_from_file(coll, filename,
content_type=content_type)
return coll |
<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_into_collection_from_url(collection, url, content_type=None):
""" Loads resources from the representation contained in the given URL into the given coll... |
parsed = urlparse.urlparse(url)
scheme = parsed.scheme # pylint: disable=E1101
if scheme == 'file':
# Assume a local path.
load_into_collection_from_file(collection,
parsed.path, # pylint: disable=E1101
content_ty... |
<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_collection_from_url(resource, url, content_type=None):
""" Creates a new collection for the registered resource and calls `load_into_collection_from_url... |
coll = create_staging_collection(resource)
load_into_collection_from_url(coll, url, content_type=content_type)
return coll |
<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_into_collections_from_zipfile(collections, zipfile):
""" Loads resources contained in the given ZIP archive into each of the given collections. The ZIP ... |
with ZipFile(zipfile) as zipf:
names = zipf.namelist()
name_map = dict([(os.path.splitext(name)[0], index)
for (index, name) in enumerate(names)])
for coll in collections:
coll_name = get_collection_name(coll)
index = name_map.get(coll_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 build_resource_dependency_graph(resource_classes, include_backrefs=False):
""" Builds a graph of dependencies among the given resource classes. The dependenc... |
def visit(mb_cls, grph, path, incl_backrefs):
for attr_name in get_resource_class_attribute_names(mb_cls):
if is_resource_class_terminal_attribute(mb_cls, attr_name):
continue
child_descr = getattr(mb_cls, attr_name)
child_mb_cls = get_member_class(child_... |
<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_resource_graph(resource, dependency_graph=None):
""" Traverses the graph of resources that is reachable from the given resource. If a resource dependen... |
def visit(rc, grph, dep_grph):
mb_cls = type(rc)
attr_map = get_resource_class_attributes(mb_cls)
for attr_name, attr in iteritems_(attr_map):
if is_resource_class_terminal_attribute(mb_cls, attr_name):
continue
# Only follow the resource attribute 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 find_connected_resources(resource, dependency_graph=None):
""" Collects all resources connected to the given resource and returns a dictionary mapping member... |
# Build a resource_graph.
resource_graph = \
build_resource_graph(resource,
dependency_graph=dependency_graph)
entity_map = OrderedDict()
for mb in topological_sorting(resource_graph):
mb_cls = get_member_class(mb)
ents = entity_map.g... |
<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_files(self, resource, directory):
""" Dumps the given resource and all resources linked to it into a set of representation files in the given directory. "... |
collections = self.__collect(resource)
for (mb_cls, coll) in iteritems_(collections):
fn = get_write_collection_path(mb_cls,
self.__content_type,
directory=directory)
with open_text(os.path.joi... |
<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_zipfile(self, resource, zipfile):
""" Dumps the given resource and all resources linked to it into the given ZIP file. """ |
rpr_map = self.to_strings(resource)
with ZipFile(zipfile, 'w') as zipf:
for (mb_cls, rpr_string) in iteritems_(rpr_map):
fn = get_collection_filename(mb_cls, self.__content_type)
zipf.writestr(fn, rpr_string, compress_type=ZIP_DEFLATED) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read(self):
"""Returns the file contents as validated JSON text. """ |
p = os.path.join(self.path, self.name)
try:
with open(p) as f:
json_text = f.read()
except FileNotFoundError as e:
raise JSONFileError(e) from e
try:
json.loads(json_text)
except (json.JSONDecodeError, TypeError) as e:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exists(self, batch_id=None):
"""Returns True if batch_id exists in the history. """ |
try:
self.model.objects.get(batch_id=batch_id)
except self.model.DoesNotExist:
return False
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 update( self, filename=None, batch_id=None, prev_batch_id=None, producer=None, count=None, ):
"""Creates an history model instance. """ |
# TODO: refactor model enforce unique batch_id
# TODO: refactor model to not allow NULLs
if not filename:
raise BatchHistoryError("Invalid filename. Got None")
if not batch_id:
raise BatchHistoryError("Invalid batch_id. Got None")
if not prev_batch_id:
... |
<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(self, deserialized_txs=None, filename=None, retry=None):
"""Populates the batch with unsaved model instances from a generator of deserialized object... |
if not deserialized_txs:
raise BatchError("Failed to populate batch. There are no objects to add.")
self.filename = filename
if not self.filename:
raise BatchError("Invalid filename. Got None")
try:
for deserialized_tx in deserialized_txs:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def peek(self, deserialized_tx):
"""Peeks into first tx and sets self attrs or raise. """ |
self.batch_id = deserialized_tx.object.batch_id
self.prev_batch_id = deserialized_tx.object.prev_batch_id
self.producer = deserialized_tx.object.producer
if self.batch_history.exists(batch_id=self.batch_id):
raise BatchAlreadyProcessed(
f"Batch {self.batch_id... |
<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):
"""Saves all model instances in the batch as model. """ |
saved = 0
if not self.objects:
raise BatchError("Save failed. Batch is empty")
for deserialized_tx in self.objects:
try:
self.model.objects.get(pk=deserialized_tx.pk)
except self.model.DoesNotExist:
data = {}
fo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_batch(self, filename):
"""Imports the batch of outgoing transactions into model IncomingTransaction. """ |
batch = self.batch_cls()
json_file = self.json_file_cls(name=filename, path=self.path)
try:
deserialized_txs = json_file.deserialized_objects
except JSONFileError as e:
raise TransactionImporterError(e) from e
try:
batch.populate(deserialized_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def timelimit(timeout):
"""borrowed from web.py""" |
def _1(function):
def _2(*args, **kw):
class Dispatch(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.result = None
self.error = None
self.setDaemon(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 _populateBuffer(self, stream, n):
""" Iterator that returns N steps of the genshi stream. Found that performance really sucks for n = 1 (0.5 requests/second ... |
try:
for x in xrange(n):
output = stream.next()
self._buffer.write(output)
except StopIteration, e:
self._deferred.callback(None)
except Exception, e:
self._deferred.errback(e)
else:
self.delayedCall = react... |
<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_message( json_meta, data, data_type=0, version=b'\x00\x01@\x00'):
"""Create message, containing meta and data in df-envelope format. @json_meta - meta... |
__check_data(data)
meta = __prepare_meta(json_meta)
data = __compress(json_meta, data)
header = __create_machine_header(
json_meta, data, data_type, version)
return header + meta + 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 parse_from_file(filename, nodata=False):
"""Parse df message from file. @filename - path to file @nodata - do not load data @return - [binary header, metadat... |
header = None
with open(filename, "rb") as file:
header = read_machine_header(file)
meta_raw = file.read(header['meta_len'])
meta = __parse_meta(meta_raw, header)
data = b''
if not nodata:
data = __decompress(meta, file.read(header['data_len']))
retu... |
<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_message(message, nodata=False):
"""Parse df message from bytearray. @message - message data @nodata - do not load data @return - [binary header, metada... |
header = read_machine_header(message)
h_len = __get_machine_header_length(header)
meta_raw = message[h_len:h_len + header['meta_len']]
meta = __parse_meta(meta_raw, header)
data_start = h_len + header['meta_len']
data = b''
if not nodata:
data = __decompress(
meta,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_machine_header(data):
"""Parse binary header. @data - bytearray, contains binary header of file opened in 'rb' mode @return - parsed binary header """ |
if isinstance(data, (bytes, bytearray)):
stream = io.BytesIO(data)
elif isinstance(data, io.BufferedReader):
stream = data
else:
raise ValueError("data should be either bytearray or file 'rb' mode.")
header = dict()
header_type = stream.read(6)
if header_type == b"#!\x0... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.