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 ```True`` and they're signing up, or when they reset a lost password. The ``verification_type`` arg is both the name of the urlpattern for the verification link, as well as the names of the email templates to use. """ |
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_template_name = "email/%s_subject.txt" % verification_type
subject = subject_template(subject_template_name, context)
send_mail_template(subject, "email/%s" % verification_type,
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 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 ``ACCOUNTS_APPROVAL_REQUIRED`` setting is ``True``. """ |
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.txt", context)
send_mail_template(subject, "email/account_approve",
settings.DEFAULT_FROM_EMAIL, approval_emails,
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 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_REQUIRED`` setting is ``True``. """ |
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
file.write("\n") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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' and 'request' field """ |
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 : [HOST=' + hostname + ', QUEUE=' + queue + ']')
done = False
attempts = 0
while not done and attempts < 100:
try:
credentials = pika.PlainCredentials(user, password)
con = pika.BlockingConnection(pika.ConnectionParameters(
host=hostname,
port=port,
virtual_host=virtual_host,
credentials=credentials
))
channel = con.channel()
channel.queue_declare(queue=queue, durable=True)
req = request['request']
logging.info('Run : [EXPERIMENT=' + req['experiment_id'] + ', RUN=' + req['run_id'] + ']')
channel.basic_publish(
exchange='',
routing_key=queue,
body=json.dumps(req),
properties=pika.BasicProperties(
delivery_mode = 2, # make message persistent
)
)
con.close()
done = True
except pika.exceptions.ConnectionClosed as ex:
attempts += 1
logging.exception(ex) |
<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 + \
``photon`` (:file:`~/.config/photon`)
* 'data_dir': The :envvar:`XDG_DATA_HOME`-directory + \
``photon`` (:file:`~/.local/share/photon`)
.. note::
* Both :func:`search_location` and :func:`make_locations` \
have the argument `locations`.
* |param_locations_none|
'''
home_dir = _path.expanduser('~')
conf_dir = _path.join(
_environ.get(
'XDG_CONFIG_HOME',
_path.join(home_dir, '.config')
),
IDENT
)
data_dir = _path.join(
_environ.get(
'XDG_DATA_HOME',
_path.join(home_dir, '.local', 'share')
),
IDENT
)
return {
'home_dir': home_dir,
'call_dir': _path.dirname(_path.abspath(_argv[0])),
'conf_dir': conf_dir,
'data_dir': data_dir
} |
<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 written in the same \
folder like `src` resides in
* Otherwise the specified path will be used.
'''
from photon.util.system import get_timestamp
src = _path.realpath(src)
if not loc or not loc.startswith(_sep):
loc = _path.dirname(src)
pth = _path.join(_path.basename(src), _path.realpath(loc))
out = '%s_backup_%s' % (_path.basename(src), get_timestamp())
change_location(src, search_location(out, create_in=pth)) |
<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 provided. Note that this is risky as it sets the name according to the name of the file the command is using. If two services use the same binary, even if their args are different, they will be named the same. """ |
# 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 will generate configuration file(s) for the service and deploy them to the tmp dir on your os. If `deploy` is True, the service will be configured to run on the current machine. If `start` is True, the service will be started as well. """ |
# 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_vars(params.get('var', '')))
)
if 'var' in params:
self.params.pop('var')
init = self.implementation(logger=logger, **self.params)
logger.info(
'Generating %s files for service %s...',
self.init_system, name)
files = init.generate(overwrite=overwrite)
for f in files:
logger.info('Generated %s', f)
if deploy or start:
init.validate_platform()
logger.info('Deploying %s service %s...', self.init_system, name)
init.install()
if start:
logger.info(
'Starting %s service %s...',
self.init_system, name)
init.start()
logger.info('Service created')
return files |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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. For instance, for upstart, it will `stop <name` and then delete /etc/init/<name>.conf. """ |
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.status(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 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 arbitrarity of this sleep time is making me sick...
time.sleep(3)
init.start() |
<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 will try to identify it automatically. Windows lookup is not supported and `nssm` is assumed. """ |
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']
logger.debug('Looking up init method...')
return self._lookup_by_mapping() \
or self._init_sys_auto_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 _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 instance) more than one init system can be found. """ |
# 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
# TODO: Move to each system's implementation
init_systems = []
if self._is_init_system_installed('/usr/lib/systemd'):
init_systems.append('systemd')
if self._is_init_system_installed('/usr/share/upstart'):
init_systems.append('upstart')
if self._is_init_system_installed('/etc/init.d'):
init_systems.append('sysv')
return init_systems |
<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 failover of the version is proposed for when no version is supplied. For instance, Arch Linux's version will most probably be "rolling" at any given time, which means that the init system cannot be idenfied by the version of the distro. On top of trying to identify by the distro's ID, if /etc/os-release contains an "ID_LIKE" field, it will be tried. That, again is true But the "ID_LIKE" field is always (?) `arch`. """ |
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))
if init_sys:
system = init_sys.get(version)
return [system] if system else [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def 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 [file_or_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 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.username == ANONYMOUS_USERNAME:
request.session["ANONYMOUS_SESSION"] = True
ANONYMOUS_SESSION = request.session.get("ANONYMOUS_SESSION", False)
# A list with items of form (RequestType, number_of_open_requests)
request_types = list()
if request.user.is_authenticated():
for request_type in RequestType.objects.filter(enabled=True):
requests = Request.objects.filter(
request_type=request_type,
status=Request.OPEN,
)
if not request_type.managers.filter(incumbent__user=request.user):
requests = requests.exclude(
~Q(owner__user=request.user),
private=True,
)
request_types.append((request_type, requests.count()))
profile_requests_count = ProfileRequest.objects.all().count()
admin_unread_count = profile_requests_count
return {
"REQUEST_TYPES": request_types,
"HOUSE": settings.HOUSE_NAME,
"ANONYMOUS_USERNAME": ANONYMOUS_USERNAME,
"SHORT_HOUSE": settings.SHORT_HOUSE_NAME,
"ADMIN": settings.ADMINS[0],
"NUM_OF_PROFILE_REQUESTS": profile_requests_count,
"ADMIN_UNREAD_COUNT": admin_unread_count,
"ANONYMOUS_SESSION": ANONYMOUS_SESSION,
"PRESIDENT": PRESIDENT,
} |
<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()
try:
if wiki:
page = wiki.pages.get(slug="landing")
else:
page = Page.objects.get(slug="landing")
except (Page.DoesNotExist, Page.MultipleObjectsReturned):
can_edit = hookset.can_create_page(wiki, request.user, slug="landing")
edit_url = binder.page_url(wiki, "landing")
else:
revision = page.revisions.latest()
can_edit = hookset.can_edit_page(page, request.user)
edit_url = page.get_edit_url()
return render_to_response('external.html', {
"page_name": "Landing",
"revision": revision,
"can_edit": can_edit,
"edit_url": edit_url,
}, context_instance=RequestContext(request)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def 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(
request.user,
request.POST if "submit_password_form" in request.POST else None,
)
update_email_form = UpdateEmailForm(
request.POST if "submit_profile_form" in request.POST else None,
instance=request.user,
prefix="user",
)
update_profile_form = UpdateProfileForm(
request.POST if "submit_profile_form" in request.POST else None,
instance=userProfile,
prefix="profile",
)
if change_password_form.is_valid():
change_password_form.save()
messages.add_message(request, messages.SUCCESS,
"Your password was successfully changed.")
return HttpResponseRedirect(reverse('my_profile'))
if update_email_form.is_valid() and update_profile_form.is_valid():
update_email_form.save()
update_profile_form.save()
messages.add_message(request, messages.SUCCESS,
"Your profile has been successfully updated.")
return HttpResponseRedirect(reverse('my_profile'))
return render_to_response('my_profile.html', {
'page_name': page_name,
"update_email_form": update_email_form,
'update_profile_form': update_profile_form,
'change_password_form': change_password_form,
}, context_instance=RequestContext(request)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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,
"notifications": notifications,
}, context_instance=RequestContext(request)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def 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 and request.user.username != ANONYMOUS_USERNAME):
return HttpResponseRedirect(redirect_to)
form = LoginForm(request.POST or None)
if form.is_valid():
user = form.save()
login(request, user)
if ANONYMOUS_SESSION:
request.session['ANONYMOUS_SESSION'] = True
return HttpResponseRedirect(redirect_to)
elif request.method == "POST":
reset_url = request.build_absolute_uri(reverse('reset_pw'))
messages.add_message(request, messages.INFO,
MESSAGES['RESET_MESSAGE'].format(reset_url=reset_url))
return render_to_response('login.html', {
'page_name': page_name,
'form': form,
'oauth_providers': _get_oauth_providers(),
'redirect_to': redirect_to,
}, context_instance=RequestContext(request)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def 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_404(User, username=targetUsername)
targetProfile = get_object_or_404(UserProfile, user=targetUser)
number_of_threads = Thread.objects.filter(owner=targetProfile).count()
number_of_messages = Message.objects.filter(owner=targetProfile).count()
number_of_requests = Request.objects.filter(owner=targetProfile).count()
rooms = Room.objects.filter(current_residents=targetProfile)
prev_rooms = PreviousResident.objects.filter(resident=targetProfile)
return render_to_response('member_profile.html', {
'page_name': page_name,
'targetUser': targetUser,
'targetProfile': targetProfile,
'number_of_threads': number_of_threads,
'number_of_messages': number_of_messages,
'number_of_requests': number_of_requests,
"rooms": rooms,
"prev_rooms": prev_rooms,
}, context_instance=RequestContext(request)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def 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(redirect_to)
form = ProfileRequestForm(
request.POST or None,
)
if form.is_valid():
username = form.cleaned_data['username']
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
email = form.cleaned_data['email']
if User.objects.filter(username=username).count():
reset_url = request.build_absolute_uri(reverse('reset_pw'))
form_add_error(form, 'username',
MESSAGES["USERNAME_TAKEN"].format(username=username))
messages.add_message(request, messages.INFO,
MESSAGES['RESET_MESSAGE'].format(reset_url=reset_url))
elif User.objects.filter(email=email).count():
reset_url = request.build_absolute_uri(reverse('reset_pw'))
messages.add_message(request, messages.INFO,
MESSAGES['RESET_MESSAGE'].format(reset_url=reset_url))
form_add_error(form, "email", MESSAGES["EMAIL_TAKEN"])
elif ProfileRequest.objects.filter(first_name=first_name, last_name=last_name).count():
form_add_error(
form, '__all__',
MESSAGES["PROFILE_TAKEN"].format(first_name=first_name,
last_name=last_name))
elif User.objects.filter(first_name=first_name, last_name=last_name).count():
reset_url = request.build_absolute_uri(reverse('reset_pw'))
messages.add_message(request, messages.INFO, MESSAGES['PROFILE_REQUEST_RESET'].format(reset_url=reset_url))
else:
form.save()
messages.add_message(request, messages.SUCCESS, MESSAGES['PROFILE_SUBMITTED'])
if settings.SEND_EMAILS and (email not in settings.EMAIL_BLACKLIST):
submission_subject = SUBMISSION_SUBJECT.format(house=settings.HOUSE_NAME)
submission_email = SUBMISSION_EMAIL.format(house=settings.HOUSE_NAME, full_name=first_name + " " + last_name, admin_name=settings.ADMINS[0][0],
admin_email=settings.ADMINS[0][1])
try:
send_mail(submission_subject, submission_email, settings.EMAIL_HOST_USER, [email], fail_silently=False)
# Add logging here
except SMTPException:
pass # Add logging here
return HttpResponseRedirect(redirect_to)
return render(request, 'request_profile.html', {
'form': form,
'page_name': page_name,
'oauth_providers': _get_oauth_providers(),
'redirect_to': redirect_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 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': UserProfile.STATUS_CHOICES,
'profile_requests': profile_requests
}, context_instance=RequestContext(request)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def 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_ADDED'].format(
username=add_user_form.cleaned_data["username"])
messages.add_message(request, messages.SUCCESS, message)
return HttpResponseRedirect(reverse('custom_add_user'))
return render_to_response('custom_add_user.html', {
'page_name': page_name,
'add_user_form': add_user_form,
'members': User.objects.all().exclude(username=ANONYMOUS_USERNAME),
}, context_instance=RequestContext(request)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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 the post_date of the latest message associated with that thread. """ |
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 Thread.objects.all():
recount = Message.objects.filter(thread=thread).count()
if thread.number_of_messages != recount:
thread.number_of_messages = recount
thread.save()
threads_changed += 1
dates_changed = 0
for thread in Thread.objects.all():
if thread.change_date != thread.message_set.latest('post_date').post_date:
thread.change_date = thread.message_set.latest('post_date').post_date
thread.save()
dates_changed += 1
messages.add_message(request, messages.SUCCESS, MESSAGES['RECOUNTED'].format(
requests_changed=requests_changed,
request_count=Request.objects.all().count(),
threads_changed=threads_changed,
thread_count=Thread.objects.all().count(),
dates_changed=dates_changed,
))
return HttpResponseRedirect(reverse('utilities')) |
<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_lst, icon_list = add_context_fun(request)
nodes += node_lst
render_list += icon_list
return render_to_response('archives.html', {
"page_name": page_name,
"render_list": render_list,
"nodes": nodes,
}, context_instance=RequestContext(request)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect(self):
if self._sStatus != 'opened': print "Netconf Connection: Invalid Status, Could not connect to %s:%s" % (self._sHost, self._uPort) sys.exit() # establish ssh connection if self._sType == 'ssh': # setup transport connection base on socket self._hSsh = paramiko.Transport(self._iSock) try: self._hSsh.start_client() except paramiko.SSHException: print 'Netconf Connection: Connect negotiation failed' self._iSock.close() sys.exit() except: print 'Netconf Connection: Connect failed' try: self._iSock.close() except: pass sys.exit() # auth check if self._sPswd != '': try: self._hSsh.auth_password(self._sUser, self._sPswd) except: print "Netconf Connection: Auth SSH username/password fail" self._iSock.close() sys.exit() # open channel for netconf ssh subsystem try: self._hSshChn = self._hSsh.open_session() self._hSshChn.settimeout(5) self._hSshChn.set_name("netconf") self._hSshChn.invoke_subsystem("netconf") self._hSshChn.setblocking(1) except: print "Netconf Connection: Open SSH Netconf SubSystem fail" self._iSock.close() sys.exit() else: print "Netconf Connection: Unsupport Connection Type, Could not connect to %s:%s" % (self._sHost, self._uPort) sys.exit() self._sStatus = 'connected' """ end of function connect """ | 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_name (str):
Name of the `container` which is indexed. index (int):
Index of the item you want to obtain from container. alt (whatever, default None):
Alternative value. Returns: str: Python code. Live example:: # pick element from list xex = xex[0] if xex else None # pick element from list xex = xex[1] if len(xex) - 1 >= 1 else 'something' """ |
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,
repr(alt)
) |
<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 container. index (int):
Index of the item you want to obtain from container. notfoundmsg (str):
Raise :class:`.UserWarning` with debug data and following message. Returns: str: Python code. """ |
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 name: " + tag_name) + " + '\\n' +\n"
output += IND + IND + IND + "'El:' + str(el) + '\\n' +\n"
output += IND + IND + IND + "'Dom:' + str(dom)\n"
output += IND + IND + ")\n\n"
return output + IND + "el = el[%d]\n\n" % index |
<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 elements with required neighbours. Args: parameters (list):
List of parameters for ``.match()``. index (int):
Index of the item you want to get from ``.match()`` call. left (bool, default True):
Look for neigbour in the left side of el. required (bool, default False):
Use :func:`_required_idiom` to returned data. notfoundmsg (str, default None):
Message which will be used for :func:`_required_idiom` if the item is not found. Returns: str: Python code. """ |
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 += IND + IND + "fn=%s\n" % fn_string
output += IND + ")\n\n"
if required:
return output + _required_idiom(
parameters.fn_params[0],
index,
notfoundmsg
)
return output + _index_idiom("el", index) |
<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 parsing function (see :func:`_get_parser_name` for details). path (obj):
:class:`.PathCall` or :class:`.Chained` instance. required (bool, default False):
Use :func:`_required_idiom` to returned data. notfoundmsg (str, default None):
Message which will be used for :func:`_required_idiom` if the item is not found. Returns: str: Python code for parsing `path`. """ |
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,
path.params,
path.index,
required,
notfoundmsg
),
"match": lambda path:
_match_template(path.params, path.index, required, notfoundmsg),
"left_neighbour_tag": lambda path:
_neigh_template(
path.params,
path.index,
True,
required,
notfoundmsg
),
"right_neighbour_tag": lambda path:
_neigh_template(
path.params,
path.index,
False,
required,
notfoundmsg
),
}
if isinstance(path, path_patterns.PathCall):
output += parser_table[path.call_type](path)
elif isinstance(path, path_patterns.Chained):
for path in path.chain:
output += parser_table[path.call_type](path)
dom = False
else:
raise UserWarning(
"Unknown type of path parameters! (%s)" % str(path)
)
output += IND + "return el\n"
output += "\n\n"
return 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_parsers(config, paths):
""" Generate parser for all `paths`. Args: config (dict):
Original configuration dictionary used to get matches for unittests. See :mod:`~harvester.autoparser.conf_reader` for details. paths (dict):
Output from :func:`.select_best_paths`. Returns: str: Python code containing all parsers for `paths`. """ |
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 functions from utils.py
output += inspect.getsource(conf_reader._get_source) + "\n\n"
output += inspect.getsource(utils._get_encoding) + "\n\n"
output += inspect.getsource(utils.handle_encodnig) + "\n\n"
output += inspect.getsource(utils.is_equal_tag) + "\n\n"
output += inspect.getsource(utils.has_neigh) + "\n\n"
output += "# Generated parsers\n"
for name, path in paths.items():
path = path[0] # pick path with highest priority
required = config[0]["vars"][name].get("required", False)
notfoundmsg = config[0]["vars"][name].get("notfoundmsg", "")
output += _generate_parser(name, path, required, notfoundmsg)
output += "# Unittest\n"
output += _unittest_template(config)
output += "# Run tests of the parser\n"
output += "if __name__ == '__main__':\n"
output += IND + "test_parsers()"
return 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 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', 'image_dir', 'width', 'height']
for key in set(keys):
if config.has_option('walls', key):
keys.remove(key)
if keys:
stderr_and_exit("Missing config keys: '{0}'\n"
.format("', '".join(keys)))
# Parse integer values
int_keys = ['width', 'height']
for key in set(int_keys):
try:
config.getint('walls', key)
int_keys.remove(key)
except ValueError:
pass
if int_keys:
stderr_and_exit("The following must be integers: '{0}'\n"
.format("', '".join(int_keys)))
# Check destination directory
path = os.path.expanduser(config.get('walls', 'image_dir'))
if not os.path.isdir(path):
stderr_and_exit('The directory {0} does not exist.\n'
.format(config.get('walls', 'image_dir')))
return config |
<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 >= min_height:
if not smallest_url or height * width < smallest_area:
smallest_area = height * width
smallest_url = size['source']
return smallest_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 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(config.get('walls', 'image_dir')))
# Find an image
tags = config.get('walls', 'tags')
for photo in flickr.walk(tags=tags, format='etree'):
try:
photo_url = smallest_url(flickr, photo.get('id'), width, height)
if photo_url:
break
except (KeyError, ValueError, TypeError):
stderr_and_exit('Unexpected data from Flickr.\n')
else:
stderr_and_exit('No matching photos found.\n')
# Download the image
dest = os.path.expanduser(config.get('walls', 'image_dir'))
try:
download(photo_url, dest)
except IOError:
stderr_and_exit('Error downloading image.\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 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) == 0:
cfg_path = os.path.expanduser('~/.wallsrc')
elif len(args) == 1:
cfg_path = args[0]
else:
stderr_and_exit('Usage: walls [-c] [config_file]\n')
config = load_config(cfg_path)
run(config, clear_opt) |
<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 = mp.JoinableQueue(ncpu*2) # input queue
Qresult = mp.Queue() # result queue
# ensure input_gen is realy an itertor not a list
if hasattr(input_gen, "__len__"):
input_gen = iter(input_gen)
for wnum in range(ncpu):
logger.debug("create worker #%s" % wnum)
worker = mp.Process(target=_reliure_worker, args=(wnum, Qdata, Qresult, pipeline, options))
worker.start()
jobs.append(worker)
while True:
# consume chunksize elements from input_gen
chunk = tuple(islice(input_gen, chunksize))
if not len(chunk):
break
logger.info("send a chunk of %s elemets to a worker" % len(chunk))
Qdata.put(chunk)
logger.info("all data has beed send to workers")
# wait until all task are done
Qdata.join()
logger.debug("wait for workers...")
for worker in jobs:
worker.terminate()
logger.debug("merge results")
try:
while not Qresult.empty():
logger.debug("result queue still have %d elements" % Qresult.qsize())
res = Qresult.get_nowait()
results.append(res)
except mp.Queue.Empty:
logger.debug("result queue is empty")
pass
logger.info("Pipeline executed in %1.3f sec" % (time() - t0))
return results |
<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 doc in docs:
print(doc["url"])
yield doc
pipeline = doc_analyse | print_ulrs
documents = ("doc_%s" % d for d in xrange(20))
res = run_parallel(pipeline, documents, ncpu=2, chunksize=5)
print(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 el_to_path_vector(el):
""" Convert `el` to vector of foregoing elements. Attr: el (obj):
Double-linked HTMLElement instance. Returns: list: HTMLElements which considered as path from root to `el`. """ |
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 example:: [1, 2] Returns: list: Common part of two vectors or blank list. """ |
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: list: Vector of HTMLElement containing path to common root. """ |
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 UserWarning(
"Vectors without common root:\n%s" % str(el_path)
)
return root_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 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(fileName)
elif(ext == "m4a"):
return pd.AudioSegment.from_file(fileName, "mp4")
else:
return pd.AudioSegment.from_file(fileName, ext) |
<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(hiddenName)]
return [trackName, hiddenName] |
<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.__getattr__(name),
self.mappings[caller_name].split('.'), self)
return func(**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 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 return only dirs or files. Args: - dir_name: Which directory we need to scan (relative) - get_dirs: Return dirs list - get_files: Return files list - hide_ignored: Exclude files and dirs with initial underscore """ |
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 dir_or_file_name.startswith('_'):
continue
is_dir = os.path.isdir(path)
if get_dirs and is_dir or get_files and not is_dir:
dirs.append(dir_or_file_name)
return dirs |
<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, "too_big": too_big} |
<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 dir you need to encrypt :param output_path: encrypted dir output path :param overwrite: if True, then silently overwrite output file if exists :param stream: if it is a very big file, stream mode can avoid using too much memory :param enable_verbose: boolean, trigger on/off the help information """ |
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.clock()
for current_dir, _, file_list in os.walk(path):
new_dir = current_dir.replace(path, output_path)
if not os.path.exists(new_dir): # pragma: no cover
os.mkdir(new_dir)
for basename in file_list:
old_path = os.path.join(current_dir, basename)
new_path = os.path.join(new_dir, basename)
self.encrypt_file(old_path, new_path,
overwrite=overwrite,
stream=stream,
enable_verbose=enable_verbose)
self._show("Complete! Elapse %.6f seconds" % (time.clock() - st,),
enable_verbose=enable_verbose)
return output_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 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 doc or None. """ |
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.s)
except:
if verbose == True:
traceback.print_exc()
print "unable to parse %s" % filename
return doc |
<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 the image would be useless since only "
"one dimention is give to resize along.")
if width is None:
width = int(round(height * aspect))
else:
height = int(round(width / aspect))
return (width, height, crop) |
<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) / float(b_image.width)
else:
target_aspect = float(width) / float(height)
aspect = float(b_image.width) / float(b_image.height)
# Fix rotation
b_image.auto_orient()
# Calculate target size
target_aspect = float(width) / float(height)
aspect = float(b_image.width) / float(b_image.height)
if ((target_aspect > aspect and not crop) or
(target_aspect <= aspect and crop)):
# target is wider than image, set height as maximum
target_height = height
# calculate width
# - iw / ih = tw / th (keep aspect)
# => th ( iw / ih ) = tw
target_width = float(target_height) * aspect
if crop:
# calculate crop coords
# - ( tw - w ) / 2
target_left = (float(target_width) - float(width)) / 2
target_left = int(round(target_left))
target_top = 0
# correct floating point error, and convert to int, round in the
# direction of the requested width
if width >= target_width:
target_width = int(math.ceil(target_width))
else:
target_width = int(math.floor(target_width))
else:
# image is wider than target, set width as maximum
target_width = width
# calculate height
# - iw / ih = tw / th (keep aspect)
# => tw / ( iw / ih ) = th
target_height = float(target_width) / aspect
if crop:
# calculate crop coords
# - ( th - h ) / 2
target_top = (float(target_height) - float(height)) / 2
target_top = int(round(target_top))
target_left = 0
# correct floating point error and convert to int
if height >= target_height:
target_height = int(math.ceil(target_height))
else:
target_height = int(math.floor(target_height))
# strip color profiles
b_image.strip()
# Resize
b_image.resize(target_width, target_height)
if crop:
# Crop to target
b_image.crop(left=target_left, top=target_top, width=width,
height=height)
# Save to temporary file
temp_file = tempfile.TemporaryFile()
b_image.save(file=temp_file)
# Rewind the file
temp_file.seek(0)
return temp_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(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
# Do resize and crop
resized_image = _resize(image, width, height, crop)
finally:
# Re-close if received a closed file
if is_closed:
image.close()
return ImageFile(resized_image) |
<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 resized file. Returns the url if as_url is True """ |
# 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 storage
try:
storage = image.storage
except AttributeError:
pass
# Test if exists or force
if force or not storage.exists(name):
resized_image = None
try:
resized_image = resize(image, width, height, crop)
name = storage.save(name, resized_image)
finally:
if resized_image is not None:
resized_image.close()
if as_url:
return storage.url(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 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 (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. sha The SHA of the commit to fetch. Returns: A dict with data about the commit. """ |
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 profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. message The commit message to give to the commit. tree The SHA of the tree to assign to the commit. parents A list enumerating the SHAs of the new commit's parent commits. Returns: A dict with data about the commit. """ |
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_name -- Name of the option (example host_name) section_name -- Which section of the config (default: name) examples: 'default result' """ |
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 section %s" % (option_name, section_name))
# If default argument was provided, we set variable my_defaults to that
# otherwise use the global nago defaults
if default != _sentinel:
my_defaults = {option_name: default}
else:
my_defaults = defaults.get('section_name', {})
# Lets parse our configuration file and see what we get
parser = get_parser(cfg_file)
return parser.get(section_name, option_name, vars=my_defaults) |
<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 /etc/nago/nago.ini defaults -- Dictionary with default values to use """ |
# 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 individual command and then removing blank commands. Parameters commands : iterable of strings Iterable of commands to strip. Returns ------- stripped_commands : list of str The stripped commands with blank ones removed. """ |
# 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 = v.split(';')[0].strip()
if len(v) != 0:
stripped_commands.append(v)
return stripped_commands |
<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.objects.all(), many=True)
return response.Response({
"skills": skills.data,
"causes": causes.data,
"cities": cities.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 _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)
return LinterFailure(description, 1, replacement=None)
header_path = relative_path.replace("\\", "/")
regex = re.compile(r"^{0} \/{1}$".format(_HDR_COMMENT,
re.escape(header_path)))
if not regex.match(contents[check_index]):
description = ("""The filename /{0} must be the """
"""first line of the header""")
return LinterFailure(description.format(header_path),
check_index + 1,
_comment_type_from_line(contents[check_index]) +
"/{0}\n".format(header_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 _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 in file""")
lineno = lineno + 1
if lineno < 2:
raise RuntimeError("""Headerblock must have at least two lines""")
return lineno - 1 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _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 line must have the """
"""following notice: {0}""")
replacement = None
comment = _comment_type_from_line(contents[lineno])
comment_footer = _end_comment_type_from_line(contents[lineno])
# If the last line has the words "Copyright" or "/LICENCE.md" the
# user probably attempted to add a notice, but failed, so just
# suggest replacing the whole line
if re.compile(r"^.*(Copyright|LICENCE.md).*$").match(contents[lineno]):
replacement = "{0}{1}\n".format(comment, notice + comment_footer)
# Put the copyright notice on a new line
else:
# Strip off the footer and the \n at the end of the line.
repl_contents = contents[lineno][:-(len(comment_footer) + 1)]
replacement = "{0}\n{1}{2}\n".format(repl_contents,
comment,
notice + comment_footer)
return LinterFailure(description.format(notice),
lineno + 1,
replacement) |
<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 suggestions from :suggestions: and uses it to populate the message and candidate replacement. The replacement will be a line in :contents:, as determined by :line_offset: and :column_offset:. """ |
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(suggestions):
suggestions_text = (""", perhaps you meant """ +
" ".join(suggestions))
else:
suggestions_text = ""
format_desc = message_start + suggestions_text
return LinterFailure(format_desc,
line_offset + 1,
replacement) |
<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 chunk and a set of valid and technical words, find errors.""" |
for chunk in chunks:
for error in spellcheck_region(chunk.data,
valid_words_dictionary,
technical_words_dictionary,
user_dictionary_words):
col_offset = _determine_character_offset(error.line_offset,
error.column_offset,
chunk.column)
msg = _SPELLCHECK_MESSAGES[error.error_type].format(error.word)
yield _populate_spelling_error(error.word,
error.suggestions,
contents,
error.line_offset +
chunk.line,
col_offset,
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 _create_technical_words_dictionary(spellchecker_cache_path, relative_path, user_words, shadow):
"""Create Dictionary at spellchecker_cache_path with technical words.""" |
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, "_"),
[os.path.realpath(relative_path)],
spellchecker_cache_path)
return technical_words |
<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/questions/ 1540822/dumping-a-multiprocessing-queue-into-a-list in order to ensure that the queue is fully drained. """ |
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-technical-terms-to is passed to the linter then open up the file specified (or create it) and then merge the set of technical words that we have now with the technical words already in it. """ |
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:
assert log_technical_terms_to_queue is not None
try:
os.makedirs(os.path.dirname(log_technical_terms_to_path))
except OSError as error:
if error.errno != errno.EEXIST:
raise error
if not log_technical_terms_to_queue.empty():
with closing(os.fdopen(os.open(log_technical_terms_to_path,
os.O_RDWR | os.O_CREAT),
"r+")) as terms_file:
# pychecker can't see through the handle returned by closing
# so we need to suppress these warnings.
terms = set(terms_file.read().splitlines())
new_terms = set(freduce(lambda x, y: x | y,
_drain(log_technical_terms_to_queue)))
if not terms.issuperset(new_terms):
terms_file.seek(0)
terms_file.truncate(0)
terms_file.write("\n".join(list(terms |
set(new_terms)))) |
<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.create(cache)
technical_words = _create_technical_words_dictionary(cache,
relative_path,
user_words,
shadow)
if linter_options.get("log_technical_terms_to"):
linter_options["log_technical_terms_to"].put(technical_words.words())
return [e for e in _find_spelling_errors_in_chunks(chunks,
contents,
valid_words,
technical_words,
user_words) if e] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _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(code1,code2) etc. """ |
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):
return True
aside = contents[error.line - 1].split("#")
if len(aside) and _line_suppresses_error_code(aside[-1].strip(), code):
return True
return False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.