Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Here is a snippet: <|code_start|> ## TODO # def test_duplicated_functions(): # m = rw.http.Module('test') # # @m.get('/') # def foo(): # pass # # with pytest.raises(rw.routing.DuplicateError): # @m.get('/something_else') # def foo(): # pass class HTTPTest(tornado.testing.AsyncTestCase): def test_http(self): self.scope = rw.scope.Scope() with self.scope(): self.scope.activate(rw.routing.plugin, callback=self.http) self.wait() def http(self, _): sub = rw.http.Module('sub') <|code_end|> . Write the next line using the current file imports: from collections import namedtuple from .common import generate_handler_func import pytest import tornado.testing import rw.scope import rw.http import rw.routing import rw.template and context from other files: # Path: test/common.py # def generate_handler_func(route_func, path, name=None): # if name is None: # name = route_func.__name__ + '_' + {'/': 'index'}[path] # f = generate_route_func(name) # return route_func(path)(f) , which may include functions, classes, or code. Output only the next line.
sub_index = generate_handler_func(sub.get, '/')
Given the following code snippet before the placeholder: <|code_start|> def test_reverse_path(): assert generate_rule('/').get_path() == '/' assert generate_rule('/somewhere').get_path() == '/somewhere' assert generate_rule('/user/<user>').get_path({'user': 'dino'}) == '/user/dino' def test_converter_default(): assert (3, 'foo') == rw.routing.converter_default('foo') assert (3, 'foo') == rw.routing.converter_default('foo/bar') def test_convert_int(): assert rw.routing.converter_int('123') == (3, 123) assert rw.routing.converter_int('4321Hello World') == (4, 4321) assert rw.routing.converter_int('-1431') == (5, -1431) with pytest.raises(rw.routing.NoMatchError): rw.routing.converter_int('foo') def test_convert_uint(): assert rw.routing.converter_uint('123') == (3, 123) assert rw.routing.converter_uint('4321Hello World') == (4, 4321) with pytest.raises(rw.routing.NoMatchError): assert rw.routing.converter_uint('-1431') == (5, -1431) def test_submodules(): rt0 = rw.routing.RoutingTable('root') <|code_end|> , predict the next line using imports from the current file: import pytest import tornado.testing import rw.routing import rw.scope from .common import generate_route_func and context including class names, function names, and sometimes code from other files: # Path: test/common.py # def generate_route_func(name): # def f(x): # return x # # f.__name__ = name # return f . Output only the next line.
rt0.add_route('get', '/', 0, generate_route_func('index'))
Based on the snippet: <|code_start|> if len(''.join(strings)) != len(''.join(strings_o)): return len(''.join(strings)) > len(''.join(strings_o)) for i in range(len(strings)): if strings[i] != strings_o[i]: return strings[i] < strings_o[i] # strings are the same, so check variables for non-default parser for i in range(len(variables)): if variables[i] != 'str' and variables_o[i] == 'str': return True return False def __gt__(self, o): """greater than `o` :param Route o: other rule to compare with """ if self == o: return False return o < self def __eq__(self, o): """equal to `o` :param Route o: other rule to compare with """ return self.route == o.route <|code_end|> , predict the immediate next line with the help of imports: import re import tornado.web import rw.plugin from future.builtins import range from tornado import util from rw import scope and context (classes, functions, sometimes code) from other files: # Path: rw/scope.py # NOT_PROVIDED = object() # SCOPE_CHAIN = None # LOG = logging.getLogger(__name__) # SCOPE_CHAIN = [] # class OutsideScopeError(Exception): # class Scope(dict): # class SubScope(Scope): # class SubScopeView(object): # def __init__(self, name=None): # def provider(self, key, provider): # def activate(self, plugin): # def subscope(self, key): # def get(self, key, default=NOT_PROVIDED, scopes=None): # def __call__(self): # def run(self, target_coroutine): # def __init__(self, name, parent): # def __init__(self, key, scope_chain): # def __getitem__(self, item): # def __eq__(self, other): # def set_context(scope): # def get_current_scope(): # def get(key, default=NOT_PROVIDED): # def inject(fn): # def wrapper(*args, **kwargs): # def setup_app_scope(name, scope): . Output only the next line.
@rw.scope.inject
Given the code snippet: <|code_start|># -*- coding:utf-8 -*- __author__ = '东方鹗' class LoginForm(FlaskForm): email = StringField('邮箱', validators=[DataRequired()]) password = PasswordField('密码', validators=[DataRequired()]) remember_me = BooleanField(label='记住我', default=False) submit = SubmitField('登 录') class AddAdminForm(FlaskForm): username = StringField('用户名', validators=[DataRequired(), Length(1, 16, message='用户名长度要在1和16之间'), Regexp('^[\u4E00-\u9FFF]+$', flags=0, message='用户名必须为中文')]) email = StringField('邮箱', validators=[DataRequired(), Length(6, 64, message='邮件长度要在6和64之间'), Email(message='邮件格式不正确!')]) password = PasswordField('密码', validators=[DataRequired(), EqualTo('password2', message='密码必须一致!')]) password2 = PasswordField('重输密码', validators=[DataRequired()]) submit = SubmitField('注 册') def validate_username(self, field): <|code_end|> , generate the next line using the imports in this file: from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField, SubmitField, SelectField, TextAreaField from wtforms.validators import DataRequired, Length, Email, Regexp, EqualTo from wtforms import ValidationError from ..models import User and context (functions, classes, or occasionally code) from other files: # Path: app/models.py # class User(UserMixin, db.Model): # __tablename__ = 'users' # id = db.Column(db.Integer, primary_key=True) # username = db.Column(db.String(64), unique=True, index=True) # email = db.Column(db.String(64), unique=True, index=True) # password_hash = db.Column(db.String(128)) # member_since = db.Column(db.DateTime(), default=datetime.utcnow) # last_seen = db.Column(db.DateTime(), default=datetime.utcnow) # status = db.Column(db.Boolean, default=False) # role = db.Column(db.Boolean, default=False) # articles = db.relationship('Article', backref='author', lazy='dynamic') # # @property # def password(self): # raise ArithmeticError('非明文密码,不可读。') # # @password.setter # def password(self, password): # self.password_hash = generate_password_hash(password=password) # # def verify_password(self, password): # return check_password_hash(self.password_hash, password=password) # # def is_admin(self): # return self.role # # def ping(self): # self.last_seen = datetime.utcnow() # db.session.add(self) # # def is_author(self): # return Article.query.filter_by(author_id=self.id).first() # # def __repr__(self): # return '<User %r>' % self.username . Output only the next line.
if User.query.filter_by(username=field.data).first():
Given the following code snippet before the placeholder: <|code_start|> -- notifications_subscription table and the same data exists -- in both tables FROM notifications_subscription s WHERE s.group_id = %s AND -- In order to prevent an IntegrityError, grab all users -- with existing UserThread object and exclude them from -- this insert. The only users who should have a UserThread -- is the author and anyone who joined to the group between -- the time the author posted the thread and the time this -- task runs (in other words, not many users) s.user_id NOT IN (SELECT user_id FROM connectmessages_userthread WHERE thread_id = %s) """, [ thread.pk, thread.group.pk, thread.pk]) else: UserThread.objects.filter( thread=thread, read=True).exclude(user=sender).update(read=False) UserThread.objects.filter( thread=thread, status='archived' ).exclude(user=sender).update(status='active') if thread.thread_type == 'group': <|code_end|> , predict the next line using imports from the current file: from celery import shared_task from django.conf import settings from django.db import connection from open_connect.notifications.tasks import ( create_group_notifications, send_immediate_notification ) from open_connect.connectmessages.models import ImageAttachment from open_connect.connectmessages.models import Message, UserThread from open_connect.connectmessages.models import Thread, Message from open_connect.notifications.models import Notification from open_connect.accounts.models import User and context including class names, function names, and sometimes code from other files: # Path: open_connect/notifications/tasks.py # @shared_task() # def create_group_notifications(message_id): # """Create notifications for messages sent to a group.""" # # Import here to avoid circular import # from open_connect.connectmessages.models import Message, UserThread # message = Message.objects.get(pk=message_id) # userthreads = UserThread.objects.filter( # thread_id=message.thread_id, # subscribed_email=True, # user__unsubscribed=False # ).exclude( # user_id=message.sender_id # ) # # # User.objects.filter(userthread__thread=message.thread) # for userthread in userthreads: # create_group_notification.delay(message.pk, userthread.pk) # # @shared_task() # def send_immediate_notification(notification_id): # """Send an email for a given notification.""" # notification = Notification.objects.select_related( # 'recipient', 'message', 'message__thread').get(pk=notification_id) # recipient = notification.recipient # message = notification.message # context = { # 'notification': notification, # 'message': message, # 'recipient': recipient, # 'email': recipient.email # } # text = render_to_string( # 'notifications/email/email_immediate.txt', context) # html = render_to_string( # 'notifications/email/email_immediate.html', context) # # # Determine the correct format of the subject line of the notification # if message.thread.thread_type == 'direct': # subject_format = u"{subject}" # else: # subject_format = u"[{group}] {subject}" # subject = subject_format.format( # group=message.thread.group, subject=message.thread.subject) # # if message.sender.is_staff: # from_name = u'{name}, Staff Member, {brand}'.format( # name=message.sender.get_full_name(), # brand=settings.BRAND_TITLE) # else: # from_name = u'{name}, {brand}'.format( # name=message.sender.get_full_name(), # brand=settings.BRAND_TITLE) # from_email = formataddr((from_name, settings.DEFAULT_FROM_ADDRESS)) # # to_email_tup = (recipient.get_full_name(), notification.recipient.email) # to_address = formataddr(to_email_tup) # # send_email( # email=to_address, # from_email=from_email, # subject=subject, # text=text, # html=html # ) # # notification.consumed = True # notification.save() . Output only the next line.
create_group_notifications.delay(message_id)
Predict the next line after this snippet: <|code_start|>@shared_task(name='send-system-message') def send_system_message(recipient, subject, message_content): """Send a direct message to a user coming from the system user""" # Handle calls where we're passed the user_id instead of a User object. if not isinstance(recipient, User): recipient = User.objects.get(pk=recipient) sysuser = User.objects.get(email=settings.SYSTEM_USER_EMAIL) thread = Thread.objects.create( subject=subject[:100], thread_type='direct', closed=True ) message = Message( thread=thread, sender=sysuser, text=message_content ) message.save(shorten=False) thread.add_user_to_thread(recipient) # Use BeautifulSoup to remove any HTML from the message to make the # plaintext email version of the message notification, created = Notification.objects.get_or_create( recipient_id=recipient.pk, message=message ) if created and recipient.group_notification_period == 'immediate': <|code_end|> using the current file's imports: from celery import shared_task from django.conf import settings from django.db import connection from open_connect.notifications.tasks import ( create_group_notifications, send_immediate_notification ) from open_connect.connectmessages.models import ImageAttachment from open_connect.connectmessages.models import Message, UserThread from open_connect.connectmessages.models import Thread, Message from open_connect.notifications.models import Notification from open_connect.accounts.models import User and any relevant context from other files: # Path: open_connect/notifications/tasks.py # @shared_task() # def create_group_notifications(message_id): # """Create notifications for messages sent to a group.""" # # Import here to avoid circular import # from open_connect.connectmessages.models import Message, UserThread # message = Message.objects.get(pk=message_id) # userthreads = UserThread.objects.filter( # thread_id=message.thread_id, # subscribed_email=True, # user__unsubscribed=False # ).exclude( # user_id=message.sender_id # ) # # # User.objects.filter(userthread__thread=message.thread) # for userthread in userthreads: # create_group_notification.delay(message.pk, userthread.pk) # # @shared_task() # def send_immediate_notification(notification_id): # """Send an email for a given notification.""" # notification = Notification.objects.select_related( # 'recipient', 'message', 'message__thread').get(pk=notification_id) # recipient = notification.recipient # message = notification.message # context = { # 'notification': notification, # 'message': message, # 'recipient': recipient, # 'email': recipient.email # } # text = render_to_string( # 'notifications/email/email_immediate.txt', context) # html = render_to_string( # 'notifications/email/email_immediate.html', context) # # # Determine the correct format of the subject line of the notification # if message.thread.thread_type == 'direct': # subject_format = u"{subject}" # else: # subject_format = u"[{group}] {subject}" # subject = subject_format.format( # group=message.thread.group, subject=message.thread.subject) # # if message.sender.is_staff: # from_name = u'{name}, Staff Member, {brand}'.format( # name=message.sender.get_full_name(), # brand=settings.BRAND_TITLE) # else: # from_name = u'{name}, {brand}'.format( # name=message.sender.get_full_name(), # brand=settings.BRAND_TITLE) # from_email = formataddr((from_name, settings.DEFAULT_FROM_ADDRESS)) # # to_email_tup = (recipient.get_full_name(), notification.recipient.email) # to_address = formataddr(to_email_tup) # # send_email( # email=to_address, # from_email=from_email, # subject=subject, # text=text, # html=html # ) # # notification.consumed = True # notification.save() . Output only the next line.
send_immediate_notification.delay(notification.pk)
Predict the next line for this snippet: <|code_start|> User = get_user_model() class ImpersonationMiddlewareTest(TestCase): """Tests for the impersonation middleware.""" def setUp(self): """Setup the ImpersonationMiddlewareTest TestCase""" self.user = User.objects.create_user( username='impersonate@me.local', password='abc') self.admin = User.objects.create_user( username='admin@dj.local', password='abc') self.client.post( reverse('account_login'), {'login': 'admin@dj.local', 'password': 'abc'} ) self.request_factory = RequestFactory() def test_process_request_admin_has_permission(self): """A user with permission should be able to impersonate another user.""" # Make sure user has can_impersonate permission permission = Permission.objects.get_by_natural_key( 'can_impersonate', 'accounts', 'user') self.admin.user_permissions.add(permission) self.admin.save() self.assertTrue(self.admin.has_perm('accounts.can_impersonate')) # Call the middleware <|code_end|> with the help of current file imports: from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission from django.core.urlresolvers import reverse from django.test import TestCase, RequestFactory from open_connect.middleware.impersonation import ImpersonationMiddleware and context from other files: # Path: open_connect/middleware/impersonation.py # class ImpersonationMiddleware(object): # """Middleware to impersonate another user.""" # # pylint: disable=no-self-use # def process_request(self, request): # """Set the request user to user to impersonate.""" # # pylint: disable=invalid-name # User = get_user_model() # impersonate_id = request.session.get('impersonate_id', None) # request.user.impersonating = False # if not impersonate_id: # return # if not request.user.can_impersonate(): # return # try: # user = User.objects.get(pk=impersonate_id) # except User.DoesNotExist: # return # else: # request.user = user # request.user.impersonating = True , which may contain function names, class names, or code. Output only the next line.
middleware = ImpersonationMiddleware()
Using the snippet: <|code_start|>"""Tests for accepting terms middleware.""" # pylint: disable=invalid-name class TestAcceptTermsAndConductMiddleware(TestCase): """Tests for AcceptTermsAndConductMiddleware.""" def setUp(self): """Setup the TestAcceptTermsAndConductMiddleware TestCase""" self.factory = RequestFactory() <|code_end|> , determine the next line of code. You have imports: from django.contrib.auth.models import AnonymousUser from django.core.urlresolvers import reverse from django.test import TestCase, RequestFactory from django.utils.timezone import now from model_mommy import mommy from open_connect.middleware.accept_terms import AcceptTermsAndConductMiddleware and context (class names, function names, or code) available: # Path: open_connect/middleware/accept_terms.py # class AcceptTermsAndConductMiddleware(object): # """Checks that users have accepted terms and conduct agreements.""" # def process_request(self, request): # """Process request and ask for an invite code if needed.""" # # Find users that are logged in but haven't been verified # user = request.user # if user.is_authenticated() and not request.is_ajax(): # if user.tos_accepted_at and user.ucoc_accepted_at: # return # path = request.path_info.lstrip('/') # # Only check the invite for paths that require login # if not any(m.match(path) for m in EXEMPT_URLS): # redirect_to = '{url}?next={next}'.format( # url=reverse('accept_terms_and_conduct'), # next=request.path_info # ) # return HttpResponseRedirect(redirect_to) . Output only the next line.
self.mw = AcceptTermsAndConductMiddleware()
Predict the next line after this snippet: <|code_start|>"""Admin functionality for group app""" class CategoryAdmin(admin.ModelAdmin): """Admin for Group Categories""" readonly_fields = [ 'modified_at', 'created_at' ] <|code_end|> using the current file's imports: from django.contrib import admin from django.contrib.auth.models import Group as AuthGroup from open_connect.groups.models import Category and any relevant context from other files: # Path: open_connect/groups/models.py # class Category(TimestampModel): # """Group Category""" # slug = models.SlugField(unique=True) # name = models.CharField(max_length=127) # color = models.CharField( # verbose_name='Category Color', max_length=7, default='#000000') # # class Meta(object): # """Meta options for Category model""" # verbose_name = 'Category' # verbose_name_plural = 'Categories' # # # def __unicode__(self): # """Unicode Representation of Category""" # return self.name . Output only the next line.
admin.site.register(Category, CategoryAdmin)
Continue the code snippet: <|code_start|>"""Connect base url definitions.""" # pylint: disable=no-value-for-parameter,invalid-name autocomplete_light.autodiscover() admin.autodiscover() urlpatterns = patterns( '', url(r'^$', include('open_connect.welcome.urls')), url(r'^admin/', include(admin.site.urls)), # Because we're overriding django-allauth's signup view with our own view # we need to include it above the include for django-allatuh url(r'^user/signup/$', <|code_end|> . Use current file imports: from urlparse import urljoin from allauth.account import views as auth_views from django.conf import settings from django.conf.urls import patterns, include, url from django.conf.urls.static import static from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.http import HttpResponse from django.views.generic import RedirectView, TemplateView from django_bouncy.views import endpoint as bouncy_endpoint from open_connect.accounts.views import SignupView as ConnectSignupView from open_connect.groups.views import GroupListView import autocomplete_light and context (classes, functions, or code) from other files: # Path: open_connect/accounts/views.py # class SignupView(AllauthSignupView): # """Connect Signup View""" # form_class = SignupForm # # Path: open_connect/groups/views.py # class GroupListView(CommonViewMixin, ListView): # """View for listing groups.""" # model = Group # located = False # template_name = "groups/group_list.html" # context_object_name = 'groups' # nav_active_item = 'Groups' # dd_active_item = 'My Groups' # # def get_queryset(self): # """Modify queryset if there are search params in the request.""" # location = self.request.GET.get('location') # query = self.request.GET.get('q') # coords = None # # if location: # coords = get_coordinates(location) # # if coords: # self.located = True # # queryset = Group.objects.search( # search=query, location=coords) # # return queryset # # def get_context_data(self, **kwargs): # """Group list view context object populator""" # context = super(GroupListView, self).get_context_data(**kwargs) # # context['q'] = self.request.GET.get('q', '') # context['categories'] = Category.objects.filter( # # Because we use `queryset.extra(select=,where=)` and the `where=` # # explictly mentions "group_groups" we cannot include that query as # # part of the query that gets our categories. # pk__in=list(self.object_list.values_list( # 'category_id', flat=True))) # context['location'] = self.request.GET.get('location') # context['located'] = self.located # # if self.request.user.is_authenticated(): # user = self.request.user # requested_ids = GroupRequest.objects.filter( # user=user, approved__isnull=True).values_list( # 'group_id', flat=True) # subscribed_ids = user.groups_joined.values_list('pk', flat=True) # moderating_ids = user.groups_moderating.values_list( # 'id', flat=True) # else: # requested_ids = [] # subscribed_ids = [] # moderating_ids = [] # # context['requested_ids'] = requested_ids # context['subscribed_ids'] = subscribed_ids # context['moderating_ids'] = moderating_ids # # return context . Output only the next line.
ConnectSignupView.as_view(),
Given the code snippet: <|code_start|> url(r'^admin/', include(admin.site.urls)), # Because we're overriding django-allauth's signup view with our own view # we need to include it above the include for django-allatuh url(r'^user/signup/$', ConnectSignupView.as_view(), name='account_signup'), url(r'^user/', include('allauth.urls')), url(r'^accounts/', include('open_connect.accounts.urls')), url(r'^groups/', include('open_connect.groups.urls')), url(r'^messages/', include('open_connect.connectmessages.urls')), url(r'^moderation/', include('open_connect.moderation.urls')), url(r'^mail/bouncy/$', bouncy_endpoint, name='ses_endpoint'), url(r'^mail/', include('open_connect.mailer.urls')), url(r'^subscriptions/', include('open_connect.notifications.urls')), url(r'^media/', include('open_connect.media.urls')), url(r'^robots\.txt$', lambda r: HttpResponse( "User-agent: *\nDisallow: /", content_type="text/plain")), # pylint: disable=line-too-long url(r'^favicon\.ico$', RedirectView.as_view( url=urljoin(settings.STATIC_URL, 'img/favicon.ico'), permanent=True)), url(r'^autocomplete/', include('autocomplete_light.urls')), url(r'^reports/', include('open_connect.reporting.urls')), <|code_end|> , generate the next line using the imports in this file: from urlparse import urljoin from allauth.account import views as auth_views from django.conf import settings from django.conf.urls import patterns, include, url from django.conf.urls.static import static from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.http import HttpResponse from django.views.generic import RedirectView, TemplateView from django_bouncy.views import endpoint as bouncy_endpoint from open_connect.accounts.views import SignupView as ConnectSignupView from open_connect.groups.views import GroupListView import autocomplete_light and context (functions, classes, or occasionally code) from other files: # Path: open_connect/accounts/views.py # class SignupView(AllauthSignupView): # """Connect Signup View""" # form_class = SignupForm # # Path: open_connect/groups/views.py # class GroupListView(CommonViewMixin, ListView): # """View for listing groups.""" # model = Group # located = False # template_name = "groups/group_list.html" # context_object_name = 'groups' # nav_active_item = 'Groups' # dd_active_item = 'My Groups' # # def get_queryset(self): # """Modify queryset if there are search params in the request.""" # location = self.request.GET.get('location') # query = self.request.GET.get('q') # coords = None # # if location: # coords = get_coordinates(location) # # if coords: # self.located = True # # queryset = Group.objects.search( # search=query, location=coords) # # return queryset # # def get_context_data(self, **kwargs): # """Group list view context object populator""" # context = super(GroupListView, self).get_context_data(**kwargs) # # context['q'] = self.request.GET.get('q', '') # context['categories'] = Category.objects.filter( # # Because we use `queryset.extra(select=,where=)` and the `where=` # # explictly mentions "group_groups" we cannot include that query as # # part of the query that gets our categories. # pk__in=list(self.object_list.values_list( # 'category_id', flat=True))) # context['location'] = self.request.GET.get('location') # context['located'] = self.located # # if self.request.user.is_authenticated(): # user = self.request.user # requested_ids = GroupRequest.objects.filter( # user=user, approved__isnull=True).values_list( # 'group_id', flat=True) # subscribed_ids = user.groups_joined.values_list('pk', flat=True) # moderating_ids = user.groups_moderating.values_list( # 'id', flat=True) # else: # requested_ids = [] # subscribed_ids = [] # moderating_ids = [] # # context['requested_ids'] = requested_ids # context['subscribed_ids'] = subscribed_ids # context['moderating_ids'] = moderating_ids # # return context . Output only the next line.
url(r'^explore/$', GroupListView.as_view(), name='explore'),
Continue the code snippet: <|code_start|> class Meta(object): """Meta options for Thread.""" ordering = ['-latest_message__created_at'] def __unicode__(self): """Return object's unicode representation.""" return "Thread %s" % self.subject @property def is_system_thread(self): """Returns true if this is a thread started by the system message""" return self.first_message.is_system_message def get_absolute_url(self): """Return absolute URL for a thread""" return reverse('thread', args=(self.pk,)) def get_unsubscribe_url(self): """Return the URL of the unsubscribe view""" return reverse('thread_unsubscribe', args=(self.pk,)) def add_user_to_thread(self, user): """Add a user to a thread.""" defaults = {} if self.thread_type == 'group': # This is put inside a try/except because it is possible for staff # to send messages to groups they are not members of and thus # do not have a subscription to. try: <|code_end|> . Use current file imports: from bs4 import BeautifulSoup from datetime import timedelta from django.core.urlresolvers import reverse from django.conf import settings from django.db import models from django.db.models import Q, ObjectDoesNotExist from django.utils.encoding import smart_text from django.utils.timezone import now from unidecode import unidecode from open_connect.media.models import Image, ShortenedURL from open_connect.notifications.models import Subscription from open_connect.connectmessages import tasks from open_connect.connect_core.utils.models import TimestampModel from open_connect.connect_core.utils.stringhelp import unicode_or_empty import logging import re import pytz and context (classes, functions, or code) from other files: # Path: open_connect/notifications/models.py # class Subscription(TimestampModel): # """Model for tracking a user's subscription preferences to a group.""" # user = models.ForeignKey( # settings.AUTH_USER_MODEL, related_name='subscriptions') # period = models.CharField( # max_length=30, choices=NOTIFICATION_PERIODS, default='immediate', # db_index=True) # group = models.ForeignKey('groups.Group') # # class Meta(object): # """Meta options for Subcription model.""" # unique_together = ['user', 'group'] # # def save(self, *args, **kwargs): # """Save method for Subscription""" # # Importing from models to address circular import # from open_connect.connectmessages.models import UserThread # # Check to see if there is already a primary key (aka, this is an edit) # if self.pk: # # Get the original version of this record # orig = Subscription.objects.get(pk=self.pk) # # Check to see if the version has changed to none # if self.period == 'none' and orig.period != 'none': # # If the original record was not none (aka the period has # # changed to 'none' from something else) update all UserThreads # UserThread.objects.filter( # thread__group_id=self.group_id, # user_id=self.user_id, # subscribed_email=True # ).update(subscribed_email=False) # elif orig.period == 'none': # UserThread.objects.filter( # thread__group_id=self.group_id, # user_id=self.user_id, # subscribed_email=False # ).update(subscribed_email=True) # # return super(Subscription, self).save(*args, **kwargs) # # def __unicode__(self): # """Unicode representation of the model.""" # return u'Subscription to {group} for {user}.'.format( # group=self.group, user=self.user) # # Path: open_connect/connectmessages/tasks.py # def import_image_attachment(): # def process_image_attachment(image_id): # def send_message(message_id, shorten=True): # def send_system_message(recipient, subject, message_content): . Output only the next line.
subscription = Subscription.objects.get(
Based on the snippet: <|code_start|> def save(self, **kwargs): """Save a message.""" self.clean_text = self._text_cleaner() shorten = kwargs.pop('shorten', True) if not self.pk: created = True self.status = self.get_initial_status() else: created = False # Save the model result = super(Message, self).save(**kwargs) if shorten: # Rewrite urls for tracking self._shorten() if created: # These fields need to be set immediately or things break. if self.thread.first_message is None: self.thread.first_message = self self.thread.latest_message = self self.thread.save() self.thread.add_user_to_thread(self.sender) if self.status == 'approved': <|code_end|> , predict the immediate next line with the help of imports: from bs4 import BeautifulSoup from datetime import timedelta from django.core.urlresolvers import reverse from django.conf import settings from django.db import models from django.db.models import Q, ObjectDoesNotExist from django.utils.encoding import smart_text from django.utils.timezone import now from unidecode import unidecode from open_connect.media.models import Image, ShortenedURL from open_connect.notifications.models import Subscription from open_connect.connectmessages import tasks from open_connect.connect_core.utils.models import TimestampModel from open_connect.connect_core.utils.stringhelp import unicode_or_empty import logging import re import pytz and context (classes, functions, sometimes code) from other files: # Path: open_connect/notifications/models.py # class Subscription(TimestampModel): # """Model for tracking a user's subscription preferences to a group.""" # user = models.ForeignKey( # settings.AUTH_USER_MODEL, related_name='subscriptions') # period = models.CharField( # max_length=30, choices=NOTIFICATION_PERIODS, default='immediate', # db_index=True) # group = models.ForeignKey('groups.Group') # # class Meta(object): # """Meta options for Subcription model.""" # unique_together = ['user', 'group'] # # def save(self, *args, **kwargs): # """Save method for Subscription""" # # Importing from models to address circular import # from open_connect.connectmessages.models import UserThread # # Check to see if there is already a primary key (aka, this is an edit) # if self.pk: # # Get the original version of this record # orig = Subscription.objects.get(pk=self.pk) # # Check to see if the version has changed to none # if self.period == 'none' and orig.period != 'none': # # If the original record was not none (aka the period has # # changed to 'none' from something else) update all UserThreads # UserThread.objects.filter( # thread__group_id=self.group_id, # user_id=self.user_id, # subscribed_email=True # ).update(subscribed_email=False) # elif orig.period == 'none': # UserThread.objects.filter( # thread__group_id=self.group_id, # user_id=self.user_id, # subscribed_email=False # ).update(subscribed_email=True) # # return super(Subscription, self).save(*args, **kwargs) # # def __unicode__(self): # """Unicode representation of the model.""" # return u'Subscription to {group} for {user}.'.format( # group=self.group, user=self.user) # # Path: open_connect/connectmessages/tasks.py # def import_image_attachment(): # def process_image_attachment(image_id): # def send_message(message_id, shorten=True): # def send_system_message(recipient, subject, message_content): . Output only the next line.
tasks.send_message(self.pk, False)
Given the code snippet: <|code_start|> subscribed_email=True, user__unsubscribed=False ).exclude( user_id=message.sender_id ) # User.objects.filter(userthread__thread=message.thread) for userthread in userthreads: create_group_notification.delay(message.pk, userthread.pk) @shared_task() def create_group_notification(message_id, userthread_id): """Create a notification for a specific user""" # Import here to avoid circular import message = Message.objects.select_related('thread').get(pk=message_id) userthread = UserThread.objects.select_related('user').extra( select={ 'subscription_id': 'notifications_subscription.id', 'subscription_period': 'notifications_subscription.period' }, tables=['notifications_subscription'], where=[ 'notifications_subscription.user_id=accounts_user.id', 'notifications_subscription.group_id=%s' ], params=[message.thread.group_id] ).get(id=userthread_id) try: <|code_end|> , generate the next line using the imports in this file: from datetime import timedelta from email.utils import formataddr from celery import shared_task from django.conf import settings from django.db import IntegrityError from django.db.models import Q from django.utils.dateparse import parse_datetime from django.utils.timezone import now from django.utils.translation import ngettext from django.template.loader import render_to_string from open_connect.mailer.utils import send_email from open_connect.notifications.models import Notification from open_connect.connectmessages.models import Message, UserThread from open_connect.connectmessages.models import Message, UserThread from open_connect.connectmessages.models import Message from open_connect.accounts.models import User from open_connect.accounts.models import User from open_connect.accounts.models import User import logging and context (functions, classes, or occasionally code) from other files: # Path: open_connect/notifications/models.py # class Notification(TimestampModel): # """Information about an individual notification.""" # recipient = models.ForeignKey(settings.AUTH_USER_MODEL) # consumed = models.BooleanField(default=False, db_index=True) # subscription = models.ForeignKey(Subscription, blank=True, null=True) # message = models.ForeignKey('connectmessages.Message') # # class Meta(object): # """Meta options for Notification model.""" # # There should only ever be 1 notification per message # unique_together = ['recipient', 'message'] . Output only the next line.
notification = Notification.objects.create(
Based on the snippet: <|code_start|>"""Tests for visit tracking middleware.""" # pylint: disable=invalid-name User = get_user_model() middleware = list(settings.MIDDLEWARE_CLASSES) # pylint: disable=line-too-long if 'open_connect.middleware.visit_tracking.VisitTrackingMiddleware' not in middleware: middleware.insert( 0, 'open_connect.middleware.visit_tracking.VisitTrackingMiddleware') @override_settings(MIDDLEWARE_CLASSES=middleware) class VisitTrackingMiddlewareTest(ConnectTestMixin, TestCase): """Tests for visit tracking middleware.""" def test_no_user_attribute(self): """Test that a request without a user attr won't trigger an error""" user = mommy.make(User) request_factory = RequestFactory() visit_tracking_mw = VisitTrackingMiddleware() <|code_end|> , predict the immediate next line with the help of imports: from django.conf import settings from django.contrib.auth import get_user_model from django.core.urlresolvers import reverse from django.test import TestCase, RequestFactory from django.test.utils import override_settings from mock import Mock from model_mommy import mommy from open_connect.middleware.visit_tracking import VisitTrackingMiddleware from open_connect.accounts.models import Visit from open_connect.connect_core.utils.basetests import ConnectTestMixin and context (classes, functions, sometimes code) from other files: # Path: open_connect/accounts/models.py # class Visit(TimestampModel): # """Store information about a user's visits to the site.""" # user = models.ForeignKey(User, blank=True, null=True) # ip_address = models.GenericIPAddressField(blank=True, null=True) # user_agent = models.TextField(blank=True) . Output only the next line.
visit_count = Visit.objects.count()
Predict the next line for this snippet: <|code_start|> def set_exit(self): # TODO: docstring self.__exit = True def process_messages(self): # TODO: docstring if self._timeout is not None: self._fail_after = time.time() + self._timeout while not self.__exit: try: self.process_one_message() _trace('self.__exit is ', self.__exit) except Exception: if not self.__exit: raise # TODO: log the error? def process_one_message(self): # TODO: docstring try: msg = self.__message.pop(0) except IndexError: with convert_eof(): self._wait_for_message() try: msg = self.__message.pop(0) except IndexError: # No messages received. if self._fail_after is not None: if time.time() < self._fail_after: <|code_end|> with the help of current file imports: import errno import itertools import json import os import os.path import sys import time import traceback import thread import _thread as thread from socket import create_connection from .socket import TimeoutError, convert_eof from encodings import ascii and context from other files: # Path: PyDevRemoteDebug/ptvsd-4.1.3/ptvsd/socket.py # class TimeoutError(socket.timeout): # """A socket timeout happened.""" # # @contextlib.contextmanager # def convert_eof(): # """A context manager to convert some socket errors into EOFError.""" # try: # yield # except ConnectionResetError: # raise EOFError # except BrokenPipeError: # raise EOFError # except OSError as exc: # if exc.errno in EOF: # raise EOFError # raise , which may contain function names, class names, or code. Output only the next line.
raise TimeoutError('connection closed?')
Based on the snippet: <|code_start|> seq=next(self.__seq), request_seq=int(request.get('seq', 0)), success=success, command=request.get('command', ''), message=message or '', body=kwargs, ) def set_exit(self): # TODO: docstring self.__exit = True def process_messages(self): # TODO: docstring if self._timeout is not None: self._fail_after = time.time() + self._timeout while not self.__exit: try: self.process_one_message() _trace('self.__exit is ', self.__exit) except Exception: if not self.__exit: raise # TODO: log the error? def process_one_message(self): # TODO: docstring try: msg = self.__message.pop(0) except IndexError: <|code_end|> , predict the immediate next line with the help of imports: import errno import itertools import json import os import os.path import sys import time import traceback import thread import _thread as thread from socket import create_connection from .socket import TimeoutError, convert_eof from encodings import ascii and context (classes, functions, sometimes code) from other files: # Path: PyDevRemoteDebug/ptvsd-4.1.3/ptvsd/socket.py # class TimeoutError(socket.timeout): # """A socket timeout happened.""" # # @contextlib.contextmanager # def convert_eof(): # """A context manager to convert some socket errors into EOFError.""" # try: # yield # except ConnectionResetError: # raise EOFError # except BrokenPipeError: # raise EOFError # except OSError as exc: # if exc.errno in EOF: # raise EOFError # raise . Output only the next line.
with convert_eof():
Here is a snippet: <|code_start|> class DjangoFormStr(object): def can_provide(self, type_object, type_name): form_class = find_mod_attr('django.forms', 'Form') return form_class is not None and issubclass(type_object, form_class) def get_str(self, val): <|code_end|> . Write the next line using the current file imports: from _pydevd_bundle.pydevd_extension_api import StrPresentationProvider from .pydevd_helpers import find_mod_attr, find_class_name import sys and context from other files: # Path: PyDevRemoteDebug/ptvsd-4.1.3/ptvsd/_vendored/pydevd/pydevd_plugins/extensions/types/pydevd_helpers.py # def find_mod_attr(mod_name, attr): # mod = find_cached_module(mod_name) # if mod is None: # return None # return getattr(mod, attr, None) # # def find_class_name(val): # class_name = str(val.__class__) # if class_name.find('.') != -1: # class_name = class_name.split('.')[-1] # # elif class_name.find("'") != -1: #does not have '.' (could be something like <type 'int'>) # class_name = class_name[class_name.index("'") + 1:] # # if class_name.endswith("'>"): # class_name = class_name[:-2] # # return class_name , which may include functions, classes, or code. Output only the next line.
return '%s: %r' % (find_class_name(val), val)
Given the code snippet: <|code_start|> class SignatureTests(unittest.TestCase): maxDiff = None def assertSigsEqual(self, found, expected, *args, **kwargs): conv = kwargs.pop('conv_first_posarg', False) if expected != found: if conv: expected = conv_first_posarg(expected) found = conv_first_posarg(found) if expected == found: return raise AssertionError( 'Did not get expected signature({0}), got {1} instead.' .format(expected, found)) def assertSourcesEqual(self, found, expected, func=None, depth_order=False): r = transform_real_sources(found) e = transform_exp_sources(expected, func) if depth_order: rd = r.pop('+depths') ed = e.pop('+depths') self.assertEqual(r, e) if depth_order: self.assertEqual( [f for f in sorted(rd, key=rd.get) if f in ed], [f for f in sorted(ed, key=ed.get)]) def downgrade_sig(self, sig): <|code_end|> , generate the next line using the imports in this file: from collections import defaultdict from functools import partial from repeated_test import tup, WithTestClass from sigtools._util import funcsigs import unittest and context (functions, classes, or occasionally code) from other files: # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() . Output only the next line.
return funcsigs.Signature(
Based on the snippet: <|code_start|>`sphinx.ext.autodoc` can only automatically discover the signatures of basic callables. This extension makes it use `sigtools.specifiers.signature` on the callable instead. Enable it by appending ``'sigtools.sphinxext'`` to the ``extensions`` list in your Sphinx ``conf.py`` """ class _cls(object): def method(self): raise NotImplementedError instancemethod = type(_cls().method) del _cls def process_signature(app, what, name, obj, options, sig, return_annotation): try: parent, obj = fetch_dotted_name(name) except AttributeError: return sig, return_annotation if isinstance(obj, instancemethod): # python 2 unbound methods obj = obj.__func__ if isinstance(parent, type) and callable(obj): obj = _util.safe_get(obj, object(), type(parent)) try: <|code_end|> , predict the immediate next line with the help of imports: from sphinx.ext import autodoc from sigtools import specifiers, _util and context (classes, functions, sometimes code) from other files: # Path: sigtools/specifiers.py # class _AsForged(object): # class _ForgerWrapper(object): # def __init__(self): # def __get__(self, instance, owner): # def set_signature_forger(obj, forger, emulate=None): # def _transform(obj, meta): # def __init__(self, obj, forger): # def _sigtools__forger(self, obj): # def __call__(self, *args, **kwargs): # def __get__(self, instance, owner): # def forger_function(func): # def _apply_forger(emulate=None, *args, **kwargs): # def _applier(obj): # def forwards(wrapper, wrapped, *args, **kwargs): # def forwards_to_function(obj, *args, **kwargs): # def forwards_to_method(obj, wrapped_name, *args, **kwargs): # def _get_origin_class(obj, cls): # def forwards_to_super(obj, cls=None, *args, **kwargs): # def apply_forwards_to_super(num_args=0, named_args=(), *member_names, # **kwargs): # def _apply_forwards_to_super(member_names, m_args, m_kwargs, cls): # # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() . Output only the next line.
sig = specifiers.signature(obj)
Next line prediction: <|code_start|>-------------------------------------------------------------------- `sphinx.ext.autodoc` can only automatically discover the signatures of basic callables. This extension makes it use `sigtools.specifiers.signature` on the callable instead. Enable it by appending ``'sigtools.sphinxext'`` to the ``extensions`` list in your Sphinx ``conf.py`` """ class _cls(object): def method(self): raise NotImplementedError instancemethod = type(_cls().method) del _cls def process_signature(app, what, name, obj, options, sig, return_annotation): try: parent, obj = fetch_dotted_name(name) except AttributeError: return sig, return_annotation if isinstance(obj, instancemethod): # python 2 unbound methods obj = obj.__func__ if isinstance(parent, type) and callable(obj): <|code_end|> . Use current file imports: (from sphinx.ext import autodoc from sigtools import specifiers, _util) and context including class names, function names, or small code snippets from other files: # Path: sigtools/specifiers.py # class _AsForged(object): # class _ForgerWrapper(object): # def __init__(self): # def __get__(self, instance, owner): # def set_signature_forger(obj, forger, emulate=None): # def _transform(obj, meta): # def __init__(self, obj, forger): # def _sigtools__forger(self, obj): # def __call__(self, *args, **kwargs): # def __get__(self, instance, owner): # def forger_function(func): # def _apply_forger(emulate=None, *args, **kwargs): # def _applier(obj): # def forwards(wrapper, wrapped, *args, **kwargs): # def forwards_to_function(obj, *args, **kwargs): # def forwards_to_method(obj, wrapped_name, *args, **kwargs): # def _get_origin_class(obj, cls): # def forwards_to_super(obj, cls=None, *args, **kwargs): # def apply_forwards_to_super(num_args=0, named_args=(), *member_names, # **kwargs): # def _apply_forwards_to_super(member_names, m_args, m_kwargs, cls): # # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() . Output only the next line.
obj = _util.safe_get(obj, object(), type(parent))
Continue the code snippet: <|code_start|># Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. class EmbedTests(Fixtures): def _test(self, result, exp_src, signatures, use_varargs=True, use_varkwargs=True): assert len(signatures) >= 2 sigs = [s(sig_str, name='_' + str(i)) for i, sig_str in enumerate(signatures, 1)] exp_src.setdefault( '+depths', ['_' + str(i+1) for i in range(len(signatures))]) <|code_end|> . Use current file imports: from sigtools.signatures import embed, IncompatibleSignatures from sigtools.support import s from sigtools.tests.util import Fixtures and context (classes, functions, or code) from other files: # Path: sigtools/signatures.py # # Path: sigtools/support.py # def s(*args, **kwargs): # """Creates a signature from the given string representation of one. # # .. warning:: # The contents of the arguments are eventually passed to `exec`. # Do not use with untrusted input. # # :: # # >>> from sigtools.support import s # >>> sig = s('a, b=2, *args, c:"annotation", **kwargs') # >>> sig # <inspect.Signature object at 0x7f15e6055550> # >>> print(sig) # (a, b=2, *args, c:'annotation', **kwargs) # """ # return specifiers.signature(f(*args, **kwargs)) # # Path: sigtools/tests/util.py # def conv_first_posarg(sig): # def func_to_name(func): # def transform_exp_sources(d, subject=None): # def transform_real_sources(d): # def assertSigsEqual(self, found, expected, *args, **kwargs): # def assertSourcesEqual(self, found, expected, func=None, depth_order=False): # def downgrade_sig(self, sig): # class SignatureTests(unittest.TestCase): . Output only the next line.
sig = embed(*sigs, use_varargs=use_varargs, use_varkwargs=use_varkwargs)
Using the snippet: <|code_start|> conv_pok_pos = '<a>', {2: 'a'}, ['*args', 'a'] conv_pok_kwo = '*, a', {2: 'a'}, ['**kwargs', 'a'] three = ( 'a, b, c', {1: 'a', 2: 'b', 3: 'c'}, ['a, *args, **kwargs', 'b, *args, **kwargs', 'c']) dont_use_varargs = ( 'a, *p, b', {1: 'ap', 2: 'b'}, ['a, *p, **k', 'b'], False) dont_use_varkwargs = ( 'a, b, /, **k', {1: 'ak', 2: 'b'}, ['a, *p, **k', 'b'], True, False) dont_use_either_empty = ( 'a, *p, **k', {1: 'apk'}, ['a, *p, **k', ''], False, False) outer_default = ( 'a, b, c, d, e, f', {1: 'abc', 2: 'def'}, ['a, b, c=0, *args, **kwargs', 'd, e, f']) outer_default_pos = ( 'a, b, c, /, d, e, f', {1: 'abc', 2: 'def'}, ['a, b, c=0, /, *args, **kwargs', 'd, e, f']) outer_default_inner_pos = ( 'a, b, c, d, /, e, f', {1: 'abc', 2: 'def'}, ['a, b, c=0, /, *args, **kwargs', 'd, /, e, f']) class EmbedRaisesTests(Fixtures): def _test(self, signatures, use_varargs=True, use_varkwargs=True): assert len(signatures) >= 2 sigs = [s(sig) for sig in signatures] <|code_end|> , determine the next line of code. You have imports: from sigtools.signatures import embed, IncompatibleSignatures from sigtools.support import s from sigtools.tests.util import Fixtures and context (class names, function names, or code) available: # Path: sigtools/signatures.py # # Path: sigtools/support.py # def s(*args, **kwargs): # """Creates a signature from the given string representation of one. # # .. warning:: # The contents of the arguments are eventually passed to `exec`. # Do not use with untrusted input. # # :: # # >>> from sigtools.support import s # >>> sig = s('a, b=2, *args, c:"annotation", **kwargs') # >>> sig # <inspect.Signature object at 0x7f15e6055550> # >>> print(sig) # (a, b=2, *args, c:'annotation', **kwargs) # """ # return specifiers.signature(f(*args, **kwargs)) # # Path: sigtools/tests/util.py # def conv_first_posarg(sig): # def func_to_name(func): # def transform_exp_sources(d, subject=None): # def transform_real_sources(d): # def assertSigsEqual(self, found, expected, *args, **kwargs): # def assertSourcesEqual(self, found, expected, func=None, depth_order=False): # def downgrade_sig(self, sig): # class SignatureTests(unittest.TestCase): . Output only the next line.
with self.assertRaises(IncompatibleSignatures):
Given snippet: <|code_start|>#!/usr/bin/env python # sigtools - Collection of Python modules for manipulating function signatures # Copyright (C) 2013-2021 Yann Kaiser # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. class EmbedTests(Fixtures): def _test(self, result, exp_src, signatures, use_varargs=True, use_varkwargs=True): assert len(signatures) >= 2 <|code_end|> , continue by predicting the next line. Consider current file imports: from sigtools.signatures import embed, IncompatibleSignatures from sigtools.support import s from sigtools.tests.util import Fixtures and context: # Path: sigtools/signatures.py # # Path: sigtools/support.py # def s(*args, **kwargs): # """Creates a signature from the given string representation of one. # # .. warning:: # The contents of the arguments are eventually passed to `exec`. # Do not use with untrusted input. # # :: # # >>> from sigtools.support import s # >>> sig = s('a, b=2, *args, c:"annotation", **kwargs') # >>> sig # <inspect.Signature object at 0x7f15e6055550> # >>> print(sig) # (a, b=2, *args, c:'annotation', **kwargs) # """ # return specifiers.signature(f(*args, **kwargs)) # # Path: sigtools/tests/util.py # def conv_first_posarg(sig): # def func_to_name(func): # def transform_exp_sources(d, subject=None): # def transform_real_sources(d): # def assertSigsEqual(self, found, expected, *args, **kwargs): # def assertSourcesEqual(self, found, expected, func=None, depth_order=False): # def downgrade_sig(self, sig): # class SignatureTests(unittest.TestCase): which might include code, classes, or functions. Output only the next line.
sigs = [s(sig_str, name='_' + str(i))
Based on the snippet: <|code_start|> @wraps(func) def _decorate(decorated): return _SimpleWrapped(func, decorated) return _decorate class _SimpleWrapped(object): def __init__(self, wrapper, wrapped): update_wrapper(self, wrapped) self.func = partial(wrapper, wrapped) self.wrapper = wrapper self._sigtools__wrappers = wrapper, self.__wrapped__ = wrapped try: del self._sigtools__forger except AttributeError: pass try: del self.__signature__ except AttributeError: pass __signature__ = specifiers.as_forged def __call__(self, *args, **kwargs): return self.func(*args, **kwargs) def __get__(self, instance, owner): return type(self)( self.wrapper, <|code_end|> , predict the immediate next line with the help of imports: from functools import partial, update_wrapper, wraps from sigtools import _util, signatures, specifiers and context (classes, functions, sometimes code) from other files: # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() # # Path: sigtools/signatures.py # # Path: sigtools/specifiers.py # class _AsForged(object): # class _ForgerWrapper(object): # def __init__(self): # def __get__(self, instance, owner): # def set_signature_forger(obj, forger, emulate=None): # def _transform(obj, meta): # def __init__(self, obj, forger): # def _sigtools__forger(self, obj): # def __call__(self, *args, **kwargs): # def __get__(self, instance, owner): # def forger_function(func): # def _apply_forger(emulate=None, *args, **kwargs): # def _applier(obj): # def forwards(wrapper, wrapped, *args, **kwargs): # def forwards_to_function(obj, *args, **kwargs): # def forwards_to_method(obj, wrapped_name, *args, **kwargs): # def _get_origin_class(obj, cls): # def forwards_to_super(obj, cls=None, *args, **kwargs): # def apply_forwards_to_super(num_args=0, named_args=(), *member_names, # **kwargs): # def _apply_forwards_to_super(member_names, m_args, m_kwargs, cls): . Output only the next line.
_util.safe_get(self.__wrapped__, instance, owner))
Given snippet: <|code_start|>`sigtools.wrappers`: Combine multiple functions ----------------------------------------------- The functions here help you combine multiple functions into a new callable which will automatically advertise the correct signature. """ class Combination(object): """Creates a callable that passes the first argument through each callable, using the result of each pass as the argument to the next """ def __init__(self, *functions): funcs = self.functions = [] for function in functions: if isinstance(function, Combination): funcs.extend(function.functions) else: funcs.append(function) specifiers.set_signature_forger(self, self.get_signature, emulate=False) def __call__(self, arg, *args, **kwargs): for function in self.functions: arg = function(arg, *args, **kwargs) return arg def get_signature(self, obj): <|code_end|> , continue by predicting the next line. Consider current file imports: from functools import partial, update_wrapper, wraps from sigtools import _util, signatures, specifiers and context: # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() # # Path: sigtools/signatures.py # # Path: sigtools/specifiers.py # class _AsForged(object): # class _ForgerWrapper(object): # def __init__(self): # def __get__(self, instance, owner): # def set_signature_forger(obj, forger, emulate=None): # def _transform(obj, meta): # def __init__(self, obj, forger): # def _sigtools__forger(self, obj): # def __call__(self, *args, **kwargs): # def __get__(self, instance, owner): # def forger_function(func): # def _apply_forger(emulate=None, *args, **kwargs): # def _applier(obj): # def forwards(wrapper, wrapped, *args, **kwargs): # def forwards_to_function(obj, *args, **kwargs): # def forwards_to_method(obj, wrapped_name, *args, **kwargs): # def _get_origin_class(obj, cls): # def forwards_to_super(obj, cls=None, *args, **kwargs): # def apply_forwards_to_super(num_args=0, named_args=(), *member_names, # **kwargs): # def _apply_forwards_to_super(member_names, m_args, m_kwargs, cls): which might include code, classes, or functions. Output only the next line.
return signatures.merge(
Next line prediction: <|code_start|># THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """ `sigtools.wrappers`: Combine multiple functions ----------------------------------------------- The functions here help you combine multiple functions into a new callable which will automatically advertise the correct signature. """ class Combination(object): """Creates a callable that passes the first argument through each callable, using the result of each pass as the argument to the next """ def __init__(self, *functions): funcs = self.functions = [] for function in functions: if isinstance(function, Combination): funcs.extend(function.functions) else: funcs.append(function) <|code_end|> . Use current file imports: (from functools import partial, update_wrapper, wraps from sigtools import _util, signatures, specifiers) and context including class names, function names, or small code snippets from other files: # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() # # Path: sigtools/signatures.py # # Path: sigtools/specifiers.py # class _AsForged(object): # class _ForgerWrapper(object): # def __init__(self): # def __get__(self, instance, owner): # def set_signature_forger(obj, forger, emulate=None): # def _transform(obj, meta): # def __init__(self, obj, forger): # def _sigtools__forger(self, obj): # def __call__(self, *args, **kwargs): # def __get__(self, instance, owner): # def forger_function(func): # def _apply_forger(emulate=None, *args, **kwargs): # def _applier(obj): # def forwards(wrapper, wrapped, *args, **kwargs): # def forwards_to_function(obj, *args, **kwargs): # def forwards_to_method(obj, wrapped_name, *args, **kwargs): # def _get_origin_class(obj, cls): # def forwards_to_super(obj, cls=None, *args, **kwargs): # def apply_forwards_to_super(num_args=0, named_args=(), *member_names, # **kwargs): # def _apply_forwards_to_super(member_names, m_args, m_kwargs, cls): . Output only the next line.
specifiers.set_signature_forger(self, self.get_signature,
Predict the next line for this snippet: <|code_start|># sigtools - Collection of Python modules for manipulating function signatures # Copyright (C) 2013-2021 Yann Kaiser # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. try: zip_longest = itertools.izip_longest except AttributeError: # pragma: no cover zip_longest = itertools.zip_longest <|code_end|> with the help of current file imports: import itertools import collections from functools import partial from sigtools import _util and context from other files: # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() , which may contain function names, class names, or code. Output only the next line.
class Signature(_util.funcsigs.Signature):
Given the following code snippet before the placeholder: <|code_start|># of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. class ForwardsTests(Fixtures): def _test(self, exp_sig, exp_src, outer, inner, num_args=0, named_args=(), hide_args=False, hide_kwargs=False, use_varargs=True, use_varkwargs=True, partial=False): outer_sig = s(outer, name='o') inner_sig = s(inner, name='i') <|code_end|> , predict the next line using imports from the current file: from sigtools.signatures import forwards from sigtools.support import s from sigtools.tests.util import Fixtures and context including class names, function names, and sometimes code from other files: # Path: sigtools/signatures.py # # Path: sigtools/support.py # def s(*args, **kwargs): # """Creates a signature from the given string representation of one. # # .. warning:: # The contents of the arguments are eventually passed to `exec`. # Do not use with untrusted input. # # :: # # >>> from sigtools.support import s # >>> sig = s('a, b=2, *args, c:"annotation", **kwargs') # >>> sig # <inspect.Signature object at 0x7f15e6055550> # >>> print(sig) # (a, b=2, *args, c:'annotation', **kwargs) # """ # return specifiers.signature(f(*args, **kwargs)) # # Path: sigtools/tests/util.py # def conv_first_posarg(sig): # def func_to_name(func): # def transform_exp_sources(d, subject=None): # def transform_real_sources(d): # def assertSigsEqual(self, found, expected, *args, **kwargs): # def assertSourcesEqual(self, found, expected, func=None, depth_order=False): # def downgrade_sig(self, sig): # class SignatureTests(unittest.TestCase): . Output only the next line.
sig = forwards(
Using the snippet: <|code_start|># Copyright (C) 2013-2021 Yann Kaiser # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. class ForwardsTests(Fixtures): def _test(self, exp_sig, exp_src, outer, inner, num_args=0, named_args=(), hide_args=False, hide_kwargs=False, use_varargs=True, use_varkwargs=True, partial=False): <|code_end|> , determine the next line of code. You have imports: from sigtools.signatures import forwards from sigtools.support import s from sigtools.tests.util import Fixtures and context (class names, function names, or code) available: # Path: sigtools/signatures.py # # Path: sigtools/support.py # def s(*args, **kwargs): # """Creates a signature from the given string representation of one. # # .. warning:: # The contents of the arguments are eventually passed to `exec`. # Do not use with untrusted input. # # :: # # >>> from sigtools.support import s # >>> sig = s('a, b=2, *args, c:"annotation", **kwargs') # >>> sig # <inspect.Signature object at 0x7f15e6055550> # >>> print(sig) # (a, b=2, *args, c:'annotation', **kwargs) # """ # return specifiers.signature(f(*args, **kwargs)) # # Path: sigtools/tests/util.py # def conv_first_posarg(sig): # def func_to_name(func): # def transform_exp_sources(d, subject=None): # def transform_real_sources(d): # def assertSigsEqual(self, found, expected, *args, **kwargs): # def assertSourcesEqual(self, found, expected, func=None, depth_order=False): # def downgrade_sig(self, sig): # class SignatureTests(unittest.TestCase): . Output only the next line.
outer_sig = s(outer, name='o')
Continue the code snippet: <|code_start|># sigtools - Collection of Python modules for manipulating function signatures # Copyright (C) 2013-2021 Yann Kaiser # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. class MaskTests(Fixtures): def _test(self, expected_str, sig_str, num_args=0, named_args=(), hide_varargs=False, hide_varkwargs=False, hide_args=False, hide_kwargs=False): expected_sig = support.s(expected_str) <|code_end|> . Use current file imports: from sigtools import signatures, support from sigtools._util import funcsigs from sigtools.tests.util import Fixtures and context (classes, functions, or code) from other files: # Path: sigtools/signatures.py # # Path: sigtools/support.py # def read_sig(sig_str, ret=_util.UNSET, *, # use_modifiers_annotate=False, # use_modifiers_posoargs=sys.version_info < (3, 8), # use_modifiers_kwoargs=False, # ): # def func_code(names, return_annotation, annotations, posoarg_n, # kwoarg_n, params, use_modifiers_annotate, # pre='', name='func', # ): # def make_func(source, locals=None, name='func', future_features=()): # def f(sig_str, ret=_util.UNSET, *, pre='', locals=None, name='func', future_features=(), **kwargs): # def s(*args, **kwargs): # def func_from_sig(sig): # def make_up_callsigs(sig, extra=2): # def bind_callsig(sig, args, kwargs): # def sort_callsigs(sig, callsigs): # def test_func_sig_coherent(func, check_return=True, check_invalid=True): # DEBUG_STDLIB=False # # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() # # Path: sigtools/tests/util.py # def conv_first_posarg(sig): # def func_to_name(func): # def transform_exp_sources(d, subject=None): # def transform_real_sources(d): # def assertSigsEqual(self, found, expected, *args, **kwargs): # def assertSourcesEqual(self, found, expected, func=None, depth_order=False): # def downgrade_sig(self, sig): # class SignatureTests(unittest.TestCase): . Output only the next line.
sig = signatures.mask(
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python # sigtools - Collection of Python modules for manipulating function signatures # Copyright (C) 2013-2021 Yann Kaiser # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. class MaskTests(Fixtures): def _test(self, expected_str, sig_str, num_args=0, named_args=(), hide_varargs=False, hide_varkwargs=False, hide_args=False, hide_kwargs=False): <|code_end|> using the current file's imports: from sigtools import signatures, support from sigtools._util import funcsigs from sigtools.tests.util import Fixtures and any relevant context from other files: # Path: sigtools/signatures.py # # Path: sigtools/support.py # def read_sig(sig_str, ret=_util.UNSET, *, # use_modifiers_annotate=False, # use_modifiers_posoargs=sys.version_info < (3, 8), # use_modifiers_kwoargs=False, # ): # def func_code(names, return_annotation, annotations, posoarg_n, # kwoarg_n, params, use_modifiers_annotate, # pre='', name='func', # ): # def make_func(source, locals=None, name='func', future_features=()): # def f(sig_str, ret=_util.UNSET, *, pre='', locals=None, name='func', future_features=(), **kwargs): # def s(*args, **kwargs): # def func_from_sig(sig): # def make_up_callsigs(sig, extra=2): # def bind_callsig(sig, args, kwargs): # def sort_callsigs(sig, callsigs): # def test_func_sig_coherent(func, check_return=True, check_invalid=True): # DEBUG_STDLIB=False # # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() # # Path: sigtools/tests/util.py # def conv_first_posarg(sig): # def func_to_name(func): # def transform_exp_sources(d, subject=None): # def transform_real_sources(d): # def assertSigsEqual(self, found, expected, *args, **kwargs): # def assertSourcesEqual(self, found, expected, func=None, depth_order=False): # def downgrade_sig(self, sig): # class SignatureTests(unittest.TestCase): . Output only the next line.
expected_sig = support.s(expected_str)
Using the snippet: <|code_start|># The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. class MaskTests(Fixtures): def _test(self, expected_str, sig_str, num_args=0, named_args=(), hide_varargs=False, hide_varkwargs=False, hide_args=False, hide_kwargs=False): expected_sig = support.s(expected_str) sig = signatures.mask( support.s(sig_str), num_args, *named_args, hide_varargs=hide_varargs, hide_varkwargs=hide_varkwargs, hide_args=hide_args, hide_kwargs=hide_kwargs) self.assertSigsEqual(sig, expected_sig) expected_src = {'func': expected_sig.parameters} self.assertSourcesEqual(sig.sources, expected_src, func='func') in_sig = support.s(sig_str) <|code_end|> , determine the next line of code. You have imports: from sigtools import signatures, support from sigtools._util import funcsigs from sigtools.tests.util import Fixtures and context (class names, function names, or code) available: # Path: sigtools/signatures.py # # Path: sigtools/support.py # def read_sig(sig_str, ret=_util.UNSET, *, # use_modifiers_annotate=False, # use_modifiers_posoargs=sys.version_info < (3, 8), # use_modifiers_kwoargs=False, # ): # def func_code(names, return_annotation, annotations, posoarg_n, # kwoarg_n, params, use_modifiers_annotate, # pre='', name='func', # ): # def make_func(source, locals=None, name='func', future_features=()): # def f(sig_str, ret=_util.UNSET, *, pre='', locals=None, name='func', future_features=(), **kwargs): # def s(*args, **kwargs): # def func_from_sig(sig): # def make_up_callsigs(sig, extra=2): # def bind_callsig(sig, args, kwargs): # def sort_callsigs(sig, callsigs): # def test_func_sig_coherent(func, check_return=True, check_invalid=True): # DEBUG_STDLIB=False # # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() # # Path: sigtools/tests/util.py # def conv_first_posarg(sig): # def func_to_name(func): # def transform_exp_sources(d, subject=None): # def transform_real_sources(d): # def assertSigsEqual(self, found, expected, *args, **kwargs): # def assertSourcesEqual(self, found, expected, func=None, depth_order=False): # def downgrade_sig(self, sig): # class SignatureTests(unittest.TestCase): . Output only the next line.
in_sig = funcsigs.Signature(in_sig.parameters.values(),
Predict the next line after this snippet: <|code_start|># # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. app = object() class SphinxExtTests(unittest.TestCase): def setUp(self): try: except SyntaxError: # sphinx does not work on py32 raise unittest.SkipTest("Sphinx could not be imported.") else: self.sphinxext = sphinxext def test_forge(self): r = self.sphinxext.process_signature( app, 'function', 'sigtools.tests.sphinxextfixt.outer', <|code_end|> using the current file's imports: import unittest from sigtools.tests import sphinxextfixt from sigtools import sphinxext and any relevant context from other files: # Path: sigtools/tests/sphinxextfixt.py # def inner(a, b): # def __init__(self): # def outer(self, c, *args, **kwargs): # def kwo(a, b, c=1, d=2): # def outer(c, *args, **kwargs): # class AClass(object): . Output only the next line.
sphinxextfixt.outer, {}, '(c, *args, **kwargs)', None)
Continue the code snippet: <|code_start|># furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """ `sigtools.modifiers`: Modify the effective signature of the decorated callable ------------------------------------------------------------------------------ The functions in this module can be used as decorators to mark and enforce some parameters to be keyword-only (`kwoargs`) or annotate (`annotate`) them, just like you can :ref:`using Python 3 syntax <def>`. You can also mark and enforce parameters to be positional-only (`posoargs`). `autokwoargs` helps you quickly make your parameters with default values become keyword-only. """ __all__ = ['annotate', 'kwoargs', 'autokwoargs', 'posoargs'] <|code_end|> . Use current file imports: from functools import partial, update_wrapper from sigtools import _util, _specifiers, _signatures from sigtools import wrappers and context (classes, functions, or code) from other files: # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() # # Path: sigtools/_specifiers.py # def forged_signature(obj, auto=True, args=(), kwargs={}): # # Path: sigtools/_signatures.py # class Signature(_util.funcsigs.Signature): # class IncompatibleSignatures(ValueError): # class _Merger(object): # def __init__(self, *args, **kwargs): # def upgrade(cls, inst, sources): # def replace(self, *args, **kwargs): # def default_sources(sig, obj): # def set_default_sources(sig, obj): # def signature(obj): # def copy_sources(src, func_swap={}, increase=False): # def sort_params(sig, sources=False): # def apply_params(sig, posargs, pokargs, varargs, kwoargs, varkwargs, # sources=None): # def __init__(self, sig, others): # def __str__(self): # def _add_sources(ret_src, name, *from_sources): # def _add_all_sources(ret_src, params, from_source): # def _exclude_from_seq(seq, el): # def merge_depths(l, r): # def __init__(self, left, right): # def perform_once(self): # def __iter__(self): # def _merge(self): # def _merge_depths(self): # def _add_starargs(self, which, left, right): # def _merge_unbalanced_pos(self, existing, src, # convert_from, o_varargs, o_src): # def _merge_unbalanced_pok( # self, existing, src, # o_varargs, o_varkwargs, o_kwargs_limbo, o_src): # def _merge_unmatched_kwoargs(self, unmatched_kwoargs, o_varkwargs, from_src): # def _concile_meta(self, left, right): # def merge(*signatures): # def _check_no_dupes(collect, params): # def _clear_defaults(ita): # def _embed(outer, inner, use_varargs=True, use_varkwargs=True, depth=1): # def embed(use_varargs=True, use_varkwargs=True, *signatures): # def _pop_chain(*sequences): # def _remove_from_src(src, ita): # def _pnames(ita): # def _mask(sig, num_args, hide_args, hide_kwargs, # hide_varargs, hide_varkwargs, named_args, partial_obj): # def mask(sig, num_args=0, # hide_args=False, hide_kwargs=False, # hide_varargs=False, hide_varkwargs=False, # *named_args): # def forwards(outer, inner, num_args=0, # hide_args=False, hide_kwargs=False, # use_varargs=True, use_varkwargs=True, # partial=False, *named_args): . Output only the next line.
class _PokTranslator(_util.OverrideableDataDesc):
Here is a snippet: <|code_start|> except AttributeError: pass try: del self._sigtools__forger except AttributeError: pass super(_PokTranslator, self).__init__(**kwargs) self.func = func self.posoarg_names = set(posoargs) self.kwoarg_names = set(kwoargs) if isinstance(func, _PokTranslator): self._merge_other(func) self._prepare() def _merge_other(self, other): self.func = other.func self.posoarg_names |= other.posoarg_names self.kwoarg_names |= other.kwoarg_names self.custom_getter = wrappers.Combination( self.custom_getter, other.custom_getter) def _prepare(self): intersection = self.posoarg_names & self.kwoarg_names if intersection: raise ValueError( 'Parameters marked as both positional-only and keyword-only: ' + ' '.join(repr(name) for name in intersection)) to_use = self.posoarg_names | self.kwoarg_names <|code_end|> . Write the next line using the current file imports: from functools import partial, update_wrapper from sigtools import _util, _specifiers, _signatures from sigtools import wrappers and context from other files: # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() # # Path: sigtools/_specifiers.py # def forged_signature(obj, auto=True, args=(), kwargs={}): # # Path: sigtools/_signatures.py # class Signature(_util.funcsigs.Signature): # class IncompatibleSignatures(ValueError): # class _Merger(object): # def __init__(self, *args, **kwargs): # def upgrade(cls, inst, sources): # def replace(self, *args, **kwargs): # def default_sources(sig, obj): # def set_default_sources(sig, obj): # def signature(obj): # def copy_sources(src, func_swap={}, increase=False): # def sort_params(sig, sources=False): # def apply_params(sig, posargs, pokargs, varargs, kwoargs, varkwargs, # sources=None): # def __init__(self, sig, others): # def __str__(self): # def _add_sources(ret_src, name, *from_sources): # def _add_all_sources(ret_src, params, from_source): # def _exclude_from_seq(seq, el): # def merge_depths(l, r): # def __init__(self, left, right): # def perform_once(self): # def __iter__(self): # def _merge(self): # def _merge_depths(self): # def _add_starargs(self, which, left, right): # def _merge_unbalanced_pos(self, existing, src, # convert_from, o_varargs, o_src): # def _merge_unbalanced_pok( # self, existing, src, # o_varargs, o_varkwargs, o_kwargs_limbo, o_src): # def _merge_unmatched_kwoargs(self, unmatched_kwoargs, o_varkwargs, from_src): # def _concile_meta(self, left, right): # def merge(*signatures): # def _check_no_dupes(collect, params): # def _clear_defaults(ita): # def _embed(outer, inner, use_varargs=True, use_varkwargs=True, depth=1): # def embed(use_varargs=True, use_varkwargs=True, *signatures): # def _pop_chain(*sequences): # def _remove_from_src(src, ita): # def _pnames(ita): # def _mask(sig, num_args, hide_args, hide_kwargs, # hide_varargs, hide_varkwargs, named_args, partial_obj): # def mask(sig, num_args=0, # hide_args=False, hide_kwargs=False, # hide_varargs=False, hide_varkwargs=False, # *named_args): # def forwards(outer, inner, num_args=0, # hide_args=False, hide_kwargs=False, # use_varargs=True, use_varkwargs=True, # partial=False, *named_args): , which may include functions, classes, or code. Output only the next line.
sig = _specifiers.forged_signature(self.func, auto=False)
Based on the snippet: <|code_start|> param.replace(kind=param.POSITIONAL_ONLY)) to_use.remove(param.name) elif param.name in self.kwoarg_names: kwoparams.append( param.replace(kind=param.KEYWORD_ONLY)) kwopos.append((i, param)) to_use.remove(param.name) else: found_pok = True params.append(param) else: # not a POK param if param.name in to_use: if param.kind == param.POSITIONAL_ONLY and param.name in self.posoarg_names: to_use.remove(param.name) elif param.kind == param.KEYWORD_ONLY and param.name in self.kwoarg_names: to_use.remove(param.name) else: raise ValueError( '{0.name!r} is not of kind POSITIONAL_OR_KEYWORD, but:' ' {0.kind}'.format(param)) if param.kind == param.VAR_KEYWORD: found_kws = True params.extend(kwoparams) params.append(param) if not found_kws: params.extend(kwoparams) if to_use: raise ValueError("Parameters not found: " + ' '.join(to_use)) self.__signature__ = sig.replace( parameters=params, <|code_end|> , predict the immediate next line with the help of imports: from functools import partial, update_wrapper from sigtools import _util, _specifiers, _signatures from sigtools import wrappers and context (classes, functions, sometimes code) from other files: # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() # # Path: sigtools/_specifiers.py # def forged_signature(obj, auto=True, args=(), kwargs={}): # # Path: sigtools/_signatures.py # class Signature(_util.funcsigs.Signature): # class IncompatibleSignatures(ValueError): # class _Merger(object): # def __init__(self, *args, **kwargs): # def upgrade(cls, inst, sources): # def replace(self, *args, **kwargs): # def default_sources(sig, obj): # def set_default_sources(sig, obj): # def signature(obj): # def copy_sources(src, func_swap={}, increase=False): # def sort_params(sig, sources=False): # def apply_params(sig, posargs, pokargs, varargs, kwoargs, varkwargs, # sources=None): # def __init__(self, sig, others): # def __str__(self): # def _add_sources(ret_src, name, *from_sources): # def _add_all_sources(ret_src, params, from_source): # def _exclude_from_seq(seq, el): # def merge_depths(l, r): # def __init__(self, left, right): # def perform_once(self): # def __iter__(self): # def _merge(self): # def _merge_depths(self): # def _add_starargs(self, which, left, right): # def _merge_unbalanced_pos(self, existing, src, # convert_from, o_varargs, o_src): # def _merge_unbalanced_pok( # self, existing, src, # o_varargs, o_varkwargs, o_kwargs_limbo, o_src): # def _merge_unmatched_kwoargs(self, unmatched_kwoargs, o_varkwargs, from_src): # def _concile_meta(self, left, right): # def merge(*signatures): # def _check_no_dupes(collect, params): # def _clear_defaults(ita): # def _embed(outer, inner, use_varargs=True, use_varkwargs=True, depth=1): # def embed(use_varargs=True, use_varkwargs=True, *signatures): # def _pop_chain(*sequences): # def _remove_from_src(src, ita): # def _pnames(ita): # def _mask(sig, num_args, hide_args, hide_kwargs, # hide_varargs, hide_varkwargs, named_args, partial_obj): # def mask(sig, num_args=0, # hide_args=False, hide_kwargs=False, # hide_varargs=False, hide_varkwargs=False, # *named_args): # def forwards(outer, inner, num_args=0, # hide_args=False, hide_kwargs=False, # use_varargs=True, use_varkwargs=True, # partial=False, *named_args): . Output only the next line.
sources=_signatures.copy_sources(sig.sources, {self.func:self}))
Given the code snippet: <|code_start|># AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. class UtilTests(unittest.TestCase): def test_conv_first_posarg(self): self.assertEqual(s(''), tutil.conv_first_posarg(s(''))) self.assertEqual( s('one, /, two, *three, four, **five'), tutil.conv_first_posarg(s('one, two, *three, four, **five'))) class TransformExpectedSourcesTests(unittest.TestCase): def test_empty(self): self.assertEqual(tutil.transform_exp_sources({}), {'+depths': {}}) def test_tf(self): self.assertEqual( tutil.transform_exp_sources({'func': 'abc', 'func2': 'def'}), { 'a': ['func'], 'b': ['func'], 'c': ['func'], 'd': ['func2'], 'e': ['func2'], 'f': ['func2'], '+depths': {'func': 0, 'func2': 1} }) def test_order(self): self.assertEqual( <|code_end|> , generate the next line using the imports in this file: import unittest from sigtools._util import OrderedDict as od from sigtools.support import s from sigtools.tests import util as tutil and context (functions, classes, or occasionally code) from other files: # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() # # Path: sigtools/support.py # def s(*args, **kwargs): # """Creates a signature from the given string representation of one. # # .. warning:: # The contents of the arguments are eventually passed to `exec`. # Do not use with untrusted input. # # :: # # >>> from sigtools.support import s # >>> sig = s('a, b=2, *args, c:"annotation", **kwargs') # >>> sig # <inspect.Signature object at 0x7f15e6055550> # >>> print(sig) # (a, b=2, *args, c:'annotation', **kwargs) # """ # return specifiers.signature(f(*args, **kwargs)) # # Path: sigtools/tests/util.py # def conv_first_posarg(sig): # def func_to_name(func): # def transform_exp_sources(d, subject=None): # def transform_real_sources(d): # def assertSigsEqual(self, found, expected, *args, **kwargs): # def assertSourcesEqual(self, found, expected, func=None, depth_order=False): # def downgrade_sig(self, sig): # class SignatureTests(unittest.TestCase): . Output only the next line.
tutil.transform_exp_sources(od([('func', 'abc'), ('func2', 'abc')])),
Using the snippet: <|code_start|># of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. class WrapperDecoratorTests(Fixtures): def _test(self, func, sig_str, args, kwargs, ret, decorators): """Tests .wrappers.wrapper_decorator Checks its reported signature, that it chains functions correctly and that it reports its decorators properly via .wrappers.wrappers """ self.assertSigsEqual(signatures.signature(func), support.s(sig_str)) self.assertEqual(func(*args, **kwargs), ret) self.assertEqual( <|code_end|> , determine the next line of code. You have imports: from sigtools import wrappers, support, signatures from sigtools.tests.util import tup, Fixtures and context (class names, function names, or code) available: # Path: sigtools/wrappers.py # def wrappers(obj): # """For introspection purposes, returns an iterable that yields each # wrapping function of obj(as done through `wrapper_decorator`, outermost # wrapper first. # # Continuing from the `wrapper_decorator` example:: # # >>> list(wrappers.wrappers(as_list)) # [<<function print_call at 0x7f28d721a950> with signature print_call(func, *args, # _show_return=True, **kwargs)>] # # """ # while True: # try: # wrappers = obj._sigtools__wrappers # except AttributeError: # return # for wrapper in wrappers: # yield wrapper # obj = obj.__wrapped__ # # Path: sigtools/support.py # def read_sig(sig_str, ret=_util.UNSET, *, # use_modifiers_annotate=False, # use_modifiers_posoargs=sys.version_info < (3, 8), # use_modifiers_kwoargs=False, # ): # def func_code(names, return_annotation, annotations, posoarg_n, # kwoarg_n, params, use_modifiers_annotate, # pre='', name='func', # ): # def make_func(source, locals=None, name='func', future_features=()): # def f(sig_str, ret=_util.UNSET, *, pre='', locals=None, name='func', future_features=(), **kwargs): # def s(*args, **kwargs): # def func_from_sig(sig): # def make_up_callsigs(sig, extra=2): # def bind_callsig(sig, args, kwargs): # def sort_callsigs(sig, callsigs): # def test_func_sig_coherent(func, check_return=True, check_invalid=True): # DEBUG_STDLIB=False # # Path: sigtools/signatures.py # # Path: sigtools/tests/util.py # def conv_first_posarg(sig): # def func_to_name(func): # def transform_exp_sources(d, subject=None): # def transform_real_sources(d): # def assertSigsEqual(self, found, expected, *args, **kwargs): # def assertSourcesEqual(self, found, expected, func=None, depth_order=False): # def downgrade_sig(self, sig): # class SignatureTests(unittest.TestCase): . Output only the next line.
list(wrappers.wrappers(func)),
Here is a snippet: <|code_start|># Copyright (C) 2013-2021 Yann Kaiser # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. class WrapperDecoratorTests(Fixtures): def _test(self, func, sig_str, args, kwargs, ret, decorators): """Tests .wrappers.wrapper_decorator Checks its reported signature, that it chains functions correctly and that it reports its decorators properly via .wrappers.wrappers """ <|code_end|> . Write the next line using the current file imports: from sigtools import wrappers, support, signatures from sigtools.tests.util import tup, Fixtures and context from other files: # Path: sigtools/wrappers.py # def wrappers(obj): # """For introspection purposes, returns an iterable that yields each # wrapping function of obj(as done through `wrapper_decorator`, outermost # wrapper first. # # Continuing from the `wrapper_decorator` example:: # # >>> list(wrappers.wrappers(as_list)) # [<<function print_call at 0x7f28d721a950> with signature print_call(func, *args, # _show_return=True, **kwargs)>] # # """ # while True: # try: # wrappers = obj._sigtools__wrappers # except AttributeError: # return # for wrapper in wrappers: # yield wrapper # obj = obj.__wrapped__ # # Path: sigtools/support.py # def read_sig(sig_str, ret=_util.UNSET, *, # use_modifiers_annotate=False, # use_modifiers_posoargs=sys.version_info < (3, 8), # use_modifiers_kwoargs=False, # ): # def func_code(names, return_annotation, annotations, posoarg_n, # kwoarg_n, params, use_modifiers_annotate, # pre='', name='func', # ): # def make_func(source, locals=None, name='func', future_features=()): # def f(sig_str, ret=_util.UNSET, *, pre='', locals=None, name='func', future_features=(), **kwargs): # def s(*args, **kwargs): # def func_from_sig(sig): # def make_up_callsigs(sig, extra=2): # def bind_callsig(sig, args, kwargs): # def sort_callsigs(sig, callsigs): # def test_func_sig_coherent(func, check_return=True, check_invalid=True): # DEBUG_STDLIB=False # # Path: sigtools/signatures.py # # Path: sigtools/tests/util.py # def conv_first_posarg(sig): # def func_to_name(func): # def transform_exp_sources(d, subject=None): # def transform_real_sources(d): # def assertSigsEqual(self, found, expected, *args, **kwargs): # def assertSourcesEqual(self, found, expected, func=None, depth_order=False): # def downgrade_sig(self, sig): # class SignatureTests(unittest.TestCase): , which may include functions, classes, or code. Output only the next line.
self.assertSigsEqual(signatures.signature(func), support.s(sig_str))
Next line prediction: <|code_start|># Copyright (C) 2013-2021 Yann Kaiser # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. class WrapperDecoratorTests(Fixtures): def _test(self, func, sig_str, args, kwargs, ret, decorators): """Tests .wrappers.wrapper_decorator Checks its reported signature, that it chains functions correctly and that it reports its decorators properly via .wrappers.wrappers """ <|code_end|> . Use current file imports: (from sigtools import wrappers, support, signatures from sigtools.tests.util import tup, Fixtures) and context including class names, function names, or small code snippets from other files: # Path: sigtools/wrappers.py # def wrappers(obj): # """For introspection purposes, returns an iterable that yields each # wrapping function of obj(as done through `wrapper_decorator`, outermost # wrapper first. # # Continuing from the `wrapper_decorator` example:: # # >>> list(wrappers.wrappers(as_list)) # [<<function print_call at 0x7f28d721a950> with signature print_call(func, *args, # _show_return=True, **kwargs)>] # # """ # while True: # try: # wrappers = obj._sigtools__wrappers # except AttributeError: # return # for wrapper in wrappers: # yield wrapper # obj = obj.__wrapped__ # # Path: sigtools/support.py # def read_sig(sig_str, ret=_util.UNSET, *, # use_modifiers_annotate=False, # use_modifiers_posoargs=sys.version_info < (3, 8), # use_modifiers_kwoargs=False, # ): # def func_code(names, return_annotation, annotations, posoarg_n, # kwoarg_n, params, use_modifiers_annotate, # pre='', name='func', # ): # def make_func(source, locals=None, name='func', future_features=()): # def f(sig_str, ret=_util.UNSET, *, pre='', locals=None, name='func', future_features=(), **kwargs): # def s(*args, **kwargs): # def func_from_sig(sig): # def make_up_callsigs(sig, extra=2): # def bind_callsig(sig, args, kwargs): # def sort_callsigs(sig, callsigs): # def test_func_sig_coherent(func, check_return=True, check_invalid=True): # DEBUG_STDLIB=False # # Path: sigtools/signatures.py # # Path: sigtools/tests/util.py # def conv_first_posarg(sig): # def func_to_name(func): # def transform_exp_sources(d, subject=None): # def transform_real_sources(d): # def assertSigsEqual(self, found, expected, *args, **kwargs): # def assertSourcesEqual(self, found, expected, func=None, depth_order=False): # def downgrade_sig(self, sig): # class SignatureTests(unittest.TestCase): . Output only the next line.
self.assertSigsEqual(signatures.signature(func), support.s(sig_str))
Continue the code snippet: <|code_start|># IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. class WrapperDecoratorTests(Fixtures): def _test(self, func, sig_str, args, kwargs, ret, decorators): """Tests .wrappers.wrapper_decorator Checks its reported signature, that it chains functions correctly and that it reports its decorators properly via .wrappers.wrappers """ self.assertSigsEqual(signatures.signature(func), support.s(sig_str)) self.assertEqual(func(*args, **kwargs), ret) self.assertEqual( list(wrappers.wrappers(func)), [x.wrapper for x in decorators]) @wrappers.wrapper_decorator def _deco_all(func, a, b, *args, **kwargs): return a, b, func(*args, **kwargs) def test_decorator_repr(self): repr(self._deco_all) <|code_end|> . Use current file imports: from sigtools import wrappers, support, signatures from sigtools.tests.util import tup, Fixtures and context (classes, functions, or code) from other files: # Path: sigtools/wrappers.py # def wrappers(obj): # """For introspection purposes, returns an iterable that yields each # wrapping function of obj(as done through `wrapper_decorator`, outermost # wrapper first. # # Continuing from the `wrapper_decorator` example:: # # >>> list(wrappers.wrappers(as_list)) # [<<function print_call at 0x7f28d721a950> with signature print_call(func, *args, # _show_return=True, **kwargs)>] # # """ # while True: # try: # wrappers = obj._sigtools__wrappers # except AttributeError: # return # for wrapper in wrappers: # yield wrapper # obj = obj.__wrapped__ # # Path: sigtools/support.py # def read_sig(sig_str, ret=_util.UNSET, *, # use_modifiers_annotate=False, # use_modifiers_posoargs=sys.version_info < (3, 8), # use_modifiers_kwoargs=False, # ): # def func_code(names, return_annotation, annotations, posoarg_n, # kwoarg_n, params, use_modifiers_annotate, # pre='', name='func', # ): # def make_func(source, locals=None, name='func', future_features=()): # def f(sig_str, ret=_util.UNSET, *, pre='', locals=None, name='func', future_features=(), **kwargs): # def s(*args, **kwargs): # def func_from_sig(sig): # def make_up_callsigs(sig, extra=2): # def bind_callsig(sig, args, kwargs): # def sort_callsigs(sig, callsigs): # def test_func_sig_coherent(func, check_return=True, check_invalid=True): # DEBUG_STDLIB=False # # Path: sigtools/signatures.py # # Path: sigtools/tests/util.py # def conv_first_posarg(sig): # def func_to_name(func): # def transform_exp_sources(d, subject=None): # def transform_real_sources(d): # def assertSigsEqual(self, found, expected, *args, **kwargs): # def assertSourcesEqual(self, found, expected, func=None, depth_order=False): # def downgrade_sig(self, sig): # class SignatureTests(unittest.TestCase): . Output only the next line.
@tup('a, b, j, k, l', (1, 2, 3, 4, 5), {}, (1, 2, (3, 4, 5)), [_deco_all])
Given the following code snippet before the placeholder: <|code_start|> def getclosure(obj): try: return obj.__closure__ except AttributeError: return obj.func_closure def getcode(obj): try: return obj.__code__ except AttributeError: return obj.func_code class WrapperTests(Fixtures): def _test(self, func, sig_str, args, kwargs, ret, exp_sources, decorators): """Tests .wrappers.decorator Checks its reported signature, that it chains functions correctly and that it its decorators are in the signature sources """ sig = signatures.signature(func) self.assertSigsEqual(sig, support.s(sig_str)) self.assertEqual(func(*args, **kwargs), ret) self.assertSourcesEqual(sig.sources, exp_sources, func, depth_order=True) self.assertEqual( <|code_end|> , predict the next line using imports from the current file: from sigtools import wrappers, support, signatures from sigtools.tests.util import tup, Fixtures and context including class names, function names, and sometimes code from other files: # Path: sigtools/wrappers.py # def wrappers(obj): # """For introspection purposes, returns an iterable that yields each # wrapping function of obj(as done through `wrapper_decorator`, outermost # wrapper first. # # Continuing from the `wrapper_decorator` example:: # # >>> list(wrappers.wrappers(as_list)) # [<<function print_call at 0x7f28d721a950> with signature print_call(func, *args, # _show_return=True, **kwargs)>] # # """ # while True: # try: # wrappers = obj._sigtools__wrappers # except AttributeError: # return # for wrapper in wrappers: # yield wrapper # obj = obj.__wrapped__ # # Path: sigtools/support.py # def read_sig(sig_str, ret=_util.UNSET, *, # use_modifiers_annotate=False, # use_modifiers_posoargs=sys.version_info < (3, 8), # use_modifiers_kwoargs=False, # ): # def func_code(names, return_annotation, annotations, posoarg_n, # kwoarg_n, params, use_modifiers_annotate, # pre='', name='func', # ): # def make_func(source, locals=None, name='func', future_features=()): # def f(sig_str, ret=_util.UNSET, *, pre='', locals=None, name='func', future_features=(), **kwargs): # def s(*args, **kwargs): # def func_from_sig(sig): # def make_up_callsigs(sig, extra=2): # def bind_callsig(sig, args, kwargs): # def sort_callsigs(sig, callsigs): # def test_func_sig_coherent(func, check_return=True, check_invalid=True): # DEBUG_STDLIB=False # # Path: sigtools/signatures.py # # Path: sigtools/tests/util.py # def conv_first_posarg(sig): # def func_to_name(func): # def transform_exp_sources(d, subject=None): # def transform_real_sources(d): # def assertSigsEqual(self, found, expected, *args, **kwargs): # def assertSourcesEqual(self, found, expected, func=None, depth_order=False): # def downgrade_sig(self, sig): # class SignatureTests(unittest.TestCase): . Output only the next line.
list(wrappers.wrappers(func)),
Given snippet: <|code_start|># AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. def getclosure(obj): try: return obj.__closure__ except AttributeError: return obj.func_closure def getcode(obj): try: return obj.__code__ except AttributeError: return obj.func_code class WrapperTests(Fixtures): def _test(self, func, sig_str, args, kwargs, ret, exp_sources, decorators): """Tests .wrappers.decorator Checks its reported signature, that it chains functions correctly and that it its decorators are in the signature sources """ sig = signatures.signature(func) <|code_end|> , continue by predicting the next line. Consider current file imports: from sigtools import wrappers, support, signatures from sigtools.tests.util import tup, Fixtures and context: # Path: sigtools/wrappers.py # def wrappers(obj): # """For introspection purposes, returns an iterable that yields each # wrapping function of obj(as done through `wrapper_decorator`, outermost # wrapper first. # # Continuing from the `wrapper_decorator` example:: # # >>> list(wrappers.wrappers(as_list)) # [<<function print_call at 0x7f28d721a950> with signature print_call(func, *args, # _show_return=True, **kwargs)>] # # """ # while True: # try: # wrappers = obj._sigtools__wrappers # except AttributeError: # return # for wrapper in wrappers: # yield wrapper # obj = obj.__wrapped__ # # Path: sigtools/support.py # def read_sig(sig_str, ret=_util.UNSET, *, # use_modifiers_annotate=False, # use_modifiers_posoargs=sys.version_info < (3, 8), # use_modifiers_kwoargs=False, # ): # def func_code(names, return_annotation, annotations, posoarg_n, # kwoarg_n, params, use_modifiers_annotate, # pre='', name='func', # ): # def make_func(source, locals=None, name='func', future_features=()): # def f(sig_str, ret=_util.UNSET, *, pre='', locals=None, name='func', future_features=(), **kwargs): # def s(*args, **kwargs): # def func_from_sig(sig): # def make_up_callsigs(sig, extra=2): # def bind_callsig(sig, args, kwargs): # def sort_callsigs(sig, callsigs): # def test_func_sig_coherent(func, check_return=True, check_invalid=True): # DEBUG_STDLIB=False # # Path: sigtools/signatures.py # # Path: sigtools/tests/util.py # def conv_first_posarg(sig): # def func_to_name(func): # def transform_exp_sources(d, subject=None): # def transform_real_sources(d): # def assertSigsEqual(self, found, expected, *args, **kwargs): # def assertSourcesEqual(self, found, expected, func=None, depth_order=False): # def downgrade_sig(self, sig): # class SignatureTests(unittest.TestCase): which might include code, classes, or functions. Output only the next line.
self.assertSigsEqual(sig, support.s(sig_str))
Predict the next line after this snippet: <|code_start|># FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. def getclosure(obj): try: return obj.__closure__ except AttributeError: return obj.func_closure def getcode(obj): try: return obj.__code__ except AttributeError: return obj.func_code class WrapperTests(Fixtures): def _test(self, func, sig_str, args, kwargs, ret, exp_sources, decorators): """Tests .wrappers.decorator Checks its reported signature, that it chains functions correctly and that it its decorators are in the signature sources """ <|code_end|> using the current file's imports: from sigtools import wrappers, support, signatures from sigtools.tests.util import tup, Fixtures and any relevant context from other files: # Path: sigtools/wrappers.py # def wrappers(obj): # """For introspection purposes, returns an iterable that yields each # wrapping function of obj(as done through `wrapper_decorator`, outermost # wrapper first. # # Continuing from the `wrapper_decorator` example:: # # >>> list(wrappers.wrappers(as_list)) # [<<function print_call at 0x7f28d721a950> with signature print_call(func, *args, # _show_return=True, **kwargs)>] # # """ # while True: # try: # wrappers = obj._sigtools__wrappers # except AttributeError: # return # for wrapper in wrappers: # yield wrapper # obj = obj.__wrapped__ # # Path: sigtools/support.py # def read_sig(sig_str, ret=_util.UNSET, *, # use_modifiers_annotate=False, # use_modifiers_posoargs=sys.version_info < (3, 8), # use_modifiers_kwoargs=False, # ): # def func_code(names, return_annotation, annotations, posoarg_n, # kwoarg_n, params, use_modifiers_annotate, # pre='', name='func', # ): # def make_func(source, locals=None, name='func', future_features=()): # def f(sig_str, ret=_util.UNSET, *, pre='', locals=None, name='func', future_features=(), **kwargs): # def s(*args, **kwargs): # def func_from_sig(sig): # def make_up_callsigs(sig, extra=2): # def bind_callsig(sig, args, kwargs): # def sort_callsigs(sig, callsigs): # def test_func_sig_coherent(func, check_return=True, check_invalid=True): # DEBUG_STDLIB=False # # Path: sigtools/signatures.py # # Path: sigtools/tests/util.py # def conv_first_posarg(sig): # def func_to_name(func): # def transform_exp_sources(d, subject=None): # def transform_real_sources(d): # def assertSigsEqual(self, found, expected, *args, **kwargs): # def assertSourcesEqual(self, found, expected, func=None, depth_order=False): # def downgrade_sig(self, sig): # class SignatureTests(unittest.TestCase): . Output only the next line.
sig = signatures.signature(func)
Predict the next line after this snippet: <|code_start|> try: return obj.__code__ except AttributeError: return obj.func_code class WrapperTests(Fixtures): def _test(self, func, sig_str, args, kwargs, ret, exp_sources, decorators): """Tests .wrappers.decorator Checks its reported signature, that it chains functions correctly and that it its decorators are in the signature sources """ sig = signatures.signature(func) self.assertSigsEqual(sig, support.s(sig_str)) self.assertEqual(func(*args, **kwargs), ret) self.assertSourcesEqual(sig.sources, exp_sources, func, depth_order=True) self.assertEqual( list(wrappers.wrappers(func)), [getclosure(d)[getcode(d).co_freevars.index('func')].cell_contents for d in decorators]) @wrappers.decorator def _deco_all(func, a, b, *args, **kwargs): return a, b, func(*args, **kwargs) def test_decorator_repr(self): repr(self._deco_all) <|code_end|> using the current file's imports: from sigtools import wrappers, support, signatures from sigtools.tests.util import tup, Fixtures and any relevant context from other files: # Path: sigtools/wrappers.py # def wrappers(obj): # """For introspection purposes, returns an iterable that yields each # wrapping function of obj(as done through `wrapper_decorator`, outermost # wrapper first. # # Continuing from the `wrapper_decorator` example:: # # >>> list(wrappers.wrappers(as_list)) # [<<function print_call at 0x7f28d721a950> with signature print_call(func, *args, # _show_return=True, **kwargs)>] # # """ # while True: # try: # wrappers = obj._sigtools__wrappers # except AttributeError: # return # for wrapper in wrappers: # yield wrapper # obj = obj.__wrapped__ # # Path: sigtools/support.py # def read_sig(sig_str, ret=_util.UNSET, *, # use_modifiers_annotate=False, # use_modifiers_posoargs=sys.version_info < (3, 8), # use_modifiers_kwoargs=False, # ): # def func_code(names, return_annotation, annotations, posoarg_n, # kwoarg_n, params, use_modifiers_annotate, # pre='', name='func', # ): # def make_func(source, locals=None, name='func', future_features=()): # def f(sig_str, ret=_util.UNSET, *, pre='', locals=None, name='func', future_features=(), **kwargs): # def s(*args, **kwargs): # def func_from_sig(sig): # def make_up_callsigs(sig, extra=2): # def bind_callsig(sig, args, kwargs): # def sort_callsigs(sig, callsigs): # def test_func_sig_coherent(func, check_return=True, check_invalid=True): # DEBUG_STDLIB=False # # Path: sigtools/signatures.py # # Path: sigtools/tests/util.py # def conv_first_posarg(sig): # def func_to_name(func): # def transform_exp_sources(d, subject=None): # def transform_real_sources(d): # def assertSigsEqual(self, found, expected, *args, **kwargs): # def assertSourcesEqual(self, found, expected, func=None, depth_order=False): # def downgrade_sig(self, sig): # class SignatureTests(unittest.TestCase): . Output only the next line.
@tup('a, b, j, k, l', (1, 2, 3, 4, 5), {}, (1, 2, (3, 4, 5)),
Next line prediction: <|code_start|># furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. def getclosure(obj): try: return obj.__closure__ except AttributeError: return obj.func_closure def getcode(obj): try: return obj.__code__ except AttributeError: return obj.func_code <|code_end|> . Use current file imports: (from sigtools import wrappers, support, signatures from sigtools.tests.util import tup, Fixtures) and context including class names, function names, or small code snippets from other files: # Path: sigtools/wrappers.py # def wrappers(obj): # """For introspection purposes, returns an iterable that yields each # wrapping function of obj(as done through `wrapper_decorator`, outermost # wrapper first. # # Continuing from the `wrapper_decorator` example:: # # >>> list(wrappers.wrappers(as_list)) # [<<function print_call at 0x7f28d721a950> with signature print_call(func, *args, # _show_return=True, **kwargs)>] # # """ # while True: # try: # wrappers = obj._sigtools__wrappers # except AttributeError: # return # for wrapper in wrappers: # yield wrapper # obj = obj.__wrapped__ # # Path: sigtools/support.py # def read_sig(sig_str, ret=_util.UNSET, *, # use_modifiers_annotate=False, # use_modifiers_posoargs=sys.version_info < (3, 8), # use_modifiers_kwoargs=False, # ): # def func_code(names, return_annotation, annotations, posoarg_n, # kwoarg_n, params, use_modifiers_annotate, # pre='', name='func', # ): # def make_func(source, locals=None, name='func', future_features=()): # def f(sig_str, ret=_util.UNSET, *, pre='', locals=None, name='func', future_features=(), **kwargs): # def s(*args, **kwargs): # def func_from_sig(sig): # def make_up_callsigs(sig, extra=2): # def bind_callsig(sig, args, kwargs): # def sort_callsigs(sig, callsigs): # def test_func_sig_coherent(func, check_return=True, check_invalid=True): # DEBUG_STDLIB=False # # Path: sigtools/signatures.py # # Path: sigtools/tests/util.py # def conv_first_posarg(sig): # def func_to_name(func): # def transform_exp_sources(d, subject=None): # def transform_real_sources(d): # def assertSigsEqual(self, found, expected, *args, **kwargs): # def assertSourcesEqual(self, found, expected, func=None, depth_order=False): # def downgrade_sig(self, sig): # class SignatureTests(unittest.TestCase): . Output only the next line.
class WrapperTests(Fixtures):
Based on the snippet: <|code_start|> self.assertSigsEqual(sig_get, support.s(expected_get)) self.assertSourcesEqual(sig_get.sources, { 'outer': exp_src_get[0], 'inner': exp_src_get[1], '+depths': ['outer', 'inner']}) a = ( 'a, *p, b, **k', 'c, *, d', (), {}, 'a, c, *, b, d', 'c, *, b, d', ['ab', 'cd'], ['b', 'cd']) b = ( 'a, *p, b, **k', 'a, c, *, b, d', (1, 'b'), {}, 'a, c, *, b, d', 'c, *, b, d', ['ab', 'cd'], ['b', 'cd']) def test_call(self): outer = support.f('*args, **kwargs') inner = support.f('a, *, b') forw = specifiers.forwards_to_function(inner)(outer) instance = object() forw_get_prox = _util.safe_get(forw, instance, object) self.assertEqual( forw_get_prox(1, b=2), {'args': (instance, 1), 'kwargs': {'b': 2}}) def sig_equal(self, obj, sig_str, exp_src): sig = specifiers.signature(obj) self.assertSigsEqual(sig, support.s(sig_str), conv_first_posarg=True) self.assertSourcesEqual(sig.sources, exp_src, obj) class _Coop(object): <|code_end|> , predict the immediate next line with the help of imports: import sys import unittest import sigtools from sigtools import modifiers, specifiers, support, _util, signatures from sigtools.tests.util import Fixtures, SignatureTests, tup and context (classes, functions, sometimes code) from other files: # Path: sigtools/modifiers.py # class _PokTranslator(_util.OverrideableDataDesc): # class annotate(object): # def __new__(cls, func=None, posoargs=(), kwoargs=(), **kwargs): # def __init__(self, func, posoargs=(), kwoargs=(), **kwargs): # def _merge_other(self, other): # def _prepare(self): # def _sigtools__autoforwards_hint(self, func): # def __call__(self, *args, **kwargs): # def parameters(self): # def __repr__(self): # def kwoargs(start=None, *kwoarg_names): # def _kwoargs_start(start, _kwoargs, func, *args, **kwargs): # def posoargs(end=None, *posoarg_names): # def _posoargs_end(end, _posoargs, func, *args, **kwargs): # def autokwoargs(func=None, exceptions=()): # def _autokwoargs(exceptions, func): # def __init__(self, __return_annotation=_util.UNSET, **annotations): # def __call__(self, obj): # def __repr__(self): # # Path: sigtools/specifiers.py # class _AsForged(object): # class _ForgerWrapper(object): # def __init__(self): # def __get__(self, instance, owner): # def set_signature_forger(obj, forger, emulate=None): # def _transform(obj, meta): # def __init__(self, obj, forger): # def _sigtools__forger(self, obj): # def __call__(self, *args, **kwargs): # def __get__(self, instance, owner): # def forger_function(func): # def _apply_forger(emulate=None, *args, **kwargs): # def _applier(obj): # def forwards(wrapper, wrapped, *args, **kwargs): # def forwards_to_function(obj, *args, **kwargs): # def forwards_to_method(obj, wrapped_name, *args, **kwargs): # def _get_origin_class(obj, cls): # def forwards_to_super(obj, cls=None, *args, **kwargs): # def apply_forwards_to_super(num_args=0, named_args=(), *member_names, # **kwargs): # def _apply_forwards_to_super(member_names, m_args, m_kwargs, cls): # # Path: sigtools/support.py # def read_sig(sig_str, ret=_util.UNSET, *, # use_modifiers_annotate=False, # use_modifiers_posoargs=sys.version_info < (3, 8), # use_modifiers_kwoargs=False, # ): # def func_code(names, return_annotation, annotations, posoarg_n, # kwoarg_n, params, use_modifiers_annotate, # pre='', name='func', # ): # def make_func(source, locals=None, name='func', future_features=()): # def f(sig_str, ret=_util.UNSET, *, pre='', locals=None, name='func', future_features=(), **kwargs): # def s(*args, **kwargs): # def func_from_sig(sig): # def make_up_callsigs(sig, extra=2): # def bind_callsig(sig, args, kwargs): # def sort_callsigs(sig, callsigs): # def test_func_sig_coherent(func, check_return=True, check_invalid=True): # DEBUG_STDLIB=False # # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() # # Path: sigtools/signatures.py # # Path: sigtools/tests/util.py # def conv_first_posarg(sig): # def func_to_name(func): # def transform_exp_sources(d, subject=None): # def transform_real_sources(d): # def assertSigsEqual(self, found, expected, *args, **kwargs): # def assertSourcesEqual(self, found, expected, func=None, depth_order=False): # def downgrade_sig(self, sig): # class SignatureTests(unittest.TestCase): . Output only the next line.
@modifiers.kwoargs('cb')
Here is a snippet: <|code_start|># AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # bulk of the testing happens in test_merge and test_embed not_py33 = sys.version_info < (3,3) def _func(*args, **kwargs): raise NotImplementedError def _free_func(x, y, z): raise NotImplementedError class _cls(object): method = _func _inst = _cls() _im_type = type(_inst.method) class MiscTests(unittest.TestCase): def test_sigtools_signature(self): <|code_end|> . Write the next line using the current file imports: import sys import unittest import sigtools from sigtools import modifiers, specifiers, support, _util, signatures from sigtools.tests.util import Fixtures, SignatureTests, tup and context from other files: # Path: sigtools/modifiers.py # class _PokTranslator(_util.OverrideableDataDesc): # class annotate(object): # def __new__(cls, func=None, posoargs=(), kwoargs=(), **kwargs): # def __init__(self, func, posoargs=(), kwoargs=(), **kwargs): # def _merge_other(self, other): # def _prepare(self): # def _sigtools__autoforwards_hint(self, func): # def __call__(self, *args, **kwargs): # def parameters(self): # def __repr__(self): # def kwoargs(start=None, *kwoarg_names): # def _kwoargs_start(start, _kwoargs, func, *args, **kwargs): # def posoargs(end=None, *posoarg_names): # def _posoargs_end(end, _posoargs, func, *args, **kwargs): # def autokwoargs(func=None, exceptions=()): # def _autokwoargs(exceptions, func): # def __init__(self, __return_annotation=_util.UNSET, **annotations): # def __call__(self, obj): # def __repr__(self): # # Path: sigtools/specifiers.py # class _AsForged(object): # class _ForgerWrapper(object): # def __init__(self): # def __get__(self, instance, owner): # def set_signature_forger(obj, forger, emulate=None): # def _transform(obj, meta): # def __init__(self, obj, forger): # def _sigtools__forger(self, obj): # def __call__(self, *args, **kwargs): # def __get__(self, instance, owner): # def forger_function(func): # def _apply_forger(emulate=None, *args, **kwargs): # def _applier(obj): # def forwards(wrapper, wrapped, *args, **kwargs): # def forwards_to_function(obj, *args, **kwargs): # def forwards_to_method(obj, wrapped_name, *args, **kwargs): # def _get_origin_class(obj, cls): # def forwards_to_super(obj, cls=None, *args, **kwargs): # def apply_forwards_to_super(num_args=0, named_args=(), *member_names, # **kwargs): # def _apply_forwards_to_super(member_names, m_args, m_kwargs, cls): # # Path: sigtools/support.py # def read_sig(sig_str, ret=_util.UNSET, *, # use_modifiers_annotate=False, # use_modifiers_posoargs=sys.version_info < (3, 8), # use_modifiers_kwoargs=False, # ): # def func_code(names, return_annotation, annotations, posoarg_n, # kwoarg_n, params, use_modifiers_annotate, # pre='', name='func', # ): # def make_func(source, locals=None, name='func', future_features=()): # def f(sig_str, ret=_util.UNSET, *, pre='', locals=None, name='func', future_features=(), **kwargs): # def s(*args, **kwargs): # def func_from_sig(sig): # def make_up_callsigs(sig, extra=2): # def bind_callsig(sig, args, kwargs): # def sort_callsigs(sig, callsigs): # def test_func_sig_coherent(func, check_return=True, check_invalid=True): # DEBUG_STDLIB=False # # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() # # Path: sigtools/signatures.py # # Path: sigtools/tests/util.py # def conv_first_posarg(sig): # def func_to_name(func): # def transform_exp_sources(d, subject=None): # def transform_real_sources(d): # def assertSigsEqual(self, found, expected, *args, **kwargs): # def assertSourcesEqual(self, found, expected, func=None, depth_order=False): # def downgrade_sig(self, sig): # class SignatureTests(unittest.TestCase): , which may include functions, classes, or code. Output only the next line.
self.assertEqual(sigtools.signature, specifiers.signature)
Using the snippet: <|code_start|> # bulk of the testing happens in test_merge and test_embed not_py33 = sys.version_info < (3,3) def _func(*args, **kwargs): raise NotImplementedError def _free_func(x, y, z): raise NotImplementedError class _cls(object): method = _func _inst = _cls() _im_type = type(_inst.method) class MiscTests(unittest.TestCase): def test_sigtools_signature(self): self.assertEqual(sigtools.signature, specifiers.signature) class ForwardsTest(Fixtures): def _test(self, outer, inner, args, kwargs, expected, expected_get, exp_src, exp_src_get): <|code_end|> , determine the next line of code. You have imports: import sys import unittest import sigtools from sigtools import modifiers, specifiers, support, _util, signatures from sigtools.tests.util import Fixtures, SignatureTests, tup and context (class names, function names, or code) available: # Path: sigtools/modifiers.py # class _PokTranslator(_util.OverrideableDataDesc): # class annotate(object): # def __new__(cls, func=None, posoargs=(), kwoargs=(), **kwargs): # def __init__(self, func, posoargs=(), kwoargs=(), **kwargs): # def _merge_other(self, other): # def _prepare(self): # def _sigtools__autoforwards_hint(self, func): # def __call__(self, *args, **kwargs): # def parameters(self): # def __repr__(self): # def kwoargs(start=None, *kwoarg_names): # def _kwoargs_start(start, _kwoargs, func, *args, **kwargs): # def posoargs(end=None, *posoarg_names): # def _posoargs_end(end, _posoargs, func, *args, **kwargs): # def autokwoargs(func=None, exceptions=()): # def _autokwoargs(exceptions, func): # def __init__(self, __return_annotation=_util.UNSET, **annotations): # def __call__(self, obj): # def __repr__(self): # # Path: sigtools/specifiers.py # class _AsForged(object): # class _ForgerWrapper(object): # def __init__(self): # def __get__(self, instance, owner): # def set_signature_forger(obj, forger, emulate=None): # def _transform(obj, meta): # def __init__(self, obj, forger): # def _sigtools__forger(self, obj): # def __call__(self, *args, **kwargs): # def __get__(self, instance, owner): # def forger_function(func): # def _apply_forger(emulate=None, *args, **kwargs): # def _applier(obj): # def forwards(wrapper, wrapped, *args, **kwargs): # def forwards_to_function(obj, *args, **kwargs): # def forwards_to_method(obj, wrapped_name, *args, **kwargs): # def _get_origin_class(obj, cls): # def forwards_to_super(obj, cls=None, *args, **kwargs): # def apply_forwards_to_super(num_args=0, named_args=(), *member_names, # **kwargs): # def _apply_forwards_to_super(member_names, m_args, m_kwargs, cls): # # Path: sigtools/support.py # def read_sig(sig_str, ret=_util.UNSET, *, # use_modifiers_annotate=False, # use_modifiers_posoargs=sys.version_info < (3, 8), # use_modifiers_kwoargs=False, # ): # def func_code(names, return_annotation, annotations, posoarg_n, # kwoarg_n, params, use_modifiers_annotate, # pre='', name='func', # ): # def make_func(source, locals=None, name='func', future_features=()): # def f(sig_str, ret=_util.UNSET, *, pre='', locals=None, name='func', future_features=(), **kwargs): # def s(*args, **kwargs): # def func_from_sig(sig): # def make_up_callsigs(sig, extra=2): # def bind_callsig(sig, args, kwargs): # def sort_callsigs(sig, callsigs): # def test_func_sig_coherent(func, check_return=True, check_invalid=True): # DEBUG_STDLIB=False # # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() # # Path: sigtools/signatures.py # # Path: sigtools/tests/util.py # def conv_first_posarg(sig): # def func_to_name(func): # def transform_exp_sources(d, subject=None): # def transform_real_sources(d): # def assertSigsEqual(self, found, expected, *args, **kwargs): # def assertSourcesEqual(self, found, expected, func=None, depth_order=False): # def downgrade_sig(self, sig): # class SignatureTests(unittest.TestCase): . Output only the next line.
outer_f = support.f(outer, name='outer')
Based on the snippet: <|code_start|> def _free_func(x, y, z): raise NotImplementedError class _cls(object): method = _func _inst = _cls() _im_type = type(_inst.method) class MiscTests(unittest.TestCase): def test_sigtools_signature(self): self.assertEqual(sigtools.signature, specifiers.signature) class ForwardsTest(Fixtures): def _test(self, outer, inner, args, kwargs, expected, expected_get, exp_src, exp_src_get): outer_f = support.f(outer, name='outer') inner_f = support.f(inner, name='inner') forw = specifiers.forwards_to_function(inner_f, *args, **kwargs)(outer_f) sig = specifiers.signature(forw) self.assertSigsEqual(sig, support.s(expected)) self.assertSourcesEqual(sig.sources, { 'outer': exp_src[0], 'inner': exp_src[1], '+depths': ['outer', 'inner']}) <|code_end|> , predict the immediate next line with the help of imports: import sys import unittest import sigtools from sigtools import modifiers, specifiers, support, _util, signatures from sigtools.tests.util import Fixtures, SignatureTests, tup and context (classes, functions, sometimes code) from other files: # Path: sigtools/modifiers.py # class _PokTranslator(_util.OverrideableDataDesc): # class annotate(object): # def __new__(cls, func=None, posoargs=(), kwoargs=(), **kwargs): # def __init__(self, func, posoargs=(), kwoargs=(), **kwargs): # def _merge_other(self, other): # def _prepare(self): # def _sigtools__autoforwards_hint(self, func): # def __call__(self, *args, **kwargs): # def parameters(self): # def __repr__(self): # def kwoargs(start=None, *kwoarg_names): # def _kwoargs_start(start, _kwoargs, func, *args, **kwargs): # def posoargs(end=None, *posoarg_names): # def _posoargs_end(end, _posoargs, func, *args, **kwargs): # def autokwoargs(func=None, exceptions=()): # def _autokwoargs(exceptions, func): # def __init__(self, __return_annotation=_util.UNSET, **annotations): # def __call__(self, obj): # def __repr__(self): # # Path: sigtools/specifiers.py # class _AsForged(object): # class _ForgerWrapper(object): # def __init__(self): # def __get__(self, instance, owner): # def set_signature_forger(obj, forger, emulate=None): # def _transform(obj, meta): # def __init__(self, obj, forger): # def _sigtools__forger(self, obj): # def __call__(self, *args, **kwargs): # def __get__(self, instance, owner): # def forger_function(func): # def _apply_forger(emulate=None, *args, **kwargs): # def _applier(obj): # def forwards(wrapper, wrapped, *args, **kwargs): # def forwards_to_function(obj, *args, **kwargs): # def forwards_to_method(obj, wrapped_name, *args, **kwargs): # def _get_origin_class(obj, cls): # def forwards_to_super(obj, cls=None, *args, **kwargs): # def apply_forwards_to_super(num_args=0, named_args=(), *member_names, # **kwargs): # def _apply_forwards_to_super(member_names, m_args, m_kwargs, cls): # # Path: sigtools/support.py # def read_sig(sig_str, ret=_util.UNSET, *, # use_modifiers_annotate=False, # use_modifiers_posoargs=sys.version_info < (3, 8), # use_modifiers_kwoargs=False, # ): # def func_code(names, return_annotation, annotations, posoarg_n, # kwoarg_n, params, use_modifiers_annotate, # pre='', name='func', # ): # def make_func(source, locals=None, name='func', future_features=()): # def f(sig_str, ret=_util.UNSET, *, pre='', locals=None, name='func', future_features=(), **kwargs): # def s(*args, **kwargs): # def func_from_sig(sig): # def make_up_callsigs(sig, extra=2): # def bind_callsig(sig, args, kwargs): # def sort_callsigs(sig, callsigs): # def test_func_sig_coherent(func, check_return=True, check_invalid=True): # DEBUG_STDLIB=False # # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() # # Path: sigtools/signatures.py # # Path: sigtools/tests/util.py # def conv_first_posarg(sig): # def func_to_name(func): # def transform_exp_sources(d, subject=None): # def transform_real_sources(d): # def assertSigsEqual(self, found, expected, *args, **kwargs): # def assertSourcesEqual(self, found, expected, func=None, depth_order=False): # def downgrade_sig(self, sig): # class SignatureTests(unittest.TestCase): . Output only the next line.
sig_get = specifiers.signature(_util.safe_get(forw, object(), object))
Based on the snippet: <|code_start|> Cls.__new__ self.assertEqual(type(Cls.__dict__['__new__'].__wrapped__), staticmethod) def test_emulation(self): func = specifiers.forwards_to_method('abc', emulate=False)(_func) self.assertTrue(_func is func) func = specifiers.forwards_to_method('abc')(_func) self.assertTrue(_func is func) class Cls(object): func = specifiers.forwards_to_method('abc')(_func) func = getattr(Cls.func, '__func__', func) self.assertTrue(_func is func) self.assertTrue(_func is Cls().func.__func__) class Cls(object): def func(self, abc, *args, **kwargs): raise NotImplementedError def abc(self, x): raise NotImplementedError method = Cls().func func = specifiers.forwards_to_method('abc')(method) self.assertTrue(isinstance(func, specifiers._ForgerWrapper)) self.assertEqual(func.__wrapped__, method) self.assertRaises( AttributeError, specifiers.forwards_to_method('abc', emulate=False), Cls().func) exp = support.s('abc, x') <|code_end|> , predict the immediate next line with the help of imports: import sys import unittest import sigtools from sigtools import modifiers, specifiers, support, _util, signatures from sigtools.tests.util import Fixtures, SignatureTests, tup and context (classes, functions, sometimes code) from other files: # Path: sigtools/modifiers.py # class _PokTranslator(_util.OverrideableDataDesc): # class annotate(object): # def __new__(cls, func=None, posoargs=(), kwoargs=(), **kwargs): # def __init__(self, func, posoargs=(), kwoargs=(), **kwargs): # def _merge_other(self, other): # def _prepare(self): # def _sigtools__autoforwards_hint(self, func): # def __call__(self, *args, **kwargs): # def parameters(self): # def __repr__(self): # def kwoargs(start=None, *kwoarg_names): # def _kwoargs_start(start, _kwoargs, func, *args, **kwargs): # def posoargs(end=None, *posoarg_names): # def _posoargs_end(end, _posoargs, func, *args, **kwargs): # def autokwoargs(func=None, exceptions=()): # def _autokwoargs(exceptions, func): # def __init__(self, __return_annotation=_util.UNSET, **annotations): # def __call__(self, obj): # def __repr__(self): # # Path: sigtools/specifiers.py # class _AsForged(object): # class _ForgerWrapper(object): # def __init__(self): # def __get__(self, instance, owner): # def set_signature_forger(obj, forger, emulate=None): # def _transform(obj, meta): # def __init__(self, obj, forger): # def _sigtools__forger(self, obj): # def __call__(self, *args, **kwargs): # def __get__(self, instance, owner): # def forger_function(func): # def _apply_forger(emulate=None, *args, **kwargs): # def _applier(obj): # def forwards(wrapper, wrapped, *args, **kwargs): # def forwards_to_function(obj, *args, **kwargs): # def forwards_to_method(obj, wrapped_name, *args, **kwargs): # def _get_origin_class(obj, cls): # def forwards_to_super(obj, cls=None, *args, **kwargs): # def apply_forwards_to_super(num_args=0, named_args=(), *member_names, # **kwargs): # def _apply_forwards_to_super(member_names, m_args, m_kwargs, cls): # # Path: sigtools/support.py # def read_sig(sig_str, ret=_util.UNSET, *, # use_modifiers_annotate=False, # use_modifiers_posoargs=sys.version_info < (3, 8), # use_modifiers_kwoargs=False, # ): # def func_code(names, return_annotation, annotations, posoarg_n, # kwoarg_n, params, use_modifiers_annotate, # pre='', name='func', # ): # def make_func(source, locals=None, name='func', future_features=()): # def f(sig_str, ret=_util.UNSET, *, pre='', locals=None, name='func', future_features=(), **kwargs): # def s(*args, **kwargs): # def func_from_sig(sig): # def make_up_callsigs(sig, extra=2): # def bind_callsig(sig, args, kwargs): # def sort_callsigs(sig, callsigs): # def test_func_sig_coherent(func, check_return=True, check_invalid=True): # DEBUG_STDLIB=False # # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() # # Path: sigtools/signatures.py # # Path: sigtools/tests/util.py # def conv_first_posarg(sig): # def func_to_name(func): # def transform_exp_sources(d, subject=None): # def transform_real_sources(d): # def assertSigsEqual(self, found, expected, *args, **kwargs): # def assertSourcesEqual(self, found, expected, func=None, depth_order=False): # def downgrade_sig(self, sig): # class SignatureTests(unittest.TestCase): . Output only the next line.
self.assertSigsEqual(signatures.signature(func), exp)
Continue the code snippet: <|code_start|># THE SOFTWARE. # bulk of the testing happens in test_merge and test_embed not_py33 = sys.version_info < (3,3) def _func(*args, **kwargs): raise NotImplementedError def _free_func(x, y, z): raise NotImplementedError class _cls(object): method = _func _inst = _cls() _im_type = type(_inst.method) class MiscTests(unittest.TestCase): def test_sigtools_signature(self): self.assertEqual(sigtools.signature, specifiers.signature) <|code_end|> . Use current file imports: import sys import unittest import sigtools from sigtools import modifiers, specifiers, support, _util, signatures from sigtools.tests.util import Fixtures, SignatureTests, tup and context (classes, functions, or code) from other files: # Path: sigtools/modifiers.py # class _PokTranslator(_util.OverrideableDataDesc): # class annotate(object): # def __new__(cls, func=None, posoargs=(), kwoargs=(), **kwargs): # def __init__(self, func, posoargs=(), kwoargs=(), **kwargs): # def _merge_other(self, other): # def _prepare(self): # def _sigtools__autoforwards_hint(self, func): # def __call__(self, *args, **kwargs): # def parameters(self): # def __repr__(self): # def kwoargs(start=None, *kwoarg_names): # def _kwoargs_start(start, _kwoargs, func, *args, **kwargs): # def posoargs(end=None, *posoarg_names): # def _posoargs_end(end, _posoargs, func, *args, **kwargs): # def autokwoargs(func=None, exceptions=()): # def _autokwoargs(exceptions, func): # def __init__(self, __return_annotation=_util.UNSET, **annotations): # def __call__(self, obj): # def __repr__(self): # # Path: sigtools/specifiers.py # class _AsForged(object): # class _ForgerWrapper(object): # def __init__(self): # def __get__(self, instance, owner): # def set_signature_forger(obj, forger, emulate=None): # def _transform(obj, meta): # def __init__(self, obj, forger): # def _sigtools__forger(self, obj): # def __call__(self, *args, **kwargs): # def __get__(self, instance, owner): # def forger_function(func): # def _apply_forger(emulate=None, *args, **kwargs): # def _applier(obj): # def forwards(wrapper, wrapped, *args, **kwargs): # def forwards_to_function(obj, *args, **kwargs): # def forwards_to_method(obj, wrapped_name, *args, **kwargs): # def _get_origin_class(obj, cls): # def forwards_to_super(obj, cls=None, *args, **kwargs): # def apply_forwards_to_super(num_args=0, named_args=(), *member_names, # **kwargs): # def _apply_forwards_to_super(member_names, m_args, m_kwargs, cls): # # Path: sigtools/support.py # def read_sig(sig_str, ret=_util.UNSET, *, # use_modifiers_annotate=False, # use_modifiers_posoargs=sys.version_info < (3, 8), # use_modifiers_kwoargs=False, # ): # def func_code(names, return_annotation, annotations, posoarg_n, # kwoarg_n, params, use_modifiers_annotate, # pre='', name='func', # ): # def make_func(source, locals=None, name='func', future_features=()): # def f(sig_str, ret=_util.UNSET, *, pre='', locals=None, name='func', future_features=(), **kwargs): # def s(*args, **kwargs): # def func_from_sig(sig): # def make_up_callsigs(sig, extra=2): # def bind_callsig(sig, args, kwargs): # def sort_callsigs(sig, callsigs): # def test_func_sig_coherent(func, check_return=True, check_invalid=True): # DEBUG_STDLIB=False # # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() # # Path: sigtools/signatures.py # # Path: sigtools/tests/util.py # def conv_first_posarg(sig): # def func_to_name(func): # def transform_exp_sources(d, subject=None): # def transform_real_sources(d): # def assertSigsEqual(self, found, expected, *args, **kwargs): # def assertSourcesEqual(self, found, expected, func=None, depth_order=False): # def downgrade_sig(self, sig): # class SignatureTests(unittest.TestCase): . Output only the next line.
class ForwardsTest(Fixtures):
Based on the snippet: <|code_start|> def __init__(self, obj, forger): self.obj = obj self.forger = forger func = specifiers.forwards_to_function(func, emulate=Emulator)(_func) self.assertTrue(isinstance(func, Emulator)) @specifiers.forwards_to_function(_func, emulate=True) def func(x, y, *args, **kwargs): return x + y self.assertEqual(5, func(2, 3)) def test_super_fail(self): class Cls(object): def m(self): raise NotImplementedError def n(self): raise NotImplementedError class Sub(Cls): @specifiers.forwards_to_super() def m(self, *args, **kwargs): raise NotImplementedError @specifiers.forwards_to_super() def n(self, *args, **kwargs): super(Sub, self).n(*args, **kwargs) # pragma: no cover self.assertRaises(ValueError, specifiers.signature, Sub().m) if sys.version_info < (3,): self.assertRaises(ValueError, specifiers.signature, Sub().n) <|code_end|> , predict the immediate next line with the help of imports: import sys import unittest import sigtools from sigtools import modifiers, specifiers, support, _util, signatures from sigtools.tests.util import Fixtures, SignatureTests, tup and context (classes, functions, sometimes code) from other files: # Path: sigtools/modifiers.py # class _PokTranslator(_util.OverrideableDataDesc): # class annotate(object): # def __new__(cls, func=None, posoargs=(), kwoargs=(), **kwargs): # def __init__(self, func, posoargs=(), kwoargs=(), **kwargs): # def _merge_other(self, other): # def _prepare(self): # def _sigtools__autoforwards_hint(self, func): # def __call__(self, *args, **kwargs): # def parameters(self): # def __repr__(self): # def kwoargs(start=None, *kwoarg_names): # def _kwoargs_start(start, _kwoargs, func, *args, **kwargs): # def posoargs(end=None, *posoarg_names): # def _posoargs_end(end, _posoargs, func, *args, **kwargs): # def autokwoargs(func=None, exceptions=()): # def _autokwoargs(exceptions, func): # def __init__(self, __return_annotation=_util.UNSET, **annotations): # def __call__(self, obj): # def __repr__(self): # # Path: sigtools/specifiers.py # class _AsForged(object): # class _ForgerWrapper(object): # def __init__(self): # def __get__(self, instance, owner): # def set_signature_forger(obj, forger, emulate=None): # def _transform(obj, meta): # def __init__(self, obj, forger): # def _sigtools__forger(self, obj): # def __call__(self, *args, **kwargs): # def __get__(self, instance, owner): # def forger_function(func): # def _apply_forger(emulate=None, *args, **kwargs): # def _applier(obj): # def forwards(wrapper, wrapped, *args, **kwargs): # def forwards_to_function(obj, *args, **kwargs): # def forwards_to_method(obj, wrapped_name, *args, **kwargs): # def _get_origin_class(obj, cls): # def forwards_to_super(obj, cls=None, *args, **kwargs): # def apply_forwards_to_super(num_args=0, named_args=(), *member_names, # **kwargs): # def _apply_forwards_to_super(member_names, m_args, m_kwargs, cls): # # Path: sigtools/support.py # def read_sig(sig_str, ret=_util.UNSET, *, # use_modifiers_annotate=False, # use_modifiers_posoargs=sys.version_info < (3, 8), # use_modifiers_kwoargs=False, # ): # def func_code(names, return_annotation, annotations, posoarg_n, # kwoarg_n, params, use_modifiers_annotate, # pre='', name='func', # ): # def make_func(source, locals=None, name='func', future_features=()): # def f(sig_str, ret=_util.UNSET, *, pre='', locals=None, name='func', future_features=(), **kwargs): # def s(*args, **kwargs): # def func_from_sig(sig): # def make_up_callsigs(sig, extra=2): # def bind_callsig(sig, args, kwargs): # def sort_callsigs(sig, callsigs): # def test_func_sig_coherent(func, check_return=True, check_invalid=True): # DEBUG_STDLIB=False # # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() # # Path: sigtools/signatures.py # # Path: sigtools/tests/util.py # def conv_first_posarg(sig): # def func_to_name(func): # def transform_exp_sources(d, subject=None): # def transform_real_sources(d): # def assertSigsEqual(self, found, expected, *args, **kwargs): # def assertSourcesEqual(self, found, expected, func=None, depth_order=False): # def downgrade_sig(self, sig): # class SignatureTests(unittest.TestCase): . Output only the next line.
class ForgerFunctionTests(SignatureTests):
Given the following code snippet before the placeholder: <|code_start|> def chain_afts(self, v, *args, **kwargs): raise NotImplementedError @_Derivate @modifiers.kwoargs('y') def _sub_inst(x, y): raise NotImplementedError base_func = _base_inst.ft, 'x, y, z', {'_free_func': 'xyz'} base_method = _base_inst.ftm, 'a, *, b', {'inner': 'ab'} base_method2 = _base_inst.ftm2, 'c, a, *, d, b', { 'ftm2': 'cd', 'inner': 'ab', '+depths': ['ftm2', 'ftm', 'inner']} base_method_cls = _Base.ftm, 'self, *args, **kwargs', { 'ftm': ['self', 'args', 'kwargs']} base_ivar = _base_inst.fti, 'a, *, b', {'_base_inst': 'ab'} base_coop = _base_inst.ccm, 'ba, bb, ca, *cr, bc, cb, **ck', { 'ccm': ['ba', 'bb', 'bc'], 'method': ['ca', 'cb', 'cr', 'ck'] } sub_method = _sub_inst.ftm, 'e, a, *, b', {'ftm': 'e', 'inner': 'ab'} sub_method2 = _sub_inst.ftm2, 'c, e, a, *, d, b', { 'ftm2': 'cd', 'ftm': 'e', 'inner': 'ab'} sub_ivar = _sub_inst.fti, 'x, *, y', {'_sub_inst': 'xy'} <|code_end|> , predict the next line using imports from the current file: import sys import unittest import sigtools from sigtools import modifiers, specifiers, support, _util, signatures from sigtools.tests.util import Fixtures, SignatureTests, tup and context including class names, function names, and sometimes code from other files: # Path: sigtools/modifiers.py # class _PokTranslator(_util.OverrideableDataDesc): # class annotate(object): # def __new__(cls, func=None, posoargs=(), kwoargs=(), **kwargs): # def __init__(self, func, posoargs=(), kwoargs=(), **kwargs): # def _merge_other(self, other): # def _prepare(self): # def _sigtools__autoforwards_hint(self, func): # def __call__(self, *args, **kwargs): # def parameters(self): # def __repr__(self): # def kwoargs(start=None, *kwoarg_names): # def _kwoargs_start(start, _kwoargs, func, *args, **kwargs): # def posoargs(end=None, *posoarg_names): # def _posoargs_end(end, _posoargs, func, *args, **kwargs): # def autokwoargs(func=None, exceptions=()): # def _autokwoargs(exceptions, func): # def __init__(self, __return_annotation=_util.UNSET, **annotations): # def __call__(self, obj): # def __repr__(self): # # Path: sigtools/specifiers.py # class _AsForged(object): # class _ForgerWrapper(object): # def __init__(self): # def __get__(self, instance, owner): # def set_signature_forger(obj, forger, emulate=None): # def _transform(obj, meta): # def __init__(self, obj, forger): # def _sigtools__forger(self, obj): # def __call__(self, *args, **kwargs): # def __get__(self, instance, owner): # def forger_function(func): # def _apply_forger(emulate=None, *args, **kwargs): # def _applier(obj): # def forwards(wrapper, wrapped, *args, **kwargs): # def forwards_to_function(obj, *args, **kwargs): # def forwards_to_method(obj, wrapped_name, *args, **kwargs): # def _get_origin_class(obj, cls): # def forwards_to_super(obj, cls=None, *args, **kwargs): # def apply_forwards_to_super(num_args=0, named_args=(), *member_names, # **kwargs): # def _apply_forwards_to_super(member_names, m_args, m_kwargs, cls): # # Path: sigtools/support.py # def read_sig(sig_str, ret=_util.UNSET, *, # use_modifiers_annotate=False, # use_modifiers_posoargs=sys.version_info < (3, 8), # use_modifiers_kwoargs=False, # ): # def func_code(names, return_annotation, annotations, posoarg_n, # kwoarg_n, params, use_modifiers_annotate, # pre='', name='func', # ): # def make_func(source, locals=None, name='func', future_features=()): # def f(sig_str, ret=_util.UNSET, *, pre='', locals=None, name='func', future_features=(), **kwargs): # def s(*args, **kwargs): # def func_from_sig(sig): # def make_up_callsigs(sig, extra=2): # def bind_callsig(sig, args, kwargs): # def sort_callsigs(sig, callsigs): # def test_func_sig_coherent(func, check_return=True, check_invalid=True): # DEBUG_STDLIB=False # # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() # # Path: sigtools/signatures.py # # Path: sigtools/tests/util.py # def conv_first_posarg(sig): # def func_to_name(func): # def transform_exp_sources(d, subject=None): # def transform_real_sources(d): # def assertSigsEqual(self, found, expected, *args, **kwargs): # def assertSourcesEqual(self, found, expected, func=None, depth_order=False): # def downgrade_sig(self, sig): # class SignatureTests(unittest.TestCase): . Output only the next line.
@tup('a, y=None, z=None', {0: 'a', '_free_func': 'yz'})
Continue the code snippet: <|code_start|>class _ForgerWrapper(object): def __init__(self, obj, forger): update_wrapper(self, obj) self.__wrapped__ = obj self._transformed = False self._signature_forger = forger try: del self.__signature__ except AttributeError: pass try: del self._sigtools__forger except AttributeError: pass __signature__ = as_forged def _sigtools__forger(self, obj): return self._signature_forger(obj=self.__wrapped__) def __call__(self, *args, **kwargs): return self.__wrapped__(*args, **kwargs) def __get__(self, instance, owner): # apply __new__ staticmethod automatic transform # and any other ones Python may come up with if not self._transformed: self.__wrapped__ = _transform(self.__wrapped__, type(owner)) self._transformed = True return type(self)( <|code_end|> . Use current file imports: from functools import partial, update_wrapper from sigtools import _util, modifiers, signatures, _specifiers and context (classes, functions, or code) from other files: # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() # # Path: sigtools/modifiers.py # class _PokTranslator(_util.OverrideableDataDesc): # class annotate(object): # def __new__(cls, func=None, posoargs=(), kwoargs=(), **kwargs): # def __init__(self, func, posoargs=(), kwoargs=(), **kwargs): # def _merge_other(self, other): # def _prepare(self): # def _sigtools__autoforwards_hint(self, func): # def __call__(self, *args, **kwargs): # def parameters(self): # def __repr__(self): # def kwoargs(start=None, *kwoarg_names): # def _kwoargs_start(start, _kwoargs, func, *args, **kwargs): # def posoargs(end=None, *posoarg_names): # def _posoargs_end(end, _posoargs, func, *args, **kwargs): # def autokwoargs(func=None, exceptions=()): # def _autokwoargs(exceptions, func): # def __init__(self, __return_annotation=_util.UNSET, **annotations): # def __call__(self, obj): # def __repr__(self): # # Path: sigtools/signatures.py # # Path: sigtools/_specifiers.py # def forged_signature(obj, auto=True, args=(), kwargs={}): . Output only the next line.
_util.safe_get(self.__wrapped__, instance, owner),
Predict the next line after this snippet: <|code_start|> """ `sigtools.specifiers`: Decorators to enhance a callable's signature ------------------------------------------------------------------- The ``forwards_to_*`` decorators from this module will leave a "note" on the decorated object for `sigtools.specifiers.signature` to pick up. These "notes" tell `signature` in which way the signature of the examinated object should be crafted. The ``forwards_to_*`` decorators here will help you tell introspection or documentation tools what the ``*args`` and ``**kwargs`` parameters stand for in your function if it forwards them to another callable. This should cover most use cases, but you can use `forger_function` or `set_signature_forger` to create your own. .. |forwards_params| replace:: See :ref:`forwards-pick` for more information on the parameters. """ __all__ = [ 'signature', 'forwards_to_function', 'forwards_to_method', 'forwards_to_super', 'apply_forwards_to_super', 'forwards', 'forger_function', 'set_signature_forger', 'as_forged' ] <|code_end|> using the current file's imports: from functools import partial, update_wrapper from sigtools import _util, modifiers, signatures, _specifiers and any relevant context from other files: # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() # # Path: sigtools/modifiers.py # class _PokTranslator(_util.OverrideableDataDesc): # class annotate(object): # def __new__(cls, func=None, posoargs=(), kwoargs=(), **kwargs): # def __init__(self, func, posoargs=(), kwoargs=(), **kwargs): # def _merge_other(self, other): # def _prepare(self): # def _sigtools__autoforwards_hint(self, func): # def __call__(self, *args, **kwargs): # def parameters(self): # def __repr__(self): # def kwoargs(start=None, *kwoarg_names): # def _kwoargs_start(start, _kwoargs, func, *args, **kwargs): # def posoargs(end=None, *posoarg_names): # def _posoargs_end(end, _posoargs, func, *args, **kwargs): # def autokwoargs(func=None, exceptions=()): # def _autokwoargs(exceptions, func): # def __init__(self, __return_annotation=_util.UNSET, **annotations): # def __call__(self, obj): # def __repr__(self): # # Path: sigtools/signatures.py # # Path: sigtools/_specifiers.py # def forged_signature(obj, auto=True, args=(), kwargs={}): . Output only the next line.
_kwowr = modifiers.kwoargs('obj')
Predict the next line after this snippet: <|code_start|> (a, b, /) """ @modifiers.kwoargs('emulate') def _apply_forger(emulate=None, *args, **kwargs): def _applier(obj): return set_signature_forger( obj, partial(func, *args, **kwargs), emulate) return _applier update_wrapper(_apply_forger, func, updated=()) set_signature_forger( _apply_forger, lambda obj: forwards(_apply_forger, func, 0, 'obj')) return _apply_forger @modifiers.autokwoargs def forwards(wrapper, wrapped, *args, **kwargs): """Returns an effective signature of ``wrapper`` when it forwards its ``*args`` and ``**kwargs`` to ``wrapped``. :param callable wrapper: The outer callable :param callable wrapped: The callable ``wrapper``'s extra arguments are passed to. :return: a `inspect.Signature` object |forwards_params| """ <|code_end|> using the current file's imports: from functools import partial, update_wrapper from sigtools import _util, modifiers, signatures, _specifiers and any relevant context from other files: # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() # # Path: sigtools/modifiers.py # class _PokTranslator(_util.OverrideableDataDesc): # class annotate(object): # def __new__(cls, func=None, posoargs=(), kwoargs=(), **kwargs): # def __init__(self, func, posoargs=(), kwoargs=(), **kwargs): # def _merge_other(self, other): # def _prepare(self): # def _sigtools__autoforwards_hint(self, func): # def __call__(self, *args, **kwargs): # def parameters(self): # def __repr__(self): # def kwoargs(start=None, *kwoarg_names): # def _kwoargs_start(start, _kwoargs, func, *args, **kwargs): # def posoargs(end=None, *posoarg_names): # def _posoargs_end(end, _posoargs, func, *args, **kwargs): # def autokwoargs(func=None, exceptions=()): # def _autokwoargs(exceptions, func): # def __init__(self, __return_annotation=_util.UNSET, **annotations): # def __call__(self, obj): # def __repr__(self): # # Path: sigtools/signatures.py # # Path: sigtools/_specifiers.py # def forged_signature(obj, auto=True, args=(), kwargs={}): . Output only the next line.
return signatures.forwards(
Given the following code snippet before the placeholder: <|code_start|>------------------------------------------------------------------- The ``forwards_to_*`` decorators from this module will leave a "note" on the decorated object for `sigtools.specifiers.signature` to pick up. These "notes" tell `signature` in which way the signature of the examinated object should be crafted. The ``forwards_to_*`` decorators here will help you tell introspection or documentation tools what the ``*args`` and ``**kwargs`` parameters stand for in your function if it forwards them to another callable. This should cover most use cases, but you can use `forger_function` or `set_signature_forger` to create your own. .. |forwards_params| replace:: See :ref:`forwards-pick` for more information on the parameters. """ __all__ = [ 'signature', 'forwards_to_function', 'forwards_to_method', 'forwards_to_super', 'apply_forwards_to_super', 'forwards', 'forger_function', 'set_signature_forger', 'as_forged' ] _kwowr = modifiers.kwoargs('obj') <|code_end|> , predict the next line using imports from the current file: from functools import partial, update_wrapper from sigtools import _util, modifiers, signatures, _specifiers and context including class names, function names, and sometimes code from other files: # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() # # Path: sigtools/modifiers.py # class _PokTranslator(_util.OverrideableDataDesc): # class annotate(object): # def __new__(cls, func=None, posoargs=(), kwoargs=(), **kwargs): # def __init__(self, func, posoargs=(), kwoargs=(), **kwargs): # def _merge_other(self, other): # def _prepare(self): # def _sigtools__autoforwards_hint(self, func): # def __call__(self, *args, **kwargs): # def parameters(self): # def __repr__(self): # def kwoargs(start=None, *kwoarg_names): # def _kwoargs_start(start, _kwoargs, func, *args, **kwargs): # def posoargs(end=None, *posoarg_names): # def _posoargs_end(end, _posoargs, func, *args, **kwargs): # def autokwoargs(func=None, exceptions=()): # def _autokwoargs(exceptions, func): # def __init__(self, __return_annotation=_util.UNSET, **annotations): # def __call__(self, obj): # def __repr__(self): # # Path: sigtools/signatures.py # # Path: sigtools/_specifiers.py # def forged_signature(obj, auto=True, args=(), kwargs={}): . Output only the next line.
signature = _specifiers.forged_signature
Here is a snippet: <|code_start|># OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """ `sigtools.support`: Utilities for use in interactive sessions and unit tests ---------------------------------------------------------------------------- """ __all__ = [ 's', 'f', 'read_sig', 'func_code', 'make_func', 'func_from_sig', 'make_up_callsigs', 'bind_callsig', 'sort_callsigs', 'test_func_sig_coherent', ] try: zip = itertools.izip except AttributeError: pass re_paramname = re.compile( r'^' r'\s*([^:=]+)' # param name r'\s*(?::(.+?))?' # annotation r'\s*(?:=(.+))?' # default value r'$') re_posoarg = re.compile(r'^<(.*)>$') <|code_end|> . Write the next line using the current file imports: import __future__ import re import sys import itertools from warnings import warn from sigtools import _util, modifiers, signatures, specifiers and context from other files: # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() # # Path: sigtools/modifiers.py # class _PokTranslator(_util.OverrideableDataDesc): # class annotate(object): # def __new__(cls, func=None, posoargs=(), kwoargs=(), **kwargs): # def __init__(self, func, posoargs=(), kwoargs=(), **kwargs): # def _merge_other(self, other): # def _prepare(self): # def _sigtools__autoforwards_hint(self, func): # def __call__(self, *args, **kwargs): # def parameters(self): # def __repr__(self): # def kwoargs(start=None, *kwoarg_names): # def _kwoargs_start(start, _kwoargs, func, *args, **kwargs): # def posoargs(end=None, *posoarg_names): # def _posoargs_end(end, _posoargs, func, *args, **kwargs): # def autokwoargs(func=None, exceptions=()): # def _autokwoargs(exceptions, func): # def __init__(self, __return_annotation=_util.UNSET, **annotations): # def __call__(self, obj): # def __repr__(self): # # Path: sigtools/signatures.py # # Path: sigtools/specifiers.py # class _AsForged(object): # class _ForgerWrapper(object): # def __init__(self): # def __get__(self, instance, owner): # def set_signature_forger(obj, forger, emulate=None): # def _transform(obj, meta): # def __init__(self, obj, forger): # def _sigtools__forger(self, obj): # def __call__(self, *args, **kwargs): # def __get__(self, instance, owner): # def forger_function(func): # def _apply_forger(emulate=None, *args, **kwargs): # def _applier(obj): # def forwards(wrapper, wrapped, *args, **kwargs): # def forwards_to_function(obj, *args, **kwargs): # def forwards_to_method(obj, wrapped_name, *args, **kwargs): # def _get_origin_class(obj, cls): # def forwards_to_super(obj, cls=None, *args, **kwargs): # def apply_forwards_to_super(num_args=0, named_args=(), *member_names, # **kwargs): # def _apply_forwards_to_super(member_names, m_args, m_kwargs, cls): , which may include functions, classes, or code. Output only the next line.
def read_sig(sig_str, ret=_util.UNSET, *,
Using the snippet: <|code_start|> code.append(f'@modifiers.annotate({return_annotation})') elif annotations: annotation_args = ', '.join( f'{key}={value}'.format(key, value) for key, value in annotations.items()) code.append(f'@modifiers.annotate({annotation_args})') if posoarg_n: posoarg_names = ', '.join(f"'{name}'" for name in posoarg_n) code.append(f'@modifiers.posoargs({posoarg_names})') if kwoarg_n: kwoargs_name = ', '.join(f"'{name}'" for name in kwoarg_n) code.append(f'@modifiers.kwoargs({kwoargs_name})') if not use_modifiers_annotate and return_annotation is not _util.UNSET: annotation_syntax = f" -> {return_annotation}" else: annotation_syntax = "" code.append(f'def {name}({params}){annotation_syntax}:') return_keyvalues = ', '.join(f'{name!r}: {name}' for name in names) code.append(f' return {{{return_keyvalues}}}') return '\n'.join(code) def make_func(source, locals=None, name='func', future_features=()): """Executes the given code and returns the object named func from the resulting namespace.""" if locals is None: locals = {} flags = 0 for feature in future_features: flags |= getattr(__future__, feature).compiler_flag code = compile(source, "<sigtools.support>", "exec", flags) <|code_end|> , determine the next line of code. You have imports: import __future__ import re import sys import itertools from warnings import warn from sigtools import _util, modifiers, signatures, specifiers and context (class names, function names, or code) available: # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() # # Path: sigtools/modifiers.py # class _PokTranslator(_util.OverrideableDataDesc): # class annotate(object): # def __new__(cls, func=None, posoargs=(), kwoargs=(), **kwargs): # def __init__(self, func, posoargs=(), kwoargs=(), **kwargs): # def _merge_other(self, other): # def _prepare(self): # def _sigtools__autoforwards_hint(self, func): # def __call__(self, *args, **kwargs): # def parameters(self): # def __repr__(self): # def kwoargs(start=None, *kwoarg_names): # def _kwoargs_start(start, _kwoargs, func, *args, **kwargs): # def posoargs(end=None, *posoarg_names): # def _posoargs_end(end, _posoargs, func, *args, **kwargs): # def autokwoargs(func=None, exceptions=()): # def _autokwoargs(exceptions, func): # def __init__(self, __return_annotation=_util.UNSET, **annotations): # def __call__(self, obj): # def __repr__(self): # # Path: sigtools/signatures.py # # Path: sigtools/specifiers.py # class _AsForged(object): # class _ForgerWrapper(object): # def __init__(self): # def __get__(self, instance, owner): # def set_signature_forger(obj, forger, emulate=None): # def _transform(obj, meta): # def __init__(self, obj, forger): # def _sigtools__forger(self, obj): # def __call__(self, *args, **kwargs): # def __get__(self, instance, owner): # def forger_function(func): # def _apply_forger(emulate=None, *args, **kwargs): # def _applier(obj): # def forwards(wrapper, wrapped, *args, **kwargs): # def forwards_to_function(obj, *args, **kwargs): # def forwards_to_method(obj, wrapped_name, *args, **kwargs): # def _get_origin_class(obj, cls): # def forwards_to_super(obj, cls=None, *args, **kwargs): # def apply_forwards_to_super(num_args=0, named_args=(), *member_names, # **kwargs): # def _apply_forwards_to_super(member_names, m_args, m_kwargs, cls): . Output only the next line.
exec(code, { "modifiers": modifiers }, locals)
Given the following code snippet before the placeholder: <|code_start|> .. warning:: The contents of the arguments are eventually passed to `exec`. Do not use with untrusted input. :: >>> from sigtools.support import s >>> sig = s('a, b=2, *args, c:"annotation", **kwargs') >>> sig <inspect.Signature object at 0x7f15e6055550> >>> print(sig) (a, b=2, *args, c:'annotation', **kwargs) """ return specifiers.signature(f(*args, **kwargs)) def func_from_sig(sig): """Creates a dummy function from the given signature object .. warning:: The contents of the arguments are eventually passed to `exec`. Do not use with untrusted input. """ ret, sep, sig_str = str(sig).rpartition(' -> ') ret = ret if sep else _util.UNSET return f(sig_str[1:-1], ret) def make_up_callsigs(sig, extra=2): """Figures out reasonably as many ways as possible to call a callable with the given signature.""" <|code_end|> , predict the next line using imports from the current file: import __future__ import re import sys import itertools from warnings import warn from sigtools import _util, modifiers, signatures, specifiers and context including class names, function names, and sometimes code from other files: # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() # # Path: sigtools/modifiers.py # class _PokTranslator(_util.OverrideableDataDesc): # class annotate(object): # def __new__(cls, func=None, posoargs=(), kwoargs=(), **kwargs): # def __init__(self, func, posoargs=(), kwoargs=(), **kwargs): # def _merge_other(self, other): # def _prepare(self): # def _sigtools__autoforwards_hint(self, func): # def __call__(self, *args, **kwargs): # def parameters(self): # def __repr__(self): # def kwoargs(start=None, *kwoarg_names): # def _kwoargs_start(start, _kwoargs, func, *args, **kwargs): # def posoargs(end=None, *posoarg_names): # def _posoargs_end(end, _posoargs, func, *args, **kwargs): # def autokwoargs(func=None, exceptions=()): # def _autokwoargs(exceptions, func): # def __init__(self, __return_annotation=_util.UNSET, **annotations): # def __call__(self, obj): # def __repr__(self): # # Path: sigtools/signatures.py # # Path: sigtools/specifiers.py # class _AsForged(object): # class _ForgerWrapper(object): # def __init__(self): # def __get__(self, instance, owner): # def set_signature_forger(obj, forger, emulate=None): # def _transform(obj, meta): # def __init__(self, obj, forger): # def _sigtools__forger(self, obj): # def __call__(self, *args, **kwargs): # def __get__(self, instance, owner): # def forger_function(func): # def _apply_forger(emulate=None, *args, **kwargs): # def _applier(obj): # def forwards(wrapper, wrapped, *args, **kwargs): # def forwards_to_function(obj, *args, **kwargs): # def forwards_to_method(obj, wrapped_name, *args, **kwargs): # def _get_origin_class(obj, cls): # def forwards_to_super(obj, cls=None, *args, **kwargs): # def apply_forwards_to_super(num_args=0, named_args=(), *member_names, # **kwargs): # def _apply_forwards_to_super(member_names, m_args, m_kwargs, cls): . Output only the next line.
pospars, pokpars, varargs, kwopars, varkwargs = signatures.sort_params(sig)
Given the following code snippet before the placeholder: <|code_start|> >>> func(1, 2, 3, 4, c=5, d=6) {'b': 2, 'a': 1, 'kwargs': {'d': 6}, 'args': (3, 4)} """ return make_func( func_code( *read_sig(sig_str, ret=ret, **kwargs), name=name, pre=pre, ), locals=locals, name=name, future_features=future_features, ) def s(*args, **kwargs): """Creates a signature from the given string representation of one. .. warning:: The contents of the arguments are eventually passed to `exec`. Do not use with untrusted input. :: >>> from sigtools.support import s >>> sig = s('a, b=2, *args, c:"annotation", **kwargs') >>> sig <inspect.Signature object at 0x7f15e6055550> >>> print(sig) (a, b=2, *args, c:'annotation', **kwargs) """ <|code_end|> , predict the next line using imports from the current file: import __future__ import re import sys import itertools from warnings import warn from sigtools import _util, modifiers, signatures, specifiers and context including class names, function names, and sometimes code from other files: # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() # # Path: sigtools/modifiers.py # class _PokTranslator(_util.OverrideableDataDesc): # class annotate(object): # def __new__(cls, func=None, posoargs=(), kwoargs=(), **kwargs): # def __init__(self, func, posoargs=(), kwoargs=(), **kwargs): # def _merge_other(self, other): # def _prepare(self): # def _sigtools__autoforwards_hint(self, func): # def __call__(self, *args, **kwargs): # def parameters(self): # def __repr__(self): # def kwoargs(start=None, *kwoarg_names): # def _kwoargs_start(start, _kwoargs, func, *args, **kwargs): # def posoargs(end=None, *posoarg_names): # def _posoargs_end(end, _posoargs, func, *args, **kwargs): # def autokwoargs(func=None, exceptions=()): # def _autokwoargs(exceptions, func): # def __init__(self, __return_annotation=_util.UNSET, **annotations): # def __call__(self, obj): # def __repr__(self): # # Path: sigtools/signatures.py # # Path: sigtools/specifiers.py # class _AsForged(object): # class _ForgerWrapper(object): # def __init__(self): # def __get__(self, instance, owner): # def set_signature_forger(obj, forger, emulate=None): # def _transform(obj, meta): # def __init__(self, obj, forger): # def _sigtools__forger(self, obj): # def __call__(self, *args, **kwargs): # def __get__(self, instance, owner): # def forger_function(func): # def _apply_forger(emulate=None, *args, **kwargs): # def _applier(obj): # def forwards(wrapper, wrapped, *args, **kwargs): # def forwards_to_function(obj, *args, **kwargs): # def forwards_to_method(obj, wrapped_name, *args, **kwargs): # def _get_origin_class(obj, cls): # def forwards_to_super(obj, cls=None, *args, **kwargs): # def apply_forwards_to_super(num_args=0, named_args=(), *member_names, # **kwargs): # def _apply_forwards_to_super(member_names, m_args, m_kwargs, cls): . Output only the next line.
return specifiers.signature(f(*args, **kwargs))
Using the snippet: <|code_start|> def inner(a, b): raise NotImplementedError class AClass(object): class_attr = True """class attr doc""" def __init__(self): self.abc = 123 """instance attr doc""" @specifiers.forwards_to(inner) def outer(self, c, *args, **kwargs): raise NotImplementedError <|code_end|> , determine the next line of code. You have imports: from sigtools import modifiers, specifiers and context (class names, function names, or code) available: # Path: sigtools/modifiers.py # class _PokTranslator(_util.OverrideableDataDesc): # class annotate(object): # def __new__(cls, func=None, posoargs=(), kwoargs=(), **kwargs): # def __init__(self, func, posoargs=(), kwoargs=(), **kwargs): # def _merge_other(self, other): # def _prepare(self): # def _sigtools__autoforwards_hint(self, func): # def __call__(self, *args, **kwargs): # def parameters(self): # def __repr__(self): # def kwoargs(start=None, *kwoarg_names): # def _kwoargs_start(start, _kwoargs, func, *args, **kwargs): # def posoargs(end=None, *posoarg_names): # def _posoargs_end(end, _posoargs, func, *args, **kwargs): # def autokwoargs(func=None, exceptions=()): # def _autokwoargs(exceptions, func): # def __init__(self, __return_annotation=_util.UNSET, **annotations): # def __call__(self, obj): # def __repr__(self): # # Path: sigtools/specifiers.py # class _AsForged(object): # class _ForgerWrapper(object): # def __init__(self): # def __get__(self, instance, owner): # def set_signature_forger(obj, forger, emulate=None): # def _transform(obj, meta): # def __init__(self, obj, forger): # def _sigtools__forger(self, obj): # def __call__(self, *args, **kwargs): # def __get__(self, instance, owner): # def forger_function(func): # def _apply_forger(emulate=None, *args, **kwargs): # def _applier(obj): # def forwards(wrapper, wrapped, *args, **kwargs): # def forwards_to_function(obj, *args, **kwargs): # def forwards_to_method(obj, wrapped_name, *args, **kwargs): # def _get_origin_class(obj, cls): # def forwards_to_super(obj, cls=None, *args, **kwargs): # def apply_forwards_to_super(num_args=0, named_args=(), *member_names, # **kwargs): # def _apply_forwards_to_super(member_names, m_args, m_kwargs, cls): . Output only the next line.
@modifiers.autokwoargs
Based on the snippet: <|code_start|> def inner(a, b): raise NotImplementedError class AClass(object): class_attr = True """class attr doc""" def __init__(self): self.abc = 123 """instance attr doc""" <|code_end|> , predict the immediate next line with the help of imports: from sigtools import modifiers, specifiers and context (classes, functions, sometimes code) from other files: # Path: sigtools/modifiers.py # class _PokTranslator(_util.OverrideableDataDesc): # class annotate(object): # def __new__(cls, func=None, posoargs=(), kwoargs=(), **kwargs): # def __init__(self, func, posoargs=(), kwoargs=(), **kwargs): # def _merge_other(self, other): # def _prepare(self): # def _sigtools__autoforwards_hint(self, func): # def __call__(self, *args, **kwargs): # def parameters(self): # def __repr__(self): # def kwoargs(start=None, *kwoarg_names): # def _kwoargs_start(start, _kwoargs, func, *args, **kwargs): # def posoargs(end=None, *posoarg_names): # def _posoargs_end(end, _posoargs, func, *args, **kwargs): # def autokwoargs(func=None, exceptions=()): # def _autokwoargs(exceptions, func): # def __init__(self, __return_annotation=_util.UNSET, **annotations): # def __call__(self, obj): # def __repr__(self): # # Path: sigtools/specifiers.py # class _AsForged(object): # class _ForgerWrapper(object): # def __init__(self): # def __get__(self, instance, owner): # def set_signature_forger(obj, forger, emulate=None): # def _transform(obj, meta): # def __init__(self, obj, forger): # def _sigtools__forger(self, obj): # def __call__(self, *args, **kwargs): # def __get__(self, instance, owner): # def forger_function(func): # def _apply_forger(emulate=None, *args, **kwargs): # def _applier(obj): # def forwards(wrapper, wrapped, *args, **kwargs): # def forwards_to_function(obj, *args, **kwargs): # def forwards_to_method(obj, wrapped_name, *args, **kwargs): # def _get_origin_class(obj, cls): # def forwards_to_super(obj, cls=None, *args, **kwargs): # def apply_forwards_to_super(num_args=0, named_args=(), *member_names, # **kwargs): # def _apply_forwards_to_super(member_names, m_args, m_kwargs, cls): . Output only the next line.
@specifiers.forwards_to(inner)
Given the code snippet: <|code_start|># THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. def remove_spaces(s): return s.strip().replace(' ', '') force_modifiers = { 'use_modifiers_annotate': True, 'use_modifiers_posoargs': True, 'use_modifiers_kwoargs': True, } class RoundTripTests(Fixtures): def _test(self, sig_str, old_fmt=None): def assert_signature_matches_original(sig): self._assert_equal_ignoring_spaces(f'({sig_str})', str(sig), f'({old_fmt})') # Using inspect.signature <|code_end|> , generate the next line using the imports in this file: import sys from repeated_test import options from sigtools import support, _specifiers from sigtools.tests.util import Fixtures and context (functions, classes, or occasionally code) from other files: # Path: sigtools/support.py # def read_sig(sig_str, ret=_util.UNSET, *, # use_modifiers_annotate=False, # use_modifiers_posoargs=sys.version_info < (3, 8), # use_modifiers_kwoargs=False, # ): # def func_code(names, return_annotation, annotations, posoarg_n, # kwoarg_n, params, use_modifiers_annotate, # pre='', name='func', # ): # def make_func(source, locals=None, name='func', future_features=()): # def f(sig_str, ret=_util.UNSET, *, pre='', locals=None, name='func', future_features=(), **kwargs): # def s(*args, **kwargs): # def func_from_sig(sig): # def make_up_callsigs(sig, extra=2): # def bind_callsig(sig, args, kwargs): # def sort_callsigs(sig, callsigs): # def test_func_sig_coherent(func, check_return=True, check_invalid=True): # DEBUG_STDLIB=False # # Path: sigtools/_specifiers.py # def forged_signature(obj, auto=True, args=(), kwargs={}): # # Path: sigtools/tests/util.py # def conv_first_posarg(sig): # def func_to_name(func): # def transform_exp_sources(d, subject=None): # def transform_real_sources(d): # def assertSigsEqual(self, found, expected, *args, **kwargs): # def assertSourcesEqual(self, found, expected, func=None, depth_order=False): # def downgrade_sig(self, sig): # class SignatureTests(unittest.TestCase): . Output only the next line.
sig = support.s(sig_str)
Next line prediction: <|code_start|># LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. def remove_spaces(s): return s.strip().replace(' ', '') force_modifiers = { 'use_modifiers_annotate': True, 'use_modifiers_posoargs': True, 'use_modifiers_kwoargs': True, } class RoundTripTests(Fixtures): def _test(self, sig_str, old_fmt=None): def assert_signature_matches_original(sig): self._assert_equal_ignoring_spaces(f'({sig_str})', str(sig), f'({old_fmt})') # Using inspect.signature sig = support.s(sig_str) assert_signature_matches_original(sig) # Roundtrip and use forged signature <|code_end|> . Use current file imports: (import sys from repeated_test import options from sigtools import support, _specifiers from sigtools.tests.util import Fixtures) and context including class names, function names, or small code snippets from other files: # Path: sigtools/support.py # def read_sig(sig_str, ret=_util.UNSET, *, # use_modifiers_annotate=False, # use_modifiers_posoargs=sys.version_info < (3, 8), # use_modifiers_kwoargs=False, # ): # def func_code(names, return_annotation, annotations, posoarg_n, # kwoarg_n, params, use_modifiers_annotate, # pre='', name='func', # ): # def make_func(source, locals=None, name='func', future_features=()): # def f(sig_str, ret=_util.UNSET, *, pre='', locals=None, name='func', future_features=(), **kwargs): # def s(*args, **kwargs): # def func_from_sig(sig): # def make_up_callsigs(sig, extra=2): # def bind_callsig(sig, args, kwargs): # def sort_callsigs(sig, callsigs): # def test_func_sig_coherent(func, check_return=True, check_invalid=True): # DEBUG_STDLIB=False # # Path: sigtools/_specifiers.py # def forged_signature(obj, auto=True, args=(), kwargs={}): # # Path: sigtools/tests/util.py # def conv_first_posarg(sig): # def func_to_name(func): # def transform_exp_sources(d, subject=None): # def transform_real_sources(d): # def assertSigsEqual(self, found, expected, *args, **kwargs): # def assertSourcesEqual(self, found, expected, func=None, depth_order=False): # def downgrade_sig(self, sig): # class SignatureTests(unittest.TestCase): . Output only the next line.
pf_sig = _specifiers.forged_signature(support.func_from_sig(sig))
Given the following code snippet before the placeholder: <|code_start|># copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. def remove_spaces(s): return s.strip().replace(' ', '') force_modifiers = { 'use_modifiers_annotate': True, 'use_modifiers_posoargs': True, 'use_modifiers_kwoargs': True, } <|code_end|> , predict the next line using imports from the current file: import sys from repeated_test import options from sigtools import support, _specifiers from sigtools.tests.util import Fixtures and context including class names, function names, and sometimes code from other files: # Path: sigtools/support.py # def read_sig(sig_str, ret=_util.UNSET, *, # use_modifiers_annotate=False, # use_modifiers_posoargs=sys.version_info < (3, 8), # use_modifiers_kwoargs=False, # ): # def func_code(names, return_annotation, annotations, posoarg_n, # kwoarg_n, params, use_modifiers_annotate, # pre='', name='func', # ): # def make_func(source, locals=None, name='func', future_features=()): # def f(sig_str, ret=_util.UNSET, *, pre='', locals=None, name='func', future_features=(), **kwargs): # def s(*args, **kwargs): # def func_from_sig(sig): # def make_up_callsigs(sig, extra=2): # def bind_callsig(sig, args, kwargs): # def sort_callsigs(sig, callsigs): # def test_func_sig_coherent(func, check_return=True, check_invalid=True): # DEBUG_STDLIB=False # # Path: sigtools/_specifiers.py # def forged_signature(obj, auto=True, args=(), kwargs={}): # # Path: sigtools/tests/util.py # def conv_first_posarg(sig): # def func_to_name(func): # def transform_exp_sources(d, subject=None): # def transform_real_sources(d): # def assertSigsEqual(self, found, expected, *args, **kwargs): # def assertSourcesEqual(self, found, expected, func=None, depth_order=False): # def downgrade_sig(self, sig): # class SignatureTests(unittest.TestCase): . Output only the next line.
class RoundTripTests(Fixtures):
Given the following code snippet before the placeholder: <|code_start|># sigtools - Collection of Python modules for manipulating function signatures # Copyright (C) 2013-2021 Yann Kaiser # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. class MergeTests(Fixtures): def _test(self, result, exp_sources, *signatures): assert len(signatures) >= 2 sigs = [s(sig, name='_' + str(i)) for i, sig in enumerate(signatures, 1)] <|code_end|> , predict the next line using imports from the current file: from sigtools.signatures import merge, IncompatibleSignatures from sigtools.support import s from sigtools.tests.util import Fixtures from sigtools._util import OrderedDict as Od, funcsigs and context including class names, function names, and sometimes code from other files: # Path: sigtools/signatures.py # # Path: sigtools/support.py # def s(*args, **kwargs): # """Creates a signature from the given string representation of one. # # .. warning:: # The contents of the arguments are eventually passed to `exec`. # Do not use with untrusted input. # # :: # # >>> from sigtools.support import s # >>> sig = s('a, b=2, *args, c:"annotation", **kwargs') # >>> sig # <inspect.Signature object at 0x7f15e6055550> # >>> print(sig) # (a, b=2, *args, c:'annotation', **kwargs) # """ # return specifiers.signature(f(*args, **kwargs)) # # Path: sigtools/tests/util.py # def conv_first_posarg(sig): # def func_to_name(func): # def transform_exp_sources(d, subject=None): # def transform_real_sources(d): # def assertSigsEqual(self, found, expected, *args, **kwargs): # def assertSourcesEqual(self, found, expected, func=None, depth_order=False): # def downgrade_sig(self, sig): # class SignatureTests(unittest.TestCase): # # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() . Output only the next line.
sig = merge(*sigs)
Here is a snippet: <|code_start|> annotation_right = 'a:1', {1: 'a', 2: 'a'}, 'a', 'a:1' star_erase = '', {}, '*args', '' star_same = '*args', {1: ['args'], 2: ['args']}, '*args', '*args' star_name = '*largs', {1: ['largs']}, '*largs', '*rargs' star_same_pok = ( 'a, *args', Od([(1, ['a', 'args']), (2, ['a', 'args'])]), 'a, *args', 'a, *args') star_extend = '<a>, *args', {1: ['a', 'args']}, '<a>, *args', '*args' star_extend_r = '<a>, *args', {2: ['a', 'args']}, '*args', '<a>, *args' stars_erase = '', {}, '**kwargs', '' stars_same = '**kwargs', {1: ['kwargs'], 2: ['kwargs']}, '**kwargs', '**kwargs' stars_name = '**lkwargs', {1: ['lkwargs']}, '**lkwargs', '**rkwargs' stars_extend = '*, a, **kwargs', {2: ['a', 'kwargs']}, '**kwargs', '*, a, **kwargs' stars_extend_r = '*, a, **kwargs', {1: ['a', 'kwargs']}, '*, a, **kwargs', '**kwargs' def test_omit_sources(self): s1 = s('a, *args, **kwargs') s2 = s('a, *args, **kwargs') ret = merge(s1, s2) self.assertSigsEqual(ret, s('a, *args, **kwargs')) three = '*, a, b, c, **k', {1: 'a', 2: 'b', 3: 'ck'}, '*, a, **k', '*, b, **k', '*, c, **k' class MergeRaiseTests(Fixtures): def _test(self, *signatures): assert len(signatures) >= 2 sigs = [s(sig) for sig in signatures] <|code_end|> . Write the next line using the current file imports: from sigtools.signatures import merge, IncompatibleSignatures from sigtools.support import s from sigtools.tests.util import Fixtures from sigtools._util import OrderedDict as Od, funcsigs and context from other files: # Path: sigtools/signatures.py # # Path: sigtools/support.py # def s(*args, **kwargs): # """Creates a signature from the given string representation of one. # # .. warning:: # The contents of the arguments are eventually passed to `exec`. # Do not use with untrusted input. # # :: # # >>> from sigtools.support import s # >>> sig = s('a, b=2, *args, c:"annotation", **kwargs') # >>> sig # <inspect.Signature object at 0x7f15e6055550> # >>> print(sig) # (a, b=2, *args, c:'annotation', **kwargs) # """ # return specifiers.signature(f(*args, **kwargs)) # # Path: sigtools/tests/util.py # def conv_first_posarg(sig): # def func_to_name(func): # def transform_exp_sources(d, subject=None): # def transform_real_sources(d): # def assertSigsEqual(self, found, expected, *args, **kwargs): # def assertSourcesEqual(self, found, expected, func=None, depth_order=False): # def downgrade_sig(self, sig): # class SignatureTests(unittest.TestCase): # # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() , which may include functions, classes, or code. Output only the next line.
self.assertRaises(IncompatibleSignatures, merge, *sigs)
Given snippet: <|code_start|>#!/usr/bin/env python # sigtools - Collection of Python modules for manipulating function signatures # Copyright (C) 2013-2021 Yann Kaiser # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. class MergeTests(Fixtures): def _test(self, result, exp_sources, *signatures): assert len(signatures) >= 2 <|code_end|> , continue by predicting the next line. Consider current file imports: from sigtools.signatures import merge, IncompatibleSignatures from sigtools.support import s from sigtools.tests.util import Fixtures from sigtools._util import OrderedDict as Od, funcsigs and context: # Path: sigtools/signatures.py # # Path: sigtools/support.py # def s(*args, **kwargs): # """Creates a signature from the given string representation of one. # # .. warning:: # The contents of the arguments are eventually passed to `exec`. # Do not use with untrusted input. # # :: # # >>> from sigtools.support import s # >>> sig = s('a, b=2, *args, c:"annotation", **kwargs') # >>> sig # <inspect.Signature object at 0x7f15e6055550> # >>> print(sig) # (a, b=2, *args, c:'annotation', **kwargs) # """ # return specifiers.signature(f(*args, **kwargs)) # # Path: sigtools/tests/util.py # def conv_first_posarg(sig): # def func_to_name(func): # def transform_exp_sources(d, subject=None): # def transform_real_sources(d): # def assertSigsEqual(self, found, expected, *args, **kwargs): # def assertSourcesEqual(self, found, expected, func=None, depth_order=False): # def downgrade_sig(self, sig): # class SignatureTests(unittest.TestCase): # # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() which might include code, classes, or functions. Output only the next line.
sigs = [s(sig, name='_' + str(i))
Using the snippet: <|code_start|> sig = merge(*sigs) exp_sig = s(result) exp_sources['+depths'] = dict( ('_' + str(i + 1), 0) for i in range(len(signatures))) self.assertSigsEqual(sig, exp_sig) self.assertSourcesEqual(sig.sources, exp_sources) sigs = [ funcsigs.Signature(sig.parameters.values(), return_annotation=sig.return_annotation) for sig in sigs] self.assertSigsEqual(merge(*sigs), exp_sig) posarg_default_erase = '', {}, '', '<a>=1' posarg_stars = '<a>', {2: 'a'}, '*args', '<a>' posarg_convert = '<a>', {1: 'a'}, '<a>', 'b' posarg_convert_left = '<b>', {2: 'b'}, 'a', '<b>' pokarg_default_erase = '', {}, '', 'a=1' pokarg_star_convert_pos = '<a>', {2: 'a'}, '*args', 'a' pokarg_star_convert_kwo = '*, a', {2: 'a'}, '**kwargs', 'a' pokarg_star_keep = 'a', {2: 'a'}, '*args, **kwargs', 'a' pokarg_rename = '<a>', {1: 'a'}, 'a', 'b' pokarg_rename_second = '<a>, <b>', {1: 'ab', 2: 'a'}, 'a, b', 'a, c' <|code_end|> , determine the next line of code. You have imports: from sigtools.signatures import merge, IncompatibleSignatures from sigtools.support import s from sigtools.tests.util import Fixtures from sigtools._util import OrderedDict as Od, funcsigs and context (class names, function names, or code) available: # Path: sigtools/signatures.py # # Path: sigtools/support.py # def s(*args, **kwargs): # """Creates a signature from the given string representation of one. # # .. warning:: # The contents of the arguments are eventually passed to `exec`. # Do not use with untrusted input. # # :: # # >>> from sigtools.support import s # >>> sig = s('a, b=2, *args, c:"annotation", **kwargs') # >>> sig # <inspect.Signature object at 0x7f15e6055550> # >>> print(sig) # (a, b=2, *args, c:'annotation', **kwargs) # """ # return specifiers.signature(f(*args, **kwargs)) # # Path: sigtools/tests/util.py # def conv_first_posarg(sig): # def func_to_name(func): # def transform_exp_sources(d, subject=None): # def transform_real_sources(d): # def assertSigsEqual(self, found, expected, *args, **kwargs): # def assertSourcesEqual(self, found, expected, func=None, depth_order=False): # def downgrade_sig(self, sig): # class SignatureTests(unittest.TestCase): # # Path: sigtools/_util.py # def get_funcsigs(): # def __repr__(self): # def noop(func): # def qualname(obj): # def __init__(self, *args, **kwargs): # def cg(func, **kwargs): # def __get__(self, instance, owner): # def safe_get(obj, instance, owner): # def iter_call(obj): # def get_introspectable(obj, forged=True, af_hint=True, partial=True): # def get_ast(func): # class _Unset(object): # class OverrideableDataDesc(object): # UNSET = _Unset() . Output only the next line.
pokarg_found_kwo = '*, a', Od([(1, 'a'), (2, 'a')]), '*, a', 'a'
Continue the code snippet: <|code_start|>logger = logging.getLogger(__name__) class CommandAdmin(admin.ModelAdmin): list_display = ('title', 'command', 'created', 'updated', "order") search_fields = ['title', 'command'] prepopulated_fields = {'slug': ('title',)} actions = tuple(list(admin.ModelAdmin.actions) + ['run_commands']) def run_commands(self, request, queryset): qs = queryset.order_by("order") count_wanted = qs.count() count_executed = count_wanted for c in qs: if c.has_filled_command(): try: c.execute() except Exception, e: logger.error("Command executed from admin failed", exc_info=True) self.message_user(request, _("Comand %(title)s faild, %(error)s") % {"title": c.title, "error": e}) count_executed -= 1 else: count_executed -= 1 logger.warning("Command %s is empty", c.slug) self.message_user(request, _("%(ce)s commands from %(cw)s was successfully executed") % {"ce": count_executed, "cw": count_wanted}) run_commands.short_description = _("Run commands") <|code_end|> . Use current file imports: from django.utils.translation import ugettext_lazy as _ from django.contrib import admin from commander.models import Command import logging and context (classes, functions, or code) from other files: # Path: commander/models.py # class Command(models.Model): # title = models.CharField(_('Title'), max_length=200) # slug = models.SlugField(_('Slug'), max_length=200, unique=True) # command = models.TextField(_('Command'), blank=True) # created = models.DateTimeField(_('Created'), editable=False) # updated = models.DateTimeField(_('Updated'), editable=False) # order = models.IntegerField(_('Command run order'), default=0) # # class Meta: # verbose_name = _('Command') # verbose_name_plural = _('Commands') # # def __unicode__(self): # return self.title # # def save(self, **kwargs): # self.updated = now() # if not self.id: # self.created = self.updated # # if not self.slug: # self.slug = slugify(self.title) # super(Command, self).save(**kwargs) # # def has_filled_command(self): # return bool(self.command) # # def _prepare_command(self): # def _parse_value(value): # if value == "True": # return True # if value == "False": # return False # if "." in value: # try: # return float(value) # except ValueError: # return value # try: # return int(value) # except ValueError: # return value # a = [] # kw = dict() # command = self.command.strip() # command_parts = delimiter_re.split(command) # c = command_parts[0] # for cp in command_parts[1:]: # if "=" in cp: # key, value = cp.split("=") # kw[key] = _parse_value(value) # else: # a.append(cp) # return c, a, kw # # def execute(self): # c, a, kw = self._prepare_command() # return call_command(c, *a, **kw) . Output only the next line.
admin.site.register(Command, CommandAdmin)
Given the code snippet: <|code_start|> class Command(BaseCommand): help = "Pulls tweets via and associates with a given fire" def handle(self, *args, **options): <|code_end|> , generate the next line using the imports in this file: from django.core.management.base import BaseCommand from calfire_tracker.tweet_manager import TwitterHashtagSearch import datetime and context (functions, classes, or occasionally code) from other files: # Path: calfire_tracker/tweet_manager.py # class TwitterHashtagSearch(object): # # def __init__(self): # date_object = datetime.datetime.now() # queryset = CalWildfire.objects.filter( # year=date_object.year).order_by("-date_time_started", "fire_name") # for item in queryset: # max_id = None # search_is_done = False # while (search_is_done == False): # tweet_results = self.get_tweets(item.twitter_hashtag, max_id) # self.build_tweet_from(item.twitter_hashtag, tweet_results) # if max_id == None: # search_is_done = True # else: # logger.debug("Retrieving more tweets since %s" % (max_id)) # # def get_tweets(self, hashtag, max_id): # """ # function to auth with twitter and return tweets # """ # twitter_object = Twitter( # auth=OAuth( # TWITTER_ACCESS_TOKEN, # TWITTER_ACCESS_TOKEN_SECRET, # TWITTER_CONSUMER_KEY, # TWITTER_CONSUMER_SECRET # ) # ) # try: # tweet_results = twitter_object.search.tweets( # q=hashtag, # count=100, # result_type="recent", # include_entities=False, # max_id=max_id, # lang="en" # ) # return tweet_results # except TwitterHTTPError, exception: # logger.error(exception.response_data["errors"]) # if exception.response_data["errors"][0]["code"] == 88: # return # # def get_max_id(self, results): # """ # get the max_id of the next twitter search if present # """ # # see if the metadata has a next_results key # # value is the idea to pull tweets from # more_tweets = results["search_metadata"].has_key("next_results") # # if there are more # if more_tweets == True: # # find the max id # parsed_string = results["search_metadata"][ # "next_results"].split("&") # parsed_string = parsed_string[0].split("?max_id=") # max_id = parsed_string[1] # # otherwise # else: # # max id is nothing # max_id = None # # return the max id # return max_id # # def build_tweet_from(self, hashtag, results): # """ # function to auth with twitter and return tweets # """ # for tweet in results["statuses"]: # if tweet["retweet_count"] == 0 or tweet["retweet_count"] == None: # logger.debug("%s: %s" % (hashtag, len(results))) # tweet_date = parser.parse(tweet["created_at"]) # tweet_date = tweet_date.replace(tzinfo=TWITTER_TIMEZONE) # obj = TwitterHashtagResult( # hashtag, # tweet["text"].encode("ascii", "ignore"), # tweet_date, # tweet["id"], # tweet["user"]["screen_name"].encode("ascii", "ignore"), # tweet["user"]["profile_image_url"].encode( # "ascii", "ignore"), # ) # obj.save_tweet(obj) . Output only the next line.
task_run = TwitterHashtagSearch()
Predict the next line for this snippet: <|code_start|> logger = logging.getLogger("calfire_tracker") class Compiler(TestCase): fixtures = ["calfire_tracker/fixtures/wildfire_sources.json"] def setUp(self): """ setup some variables for our tests """ logger.debug("Setting up tests") self.date_object = datetime.datetime.now() self.date_string = self.date_object.strftime("%Y_%m_%d_%H_%M_%S") <|code_end|> with the help of current file imports: from django.test import SimpleTestCase, TestCase from django.conf import settings from calfire_tracker.models import WildfireSource from requests.packages.urllib3.util.retry import Retry from requests.adapters import HTTPAdapter from BeautifulSoup import BeautifulSoup, Tag, BeautifulStoneSoup import requests import datetime import logging import re and context from other files: # Path: calfire_tracker/models.py # class WildfireSource(models.Model): # """ # describes a source of data for a wildfire # """ # SIMPLE = "Simple Scrape" # COMPLEX = "Complex Scrape" # API = "API request" # # EXTRACTION_CHOICES = ( # (SIMPLE, "Simple Scrape"), # (COMPLEX, "Complex Scrape"), # (API, "API request"), # ) # # source_name = models.CharField("Data Source Name", db_index=True, unique=True, max_length=255) # source_short = models.CharField("Data Source Shortname", max_length=15) # source_slug = models.SlugField("Data Source Slug", unique=True, max_length=255, null=True, blank=True) # source_url = models.URLField("URL To Data Source", max_length=1024, null=True, blank=True) # source_active = models.BooleanField("Active Data Source?", default=False) # parent_tag = models.CharField("Parent HTML Tag", max_length=255, null=True, blank=True) # parent_attrib = models.CharField("Parent Attribute (id/class)", max_length=255, null=True, blank=True) # parent_selector = models.CharField("Parent Selector (id/class name)", max_length=255, null=True, blank=True) # target_tag = models.CharField("Target HTML Tag", max_length=255, null=True, blank=True) # target_attrib = models.CharField("Target Attribute (id/class)", max_length=255, null=True, blank=True) # target_selector = models.CharField("Target Selector (id/class name)", max_length=255, null=True, blank=True) # extraction_type = models.CharField("How Hard is Data Acquisition?", max_length=255, choices=EXTRACTION_CHOICES, default=SIMPLE) # target_index = models.IntegerField("List Element for Targeted Selector", max_length=3, null=True, blank=True) # data_paginated = models.BooleanField("Does the source use pagination?", default=False) # number_of_pages = models.IntegerField("How many pages?", max_length=5, null=True, blank=True) # created = models.DateTimeField("Date Created", auto_now_add=True) # modified = models.DateTimeField("Date Modified", auto_now=True) # # def __unicode__(self): # return self.source_short # # def save(self, *args, **kwargs): # super(WildfireSource, self).save(*args, **kwargs) , which may contain function names, class names, or code. Output only the next line.
self.source = WildfireSource.objects.filter(source_short="calfire", source_active=True)[0]
Here is a snippet: <|code_start|> logger = logging.getLogger("calfire_tracker") class Command(BaseCommand): help = "Scrapes California Wildfires data from CalFire and some Inciweb Pages" def calfire_current_incidents(self, *args, **options): <|code_end|> . Write the next line using the current file imports: from django.conf import settings from django.core.management.base import BaseCommand from calfire_tracker.manager_calfire import RetrieveCalFireCurrentIncidents import datetime import logging and context from other files: # Path: calfire_tracker/manager_calfire.py # class RetrieveCalFireCurrentIncidents(object): # """ # """ # # req = Requester() # prep = Prepper() # norm = Normalizer() # svr = Saver() # source = WildfireSource.objects.filter(source_short="calfire", source_active=True)[0] # # def _init(self, *args, **kwargs): # """ # """ # self.source.raw_html = self.req._make_request_to(self.source.source_url) # self.source.soup = self.req._make_soup_from(self.source.raw_html) # if self.source.extraction_type == "Simple Scrape": # self.req._extract_simple_data_from(self.source) # else: # logger.debug("**need a new scraper**") # for table in self.source.target_content: # f = self.prep.give_fire() # f["name"] = table.findAll("tr")[0].findAll("td")[0].text.encode("utf-8") # f["name"] = f["name"].replace(":", "").replace("more info...", "").strip() # f["details_source"] = self.source.source_short # table_row = table.findAll("tr")[1:] # f = self.prep.tablerow_to_dicts(table_row, f) # f["details_link"] = self.prep.has_calfire_link(table.findAll("tr")[0].findAll("td")[0]) # if f["details_link"]: # logger.debug("gonna need to request the details url") # raw_html = self.req._make_request_to(f["details_link"]) # soup = self.req._make_soup_from(raw_html) # table = soup.findAll("table", {"id": "incident_information"}) # table_row = table[0].findAll("tr")[1:] # f = self.prep.tablerow_to_dicts(table_row, f) # f["update_this_fire"] = self.prep.fire_exists_and_is_new(f) # # f = {k: v for k, v in f.iteritems() if v is not None} # output = self.norm.marshal_fire_data(f) # self.svr.save_dict_to_model(output) , which may include functions, classes, or code. Output only the next line.
task_run = RetrieveCalFireCurrentIncidents()
Using the snippet: <|code_start|> class Agora(models.Model): ''' Represents an Agora, formed by a group of people which can vote and delegate ''' ELECTION_TYPES = ( ('SIMPLE_DELEGATION', _('Simple election for delegates where only one delegate can be chosen')), <|code_end|> , determine the next line of code. You have imports: import datetime import uuid from django.conf import settings from django.core.urlresolvers import reverse from django.contrib.auth.models import User from django.db import models from django.db.models import Q from django.template.defaultfilters import slugify from django.utils.translation import ugettext_lazy as _ from django.utils import timezone from django.db.models.signals import post_save from django.core.validators import validate_email from django.core.exceptions import ValidationError from guardian.shortcuts import * from agora_site.misc.utils import JSONField, get_users_with_perm from agora_site.agora_core.models.voting_systems.base import parse_voting_methods from actstream.models import Action from agora_site.agora_core.models import CastVote from agora_site.agora_core.models import CastVote from agora_site.agora_core.models import CastVote from agora_site.agora_core.models import Election and context (class names, function names, or code) available: # Path: agora_site/agora_core/models/voting_systems/base.py # def parse_voting_methods(): # ''' # Returns a tuple of pairs with the id and description of the voting system # classes # ''' # classes = get_voting_system_classes() # return tuple( # [(k.get_id(), k.get_description()) for k in classes] # ) . Output only the next line.
) + parse_voting_methods()
Given the code snippet: <|code_start|> # find question in election question = None for q in self.election.questions: if q['question'] == self.label: question = q # gather possible answers possible_answers = [answer['value'] for answer in question['answers']] # check the answers provided are valid for i in value: if i not in possible_answers: raise error # NOTE: in the future, when encryption support is added, this will be # handled differently, probably in a more generic way so that # BaseSTVField doesn't know anything about plaintext or encryption. if len(value) > 0: clean_value = super(BaseSTVField, self).clean(value) return { "a": "plaintext-answer", "choices": clean_value, } else: return { "a": "plaintext-answer", "choices": [], } <|code_end|> , generate the next line using the imports in this file: import random import copy import sys import os import uuid import codecs from django import forms as django_forms from django.conf import settings from django.utils.translation import ugettext_lazy as _ from .base import BaseVotingSystem, BaseTally from agora_site.misc.utils import * from openstv.ballots import Ballots from openstv.plugins import getMethodPlugins from .json_report import JsonReport and context (functions, classes, or occasionally code) from other files: # Path: agora_site/agora_core/models/voting_systems/base.py # class BaseVotingSystem(object): # ''' # Defines the helper functions that allows agora to manage a voting system. # ''' # # @staticmethod # def get_id(): # ''' # Returns the identifier of the voting system, used internally to # discriminate the voting system used in an election # ''' # return 'base' # # @staticmethod # def get_description(): # ''' # Returns the user text description of the voting system # ''' # pass # # @staticmethod # def create_tally(election, question_num): # ''' # Create object that helps to compute the tally # ''' # return BaseTally(election, question_num) # # @staticmethod # def get_question_field(election, question): # ''' # Creates a voting field that can be used to answer a question in a ballot # ''' # pass # # @staticmethod # def validate_question(question): # ''' # Validates the value of a given question in an election. Raises a # django_forms.ValidationError exception if validation fails # ''' # pass # # class BaseTally(object): # ''' # Class oser to tally an election # ''' # election = None # question_num = None # # def __init__(self, election, question_num): # self.election = election # self.question_num = question_num # self.init() # # def init(self): # pass # # def pre_tally(self, result): # ''' # Function called once before the tally begins # ''' # pass # # def add_vote(self, voter_answers, result, is_delegated): # ''' # Add to the count a vote from a voter # ''' # pass # # def post_tally(self, result): # ''' # Once all votes have been added, this function is called once # ''' # pass # # def get_log(self): # ''' # Returns the tally log. Called after post_tally() # ''' # return None . Output only the next line.
class BaseSTVTally(BaseTally):
Here is a snippet: <|code_start|> def __init__(self, *args, **kwargs): self.election = kwargs['election'] del kwargs['election'] self.question = kwargs['question'] del kwargs['question'] return super(PluralityField, self).__init__(*args, **kwargs) def clean(self, value): """ Wraps the choice field the proper way """ # NOTE: in the future, when encryption support is added, this will be # handled differently, probably in a more generic way so that # PluralityField doesn't know anything about plaintext or encryption. if value or self.question['min'] > 0: clean_value = super(PluralityField, self).clean(value) return { "a": "plaintext-answer", "choices": [clean_value], } else: return { "a": "plaintext-answer", "choices": [], } <|code_end|> . Write the next line using the current file imports: import random from django import forms as django_forms from django.utils.translation import ugettext_lazy as _ from .base import BaseVotingSystem, BaseTally from agora_site.misc.utils import * and context from other files: # Path: agora_site/agora_core/models/voting_systems/base.py # class BaseVotingSystem(object): # ''' # Defines the helper functions that allows agora to manage a voting system. # ''' # # @staticmethod # def get_id(): # ''' # Returns the identifier of the voting system, used internally to # discriminate the voting system used in an election # ''' # return 'base' # # @staticmethod # def get_description(): # ''' # Returns the user text description of the voting system # ''' # pass # # @staticmethod # def create_tally(election, question_num): # ''' # Create object that helps to compute the tally # ''' # return BaseTally(election, question_num) # # @staticmethod # def get_question_field(election, question): # ''' # Creates a voting field that can be used to answer a question in a ballot # ''' # pass # # @staticmethod # def validate_question(question): # ''' # Validates the value of a given question in an election. Raises a # django_forms.ValidationError exception if validation fails # ''' # pass # # class BaseTally(object): # ''' # Class oser to tally an election # ''' # election = None # question_num = None # # def __init__(self, election, question_num): # self.election = election # self.question_num = question_num # self.init() # # def init(self): # pass # # def pre_tally(self, result): # ''' # Function called once before the tally begins # ''' # pass # # def add_vote(self, voter_answers, result, is_delegated): # ''' # Add to the count a vote from a voter # ''' # pass # # def post_tally(self, result): # ''' # Once all votes have been added, this function is called once # ''' # pass # # def get_log(self): # ''' # Returns the tally log. Called after post_tally() # ''' # return None , which may include functions, classes, or code. Output only the next line.
class PluralityTally(BaseTally):
Given the code snippet: <|code_start|> if not election.is_frozen(): election.frozen_at_date = election.archived_at_date election.save() context = get_base_email_context(self.request) context.update(dict( election=election, election_url=reverse('election-view', kwargs=dict(username=election.agora.creator.username, agoraname=election.agora.name, electionname=election.name)), agora_url=reverse('agora-view', kwargs=dict(username=election.agora.creator.username, agoraname=election.agora.name)), )) # List of emails to send. tuples are of format: # # (subject, text, html, from_email, recipient) datatuples = [] for vote in election.get_all_votes(): if not vote.voter.email or not vote.voter.get_profile().email_updates: continue context['to'] = vote.voter try: <|code_end|> , generate the next line using the imports in this file: import datetime from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required, user_passes_test from django.contrib.auth.models import User from django.conf.urls import patterns, url, include from django.conf import settings from django.core.urlresolvers import reverse from django.core.mail import EmailMultiAlternatives, EmailMessage, send_mass_mail from django.utils import simplejson as json from django.utils.decorators import method_decorator from django.utils.translation import ugettext as _ from django.utils.translation import check_for_language from django.utils import timezone from django.shortcuts import redirect, get_object_or_404, render_to_response from django.template.loader import render_to_string from django.views.generic import TemplateView, ListView, CreateView, RedirectView from django.views.generic.edit import UpdateView, FormView from django.views.i18n import set_language as django_set_language from django import http from django.db import transaction from actstream.actions import follow, unfollow, is_following from actstream.models import (object_stream, election_stream, Action, user_stream, actor_stream) from actstream.signals import action from guardian.shortcuts import * from haystack.query import EmptySearchQuerySet from haystack.forms import ModelSearchForm, FacetedSearchForm from haystack.query import SearchQuerySet from haystack.views import SearchView as HaystackSearchView from agora_site.agora_core.templatetags.agora_utils import get_delegate_in_agora from agora_site.agora_core.models import Agora, Election, Profile, CastVote from agora_site.agora_core.backends.fnmt import fnmt_data_from_pem from agora_site.agora_core.forms import * from agora_site.agora_core.tasks import * from agora_site.misc.utils import * and context (functions, classes, or occasionally code) from other files: # Path: agora_site/agora_core/templatetags/agora_utils.py # @register.filter # def get_delegate_in_agora(user, agora): # return user.get_profile().get_delegation_in_agora(agora).get_delegate() . Output only the next line.
context['delegate'] = get_delegate_in_agora(vote.voter, election.agora)
Using the snippet: <|code_start|># Copyright (C) 2012 Eduardo Robles Elvira <edulix AT wadobo DOT com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. if 'rosetta' in settings.INSTALLED_APPS: urlpatterns = patterns('', url(r'^rosetta/', include('rosetta.urls')), ) # The Agora REST v API urlpatterns += patterns('', <|code_end|> , determine the next line of code. You have imports: from django.conf.urls.defaults import * from django.contrib.auth.decorators import login_required from django.views.generic import CreateView, RedirectView, TemplateView from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ from agora_site.agora_core.views import * from agora_site.misc.utils import RequestCreateView from .api import v1 and context (class names, function names, or code) available: # Path: agora_site/agora_core/api.py . Output only the next line.
url(r'^api/', include(v1.urls)),
Based on the snippet: <|code_start|> if not isinstance(value, list): raise error # check for repeated answers if len(value) != len(set(value)): raise error # find question in election question = None for q in self.election.questions: if q['question'] == self.label: question = q # gather possible answers possible_answers = [answer['value'] for answer in question['answers']] # check the answers provided are valid for i in value: if i not in possible_answers: raise error # NOTE: in the future, when encryption support is added, this will be # handled differently, probably in a more generic way so that # WrightSTVField doesn't know anything about plaintext or encryption. return { "a": "plaintext-answer", "choices": clean_value, } <|code_end|> , predict the immediate next line with the help of imports: import random import copy import sys from django import forms as django_forms from django.utils.translation import ugettext_lazy as _ from .base import BaseVotingSystem, BaseTally from agora_site.misc.utils import * and context (classes, functions, sometimes code) from other files: # Path: agora_site/agora_core/models/voting_systems/base.py # class BaseVotingSystem(object): # ''' # Defines the helper functions that allows agora to manage a voting system. # ''' # # @staticmethod # def get_id(): # ''' # Returns the identifier of the voting system, used internally to # discriminate the voting system used in an election # ''' # return 'base' # # @staticmethod # def get_description(): # ''' # Returns the user text description of the voting system # ''' # pass # # @staticmethod # def create_tally(election, question_num): # ''' # Create object that helps to compute the tally # ''' # return BaseTally(election, question_num) # # @staticmethod # def get_question_field(election, question): # ''' # Creates a voting field that can be used to answer a question in a ballot # ''' # pass # # @staticmethod # def validate_question(question): # ''' # Validates the value of a given question in an election. Raises a # django_forms.ValidationError exception if validation fails # ''' # pass # # class BaseTally(object): # ''' # Class oser to tally an election # ''' # election = None # question_num = None # # def __init__(self, election, question_num): # self.election = election # self.question_num = question_num # self.init() # # def init(self): # pass # # def pre_tally(self, result): # ''' # Function called once before the tally begins # ''' # pass # # def add_vote(self, voter_answers, result, is_delegated): # ''' # Add to the count a vote from a voter # ''' # pass # # def post_tally(self, result): # ''' # Once all votes have been added, this function is called once # ''' # pass # # def get_log(self): # ''' # Returns the tally log. Called after post_tally() # ''' # return None . Output only the next line.
class WrightSTVTally(BaseTally):
Given the following code snippet before the placeholder: <|code_start|> # anonymous user has no special permissions data = self.postAndParse('agora/1/action/', data=orig_data, code=HTTP_OK, content_type='application/json') self.assertEquals(set(data["permissions"]), set([])) # david user should have admin permissions self.login('david', 'david') data = self.postAndParse('agora/1/action/', data=orig_data, code=HTTP_OK, content_type='application/json') self.assertEquals(set(data["permissions"]), set(['admin', 'delete', 'comment', 'create_election', 'delegate', 'receive_mail'])) # user2 should have some permissions self.login('user2', '123') data = self.postAndParse('agora/1/action/', data=orig_data, code=HTTP_OK, content_type='application/json') self.assertEquals(set(data["permissions"]), set(['join', 'comment', 'create_election'])) def test_send_request_membership_mails(self): ''' test the celery send_request_membership_mails function ''' kwargs=dict( agora_id=1, user_id=1, is_secure=True, site_id=Site.objects.all()[0].id, remote_addr='127.0.0.1' ) <|code_end|> , predict the next line using imports from the current file: from common import (HTTP_OK, HTTP_CREATED, HTTP_ACCEPTED, HTTP_NO_CONTENT, HTTP_BAD_REQUEST, HTTP_FORBIDDEN, HTTP_NOT_FOUND, HTTP_METHOD_NOT_ALLOWED) from common import RootTestCase from django.contrib.sites.models import Site from django.contrib.markup.templatetags.markup import textile from agora_site.agora_core.tasks.agora import send_request_membership_mails and context including class names, function names, and sometimes code from other files: # Path: agora_site/agora_core/tasks/agora.py # @task(ignore_result=True) # def send_request_membership_mails(agora_id, user_id, is_secure, site_id, remote_addr): # user = User.objects.get(pk=user_id) # agora = Agora.objects.get(pk=agora_id) # # # Mail to the admins # context = get_base_email_context_task(is_secure, site_id) # context.update(dict( # agora=agora, # other_user=user, # notification_text=_('%(username)s has requested membership at ' # '%(agora)s. Please review this pending request') % dict( # username=user.username, # agora=agora.get_full_name() # ), # extra_urls=( # (_('List of membership requests'), # reverse('agora-members', # kwargs=dict( # username=agora.creator, # agoraname=agora.name, # members_filter="membership_requests" # )) # ), # ), # )) # for admin in agora.admins.all(): # translation.activate(admin.get_profile().lang_code) # # if not admin.get_profile().has_perms('receive_email_updates'): # continue # # context['to'] = admin # # email = EmailMultiAlternatives( # subject=_('%(site)s - New membership request at %(agora)s') %\ # dict( # site=Site.objects.get_current().domain, # agora=agora.get_full_name() # ), # body=render_to_string('agora_core/emails/agora_notification.txt', # context), # to=[admin.email]) # # email.attach_alternative( # render_to_string('agora_core/emails/agora_notification.html', # context), "text/html") # email.send() # # translation.deactivate() . Output only the next line.
result = send_request_membership_mails.apply_async(kwargs=kwargs)
Based on the snippet: <|code_start|> # Give permissions to view and change profile for perm in ASSIGNED_PERMISSIONS['profile']: assign(perm[0], new_user, new_profile) # Give permissions to view and change itself for perm in ASSIGNED_PERMISSIONS['user']: assign(perm[0], new_user, new_user) if send_email: userena_profile.send_activation_email() # Send the signup complete signal userena_signals.signup_complete.send(sender=None, user=new_user) return new_user def create_userena_profile(self, user): """ Creates an :class:`UserenaSignup` instance for this user. :param user: Django :class:`User` instance. :return: The newly created :class:`UserenaSignup` instance. """ if isinstance(user.username, unicode): user.username = user.username.encode('utf-8') <|code_end|> , predict the immediate next line with the help of imports: from django.db import models from django.db.models import Q from django.contrib.auth.models import User, UserManager, Permission, AnonymousUser from django.contrib.contenttypes.models import ContentType from django.utils.translation import ugettext as _ from django.utils import timezone from userena import settings as userena_settings from userena.utils import generate_sha1, get_profile_model from userena import signals as userena_signals from guardian.shortcuts import assign, get_perms import re, datetime and context (classes, functions, sometimes code) from other files: # Path: userena/utils.py # def generate_sha1(string, salt=None): # """ # Generates a sha1 hash for supplied string. Doesn't need to be very secure # because it's not used for password checking. We got Django for that. # # :param string: # The string that needs to be encrypted. # # :param salt: # Optionally define your own salt. If none is supplied, will use a random # string of 5 characters. # # :return: Tuple containing the salt and hash. # # """ # if not salt: # salt = sha_constructor(str(random.random())).hexdigest()[:5] # hash = sha_constructor(salt+str(string)).hexdigest() # # return (salt, hash) # # def get_profile_model(): # """ # Return the model class for the currently-active user profile # model, as defined by the ``AUTH_PROFILE_MODULE`` setting. # # :return: The model that is used as profile. # # """ # if (not hasattr(settings, 'AUTH_PROFILE_MODULE')) or \ # (not settings.AUTH_PROFILE_MODULE): # raise SiteProfileNotAvailable # # profile_mod = get_model(*settings.AUTH_PROFILE_MODULE.split('.')) # if profile_mod is None: # raise SiteProfileNotAvailable # return profile_mod . Output only the next line.
salt, activation_key = generate_sha1(user.username)
Given snippet: <|code_start|> String containing the username of the new user. :param email: String containing the email address of the new user. :param password: String containing the password for the new user. :param active: Boolean that defines if the user requires activation by clicking on a link in an e-mail. Defauts to ``True``. :param send_email: Boolean that defines if the user should be send an email. You could set this to ``False`` when you want to create a user in your own code, but don't want the user to activate through email. :return: :class:`User` instance representing the new user. """ now = timezone.now() new_user = User.objects.create_user(username, email, password) new_user.first_name = firstname new_user.is_active = active new_user.save() userena_profile = self.create_userena_profile(new_user) # All users have an empty profile <|code_end|> , continue by predicting the next line. Consider current file imports: from django.db import models from django.db.models import Q from django.contrib.auth.models import User, UserManager, Permission, AnonymousUser from django.contrib.contenttypes.models import ContentType from django.utils.translation import ugettext as _ from django.utils import timezone from userena import settings as userena_settings from userena.utils import generate_sha1, get_profile_model from userena import signals as userena_signals from guardian.shortcuts import assign, get_perms import re, datetime and context: # Path: userena/utils.py # def generate_sha1(string, salt=None): # """ # Generates a sha1 hash for supplied string. Doesn't need to be very secure # because it's not used for password checking. We got Django for that. # # :param string: # The string that needs to be encrypted. # # :param salt: # Optionally define your own salt. If none is supplied, will use a random # string of 5 characters. # # :return: Tuple containing the salt and hash. # # """ # if not salt: # salt = sha_constructor(str(random.random())).hexdigest()[:5] # hash = sha_constructor(salt+str(string)).hexdigest() # # return (salt, hash) # # def get_profile_model(): # """ # Return the model class for the currently-active user profile # model, as defined by the ``AUTH_PROFILE_MODULE`` setting. # # :return: The model that is used as profile. # # """ # if (not hasattr(settings, 'AUTH_PROFILE_MODULE')) or \ # (not settings.AUTH_PROFILE_MODULE): # raise SiteProfileNotAvailable # # profile_mod = get_model(*settings.AUTH_PROFILE_MODULE.split('.')) # if profile_mod is None: # raise SiteProfileNotAvailable # return profile_mod which might include code, classes, or functions. Output only the next line.
profile_model = get_profile_model()
Predict the next line for this snippet: <|code_start|> election.save() context = get_base_email_context_task(is_secure, site_id) context.update(dict( election=election, election_url=reverse('election-view', kwargs=dict(username=election.agora.creator.username, agoraname=election.agora.name, electionname=election.name)), agora_url=reverse('agora-view', kwargs=dict(username=election.agora.creator.username, agoraname=election.agora.name)), )) # List of emails to send. tuples are of format: # # (subject, text, html, from_email, recipient) datatuples = [] # NOTE: for now, electorate is dynamic and just taken from the election's # agora members' list for voter in election.agora.members.all(): if not voter.get_profile().has_perms('receive_email_updates'): continue translation.activate(voter.get_profile().lang_code) context['to'] = voter context['allow_delegation'] = (election.agora.delegation_policy == Agora.DELEGATION_TYPE[0][0]) try: <|code_end|> with the help of current file imports: from agora_site.agora_core.models import Agora, Election, Profile, CastVote from agora_site.misc.utils import * from agora_site.agora_core.templatetags.agora_utils import get_delegate_in_agora from actstream.signals import action from django.contrib.auth.models import User from django.utils.translation import ugettext as _ from django.template.loader import render_to_string from django.utils import translation, timezone from django.contrib.sites.models import Site from django.core.urlresolvers import reverse from celery import task from userena.models import UserenaSignup import datetime and context from other files: # Path: agora_site/agora_core/templatetags/agora_utils.py # @register.filter # def get_delegate_in_agora(user, agora): # return user.get_profile().get_delegation_in_agora(agora).get_delegate() , which may contain function names, class names, or code. Output only the next line.
context['delegate'] = get_delegate_in_agora(voter, election.agora)
Predict the next line after this snippet: <|code_start|>"""A management command to create an offlineimap configuration file.""" class Command(BaseCommand): """Command definition.""" help = "Generate an offlineimap configuration file." def add_arguments(self, parser): """Add extra arguments to command line.""" parser.add_argument( "--output", default="/tmp/offlineimap.conf", help="Path of the generated file") def handle(self, *args, **options): """Entry point.""" load_admin_settings() <|code_end|> using the current file's imports: import os import stat from django.core.management.base import BaseCommand from django.template.loader import render_to_string from modoboa.admin.app_settings import load_admin_settings from modoboa.parameters import tools as param_tools from ...modo_extension import ImapMigration from ...models import Migration and any relevant context from other files: # Path: modoboa_imap_migration/modo_extension.py # class ImapMigration(ModoExtension): # """The ImapMigration extension class.""" # # name = "modoboa_imap_migration" # label = ugettext_lazy("IMAP migration using OfflineIMAP") # version = __version__ # description = ugettext_lazy( # "Migrate existing mailboxes using IMAP and OfflineIMAP" # ) # # def load(self): # """Load extension.""" # param_tools.registry.add( # "global", forms.ParametersForm, _("IMAP migration")) # # Path: modoboa_imap_migration/models.py # class Migration(models.Model): # """Represent mailboxes to migrate.""" # # provider = models.ForeignKey(EmailProvider, on_delete=models.CASCADE) # mailbox = models.ForeignKey(Mailbox, on_delete=models.CASCADE) # username = models.CharField(max_length=254, unique=True) # _password = models.CharField(max_length=255) # # def __str__(self): # return self.username # # @property # def password(self): # """Password getter.""" # return decrypt(self._password) # # @password.setter # def password(self, value): # """Password setter.""" # self._password = encrypt(value) . Output only the next line.
ImapMigration().load()
Given the following code snippet before the placeholder: <|code_start|>"""A management command to create an offlineimap configuration file.""" class Command(BaseCommand): """Command definition.""" help = "Generate an offlineimap configuration file." def add_arguments(self, parser): """Add extra arguments to command line.""" parser.add_argument( "--output", default="/tmp/offlineimap.conf", help="Path of the generated file") def handle(self, *args, **options): """Entry point.""" load_admin_settings() ImapMigration().load() conf = dict( param_tools.get_global_parameters("modoboa_imap_migration")) context = { "imap_create_folders": conf["create_folders"], "imap_folder_filter_exclude": conf["folder_filter_exclude"], "imap_folder_filter_include": ", ".join( "'{0}'".format(w) for w in conf["folder_filter_include"].split(",")), <|code_end|> , predict the next line using imports from the current file: import os import stat from django.core.management.base import BaseCommand from django.template.loader import render_to_string from modoboa.admin.app_settings import load_admin_settings from modoboa.parameters import tools as param_tools from ...modo_extension import ImapMigration from ...models import Migration and context including class names, function names, and sometimes code from other files: # Path: modoboa_imap_migration/modo_extension.py # class ImapMigration(ModoExtension): # """The ImapMigration extension class.""" # # name = "modoboa_imap_migration" # label = ugettext_lazy("IMAP migration using OfflineIMAP") # version = __version__ # description = ugettext_lazy( # "Migrate existing mailboxes using IMAP and OfflineIMAP" # ) # # def load(self): # """Load extension.""" # param_tools.registry.add( # "global", forms.ParametersForm, _("IMAP migration")) # # Path: modoboa_imap_migration/models.py # class Migration(models.Model): # """Represent mailboxes to migrate.""" # # provider = models.ForeignKey(EmailProvider, on_delete=models.CASCADE) # mailbox = models.ForeignKey(Mailbox, on_delete=models.CASCADE) # username = models.CharField(max_length=254, unique=True) # _password = models.CharField(max_length=255) # # def __str__(self): # return self.username # # @property # def password(self): # """Password getter.""" # return decrypt(self._password) # # @password.setter # def password(self, value): # """Password setter.""" # self._password = encrypt(value) . Output only the next line.
"migrations": Migration.objects.select_related(
Here is a snippet: <|code_start|> 'syslog': { 'format': '%(name)s: %(levelname)s %(message)s' }, }, 'handlers': { 'syslog-auth': { 'class': 'logging.handlers.SysLogHandler', 'facility': SysLogHandler.LOG_AUTH, 'formatter': 'syslog' }, 'modoboa': { 'class': 'modoboa.core.loggers.SQLHandler', } }, 'loggers': { 'modoboa.auth': { 'handlers': ['syslog-auth', 'modoboa'], 'level': 'INFO', 'propagate': False }, 'modoboa.admin': { 'handlers': ['modoboa'], 'level': 'INFO', 'propagate': False } } } # Load settings from extensions <|code_end|> . Write the next line using the current file imports: from logging.handlers import SysLogHandler from modoboa.test_settings import * # noqa from modoboa_imap_migration import settings as modoboa_imap_migration_settings import os and context from other files: # Path: modoboa_imap_migration/settings.py # PLUGIN_BASE_DIR = os.path.dirname(__file__) # STATS_FILE = os.path.join( # PLUGIN_BASE_DIR, "static/modoboa_imap_migration/webpack-stats.json") # DEBUG = settings["DEBUG"] # def apply(settings): , which may include functions, classes, or code. Output only the next line.
modoboa_imap_migration_settings.apply(globals())
Predict the next line for this snippet: <|code_start|> 2: "(noSuchName)", 3: "(badValue)", 4: "(readOnly)", 5: "(genErr)", 6: "(noAccess)", 7: "(wrongType)", 8: "(wrongLength)", 9: "(wrongEncoding)", 10: "(wrongValue)", 11: "(noCreation)", 12: "(inconsistentValue)", 13: "(resourceUnavailable)", 14: "(commitFailed)", 15: "(undoFailed)", 16: "(authorizationError)", 17: "(notWritable)", 18: "(inconsistentName)", } class VarBind: """ A "VarBind" is a 2-tuple containing an object-identifier and the corresponding value. """ # TODO: This class should be split in two for both the raw and pythonic # API, that would simplify the typing of both "oid" and "value"a lot # and keep things explicit oid: ObjectIdentifier = ObjectIdentifier(0) <|code_end|> with the help of current file imports: from typing import Any, Iterator, Union from x690.types import ObjectIdentifier, Type # type: ignore from puresnmp.typevars import PyType and context from other files: # Path: puresnmp/typevars.py # class SocketInfo: # class SocketResponse: , which may contain function names, class names, or code. Output only the next line.
value: Union[PyType, Type, None] = None
Given snippet: <|code_start|>""" Unit tests for types specified in RFC-2578 """ @pytest.mark.parametrize( "value, expected", [ (-42, 0), # Underflow below threshold (-1, 0), # Underflow at threshold (0, 0), # The minimum value (42, 42), # A normal value (2 ** 32 - 1, 2 ** 32 - 1), # max value (2 ** 32, 0), # overflow at threshold (2 ** 32 + 42, 42), # overflow above threshold ((2 ** 32) * 2 + 42, 42), # overflow above threshold ], ) def test_counter(value, expected): """ A counter instance should be a non-negative integer """ <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest from puresnmp import types as t and context: # Path: puresnmp/types.py # class IpAddress(OctetString): # type: ignore # class Counter(Integer): # type: ignore # class Gauge(Integer): # type: ignore # class TimeTicks(Integer): # type: ignore # class Opaque(OctetString): # type: ignore # class NsapAddress(Integer): # type: ignore # class Counter64(Integer): # type: ignore # TYPECLASS = TypeInfo.APPLICATION # TAG = 0x00 # SIGNED = False # TYPECLASS = TypeInfo.APPLICATION # TAG = 0x01 # SIGNED = False # TYPECLASS = TypeInfo.APPLICATION # TAG = 0x02 # SIGNED = False # TYPECLASS = TypeInfo.APPLICATION # TAG = 0x03 # TYPECLASS = TypeInfo.APPLICATION # TAG = 0x04 # TYPECLASS = TypeInfo.APPLICATION # TAG = 0x05 # SIGNED = False # TYPECLASS = TypeInfo.APPLICATION # TAG = 0x06 # def __init__(self, value): # def pythonize(self): # def __init__(self, value): # def __init__(self, value): # def pythonize(self): # def __init__(self, value): # def _walk_subclasses(cls, indent=0): # pragma: no cover # def main(): # pragma: no cover which might include code, classes, or functions. Output only the next line.
instance = t.Counter(value)
Given the following code snippet before the placeholder: <|code_start|>asyncio. Care is taken to make this as pythonic as possible and hide as many of the gory implementations as possible. This module provides "syntactic sugar" around the lower-level, but almost identical, module :py:mod:`puresnmp.aio.api.raw`. The "raw" module returns the variable types unmodified which are all subclasses of :py:class:`x690.types.Type`. """ # TODO (advanced): This module should not make use of it's own functions. The # is beginning to be too "thick", containing too much business logic for a # mere abstraction layer. # module exists as an abstraction layer only. If one function uses a # "siblng" function, valuable information is lost. In general, this module if TYPE_CHECKING: # pragma: no cover # pylint: disable=unused-import, invalid-name, ungrouped-imports TWalkResponse = AsyncGenerator[VarBind, None] TFetcher = Callable[ [str, str, List[str], int, int], Coroutine[Any, Any, List[VarBind]] ] <|code_end|> , predict the next line using imports from the current file: import logging from collections import OrderedDict from typing import TYPE_CHECKING, Any, Dict, List, Tuple from typing import Type as TType from warnings import warn from x690.types import ObjectIdentifier, Type # type: ignore from puresnmp.typevars import PyType, TWrappedPyType from ...const import DEFAULT_TIMEOUT from ...snmp import VarBind from ...util import BulkResult from . import raw from typing import AsyncGenerator, Callable, Coroutine, TypeVar, Union and context including class names, function names, and sometimes code from other files: # Path: puresnmp/typevars.py # class SocketInfo: # class SocketResponse: # # Path: puresnmp/const.py # DEFAULT_TIMEOUT = 6 # # Path: puresnmp/snmp.py # class VarBind: # """ # A "VarBind" is a 2-tuple containing an object-identifier and the # corresponding value. # """ # # # TODO: This class should be split in two for both the raw and pythonic # # API, that would simplify the typing of both "oid" and "value"a lot # # and keep things explicit # oid: ObjectIdentifier = ObjectIdentifier(0) # value: Union[PyType, Type, None] = None # # def __init__(self, oid, value): # # type: (Union[ObjectIdentifier, str], PyType) -> None # if not isinstance(oid, (ObjectIdentifier, str)): # raise TypeError( # "OIDs for VarBinds must be ObjectIdentifier or str" # " instances! Your value: %r" % oid # ) # if isinstance(oid, str): # oid = ObjectIdentifier.from_string(oid) # self.oid = oid # self.value = value # # def __iter__(self) -> Iterator[Union[ObjectIdentifier, PyType]]: # return iter([self.oid, self.value]) # # def __getitem__(self, idx: int) -> Union[PyType, Type, None]: # return list(self)[idx] # # def __lt__(self, other): # # type: (Any) -> bool # return (self.oid, self.value) < (other.oid, other.value) # # def __eq__(self, other): # # type: (Any) -> bool # return (self.oid, self.value) == (other.oid, other.value) # # def __hash__(self): # # type: () -> int # return hash((self.oid, self.value)) # # def __repr__(self): # # type: () -> str # return "VarBind(%r, %r)" % (self.oid, self.value) # # Path: puresnmp/util.py # class BulkResult: # """ # A representation for results of a "bulk" request. # # These requests get both "non-repeating values" (scalars) and "repeating # values" (lists). This wrapper makes these terms a bit friendlier to use. # """ # # scalars: Dict[str, Any] # listing: Dict[str, Any] . Output only the next line.
T = TypeVar("T", bound=PyType) # pylint: disable=invalid-name
Given snippet: <|code_start|> See the "raw" equivalent for detailed documentation & examples. """ raw_output = raw.multiwalk(ip, community, oids, port, timeout, fetcher) async for oid, value in raw_output: if isinstance(value, Type): value = value.pythonize() yield VarBind(oid, value) async def set( ip, community, oid, value, port=161, timeout=DEFAULT_TIMEOUT ): # pylint: disable=redefined-builtin # type: (str, str, str, Type[T], int, int) -> T """ Delegates to :py:func:`~puresnmp.aio.api.raw.set` but returns simple Python types. See the "raw" equivalent for detailed documentation & examples. """ result = await multiset( ip, community, [(oid, value)], port, timeout=timeout ) return result[oid.lstrip(".")] # type: ignore async def multiset( ip: str, community: str, <|code_end|> , continue by predicting the next line. Consider current file imports: import logging from collections import OrderedDict from typing import TYPE_CHECKING, Any, Dict, List, Tuple from typing import Type as TType from warnings import warn from x690.types import ObjectIdentifier, Type # type: ignore from puresnmp.typevars import PyType, TWrappedPyType from ...const import DEFAULT_TIMEOUT from ...snmp import VarBind from ...util import BulkResult from . import raw from typing import AsyncGenerator, Callable, Coroutine, TypeVar, Union and context: # Path: puresnmp/typevars.py # class SocketInfo: # class SocketResponse: # # Path: puresnmp/const.py # DEFAULT_TIMEOUT = 6 # # Path: puresnmp/snmp.py # class VarBind: # """ # A "VarBind" is a 2-tuple containing an object-identifier and the # corresponding value. # """ # # # TODO: This class should be split in two for both the raw and pythonic # # API, that would simplify the typing of both "oid" and "value"a lot # # and keep things explicit # oid: ObjectIdentifier = ObjectIdentifier(0) # value: Union[PyType, Type, None] = None # # def __init__(self, oid, value): # # type: (Union[ObjectIdentifier, str], PyType) -> None # if not isinstance(oid, (ObjectIdentifier, str)): # raise TypeError( # "OIDs for VarBinds must be ObjectIdentifier or str" # " instances! Your value: %r" % oid # ) # if isinstance(oid, str): # oid = ObjectIdentifier.from_string(oid) # self.oid = oid # self.value = value # # def __iter__(self) -> Iterator[Union[ObjectIdentifier, PyType]]: # return iter([self.oid, self.value]) # # def __getitem__(self, idx: int) -> Union[PyType, Type, None]: # return list(self)[idx] # # def __lt__(self, other): # # type: (Any) -> bool # return (self.oid, self.value) < (other.oid, other.value) # # def __eq__(self, other): # # type: (Any) -> bool # return (self.oid, self.value) == (other.oid, other.value) # # def __hash__(self): # # type: () -> int # return hash((self.oid, self.value)) # # def __repr__(self): # # type: () -> str # return "VarBind(%r, %r)" % (self.oid, self.value) # # Path: puresnmp/util.py # class BulkResult: # """ # A representation for results of a "bulk" request. # # These requests get both "non-repeating values" (scalars) and "repeating # values" (lists). This wrapper makes these terms a bit friendlier to use. # """ # # scalars: Dict[str, Any] # listing: Dict[str, Any] which might include code, classes, or functions. Output only the next line.
mappings: List[Tuple[str, TWrappedPyType]],
Predict the next line for this snippet: <|code_start|>The "raw" module returns the variable types unmodified which are all subclasses of :py:class:`x690.types.Type`. """ # TODO (advanced): This module should not make use of it's own functions. The # is beginning to be too "thick", containing too much business logic for a # mere abstraction layer. # module exists as an abstraction layer only. If one function uses a # "siblng" function, valuable information is lost. In general, this module if TYPE_CHECKING: # pragma: no cover # pylint: disable=unused-import, invalid-name, ungrouped-imports TWalkResponse = AsyncGenerator[VarBind, None] TFetcher = Callable[ [str, str, List[str], int, int], Coroutine[Any, Any, List[VarBind]] ] T = TypeVar("T", bound=PyType) # pylint: disable=invalid-name _set = set LOG = logging.getLogger(__name__) OID = ObjectIdentifier.from_string <|code_end|> with the help of current file imports: import logging from collections import OrderedDict from typing import TYPE_CHECKING, Any, Dict, List, Tuple from typing import Type as TType from warnings import warn from x690.types import ObjectIdentifier, Type # type: ignore from puresnmp.typevars import PyType, TWrappedPyType from ...const import DEFAULT_TIMEOUT from ...snmp import VarBind from ...util import BulkResult from . import raw from typing import AsyncGenerator, Callable, Coroutine, TypeVar, Union and context from other files: # Path: puresnmp/typevars.py # class SocketInfo: # class SocketResponse: # # Path: puresnmp/const.py # DEFAULT_TIMEOUT = 6 # # Path: puresnmp/snmp.py # class VarBind: # """ # A "VarBind" is a 2-tuple containing an object-identifier and the # corresponding value. # """ # # # TODO: This class should be split in two for both the raw and pythonic # # API, that would simplify the typing of both "oid" and "value"a lot # # and keep things explicit # oid: ObjectIdentifier = ObjectIdentifier(0) # value: Union[PyType, Type, None] = None # # def __init__(self, oid, value): # # type: (Union[ObjectIdentifier, str], PyType) -> None # if not isinstance(oid, (ObjectIdentifier, str)): # raise TypeError( # "OIDs for VarBinds must be ObjectIdentifier or str" # " instances! Your value: %r" % oid # ) # if isinstance(oid, str): # oid = ObjectIdentifier.from_string(oid) # self.oid = oid # self.value = value # # def __iter__(self) -> Iterator[Union[ObjectIdentifier, PyType]]: # return iter([self.oid, self.value]) # # def __getitem__(self, idx: int) -> Union[PyType, Type, None]: # return list(self)[idx] # # def __lt__(self, other): # # type: (Any) -> bool # return (self.oid, self.value) < (other.oid, other.value) # # def __eq__(self, other): # # type: (Any) -> bool # return (self.oid, self.value) == (other.oid, other.value) # # def __hash__(self): # # type: () -> int # return hash((self.oid, self.value)) # # def __repr__(self): # # type: () -> str # return "VarBind(%r, %r)" % (self.oid, self.value) # # Path: puresnmp/util.py # class BulkResult: # """ # A representation for results of a "bulk" request. # # These requests get both "non-repeating values" (scalars) and "repeating # values" (lists). This wrapper makes these terms a bit friendlier to use. # """ # # scalars: Dict[str, Any] # listing: Dict[str, Any] , which may contain function names, class names, or code. Output only the next line.
async def get(ip, community, oid, port=161, timeout=DEFAULT_TIMEOUT):
Using the snippet: <|code_start|>""" This module contains the high-level functions to access the library with asyncio. Care is taken to make this as pythonic as possible and hide as many of the gory implementations as possible. This module provides "syntactic sugar" around the lower-level, but almost identical, module :py:mod:`puresnmp.aio.api.raw`. The "raw" module returns the variable types unmodified which are all subclasses of :py:class:`x690.types.Type`. """ # TODO (advanced): This module should not make use of it's own functions. The # is beginning to be too "thick", containing too much business logic for a # mere abstraction layer. # module exists as an abstraction layer only. If one function uses a # "siblng" function, valuable information is lost. In general, this module if TYPE_CHECKING: # pragma: no cover # pylint: disable=unused-import, invalid-name, ungrouped-imports <|code_end|> , determine the next line of code. You have imports: import logging from collections import OrderedDict from typing import TYPE_CHECKING, Any, Dict, List, Tuple from typing import Type as TType from warnings import warn from x690.types import ObjectIdentifier, Type # type: ignore from puresnmp.typevars import PyType, TWrappedPyType from ...const import DEFAULT_TIMEOUT from ...snmp import VarBind from ...util import BulkResult from . import raw from typing import AsyncGenerator, Callable, Coroutine, TypeVar, Union and context (class names, function names, or code) available: # Path: puresnmp/typevars.py # class SocketInfo: # class SocketResponse: # # Path: puresnmp/const.py # DEFAULT_TIMEOUT = 6 # # Path: puresnmp/snmp.py # class VarBind: # """ # A "VarBind" is a 2-tuple containing an object-identifier and the # corresponding value. # """ # # # TODO: This class should be split in two for both the raw and pythonic # # API, that would simplify the typing of both "oid" and "value"a lot # # and keep things explicit # oid: ObjectIdentifier = ObjectIdentifier(0) # value: Union[PyType, Type, None] = None # # def __init__(self, oid, value): # # type: (Union[ObjectIdentifier, str], PyType) -> None # if not isinstance(oid, (ObjectIdentifier, str)): # raise TypeError( # "OIDs for VarBinds must be ObjectIdentifier or str" # " instances! Your value: %r" % oid # ) # if isinstance(oid, str): # oid = ObjectIdentifier.from_string(oid) # self.oid = oid # self.value = value # # def __iter__(self) -> Iterator[Union[ObjectIdentifier, PyType]]: # return iter([self.oid, self.value]) # # def __getitem__(self, idx: int) -> Union[PyType, Type, None]: # return list(self)[idx] # # def __lt__(self, other): # # type: (Any) -> bool # return (self.oid, self.value) < (other.oid, other.value) # # def __eq__(self, other): # # type: (Any) -> bool # return (self.oid, self.value) == (other.oid, other.value) # # def __hash__(self): # # type: () -> int # return hash((self.oid, self.value)) # # def __repr__(self): # # type: () -> str # return "VarBind(%r, %r)" % (self.oid, self.value) # # Path: puresnmp/util.py # class BulkResult: # """ # A representation for results of a "bulk" request. # # These requests get both "non-repeating values" (scalars) and "repeating # values" (lists). This wrapper makes these terms a bit friendlier to use. # """ # # scalars: Dict[str, Any] # listing: Dict[str, Any] . Output only the next line.
TWalkResponse = AsyncGenerator[VarBind, None]
Based on the snippet: <|code_start|> community, scalar_oids, repeating_oids, max_list_size=1, port=161, timeout=DEFAULT_TIMEOUT, ): # type: (str, str, List[str], List[str], int, int, int) -> BulkResult """ Delegates to :py:func:`~puresnmp.aio.api.raw.bulkget` but returns simple Python types. See the "raw" equivalent for detailed documentation & examples. """ raw_output = await raw.bulkget( ip, community, scalar_oids, repeating_oids, max_list_size=max_list_size, port=port, timeout=timeout, ) pythonized_scalars = { oid: value.pythonize() for oid, value in raw_output.scalars.items() } pythonized_list = OrderedDict( [(oid, value.pythonize()) for oid, value in raw_output.listing.items()] ) <|code_end|> , predict the immediate next line with the help of imports: import logging from collections import OrderedDict from typing import TYPE_CHECKING, Any, Dict, List, Tuple from typing import Type as TType from warnings import warn from x690.types import ObjectIdentifier, Type # type: ignore from puresnmp.typevars import PyType, TWrappedPyType from ...const import DEFAULT_TIMEOUT from ...snmp import VarBind from ...util import BulkResult from . import raw from typing import AsyncGenerator, Callable, Coroutine, TypeVar, Union and context (classes, functions, sometimes code) from other files: # Path: puresnmp/typevars.py # class SocketInfo: # class SocketResponse: # # Path: puresnmp/const.py # DEFAULT_TIMEOUT = 6 # # Path: puresnmp/snmp.py # class VarBind: # """ # A "VarBind" is a 2-tuple containing an object-identifier and the # corresponding value. # """ # # # TODO: This class should be split in two for both the raw and pythonic # # API, that would simplify the typing of both "oid" and "value"a lot # # and keep things explicit # oid: ObjectIdentifier = ObjectIdentifier(0) # value: Union[PyType, Type, None] = None # # def __init__(self, oid, value): # # type: (Union[ObjectIdentifier, str], PyType) -> None # if not isinstance(oid, (ObjectIdentifier, str)): # raise TypeError( # "OIDs for VarBinds must be ObjectIdentifier or str" # " instances! Your value: %r" % oid # ) # if isinstance(oid, str): # oid = ObjectIdentifier.from_string(oid) # self.oid = oid # self.value = value # # def __iter__(self) -> Iterator[Union[ObjectIdentifier, PyType]]: # return iter([self.oid, self.value]) # # def __getitem__(self, idx: int) -> Union[PyType, Type, None]: # return list(self)[idx] # # def __lt__(self, other): # # type: (Any) -> bool # return (self.oid, self.value) < (other.oid, other.value) # # def __eq__(self, other): # # type: (Any) -> bool # return (self.oid, self.value) == (other.oid, other.value) # # def __hash__(self): # # type: () -> int # return hash((self.oid, self.value)) # # def __repr__(self): # # type: () -> str # return "VarBind(%r, %r)" % (self.oid, self.value) # # Path: puresnmp/util.py # class BulkResult: # """ # A representation for results of a "bulk" request. # # These requests get both "non-repeating values" (scalars) and "repeating # values" (lists). This wrapper makes these terms a bit friendlier to use. # """ # # scalars: Dict[str, Any] # listing: Dict[str, Any] . Output only the next line.
return BulkResult(pythonized_scalars, pythonized_list)
Given the code snippet: <|code_start|> @property def values(self): # type: () -> Dict[str, Any] """ Returns all the values contained in this trap as dictionary mapping OIDs to values. """ output = {} for oid_raw, value_raw in self.raw_trap.varbinds[2:]: oid = oid_raw.pythonize() # type: ignore value = value_raw.pythonize() # type: ignore output[oid] = value return output def get(ip, community, oid, port=161, timeout=2, version=Version.V2C): # type: (str, str, str, int, int, int) -> PyType """ Delegates to :py:func:`~puresnmp.api.raw.get` but returns simple Python types. See the "raw" equivalent for detailed documentation & examples. """ raw_value = raw.get( ip, community, oid, port, timeout=timeout, version=version ) return raw_value.pythonize() # type: ignore def multiget( <|code_end|> , generate the next line using the imports in this file: import logging from collections import OrderedDict from datetime import timedelta from typing import TYPE_CHECKING, Generator, List, TypeVar from warnings import warn from x690.types import ObjectIdentifier, Type # type: ignore from ..const import DEFAULT_TIMEOUT, Version from ..pdu import Trap from ..snmp import VarBind from ..util import BulkResult from . import raw from typing import Any, Callable, Dict, Tuple, Union from puresnmp.typevars import PyType and context (functions, classes, or occasionally code) from other files: # Path: puresnmp/const.py # DEFAULT_TIMEOUT = 6 # # class Version: # """ # The SNMP Version identifier. This is used in the SNMP :term:`PDU`. # """ # # V2C = 0x01 # V1 = 0x00 # # Path: puresnmp/pdu.py # class Trap(PDU): # """ # Represents an SNMP Trap # """ # # TAG = 7 # # def __init__(self, *args, **kwargs): # # type: (Any, Any) -> None # super().__init__(*args, **kwargs) # self.source = None # type: Optional[SocketInfo] # # Path: puresnmp/snmp.py # class VarBind: # """ # A "VarBind" is a 2-tuple containing an object-identifier and the # corresponding value. # """ # # # TODO: This class should be split in two for both the raw and pythonic # # API, that would simplify the typing of both "oid" and "value"a lot # # and keep things explicit # oid: ObjectIdentifier = ObjectIdentifier(0) # value: Union[PyType, Type, None] = None # # def __init__(self, oid, value): # # type: (Union[ObjectIdentifier, str], PyType) -> None # if not isinstance(oid, (ObjectIdentifier, str)): # raise TypeError( # "OIDs for VarBinds must be ObjectIdentifier or str" # " instances! Your value: %r" % oid # ) # if isinstance(oid, str): # oid = ObjectIdentifier.from_string(oid) # self.oid = oid # self.value = value # # def __iter__(self) -> Iterator[Union[ObjectIdentifier, PyType]]: # return iter([self.oid, self.value]) # # def __getitem__(self, idx: int) -> Union[PyType, Type, None]: # return list(self)[idx] # # def __lt__(self, other): # # type: (Any) -> bool # return (self.oid, self.value) < (other.oid, other.value) # # def __eq__(self, other): # # type: (Any) -> bool # return (self.oid, self.value) == (other.oid, other.value) # # def __hash__(self): # # type: () -> int # return hash((self.oid, self.value)) # # def __repr__(self): # # type: () -> str # return "VarBind(%r, %r)" % (self.oid, self.value) # # Path: puresnmp/util.py # class BulkResult: # """ # A representation for results of a "bulk" request. # # These requests get both "non-repeating values" (scalars) and "repeating # values" (lists). This wrapper makes these terms a bit friendlier to use. # """ # # scalars: Dict[str, Any] # listing: Dict[str, Any] . Output only the next line.
ip, community, oids, port=161, timeout=DEFAULT_TIMEOUT, version=Version.V2C
Continue the code snippet: <|code_start|> @property def uptime(self) -> timedelta: """ Returns the uptime of the device. """ return self.raw_trap.varbinds[0].value.pythonize() # type: ignore @property def oid(self) -> str: """ Returns the Trap-OID """ return self.raw_trap.varbinds[1].value.pythonize() # type: ignore @property def values(self): # type: () -> Dict[str, Any] """ Returns all the values contained in this trap as dictionary mapping OIDs to values. """ output = {} for oid_raw, value_raw in self.raw_trap.varbinds[2:]: oid = oid_raw.pythonize() # type: ignore value = value_raw.pythonize() # type: ignore output[oid] = value return output <|code_end|> . Use current file imports: import logging from collections import OrderedDict from datetime import timedelta from typing import TYPE_CHECKING, Generator, List, TypeVar from warnings import warn from x690.types import ObjectIdentifier, Type # type: ignore from ..const import DEFAULT_TIMEOUT, Version from ..pdu import Trap from ..snmp import VarBind from ..util import BulkResult from . import raw from typing import Any, Callable, Dict, Tuple, Union from puresnmp.typevars import PyType and context (classes, functions, or code) from other files: # Path: puresnmp/const.py # DEFAULT_TIMEOUT = 6 # # class Version: # """ # The SNMP Version identifier. This is used in the SNMP :term:`PDU`. # """ # # V2C = 0x01 # V1 = 0x00 # # Path: puresnmp/pdu.py # class Trap(PDU): # """ # Represents an SNMP Trap # """ # # TAG = 7 # # def __init__(self, *args, **kwargs): # # type: (Any, Any) -> None # super().__init__(*args, **kwargs) # self.source = None # type: Optional[SocketInfo] # # Path: puresnmp/snmp.py # class VarBind: # """ # A "VarBind" is a 2-tuple containing an object-identifier and the # corresponding value. # """ # # # TODO: This class should be split in two for both the raw and pythonic # # API, that would simplify the typing of both "oid" and "value"a lot # # and keep things explicit # oid: ObjectIdentifier = ObjectIdentifier(0) # value: Union[PyType, Type, None] = None # # def __init__(self, oid, value): # # type: (Union[ObjectIdentifier, str], PyType) -> None # if not isinstance(oid, (ObjectIdentifier, str)): # raise TypeError( # "OIDs for VarBinds must be ObjectIdentifier or str" # " instances! Your value: %r" % oid # ) # if isinstance(oid, str): # oid = ObjectIdentifier.from_string(oid) # self.oid = oid # self.value = value # # def __iter__(self) -> Iterator[Union[ObjectIdentifier, PyType]]: # return iter([self.oid, self.value]) # # def __getitem__(self, idx: int) -> Union[PyType, Type, None]: # return list(self)[idx] # # def __lt__(self, other): # # type: (Any) -> bool # return (self.oid, self.value) < (other.oid, other.value) # # def __eq__(self, other): # # type: (Any) -> bool # return (self.oid, self.value) == (other.oid, other.value) # # def __hash__(self): # # type: () -> int # return hash((self.oid, self.value)) # # def __repr__(self): # # type: () -> str # return "VarBind(%r, %r)" % (self.oid, self.value) # # Path: puresnmp/util.py # class BulkResult: # """ # A representation for results of a "bulk" request. # # These requests get both "non-repeating values" (scalars) and "repeating # values" (lists). This wrapper makes these terms a bit friendlier to use. # """ # # scalars: Dict[str, Any] # listing: Dict[str, Any] . Output only the next line.
def get(ip, community, oid, port=161, timeout=2, version=Version.V2C):
Next line prediction: <|code_start|> if TYPE_CHECKING: # pragma: no cover # pylint: disable=unused-import, invalid-name, ungrouped-imports T = TypeVar("T", bound=PyType) _set = set LOG = logging.getLogger(__name__) OID = ObjectIdentifier.from_string TWalkResponse = Generator[VarBind, None, None] class TrapInfo: """ This class wraps a :py:class:`puresnmp.pdu.Trap` instance (accessible via ``raw_trap`` and makes values available as "pythonic" values. """ #: The raw Trap PDU. #: #: .. warning:: #: This will leak data-types which are used internally by ``puresnmp`` #: and may change even in minor updates. You should, if possible use #: the values from the properties on this object. This exist mainly to #: expose values which can be helpful in debugging. If something is #: missing from the properties, please open a corresponding support #: ticket! <|code_end|> . Use current file imports: (import logging from collections import OrderedDict from datetime import timedelta from typing import TYPE_CHECKING, Generator, List, TypeVar from warnings import warn from x690.types import ObjectIdentifier, Type # type: ignore from ..const import DEFAULT_TIMEOUT, Version from ..pdu import Trap from ..snmp import VarBind from ..util import BulkResult from . import raw from typing import Any, Callable, Dict, Tuple, Union from puresnmp.typevars import PyType) and context including class names, function names, or small code snippets from other files: # Path: puresnmp/const.py # DEFAULT_TIMEOUT = 6 # # class Version: # """ # The SNMP Version identifier. This is used in the SNMP :term:`PDU`. # """ # # V2C = 0x01 # V1 = 0x00 # # Path: puresnmp/pdu.py # class Trap(PDU): # """ # Represents an SNMP Trap # """ # # TAG = 7 # # def __init__(self, *args, **kwargs): # # type: (Any, Any) -> None # super().__init__(*args, **kwargs) # self.source = None # type: Optional[SocketInfo] # # Path: puresnmp/snmp.py # class VarBind: # """ # A "VarBind" is a 2-tuple containing an object-identifier and the # corresponding value. # """ # # # TODO: This class should be split in two for both the raw and pythonic # # API, that would simplify the typing of both "oid" and "value"a lot # # and keep things explicit # oid: ObjectIdentifier = ObjectIdentifier(0) # value: Union[PyType, Type, None] = None # # def __init__(self, oid, value): # # type: (Union[ObjectIdentifier, str], PyType) -> None # if not isinstance(oid, (ObjectIdentifier, str)): # raise TypeError( # "OIDs for VarBinds must be ObjectIdentifier or str" # " instances! Your value: %r" % oid # ) # if isinstance(oid, str): # oid = ObjectIdentifier.from_string(oid) # self.oid = oid # self.value = value # # def __iter__(self) -> Iterator[Union[ObjectIdentifier, PyType]]: # return iter([self.oid, self.value]) # # def __getitem__(self, idx: int) -> Union[PyType, Type, None]: # return list(self)[idx] # # def __lt__(self, other): # # type: (Any) -> bool # return (self.oid, self.value) < (other.oid, other.value) # # def __eq__(self, other): # # type: (Any) -> bool # return (self.oid, self.value) == (other.oid, other.value) # # def __hash__(self): # # type: () -> int # return hash((self.oid, self.value)) # # def __repr__(self): # # type: () -> str # return "VarBind(%r, %r)" % (self.oid, self.value) # # Path: puresnmp/util.py # class BulkResult: # """ # A representation for results of a "bulk" request. # # These requests get both "non-repeating values" (scalars) and "repeating # values" (lists). This wrapper makes these terms a bit friendlier to use. # """ # # scalars: Dict[str, Any] # listing: Dict[str, Any] . Output only the next line.
raw_trap: Trap
Next line prediction: <|code_start|> Care is taken to make this as pythonic as possible and hide as many of the gory implementations as possible. This module provides "syntactic sugar" around the lower-level, but almost identical, module :py:mod:`puresnmp.api.raw`. The "raw" module returns the variable types unmodified which are all subclasses of :py:class:`x690.types.Type`. """ # TODO (advanced): This module should not make use of it's own functions. The # is beginning to be too "thick", containing too much business logic for a # mere abstraction layer. # module exists as an abstraction layer only. If one function uses a # "siblng" function, valuable information is lost. In general, this module if TYPE_CHECKING: # pragma: no cover # pylint: disable=unused-import, invalid-name, ungrouped-imports T = TypeVar("T", bound=PyType) _set = set LOG = logging.getLogger(__name__) OID = ObjectIdentifier.from_string <|code_end|> . Use current file imports: (import logging from collections import OrderedDict from datetime import timedelta from typing import TYPE_CHECKING, Generator, List, TypeVar from warnings import warn from x690.types import ObjectIdentifier, Type # type: ignore from ..const import DEFAULT_TIMEOUT, Version from ..pdu import Trap from ..snmp import VarBind from ..util import BulkResult from . import raw from typing import Any, Callable, Dict, Tuple, Union from puresnmp.typevars import PyType) and context including class names, function names, or small code snippets from other files: # Path: puresnmp/const.py # DEFAULT_TIMEOUT = 6 # # class Version: # """ # The SNMP Version identifier. This is used in the SNMP :term:`PDU`. # """ # # V2C = 0x01 # V1 = 0x00 # # Path: puresnmp/pdu.py # class Trap(PDU): # """ # Represents an SNMP Trap # """ # # TAG = 7 # # def __init__(self, *args, **kwargs): # # type: (Any, Any) -> None # super().__init__(*args, **kwargs) # self.source = None # type: Optional[SocketInfo] # # Path: puresnmp/snmp.py # class VarBind: # """ # A "VarBind" is a 2-tuple containing an object-identifier and the # corresponding value. # """ # # # TODO: This class should be split in two for both the raw and pythonic # # API, that would simplify the typing of both "oid" and "value"a lot # # and keep things explicit # oid: ObjectIdentifier = ObjectIdentifier(0) # value: Union[PyType, Type, None] = None # # def __init__(self, oid, value): # # type: (Union[ObjectIdentifier, str], PyType) -> None # if not isinstance(oid, (ObjectIdentifier, str)): # raise TypeError( # "OIDs for VarBinds must be ObjectIdentifier or str" # " instances! Your value: %r" % oid # ) # if isinstance(oid, str): # oid = ObjectIdentifier.from_string(oid) # self.oid = oid # self.value = value # # def __iter__(self) -> Iterator[Union[ObjectIdentifier, PyType]]: # return iter([self.oid, self.value]) # # def __getitem__(self, idx: int) -> Union[PyType, Type, None]: # return list(self)[idx] # # def __lt__(self, other): # # type: (Any) -> bool # return (self.oid, self.value) < (other.oid, other.value) # # def __eq__(self, other): # # type: (Any) -> bool # return (self.oid, self.value) == (other.oid, other.value) # # def __hash__(self): # # type: () -> int # return hash((self.oid, self.value)) # # def __repr__(self): # # type: () -> str # return "VarBind(%r, %r)" % (self.oid, self.value) # # Path: puresnmp/util.py # class BulkResult: # """ # A representation for results of a "bulk" request. # # These requests get both "non-repeating values" (scalars) and "repeating # values" (lists). This wrapper makes these terms a bit friendlier to use. # """ # # scalars: Dict[str, Any] # listing: Dict[str, Any] . Output only the next line.
TWalkResponse = Generator[VarBind, None, None]