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 calculate_infixop(self, node, previous, next_node):
"""Create new node for infixop""" |
previous_position = (previous.last_line, previous.last_col - 1)
position = (next_node.first_line, next_node.first_col + 1)
possible = []
for ch in OPERATORS[node.__class__]:
try:
pos = self.operators[ch].find_previous(position)
if previous_pos... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calculate_unaryop(self, node, next_node):
"""Create new node for unaryop""" |
position = (next_node.first_line, next_node.first_col + 1)
possible = []
for ch in OPERATORS[node.__class__]:
try:
pos = self.operators[ch].find_previous(position)
if pos[1] < position:
possible.append(pos)
except KeyEr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def uid_something_colon(self, node):
""" Creates op_pos for node from uid to colon """ |
node.op_pos = [
NodeWithPosition(node.uid, (node.first_line, node.first_col))
]
position = (node.body[0].first_line, node.body[0].first_col)
last, first = self.operators[':'].find_previous(position)
node.op_pos.append(NodeWithPosition(last, first))
return las... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def optional_else(self, node, last):
""" Create op_pos for optional else """ |
if node.orelse:
min_first_max_last(node, node.orelse[-1])
if 'else' in self.operators:
position = (node.orelse[0].first_line, node.orelse[0].first_col)
_, efirst = self.operators['else'].find_previous(position)
if efirst and efirst > last:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def comma_separated_list(self, node, subnodes):
"""Process comma separated list """ |
for item in subnodes:
position = (item.last_line, item.last_col)
first, last = find_next_comma(self.lcode, position)
if first: # comma exists
node.op_pos.append(NodeWithPosition(last, first)) |
<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_next_comma(self, node, sub):
"""Find comma after sub andd add NodeWithPosition in node""" |
position = (sub.last_line, sub.last_col)
first, last = find_next_comma(self.lcode, position)
if first: # comma exists
node.op_pos.append(NodeWithPosition(last, first)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fields(self):
""" Provides an iterable for all model fields. """ |
for attr, value in self._meta.fields.items():
if isinstance(value, Field):
yield attr, 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 wrap(self, data):
""" Wraps and consumes an arbitrary dictionary into the model. """ |
for name, field in self.fields:
try:
self._state[name] = field.consume(
self._state.get(name, None), data[name])
except KeyError:
self._state[name] = None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate(self):
""" Validates all field values for the model. """ |
errors = {}
for name, field in self.fields:
try:
field.validate(self._state.get(name))
except Exception as e:
errors[name] = e
if len(errors) is not 0:
raise Exception(errors)
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:
async def save(self):
""" Persists the model to the database. If the model holds no primary key, a new one will automatically created by RethinkDB. Otherwise it ... |
if hasattr(self, "before_save"):
self.before_save()
query = r.table(self.table_name)
if self._state.get("id"):
query = query \
.get(self._state.get("id")) \
.update(self.__db_repr, return_changes=True)
else:
query = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def delete(self):
""" Deletes the model from the database. """ |
await r.table_name(self.table_name) \
.get(self.id) \
.delete() \
.run(await conn.get()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _raw_split(itxt):
""" Parse HTML from text into array filled with tags end text. Source code is little bit unintutive, because it is state machine parser. Fo... |
echr = ""
buff = ["", "", "", ""]
content = ""
array = []
next_state = 0
inside_tag = False
escaped = False
COMMENT_START = ["-", "!", "<"]
COMMENT_END = ["-", "-"]
gc.disable()
for c in itxt:
# content
if next_state == StateEnum.content:
if 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 _indexOfEndTag(istack):
""" Go through `istack` and search endtag. Element at first index is considered as opening tag. Args: istack (list):
List of :class:... |
if len(istack) <= 0:
return 0
if not istack[0].isOpeningTag():
return 0
cnt = 0
opener = istack[0]
for index, el in enumerate(istack[1:]):
if el.isOpeningTag() and \
el.getTagName().lower() == opener.getTagName().lower():
cnt += 1
elif el.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 _parseDOM(istack):
""" Recursively go through element array and create DOM. Args: istack (list):
List of :class:`.HTMLElement` objects. Returns: list: DOM t... |
ostack = []
end_tag_index = 0
def neither_nonpair_or_end_or_comment(el):
return not (el.isNonPairTag() or el.isEndTag() or el.isComment())
index = 0
while index < len(istack):
el = istack[index]
# check if this is pair tag
end_tag_index = _indexOfEndTag(istack[ind... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def makeDoubleLinked(dom, parent=None):
""" Standard output from `dhtmlparser` is single-linked tree. This will make it double-linked. Args: dom (obj):
:class:`... |
dom.parent = parent
for child in dom.childs:
child.parent = dom
makeDoubleLinked(child, dom) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def removeTags(dom):
""" Remove all tags from `dom` and obtain plaintext representation. Args: dom (str, obj, array):
str, HTMLElement instance or array of elem... |
# python 2 / 3 shill
try:
string_type = basestring
except NameError:
string_type = str
# initialize stack with proper value (based on dom parameter)
element_stack = None
if type(dom) in [list, tuple]:
element_stack = dom
elif isinstance(dom, HTMLElement):
el... |
<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_method(obj, name):
""" Checks if object has a method with specified name. :param obj: an object to introspect. :param name: a name of the method to check... |
if obj == None:
raise Exception("Object cannot be null")
if name == None:
raise Exception("Method name cannot be null")
name = name.lower()
for method_name in dir(obj):
if method_name.lower() != name:
continue
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 invoke_method(obj, name, *args):
""" Invokes an object method by its name with specified parameters. :param obj: an object to invoke. :param name: a name of ... |
if obj == None:
raise Exception("Object cannot be null")
if name == None:
raise Exception("Method name cannot be null")
name = name.lower()
try:
for method_name in dir(obj):
if method_name.lower() != 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 get_method_names(obj):
""" Gets names of all methods implemented in specified object. :param obj: an object to introspect. :return: a list with method names.... |
method_names = []
for method_name in dir(obj):
method = getattr(obj, method_name)
if MethodReflector._is_method(method, method_name):
method_names.append(method_name)
return method_names |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_to_delivery_stream(events, stream_name):
"""Sends a list of events to a Firehose delivery stream.""" |
if not events:
logger.info("No events provided: nothing delivered to Firehose")
return
records = []
for event in events:
if not isinstance(event, str):
# csv events already have a newline
event = json.dumps(event) + "\n"
records.append({"Data": event... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_to_kinesis_stream(events, stream_name, partition_key=None, packer=None, serializer=json.dumps):
"""Sends events to a Kinesis stream.""" |
if not events:
logger.info("No events provided: nothing delivered to Firehose")
return
records = []
for event in events:
if not partition_key:
partition_key_value = str(uuid.uuid4())
elif hasattr(partition_key, "__call__"):
partition_key_value = part... |
<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_app(self, app):
"""Register the extension with the application. Args: app (flask.Flask):
The application to register with. """ |
app.url_rule_class = partial(NavigationRule, copilot=self)
app.context_processor(self.inject_context) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inject_context(self):
"""Return a dict used for a template context.""" |
navbar = filter(lambda entry: entry.visible, self.navbar_entries)
return {'navbar': navbar} |
<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_entry(self, navbar_kwargs):
"""Register a navbar entry with the copilot. Args: navbar_kwargs (dict):
Arguments passed to the :class:`NavbarEntry` i... |
# Add a new rule for each level in the path.
path = navbar_kwargs.pop('path')
# If a single object is used rather than an iterable (including
# a single string), wrap it before using.
if not hasattr(path, '__iter__') or isinstance(path, basestring):
path = [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 reversed(self):
"""Create a connectivity matrix where each incoming edge becomes outgoing.""" |
n_rows = len(self)
reversed = DirectedAdjacencyMatrix(n_rows, self.dtype)
for r, row in enumerate(py.prog_iter(self)):
for c in row:
reversed[c].append(r)
return reversed |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def crc7(data):
""" Compute CRC of a whole message. """ |
crc = 0
for c in data:
crc = CRC7_TABLE[crc ^ c]
return crc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _unhandledInput(event, workbench, launcher):
"""Handles input events that weren't handled anywhere else. """ |
if event == "ctrl w":
raise urwid.ExitMainLoop()
elif event == "esc":
workbench.clear()
workbench.display(launcher)
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 _runPopUp(workbench, popUp):
"""Displays the pop-up on the workbench and gets a completion notification deferred. When that fires, undisplay the pop-up and r... |
workbench.display(popUp)
d = popUp.notifyCompleted()
d.addCallback(_popUpCompleted, workbench)
return d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def display(self, tool):
"""Displays the given tool above the current layer, and sets the title to its name. """ |
self._tools.append(tool)
self._justDisplay(tool) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _justDisplay(self, tool):
""" Displays the given tool. Does not register it in the tools list. """ |
self.header.title.set_text(tool.name)
body, _options = self.widget.contents["body"]
overlay = urwid.Overlay(tool.widget, body, *tool.position)
self._surface = urwid.AttrMap(overlay, "foreground")
self.widget.contents["body"] = self._surface, None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def undisplay(self):
"""Undisplays the top tool. This actually forces a complete re-render. """ |
self._tools.pop()
self._justClear()
for tool in self._tools:
self._justDisplay(tool) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _makeButtons(self):
"""Makes buttons and wires them up. """ |
self.button = button = urwid.Button(u"OK")
urwid.connect_signal(button, "click", self._completed)
return [self.button] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _makeTextWidgets(self):
"""Makes an editable prompt widget. """ |
self.prompt = urwid.Edit(self.promptText, multiline=False)
return [self.prompt] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _secrets_table_name(environment=None, stage=None):
"""Name of the secrets table associated to a humilis deployment.""" |
if environment is None:
environment = os.environ.get("HUMILIS_ENVIRONMENT")
if stage is None:
stage = os.environ.get("HUMILIS_STAGE")
if environment:
if stage:
return "{environment}-{stage}-secrets".format(**locals())
else:
return "{environment}-sec... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _state_table_name(environment=None, layer=None, stage=None):
"""The name of the state table associated to a humilis deployment.""" |
if environment is None:
# For backwards compatiblity
environment = os.environ.get("HUMILIS_ENVIRONMENT")
if layer is None:
layer = os.environ.get("HUMILIS_LAYER")
if stage is None:
stage = os.environ.get("HUMILIS_STAGE")
if environment:
if stage:
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 _get_secret_from_vault( key, environment=None, stage=None, namespace=None, wait_exponential_multiplier=50, wait_exponential_max=5000, stop_max_delay=10000):
... |
# Get the encrypted secret from DynamoDB
table_name = _secrets_table_name(environment=environment, stage=stage)
if namespace:
key = "{}:{}".format(namespace, key)
if table_name is None:
logger.warning("Can't produce secrets table name: unable to retrieve "
"secr... |
<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_secret(key, *args, **kwargs):
"""Retrieves a secret.""" |
env_value = os.environ.get(key.replace('.', '_').upper())
if not env_value:
# Backwards compatibility: the deprecated secrets vault
return _get_secret_from_vault(key, *args, **kwargs)
return env_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_state_batch(keys, namespace=None, consistent=True):
"""Get a batch of items from the state store.""" |
ukeys = set(keys)
if namespace:
ns_keys = ["{}:{}".format(namespace, key) for key in ukeys]
uvalues = {k: v for k, v
in zip(ukeys, get_item_batch(ns_keys, consistent=consistent))}
return list(zip(keys, (uvalues[k] for k in keys))) |
<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_state_batch(keys, values, namespace=None, ttl=3600*24*365):
"""Set a batch of items in the state store.""" |
keys, values = zip(*{k: v for k, v in zip(keys, values)}.items())
if namespace:
keys = ["{}:{}".format(namespace, key) for key in keys]
return set_item_batch(keys, values, ttl) |
<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_state(key, value, namespace=None, table_name=None, environment=None, layer=None, stage=None, shard_id=None, consistent=True, serializer=json.dumps, wait_e... |
if table_name is None:
table_name = _state_table_name(environment=environment, layer=layer,
stage=stage)
if not table_name:
msg = ("Can't produce state table name: unable to set state "
"item '{}'".format(key))
logger.error(msg)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_state(key, namespace=None, table_name=None, environment=None, layer=None, stage=None, shard_id=None, consistent=True, wait_exponential_multiplier=500, ... |
if table_name is None:
table_name = _state_table_name(environment=environment, layer=layer,
stage=stage)
if not table_name:
msg = ("Can't produce state table name: unable to set state "
"item '{}'".format(key))
logger.error(msg)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def produce_context(namespace, context_id, max_delay=None):
"""Produce event context.""" |
try:
context_obj = get_context(namespace, context_id)
logger.info("Found context '%s:%s'", namespace, context_id)
except ContextError:
logger.info("Context '%s:%s' not found", namespace, context_id)
if max_delay is not None:
max_delay = float(max_delay)
logge... |
<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_context(namespace, context_id):
"""Get stored context object.""" |
context_obj = get_state(context_id, namespace=namespace)
if not context_obj:
raise ContextError("Context '{}' not found in namespace '{}'".format(
context_id, namespace))
return context_obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def arrival_delay_greater_than(item_id, delay, namespace="_expected_arrival"):
"""Check if an item arrival is delayed more than a given amount.""" |
expected = get_state(item_id, namespace=namespace)
now = time.time()
if expected and (now - expected) > delay:
logger.error("Timeout: waited %s seconds for parent.", delay)
return True
elif expected:
logger.info("Still out of order but no timeout: %s-%s <= %s.",
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(name, stype, **kwargs):
"""Returns the rcParams specified in the style file given by `name` and `stype`. Parameters name: str The name of the style. styp... |
stype = str(stype)
params = {}
if stype in MPLS_STYPES:
params.update(__get(name, stype, **kwargs))
else:
raise ValueError('unexpected stype: {}! Must be any of {!r}'.format(stype, MPLS_STYPES))
# color palette hack
if params.get('axes.prop_cycle'):
params['axes.prop_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 collect(context=None, style=None, palette=None, **kwargs):
"""Returns the merged rcParams dict of the specified context, style, and palette. Parameters conte... |
params = {}
if context:
params.update(get(context, 'context', **kwargs))
if style:
params.update(get(style, 'style', **kwargs))
if palette:
params.update(get(palette, 'palette', **kwargs))
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 str_to_num(i, exact_match=True):
""" Attempts to convert a str to either an int or float """ |
# TODO: Cleanup -- this is really ugly
if not isinstance(i, str):
return i
try:
if not exact_match:
return int(i)
elif str(int(i)) == i:
return int(i)
elif str(float(i)) == i:
return float(i)
else:
pass
except 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 make_link(title, url, blank=False):
""" Make a HTML link out of an URL. Args: title (str):
Text to show for the link. url (str):
URL the link will p... |
attrs = 'href="%s"' % url
if blank:
attrs += ' target="_blank" rel="noopener noreferrer"'
return '<a %s>%s</a>' % (attrs, title) |
<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_asset_url(self, path):
""" Get the URL of an asset. If asset hashes are added and one exists for the path, it will be appended as a query string. ... |
url = self.root_url + '/assets/' + path
if path in self.asset_hash:
url += '?' + self.asset_hash[path]
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 add_pages(self, path='pages'):
""" Look through a directory for markdown files and add them as pages. """ |
pages_path = os.path.join(self.root_path, path)
pages = []
for file in _listfiles(pages_path):
page_dir = os.path.relpath(os.path.dirname(file), pages_path)
if page_dir == '.':
page_dir = None
pages.append(self.cm.Page.from_file(file, directory=page_dir))
self.cm.add_pages(pages) |
<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_posts(self, path='posts'):
""" Look through a directory for markdown files and add them as posts. """ |
path = os.path.join(self.root_path, path)
self.cm.add_posts([
self.cm.Post.from_file(file)
for file in _listfiles(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 copy_assets(self, path='assets'):
""" Copy assets into the destination directory. """ |
path = os.path.join(self.root_path, path)
for root, _, files in os.walk(path):
for file in files:
fullpath = os.path.join(root, file)
relpath = os.path.relpath(fullpath, path)
copy_to = os.path.join(self._get_dist_path(relpath, directory='assets'))
LOG.debug('copying %r to %r', fullpath, copy_to... |
<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_asset_hashes(self, path='dist/assets'):
""" Scan through a directory and add hashes for each file found. """ |
for fullpath in _listfiles(os.path.join(self.root_path, path)):
relpath = fullpath.replace(self.root_path + '/' + path + '/', '')
md5sum = hashlib.md5(open(fullpath, 'rb').read()).hexdigest()
LOG.debug('MD5 of %s (%s): %s', fullpath, relpath, md5sum)
self.asset_hash[relpath] = md5sum |
<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_posts(self, num=None, tag=None, private=False):
""" Get all the posts added to the blog. Args: num (int):
Optional. If provided, only return N ... |
posts = self.posts
if not private:
posts = [post for post in posts if post.public]
if tag:
posts = [post for post in posts if tag in post.tags]
if num:
return posts[:num]
return posts |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_pages(self):
""" Generate HTML out of the pages added to the blog. """ |
for page in self.pages:
self.generate_page(page.slug, template='page.html.jinja', page=page) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_posts(self):
""" Generate single-post HTML files out of posts added to the blog. Will not generate front page, archives or tag files - those h... |
for post in self.posts:
self.generate_page(
['posts', post.slug],
template='post.html.jinja',
post=post,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_tags(self):
""" Generate one HTML page for each tag, each containing all posts that match that tag. """ |
for tag in self.tags:
posts = self.get_posts(tag=tag, private=True)
self.generate_page(['tags', tag.slug],
template='archive.html.jinja', posts=posts) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_page(self, path, template, **kwargs):
""" Generate the HTML for a single page. You usually don't need to call this method manually, it is used... |
directory = None
if kwargs.get('page'):
directory = kwargs['page'].dir
path = self._get_dist_path(path, directory=directory)
if not path.endswith('.html'):
path = path + '.html'
if not os.path.isdir(os.path.dirname(path)):
os.makedirs(os.path.dirname(path))
html = self._get_template(template).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 generate_index(self, num_posts=5):
""" Generate the front page, aka index.html. """ |
posts = self.get_posts(num=num_posts)
self.generate_page('index', template='index.html.jinja', posts=posts) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_rss(self, path='rss.xml', only_excerpt=True, https=False):
""" Generate the RSS feed. Args: path (str):
Where to save the RSS file. Make s... |
feed = russell.feed.get_rss_feed(self, only_excerpt=only_excerpt, https=https)
feed.rss_file(self._get_dist_path(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 generate_sitemap(self, path='sitemap.xml', https=False):
""" Generate an XML sitemap. Args: path (str):
The name of the file to write to. https ... |
sitemap = russell.sitemap.generate_sitemap(self, https=https)
self.write_file(path, sitemap) |
<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_file(self, path, contents):
""" Write a file of any type to the destination path. Useful for files like robots.txt, manifest.json, and so on. A... |
path = self._get_dist_path(path)
if not os.path.isdir(os.path.dirname(path)):
os.makedirs(os.path.dirname(path))
if isinstance(contents, bytes):
mode = 'wb+'
else:
mode = 'w'
with open(path, mode) as file:
file.write(contents) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enable_travis(token, slug, log):
""" Enable Travis automatically for the given repo. this need to have access to the GitHub token. """ |
# Done with github directly. Login to travis
travis = TravisPy.github_auth(token, uri='https://api.travis-ci.org')
user = travis.user()
log.info('Travis user: %s', user.name)
# Ask travis to sync with github, try to fetch created repo with exponentially decaying time.
last_sync = user.synce... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def project_layout(proposal, user=None, repo=None, log=None):
""" generate the project template proposal is the name of the project, user is an object containing... |
proposal = proposal.lower()
#context_file = os.path.expanduser('~/.cookiecutters/cookiecutter-pypackage/cookiecutter.json')
#context = generate_context(context_file)
# os.chdir('..')
# context['cookiecutter']['full_name'] = user.name
# context['cookiecutter']['email'] = user.email
# cont... |
<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_db_user(username, password=None, flags=None):
"""Create a databse user.""" |
flags = flags or u'-D -A -R'
sudo(u'createuser %s %s' % (flags, username), user=u'postgres')
if password:
change_db_user_password(username, password) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def excute_query(query, db=None, flags=None, use_sudo=False, **kwargs):
"""Execute remote psql query.""" |
flags = flags or u''
if db:
flags = u"%s -d %s" % (flags, db)
command = u'psql %s -c "%s"' % (flags, query)
if use_sudo:
sudo(command, user='postgres', **kwargs)
else:
run(command, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def db_user_exists(username):
"""Return True if the DB user already exists. """ |
qry = u"""SELECT COUNT(*) FROM pg_roles where rolname = \'{username}\';"""
output = StringIO()
excute_query(
qry.format(username=username),
flags="-Aqt",
use_sudo=True,
stdout=output
)
# FIXME: is there a way to get fabric to not clutter the output
# with "[127.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 change_db_user_password(username, password):
"""Change a db user's password.""" |
sql = "ALTER USER %s WITH PASSWORD '%s'" % (username, password)
excute_query(sql, use_sudo=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 create_db(name, owner=None, encoding=u'UTF-8', template='template1', **kwargs):
"""Create a Postgres database.""" |
flags = u''
if encoding:
flags = u'-E %s' % encoding
if owner:
flags = u'%s -O %s' % (flags, owner)
if template and template != 'template1':
flags = u'%s --template=%s' % (flags, template)
sudo('createdb %s %s' % (flags, name), user='postgres', **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload_pg_hba_conf(template_name=None, pg_version=None, pg_cluster='main', restart=True):
""" Upload configuration for pg_hba.conf If the version is not give... |
template_name = template_name or u'postgres/pg_hba.conf'
version = pg_version or detect_version()
config = {'version': version, 'cluster': pg_cluster}
destination = u'/etc/postgresql/%(version)s/%(cluster)s/pg_hba.conf' % config
upload_template(template_name, destination, use_sudo=True)
if 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 detect_version():
"""Parse the output of psql to detect Postgres version.""" |
version_regex = re.compile(r'\(PostgreSQL\) (?P<major>\d)\.(?P<minor>\d)\.(?P<bugfix>\d)')
pg_version = None
with hide('running', 'stdout', 'stderr'):
output = run('psql --version')
match = version_regex.search(output)
if match:
result = match.groupdict()
if 'major' in resul... |
<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_cluster(pg_cluster='main', pg_version=None, encoding=u'UTF-8', locale=u'en_US.UTF-8'):
"""Drop and restore a given cluster.""" |
warning = u'You are about to drop the %s cluster. This cannot be undone.' \
u' Are you sure you want to continue?' % pg_cluster
if confirm(warning, default=False):
version = pg_version or detect_version()
config = {'version': version, 'cluster': pg_cluster,
'enco... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def require_request_model(cls, validate=True):
""" Makes a handler require that a request body that map towards the given model is provided. Unless the ``validat... |
def decorator(handler):
async def new_handler(request, *args, **kwargs):
body = await request.json()
model = cls(**body)
if validate:
model.validate()
return await handler(request, model, *args, **kwargs)
return new_handler
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 read_csv(csv_file, options, ensemble_list=None):
""" Read csv and return molList, otherwise print error and exit. """ |
name, ext = os.path.splitext(csv_file)
try:
if ext == '.gz':
f = gzip.open(csv_file, 'rb')
else:
f = open(csv_file, 'rU')
except IOError:
print(" \n '{f}' could not be opened\n".format(f=os.path.basename(csv_file)))
sys.exit(1)
csv_reader = csv.... |
<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_rules(specs):
"""Adapts the list of anillo urlmapping specs into a list of werkzeug rules or rules subclasses. :param list specs: A list of anillo url... |
for spec in specs:
if "context" in spec:
yield Context(spec["context"], list(_build_rules(spec.get("routes", []))))
else:
rulespec = spec.copy()
match = rulespec.pop("match")
name = rulespec.pop("name")
yield Rule(match, endpoint=name, **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 _build_urlmapping(urls, strict_slashes=False, **kwargs):
"""Convers the anillo urlmappings list into werkzeug Map instance. :return: a werkzeug Map instance ... |
rules = _build_rules(urls)
return Map(rules=list(rules), strict_slashes=strict_slashes, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def default_match_error_handler(exc):
""" Default implementation for match error handling. """ |
if isinstance(exc, NotFound):
return http.NotFound()
elif isinstance(exc, MethodNotAllowed):
return http.MethodNotAllowed()
elif isinstance(exc, RequestRedirect):
return redirect(exc.new_url)
else:
raise exc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def r_oauth_login(self):
""" Route for OAuth2 Login :param next next url :type str :return: Redirects to OAuth Provider Login URL """ |
session['next'] = request.args.get('next','')
callback_url = self.authcallback
if callback_url is None:
callback_url = url_for('.r_oauth_authorized', _external=True)
return self.authobj.authorize(callback=callback_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 wrap_session(func=None, *, storage=MemoryStorage):
""" A middleware that adds the session management to the request. This middleware optionally accepts a `st... |
if func is None:
return functools.partial(wrap_session, storage=storage)
# Initialize the storage
storage = storage()
def wrapper(request, *args, **kwargs):
session_key = storage.get_session_key(request)
request.session = storage.retrieve(request, session_key)
respons... |
<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_added_dimensions(self, n):
""" Adds n dimensions and returns the Rect. If n < 0, removes dimensions. """ |
if n > 0:
return Rect(np.pad(self.data, ((0, 0), (0, n)), 'constant'))
return Rect(self.data[:, :self.dimensions + 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 clamped(self, point_or_rect):
""" Returns the point or rectangle clamped to this rectangle. """ |
if isinstance(point_or_rect, Rect):
return Rect(np.minimum(self.mins, point_or_rect.mins),
np.maximum(self.maxes, point_or_rect.maxes))
return np.clip(point_or_rect, self.mins, self.maxes) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rectified(self):
""" Fixes swaped min-max pairs. """ |
return Rect(np.minimum(self.mins, self.maxes),
np.maximum(self.maxes, self.mins)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(self, *args, **kwargs):
#pylint:disable=unused-argument """ | Launch the SSE consumer. | It can listen forever for messages or just wait for one. :param... |
limit = kwargs.get('limit', None)
timeout = kwargs.get('timeout', None)
self.run(limit=limit, timeout=timeout) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def phrase(min_size, max_size = None):
""" Generates a random phrase which consists of few words separated by spaces. The first word is capitalized, others are n... |
max_size = max_size if max_size != None else min_size
size = RandomInteger.next_integer(min_size, max_size)
if size <= 0:
return ""
result = ""
result += random.choice(_all_words)
while len(result) < size:
result += " " + random.choice(_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 words(min_size, max_size = None):
""" Generates a random text that consists of random number of random words separated by spaces. :param min_size: (optional)... |
max_size = max_size if max_size != None else min_size
result = ""
count = RandomInteger.next_integer(min_size, max_size)
for i in range(count):
result += random.choice(_all_words)
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 text(min_size, max_size):
""" Generates a random text, consisting of first names, last names, colors, stuffs, adjectives, verbs, and punctuation marks. :para... |
max_size = max_size if max_size != None else min_size
size = RandomInteger.next_integer(min_size, max_size)
result = ""
result += random.choice(_all_words)
while len(result) < size:
next = random.choice(_all_words)
if RandomBoolean.chance(4, 6):... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wrap_form_params(func):
""" A middleware that parses the url-encoded body and attach the result to the request `form_params` attribute. This middleware also ... |
@functools.wraps(func)
def wrapper(request, *args, **kwargs):
ctype, pdict = parse_header(request.headers.get('Content-Type', ''))
if ctype == "application/x-www-form-urlencoded":
params = {}
for key, value in parse_qs(request.body.decode("utf-8")).items():
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wrap_query_params(func):
""" A middleware that parses the urlencoded params from the querystring and attach it to the request `query_params` attribute. This ... |
@functools.wraps(func)
def wrapper(request, *args, **kwargs):
params = {}
for key, value in parse_qs(request.query_string.decode("utf-8")).items():
if len(value) == 1:
params[key] = value[0]
else:
params[key] = value
request.para... |
<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_node(cls, *args, **kwargs):
"""Initializes an ast node with the provided attributes. Python 2.6+ supports this in the node class initializers, but Pytho... |
node = cls()
for name, value in zip(cls._fields, args):
setattr(node, name, value)
for name, value in kwargs:
setattr(node, name, value)
return node |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_the(node, node_type):
"""Extracts the node of type node_type from the provided node. - If the node is itself of node_type, returns node. - If the nod... |
if isinstance(node, node_type):
return node
try:
body = node.body
except AttributeError:
raise cypy.Error(
"Expecting suite containing a single %s, or a %s, but got %s." %
(node_type.__name__, node_type.__name__, type(node).__name__))
if len(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_version():
"""Use git describe to get version from tag""" |
proc = subprocess.Popen(
("git", "describe", "--tag", "--always"),
stdout=subprocess.PIPE, stderr=subprocess.STDOUT
)
output, _ = proc.communicate()
result = output.decode("utf-8").strip()
if proc.returncode != 0:
sys.stderr.write(
">>> Git Describe Error:\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 get_file(fn):
"""Returns file contents in unicode as list.""" |
fn = os.path.join(os.path.dirname(__file__), 'data', fn)
f = open(fn, 'rb')
lines = [line.decode('utf-8').strip() for line in f.readlines()]
return lines |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def name_generator(names=None):
"""Creates a generator for generating names. :arg names: list or tuple of names you want to use; defaults to ENGLISH_MONARCHS :re... |
if names is None:
names = ENGLISH_MONARCHS
while True:
yield text_type(random.choice(names)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def email_generator(names=None, domains=None, unique=False):
"""Creates a generator for generating email addresses. :arg names: list of names to use; defaults to... |
if names is None:
names = [name.encode('ascii', 'ignore').lower().replace(b' ', b'')
for name in ENGLISH_MONARCHS]
if domains is None:
domains = DOMAINS
if unique:
uniquifyer = lambda: str(next(_unique_counter))
else:
uniquifyer = lambda: ''
while ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def paragraph_generator(sentences=None):
"""Creates a generator for generating paragraphs. :arg sentences: list or tuple of sentences you want to use; defaults t... |
if sentences is None:
sentences = LOREM
while True:
# Paragraph consists of 1-7 sentences.
paragraph = [random.choice(sentences)
for num in range(random.randint(1, 7))]
yield u' '.join(paragraph) |
<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_dotted_path(path):
""" Takes a dotted path to a member name in a module, and returns the member after importing it. """ |
# stolen from Mezzanine (mezzanine.utils.importing.import_dotted_path)
try:
module_path, member_name = path.rsplit(".", 1)
module = import_module(module_path)
return getattr(module, member_name)
except (ValueError, ImportError, AttributeError) as e:
raise ImportError('Could ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def discoverAuthEndpoints(authDomain, content=None, look_in={'name': 'link'}, test_urls=True, validateCerts=True, headers={}):
"""Find the authorization or redir... |
if test_urls:
ronkyuu.URLValidator(message='invalid domain URL')(authDomain)
if content:
result = {'status': requests.codes.ok,
'headers': None,
'content': content
}
else:
r = requests.get(authDomain, verify=validateCerts, h... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validateAuthCode(code, redirect_uri, client_id, state=None, validationEndpoint='https://indieauth.com/auth', headers={}):
"""Call authorization endpoint to v... |
payload = {'code': code,
'redirect_uri': redirect_uri,
'client_id': client_id,
}
if state is not None:
payload['state'] = state
authURL = None
authEndpoints = discoverAuthEndpoints(client_id, headers=headers)
for url in authEndpoints['... |
<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_params(url, ignore_empty=False):
""" Static method that parses a given `url` and retrieves `url`'s parameters. Could also ignore empty value parameters. ... |
try:
params_start_index = url.index('?')
except ValueError:
params_start_index = 0
params_string = url[params_start_index + 1:]
params_dict = {}
for pair in params_string.split('&'):
if not pair:
continue
splitted ... |
<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_date(table_data):
""" Static method that parses a given table data element with `Url.DATE_STRPTIME_FORMAT` and creates a `date` object from td's text c... |
text = table_data.text.split('Added on ')
# Then it's 'Added today'. Hacky
if len(text) < 2:
return date.today()
# Looks like ['', 'Thursday, Mar 05, 2015']
return datetime.strptime(text[1], Parser.DATE_STRPTIME_FORMAT).date() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.