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 _get_username_hostname():
'''Best attempt to get username and hostname, returns "na" if problem.'''
user = 'na'
host = 'na'
try:
user = getpass.getuser()
except Exception:
pass
try:
host = socket.gethostname()
except Exception:
pass
return user, host |
<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_user_details(self, response):
""" Complete with additional information from original LTI POST data, as available. """ |
data = {}
# None of them is mandatory
data['id'] = response.get('user_id', None)
data['username'] = response.get('custom_username', None)
if not data['username']:
data['username'] = response.get('ext_user_username', None)
data['last_name'] = response.get('lis... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def user_unicode(self):
'''
Monkey patch for getting better user name stringification,
user proxies did not make the job.
Django's custom user model feature would have needed to be introduced
before the first syncdb, which does not work for existing installations.
'''
if self.ema... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def move_user_data(primary, secondary):
'''
Moves all submissions and other data linked to the secondary user into the primary user.
Nothing is deleted here, we just modify foreign user keys.
'''
# Update all submission authorships of the secondary to the primary
submissions = Submission... |
<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_course_safe(self, id):
'''
Adds a course for the user after conducting a set of sanity checks.
Return the title of the course or an exception.
'''
course = get_object_or_404(Course, pk=int(id), active=True)
if course not in self.courses.all():
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def tutor_courses(self):
'''
Returns the list of courses this user is tutor or owner for.
'''
tutoring = self.user.courses_tutoring.all().filter(active__exact=True)
owning = self.user.courses.all().filter(active__exact=True)
result = (tutoring | owning).distinct()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def user_courses(self):
'''
Returns the list of courses this user is subscribed for,
or owning, or tutoring.
This leads to the fact that tutors and owners don't need
course membership.
'''
registered = self.courses.filter(active__exact=True).distin... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def open_assignments(self):
'''
Returns the list of open assignments from the
viewpoint of this user.
'''
# Include only assignments with future, or no, hard deadline
qs = Assignment.objects.filter(hard_deadline__gt=timezone.now(
)) | Assignment.objects.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 gone_assignments(self):
'''
Returns the list of past assignments the user did not submit for
before the hard deadline.
'''
# Include only assignments with past hard deadline
qs = Assignment.objects.filter(hard_deadline__lt=timezone.now())
# Include onl... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _build_message(self, to, text, subject=None, mtype=None, unsubscribe_url=None):
"""Constructs a MIME message from message and dispatch models.""" |
# TODO Maybe file attachments handling through `files` message_model context var.
if subject is None:
subject = u'%s' % _('No Subject')
if mtype == 'html':
msg = self.mime_multipart()
text_part = self.mime_multipart('alternative')
text_part.atta... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _social_auth_login(self, request, **kwargs):
'''
View function that redirects to social auth login,
in case the user is not logged in.
'''
if request.user.is_authenticated():
if not request.user.is_active or not request.user.is_staff:
raise PermissionDenied()
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 get_queryset(self, request):
''' Restrict the listed courses for the current user.'''
qs = super(CourseAdmin, self).get_queryset(request)
if request.user.is_superuser:
return qs
else:
return qs.filter(Q(tutors__pk=request.user.pk) | Q(owner=request.user)).dist... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _build_tag_families(tagged_paired_aligns,
ranked_tags,
hamming_threshold,
consensus_threshold,
family_filter=lambda _: None):
'''Partition paired aligns into families.
Each read is considered against each ranked... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _rank_tags(tagged_paired_aligns):
'''Return the list of tags ranked from most to least popular.'''
tag_count_dict = defaultdict(int)
for paired_align in tagged_paired_aligns:
tag_count_dict[paired_align.umt] += 1
tags_by_count = utils.sort_dict(tag_count_dict)
ranked_tags = [tag_count[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 main(command_line_args=None):
'''Connor entry point. See help for more info'''
log = None
if not command_line_args:
command_line_args = sys.argv
try:
start_time = time.time()
args = parse_command_line_args(command_line_args)
log = utils.Logger(args)
command_va... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def schedule_email(message, to, subject=None, sender=None, priority=None):
"""Schedules an email message for delivery. :param dict, str message: str or dict: use... |
if SHORTCUT_EMAIL_MESSAGE_TYPE:
message_cls = get_registered_message_type(SHORTCUT_EMAIL_MESSAGE_TYPE)
else:
if isinstance(message, dict):
message_cls = EmailHtmlMessage
else:
message_cls = EmailTextMessage
schedule_messages(
message_cls(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 schedule_jabber_message(message, to, sender=None, priority=None):
"""Schedules Jabber XMPP message for delivery. :param str message: text to send. :param lis... |
schedule_messages(message, recipients('xmppsleek', to), sender=sender, priority=priority) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def schedule_tweet(message, to='', sender=None, priority=None):
"""Schedules a Tweet for delivery. :param str message: text to send. :param list|str|unicode to: ... |
schedule_messages(message, recipients('twitter', to), sender=sender, priority=priority) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def schedule_telegram_message(message, to, sender=None, priority=None):
"""Schedules Telegram message for delivery. :param str message: text to send. :param list... |
schedule_messages(message, recipients('telegram', to), sender=sender, priority=priority) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def schedule_facebook_message(message, sender=None, priority=None):
"""Schedules Facebook wall message for delivery. :param str message: text or URL to publish. ... |
schedule_messages(message, recipients('fb', ''), sender=sender, priority=priority) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def schedule_vkontakte_message(message, to, sender=None, priority=None):
"""Schedules VKontakte message for delivery. :param str message: text or URL to publish ... |
schedule_messages(message, recipients('vk', to), sender=sender, priority=priority) |
<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_alias(cls):
"""Returns messenger alias. :return: str :rtype: str """ |
if cls.alias is None:
cls.alias = cls.__name__
return cls.alias |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _structure_recipients_data(cls, recipients):
"""Converts recipients data into a list of Recipient objects. :param list recipients: list of objects :return: l... |
try: # That's all due Django 1.7 apps loading.
from django.contrib.auth import get_user_model
USER_MODEL = get_user_model()
except ImportError:
# Django 1.4 fallback.
from django.contrib.auth.models import User as USER_MODEL
if not is_iterable(r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mark_error(self, dispatch, error_log, message_cls):
"""Marks a dispatch as having error or consequently as failed if send retry limit for that message type i... |
if message_cls.send_retry_limit is not None and (dispatch.retry_count + 1) >= message_cls.send_retry_limit:
self.mark_failed(dispatch, error_log)
else:
dispatch.error_log = error_log
self._st['error'].append(dispatch) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mark_failed(self, dispatch, error_log):
"""Marks a dispatch as failed. Sitemessage won't try to deliver already failed messages. Should be used within send()... |
dispatch.error_log = error_log
self._st['failed'].append(dispatch) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _process_messages(self, messages, ignore_unknown_message_types=False):
"""Performs message processing. :param dict messages: indexed by message id dict with ... |
with self.before_after_send_handling():
for message_id, message_data in messages.items():
message_model, dispatch_models = message_data
try:
message_cls = get_registered_message_type(message_model.cls)
except UnknownMessageTypeErro... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def setup(self, app):
'''
Make sure that other installed plugins don't affect the same keyword argument.
'''
for other in app.plugins:
if not isinstance(other, MySQLPlugin):
continue
if other.keyword == self.keyword:
raise PluginErr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def assign_role(backend, user, response, *args, **kwargs):
'''
Part of the Python Social Auth Pipeline.
Checks if the created demo user should be pushed into some group.
'''
if backend.name is 'passthrough' and settings.DEMO is True and 'role' in kwargs['request'].session[passthrough.SESSION_VAR]:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def fetch(url, fullpath):
'''
Fetch data from an URL and save it under the given target name.
'''
logger.debug("Fetching %s from %s" % (fullpath, url))
try:
tmpfile, headers = urlretrieve(url)
if os.path.exists(fullpath):
os.remove(fullpath)
shutil.move(tmpfile, ... |
<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_post(config, urlpath, post_data):
'''
Send POST data to an OpenSubmit server url path,
according to the configuration.
'''
server = config.get("Server", "url")
logger.debug("Sending executor payload to " + server)
post_data = urlencode(post_data)
post_data = post_data.encode("ut... |
<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_hostinfo(config):
'''
Register this host on OpenSubmit test machine.
'''
info = all_host_infos()
logger.debug("Sending host information: " + str(info))
post_data = [("Config", json.dumps(info)),
("Action", "get_config"),
("UUID", config.get("Server", "u... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def compatible_api_version(server_version):
'''
Check if this server API version is compatible to us.
'''
try:
semver = server_version.split('.')
if semver[0] != '1':
logger.error(
'Server API version (%s) is too new for us. Please update the executor installa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def fetch_job(config):
'''
Fetch any available work from the OpenSubmit server and
return an according job object.
Returns None if no work is available.
Errors are reported by this function directly.
'''
url = "%s/jobs/?Secret=%s&UUID=%s" % (config.get("Server", "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 fake_fetch_job(config, src_dir):
'''
Act like fetch_job, but take the validator file and the student
submission files directly from a directory.
Intended for testing purposes when developing test scripts.
Check also cmdline.py.
'''
logger.debug("Creating fake job from " + src_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 run_configure(self, mandatory=True):
"""Runs the 'configure' program in the working directory. Args: mandatory (bool):
Throw exception if 'configure' fails ... |
if not has_file(self.working_dir, 'configure'):
if mandatory:
raise FileNotFoundError(
"Could not find a configure script for execution.")
else:
return
try:
prog = RunningProgram(self, 'configure')
prog.... |
<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_compiler(self, compiler=GCC, inputs=None, output=None):
"""Runs a compiler in the working directory. Args: compiler (tuple):
The compiler program and it... |
# Let exceptions travel through
prog = RunningProgram(self, *compiler_cmdline(compiler=compiler,
inputs=inputs,
output=output))
prog.expect_exit_status(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 run_build(self, compiler=GCC, inputs=None, output=None):
"""Combined call of 'configure', 'make' and the compiler. The success of 'configure' and 'make' is o... |
logger.info("Running build steps ...")
self.run_configure(mandatory=False)
self.run_make(mandatory=False)
self.run_compiler(compiler=compiler,
inputs=inputs,
output=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 spawn_program(self, name, arguments=[], timeout=30, exclusive=False):
"""Spawns a program in the working directory. This method allows the interaction with t... |
logger.debug("Spawning program for interaction ...")
if exclusive:
kill_longrunning(self.config)
return RunningProgram(self, name, arguments, timeout) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_program(self, name, arguments=[], timeout=30, exclusive=False):
"""Runs a program in the working directory to completion. Args: name (str):
The name of ... |
logger.debug("Running program ...")
if exclusive:
kill_longrunning(self.config)
prog = RunningProgram(self, name, arguments, timeout)
return prog.expect_end() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def grep(self, regex):
"""Scans the student files for text patterns. Args: regex (str):
Regular expression used for scanning inside the files. Returns: tuple: N... |
matches = []
logger.debug("Searching student files for '{0}'".format(regex))
for fname in self.student_files:
if os.path.isfile(self.working_dir + fname):
for line in open(self.working_dir + fname, 'br'):
if re.search(regex.encode(), 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 ensure_files(self, filenames):
"""Checks the student submission for specific files. Args: filenames (tuple):
The list of file names to be cjecked for. Retur... |
logger.debug("Testing {0} for the following files: {1}".format(
self.working_dir, filenames))
dircontent = os.listdir(self.working_dir)
for fname in filenames:
if fname not in dircontent:
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def live_chat_banner(context):
""" Display any available live chats as advertisements. """ |
context = copy(context)
# Find any upcoming or current live chat. The Chat date must be less than 5
# days away, or currently in progress.
oldchat = LiveChat.chat_finder.get_last_live_chat()
if oldchat:
context['last_live_chat'] = {
'title': oldchat.title,
'chat_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 kill_longrunning(config):
'''
Terminate everything under the current user account
that has run too long. This is a final safeguard if
the subprocess timeout stuff is not working.
You better have no production servers running also
under the current user account ...
'''... |
<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_exitstatus(self):
"""Get the exit status of the program execution. Returns: int: Exit status as reported by the operating system, or None if it is not av... |
logger.debug("Exit status is {0}".format(self._spawn.exitstatus))
return self._spawn.exitstatus |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expect_output(self, pattern, timeout=-1):
"""Wait until the running program performs some given output, or terminates. Args: pattern: The pattern the output ... |
logger.debug("Expecting output '{0}' from '{1}'".format(pattern, self.name))
try:
return self._spawn.expect(pattern, timeout)
except pexpect.exceptions.EOF as e:
logger.debug("Raising termination exception.")
raise TerminationException(instance=self, real_exc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sendline(self, text):
"""Sends an input line to the running program, including os.linesep. Args: text (str):
The input text to be send. Raises: TerminationE... |
logger.debug("Sending input '{0}' to '{1}'".format(text, self.name))
try:
return self._spawn.sendline(text)
except pexpect.exceptions.EOF as e:
logger.debug("Raising termination exception.")
raise TerminationException(instance=self, real_exception=e, output=s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expect_end(self):
"""Wait for the running program to finish. Returns: A tuple with the exit code, as reported by the operating system, and the output produce... |
logger.debug("Waiting for termination of '{0}'".format(self.name))
try:
# Make sure we fetch the last output bytes.
# Recommendation from the pexpect docs.
self._spawn.expect(pexpect.EOF)
self._spawn.wait()
dircontent = str(os.listdir(self.job... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expect_exitstatus(self, exit_status):
"""Wait for the running program to finish and expect some exit status. Args: exit_status (int):
The expected exit stat... |
self.expect_end()
logger.debug("Checking exit status of '{0}', output so far: {1}".format(
self.name, self.get_output()))
if self._spawn.exitstatus is None:
raise WrongExitStatusException(
instance=self, expected=exit_status, output=self.get_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 unsubscribe(request, message_id, dispatch_id, hashed, redirect_to=None):
"""Handles unsubscribe request. :param Request request: :param int message_id: :para... |
return _generic_view(
'handle_unsubscribe_request', sig_unsubscribe_failed,
request, message_id, dispatch_id, hashed, 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 mark_read(request, message_id, dispatch_id, hashed, redirect_to=None):
"""Handles mark message as read request. :param Request request: :param int message_id... |
if redirect_to is None:
redirect_to = get_static_url('img/sitemessage/blank.png')
return _generic_view(
'handle_mark_read_request', sig_mark_read_failed,
request, message_id, dispatch_id, hashed, 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 schedule_messages(messages, recipients=None, sender=None, priority=None):
"""Schedules a message or messages. :param MessageBase|str|list messages: str or Me... |
if not is_iterable(messages):
messages = (messages,)
results = []
for message in messages:
if isinstance(message, six.string_types):
message = PlainTextMessage(message)
resulting_priority = message.priority
if priority is not None:
resulting_priorit... |
<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_scheduled_messages(priority=None, ignore_unknown_messengers=False, ignore_unknown_message_types=False):
"""Sends scheduled messages. :param int, None pr... |
dispatches_by_messengers = Dispatch.group_by_messengers(Dispatch.get_unsent(priority=priority))
for messenger_id, messages in dispatches_by_messengers.items():
try:
messenger_obj = get_registered_messenger_object(messenger_id)
messenger_obj._process_messages(messages, ignore_un... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_undelivered(to=None):
"""Sends a notification email if any undelivered dispatches. Returns undelivered (failed) dispatches count. :param str|unicode to... |
failed_count = Dispatch.objects.filter(dispatch_status=Dispatch.DISPATCH_STATUS_FAILED).count()
if failed_count:
from sitemessage.shortcuts import schedule_email
from sitemessage.messages.email import EmailTextMessage
if to is None:
admins = settings.ADMINS
if... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare_dispatches():
"""Automatically creates dispatches for messages without them. :return: list of Dispatch :rtype: list """ |
dispatches = []
target_messages = Message.get_without_dispatches()
cache = {}
for message_model in target_messages:
if message_model.cls not in cache:
message_cls = get_registered_message_type(message_model.cls)
subscribers = message_cls.get_subscribers()
... |
<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_user_preferences_for_ui(user, message_filter=None, messenger_filter=None, new_messengers_titles=None):
"""Returns a two element tuple with user subscript... |
if new_messengers_titles is None:
new_messengers_titles = {}
msgr_to_msg = defaultdict(set)
msg_titles = OrderedDict()
msgr_titles = OrderedDict()
for msgr in get_registered_messenger_objects().values():
if not (messenger_filter is None or messenger_filter(msgr)) or not msgr.allow... |
<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_user_preferences_from_request(request):
"""Sets user subscription preferences using data from a request. Expects data sent by form built with `sitemessag... |
prefs = []
for pref in request.POST.getlist(_PREF_POST_KEY):
message_alias, messenger_alias = pref.split(_ALIAS_SEP)
try:
get_registered_message_type(message_alias)
get_registered_messenger_object(messenger_alias)
except (UnknownMessengerError, UnknownMessageT... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def formfield_for_dbfield(self, db_field, **kwargs):
''' Offer only gradings that are not used by other schemes, which means they are used by this scheme or not at all.'''
if db_field.name == "gradings":
request=kwargs['request']
try:
#TODO: MockRequst object fro... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def build_bam_tags():
'''builds the list of BAM tags to be added to output BAMs'''
#pylint: disable=unused-argument
def _combine_filters(fam, paired_align, align):
filters = [x.filter_value for x in [fam, align] if x and x.filter_value]
if filters:
return ";".join(filters).replac... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def current_livechat(request):
""" Checks if a live chat is currently on the go, and add it to the request context. This is to allow the AskMAMA URL in the top-n... |
result = {}
livechat = LiveChat.chat_finder.get_current_live_chat()
if livechat:
result['live_chat'] = {}
result['live_chat']['current_live_chat'] = livechat
can_comment, reason_code = livechat.can_comment(request)
result['live_chat']['can_render_comment_form'] = can_comment... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def upload_path(instance, filename):
'''
Sanitize the user-provided file name, add timestamp for uniqness.
'''
filename = filename.replace(" ", "_")
filename = unicodedata.normalize('NFKD', filename).lower()
return os.path.join(str(timezone.now().date().isoformat()), filename) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def is_archive(self):
'''
Determines if the attachment is an archive.
'''
try:
if zipfile.is_zipfile(self.attachment.path) or tarfile.is_tarfile(self.attachment.path):
return True
except Exception:
pass
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 get_user_details(self, response):
""" Complete with additional information from session, as available. """ |
result = {
'id': response['id'],
'username': response.get('username', None),
'email': response.get('email', None),
'first_name': response.get('first_name', None),
'last_name': response.get('last_name', None)
}
if result['first_name'] 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 paired_reader_from_bamfile(args,
log,
usage_logger,
annotated_writer):
'''Given a BAM file, return a generator that yields filtered, paired reads'''
total_aligns = pysamwrapper.total_align_count(args.input_bam)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def opencl():
'''
Determine some system information about the installed OpenCL device.
'''
result = []
try:
import pyopencl as ocl
for plt in ocl.get_platforms():
result.append("Platform: " + platform.name)
for device in plt.get_devices():
... |
<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_host_infos():
'''
Summarize all host information.
'''
output = []
output.append(["Operating system", os()])
output.append(["CPUID information", cpu()])
output.append(["CC information", compiler()])
output.append(["JDK information", from_cmd("java -version")])
output.appen... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _completed_families(self, reference_name, rightmost_boundary):
'''returns one or more families whose end < rightmost boundary'''
in_progress = self._right_coords_in_progress[reference_name]
while len(in_progress):
right_coord = in_progress[0]
if right_coord < rightmos... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def inform_student(submission, request, state):
'''
Create an email message for the student,
based on the given submission state.
Sending eMails on validation completion does
not work, since this may have been triggered
by the admin.
'''
details_url = request.build_absolute_uri(reverse(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def graded_submissions(self):
'''
Queryset for the graded submissions, which are worth closing.
'''
qs = self._valid_submissions().filter(state__in=[Submission.GRADED])
return qs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def authors(self):
'''
Queryset for all distinct authors this course had so far. Important for statistics.
Note that this may be different from the list of people being registered for the course,
f.e. when they submit something and the leave the course.
'''
qs... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def post_user_login(sender, request, user, **kwargs):
""" Create a profile for the user, when missing. Make sure that all neccessary user groups exist and have t... |
logger.debug("Running post-processing for user login.")
# Users created by social login or admins have no profile.
# We fix that during their first login.
try:
with transaction.atomic():
profile, created = UserProfile.objects.get_or_create(user=user)
if created:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def submissionfile_post_save(sender, instance, signal, created, **kwargs):
'''
Update MD5 field for newly uploaded files.
'''
if created:
logger.debug("Running post-processing for new submission file.")
instance.md5 = instance.attachment_md5()
instance.save() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def submission_post_save(sender, instance, **kwargs):
''' Several sanity checks after we got a valid submission object.'''
logger.debug("Running post-processing for submission")
# Make the submitter an author
if instance.submitter not in instance.authors.all():
instance.authors.add(instance.subm... |
<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_subscribers(cls, active_only=True):
"""Returns a list of Recipient objects subscribed for this message type. :param bool active_only: Flag whether :retur... |
subscribers_raw = Subscription.get_for_message_cls(cls.alias)
subscribers = []
for subscriber in subscribers_raw:
messenger_cls = subscriber.messenger_cls
address = subscriber.address
recipient = subscriber.recipient
# Do not send messages to in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_url(cls, name, message_model, dispatch_model):
"""Returns a common pattern sitemessage URL. :param str name: URL name :param Message message_model: :par... |
global APP_URLS_ATTACHED
url = ''
if dispatch_model is None:
return url
if APP_URLS_ATTACHED != False: # sic!
hashed = cls.get_dispatch_hash(dispatch_model.id, message_model.id)
try:
url = reverse(name, args=[message_model.id, 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 handle_unsubscribe_request(cls, request, message, dispatch, hash_is_valid, redirect_to):
"""Handles user subscription cancelling request. :param Request requ... |
if hash_is_valid:
Subscription.cancel(
dispatch.recipient_id or dispatch.address, cls.alias, dispatch.messenger
)
signal = sig_unsubscribe_success
else:
signal = sig_unsubscribe_failed
signal.send(cls, request=request, message=me... |
<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_mark_read_request(cls, request, message, dispatch, hash_is_valid, redirect_to):
"""Handles a request to mark a message as read. :param Request request... |
if hash_is_valid:
dispatch.mark_read()
dispatch.save()
signal = sig_mark_read_success
else:
signal = sig_mark_read_failed
signal.send(cls, request=request, message=message, dispatch=dispatch)
return redirect(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 get_template(cls, message, messenger):
"""Get a template path to compile a message. 1. `tpl` field of message context; 2. `template` field of message class; ... |
template = message.context.get('tpl', None)
if template: # Template name is taken from message context.
return template
if cls.template is None:
cls.template = 'sitemessage/messages/%s__%s.%s' % (
cls.get_alias(), messenger.get_alias(), cls.template_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 compile(cls, message, messenger, dispatch=None):
"""Compiles and returns a message text. Considers `use_tpl` field from message context to decide whether tem... |
if message.context.get('use_tpl', False):
context = message.context
context.update({
'SITE_URL': get_site_url(),
'directive_unsubscribe': cls.get_unsubscribe_directive(message, dispatch),
'directive_mark_read': cls.get_mark_read_directive(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_context(cls, base_context, str_or_dict, template_path=None):
"""Helper method to structure initial message context data. NOTE: updates `base_context` ... |
if isinstance(str_or_dict, dict):
base_context.update(str_or_dict)
base_context['use_tpl'] = True
else:
base_context[cls.SIMPLE_TEXT_ID] = str_or_dict
if cls.SIMPLE_TEXT_ID in str_or_dict:
base_context['use_tpl'] = False
base_context['tp... |
<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_dispatches(cls, message, recipients=None):
"""Creates Dispatch models for a given message and return them. :param Message message: Message model inst... |
return Dispatch.create(message, recipients or cls.get_subscribers()) |
<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_page_access_token(self, app_id, app_secret, user_token):
"""Returns a dictionary of never expired page token indexed by page names. :param str app_id: Ap... |
url_extend = (
self._url_base + '/oauth/access_token?grant_type=fb_exchange_token&'
'client_id=%(app_id)s&client_secret=%(app_secret)s&fb_exchange_token=%(user_token)s')
response = self.lib.get(url_extend % {'app_id': app_id, 'app_secret': app_secret, 'user_tok... |
<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_working_dir(config, prefix):
'''
Create a fresh temporary directory, based on the fiven prefix.
Returns the new path.
'''
# Fetch base directory from executor configuration
basepath = config.get("Execution", "directory")
if not prefix:
prefix = 'opensubmit'
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 prepare_working_directory(job, submission_path, validator_path):
'''
Based on two downloaded files in the working directory,
the student submission and the validation package,
the working directory is prepared.
We unpack student submission first, so that teacher files overwrite
them in case... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def django_admin(args):
'''
Run something like it would be done through Django's manage.py.
'''
from django.core.management import execute_from_command_line
from django.core.exceptions import ImproperlyConfigured
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "opensubmit.settings")
try:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def check_path(file_path):
'''
Checks if the directories for this path exist, and creates them in case.
'''
directory = os.path.dirname(file_path)
if directory != '':
if not os.path.exists(directory):
os.makedirs(directory, 0o775) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def check_file(filepath):
'''
- Checks if the parent directories for this path exist.
- Checks that the file exists.
- Donates the file to the web server user.
TODO: This is Debian / Ubuntu specific.
'''
check_path(filepath)
if not os.path.exists(filepath):
print... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def check_web_config_consistency(config):
'''
Check the web application config file for consistency.
'''
login_conf_deps = {
'LOGIN_TWITTER_OAUTH_KEY': ['LOGIN_TWITTER_OAUTH_SECRET'],
'LOGIN_GOOGLE_OAUTH_KEY': ['LOGIN_GOOGLE_OAUTH_SECRET'],
'LOGIN_GITHUB_OAUTH_KEY': ['LOGIN_G... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def check_web_config(config_fname):
'''
Try to load the Django settings.
If this does not work, than settings file does not exist.
Returns:
Loaded configuration, or None.
'''
print("Looking for config file at {0} ...".format(config_fname))
config = RawConfigParser()
... |
<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_url(url: str) -> str: """ Remove leading and trailing slashes from a URL :param url: URL :return: URL with no leading and trailing slashes :private:... |
if url.startswith('/'):
url = url[1:]
if url.endswith('/'):
url = url[:-1]
return url |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _unwrap(variable_parts: VariablePartsType):
""" Yield URL parts. The given parts are usually in reverse order. """ |
curr_parts = variable_parts
var_any = []
while curr_parts:
curr_parts, (var_type, part) = curr_parts
if var_type == Routes._VAR_ANY_NODE:
var_any.append(part)
continue
if var_type == Routes._VAR_ANY_BREAK:
if var_any:
yield tupl... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_params( key_parts: Sequence[str], variable_parts: VariablePartsType) -> Dict[str, Union[str, Tuple[str]]]: """ Map keys to variables. This map\ URL-patte... |
# The unwrapped variable parts are in reverse order.
# Instead of reversing those we reverse the key parts
# and avoid the O(n) space required for reversing the vars
return dict(zip(reversed(key_parts), _unwrap(variable_parts))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _deconstruct_url(self, url: str) -> List[str]: """ Split a regular URL into parts :param url: A normalized URL :return: Parts of the URL :raises kua.routes.Ro... |
parts = url.split('/', self._max_depth + 1)
if depth_of(parts) > self._max_depth:
raise RouteError('No match')
return parts |
<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(self, parts: Sequence[str]) -> RouteResolved: """ Match URL parts to a registered pattern. This function is basically where all\ the CPU-heavy work is ... |
route_match = None # type: RouteResolved
route_variable_parts = tuple() # type: VariablePartsType
# (route_partial, variable_parts, depth)
to_visit = [(self._routes, tuple(), 0)] # type: List[Tuple[dict, tuple, int]]
# Walk through the graph,
# keep track of all poss... |
<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(self, url: str) -> RouteResolved: """ Match a URL to a registered pattern. :param url: URL :return: Matched route :raises kua.RouteError: If there is no... |
url = normalize_url(url)
parts = self._deconstruct_url(url)
return self._match(parts) |
<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(self, url: str, anything: Any) -> None: """ Register a URL pattern into\ the routes for later matching. It's possible to attach any kind of\ object to the... |
url = normalize_url(url)
parts = url.split('/')
curr_partial_routes = self._routes
curr_key_parts = []
for part in parts:
if part.startswith(':*'):
curr_key_parts.append(part[2:])
part = self._VAR_ANY_NODE
self._max_de... |
<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_site_url():
"""Returns a URL for current site. :rtype: str|unicode """ |
site_url = getattr(_THREAD_LOCAL, _THREAD_SITE_URL, None)
if site_url is None:
site_url = SITE_URL or get_site_url_()
setattr(_THREAD_LOCAL, _THREAD_SITE_URL, site_url)
return site_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 get_message_type_for_app(app_name, default_message_type_alias):
"""Returns a registered message type object for a given application. Supposed to be used by r... |
message_type = default_message_type_alias
try:
message_type = _MESSAGES_FOR_APPS[app_name][message_type]
except KeyError:
pass
return get_registered_message_type(message_type) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def recipients(messenger, addresses):
"""Structures recipients data. :param str|unicode, MessageBase messenger: MessengerBase heir :param list[str|unicode]|str|u... |
if isinstance(messenger, six.string_types):
messenger = get_registered_messenger_object(messenger)
return messenger._structure_recipients_data(addresses) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upcoming_live_chat(self):
""" Find any upcoming or current live chat to advertise on the home page or live chat page. These are LiveChat's with primary categ... |
chat = None
now = datetime.now()
lcqs = self.get_query_set()
lcqs = lcqs.filter(
chat_ends_at__gte=now).order_by('-chat_starts_at')
try:
if settings.LIVECHAT_PRIMARY_CATEGORY:
lcqs = lcqs.filter(
primary_category__slu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_current_live_chat(self):
""" Check if there is a live chat on the go, so that we should take over the AskMAMA page with the live chat. """ |
now = datetime.now()
chat = self.upcoming_live_chat()
if chat and chat.is_in_progress():
return chat
return None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.