Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given the following code snippet before the placeholder: <|code_start|> class JobsView(browsers.ResourceBrowserView): browser_class = project_browsers.ContainerBrowser template_name = "disaster_recovery/jobs/browser.html" @shield("Unable to get job", redirect='jobs:index') def get_jobs_data(self): return freezer_api.Job(self.request).list(limit=100) @shield("Unable to get actions for this job.", redirect='jobs:index') def get_actions_in_job_data(self): if self.kwargs['job_id']: return freezer_api.Job(self.request).actions(self.kwargs['job_id']) return [] class JobWorkflowView(workflows.WorkflowView): workflow_class = configure_workflow.ConfigureJob @shield("Unable to get job", redirect="jobs:index") def get_object(self): return freezer_api.Job(self.request).get(self.kwargs['job_id']) def is_update(self): return 'job_id' in self.kwargs and bool(self.kwargs['job_id']) @shield("Unable to get job", redirect="jobs:index") def get_initial(self): initial = super(JobWorkflowView, self).get_initial() <|code_end|> , predict the next line using imports from the current file: from horizon import browsers from horizon import workflows from disaster_recovery.jobs.workflows import create as configure_workflow from disaster_recovery.jobs.workflows import update_job as update_job_workflow from disaster_recovery.jobs.workflows import update_actions as update_workflow from disaster_recovery.utils import shield import disaster_recovery.api.api as freezer_api import disaster_recovery.jobs.browsers as project_browsers and context including class names, function names, and sometimes code from other files: # Path: disaster_recovery/jobs/workflows/create.py # class ActionsConfigurationAction(workflows.Action): # class Meta(object): # class ActionsConfiguration(workflows.Step): # class ClientsConfigurationAction(workflows.MembershipAction): # class Meta: # class ClientsConfiguration(workflows.UpdateMembersStep): # class InfoConfigurationAction(workflows.Action): # class Meta(object): # class InfoConfiguration(workflows.Step): # class ConfigureJob(workflows.Workflow): # def __init__(self, request, *args, **kwargs): # def contribute(self, data, context): # def __init__(self, request, context, *args, **kwargs): # def clean(self): # def _validate_iso_format(self, start_date): # def populate_interval_uint_choices(self, request, context): # def _check_start_datetime(self, cleaned_data): # def _check_end_datetime(self, cleaned_data): # def handle(self, request, context): # # Path: disaster_recovery/jobs/workflows/update_job.py # class InfoConfigurationAction(workflows.Action): # class Meta(object): # class InfoConfiguration(workflows.Step): # class UpdateJob(workflows.Workflow): # def __init__(self, request, context, *args, **kwargs): # def clean(self): # def _validate_iso_format(self, start_date): # def _check_start_datetime(self, cleaned_data): # def _check_end_datetime(self, cleaned_data): # def handle(self, request, context): # # Path: disaster_recovery/jobs/workflows/update_actions.py # class ActionsConfigurationAction(workflows.Action): # class Meta(object): # class ActionsConfiguration(workflows.Step): # class UpdateActions(workflows.Workflow): # def handle(self, request, context): # # Path: disaster_recovery/utils.py # def shield(message, redirect=''): # """decorator to reduce boilerplate try except blocks for horizon functions # :param message: a str error message # :param redirect: a str with the redirect namespace without including # horizon:disaster_recovery: # eg. @shield('error', redirect='jobs:index') # """ # def wrap(function): # # @wraps(function) # def wrapped_function(view, *args, **kwargs): # # try: # return function(view, *args, **kwargs) # except Exception as error: # LOG.error(error.message) # namespace = "horizon:disaster_recovery:" # r = reverse("{0}{1}".format(namespace, redirect)) # # if view.request.path == r: # # To avoid an endless loop, we must not redirect to the # # same page on which the error happened # user_home = get_user_home(view.request.user) # exceptions.handle(view.request, _(error.message), # redirect=user_home) # else: # exceptions.handle(view.request, _(error.message), # redirect=r) # # return wrapped_function # return wrap . Output only the next line.
if self.is_update():
Given the code snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. class JobsView(browsers.ResourceBrowserView): browser_class = project_browsers.ContainerBrowser template_name = "disaster_recovery/jobs/browser.html" @shield("Unable to get job", redirect='jobs:index') def get_jobs_data(self): return freezer_api.Job(self.request).list(limit=100) @shield("Unable to get actions for this job.", redirect='jobs:index') <|code_end|> , generate the next line using the imports in this file: from horizon import browsers from horizon import workflows from disaster_recovery.jobs.workflows import create as configure_workflow from disaster_recovery.jobs.workflows import update_job as update_job_workflow from disaster_recovery.jobs.workflows import update_actions as update_workflow from disaster_recovery.utils import shield import disaster_recovery.api.api as freezer_api import disaster_recovery.jobs.browsers as project_browsers and context (functions, classes, or occasionally code) from other files: # Path: disaster_recovery/jobs/workflows/create.py # class ActionsConfigurationAction(workflows.Action): # class Meta(object): # class ActionsConfiguration(workflows.Step): # class ClientsConfigurationAction(workflows.MembershipAction): # class Meta: # class ClientsConfiguration(workflows.UpdateMembersStep): # class InfoConfigurationAction(workflows.Action): # class Meta(object): # class InfoConfiguration(workflows.Step): # class ConfigureJob(workflows.Workflow): # def __init__(self, request, *args, **kwargs): # def contribute(self, data, context): # def __init__(self, request, context, *args, **kwargs): # def clean(self): # def _validate_iso_format(self, start_date): # def populate_interval_uint_choices(self, request, context): # def _check_start_datetime(self, cleaned_data): # def _check_end_datetime(self, cleaned_data): # def handle(self, request, context): # # Path: disaster_recovery/jobs/workflows/update_job.py # class InfoConfigurationAction(workflows.Action): # class Meta(object): # class InfoConfiguration(workflows.Step): # class UpdateJob(workflows.Workflow): # def __init__(self, request, context, *args, **kwargs): # def clean(self): # def _validate_iso_format(self, start_date): # def _check_start_datetime(self, cleaned_data): # def _check_end_datetime(self, cleaned_data): # def handle(self, request, context): # # Path: disaster_recovery/jobs/workflows/update_actions.py # class ActionsConfigurationAction(workflows.Action): # class Meta(object): # class ActionsConfiguration(workflows.Step): # class UpdateActions(workflows.Workflow): # def handle(self, request, context): # # Path: disaster_recovery/utils.py # def shield(message, redirect=''): # """decorator to reduce boilerplate try except blocks for horizon functions # :param message: a str error message # :param redirect: a str with the redirect namespace without including # horizon:disaster_recovery: # eg. @shield('error', redirect='jobs:index') # """ # def wrap(function): # # @wraps(function) # def wrapped_function(view, *args, **kwargs): # # try: # return function(view, *args, **kwargs) # except Exception as error: # LOG.error(error.message) # namespace = "horizon:disaster_recovery:" # r = reverse("{0}{1}".format(namespace, redirect)) # # if view.request.path == r: # # To avoid an endless loop, we must not redirect to the # # same page on which the error happened # user_home = get_user_home(view.request.user) # exceptions.handle(view.request, _(error.message), # redirect=user_home) # else: # exceptions.handle(view.request, _(error.message), # redirect=r) # # return wrapped_function # return wrap . Output only the next line.
def get_actions_in_job_data(self):
Continue the code snippet: <|code_start|># -*- encoding: utf-8 -*- # # Copyright © 2018 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. class InjectorTestCase(base.TestCase): def test_inject(self): self.assertEqual(100, injector._inject( self.incoming, self.coord, self.storage, self.index, measures=10, metrics=10)) def test_inject_process(self): self.assertEqual(100, injector._inject( self.incoming, self.coord, self.storage, self.index, <|code_end|> . Use current file imports: from gnocchi.cli import injector from gnocchi.tests import base and context (classes, functions, or code) from other files: # Path: gnocchi/cli/injector.py # def injector(): # conf = cfg.ConfigOpts() # conf.register_cli_opts([ # cfg.IntOpt("--measures", # help="Measures per metric."), # cfg.IntOpt("--metrics", # help="Number of metrics to create."), # cfg.IntOpt("--archive-policy-name", # help="Name of archive policy to use.", # default="low"), # cfg.IntOpt("--interval", # help="Interval to sleep between metrics sending."), # cfg.BoolOpt("--process", default=False, # help="Process the ingested measures."), # ]) # return _inject(service.prepare_service(conf=conf, log_to_std=True), # metrics=conf.metrics, # measures=conf.measures, # archive_policy_name=conf.archive_policy_name, # process=conf.process, # interval=conf.interval) # # Path: gnocchi/tests/base.py # class SkipNotImplementedMeta(type): # class FakeSwiftClient(object): # class CaptureOutput(fixtures.Fixture): # class BaseTestCase(testcase.TestCase): # class TestCase(BaseTestCase): # def __new__(cls, name, bases, local): # def _skip_decorator(func): # def skip_if_not_implemented(*args, **kwargs): # def __init__(self, *args, **kwargs): # def put_container(self, container, response_dict=None): # def get_container(self, container, delimiter=None, # path=None, full_listing=False, limit=None): # def put_object(self, container, key, obj): # def get_object(self, container, key): # def delete_object(self, container, obj): # def delete_container(self, container): # def head_container(self, container): # def post_account(self, headers, query_string=None, data=None, # response_dict=None): # def setUp(self): # def output(self): # def setUp(self): # def setUp(self): # def tearDown(self): # def _create_metric(self, archive_policy_name="low"): # def trigger_processing(self, metrics=None): # REDIS_DB_INDEX = 0 # REDIS_DB_LOCK = threading.Lock() # ARCHIVE_POLICIES = { # 'no_granularity_match': archive_policy.ArchivePolicy( # "no_granularity_match", # 0, [ # # 2 second resolution for a day # archive_policy.ArchivePolicyItem( # granularity=numpy.timedelta64(2, 's'), # timespan=numpy.timedelta64(1, 'D'), # ), # ], # ), # 'low': archive_policy.ArchivePolicy( # "low", 0, [ # # 5 minutes resolution for an hour # archive_policy.ArchivePolicyItem( # granularity=numpy.timedelta64(5, 'm'), points=12), # # 1 hour resolution for a day # archive_policy.ArchivePolicyItem( # granularity=numpy.timedelta64(1, 'h'), points=24), # # 1 day resolution for a month # archive_policy.ArchivePolicyItem( # granularity=numpy.timedelta64(1, 'D'), points=30), # ], # ), # 'medium': archive_policy.ArchivePolicy( # "medium", 0, [ # # 1 minute resolution for an day # archive_policy.ArchivePolicyItem( # granularity=numpy.timedelta64(1, 'm'), points=60 * 24), # # 1 hour resolution for a week # archive_policy.ArchivePolicyItem( # granularity=numpy.timedelta64(1, 'h'), points=7 * 24), # # 1 day resolution for a year # archive_policy.ArchivePolicyItem( # granularity=numpy.timedelta64(1, 'D'), points=365), # ], # ), # 'high': archive_policy.ArchivePolicy( # "high", 0, [ # # 1 second resolution for an hour # archive_policy.ArchivePolicyItem( # granularity=numpy.timedelta64(1, 's'), points=3600), # # 1 minute resolution for a week # archive_policy.ArchivePolicyItem( # granularity=numpy.timedelta64(1, 'm'), points=60 * 24 * 7), # # 1 hour resolution for a year # archive_policy.ArchivePolicyItem( # granularity=numpy.timedelta64(1, 'h'), points=365 * 24), # ], # ), # } . Output only the next line.
measures=10, metrics=10, process=True))
Given snippet: <|code_start|># -*- encoding: utf-8 -*- # # Copyright © 2018 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. class InjectorTestCase(base.TestCase): def test_inject(self): self.assertEqual(100, injector._inject( <|code_end|> , continue by predicting the next line. Consider current file imports: from gnocchi.cli import injector from gnocchi.tests import base and context: # Path: gnocchi/cli/injector.py # def injector(): # conf = cfg.ConfigOpts() # conf.register_cli_opts([ # cfg.IntOpt("--measures", # help="Measures per metric."), # cfg.IntOpt("--metrics", # help="Number of metrics to create."), # cfg.IntOpt("--archive-policy-name", # help="Name of archive policy to use.", # default="low"), # cfg.IntOpt("--interval", # help="Interval to sleep between metrics sending."), # cfg.BoolOpt("--process", default=False, # help="Process the ingested measures."), # ]) # return _inject(service.prepare_service(conf=conf, log_to_std=True), # metrics=conf.metrics, # measures=conf.measures, # archive_policy_name=conf.archive_policy_name, # process=conf.process, # interval=conf.interval) # # Path: gnocchi/tests/base.py # class SkipNotImplementedMeta(type): # class FakeSwiftClient(object): # class CaptureOutput(fixtures.Fixture): # class BaseTestCase(testcase.TestCase): # class TestCase(BaseTestCase): # def __new__(cls, name, bases, local): # def _skip_decorator(func): # def skip_if_not_implemented(*args, **kwargs): # def __init__(self, *args, **kwargs): # def put_container(self, container, response_dict=None): # def get_container(self, container, delimiter=None, # path=None, full_listing=False, limit=None): # def put_object(self, container, key, obj): # def get_object(self, container, key): # def delete_object(self, container, obj): # def delete_container(self, container): # def head_container(self, container): # def post_account(self, headers, query_string=None, data=None, # response_dict=None): # def setUp(self): # def output(self): # def setUp(self): # def setUp(self): # def tearDown(self): # def _create_metric(self, archive_policy_name="low"): # def trigger_processing(self, metrics=None): # REDIS_DB_INDEX = 0 # REDIS_DB_LOCK = threading.Lock() # ARCHIVE_POLICIES = { # 'no_granularity_match': archive_policy.ArchivePolicy( # "no_granularity_match", # 0, [ # # 2 second resolution for a day # archive_policy.ArchivePolicyItem( # granularity=numpy.timedelta64(2, 's'), # timespan=numpy.timedelta64(1, 'D'), # ), # ], # ), # 'low': archive_policy.ArchivePolicy( # "low", 0, [ # # 5 minutes resolution for an hour # archive_policy.ArchivePolicyItem( # granularity=numpy.timedelta64(5, 'm'), points=12), # # 1 hour resolution for a day # archive_policy.ArchivePolicyItem( # granularity=numpy.timedelta64(1, 'h'), points=24), # # 1 day resolution for a month # archive_policy.ArchivePolicyItem( # granularity=numpy.timedelta64(1, 'D'), points=30), # ], # ), # 'medium': archive_policy.ArchivePolicy( # "medium", 0, [ # # 1 minute resolution for an day # archive_policy.ArchivePolicyItem( # granularity=numpy.timedelta64(1, 'm'), points=60 * 24), # # 1 hour resolution for a week # archive_policy.ArchivePolicyItem( # granularity=numpy.timedelta64(1, 'h'), points=7 * 24), # # 1 day resolution for a year # archive_policy.ArchivePolicyItem( # granularity=numpy.timedelta64(1, 'D'), points=365), # ], # ), # 'high': archive_policy.ArchivePolicy( # "high", 0, [ # # 1 second resolution for an hour # archive_policy.ArchivePolicyItem( # granularity=numpy.timedelta64(1, 's'), points=3600), # # 1 minute resolution for a week # archive_policy.ArchivePolicyItem( # granularity=numpy.timedelta64(1, 'm'), points=60 * 24 * 7), # # 1 hour resolution for a year # archive_policy.ArchivePolicyItem( # granularity=numpy.timedelta64(1, 'h'), points=365 * 24), # ], # ), # } which might include code, classes, or functions. Output only the next line.
self.incoming, self.coord, self.storage, self.index,
Continue the code snippet: <|code_start|> def namedtuplefetchall(cursor): "Return all rows from a cursor as a namedtuple" desc = cursor.description nt_result = namedtuple('Result', [col[0] for col in desc]) return [nt_result(*row) for row in cursor.fetchall()] # Create your views here. def weather_query(request, id): check = check_if_auth_user(request) current_user = None if check: cursor = connection.cursor() if request.session["user_class"] == 'E': query = "SELECT * FROM User_expert WHERE `User_expert`.'user_id' = %s" else: query = "SELECT * FROM User_farmer WHERE `User_farmer`.'user_id' = %s" cursor.execute(query, [check, ]) result = namedtuplefetchall(cursor) current_user = result[0] if current_user is None: messages.error(request, "Perform Login first") return redirect("home:welcome") if request.session["user_class"] == 'F': messages.error(request, "Sorry, only experts are allowed to study location's weather.") <|code_end|> . Use current file imports: from django.shortcuts import render, redirect from django.core.urlresolvers import reverse from django.contrib import messages from django.db import connection, transaction from User.models import check_if_auth_user from collections import namedtuple and context (classes, functions, or code) from other files: # Path: User/models.py # def check_if_auth_user(request): # if (request.session is not None) and request.session.has_key("user_mail_id"): # return request.session["user_mail_id"] # else: # return None . Output only the next line.
return redirect("home:welcome")
Using the snippet: <|code_start|> messages.success(request, "Crop succesfully registered.") return redirect("crop:detail") context_data={ "crop_names" : all_crop_names, } return render(request,"register_crop.html",context_data) def view_crops(request): check = check_if_auth_user(request) current_user = None user_class = None if check: cursor = connection.cursor() user_class = request.session["user_class"] if user_class == 'E': query = "SELECT * FROM User_expert WHERE `User_expert`.'user_id' = %s" else: query = "SELECT * FROM User_farmer WHERE `User_farmer`.'user_id' = %s" cursor.execute(query, [check, ]) result = namedtuplefetchall(cursor) current_user = result[0] if current_user is None: messages.error(request, "Perform Login first") return redirect("home:welcome") if user_class == 'E': messages.error(request, "Sorry, but only farmers are allowed here.") <|code_end|> , determine the next line of code. You have imports: from django.shortcuts import render, get_object_or_404, redirect from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.contrib import messages from django.db import connection, transaction from User.models import check_if_auth_user from collections import namedtuple and context (class names, function names, or code) available: # Path: User/models.py # def check_if_auth_user(request): # if (request.session is not None) and request.session.has_key("user_mail_id"): # return request.session["user_mail_id"] # else: # return None . Output only the next line.
return redirect("home:welcome")
Given the code snippet: <|code_start|> for person in result: if person.user_id == temp_id: if bcrypt.verify(temp_pwd, person.user_pwd): messages.success(request, "Successful Login") request = start_user_session(request, temp_id, 'F') # 'F' = Farmer return redirect("home:welcome") else: messages.error(request, "Enter correct userID or password") return redirect("home:welcome") def signup_user(request): if check_if_auth_user(request): messages.error(request, "Log out to perform sign up") return redirect("home:welcome") name = request.POST.get('user_name') email = request.POST.get('user_email') pwd = request.POST.get('user_passwd') con = request.POST.get('user_contact') city = request.POST.get('user_city') state = request.POST.get('user_state') category = request.POST.get('user_category') if name and email and pwd and city and state: flag = 0 <|code_end|> , generate the next line using the imports in this file: from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse from django.contrib import messages from django.db import connection, transaction from passlib.hash import bcrypt from .models import start_user_session, check_if_auth_user, stop_user_session from collections import namedtuple import datetime import re and context (functions, classes, or occasionally code) from other files: # Path: User/models.py # def start_user_session(request, user_id, user_class): # if request.session is not None: # request.session["user_mail_id"] = user_id # request.session["user_class"] = user_class # return request # # def check_if_auth_user(request): # if (request.session is not None) and request.session.has_key("user_mail_id"): # return request.session["user_mail_id"] # else: # return None # # def stop_user_session(request): # if (request.session is not None) and request.session.has_key("user_mail_id"): # del request.session["user_mail_id"] # del request.session["user_class"] # return True # return False . Output only the next line.
if len(pwd) < 6:
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- from __future__ import unicode_literals # Create your views here. def namedtuplefetchall(cursor): "Return all rows from a cursor as a namedtuple" desc = cursor.description nt_result = namedtuple('Result', [col[0] for col in desc]) return [nt_result(*row) for row in cursor.fetchall()] # Create your views here. def view_profile(request): check = check_if_auth_user(request) current_user = None if not check: <|code_end|> , predict the next line using imports from the current file: from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse from django.contrib import messages from django.db import connection, transaction from passlib.hash import bcrypt from .models import start_user_session, check_if_auth_user, stop_user_session from collections import namedtuple import datetime import re and context including class names, function names, and sometimes code from other files: # Path: User/models.py # def start_user_session(request, user_id, user_class): # if request.session is not None: # request.session["user_mail_id"] = user_id # request.session["user_class"] = user_class # return request # # def check_if_auth_user(request): # if (request.session is not None) and request.session.has_key("user_mail_id"): # return request.session["user_mail_id"] # else: # return None # # def stop_user_session(request): # if (request.session is not None) and request.session.has_key("user_mail_id"): # del request.session["user_mail_id"] # del request.session["user_class"] # return True # return False . Output only the next line.
messages.error(request, "Log In to see your profile")
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import unicode_literals # Create your views here. def namedtuplefetchall(cursor): "Return all rows from a cursor as a namedtuple" desc = cursor.description nt_result = namedtuple('Result', [col[0] for col in desc]) return [nt_result(*row) for row in cursor.fetchall()] # Create your views here. def view_profile(request): check = check_if_auth_user(request) current_user = None if not check: messages.error(request, "Log In to see your profile") return redirect("home:welcome") cursor = connection.cursor() if request.session["user_class"] == 'E': query = "SELECT * FROM User_expert WHERE `User_expert`.'user_id' = %s" else: <|code_end|> . Write the next line using the current file imports: from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse from django.contrib import messages from django.db import connection, transaction from passlib.hash import bcrypt from .models import start_user_session, check_if_auth_user, stop_user_session from collections import namedtuple import datetime import re and context from other files: # Path: User/models.py # def start_user_session(request, user_id, user_class): # if request.session is not None: # request.session["user_mail_id"] = user_id # request.session["user_class"] = user_class # return request # # def check_if_auth_user(request): # if (request.session is not None) and request.session.has_key("user_mail_id"): # return request.session["user_mail_id"] # else: # return None # # def stop_user_session(request): # if (request.session is not None) and request.session.has_key("user_mail_id"): # del request.session["user_mail_id"] # del request.session["user_class"] # return True # return False , which may include functions, classes, or code. Output only the next line.
query = "SELECT * FROM User_farmer WHERE `User_farmer`.'user_id' = %s"
Given the code snippet: <|code_start|> messages.error(request, "Perform Login first") return redirect("home:welcome") cursor = connection.cursor() query = "SELECT * FROM post_post WHERE `post_post`.'post_id' = %s" cursor.execute(query, [id, ]) result = namedtuplefetchall(cursor) if not result: messages.error(request,"Given post was not found") return redirect("home:welcome") instance = result[0] if request.session["user_class"] == 'E': if current_user.auto_id != instance.author_expert_id: messages.error(request,"You can not edit this post!") return redirect(reverse("post:detail", kwargs={ "id":instance.post_id})) else: if current_user.auto_id != instance.author_farmer_id: messages.error(request,"You can not edit this post!") return redirect(reverse("post:detail", kwargs={ "id":instance.post_id})) if request.method == "POST": title = request.POST.get('post_title') disc = request.POST.get('post_disc') category = request.POST.get('post_category') try: image = request.FILES['post_image'] except Exception: <|code_end|> , generate the next line using the imports in this file: from django.shortcuts import render, get_object_or_404, redirect from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.contrib import messages from django.core.files.base import ContentFile from django.db import connection, transaction from .models import POST_CATEGORIES from User.models import check_if_auth_user from Farmers_Portal.settings import MEDIA_ROOT from collections import namedtuple import datetime import os import base64 and context (functions, classes, or occasionally code) from other files: # Path: post/models.py # POST_CATEGORIES = { # 1: "Crop Disease/Problems", # 2: "Climate Related", # 3: "Others", # } # # Path: User/models.py # def check_if_auth_user(request): # if (request.session is not None) and request.session.has_key("user_mail_id"): # return request.session["user_mail_id"] # else: # return None # # Path: Farmers_Portal/settings.py # MEDIA_ROOT = os.path.join(BASE_DIR,"media_cdn") . Output only the next line.
image = None
Given the code snippet: <|code_start|> return [nt_result(*row) for row in cursor.fetchall()] def remove_from_dir(dir_path, filename): full_path = os.path.join(dir_path, filename) if os.path.isfile(full_path): os.remove(full_path) #CRUD implemented here def posts_create(request): check = check_if_auth_user(request) current_user = None if check: cursor = connection.cursor() if request.session["user_class"] == 'E': query = "SELECT * FROM User_expert WHERE `User_expert`.'user_id' = %s" else: query = "SELECT * FROM User_farmer WHERE `User_farmer`.'user_id' = %s" cursor.execute(query, [check, ]) result = namedtuplefetchall(cursor) current_user = result[0] if current_user is None: messages.error(request, "Perform Login first") return redirect("home:welcome") if request.method == "POST": title = request.POST.get('post_title') disc = request.POST.get('post_disc') category = request.POST.get('post_category') <|code_end|> , generate the next line using the imports in this file: from django.shortcuts import render, get_object_or_404, redirect from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.contrib import messages from django.core.files.base import ContentFile from django.db import connection, transaction from .models import POST_CATEGORIES from User.models import check_if_auth_user from Farmers_Portal.settings import MEDIA_ROOT from collections import namedtuple import datetime import os import base64 and context (functions, classes, or occasionally code) from other files: # Path: post/models.py # POST_CATEGORIES = { # 1: "Crop Disease/Problems", # 2: "Climate Related", # 3: "Others", # } # # Path: User/models.py # def check_if_auth_user(request): # if (request.session is not None) and request.session.has_key("user_mail_id"): # return request.session["user_mail_id"] # else: # return None # # Path: Farmers_Portal/settings.py # MEDIA_ROOT = os.path.join(BASE_DIR,"media_cdn") . Output only the next line.
try:
Given the following code snippet before the placeholder: <|code_start|> image_read = image.read() file_content = ContentFile(image_read) # Iterate through the chunks. for chunk in file_content.chunks(): fout.write(chunk) fout.close() image_64_encode = base64.encodestring(image_read) cursor = connection.cursor() # Data modifying operation - commit required if image: query = "UPDATE post_post SET 'title' = %s, 'description' = %s, 'category' = %s, 'updated' = %s, 'image' = %s, 'image_db' = %s WHERE `post_post`.'post_id' = %s" cursor.execute(query, [title, disc, category, datetime.datetime.now(), image.name, image_64_encode, id]) else: query = "UPDATE post_post SET 'title' = %s, 'description' = %s, 'category' = %s, 'updated' = %s, 'image' = NULL, 'image_db' = NULL WHERE `post_post`.'post_id' = %s" cursor.execute(query, [title, disc, category, datetime.datetime.now(), id]) transaction.commit() messages.success(request, "Your post was successfully updated.") return redirect(reverse("post:detail", kwargs={ "id":id})) context_data={ "post_obj": instance, "category" : POST_CATEGORIES, } <|code_end|> , predict the next line using imports from the current file: from django.shortcuts import render, get_object_or_404, redirect from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.contrib import messages from django.core.files.base import ContentFile from django.db import connection, transaction from .models import POST_CATEGORIES from User.models import check_if_auth_user from Farmers_Portal.settings import MEDIA_ROOT from collections import namedtuple import datetime import os import base64 and context including class names, function names, and sometimes code from other files: # Path: post/models.py # POST_CATEGORIES = { # 1: "Crop Disease/Problems", # 2: "Climate Related", # 3: "Others", # } # # Path: User/models.py # def check_if_auth_user(request): # if (request.session is not None) and request.session.has_key("user_mail_id"): # return request.session["user_mail_id"] # else: # return None # # Path: Farmers_Portal/settings.py # MEDIA_ROOT = os.path.join(BASE_DIR,"media_cdn") . Output only the next line.
return render(request, "create_edit_post.html", context_data)
Given the code snippet: <|code_start|> cursor.execute(query, [check, ]) result = namedtuplefetchall(cursor) current_user = result[0] if not current_user: messages.error(request, "Please login first.") return redirect("home:welcome") if int(id) > 3: messages.error(request, "This is not a searchable query. Redirecting.") return redirect(reverse("home:query", kwargs={"id":id})) search_query = request.GET.get('search_query') if not search_query: messages.error(request, "Enter a suitable query. Try again") return redirect(reverse("home:query", kwargs={"id":id})) search_query += '%' # '%' because it will search for a pattern using LIKE op cursor.execute(QUERY_DICT[int(id)], [search_query, search_query, search_query]) result = namedtuplefetchall(cursor) result_header = [col[0] for col in cursor.description] if not result: messages.error(request, "No records match. Try again") result_farmers = [] <|code_end|> , generate the next line using the imports in this file: from django.shortcuts import render, get_object_or_404, redirect from django.http import HttpResponse, HttpResponseRedirect from django.core.urlresolvers import reverse from django.contrib import messages from django.db.models import Count from django.db import connection, transaction from post.models import POST_CATEGORIES from User.models import check_if_auth_user from collections import namedtuple and context (functions, classes, or occasionally code) from other files: # Path: post/models.py # POST_CATEGORIES = { # 1: "Crop Disease/Problems", # 2: "Climate Related", # 3: "Others", # } # # Path: User/models.py # def check_if_auth_user(request): # if (request.session is not None) and request.session.has_key("user_mail_id"): # return request.session["user_mail_id"] # else: # return None . Output only the next line.
if int(id) == 3:
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import unicode_literals # Register your models here. class LocationModelAdmin(admin.ModelAdmin): class Meta: model = Location list_display=["__unicode__"] class WeatherModelAdmin(admin.ModelAdmin): class Meta: model = Weather <|code_end|> using the current file's imports: from django.contrib import admin from .models import Location, Weather and any relevant context from other files: # Path: location/models.py # class Location(models.Model): # loc_id = models.AutoField(primary_key=True) # city = models.CharField(max_length=30) # state = models.CharField(max_length=30) # # def __unicode__(self): # return self.city + ', ' + self.state # def __str__(self): # return self.city + ', ' + self.state # # class Weather(models.Model): # wea_id = models.AutoField(primary_key=True) # temperature = models.IntegerField() # humidity = models.IntegerField() # date_record = models.DateField() # location = models.ForeignKey(Location, on_delete=models.CASCADE) # # def __unicode__(self): # return str(self.location) + ', ' + str(self.wea_id) # def __str__(self): # return str(self.location) + ', ' + str(self.wea_id) . Output only the next line.
list_display=["__unicode__"]
Based on the snippet: <|code_start|> u'î': ['I_CIRC'], u'ï': ['I_UML'], u'ð': ['ETH'], u'ñ': ['N_TILDE'], u'ò': ['O_GRAVE'], u'ó': ['O_ACUTE'], u'ô': ['O_CIRC'], u'õ': ['O_TILDE'], u'ö': ['O_UML'], u'÷': ['DIVIDE'], u'ø': ['O_SLASH'], u'ù': ['U_GRAVE'], u'ú': ['U_ACUTE'], u'û': ['U_CIRC'], u'ü': ['U_UML'], u'ý': ['Y_ACUTE'], u'þ': ['THORN'], u'ÿ': ['Y_UML'], u'Œ': ['CAP_OE'], u'œ': ['OE'], u'Š': ['CAP_S_CARON'], u'š': ['S_CARON'], u'Ÿ': ['CAP_Y_UML'], u'ƒ': ['FUNCTION'], u'—': ['MINUS'], u'’': ['SINGLE_QUOTE_RIGHT'], u'“': ['DOUBLE_QUOTE'], # this is usually what is meant <|code_end|> , predict the immediate next line with the help of imports: from .logger import getlog and context (classes, functions, sometimes code) from other files: # Path: shmaplib/logger.py # def getlog(): # """Get the global log setup by the __main__ script""" # # if LogData.log_instance is None: # setuplog() # # return LogData.log_instance . Output only the next line.
u'”': ['DOUBLE_QUOTE_RIGHT'],
Given snippet: <|code_start|> # Import common scripts CWD = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, CWD) sys.path.insert(0, os.path.normpath(os.path.join(CWD, '..', '..'))) # Import common shortcut mapper library log = shmaplib.setuplog(os.path.join(CWD, 'output.log')) def main(): parser = argparse.ArgumentParser(description="Converts Illustrator's raw files to an intermediate format.") parser.add_argument('-v', '--verbose', action='store_true', required=False, help="Verbose output") parser.add_argument('-o', '--output', required=True, help="Output filepath") parser.add_argument('source', help="Source: HTML file containing shortcuts saved directly from adobe's online documentation (/raw folder)") args = parser.parse_args() args.source = os.path.abspath(args.source) args.output = os.path.abspath(args.output) if not os.path.exists(args.source): print("Error: the input source file doesn't exist.") return # Verbosity setting on log <|code_end|> , continue by predicting the next line. Consider current file imports: import sys import os import glob import logging import argparse import re import shmaplib from shmaplib.adobe import AdobeDocsParser and context: # Path: shmaplib/adobe.py # class AdobeDocsParser(object): # """This parser scrapes shortcuts and contexts from an adobe shortcuts documentation html file, such as: # http://helpx.adobe.com/en/photoshop/using/default-keyboard-shortcuts.html # # It assumes the main relevant data is contained in a wrapper div: <div class="parsys main-pars">...</div> # From the contents of this div, it can extract shortcut contexts, shortcut names and keys for Windows and MacOS # """ # # def __init__(self, app_name): # super(AdobeDocsParser, self).__init__() # self.idata = IntermediateShortcutData(app_name) # # @staticmethod # def _clean_text(text): # text = text.replace(u'\n', u' ').strip(u' ').replace(u'\xa0', u' ') # # Remove stuff within braces # text = re.sub("([\(]).*?([\)])", "", text) # # Remove meta-data tags # text = text.replace(u'†', u'').replace(u'‡', u'').strip(u'*') # # return text.strip(u' ') # # def parse(self, source_file_path): # if not os.path.exists(source_file_path): # log.error("Source file '%s' does not exist", source_file_path) # return # # # Use BeautifulSoup to parse the html document # doc = BeautifulSoup(_get_file_contents(source_file_path)) # main_wrapper_div = doc.find("div", class_="parsys main-pars") # if main_wrapper_div is None: # main_wrapper_div = doc.find("div", id="main") # sections = main_wrapper_div.find_all("div", class_="parbase") # # # Iterate sections (headers are contexts, tables contain the shortcuts) # context_name = None # for section in sections: # # This section is a header, the only relevant information here is the context # if 'header' in section['class']: # h2 = section.find('h2') # context_name = str(h2.contents[0]).replace('\n', ' ').strip(' ') # log.debug('Scanning context: "%s"', context_name) # # # This is a section containing the shortcuts table # elif 'table' in section['class']: # rows = section.find('tbody').find_all('tr') # # for row in rows: # cols = row.find_all("td") # if len(cols) != 3: # continue # # shortcut_name = self._clean_text(cols[0].get_text()) # keys_win = self._clean_text(cols[1].get_text()) # keys_mac = self._clean_text(cols[2].get_text()) # # self.idata.add_shortcut(context_name, shortcut_name, keys_win, keys_mac) # log.debug('...found shortcut "%s"', shortcut_name) # # return self.idata which might include code, classes, or functions. Output only the next line.
log.setLevel(logging.INFO)
Next line prediction: <|code_start|> # Import common scripts CWD = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, CWD) sys.path.insert(0, os.path.normpath(os.path.join(CWD, '..', '..'))) # Import common shortcut mapper library <|code_end|> . Use current file imports: (import sys import os import glob import logging import argparse import re import shmaplib from shmaplib.adobe import AdobeDocsParser) and context including class names, function names, or small code snippets from other files: # Path: shmaplib/adobe.py # class AdobeDocsParser(object): # """This parser scrapes shortcuts and contexts from an adobe shortcuts documentation html file, such as: # http://helpx.adobe.com/en/photoshop/using/default-keyboard-shortcuts.html # # It assumes the main relevant data is contained in a wrapper div: <div class="parsys main-pars">...</div> # From the contents of this div, it can extract shortcut contexts, shortcut names and keys for Windows and MacOS # """ # # def __init__(self, app_name): # super(AdobeDocsParser, self).__init__() # self.idata = IntermediateShortcutData(app_name) # # @staticmethod # def _clean_text(text): # text = text.replace(u'\n', u' ').strip(u' ').replace(u'\xa0', u' ') # # Remove stuff within braces # text = re.sub("([\(]).*?([\)])", "", text) # # Remove meta-data tags # text = text.replace(u'†', u'').replace(u'‡', u'').strip(u'*') # # return text.strip(u' ') # # def parse(self, source_file_path): # if not os.path.exists(source_file_path): # log.error("Source file '%s' does not exist", source_file_path) # return # # # Use BeautifulSoup to parse the html document # doc = BeautifulSoup(_get_file_contents(source_file_path)) # main_wrapper_div = doc.find("div", class_="parsys main-pars") # if main_wrapper_div is None: # main_wrapper_div = doc.find("div", id="main") # sections = main_wrapper_div.find_all("div", class_="parbase") # # # Iterate sections (headers are contexts, tables contain the shortcuts) # context_name = None # for section in sections: # # This section is a header, the only relevant information here is the context # if 'header' in section['class']: # h2 = section.find('h2') # context_name = str(h2.contents[0]).replace('\n', ' ').strip(' ') # log.debug('Scanning context: "%s"', context_name) # # # This is a section containing the shortcuts table # elif 'table' in section['class']: # rows = section.find('tbody').find_all('tr') # # for row in rows: # cols = row.find_all("td") # if len(cols) != 3: # continue # # shortcut_name = self._clean_text(cols[0].get_text()) # keys_win = self._clean_text(cols[1].get_text()) # keys_mac = self._clean_text(cols[2].get_text()) # # self.idata.add_shortcut(context_name, shortcut_name, keys_win, keys_mac) # log.debug('...found shortcut "%s"', shortcut_name) # # return self.idata . Output only the next line.
log = shmaplib.setuplog(os.path.join(CWD, 'output.log'))
Next line prediction: <|code_start|> # Import common scripts CWD = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, CWD) sys.path.insert(0, os.path.normpath(os.path.join(CWD, '..', '..'))) # Import common shortcut mapper library log = shmaplib.setuplog(os.path.join(CWD, 'output.log')) def main(): parser = argparse.ArgumentParser(description="Converts Lightrooms's raw files to an intermediate format.") parser.add_argument('-v', '--verbose', action='store_true', required=False, help="Verbose output") parser.add_argument('-o', '--output', required=True, help="Output filepath") parser.add_argument('source', help="Source: HTML file containing shortcuts saved directly from adobe's online documentation (/raw folder)") args = parser.parse_args() args.source = os.path.abspath(args.source) args.output = os.path.abspath(args.output) if not os.path.exists(args.source): print("Error: the input source file doesn't exist.") return # Verbosity setting on log log.setLevel(logging.INFO) <|code_end|> . Use current file imports: (import sys import os import glob import logging import argparse import re import shmaplib from shmaplib.adobe import AdobeDocsParser) and context including class names, function names, or small code snippets from other files: # Path: shmaplib/adobe.py # class AdobeDocsParser(object): # """This parser scrapes shortcuts and contexts from an adobe shortcuts documentation html file, such as: # http://helpx.adobe.com/en/photoshop/using/default-keyboard-shortcuts.html # # It assumes the main relevant data is contained in a wrapper div: <div class="parsys main-pars">...</div> # From the contents of this div, it can extract shortcut contexts, shortcut names and keys for Windows and MacOS # """ # # def __init__(self, app_name): # super(AdobeDocsParser, self).__init__() # self.idata = IntermediateShortcutData(app_name) # # @staticmethod # def _clean_text(text): # text = text.replace(u'\n', u' ').strip(u' ').replace(u'\xa0', u' ') # # Remove stuff within braces # text = re.sub("([\(]).*?([\)])", "", text) # # Remove meta-data tags # text = text.replace(u'†', u'').replace(u'‡', u'').strip(u'*') # # return text.strip(u' ') # # def parse(self, source_file_path): # if not os.path.exists(source_file_path): # log.error("Source file '%s' does not exist", source_file_path) # return # # # Use BeautifulSoup to parse the html document # doc = BeautifulSoup(_get_file_contents(source_file_path)) # main_wrapper_div = doc.find("div", class_="parsys main-pars") # if main_wrapper_div is None: # main_wrapper_div = doc.find("div", id="main") # sections = main_wrapper_div.find_all("div", class_="parbase") # # # Iterate sections (headers are contexts, tables contain the shortcuts) # context_name = None # for section in sections: # # This section is a header, the only relevant information here is the context # if 'header' in section['class']: # h2 = section.find('h2') # context_name = str(h2.contents[0]).replace('\n', ' ').strip(' ') # log.debug('Scanning context: "%s"', context_name) # # # This is a section containing the shortcuts table # elif 'table' in section['class']: # rows = section.find('tbody').find_all('tr') # # for row in rows: # cols = row.find_all("td") # if len(cols) != 3: # continue # # shortcut_name = self._clean_text(cols[0].get_text()) # keys_win = self._clean_text(cols[1].get_text()) # keys_mac = self._clean_text(cols[2].get_text()) # # self.idata.add_shortcut(context_name, shortcut_name, keys_win, keys_mac) # log.debug('...found shortcut "%s"', shortcut_name) # # return self.idata . Output only the next line.
if args.verbose:
Given snippet: <|code_start|> # Import common scripts CWD = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, CWD) sys.path.insert(0, os.path.normpath(os.path.join(CWD, '..'))) # Import common shortcut mapper library <|code_end|> , continue by predicting the next line. Consider current file imports: import sys import os import glob import logging import argparse import shmaplib from shmaplib.constants import DIR_SOURCES and context: # Path: shmaplib/constants.py # DIR_SOURCES = os.path.normpath(os.path.join(DIR_ROOT, "sources")) which might include code, classes, or functions. Output only the next line.
log = shmaplib.setuplog(os.path.join(CWD, 'output.log'))
Given the following code snippet before the placeholder: <|code_start|> def basename(self): return self._path.basename() def has_extension(self, extension=None): return self._path.has_extension(extension) def has_extension_from(self, candidates_extensions): for any_extension in candidates_extensions: if self._path.has_extension(any_extension): return True def extension(self): return self._path.extension() def container(self): return self.fileSystem.open(self._path.container()) def sibling(self, name): return self.fileSystem.open(self._path.container() / name) @classmethod def files(cls): return [] def files_that_matches(self, pattern): path = Path.fromText(str(self._path) + "/" + str(pattern)) directory = self.fileSystem.open(path.container()) return [any_file for any_file in directory.files() if str(any_file.path()) == str(path) <|code_end|> , predict the next line using imports from the current file: import os import shutil import shutil from flap.util.path import Path, ROOT and context including class names, function names, and sometimes code from other files: # Path: flap/util/path.py # class Path: # # @staticmethod # def fromText(text): # pattern = re.compile("[\\\\/]+") # parts = [Unit(eachPart) for eachPart in pattern.split(text)] # # Remove the last one, if it is "" (e.g., in project/img/) # if parts[-1].is_root(): # parts = parts[:-1] # return Path(parts) # # def __init__(self, parts): # if not parts: # raise ValueError("Invalid path, no part given") # self._parts = [part for (index, part) in enumerate(parts) # if not (part.is_current_directory() and index > 0)] # # def resource(self): # return self._parts[-1] # # def fullname(self): # return self.resource().fullname() # # def basename(self): # return self.resource().basename() # # def extension(self): # return self.resource().extension() # # def has_extension(self, extension=None): # if extension: # return self.resource().has_extension(extension) # else: # return self.resource().has_any_extension() # # def container(self): # if len(self._parts) == 1: # if self._parts[0].is_root(): # raise ValueError("The root directory has no parent") # else: # return Path([Unit(".")]) # return Path(self._parts[:-1]) # # def isRoot(self): # return self.resource().is_root() # # def is_absolute(self): # return self._parts[0].is_root() # # def absolute_from(self, current_directory): # parts = self.parts() # if parts[0].is_root(): # return self # elif parts[0].is_current_directory(): # parts = current_directory.parts() + parts[1:] # elif parts[0].is_parent_directory(): # parts = current_directory.container().parts() + parts[1:] # else: # parts = current_directory.parts() + parts # return Path.fromText("/".join([each.fullname() for each in parts])) # # def relative_to(self, location): # position = 0 # while position < len(location._parts) \ # and self._parts[position] == location._parts[position]: # position += 1 # return Path(self._parts[position:]) # # def without_extension(self): # return Path(self._parts[:-1] + [Unit(self._parts[-1].basename())]) # # def parts(self): # return self._parts # # def __contains__(self, other): # return self != other and self.__str__() in other.__str__() # # def __truediv__(self, other): # if isinstance(other, str): # return Path(self._parts + Path.fromText(other)._parts) # elif isinstance(other, Path): # return Path(self._parts + other._parts) # # def __repr__(self): # return "/".join([eachPart.fullname() for eachPart in self._parts]) # # def __str__(self): # return self.__repr__() # # def __eq__(self, other): # return isinstance(other, Path) and self._parts == other._parts # # def __hash__(self): # return self.__str__().__hash__() # # ROOT = Path([Unit("")]) . Output only the next line.
or str(any_file.path()).startswith(str(path) + ".")]
Continue the code snippet: <|code_start|> def is_file(): return True def is_directory(self): return not self.is_file() @classmethod def exists(cls): return True def is_missing(self): return not self.exists() def contains(self, content): return self._content == content def content(self): if not self._content: self._content = self.fileSystem.load(self._path) return self._content def path(self): return self._path def fullname(self): return self._path.fullname() def basename(self): return self._path.basename() <|code_end|> . Use current file imports: import os import shutil import shutil from flap.util.path import Path, ROOT and context (classes, functions, or code) from other files: # Path: flap/util/path.py # class Path: # # @staticmethod # def fromText(text): # pattern = re.compile("[\\\\/]+") # parts = [Unit(eachPart) for eachPart in pattern.split(text)] # # Remove the last one, if it is "" (e.g., in project/img/) # if parts[-1].is_root(): # parts = parts[:-1] # return Path(parts) # # def __init__(self, parts): # if not parts: # raise ValueError("Invalid path, no part given") # self._parts = [part for (index, part) in enumerate(parts) # if not (part.is_current_directory() and index > 0)] # # def resource(self): # return self._parts[-1] # # def fullname(self): # return self.resource().fullname() # # def basename(self): # return self.resource().basename() # # def extension(self): # return self.resource().extension() # # def has_extension(self, extension=None): # if extension: # return self.resource().has_extension(extension) # else: # return self.resource().has_any_extension() # # def container(self): # if len(self._parts) == 1: # if self._parts[0].is_root(): # raise ValueError("The root directory has no parent") # else: # return Path([Unit(".")]) # return Path(self._parts[:-1]) # # def isRoot(self): # return self.resource().is_root() # # def is_absolute(self): # return self._parts[0].is_root() # # def absolute_from(self, current_directory): # parts = self.parts() # if parts[0].is_root(): # return self # elif parts[0].is_current_directory(): # parts = current_directory.parts() + parts[1:] # elif parts[0].is_parent_directory(): # parts = current_directory.container().parts() + parts[1:] # else: # parts = current_directory.parts() + parts # return Path.fromText("/".join([each.fullname() for each in parts])) # # def relative_to(self, location): # position = 0 # while position < len(location._parts) \ # and self._parts[position] == location._parts[position]: # position += 1 # return Path(self._parts[position:]) # # def without_extension(self): # return Path(self._parts[:-1] + [Unit(self._parts[-1].basename())]) # # def parts(self): # return self._parts # # def __contains__(self, other): # return self != other and self.__str__() in other.__str__() # # def __truediv__(self, other): # if isinstance(other, str): # return Path(self._parts + Path.fromText(other)._parts) # elif isinstance(other, Path): # return Path(self._parts + other._parts) # # def __repr__(self): # return "/".join([eachPart.fullname() for eachPart in self._parts]) # # def __str__(self): # return self.__repr__() # # def __eq__(self, other): # return isinstance(other, Path) and self._parts == other._parts # # def __hash__(self): # return self.__str__().__hash__() # # ROOT = Path([Unit("")]) . Output only the next line.
def has_extension(self, extension=None):
Predict the next line after this snippet: <|code_start|> self._log("On command:" + str(token)) command = str(token) command_name = command[1:] if command_name not in self._definitions: self._log("Unknown command '{}'.\n" "\tCandidates are {}" .format(command_name, self._definitions.available_macros)) self._print([token]) else: macro = self._definitions[command_name] invocation = macro.capture_invocation(self, token) self.process_invocation(invocation) def process_invocation(self, invocation): self._log("On invocation: " + invocation.as_text) macro = self.look_up(invocation.command_name) if macro.is_user_defined: self._log("User defined!") self.open_scope() for each_argument, tokens in invocation.arguments.items(): self._log(f"Evaluating argument {each_argument}") evaluated = self.evaluate(tokens) self._definitions[each_argument] = evaluated self._log("Evaluating macro body") output = self.evaluate(macro._body) self._print(output) self.close_scope() <|code_end|> using the current file's imports: from flap.latex.commons import Context from flap.latex.processor import Processor and any relevant context from other files: # Path: flap/latex/commons.py # class Context: # # def __init__(self, parent=None, definitions=None): # self._definitions = definitions or dict() # self._parent = parent # # def define(self, macro): # logger.debug("Defining macro {}".format(macro.name)) # self._definitions[macro.name] = macro # # def look_up(self, symbol): # result = self._definitions.get(symbol, None) # if not result and self._parent: # return self._parent.look_up(symbol) # return result # # @property # def available_macros(self): # return list(self._definitions.keys()) # # def items(self): # return self._definitions.items() # # def __setitem__(self, key, value): # self._definitions[key] = value # # def __getitem__(self, key): # if self._parent and key not in self._definitions: # return self._parent[key] # else: # return self._definitions.get(key) # # def __contains__(self, key): # return key in self._definitions or ( # self._parent and key in self._parent) # # Path: flap/latex/processor.py # class Processor: # # def __init__(self, name, tokens, factory, environment): # self._create = factory # self._tokens = self._create.as_stream(tokens) # self._definitions = environment # self._level = 0 # self._name = name # # Outputs # self._outputs = [{"is_active": True, "data": []}] # # def process(self): # while not self._tokens.is_empty: # token = self._tokens.take() # token.send_to(self) # self._log("----------- DONE") # return self._outputs[-1]["data"] # # def process_control(self, token): # self._default(token) # # def process_begin_group(self, token): # self._default(token) # # def process_end_group(self, end_group): # self._default(end_group) # # def process_character(self, character): # self._default(character) # # def process_comment(self, comment): # self._default(comment) # # def process_parameter(self, parameter): # self._default(parameter) # # def process_white_spaces(self, space): # self._default(space) # # def process_new_line(self, new_line): # self._default(new_line) # # def process_others(self, other): # self._default(other) # # def process_invocation(self, invocation): # self._default(invocation) # # def _default(self, token): # self._log("On " + str(token)) # self._print([token]) # # # Helpers # # # Debugging # # def _log(self, message): # logger.debug(self._name + ": " + message) # # # Methods that manage the output # # def _print(self, tokens): # if self._outputs[-1]["is_active"]: # self._outputs[-1]["data"] += tokens # # def push_new_output(self): # self._log("Setup new output") # new_output = {"is_active": True, "data": []} # self._outputs.append(new_output) # # def pop_output(self): # self._log("Discarding current output: " + self.output_as_text()) # output = self._outputs.pop() # return output["data"] # # def output_as_text(self): # return "".join(each_token.as_text # for each_token in self._outputs[-1]["data"]) # # # Scope and look up # # def open_scope(self): # self._definitions = Context(self._definitions) # # def close_scope(self): # self._definitions = self._definitions._parent # # def look_up(self, symbol): # return self._definitions.look_up(symbol) # # def find_environment(self, invocation): # symbol = "".join(each_token.as_text # for each_token # in invocation.argument("environment")[1:-1]) # environment = self._definitions.look_up(symbol) # return environment # # def _debug(self, category, action, tokens): # text = "" # position = "None" # if not len(tokens) == 0: # text = truncate(self._as_text(tokens), 30) # position = tokens[-1].location, # logger.debug( # "GL={} {} {} {}".format( # self._level, # action, # category, # text # )) # # @staticmethod # def _as_text(tokens): # return "".join(map(str, tokens)) . Output only the next line.
else: # Built-in commands
Here is a snippet: <|code_start|>#!/usr/bin/env python # # This file is part of Flap. # # Flap is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Flap is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Flap. If not, see <http://www.gnu.org/licenses/>. # class Interpreter(Processor): def __init__(self, tokens, factory, environment, name=None): super().__init__(name or "INTERPRETER", <|code_end|> . Write the next line using the current file imports: from flap.latex.commons import Context from flap.latex.processor import Processor and context from other files: # Path: flap/latex/commons.py # class Context: # # def __init__(self, parent=None, definitions=None): # self._definitions = definitions or dict() # self._parent = parent # # def define(self, macro): # logger.debug("Defining macro {}".format(macro.name)) # self._definitions[macro.name] = macro # # def look_up(self, symbol): # result = self._definitions.get(symbol, None) # if not result and self._parent: # return self._parent.look_up(symbol) # return result # # @property # def available_macros(self): # return list(self._definitions.keys()) # # def items(self): # return self._definitions.items() # # def __setitem__(self, key, value): # self._definitions[key] = value # # def __getitem__(self, key): # if self._parent and key not in self._definitions: # return self._parent[key] # else: # return self._definitions.get(key) # # def __contains__(self, key): # return key in self._definitions or ( # self._parent and key in self._parent) # # Path: flap/latex/processor.py # class Processor: # # def __init__(self, name, tokens, factory, environment): # self._create = factory # self._tokens = self._create.as_stream(tokens) # self._definitions = environment # self._level = 0 # self._name = name # # Outputs # self._outputs = [{"is_active": True, "data": []}] # # def process(self): # while not self._tokens.is_empty: # token = self._tokens.take() # token.send_to(self) # self._log("----------- DONE") # return self._outputs[-1]["data"] # # def process_control(self, token): # self._default(token) # # def process_begin_group(self, token): # self._default(token) # # def process_end_group(self, end_group): # self._default(end_group) # # def process_character(self, character): # self._default(character) # # def process_comment(self, comment): # self._default(comment) # # def process_parameter(self, parameter): # self._default(parameter) # # def process_white_spaces(self, space): # self._default(space) # # def process_new_line(self, new_line): # self._default(new_line) # # def process_others(self, other): # self._default(other) # # def process_invocation(self, invocation): # self._default(invocation) # # def _default(self, token): # self._log("On " + str(token)) # self._print([token]) # # # Helpers # # # Debugging # # def _log(self, message): # logger.debug(self._name + ": " + message) # # # Methods that manage the output # # def _print(self, tokens): # if self._outputs[-1]["is_active"]: # self._outputs[-1]["data"] += tokens # # def push_new_output(self): # self._log("Setup new output") # new_output = {"is_active": True, "data": []} # self._outputs.append(new_output) # # def pop_output(self): # self._log("Discarding current output: " + self.output_as_text()) # output = self._outputs.pop() # return output["data"] # # def output_as_text(self): # return "".join(each_token.as_text # for each_token in self._outputs[-1]["data"]) # # # Scope and look up # # def open_scope(self): # self._definitions = Context(self._definitions) # # def close_scope(self): # self._definitions = self._definitions._parent # # def look_up(self, symbol): # return self._definitions.look_up(symbol) # # def find_environment(self, invocation): # symbol = "".join(each_token.as_text # for each_token # in invocation.argument("environment")[1:-1]) # environment = self._definitions.look_up(symbol) # return environment # # def _debug(self, category, action, tokens): # text = "" # position = "None" # if not len(tokens) == 0: # text = truncate(self._as_text(tokens), 30) # position = tokens[-1].location, # logger.debug( # "GL={} {} {} {}".format( # self._level, # action, # category, # text # )) # # @staticmethod # def _as_text(tokens): # return "".join(map(str, tokens)) , which may include functions, classes, or code. Output only the next line.
tokens,
Given the following code snippet before the placeholder: <|code_start|># but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Flap. If not, see <http://www.gnu.org/licenses/>. # class TokenTests(TestCase): def setUp(self): self._tokens = TokenFactory(SymbolTable.default()) self._token = self._tokens.character(Position(1, 1), "a") def test_equals_itself(self): self.assertEqual(self._token, self._token) def test_equals_a_similar_tokens(self): self.assertEqual( self._tokens.character( Position( 1, 1), "a"), self._token) def test_differs_from_a_different_character(self): <|code_end|> , predict the next line using imports from the current file: from unittest import TestCase, main from flap.latex.commons import Position from flap.latex.tokens import SymbolTable, Token, TokenFactory and context including class names, function names, and sometimes code from other files: # Path: flap/latex/commons.py # class Position: # # UNKNOWN = "Unknown source file" # REPRESENTATION = "{source} @({line}, {column})" # # def __init__(self, line, column, source=None): # self._source = source or self.UNKNOWN # self._line = line # self._column = column # # @property # def source(self): # return self._source # # @property # def line(self): # return self._line # # @property # def column(self): # return self._column # # def next_line(self): # return Position(self._line + 1, 0, self._source) # # def next_character(self): # return Position(self._line, self._column + 1, self._source) # # def __eq__(self, other): # if not isinstance(other, Position): # return False # return self._line == other._line and \ # self._column == other._column # # def __repr__(self): # return self.REPRESENTATION.format( # source=self._source, line=self._line, column=self._column) # # Path: flap/latex/tokens.py # class Token: # class TokenFactory: # DISPLAY = "{category}({text}){location}" # def __init__(self, text, category, location): # def send_to(self, parser): # def location(self): # def as_text(self): # def satisfies(self, predicate): # def is_a(self, category): # def is_ignored(self): # def is_a_comment(self): # def is_a_new_line(self): # def is_a_command(self): # def has_text(self, text): # def ends_with(self, text): # def ends_the_text(self): # def is_a_character(self): # def is_a_parameter(self): # def begins_a_group(self): # def ends_a_group(self): # def is_a_whitespace(self): # def __eq__(self, other_token): # def __repr__(self): # def __str__(self): # def __init__(self, symbol_table): # def character(location, text): # def command(location, text): # def white_space(location, text): # def comment(location, text): # def new_line(self, location, text=None): # def begin_group(self, location, text=None): # def end_group(self, location, text=None): # def parameter(location, key): # def math(self, location): # def superscript(self, location, text=None): # def subscript(self, location, text=None): # def non_breaking_space(self, location, text=None): # def others(self, location, text=None): . Output only the next line.
self.assertNotEqual(
Using the snippet: <|code_start|> class TokenTests(TestCase): def setUp(self): self._tokens = TokenFactory(SymbolTable.default()) self._token = self._tokens.character(Position(1, 1), "a") def test_equals_itself(self): self.assertEqual(self._token, self._token) def test_equals_a_similar_tokens(self): self.assertEqual( self._tokens.character( Position( 1, 1), "a"), self._token) def test_differs_from_a_different_character(self): self.assertNotEqual( self._tokens.character( Position( 1, 1), "b"), self._token) <|code_end|> , determine the next line of code. You have imports: from unittest import TestCase, main from flap.latex.commons import Position from flap.latex.tokens import SymbolTable, Token, TokenFactory and context (class names, function names, or code) available: # Path: flap/latex/commons.py # class Position: # # UNKNOWN = "Unknown source file" # REPRESENTATION = "{source} @({line}, {column})" # # def __init__(self, line, column, source=None): # self._source = source or self.UNKNOWN # self._line = line # self._column = column # # @property # def source(self): # return self._source # # @property # def line(self): # return self._line # # @property # def column(self): # return self._column # # def next_line(self): # return Position(self._line + 1, 0, self._source) # # def next_character(self): # return Position(self._line, self._column + 1, self._source) # # def __eq__(self, other): # if not isinstance(other, Position): # return False # return self._line == other._line and \ # self._column == other._column # # def __repr__(self): # return self.REPRESENTATION.format( # source=self._source, line=self._line, column=self._column) # # Path: flap/latex/tokens.py # class Token: # class TokenFactory: # DISPLAY = "{category}({text}){location}" # def __init__(self, text, category, location): # def send_to(self, parser): # def location(self): # def as_text(self): # def satisfies(self, predicate): # def is_a(self, category): # def is_ignored(self): # def is_a_comment(self): # def is_a_new_line(self): # def is_a_command(self): # def has_text(self, text): # def ends_with(self, text): # def ends_the_text(self): # def is_a_character(self): # def is_a_parameter(self): # def begins_a_group(self): # def ends_a_group(self): # def is_a_whitespace(self): # def __eq__(self, other_token): # def __repr__(self): # def __str__(self): # def __init__(self, symbol_table): # def character(location, text): # def command(location, text): # def white_space(location, text): # def comment(location, text): # def new_line(self, location, text=None): # def begin_group(self, location, text=None): # def end_group(self, location, text=None): # def parameter(location, key): # def math(self, location): # def superscript(self, location, text=None): # def subscript(self, location, text=None): # def non_breaking_space(self, location, text=None): # def others(self, location, text=None): . Output only the next line.
def test_differs_from_an_object_of_another_type(self):
Predict the next line for this snippet: <|code_start|># (at your option) any later version. # # Flap is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Flap. If not, see <http://www.gnu.org/licenses/>. # class TokenTests(TestCase): def setUp(self): self._tokens = TokenFactory(SymbolTable.default()) self._token = self._tokens.character(Position(1, 1), "a") def test_equals_itself(self): self.assertEqual(self._token, self._token) def test_equals_a_similar_tokens(self): self.assertEqual( self._tokens.character( Position( 1, 1), "a"), <|code_end|> with the help of current file imports: from unittest import TestCase, main from flap.latex.commons import Position from flap.latex.tokens import SymbolTable, Token, TokenFactory and context from other files: # Path: flap/latex/commons.py # class Position: # # UNKNOWN = "Unknown source file" # REPRESENTATION = "{source} @({line}, {column})" # # def __init__(self, line, column, source=None): # self._source = source or self.UNKNOWN # self._line = line # self._column = column # # @property # def source(self): # return self._source # # @property # def line(self): # return self._line # # @property # def column(self): # return self._column # # def next_line(self): # return Position(self._line + 1, 0, self._source) # # def next_character(self): # return Position(self._line, self._column + 1, self._source) # # def __eq__(self, other): # if not isinstance(other, Position): # return False # return self._line == other._line and \ # self._column == other._column # # def __repr__(self): # return self.REPRESENTATION.format( # source=self._source, line=self._line, column=self._column) # # Path: flap/latex/tokens.py # class Token: # class TokenFactory: # DISPLAY = "{category}({text}){location}" # def __init__(self, text, category, location): # def send_to(self, parser): # def location(self): # def as_text(self): # def satisfies(self, predicate): # def is_a(self, category): # def is_ignored(self): # def is_a_comment(self): # def is_a_new_line(self): # def is_a_command(self): # def has_text(self, text): # def ends_with(self, text): # def ends_the_text(self): # def is_a_character(self): # def is_a_parameter(self): # def begins_a_group(self): # def ends_a_group(self): # def is_a_whitespace(self): # def __eq__(self, other_token): # def __repr__(self): # def __str__(self): # def __init__(self, symbol_table): # def character(location, text): # def command(location, text): # def white_space(location, text): # def comment(location, text): # def new_line(self, location, text=None): # def begin_group(self, location, text=None): # def end_group(self, location, text=None): # def parameter(location, key): # def math(self, location): # def superscript(self, location, text=None): # def subscript(self, location, text=None): # def non_breaking_space(self, location, text=None): # def others(self, location, text=None): , which may contain function names, class names, or code. Output only the next line.
self._token)
Given the code snippet: <|code_start|> path = Path.fromText("C:\\Users\\franckc\\pub\\JOCC\\main.tex") self.verify_parts(path, ["C:", "Users", "franckc", "pub", "JOCC", "main.tex"]) def verify_parts(self, path, expectedParts, ): parts = [each.fullname() for each in path.parts()] self.assertEqual(parts, expectedParts) def testPathWithNewlines(self): path = Path.fromText("/Root/Foo\nBar\nBaz/home") self.verify_parts(path, ["", "Root", "FooBarBaz", "home"]) def test_remove_trailing_spaces(self): path = Path.fromText("/text/ blabla /test.txt") self.assertEqual(path, Path.fromText("/text/blabla/test.txt")) def test_is_absolute_on_unix_paths(self): path = Path.fromText("/home/franck/test.tex") self.assertTrue(path.is_absolute()) def test_is_absolute_on_windows_paths(self): path = Path.fromText("C:\\Users\\franckc\\file.txt") self.assertTrue(path.is_absolute()) def test_is_absolute_with_relative(self): path = Path.fromText("franck/test.tex") self.assertFalse(path.is_absolute()) <|code_end|> , generate the next line using the imports in this file: import unittest from flap.util.path import Path, ROOT, TEMP, CURRENT_DIRECTORY from tempfile import gettempdir and context (functions, classes, or occasionally code) from other files: # Path: flap/util/path.py # class Path: # # @staticmethod # def fromText(text): # pattern = re.compile("[\\\\/]+") # parts = [Unit(eachPart) for eachPart in pattern.split(text)] # # Remove the last one, if it is "" (e.g., in project/img/) # if parts[-1].is_root(): # parts = parts[:-1] # return Path(parts) # # def __init__(self, parts): # if not parts: # raise ValueError("Invalid path, no part given") # self._parts = [part for (index, part) in enumerate(parts) # if not (part.is_current_directory() and index > 0)] # # def resource(self): # return self._parts[-1] # # def fullname(self): # return self.resource().fullname() # # def basename(self): # return self.resource().basename() # # def extension(self): # return self.resource().extension() # # def has_extension(self, extension=None): # if extension: # return self.resource().has_extension(extension) # else: # return self.resource().has_any_extension() # # def container(self): # if len(self._parts) == 1: # if self._parts[0].is_root(): # raise ValueError("The root directory has no parent") # else: # return Path([Unit(".")]) # return Path(self._parts[:-1]) # # def isRoot(self): # return self.resource().is_root() # # def is_absolute(self): # return self._parts[0].is_root() # # def absolute_from(self, current_directory): # parts = self.parts() # if parts[0].is_root(): # return self # elif parts[0].is_current_directory(): # parts = current_directory.parts() + parts[1:] # elif parts[0].is_parent_directory(): # parts = current_directory.container().parts() + parts[1:] # else: # parts = current_directory.parts() + parts # return Path.fromText("/".join([each.fullname() for each in parts])) # # def relative_to(self, location): # position = 0 # while position < len(location._parts) \ # and self._parts[position] == location._parts[position]: # position += 1 # return Path(self._parts[position:]) # # def without_extension(self): # return Path(self._parts[:-1] + [Unit(self._parts[-1].basename())]) # # def parts(self): # return self._parts # # def __contains__(self, other): # return self != other and self.__str__() in other.__str__() # # def __truediv__(self, other): # if isinstance(other, str): # return Path(self._parts + Path.fromText(other)._parts) # elif isinstance(other, Path): # return Path(self._parts + other._parts) # # def __repr__(self): # return "/".join([eachPart.fullname() for eachPart in self._parts]) # # def __str__(self): # return self.__repr__() # # def __eq__(self, other): # return isinstance(other, Path) and self._parts == other._parts # # def __hash__(self): # return self.__str__().__hash__() # # ROOT = Path([Unit("")]) # # TEMP = Path.fromText(tempfile.gettempdir()) # # CURRENT_DIRECTORY = Path([Unit(".")]) . Output only the next line.
if __name__ == "__main__":
Given snippet: <|code_start|> self.assertEqual(path, ROOT / "Users" / "franckc" / "file.txt") def test_parsing_directory(self): path = Path.fromText("project/img/") parts = [each.fullname() for each in path.parts()] self.assertEqual(parts, ["project", "img"], "Wrong parts!") def testParts(self): path = Path.fromText("C:\\Users\\franckc\\pub\\JOCC\\main.tex") self.verify_parts(path, ["C:", "Users", "franckc", "pub", "JOCC", "main.tex"]) def verify_parts(self, path, expectedParts, ): parts = [each.fullname() for each in path.parts()] self.assertEqual(parts, expectedParts) def testPathWithNewlines(self): path = Path.fromText("/Root/Foo\nBar\nBaz/home") self.verify_parts(path, ["", "Root", "FooBarBaz", "home"]) def test_remove_trailing_spaces(self): path = Path.fromText("/text/ blabla /test.txt") self.assertEqual(path, Path.fromText("/text/blabla/test.txt")) def test_is_absolute_on_unix_paths(self): path = Path.fromText("/home/franck/test.tex") self.assertTrue(path.is_absolute()) <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest from flap.util.path import Path, ROOT, TEMP, CURRENT_DIRECTORY from tempfile import gettempdir and context: # Path: flap/util/path.py # class Path: # # @staticmethod # def fromText(text): # pattern = re.compile("[\\\\/]+") # parts = [Unit(eachPart) for eachPart in pattern.split(text)] # # Remove the last one, if it is "" (e.g., in project/img/) # if parts[-1].is_root(): # parts = parts[:-1] # return Path(parts) # # def __init__(self, parts): # if not parts: # raise ValueError("Invalid path, no part given") # self._parts = [part for (index, part) in enumerate(parts) # if not (part.is_current_directory() and index > 0)] # # def resource(self): # return self._parts[-1] # # def fullname(self): # return self.resource().fullname() # # def basename(self): # return self.resource().basename() # # def extension(self): # return self.resource().extension() # # def has_extension(self, extension=None): # if extension: # return self.resource().has_extension(extension) # else: # return self.resource().has_any_extension() # # def container(self): # if len(self._parts) == 1: # if self._parts[0].is_root(): # raise ValueError("The root directory has no parent") # else: # return Path([Unit(".")]) # return Path(self._parts[:-1]) # # def isRoot(self): # return self.resource().is_root() # # def is_absolute(self): # return self._parts[0].is_root() # # def absolute_from(self, current_directory): # parts = self.parts() # if parts[0].is_root(): # return self # elif parts[0].is_current_directory(): # parts = current_directory.parts() + parts[1:] # elif parts[0].is_parent_directory(): # parts = current_directory.container().parts() + parts[1:] # else: # parts = current_directory.parts() + parts # return Path.fromText("/".join([each.fullname() for each in parts])) # # def relative_to(self, location): # position = 0 # while position < len(location._parts) \ # and self._parts[position] == location._parts[position]: # position += 1 # return Path(self._parts[position:]) # # def without_extension(self): # return Path(self._parts[:-1] + [Unit(self._parts[-1].basename())]) # # def parts(self): # return self._parts # # def __contains__(self, other): # return self != other and self.__str__() in other.__str__() # # def __truediv__(self, other): # if isinstance(other, str): # return Path(self._parts + Path.fromText(other)._parts) # elif isinstance(other, Path): # return Path(self._parts + other._parts) # # def __repr__(self): # return "/".join([eachPart.fullname() for eachPart in self._parts]) # # def __str__(self): # return self.__repr__() # # def __eq__(self, other): # return isinstance(other, Path) and self._parts == other._parts # # def __hash__(self): # return self.__str__().__hash__() # # ROOT = Path([Unit("")]) # # TEMP = Path.fromText(tempfile.gettempdir()) # # CURRENT_DIRECTORY = Path([Unit(".")]) which might include code, classes, or functions. Output only the next line.
def test_is_absolute_on_windows_paths(self):
Here is a snippet: <|code_start|> self.assertTrue(path.fullname() in gettempdir()) def test_path_to_file(self): path = (ROOT / "test" / "source.tex") self.assertEqual(path.container(), ROOT / "test") self.assertEqual(path.fullname(), "source.tex") def test_appending_a_path(self): path1 = ROOT / "dir/test" path2 = ROOT / "dir" / "test" self.assertEqual(path1, path2) def test_appending_a_path_that_ends_with_a_slash(self): path1 = ROOT / "dir/test/" path2 = ROOT / "dir" / "test" self.assertEqual(path1, path2) def test_appending_a_path_that_starts_with_a_dot(self): path1 = ROOT / "./dir/test/" path2 = ROOT / "dir" / "test" self.assertEqual(path1, path2) def test_has_extension(self): path = ROOT / "source.tex" self.assertTrue(path.has_extension()) <|code_end|> . Write the next line using the current file imports: import unittest from flap.util.path import Path, ROOT, TEMP, CURRENT_DIRECTORY from tempfile import gettempdir and context from other files: # Path: flap/util/path.py # class Path: # # @staticmethod # def fromText(text): # pattern = re.compile("[\\\\/]+") # parts = [Unit(eachPart) for eachPart in pattern.split(text)] # # Remove the last one, if it is "" (e.g., in project/img/) # if parts[-1].is_root(): # parts = parts[:-1] # return Path(parts) # # def __init__(self, parts): # if not parts: # raise ValueError("Invalid path, no part given") # self._parts = [part for (index, part) in enumerate(parts) # if not (part.is_current_directory() and index > 0)] # # def resource(self): # return self._parts[-1] # # def fullname(self): # return self.resource().fullname() # # def basename(self): # return self.resource().basename() # # def extension(self): # return self.resource().extension() # # def has_extension(self, extension=None): # if extension: # return self.resource().has_extension(extension) # else: # return self.resource().has_any_extension() # # def container(self): # if len(self._parts) == 1: # if self._parts[0].is_root(): # raise ValueError("The root directory has no parent") # else: # return Path([Unit(".")]) # return Path(self._parts[:-1]) # # def isRoot(self): # return self.resource().is_root() # # def is_absolute(self): # return self._parts[0].is_root() # # def absolute_from(self, current_directory): # parts = self.parts() # if parts[0].is_root(): # return self # elif parts[0].is_current_directory(): # parts = current_directory.parts() + parts[1:] # elif parts[0].is_parent_directory(): # parts = current_directory.container().parts() + parts[1:] # else: # parts = current_directory.parts() + parts # return Path.fromText("/".join([each.fullname() for each in parts])) # # def relative_to(self, location): # position = 0 # while position < len(location._parts) \ # and self._parts[position] == location._parts[position]: # position += 1 # return Path(self._parts[position:]) # # def without_extension(self): # return Path(self._parts[:-1] + [Unit(self._parts[-1].basename())]) # # def parts(self): # return self._parts # # def __contains__(self, other): # return self != other and self.__str__() in other.__str__() # # def __truediv__(self, other): # if isinstance(other, str): # return Path(self._parts + Path.fromText(other)._parts) # elif isinstance(other, Path): # return Path(self._parts + other._parts) # # def __repr__(self): # return "/".join([eachPart.fullname() for eachPart in self._parts]) # # def __str__(self): # return self.__repr__() # # def __eq__(self, other): # return isinstance(other, Path) and self._parts == other._parts # # def __hash__(self): # return self.__str__().__hash__() # # ROOT = Path([Unit("")]) # # TEMP = Path.fromText(tempfile.gettempdir()) # # CURRENT_DIRECTORY = Path([Unit(".")]) , which may include functions, classes, or code. Output only the next line.
def test_basename(self):
Given snippet: <|code_start|># # Flap is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Flap is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Flap. If not, see <http://www.gnu.org/licenses/>. # class InMemoryFileSystemTest(unittest.TestCase): def setUp(self): self.fileSystem = InMemoryFileSystem() self.current_directory = Path.fromText("/temp") def test_file_creation(self): path = Path.fromText("dir/test/source.tex") self.fileSystem.create_file(path, "blah") file = self.fileSystem.open(Path.fromText("dir/test/source.tex")) <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest from flap.util.oofs import InMemoryFileSystem from flap.util.path import Path, ROOT and context: # Path: flap/util/oofs.py # class InMemoryFileSystem(FileSystem): # # def __init__(self, path_separator=os.path.sep): # super().__init__() # self.drive = {} # self._current_directory = ROOT # self.pathSeparator = path_separator # # def move_to_directory(self, path): # self._current_directory = path.absolute_from(self._current_directory) # # def createDirectory(self, path): # if path in self.drive.keys(): # if self.drive[path].is_file(): # raise ValueError("There is already a resource at '%s'" # % path.full()) # self.drive[path] = Directory(self, path) # if not path.isRoot(): # self.createDirectory(path.container()) # # def create_file(self, path, content): # if not isinstance(content, str): # raise ValueError("File content should be text!") # absolute = path.absolute_from(self._current_directory) # self.drive[absolute] = File(self, absolute, content) # self.createDirectory(absolute.container()) # # def filesIn(self, path): # return [self.drive[p] for p in self.drive.keys() # if p in path and len(p.parts()) == len(path.parts()) + 1] # # def open(self, path): # absolute = path.absolute_from(self._current_directory) # if absolute in self.drive.keys(): # return self.drive[absolute] # else: # return MissingFile(absolute) # # def copy(self, file, destination): # if destination.has_extension(): # path = destination # else: # path = destination / file.path().fullname() # absolute = path.absolute_from(self._current_directory) # self.drive[absolute] = File(self, absolute, file.content()) # # Path: flap/util/path.py # class Path: # # @staticmethod # def fromText(text): # pattern = re.compile("[\\\\/]+") # parts = [Unit(eachPart) for eachPart in pattern.split(text)] # # Remove the last one, if it is "" (e.g., in project/img/) # if parts[-1].is_root(): # parts = parts[:-1] # return Path(parts) # # def __init__(self, parts): # if not parts: # raise ValueError("Invalid path, no part given") # self._parts = [part for (index, part) in enumerate(parts) # if not (part.is_current_directory() and index > 0)] # # def resource(self): # return self._parts[-1] # # def fullname(self): # return self.resource().fullname() # # def basename(self): # return self.resource().basename() # # def extension(self): # return self.resource().extension() # # def has_extension(self, extension=None): # if extension: # return self.resource().has_extension(extension) # else: # return self.resource().has_any_extension() # # def container(self): # if len(self._parts) == 1: # if self._parts[0].is_root(): # raise ValueError("The root directory has no parent") # else: # return Path([Unit(".")]) # return Path(self._parts[:-1]) # # def isRoot(self): # return self.resource().is_root() # # def is_absolute(self): # return self._parts[0].is_root() # # def absolute_from(self, current_directory): # parts = self.parts() # if parts[0].is_root(): # return self # elif parts[0].is_current_directory(): # parts = current_directory.parts() + parts[1:] # elif parts[0].is_parent_directory(): # parts = current_directory.container().parts() + parts[1:] # else: # parts = current_directory.parts() + parts # return Path.fromText("/".join([each.fullname() for each in parts])) # # def relative_to(self, location): # position = 0 # while position < len(location._parts) \ # and self._parts[position] == location._parts[position]: # position += 1 # return Path(self._parts[position:]) # # def without_extension(self): # return Path(self._parts[:-1] + [Unit(self._parts[-1].basename())]) # # def parts(self): # return self._parts # # def __contains__(self, other): # return self != other and self.__str__() in other.__str__() # # def __truediv__(self, other): # if isinstance(other, str): # return Path(self._parts + Path.fromText(other)._parts) # elif isinstance(other, Path): # return Path(self._parts + other._parts) # # def __repr__(self): # return "/".join([eachPart.fullname() for eachPart in self._parts]) # # def __str__(self): # return self.__repr__() # # def __eq__(self, other): # return isinstance(other, Path) and self._parts == other._parts # # def __hash__(self): # return self.__str__().__hash__() # # ROOT = Path([Unit("")]) which might include code, classes, or functions. Output only the next line.
self.assertTrue(file.exists())
Predict the next line for this snippet: <|code_start|># Flap is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Flap. If not, see <http://www.gnu.org/licenses/>. # class InMemoryFileSystemTest(unittest.TestCase): def setUp(self): self.fileSystem = InMemoryFileSystem() self.current_directory = Path.fromText("/temp") def test_file_creation(self): path = Path.fromText("dir/test/source.tex") self.fileSystem.create_file(path, "blah") file = self.fileSystem.open(Path.fromText("dir/test/source.tex")) self.assertTrue(file.exists()) self.assertTrue(file.contains("blah")) def test_create_file_rejects_content_that_is_not_text(self): path = Path.fromText("dir/test.txt") with self.assertRaises(ValueError): <|code_end|> with the help of current file imports: import unittest from flap.util.oofs import InMemoryFileSystem from flap.util.path import Path, ROOT and context from other files: # Path: flap/util/oofs.py # class InMemoryFileSystem(FileSystem): # # def __init__(self, path_separator=os.path.sep): # super().__init__() # self.drive = {} # self._current_directory = ROOT # self.pathSeparator = path_separator # # def move_to_directory(self, path): # self._current_directory = path.absolute_from(self._current_directory) # # def createDirectory(self, path): # if path in self.drive.keys(): # if self.drive[path].is_file(): # raise ValueError("There is already a resource at '%s'" # % path.full()) # self.drive[path] = Directory(self, path) # if not path.isRoot(): # self.createDirectory(path.container()) # # def create_file(self, path, content): # if not isinstance(content, str): # raise ValueError("File content should be text!") # absolute = path.absolute_from(self._current_directory) # self.drive[absolute] = File(self, absolute, content) # self.createDirectory(absolute.container()) # # def filesIn(self, path): # return [self.drive[p] for p in self.drive.keys() # if p in path and len(p.parts()) == len(path.parts()) + 1] # # def open(self, path): # absolute = path.absolute_from(self._current_directory) # if absolute in self.drive.keys(): # return self.drive[absolute] # else: # return MissingFile(absolute) # # def copy(self, file, destination): # if destination.has_extension(): # path = destination # else: # path = destination / file.path().fullname() # absolute = path.absolute_from(self._current_directory) # self.drive[absolute] = File(self, absolute, file.content()) # # Path: flap/util/path.py # class Path: # # @staticmethod # def fromText(text): # pattern = re.compile("[\\\\/]+") # parts = [Unit(eachPart) for eachPart in pattern.split(text)] # # Remove the last one, if it is "" (e.g., in project/img/) # if parts[-1].is_root(): # parts = parts[:-1] # return Path(parts) # # def __init__(self, parts): # if not parts: # raise ValueError("Invalid path, no part given") # self._parts = [part for (index, part) in enumerate(parts) # if not (part.is_current_directory() and index > 0)] # # def resource(self): # return self._parts[-1] # # def fullname(self): # return self.resource().fullname() # # def basename(self): # return self.resource().basename() # # def extension(self): # return self.resource().extension() # # def has_extension(self, extension=None): # if extension: # return self.resource().has_extension(extension) # else: # return self.resource().has_any_extension() # # def container(self): # if len(self._parts) == 1: # if self._parts[0].is_root(): # raise ValueError("The root directory has no parent") # else: # return Path([Unit(".")]) # return Path(self._parts[:-1]) # # def isRoot(self): # return self.resource().is_root() # # def is_absolute(self): # return self._parts[0].is_root() # # def absolute_from(self, current_directory): # parts = self.parts() # if parts[0].is_root(): # return self # elif parts[0].is_current_directory(): # parts = current_directory.parts() + parts[1:] # elif parts[0].is_parent_directory(): # parts = current_directory.container().parts() + parts[1:] # else: # parts = current_directory.parts() + parts # return Path.fromText("/".join([each.fullname() for each in parts])) # # def relative_to(self, location): # position = 0 # while position < len(location._parts) \ # and self._parts[position] == location._parts[position]: # position += 1 # return Path(self._parts[position:]) # # def without_extension(self): # return Path(self._parts[:-1] + [Unit(self._parts[-1].basename())]) # # def parts(self): # return self._parts # # def __contains__(self, other): # return self != other and self.__str__() in other.__str__() # # def __truediv__(self, other): # if isinstance(other, str): # return Path(self._parts + Path.fromText(other)._parts) # elif isinstance(other, Path): # return Path(self._parts + other._parts) # # def __repr__(self): # return "/".join([eachPart.fullname() for eachPart in self._parts]) # # def __str__(self): # return self.__repr__() # # def __eq__(self, other): # return isinstance(other, Path) and self._parts == other._parts # # def __hash__(self): # return self.__str__().__hash__() # # ROOT = Path([Unit("")]) , which may contain function names, class names, or code. Output only the next line.
self.fileSystem.create_file(path, [1, 2, 3, 4])
Given the following code snippet before the placeholder: <|code_start|> self._verify(self._line + 1, 0, self._position.next_line()) def _verify(self, line, column, position): self.assertEqual(line, position.line) self.assertEqual(column, position.column) def test_next_character(self): self._verify( self._line, self._column + 1, self._position.next_character()) def test_equals_itself(self): self.assertEqual(self._position, self._position) def test_equals_an_equivalent_position(self): self.assertEqual(self._at(self._line, self._column), self._position) def test_differs_from_a_position_with_different_column(self): self.assertNotEqual( self._at( self._line, self._column + 1), self._position) def test_differs_from_a_position_with_different_line(self): self.assertNotEqual( self._at( self._line + 1, self._column), <|code_end|> , predict the next line using imports from the current file: from unittest import TestCase, main from unittest.mock import MagicMock from flap.latex.commons import Stream, Position and context including class names, function names, and sometimes code from other files: # Path: flap/latex/commons.py # class Stream: # """ # A stream of characters, on which we can peek. # # One can equip a stream with an event handler that gets triggered # every times the stream moves forward, that is every time the take # method is called, directly or indirectly. # """ # # def __init__(self, iterable, handler=lambda x: None): # assert hasattr(iterable, "__iter__"), \ # "Stream requires an iterable, but found an '%s'!" % ( # type(iterable)) # self._characters = iter(iterable) # assert callable(handler), \ # "Stream expect a callable hanlder, but found a '%s" % ( # type(handler)) # self._handler = handler # self._cache = [] # # def look_ahead(self): # next_item = self._take() # if next_item: # self._cache.append(next_item) # return next_item # # @property # def is_empty(self): # return self.look_ahead() is None # # def _take(self): # if self._cache: # return self._cache.pop() # try: # return next(self._characters) # except StopIteration: # return None # # def take(self): # element = self._take() # # logger.debug("Taking %s", str(element)) # self._handler(element) # return element # # def take_while(self, match): # buffer = [] # while self.look_ahead() and match(self.look_ahead()): # buffer.append(self.take()) # return buffer # # def take_all(self): # return self.take_while(lambda e: e is not None) # # def push(self, items): # if isinstance(items, list): # assert not any(i is None for i in items), \ # "Cannot push None!" # self._cache.extend(reversed(items)) # else: # assert items is not None, \ # "Cannot push None" # self._cache.append(items) # logger.debug(f"Pushing! New cache size: {str(len(self._cache))}") # # self.debug() # # def debug(self): # logger.debug("View of the stack ...") # for index in range(len(self._cache)): # item = self._cache[-(index+1)] # text = str(item) if isinstance(item, str) else item.as_text # logger.debug(f" - {index}: {item}") # # class Position: # # UNKNOWN = "Unknown source file" # REPRESENTATION = "{source} @({line}, {column})" # # def __init__(self, line, column, source=None): # self._source = source or self.UNKNOWN # self._line = line # self._column = column # # @property # def source(self): # return self._source # # @property # def line(self): # return self._line # # @property # def column(self): # return self._column # # def next_line(self): # return Position(self._line + 1, 0, self._source) # # def next_character(self): # return Position(self._line, self._column + 1, self._source) # # def __eq__(self, other): # if not isinstance(other, Position): # return False # return self._line == other._line and \ # self._column == other._column # # def __repr__(self): # return self.REPRESENTATION.format( # source=self._source, line=self._line, column=self._column) . Output only the next line.
self._position)
Given the following code snippet before the placeholder: <|code_start|># # This file is part of Flap. # # Flap is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Flap is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Flap. If not, see <http://www.gnu.org/licenses/>. # class EmptyStreamTest(TestCase): def setUp(self): self._stream = Stream(iter([])) def test_reject_non_iterable_types(self): with self.assertRaises(AssertionError): Stream(34) def test_is_empty(self): <|code_end|> , predict the next line using imports from the current file: from unittest import TestCase, main from unittest.mock import MagicMock from flap.latex.commons import Stream, Position and context including class names, function names, and sometimes code from other files: # Path: flap/latex/commons.py # class Stream: # """ # A stream of characters, on which we can peek. # # One can equip a stream with an event handler that gets triggered # every times the stream moves forward, that is every time the take # method is called, directly or indirectly. # """ # # def __init__(self, iterable, handler=lambda x: None): # assert hasattr(iterable, "__iter__"), \ # "Stream requires an iterable, but found an '%s'!" % ( # type(iterable)) # self._characters = iter(iterable) # assert callable(handler), \ # "Stream expect a callable hanlder, but found a '%s" % ( # type(handler)) # self._handler = handler # self._cache = [] # # def look_ahead(self): # next_item = self._take() # if next_item: # self._cache.append(next_item) # return next_item # # @property # def is_empty(self): # return self.look_ahead() is None # # def _take(self): # if self._cache: # return self._cache.pop() # try: # return next(self._characters) # except StopIteration: # return None # # def take(self): # element = self._take() # # logger.debug("Taking %s", str(element)) # self._handler(element) # return element # # def take_while(self, match): # buffer = [] # while self.look_ahead() and match(self.look_ahead()): # buffer.append(self.take()) # return buffer # # def take_all(self): # return self.take_while(lambda e: e is not None) # # def push(self, items): # if isinstance(items, list): # assert not any(i is None for i in items), \ # "Cannot push None!" # self._cache.extend(reversed(items)) # else: # assert items is not None, \ # "Cannot push None" # self._cache.append(items) # logger.debug(f"Pushing! New cache size: {str(len(self._cache))}") # # self.debug() # # def debug(self): # logger.debug("View of the stack ...") # for index in range(len(self._cache)): # item = self._cache[-(index+1)] # text = str(item) if isinstance(item, str) else item.as_text # logger.debug(f" - {index}: {item}") # # class Position: # # UNKNOWN = "Unknown source file" # REPRESENTATION = "{source} @({line}, {column})" # # def __init__(self, line, column, source=None): # self._source = source or self.UNKNOWN # self._line = line # self._column = column # # @property # def source(self): # return self._source # # @property # def line(self): # return self._line # # @property # def column(self): # return self._column # # def next_line(self): # return Position(self._line + 1, 0, self._source) # # def next_character(self): # return Position(self._line, self._column + 1, self._source) # # def __eq__(self, other): # if not isinstance(other, Position): # return False # return self._line == other._line and \ # self._column == other._column # # def __repr__(self): # return self.REPRESENTATION.format( # source=self._source, line=self._line, column=self._column) . Output only the next line.
self.assertTrue(self._stream.is_empty)
Predict the next line after this snippet: <|code_start|>class OSFileSystemTest(TestCase): def setUp(self): self.fileSystem = OSFileSystem() self.path = TEMP / "flap_os" / "test.txt" self.content = "blahblah blah" self.fileSystem.deleteDirectory(TEMP / "flap_os") self.fileSystem.deleteDirectory(TEMP / "flatexer_copy") def createAndOpenTestFile(self): self.fileSystem.create_file(self.path, self.content) return self.fileSystem.open(self.path) def testCreateAndOpenFile(self): file = self.createAndOpenTestFile() self.assertEqual(file.content(), self.content) def testCopyAndOpenFile(self): file = self.createAndOpenTestFile() copyPath = TEMP / "flatexer_copy" self.fileSystem.copy(file, copyPath) copy = self.fileSystem.open(copyPath / "test.txt") self.assertEqual(copy.content(), self.content) def test_copyAndRename(self): <|code_end|> using the current file's imports: from unittest import TestCase, main as testmain from flap.util.oofs import OSFileSystem from flap.util.path import TEMP and any relevant context from other files: # Path: flap/util/oofs.py # class OSFileSystem(FileSystem): # # def __init__(self): # super().__init__() # self.current_directory = Path.fromText(os.getcwd()) # # @staticmethod # def for_OS(path): # return os.path.sep.join([eachPart.fullname() # for eachPart in path.parts()]) # # def move_to_directory(self, path): # os.chdir(self.for_OS(path)) # # def create_file(self, path, content): # self._create_path(path) # os_path = self.for_OS(path) # with open(os_path, "w") as f: # f.write(content) # # def deleteDirectory(self, path): # import shutil # osPath = self.for_OS(path) # if os.path.exists(osPath): # shutil.rmtree(osPath) # # def open(self, path): # osPath = self.for_OS(path) # if os.path.isdir(osPath): # return Directory(self, path) # else: # return File(self, path, None) # # def filesIn(self, path): # return [self.open(path / each) # for each in os.listdir(self.for_OS(path))] # # def copy(self, file, destination): # import shutil # # self._create_path(destination) # # source = self.for_OS(file.path()) # target = destination if destination.has_extension() \ # else destination / file.fullname() # # shutil.copyfile(source, self.for_OS(target)) # # def _create_path(self, path): # targetDir = path # if path.has_extension(): # targetDir = path.container() # # os_target = self.for_OS(targetDir) # if not os.path.exists(os_target): # os.makedirs(os_target) # # def load(self, path): # assert path, "Invalid path (found '%s')" % path # os_path = self.for_OS(path) # with open(os_path) as file: # return file.read() # # Path: flap/util/path.py # TEMP = Path.fromText(tempfile.gettempdir()) . Output only the next line.
file = self.createAndOpenTestFile()
Next line prediction: <|code_start|># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Flap. If not, see <http://www.gnu.org/licenses/>. # class OSFileSystemTest(TestCase): def setUp(self): self.fileSystem = OSFileSystem() self.path = TEMP / "flap_os" / "test.txt" self.content = "blahblah blah" self.fileSystem.deleteDirectory(TEMP / "flap_os") self.fileSystem.deleteDirectory(TEMP / "flatexer_copy") def createAndOpenTestFile(self): self.fileSystem.create_file(self.path, self.content) return self.fileSystem.open(self.path) def testCreateAndOpenFile(self): file = self.createAndOpenTestFile() self.assertEqual(file.content(), self.content) def testCopyAndOpenFile(self): <|code_end|> . Use current file imports: (from unittest import TestCase, main as testmain from flap.util.oofs import OSFileSystem from flap.util.path import TEMP) and context including class names, function names, or small code snippets from other files: # Path: flap/util/oofs.py # class OSFileSystem(FileSystem): # # def __init__(self): # super().__init__() # self.current_directory = Path.fromText(os.getcwd()) # # @staticmethod # def for_OS(path): # return os.path.sep.join([eachPart.fullname() # for eachPart in path.parts()]) # # def move_to_directory(self, path): # os.chdir(self.for_OS(path)) # # def create_file(self, path, content): # self._create_path(path) # os_path = self.for_OS(path) # with open(os_path, "w") as f: # f.write(content) # # def deleteDirectory(self, path): # import shutil # osPath = self.for_OS(path) # if os.path.exists(osPath): # shutil.rmtree(osPath) # # def open(self, path): # osPath = self.for_OS(path) # if os.path.isdir(osPath): # return Directory(self, path) # else: # return File(self, path, None) # # def filesIn(self, path): # return [self.open(path / each) # for each in os.listdir(self.for_OS(path))] # # def copy(self, file, destination): # import shutil # # self._create_path(destination) # # source = self.for_OS(file.path()) # target = destination if destination.has_extension() \ # else destination / file.fullname() # # shutil.copyfile(source, self.for_OS(target)) # # def _create_path(self, path): # targetDir = path # if path.has_extension(): # targetDir = path.container() # # os_target = self.for_OS(targetDir) # if not os.path.exists(os_target): # os.makedirs(os_target) # # def load(self, path): # assert path, "Invalid path (found '%s')" % path # os_path = self.for_OS(path) # with open(os_path) as file: # return file.read() # # Path: flap/util/path.py # TEMP = Path.fromText(tempfile.gettempdir()) . Output only the next line.
file = self.createAndOpenTestFile()
Next line prediction: <|code_start|> self._invocation.append_argument( "options", [each for each in "[this is a text]"]) self._invocation.append([each for each in "----"]) self._invocation.append_argument( "link", [each for each in "{link/to/a/file.tex}"]) self.assertEqual([r"\foo"] + [each for each in "[this is a text]"] + [each for each in "----"] + [each for each in "{link/to/a/file.tex}"], self._invocation.as_tokens) def test_iterating_over_items(self): self._invocation.name = r"\foo" self._invocation.append_argument("options", "this is a text") self._invocation.append("----") self._invocation.append_argument("link", "{link/to/a/file.tex}") self.assertEqual({"options": "this is a text", "link": "{link/to/a/file.tex}"}, self._invocation.arguments) def test_argument_substitution(self): self._invocation.name = r"\foo" self._invocation.append_argument("text", ["z", "y", "x"]) self.assertEqual( "bar", self._invocation.substitute( "text", "bar").arguments["text"]) def test_argument(self): self._invocation.name = [r"\foo"] self._invocation.append_argument("link", ["p1", ",", "p2"]) <|code_end|> . Use current file imports: (from unittest import TestCase, main from flap.latex.macros.commons import Invocation) and context including class names, function names, or small code snippets from other files: # Path: flap/latex/macros/commons.py # class Invocation: # """ The invocation of a LaTeX command, including the name of the # command, and its parameters indexed by name as sequences of # tokens. # """ # # def __init__(self, command): # self.name = command # self._arguments = [] # self._keys = dict() # # @property # def as_text(self): # text = self.to_text(self.name) # for each_argument in self._arguments: # text += "".join(map(str, each_argument)) # return text # # @staticmethod # def to_text(parameter): # if isinstance(parameter, list): # return "".join(map(Invocation.to_text, parameter)) # elif isinstance(parameter, str): # return parameter # else: # return parameter.as_text # # @property # def command_name(self): # """Returns the name (as a string) of the command without the first # control character. # """ # return str(self.name)[1:] # # def send_to(self, parser): # return parser.process_invocation(self) # # def append(self, tokens): # self._arguments.append(tokens) # # def append_argument(self, name, value): # self._arguments.append(value) # self._keys[name] = len(self._arguments) - 1 # # def argument(self, key): # return self._arguments[self._keys[key]] # # def argument_as_text(self, key): # return "".join(each_token.as_text # for each_token in self.argument(key)) # # @property # def location(self): # assert self.as_tokens, \ # "Could not fetch invocation's position '%s'" % self.as_text # return self.as_tokens[0].location # # @property # def arguments(self): # return {key: self._arguments[value] # for (key, value) in self._keys.items()} # # # @property # def as_tokens(self): # start = copy(self.name) \ # if isinstance(self.name, list) \ # else [self.name] # return sum(self._arguments, start) # # def substitute(self, argument, value): # clone = Invocation(self.name) # clone.name = copy(self.name) # clone._arguments = copy(self._arguments) # clone._keys = copy(self._keys) # clone._arguments[clone._keys[argument]] = value # return clone . Output only the next line.
self.assertEqual([r"\foo"], self._invocation.name)
Given the code snippet: <|code_start|> collection.put_string('main', """ <%inherit file="layout"/> <%def name="d()">main_d</%def> main_body ${parent.d()} full stack from the top: ${self.name} ${parent.name} ${parent.context['parent'].name} ${parent.context['parent'].context['parent'].name} """) collection.put_string('layout', """ <%inherit file="general"/> <%def name="d()">layout_d</%def> layout_body parent name: ${parent.name} ${parent.d()} ${parent.context['parent'].d()} ${next.body()} """) collection.put_string('general', """ <%inherit file="base"/> <%def name="d()">general_d</%def> general_body ${next.d()} ${next.context['next'].d()} ${next.body()} """) collection.put_string('base', """ base_body full stack from the base: <|code_end|> , generate the next line using the imports in this file: from mako.template import Template from mako import lookup from util import flatten_result, result_lines import unittest and context (functions, classes, or occasionally code) from other files: # Path: mako/lookup.py # class TemplateCollection(object): # class TemplateLookup(TemplateCollection): # def has_template(self, uri): # def get_template(self, uri, relativeto=None): # def filename_to_uri(self, uri, filename): # def adjust_uri(self, uri, filename): # def __init__(self, # directories=None, # module_directory=None, # filesystem_checks=True, # collection_size=-1, # format_exceptions=False, # error_handler=None, # disable_unicode=False, # output_encoding=None, # encoding_errors='strict', # cache_type=None, # cache_dir=None, cache_url=None, # cache_enabled=True, # modulename_callable=None, # default_filters=None, # buffer_filters=(), # imports=None, # input_encoding=None, # preprocessor=None): # def get_template(self, uri): # def adjust_uri(self, uri, relativeto): # def filename_to_uri(self, filename): # def _relativeize(self, filename): # def _load(self, filename, uri): # def _check(self, uri, template): # def put_string(self, uri, text): # def put_template(self, uri, template): . Output only the next line.
${self.name} ${self.context['parent'].name} ${self.context['parent'].context['parent'].name} ${self.context['parent'].context['parent'].context['parent'].name}
Here is a snippet: <|code_start|> def test_getattr(self): collection = lookup.TemplateLookup() collection.put_string("main.html", """ <%namespace name="foo" file="ns.html"/> <% if hasattr(foo, 'lala'): foo.lala() if not hasattr(foo, 'hoho'): context.write('foo has no hoho.') %> """) collection.put_string("ns.html", """ <%def name="lala()">this is lala.</%def> """) assert flatten_result(collection.get_template("main.html").render()) == "this is lala.foo has no hoho." def test_in_def(self): collection = lookup.TemplateLookup() collection.put_string("main.html", """ <%namespace name="foo" file="ns.html"/> this is main. ${bar()} <%def name="bar()"> this is bar, foo is ${foo.bar()} </%def> """) collection.put_string("ns.html", """ <%def name="bar()"> <|code_end|> . Write the next line using the current file imports: from mako.template import Template from mako import lookup from util import flatten_result, result_lines import unittest and context from other files: # Path: mako/lookup.py # class TemplateCollection(object): # class TemplateLookup(TemplateCollection): # def has_template(self, uri): # def get_template(self, uri, relativeto=None): # def filename_to_uri(self, uri, filename): # def adjust_uri(self, uri, filename): # def __init__(self, # directories=None, # module_directory=None, # filesystem_checks=True, # collection_size=-1, # format_exceptions=False, # error_handler=None, # disable_unicode=False, # output_encoding=None, # encoding_errors='strict', # cache_type=None, # cache_dir=None, cache_url=None, # cache_enabled=True, # modulename_callable=None, # default_filters=None, # buffer_filters=(), # imports=None, # input_encoding=None, # preprocessor=None): # def get_template(self, uri): # def adjust_uri(self, uri, relativeto): # def filename_to_uri(self, filename): # def _relativeize(self, filename): # def _load(self, filename, uri): # def _check(self, uri, template): # def put_string(self, uri, text): # def put_template(self, uri, template): , which may include functions, classes, or code. Output only the next line.
this is ns.html->bar
Using the snippet: <|code_start|> if not os.access('./test_htdocs', os.F_OK): os.mkdir('./test_htdocs') file('./test_htdocs/index.html', 'w').write("this is index") <|code_end|> , determine the next line of code. You have imports: from mako.template import Template from mako import lookup, exceptions from util import flatten_result, result_lines import unittest import os and context (class names, function names, or code) available: # Path: mako/lookup.py # class TemplateCollection(object): # class TemplateLookup(TemplateCollection): # def has_template(self, uri): # def get_template(self, uri, relativeto=None): # def filename_to_uri(self, uri, filename): # def adjust_uri(self, uri, filename): # def __init__(self, # directories=None, # module_directory=None, # filesystem_checks=True, # collection_size=-1, # format_exceptions=False, # error_handler=None, # disable_unicode=False, # output_encoding=None, # encoding_errors='strict', # cache_type=None, # cache_dir=None, cache_url=None, # cache_enabled=True, # modulename_callable=None, # default_filters=None, # buffer_filters=(), # imports=None, # input_encoding=None, # preprocessor=None): # def get_template(self, uri): # def adjust_uri(self, uri, relativeto): # def filename_to_uri(self, filename): # def _relativeize(self, filename): # def _load(self, filename, uri): # def _check(self, uri, template): # def put_string(self, uri, text): # def put_template(self, uri, template): # # Path: mako/exceptions.py # class MakoException(Exception): # class RuntimeException(MakoException): # class CompileException(MakoException): # class SyntaxException(MakoException): # class TemplateLookupException(MakoException): # class TopLevelLookupException(TemplateLookupException): # class RichTraceback(object): # def _format_filepos(lineno, pos, filename): # def __init__(self, message, source, lineno, pos, filename): # def __init__(self, message, source, lineno, pos, filename): # def __init__(self, traceback=None): # def init_message(self): # def _get_reformatted_records(self, records): # def _init(self, trcback): # def text_error_template(lookup=None): # def html_error_template(): . Output only the next line.
file('./test_htdocs/incl.html', 'w').write("this is include 1")
Next line prediction: <|code_start|> if not os.access('./test_htdocs', os.F_OK): os.mkdir('./test_htdocs') file('./test_htdocs/index.html', 'w').write("this is index") <|code_end|> . Use current file imports: (from mako.template import Template from mako import lookup, exceptions from util import flatten_result, result_lines import unittest import os) and context including class names, function names, or small code snippets from other files: # Path: mako/lookup.py # class TemplateCollection(object): # class TemplateLookup(TemplateCollection): # def has_template(self, uri): # def get_template(self, uri, relativeto=None): # def filename_to_uri(self, uri, filename): # def adjust_uri(self, uri, filename): # def __init__(self, # directories=None, # module_directory=None, # filesystem_checks=True, # collection_size=-1, # format_exceptions=False, # error_handler=None, # disable_unicode=False, # output_encoding=None, # encoding_errors='strict', # cache_type=None, # cache_dir=None, cache_url=None, # cache_enabled=True, # modulename_callable=None, # default_filters=None, # buffer_filters=(), # imports=None, # input_encoding=None, # preprocessor=None): # def get_template(self, uri): # def adjust_uri(self, uri, relativeto): # def filename_to_uri(self, filename): # def _relativeize(self, filename): # def _load(self, filename, uri): # def _check(self, uri, template): # def put_string(self, uri, text): # def put_template(self, uri, template): # # Path: mako/exceptions.py # class MakoException(Exception): # class RuntimeException(MakoException): # class CompileException(MakoException): # class SyntaxException(MakoException): # class TemplateLookupException(MakoException): # class TopLevelLookupException(TemplateLookupException): # class RichTraceback(object): # def _format_filepos(lineno, pos, filename): # def __init__(self, message, source, lineno, pos, filename): # def __init__(self, message, source, lineno, pos, filename): # def __init__(self, traceback=None): # def init_message(self): # def _get_reformatted_records(self, records): # def _init(self, trcback): # def text_error_template(lookup=None): # def html_error_template(): . Output only the next line.
file('./test_htdocs/incl.html', 'w').write("this is include 1")
Here is a snippet: <|code_start|> """) assert flatten_result(t.render(x=5)) == "b. x is 10. a: x is 5" def test_scope_nine(self): """test that 'enclosing scope' doesnt get exported to other templates""" l = lookup.TemplateLookup() l.put_string('main', """ <% x = 5 %> this is main. <%include file="secondary"/> """) l.put_string('secondary', """ this is secondary. x is ${x} """) assert flatten_result(l.get_template('main').render(x=2)) == "this is main. this is secondary. x is 2" def test_scope_ten(self): t = Template(""" <%def name="a()"> <%def name="b()"> <% y = 19 %> b/c: ${c()} b/y: ${y} </%def> <|code_end|> . Write the next line using the current file imports: from mako.template import Template from mako import lookup from util import flatten_result, result_lines import unittest and context from other files: # Path: mako/lookup.py # class TemplateCollection(object): # class TemplateLookup(TemplateCollection): # def has_template(self, uri): # def get_template(self, uri, relativeto=None): # def filename_to_uri(self, uri, filename): # def adjust_uri(self, uri, filename): # def __init__(self, # directories=None, # module_directory=None, # filesystem_checks=True, # collection_size=-1, # format_exceptions=False, # error_handler=None, # disable_unicode=False, # output_encoding=None, # encoding_errors='strict', # cache_type=None, # cache_dir=None, cache_url=None, # cache_enabled=True, # modulename_callable=None, # default_filters=None, # buffer_filters=(), # imports=None, # input_encoding=None, # preprocessor=None): # def get_template(self, uri): # def adjust_uri(self, uri, relativeto): # def filename_to_uri(self, filename): # def _relativeize(self, filename): # def _load(self, filename, uri): # def _check(self, uri, template): # def put_string(self, uri, text): # def put_template(self, uri, template): , which may include functions, classes, or code. Output only the next line.
<%def name="c()">
Based on the snippet: <|code_start|>#! /usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'maxim' class NamedDictTest(unittest.TestCase): def test_embedded_dict(self): spec = hype.spec.new({ 'foo': { <|code_end|> , predict the immediate next line with the help of imports: import six import unittest import numpy as np import hyperengine as hype from hyperengine.base import NamedDict and context (classes, functions, sometimes code) from other files: # Path: hyperengine/base/named_dict.py # class NamedDict(object): # def __init__(self, input): # for k, v in input.items(): # if isinstance(v, (list, tuple)): # setattr(self, k, [NamedDict(x) if isinstance(x, dict) else x for x in v]) # else: # setattr(self, k, NamedDict(v) if isinstance(v, dict) else v) # # def keys(self): # return self.__dict__.keys() # # def items(self): # return self.__dict__.items() # # def values(self): # return self.__dict__.values() # # def get(self, key, default=None): # return self.__dict__.get(key, default) # # def __getitem__(self, key): # return self.__dict__[key] # # def __getattribute__(self, key): # if (key in ['get', 'keys', 'items', 'values']) or (key.startswith('__') and key.endswith('__')): # return object.__getattribute__(self, key) # return self.__dict__.get(key, None) # # def __contains__(self, key): # return key in self.__dict__ # # def __repr__(self): # return smart_str(self.__dict__) . Output only the next line.
'bar': {
Given the code snippet: <|code_start|> return {} if self._accuracy is None: loss = self._session.run(self._loss, feed_dict=feed_dict) return {'loss': loss} if self._loss is None: accuracy = self._session.run(self._accuracy, feed_dict=feed_dict) return {'accuracy': accuracy} loss, accuracy = self._session.run([self._loss, self._accuracy], feed_dict=feed_dict) return {'loss': loss, 'accuracy': accuracy} def terminate(self): tf.reset_default_graph() def graph(self): return self._graph def model_size(self): return self._model_size def _get_feed_dict(self, batch_x, batch_y, mode): feed_dict = {self._x: batch_x, self._y: batch_y} if self._mode is not None: feed_dict[self._mode] = mode for k, v in self._extra_feed.items(): if isinstance(v, dict) and mode in v.keys(): v = v[mode] feed_dict[k] = v return feed_dict def _find_tensor(self, name, mandatory=True): <|code_end|> , generate the next line using the imports in this file: import tensorflow as tf from ...base import * from ...model.base_runner import BaseRunner from .tf_util import graph_vars, get_total_dim and context (functions, classes, or occasionally code) from other files: # Path: hyperengine/model/base_runner.py # class BaseRunner(object): # """ # The runner represents a connecting layer between the solver and the machine learning model. # Responsible for communicating with the model with a data batch: prepare, train, evaluate. # """ # # def build_model(self): # """ # Builds and prepares a model. Method is not expected to return anything. # """ # raise NotImplementedError() # # def init(self, **kwargs): # """ # Runs the model initializer. # """ # raise NotImplementedError() # # def run_batch(self, batch_x, batch_y): # """ # Runs the training iteration for a batch of data. Method is not expected to return anything. # """ # raise NotImplementedError() # # def evaluate(self, batch_x, batch_y): # """ # Evaluates the test result for a batch of data. Method should return the dictionary that contains # one (or all) of the following: # - batch accuracy (key 'accuracy') # - associated loss (key 'loss') # - any other computed data (key 'data') # """ # raise NotImplementedError() # # def model_size(self): # """ # Returns the model size. # """ # raise NotImplementedError() # # Path: hyperengine/impl/tensorflow/tf_util.py # def graph_vars(graph): # for n in graph.as_graph_def().node: # element = graph.as_graph_element(n.name) # if element.type == 'Variable' or element.type == 'VariableV2': # yield element # # def get_total_dim(element): # # See TensorShapeProto # shape = element.get_attr('shape') # dims = shape.dim # return functools.reduce(lambda x, y: x * y, [dim.size for dim in dims], 1) . Output only the next line.
try:
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- __author__ = 'maxim' class TensorflowRunner(BaseRunner): def __init__(self, model=None, extra_feed={}, input='input', label='label', mode='mode', loss='loss', accuracy='accuracy', train='minimize'): super(TensorflowRunner, self).__init__() self._graph = model or tf.get_default_graph() assert isinstance(self._graph, tf.Graph), '"model" argument must be either tf.Graph instance or None' self._extra_feed = extra_feed assert isinstance(self._extra_feed, dict), '"extra_feed" must be a dictionary (tensor -> value)' self._x = self._find_tensor(input) self._y = self._find_tensor(label) self._mode = self._find_tensor(mode, mandatory=False) self._loss = self._find_tensor(loss, mandatory=False) self._accuracy = self._find_tensor(accuracy, mandatory=False) self._minimize = self._find_op(train) self._model_size = self._calc_model_size() def build_model(self): pass def init(self, **kwargs): <|code_end|> . Write the next line using the current file imports: import tensorflow as tf from ...base import * from ...model.base_runner import BaseRunner from .tf_util import graph_vars, get_total_dim and context from other files: # Path: hyperengine/model/base_runner.py # class BaseRunner(object): # """ # The runner represents a connecting layer between the solver and the machine learning model. # Responsible for communicating with the model with a data batch: prepare, train, evaluate. # """ # # def build_model(self): # """ # Builds and prepares a model. Method is not expected to return anything. # """ # raise NotImplementedError() # # def init(self, **kwargs): # """ # Runs the model initializer. # """ # raise NotImplementedError() # # def run_batch(self, batch_x, batch_y): # """ # Runs the training iteration for a batch of data. Method is not expected to return anything. # """ # raise NotImplementedError() # # def evaluate(self, batch_x, batch_y): # """ # Evaluates the test result for a batch of data. Method should return the dictionary that contains # one (or all) of the following: # - batch accuracy (key 'accuracy') # - associated loss (key 'loss') # - any other computed data (key 'data') # """ # raise NotImplementedError() # # def model_size(self): # """ # Returns the model size. # """ # raise NotImplementedError() # # Path: hyperengine/impl/tensorflow/tf_util.py # def graph_vars(graph): # for n in graph.as_graph_def().node: # element = graph.as_graph_element(n.name) # if element.type == 'Variable' or element.type == 'VariableV2': # yield element # # def get_total_dim(element): # # See TensorShapeProto # shape = element.get_attr('shape') # dims = shape.dim # return functools.reduce(lambda x, y: x * y, [dim.size for dim in dims], 1) , which may include functions, classes, or code. Output only the next line.
self._session = kwargs['session']
Here is a snippet: <|code_start|> def __init__(self, model=None, extra_feed={}, input='input', label='label', mode='mode', loss='loss', accuracy='accuracy', train='minimize'): super(TensorflowRunner, self).__init__() self._graph = model or tf.get_default_graph() assert isinstance(self._graph, tf.Graph), '"model" argument must be either tf.Graph instance or None' self._extra_feed = extra_feed assert isinstance(self._extra_feed, dict), '"extra_feed" must be a dictionary (tensor -> value)' self._x = self._find_tensor(input) self._y = self._find_tensor(label) self._mode = self._find_tensor(mode, mandatory=False) self._loss = self._find_tensor(loss, mandatory=False) self._accuracy = self._find_tensor(accuracy, mandatory=False) self._minimize = self._find_op(train) self._model_size = self._calc_model_size() def build_model(self): pass def init(self, **kwargs): self._session = kwargs['session'] init = self._find_op('initializer', tf.global_variables_initializer()) self._session.run(init) def run_batch(self, batch_x, batch_y): feed_dict = self._get_feed_dict(batch_x, batch_y, 'train') self._session.run(self._minimize, feed_dict=feed_dict) def evaluate(self, batch_x, batch_y): <|code_end|> . Write the next line using the current file imports: import tensorflow as tf from ...base import * from ...model.base_runner import BaseRunner from .tf_util import graph_vars, get_total_dim and context from other files: # Path: hyperengine/model/base_runner.py # class BaseRunner(object): # """ # The runner represents a connecting layer between the solver and the machine learning model. # Responsible for communicating with the model with a data batch: prepare, train, evaluate. # """ # # def build_model(self): # """ # Builds and prepares a model. Method is not expected to return anything. # """ # raise NotImplementedError() # # def init(self, **kwargs): # """ # Runs the model initializer. # """ # raise NotImplementedError() # # def run_batch(self, batch_x, batch_y): # """ # Runs the training iteration for a batch of data. Method is not expected to return anything. # """ # raise NotImplementedError() # # def evaluate(self, batch_x, batch_y): # """ # Evaluates the test result for a batch of data. Method should return the dictionary that contains # one (or all) of the following: # - batch accuracy (key 'accuracy') # - associated loss (key 'loss') # - any other computed data (key 'data') # """ # raise NotImplementedError() # # def model_size(self): # """ # Returns the model size. # """ # raise NotImplementedError() # # Path: hyperengine/impl/tensorflow/tf_util.py # def graph_vars(graph): # for n in graph.as_graph_def().node: # element = graph.as_graph_element(n.name) # if element.type == 'Variable' or element.type == 'VariableV2': # yield element # # def get_total_dim(element): # # See TensorShapeProto # shape = element.get_attr('shape') # dims = shape.dim # return functools.reduce(lambda x, y: x * y, [dim.size for dim in dims], 1) , which may include functions, classes, or code. Output only the next line.
feed_dict = self._get_feed_dict(batch_x, batch_y, 'test')
Predict the next line after this snippet: <|code_start|> def __init__(self, input): for k, v in input.items(): if isinstance(v, (list, tuple)): setattr(self, k, [NamedDict(x) if isinstance(x, dict) else x for x in v]) else: setattr(self, k, NamedDict(v) if isinstance(v, dict) else v) def keys(self): return self.__dict__.keys() def items(self): return self.__dict__.items() def values(self): return self.__dict__.values() def get(self, key, default=None): return self.__dict__.get(key, default) def __getitem__(self, key): return self.__dict__[key] def __getattribute__(self, key): if (key in ['get', 'keys', 'items', 'values']) or (key.startswith('__') and key.endswith('__')): return object.__getattribute__(self, key) return self.__dict__.get(key, None) def __contains__(self, key): return key in self.__dict__ <|code_end|> using the current file's imports: from .util import smart_str and any relevant context from other files: # Path: hyperengine/base/util.py # def smart_str(val): # if type(val) in [float, np.float32, np.float64] and val: # return '%.6f' % val if abs(val) > 1e-6 else '%e' % val # if type(val) == dict: # return '{%s}' % ', '.join(['%s: %s' % (repr(k), smart_str(val[k])) for k in sorted(val.keys())]) # if type(val) in [list, tuple]: # return '[%s]' % ', '.join(['%s' % smart_str(i) for i in val]) # return repr(val) . Output only the next line.
def __repr__(self):
Given snippet: <|code_start|>#! /usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'maxim' reducers = { 'max': lambda curve: np.max(curve) if curve else 0, <|code_end|> , continue by predicting the next line. Consider current file imports: import inspect import numpy as np from ..base import * from .data_set import IterableDataProvider and context: # Path: hyperengine/model/data_set.py # class IterableDataProvider(DataProvider): # def __init__(self): # super(IterableDataProvider, self).__init__() # self._size = 0 # self._step = 0 # self._epochs_completed = 0 # self._index_in_epoch = 0 # self._just_completed = False # # @property # def size(self): # """ # Data size (number of rows) # """ # return self._size # # @property # def step(self): # """ # The number of batches processed # """ # return self._step # # @property # def index(self): # """ # Total index of input rows (over all epochs) # """ # return self._epochs_completed * self._size + self._index_in_epoch # # @property # def index_in_epoch(self): # """ # The index of input rows in a current epoch # """ # return self._index_in_epoch # # @property # def epochs_completed(self): # """ # A number of completed epochs # """ # return self._epochs_completed # # @property # def just_completed(self): # """ # Whether the previous epoch was just completed # """ # return self._just_completed # # def reset_counters(self): # """ # Resets all counters. # """ # self._step = 0 # self._epochs_completed = 0 # self._index_in_epoch = 0 # self._just_completed = False # # def next_batch(self, batch_size): # """ # Returns the next `batch_size` examples from this data set. # """ # raise NotImplementedError # # def _inc_index(self): # index = self._index_in_epoch + 1 # if index >= self._size: # self._index_in_epoch = 0 # self._epochs_completed += 1 # self._just_completed = True # else: # self._index_in_epoch = index # self._just_completed = False which might include code, classes, or functions. Output only the next line.
'avg': lambda curve: np.mean(curve) if curve else 0,
Here is a snippet: <|code_start|>#! /usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'maxim' class TensorflowModelIO(ModelIO): def __init__(self, **params): super(TensorflowModelIO, self).__init__(**params) self.saver = tf.train.Saver(defer_build=True) def save_session(self, session, directory=None): directory = directory or self.save_dir if not ModelIO._prepare(directory): return destination = os.path.join(self.save_dir, 'session.data') self.saver.build() <|code_end|> . Write the next line using the current file imports: import os import tensorflow as tf from ...base import * from hyperengine.model import ModelIO and context from other files: # Path: hyperengine/model/model_io.py # class ModelIO(BaseIO): # def __init__(self, **params): # super(ModelIO, self).__init__(**params) # self.data_saver = params.get('data_saver') # # def save_results(self, results, directory=None): # directory = directory or self.save_dir # if not ModelIO._prepare(directory): # return # # destination = os.path.join(directory, 'results.xjson') # with open(destination, 'w') as file_: # file_.write(smart_str(results)) # debug('Results saved to %s' % destination) # # def load_results(self, directory, log_level): # if directory is None: # return # # destination = os.path.join(directory, 'results.xjson') # if os.path.exists(destination): # results = ModelIO._load_dict(destination) # log_at_level(log_level, 'Loaded results: %s from %s' % (smart_str(results), destination)) # return results # # def save_hyper_params(self, hyper_params, directory=None): # directory = directory or self.save_dir # if not ModelIO._prepare(directory): # return # # destination = os.path.join(directory, 'hyper_params.xjson') # with open(destination, 'w') as file_: # file_.write(smart_str(hyper_params)) # debug('Hyper parameters saved to %s' % destination) # # def load_hyper_params(self, directory=None): # directory = directory or self.load_dir # if directory is None: # return # # hyper_params = ModelIO._load_dict(os.path.join(directory, 'hyper_params.xjson')) # if hyper_params: # info('Loaded hyper-params: %s' % smart_str(hyper_params)) # return hyper_params # # def save_data(self, data, directory=None): # directory = directory or self.save_dir # if self.data_saver is None or data is None or not ModelIO._prepare(directory): # return # # destination = os.path.join(directory, 'misclassified') # actual_destination = call(self.data_saver, data, destination) # if actual_destination: # debug('Misclassified data saved to %s' % actual_destination) # else: # warn('Data saver can not be not called or returns None') , which may include functions, classes, or code. Output only the next line.
self.saver.save(session, destination)
Predict the next line for this snippet: <|code_start|> def test_successful_to_be(self): expect_object = Expect(self.data) expect_object.negate = False try: expect_object.to_be(self.data) except ExpectationException: raise AssertionError def test_failure_to_be_call(self): expect_object = Expect(self.data) expect_object.negate = False with self.assertRaises(ExpectationException): expect_object.to_be({'foo': 'bar'}) def test_successful_not_to_be_call(self): expect_object = Expect(self.data) expect_object.negate = True try: expect_object.to_be({'foo': 'bar'}) except ExpectationException: raise AssertionError def test_failure_not_to_be_call(self): expect_object = Expect(self.data) expect_object.negate = True with self.assertRaises(ExpectationException): <|code_end|> with the help of current file imports: from unittest import TestCase from jasper.expect import Expect from jasper.exceptions import ExpectationException and context from other files: # Path: jasper/expect.py # class Expect(object): # """ # A class for making assertions on data. # """ # def __init__(self, actual_data): # """ # Initialize a new Expect object. # # :param actual_data: The actual data to make assertions against. # """ # self.actual_data = actual_data # self.negate = False # # def not_(self): # """ # Negate any future expectations. # # :return: This Expect object. # """ # self.negate = True # return self # # def to_be(self, expected_data): # """ # Make an assertion that this objects actual data is the expected data. # # :param expected_data: The data to expect the actual data to be. # :raise ExpectationException: If the expectation fails. # """ # if self.negate and self.actual_data is expected_data: # raise ExpectationException(self.actual_data, expected_data, 'not_to_be') # elif not self.negate and self.actual_data is not expected_data: # raise ExpectationException(self.actual_data, expected_data, 'to_be') # # def to_equal(self, expected_data): # """ # Make an assertion that this objects actual data is equal to the expected data. # # :param expected_data: The data to expect the actual data to be equal to. # :raise ExpectationException: If the expectation fails. # """ # if self.negate and self.actual_data == expected_data: # raise ExpectationException(self.actual_data, expected_data, 'not_to_equal') # elif not self.negate and self.actual_data != expected_data: # raise ExpectationException(self.actual_data, expected_data, 'to_equal') # # def to_be_less_than(self, expected_data): # """ # Make an assertion that this objects actual data is less than the expected data. # # :param expected_data: The data to expect the actual data to be less than. # :raise ExpectationException: If the expectation fails. # """ # if self.negate and self.actual_data < expected_data: # raise ExpectationException(self.actual_data, expected_data, 'not_to_be_less_than') # elif not self.negate and not self.actual_data < expected_data: # raise ExpectationException(self.actual_data, expected_data, 'to_be_less_than') # # def to_be_greater_than(self, expected_data): # """ # Make an assertion that this objects actual data is greater than the expected data. # # :param expected_data: The data to expect the actual data to be less than. # :raise ExpectationException: If the expectation fails. # """ # if self.negate and self.actual_data > expected_data: # raise ExpectationException(self.actual_data, expected_data, 'not_to_be_greater_than') # elif not self.negate and not self.actual_data > expected_data: # raise ExpectationException(self.actual_data, expected_data, 'to_be_greater_than') # # def to_be_less_than_or_equal_to(self, expected_data): # """ # Make an assertion that this objects actual data is less than or equal to the expected data # # :param expected_data: The data to expect the actual data to be less than or equal to. # :raise ExpectationException: If the expectation fails. # """ # if self.negate and self.actual_data <= expected_data: # raise ExpectationException(self.actual_data, expected_data, 'not_to_be_less_than_or_equal_to') # elif not self.negate and not self.actual_data <= expected_data: # raise ExpectationException(self.actual_data, expected_data, 'to_be_less_than_or_equal_to') # # def to_be_greater_than_or_equal_to(self, expected_data): # """ # Make an assertion that this objects actual data is greater than or equal to the expected data # # :param expected_data: The data to expect the actual data to be greater than or equal to. # :raise ExpectationException: If the expectation fails. # """ # if self.negate and self.actual_data >= expected_data: # raise ExpectationException(self.actual_data, expected_data, 'not_to_be_greater_than_or_equal_to') # elif not self.negate and not self.actual_data >= expected_data: # raise ExpectationException(self.actual_data, expected_data, 'to_be_greater_than_or_equal_to') # # Path: jasper/exceptions.py # class ExpectationException(Exception): # """ # An Exception that is thrown when an expectation fails in the Expect class. # """ # def __init__(self, actual, expected, operator): # """ # Initialize this ExpectationException object. # # :param actual: The actual data used during the expectation. # :param expected: The expected data used during the expectation. # :param operator: The operator used during the expectation. # """ # super().__init__() # self.actual = actual # self.expected = expected # self.operator = operator # # def __str__(self): # return f'FAILURE: Expected {self.actual} {self.operator} {self.expected}' , which may contain function names, class names, or code. Output only the next line.
expect_object.to_be(self.data)
Given snippet: <|code_start|> raise AssertionError def test_failure_to_be_less_than_or_equal_to(self): expect_object = Expect(10) expect_object.negate = False with self.assertRaises(ExpectationException): expect_object.to_be_less_than_or_equal_to(9) def test_successful_not_to_be_less_than_or_equal_to(self): expect_object = Expect(10) expect_object.negate = True try: expect_object.to_be_less_than_or_equal_to(9) except ExpectationException: raise AssertionError def test_failure_not_to_be_less_than_or_equal_to(self): expect_object = Expect(10) expect_object.negate = True with self.assertRaises(ExpectationException): expect_object.to_be_less_than_or_equal_to(10) with self.assertRaises(ExpectationException): expect_object.to_be_less_than_or_equal_to(15) def test_successful_to_be_greater_than_or_equal_to(self): expect_object = Expect(10) <|code_end|> , continue by predicting the next line. Consider current file imports: from unittest import TestCase from jasper.expect import Expect from jasper.exceptions import ExpectationException and context: # Path: jasper/expect.py # class Expect(object): # """ # A class for making assertions on data. # """ # def __init__(self, actual_data): # """ # Initialize a new Expect object. # # :param actual_data: The actual data to make assertions against. # """ # self.actual_data = actual_data # self.negate = False # # def not_(self): # """ # Negate any future expectations. # # :return: This Expect object. # """ # self.negate = True # return self # # def to_be(self, expected_data): # """ # Make an assertion that this objects actual data is the expected data. # # :param expected_data: The data to expect the actual data to be. # :raise ExpectationException: If the expectation fails. # """ # if self.negate and self.actual_data is expected_data: # raise ExpectationException(self.actual_data, expected_data, 'not_to_be') # elif not self.negate and self.actual_data is not expected_data: # raise ExpectationException(self.actual_data, expected_data, 'to_be') # # def to_equal(self, expected_data): # """ # Make an assertion that this objects actual data is equal to the expected data. # # :param expected_data: The data to expect the actual data to be equal to. # :raise ExpectationException: If the expectation fails. # """ # if self.negate and self.actual_data == expected_data: # raise ExpectationException(self.actual_data, expected_data, 'not_to_equal') # elif not self.negate and self.actual_data != expected_data: # raise ExpectationException(self.actual_data, expected_data, 'to_equal') # # def to_be_less_than(self, expected_data): # """ # Make an assertion that this objects actual data is less than the expected data. # # :param expected_data: The data to expect the actual data to be less than. # :raise ExpectationException: If the expectation fails. # """ # if self.negate and self.actual_data < expected_data: # raise ExpectationException(self.actual_data, expected_data, 'not_to_be_less_than') # elif not self.negate and not self.actual_data < expected_data: # raise ExpectationException(self.actual_data, expected_data, 'to_be_less_than') # # def to_be_greater_than(self, expected_data): # """ # Make an assertion that this objects actual data is greater than the expected data. # # :param expected_data: The data to expect the actual data to be less than. # :raise ExpectationException: If the expectation fails. # """ # if self.negate and self.actual_data > expected_data: # raise ExpectationException(self.actual_data, expected_data, 'not_to_be_greater_than') # elif not self.negate and not self.actual_data > expected_data: # raise ExpectationException(self.actual_data, expected_data, 'to_be_greater_than') # # def to_be_less_than_or_equal_to(self, expected_data): # """ # Make an assertion that this objects actual data is less than or equal to the expected data # # :param expected_data: The data to expect the actual data to be less than or equal to. # :raise ExpectationException: If the expectation fails. # """ # if self.negate and self.actual_data <= expected_data: # raise ExpectationException(self.actual_data, expected_data, 'not_to_be_less_than_or_equal_to') # elif not self.negate and not self.actual_data <= expected_data: # raise ExpectationException(self.actual_data, expected_data, 'to_be_less_than_or_equal_to') # # def to_be_greater_than_or_equal_to(self, expected_data): # """ # Make an assertion that this objects actual data is greater than or equal to the expected data # # :param expected_data: The data to expect the actual data to be greater than or equal to. # :raise ExpectationException: If the expectation fails. # """ # if self.negate and self.actual_data >= expected_data: # raise ExpectationException(self.actual_data, expected_data, 'not_to_be_greater_than_or_equal_to') # elif not self.negate and not self.actual_data >= expected_data: # raise ExpectationException(self.actual_data, expected_data, 'to_be_greater_than_or_equal_to') # # Path: jasper/exceptions.py # class ExpectationException(Exception): # """ # An Exception that is thrown when an expectation fails in the Expect class. # """ # def __init__(self, actual, expected, operator): # """ # Initialize this ExpectationException object. # # :param actual: The actual data used during the expectation. # :param expected: The expected data used during the expectation. # :param operator: The operator used during the expectation. # """ # super().__init__() # self.actual = actual # self.expected = expected # self.operator = operator # # def __str__(self): # return f'FAILURE: Expected {self.actual} {self.operator} {self.expected}' which might include code, classes, or functions. Output only the next line.
expect_object.negate = False
Given snippet: <|code_start|> def setUp(self): self.slow_function_called = False self.slow_function_called_with = None def slow_function(context, sleep_time=0.5, fail=False): time.sleep(sleep_time) self.slow_function_called = True self.slow_function_called_with = {'context': context, 'sleep_time': sleep_time, 'fail': fail} if fail: raise Exception self.async_slow_function_called = False self.async_slow_function_called_with = None async def async_slow_function(context, sleep_time=0.5, fail=False): await asyncio.sleep(sleep_time) self.async_slow_function_called = True self.async_slow_function_called_with = {'context': context, 'sleep_time': sleep_time, 'fail': fail} if fail: raise Exception self.slow_function = slow_function self.async_slow_function = async_slow_function self.loop = asyncio.new_event_loop() def tearDown(self): self.loop.close() <|code_end|> , continue by predicting the next line. Consider current file imports: from unittest import TestCase, mock from jasper.steps import Step, step import time import asyncio and context: # Path: jasper/steps.py # class Step(object): # """ # The Step class is used as a wrapper around functions for testing behaviours. # """ # def __init__(self, function, **kwargs): # """ # Initialize a new Step object. # # :param function: The function this step will call when this step is run. # :param kwargs: Kwargs to call the given function with. # """ # self.function = function # self.kwargs = kwargs # self.ran = False # self.passed = False # # async def run(self, context): # """ # Run this step and record the results. # # :param context: A context object too pass into this steps function. # """ # try: # if asyncio.iscoroutinefunction(self.function): # await self.function(context, **self.kwargs) # else: # self.function(context, **self.kwargs) # except Exception: # raise # else: # self.passed = True # finally: # self.ran = True # # def step(func): # """ # A decorator for wrapping a function into a Step object. # # :param func: The function to create a step out of. # :return: A function which when called will return a new instance of a Step object. # """ # @wraps(func) # def wrapper(**kwargs): # return Step(func, **kwargs) # # return wrapper which might include code, classes, or functions. Output only the next line.
def test_init(self):
Given the following code snippet before the placeholder: <|code_start|> self.async_slow_function_called_with = {'context': context, 'sleep_time': sleep_time, 'fail': fail} if fail: raise Exception self.slow_function = slow_function self.async_slow_function = async_slow_function self.loop = asyncio.new_event_loop() def tearDown(self): self.loop.close() def test_init(self): some_step = Step(self.slow_function, sleep_time=0.1, fail=False) self.assertEqual(some_step.function, self.slow_function) self.assertEqual(some_step.kwargs, {'sleep_time': 0.1, 'fail': False}) self.assertFalse(some_step.ran) self.assertFalse(some_step.passed) def test_successful_run(self): mock_context = mock.MagicMock() some_step = Step(self.slow_function, sleep_time=0.1, fail=False) try: self.loop.run_until_complete(some_step.run(mock_context)) except Exception: raise AssertionError else: self.assertTrue(some_step.ran) <|code_end|> , predict the next line using imports from the current file: from unittest import TestCase, mock from jasper.steps import Step, step import time import asyncio and context including class names, function names, and sometimes code from other files: # Path: jasper/steps.py # class Step(object): # """ # The Step class is used as a wrapper around functions for testing behaviours. # """ # def __init__(self, function, **kwargs): # """ # Initialize a new Step object. # # :param function: The function this step will call when this step is run. # :param kwargs: Kwargs to call the given function with. # """ # self.function = function # self.kwargs = kwargs # self.ran = False # self.passed = False # # async def run(self, context): # """ # Run this step and record the results. # # :param context: A context object too pass into this steps function. # """ # try: # if asyncio.iscoroutinefunction(self.function): # await self.function(context, **self.kwargs) # else: # self.function(context, **self.kwargs) # except Exception: # raise # else: # self.passed = True # finally: # self.ran = True # # def step(func): # """ # A decorator for wrapping a function into a Step object. # # :param func: The function to create a step out of. # :return: A function which when called will return a new instance of a Step object. # """ # @wraps(func) # def wrapper(**kwargs): # return Step(func, **kwargs) # # return wrapper . Output only the next line.
self.assertTrue(some_step.passed)
Predict the next line after this snippet: <|code_start|> class ExpectationExceptionTestCase(TestCase): def test_init(self): expectation_exception = ExpectationException('foo', 'bar', 'some_operator') self.assertTrue(isinstance(expectation_exception, Exception)) <|code_end|> using the current file's imports: from unittest import TestCase from jasper.exceptions import ExpectationException, ValidationException and any relevant context from other files: # Path: jasper/exceptions.py # class ExpectationException(Exception): # """ # An Exception that is thrown when an expectation fails in the Expect class. # """ # def __init__(self, actual, expected, operator): # """ # Initialize this ExpectationException object. # # :param actual: The actual data used during the expectation. # :param expected: The expected data used during the expectation. # :param operator: The operator used during the expectation. # """ # super().__init__() # self.actual = actual # self.expected = expected # self.operator = operator # # def __str__(self): # return f'FAILURE: Expected {self.actual} {self.operator} {self.expected}' # # class ValidationException(Exception): # """ # An Exception that is thrown when an object fails validation during construction. # """ # pass . Output only the next line.
self.assertEqual(expectation_exception.actual, 'foo')
Based on the snippet: <|code_start|> class ContextTestCase(TestCase): def test_empty_init(self): context = Context() self.assertEqual(context.__dict__, {'_items': {}}) def test_init_with_kwargs(self): context = Context(foo='bar', foobar='barfoo') <|code_end|> , predict the immediate next line with the help of imports: from unittest import TestCase from jasper.context import Context and context (classes, functions, sometimes code) from other files: # Path: jasper/context.py # class Context(object): # """ # A dictionary-like object where attributes can be accessed using the '.' operator. # """ # def __init__(self, **kwargs): # """ # Initialize a new Context object. # # :param kwargs: Keys and values to store into this Context on creation. # """ # self.__dict__['_items'] = dict(**kwargs) # # def __getattr__(self, item): # """ # Get an attribute from this Context. # # :param item: The item to get from this Context. # :return: The item # :raise: AttributeError: If the item is not in this Context. # """ # try: # return self._items[item] # except KeyError: # raise AttributeError(f'{item} not in Context.') # # def __setattr__(self, key, value): # """ # Set an attribute on this Context. # # :param key: The name of the attribute to set. # :param value: The value of the attribute to set. # """ # self._items[key] = value # # def __str__(self): # """ # Get a string representation of this Context. # # :return: A string representation of this Context. # """ # return f"{self.__dict__['_items']}" # # def copy(self): # """ # Get a deep copy of this Context. # # :return: A new Context object which is a copy of this Context. # """ # return Context(**deepcopy(self.__dict__['_items'])) . Output only the next line.
self.assertEqual(context.__dict__, {'_items': {'foo': 'bar', 'foobar': 'barfoo'}})
Based on the snippet: <|code_start|> class JasperTestCase(TestCase): def setUp(self): self.test_directory = os.path.abspath('.\mock_features') @mock.patch('jasper.entrypoints.Display') @mock.patch('jasper.entrypoints.Runner') def test_jasper_without_options(self, mock_runner_class, mock_display_class): mock_runner = mock.MagicMock() mock_runner.run.return_value = 'foobar' mock_runner_class.return_value = mock_runner mock_display = mock.MagicMock() mock_display_class.return_value = mock_display click_runner = CliRunner() result = click_runner.invoke(jasper, [self.test_directory]) self.assertEqual(result.exit_code, 0) mock_runner_class.assert_called_once_with(self.test_directory) mock_runner.run.assert_called_once() mock_display_class.assert_called_once_with(force_ansi=False, verbosity_level=0) mock_display.prepare_suite.assert_called_once_with(mock_runner.run.return_value) mock_display.display.assert_called_once() <|code_end|> , predict the immediate next line with the help of imports: from unittest import TestCase, mock from click.testing import CliRunner from jasper.entrypoints import jasper import os and context (classes, functions, sometimes code) from other files: # Path: jasper/entrypoints.py # @click.command() # @click.argument('test_directory', type=click.Path(exists=True, file_okay=False, dir_okay=True, resolve_path=True)) # @click.option('--ansi', is_flag=True, default=False, help="Flag to force display to use ansi escape sequences for coloring.") # @click.option('-v', type=click.IntRange(0, 2), default=0, help="Verbosity level from 0 to 2. default is 0.") # def jasper(test_directory, ansi, v): # """ # The entrypoint of the application. # # Runs Jasper tests within a given directory and displays the results. # # :param test_directory: The directory containing feature files to run. # :param ansi: A flag for whether or not to force ansi escape sequences in the display for coloring purposes. # :param v: A verbosity level for the display. Ranges from 0 to 2. # """ # runner = Runner(test_directory) # completed_suite = runner.run() # display = Display(force_ansi=ansi, verbosity_level=v) # display.prepare_suite(completed_suite) # display.display() . Output only the next line.
@mock.patch('jasper.entrypoints.Display')
Predict the next line after this snippet: <|code_start|> def test_num_scenarios_failed(self): suite = Suite() suite.features = [self.passing_feature_mock(), self.failing_feature_mock()] self.assertEqual(suite.num_scenarios_failed, 1) def test_add_feature(self): suite = Suite() feature_one = self.passing_feature_mock() feature_two = self.failing_feature_mock() suite.add_feature(feature_one) self.assertEqual(suite.features, [feature_one]) suite.add_feature(feature_two) self.assertEqual(suite.features, [feature_one, feature_two]) def test_successful_run(self): suite = Suite() feature_one = self.passing_feature_mock() feature_two = self.passing_feature_mock() suite.features = [feature_one, feature_two] self.loop.run_until_complete(suite.run()) <|code_end|> using the current file's imports: from unittest import TestCase from jasper.suite import Suite import asyncio and any relevant context from other files: # Path: jasper/suite.py # class Suite(object): # """ # An internal class for running a collection of Feature of objects and collecting results. # """ # def __init__(self): # """ # Initialize a new Suite object. # """ # self.features = [] # self.successes = [] # self.failures = [] # self.passed = True # # @property # def num_features_passed(self): # """ # The number of features that passed after running this suite. # """ # return len(self.successes) # # @property # def num_features_failed(self): # """ # The number of features that failed after running this suite. # """ # return len(self.failures) # # @property # def num_scenarios_passed(self): # """ # The number of scenarios that passed running this suite. # """ # return sum([feature.num_scenarios_passed for feature in self.features]) # # @property # def num_scenarios_failed(self): # """ # The number of scenarios that failed after running this suite. # """ # return sum([feature.num_scenarios_failed for feature in self.features]) # # def add_feature(self, feature): # """ # Add a feature to this suite. # # :param feature: The Feature object to add to this suite. # """ # self.features.append(feature) # # async def run(self): # """ # Run all the features of this suite. # """ # await self.__wait_with_progress([self.__run_feature(feature) for feature in self.features]) # # async def __run_feature(self, feature): # await feature.run() # if feature.passed: # self.successes.append(feature) # else: # self.failures.append(feature) # self.passed = False # # return feature # # async def __wait_with_progress(self, coros): # with tqdm.tqdm( # total=sum([len(feature.scenarios) for feature in self.features]), # desc=f'Running {len(self.features)} features and ' # f'{sum([len(feature.scenarios) for feature in self.features])} scenarios', # ncols=100, bar_format='{desc}{percentage:3.0f}%|{bar}| {elapsed}' # ) as progress_bar: # for future in asyncio.as_completed(coros): # completed_feature = await future # progress_bar.update(len(completed_feature.scenarios)) . Output only the next line.
self.assertTrue(feature_one.ran)
Continue the code snippet: <|code_start|> @mock.patch('jasper.runner.Suite') def test_init(self, mock_suite): runner = Runner(self.test_directory) self.assertEqual(runner.test_directory, self.test_directory) self.assertEqual(runner.test_file_paths, []) self.assertTrue(isinstance(runner.suite, mock.MagicMock)) @mock.patch('jasper.runner.Suite') def test_discover(self, mock_suite): runner = Runner(self.test_directory) runner.discover() self.assertEqual(runner.test_file_paths, [ os.path.abspath(".\\mock_features\\runner\\runner_feature.py"), os.path.abspath(".\\mock_features\\runner_two\\runner_two_feature.py") ]) @mock.patch('jasper.runner.Suite') def test_build_suite(self, mock_suite): added_features = [] def save_feature(feature): added_features.append(feature) runner = Runner(self.test_directory) runner.suite.add_feature.side_effect = save_feature runner.test_file_paths = [ ".\\mock_features\\runner\\runner_feature.py", <|code_end|> . Use current file imports: from unittest import TestCase, mock from jasper.runner import Runner import os and context (classes, functions, or code) from other files: # Path: jasper/runner.py # class Runner(object): # """ # The class responsible for finding, building, and running features. # """ # def __init__(self, test_directory): # """ # Initialize a new Runner object. # # :param test_directory: The directory to search for feature files in. # """ # self.test_directory = test_directory # self.test_file_paths = [] # self.suite = Suite() # # def run(self): # """ # Discover the feature files, build the suite, and run the tests. # # :return: The Suite that has been built and run. # """ # self.discover() # self.build_suite() # loop = asyncio.get_event_loop() # loop.run_until_complete(self.suite.run()) # loop.close() # time.sleep(0.5) # return self.suite # # def discover(self): # """ # Find any feature files within the given test directory. # """ # for dir_path, dir_names, files in os.walk(self.test_directory): # for file_name in files: # if file_name.lower().endswith('feature.py'): # self.test_file_paths.append(os.path.join(dir_path, file_name)) # # def build_suite(self): # """ # Build a Suite object out of the Features contained within the found feature files. # """ # for test_file_path in self.test_file_paths: # spec = importlib.util.spec_from_file_location("module.name", test_file_path) # module = importlib.util.module_from_spec(spec) # spec.loader.exec_module(module) # for name in dir(module): # obj = getattr(module, name) # if isinstance(obj, Feature): # self.suite.add_feature(obj) . Output only the next line.
".\\mock_features\\runner_two\\runner_two_feature.py"
Given the following code snippet before the placeholder: <|code_start|># -*- coding: iso-8859-1 -*- r''' This file is part of orbkit. See the main program or documentation for information on the license. It shows two examples of how to use orbkit for evaluating analytical integrals. First Part: Compute the electron number analytically using the standard density formula. <|code_end|> , predict the next line using imports from the current file: from orbkit.read import main_read from orbkit.tools import * from orbkit.analytical_integrals import get_ao_overlap,get_mo_overlap,print2D and context including class names, function names, and sometimes code from other files: # Path: orbkit/read/high_level.py # def main_read(fname, all_mo=False, spin=None, itype='auto', check_norm=False, **kwargs): # ''' # This is the high-lever interface for the # orbkit reading routines. # # **Parameters:** # # fname: str, file descriptor # Specifies the filename for the input file. # fname can also be used with a file descriptor instad of a filename. # all_mo : bool, optional # If True, all molecular orbitals are returned. # spin : {None, 'alpha', or 'beta'}, optional # If not None, returns exclusively 'alpha' or 'beta' molecular orbitals. # itype : str, optional # Can be used to manually specify the input filetype. # check_norm : bool, optional # If True, ORBKIT verifies that molecular orbitals are orthonormal. # # **Note:** # # All additional keyword arguments are forwarded to the reading functions. # # **Returns:** # # qc (class QCinfo) with attributes geo_spec, geo_info, ao_spec, mo_spec, etot : # See :ref:`Central Variables` for details. # ''' # # if isinstance(fname, str): # filename = fname # else: # filename = fname.name # # if itype == 'auto': # itype = find_itype(fname) # # display('Loading data from {0} type file {1}\n'.format(itype, filename)) # # qc = readers[itype](fname, all_mo=all_mo, spin=spin, **kwargs) # # if check_norm: # deviation = check_mo_norm(qc) # if deviation >= 1e-5: # raise ValueError('Bad molecular orbital norm: {0:%4e}'.format(deviation)) # # return qc # # Path: orbkit/analytical_integrals.py # def get_ao_overlap(coord_a, coord_b, ao_spec, lxlylz_b=None, # drv=None): # def cartesian2spherical_aoom(ao_overlap_matrix,ao_spec): # def get_mo_overlap(mo_a,mo_b,ao_overlap_matrix): # def initializer(gargs): # def get_slice(x): # def get_mo_overlap_matrix(mo_a,mo_b,ao_overlap_matrix,numproc=1): # def get_moom_atoms(atoms,qc,mo_a,mo_b,ao_overlap_matrix,numproc=1): # def check_mo_norm(qc): # def get_dipole_moment(qc,component=['x','y','z']): # def get_ao_dipole_matrix(qc,component='x'): # def get_nuclear_dipole_moment(qc,component='x'): # def get_atom2mo(qc): # def get_lc(atoms,atom2mo,strict=False): . Output only the next line.
Second Part:
Using the snippet: <|code_start|># -*- coding: iso-8859-1 -*- r''' This file is part of orbkit. See the main program or documentation for information on the license. It shows two examples of how to use orbkit for evaluating analytical integrals. First Part: Compute the electron number analytically using the standard density formula. Second Part: Compute the dipole moments analytically. This expectation value is more complex. As an explanation, consider the following expectation value between two primitive $p_z$ orbitals: .. math:: <|code_end|> , determine the next line of code. You have imports: from orbkit.read import main_read from orbkit.tools import * from orbkit.analytical_integrals import get_ao_overlap,get_mo_overlap,print2D and context (class names, function names, or code) available: # Path: orbkit/read/high_level.py # def main_read(fname, all_mo=False, spin=None, itype='auto', check_norm=False, **kwargs): # ''' # This is the high-lever interface for the # orbkit reading routines. # # **Parameters:** # # fname: str, file descriptor # Specifies the filename for the input file. # fname can also be used with a file descriptor instad of a filename. # all_mo : bool, optional # If True, all molecular orbitals are returned. # spin : {None, 'alpha', or 'beta'}, optional # If not None, returns exclusively 'alpha' or 'beta' molecular orbitals. # itype : str, optional # Can be used to manually specify the input filetype. # check_norm : bool, optional # If True, ORBKIT verifies that molecular orbitals are orthonormal. # # **Note:** # # All additional keyword arguments are forwarded to the reading functions. # # **Returns:** # # qc (class QCinfo) with attributes geo_spec, geo_info, ao_spec, mo_spec, etot : # See :ref:`Central Variables` for details. # ''' # # if isinstance(fname, str): # filename = fname # else: # filename = fname.name # # if itype == 'auto': # itype = find_itype(fname) # # display('Loading data from {0} type file {1}\n'.format(itype, filename)) # # qc = readers[itype](fname, all_mo=all_mo, spin=spin, **kwargs) # # if check_norm: # deviation = check_mo_norm(qc) # if deviation >= 1e-5: # raise ValueError('Bad molecular orbital norm: {0:%4e}'.format(deviation)) # # return qc # # Path: orbkit/analytical_integrals.py # def get_ao_overlap(coord_a, coord_b, ao_spec, lxlylz_b=None, # drv=None): # def cartesian2spherical_aoom(ao_overlap_matrix,ao_spec): # def get_mo_overlap(mo_a,mo_b,ao_overlap_matrix): # def initializer(gargs): # def get_slice(x): # def get_mo_overlap_matrix(mo_a,mo_b,ao_overlap_matrix,numproc=1): # def get_moom_atoms(atoms,qc,mo_a,mo_b,ao_overlap_matrix,numproc=1): # def check_mo_norm(qc): # def get_dipole_moment(qc,component=['x','y','z']): # def get_ao_dipole_matrix(qc,component='x'): # def get_nuclear_dipole_moment(qc,component='x'): # def get_atom2mo(qc): # def get_lc(atoms,atom2mo,strict=False): . Output only the next line.
<\phi_k|z|\phi_l> = \int dxdydz (z - Z_k)^{k_z} e^{\alpha_k r_k^2} (z - Z_l)^{l_z+1} e^{\alpha_l r_l^2}
Here is a snippet: <|code_start|># -*- coding: iso-8859-1 -*- r''' This file is part of orbkit. See the main program or documentation for information on the license. It shows two examples of how to use orbkit for evaluating analytical integrals. <|code_end|> . Write the next line using the current file imports: from orbkit.read import main_read from orbkit.tools import * from orbkit.analytical_integrals import get_ao_overlap,get_mo_overlap,print2D and context from other files: # Path: orbkit/read/high_level.py # def main_read(fname, all_mo=False, spin=None, itype='auto', check_norm=False, **kwargs): # ''' # This is the high-lever interface for the # orbkit reading routines. # # **Parameters:** # # fname: str, file descriptor # Specifies the filename for the input file. # fname can also be used with a file descriptor instad of a filename. # all_mo : bool, optional # If True, all molecular orbitals are returned. # spin : {None, 'alpha', or 'beta'}, optional # If not None, returns exclusively 'alpha' or 'beta' molecular orbitals. # itype : str, optional # Can be used to manually specify the input filetype. # check_norm : bool, optional # If True, ORBKIT verifies that molecular orbitals are orthonormal. # # **Note:** # # All additional keyword arguments are forwarded to the reading functions. # # **Returns:** # # qc (class QCinfo) with attributes geo_spec, geo_info, ao_spec, mo_spec, etot : # See :ref:`Central Variables` for details. # ''' # # if isinstance(fname, str): # filename = fname # else: # filename = fname.name # # if itype == 'auto': # itype = find_itype(fname) # # display('Loading data from {0} type file {1}\n'.format(itype, filename)) # # qc = readers[itype](fname, all_mo=all_mo, spin=spin, **kwargs) # # if check_norm: # deviation = check_mo_norm(qc) # if deviation >= 1e-5: # raise ValueError('Bad molecular orbital norm: {0:%4e}'.format(deviation)) # # return qc # # Path: orbkit/analytical_integrals.py # def get_ao_overlap(coord_a, coord_b, ao_spec, lxlylz_b=None, # drv=None): # def cartesian2spherical_aoom(ao_overlap_matrix,ao_spec): # def get_mo_overlap(mo_a,mo_b,ao_overlap_matrix): # def initializer(gargs): # def get_slice(x): # def get_mo_overlap_matrix(mo_a,mo_b,ao_overlap_matrix,numproc=1): # def get_moom_atoms(atoms,qc,mo_a,mo_b,ao_overlap_matrix,numproc=1): # def check_mo_norm(qc): # def get_dipole_moment(qc,component=['x','y','z']): # def get_ao_dipole_matrix(qc,component='x'): # def get_nuclear_dipole_moment(qc,component='x'): # def get_atom2mo(qc): # def get_lc(atoms,atom2mo,strict=False): , which may include functions, classes, or code. Output only the next line.
First Part:
Based on the snippet: <|code_start|> try: except: # search and load libcint from $PATH libcint = None for dirname in os.environ['PATH'].split(':'): if os.path.isfile(os.path.join(dirname, 'lib', 'libcint.so')): libcint = ctypes.cdll.LoadLibrary(os.path.abspath(os.path.join(dirname, 'lib', 'libcint.so'))) break if libcint is None: raise ImportError("libcint not found: please add to PATH environment variable") class CINTOpt(ctypes.Structure): _fields_ = [ ('index_xyz_array', ctypes.POINTER(ctypes.POINTER(ctypes.c_int))), ('prim_offset', ctypes.POINTER(ctypes.c_int)), ('non0ctr', ctypes.POINTER(ctypes.c_int)), ('non0idx', ctypes.POINTER(ctypes.POINTER(ctypes.c_int))), ('non0coeff', ctypes.POINTER(ctypes.POINTER(ctypes.c_double))), ('expij', ctypes.POINTER(ctypes.POINTER(ctypes.c_double))), <|code_end|> , predict the immediate next line with the help of imports: import numpy import ctypes import time import os from ..tools import lquant from ..display import display from itertools import chain, combinations_with_replacement from numpy import moveaxis from orbkit.tools import moveaxis and context (classes, functions, sometimes code) from other files: # Path: orbkit/tools.py # def read_nist(): # def rm_brackets(text,rm=['(',')','[',']']): # def standard_mass(atom): # def get_atom_symbol(atom): # def l_deg(l=0,ao=None,cartesian_basis=True): # def get_cart2sph(l,m): # def remove_from_list(inlist, value): # def validate_drv(drv): # def each_ao_is_normalized(ao_spec): # def prepare_ao_calc(ao_spec): # def is_mo_spec(mo): # def moveaxis(array, source, target): # def require(data,dtype='f',requirements='CA'): # def convert(data,was_vector,N): # def zeros(shape,name,hdf5_file=None,chunks=True): # def reshape(data,shape,save_hdf5): # def print2D(x,format='%+.2f ',start='\t',end=''): # def pmat(matrix,vmax=lambda x: numpy.max(numpy.abs(x))): # # Path: orbkit/display.py # def display(string): # '''Prints :literal:`string` to the terminal output and to the .oklog file.''' # global log_fid # if not options.quiet: # print(string) # if not options.no_log: # if log_fid is None: # if options.outputname is None or options.outputname == '': # return # else: # log_fid = '%s.oklog' % options.outputname.split('@')[0] # if not is_initiated: # init_display(log_fid) # f = open(log_fid, 'a') # f.write('%s\n' % string) # f.close() . Output only the next line.
('rij', ctypes.POINTER(ctypes.POINTER(ctypes.c_double))),
Predict the next line after this snippet: <|code_start|> try: except ImportError: ao_dict_synonyms = {'atom': 'atom', 'pnum': 'pnum', 'type': 'type', 'coeffs': 'coeffs', 'lxlylz': 'lxlylz', 'exp_list': 'lxlylz', <|code_end|> using the current file's imports: import numpy import sys import warnings import re from os import path from copy import copy from UserList import UserList from collections import UserList from .tools import * from .display import display and any relevant context from other files: # Path: orbkit/display.py # def display(string): # '''Prints :literal:`string` to the terminal output and to the .oklog file.''' # global log_fid # if not options.quiet: # print(string) # if not options.no_log: # if log_fid is None: # if options.outputname is None or options.outputname == '': # return # else: # log_fid = '%s.oklog' % options.outputname.split('@')[0] # if not is_initiated: # init_display(log_fid) # f = open(log_fid, 'a') # f.write('%s\n' % string) # f.close() . Output only the next line.
'lm': 'lm',
Based on the snippet: <|code_start|> def each_ao_is_normalized(ao_spec): is_normalized = [] for sel_ao in range(len(ao_spec)): is_normalized.append((ao_spec[sel_ao]['pnum'] < 0)) if all(is_normalized) != any(is_normalized): raise ValueError('Either all or none of the atomic orbitals have to be normalized!') return all(is_normalized) def prepare_ao_calc(ao_spec): pnum_list = [] atom_indices = [] ao_coeffs = numpy.zeros((0,2)) for sel_ao in range(len(ao_spec)): atom_indices.append(ao_spec[sel_ao]['atom']) c = ao_spec[sel_ao]['coeffs'] ao_coeffs = numpy.append(ao_coeffs,c,axis=0) pnum_list.append(len(c)) pnum_list = require(pnum_list, dtype='i') atom_indices = require(atom_indices, dtype='i') ao_coeffs = require(ao_coeffs, dtype='f') return ao_coeffs,pnum_list,atom_indices def is_mo_spec(mo): '''Checks if :literal:`mo` is of :literal:`mo_spec` type. (See :ref:`Central Variables` for details.)''' #Avoids circular inports: if not isinstance(mo, MOClass): <|code_end|> , predict the immediate next line with the help of imports: import string import numpy import matplotlib.pyplot as plt from os import path from orbkit.units import u_to_me from orbkit.orbitals import MOClass and context (classes, functions, sometimes code) from other files: # Path: orbkit/units.py . Output only the next line.
return False
Based on the snippet: <|code_start|> or the specified mo_set, respectively. ''') parser.add_option_group(group) group = optparse.OptionGroup(parser, "Grid-Related Options") group.add_option("--adjust_grid",dest="adjust_grid", type="float",nargs=2,default=[5,0.5], help=('''create a grid using a spacing of X a_0 and having the size of the molecule plus D a_0 in each direction, e.g., --adjust_grid=D X [default: --adjust_grid=5 0.5]''' ).replace(' ','').replace('\n','')) group.add_option("--grid", dest="grid_file", type="string", help='''read the grid from the plain text file GRID_FILE''') group.add_option("--random_grid", dest="random_grid", default=False, action="store_true", help=optparse.SUPPRESS_HELP) group.add_option("--center", dest="center_grid", metavar="ATOM",type="int", help='''center with respect to the origin and the atom number ATOM (input order)''') group.add_option("-s", "--slice_length",dest="slice_length", default=1e4, type="int", help=('''specify how many grid points are computed at once (per subprocess).''').replace(' ','').replace('\n','')) group.add_option("-v", "--vector",dest="is_vector", default=False, action="store_true", help=('''store the output in a vector format.''') ) parser.add_option_group(group) <|code_end|> , predict the immediate next line with the help of imports: import os import sys import optparse import h5py from copy import deepcopy from orbkit import grid from orbkit.test import test and context (classes, functions, sometimes code) from other files: # Path: orbkit/grid.py # def grid_init(is_vector=False, force=False): # def get_grid(start='\t'): # def tolist(): # def todict(): # def get_shape(): # def set_grid(xnew,ynew,znew,is_vector): # def set_boundaries(is_regular,Nx=None,Ny=None,Nz=None): # def get_bbox(): # def grid2vector(): # def vector2grid(Nx,Ny,Nz): # def matrix_grid2vector(matrix): # def matrix_vector2grid(matrix,Nx=None,Ny=None,Nz=None): # def mv2g(**kwargs): # def grid_sym_op(symop): # def grid_translate(dx,dy,dz): # def rot(ang,axis): # def reflect(plane): # def inversion(): # def sph2cart_vector(r,theta,phi): # def cyl2cart_vector(r,phi,zed): # def random_grid(geo_spec,N=1e6,scale=0.5): # def read(filename, comment='#'): # def check(i, is_vector): # def adjust_to_geo(qc,extend=5.0,step=0.1): # def check_atom_select(atom,geo_info,geo_spec,interactive=True, # display=sys.stdout.write): # def center_grid(ac,display=sys.stdout.write): # def reset_grid(): # N_ = [len(x),len(y),len(z)] # N_ = [Nx,Ny,Nz] # P=[numpy.zeros((3,1)), numpy.reshape(ac,(3,1))] # N_ = [len(grid[0]), len(grid[1]), len(grid[2])] # N_ = [ 101, 101, 101] # N_ = [ 101, 101, 101] #: Specifies the number of grid points (regular grid). . Output only the next line.
group = optparse.OptionGroup(parser, "Additional Options")
Based on the snippet: <|code_start|> tests_home = os.path.dirname(inspect.getfile(inspect.currentframe())) folder = os.path.join(tests_home, '../outputs_for_testing') files = {'fchk': 'gaussian/h2o_rhf_cart.fchk', 'gaussian_log': 'gaussian/h2o_rhf_cart.inp.log', 'gamess': 'gamess/formaldehyde.log', <|code_end|> , predict the immediate next line with the help of imports: from orbkit.read.tools import find_itype import os, inspect and context (classes, functions, sometimes code) from other files: # Path: orbkit/read/tools.py # def find_itype(fname, extension=None): # ''' # This function is used by the high-level read # to determine what reader to use. # Filetypes are determined either by extension or # by looking for magic strings within the files. # # **Parameters:** # # fname: str, file descriptor # Specifies the filename for the input file. # fname can also be used with a file descriptor instad of a filename. # extension: str, optional # If extension is not None it will be used to attempt determining # filetypes by extension in place of fname. # # **Returns:** # # filetype, str # Filetype for the file specified by fname # # filetypes determied from file extension: # - .fchk # - .wfx # - .wfn # - .npz # - .hdf5 / .h5 # # filetypes determined from magic strings: # - Molden # - Gamess US # - Gaussian log # - AOMix # ''' # # #Don't like this was_str stuff... but I don't know what to do # if isinstance(fname, str): # filename = fname # fname = descriptor_from_file(filename, index=0) # was_str = True # else: # filename = fname.name # was_str = False # # if not extension: # extension = filename.split('.')[-1] # if extension.lower() in ['fchk', 'wfx', 'wfn']: # return extension # elif extension.lower() in ['numpy', 'npz', 'hdf5', 'h5']: # return 'native' # # molden_regex = re.compile(r"\[[ ]{,}[Mm]olden[ ]+[Ff]ormat[ ]{,}\]") # gamess_regex = re.compile(r"[Gg][Aa][Mm][Ee][Ss][Ss]") #This might be too weak - Can someone who knows Gamess please check? # gaussian_regex = re.compile(r"[Cc]opyright[,\s\(\)c0-9]+[Gg]aussian\s{,},\s+Inc.") # aomix_regex = re.compile(r"\[[ ]{,}[Aa][Oo][Mm]ix[ ]+[Ff]ormat[ ]{,}\]") # # regexes = {'molden': molden_regex, 'gamess': gamess_regex, 'gaussian_log': gaussian_regex, 'aomix': aomix_regex} # # itypes = ['molden', 'gamess', 'gaussian_log', 'aomix'] # # from io import TextIOWrapper # if isinstance(fname, TextIOWrapper): # text = fname.read() # else: # text = fname.read().decode("iso-8859-1") # fname.seek(0) # # for regname in itypes: # if regexes[regname].search(text): # return regname # # if was_str: # fname.close() # # raise NotImplementedError('File format not reccognized or reader not implemented!') . Output only the next line.
'molden': 'molpro/h2o_rhf_sph.molden',
Given snippet: <|code_start|>from __future__ import division try: except ImportError: class DM: def __init__(self, zero, sing, qc): zero = numpy.array(zero) self.qc = qc self.Tij = numpy.matrix(numpy.zeros((len(self.qc.mo_spec),len(self.qc.mo_spec)))) #build the trace of Tij zero0 = zero[0].flatten() zero1 = zero[1].flatten() <|code_end|> , continue by predicting the next line. Consider current file imports: import numpy, scipy from itertools import product from orbkit.detci import occ_check from UserList import UserList from collections import UserList and context: # Path: orbkit/detci/occ_check.py # def slice_occ(ij): # def compare(cia,cib,moocc=None,numproc=1): which might include code, classes, or functions. Output only the next line.
for imo, it in enumerate(zero1):
Using the snippet: <|code_start|># ################################################################### # FILENAME: test_i18n.py # PROJECT: # DESCRIPTION: Test internationalization support # # # $Id$ # ################################################################### # (C)2015 DigiTar Inc. # Licensed under the MIT License. # ################################################################### class PostalCodeValidatorTests(unittest.TestCase): "Postal code validator tests." def setUp(self): script_path = os.path.dirname(os.path.realpath(__file__)) self.fn_postal_data = "%s/sample_cldr_data/postalCodeData.xml" % script_path self.sample_postal_data = {"GB" : """GIR[ ]?0AA|((AB|AL|B|BA|BB|BD|BH|BL|BN|BR|BS|BT|CA|CB|CF|CH|CM|CO|CR|CT|CV|CW|DA|DD|DE|DG|DH|DL|DN|DT|DY|E|EC|EH|EN|EX|FK|FY|G|GL|GY|GU|HA|HD|HG|HP|HR|HS|HU|HX|IG|IM|IP|IV|JE|KA|KT|KW|KY|L|LA|LD|LE|LL|LN|LS|LU|M|ME|MK|ML|N|NE|NG|NN|NP|NR|NW|OL|OX|PA|PE|PH|PL|PO|PR|RG|RH|RM|S|SA|SE|SG|SK|SL|SM|SN|SO|SP|SR|SS|ST|SW|SY|TA|TD|TF|TN|TQ|TR|TS|TW|UB|W|WA|WC|WD|WF|WN|WR|WS|WV|YO|ZE)(\d[\dA-Z]?[ ]?\d[ABD-HJLN-UW-Z]{2}))|BFPO[ ]?\d{1,4}}""" <|code_end|> , determine the next line of code. You have imports: import os from twisted.trial import unittest from shiji.i18n import postal_code_validator and context (class names, function names, or code) available: # Path: shiji/i18n/postal_code_validator.py # class PostalCodeValidator (object): # class PostalCodeDataFileDNEError(Exception): # class InvalidISO2DCountryCodeError(Exception): # class UnsupportedCountryError(Exception): # def __init__(self, postal_data_path=None): # def supported_countries(self): # def load_country(self, iso_code, pattern): # def valid_postal_code(self, iso_code, postal_code): # def valid_postal_code_global(self, postal_code): # def __init__(self, path): # def __init__(self): # def __init__(self, iso_code): . Output only the next line.
}
Given the following code snippet before the placeholder: <|code_start|>#################################################################### # FILENAME: auth/test_errors.py # PROJECT: Shiji API # DESCRIPTION: Tests auth.errors module. # # Requires: TwistedWeb >= 10.0 # (Python 2.5 & SimpleJSON) or Python 2.6 # # # # $Id$ #################################################################### # (C)2015 DigiTar Inc. # Licensed under the MIT License. #################################################################### class AuthBaseExceptionTestCase(unittest.TestCase): def test_init(self): exc = errors.AuthBaseException("test") self.assertEqual(exc.value, "test") def test_to_str(self): exc = errors.AuthBaseException(123) <|code_end|> , predict the next line using imports from the current file: from twisted.trial import unittest from shiji.auth import errors, base_backend and context including class names, function names, and sometimes code from other files: # Path: shiji/auth/errors.py # class AuthBaseException(Exception): # class AuthBadBackend(AuthBaseException): # class AuthNoBackend(AuthBaseException): # class InvalidAuthentication(AuthBaseException): # class NotAuthorized(AuthBaseException): # class BackendWarmingUp(AuthBaseException): # def __init__(self, value): # def __str__(self): # # Path: shiji/auth/base_backend.py # class AuthBackend(object): # def __init__(self): # def perm_list(self): # def authenticate(self, request): # def cb_finish_authentication(result): . Output only the next line.
self.assertEqual(exc.__str__(), "123")
Predict the next line after this snippet: <|code_start|># # # $Id$ #################################################################### # (C)2015 DigiTar Inc. # Licensed under the MIT License. #################################################################### ARG_ERR = -1 MKDIR_ERR = -2 WRITE_FILE_ERR = -3 TEMPLATE_ERR = -4 re_version_entry = re.compile(r'\s*"(?P<version_id>[.\d]+)"\s*:\s*\(r"(?P<version>[.\d]+)",\s*(?P<version_module>v[_\d]+)\)\s*') curr_dir = os.getcwdu() templates_dir = os.path.dirname(os.path.realpath(__file__)) + "/utility_templates" template_lookup = TemplateLookup(directories=templates_dir, output_encoding="utf-8", input_encoding="utf-8", encoding_errors="replace") def extract_version_map(fn): version_list = [] f_api_init = open(fn, "r") in_versions = False for line in f_api_init.readlines(): if line[:16] == "api_versions = {": <|code_end|> using the current file's imports: import sys, os, re, inspect, json import mako, markdown from optparse import OptionParser from datetime import date from mako.lookup import TemplateLookup from shiji import urldispatch, webapi and any relevant context from other files: # Path: shiji/urldispatch.py # API_VERSION_HEADER = "X-DigiTar-API-Version" # def get_version(request): # def __init__(self, request, url_matches, call_router=None): # def render(self, request): # def cb_deferred_finish(result): # def eb_failed(failure): # def __init__(self, request, api_router): # def render_OPTIONS(self, request): # def render_GET(self, request): # def render_POST(self, request): # def render_GET(self, request): # def render_POST(self, request): # def render_GET(self, request): # def render_POST(self, request): # def render_GET(self, request): # def __init__(self, calls_module, version_router=None, auto_list_versions=False): # def _createRouteMap(self, calls_module): # def getChild(self, name, request): # def __init__(self, version_map, api_router=None): # def getChild(self, name, request): # def get_version_map(self): # def __init__(self, route_map, config={}, cross_origin_domains=None, inhibit_http_caching=True): # def getChild(self, name, request): # def get_route_map(self): # def __init__(self, route_map): # def getChild(self, name, request): # class URLMatchJSONResource(Resource): # class CORSInterrogation(Resource): # class UnknownAPI(Resource): # class UnknownCall(Resource): # class UnknownVersion(Resource): # class ListVersionsCall (URLMatchJSONResource): # class CallRouter(Resource): # class VersionRouter(Resource): # class APIRouter(Resource): # class URLRouter(Resource): # # Path: shiji/webapi.py # ARG_OPTIONAL = True # ARG_REQUIRED = False # def json_arguments(arg_list, content_type="application/json"): # def jsonValidateArgWrap(render_func): # def jsonWrappedFilet(self, request): # def paged_results(default_page=0,default_page_len=50,max_page_len=100): # def pageValidateWrap(render_func): # def wrappedFunction(self, request): # def url_arguments(arg_list, content_type=""): # def urlValidateArgWrap(render_func): # def urlWrappedFilet(self, request): # def auth_http_basic(auth_func, realm="Shiji"): # def authValidateCallerWrap(render_func): # def authWrappedFilet(self, request): # def write_json(request, obj): # def __init__(self, request_object, error_code=None, exception_class=None, exception_text=None): # def obj_err(self): # def json_err(self): # def __str__(self): # def __init__(self, request_object, api_name): # def __init__(self, request_object, api_version): # def __init__(self, request_object, call_name): # def __init__(self, request_object, arg_name, extra_desc): # def __init__(self, request_object): # def __init__(self, request_object, error_msg): # def __init__(self, request_object, name, signature): # def __init__(self, request_object, name): # class APIError(BaseException): # class UnknownAPIError(APIError): # class UnknownAPIVersionError(APIError): # class UnknownAPICallError(APIError): # class JSONEncodeError(APIError): # class JSONDecodeError(APIError): # class RequestNotHashError(APIError): # class AccessDeniedError(APIError): # class ValueError(APIError): # class ContentTypeError(APIError): # class CharsetNotUTF8Error(APIError): # class UnexpectedServerError(APIError): # class InvalidAuthenticationError(APIError): # class InvalidSecureCookieError(APIError): # class ExpiredSecureCookieError(APIError): . Output only the next line.
in_versions = True
Continue the code snippet: <|code_start|> @classmethod def dumps_all(cls): "write all objects of Model class to a JSON-encoded array" return cls.__schema__().dumps(cls.query.all(), many=True).data @classmethod def dumpf_all(cls, file_handle): "write all objects of Model class to file_handle as JSON" file_handle.write(cls.dumps_all()) # load_all @classmethod def load_all(cls, python_objects): "create objects of Model class from an array of python objects" objs = cls.__schema__().load(python_objects, many=True) for obj in objs.data: cls.create(_commit=False, **obj) db.session.commit() db.session.flush() @classmethod def loads_all(cls, buf): "create objects of Model class from a string containing an array of JSON-encoded objects" objs = cls.__schema__().loads(buf, many=True) for obj in objs.data: cls.create(_commit=False, **obj) db.session.commit() db.session.flush() <|code_end|> . Use current file imports: from ..facets.database import db and context (classes, functions, or code) from other files: # Path: flask_diamond/facets/database.py # def init_database(self): . Output only the next line.
@classmethod
Continue the code snippet: <|code_start|> @pytest.mark.parametrize('event_name, event_type, event_data', [ ('low-battery', 'battery', '{"status": "low-charge"}'), ('auto-poweroff', 'battery', '{"status": "automatic-poweroff"}') ]) def test_generate_low_battery_event(event_name, event_type, event_data): if os.path.exists(tracker_events_file): os.remove(tracker_events_file) tracking_events.generate_event(event_name) assert os.path.exists(tracker_events_file) events = [] with open(tracker_events_file, 'r') as events_f: events.append(json.loads(events_f.readline())) assert len(events) == 1 event = events[0] expected_keys = [ 'name', 'language', 'type', <|code_end|> . Use current file imports: import os import json import time import pytest import kano_profile.tracker.tracking_events as tracking_events from kano_profile.paths import tracker_events_file from kano_profile.tracker.tracker_token import TOKEN and context (classes, functions, or code) from other files: # Path: kano_profile/paths.py # TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids') # PAUSED_SESSIONS_FILE = os.path.join(kanoprofile_dir, '.paused_sessions') # # Path: kano_profile/tracker/tracker_token.py # TOKEN = load_token() . Output only the next line.
'timezone_offset',
Predict the next line after this snippet: <|code_start|> events.append(json.loads(events_f.readline())) assert len(events) == 1 event = events[0] expected_keys = [ 'name', 'language', 'type', 'timezone_offset', 'cpu_id', 'os_version', 'token', 'time', 'data' ] for key in expected_keys: assert key in event assert event['name'] == event_type # language: en_GB, assert event['type'] == 'data' # timezone_offset: 3600, # cpu_id: None, # os_version: None, assert event['token'] == TOKEN # Allow some margin for time passing assert abs(time.time() - event['time']) < 5 <|code_end|> using the current file's imports: import os import json import time import pytest import kano_profile.tracker.tracking_events as tracking_events from kano_profile.paths import tracker_events_file from kano_profile.tracker.tracker_token import TOKEN and any relevant context from other files: # Path: kano_profile/paths.py # TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids') # PAUSED_SESSIONS_FILE = os.path.join(kanoprofile_dir, '.paused_sessions') # # Path: kano_profile/tracker/tracker_token.py # TOKEN = load_token() . Output only the next line.
assert event['data'] == json.loads(event_data)
Given snippet: <|code_start|>#!/usr/bin/env python # images.py # # Copyright (C) 2014, 2015 Kano Computing Ltd. # License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2 # # "Badge", folder_name, file_name, width of image def get_image(category, subcategory, name, subfolder_str): # The online badge image files are stored in the home directory. # The function bellow gets the corrects path. if category == 'badges' and subcategory == 'online': return get_online_badge_path(name) folder = os.path.join(image_dir, category, subfolder_str, subcategory) filename = '{name}.png'.format(name=name) fullpath = os.path.join(folder, filename) <|code_end|> , continue by predicting the next line. Consider current file imports: import os from kano.logging import logger from .paths import image_dir from kano_profile.paths import online_badges_dir and context: # Path: kano_profile_gui/paths.py # # Path: kano_profile/paths.py # TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids') # PAUSED_SESSIONS_FILE = os.path.join(kanoprofile_dir, '.paused_sessions') which might include code, classes, or functions. Output only the next line.
if not os.path.exists(fullpath):
Predict the next line for this snippet: <|code_start|> def __repr__(self): return 'Tracking Session [Name: {name}, PID: {pid}]: {is_open}'.format( name=self.name, pid=self.pid, is_open='OPEN' if self.is_open() else 'CLOSED' ) def __str__(self): return self.__repr__() def __eq__(self, other): return self.file == other.file @property def file(self): return self._file @property def path(self): return os.path.join(tracker_dir, self.file) @property def name(self): return self._name.encode('utf-8') @property def pid(self): return self._pid or 0 <|code_end|> with the help of current file imports: import os import re import json from kano.logging import logger from kano_profile.paths import tracker_dir from kano_profile.tracker.tracking_utils import is_pid_running, open_locked and context from other files: # Path: kano_profile/paths.py # TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids') # PAUSED_SESSIONS_FILE = os.path.join(kanoprofile_dir, '.paused_sessions') # # Path: kano_profile/tracker/tracking_utils.py # def is_pid_running(pid): # ''' # Sending a signal 0 to a running process will do nothing. Sending it to a # dead process will throw an OSError exception # ''' # # try: # os.kill(pid, 0) # except OSError: # return False # else: # return True # # class open_locked(file): # """ A version of open with an exclusive lock to be used within # controlled execution statements. # """ # def __init__(self, *args, **kwargs): # super(open_locked, self).__init__(*args, **kwargs) # fcntl.flock(self, fcntl.LOCK_EX) , which may contain function names, class names, or code. Output only the next line.
def is_open(self):
Predict the next line for this snippet: <|code_start|> @property def name(self): return self._name.encode('utf-8') @property def pid(self): return self._pid or 0 def is_open(self): return is_pid_running(self.pid) def open(self, mode): try: session_f = open_locked(self.path, mode) except IOError as exc: logger.error( 'Error opening the tracking session file "{f}": {err}' .format(f=self.path, err=exc) ) else: yield session_f def dumps(self): return json.dumps({ 'name': self.name, 'pid': self.pid }) @staticmethod def loads(session): <|code_end|> with the help of current file imports: import os import re import json from kano.logging import logger from kano_profile.paths import tracker_dir from kano_profile.tracker.tracking_utils import is_pid_running, open_locked and context from other files: # Path: kano_profile/paths.py # TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids') # PAUSED_SESSIONS_FILE = os.path.join(kanoprofile_dir, '.paused_sessions') # # Path: kano_profile/tracker/tracking_utils.py # def is_pid_running(pid): # ''' # Sending a signal 0 to a running process will do nothing. Sending it to a # dead process will throw an OSError exception # ''' # # try: # os.kill(pid, 0) # except OSError: # return False # else: # return True # # class open_locked(file): # """ A version of open with an exclusive lock to be used within # controlled execution statements. # """ # def __init__(self, *args, **kwargs): # super(open_locked, self).__init__(*args, **kwargs) # fcntl.flock(self, fcntl.LOCK_EX) , which may contain function names, class names, or code. Output only the next line.
session_data = json.loads(session.rstrip().lstrip())
Given snippet: <|code_start|># # tracking_session.py # # Copyright (C) 2017 Kano Computing Ltd. # License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2 # # A class to manage tracking session files # class TrackingSession(object): SESSION_FILE_RE = re.compile(r'^(\d+)-(.*).json$') def __init__(self, session_file=None, name=None, pid=None): if session_file: self._file = os.path.basename(session_file) self._pid, self._name = self.parse_session_file(self.file) elif name and pid: self._name = name self._pid = int(pid) self._file = self.parse_name_and_pid(self.name, self.pid) else: raise TypeError( <|code_end|> , continue by predicting the next line. Consider current file imports: import os import re import json from kano.logging import logger from kano_profile.paths import tracker_dir from kano_profile.tracker.tracking_utils import is_pid_running, open_locked and context: # Path: kano_profile/paths.py # TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids') # PAUSED_SESSIONS_FILE = os.path.join(kanoprofile_dir, '.paused_sessions') # # Path: kano_profile/tracker/tracking_utils.py # def is_pid_running(pid): # ''' # Sending a signal 0 to a running process will do nothing. Sending it to a # dead process will throw an OSError exception # ''' # # try: # os.kill(pid, 0) # except OSError: # return False # else: # return True # # class open_locked(file): # """ A version of open with an exclusive lock to be used within # controlled execution statements. # """ # def __init__(self, *args, **kwargs): # super(open_locked, self).__init__(*args, **kwargs) # fcntl.flock(self, fcntl.LOCK_EX) which might include code, classes, or functions. Output only the next line.
'TrackingSession requires a file or a name/pid combination'
Next line prediction: <|code_start|># GetData.py # # Copyright (C) 2015-2019 Kano Computing Ltd. # License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2 # # This contains the RegistrationScreen form component with all the widgets def is_email(email): if '@' in parseaddr(email)[1]: return True <|code_end|> . Use current file imports: (import os import re from email.utils import parseaddr from gi.repository import GObject, Gtk from kano.gtk3.kano_dialog import KanoDialog from kano.logging import logger from kano_profile.paths import legal_dir from kano_registration_gui.LabelledEntry import LabelledEntry from kano_registration_gui.TermsAndConditions import TermsAndConditions from kano_registration_gui.cache_functions import cache_data, cache_emails, \ get_cached_data) and context including class names, function names, or small code snippets from other files: # Path: kano_profile/paths.py # TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids') # PAUSED_SESSIONS_FILE = os.path.join(kanoprofile_dir, '.paused_sessions') # # Path: kano_registration_gui/LabelledEntry.py # class LabelledEntry(Gtk.Box): # '''Produces a labelled entry, suitable for the registration screens # ''' # __gsignals__ = { # 'labelled-entry-key-release': (GObject.SIGNAL_RUN_FIRST, None, ()) # } # # def __init__(self, text, entry_contents=None): # # Gtk.Box.__init__(self, orientation=Gtk.Orientation.VERTICAL) # # # This is for the two labels above the entry # # One is information about the entry information # # The other is about whether the information is valid # label_hbox = Gtk.Box() # self._title_label = Gtk.Label(text, xalign=0) # self._title_label.get_style_context().add_class('get_data_label') # # self._validated = False # # self._validation_label = Gtk.Label() # self._validation_label.get_style_context().add_class('validation_label') # label_hbox.pack_start(self._title_label, False, False, 0) # label_hbox.pack_start(self._validation_label, False, False, 0) # self.pack_start(label_hbox, False, False, 0) # # self._entry = ValidationEntry() # self._entry.get_style_context().add_class('get_data_entry') # self._entry.set_size_request(250, -1) # # if entry_contents: # self._entry.set_text(entry_contents) # # self.pack_start(self._entry, False, False, 0) # self._entry.connect('key-release-event', self.emit_signal) # # self.set_margin_right(30) # self.set_margin_left(30) # # @property # def validated(self): # '''How we find out whether the entry is validated # ''' # return self._validated # # # This is a public function # def label_success(self, text="", successful=None): # '''successful is "success", "fail" or None # If success, turn validation label green # Fail turns it red # Otherwise, don't show it. # ''' # self._validation_label.get_style_context().remove_class('fail') # self._validation_label.get_style_context().remove_class('success') # # # Change the image - if successful is nothing, then icon # # is removed # self.set_image(successful) # # # If successful is not nothing, set the class appropriately # if successful: # self._validation_label.get_style_context().add_class(successful) # self._validation_label.set_text(text) # self._validated = (successful == 'success') # # self._validation_label.show_all() # # def set_image(self, name): # self._entry.set_image(name) # # def set_visibility(self, value): # return self._entry.set_visibility(value) # # def set_placeholder_text(self, text): # self._entry.set_placeholder_text(text) # # def get_text(self): # return self._entry.get_text() # # def set_text(self, text): # self._entry.set_text(text) # # def emit_signal(self, widget, event): # self.emit('labelled-entry-key-release') # # def get_label_text(self): # return self._label.get_text() # # Path: kano_registration_gui/TermsAndConditions.py # class TermsAndConditions(Gtk.Box): # __gsignals__ = { # 't-and-cs-clicked': (GObject.SIGNAL_RUN_FIRST, None, ()) # } # # def __init__(self): # Gtk.Box.__init__(self) # # self.checkbutton = Gtk.CheckButton() # self.checkbutton.get_style_context().add_class('get_data_checkbutton') # self.checkbutton.set_margin_left(30) # # self.tc_button = OrangeButton(_("I agree to the terms and conditions")) # self.tc_button.connect('clicked', self._emit_t_and_c_signal) # # self.pack_start(self.checkbutton, False, False, 0) # self.pack_start(self.tc_button, False, False, 0) # # def is_checked(self): # return self.checkbutton.get_active() # # def _emit_t_and_c_signal(self, widget): # self.emit('t-and-cs-clicked') # # def disable_all(self): # self.checkbutton.set_sensitive(False) # self.tc_button.set_sensitive(False) # # def enable_all(self): # self.checkbutton.set_sensitive(True) # self.tc_button.set_sensitive(True) # # Path: kano_registration_gui/cache_functions.py # def cache_data(category, value): # if category in ['username', 'email']: # save_app_state_variable('kano-avatar-registration', category, value) # # def cache_emails(email): # cache_data('email', email) # # def get_cached_data(category): # return load_app_state_variable('kano-avatar-registration', category) . Output only the next line.
else:
Based on the snippet: <|code_start|># GetData.py # # Copyright (C) 2015-2019 Kano Computing Ltd. # License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2 # # This contains the RegistrationScreen form component with all the widgets def is_email(email): if '@' in parseaddr(email)[1]: return True <|code_end|> , predict the immediate next line with the help of imports: import os import re from email.utils import parseaddr from gi.repository import GObject, Gtk from kano.gtk3.kano_dialog import KanoDialog from kano.logging import logger from kano_profile.paths import legal_dir from kano_registration_gui.LabelledEntry import LabelledEntry from kano_registration_gui.TermsAndConditions import TermsAndConditions from kano_registration_gui.cache_functions import cache_data, cache_emails, \ get_cached_data and context (classes, functions, sometimes code) from other files: # Path: kano_profile/paths.py # TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids') # PAUSED_SESSIONS_FILE = os.path.join(kanoprofile_dir, '.paused_sessions') # # Path: kano_registration_gui/LabelledEntry.py # class LabelledEntry(Gtk.Box): # '''Produces a labelled entry, suitable for the registration screens # ''' # __gsignals__ = { # 'labelled-entry-key-release': (GObject.SIGNAL_RUN_FIRST, None, ()) # } # # def __init__(self, text, entry_contents=None): # # Gtk.Box.__init__(self, orientation=Gtk.Orientation.VERTICAL) # # # This is for the two labels above the entry # # One is information about the entry information # # The other is about whether the information is valid # label_hbox = Gtk.Box() # self._title_label = Gtk.Label(text, xalign=0) # self._title_label.get_style_context().add_class('get_data_label') # # self._validated = False # # self._validation_label = Gtk.Label() # self._validation_label.get_style_context().add_class('validation_label') # label_hbox.pack_start(self._title_label, False, False, 0) # label_hbox.pack_start(self._validation_label, False, False, 0) # self.pack_start(label_hbox, False, False, 0) # # self._entry = ValidationEntry() # self._entry.get_style_context().add_class('get_data_entry') # self._entry.set_size_request(250, -1) # # if entry_contents: # self._entry.set_text(entry_contents) # # self.pack_start(self._entry, False, False, 0) # self._entry.connect('key-release-event', self.emit_signal) # # self.set_margin_right(30) # self.set_margin_left(30) # # @property # def validated(self): # '''How we find out whether the entry is validated # ''' # return self._validated # # # This is a public function # def label_success(self, text="", successful=None): # '''successful is "success", "fail" or None # If success, turn validation label green # Fail turns it red # Otherwise, don't show it. # ''' # self._validation_label.get_style_context().remove_class('fail') # self._validation_label.get_style_context().remove_class('success') # # # Change the image - if successful is nothing, then icon # # is removed # self.set_image(successful) # # # If successful is not nothing, set the class appropriately # if successful: # self._validation_label.get_style_context().add_class(successful) # self._validation_label.set_text(text) # self._validated = (successful == 'success') # # self._validation_label.show_all() # # def set_image(self, name): # self._entry.set_image(name) # # def set_visibility(self, value): # return self._entry.set_visibility(value) # # def set_placeholder_text(self, text): # self._entry.set_placeholder_text(text) # # def get_text(self): # return self._entry.get_text() # # def set_text(self, text): # self._entry.set_text(text) # # def emit_signal(self, widget, event): # self.emit('labelled-entry-key-release') # # def get_label_text(self): # return self._label.get_text() # # Path: kano_registration_gui/TermsAndConditions.py # class TermsAndConditions(Gtk.Box): # __gsignals__ = { # 't-and-cs-clicked': (GObject.SIGNAL_RUN_FIRST, None, ()) # } # # def __init__(self): # Gtk.Box.__init__(self) # # self.checkbutton = Gtk.CheckButton() # self.checkbutton.get_style_context().add_class('get_data_checkbutton') # self.checkbutton.set_margin_left(30) # # self.tc_button = OrangeButton(_("I agree to the terms and conditions")) # self.tc_button.connect('clicked', self._emit_t_and_c_signal) # # self.pack_start(self.checkbutton, False, False, 0) # self.pack_start(self.tc_button, False, False, 0) # # def is_checked(self): # return self.checkbutton.get_active() # # def _emit_t_and_c_signal(self, widget): # self.emit('t-and-cs-clicked') # # def disable_all(self): # self.checkbutton.set_sensitive(False) # self.tc_button.set_sensitive(False) # # def enable_all(self): # self.checkbutton.set_sensitive(True) # self.tc_button.set_sensitive(True) # # Path: kano_registration_gui/cache_functions.py # def cache_data(category, value): # if category in ['username', 'email']: # save_app_state_variable('kano-avatar-registration', category, value) # # def cache_emails(email): # cache_data('email', email) # # def get_cached_data(category): # return load_app_state_variable('kano-avatar-registration', category) . Output only the next line.
else:
Next line prediction: <|code_start|># GetData.py # # Copyright (C) 2015-2019 Kano Computing Ltd. # License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2 # # This contains the RegistrationScreen form component with all the widgets def is_email(email): if '@' in parseaddr(email)[1]: return True else: <|code_end|> . Use current file imports: (import os import re from email.utils import parseaddr from gi.repository import GObject, Gtk from kano.gtk3.kano_dialog import KanoDialog from kano.logging import logger from kano_profile.paths import legal_dir from kano_registration_gui.LabelledEntry import LabelledEntry from kano_registration_gui.TermsAndConditions import TermsAndConditions from kano_registration_gui.cache_functions import cache_data, cache_emails, \ get_cached_data) and context including class names, function names, or small code snippets from other files: # Path: kano_profile/paths.py # TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids') # PAUSED_SESSIONS_FILE = os.path.join(kanoprofile_dir, '.paused_sessions') # # Path: kano_registration_gui/LabelledEntry.py # class LabelledEntry(Gtk.Box): # '''Produces a labelled entry, suitable for the registration screens # ''' # __gsignals__ = { # 'labelled-entry-key-release': (GObject.SIGNAL_RUN_FIRST, None, ()) # } # # def __init__(self, text, entry_contents=None): # # Gtk.Box.__init__(self, orientation=Gtk.Orientation.VERTICAL) # # # This is for the two labels above the entry # # One is information about the entry information # # The other is about whether the information is valid # label_hbox = Gtk.Box() # self._title_label = Gtk.Label(text, xalign=0) # self._title_label.get_style_context().add_class('get_data_label') # # self._validated = False # # self._validation_label = Gtk.Label() # self._validation_label.get_style_context().add_class('validation_label') # label_hbox.pack_start(self._title_label, False, False, 0) # label_hbox.pack_start(self._validation_label, False, False, 0) # self.pack_start(label_hbox, False, False, 0) # # self._entry = ValidationEntry() # self._entry.get_style_context().add_class('get_data_entry') # self._entry.set_size_request(250, -1) # # if entry_contents: # self._entry.set_text(entry_contents) # # self.pack_start(self._entry, False, False, 0) # self._entry.connect('key-release-event', self.emit_signal) # # self.set_margin_right(30) # self.set_margin_left(30) # # @property # def validated(self): # '''How we find out whether the entry is validated # ''' # return self._validated # # # This is a public function # def label_success(self, text="", successful=None): # '''successful is "success", "fail" or None # If success, turn validation label green # Fail turns it red # Otherwise, don't show it. # ''' # self._validation_label.get_style_context().remove_class('fail') # self._validation_label.get_style_context().remove_class('success') # # # Change the image - if successful is nothing, then icon # # is removed # self.set_image(successful) # # # If successful is not nothing, set the class appropriately # if successful: # self._validation_label.get_style_context().add_class(successful) # self._validation_label.set_text(text) # self._validated = (successful == 'success') # # self._validation_label.show_all() # # def set_image(self, name): # self._entry.set_image(name) # # def set_visibility(self, value): # return self._entry.set_visibility(value) # # def set_placeholder_text(self, text): # self._entry.set_placeholder_text(text) # # def get_text(self): # return self._entry.get_text() # # def set_text(self, text): # self._entry.set_text(text) # # def emit_signal(self, widget, event): # self.emit('labelled-entry-key-release') # # def get_label_text(self): # return self._label.get_text() # # Path: kano_registration_gui/TermsAndConditions.py # class TermsAndConditions(Gtk.Box): # __gsignals__ = { # 't-and-cs-clicked': (GObject.SIGNAL_RUN_FIRST, None, ()) # } # # def __init__(self): # Gtk.Box.__init__(self) # # self.checkbutton = Gtk.CheckButton() # self.checkbutton.get_style_context().add_class('get_data_checkbutton') # self.checkbutton.set_margin_left(30) # # self.tc_button = OrangeButton(_("I agree to the terms and conditions")) # self.tc_button.connect('clicked', self._emit_t_and_c_signal) # # self.pack_start(self.checkbutton, False, False, 0) # self.pack_start(self.tc_button, False, False, 0) # # def is_checked(self): # return self.checkbutton.get_active() # # def _emit_t_and_c_signal(self, widget): # self.emit('t-and-cs-clicked') # # def disable_all(self): # self.checkbutton.set_sensitive(False) # self.tc_button.set_sensitive(False) # # def enable_all(self): # self.checkbutton.set_sensitive(True) # self.tc_button.set_sensitive(True) # # Path: kano_registration_gui/cache_functions.py # def cache_data(category, value): # if category in ['username', 'email']: # save_app_state_variable('kano-avatar-registration', category, value) # # def cache_emails(email): # cache_data('email', email) # # def get_cached_data(category): # return load_app_state_variable('kano-avatar-registration', category) . Output only the next line.
return False
Here is a snippet: <|code_start|>#!/usr/bin/env python # activate_account.py # # Copyright (C) 2014, 2015 Kano Computing Ltd. # License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2 # # # TODO: Remove this statement after upgrading to a friendly Python-requests match requests.packages.urllib3.disable_warnings() if __name__ == '__main__' and __package__ is None: dir_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) if dir_path != '/usr': sys.path.insert(1, dir_path) if len(sys.argv) != 2: sys.exit("Wrong usage, needs to supply code") <|code_end|> . Write the next line using the current file imports: import sys import os import requests from kano_world.connection import api_url and context from other files: # Path: kano_world/connection.py # def _remove_sensitive_data(request_debug): # def request_wrapper(method, endpoint, data=None, headers=None, # session=None, files=None, params=None): , which may include functions, classes, or code. Output only the next line.
else:
Given the code snippet: <|code_start|> def request_wrapper(method, endpoint, data=None, headers=None, session=None, files=None, params=None): if method not in ['put', 'get', 'post', 'delete']: return False, "Wrong method name!", None if session: req_object = session else: req_object = requests method = getattr(req_object, method) request_debug = { 'url': API_URL + endpoint, 'data': data, 'headers': headers, 'files': files, 'params': params, 'proxies': proxies, } # Provide 2 separate timeouts - for CONNECT and READ, to requests library connect_timeout = 5 read_timeout = 20 try: r = method( API_URL + endpoint, data=data, headers=headers, files=files, params=params, proxies=proxies, <|code_end|> , generate the next line using the imports in this file: import requests import ast from kano.logging import logger from kano_world.config import API_URL from pprint import pformat from kano_settings.system.proxy import get_requests_proxies and context (functions, classes, or occasionally code) from other files: # Path: kano_world/config.py # API_URL = CONF['api_url'] . Output only the next line.
timeout=(connect_timeout, read_timeout)
Given the code snippet: <|code_start|># # PopUpItemMenu.py # # Copyright (C) 2015 - 2018 Kano Computing Ltd. # License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2 # require_version('Gtk', '3.0') # Having to include the translatable strings here for the time being # as they are buried in the conf.json file. CATEGORIES = [ N_("Faces"), N_("Skins"), N_("Belts"), N_("Hair"), N_("Suits"), N_("Stickers"), N_("Accessories"), N_("Hats"), N_("Scarves"), N_("Headwear"), ] <|code_end|> , generate the next line using the imports in this file: from gi import require_version from gi.repository import Gtk, GObject from kano_avatar_gui.SelectMenu import SelectMenu from kano.logging import logger from kano.gtk3.cursor import attach_cursor_events from kano.gtk3.scrolled_window import ScrolledWindow and context (functions, classes, or occasionally code) from other files: # Path: kano_avatar_gui/SelectMenu.py # class SelectMenu(Gtk.EventBox): # def __init__(self, list_of_names, signal_name): # # Gtk.EventBox.__init__(self) # apply_styling_to_screen(CSS_PATH) # # # Initialise self._items # self._set_items(list_of_names) # # self._signal_name = signal_name # # # This is the selected_identifier # self._selected = None # self.get_style_context().add_class('select_menu') # # def _set_items(self, list_of_names): # self._items = {} # # for name in list_of_names: # self._items[name] = {} # self._items[name]['selected'] = False # # def set_selected(self, identifier): # '''Sets the selected element in the dictionary to True, # and sets all the others to False # ''' # # self._selected = identifier # # def get_selected(self): # '''Gets the name of the current selected image # ''' # # return self._selected # # def _unselect_all(self): # '''Remove all styling on all images, and sets the 'selected' # field to False # ''' # self._selected = None # # def _add_option_to_items(self, identifier, name, item): # '''Adds a new option in the self._items # ''' # if identifier in self._items: # self._items[identifier][name] = item # # def _remove_option_from_items(self, identifier, name): # if identifier in self._items: # self._items[identifier].pop(name, None) # # def get_option(self, identifier, option): # if identifier in self._items: # if option in self._items[identifier]: # return self._items[identifier][option] # # return None # # def set_button(self, identifier, button): # if identifier in self._items: # self._items[identifier]['button'] = button # else: # logger.error( # "Trying to set a button for an identifier that is not present") # # def unset_button(self, identifier): # self._remove_option_from_items(identifier, 'button') # # def get_button(self, identifier): # if identifier in self._items: # if 'button' in self._items[identifier]: # return self._items[identifier]['button'] # # logger.error( # "Trying to get a button for an identifier that is not present") # return None # # def _add_selected_css(self, button): # style = button.get_style_context() # style.add_class('selected') # # def _remove_selected_css(self, button): # style = button.get_style_context() # style.remove_class('selected') # # def _add_selected_image(self, button, identifier): # '''Pack the selected image into the button # ''' # if 'active_path' in self._items[identifier]: # path = self._items[identifier]['active_path'] # image = Gtk.Image.new_from_file(path) # button.set_image(image) # # def _remove_selected_image(self, button, identifier): # '''Pack the grey unselected image into the button # ''' # if 'inactive_path' in self._items[identifier]: # path = self._items[identifier]['inactive_path'] # image = Gtk.Image.new_from_file(path) # button.set_image(image) . Output only the next line.
SPECIAL_CATEGORIES = [
Given snippet: <|code_start|># ValidationEntry.py # # Copyright (C) 2015 Kano Computing Ltd. # License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2 # if __name__ == '__main__' and __package__ is None: dir_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) if dir_path != '/usr': sys.path.insert(1, dir_path) print sys.path class ValidationEntry(Gtk.Entry): def __init__(self): Gtk.Entry.__init__(self) def set_image(self, name=""): if name == 'success': filename = os.path.join(media_dir, "images/icons/success.png") elif name == 'fail': filename = os.path.join(media_dir, "images/icons/error.png") else: # if name not correct, leave it blank filename = None <|code_end|> , continue by predicting the next line. Consider current file imports: import os import sys from gi.repository import Gtk, GdkPixbuf from kano_profile_gui.paths import media_dir and context: # Path: kano_profile_gui/paths.py which might include code, classes, or functions. Output only the next line.
if filename:
Given the code snippet: <|code_start|># tracking_uuids.py # # Copyright (C) 2018 Kano Computing Ltd. # License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2 # # Functions for creating namespaced UUIDs for apps. SECOND = 1 MINUTE = 60 * SECOND HOUR = 60 * MINUTE DAY = 24 * HOUR <|code_end|> , generate the next line using the imports in this file: import os import time import json from uuid import uuid1, uuid5 from kano.utils.file_operations import chown_path, touch from kano.logging import logger from kano_profile.tracker.tracking_utils import open_locked from kano_profile.paths import TRACKER_UUIDS_PATH and context (functions, classes, or occasionally code) from other files: # Path: kano_profile/tracker/tracking_utils.py # class open_locked(file): # """ A version of open with an exclusive lock to be used within # controlled execution statements. # """ # def __init__(self, *args, **kwargs): # super(open_locked, self).__init__(*args, **kwargs) # fcntl.flock(self, fcntl.LOCK_EX) # # Path: kano_profile/paths.py # TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids') . Output only the next line.
def get_tracking_uuid(key, expires=3 * DAY):
Predict the next line after this snippet: <|code_start|> self.get_style_context().add_class('menu_bar_container') self.height = 110 self.width = win_width self.set_size_request(self.width, self.height) self._quests = quests hbox = Gtk.Box() self.add(hbox) self.buttons = {} self.selected = None # Home button self.home_button = HomeButton() self.home_button.connect('clicked', self.emit_home_signal) self.home_button.connect('clicked', self.set_selected_wrapper, _("CHARACTER")) hbox.pack_start(self.home_button, False, False, 0) close_button = self._create_cross_button() hbox.pack_end(close_button, False, False, 0) close_button.connect('clicked', self.close_window) name_array = [ MenuBar.BADGES_STR, MenuBar.CHARACTER_STR ] # TODO: add MenuBar.QUESTS_STR to enable for name in name_array: button = MenuButton(_(name), self._quests) <|code_end|> using the current file's imports: import os from gi.repository import Gtk, GObject from kano.gtk3.cursor import attach_cursor_events from kano_world.functions import get_mixed_username from kano_profile.badges import calculate_kano_level from kano_profile_gui.components.icons import get_ui_icon and any relevant context from other files: # Path: kano_world/functions.py # def get_mixed_username(): # if is_registered(): # import mercury # Lazy import to avoid dynamically linking with global import # kw = mercury.KanoWorld(kw_url) # username = kw.get_username() # else: # username = get_user_unsudoed() # return username # # Path: kano_profile/badges.py # def calculate_kano_level(): # ''' # Calculates the current level of the user # Returns: level, percentage and current xp # ''' # level_rules = read_json(levels_file) # if not level_rules: # return -1, 0, 0 # # max_level = max([int(n) for n in level_rules.keys()]) # xp_now = calculate_xp() # # for level in xrange(1, max_level + 1): # level_min = level_rules[str(level)] # # if level != max_level: # level_max = level_rules[str(level + 1)] - 1 # else: # level_max = float('inf') # # if level_min <= xp_now <= level_max: # reached_level = level # reached_percentage = (xp_now - level_min) / (level_max + 1 - level_min) # # return int(reached_level), reached_percentage, xp_now # # Path: kano_profile_gui/components/icons.py # def get_ui_icon(name): # if name == 'green_arrow': # icon_number = 0 # elif name == 'pale_right_arrow': # icon_number = 1 # elif name == 'dark_left_arrow': # icon_number = 2 # elif name == 'dark_right_arrow': # icon_number = 3 # elif name == 'pale_left_arrow': # icon_number = 4 # elif name == 'tick': # icon_number = 5 # elif name == 'cross': # icon_number = 6 # elif name == 'dropdown_arrow': # icon_number = 7 # else: # raise Exception('Unknown icon name ' + name) # # src_loc = os.path.join(media_dir, 'images/icons/systemsetup-icons.png') # pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(src_loc, 192, 24) # # subpixbuf = pixbuf.new_subpixbuf(24 * icon_number, 0, 24, 24) # buf = subpixbuf.add_alpha(True, 255, 255, 255) # # icon = Gtk.Image() # icon.set_from_pixbuf(buf) # return icon . Output only the next line.
button.connect('clicked', self.emit_menu_signal, name)
Using the snippet: <|code_start|> MenuBar.BADGES_STR, MenuBar.CHARACTER_STR ] # TODO: add MenuBar.QUESTS_STR to enable for name in name_array: button = MenuButton(_(name), self._quests) button.connect('clicked', self.emit_menu_signal, name) button.connect('clicked', self.set_selected_wrapper, name) hbox.pack_end(button, False, False, 0) # add to the self.buttons dictionary self.buttons[name] = {} self.buttons[name]['button'] = button if name == MenuBar.QUESTS_STR: # check the notification image button.check_for_notification() # HACKY: avoiding packing the label divider after the last element if name != MenuBar.CHARACTER_STR: label = self._create_divider_label() hbox.pack_end(label, False, False, 0) attach_cursor_events(button) # initialise with the CHARACTER button selected self.set_selected(self.CHARACTER_STR) def _create_divider_label(self): label = Gtk.Label("|") label.get_style_context().add_class('button_divider') <|code_end|> , determine the next line of code. You have imports: import os from gi.repository import Gtk, GObject from kano.gtk3.cursor import attach_cursor_events from kano_world.functions import get_mixed_username from kano_profile.badges import calculate_kano_level from kano_profile_gui.components.icons import get_ui_icon and context (class names, function names, or code) available: # Path: kano_world/functions.py # def get_mixed_username(): # if is_registered(): # import mercury # Lazy import to avoid dynamically linking with global import # kw = mercury.KanoWorld(kw_url) # username = kw.get_username() # else: # username = get_user_unsudoed() # return username # # Path: kano_profile/badges.py # def calculate_kano_level(): # ''' # Calculates the current level of the user # Returns: level, percentage and current xp # ''' # level_rules = read_json(levels_file) # if not level_rules: # return -1, 0, 0 # # max_level = max([int(n) for n in level_rules.keys()]) # xp_now = calculate_xp() # # for level in xrange(1, max_level + 1): # level_min = level_rules[str(level)] # # if level != max_level: # level_max = level_rules[str(level + 1)] - 1 # else: # level_max = float('inf') # # if level_min <= xp_now <= level_max: # reached_level = level # reached_percentage = (xp_now - level_min) / (level_max + 1 - level_min) # # return int(reached_level), reached_percentage, xp_now # # Path: kano_profile_gui/components/icons.py # def get_ui_icon(name): # if name == 'green_arrow': # icon_number = 0 # elif name == 'pale_right_arrow': # icon_number = 1 # elif name == 'dark_left_arrow': # icon_number = 2 # elif name == 'dark_right_arrow': # icon_number = 3 # elif name == 'pale_left_arrow': # icon_number = 4 # elif name == 'tick': # icon_number = 5 # elif name == 'cross': # icon_number = 6 # elif name == 'dropdown_arrow': # icon_number = 7 # else: # raise Exception('Unknown icon name ' + name) # # src_loc = os.path.join(media_dir, 'images/icons/systemsetup-icons.png') # pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(src_loc, 192, 24) # # subpixbuf = pixbuf.new_subpixbuf(24 * icon_number, 0, 24, 24) # buf = subpixbuf.add_alpha(True, 255, 255, 255) # # icon = Gtk.Image() # icon.set_from_pixbuf(buf) # return icon . Output only the next line.
return label
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python # MenuBar.py # # Copyright (C) 2014, 2015 Kano Computing Ltd. # License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2 # # This controls the styling of the (pretend) top window bar. # -*- coding: utf-8 -*- # In case we change the colour of the menu bar, we have a background # across all of them. class MenuBar(Gtk.EventBox): __gsignals__ = { 'home-button-clicked': (GObject.SIGNAL_RUN_FIRST, None, (str,)), 'menu-button-clicked': (GObject.SIGNAL_RUN_FIRST, None, (str,)) <|code_end|> , predict the next line using imports from the current file: import os from gi.repository import Gtk, GObject from kano.gtk3.cursor import attach_cursor_events from kano_world.functions import get_mixed_username from kano_profile.badges import calculate_kano_level from kano_profile_gui.components.icons import get_ui_icon and context including class names, function names, and sometimes code from other files: # Path: kano_world/functions.py # def get_mixed_username(): # if is_registered(): # import mercury # Lazy import to avoid dynamically linking with global import # kw = mercury.KanoWorld(kw_url) # username = kw.get_username() # else: # username = get_user_unsudoed() # return username # # Path: kano_profile/badges.py # def calculate_kano_level(): # ''' # Calculates the current level of the user # Returns: level, percentage and current xp # ''' # level_rules = read_json(levels_file) # if not level_rules: # return -1, 0, 0 # # max_level = max([int(n) for n in level_rules.keys()]) # xp_now = calculate_xp() # # for level in xrange(1, max_level + 1): # level_min = level_rules[str(level)] # # if level != max_level: # level_max = level_rules[str(level + 1)] - 1 # else: # level_max = float('inf') # # if level_min <= xp_now <= level_max: # reached_level = level # reached_percentage = (xp_now - level_min) / (level_max + 1 - level_min) # # return int(reached_level), reached_percentage, xp_now # # Path: kano_profile_gui/components/icons.py # def get_ui_icon(name): # if name == 'green_arrow': # icon_number = 0 # elif name == 'pale_right_arrow': # icon_number = 1 # elif name == 'dark_left_arrow': # icon_number = 2 # elif name == 'dark_right_arrow': # icon_number = 3 # elif name == 'pale_left_arrow': # icon_number = 4 # elif name == 'tick': # icon_number = 5 # elif name == 'cross': # icon_number = 6 # elif name == 'dropdown_arrow': # icon_number = 7 # else: # raise Exception('Unknown icon name ' + name) # # src_loc = os.path.join(media_dir, 'images/icons/systemsetup-icons.png') # pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(src_loc, 192, 24) # # subpixbuf = pixbuf.new_subpixbuf(24 * icon_number, 0, 24, 24) # buf = subpixbuf.add_alpha(True, 255, 255, 255) # # icon = Gtk.Image() # icon.set_from_pixbuf(buf) # return icon . Output only the next line.
}
Based on the snippet: <|code_start|>#!/usr/bin/env python # image_.py # # Copyright (C) 2014, 2015 Kano Computing Ltd. # License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2 # # This controls the size and styling of the pictures displayed on the table # Used for badges, environments and avatar screen def create_translucent_layer(width, height): translucent_layer = Gtk.EventBox() translucent_layer.get_style_context().add_class('locked_translucent') translucent_layer.set_size_request(width, height) return translucent_layer <|code_end|> , predict the immediate next line with the help of imports: import os from gi.repository import Gtk from kano_profile_gui.paths import media_dir and context (classes, functions, sometimes code) from other files: # Path: kano_profile_gui/paths.py . Output only the next line.
def get_image_path_at_size(category, name, width, height, locked):
Given the code snippet: <|code_start|> win_size = '-W 590 -H 600' def __init__(self, win, dummy=None): FirstScreenTemplate.__init__(self) self.win = win self.win.set_decorated(False) self.win.set_main_widget(self) self.kano_button.connect('button_release_event', self.register_screen) self.login_button.connect( 'button_release_event', self.login_screen ) self.skip_button.connect( 'button_release_event', self.exit_registration ) self.kano_button.connect( 'key_release_event', self.register_screen ) self.button_box.set_margin_bottom(30) self.kano_button.grab_focus() self.win.show_all() def login_screen(self, widget, event): self.win.remove_main_widget() if is_internet(): # Hand-off from the Gtk to the web view <|code_end|> , generate the next line using the imports in this file: import os import sys from gi.repository import Gtk from kano.gtk3.buttons import KanoButton, OrangeButton from kano.gtk3.heading import Heading from kano.network import is_internet from kano_login.swag_screen import SwagScreen from kano_login.templates.template import Template from kano_profile_gui.images import get_image from kano_world.config import AUTH_URL and context (functions, classes, or occasionally code) from other files: # Path: kano_login/swag_screen.py # class SwagScreen(Template): # def __init__(self, win): # # # Set window # self.win = win # self.win.set_decorated(False) # self.win.set_resizable(True) # # # Set text depending on login # login = is_registered() # if login: # header = _("Profile activated!") # subheader = _( # u"Now you can share stuff, build your character, " \ # u"and connect with friends! You've earned some " \ # u"rewards\N{HORIZONTAL ELLIPSIS}" # ) # image_name = 'profile-created' # button_label = _("LET'S GO") # else: # header = _("No online profile - for now.") # subheader = _( # "Your profile stores all your rewards, projects, and " \ # "challenges. But fear not - we'll save everything for " \ # "when you have internet." # ) # image_name = 'no-profile-new' # button_label = _("LET'S GO") # # # Set image # img_width = 590 # img_height = 270 # image_filename = get_image( # 'login', '', image_name, str(img_width) + 'x' + str(img_height) # ) # # # Create template # Template.__init__(self, image_filename, header, subheader, # button_label, "") # # self.win.set_main_widget(self) # self.kano_button.connect('button_release_event', self.next_screen) # self.kano_button.connect('key_release_event', self.next_screen) # self.kano_button.grab_focus() # self.win.show_all() # # # Force the cross button to hide # self.win.headerbar.close_button.hide() # # def next_screen(self, widget, event): # # If enter key is pressed or mouse button is clicked # if not hasattr(event, 'keyval') or event.keyval == 65293: # # Exit # sys.exit(0) # # Path: kano_login/templates/template.py # class Template(Gtk.Box): # # def __init__(self, img_filename, title, description, kano_button_text, orange_button_text): # Gtk.Box.__init__(self, orientation=Gtk.Orientation.VERTICAL) # # if img_filename: # self.image = Gtk.Image.new_from_file(img_filename) # self.pack_start(self.image, False, False, 0) # # self.heading = Heading(title, description) # self.kano_button = KanoButton(kano_button_text) # # self.pack_start(self.heading.container, False, False, 0) # # self.button_box = Gtk.ButtonBox(spacing=10) # self.button_box.set_layout(Gtk.ButtonBoxStyle.SPREAD) # self.button_box.set_margin_bottom(30) # self.pack_start(self.button_box, False, False, 0) # # if not orange_button_text == "": # self.orange_button = OrangeButton(orange_button_text) # self.button_box.pack_start(self.orange_button, False, False, 0) # self.button_box.pack_start(self.kano_button, False, False, 0) # # The empty label is to centre the kano_button # label = Gtk.Label(" ") # self.button_box.pack_start(label, False, False, 0) # else: # self.button_box.pack_start(self.kano_button, False, False, 0) # # Path: kano_profile_gui/images.py # def get_image(category, subcategory, name, subfolder_str): # # The online badge image files are stored in the home directory. # # The function bellow gets the corrects path. # if category == 'badges' and subcategory == 'online': # return get_online_badge_path(name) # # folder = os.path.join(image_dir, category, subfolder_str, subcategory) # filename = '{name}.png'.format(name=name) # fullpath = os.path.join(folder, filename) # if not os.path.exists(fullpath): # logger.error("missing image: {}".format(fullpath)) # return os.path.join(image_dir, 'icons/50/_missing.png') # #ensure_dir(folder) # #open(fullpath, 'w').close() # #print '{} created'.format(fullpath) # # try: # # from randomavatar.randomavatar import Avatar # # ensure_dir(folder) # # avatar = Avatar(rows=10, columns=10) # # image_byte_array = avatar.get_image(string=filename, width=width, height=width, pad=10) # # avatar.save(image_byte_array=image_byte_array, save_location=fullpath) # # print '{} created'.format(fullpath) # # except Exception: # # return os.path.join(image_dir, 'icons/50/_missing.png') # return fullpath # # Path: kano_world/config.py # AUTH_URL = CONF['auth_url'] . Output only the next line.
Gtk.main_quit()
Next line prediction: <|code_start|> def exit_registration(self, widget, event): # We are done, clean up self.win.remove_main_widget() sys.exit(0) def repack(self): self.win.remove_main_widget() self.win.set_main_widget(self) class NoInternet(Template): def __init__(self, win): self.win = win self.win.set_decorated(False) img_width = 590 img_height = 270 header = _("Oops! You need Internet to make a profile") subheader = _( "But you can skip this if you have no connection right now" ) image_filename = get_image('login', "", 'no-internet', str(img_width) + 'x' + str(img_height)) kano_button_label = _("CONNECT") orange_button_label = _("Register later") Template.__init__(self, image_filename, header, subheader, <|code_end|> . Use current file imports: (import os import sys from gi.repository import Gtk from kano.gtk3.buttons import KanoButton, OrangeButton from kano.gtk3.heading import Heading from kano.network import is_internet from kano_login.swag_screen import SwagScreen from kano_login.templates.template import Template from kano_profile_gui.images import get_image from kano_world.config import AUTH_URL) and context including class names, function names, or small code snippets from other files: # Path: kano_login/swag_screen.py # class SwagScreen(Template): # def __init__(self, win): # # # Set window # self.win = win # self.win.set_decorated(False) # self.win.set_resizable(True) # # # Set text depending on login # login = is_registered() # if login: # header = _("Profile activated!") # subheader = _( # u"Now you can share stuff, build your character, " \ # u"and connect with friends! You've earned some " \ # u"rewards\N{HORIZONTAL ELLIPSIS}" # ) # image_name = 'profile-created' # button_label = _("LET'S GO") # else: # header = _("No online profile - for now.") # subheader = _( # "Your profile stores all your rewards, projects, and " \ # "challenges. But fear not - we'll save everything for " \ # "when you have internet." # ) # image_name = 'no-profile-new' # button_label = _("LET'S GO") # # # Set image # img_width = 590 # img_height = 270 # image_filename = get_image( # 'login', '', image_name, str(img_width) + 'x' + str(img_height) # ) # # # Create template # Template.__init__(self, image_filename, header, subheader, # button_label, "") # # self.win.set_main_widget(self) # self.kano_button.connect('button_release_event', self.next_screen) # self.kano_button.connect('key_release_event', self.next_screen) # self.kano_button.grab_focus() # self.win.show_all() # # # Force the cross button to hide # self.win.headerbar.close_button.hide() # # def next_screen(self, widget, event): # # If enter key is pressed or mouse button is clicked # if not hasattr(event, 'keyval') or event.keyval == 65293: # # Exit # sys.exit(0) # # Path: kano_login/templates/template.py # class Template(Gtk.Box): # # def __init__(self, img_filename, title, description, kano_button_text, orange_button_text): # Gtk.Box.__init__(self, orientation=Gtk.Orientation.VERTICAL) # # if img_filename: # self.image = Gtk.Image.new_from_file(img_filename) # self.pack_start(self.image, False, False, 0) # # self.heading = Heading(title, description) # self.kano_button = KanoButton(kano_button_text) # # self.pack_start(self.heading.container, False, False, 0) # # self.button_box = Gtk.ButtonBox(spacing=10) # self.button_box.set_layout(Gtk.ButtonBoxStyle.SPREAD) # self.button_box.set_margin_bottom(30) # self.pack_start(self.button_box, False, False, 0) # # if not orange_button_text == "": # self.orange_button = OrangeButton(orange_button_text) # self.button_box.pack_start(self.orange_button, False, False, 0) # self.button_box.pack_start(self.kano_button, False, False, 0) # # The empty label is to centre the kano_button # label = Gtk.Label(" ") # self.button_box.pack_start(label, False, False, 0) # else: # self.button_box.pack_start(self.kano_button, False, False, 0) # # Path: kano_profile_gui/images.py # def get_image(category, subcategory, name, subfolder_str): # # The online badge image files are stored in the home directory. # # The function bellow gets the corrects path. # if category == 'badges' and subcategory == 'online': # return get_online_badge_path(name) # # folder = os.path.join(image_dir, category, subfolder_str, subcategory) # filename = '{name}.png'.format(name=name) # fullpath = os.path.join(folder, filename) # if not os.path.exists(fullpath): # logger.error("missing image: {}".format(fullpath)) # return os.path.join(image_dir, 'icons/50/_missing.png') # #ensure_dir(folder) # #open(fullpath, 'w').close() # #print '{} created'.format(fullpath) # # try: # # from randomavatar.randomavatar import Avatar # # ensure_dir(folder) # # avatar = Avatar(rows=10, columns=10) # # image_byte_array = avatar.get_image(string=filename, width=width, height=width, pad=10) # # avatar.save(image_byte_array=image_byte_array, save_location=fullpath) # # print '{} created'.format(fullpath) # # except Exception: # # return os.path.join(image_dir, 'icons/50/_missing.png') # return fullpath # # Path: kano_world/config.py # AUTH_URL = CONF['auth_url'] . Output only the next line.
kano_button_label, orange_button_label)
Given snippet: <|code_start|> Gtk.Button.__init__(self) self.badge_info = badge_info self.title = badge_info['title'] self.unlocked_description = badge_info['desc_unlocked'] self.locked_description = badge_info['desc_locked'] background_color = badge_info['bg_color'] self.locked = not badge_info['achieved'] # This is the dimensions of the actual item self.width = 243 self.height = 194 # Dimensions of the image self.img_width = 230 self.img_height = 180 # Dimensions of the hover over label. self.label_height = 44 self.get_style_context().add_class('badge_item') self.background_color = unicodedata.normalize( 'NFKD', '#' + background_color ).encode('ascii', 'ignore') self.locked_background_color = '#e7e7e7' self.create_hover_box() <|code_end|> , continue by predicting the next line. Consider current file imports: from gi.repository import Gtk, GdkPixbuf from kano_profile_gui.image_helper_functions import ( create_translucent_layer, get_image_path_at_size ) import kano_profile_gui.components.icons as icons import kano.gtk3.cursor as cursor import unicodedata and context: # Path: kano_profile_gui/image_helper_functions.py # def create_translucent_layer(width, height): # translucent_layer = Gtk.EventBox() # translucent_layer.get_style_context().add_class('locked_translucent') # translucent_layer.set_size_request(width, height) # return translucent_layer # # def get_image_path_at_size(category, name, width, height, locked): # # size_dir = str(width) + 'x' + str(height) # # if locked: # name = name + "_locked" # # path = os.path.join( # media_dir, # "images/badges", # size_dir, # category, # name + '.png' # ) # return path which might include code, classes, or functions. Output only the next line.
self.set_size_request(self.width, self.height)
Given snippet: <|code_start|> Gtk.Button.__init__(self) self.badge_info = badge_info self.title = badge_info['title'] self.unlocked_description = badge_info['desc_unlocked'] self.locked_description = badge_info['desc_locked'] background_color = badge_info['bg_color'] self.locked = not badge_info['achieved'] # This is the dimensions of the actual item self.width = 243 self.height = 194 # Dimensions of the image self.img_width = 230 self.img_height = 180 # Dimensions of the hover over label. self.label_height = 44 self.get_style_context().add_class('badge_item') self.background_color = unicodedata.normalize( 'NFKD', '#' + background_color ).encode('ascii', 'ignore') self.locked_background_color = '#e7e7e7' self.create_hover_box() self.set_size_request(self.width, self.height) <|code_end|> , continue by predicting the next line. Consider current file imports: from gi.repository import Gtk, GdkPixbuf from kano_profile_gui.image_helper_functions import ( create_translucent_layer, get_image_path_at_size ) import kano_profile_gui.components.icons as icons import kano.gtk3.cursor as cursor import unicodedata and context: # Path: kano_profile_gui/image_helper_functions.py # def create_translucent_layer(width, height): # translucent_layer = Gtk.EventBox() # translucent_layer.get_style_context().add_class('locked_translucent') # translucent_layer.set_size_request(width, height) # return translucent_layer # # def get_image_path_at_size(category, name, width, height, locked): # # size_dir = str(width) + 'x' + str(height) # # if locked: # name = name + "_locked" # # path = os.path.join( # media_dir, # "images/badges", # size_dir, # category, # name + '.png' # ) # return path which might include code, classes, or functions. Output only the next line.
self.connect('enter-notify-event', self.add_hover_style,
Given the code snippet: <|code_start|>#!/usr/bin/env python # upload-share.py # # Copyright (C) 2014, 2015 Kano Computing Ltd. # License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2 # # if __name__ == '__main__' and __package__ is None: dir_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) if dir_path != '/usr': <|code_end|> , generate the next line using the imports in this file: import sys import os from pprint import pprint from kano.utils import run_cmd from kano_world.functions import login_using_token from kano_world.share import upload_share and context (functions, classes, or occasionally code) from other files: # Path: kano_world/functions.py # def login_using_token(): # if is_registered(): # return True, None # return False, _("User is not logged in") # # Path: kano_world/share.py # def upload_share(file_path, title, app_name): # glob_session = get_glob_session() # if not glob_session: # return False, _("You are not logged in!") # # return glob_session.upload_share(file_path, title, app_name) . Output only the next line.
sys.path.insert(1, dir_path)
Continue the code snippet: <|code_start|># # SelectMenu.py # # Copyright (C) 2015 - 2018 Kano Computing Ltd. # License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2 # require_version('Gtk', '3.0') # TODO: try and replace the current structure with the parser? # the selected functions would then be redundant # However, the parser doesn't have a selected category section, so it may not # work for the selcted categories. class SelectMenu(Gtk.EventBox): def __init__(self, list_of_names, signal_name): Gtk.EventBox.__init__(self) apply_styling_to_screen(CSS_PATH) # Initialise self._items <|code_end|> . Use current file imports: from gi import require_version from gi.repository import Gtk from kano.gtk3.apply_styles import apply_styling_to_screen from kano_avatar.paths import CSS_PATH from kano.logging import logger and context (classes, functions, or code) from other files: # Path: kano_avatar/paths.py # CSS_PATH = '/usr/share/kano-profile/media/CSS/avatar_generator.css' . Output only the next line.
self._set_items(list_of_names)
Given the code snippet: <|code_start|> open_session_path = tracking_sessions.get_session_file_path( open_session['name'], open_session['pid'] ) assert os.path.basename(open_session_path) == listed_session.file assert os.path.abspath(open_session_path) == listed_session.path assert open_session['name'] == listed_session.name assert open_session['pid'] == listed_session.pid @pytest.mark.parametrize('name, pid, expected', [ ('test-1', 1234, os.path.join(tracker_dir, '1234-test-1.json')), ('test-2', 5830, os.path.join(tracker_dir, '5830-test-2.json')), ]) def test_get_session_file_path(name, pid, expected): session_file_path = os.path.abspath( tracking_sessions.get_session_file_path(name, pid) ) assert session_file_path == expected # TODO: Populate this test # @pytest.mark.parametrize('name, pid', TEST_DATA) # def test_get_session_unique_id(name, pid): # pass <|code_end|> , generate the next line using the imports in this file: import os import json import pytest import kano_profile.tracker.tracking_sessions as tracking_sessions import kano_profile.tracker.tracking_sessions as tracking_sessions import kano_profile.tracker.tracking_sessions as tracking_sessions import kano_profile.tracker.tracking_sessions as tracking_sessions import kano_profile.tracker.tracking_sessions as tracking_sessions import kano_profile.tracker.tracking_sessions as tracking_sessions import kano_profile.tracker.tracking_sessions as tracking_sessions import kano_profile.tracker.tracking_sessions as tracking_sessions import kano_profile.tracker.tracking_sessions as tracking_sessions import kano_profile.tracker.tracking_sessions as tracking_sessions from tests.fixtures.tracking import TRACKING_SESSIONS from kano_profile.paths import tracker_dir from kano_profile.tracker.tracking_session import TrackingSession from kano_profile.tracker.tracking_session import TrackingSession from kano_profile.tracker.tracking_session import TrackingSession from kano_profile.tracker.tracking_session import TrackingSession from kano_profile.paths import PAUSED_SESSIONS_FILE from kano_profile.tracker.tracking_session import TrackingSession from kano_profile.paths import tracker_dir from kano_profile.paths import tracker_events_file and context (functions, classes, or occasionally code) from other files: # Path: tests/fixtures/tracking.py # TRACKING_SESSIONS = [ # TrackingSessionFixture.format_session( # 'test-1', 12345678, 1234, 60, True # ), # TrackingSessionFixture.format_session( # 'test-2', 22345678, 1234, 32, True # ), # TrackingSessionFixture.format_session( # 'test-3', 32345678, 1234, 288, True # ), # TrackingSessionFixture.format_session( # 'test-4', 42345678, 1234, 119, False # ), # TrackingSessionFixture.format_session( # 'test-5', 52345678, 1234, 3, False # ), # ] # # Path: kano_profile/paths.py # TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids') # PAUSED_SESSIONS_FILE = os.path.join(kanoprofile_dir, '.paused_sessions') . Output only the next line.
def test_session_start_with_pid(tracking_session):
Based on the snippet: <|code_start|> def test_list_sessions(tracking_session, sample_tracking_sessions): tracking_session.setup_sessions(sample_tracking_sessions) tracking_session.setup_paused_sessions(None) listed_sessions = tracking_sessions.list_sessions() assert len(listed_sessions) == len(sample_tracking_sessions) for session in sample_tracking_sessions: session_path = tracking_sessions.get_session_file_path( session['name'], session['pid'] ) assert os.path.basename(session_path) in listed_sessions def test_get_open_sessions(tracking_session, sample_tracking_sessions): sample_sessions = sample_tracking_sessions[:] open_session = tracking_session.format_session( 'active-session', 987654321, os.getpid(), 55, True ) sample_sessions.append(open_session) tracking_session.setup_sessions(sample_sessions) tracking_session.setup_paused_sessions(None) listed_sessions = tracking_sessions.get_open_sessions() <|code_end|> , predict the immediate next line with the help of imports: import os import json import pytest import kano_profile.tracker.tracking_sessions as tracking_sessions import kano_profile.tracker.tracking_sessions as tracking_sessions import kano_profile.tracker.tracking_sessions as tracking_sessions import kano_profile.tracker.tracking_sessions as tracking_sessions import kano_profile.tracker.tracking_sessions as tracking_sessions import kano_profile.tracker.tracking_sessions as tracking_sessions import kano_profile.tracker.tracking_sessions as tracking_sessions import kano_profile.tracker.tracking_sessions as tracking_sessions import kano_profile.tracker.tracking_sessions as tracking_sessions import kano_profile.tracker.tracking_sessions as tracking_sessions from tests.fixtures.tracking import TRACKING_SESSIONS from kano_profile.paths import tracker_dir from kano_profile.tracker.tracking_session import TrackingSession from kano_profile.tracker.tracking_session import TrackingSession from kano_profile.tracker.tracking_session import TrackingSession from kano_profile.tracker.tracking_session import TrackingSession from kano_profile.paths import PAUSED_SESSIONS_FILE from kano_profile.tracker.tracking_session import TrackingSession from kano_profile.paths import tracker_dir from kano_profile.paths import tracker_events_file and context (classes, functions, sometimes code) from other files: # Path: tests/fixtures/tracking.py # TRACKING_SESSIONS = [ # TrackingSessionFixture.format_session( # 'test-1', 12345678, 1234, 60, True # ), # TrackingSessionFixture.format_session( # 'test-2', 22345678, 1234, 32, True # ), # TrackingSessionFixture.format_session( # 'test-3', 32345678, 1234, 288, True # ), # TrackingSessionFixture.format_session( # 'test-4', 42345678, 1234, 119, False # ), # TrackingSessionFixture.format_session( # 'test-5', 52345678, 1234, 3, False # ), # ] # # Path: kano_profile/paths.py # TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids') # PAUSED_SESSIONS_FILE = os.path.join(kanoprofile_dir, '.paused_sessions') . Output only the next line.
for session in listed_sessions:
Predict the next line for this snippet: <|code_start|> self.fixed = Gtk.Fixed() self.add(self.fixed) vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) self.fixed.add(vbox) if path and os.path.exists(path): pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size( path, self.img_height, self.img_width ) margin_top = (self.height - self.img_height) / 2 margin_bottom = margin_top margin_left = (self.width - self.img_width) / 2 margin_right = margin_left image = Gtk.Image.new_from_pixbuf(pixbuf) image.set_margin_top(margin_top) image.set_margin_bottom(margin_bottom) image.set_margin_right(margin_right) image.set_margin_left(margin_left) vbox.pack_start(image, False, False, 0) def hover_over_effect(self, widget, event): label = Gtk.Label(self.title) label.set_line_wrap(True) label.get_style_context().add_class('reward_hover_label') self.hover_info = Gtk.EventBox() self.hover_info.set_size_request(self.width, self.height) <|code_end|> with the help of current file imports: import os from gi.repository import Gtk, GdkPixbuf from kano.gtk3.apply_styles import apply_styling_to_screen from kano_profile_gui.paths import css_dir, image_dir from kano_profile_gui.ProgressDot import ProgressDot and context from other files: # Path: kano_profile_gui/paths.py # # Path: kano_profile_gui/ProgressDot.py # class ProgressDot(Gtk.Fixed): # ''' # A filled or unfilled spot. # ''' # # def __init__(self, filled=False, color='orange'): # ''' # Args: # color (str): "orange", "green" or "grey" # ''' # # Gtk.Fixed.__init__(self) # self.set_size_request(60, 60) # # white_ring = Gtk.EventBox() # white_ring.get_style_context().add_class('progress_outer_ring') # white_ring.set_size_request(44, 44) # self.put(white_ring, 0, 10) # # align1 = Gtk.Alignment(xscale=0, yscale=0, xalign=0.5, yalign=0.5) # white_ring.add(align1) # # brown_ring = Gtk.EventBox() # brown_ring.get_style_context().add_class('progress_scroll_section') # brown_ring.set_size_request(34, 34) # # align1.add(brown_ring) # # align2 = Gtk.Alignment(xscale=0, yscale=0, xalign=0.5, yalign=0.5) # brown_ring.add(align2) # # tick_background = Gtk.EventBox() # tick_background.get_style_context().add_class('transparent') # self.put(tick_background, 5, 0) # # if filled: # self._tick = Tick(50, 50) # tick_background.add(self._tick) # # @property # def tick(self): # return self._tick , which may contain function names, class names, or code. Output only the next line.
self.hover_info.get_style_context().add_class('reward_hover_background')
Predict the next line after this snippet: <|code_start|> self.get_style_context().add_class('quest_screen_background') vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) self.add(vbox) self.grid = Gtk.Grid() self.grid.set_column_spacing(10) self.grid.set_row_spacing(10) self.grid.set_margin_left(10) self.grid.set_margin_right(10) self.grid.set_margin_bottom(10) self.grid.set_margin_top(10) vbox.pack_start(self.grid, False, False, 0) # May be better elsewhere self.win = keywords['win'] self.quest = keywords['quest_info'] self.win.pack_in_main_content(self) # Pack in Progress progress_section = self.create_progress_section() self.grid.attach(progress_section, 0, 0, 1, 1) # Pack in Rewards rewards = self.create_reward_section() self.grid.attach(rewards, 1, 0, 1, 1) self.win.show_all() <|code_end|> using the current file's imports: import os from gi.repository import Gtk, GdkPixbuf from kano.gtk3.apply_styles import apply_styling_to_screen from kano_profile_gui.paths import css_dir, image_dir from kano_profile_gui.ProgressDot import ProgressDot and any relevant context from other files: # Path: kano_profile_gui/paths.py # # Path: kano_profile_gui/ProgressDot.py # class ProgressDot(Gtk.Fixed): # ''' # A filled or unfilled spot. # ''' # # def __init__(self, filled=False, color='orange'): # ''' # Args: # color (str): "orange", "green" or "grey" # ''' # # Gtk.Fixed.__init__(self) # self.set_size_request(60, 60) # # white_ring = Gtk.EventBox() # white_ring.get_style_context().add_class('progress_outer_ring') # white_ring.set_size_request(44, 44) # self.put(white_ring, 0, 10) # # align1 = Gtk.Alignment(xscale=0, yscale=0, xalign=0.5, yalign=0.5) # white_ring.add(align1) # # brown_ring = Gtk.EventBox() # brown_ring.get_style_context().add_class('progress_scroll_section') # brown_ring.set_size_request(34, 34) # # align1.add(brown_ring) # # align2 = Gtk.Alignment(xscale=0, yscale=0, xalign=0.5, yalign=0.5) # brown_ring.add(align2) # # tick_background = Gtk.EventBox() # tick_background.get_style_context().add_class('transparent') # self.put(tick_background, 5, 0) # # if filled: # self._tick = Tick(50, 50) # tick_background.add(self._tick) # # @property # def tick(self): # return self._tick . Output only the next line.
def create_progress_section(self):
Next line prediction: <|code_start|> self.grid.set_margin_bottom(10) self.grid.set_margin_top(10) vbox.pack_start(self.grid, False, False, 0) # May be better elsewhere self.win = keywords['win'] self.quest = keywords['quest_info'] self.win.pack_in_main_content(self) # Pack in Progress progress_section = self.create_progress_section() self.grid.attach(progress_section, 0, 0, 1, 1) # Pack in Rewards rewards = self.create_reward_section() self.grid.attach(rewards, 1, 0, 1, 1) self.win.show_all() def create_progress_section(self): scroll_path = os.path.join(image_dir, "quests/scroll.svg") scroll_pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(scroll_path, 505, -1) scroll_img = Gtk.Image.new_from_pixbuf(scroll_pixbuf) fixed = Gtk.Fixed() fixed.put(scroll_img, 0, 0) vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) vbox.set_margin_left(10) <|code_end|> . Use current file imports: (import os from gi.repository import Gtk, GdkPixbuf from kano.gtk3.apply_styles import apply_styling_to_screen from kano_profile_gui.paths import css_dir, image_dir from kano_profile_gui.ProgressDot import ProgressDot) and context including class names, function names, or small code snippets from other files: # Path: kano_profile_gui/paths.py # # Path: kano_profile_gui/ProgressDot.py # class ProgressDot(Gtk.Fixed): # ''' # A filled or unfilled spot. # ''' # # def __init__(self, filled=False, color='orange'): # ''' # Args: # color (str): "orange", "green" or "grey" # ''' # # Gtk.Fixed.__init__(self) # self.set_size_request(60, 60) # # white_ring = Gtk.EventBox() # white_ring.get_style_context().add_class('progress_outer_ring') # white_ring.set_size_request(44, 44) # self.put(white_ring, 0, 10) # # align1 = Gtk.Alignment(xscale=0, yscale=0, xalign=0.5, yalign=0.5) # white_ring.add(align1) # # brown_ring = Gtk.EventBox() # brown_ring.get_style_context().add_class('progress_scroll_section') # brown_ring.set_size_request(34, 34) # # align1.add(brown_ring) # # align2 = Gtk.Alignment(xscale=0, yscale=0, xalign=0.5, yalign=0.5) # brown_ring.add(align2) # # tick_background = Gtk.EventBox() # tick_background.get_style_context().add_class('transparent') # self.put(tick_background, 5, 0) # # if filled: # self._tick = Tick(50, 50) # tick_background.add(self._tick) # # @property # def tick(self): # return self._tick . Output only the next line.
text_background = Gtk.EventBox()
Next line prediction: <|code_start|>#!/usr/bin/env python # logged_in.py # # Copyright (C) 2014, 2015 Kano Computing Ltd. # License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2 # # UI for login screen class LoggedIn(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title='Profile') self.set_size_request(200, 150) self.set_decorated(False) self.set_position(Gtk.WindowPosition.CENTER) self.set_resizable(False) self.ok_button = KanoButton(_("OK")) self.ok_button.pack_and_align() self.ok_button.set_padding(20, 20, 0, 0) self.ok_button.connect('clicked', Gtk.main_quit) self.title = Heading(_("Logged in!"), _("You're already logged in")) self.main_container = Gtk.Box( <|code_end|> . Use current file imports: (from kano_world.functions import remove_token from kano.gtk3.buttons import KanoButton from kano.gtk3.heading import Heading from gi.repository import Gtk import kano.gtk3.cursor as cursor) and context including class names, function names, or small code snippets from other files: # Path: kano_world/functions.py # def remove_token(): # profile = load_profile() # profile.pop('token', None) # save_profile(profile) . Output only the next line.
orientation=Gtk.Orientation.VERTICAL, spacing=0)