Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given snippet: <|code_start|>class ProgramForm(forms.ModelForm):
def clean(self):
cleaned_data = super(ProgramForm, self).clean()
join_year = cleaned_data.get('join_year')
graduation_year = cleaned_data.get('graduation_year')
if join_year and graduation_year:
if graduation_year <= join_year:
validation_err = forms.ValidationError(_('How come you graduated before you joined?'), code='bad_input')
self.add_error('graduation_year', validation_err)
if join_year >= graduation_year:
validation_err = forms.ValidationError(
_('How come you joined after you graduated? You must be in alternate timeline!'), code='bade_input')
self.add_error('join_year', validation_err)
class Meta:
model = Program
fields = ['department', 'join_year', 'graduation_year', 'degree']
widgets = {
'department': forms.Select(
attrs={'class': 'form-control', },
),
'join_year': forms.NumberInput(
attrs={'class': 'form-control', },
),
'graduation_year': forms.NumberInput(
attrs={'class': 'form-control', },
),
'degree': forms.Select(
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django import forms
from django.template.defaultfilters import filesizeformat
from django.utils.translation import ugettext_lazy as _
from core.utils import SEXES, get_choices_with_blank_dash
from .models import InstituteAddress, Program
and context:
# Path: core/utils.py
# SEXES = [
# ('male', 'Male'),
# ('female', 'Female'),
# ('other', 'Other'),
# ]
#
# def get_choices_with_blank_dash(choices):
# return BLANK_CHOICE_DASH + list(choices)
#
# Path: user_resource/models.py
# class InstituteAddress(models.Model):
# user = models.OneToOneField(User, related_name='insti_address')
# room = models.CharField(max_length=8, null=True, blank=True)
# hostel = models.CharField(max_length=8, choices=HOSTELS, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def clean(self):
# if self.room:
# if self.hostel in HOSTELS_WITH_WINGS:
# if not ROOM_VALIDATION_REGEX.match(self.room):
# raise ValidationError(_('Room number must have wing name like A-123'))
#
# def __str__(self):
# if self.hostel:
# if self.room:
# return "%s-%s" % (self.hostel, self.room)
# return self.hostel
# return ''
#
# class Program(models.Model):
# user = models.OneToOneField(User, related_name='program')
# department = models.CharField(max_length=16, choices=SORTED_DISCIPLINES, null=True, blank=True)
# join_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_join_year])
# graduation_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_graduation_year])
# degree = models.CharField(max_length=16, choices=DEGREES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return "%s, %s" % (self.get_degree_display(), self.get_department_display())
which might include code, classes, or functions. Output only the next line. | attrs={'class': 'form-control', }, |
Given snippet: <|code_start|>
class ProfilePictureForm(forms.Form):
profile_picture = forms.ImageField()
def clean_profile_picture(self):
profile_picture = self.cleaned_data['profile_picture']
content_type = profile_picture.content_type.split('/')[0]
if content_type in ['image']:
if profile_picture.size > 5242880:
raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s') % (
filesizeformat(5242880), filesizeformat(profile_picture.size)))
else:
raise forms.ValidationError(_('File type is not supported'))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django import forms
from django.template.defaultfilters import filesizeformat
from django.utils.translation import ugettext_lazy as _
from core.utils import SEXES, get_choices_with_blank_dash
from .models import InstituteAddress, Program
and context:
# Path: core/utils.py
# SEXES = [
# ('male', 'Male'),
# ('female', 'Female'),
# ('other', 'Other'),
# ]
#
# def get_choices_with_blank_dash(choices):
# return BLANK_CHOICE_DASH + list(choices)
#
# Path: user_resource/models.py
# class InstituteAddress(models.Model):
# user = models.OneToOneField(User, related_name='insti_address')
# room = models.CharField(max_length=8, null=True, blank=True)
# hostel = models.CharField(max_length=8, choices=HOSTELS, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def clean(self):
# if self.room:
# if self.hostel in HOSTELS_WITH_WINGS:
# if not ROOM_VALIDATION_REGEX.match(self.room):
# raise ValidationError(_('Room number must have wing name like A-123'))
#
# def __str__(self):
# if self.hostel:
# if self.room:
# return "%s-%s" % (self.hostel, self.room)
# return self.hostel
# return ''
#
# class Program(models.Model):
# user = models.OneToOneField(User, related_name='program')
# department = models.CharField(max_length=16, choices=SORTED_DISCIPLINES, null=True, blank=True)
# join_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_join_year])
# graduation_year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[validate_graduation_year])
# degree = models.CharField(max_length=16, choices=DEGREES, null=True, blank=True)
# _history_ = HistoricalRecords()
#
# def __str__(self):
# return "%s, %s" % (self.get_degree_display(), self.get_department_display())
which might include code, classes, or functions. Output only the next line. | return profile_picture |
Using the snippet: <|code_start|>
urlpatterns = [
url(r'^authorize/$', CustomAuthorizationView.as_view(), name='authorize'),
url(r'^applications/register/$', ApplicationRegistrationView.as_view(), name='register'),
url(r'^applications/(?P<pk>\d+)/update/$', ApplicationUpdateView.as_view(), name='update'),
<|code_end|>
, determine the next line of code. You have imports:
from django.conf.urls import url
from .views import ApplicationRegistrationView, ApplicationUpdateView, CustomAuthorizationView
and context (class names, function names, or code) available:
# Path: application/views.py
# class ApplicationRegistrationView(ApplicationRegistration):
# form_class = RegistrationForm
#
# class ApplicationUpdateView(LoginRequiredMixin, UpdateView):
# """
# View used to update an application owned by the request.user
# """
# form_class = RegistrationForm
# context_object_name = 'application'
# template_name = "oauth2_provider/application_form.html"
#
# def get_queryset(self):
# return get_oauth2_application_model().objects.filter(user=self.request.user)
#
# class CustomAuthorizationView(AuthorizationView):
#
# def form_valid(self, form):
# client_id = form.cleaned_data.get('client_id', '')
# application = get_oauth2_application_model().objects.get(client_id=client_id)
# scopes = form.cleaned_data.get('scope', '')
# scopes = set(scopes.split(' '))
# scopes.update(set(get_default_scopes(application)))
# private_scopes = application.private_scopes
# if private_scopes:
# private_scopes = set(private_scopes.split(' '))
# scopes.update(private_scopes)
# scopes = ' '.join(list(scopes))
# form.cleaned_data['scope'] = scopes
# return super(CustomAuthorizationView, self).form_valid(form)
#
# def get(self, request, *args, **kwargs):
# """
# Copied blatantly from super method. Had to change few stuff, but didn't find better way
# than copying and editing the whole stuff.
# Sin Count += 1
# """
# try:
# scopes, credentials = self.validate_authorization_request(request)
# try:
# del credentials['request']
# # Removing oauthlib.Request from credentials. This is not required in future
# except KeyError: # pylint: disable=pointless-except
# pass
#
# kwargs['scopes_descriptions'] = [oauth2_settings.SCOPES[scope] for scope in scopes]
# kwargs['scopes'] = scopes
# # at this point we know an Application instance with such client_id exists in the database
# application = get_oauth2_application_model().objects.get(
# client_id=credentials['client_id']) # TODO: cache it!
# kwargs['application'] = application
# kwargs.update(credentials)
# self.oauth2_data = kwargs
# # following two loc are here only because of https://code.djangoproject.com/ticket/17795
# form = self.get_form(self.get_form_class())
# kwargs['form'] = form
#
# # Check to see if the user has already granted access and return
# # a successful response depending on 'approval_prompt' url parameter
# require_approval = request.GET.get('approval_prompt', oauth2_settings.REQUEST_APPROVAL_PROMPT)
#
# # If skip_authorization field is True, skip the authorization screen even
# # if this is the first use of the application and there was no previous authorization.
# # This is useful for in-house applications-> assume an in-house applications
# # are already approved.
# if application.skip_authorization:
# uri, headers, body, status = self.create_authorization_response(
# request=self.request, scopes=" ".join(scopes),
# credentials=credentials, allow=True)
# return HttpResponseUriRedirect(uri)
#
# elif require_approval == 'auto':
# tokens = request.user.accesstoken_set.filter(application=kwargs['application']).all().order_by('-id')
# if len(tokens) > 0:
# token = tokens[0]
# if len(tokens) > 1:
# # Enforce one token pair per user policy. Remove all older tokens
# request.user.accesstoken_set.exclude(pk=token.id).all().delete()
#
# # check past authorizations regarded the same scopes as the current one
# if token.allow_scopes(scopes):
# uri, headers, body, status = self.create_authorization_response(
# request=self.request, scopes=" ".join(scopes),
# credentials=credentials, allow=True)
# return HttpResponseUriRedirect(uri)
#
# return self.render_to_response(self.get_context_data(**kwargs))
#
# except OAuthToolkitError as error:
# return self.error_response(error)
. Output only the next line. | ] |
Predict the next line after this snippet: <|code_start|>
logger = logging.getLogger(__name__)
class UserViewset(viewsets.GenericViewSet):
required_scopes = ['basic']
permission_classes = [TokenHasScope]
serializer_class = UserSerializer
def get_queryset(self):
token = self.request.auth
user = token.user
return User.objects.all().filter(pk=user.id)
def list(self, request):
<|code_end|>
using the current file's imports:
import logging
from smtplib import SMTPException
from django.contrib.auth.models import User
from django.core.mail import EmailMessage
from oauth2_provider.ext.rest_framework.permissions import TokenHasScope
from rest_framework import viewsets
from rest_framework.decorators import list_route
from rest_framework.response import Response
from rest_framework.status import HTTP_400_BAD_REQUEST
from ..models import SentMessage
from ..oauth import DEFAULT_FIELDS, SCOPE_TO_FIELD_MAP, USER_FIELDS
from ..serializers import SendMailSerializer, UserSerializer
and any relevant context from other files:
# Path: user_resource/models.py
# class SentMessage(models.Model):
# message_id = models.CharField(max_length=256)
# sender = models.ForeignKey(Application)
# user = models.ForeignKey(User)
# status = models.BooleanField(default=True)
# error_message = models.TextField(null=True, blank=True)
# created = models.DateTimeField(auto_now_add=True)
#
# def __str__(self):
# return self.message_id
#
# Path: user_resource/oauth.py
# DEFAULT_FIELDS = ['id', ]
#
# SCOPE_TO_FIELD_MAP = {
# 'basic': ['id', ],
# 'profile': ['first_name', 'last_name', 'type', 'is_alumni', ],
# 'sex': ['sex', ],
# 'picture': ['profile_picture'],
# 'ldap': ['username', 'email'],
# 'phone': ['contacts', 'mobile', ],
# 'insti_address': ['insti_address', ],
# 'program': ['program', 'roll_number', ],
# 'secondary_emails': ['secondary_emails', ],
# 'send_mail': [],
# }
#
# USER_FIELDS = [
# 'username',
# 'first_name',
# 'last_name',
# 'type',
# 'is_alumni',
# 'sex',
# 'profile_picture',
# 'email',
# 'program',
# 'secondary_emails',
# 'contacts',
# 'insti_address',
# 'mobile',
# 'roll_number',
# ]
#
# Path: user_resource/serializers.py
# class SendMailSerializer(serializers.Serializer): # pylint: disable=abstract-method
# subject = serializers.CharField()
# message = serializers.CharField()
# reply_to = serializers.ListField(
# child=serializers.EmailField()
# )
#
# class UserSerializer(serializers.ModelSerializer):
# program = ProgramSerializer()
# secondary_emails = SecondaryEmailSerializer(many=True)
# contacts = ContactNumberSerializer(many=True)
# insti_address = InstituteAddressSerializer()
# mobile = serializers.CharField(source='userprofile.mobile')
# roll_number = serializers.CharField(source='userprofile.roll_number')
# profile_picture = serializers.ImageField(source='userprofile.profile_picture')
# sex = serializers.CharField(source='userprofile.sex')
# type = serializers.CharField(source='userprofile.type')
# is_alumni = serializers.BooleanField(source='userprofile.is_alumni')
#
# def __init__(self, *args, **kwargs):
# super(UserSerializer, self).__init__(*args, **kwargs)
# fields = self.context.get('fields')
# if not isinstance(fields, list) and not isinstance(fields, set):
# fields = []
# fields.extend(DEFAULT_FIELDS)
#
# if fields is not None:
# allowed = set(fields)
# existing = set(self.fields.keys())
# fields_to_remove = existing - allowed
# for field in fields_to_remove:
# self.fields.pop(field)
#
# class Meta:
# model = User
# fields = copy.deepcopy(DEFAULT_FIELDS).extend(USER_FIELDS)
. Output only the next line. | user_queryset = self.get_queryset().first() |
Here is a snippet: <|code_start|>
logger = logging.getLogger(__name__)
class UserViewset(viewsets.GenericViewSet):
required_scopes = ['basic']
permission_classes = [TokenHasScope]
serializer_class = UserSerializer
def get_queryset(self):
<|code_end|>
. Write the next line using the current file imports:
import logging
from smtplib import SMTPException
from django.contrib.auth.models import User
from django.core.mail import EmailMessage
from oauth2_provider.ext.rest_framework.permissions import TokenHasScope
from rest_framework import viewsets
from rest_framework.decorators import list_route
from rest_framework.response import Response
from rest_framework.status import HTTP_400_BAD_REQUEST
from ..models import SentMessage
from ..oauth import DEFAULT_FIELDS, SCOPE_TO_FIELD_MAP, USER_FIELDS
from ..serializers import SendMailSerializer, UserSerializer
and context from other files:
# Path: user_resource/models.py
# class SentMessage(models.Model):
# message_id = models.CharField(max_length=256)
# sender = models.ForeignKey(Application)
# user = models.ForeignKey(User)
# status = models.BooleanField(default=True)
# error_message = models.TextField(null=True, blank=True)
# created = models.DateTimeField(auto_now_add=True)
#
# def __str__(self):
# return self.message_id
#
# Path: user_resource/oauth.py
# DEFAULT_FIELDS = ['id', ]
#
# SCOPE_TO_FIELD_MAP = {
# 'basic': ['id', ],
# 'profile': ['first_name', 'last_name', 'type', 'is_alumni', ],
# 'sex': ['sex', ],
# 'picture': ['profile_picture'],
# 'ldap': ['username', 'email'],
# 'phone': ['contacts', 'mobile', ],
# 'insti_address': ['insti_address', ],
# 'program': ['program', 'roll_number', ],
# 'secondary_emails': ['secondary_emails', ],
# 'send_mail': [],
# }
#
# USER_FIELDS = [
# 'username',
# 'first_name',
# 'last_name',
# 'type',
# 'is_alumni',
# 'sex',
# 'profile_picture',
# 'email',
# 'program',
# 'secondary_emails',
# 'contacts',
# 'insti_address',
# 'mobile',
# 'roll_number',
# ]
#
# Path: user_resource/serializers.py
# class SendMailSerializer(serializers.Serializer): # pylint: disable=abstract-method
# subject = serializers.CharField()
# message = serializers.CharField()
# reply_to = serializers.ListField(
# child=serializers.EmailField()
# )
#
# class UserSerializer(serializers.ModelSerializer):
# program = ProgramSerializer()
# secondary_emails = SecondaryEmailSerializer(many=True)
# contacts = ContactNumberSerializer(many=True)
# insti_address = InstituteAddressSerializer()
# mobile = serializers.CharField(source='userprofile.mobile')
# roll_number = serializers.CharField(source='userprofile.roll_number')
# profile_picture = serializers.ImageField(source='userprofile.profile_picture')
# sex = serializers.CharField(source='userprofile.sex')
# type = serializers.CharField(source='userprofile.type')
# is_alumni = serializers.BooleanField(source='userprofile.is_alumni')
#
# def __init__(self, *args, **kwargs):
# super(UserSerializer, self).__init__(*args, **kwargs)
# fields = self.context.get('fields')
# if not isinstance(fields, list) and not isinstance(fields, set):
# fields = []
# fields.extend(DEFAULT_FIELDS)
#
# if fields is not None:
# allowed = set(fields)
# existing = set(self.fields.keys())
# fields_to_remove = existing - allowed
# for field in fields_to_remove:
# self.fields.pop(field)
#
# class Meta:
# model = User
# fields = copy.deepcopy(DEFAULT_FIELDS).extend(USER_FIELDS)
, which may include functions, classes, or code. Output only the next line. | token = self.request.auth |
Given the following code snippet before the placeholder: <|code_start|>
allowed_fields = list(set(fields).intersection(set(granted_fields)))
user_serialized = UserSerializer(user_queryset, context={'fields': allowed_fields}).data
return Response(user_serialized)
@list_route(methods=['POST'], required_scopes=['send_mail'])
def send_mail(self, request):
token = request.auth
app = token.application
app_admin = token.application.user
user = self.get_queryset().first()
mail = SendMailSerializer(data=request.data)
if mail.is_valid():
subject = '[SSO] [%s] %s' % (app.name, mail.validated_data.get('subject'))
body = ('%s\n\n\n'
'Sent via SSO by %s\n\n'
'You received this message because you\'ve provided the email sending'
' permission to the application')
body = body % (mail.validated_data.get('message'), app.name)
from_email = '%s <%s>' % (app_admin.first_name, app_admin.email)
email_message = EmailMessage(
subject=subject,
body=body,
from_email=from_email,
to=[user.email],
reply_to=mail.validated_data.get('reply_to'),
)
message = email_message.message()
sent_message = SentMessage(
message_id=message['Message-ID'],
<|code_end|>
, predict the next line using imports from the current file:
import logging
from smtplib import SMTPException
from django.contrib.auth.models import User
from django.core.mail import EmailMessage
from oauth2_provider.ext.rest_framework.permissions import TokenHasScope
from rest_framework import viewsets
from rest_framework.decorators import list_route
from rest_framework.response import Response
from rest_framework.status import HTTP_400_BAD_REQUEST
from ..models import SentMessage
from ..oauth import DEFAULT_FIELDS, SCOPE_TO_FIELD_MAP, USER_FIELDS
from ..serializers import SendMailSerializer, UserSerializer
and context including class names, function names, and sometimes code from other files:
# Path: user_resource/models.py
# class SentMessage(models.Model):
# message_id = models.CharField(max_length=256)
# sender = models.ForeignKey(Application)
# user = models.ForeignKey(User)
# status = models.BooleanField(default=True)
# error_message = models.TextField(null=True, blank=True)
# created = models.DateTimeField(auto_now_add=True)
#
# def __str__(self):
# return self.message_id
#
# Path: user_resource/oauth.py
# DEFAULT_FIELDS = ['id', ]
#
# SCOPE_TO_FIELD_MAP = {
# 'basic': ['id', ],
# 'profile': ['first_name', 'last_name', 'type', 'is_alumni', ],
# 'sex': ['sex', ],
# 'picture': ['profile_picture'],
# 'ldap': ['username', 'email'],
# 'phone': ['contacts', 'mobile', ],
# 'insti_address': ['insti_address', ],
# 'program': ['program', 'roll_number', ],
# 'secondary_emails': ['secondary_emails', ],
# 'send_mail': [],
# }
#
# USER_FIELDS = [
# 'username',
# 'first_name',
# 'last_name',
# 'type',
# 'is_alumni',
# 'sex',
# 'profile_picture',
# 'email',
# 'program',
# 'secondary_emails',
# 'contacts',
# 'insti_address',
# 'mobile',
# 'roll_number',
# ]
#
# Path: user_resource/serializers.py
# class SendMailSerializer(serializers.Serializer): # pylint: disable=abstract-method
# subject = serializers.CharField()
# message = serializers.CharField()
# reply_to = serializers.ListField(
# child=serializers.EmailField()
# )
#
# class UserSerializer(serializers.ModelSerializer):
# program = ProgramSerializer()
# secondary_emails = SecondaryEmailSerializer(many=True)
# contacts = ContactNumberSerializer(many=True)
# insti_address = InstituteAddressSerializer()
# mobile = serializers.CharField(source='userprofile.mobile')
# roll_number = serializers.CharField(source='userprofile.roll_number')
# profile_picture = serializers.ImageField(source='userprofile.profile_picture')
# sex = serializers.CharField(source='userprofile.sex')
# type = serializers.CharField(source='userprofile.type')
# is_alumni = serializers.BooleanField(source='userprofile.is_alumni')
#
# def __init__(self, *args, **kwargs):
# super(UserSerializer, self).__init__(*args, **kwargs)
# fields = self.context.get('fields')
# if not isinstance(fields, list) and not isinstance(fields, set):
# fields = []
# fields.extend(DEFAULT_FIELDS)
#
# if fields is not None:
# allowed = set(fields)
# existing = set(self.fields.keys())
# fields_to_remove = existing - allowed
# for field in fields_to_remove:
# self.fields.pop(field)
#
# class Meta:
# model = User
# fields = copy.deepcopy(DEFAULT_FIELDS).extend(USER_FIELDS)
. Output only the next line. | sender=app, |
Given snippet: <|code_start|>
logger = logging.getLogger(__name__)
class UserViewset(viewsets.GenericViewSet):
required_scopes = ['basic']
permission_classes = [TokenHasScope]
serializer_class = UserSerializer
def get_queryset(self):
token = self.request.auth
user = token.user
return User.objects.all().filter(pk=user.id)
def list(self, request):
user_queryset = self.get_queryset().first()
fields = request.query_params.get('fields')
granted_scopes = request.auth.scope
granted_scopes = granted_scopes.split()
granted_fields = []
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
from smtplib import SMTPException
from django.contrib.auth.models import User
from django.core.mail import EmailMessage
from oauth2_provider.ext.rest_framework.permissions import TokenHasScope
from rest_framework import viewsets
from rest_framework.decorators import list_route
from rest_framework.response import Response
from rest_framework.status import HTTP_400_BAD_REQUEST
from ..models import SentMessage
from ..oauth import DEFAULT_FIELDS, SCOPE_TO_FIELD_MAP, USER_FIELDS
from ..serializers import SendMailSerializer, UserSerializer
and context:
# Path: user_resource/models.py
# class SentMessage(models.Model):
# message_id = models.CharField(max_length=256)
# sender = models.ForeignKey(Application)
# user = models.ForeignKey(User)
# status = models.BooleanField(default=True)
# error_message = models.TextField(null=True, blank=True)
# created = models.DateTimeField(auto_now_add=True)
#
# def __str__(self):
# return self.message_id
#
# Path: user_resource/oauth.py
# DEFAULT_FIELDS = ['id', ]
#
# SCOPE_TO_FIELD_MAP = {
# 'basic': ['id', ],
# 'profile': ['first_name', 'last_name', 'type', 'is_alumni', ],
# 'sex': ['sex', ],
# 'picture': ['profile_picture'],
# 'ldap': ['username', 'email'],
# 'phone': ['contacts', 'mobile', ],
# 'insti_address': ['insti_address', ],
# 'program': ['program', 'roll_number', ],
# 'secondary_emails': ['secondary_emails', ],
# 'send_mail': [],
# }
#
# USER_FIELDS = [
# 'username',
# 'first_name',
# 'last_name',
# 'type',
# 'is_alumni',
# 'sex',
# 'profile_picture',
# 'email',
# 'program',
# 'secondary_emails',
# 'contacts',
# 'insti_address',
# 'mobile',
# 'roll_number',
# ]
#
# Path: user_resource/serializers.py
# class SendMailSerializer(serializers.Serializer): # pylint: disable=abstract-method
# subject = serializers.CharField()
# message = serializers.CharField()
# reply_to = serializers.ListField(
# child=serializers.EmailField()
# )
#
# class UserSerializer(serializers.ModelSerializer):
# program = ProgramSerializer()
# secondary_emails = SecondaryEmailSerializer(many=True)
# contacts = ContactNumberSerializer(many=True)
# insti_address = InstituteAddressSerializer()
# mobile = serializers.CharField(source='userprofile.mobile')
# roll_number = serializers.CharField(source='userprofile.roll_number')
# profile_picture = serializers.ImageField(source='userprofile.profile_picture')
# sex = serializers.CharField(source='userprofile.sex')
# type = serializers.CharField(source='userprofile.type')
# is_alumni = serializers.BooleanField(source='userprofile.is_alumni')
#
# def __init__(self, *args, **kwargs):
# super(UserSerializer, self).__init__(*args, **kwargs)
# fields = self.context.get('fields')
# if not isinstance(fields, list) and not isinstance(fields, set):
# fields = []
# fields.extend(DEFAULT_FIELDS)
#
# if fields is not None:
# allowed = set(fields)
# existing = set(self.fields.keys())
# fields_to_remove = existing - allowed
# for field in fields_to_remove:
# self.fields.pop(field)
#
# class Meta:
# model = User
# fields = copy.deepcopy(DEFAULT_FIELDS).extend(USER_FIELDS)
which might include code, classes, or functions. Output only the next line. | for scope in granted_scopes: |
Here is a snippet: <|code_start|>
logger = logging.getLogger(__name__)
class UserViewset(viewsets.GenericViewSet):
required_scopes = ['basic']
permission_classes = [TokenHasScope]
serializer_class = UserSerializer
def get_queryset(self):
token = self.request.auth
user = token.user
return User.objects.all().filter(pk=user.id)
def list(self, request):
user_queryset = self.get_queryset().first()
<|code_end|>
. Write the next line using the current file imports:
import logging
from smtplib import SMTPException
from django.contrib.auth.models import User
from django.core.mail import EmailMessage
from oauth2_provider.ext.rest_framework.permissions import TokenHasScope
from rest_framework import viewsets
from rest_framework.decorators import list_route
from rest_framework.response import Response
from rest_framework.status import HTTP_400_BAD_REQUEST
from ..models import SentMessage
from ..oauth import DEFAULT_FIELDS, SCOPE_TO_FIELD_MAP, USER_FIELDS
from ..serializers import SendMailSerializer, UserSerializer
and context from other files:
# Path: user_resource/models.py
# class SentMessage(models.Model):
# message_id = models.CharField(max_length=256)
# sender = models.ForeignKey(Application)
# user = models.ForeignKey(User)
# status = models.BooleanField(default=True)
# error_message = models.TextField(null=True, blank=True)
# created = models.DateTimeField(auto_now_add=True)
#
# def __str__(self):
# return self.message_id
#
# Path: user_resource/oauth.py
# DEFAULT_FIELDS = ['id', ]
#
# SCOPE_TO_FIELD_MAP = {
# 'basic': ['id', ],
# 'profile': ['first_name', 'last_name', 'type', 'is_alumni', ],
# 'sex': ['sex', ],
# 'picture': ['profile_picture'],
# 'ldap': ['username', 'email'],
# 'phone': ['contacts', 'mobile', ],
# 'insti_address': ['insti_address', ],
# 'program': ['program', 'roll_number', ],
# 'secondary_emails': ['secondary_emails', ],
# 'send_mail': [],
# }
#
# USER_FIELDS = [
# 'username',
# 'first_name',
# 'last_name',
# 'type',
# 'is_alumni',
# 'sex',
# 'profile_picture',
# 'email',
# 'program',
# 'secondary_emails',
# 'contacts',
# 'insti_address',
# 'mobile',
# 'roll_number',
# ]
#
# Path: user_resource/serializers.py
# class SendMailSerializer(serializers.Serializer): # pylint: disable=abstract-method
# subject = serializers.CharField()
# message = serializers.CharField()
# reply_to = serializers.ListField(
# child=serializers.EmailField()
# )
#
# class UserSerializer(serializers.ModelSerializer):
# program = ProgramSerializer()
# secondary_emails = SecondaryEmailSerializer(many=True)
# contacts = ContactNumberSerializer(many=True)
# insti_address = InstituteAddressSerializer()
# mobile = serializers.CharField(source='userprofile.mobile')
# roll_number = serializers.CharField(source='userprofile.roll_number')
# profile_picture = serializers.ImageField(source='userprofile.profile_picture')
# sex = serializers.CharField(source='userprofile.sex')
# type = serializers.CharField(source='userprofile.type')
# is_alumni = serializers.BooleanField(source='userprofile.is_alumni')
#
# def __init__(self, *args, **kwargs):
# super(UserSerializer, self).__init__(*args, **kwargs)
# fields = self.context.get('fields')
# if not isinstance(fields, list) and not isinstance(fields, set):
# fields = []
# fields.extend(DEFAULT_FIELDS)
#
# if fields is not None:
# allowed = set(fields)
# existing = set(self.fields.keys())
# fields_to_remove = existing - allowed
# for field in fields_to_remove:
# self.fields.pop(field)
#
# class Meta:
# model = User
# fields = copy.deepcopy(DEFAULT_FIELDS).extend(USER_FIELDS)
, which may include functions, classes, or code. Output only the next line. | fields = request.query_params.get('fields') |
Next line prediction: <|code_start|> required_scopes = ['basic']
permission_classes = [TokenHasScope]
serializer_class = UserSerializer
def get_queryset(self):
token = self.request.auth
user = token.user
return User.objects.all().filter(pk=user.id)
def list(self, request):
user_queryset = self.get_queryset().first()
fields = request.query_params.get('fields')
granted_scopes = request.auth.scope
granted_scopes = granted_scopes.split()
granted_fields = []
for scope in granted_scopes:
granted_fields.extend(SCOPE_TO_FIELD_MAP[scope])
if fields is None:
fields = []
else:
fields = fields.split(',')
fields = [field.strip() for field in fields if field.strip()]
fields = set(fields)
all_fields = set(DEFAULT_FIELDS + USER_FIELDS)
undefined_fields = list(fields - all_fields)
if undefined_fields:
error_message = {
'detail': 'fields (%s) not found' % ', '.join(undefined_fields)
}
<|code_end|>
. Use current file imports:
(import logging
from smtplib import SMTPException
from django.contrib.auth.models import User
from django.core.mail import EmailMessage
from oauth2_provider.ext.rest_framework.permissions import TokenHasScope
from rest_framework import viewsets
from rest_framework.decorators import list_route
from rest_framework.response import Response
from rest_framework.status import HTTP_400_BAD_REQUEST
from ..models import SentMessage
from ..oauth import DEFAULT_FIELDS, SCOPE_TO_FIELD_MAP, USER_FIELDS
from ..serializers import SendMailSerializer, UserSerializer)
and context including class names, function names, or small code snippets from other files:
# Path: user_resource/models.py
# class SentMessage(models.Model):
# message_id = models.CharField(max_length=256)
# sender = models.ForeignKey(Application)
# user = models.ForeignKey(User)
# status = models.BooleanField(default=True)
# error_message = models.TextField(null=True, blank=True)
# created = models.DateTimeField(auto_now_add=True)
#
# def __str__(self):
# return self.message_id
#
# Path: user_resource/oauth.py
# DEFAULT_FIELDS = ['id', ]
#
# SCOPE_TO_FIELD_MAP = {
# 'basic': ['id', ],
# 'profile': ['first_name', 'last_name', 'type', 'is_alumni', ],
# 'sex': ['sex', ],
# 'picture': ['profile_picture'],
# 'ldap': ['username', 'email'],
# 'phone': ['contacts', 'mobile', ],
# 'insti_address': ['insti_address', ],
# 'program': ['program', 'roll_number', ],
# 'secondary_emails': ['secondary_emails', ],
# 'send_mail': [],
# }
#
# USER_FIELDS = [
# 'username',
# 'first_name',
# 'last_name',
# 'type',
# 'is_alumni',
# 'sex',
# 'profile_picture',
# 'email',
# 'program',
# 'secondary_emails',
# 'contacts',
# 'insti_address',
# 'mobile',
# 'roll_number',
# ]
#
# Path: user_resource/serializers.py
# class SendMailSerializer(serializers.Serializer): # pylint: disable=abstract-method
# subject = serializers.CharField()
# message = serializers.CharField()
# reply_to = serializers.ListField(
# child=serializers.EmailField()
# )
#
# class UserSerializer(serializers.ModelSerializer):
# program = ProgramSerializer()
# secondary_emails = SecondaryEmailSerializer(many=True)
# contacts = ContactNumberSerializer(many=True)
# insti_address = InstituteAddressSerializer()
# mobile = serializers.CharField(source='userprofile.mobile')
# roll_number = serializers.CharField(source='userprofile.roll_number')
# profile_picture = serializers.ImageField(source='userprofile.profile_picture')
# sex = serializers.CharField(source='userprofile.sex')
# type = serializers.CharField(source='userprofile.type')
# is_alumni = serializers.BooleanField(source='userprofile.is_alumni')
#
# def __init__(self, *args, **kwargs):
# super(UserSerializer, self).__init__(*args, **kwargs)
# fields = self.context.get('fields')
# if not isinstance(fields, list) and not isinstance(fields, set):
# fields = []
# fields.extend(DEFAULT_FIELDS)
#
# if fields is not None:
# allowed = set(fields)
# existing = set(self.fields.keys())
# fields_to_remove = existing - allowed
# for field in fields_to_remove:
# self.fields.pop(field)
#
# class Meta:
# model = User
# fields = copy.deepcopy(DEFAULT_FIELDS).extend(USER_FIELDS)
. Output only the next line. | return Response(error_message, status=HTTP_400_BAD_REQUEST) |
Predict the next line for this snippet: <|code_start|>
@click.group(
"pipelimit",
help="Manage pipelimit module",
short_help="Manage pipelimit module",
)
@pass_context
def cli(ctx):
<|code_end|>
with the help of current file imports:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and context from other files:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
, which may contain function names, class names, or code. Output only the next line. | pass |
Here is a snippet: <|code_start|>
@click.group(
"pipelimit",
help="Manage pipelimit module",
short_help="Manage pipelimit module",
)
@pass_context
def cli(ctx):
pass
@cli.command("db-add", short_help="Add a new pipelimit record to database")
@click.option(
"dbtname",
"--dbtname",
default="pl_pipes",
help='The name of database table (default: "pl_pipes")',
)
@click.option(
"alg",
<|code_end|>
. Write the next line using the current file imports:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and context from other files:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
, which may include functions, classes, or code. Output only the next line. | "--alg", |
Here is a snippet: <|code_start|>
@click.group(
"aliasdb",
help="Manage database user aliases",
short_help="Manage database user aliases",
)
@pass_context
<|code_end|>
. Write the next line using the current file imports:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.cli import parse_user_spec
and context from other files:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/cli.py
# def parse_user_spec(ctx, ustr):
# """Get details of the user from ustr (username, aor or sip uri)"""
# udata = {}
# if ":" in ustr:
# uaor = ustr.split(":")[1]
# else:
# uaor = ustr
# if "@" in uaor:
# udata["username"] = uaor.split("@")[0]
# udata["domain"] = uaor.split("@")[1]
# else:
# udata["username"] = uaor.split("@")[0]
# try:
# udata["domain"] = ctx.gconfig.get("main", "domain")
# except configparser.NoOptionError:
# ctx.log("Default domain not set in config file")
# sys.exit()
# if udata["username"] is None:
# ctx.log("Failed to get username")
# sys.exit()
# if udata["domain"] is None:
# ctx.log("Failed to get domain")
# sys.exit()
# udata["username"] = udata["username"].encode("ascii", "ignore").decode()
# udata["domain"] = udata["domain"].encode("ascii", "ignore").decode()
# return udata
, which may include functions, classes, or code. Output only the next line. | def cli(ctx): |
Given the following code snippet before the placeholder: <|code_start|>
@click.group(
"aliasdb",
help="Manage database user aliases",
short_help="Manage database user aliases",
)
@pass_context
def cli(ctx):
pass
@cli.command("add", short_help="Add a user-alias pair")
@click.option(
"table",
"--table",
default="dbaliases",
<|code_end|>
, predict the next line using imports from the current file:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.cli import parse_user_spec
and context including class names, function names, and sometimes code from other files:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/cli.py
# def parse_user_spec(ctx, ustr):
# """Get details of the user from ustr (username, aor or sip uri)"""
# udata = {}
# if ":" in ustr:
# uaor = ustr.split(":")[1]
# else:
# uaor = ustr
# if "@" in uaor:
# udata["username"] = uaor.split("@")[0]
# udata["domain"] = uaor.split("@")[1]
# else:
# udata["username"] = uaor.split("@")[0]
# try:
# udata["domain"] = ctx.gconfig.get("main", "domain")
# except configparser.NoOptionError:
# ctx.log("Default domain not set in config file")
# sys.exit()
# if udata["username"] is None:
# ctx.log("Failed to get username")
# sys.exit()
# if udata["domain"] is None:
# ctx.log("Failed to get domain")
# sys.exit()
# udata["username"] = udata["username"].encode("ascii", "ignore").decode()
# udata["domain"] = udata["domain"].encode("ascii", "ignore").decode()
# return udata
. Output only the next line. | help="Name of database table (default: dbaliases)", |
Next line prediction: <|code_start|>
@click.group(
"aliasdb",
help="Manage database user aliases",
short_help="Manage database user aliases",
)
@pass_context
def cli(ctx):
pass
@cli.command("add", short_help="Add a user-alias pair")
@click.option(
"table",
<|code_end|>
. Use current file imports:
(import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.cli import parse_user_spec)
and context including class names, function names, or small code snippets from other files:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/cli.py
# def parse_user_spec(ctx, ustr):
# """Get details of the user from ustr (username, aor or sip uri)"""
# udata = {}
# if ":" in ustr:
# uaor = ustr.split(":")[1]
# else:
# uaor = ustr
# if "@" in uaor:
# udata["username"] = uaor.split("@")[0]
# udata["domain"] = uaor.split("@")[1]
# else:
# udata["username"] = uaor.split("@")[0]
# try:
# udata["domain"] = ctx.gconfig.get("main", "domain")
# except configparser.NoOptionError:
# ctx.log("Default domain not set in config file")
# sys.exit()
# if udata["username"] is None:
# ctx.log("Failed to get username")
# sys.exit()
# if udata["domain"] is None:
# ctx.log("Failed to get domain")
# sys.exit()
# udata["username"] = udata["username"].encode("ascii", "ignore").decode()
# udata["domain"] = udata["domain"].encode("ascii", "ignore").decode()
# return udata
. Output only the next line. | "--table", |
Predict the next line after this snippet: <|code_start|>
@click.group(
"pkg",
help="Private memory (pkg) management",
short_help="Private memory (pkg) management",
)
@pass_context
def cli(ctx):
<|code_end|>
using the current file's imports:
import click
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and any relevant context from other files:
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
. Output only the next line. | pass |
Given the code snippet: <|code_start|>)
@click.option(
"colusername",
"--colusername",
default="username",
help='Column name for uuid (default: "username")',
)
@click.option(
"coldomain",
"--coldomain",
default="domain",
help='Column name for domain (default: "domain")',
)
@click.option(
"colattribute",
"--colattribute",
default="attribute",
help='Column name for attribute (default: "attribute")',
)
@click.option(
"coltype",
"--coltype",
default="type",
help='Column name for type (default: "type")',
)
@click.option(
"colvalue",
"--colvalue",
default="value",
help='Column name for value (default: "value")',
<|code_end|>
, generate the next line using the imports in this file:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.cli import parse_user_spec
and context (functions, classes, or occasionally code) from other files:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/cli.py
# def parse_user_spec(ctx, ustr):
# """Get details of the user from ustr (username, aor or sip uri)"""
# udata = {}
# if ":" in ustr:
# uaor = ustr.split(":")[1]
# else:
# uaor = ustr
# if "@" in uaor:
# udata["username"] = uaor.split("@")[0]
# udata["domain"] = uaor.split("@")[1]
# else:
# udata["username"] = uaor.split("@")[0]
# try:
# udata["domain"] = ctx.gconfig.get("main", "domain")
# except configparser.NoOptionError:
# ctx.log("Default domain not set in config file")
# sys.exit()
# if udata["username"] is None:
# ctx.log("Failed to get username")
# sys.exit()
# if udata["domain"] is None:
# ctx.log("Failed to get domain")
# sys.exit()
# udata["username"] = udata["username"].encode("ascii", "ignore").decode()
# udata["domain"] = udata["domain"].encode("ascii", "ignore").decode()
# return udata
. Output only the next line. | ) |
Predict the next line after this snippet: <|code_start|>@click.option(
"colusername",
"--colusername",
default="username",
help='Column name for uuid (default: "username")',
)
@click.option(
"coldomain",
"--coldomain",
default="domain",
help='Column name for domain (default: "domain")',
)
@click.option(
"colattribute",
"--colattribute",
default="attribute",
help='Column name for attribute (default: "attribute")',
)
@click.option(
"coltype",
"--coltype",
default="type",
help='Column name for type (default: "type")',
)
@click.option(
"colvalue",
"--colvalue",
default="value",
help='Column name for value (default: "value")',
)
<|code_end|>
using the current file's imports:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.cli import parse_user_spec
and any relevant context from other files:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/cli.py
# def parse_user_spec(ctx, ustr):
# """Get details of the user from ustr (username, aor or sip uri)"""
# udata = {}
# if ":" in ustr:
# uaor = ustr.split(":")[1]
# else:
# uaor = ustr
# if "@" in uaor:
# udata["username"] = uaor.split("@")[0]
# udata["domain"] = uaor.split("@")[1]
# else:
# udata["username"] = uaor.split("@")[0]
# try:
# udata["domain"] = ctx.gconfig.get("main", "domain")
# except configparser.NoOptionError:
# ctx.log("Default domain not set in config file")
# sys.exit()
# if udata["username"] is None:
# ctx.log("Failed to get username")
# sys.exit()
# if udata["domain"] is None:
# ctx.log("Failed to get domain")
# sys.exit()
# udata["username"] = udata["username"].encode("ascii", "ignore").decode()
# udata["domain"] = udata["domain"].encode("ascii", "ignore").decode()
# return udata
. Output only the next line. | @click.option( |
Continue the code snippet: <|code_start|>
@click.group(
"avp",
help="Manage AVP user preferences",
short_help="Manage AVP user preferences",
)
@pass_context
def cli(ctx):
pass
@cli.command("db-add", short_help="Add a new AVP to database")
@click.option(
<|code_end|>
. Use current file imports:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.cli import parse_user_spec
and context (classes, functions, or code) from other files:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/cli.py
# def parse_user_spec(ctx, ustr):
# """Get details of the user from ustr (username, aor or sip uri)"""
# udata = {}
# if ":" in ustr:
# uaor = ustr.split(":")[1]
# else:
# uaor = ustr
# if "@" in uaor:
# udata["username"] = uaor.split("@")[0]
# udata["domain"] = uaor.split("@")[1]
# else:
# udata["username"] = uaor.split("@")[0]
# try:
# udata["domain"] = ctx.gconfig.get("main", "domain")
# except configparser.NoOptionError:
# ctx.log("Default domain not set in config file")
# sys.exit()
# if udata["username"] is None:
# ctx.log("Failed to get username")
# sys.exit()
# if udata["domain"] is None:
# ctx.log("Failed to get domain")
# sys.exit()
# udata["username"] = udata["username"].encode("ascii", "ignore").decode()
# udata["domain"] = udata["domain"].encode("ascii", "ignore").decode()
# return udata
. Output only the next line. | "dbtname", |
Predict the next line after this snippet: <|code_start|>
@click.group(
"speeddial",
help="Manage speed dial records",
short_help="Manage speed dial records",
)
@pass_context
def cli(ctx):
pass
@cli.command("add", short_help="Add a speed dial record")
@click.option(
"table",
"--table",
default="speed_dial",
help="Name of database table (default: speed_dial)",
)
@click.argument("userid", metavar="<userid>")
<|code_end|>
using the current file's imports:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.cli import parse_user_spec
and any relevant context from other files:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/cli.py
# def parse_user_spec(ctx, ustr):
# """Get details of the user from ustr (username, aor or sip uri)"""
# udata = {}
# if ":" in ustr:
# uaor = ustr.split(":")[1]
# else:
# uaor = ustr
# if "@" in uaor:
# udata["username"] = uaor.split("@")[0]
# udata["domain"] = uaor.split("@")[1]
# else:
# udata["username"] = uaor.split("@")[0]
# try:
# udata["domain"] = ctx.gconfig.get("main", "domain")
# except configparser.NoOptionError:
# ctx.log("Default domain not set in config file")
# sys.exit()
# if udata["username"] is None:
# ctx.log("Failed to get username")
# sys.exit()
# if udata["domain"] is None:
# ctx.log("Failed to get domain")
# sys.exit()
# udata["username"] = udata["username"].encode("ascii", "ignore").decode()
# udata["domain"] = udata["domain"].encode("ascii", "ignore").decode()
# return udata
. Output only the next line. | @click.argument("shortdial", metavar="<shortdial>") |
Using the snippet: <|code_start|>
@click.group(
"speeddial",
help="Manage speed dial records",
short_help="Manage speed dial records",
)
@pass_context
def cli(ctx):
pass
@cli.command("add", short_help="Add a speed dial record")
@click.option(
"table",
"--table",
default="speed_dial",
<|code_end|>
, determine the next line of code. You have imports:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.cli import parse_user_spec
and context (class names, function names, or code) available:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/cli.py
# def parse_user_spec(ctx, ustr):
# """Get details of the user from ustr (username, aor or sip uri)"""
# udata = {}
# if ":" in ustr:
# uaor = ustr.split(":")[1]
# else:
# uaor = ustr
# if "@" in uaor:
# udata["username"] = uaor.split("@")[0]
# udata["domain"] = uaor.split("@")[1]
# else:
# udata["username"] = uaor.split("@")[0]
# try:
# udata["domain"] = ctx.gconfig.get("main", "domain")
# except configparser.NoOptionError:
# ctx.log("Default domain not set in config file")
# sys.exit()
# if udata["username"] is None:
# ctx.log("Failed to get username")
# sys.exit()
# if udata["domain"] is None:
# ctx.log("Failed to get domain")
# sys.exit()
# udata["username"] = udata["username"].encode("ascii", "ignore").decode()
# udata["domain"] = udata["domain"].encode("ascii", "ignore").decode()
# return udata
. Output only the next line. | help="Name of database table (default: speed_dial)", |
Predict the next line after this snippet: <|code_start|>
@click.group(
"config",
help="Manage the config file",
<|code_end|>
using the current file's imports:
import os
import sys
import json
import click
import shutil
from kamcli.cli import pass_context
from kamcli.cli import COMMAND_ALIASES
and any relevant context from other files:
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
. Output only the next line. | short_help="Manage the config file", |
Here is a snippet: <|code_start|>
@click.group(
"domain",
help="Manage domain module (multi-domain records)",
short_help="Manage domain module",
)
@pass_context
def cli(ctx):
pass
@cli.command("add", short_help="Add a new domain")
@click.argument("domain", metavar="<domain>")
@pass_context
<|code_end|>
. Write the next line using the current file imports:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and context from other files:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
, which may include functions, classes, or code. Output only the next line. | def domain_add(ctx, domain): |
Using the snippet: <|code_start|>
@click.group(
"domain",
help="Manage domain module (multi-domain records)",
short_help="Manage domain module",
)
@pass_context
def cli(ctx):
pass
@cli.command("add", short_help="Add a new domain")
@click.argument("domain", metavar="<domain>")
@pass_context
<|code_end|>
, determine the next line of code. You have imports:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and context (class names, function names, or code) available:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
. Output only the next line. | def domain_add(ctx, domain): |
Continue the code snippet: <|code_start|>
@click.group(
"ul",
help="Manage user location records",
short_help="Manage user location records",
)
@pass_context
<|code_end|>
. Use current file imports:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.ioutils import ioutils_formats_list
from kamcli.cli import pass_context
from kamcli.cli import parse_user_spec
from kamcli.iorpc import command_ctl
and context (classes, functions, or code) from other files:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/cli.py
# def parse_user_spec(ctx, ustr):
# """Get details of the user from ustr (username, aor or sip uri)"""
# udata = {}
# if ":" in ustr:
# uaor = ustr.split(":")[1]
# else:
# uaor = ustr
# if "@" in uaor:
# udata["username"] = uaor.split("@")[0]
# udata["domain"] = uaor.split("@")[1]
# else:
# udata["username"] = uaor.split("@")[0]
# try:
# udata["domain"] = ctx.gconfig.get("main", "domain")
# except configparser.NoOptionError:
# ctx.log("Default domain not set in config file")
# sys.exit()
# if udata["username"] is None:
# ctx.log("Failed to get username")
# sys.exit()
# if udata["domain"] is None:
# ctx.log("Failed to get domain")
# sys.exit()
# udata["username"] = udata["username"].encode("ascii", "ignore").decode()
# udata["domain"] = udata["domain"].encode("ascii", "ignore").decode()
# return udata
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
. Output only the next line. | def cli(ctx): |
Here is a snippet: <|code_start|>
@click.group(
"ul",
help="Manage user location records",
short_help="Manage user location records",
)
@pass_context
def cli(ctx):
pass
@cli.command("show", short_help="Show details for location records in memory")
@click.option(
<|code_end|>
. Write the next line using the current file imports:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.ioutils import ioutils_formats_list
from kamcli.cli import pass_context
from kamcli.cli import parse_user_spec
from kamcli.iorpc import command_ctl
and context from other files:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/cli.py
# def parse_user_spec(ctx, ustr):
# """Get details of the user from ustr (username, aor or sip uri)"""
# udata = {}
# if ":" in ustr:
# uaor = ustr.split(":")[1]
# else:
# uaor = ustr
# if "@" in uaor:
# udata["username"] = uaor.split("@")[0]
# udata["domain"] = uaor.split("@")[1]
# else:
# udata["username"] = uaor.split("@")[0]
# try:
# udata["domain"] = ctx.gconfig.get("main", "domain")
# except configparser.NoOptionError:
# ctx.log("Default domain not set in config file")
# sys.exit()
# if udata["username"] is None:
# ctx.log("Failed to get username")
# sys.exit()
# if udata["domain"] is None:
# ctx.log("Failed to get domain")
# sys.exit()
# udata["username"] = udata["username"].encode("ascii", "ignore").decode()
# udata["domain"] = udata["domain"].encode("ascii", "ignore").decode()
# return udata
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
, which may include functions, classes, or code. Output only the next line. | "brief", "--brief", is_flag=True, help="Show brief format of the records." |
Given the code snippet: <|code_start|>
@click.group(
"ul",
help="Manage user location records",
short_help="Manage user location records",
)
@pass_context
def cli(ctx):
<|code_end|>
, generate the next line using the imports in this file:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.ioutils import ioutils_formats_list
from kamcli.cli import pass_context
from kamcli.cli import parse_user_spec
from kamcli.iorpc import command_ctl
and context (functions, classes, or occasionally code) from other files:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/cli.py
# def parse_user_spec(ctx, ustr):
# """Get details of the user from ustr (username, aor or sip uri)"""
# udata = {}
# if ":" in ustr:
# uaor = ustr.split(":")[1]
# else:
# uaor = ustr
# if "@" in uaor:
# udata["username"] = uaor.split("@")[0]
# udata["domain"] = uaor.split("@")[1]
# else:
# udata["username"] = uaor.split("@")[0]
# try:
# udata["domain"] = ctx.gconfig.get("main", "domain")
# except configparser.NoOptionError:
# ctx.log("Default domain not set in config file")
# sys.exit()
# if udata["username"] is None:
# ctx.log("Failed to get username")
# sys.exit()
# if udata["domain"] is None:
# ctx.log("Failed to get domain")
# sys.exit()
# udata["username"] = udata["username"].encode("ascii", "ignore").decode()
# udata["domain"] = udata["domain"].encode("ascii", "ignore").decode()
# return udata
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
. Output only the next line. | pass |
Predict the next line for this snippet: <|code_start|>
@click.group(
"ul",
help="Manage user location records",
short_help="Manage user location records",
)
@pass_context
def cli(ctx):
<|code_end|>
with the help of current file imports:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.ioutils import ioutils_formats_list
from kamcli.cli import pass_context
from kamcli.cli import parse_user_spec
from kamcli.iorpc import command_ctl
and context from other files:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/cli.py
# def parse_user_spec(ctx, ustr):
# """Get details of the user from ustr (username, aor or sip uri)"""
# udata = {}
# if ":" in ustr:
# uaor = ustr.split(":")[1]
# else:
# uaor = ustr
# if "@" in uaor:
# udata["username"] = uaor.split("@")[0]
# udata["domain"] = uaor.split("@")[1]
# else:
# udata["username"] = uaor.split("@")[0]
# try:
# udata["domain"] = ctx.gconfig.get("main", "domain")
# except configparser.NoOptionError:
# ctx.log("Default domain not set in config file")
# sys.exit()
# if udata["username"] is None:
# ctx.log("Failed to get username")
# sys.exit()
# if udata["domain"] is None:
# ctx.log("Failed to get domain")
# sys.exit()
# udata["username"] = udata["username"].encode("ascii", "ignore").decode()
# udata["domain"] = udata["domain"].encode("ascii", "ignore").decode()
# return udata
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
, which may contain function names, class names, or code. Output only the next line. | pass |
Given the following code snippet before the placeholder: <|code_start|>
@click.group(
"shv",
help="Manage $shv(name) variables",
<|code_end|>
, predict the next line using imports from the current file:
import click
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and context including class names, function names, and sometimes code from other files:
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
. Output only the next line. | short_help="Manage $shv(name) variables", |
Next line prediction: <|code_start|>
@click.group(
"htable",
help="Management of htable module",
short_help="Management of htable module",
)
@pass_context
def cli(ctx):
pass
@cli.command("list", short_help="List the content of hash table named htname")
<|code_end|>
. Use current file imports:
(import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl)
and context including class names, function names, or small code snippets from other files:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
. Output only the next line. | @click.argument("htname", metavar="<htname>") |
Given the following code snippet before the placeholder: <|code_start|>
@click.group(
"htable",
help="Management of htable module",
short_help="Management of htable module",
)
@pass_context
def cli(ctx):
pass
@cli.command("list", short_help="List the content of hash table named htname")
<|code_end|>
, predict the next line using imports from the current file:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and context including class names, function names, and sometimes code from other files:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
. Output only the next line. | @click.argument("htname", metavar="<htname>") |
Given snippet: <|code_start|>
@click.group(
"htable",
help="Management of htable module",
short_help="Management of htable module",
)
@pass_context
def cli(ctx):
pass
@cli.command("list", short_help="List the content of hash table named htname")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and context:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
which might include code, classes, or functions. Output only the next line. | @click.argument("htname", metavar="<htname>") |
Given the following code snippet before the placeholder: <|code_start|>
@click.command("stats", short_help="Print internal statistics")
@click.option(
"single",
"--single",
"-s",
is_flag=True,
help="The name belong to one statistic (otherwise the name is "
"for a group)",
)
<|code_end|>
, predict the next line using imports from the current file:
import click
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and context including class names, function names, and sometimes code from other files:
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
. Output only the next line. | @click.option( |
Here is a snippet: <|code_start|>
@click.command("stats", short_help="Print internal statistics")
@click.option(
"single",
"--single",
"-s",
is_flag=True,
help="The name belong to one statistic (otherwise the name is "
"for a group)",
<|code_end|>
. Write the next line using the current file imports:
import click
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and context from other files:
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
, which may include functions, classes, or code. Output only the next line. | ) |
Based on the snippet: <|code_start|>
@click.group(
"uacreg",
help="Manage uac remote registrations",
short_help="Manage uac registrations",
)
@pass_context
def cli(ctx):
pass
@cli.command("add", short_help="Add a new remote registration account")
@click.option("realm", "--realm", default="", help='Realm (default: "")')
@click.option(
"authha1", "--auth-ha1", is_flag=True, help="Auth password in HA1 format"
)
<|code_end|>
, predict the immediate next line with the help of imports:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and context (classes, functions, sometimes code) from other files:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
. Output only the next line. | @click.option( |
Next line prediction: <|code_start|> "regdelay",
"--reg-delay",
type=int,
default=0,
help="Registration delay (default: 0)",
)
@click.option(
"socket", "--socket", default="", help='Local socket (default: "")'
)
@click.argument("l_uuid", metavar="<l_uuid>")
@click.argument("l_username", metavar="<l_username>")
@click.argument("l_domain", metavar="<l_domain>")
@click.argument("r_username", metavar="<r_username>")
@click.argument("r_domain", metavar="<r_domain>")
@click.argument("auth_username", metavar="<auth_username>")
@click.argument("auth_password", metavar="<auth_password>")
@click.argument("auth_proxy", metavar="<auth_proxy>")
@click.argument("expires", metavar="<expires>", type=int)
@pass_context
def uacreg_add(
ctx,
realm,
authha1,
flags,
regdelay,
socket,
l_uuid,
l_username,
l_domain,
r_username,
<|code_end|>
. Use current file imports:
(import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl)
and context including class names, function names, or small code snippets from other files:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
. Output only the next line. | r_domain, |
Predict the next line for this snippet: <|code_start|>)
@pass_context
def cli(ctx):
pass
@cli.command("add", short_help="Add a new remote registration account")
@click.option("realm", "--realm", default="", help='Realm (default: "")')
@click.option(
"authha1", "--auth-ha1", is_flag=True, help="Auth password in HA1 format"
)
@click.option(
"flags", "--flags", type=int, default=0, help="Flags (default: 0)"
)
@click.option(
"regdelay",
"--reg-delay",
type=int,
default=0,
help="Registration delay (default: 0)",
)
@click.option(
"socket", "--socket", default="", help='Local socket (default: "")'
)
@click.argument("l_uuid", metavar="<l_uuid>")
@click.argument("l_username", metavar="<l_username>")
@click.argument("l_domain", metavar="<l_domain>")
@click.argument("r_username", metavar="<r_username>")
@click.argument("r_domain", metavar="<r_domain>")
@click.argument("auth_username", metavar="<auth_username>")
<|code_end|>
with the help of current file imports:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and context from other files:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
, which may contain function names, class names, or code. Output only the next line. | @click.argument("auth_password", metavar="<auth_password>") |
Using the snippet: <|code_start|>
@click.group(
"dialplan",
help="Manage dialplan module (regexp translations)",
short_help="Manage dialplan module",
<|code_end|>
, determine the next line of code. You have imports:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and context (class names, function names, or code) available:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
. Output only the next line. | ) |
Using the snippet: <|code_start|>
@click.group(
"dialplan",
help="Manage dialplan module (regexp translations)",
short_help="Manage dialplan module",
)
@pass_context
def cli(ctx):
pass
@cli.command("add", short_help="Add a new dialplan rule")
<|code_end|>
, determine the next line of code. You have imports:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and context (class names, function names, or code) available:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
. Output only the next line. | @click.option( |
Using the snippet: <|code_start|>
@click.group(
"dialplan",
help="Manage dialplan module (regexp translations)",
short_help="Manage dialplan module",
)
@pass_context
def cli(ctx):
pass
@cli.command("add", short_help="Add a new dialplan rule")
@click.option(
<|code_end|>
, determine the next line of code. You have imports:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and context (class names, function names, or code) available:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
. Output only the next line. | "priority", |
Using the snippet: <|code_start|>
@click.group(
"address",
help="Manage permissions address records",
short_help="Manage permissions address records",
)
@pass_context
def cli(ctx):
pass
@cli.command("add", short_help="Add a new record to address table")
@click.option(
"mask", "--mask", type=int, default=32, help="Mask value (default 32)"
)
@click.option(
"port", "--port", type=int, default=0, help="Port value (default 0)"
)
@click.option("tag", "--tag", default="", help='Tag value (default: "")')
<|code_end|>
, determine the next line of code. You have imports:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and context (class names, function names, or code) available:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
. Output only the next line. | @click.argument("group", metavar="<group>", type=int) |
Predict the next line after this snippet: <|code_start|>
@click.group(
"address",
help="Manage permissions address records",
short_help="Manage permissions address records",
)
@pass_context
def cli(ctx):
pass
@cli.command("add", short_help="Add a new record to address table")
@click.option(
"mask", "--mask", type=int, default=32, help="Mask value (default 32)"
)
@click.option(
"port", "--port", type=int, default=0, help="Port value (default 0)"
)
@click.option("tag", "--tag", default="", help='Tag value (default: "")')
@click.argument("group", metavar="<group>", type=int)
<|code_end|>
using the current file's imports:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and any relevant context from other files:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
. Output only the next line. | @click.argument("address", metavar="<address>") |
Predict the next line after this snippet: <|code_start|>
@click.group(
"address",
help="Manage permissions address records",
<|code_end|>
using the current file's imports:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and any relevant context from other files:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
. Output only the next line. | short_help="Manage permissions address records", |
Predict the next line after this snippet: <|code_start|>
@click.group(
"apiban", help="Manage APIBan records", short_help="Manage APIBan records",
)
@pass_context
def cli(ctx):
pass
def apiban_key(ctx, key):
if key is None:
key = ctx.gconfig.get("apiban", "key", fallback=None)
if key is None:
return os.environ.get("APIBANKEY")
return key
def apiban_fetch(ctx, key):
<|code_end|>
using the current file's imports:
import click
import http.client
import os
import json
import time
import pprint
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and any relevant context from other files:
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
. Output only the next line. | conn = http.client.HTTPSConnection("apiban.org", timeout=4) |
Here is a snippet: <|code_start|>
@click.group(
"apiban", help="Manage APIBan records", short_help="Manage APIBan records",
)
@pass_context
def cli(ctx):
pass
def apiban_key(ctx, key):
if key is None:
key = ctx.gconfig.get("apiban", "key", fallback=None)
if key is None:
return os.environ.get("APIBANKEY")
return key
def apiban_fetch(ctx, key):
conn = http.client.HTTPSConnection("apiban.org", timeout=4)
idval = ""
allAddresses = []
while True:
time.sleep(1)
conn.request("GET", "/api/" + key + "/banned" + idval)
r1 = conn.getresponse()
ctx.vlog("response: " + str(r1.status) + " " + r1.reason)
if r1.status == 200:
data1 = r1.read()
jdata = json.loads(data1)
<|code_end|>
. Write the next line using the current file imports:
import click
import http.client
import os
import json
import time
import pprint
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and context from other files:
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
, which may include functions, classes, or code. Output only the next line. | ctx.vlog( |
Given the following code snippet before the placeholder: <|code_start|>
@click.group(
"rtpengine",
help="Manage rtpengine module",
short_help="Manage rtpengine module",
)
@pass_context
def cli(ctx):
pass
@cli.command("showdb", short_help="Show the rtpengine records in database")
@click.option(
"oformat",
"--output-format",
"-F",
type=click.Choice(["raw", "json", "table", "dict"]),
default=None,
help="Format the output",
)
<|code_end|>
, predict the next line using imports from the current file:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and context including class names, function names, and sometimes code from other files:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
. Output only the next line. | @click.option( |
Predict the next line after this snippet: <|code_start|>
@click.group(
"rtpengine",
help="Manage rtpengine module",
short_help="Manage rtpengine module",
)
@pass_context
def cli(ctx):
pass
@cli.command("showdb", short_help="Show the rtpengine records in database")
@click.option(
"oformat",
"--output-format",
"-F",
type=click.Choice(["raw", "json", "table", "dict"]),
default=None,
help="Format the output",
<|code_end|>
using the current file's imports:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and any relevant context from other files:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
. Output only the next line. | ) |
Here is a snippet: <|code_start|>
@click.group(
"rtpengine",
help="Manage rtpengine module",
short_help="Manage rtpengine module",
)
@pass_context
def cli(ctx):
pass
<|code_end|>
. Write the next line using the current file imports:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and context from other files:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
, which may include functions, classes, or code. Output only the next line. | @cli.command("showdb", short_help="Show the rtpengine records in database") |
Given the following code snippet before the placeholder: <|code_start|>
@click.group(
"dlgs",
help="Manage dlgs module (active calls stats)",
short_help="Manage dlgs module",
)
@pass_context
def cli(ctx):
pass
@cli.command("list", short_help="Show details for dialog records in memory")
@pass_context
<|code_end|>
, predict the next line using imports from the current file:
import click
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and context including class names, function names, and sometimes code from other files:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
. Output only the next line. | def dlgs_list(ctx): |
Next line prediction: <|code_start|>
@click.command("ping", short_help="Send an OPTIONS ping request")
@click.option(
"nowait", "--nowait", "-n", is_flag=True, help="Do wait for response",
)
@click.option("furi", "--furi", default="", help='From URI (default: "")')
<|code_end|>
. Use current file imports:
(import click
import json
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl)
and context including class names, function names, or small code snippets from other files:
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
. Output only the next line. | @click.argument("uri", nargs=1, metavar="[<uri>]") |
Here is a snippet: <|code_start|>
@click.command("ping", short_help="Send an OPTIONS ping request")
@click.option(
"nowait", "--nowait", "-n", is_flag=True, help="Do wait for response",
)
@click.option("furi", "--furi", default="", help='From URI (default: "")')
<|code_end|>
. Write the next line using the current file imports:
import click
import json
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and context from other files:
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
, which may include functions, classes, or code. Output only the next line. | @click.argument("uri", nargs=1, metavar="[<uri>]") |
Based on the snippet: <|code_start|> """
command_ctl(ctx, "tls.list", [])
@cli.command("info", short_help="Summary of tls usage")
@pass_context
def tls_info(ctx):
"""Summary of tls usage
\b
"""
command_ctl(ctx, "tls.info", [])
@cli.command(
"sqlprint", short_help="Print SQL statement to create the db table"
)
@pass_context
def tls_sqlprint(ctx):
"""Print SQL statement to create the db table
\b
"""
sqls = """
CREATE TABLE `tlscfg` (
`id` INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY NOT NULL,
`profile_type` VARCHAR(64) NOT NULL,
`profile_name` VARCHAR(128) NOT NULL,
`method` VARCHAR(128),
`verify_certificate` INT DEFAULT 0 NOT NULL,
<|code_end|>
, predict the immediate next line with the help of imports:
import sys
import os
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and context (classes, functions, sometimes code) from other files:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
. Output only the next line. | `verify_depth` INT DEFAULT 9 NOT NULL, |
Given the code snippet: <|code_start|>
@click.group(
"shm",
help="Shared memory (shm) management",
short_help="Shared memory (shm) management",
)
@pass_context
def cli(ctx):
pass
@cli.command("stats", short_help="Show the stats for shared (shm) memory")
@pass_context
<|code_end|>
, generate the next line using the imports in this file:
import click
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and context (functions, classes, or occasionally code) from other files:
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
. Output only the next line. | def shm_stats(ctx): |
Here is a snippet: <|code_start|>
@click.group(
"subscriber",
help="Manage the subscribers",
short_help="Manage the subscribers",
)
@pass_context
<|code_end|>
. Write the next line using the current file imports:
import click
import hashlib
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.cli import parse_user_spec
and context from other files:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/cli.py
# def parse_user_spec(ctx, ustr):
# """Get details of the user from ustr (username, aor or sip uri)"""
# udata = {}
# if ":" in ustr:
# uaor = ustr.split(":")[1]
# else:
# uaor = ustr
# if "@" in uaor:
# udata["username"] = uaor.split("@")[0]
# udata["domain"] = uaor.split("@")[1]
# else:
# udata["username"] = uaor.split("@")[0]
# try:
# udata["domain"] = ctx.gconfig.get("main", "domain")
# except configparser.NoOptionError:
# ctx.log("Default domain not set in config file")
# sys.exit()
# if udata["username"] is None:
# ctx.log("Failed to get username")
# sys.exit()
# if udata["domain"] is None:
# ctx.log("Failed to get domain")
# sys.exit()
# udata["username"] = udata["username"].encode("ascii", "ignore").decode()
# udata["domain"] = udata["domain"].encode("ascii", "ignore").decode()
# return udata
, which may include functions, classes, or code. Output only the next line. | def cli(ctx): |
Next line prediction: <|code_start|>
@click.group(
"subscriber",
help="Manage the subscribers",
short_help="Manage the subscribers",
)
@pass_context
def cli(ctx):
pass
@cli.command("add", short_help="Add a new subscriber")
@click.option(
"dbtname",
"--dbtname",
"-T",
default="subscriber",
help='Database table name (default: "subscriber")',
)
@click.option(
"pwtext",
"--text-password",
"-t",
type=click.Choice(["yes", "no"]),
default="yes",
<|code_end|>
. Use current file imports:
(import click
import hashlib
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.cli import parse_user_spec)
and context including class names, function names, or small code snippets from other files:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/cli.py
# def parse_user_spec(ctx, ustr):
# """Get details of the user from ustr (username, aor or sip uri)"""
# udata = {}
# if ":" in ustr:
# uaor = ustr.split(":")[1]
# else:
# uaor = ustr
# if "@" in uaor:
# udata["username"] = uaor.split("@")[0]
# udata["domain"] = uaor.split("@")[1]
# else:
# udata["username"] = uaor.split("@")[0]
# try:
# udata["domain"] = ctx.gconfig.get("main", "domain")
# except configparser.NoOptionError:
# ctx.log("Default domain not set in config file")
# sys.exit()
# if udata["username"] is None:
# ctx.log("Failed to get username")
# sys.exit()
# if udata["domain"] is None:
# ctx.log("Failed to get domain")
# sys.exit()
# udata["username"] = udata["username"].encode("ascii", "ignore").decode()
# udata["domain"] = udata["domain"].encode("ascii", "ignore").decode()
# return udata
. Output only the next line. | help="Store password in clear text (default yes)", |
Using the snippet: <|code_start|>
@click.group(
"subscriber",
help="Manage the subscribers",
short_help="Manage the subscribers",
)
@pass_context
def cli(ctx):
pass
@cli.command("add", short_help="Add a new subscriber")
@click.option(
"dbtname",
"--dbtname",
"-T",
default="subscriber",
help='Database table name (default: "subscriber")',
)
@click.option(
<|code_end|>
, determine the next line of code. You have imports:
import click
import hashlib
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.cli import parse_user_spec
and context (class names, function names, or code) available:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/cli.py
# def parse_user_spec(ctx, ustr):
# """Get details of the user from ustr (username, aor or sip uri)"""
# udata = {}
# if ":" in ustr:
# uaor = ustr.split(":")[1]
# else:
# uaor = ustr
# if "@" in uaor:
# udata["username"] = uaor.split("@")[0]
# udata["domain"] = uaor.split("@")[1]
# else:
# udata["username"] = uaor.split("@")[0]
# try:
# udata["domain"] = ctx.gconfig.get("main", "domain")
# except configparser.NoOptionError:
# ctx.log("Default domain not set in config file")
# sys.exit()
# if udata["username"] is None:
# ctx.log("Failed to get username")
# sys.exit()
# if udata["domain"] is None:
# ctx.log("Failed to get domain")
# sys.exit()
# udata["username"] = udata["username"].encode("ascii", "ignore").decode()
# udata["domain"] = udata["domain"].encode("ascii", "ignore").decode()
# return udata
. Output only the next line. | "pwtext", |
Using the snippet: <|code_start|>
@click.group(
"dispatcher",
help="Manage dispatcher module (load balancer)",
short_help="Manage dispatcher module",
)
@pass_context
def cli(ctx):
pass
@cli.command("add", short_help="Add a new dispatcher destination")
<|code_end|>
, determine the next line of code. You have imports:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and context (class names, function names, or code) available:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
. Output only the next line. | @click.option("flags", "--flags", type=int, default=0, help="Flags value") |
Continue the code snippet: <|code_start|>
@click.group(
"dispatcher",
help="Manage dispatcher module (load balancer)",
short_help="Manage dispatcher module",
)
@pass_context
def cli(ctx):
pass
@cli.command("add", short_help="Add a new dispatcher destination")
<|code_end|>
. Use current file imports:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and context (classes, functions, or code) from other files:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
. Output only the next line. | @click.option("flags", "--flags", type=int, default=0, help="Flags value") |
Continue the code snippet: <|code_start|>
@click.group(
"dispatcher",
help="Manage dispatcher module (load balancer)",
short_help="Manage dispatcher module",
)
@pass_context
def cli(ctx):
pass
<|code_end|>
. Use current file imports:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and context (classes, functions, or code) from other files:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
. Output only the next line. | @cli.command("add", short_help="Add a new dispatcher destination") |
Predict the next line after this snippet: <|code_start|>
@click.command(
"pstrap",
help="Store runtime details and gdb full backtrace for all Kamailio processes to a file",
short_help="Get runtime details and gdb backtrace with ps",
)
@click.option(
"all",
"--all",
"-a",
is_flag=True,
help="Print all details in the trap file",
<|code_end|>
using the current file's imports:
import click
import os
import subprocess
import json
import datetime
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and any relevant context from other files:
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
. Output only the next line. | ) |
Predict the next line after this snippet: <|code_start|>
@click.group(
"mtree",
help="Manage mtree module (memory trees)",
short_help="Manage mtree module",
)
@pass_context
<|code_end|>
using the current file's imports:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and any relevant context from other files:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
. Output only the next line. | def cli(ctx): |
Based on the snippet: <|code_start|>
@click.group(
"mtree",
help="Manage mtree module (memory trees)",
short_help="Manage mtree module",
)
@pass_context
def cli(ctx):
<|code_end|>
, predict the immediate next line with the help of imports:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and context (classes, functions, sometimes code) from other files:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
. Output only the next line. | pass |
Given the code snippet: <|code_start|> short_help="Manage mtree module",
)
@pass_context
def cli(ctx):
pass
@cli.command("db-add", short_help="Add a new mtree record to database")
@click.option(
"tname",
"--tname",
default="",
help='Tree name to be stored in column tname (default: "")',
)
@click.option(
"coltprefix",
"--coltprefix",
default="tprefix",
help='Column name for prefix (default: "tprefix")',
)
@click.option(
"coltvalue",
"--coltvalue",
default="tvalue",
help='Column name for value (default: "tvalue")',
)
@click.argument("dbtname", metavar="<dbtname>")
@click.argument("tprefix", metavar="<tprefix>")
@click.argument("tvalue", metavar="<tvalue>")
@pass_context
<|code_end|>
, generate the next line using the imports in this file:
import click
from sqlalchemy import create_engine
from kamcli.ioutils import ioutils_dbres_print
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and context (functions, classes, or occasionally code) from other files:
# Path: kamcli/ioutils.py
# def ioutils_dbres_print(ctx, oformat, ostyle, res):
# """ print a database result using different formats and styles """
# if oformat is None:
# oformat = ctx.gconfig.get("db", "outformat", fallback=None)
# if oformat is None:
# if ioutils_tabulate_format is True:
# oformat = "table"
# else:
# oformat = "json"
#
# if oformat == "table":
# if ioutils_tabulate_format is False:
# ctx.log("Package tabulate is not installed")
# sys.exit()
#
# if oformat == "yaml":
# if ioutils_yaml_format is False:
# ctx.log("Package yaml is not installed")
# sys.exit()
#
# if ostyle is None:
# ostyle = ctx.gconfig.get("db", "outstyle", fallback="grid")
# if ostyle is None:
# ostyle = "grid"
#
# if oformat == "json":
# jdata = []
# for row in res:
# jdata.append(dict(row))
# print(json.dumps(jdata, indent=4))
# print()
# elif oformat == "yaml":
# ydata = []
# for row in res:
# ydata.append(dict(row))
# print(yaml.dump(ydata, indent=4))
# print()
# elif oformat == "dict":
# for row in res:
# print(dict(row))
# # pprint.pprint(dict(row), indent=4)
# print()
# elif oformat == "table":
# arows = res.fetchall()
# dcols = dict((k, k) for k in res.keys())
# drows = [dict(r) for r in arows]
# gstring = tabulate(drows, headers=dcols, tablefmt=ostyle)
# print(gstring)
# else:
# allrows = res.fetchall()
# print(allrows)
#
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
. Output only the next line. | def mtree_dbadd(ctx, tname, coltprefix, coltvalue, dbtname, tprefix, tvalue): |
Based on the snippet: <|code_start|>
@click.command("sipreq", short_help="Send a SIP request via RPC command")
@click.option(
"nowait", "--nowait", "-n", is_flag=True, help="Do not wait for response",
)
@click.option(
"method",
"--method",
"-m",
<|code_end|>
, predict the immediate next line with the help of imports:
import click
import json
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and context (classes, functions, sometimes code) from other files:
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
. Output only the next line. | default="OPTIONS", |
Given the following code snippet before the placeholder: <|code_start|>
@click.command("sipreq", short_help="Send a SIP request via RPC command")
@click.option(
"nowait", "--nowait", "-n", is_flag=True, help="Do not wait for response",
)
@click.option(
"method",
"--method",
"-m",
default="OPTIONS",
help='SIP method (default: "OPTIONS")',
)
<|code_end|>
, predict the next line using imports from the current file:
import click
import json
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and context including class names, function names, and sometimes code from other files:
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
. Output only the next line. | @click.option( |
Using the snippet: <|code_start|>
@click.command("moni", short_help="Monitor relevant statistics")
@click.option(
"norefresh",
"--no-refresh",
is_flag=True,
help="Do not refresh (execute once)",
<|code_end|>
, determine the next line of code. You have imports:
import os
import time
import click
import json
from kamcli.cli import pass_context
from kamcli.iorpc import command_ctl
and context (class names, function names, or code) available:
# Path: kamcli/cli.py
# COMMAND_ALIASES = {
# "subs": "subscriber",
# "rpc": "jsonrpc",
# "sht": "htable",
# }
# CONTEXT_SETTINGS = dict(
# auto_envvar_prefix="KAMCLI", help_option_names=["-h", "--help"]
# )
# def read_global_config(config_paths):
# def parse_user_spec(ctx, ustr):
# def __init__(self):
# def log(self, msg, *args):
# def vlog(self, msg, *args):
# def printf(self, msg, *args):
# def printnlf(self, msg, *args):
# def read_config(self):
# def gconfig(self):
# def list_commands(self, ctx):
# def get_command(self, ctx, name):
# def cli(ctx, debug, config, wdir, nodefaultconfigs, oformat):
# class Context(object):
# class KamCLI(click.MultiCommand):
#
# Path: kamcli/iorpc.py
# def command_ctl(ctx, cmd, params=[], cbexec={}):
# """Execute a rpc control command
#
# \b
# Parameters:
# - ctx: kamcli execution context
# - cmd: the string with rpc control command
# - params: an array with the parameters for the rpc control command
# - cbexec: dictionary with callaback function and its parameters
# to handle the response of the rpc control commands. If not
# provided, the response will be printed with the function
# command_ctl_response_print().
# The callback function has to be provided by 'func' key in
# the dictionary and its parameters by 'params' key.
# """
#
# if ctx.gconfig.get("jsonrpc", "transport") == "socket":
# command_jsonrpc_socket(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "srvaddr"),
# ctx.gconfig.get("jsonrpc", "rcvaddr"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
# else:
# command_jsonrpc_fifo(
# ctx,
# False,
# ctx.gconfig.get("jsonrpc", "path"),
# ctx.gconfig.get("jsonrpc", "rplnamebase"),
# ctx.gconfig.get("jsonrpc", "outformat"),
# command_ctl_name(cmd, "rpc"),
# params,
# cbexec,
# )
. Output only the next line. | ) |
Continue the code snippet: <|code_start|>
if len(sys.argv) < 2:
delay = 200
else:
delay = int(sys.argv[1])
if len(sys.argv) < 3:
sol = 'low'
else:
sol = sys.argv[2]
if sol != 'low' and sol != 'high':
print("You must provide either 'low' or 'high' as a possible solution.")
sys.exit()
#### Load chains ####
# Regular model
chains = np.load("../data/J0513_" + sol + "_chain.npy")
if chains.ndim == 4: chains = chains[0]
chains = chains[:,delay:,:]
n_chains, length, n_var = chains.shape
chains = chains.reshape((n_chains*length, n_var))
print(chains.shape)
# Flat star formation history
<|code_end|>
. Use current file imports:
import numpy as np
import sys
import matplotlib
import corner
import matplotlib.pyplot as plt
from matplotlib import font_manager
from dart_board import posterior, forward_pop_synth
from scipy import stats
and context (classes, functions, or code) from other files:
# Path: dart_board/posterior.py
# def ln_posterior(x, dart):
# def ln_likelihood(x, dart):
# def posterior_properties(x, output, dart):
# def get_error_from_kwargs(param, **kwargs):
# def calculate_ADAF_efficiency(Mdot, Mdot_edd, delta=0.1):
# def calculate_L_x(M1, mdot, k1):
# def calc_prob_from_mass_function(M1, M2, f_obs, f_err):
# def model_h(M1, M2, f):
# def func_integrand(f, f_obs, f_err, M1, M2):
# def calc_f(f_obs, f_err, M1, M2):
# def check_output(output, binary_type):
# def get_theta_proj(ra, dec, ra_b, dec_b):
# def get_dtheta_dalpha(alpha, delta, alpha_b, delta_b):
# def get_dtheta_ddelta(alpha, delta, alpha_b, delta_b):
# def get_domega_dalpha(alpha, delta, alpha_b, delta_b):
# def get_domega_ddelta(alpha, delta, alpha_b, delta_b):
# def get_J_coor(alpha, delta, alpha_b, delta_b):
# M1 = np.exp(ln_M1)
# M2 = np.exp(ln_M2)
# M1 = np.exp(ln_M1)
# M2 = np.exp(ln_M2)
# N = 100000
#
# Path: dart_board/forward_pop_synth.py
# def generate_population(dart, N, ra_in=None, dec_in=None):
# def get_v_kick(N, sigma=c.v_kick_sigma):
# def get_theta(N):
# def get_phi(N):
# def get_omega(N):
# def get_M1(N, alpha=c.alpha, M1_min=c.min_mass_M1, M1_max=c.max_mass_M1):
# def get_M2(M1, N, M2_min=c.min_mass_M2, M2_max=c.max_mass_M2):
# def get_a(N, a_min=c.min_a, a_max=c.max_a):
# def get_ecc(N):
# def get_t(N, min_time=c.min_t, max_time=c.max_t):
# def get_z(t_b, N, min_z=c.min_z, max_z=c.max_z):
# def get_new_ra_dec(ra, dec, theta_proj, pos_ang):
# M1 = dart.generate_M1(N)
# M2 = dart.generate_M2(M1, N)
# A = (alpha+1.0) / (np.power(M1_max, alpha+1.0) - np.power(M1_min, alpha+1.0))
# C = 1.0 / (np.log(a_max) - np.log(a_min))
# C = 1.0 / (np.log(max_z) - np.log(min_z))
. Output only the next line. | chains_flat = np.load("../data/J0513_flatsfh_" + sol + "_chain.npy") |
Here is a snippet: <|code_start|>
# # Load traditional population synthesis results
# trad_x_i = np.load("../data/J0513_trad_chain.npy")
# trad_likelihood = np.load("../data/J0513_trad_likelihood.npy")
# trad_likelihood = np.exp(trad_likelihood) # Since ln likelihoods are actually provided
# trad_derived = np.load("../data/J0513_trad_derived.npy")
#
# trad_x_i = trad_x_i.reshape((len(trad_likelihood), 13))
# trad_derived = trad_derived.reshape((len(trad_likelihood), 9))
# print(trad_x_i.shape)
# print(trad_derived.shape)
# Plot distribution of initial binary parameters
fig, ax = plt.subplots(2, 5, figsize=(8,4))
for k in range(2):
for j in range(5):
i = 5*k+j
# if i != 7 and i != 8:
# ax[k,j].hist(trad_x_i.T[i], range=plt_range[i], bins=20, normed=True, weights=trad_likelihood, color='C0', label="Traditional", alpha=0.3)
ax[k,j].hist(chains.T[i], range=plt_range[i], bins=20, normed=True, color='k', alpha=0.3, label='Full Model')
ax[k,j].hist(chains_flat.T[i], range=plt_range[i], bins=20, normed=True, histtype='step', color='C2', label='Flat SFH')
if i < 7:
<|code_end|>
. Write the next line using the current file imports:
import numpy as np
import sys
import matplotlib
import corner
import matplotlib.pyplot as plt
from matplotlib import font_manager
from dart_board import posterior, forward_pop_synth
from scipy import stats
and context from other files:
# Path: dart_board/posterior.py
# def ln_posterior(x, dart):
# def ln_likelihood(x, dart):
# def posterior_properties(x, output, dart):
# def get_error_from_kwargs(param, **kwargs):
# def calculate_ADAF_efficiency(Mdot, Mdot_edd, delta=0.1):
# def calculate_L_x(M1, mdot, k1):
# def calc_prob_from_mass_function(M1, M2, f_obs, f_err):
# def model_h(M1, M2, f):
# def func_integrand(f, f_obs, f_err, M1, M2):
# def calc_f(f_obs, f_err, M1, M2):
# def check_output(output, binary_type):
# def get_theta_proj(ra, dec, ra_b, dec_b):
# def get_dtheta_dalpha(alpha, delta, alpha_b, delta_b):
# def get_dtheta_ddelta(alpha, delta, alpha_b, delta_b):
# def get_domega_dalpha(alpha, delta, alpha_b, delta_b):
# def get_domega_ddelta(alpha, delta, alpha_b, delta_b):
# def get_J_coor(alpha, delta, alpha_b, delta_b):
# M1 = np.exp(ln_M1)
# M2 = np.exp(ln_M2)
# M1 = np.exp(ln_M1)
# M2 = np.exp(ln_M2)
# N = 100000
#
# Path: dart_board/forward_pop_synth.py
# def generate_population(dart, N, ra_in=None, dec_in=None):
# def get_v_kick(N, sigma=c.v_kick_sigma):
# def get_theta(N):
# def get_phi(N):
# def get_omega(N):
# def get_M1(N, alpha=c.alpha, M1_min=c.min_mass_M1, M1_max=c.max_mass_M1):
# def get_M2(M1, N, M2_min=c.min_mass_M2, M2_max=c.max_mass_M2):
# def get_a(N, a_min=c.min_a, a_max=c.max_a):
# def get_ecc(N):
# def get_t(N, min_time=c.min_t, max_time=c.max_t):
# def get_z(t_b, N, min_z=c.min_z, max_z=c.max_z):
# def get_new_ra_dec(ra, dec, theta_proj, pos_ang):
# M1 = dart.generate_M1(N)
# M2 = dart.generate_M2(M1, N)
# A = (alpha+1.0) / (np.power(M1_max, alpha+1.0) - np.power(M1_min, alpha+1.0))
# C = 1.0 / (np.log(a_max) - np.log(a_min))
# C = 1.0 / (np.log(max_z) - np.log(min_z))
, which may include functions, classes, or code. Output only the next line. | ax[k,j].hist(chains_nosfh.T[i], range=plt_range[i], bins=20, normed=True, histtype='step', color='C4', label='No SFH', linestyle='dashed', zorder=10) |
Given the code snippet: <|code_start|>matplotlib.use('Agg')
N_times = 500
# Colors
C0 = 'C0'
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.patches as mpatches
from .utils import A_to_P, P_to_A
and context (functions, classes, or occasionally code) from other files:
# Path: dart_board/utils.py
# def A_to_P(M1, M2, a):
# """
# Calculate the orbital period from the stellar masses and orbital separation.
#
# Args:
# M1, M2 : floats, masses of the two stars (Msun)
# a : float, orbital separation (Rsun)
#
# Returns:
# P : float, orbital period (days)
# """
#
# mu = c.G * (M1 + M2) * c.Msun_to_g
# n = np.sqrt(mu/(a**3 * c.Rsun_to_cm**3))
# P = 2.0*np.pi / n
#
# return P / c.day_to_sec
#
# def P_to_A(M1, M2, P):
# """
# Calculate the orbital separation from the stellar masses and orbital period.
#
# Args:
# M1, M2 : floats, masses of the two stars (Msun)
# P : float, orbital period (days)
#
# Returns:
# a : float, orbital separation (Rsun)
# """
#
# mu = c.G * (M1 + M2) * c.Msun_to_g
# n = 2.0*np.pi / P / c.day_to_sec
# a = np.power(mu/(n*n), 1.0/3.0) / c.Rsun_to_cm
#
# return a
. Output only the next line. | C1 = 'C1' |
Continue the code snippet: <|code_start|># Create a corner plot to show the posterior distribution
# fontProperties = {'family':'serif', 'serif':['Times New Roman'], 'weight':'normal', 'size':12}
# ticks_font = font_manager.FontProperties(family='Times New Roman', style='normal', \
# weight='normal', stretch='normal', size=10)
# plt.rc('font', **fontProperties)
# Corner plot
labels = [r"$M_{\rm 1, i}\ (M_{\odot})$",
r"$M_{\rm 2, i}\ (M_{\odot})$",
r"log $a_{\rm i}\ (R_{\odot})$",
r"$e_{\rm i}$",
r"$v_{\rm k, i}\ ({\rm km}\ {\rm s}^{-1})$",
r"$\theta_{\rm k}\ ({\rm rad.})$",
r"$\phi_{\rm k}\ ({\rm rad.})$",
r"$t_{\rm i}\ ({\rm Myr})$"]
# plt_range = ([13.9,13.95], [12,13], [0,4000], [0.7,1], [0,750], [0.0,np.pi], [0.0,np.pi], [15,22])
# plt_range = ([0,25], [0,20], [0,4000], [0.0,1], [0,750], [0.0,np.pi], [0.0,np.pi], [10,60])
plt_range = ([0,40], [0,30], [1,4], [0.0,1], [0,750], [0.0,np.pi], [0.0,np.pi], [0,60])
# Load traditional population synthesis results
trad_x_i = np.load("../data/HMXB_trad_chain.npy")
length, ndim = trad_x_i.shape
trad_likelihood = np.load("../data/HMXB_trad_lnprobability.npy")
trad_derived = np.load("../data/HMXB_trad_derived.npy")
length, ndim = trad_x_i.shape
<|code_end|>
. Use current file imports:
import numpy as np
import pickle
import matplotlib
import corner
import matplotlib.pyplot as plt
from matplotlib import font_manager
from dart_board import posterior
from dart_board import posterior
from scipy import stats
and context (classes, functions, or code) from other files:
# Path: dart_board/posterior.py
# def ln_posterior(x, dart):
# def ln_likelihood(x, dart):
# def posterior_properties(x, output, dart):
# def get_error_from_kwargs(param, **kwargs):
# def calculate_ADAF_efficiency(Mdot, Mdot_edd, delta=0.1):
# def calculate_L_x(M1, mdot, k1):
# def calc_prob_from_mass_function(M1, M2, f_obs, f_err):
# def model_h(M1, M2, f):
# def func_integrand(f, f_obs, f_err, M1, M2):
# def calc_f(f_obs, f_err, M1, M2):
# def check_output(output, binary_type):
# def get_theta_proj(ra, dec, ra_b, dec_b):
# def get_dtheta_dalpha(alpha, delta, alpha_b, delta_b):
# def get_dtheta_ddelta(alpha, delta, alpha_b, delta_b):
# def get_domega_dalpha(alpha, delta, alpha_b, delta_b):
# def get_domega_ddelta(alpha, delta, alpha_b, delta_b):
# def get_J_coor(alpha, delta, alpha_b, delta_b):
# M1 = np.exp(ln_M1)
# M2 = np.exp(ln_M2)
# M1 = np.exp(ln_M1)
# M2 = np.exp(ln_M2)
# N = 100000
#
# Path: dart_board/posterior.py
# def ln_posterior(x, dart):
# def ln_likelihood(x, dart):
# def posterior_properties(x, output, dart):
# def get_error_from_kwargs(param, **kwargs):
# def calculate_ADAF_efficiency(Mdot, Mdot_edd, delta=0.1):
# def calculate_L_x(M1, mdot, k1):
# def calc_prob_from_mass_function(M1, M2, f_obs, f_err):
# def model_h(M1, M2, f):
# def func_integrand(f, f_obs, f_err, M1, M2):
# def calc_f(f_obs, f_err, M1, M2):
# def check_output(output, binary_type):
# def get_theta_proj(ra, dec, ra_b, dec_b):
# def get_dtheta_dalpha(alpha, delta, alpha_b, delta_b):
# def get_dtheta_ddelta(alpha, delta, alpha_b, delta_b):
# def get_domega_dalpha(alpha, delta, alpha_b, delta_b):
# def get_domega_ddelta(alpha, delta, alpha_b, delta_b):
# def get_J_coor(alpha, delta, alpha_b, delta_b):
# M1 = np.exp(ln_M1)
# M2 = np.exp(ln_M2)
# M1 = np.exp(ln_M1)
# M2 = np.exp(ln_M2)
# N = 100000
. Output only the next line. | trad_x_i = trad_x_i[int(length*frac):,:] |
Continue the code snippet: <|code_start|> 'page': 1,
})
warnings = service.collect_response_warnings()
return {
'status': 'OK' if len(warnings) == 0 else 'WR',
'warnings': warnings,
'response': response
}
def _test_licensing_component(service, test_config, context):
resource_id = test_config.get('ac_resource_id_for_licensing')
service.clear_response_warnings()
response = service.license(context=context, acid=resource_id)
warnings = service.collect_response_warnings()
return {
'status': 'OK' if len(warnings) == 0 else 'WR',
'warnings': warnings,
'response': response
}
def _test_download_component(service, test_config, context):
resource_id = test_config.get('ac_resource_id_for_download')
service.clear_response_warnings()
response = service.download(context=context, acid=resource_id)
warnings = service.collect_response_warnings()
return {
'status': 'OK' if len(warnings) == 0 else 'WR',
'warnings': warnings,
<|code_end|>
. Use current file imports:
from django.core.management.base import BaseCommand
from django.template.loader import render_to_string
from accounts.models import Account
from services.acservice.constants import *
from ac_mediator.exceptions import *
from services.mgmt import get_service_by_name
import configparser
import os
import logging
import json
and context (classes, functions, or code) from other files:
# Path: accounts/models.py
# class Account(AbstractUser):
# """
# This is our custom 'User' model.
# """
#
# is_developer = models.BooleanField(default=False, blank=False)
# accepted_tos = models.BooleanField(default=False, blank=False)
# # Add more custom fields here like avatar...
#
# def send_activation_email(self):
# tvars = {
# 'user': self,
# 'username': self.username,
# 'hash': create_hash(self.id)
# }
# send_mail(self.email, subject='Activate your Audio Commons user account',
# template='emails/account_activation.txt', context=tvars)
#
# class Meta:
# verbose_name = _('account')
# verbose_name_plural = _('accounts')
#
# Path: services/mgmt.py
# def get_service_by_name(service_name):
# for service in available_services:
# if service.name == service_name:
# return service
# raise ACServiceDoesNotExist('Service with name {0} does not exist'.format(service_name))
. Output only the next line. | 'response': response |
Using the snippet: <|code_start|>
logger = logging.getLogger('management')
def _test_search_component(service, test_config, context):
query = test_config.get('text_search_query', 'dogs')
service.clear_response_warnings()
response = service.text_search(
context=context, q=query, f=None, s=None, common_search_params={
'fields': MINIMUM_RESOURCE_DESCRIPTION_FIELDS,
'size': 10,
'page': 1,
})
warnings = service.collect_response_warnings()
return {
'status': 'OK' if len(warnings) == 0 else 'WR',
'warnings': warnings,
'response': response
}
def _test_licensing_component(service, test_config, context):
resource_id = test_config.get('ac_resource_id_for_licensing')
<|code_end|>
, determine the next line of code. You have imports:
from django.core.management.base import BaseCommand
from django.template.loader import render_to_string
from accounts.models import Account
from services.acservice.constants import *
from ac_mediator.exceptions import *
from services.mgmt import get_service_by_name
import configparser
import os
import logging
import json
and context (class names, function names, or code) available:
# Path: accounts/models.py
# class Account(AbstractUser):
# """
# This is our custom 'User' model.
# """
#
# is_developer = models.BooleanField(default=False, blank=False)
# accepted_tos = models.BooleanField(default=False, blank=False)
# # Add more custom fields here like avatar...
#
# def send_activation_email(self):
# tvars = {
# 'user': self,
# 'username': self.username,
# 'hash': create_hash(self.id)
# }
# send_mail(self.email, subject='Activate your Audio Commons user account',
# template='emails/account_activation.txt', context=tvars)
#
# class Meta:
# verbose_name = _('account')
# verbose_name_plural = _('accounts')
#
# Path: services/mgmt.py
# def get_service_by_name(service_name):
# for service in available_services:
# if service.name == service_name:
# return service
# raise ACServiceDoesNotExist('Service with name {0} does not exist'.format(service_name))
. Output only the next line. | service.clear_response_warnings() |
Using the snippet: <|code_start|>
urlpatterns = [
url(r'^clients/$', dev_views.ApplicationList.as_view(),
name="developers-app-list"),
url(r'^clients/register/$', dev_views.ApplicationRegistration.as_view(),
name="developers-app-register"),
url(r'^clients/(?P<pk>\d+)/$', dev_views.ApplicationDetail.as_view(),
<|code_end|>
, determine the next line of code. You have imports:
from django.conf.urls import url
from developers import views as dev_views
and context (class names, function names, or code) available:
# Path: developers/views.py
# class ApplicationRegistration(ProviderApplicationRegistration):
# class ApplicationDetail(ProviderApplicationDetail):
# class ApplicationList(ProviderApplicationList):
# class ApplicationDelete(ProviderApplicationDelete):
# class ApplicationUpdate(ProviderApplicationUpdate):
# def get_form_class(self):
# def get_form_class(self):
# def application_monitor(request, pk):
# def get_application_monitor_data(request, pk):
# N_FAKE_POINTS = 1000
# DAYS_SPAN = 60
. Output only the next line. | name="developers-app-detail"), |
Given the code snippet: <|code_start|>setattr(Field, 'is_checkbox', lambda self: isinstance(self.widget, forms.CheckboxInput)) # Used in the template
class ApiClientForm(ModelForm):
# We define a number of predefined combinations of client type and authorization grant type
# from which developers can choose when registering a new API client
PUBLIC_IMPLICIT = 'public_implicit'
<|code_end|>
, generate the next line using the imports in this file:
from django import forms
from django.forms import ModelForm
from django.forms.fields import Field
from django.utils.text import mark_safe
from django.forms.widgets import HiddenInput
from api.models import ApiClient
and context (functions, classes, or occasionally code) from other files:
# Path: api/models.py
# class ApiClient(AbstractApplication):
# """
# This is our custom 'Application' model for Oauth authentication.
# """
#
# agree_tos = models.BooleanField(default=False)
# password_grant_is_allowed = models.BooleanField(default=False) # Enable password grant in OAuth2 authentication
# created = models.DateTimeField(auto_now_add=True)
# # Add more custom fields here like description, logo, preferred services...
#
# def get_absolute_url(self):
# return reverse('developers-app-detail', args=[self.id])
#
# def clean(self):
# """
# The AbstractApplication model includes a clean method that raises a ValidationError
# if the redirect_uri is empty and is required by the authorization_grant_type. We have
# implemented a custom version of this check (with a custom message) in api.forms.ApiClientForm
# therefore we don't need model's clean method to do anything.
# """
# pass
. Output only the next line. | PUBLIC_PASSWORD = 'public_password' |
Based on the snippet: <|code_start|>
@override_settings(EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend')
class AccountRegistrationTestCase(TestCase):
def test_user_registration(self):
# Register new account
post_data = {
'password1': '123456',
'password2': '123456',
'accepted_tos': 'on',
'username': 'test_username',
'email1': 'example@email.com',
'email2': 'example@email.com',
}
resp = self.client.post(reverse('registration'), data=post_data)
self.assertEquals(resp.status_code, 200)
# Check that a user object has been created with that user name but it is still inactive
account = Account.objects.get(username='test_username')
self.assertEquals(account.is_active, False)
# Check that an email was sent
self.assertEquals(len(mail.outbox), 1)
# Try to activate user with wrong username
resp = self.client.get(reverse('accounts-activate', args=['fake_username', 'fake_hash']))
self.assertEquals(resp.status_code, 200)
<|code_end|>
, predict the immediate next line with the help of imports:
from django.test import TestCase, override_settings
from accounts.models import Account
from django.core.urlresolvers import reverse
from django.core import mail
from django.conf import settings
and context (classes, functions, sometimes code) from other files:
# Path: accounts/models.py
# class Account(AbstractUser):
# """
# This is our custom 'User' model.
# """
#
# is_developer = models.BooleanField(default=False, blank=False)
# accepted_tos = models.BooleanField(default=False, blank=False)
# # Add more custom fields here like avatar...
#
# def send_activation_email(self):
# tvars = {
# 'user': self,
# 'username': self.username,
# 'hash': create_hash(self.id)
# }
# send_mail(self.email, subject='Activate your Audio Commons user account',
# template='emails/account_activation.txt', context=tvars)
#
# class Meta:
# verbose_name = _('account')
# verbose_name_plural = _('accounts')
. Output only the next line. | self.assertEquals('the user you are trying to activate does not exist' in resp.content.decode("utf-8"), True) |
Next line prediction: <|code_start|>
# Auth urls
# https://stackoverflow.com/questions/6930982/how-to-use-a-variable-inside-a-regular-expression
# domainPrefix = "authenticate/"
domainPrefix = ""
urlpatterns = [
# Home
url(r'^%s$' % domainPrefix, home, name='home'),
url(r'^%sabout/$' % domainPrefix, views.about, name='about'),
# Link services
url(r'^%slink_services/$' % domainPrefix, views.link_services, name='link_services'),
url(r'^%slink_service/(?P<service_id>[^\/]+)/$' % domainPrefix, views.link_service_callback, name='link_service_callback'),
url(r'^%slink_service_get_token/(?P<service_id>[^\/]+)/$' % domainPrefix, views.link_service_get_token, name='link_service_get_token'),
url(r'^%sunlink_service/(?P<service_id>[^\/]+)/$' % domainPrefix, views.unlink_service, name='unlink_service'),
# Manage given api credentials
url(r'^%sauthorized_clients/$' % domainPrefix, AuthorizedTokensListView.as_view(
<|code_end|>
. Use current file imports:
(from django.conf.urls import url
from django.core.urlresolvers import reverse_lazy
from accounts import views
from oauth2_provider.views.token import AuthorizedTokenDeleteView, AuthorizedTokensListView
from accounts.views import home)
and context including class names, function names, or small code snippets from other files:
# Path: accounts/views.py
# def registration(request):
# def activate_account(request, username, uid_hash):
# def resend_activation_emmil(request):
# def home(request):
# def about(request):
# def link_services(request):
# def link_service_callback(request, service_id):
# def store_service_credentials_helper(credentials, account, service_id):
# def link_service_get_token(request, service_id):
# def unlink_service(request, service_id):
#
# Path: accounts/views.py
# @login_required
# def home(request):
# return render(request, 'accounts/home.html')
. Output only the next line. | template_name='accounts/authorized-tokens.html', |
Continue the code snippet: <|code_start|>
# Auth urls
# https://stackoverflow.com/questions/6930982/how-to-use-a-variable-inside-a-regular-expression
# domainPrefix = "authenticate/"
domainPrefix = ""
urlpatterns = [
# Home
url(r'^%s$' % domainPrefix, home, name='home'),
url(r'^%sabout/$' % domainPrefix, views.about, name='about'),
# Link services
url(r'^%slink_services/$' % domainPrefix, views.link_services, name='link_services'),
url(r'^%slink_service/(?P<service_id>[^\/]+)/$' % domainPrefix, views.link_service_callback, name='link_service_callback'),
url(r'^%slink_service_get_token/(?P<service_id>[^\/]+)/$' % domainPrefix, views.link_service_get_token, name='link_service_get_token'),
url(r'^%sunlink_service/(?P<service_id>[^\/]+)/$' % domainPrefix, views.unlink_service, name='unlink_service'),
# Manage given api credentials
<|code_end|>
. Use current file imports:
from django.conf.urls import url
from django.core.urlresolvers import reverse_lazy
from accounts import views
from oauth2_provider.views.token import AuthorizedTokenDeleteView, AuthorizedTokensListView
from accounts.views import home
and context (classes, functions, or code) from other files:
# Path: accounts/views.py
# def registration(request):
# def activate_account(request, username, uid_hash):
# def resend_activation_emmil(request):
# def home(request):
# def about(request):
# def link_services(request):
# def link_service_callback(request, service_id):
# def store_service_credentials_helper(credentials, account, service_id):
# def link_service_get_token(request, service_id):
# def unlink_service(request, service_id):
#
# Path: accounts/views.py
# @login_required
# def home(request):
# return render(request, 'accounts/home.html')
. Output only the next line. | url(r'^%sauthorized_clients/$' % domainPrefix, AuthorizedTokensListView.as_view( |
Here is a snippet: <|code_start|>
# Auth urls
# https://stackoverflow.com/questions/6930982/how-to-use-a-variable-inside-a-regular-expression
# domainPrefix = "authenticate/"
domainPrefix = ""
urlpatterns = [
url(r'^%scrash/$' % domainPrefix, crash_me, name='crash_me'),
url(r'^%sregister/$' % domainPrefix, registration, name='registration'),
url(r'^%sactivate/(?P<username>[^\/]+)/(?P<uid_hash>[^\/]+)/.*$' % domainPrefix, activate_account, name="accounts-activate"),
url(r'^%sreactivate/$' % domainPrefix, resend_activation_emmil, name="accounts-resend-activation"),
url(r'^%slogin/$' % domainPrefix, auth_views.login, {'template_name': 'accounts/login.html'}, name='login'),
<|code_end|>
. Write the next line using the current file imports:
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from accounts.views import registration, activate_account, resend_activation_emmil
from ac_mediator.views import monitor, crash_me
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
and context from other files:
# Path: accounts/views.py
# def registration(request):
# if request.user.is_authenticated():
# return HttpResponseRedirect(reverse('home'))
# if request.method == 'POST':
# form = RegistrationForm(request.POST)
# if form.is_valid():
# account = form.save()
# account.is_active = False
# account.save()
# account.send_activation_email()
# return render(request, 'accounts/registration.html', {'form': None})
# else:
# form = RegistrationForm()
# return render(request, 'accounts/registration.html', {'form': form})
#
# def activate_account(request, username, uid_hash):
# if request.user.is_authenticated:
# return HttpResponseRedirect(reverse('home'))
#
# try:
# account = Account.objects.get(username__iexact=username)
# except Account.DoesNotExist:
# return render(request, 'accounts/activate.html', {'user_does_not_exist': True})
#
# new_hash = create_hash(account.id)
# if new_hash != uid_hash:
# return render(request, 'accounts/activate.html', {'decode_error': True})
#
# account.is_active = True
# account.save()
# return render(request, 'accounts/activate.html', {'all_ok': True})
#
# def resend_activation_emmil(request):
# if request.user.is_authenticated:
# return HttpResponseRedirect(reverse('home'))
#
# if request.method == 'POST':
# form = ReactivationForm(request.POST)
# if form.is_valid():
# account = form.cleaned_data['account']
# account.send_activation_email()
# return render(request, 'accounts/resend_activation.html', {'form': None})
# else:
# form = ReactivationForm()
# return render(request, 'accounts/resend_activation.html', {'form': form})
#
# Path: ac_mediator/views.py
# @login_required
# def monitor(request):
# flower_auth = os.getenv('FLOWER_BASIC_AUTH', ':').split(':')
# redmon_auth = os.getenv('FLOWER_BASIC_AUTH', ':').split(':')
# return render(request, 'admin/monitor.html', {
# 'flower_auth': flower_auth,
# 'redmon_auth': redmon_auth,
# })
#
# @login_required
# @user_passes_test(lambda u: u.is_staff, login_url='/')
# def crash_me(request):
# raise Exception('Everything is under control')
, which may include functions, classes, or code. Output only the next line. | url(r'^%slogout/$' % domainPrefix, auth_views.logout, {'next_page': settings.LOGOUT_URL}, name='logout'), |
Based on the snippet: <|code_start|> template_name='accounts/password_reset_form.html',
subject_template_name='emails/password_reset_subject.txt',
email_template_name='emails/password_reset.txt',
), name='password_reset'),
url(r'^%spassword_reset/done/$' % domainPrefix, auth_views.password_reset_done, dict(
template_name='accounts/password_reset_done.html'
), name='password_reset_done'),
url(r'^%sreset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$' % domainPrefix,
auth_views.password_reset_confirm, dict(
template_name='accounts/password_reset_confirm.html'
), name='password_reset_confirm'),
url(r'^%sreset/done/$' % domainPrefix, auth_views.password_reset_complete, dict(
template_name='accounts/password_reset_complete.html'
), name='password_reset_complete'),
# Accounts
url(r'^%s' % domainPrefix, include('accounts.urls')),
# Developers
url(r'^developers/', include('developers.urls')),
# Api
url(r'^%sapi/' % domainPrefix, include('api.urls')),
# Admin
url(r'^admin/monitor/$', monitor, name="admin-monitor"),
url(r'^admin/', admin.site.urls),
# Documentation
url(r'^docs/', include('docs.urls')),
<|code_end|>
, predict the immediate next line with the help of imports:
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from accounts.views import registration, activate_account, resend_activation_emmil
from ac_mediator.views import monitor, crash_me
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
and context (classes, functions, sometimes code) from other files:
# Path: accounts/views.py
# def registration(request):
# if request.user.is_authenticated():
# return HttpResponseRedirect(reverse('home'))
# if request.method == 'POST':
# form = RegistrationForm(request.POST)
# if form.is_valid():
# account = form.save()
# account.is_active = False
# account.save()
# account.send_activation_email()
# return render(request, 'accounts/registration.html', {'form': None})
# else:
# form = RegistrationForm()
# return render(request, 'accounts/registration.html', {'form': form})
#
# def activate_account(request, username, uid_hash):
# if request.user.is_authenticated:
# return HttpResponseRedirect(reverse('home'))
#
# try:
# account = Account.objects.get(username__iexact=username)
# except Account.DoesNotExist:
# return render(request, 'accounts/activate.html', {'user_does_not_exist': True})
#
# new_hash = create_hash(account.id)
# if new_hash != uid_hash:
# return render(request, 'accounts/activate.html', {'decode_error': True})
#
# account.is_active = True
# account.save()
# return render(request, 'accounts/activate.html', {'all_ok': True})
#
# def resend_activation_emmil(request):
# if request.user.is_authenticated:
# return HttpResponseRedirect(reverse('home'))
#
# if request.method == 'POST':
# form = ReactivationForm(request.POST)
# if form.is_valid():
# account = form.cleaned_data['account']
# account.send_activation_email()
# return render(request, 'accounts/resend_activation.html', {'form': None})
# else:
# form = ReactivationForm()
# return render(request, 'accounts/resend_activation.html', {'form': form})
#
# Path: ac_mediator/views.py
# @login_required
# def monitor(request):
# flower_auth = os.getenv('FLOWER_BASIC_AUTH', ':').split(':')
# redmon_auth = os.getenv('FLOWER_BASIC_AUTH', ':').split(':')
# return render(request, 'admin/monitor.html', {
# 'flower_auth': flower_auth,
# 'redmon_auth': redmon_auth,
# })
#
# @login_required
# @user_passes_test(lambda u: u.is_staff, login_url='/')
# def crash_me(request):
# raise Exception('Everything is under control')
. Output only the next line. | ] |
Given the code snippet: <|code_start|>
# Auth urls
# https://stackoverflow.com/questions/6930982/how-to-use-a-variable-inside-a-regular-expression
# domainPrefix = "authenticate/"
domainPrefix = ""
urlpatterns = [
url(r'^%scrash/$' % domainPrefix, crash_me, name='crash_me'),
url(r'^%sregister/$' % domainPrefix, registration, name='registration'),
url(r'^%sactivate/(?P<username>[^\/]+)/(?P<uid_hash>[^\/]+)/.*$' % domainPrefix, activate_account, name="accounts-activate"),
url(r'^%sreactivate/$' % domainPrefix, resend_activation_emmil, name="accounts-resend-activation"),
url(r'^%slogin/$' % domainPrefix, auth_views.login, {'template_name': 'accounts/login.html'}, name='login'),
url(r'^%slogout/$' % domainPrefix, auth_views.logout, {'next_page': settings.LOGOUT_URL}, name='logout'),
url(r'^%spassword_reset/$' % domainPrefix, auth_views.password_reset, dict(
template_name='accounts/password_reset_form.html',
subject_template_name='emails/password_reset_subject.txt',
email_template_name='emails/password_reset.txt',
), name='password_reset'),
url(r'^%spassword_reset/done/$' % domainPrefix, auth_views.password_reset_done, dict(
template_name='accounts/password_reset_done.html'
), name='password_reset_done'),
url(r'^%sreset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$' % domainPrefix,
auth_views.password_reset_confirm, dict(
template_name='accounts/password_reset_confirm.html'
<|code_end|>
, generate the next line using the imports in this file:
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from accounts.views import registration, activate_account, resend_activation_emmil
from ac_mediator.views import monitor, crash_me
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
and context (functions, classes, or occasionally code) from other files:
# Path: accounts/views.py
# def registration(request):
# if request.user.is_authenticated():
# return HttpResponseRedirect(reverse('home'))
# if request.method == 'POST':
# form = RegistrationForm(request.POST)
# if form.is_valid():
# account = form.save()
# account.is_active = False
# account.save()
# account.send_activation_email()
# return render(request, 'accounts/registration.html', {'form': None})
# else:
# form = RegistrationForm()
# return render(request, 'accounts/registration.html', {'form': form})
#
# def activate_account(request, username, uid_hash):
# if request.user.is_authenticated:
# return HttpResponseRedirect(reverse('home'))
#
# try:
# account = Account.objects.get(username__iexact=username)
# except Account.DoesNotExist:
# return render(request, 'accounts/activate.html', {'user_does_not_exist': True})
#
# new_hash = create_hash(account.id)
# if new_hash != uid_hash:
# return render(request, 'accounts/activate.html', {'decode_error': True})
#
# account.is_active = True
# account.save()
# return render(request, 'accounts/activate.html', {'all_ok': True})
#
# def resend_activation_emmil(request):
# if request.user.is_authenticated:
# return HttpResponseRedirect(reverse('home'))
#
# if request.method == 'POST':
# form = ReactivationForm(request.POST)
# if form.is_valid():
# account = form.cleaned_data['account']
# account.send_activation_email()
# return render(request, 'accounts/resend_activation.html', {'form': None})
# else:
# form = ReactivationForm()
# return render(request, 'accounts/resend_activation.html', {'form': form})
#
# Path: ac_mediator/views.py
# @login_required
# def monitor(request):
# flower_auth = os.getenv('FLOWER_BASIC_AUTH', ':').split(':')
# redmon_auth = os.getenv('FLOWER_BASIC_AUTH', ':').split(':')
# return render(request, 'admin/monitor.html', {
# 'flower_auth': flower_auth,
# 'redmon_auth': redmon_auth,
# })
#
# @login_required
# @user_passes_test(lambda u: u.is_staff, login_url='/')
# def crash_me(request):
# raise Exception('Everything is under control')
. Output only the next line. | ), name='password_reset_confirm'), |
Next line prediction: <|code_start|># domainPrefix = "authenticate/"
domainPrefix = ""
urlpatterns = [
url(r'^%scrash/$' % domainPrefix, crash_me, name='crash_me'),
url(r'^%sregister/$' % domainPrefix, registration, name='registration'),
url(r'^%sactivate/(?P<username>[^\/]+)/(?P<uid_hash>[^\/]+)/.*$' % domainPrefix, activate_account, name="accounts-activate"),
url(r'^%sreactivate/$' % domainPrefix, resend_activation_emmil, name="accounts-resend-activation"),
url(r'^%slogin/$' % domainPrefix, auth_views.login, {'template_name': 'accounts/login.html'}, name='login'),
url(r'^%slogout/$' % domainPrefix, auth_views.logout, {'next_page': settings.LOGOUT_URL}, name='logout'),
url(r'^%spassword_reset/$' % domainPrefix, auth_views.password_reset, dict(
template_name='accounts/password_reset_form.html',
subject_template_name='emails/password_reset_subject.txt',
email_template_name='emails/password_reset.txt',
), name='password_reset'),
url(r'^%spassword_reset/done/$' % domainPrefix, auth_views.password_reset_done, dict(
template_name='accounts/password_reset_done.html'
), name='password_reset_done'),
url(r'^%sreset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$' % domainPrefix,
auth_views.password_reset_confirm, dict(
template_name='accounts/password_reset_confirm.html'
), name='password_reset_confirm'),
url(r'^%sreset/done/$' % domainPrefix, auth_views.password_reset_complete, dict(
template_name='accounts/password_reset_complete.html'
), name='password_reset_complete'),
# Accounts
url(r'^%s' % domainPrefix, include('accounts.urls')),
# Developers
<|code_end|>
. Use current file imports:
(from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from accounts.views import registration, activate_account, resend_activation_emmil
from ac_mediator.views import monitor, crash_me
from django.contrib.staticfiles.urls import staticfiles_urlpatterns)
and context including class names, function names, or small code snippets from other files:
# Path: accounts/views.py
# def registration(request):
# if request.user.is_authenticated():
# return HttpResponseRedirect(reverse('home'))
# if request.method == 'POST':
# form = RegistrationForm(request.POST)
# if form.is_valid():
# account = form.save()
# account.is_active = False
# account.save()
# account.send_activation_email()
# return render(request, 'accounts/registration.html', {'form': None})
# else:
# form = RegistrationForm()
# return render(request, 'accounts/registration.html', {'form': form})
#
# def activate_account(request, username, uid_hash):
# if request.user.is_authenticated:
# return HttpResponseRedirect(reverse('home'))
#
# try:
# account = Account.objects.get(username__iexact=username)
# except Account.DoesNotExist:
# return render(request, 'accounts/activate.html', {'user_does_not_exist': True})
#
# new_hash = create_hash(account.id)
# if new_hash != uid_hash:
# return render(request, 'accounts/activate.html', {'decode_error': True})
#
# account.is_active = True
# account.save()
# return render(request, 'accounts/activate.html', {'all_ok': True})
#
# def resend_activation_emmil(request):
# if request.user.is_authenticated:
# return HttpResponseRedirect(reverse('home'))
#
# if request.method == 'POST':
# form = ReactivationForm(request.POST)
# if form.is_valid():
# account = form.cleaned_data['account']
# account.send_activation_email()
# return render(request, 'accounts/resend_activation.html', {'form': None})
# else:
# form = ReactivationForm()
# return render(request, 'accounts/resend_activation.html', {'form': form})
#
# Path: ac_mediator/views.py
# @login_required
# def monitor(request):
# flower_auth = os.getenv('FLOWER_BASIC_AUTH', ':').split(':')
# redmon_auth = os.getenv('FLOWER_BASIC_AUTH', ':').split(':')
# return render(request, 'admin/monitor.html', {
# 'flower_auth': flower_auth,
# 'redmon_auth': redmon_auth,
# })
#
# @login_required
# @user_passes_test(lambda u: u.is_staff, login_url='/')
# def crash_me(request):
# raise Exception('Everything is under control')
. Output only the next line. | url(r'^developers/', include('developers.urls')), |
Given snippet: <|code_start|>
urlpatterns = [
url(r'^v1/services/$', views.services, name='api-services'),
url(r'^v1/collect/$', views.collect_response, name='api-collect'),
url(r'^v1/search/text/$', views.text_search, name='api-text-search'),
url(r'^v1/license/$', views.licensing, name='api-licensing'),
url(r'^v1/download/$', views.download, name='api-download'),
url(r'^v1/me/$', views.me, name='api-me'),
# Oauth2 urls
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.conf.urls import include, url
from api import views
and context:
# Path: api/views.py
# def get_request_context(request):
# def parse_request_distributor_query_params(request):
# def parse_common_search_query_params(request):
# def get_service_name_from_acid(acid):
# def invalid_url(request):
# def me(request):
# def collect_response(request):
# def services(request):
# def text_search(request):
# def licensing(request):
# def download(request):
which might include code, classes, or functions. Output only the next line. | url(r'^o/', include('api.oauth2_urls', namespace='oauth2_provider')), |
Using the snippet: <|code_start|>logger = logging.getLogger('management')
class Command(BaseCommand):
help = 'Renew access tokens to 3rd party services whose refresh tokens are about to expire. ' \
'Use as `python manage.py renew_access_tokens`.'
def add_arguments(self, parser):
pass
<|code_end|>
, determine the next line of code. You have imports:
from django.core.management.base import BaseCommand
from accounts.models import ServiceCredentials
from services.mgmt import get_service_by_id
from ac_mediator.exceptions import ACServiceDoesNotExist
import logging
and context (class names, function names, or code) available:
# Path: accounts/models.py
# class ServiceCredentials(models.Model):
# """
# This model is intended to store the credentials returned by a service after
# an Audio Commons account is linked with it. Credentials are intentionally
# stored in a JSONField to accommodate different types of credentials returned
# by services. The ACServiceBase authentication methods will be in charge of
# interpreting the contests of the 'credentials' field.
# """
#
# account = models.ForeignKey(Account, related_name='service_credentials')
# service_id = models.CharField(max_length=64)
# credentials = JSONField(null=False, default={})
# created = models.DateTimeField(auto_now_add=True)
# modified = models.DateTimeField(auto_now=True)
#
# class Meta:
# verbose_name = _('service credentials')
# verbose_name_plural = _('service credentials')
# unique_together = (('account', 'service_id'),)
#
# def __str__(self):
# return 'ServiceCredentials for {0} and {1}'.format(self.account.username, self.service_id)
#
# Path: services/mgmt.py
# def get_service_by_id(service_id):
# for service in available_services:
# if service.id == service_id:
# return service
# raise ACServiceDoesNotExist('Service with id {0} does not exist'.format(service_id))
#
# Path: ac_mediator/exceptions.py
# class ACServiceDoesNotExist(ACException):
# pass
. Output only the next line. | def handle(self, *args, **options): |
Given the code snippet: <|code_start|>logger = logging.getLogger('management')
class Command(BaseCommand):
help = 'Renew access tokens to 3rd party services whose refresh tokens are about to expire. ' \
'Use as `python manage.py renew_access_tokens`.'
def add_arguments(self, parser):
<|code_end|>
, generate the next line using the imports in this file:
from django.core.management.base import BaseCommand
from accounts.models import ServiceCredentials
from services.mgmt import get_service_by_id
from ac_mediator.exceptions import ACServiceDoesNotExist
import logging
and context (functions, classes, or occasionally code) from other files:
# Path: accounts/models.py
# class ServiceCredentials(models.Model):
# """
# This model is intended to store the credentials returned by a service after
# an Audio Commons account is linked with it. Credentials are intentionally
# stored in a JSONField to accommodate different types of credentials returned
# by services. The ACServiceBase authentication methods will be in charge of
# interpreting the contests of the 'credentials' field.
# """
#
# account = models.ForeignKey(Account, related_name='service_credentials')
# service_id = models.CharField(max_length=64)
# credentials = JSONField(null=False, default={})
# created = models.DateTimeField(auto_now_add=True)
# modified = models.DateTimeField(auto_now=True)
#
# class Meta:
# verbose_name = _('service credentials')
# verbose_name_plural = _('service credentials')
# unique_together = (('account', 'service_id'),)
#
# def __str__(self):
# return 'ServiceCredentials for {0} and {1}'.format(self.account.username, self.service_id)
#
# Path: services/mgmt.py
# def get_service_by_id(service_id):
# for service in available_services:
# if service.id == service_id:
# return service
# raise ACServiceDoesNotExist('Service with id {0} does not exist'.format(service_id))
#
# Path: ac_mediator/exceptions.py
# class ACServiceDoesNotExist(ACException):
# pass
. Output only the next line. | pass |
Predict the next line for this snippet: <|code_start|>
request_distributor = get_request_distributor()
response_aggregator = get_response_aggregator()
def get_request_context(request):
user_account_id = None
dev_account_id = None
if hasattr(request, 'successful_authenticator') and request.successful_authenticator:
# In production API calls this should be always the case as otherwise API returns 401 before reaching here
user_account_id = request.user.id
dev_account_id = request.auth.application.user.id
else:
# In integration tests or local development it can happen that successful_authenticator does not exist
# In that case we provide 'fake' context so tests can be carried out correctly
if request.user.is_authenticated():
user_account_id = request.user.id
dev_account_id = user_account_id
else:
if settings.DEBUG and settings.ALLOW_UNAUTHENTICATED_API_REQUESTS_ON_DEBUG:
user_account_id = Account.objects.all()[0].id
dev_account_id = user_account_id
response_format = request.GET.get(QUERY_PARAM_FORMAT, settings.DEFAULT_RESPONSE_FORMAT)
if response_format not in [settings.JSON_FORMAT_KEY, settings.JSON_LD_FORMAT_KEY]:
response_format = settings.DEFAULT_RESPONSE_FORMAT
return {
'user_account_id': user_account_id,
'dev_account_id': dev_account_id,
<|code_end|>
with the help of current file imports:
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from ac_mediator.exceptions import *
from api.request_distributor import get_request_distributor
from api.response_aggregator import get_response_aggregator
from services.mgmt import get_available_services
from services.acservice.constants import *
from django.conf import settings
from accounts.models import Account
and context from other files:
# Path: api/request_distributor.py
# def get_request_distributor():
# return request_distributor
#
# Path: api/response_aggregator.py
# def get_response_aggregator():
# return response_aggregator
#
# Path: services/mgmt.py
# def get_available_services(component=None, exclude=None, include=None):
# """
# Get all available services which implement a particular component (or all services if
# 'component' is None). Allows excluding particular services and restricting those from which to filter.
# :param component: component (mixin) that should be implemented by returned services
# :param exclude: exclude services passed through this parameter (should be a list of service names)
# :param include: consider only services passed through this parameter (should be a list of service names)
# :return: list of matching services (can be empty)
# """
# out_services = list()
# for service in available_services:
# if component is not None:
# if component not in service.implemented_components:
# continue
# if exclude is not None:
# if service.name in exclude:
# continue
# if include is not None:
# if service.name not in include:
# continue
# out_services.append(service)
# return out_services
#
# Path: accounts/models.py
# class Account(AbstractUser):
# """
# This is our custom 'User' model.
# """
#
# is_developer = models.BooleanField(default=False, blank=False)
# accepted_tos = models.BooleanField(default=False, blank=False)
# # Add more custom fields here like avatar...
#
# def send_activation_email(self):
# tvars = {
# 'user': self,
# 'username': self.username,
# 'hash': create_hash(self.id)
# }
# send_mail(self.email, subject='Activate your Audio Commons user account',
# template='emails/account_activation.txt', context=tvars)
#
# class Meta:
# verbose_name = _('account')
# verbose_name_plural = _('accounts')
, which may contain function names, class names, or code. Output only the next line. | 'format': response_format, |
Based on the snippet: <|code_start|> if exclude is not None:
exclude = exclude.split(',')
wait_until_complete = \
request.GET.get(QUERY_PARAM_WAIT_UNTIL_COMPLETE, False) # This option is left intentionally undocumented
return {
QUERY_PARAM_INCLUDE: include,
QUERY_PARAM_EXCLUDE: exclude,
'wait_until_complete': wait_until_complete,
}
def parse_common_search_query_params(request):
fields = request.GET.get(QUERY_PARAM_FIELDS, None)
if fields is None:
fields = MINIMUM_RESOURCE_DESCRIPTION_FIELDS
else:
if fields == '*':
fields = ALL_RESOURCE_DESCRIPTION_FIELDS
else:
fields = fields.split(',')
size = request.GET.get(QUERY_PARAM_SIZE, 15)
try:
size = int(size)
except ValueError:
raise ACAPIBadRequest("Invalid '{0}' value".format(QUERY_PARAM_SIZE))
page = request.GET.get(QUERY_PARAM_PAGE, None)
if page is not None:
try:
page = int(page)
except ValueError:
<|code_end|>
, predict the immediate next line with the help of imports:
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from ac_mediator.exceptions import *
from api.request_distributor import get_request_distributor
from api.response_aggregator import get_response_aggregator
from services.mgmt import get_available_services
from services.acservice.constants import *
from django.conf import settings
from accounts.models import Account
and context (classes, functions, sometimes code) from other files:
# Path: api/request_distributor.py
# def get_request_distributor():
# return request_distributor
#
# Path: api/response_aggregator.py
# def get_response_aggregator():
# return response_aggregator
#
# Path: services/mgmt.py
# def get_available_services(component=None, exclude=None, include=None):
# """
# Get all available services which implement a particular component (or all services if
# 'component' is None). Allows excluding particular services and restricting those from which to filter.
# :param component: component (mixin) that should be implemented by returned services
# :param exclude: exclude services passed through this parameter (should be a list of service names)
# :param include: consider only services passed through this parameter (should be a list of service names)
# :return: list of matching services (can be empty)
# """
# out_services = list()
# for service in available_services:
# if component is not None:
# if component not in service.implemented_components:
# continue
# if exclude is not None:
# if service.name in exclude:
# continue
# if include is not None:
# if service.name not in include:
# continue
# out_services.append(service)
# return out_services
#
# Path: accounts/models.py
# class Account(AbstractUser):
# """
# This is our custom 'User' model.
# """
#
# is_developer = models.BooleanField(default=False, blank=False)
# accepted_tos = models.BooleanField(default=False, blank=False)
# # Add more custom fields here like avatar...
#
# def send_activation_email(self):
# tvars = {
# 'user': self,
# 'username': self.username,
# 'hash': create_hash(self.id)
# }
# send_mail(self.email, subject='Activate your Audio Commons user account',
# template='emails/account_activation.txt', context=tvars)
#
# class Meta:
# verbose_name = _('account')
# verbose_name_plural = _('accounts')
. Output only the next line. | raise ACAPIBadRequest("Invalid '{0}' value".format(QUERY_PARAM_PAGE)) |
Given snippet: <|code_start|> 'dev_account_id': dev_account_id,
'format': response_format,
# NOTE: we use id's instead of the objects so that the dict can be serialized and passed to Celery
}
def parse_request_distributor_query_params(request):
include = request.GET.get(QUERY_PARAM_INCLUDE, None)
if include is not None:
include = include.split(',')
exclude = request.GET.get(QUERY_PARAM_EXCLUDE, None)
if exclude is not None:
exclude = exclude.split(',')
wait_until_complete = \
request.GET.get(QUERY_PARAM_WAIT_UNTIL_COMPLETE, False) # This option is left intentionally undocumented
return {
QUERY_PARAM_INCLUDE: include,
QUERY_PARAM_EXCLUDE: exclude,
'wait_until_complete': wait_until_complete,
}
def parse_common_search_query_params(request):
fields = request.GET.get(QUERY_PARAM_FIELDS, None)
if fields is None:
fields = MINIMUM_RESOURCE_DESCRIPTION_FIELDS
else:
if fields == '*':
fields = ALL_RESOURCE_DESCRIPTION_FIELDS
else:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from ac_mediator.exceptions import *
from api.request_distributor import get_request_distributor
from api.response_aggregator import get_response_aggregator
from services.mgmt import get_available_services
from services.acservice.constants import *
from django.conf import settings
from accounts.models import Account
and context:
# Path: api/request_distributor.py
# def get_request_distributor():
# return request_distributor
#
# Path: api/response_aggregator.py
# def get_response_aggregator():
# return response_aggregator
#
# Path: services/mgmt.py
# def get_available_services(component=None, exclude=None, include=None):
# """
# Get all available services which implement a particular component (or all services if
# 'component' is None). Allows excluding particular services and restricting those from which to filter.
# :param component: component (mixin) that should be implemented by returned services
# :param exclude: exclude services passed through this parameter (should be a list of service names)
# :param include: consider only services passed through this parameter (should be a list of service names)
# :return: list of matching services (can be empty)
# """
# out_services = list()
# for service in available_services:
# if component is not None:
# if component not in service.implemented_components:
# continue
# if exclude is not None:
# if service.name in exclude:
# continue
# if include is not None:
# if service.name not in include:
# continue
# out_services.append(service)
# return out_services
#
# Path: accounts/models.py
# class Account(AbstractUser):
# """
# This is our custom 'User' model.
# """
#
# is_developer = models.BooleanField(default=False, blank=False)
# accepted_tos = models.BooleanField(default=False, blank=False)
# # Add more custom fields here like avatar...
#
# def send_activation_email(self):
# tvars = {
# 'user': self,
# 'username': self.username,
# 'hash': create_hash(self.id)
# }
# send_mail(self.email, subject='Activate your Audio Commons user account',
# template='emails/account_activation.txt', context=tvars)
#
# class Meta:
# verbose_name = _('account')
# verbose_name_plural = _('accounts')
which might include code, classes, or functions. Output only the next line. | fields = fields.split(',') |
Using the snippet: <|code_start|> if request.user.is_authenticated():
user_account_id = request.user.id
dev_account_id = user_account_id
else:
if settings.DEBUG and settings.ALLOW_UNAUTHENTICATED_API_REQUESTS_ON_DEBUG:
user_account_id = Account.objects.all()[0].id
dev_account_id = user_account_id
response_format = request.GET.get(QUERY_PARAM_FORMAT, settings.DEFAULT_RESPONSE_FORMAT)
if response_format not in [settings.JSON_FORMAT_KEY, settings.JSON_LD_FORMAT_KEY]:
response_format = settings.DEFAULT_RESPONSE_FORMAT
return {
'user_account_id': user_account_id,
'dev_account_id': dev_account_id,
'format': response_format,
# NOTE: we use id's instead of the objects so that the dict can be serialized and passed to Celery
}
def parse_request_distributor_query_params(request):
include = request.GET.get(QUERY_PARAM_INCLUDE, None)
if include is not None:
include = include.split(',')
exclude = request.GET.get(QUERY_PARAM_EXCLUDE, None)
if exclude is not None:
exclude = exclude.split(',')
wait_until_complete = \
request.GET.get(QUERY_PARAM_WAIT_UNTIL_COMPLETE, False) # This option is left intentionally undocumented
return {
<|code_end|>
, determine the next line of code. You have imports:
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from ac_mediator.exceptions import *
from api.request_distributor import get_request_distributor
from api.response_aggregator import get_response_aggregator
from services.mgmt import get_available_services
from services.acservice.constants import *
from django.conf import settings
from accounts.models import Account
and context (class names, function names, or code) available:
# Path: api/request_distributor.py
# def get_request_distributor():
# return request_distributor
#
# Path: api/response_aggregator.py
# def get_response_aggregator():
# return response_aggregator
#
# Path: services/mgmt.py
# def get_available_services(component=None, exclude=None, include=None):
# """
# Get all available services which implement a particular component (or all services if
# 'component' is None). Allows excluding particular services and restricting those from which to filter.
# :param component: component (mixin) that should be implemented by returned services
# :param exclude: exclude services passed through this parameter (should be a list of service names)
# :param include: consider only services passed through this parameter (should be a list of service names)
# :return: list of matching services (can be empty)
# """
# out_services = list()
# for service in available_services:
# if component is not None:
# if component not in service.implemented_components:
# continue
# if exclude is not None:
# if service.name in exclude:
# continue
# if include is not None:
# if service.name not in include:
# continue
# out_services.append(service)
# return out_services
#
# Path: accounts/models.py
# class Account(AbstractUser):
# """
# This is our custom 'User' model.
# """
#
# is_developer = models.BooleanField(default=False, blank=False)
# accepted_tos = models.BooleanField(default=False, blank=False)
# # Add more custom fields here like avatar...
#
# def send_activation_email(self):
# tvars = {
# 'user': self,
# 'username': self.username,
# 'hash': create_hash(self.id)
# }
# send_mail(self.email, subject='Activate your Audio Commons user account',
# template='emails/account_activation.txt', context=tvars)
#
# class Meta:
# verbose_name = _('account')
# verbose_name_plural = _('accounts')
. Output only the next line. | QUERY_PARAM_INCLUDE: include, |
Predict the next line for this snippet: <|code_start|> self.assertEqual(resp.json()['error'], 'invalid_client')
# Return 'unsupported_grant_type' when grant type does not exist
resp = self.client.post(
reverse('oauth2_provider:token'),
{
'client_id': client.client_id,
'grant_type': 'invented_grant',
'username': self.end_user.username,
'password': self.end_user_password,
})
self.assertEqual(resp.status_code, 400)
self.assertEqual(resp.json()['error'], 'unsupported_grant_type')
# Return 'invalid_request' when no username is provided
resp = self.client.post(
reverse('oauth2_provider:token'),
{
'client_id': client.client_id,
'grant_type': 'password',
#'username': self.end_user.username,
'password': self.end_user_password,
})
self.assertEqual(resp.status_code, 400)
self.assertEqual(resp.json()['error'], 'invalid_request')
# Return 'invalid_request' when no password is provided
resp = self.client.post(
reverse('oauth2_provider:token'),
{
<|code_end|>
with the help of current file imports:
from django.test import TestCase, override_settings
from api.models import ApiClient
from accounts.models import Account
from django.core.urlresolvers import reverse
from services import management
from django.conf import settings
from services.acservice.base import BaseACService
from services.acservice.download import ACDownloadMixin
import oauth2_provider
import datetime
and context from other files:
# Path: api/models.py
# class ApiClient(AbstractApplication):
# """
# This is our custom 'Application' model for Oauth authentication.
# """
#
# agree_tos = models.BooleanField(default=False)
# password_grant_is_allowed = models.BooleanField(default=False) # Enable password grant in OAuth2 authentication
# created = models.DateTimeField(auto_now_add=True)
# # Add more custom fields here like description, logo, preferred services...
#
# def get_absolute_url(self):
# return reverse('developers-app-detail', args=[self.id])
#
# def clean(self):
# """
# The AbstractApplication model includes a clean method that raises a ValidationError
# if the redirect_uri is empty and is required by the authorization_grant_type. We have
# implemented a custom version of this check (with a custom message) in api.forms.ApiClientForm
# therefore we don't need model's clean method to do anything.
# """
# pass
#
# Path: accounts/models.py
# class Account(AbstractUser):
# """
# This is our custom 'User' model.
# """
#
# is_developer = models.BooleanField(default=False, blank=False)
# accepted_tos = models.BooleanField(default=False, blank=False)
# # Add more custom fields here like avatar...
#
# def send_activation_email(self):
# tvars = {
# 'user': self,
# 'username': self.username,
# 'hash': create_hash(self.id)
# }
# send_mail(self.email, subject='Activate your Audio Commons user account',
# template='emails/account_activation.txt', context=tvars)
#
# class Meta:
# verbose_name = _('account')
# verbose_name_plural = _('accounts')
, which may contain function names, class names, or code. Output only the next line. | 'client_id': client.client_id, |
Given the following code snippet before the placeholder: <|code_start|> self.service.configure({'service_id': 'downloadserviceid', 'enabled': 'yes'})
management.available_services = [self.service]
def test_get_download_link(self):
# Make unauthenticated request and assert it returns 401
resp = self.client.get(reverse('api-download'), {
'acid': 'DownloadService:123',
})
self.assertEqual(resp.status_code, 401)
# Create an access token for application and user
client = ApiClient.objects.get(name='TestClient')
access_token = self.access_token = oauth2_provider.models.AccessToken.objects.create(
token='a_fake_token',
application=client,
user=self.end_user,
expires=datetime.datetime.today() + datetime.timedelta(hours=1)
)
# Make API request authenticated and assert it returns 200
resp = self.client.get(reverse('api-download'), {
'acid': 'DownloadService:123',
}, HTTP_AUTHORIZATION='Bearer {0}'.format(access_token))
self.assertEqual(resp.status_code, 200)
# Ensure request for non existing service returns 404
resp = self.client.get(reverse('api-download'), {
'acid': 'DownloadService2:123',
}, HTTP_AUTHORIZATION='Bearer {0}'.format(access_token))
<|code_end|>
, predict the next line using imports from the current file:
from django.test import TestCase, override_settings
from api.models import ApiClient
from accounts.models import Account
from django.core.urlresolvers import reverse
from services import management
from django.conf import settings
from services.acservice.base import BaseACService
from services.acservice.download import ACDownloadMixin
import oauth2_provider
import datetime
and context including class names, function names, and sometimes code from other files:
# Path: api/models.py
# class ApiClient(AbstractApplication):
# """
# This is our custom 'Application' model for Oauth authentication.
# """
#
# agree_tos = models.BooleanField(default=False)
# password_grant_is_allowed = models.BooleanField(default=False) # Enable password grant in OAuth2 authentication
# created = models.DateTimeField(auto_now_add=True)
# # Add more custom fields here like description, logo, preferred services...
#
# def get_absolute_url(self):
# return reverse('developers-app-detail', args=[self.id])
#
# def clean(self):
# """
# The AbstractApplication model includes a clean method that raises a ValidationError
# if the redirect_uri is empty and is required by the authorization_grant_type. We have
# implemented a custom version of this check (with a custom message) in api.forms.ApiClientForm
# therefore we don't need model's clean method to do anything.
# """
# pass
#
# Path: accounts/models.py
# class Account(AbstractUser):
# """
# This is our custom 'User' model.
# """
#
# is_developer = models.BooleanField(default=False, blank=False)
# accepted_tos = models.BooleanField(default=False, blank=False)
# # Add more custom fields here like avatar...
#
# def send_activation_email(self):
# tvars = {
# 'user': self,
# 'username': self.username,
# 'hash': create_hash(self.id)
# }
# send_mail(self.email, subject='Activate your Audio Commons user account',
# template='emails/account_activation.txt', context=tvars)
#
# class Meta:
# verbose_name = _('account')
# verbose_name_plural = _('accounts')
. Output only the next line. | self.assertEqual(resp.status_code, 404) |
Here is a snippet: <|code_start|> )
email1 = forms.EmailField(label=_("Email"), help_text=_("We will send you a confirmation/activation email, so make "
"sure this is correct!."))
email2 = forms.EmailField(label=_("Email confirmation"))
password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
password2 = forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput)
accepted_tos = forms.BooleanField(
label='',
help_text=_('Check this box to accept the <a href="/docs/api_tos.html" target="_blank">terms of service and '
'privacy policy</a>'),
required=True,
error_messages={'required': _('You must accept the terms of use in order to register.')}
)
def clean_username(self):
username = self.cleaned_data["username"]
try:
Account.objects.get(username__iexact=username)
except Account.DoesNotExist:
return username
raise forms.ValidationError(_("A user with that username already exists."))
def clean_password2(self):
password1 = self.cleaned_data.get("password1", "")
password2 = self.cleaned_data["password2"]
if password1 != password2:
raise forms.ValidationError(_("The two password fields didn't match."))
return password2
def clean_email2(self):
<|code_end|>
. Write the next line using the current file imports:
from django import forms
from accounts.models import Account
from django.utils.translation import ugettext as _
and context from other files:
# Path: accounts/models.py
# class Account(AbstractUser):
# """
# This is our custom 'User' model.
# """
#
# is_developer = models.BooleanField(default=False, blank=False)
# accepted_tos = models.BooleanField(default=False, blank=False)
# # Add more custom fields here like avatar...
#
# def send_activation_email(self):
# tvars = {
# 'user': self,
# 'username': self.username,
# 'hash': create_hash(self.id)
# }
# send_mail(self.email, subject='Activate your Audio Commons user account',
# template='emails/account_activation.txt', context=tvars)
#
# class Meta:
# verbose_name = _('account')
# verbose_name_plural = _('accounts')
, which may include functions, classes, or code. Output only the next line. | email1 = self.cleaned_data.get("email1", "") |
Predict the next line after this snippet: <|code_start|>
response_aggregator = get_response_aggregator()
@shared_task
def perform_request_and_aggregate(request, response_id, service_id):
service = get_service_by_id(service_id)
try:
print('Requesting response from {0} ({1})'.format(service.name, response_id))
<|code_end|>
using the current file's imports:
from django.conf import settings
from ac_mediator.exceptions import *
from services.acservice.constants import *
from services.mgmt import get_available_services, get_service_by_id
from api.response_aggregator import get_response_aggregator
from celery import shared_task
and any relevant context from other files:
# Path: services/mgmt.py
# def get_available_services(component=None, exclude=None, include=None):
# """
# Get all available services which implement a particular component (or all services if
# 'component' is None). Allows excluding particular services and restricting those from which to filter.
# :param component: component (mixin) that should be implemented by returned services
# :param exclude: exclude services passed through this parameter (should be a list of service names)
# :param include: consider only services passed through this parameter (should be a list of service names)
# :return: list of matching services (can be empty)
# """
# out_services = list()
# for service in available_services:
# if component is not None:
# if component not in service.implemented_components:
# continue
# if exclude is not None:
# if service.name in exclude:
# continue
# if include is not None:
# if service.name not in include:
# continue
# out_services.append(service)
# return out_services
#
# def get_service_by_id(service_id):
# for service in available_services:
# if service.id == service_id:
# return service
# raise ACServiceDoesNotExist('Service with id {0} does not exist'.format(service_id))
#
# Path: api/response_aggregator.py
# def get_response_aggregator():
# return response_aggregator
. Output only the next line. | service.clear_response_warnings() |
Using the snippet: <|code_start|>
response_aggregator = get_response_aggregator()
@shared_task
def perform_request_and_aggregate(request, response_id, service_id):
service = get_service_by_id(service_id)
try:
print('Requesting response from {0} ({1})'.format(service.name, response_id))
service.clear_response_warnings()
service_response = getattr(service, request['method'])(request['context'], **request['kwargs'])
warnings = service.collect_response_warnings()
response_aggregator.aggregate_response(response_id, service.name, service_response, warnings=warnings)
<|code_end|>
, determine the next line of code. You have imports:
from django.conf import settings
from ac_mediator.exceptions import *
from services.acservice.constants import *
from services.mgmt import get_available_services, get_service_by_id
from api.response_aggregator import get_response_aggregator
from celery import shared_task
and context (class names, function names, or code) available:
# Path: services/mgmt.py
# def get_available_services(component=None, exclude=None, include=None):
# """
# Get all available services which implement a particular component (or all services if
# 'component' is None). Allows excluding particular services and restricting those from which to filter.
# :param component: component (mixin) that should be implemented by returned services
# :param exclude: exclude services passed through this parameter (should be a list of service names)
# :param include: consider only services passed through this parameter (should be a list of service names)
# :return: list of matching services (can be empty)
# """
# out_services = list()
# for service in available_services:
# if component is not None:
# if component not in service.implemented_components:
# continue
# if exclude is not None:
# if service.name in exclude:
# continue
# if include is not None:
# if service.name not in include:
# continue
# out_services.append(service)
# return out_services
#
# def get_service_by_id(service_id):
# for service in available_services:
# if service.id == service_id:
# return service
# raise ACServiceDoesNotExist('Service with id {0} does not exist'.format(service_id))
#
# Path: api/response_aggregator.py
# def get_response_aggregator():
# return response_aggregator
. Output only the next line. | except (ACException, ACAPIException) as e: |
Predict the next line for this snippet: <|code_start|>
response_aggregator = get_response_aggregator()
@shared_task
def perform_request_and_aggregate(request, response_id, service_id):
service = get_service_by_id(service_id)
try:
print('Requesting response from {0} ({1})'.format(service.name, response_id))
service.clear_response_warnings()
service_response = getattr(service, request['method'])(request['context'], **request['kwargs'])
warnings = service.collect_response_warnings()
response_aggregator.aggregate_response(response_id, service.name, service_response, warnings=warnings)
except (ACException, ACAPIException) as e:
# Aggregate error response in response aggregator and continue with next service
<|code_end|>
with the help of current file imports:
from django.conf import settings
from ac_mediator.exceptions import *
from services.acservice.constants import *
from services.mgmt import get_available_services, get_service_by_id
from api.response_aggregator import get_response_aggregator
from celery import shared_task
and context from other files:
# Path: services/mgmt.py
# def get_available_services(component=None, exclude=None, include=None):
# """
# Get all available services which implement a particular component (or all services if
# 'component' is None). Allows excluding particular services and restricting those from which to filter.
# :param component: component (mixin) that should be implemented by returned services
# :param exclude: exclude services passed through this parameter (should be a list of service names)
# :param include: consider only services passed through this parameter (should be a list of service names)
# :return: list of matching services (can be empty)
# """
# out_services = list()
# for service in available_services:
# if component is not None:
# if component not in service.implemented_components:
# continue
# if exclude is not None:
# if service.name in exclude:
# continue
# if include is not None:
# if service.name not in include:
# continue
# out_services.append(service)
# return out_services
#
# def get_service_by_id(service_id):
# for service in available_services:
# if service.id == service_id:
# return service
# raise ACServiceDoesNotExist('Service with id {0} does not exist'.format(service_id))
#
# Path: api/response_aggregator.py
# def get_response_aggregator():
# return response_aggregator
, which may contain function names, class names, or code. Output only the next line. | response_aggregator.aggregate_response(response_id, service.name, e) |
Continue the code snippet: <|code_start|>
def _encode_jwt(
algorithm: str,
audience: Union[str, Iterable[str]],
claim_overrides: dict,
csrf: bool,
expires_delta: ExpiresDelta,
fresh: bool,
header_overrides: dict,
identity: Any,
identity_claim_key: str,
<|code_end|>
. Use current file imports:
import uuid
import jwt
from datetime import datetime
from datetime import timedelta
from datetime import timezone
from hmac import compare_digest
from typing import Any
from typing import Iterable
from typing import List
from typing import Type
from typing import Union
from flask.json import JSONEncoder
from flask_jwt_extended.exceptions import CSRFError
from flask_jwt_extended.exceptions import JWTDecodeError
from flask_jwt_extended.typing import ExpiresDelta
and context (classes, functions, or code) from other files:
# Path: flask_jwt_extended/exceptions.py
# class CSRFError(JWTExtendedException):
# """
# An error with CSRF protection
# """
#
# pass
#
# Path: flask_jwt_extended/exceptions.py
# class JWTDecodeError(JWTExtendedException):
# """
# An error decoding a JWT
# """
#
# pass
#
# Path: flask_jwt_extended/typing.py
. Output only the next line. | issuer: str, |
Given the following code snippet before the placeholder: <|code_start|> fresh = datetime.timestamp(now + fresh)
token_data = {
"fresh": fresh,
"iat": now,
"jti": str(uuid.uuid4()),
"type": token_type,
identity_claim_key: identity,
}
if nbf:
token_data["nbf"] = now
if csrf:
token_data["csrf"] = str(uuid.uuid4())
if audience:
token_data["aud"] = audience
if issuer:
token_data["iss"] = issuer
if expires_delta:
token_data["exp"] = now + expires_delta
if claim_overrides:
token_data.update(claim_overrides)
return jwt.encode(
token_data,
<|code_end|>
, predict the next line using imports from the current file:
import uuid
import jwt
from datetime import datetime
from datetime import timedelta
from datetime import timezone
from hmac import compare_digest
from typing import Any
from typing import Iterable
from typing import List
from typing import Type
from typing import Union
from flask.json import JSONEncoder
from flask_jwt_extended.exceptions import CSRFError
from flask_jwt_extended.exceptions import JWTDecodeError
from flask_jwt_extended.typing import ExpiresDelta
and context including class names, function names, and sometimes code from other files:
# Path: flask_jwt_extended/exceptions.py
# class CSRFError(JWTExtendedException):
# """
# An error with CSRF protection
# """
#
# pass
#
# Path: flask_jwt_extended/exceptions.py
# class JWTDecodeError(JWTExtendedException):
# """
# An error decoding a JWT
# """
#
# pass
#
# Path: flask_jwt_extended/typing.py
. Output only the next line. | secret, |
Given snippet: <|code_start|>
def _encode_jwt(
algorithm: str,
audience: Union[str, Iterable[str]],
claim_overrides: dict,
csrf: bool,
expires_delta: ExpiresDelta,
fresh: bool,
header_overrides: dict,
identity: Any,
identity_claim_key: str,
issuer: str,
json_encoder: Type[JSONEncoder],
secret: str,
token_type: str,
nbf: bool,
) -> str:
now = datetime.now(timezone.utc)
if isinstance(fresh, timedelta):
fresh = datetime.timestamp(now + fresh)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import uuid
import jwt
from datetime import datetime
from datetime import timedelta
from datetime import timezone
from hmac import compare_digest
from typing import Any
from typing import Iterable
from typing import List
from typing import Type
from typing import Union
from flask.json import JSONEncoder
from flask_jwt_extended.exceptions import CSRFError
from flask_jwt_extended.exceptions import JWTDecodeError
from flask_jwt_extended.typing import ExpiresDelta
and context:
# Path: flask_jwt_extended/exceptions.py
# class CSRFError(JWTExtendedException):
# """
# An error with CSRF protection
# """
#
# pass
#
# Path: flask_jwt_extended/exceptions.py
# class JWTDecodeError(JWTExtendedException):
# """
# An error decoding a JWT
# """
#
# pass
#
# Path: flask_jwt_extended/typing.py
which might include code, classes, or functions. Output only the next line. | token_data = { |
Next line prediction: <|code_start|> #extract calib data from cam_config
self.a = cam_config["a"]
self.n = cam_config["n"]
self.cam = cv2.VideoCapture(cam_num)
self.cam.set(3, 1280)
self.cam.set(4, 720)
self.resX = int(self.cam.get(3))
self.resY = int(self.cam.get(4))
# QR scanning tools
self.scanner = zbar.ImageScanner()
self.scanner.parse_config('enable')
(self.grabbed, self.frame) = self.cam.read()
self.stopped = True
def start(self):
# start the thread to read frames from the video stream
thread = Thread(target=self.update, args=())
thread.setDaemon(True)
self.stopped = False
thread.start()
return thread
def update(self):
# keep looping infinitely until the thread is stopped
<|code_end|>
. Use current file imports:
(import numpy as np
import time
import subprocess
import zbar
import cv2
import cv2
import math
import bot.lib.lib as lib
from PIL import Image
from PIL import ImageEnhance
from threading import Thread
from bot.hardware.qr_code import QRCode
from bot.hardware.complex_hardware.QRCode2 import QRCode2
from bot.hardware.complex_hardware.QRCode2 import Block
from bot.hardware.complex_hardware.partial_qr import *)
and context including class names, function names, or small code snippets from other files:
# Path: bot/hardware/qr_code.py
# class QRCode(object):
# """ Represents a QR code.
# Locations are not accurate.
# Useful properties:
# self.value: the value of the code.
# self.points: numpy
# self.X: X value of center
# self.Y: Y value of center
#
# """
#
# def __init__(self, symbol, size):
#
# # Raw object from zbar.
# self.symbol = symbol
# self.value = self.symbol.data
#
# # Begin Processing symbol
# self.topLeft, self.bottomLeft, self.bottomRight, self.topRight = [item for item in self.symbol.location]
#
# self.points = np.float32(symbol.location)
# self.set_centroid_location()
#
# l = size
# self.verts = np.float32([[-l/2, -l/2, 0],
# [-l/2, l/2, 0],
# [l/2, -l/2, 0],
# [l/2, l/2, 0]])
# self.rvec = [999]*3
# self.tvec = [999]*3
# self.displacement = []
# self.displacement_2d = []
#
# def __str__(self):
# return "value: %s \n Location: %s \n Verts: %s" % \
# (self.value, self.centroid_location, self.points)
#
# @property
# def tvec(self):
# return self.__tvec
#
# @tvec.setter
# def tvec(self, vec):
# self.__tvec = vec
# self.displacement_2d = sqrt(vec[0]**2 + vec[1]**2)
# self.displacement = sqrt(vec[0]**2 + vec[1]**2 + vec[2]**2)
#
# @property
# def points(self):
# return self.__points
#
# @points.setter
# def points(self, value):
# """Numpy array of corners of QR code. """
# self.__points = np.float32(value)
#
# def set_centroid_location(self):
# x_sum = 0
# y_sum = 0
# # calculate center from x and y of points
# for item in self.symbol.location:
# x_sum += item[0]
# y_sum += item[1]
# X = x_sum / 4
# Y = y_sum /4
# self.centroid_location = (X, Y)
#
# Path: bot/hardware/complex_hardware/QRCode2.py
# class QRCode2(object):
# def __init__(self, tvec, value, top_right):
# self.tvec = tvec
# self.value = value
# self.tr = top_right
#
# Path: bot/hardware/complex_hardware/QRCode2.py
# class Block(object):
# def __init__(self, size, color):
# self.size = size
# self.color = color
. Output only the next line. | while not self.stopped: |
Predict the next line for this snippet: <|code_start|> # QR scanning tools
self.scanner = zbar.ImageScanner()
self.scanner.parse_config('enable')
(self.grabbed, self.frame) = self.cam.read()
self.stopped = True
def start(self):
# start the thread to read frames from the video stream
thread = Thread(target=self.update, args=())
thread.setDaemon(True)
self.stopped = False
thread.start()
return thread
def update(self):
# keep looping infinitely until the thread is stopped
while not self.stopped:
print "In the update camera thread"
# otherwise, read the next frame from the stream
(self.grabbed, self.frame) = self.cam.read()
time.sleep(.1)
return
def read(self):
# return the frame most recently read
return self.frame
<|code_end|>
with the help of current file imports:
import numpy as np
import time
import subprocess
import zbar
import cv2
import cv2
import math
import bot.lib.lib as lib
from PIL import Image
from PIL import ImageEnhance
from threading import Thread
from bot.hardware.qr_code import QRCode
from bot.hardware.complex_hardware.QRCode2 import QRCode2
from bot.hardware.complex_hardware.QRCode2 import Block
from bot.hardware.complex_hardware.partial_qr import *
and context from other files:
# Path: bot/hardware/qr_code.py
# class QRCode(object):
# """ Represents a QR code.
# Locations are not accurate.
# Useful properties:
# self.value: the value of the code.
# self.points: numpy
# self.X: X value of center
# self.Y: Y value of center
#
# """
#
# def __init__(self, symbol, size):
#
# # Raw object from zbar.
# self.symbol = symbol
# self.value = self.symbol.data
#
# # Begin Processing symbol
# self.topLeft, self.bottomLeft, self.bottomRight, self.topRight = [item for item in self.symbol.location]
#
# self.points = np.float32(symbol.location)
# self.set_centroid_location()
#
# l = size
# self.verts = np.float32([[-l/2, -l/2, 0],
# [-l/2, l/2, 0],
# [l/2, -l/2, 0],
# [l/2, l/2, 0]])
# self.rvec = [999]*3
# self.tvec = [999]*3
# self.displacement = []
# self.displacement_2d = []
#
# def __str__(self):
# return "value: %s \n Location: %s \n Verts: %s" % \
# (self.value, self.centroid_location, self.points)
#
# @property
# def tvec(self):
# return self.__tvec
#
# @tvec.setter
# def tvec(self, vec):
# self.__tvec = vec
# self.displacement_2d = sqrt(vec[0]**2 + vec[1]**2)
# self.displacement = sqrt(vec[0]**2 + vec[1]**2 + vec[2]**2)
#
# @property
# def points(self):
# return self.__points
#
# @points.setter
# def points(self, value):
# """Numpy array of corners of QR code. """
# self.__points = np.float32(value)
#
# def set_centroid_location(self):
# x_sum = 0
# y_sum = 0
# # calculate center from x and y of points
# for item in self.symbol.location:
# x_sum += item[0]
# y_sum += item[1]
# X = x_sum / 4
# Y = y_sum /4
# self.centroid_location = (X, Y)
#
# Path: bot/hardware/complex_hardware/QRCode2.py
# class QRCode2(object):
# def __init__(self, tvec, value, top_right):
# self.tvec = tvec
# self.value = value
# self.tr = top_right
#
# Path: bot/hardware/complex_hardware/QRCode2.py
# class Block(object):
# def __init__(self, size, color):
# self.size = size
# self.color = color
, which may contain function names, class names, or code. Output only the next line. | def stop(self): |
Using the snippet: <|code_start|>
def find_name(symlink):
# find where symlink is pointing (/dev/vide0, video1, etc)
cmd = "readlink -f /dev/" + symlink
process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
out = process.communicate()[0]
#extract ints from name video0, etc
nums = [int(x) for x in out if x.isdigit()]
# There should nto be more than one digit
interface_num = nums[0]
return interface_num
class Camera(object):
L = 1.5
qr_verts = np.float32([[-L/2, -L/2, 0],
[-L/2, L/2, 0],
[ L/2, -L/2, 0],
[ L/2, L/2, 0]])
def __init__(self, cam_config):
self.logger = lib.get_logger()
udev_name = cam_config["udev_name"]
print udev_name
<|code_end|>
, determine the next line of code. You have imports:
import numpy as np
import time
import subprocess
import zbar
import cv2
import cv2
import math
import bot.lib.lib as lib
from PIL import Image
from PIL import ImageEnhance
from threading import Thread
from bot.hardware.qr_code import QRCode
from bot.hardware.complex_hardware.QRCode2 import QRCode2
from bot.hardware.complex_hardware.QRCode2 import Block
from bot.hardware.complex_hardware.partial_qr import *
and context (class names, function names, or code) available:
# Path: bot/hardware/qr_code.py
# class QRCode(object):
# """ Represents a QR code.
# Locations are not accurate.
# Useful properties:
# self.value: the value of the code.
# self.points: numpy
# self.X: X value of center
# self.Y: Y value of center
#
# """
#
# def __init__(self, symbol, size):
#
# # Raw object from zbar.
# self.symbol = symbol
# self.value = self.symbol.data
#
# # Begin Processing symbol
# self.topLeft, self.bottomLeft, self.bottomRight, self.topRight = [item for item in self.symbol.location]
#
# self.points = np.float32(symbol.location)
# self.set_centroid_location()
#
# l = size
# self.verts = np.float32([[-l/2, -l/2, 0],
# [-l/2, l/2, 0],
# [l/2, -l/2, 0],
# [l/2, l/2, 0]])
# self.rvec = [999]*3
# self.tvec = [999]*3
# self.displacement = []
# self.displacement_2d = []
#
# def __str__(self):
# return "value: %s \n Location: %s \n Verts: %s" % \
# (self.value, self.centroid_location, self.points)
#
# @property
# def tvec(self):
# return self.__tvec
#
# @tvec.setter
# def tvec(self, vec):
# self.__tvec = vec
# self.displacement_2d = sqrt(vec[0]**2 + vec[1]**2)
# self.displacement = sqrt(vec[0]**2 + vec[1]**2 + vec[2]**2)
#
# @property
# def points(self):
# return self.__points
#
# @points.setter
# def points(self, value):
# """Numpy array of corners of QR code. """
# self.__points = np.float32(value)
#
# def set_centroid_location(self):
# x_sum = 0
# y_sum = 0
# # calculate center from x and y of points
# for item in self.symbol.location:
# x_sum += item[0]
# y_sum += item[1]
# X = x_sum / 4
# Y = y_sum /4
# self.centroid_location = (X, Y)
#
# Path: bot/hardware/complex_hardware/QRCode2.py
# class QRCode2(object):
# def __init__(self, tvec, value, top_right):
# self.tvec = tvec
# self.value = value
# self.tr = top_right
#
# Path: bot/hardware/complex_hardware/QRCode2.py
# class Block(object):
# def __init__(self, size, color):
# self.size = size
# self.color = color
. Output only the next line. | cam_num = find_name(udev_name) |
Based on the snippet: <|code_start|>
# Some helpers for random.
def randloc():
return randint(-100, 100)
def randrot():
<|code_end|>
, predict the immediate next line with the help of imports:
from random import randint, uniform
from elixir_models import Object
from sys import maxint
import logging
and context (classes, functions, sometimes code) from other files:
# Path: elixir_models.py
# class Object(BaseModel):
# '''In-world objects.'''
#
# name = CharField()
# resource = CharField(default="none")
# owner = CharField(null=True)
#
# loc_x = FloatField(default=0)
# loc_y = FloatField(default=0)
# loc_z = FloatField(default=0)
#
# rot_x = FloatField(default=0)
# rot_y = FloatField(default=0)
# rot_z = FloatField(default=0)
#
# scale_x = FloatField(default=1)
# scale_y = FloatField(default=1)
# scale_z = FloatField(default=1)
#
# speed = FloatField(default=1)
# vel_x = FloatField(default=0)
# vel_y = FloatField(default=0)
# vel_z = FloatField(default=0)
#
# states = JSONField(default=[])
# physical = BooleanField(default=True)
# last_modified = DateTimeField(default=datetime.datetime.now)
#
# scripts = JSONField(default=[])
#
# @property
# def loc(self):
# return (self.loc_x, self.loc_y, self.loc_z)
#
# @loc.setter
# def loc(self, val):
# self.loc_x, self.loc_y, self.loc_z = val
#
# def set_modified(self, date_time=None):
# if date_time is None:
# date_time = datetime.datetime.now()
# self.last_modified = date_time
# self.save()
#
# @staticmethod
# def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# # TODO: Needs integration test.
# obj = Object.select()
#
# if since is not None:
# obj = obj.where(Object.last_modified>=since)
#
# if physical is not None:
# obj = obj.where(Object.physical==physical)
#
# if player is not None:
# obj = obj.where(Object.states.contains('player')).where(Object.name==player)
#
# if scripted is not None:
# obj = obj.where(Object.scripts!=None) # TODO: Have this only return objects with scripts.
#
# if name is not None:
# obj = obj.where(Object.name==name)
#
# obj = obj.order_by(Object.last_modified.desc())
#
# if limit is not None:
# obj = obj.limit(limit)
#
# if limit == 1:
# return obj
#
# return [o for o in obj]
. Output only the next line. | return randint(-360, 360) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.