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 send_verification_mail(request, user, verification_type):
""" Sends an email with a verification link to users when ``ACCOUNTS_VERIFICATION_REQUIRED`` is ```... |
verify_url = reverse(verification_type, kwargs={
"uidb36": int_to_base36(user.id),
"token": default_token_generator.make_token(user),
}) + "?next=" + (next_url(request) or "/")
context = {
"request": request,
"user": user,
"verify_url": verify_url,
}
subject_... |
<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_approve_mail(request, user):
""" Sends an email to staff in listed in the setting ``ACCOUNTS_APPROVAL_EMAILS``, when a new user signs up and the ``ACCOU... |
approval_emails = split_addresses(settings.ACCOUNTS_APPROVAL_EMAILS)
if not approval_emails:
return
context = {
"request": request,
"user": user,
"change_url": admin_url(user.__class__, "change", user.id),
}
subject = subject_template("email/account_approve_subject.t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_approved_mail(request, user):
""" Sends an email to a user once their ``is_active`` status goes from ``False`` to ``True`` when the ``ACCOUNTS_APPROVAL_... |
context = {"request": request, "user": user}
subject = subject_template("email/account_approved_subject.txt", context)
send_mail_template(subject, "email/account_approved",
settings.DEFAULT_FROM_EMAIL, user.email,
context=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 GetColumnNumber (self, columnName):
"""returns the column number for a given column heading name, 0 if not found""" |
for row in range(1, self.maxRow + 1):
for column in range(1, self.maxColumn + 1):
if self.GetCellValue(column, row, "") == columnName:
return column
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 DumpAsCSV (self, separator=",", file=sys.stdout):
"""dump as a comma separated value file""" |
for row in range(1, self.maxRow + 1):
sep = ""
for column in range(1, self.maxColumn + 1):
file.write("%s\"%s\"" % (sep, self.GetCellValue(column, row, "")))
sep = separator
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GetWorksheet(self, nameOrNumber):
"""get a sheet by number""" |
if isinstance(nameOrNumber, int):
return self.worksheets[nameOrNumber]
else:
return self.worksheetsByName[nameOrNumber] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def startElement (self, name, attrs):
'''if there's a start method for this element, call it
'''
func = getattr(self, 'start_' + name, None)
if func:
func(attrs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_request(request):
"""Convert a model run request from the buffer into a message in a RabbitMQ queue. Parameters request : dict Buffer entry containing... |
connector = request['connector']
hostname = connector['host']
port = connector['port']
virtual_host = connector['virtualHost']
queue = connector['queue']
user = connector['user']
password = connector['password']
# Establish connection with RabbitMQ server
logging.info('Connect : [HO... |
<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_locations():
'''
Compiles default locations
:returns:
A dictionary with folders as values:
* 'home_dir': Your home-directory (:file:`~`)
* 'call_dir': Where you called the first Python script from. (``argv[0]``)
* 'conf_dir': The :envvar:`XDG_CONFIG_HOME`-directory + \
``... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def backup_location(src, loc=None):
'''
Writes Backups of locations
:param src:
The source file/folder to backup
:param loc:
The target folder to backup into
The backup will be called `src` + :func:`util.system.get_timestamp`.
* If `loc` left to none, the backup gets wr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def status(name, init_system, verbose):
"""WIP! Try at your own expense """ |
try:
status = Serv(init_system, verbose=verbose).status(name)
except ServError as ex:
sys.exit(ex)
click.echo(json.dumps(status, indent=4, sort_keys=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 _parse_service_env_vars(self, env_vars):
"""Return a dict based on `key=value` pair strings. """ |
env = {}
for var in env_vars:
# Yeah yeah.. it's less performant.. splitting twice.. who cares.
k, v = var.split('=')
env.update({k: v})
return env |
<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_service_name_from_command(self, cmd):
"""Set the name of a service according to the command. This is only relevant if the name wasn't explicitly provide... |
# TODO: Consider assign incremental integers to the name if a service
# with the same name already exists.
name = os.path.basename(cmd)
logger.info(
'Service name not supplied. Assigning name according to '
'executable: %s', name)
return 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 generate(self, cmd, name='', overwrite=False, deploy=False, start=False, **params):
"""Generate service files and returns a list of the generated files. It w... |
# TODO: parsing env vars and setting the name should probably be under
# `base.py`.
name = name or self._set_service_name_from_command(cmd)
self.params.update(**params)
self.params.update(dict(
cmd=cmd,
name=name,
env=self._parse_service_env_v... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove(self, name):
"""Remove a service completely. It will try to stop the service and then uninstall it. The implementation is, of course, system specific.... |
init = self._get_implementation(name)
self._assert_service_installed(init, name)
logger.info('Removing %s service %s...', self.init_system, name)
init.stop()
init.uninstall()
logger.info('Service removed') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def status(self, name=''):
"""Return a list containing a single service's info if `name` is supplied, else returns a list of all services' info. """ |
logger.warn(
'Note that `status` is currently not so robust and may break on '
'different systems')
init = self._get_implementation(name)
if name:
self._assert_service_installed(init, name)
logger.info('Retrieving status...')
return init.statu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop(self, name):
"""Stop a service """ |
init = self._get_implementation(name)
self._assert_service_installed(init, name)
logger.info('Stopping service: %s...', name)
init.stop() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def restart(self, name):
"""Restart a service """ |
init = self._get_implementation(name)
self._assert_service_installed(init, name)
logger.info('Restarting service: %s...', name)
init.stop()
# Here we would use status to verify that the service stopped
# before restarting. If only status was stable. eh..
# The ar... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lookup_init_systems(self):
"""Return the relevant init system and its version. This will try to look at the mapping first. If the mapping doesn't exist, it w... |
if utils.IS_WIN:
logger.debug(
'Lookup is not supported on Windows. Assuming nssm...')
return ['nssm']
if utils.IS_DARWIN:
logger.debug(
'Lookup is not supported on OS X, Assuming launchd...')
return ['launchd']
lo... |
<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_sys_auto_lookup(self):
"""Return a list of tuples of available init systems on the current machine. Note that in some situations (Ubuntu 14.04 for inst... |
# TODO: Instead, check for executables for systemd and upstart
# systemctl for systemd and initctl for upstart.
# An alternative might be to check the second answer here:
# http://unix.stackexchange.com/questions/196166/how-to-find-out-if-a-system-uses-sysv-upstart-or-systemd-initsystem... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _lookup_by_mapping():
"""Return a the init system based on a constant mapping of distribution+version to init system.. See constants.py for the mapping. A fa... |
like = distro.like().lower()
distribution_id = distro.id().lower()
version = distro.major_version()
if 'arch' in (distribution_id, like):
version = 'any'
init_sys = constants.DIST_TO_INITSYS.get(
distribution_id, constants.DIST_TO_INITSYS.get(like))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def all_files(file_or_directory):
'return all files under file_or_directory.'
if os.path.isdir(file_or_directory):
return [os.path.join(dirname, filename)
for dirname, dirnames, filenames in os.walk(file_or_directory)
for filename in filenames]
else:
return [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 add_context(request):
""" Add variables to all dictionaries passed to templates. """ |
# Whether the user has president privileges
try:
PRESIDENT = Manager.objects.filter(
incumbent__user=request.user,
president=True,
).count() > 0
except TypeError:
PRESIDENT = False
# If the user is logged in as an anymous user
if request.user.usernam... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def landing_view(request):
''' The external landing.'''
revision = None
can_edit = False
edit_url = None
if "farnswiki" in settings.INSTALLED_APPS:
from wiki.models import Page
from wiki.hooks import hookset
binder = settings.WIKI_BINDERS[0]
wiki = binder.lookup()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def my_profile_view(request):
''' The view of the profile page. '''
page_name = "Profile Page"
if request.user.username == ANONYMOUS_USERNAME:
return red_home(request, MESSAGES['SPINELESS'])
userProfile = UserProfile.objects.get(user=request.user)
change_password_form = PasswordChangeForm(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def notifications_view(request):
""" Show a user their notifications. """ |
page_name = "Your Notifications"
# Copy the notifications so that they are still unread when we render the page
notifications = list(request.user.notifications.all())
request.user.notifications.mark_all_as_read()
return render_to_response("list_notifications.html", {
"page_name": page_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 login_view(request):
''' The view of the login page. '''
ANONYMOUS_SESSION = request.session.get('ANONYMOUS_SESSION', False)
page_name = "Login Page"
redirect_to = request.GET.get('next', reverse('homepage'))
if (request.user.is_authenticated() and not ANONYMOUS_SESSION) or (ANONYMOUS_SESSION an... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def member_profile_view(request, targetUsername):
''' View a member's Profile. '''
if targetUsername == request.user.username and targetUsername != ANONYMOUS_USERNAME:
return HttpResponseRedirect(reverse('my_profile'))
page_name = "{0}'s Profile".format(targetUsername)
targetUser = get_object_or... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def request_profile_view(request):
''' The page to request a user profile on the site. '''
page_name = "Profile Request Page"
redirect_to = request.GET.get('next', reverse('homepage'))
if request.user.is_authenticated() and request.user.username != ANONYMOUS_USERNAME:
return HttpResponseRedirect... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def manage_profile_requests_view(request):
''' The page to manage user profile requests. '''
page_name = "Admin - Manage Profile Requests"
profile_requests = ProfileRequest.objects.all()
return render_to_response('manage_profile_requests.html', {
'page_name': page_name,
'choices': UserPr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def custom_add_user_view(request):
''' The page to add a new user. '''
page_name = "Admin - Add User"
add_user_form = AddUserForm(request.POST or None, initial={
'status': UserProfile.RESIDENT,
})
if add_user_form.is_valid():
add_user_form.save()
message = MESSAGES['USER_... |
<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_pw_confirm_view(request, uidb64=None, token=None):
""" View to confirm resetting password. """ |
return password_reset_confirm(request,
template_name="reset_confirmation.html",
uidb64=uidb64, token=token, post_reset_redirect=reverse('login')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def recount_view(request):
""" Recount number_of_messages for all threads and number_of_responses for all requests. Also set the change_date for every thread to ... |
requests_changed = 0
for req in Request.objects.all():
recount = Response.objects.filter(request=req).count()
if req.number_of_responses != recount:
req.number_of_responses = recount
req.save()
requests_changed += 1
threads_changed = 0
for thread in T... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def archives_view(request):
""" View of the archives page. """ |
page_name = "Archives"
nodes, render_list = [], []
for add_context_str in settings.BASE_ARCHIVE_FUNCTIONS:
module, fun = add_context_str.rsplit(".", 1)
add_context_fun = getattr(import_module(module), fun)
# add_context should return list of (title, url icon, number)
node_ls... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect(self):
if self._sStatus != 'opened': print "Netconf Connection: Invalid Status, Could not connect to %s:%s" % (self._sHost, self._uPort) sys.exit() #... | null |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _index_idiom(el_name, index, alt=None):
""" Generate string where `el_name` is indexed by `index` if there are enough items or `alt` is returned. Args: el_na... |
el_index = "%s[%d]" % (el_name, index)
if index == 0:
cond = "%s" % el_name
else:
cond = "len(%s) - 1 >= %d" % (el_name, index)
output = IND + "# pick element from list\n"
return output + IND + "%s = %s if %s else %s\n\n" % (
el_name,
el_index,
cond,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _required_idiom(tag_name, index, notfoundmsg):
""" Generate code, which make sure that `tag_name` has enoug items. Args: tag_name (str):
Name of the contain... |
cond = ""
if index > 0:
cond = " or len(el) - 1 < %d" % index
tag_name = str(tag_name)
output = IND + "if not el%s:\n" % cond
output += IND + IND + "raise UserWarning(\n"
output += IND + IND + IND + "%s +\n" % repr(notfoundmsg.strip() + "\n")
output += IND + IND + IND + repr("Tag ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _neigh_template(parameters, index, left=True, required=False, notfoundmsg=None):
""" Generate neighbour matching call for HTMLElement, which returns only ele... |
fn_string = "has_neigh(%s, left=%s)" % (
repr(parameters.fn_params)[1:-1],
repr(left)
)
output = IND + "el = dom.find(\n"
output += IND + IND + "%s,\n" % repr(parameters.tag_name)
if parameters.params:
output += IND + IND + "%s,\n" % repr(parameters.params)
output += ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _generate_parser(name, path, required=False, notfoundmsg=None):
""" Generate parser named `name` for given `path`. Args: name (str):
Basename for the parsin... |
output = "def %s(dom):\n" % _get_parser_name(name)
dom = True # used specifically in _wfind_template
parser_table = {
"find": lambda path:
_find_template(path.params, path.index, required, notfoundmsg),
"wfind": lambda path:
_wfind_template(
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 generate_parsers(config, paths):
""" Generate parser for all `paths`. Args: config (dict):
Original configuration dictionary used to get matches for unittes... |
output = """#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interpreter version: python 2.7
#
# HTML parser generated by Autoparser
# (https://github.com/edeposit/edeposit.amqp.harvester)
#
import os
import os.path
import httpkie
import dhtmlparser
# Utilities
"""
# add source of neighbour picking functi... |
<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_config(path):
"""Load the config value from various arguments.""" |
config = ConfigParser()
if len(config.read(path)) == 0:
stderr_and_exit("Couldn't load config {0}\n".format(path))
if not config.has_section('walls'):
stderr_and_exit('Config missing [walls] section.\n')
# Print out all of the missing keys
keys = ['api_key', 'api_secret', 'tags', ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clear_dir(path):
"""Empty out the image directory.""" |
for f in os.listdir(path):
f_path = os.path.join(path, f)
if os.path.isfile(f_path) or os.path.islink(f_path):
os.unlink(f_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 smallest_url(flickr, pid, min_width, min_height):
"""Return the url of the smallest photo above the dimensions. If no such photo exists, return None. """ |
sizes = flickr.photos_getSizes(photo_id=pid, format='parsed-json')
smallest_url = None
smallest_area = None
for size in sizes['sizes']['size']:
width = int(size['width'])
height = int(size['height'])
# Enforce a minimum height and width
if width >= min_width and height >... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download(url, dest):
"""Download the image to disk.""" |
path = os.path.join(dest, url.split('/')[-1])
r = requests.get(url, stream=True)
r.raise_for_status()
with open(path, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
return 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 run(config, clear_opt=False):
"""Find an image and download it.""" |
flickr = flickrapi.FlickrAPI(config.get('walls', 'api_key'),
config.get('walls', 'api_secret'))
width = config.getint('walls', 'width')
height = config.getint('walls', 'height')
# Clear out the destination dir
if clear_opt:
clear_dir(os.path.expanduser(conf... |
<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(args=sys.argv):
"""Parse the arguments, and pass the config object on to run.""" |
# Don't make changes to sys.argv
args = list(args)
# Remove arg[0]
args.pop(0)
# Pop off the options
clear_opt = False
if '-c' in args:
args.remove('-c')
clear_opt = True
elif '--clear' in args:
args.remove('--clear')
clear_opt = True
if len(args) ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(pipeline, input_gen, options={}):
""" Run a pipeline over a input generator a b c d e it is also possible to run any reliure pipeline this way: A B C D E... |
logger = logging.getLogger("reliure.run")
t0 = time()
res = [output for output in pipeline(input_gen, **options)]
logger.info("Pipeline executed in %1.3f sec" % (time() - t0))
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_parallel(pipeline, input_gen, options={}, ncpu=4, chunksize=200):
""" Run a pipeline in parallel over a input generator cutting it into small chunks. """ |
t0 = time()
#FIXME: there is a know issue when pipeline results are "big" object, the merge is bloking... to be investigate
#TODO: add get_pipeline args to prodvide a fct to build the pipeline (in each worker)
logger = logging.getLogger("reliure.run_parallel")
jobs = []
results = []
Qdata =... |
<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():
""" Small run usage exemple """ |
#TODO: need to be mv in .rst doc
from reliure.pipeline import Composable
@Composable
def doc_analyse(docs):
for doc in docs:
yield {
"title": doc,
"url": "http://lost.com/%s" % doc,
}
@Composable
def print_ulrs(docs):
for 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 el_to_path_vector(el):
""" Convert `el` to vector of foregoing elements. Attr: el (obj):
Double-linked HTMLElement instance. Returns: list: HTMLElements whi... |
path = []
while el.parent:
path.append(el)
el = el.parent
return list(reversed(path + [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 common_vector_root(vec1, vec2):
""" Return common root of the two vectors. Args: vec1 (list/tuple):
First vector. vec2 (list/tuple):
Second vector. Usage e... |
root = []
for v1, v2 in zip(vec1, vec2):
if v1 == v2:
root.append(v1)
else:
return root
return root |
<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_common_root(elements):
""" Find root which is common for all `elements`. Args: elements (list):
List of double-linked HTMLElement objects. Returns: lis... |
if not elements:
raise UserWarning("Can't find common root - no elements suplied.")
root_path = el_to_path_vector(elements.pop())
for el in elements:
el_path = el_to_path_vector(el)
root_path = common_vector_root(root_path, el_path)
if not root_path:
raise Us... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instantiateSong(fileName):
"""Create an AudioSegment with the data from the given file""" |
ext = detectFormat(fileName)
if(ext == "mp3"):
return pd.AudioSegment.from_mp3(fileName)
elif(ext == "wav"):
return pd.AudioSegment.from_wav(fileName)
elif(ext == "ogg"):
return pd.AudioSegment.from_ogg(fileName)
elif(ext == "flv"):
return pd.AudioSegment.from_flv(fi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def findGap(song):
"""Return the position of silence in a song""" |
try:
silence = pd.silence.detect_silence(song)
except IOError:
print("There isn't a song there!")
maxlength = 0
for pair in silence:
length = pair[1] - pair[0]
if length >= maxlength:
maxlength = length
gap = pair
return gap |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def splitSong(songToSplit, start1, start2):
"""Split a song into two parts, one starting at start1, the other at start2""" |
print "start1 " + str(start1)
print "start2 " + str(start2)
# songs = [songToSplit[:start1+2000], songToSplit[start2-2000:]]
songs = [songToSplit[:start1], songToSplit[start2:]]
return songs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def trackSeek(path, artist, album, track, trackNum, fmt):
"""Actually runs the program""" |
hiddenName = "(Hidden Track).{}".format(fmt)
trackName = track + ".{}".format(fmt)
songIn = instantiateSong(path)
times = findGap(songIn)
saveFiles(trackName, hiddenName, splitSong(songIn, times[0], times[1]), artist, album, trackNum)
# return [path, track.rsplit('/',1)[0] +'/{}'.format(hiddenN... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parseArgs():
"""Parses arguments passed in via the command line""" |
parser = argparse.ArgumentParser()
parser.add_argument("name", help="the file you want to split")
parser.add_argument("out1", help="the name of the first file you want to output")
parser.add_argument("out2", help="the name of the second file you want to output")
return parser.parse_args() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _sub_resource(self, path):
""" get or create sub resource """ |
if path not in self.resource_map:
self.resource_map[path] = Resource(
path, self.fetch, self.resource_map,
default_headers=self.default_headers)
return self.resource_map[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 prepare_request(self, *args, **kw):
""" creates a full featured HTTPRequest objects """ |
self.http_request = self.request_class(self.path, *args, **kw) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def token(self):
""" get the token """ |
header = self.default_headers.get('Authorization', '')
prefex = 'Bearer '
if header.startswith(prefex):
token = header[len(prefex):]
else:
token = header
return token |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _request(self):
""" retrieve the caller frame, extract the parameters from the caller function, find the matching function, and fire the request """ |
caller_frame = inspect.getouterframes(inspect.currentframe())[1]
args, _, _, values = inspect.getargvalues(caller_frame[0])
caller_name = caller_frame[3]
kwargs = {arg: values[arg] for arg in args if arg != 'self'}
func = reduce(
lambda resource, name: resource.__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 listdir(dir_name, get_dirs=None, get_files=None, hide_ignored=False):
""" Return list of all dirs and files inside given dir. Also can filter contents to ret... |
if get_dirs is None and get_files is None:
get_dirs = True
get_files = True
source_dir = os.path.join(settings.BASE_DIR, 'app', dir_name)
dirs = []
for dir_or_file_name in os.listdir(source_dir):
path = os.path.join(source_dir, dir_or_file_name)
if hide_ignored and di... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_types(obj, **kwargs):
"""Get the types of an iterable.""" |
max_iterable_length = kwargs.get('max_iterable_length', 100000)
it, = itertools.tee(obj, 1)
s = set()
too_big = False
for i, v in enumerate(it):
if i <= max_iterable_length:
s.add(type(v))
else:
too_big = True
break
return {"types": s, "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 encrypt_text(self, text, *args, **kwargs):
""" Encrypt a string. input: unicode str, output: unicode str """ |
b = text.encode("utf-8")
token = self.encrypt(b, *args, **kwargs)
return base64.b64encode(token).decode("utf-8") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decrypt_text(self, text, *args, **kwargs):
""" Decrypt a string. input: unicode str, output: unicode str """ |
b = text.encode("utf-8")
token = base64.b64decode(b)
return self.decrypt(token, *args, **kwargs).decode("utf-8") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _show(self, message, indent=0, enable_verbose=True):
# pragma: no cover """Message printer. """ |
if enable_verbose:
print(" " * indent + message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encrypt_dir(self, path, output_path=None, overwrite=False, stream=True, enable_verbose=True):
""" Encrypt everything in a directory. :param path: path of the... |
path, output_path = files.process_dst_overwrite_args(
src=path, dst=output_path, overwrite=overwrite,
src_to_dst_func=files.get_encrpyted_path,
)
self._show("--- Encrypt directory '%s' ---" % path,
enable_verbose=enable_verbose)
st = time.cloc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def schema_map(schema):
"""Return a valid ICachedItemMapper.map for schema""" |
mapper = {}
for name in getFieldNames(schema):
mapper[name] = name
return mapper |
<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_docstring(filename, verbose=False):
""" Search for assignment of the DOCUMENTATION variable in the given file. Parse that from YAML and return the YAML d... |
doc = None
try:
# Thank you, Habbie, for this bit of code :-)
M = ast.parse(''.join(open(filename)))
for child in M.body:
if isinstance(child, ast.Assign):
if 'DOCUMENTATION' in (t.id for t in child.targets):
doc = yaml.load(child.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 _normalize_params(image, width, height, crop):
""" Normalize params and calculate aspect. """ |
if width is None and height is None:
raise ValueError("Either width or height must be set. Otherwise "
"resizing is useless.")
if width is None or height is None:
aspect = float(image.width) / float(image.height)
if crop:
raise ValueError("Cropping... |
<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_resized_name(image, width, height, crop, namespace):
""" Get the name of the resized file when assumed it exists. """ |
path, name = os.path.split(image.name)
name_part = "%s/%ix%i" % (namespace, width, height)
if crop:
name_part += "_cropped"
return os.path.join(path, name_part, 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 _resize(image, width, height, crop):
""" Resize the image with respect to the aspect ratio """ |
ext = os.path.splitext(image.name)[1].strip(".")
with Image(file=image, format=ext) as b_image:
# Account for orientation
if ORIENTATION_TYPES.index(b_image.orientation) > 4:
# Flip
target_aspect = float(width) / float(height)
aspect = float(b_image.height) ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resize(image, width=None, height=None, crop=False):
""" Resize an image and return the resized file. """ |
# First normalize params to determine which file to get
width, height, crop = _normalize_params(image, width, height, crop)
try:
# Check the image file state for clean close
is_closed = image.closed
if is_closed:
image.open()
# Create the resized file
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resize_lazy(image, width=None, height=None, crop=False, force=False, namespace="resized", storage=default_storage, as_url=False):
""" Returns the name of the... |
# First normalize params to determine which file to get
width, height, crop = _normalize_params(image, width, height, crop)
# Fetch the name of the resized image so i can test it if exists
name = _get_resized_name(image, width, height, crop, namespace)
# Fetch storage if an image has a specific st... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resized(*args, **kwargs):
""" Auto file closing resize function """ |
resized_image = None
try:
resized_image = resize(*args, **kwargs)
yield resized_image
finally:
if resized_image is not None:
resized_image.close() |
<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_package(repo_url, pkg_name, timeout=1):
"""Retrieve package information from a Bower registry at repo_url. Returns a dict of package data.""" |
url = repo_url + "/packages/" + pkg_name
headers = {'accept': 'application/json'}
resp = requests.get(url, headers=headers, timeout=timeout)
if resp.status_code == 404:
return None
return resp.json() |
<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_commit(profile, sha):
"""Fetch a commit. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (... |
resource = "/commits/" + sha
data = api.get_request(profile, resource)
return prepare(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 create_commit(profile, message, tree, parents):
"""Create a commit. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such prof... |
resource = "/commits"
payload = {"message": message, "tree": tree, "parents": parents}
data = api.post_request(profile, resource, payload)
return prepare(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 collect_publications(self):
""" Recursively collect list of all publications referenced in this tree and all sub-trees. Returns: list: List of UUID strings. ... |
pubs = list(self.sub_publications)
for sub_tree in self.sub_trees:
pubs.extend(sub_tree.collect_publications())
return pubs |
<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_option(option_name, section_name="main", default=_sentinel, cfg_file=cfg_file):
""" Returns a specific option specific in a config file Arguments: option... |
defaults = get_defaults()
# As a quality issue, we strictly disallow looking up an option that does not have a default
# value specified in the code
#if option_name not in defaults.get(section_name, {}) and default == _sentinel:
# raise ValueError("There is no default value for Option %s in 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 set_option(section='main', cfg_file=cfg_file, **kwargs):
""" Change an option in our configuration file """ |
parser = get_parser(cfg_file=cfg_file)
if section not in parser.sections():
parser.add_section(section)
for k, v in kwargs.items():
parser.set(section=section, option=k, value=v)
with open(cfg_file, 'w') as f:
parser.write(f)
return "Done" |
<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_section(section_name, cfg_file=cfg_file):
""" Returns a dictionary of an entire section """ |
parser = get_parser(cfg_file=cfg_file)
options = parser.options(section_name)
result = {}
for option in options:
result[option] = parser.get(section=section_name, option=option)
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 _mkdir_for_config(cfg_file=cfg_file):
""" Given a path to a filename, make sure the directory exists """ |
dirname, filename = os.path.split(cfg_file)
try:
os.makedirs(dirname)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(dirname):
pass
else:
raise |
<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_configfile(cfg_file,defaults=defaults):
""" Write a new nago.ini config file from the defaults. Arguments: cfg_file -- File that is written to like ... |
# Create a directory if needed and write an empty file
_mkdir_for_config(cfg_file=cfg_file)
with open(cfg_file, 'w') as f:
f.write('')
for section in defaults.keys():
set_option(section, cfg_file=cfg_file, **defaults[section]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def strip_commands(commands):
""" Strips a sequence of commands. Strips down the sequence of commands by removing comments and surrounding whitespace around each... |
# Go through each command one by one, stripping it and adding it to
# a growing list if it is not blank. Each command needs to be
# converted to an str if it is a bytes.
stripped_commands = []
for v in commands:
if isinstance(v, bytes):
v = v.decode(errors='replace')
v =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def startup(request):
""" This view provides initial data to the client, such as available skills and causes """ |
with translation.override(translation.get_language_from_request(request)):
skills = serializers.SkillSerializer(models.Skill.objects.all(), many=True)
causes = serializers.CauseSerializer(models.Cause.objects.all(), many=True)
cities = serializers.GoogleAddressCityStateSerializer(models.GoogleAddress.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 _line_is_shebang(line):
"""Return true if line is a shebang.""" |
regex = re.compile(r"^(#!|@echo off).*$")
if regex.match(line):
return True
return 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 _filename_in_headerblock(relative_path, contents, linter_options):
"""Check for a filename in a header block. like such: # /path/to/filename """ |
del linter_options
check_index = 0
if len(contents) > 0:
if _line_is_shebang(contents[0]):
check_index = 1
if len(contents) < check_index + 1:
description = ("""Document cannot have less than """
"""{0} lines""").format(check_index + 1)
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 _match_space_at_line(line):
"""Return a re.match object if an empty comment was found on line.""" |
regex = re.compile(r"^{0}$".format(_MDL_COMMENT))
return regex.match(line) |
<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_last_line_index(contents):
"""Find the last line of the headerblock in contents.""" |
lineno = 0
headerblock = re.compile(r"^{0}.*$".format(_ALL_COMMENT))
if not len(contents):
raise RuntimeError("""File does not not have any contents""")
while headerblock.match(contents[lineno]):
if lineno + 1 == len(contents):
raise RuntimeError("""No end of headerblock i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _copyright_end_of_headerblock(relative_path, contents, linter_options):
"""Check for copyright notice at end of headerblock.""" |
del relative_path
del linter_options
lineno = _find_last_line_index(contents)
notice = "See /LICENCE.md for Copyright information"
regex = re.compile(r"^{0} {1}( .*$|$)".format(_MDL_COMMENT, notice))
if not regex.match(contents[lineno]):
description = ("""The last of the header block l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _populate_spelling_error(word, suggestions, contents, line_offset, column_offset, message_start):
"""Create a LinterFailure for word. This function takes sug... |
error_line = contents[line_offset]
if len(suggestions):
char_word_offset = (column_offset + len(word))
replacement = (error_line[:column_offset] +
suggestions[0] +
error_line[char_word_offset:])
else:
replacement = None
if len(sugge... |
<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_spelling_errors_in_chunks(chunks, contents, valid_words_dictionary=None, technical_words_dictionary=None, user_dictionary_words=None):
"""For each chun... |
for chunk in chunks:
for error in spellcheck_region(chunk.data,
valid_words_dictionary,
technical_words_dictionary,
user_dictionary_words):
col_offset = _determine_character_offs... |
<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_technical_words_dictionary(spellchecker_cache_path, relative_path, user_words, shadow):
"""Create Dictionary at spellchecker_cache_path with technica... |
technical_terms_set = (user_words |
technical_words_from_shadow_contents(shadow))
technical_words = Dictionary(technical_terms_set,
"technical_words_" +
relative_path.replace(os.path.sep, "_"),
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _construct_user_dictionary(global_options, tool_options):
"""Cause dictionary with valid and user words to be cached on disk.""" |
del global_options
spellchecker_cache_path = tool_options.get("spellcheck_cache", None)
valid_words_dictionary_helper.create(spellchecker_cache_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 _drain(queue_to_drain, sentinel=None):
"""Remove all values from queue_to_drain and return as list. This uses the trick from http://stackoverflow.com/questio... |
queue_to_drain.put(sentinel)
queued_items = [i for i in iter(queue_to_drain.get, None)]
return queued_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 _maybe_log_technical_terms(global_options, tool_options):
"""Log technical terms as appropriate if the user requested it. As a side effect, if --log-technica... |
log_technical_terms_to_path = global_options.get("log_technical_terms_to",
None)
log_technical_terms_to_queue = tool_options.get("log_technical_terms_to",
None)
if log_technical_terms_to_path:
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 _no_spelling_errors(relative_path, contents, linter_options):
"""No spelling errors in strings, comments or anything of the like.""" |
block_regexps = linter_options.get("block_regexps", None)
chunks, shadow = spellcheckable_and_shadow_contents(contents,
block_regexps)
cache = linter_options.get("spellcheck_cache", None)
user_words, valid_words = valid_words_dictionary_helper.cre... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _line_suppresses_error_code(line, code):
"""Check if line contains necessary content to suppress code. A line suppresses code if it is in the format suppress... |
match = re.compile(r"suppress\((.*)\)").match(line)
if match:
codes = match.group(1).split(",")
return code in codes
return 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 _error_is_suppressed(error, code, contents):
"""Return true if error is suppressed by an inline suppression.""" |
if len(contents) == 0:
return False
if error.line > 1:
# Check above, and then to the side for suppressions
above = contents[error.line - 2].split("#")
if len(above) and _line_suppresses_error_code(above[-1].strip(),
code):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.