Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given snippet: <|code_start|>
class TestMouser(TestCase):
def setUp(self):
self.api = MouserApi()
@skip
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.test import TestCase
from .mouser import MouserApi
from unittest import skip
and context:
# Path: bom/third_party_apis/mouser.py
# class MouserApi(BaseApi):
# def __init__(self, *args, **kwargs):
# api_settings_key = 'mouser_api_key'
# root_url='https://api.mouser.com/api/v1'
# api_key_query = 'apiKey'
# super().__init__(api_settings_key, root_url, api_key_query=api_key_query)
#
# @staticmethod
# def parse_and_check_for_errors(content):
# data = json.loads(content)
# errors = data['Errors']
# if len(errors) > 0:
# raise BaseApiError("Error(s): {}".format(errors))
# return data
#
# def search_keyword(self, keyword):
# content = self.request('/search/keyword', data={
# "SearchByKeywordRequest": {
# "keyword": keyword,
# "records": 0,
# "startingRecord": 0,
# "searchOptions": "",
# "searchWithYourSignUpLanguage": ""
# }
# })
# data = self.parse_and_check_for_errors(content)
# return data["SearchResults"]
#
# def get_manufacturer_list(self):
# content = self.request('/search/manufacturerlist')
# data = self.parse_and_check_for_errors(content)
# return data["MouserManufacturerList"]
#
# def search_part(self, part_number):
# content = self.request('/search/partnumber', data={
# "SearchByPartRequest": {
# "mouserPartNumber": part_number,
# "partSearchOptions": "",
# }
# })
# data = self.parse_and_check_for_errors(content)
# return data["SearchResults"]
#
# def search_part_and_manufacturer(self, part_number, manufacturer_id):
# content = self.request('/search/partnumberandmanufacturer', data={
# "SearchByPartMfrRequest": {
# "manufacturerId": manufacturer_id,
# "mouserPartNumber": part_number,
# "partSearchOptions": "",
# }
# })
# data = self.parse_and_check_for_errors(content)
# return data["SearchResults"]
which might include code, classes, or functions. Output only the next line. | def test_search_keyword(self): |
Next line prediction: <|code_start|> path('part/<int:part_id>/rev/<int:part_revision_id>/remove-subpart/<int:subpart_id>/', views.remove_subpart, name='part-remove-subpart'),
path('part/<int:part_id>/rev/<int:part_revision_id>/manage-bom/', views.manage_bom, name='part-manage-bom'),
path('part/<int:part_id>/rev/<int:part_revision_id>/add-subpart/', views.add_subpart, name='part-add-subpart'),
path('part-rev/<int:part_revision_id>/export/', views.part_export_bom, name='part-revision-export-bom'),
path('part-rev/<int:part_revision_id>/export-sourcing/', views.part_export_bom, name='part-revision-export-bom-sourcing', kwargs={'sourcing': True}),
path('part-rev/<int:part_revision_id>/export-sourcing-detailed/', views.part_export_bom, name='part-revision-export-bom-sourcing-detailed', kwargs={'sourcing_detailed': True}),
path('part-rev/<int:part_revision_id>/export-flat/', views.part_export_bom, name='part-revision-export-bom-flat', kwargs={'flat': True}),
path('part-rev/<int:part_revision_id>/export-flat-sourcing/', views.part_export_bom, name='part-revision-export-bom-flat-sourcing', kwargs={'flat': True, 'sourcing': True}),
path('part-rev/<int:part_revision_id>/export-flat-sourcing-detailed/', views.part_export_bom, name='part-revision-export-bom-flat-sourcing-detailed', kwargs={'flat': True, 'sourcing_detailed': True}),
path('sellerpart/<int:sellerpart_id>/edit/', views.sellerpart_edit, name='sellerpart-edit'),
path('sellerpart/<int:sellerpart_id>/delete/', views.sellerpart_delete, name='sellerpart-delete'),
path('manufacturer-part/<int:manufacturer_part_id>/add-sellerpart/', views.add_sellerpart, name='manufacturer-part-add-sellerpart'),
path('manufacturer-part/<int:manufacturer_part_id>/edit', views.manufacturer_part_edit, name='manufacturer-part-edit'),
path('manufacturer-part/<int:manufacturer_part_id>/delete', views.manufacturer_part_delete, name='manufacturer-part-delete'),
]
google_drive_patterns = [
path('folder/<int:part_id>/', google_drive.get_or_create_and_open_folder, name='add-folder'),
]
json_patterns = [
path('mouser-part-match-bom/<int:part_revision_id>/', json_views.MouserPartMatchBOM.as_view(), name='mouser-part-match-bom')
]
urlpatterns = [
path('', include((bom_patterns, 'bom'))),
path('', include('social_django.urls', namespace='social')),
path('google-drive/', include((google_drive_patterns, 'google-drive'))),
<|code_end|>
. Use current file imports:
(from django.conf.urls import include
from django.urls import path
from django.contrib.auth import views as auth_views
from django.contrib import admin
from bom.views import views, json_views
from bom.third_party_apis import google_drive)
and context including class names, function names, or small code snippets from other files:
# Path: bom/views/views.py
# def form_error_messages(form_errors) -> [str]:
# def home(request):
# def organization_create(request):
# def search_help(request):
# def signup(request):
# def bom_signup(request):
# def bom_settings(request, tab_anchor=None):
# def user_meta_edit(request, user_meta_id):
# def part_info(request, part_id, part_revision_id=None):
# def part_export_bom(request, part_id=None, part_revision_id=None, flat=False, sourcing=False, sourcing_detailed=False):
# def upload_bom(request):
# def part_upload_bom(request, part_id):
# def upload_parts_help(request):
# def upload_parts(request):
# def export_part_list(request):
# def create_part(request):
# def part_edit(request, part_id):
# def manage_bom(request, part_id, part_revision_id):
# def part_delete(request, part_id):
# def add_subpart(request, part_id, part_revision_id):
# def remove_subpart(request, part_id, part_revision_id, subpart_id):
# def part_class_edit(request, part_class_id):
# def edit_subpart(request, part_id, part_revision_id, subpart_id):
# def remove_all_subparts(request, part_id, part_revision_id):
# def add_sellerpart(request, manufacturer_part_id):
# def add_manufacturer_part(request, part_id):
# def manufacturer_part_edit(request, manufacturer_part_id):
# def manufacturer_part_delete(request, manufacturer_part_id):
# def sellerpart_edit(request, sellerpart_id):
# def sellerpart_delete(request, sellerpart_id):
# def part_revision_release(request, part_id, part_revision_id):
# def part_revision_revert(request, part_id, part_revision_id):
# def part_revision_new(request, part_id):
# def part_revision_edit(request, part_id, part_revision_id):
# def part_revision_delete(request, part_id, part_revision_id):
# def get_context_data(self, *args, **kwargs):
# USER_TAB = 'user'
# ORGANIZATION_TAB = 'organization'
# INDABOM_TAB = 'indabom'
# class Help(TemplateView):
#
# Path: bom/views/json_views.py
# class BomJsonResponse(View):
# class MouserPartMatchBOM(BomJsonResponse):
# def get(self, request, part_revision_id):
#
# Path: bom/third_party_apis/google_drive.py
# def get_service(user):
# def create_root(user):
# def create_part_folder(user, part):
# def get_files_list(user, part):
# def initialize_parent(backend, user, response, *args, **kwargs):
# def uninitialize_parent(backend, user, *args, **kwargs):
# def get_or_create_and_open_folder(request, part_id):
# def update_folder_name(request, part_id):
. Output only the next line. | path('json/', include((json_patterns, 'json'))), |
Here is a snippet: <|code_start|> path('part/<int:part_id>/rev/<int:part_revision_id>/edit-subpart/<int:subpart_id>', views.edit_subpart, name='part-edit-subpart'),
path('part/<int:part_id>/rev/<int:part_revision_id>/remove-subpart/<int:subpart_id>/', views.remove_subpart, name='part-remove-subpart'),
path('part/<int:part_id>/rev/<int:part_revision_id>/manage-bom/', views.manage_bom, name='part-manage-bom'),
path('part/<int:part_id>/rev/<int:part_revision_id>/add-subpart/', views.add_subpart, name='part-add-subpart'),
path('part-rev/<int:part_revision_id>/export/', views.part_export_bom, name='part-revision-export-bom'),
path('part-rev/<int:part_revision_id>/export-sourcing/', views.part_export_bom, name='part-revision-export-bom-sourcing', kwargs={'sourcing': True}),
path('part-rev/<int:part_revision_id>/export-sourcing-detailed/', views.part_export_bom, name='part-revision-export-bom-sourcing-detailed', kwargs={'sourcing_detailed': True}),
path('part-rev/<int:part_revision_id>/export-flat/', views.part_export_bom, name='part-revision-export-bom-flat', kwargs={'flat': True}),
path('part-rev/<int:part_revision_id>/export-flat-sourcing/', views.part_export_bom, name='part-revision-export-bom-flat-sourcing', kwargs={'flat': True, 'sourcing': True}),
path('part-rev/<int:part_revision_id>/export-flat-sourcing-detailed/', views.part_export_bom, name='part-revision-export-bom-flat-sourcing-detailed', kwargs={'flat': True, 'sourcing_detailed': True}),
path('sellerpart/<int:sellerpart_id>/edit/', views.sellerpart_edit, name='sellerpart-edit'),
path('sellerpart/<int:sellerpart_id>/delete/', views.sellerpart_delete, name='sellerpart-delete'),
path('manufacturer-part/<int:manufacturer_part_id>/add-sellerpart/', views.add_sellerpart, name='manufacturer-part-add-sellerpart'),
path('manufacturer-part/<int:manufacturer_part_id>/edit', views.manufacturer_part_edit, name='manufacturer-part-edit'),
path('manufacturer-part/<int:manufacturer_part_id>/delete', views.manufacturer_part_delete, name='manufacturer-part-delete'),
]
google_drive_patterns = [
path('folder/<int:part_id>/', google_drive.get_or_create_and_open_folder, name='add-folder'),
]
json_patterns = [
path('mouser-part-match-bom/<int:part_revision_id>/', json_views.MouserPartMatchBOM.as_view(), name='mouser-part-match-bom')
]
urlpatterns = [
path('', include((bom_patterns, 'bom'))),
path('', include('social_django.urls', namespace='social')),
<|code_end|>
. Write the next line using the current file imports:
from django.conf.urls import include
from django.urls import path
from django.contrib.auth import views as auth_views
from django.contrib import admin
from bom.views import views, json_views
from bom.third_party_apis import google_drive
and context from other files:
# Path: bom/views/views.py
# def form_error_messages(form_errors) -> [str]:
# def home(request):
# def organization_create(request):
# def search_help(request):
# def signup(request):
# def bom_signup(request):
# def bom_settings(request, tab_anchor=None):
# def user_meta_edit(request, user_meta_id):
# def part_info(request, part_id, part_revision_id=None):
# def part_export_bom(request, part_id=None, part_revision_id=None, flat=False, sourcing=False, sourcing_detailed=False):
# def upload_bom(request):
# def part_upload_bom(request, part_id):
# def upload_parts_help(request):
# def upload_parts(request):
# def export_part_list(request):
# def create_part(request):
# def part_edit(request, part_id):
# def manage_bom(request, part_id, part_revision_id):
# def part_delete(request, part_id):
# def add_subpart(request, part_id, part_revision_id):
# def remove_subpart(request, part_id, part_revision_id, subpart_id):
# def part_class_edit(request, part_class_id):
# def edit_subpart(request, part_id, part_revision_id, subpart_id):
# def remove_all_subparts(request, part_id, part_revision_id):
# def add_sellerpart(request, manufacturer_part_id):
# def add_manufacturer_part(request, part_id):
# def manufacturer_part_edit(request, manufacturer_part_id):
# def manufacturer_part_delete(request, manufacturer_part_id):
# def sellerpart_edit(request, sellerpart_id):
# def sellerpart_delete(request, sellerpart_id):
# def part_revision_release(request, part_id, part_revision_id):
# def part_revision_revert(request, part_id, part_revision_id):
# def part_revision_new(request, part_id):
# def part_revision_edit(request, part_id, part_revision_id):
# def part_revision_delete(request, part_id, part_revision_id):
# def get_context_data(self, *args, **kwargs):
# USER_TAB = 'user'
# ORGANIZATION_TAB = 'organization'
# INDABOM_TAB = 'indabom'
# class Help(TemplateView):
#
# Path: bom/views/json_views.py
# class BomJsonResponse(View):
# class MouserPartMatchBOM(BomJsonResponse):
# def get(self, request, part_revision_id):
#
# Path: bom/third_party_apis/google_drive.py
# def get_service(user):
# def create_root(user):
# def create_part_folder(user, part):
# def get_files_list(user, part):
# def initialize_parent(backend, user, response, *args, **kwargs):
# def uninitialize_parent(backend, user, *args, **kwargs):
# def get_or_create_and_open_folder(request, part_id):
# def update_folder_name(request, part_id):
, which may include functions, classes, or code. Output only the next line. | path('google-drive/', include((google_drive_patterns, 'google-drive'))), |
Given snippet: <|code_start|> return self.get_synoynms(hdr_name)[0] if synonyms is not None else None
# Preserves order of definitions as listed in all_header_defns:
def get_default_all(self):
return [d.name for d in self.all_headers_defns]
# Given a list of header names returns the default name for each. The return list
# matches the order of the input list. If a name is not recognized, then returns
# None as its default:
def get_defaults_list(self, hdr_names):
defaults_list = []
for hdr_name in hdr_names:
defaults_list.append(self.get_default(hdr_name))
return defaults_list
def is_valid(self, hdr_name):
return self.get_synoynms(hdr_name) is not None
def get_val_from_row(self, input_dict, hdr_name):
synonyms = self.get_synoynms(hdr_name)
return get_from_dict(input_dict, synonyms) if synonyms is not None else None
def count_matches(self, header, hdr_name):
c = 0
syns = self.get_synoynms(hdr_name)
if syns is not None:
for h in header:
c += 1 if h in syns else 0
return c
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from abc import ABC
from .utils import get_from_dict
and context:
# Path: bom/utils.py
# def get_from_dict(input_dict, key_options):
# for key in key_options:
# val = input_dict.get(key, None)
# if val:
# return val
# return None
which might include code, classes, or functions. Output only the next line. | def validate_header_names(self, headers): |
Given the code snippet: <|code_start|> 'part_synopsis': self.part_revision.synopsis(),
'part_revision': self.part_revision.revision,
'part_manufacturer': self.part.primary_manufacturer_part.manufacturer.name if self.part.primary_manufacturer_part is not None and self.part.primary_manufacturer_part.manufacturer is not None else '',
'part_manufacturer_part_number': self.part.primary_manufacturer_part.manufacturer_part_number if self.part.primary_manufacturer_part is not None else '',
'part_ext_qty': self.extended_quantity,
'part_order_qty': self.order_quantity,
'part_seller': self.seller_part.seller.name if self.seller_part is not None else '',
'part_cost': self.seller_part.unit_cost if self.seller_part is not None else '',
'part_moq': self.seller_part.minimum_order_quantity if self.seller_part is not None else 0,
'part_nre': self.seller_part.nre_cost if self.seller_part is not None else 0,
'part_ext_cost': self.extended_cost(),
'part_out_of_pocket_cost': self.out_of_pocket_cost(),
'part_lead_time_days': self.seller_part.lead_time_days if self.seller_part is not None else 0,
}
def manufacturer_parts_for_export(self):
return [mp.as_dict_for_export() for mp in self.part.manufacturer_parts(exclude_primary=True)]
def seller_parts_for_export(self):
return [sp.as_dict_for_export() for sp in self.part.seller_parts(exclude_primary=True)]
class PartIndentedBomItem(PartBomItem, AsDictModel):
def __init__(self, indent_level, parent_id, subpart, parent_quantity, *args, **kwargs):
super().__init__(*args, **kwargs)
self.indent_level = indent_level
self.parent_id = parent_id
self.subpart = subpart
self.parent_quantity = parent_quantity
<|code_end|>
, generate the next line using the imports in this file:
from .base_classes import AsDictModel
from collections import OrderedDict
from djmoney.money import Money
import logging
and context (functions, classes, or occasionally code) from other files:
# Path: bom/base_classes.py
# class AsDictModel:
# def as_dict(self):
# try:
# return model_to_dict(self)
# except (TypeError, AttributeError):
# return dict(self)
#
# def __iter__(self):
# for key in dir(self):
# if not key.startswith("_") and not key == "objects":
# value = getattr(self, key)
# if not callable(value):
# if isinstance(value, (dict, OrderedDict)):
# for subkey, subvalue in value.items():
# try:
# value[subkey] = subvalue.as_dict()
# except AttributeError:
# pass
# yield key, value
# else:
# try:
# yield key, value.as_dict()
# except AttributeError:
# if isinstance(value, (int, float, complex, bool)):
# yield key, value
# else:
# yield key, str(value)
. Output only the next line. | def as_dict_for_export(self): |
Here is a snippet: <|code_start|> pr.save()
except ValueError:
pr.searchable_synopsis = pr.description
pr.save()
pass
class Migration(migrations.Migration):
dependencies = [
('bom', '0023_auto_20191205_2351'),
]
operations = [
migrations.AddField(
model_name='partrevision',
name='searchable_synopsis',
field=models.TextField(blank=True, default='', null=True),
),
migrations.AlterField(
model_name='organization',
name='number_item_len',
field=models.PositiveIntegerField(default=3, validators=[django.core.validators.MinValueValidator(3), django.core.validators.MaxValueValidator(10)]),
),
migrations.AlterField(
model_name='partrevision',
name='package',
field=models.CharField(blank=True, choices=[('', '-----'), ('0201 smd', '0201 smd'), ('0402 smd', '0402 smd'), ('0603 smd', '0603 smd'), ('0805 smd', '0805 smd'), ('1206 smd', '1206 smd'),
('1210 smd', '1210 smd'), ('1812 smd', '1812 smd'), ('2010 smd', '2010 smd'), ('2512 smd', '2512 smd'), ('1/8 radial', '1/8 radial'),
('1/4 radial', '1/4 radial'), ('1/2 radial', '1/2 radial'), ('Size A', 'Size A'), ('Size B', 'Size B'), ('Size C', 'Size C'),
('Size D', 'Size D'), ('Size E', 'Size E'), ('SOT-23', 'SOT-23'), ('SOT-223', 'SOT-233'), ('DIL', 'DIL'), ('SOP', 'SOP'), ('SOIC', 'SOIC'),
<|code_end|>
. Write the next line using the current file imports:
from django.db import migrations, models
from bom.utils import strip_trailing_zeros
import django.utils.timezone
and context from other files:
# Path: bom/utils.py
# def strip_trailing_zeros(num):
# found = False
# for c in num:
# if c.isdigit():
# found = True
# elif c not in ['-', '+', '.']:
# found = False
# break
# return ('%f' % float(num)).rstrip('0').rstrip('.') if found else num
, which may include functions, classes, or code. Output only the next line. | ('QFN', 'QFN'), ('QFP', 'QFP'), ('QFT', 'QFT'), ('PLCC', 'PLCC'), ('VGA', 'VGA'), ('Other', 'Other')], default=None, max_length=16, null=True), |
Next line prediction: <|code_start|># -*- coding: utf-8 -*- vim:fileencoding=utf-8:
# Copyright (C) 2010-2014 GRNET S.A.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
urlpatterns = [
url(r'^usergrps/$', views.get_user_group_list, name="usergroups"),
url(r'^(?P<instance>[^/]+)/$', views.notify, name="notify"),
url(r'^archive/(?P<notification>\w+)/$', views.archive, name="notification-details"),
url(r'^$', views.notify, name="notify"),
<|code_end|>
. Use current file imports:
(from django.conf.urls import url
from notifications import views)
and context including class names, function names, or small code snippets from other files:
# Path: notifications/views.py
# def notify(request, instance=None):
# def archive(request, notification):
# def get_user_group_list(request):
. Output only the next line. | ] |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- vim:fileencoding=utf-8:
# Copyright (C) 2010-2014 GRNET S.A.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
class CustomRegistrationView(RegistrationView):
def register(self, form):
new_user = super(RegistrationView, self).register(form)
telephone = form.cleaned_data['phone']
<|code_end|>
, predict the immediate next line with the help of imports:
from registration.backends.admin_approval.views import RegistrationView
from apply.models import Organization
from accounts.models import UserProfile
and context (classes, functions, sometimes code) from other files:
# Path: apply/models.py
# class Organization(models.Model):
# title = models.CharField(max_length=255)
# website = models.CharField(max_length=255, null=True, blank=True)
# email = models.EmailField(null=True, blank=True)
# tag = models.SlugField(max_length=255, null=True, blank=True)
# phone = models.CharField(max_length=255, null=True, blank=True)
# users = models.ManyToManyField(User, blank=True)
#
# class Meta:
# verbose_name = _("organization")
# verbose_name_plural = _("organizations")
# ordering = ["title"]
#
# def __unicode__(self):
# return self.title
#
# Path: accounts/models.py
# class UserProfile(models.Model):
# user = models.OneToOneField(User)
# first_login = models.BooleanField(default=True)
# force_logout_date = models.DateTimeField(null=True, blank=True)
# organization = models.ForeignKey(Organization, blank=True, null=True)
# telephone = models.CharField(max_length=13, blank=True, null=True)
#
# def force_logout(self):
# self.force_logout_date = datetime.datetime.now()
# self.save()
#
# def is_owner(self, instance):
# if self.user in instance.users:
# return True
# else:
# for group in self.user.groups.all():
# if group in instance.groups:
# return True
# return False
#
# def __unicode__(self):
# return "%s profile" % self.user
. Output only the next line. | organization = form.cleaned_data['organization'] |
Based on the snippet: <|code_start|> datetime_now = datetime.datetime.now
class UserProfile(models.Model):
user = models.OneToOneField(User)
first_login = models.BooleanField(default=True)
force_logout_date = models.DateTimeField(null=True, blank=True)
organization = models.ForeignKey(Organization, blank=True, null=True)
telephone = models.CharField(max_length=13, blank=True, null=True)
def force_logout(self):
self.force_logout_date = datetime.datetime.now()
self.save()
def is_owner(self, instance):
if self.user in instance.users:
return True
else:
for group in self.user.groups.all():
if group in instance.groups:
return True
return False
def __unicode__(self):
return "%s profile" % self.user
# Signals
def create_user_profile(sender, instance, created, **kwargs):
if created and not kwargs.get('raw', False):
<|code_end|>
, predict the immediate next line with the help of imports:
import datetime
from apply.models import Organization
from django.contrib.auth.models import User
from django.contrib.auth.signals import user_logged_in
from django.db import models
from django.db.models.signals import post_save
from django.utils.timezone import now as datetime_now
and context (classes, functions, sometimes code) from other files:
# Path: apply/models.py
# class Organization(models.Model):
# title = models.CharField(max_length=255)
# website = models.CharField(max_length=255, null=True, blank=True)
# email = models.EmailField(null=True, blank=True)
# tag = models.SlugField(max_length=255, null=True, blank=True)
# phone = models.CharField(max_length=255, null=True, blank=True)
# users = models.ManyToManyField(User, blank=True)
#
# class Meta:
# verbose_name = _("organization")
# verbose_name_plural = _("organizations")
# ordering = ["title"]
#
# def __unicode__(self):
# return self.title
. Output only the next line. | UserProfile.objects.create(user=instance) |
Predict the next line after this snippet: <|code_start|># This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
urlpatterns = [
url(
r'^register/$',
RegistrationView.as_view(),
name='registration_register'
),
url(
r'^password/reset/$',
auth_views.password_reset,
{
'password_reset_form':
PasswordResetFormPatched,
},
name='password_reset'
),
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
auth_views.password_reset_confirm, name='password_reset_confirm'),
url(r'^reset/done/$', auth_views.password_reset_complete, name='password_reset_complete'),
url(
<|code_end|>
using the current file's imports:
from accounts.forms import PasswordResetFormPatched
from django.conf.urls import url, include
from django.contrib.auth import views as auth_views
from .views import CustomRegistrationView as RegistrationView
and any relevant context from other files:
# Path: accounts/forms.py
# class PasswordResetFormPatched(PasswordResetForm):
# error_messages = {
# 'unknown': _("That e-mail address doesn't have an associated "
# "user account or the account has not been activated yet. Are you sure you've registered?"),
# 'unusable': _("The user account associated with this e-mail "
# "address cannot reset the password."),
# }
#
# Path: accounts/views.py
# class CustomRegistrationView(RegistrationView):
#
# def register(self, form):
#
# new_user = super(RegistrationView, self).register(form)
#
# telephone = form.cleaned_data['phone']
# organization = form.cleaned_data['organization']
#
# profile, created = UserProfile.objects.get_or_create(user=new_user)
# try:
# organization = Organization.objects.get(title=organization)
# profile.organization = organization
# except Organization.DoesNotExist:
# profile.organization = None
#
# profile.telephone = telephone
# profile.user = new_user
# profile.save()
#
# new_user.first_name = form.cleaned_data['name']
# new_user.last_name = form.cleaned_data['surname']
# new_user.save()
#
# return new_user
. Output only the next line. | r'^password_reset/done/$', |
Here is a snippet: <|code_start|># the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
urlpatterns = [
url(
r'^register/$',
RegistrationView.as_view(),
name='registration_register'
),
url(
r'^password/reset/$',
auth_views.password_reset,
{
'password_reset_form':
PasswordResetFormPatched,
},
name='password_reset'
),
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
<|code_end|>
. Write the next line using the current file imports:
from accounts.forms import PasswordResetFormPatched
from django.conf.urls import url, include
from django.contrib.auth import views as auth_views
from .views import CustomRegistrationView as RegistrationView
and context from other files:
# Path: accounts/forms.py
# class PasswordResetFormPatched(PasswordResetForm):
# error_messages = {
# 'unknown': _("That e-mail address doesn't have an associated "
# "user account or the account has not been activated yet. Are you sure you've registered?"),
# 'unusable': _("The user account associated with this e-mail "
# "address cannot reset the password."),
# }
#
# Path: accounts/views.py
# class CustomRegistrationView(RegistrationView):
#
# def register(self, form):
#
# new_user = super(RegistrationView, self).register(form)
#
# telephone = form.cleaned_data['phone']
# organization = form.cleaned_data['organization']
#
# profile, created = UserProfile.objects.get_or_create(user=new_user)
# try:
# organization = Organization.objects.get(title=organization)
# profile.organization = organization
# except Organization.DoesNotExist:
# profile.organization = None
#
# profile.telephone = telephone
# profile.user = new_user
# profile.save()
#
# new_user.first_name = form.cleaned_data['name']
# new_user.last_name = form.cleaned_data['surname']
# new_user.save()
#
# return new_user
, which may include functions, classes, or code. Output only the next line. | auth_views.password_reset_confirm, name='password_reset_confirm'), |
Next line prediction: <|code_start|># -*- coding: utf-8 -*- vim:fileencoding=utf-8:
# Copyright (C) 2010-2014 GRNET S.A.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
urlpatterns = [
url(r'^applications/?', views.stats_ajax_applications, name="stats_ajax_apps"),
url(r'^instances/?', views.stats_ajax_instances, name="stats_ajax_instances"),
url(r'^vms_cluster/(?P<cluster_slug>[^/]+)/?', views.stats_ajax_vms_per_cluster, name="stats_ajax_vms_pc"),
url(r'^$', views.stats, name="stats"),
<|code_end|>
. Use current file imports:
(from django.conf.urls import url
from stats import views)
and context including class names, function names, or small code snippets from other files:
# Path: stats/views.py
# def instance_owners(request):
# def _get_instances(cluster):
# def cmp_users(x, y):
# def stats_ajax_applications(request):
# def stats_ajax_instances(request):
# def stats_ajax_vms_per_cluster(request, cluster_slug):
# def stats(request):
# def _get_instances(cluster):
. Output only the next line. | ] |
Given snippet: <|code_start|># (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
class RegistrationForm(_RegistrationForm):
name = forms.CharField()
surname = forms.CharField()
phone = forms.CharField(required=False)
organization = forms.ModelChoiceField(
queryset=Organization.objects.all(),
required=False,
label=_("Organization")
)
recaptcha = NoReCaptchaField()
class PasswordResetFormPatched(PasswordResetForm):
error_messages = {
'unknown': _("That e-mail address doesn't have an associated "
"user account or the account has not been activated yet. Are you sure you've registered?"),
'unusable': _("The user account associated with this e-mail "
"address cannot reset the password."),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.forms import PasswordResetForm
from registration.forms import RegistrationFormUniqueEmail as _RegistrationForm
from apply.models import Organization
from nocaptcha_recaptcha.fields import NoReCaptchaField
and context:
# Path: apply/models.py
# class Organization(models.Model):
# title = models.CharField(max_length=255)
# website = models.CharField(max_length=255, null=True, blank=True)
# email = models.EmailField(null=True, blank=True)
# tag = models.SlugField(max_length=255, null=True, blank=True)
# phone = models.CharField(max_length=255, null=True, blank=True)
# users = models.ManyToManyField(User, blank=True)
#
# class Meta:
# verbose_name = _("organization")
# verbose_name_plural = _("organizations")
# ordering = ["title"]
#
# def __unicode__(self):
# return self.title
which might include code, classes, or functions. Output only the next line. | } |
Next line prediction: <|code_start|> region = parsed_args.region
if not username:
raise ValueError('Missing required argument: username')
if not api_key:
raise ValueError('Missing required argument: api-key')
kwargs = {}
if api_url is not None:
kwargs['base_url'] = api_url
if region is not None:
kwargs['region'] = region
c = Client(username=username, api_key=api_key, **kwargs)
return c
def format_metadata(metadata_dict):
metadata_str = ''
count = len(metadata_dict)
i = 0
for key, value in metadata_dict.items():
i += 1
metadata_str += '%s: %s' % (key, value)
if i < count:
<|code_end|>
. Use current file imports:
(from datetime import datetime
from service_registry.client import Client
from raxcli.config import get_config as get_base_config
from raxcli.commands import BaseCommand, BaseShowCommand, BaseListCommand
from raxcli.apps.registry.constants import SERVICE_EVENTS)
and context including class names, function names, or small code snippets from other files:
# Path: raxcli/config.py
# def get_config(app, default_values=None, config_path=DEFAULT_CONFIG_PATH,
# env_prefix=DEFAULT_ENV_PREFIX, env_dict=None):
# """
# Return dictionary with configuration values for a provided app.
#
# @param app: Name of the app configuration is being retrieved for.
# @type app: C{str}
#
# @param default_values: Default configuration values.
# @type default_values: C{dict}
#
# @param config_path: Path to the config file.
# @type config_path: C{str}
#
# @param env_prefix: Environment variables prefix.
# @type env_prefix: C{str}
#
# @param env_dict: Dictionary with environment variables. If not provided,
# os.environ is used.
# @type env_dict: C{dict}
#
# @return Configuration values.
# @rtype: C{dict}
# """
# result = {}
#
# if env_dict is None:
# env_dict = os.environ
#
# if default_values is None:
# default_values = {}
#
# keys = [
# ['global', 'username', 'username'],
# ['global', 'api_key', 'api_key'],
# ['global', 'verify_ssl', 'verify_ssl'],
# ['global', 'auth_url', 'auth_url'],
# ]
#
# env_keys = ['username', 'api_key', 'api_url', 'auth_url', 'verify_ssl']
#
# for key in env_keys:
# env_key = env_prefix + key
# env_key = env_key.upper()
#
# if env_key in env_dict:
# result[key] = env_dict[env_key]
#
# config_path = env_dict.get(env_prefix + 'RAXRC', config_path)
#
# config = ConfigParser.ConfigParser()
# config.read(config_path)
#
# for (config_section, config_key, key) in keys:
# if key in result:
# # Already specified as an env variable
# continue
#
# # global section
# try:
# value = config.get(config_section, config_key)
# except ConfigParser.Error:
# pass
# else:
# result[key] = value
#
# # app specific section
# try:
# value = config.get(app, config_key)
# except ConfigParser.Error:
# pass
# else:
# result[key] = value
#
# if 'verify_ssl' in result:
# result['verify_ssl'] = to_bolean(result['verify_ssl'],
# default_value=True)
#
# for key, value in default_values.items():
# if key not in result:
# result[key] = value
#
# return result
#
# Path: raxcli/commands.py
# class BaseCommand(Command):
# def get_parser(self, prog_name):
# parser = super(BaseCommand, self).get_parser(prog_name=prog_name)
# parser.add_argument('--username', dest='username')
# parser.add_argument('--api-key', dest='api_key')
# parser.add_argument('--api-url', dest='api_url')
# parser.add_argument('--json', dest='json_options')
# return parser
#
# class BaseShowCommand(BaseCommand, ShowOne):
# def get_parser(self, prog_name):
# parser = super(BaseShowCommand, self).get_parser(prog_name=prog_name)
# parser.add_argument('--id', dest='object_id', required=True)
# return parser
#
# class BaseListCommand(BaseCommand, Lister):
# def get_parser(self, prog_name):
# parser = super(BaseListCommand, self).get_parser(prog_name=prog_name)
# return parser
#
# @property
# def formatter_default(self):
# return 'paginated_table'
#
# Path: raxcli/apps/registry/constants.py
# SERVICE_EVENTS = ['service.join', 'service.timeout', 'service.remove']
. Output only the next line. | metadata_str += ', ' |
Predict the next line for this snippet: <|code_start|>
kwargs = {}
if api_url is not None:
kwargs['base_url'] = api_url
if region is not None:
kwargs['region'] = region
c = Client(username=username, api_key=api_key, **kwargs)
return c
def format_metadata(metadata_dict):
metadata_str = ''
count = len(metadata_dict)
i = 0
for key, value in metadata_dict.items():
i += 1
metadata_str += '%s: %s' % (key, value)
if i < count:
metadata_str += ', '
return metadata_str
def format_timestamp(timestamp):
if not timestamp:
<|code_end|>
with the help of current file imports:
from datetime import datetime
from service_registry.client import Client
from raxcli.config import get_config as get_base_config
from raxcli.commands import BaseCommand, BaseShowCommand, BaseListCommand
from raxcli.apps.registry.constants import SERVICE_EVENTS
and context from other files:
# Path: raxcli/config.py
# def get_config(app, default_values=None, config_path=DEFAULT_CONFIG_PATH,
# env_prefix=DEFAULT_ENV_PREFIX, env_dict=None):
# """
# Return dictionary with configuration values for a provided app.
#
# @param app: Name of the app configuration is being retrieved for.
# @type app: C{str}
#
# @param default_values: Default configuration values.
# @type default_values: C{dict}
#
# @param config_path: Path to the config file.
# @type config_path: C{str}
#
# @param env_prefix: Environment variables prefix.
# @type env_prefix: C{str}
#
# @param env_dict: Dictionary with environment variables. If not provided,
# os.environ is used.
# @type env_dict: C{dict}
#
# @return Configuration values.
# @rtype: C{dict}
# """
# result = {}
#
# if env_dict is None:
# env_dict = os.environ
#
# if default_values is None:
# default_values = {}
#
# keys = [
# ['global', 'username', 'username'],
# ['global', 'api_key', 'api_key'],
# ['global', 'verify_ssl', 'verify_ssl'],
# ['global', 'auth_url', 'auth_url'],
# ]
#
# env_keys = ['username', 'api_key', 'api_url', 'auth_url', 'verify_ssl']
#
# for key in env_keys:
# env_key = env_prefix + key
# env_key = env_key.upper()
#
# if env_key in env_dict:
# result[key] = env_dict[env_key]
#
# config_path = env_dict.get(env_prefix + 'RAXRC', config_path)
#
# config = ConfigParser.ConfigParser()
# config.read(config_path)
#
# for (config_section, config_key, key) in keys:
# if key in result:
# # Already specified as an env variable
# continue
#
# # global section
# try:
# value = config.get(config_section, config_key)
# except ConfigParser.Error:
# pass
# else:
# result[key] = value
#
# # app specific section
# try:
# value = config.get(app, config_key)
# except ConfigParser.Error:
# pass
# else:
# result[key] = value
#
# if 'verify_ssl' in result:
# result['verify_ssl'] = to_bolean(result['verify_ssl'],
# default_value=True)
#
# for key, value in default_values.items():
# if key not in result:
# result[key] = value
#
# return result
#
# Path: raxcli/commands.py
# class BaseCommand(Command):
# def get_parser(self, prog_name):
# parser = super(BaseCommand, self).get_parser(prog_name=prog_name)
# parser.add_argument('--username', dest='username')
# parser.add_argument('--api-key', dest='api_key')
# parser.add_argument('--api-url', dest='api_url')
# parser.add_argument('--json', dest='json_options')
# return parser
#
# class BaseShowCommand(BaseCommand, ShowOne):
# def get_parser(self, prog_name):
# parser = super(BaseShowCommand, self).get_parser(prog_name=prog_name)
# parser.add_argument('--id', dest='object_id', required=True)
# return parser
#
# class BaseListCommand(BaseCommand, Lister):
# def get_parser(self, prog_name):
# parser = super(BaseListCommand, self).get_parser(prog_name=prog_name)
# return parser
#
# @property
# def formatter_default(self):
# return 'paginated_table'
#
# Path: raxcli/apps/registry/constants.py
# SERVICE_EVENTS = ['service.join', 'service.timeout', 'service.remove']
, which may contain function names, class names, or code. Output only the next line. | return '' |
Predict the next line after this snippet: <|code_start|># Copyright 2013 Rackspace
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__all__ = [
'BaseRegistryCommand',
'BaseRegistryShowCommand',
'BaseRegistryListCommand',
'get_client',
'format_metadata',
<|code_end|>
using the current file's imports:
from datetime import datetime
from service_registry.client import Client
from raxcli.config import get_config as get_base_config
from raxcli.commands import BaseCommand, BaseShowCommand, BaseListCommand
from raxcli.apps.registry.constants import SERVICE_EVENTS
and any relevant context from other files:
# Path: raxcli/config.py
# def get_config(app, default_values=None, config_path=DEFAULT_CONFIG_PATH,
# env_prefix=DEFAULT_ENV_PREFIX, env_dict=None):
# """
# Return dictionary with configuration values for a provided app.
#
# @param app: Name of the app configuration is being retrieved for.
# @type app: C{str}
#
# @param default_values: Default configuration values.
# @type default_values: C{dict}
#
# @param config_path: Path to the config file.
# @type config_path: C{str}
#
# @param env_prefix: Environment variables prefix.
# @type env_prefix: C{str}
#
# @param env_dict: Dictionary with environment variables. If not provided,
# os.environ is used.
# @type env_dict: C{dict}
#
# @return Configuration values.
# @rtype: C{dict}
# """
# result = {}
#
# if env_dict is None:
# env_dict = os.environ
#
# if default_values is None:
# default_values = {}
#
# keys = [
# ['global', 'username', 'username'],
# ['global', 'api_key', 'api_key'],
# ['global', 'verify_ssl', 'verify_ssl'],
# ['global', 'auth_url', 'auth_url'],
# ]
#
# env_keys = ['username', 'api_key', 'api_url', 'auth_url', 'verify_ssl']
#
# for key in env_keys:
# env_key = env_prefix + key
# env_key = env_key.upper()
#
# if env_key in env_dict:
# result[key] = env_dict[env_key]
#
# config_path = env_dict.get(env_prefix + 'RAXRC', config_path)
#
# config = ConfigParser.ConfigParser()
# config.read(config_path)
#
# for (config_section, config_key, key) in keys:
# if key in result:
# # Already specified as an env variable
# continue
#
# # global section
# try:
# value = config.get(config_section, config_key)
# except ConfigParser.Error:
# pass
# else:
# result[key] = value
#
# # app specific section
# try:
# value = config.get(app, config_key)
# except ConfigParser.Error:
# pass
# else:
# result[key] = value
#
# if 'verify_ssl' in result:
# result['verify_ssl'] = to_bolean(result['verify_ssl'],
# default_value=True)
#
# for key, value in default_values.items():
# if key not in result:
# result[key] = value
#
# return result
#
# Path: raxcli/commands.py
# class BaseCommand(Command):
# def get_parser(self, prog_name):
# parser = super(BaseCommand, self).get_parser(prog_name=prog_name)
# parser.add_argument('--username', dest='username')
# parser.add_argument('--api-key', dest='api_key')
# parser.add_argument('--api-url', dest='api_url')
# parser.add_argument('--json', dest='json_options')
# return parser
#
# class BaseShowCommand(BaseCommand, ShowOne):
# def get_parser(self, prog_name):
# parser = super(BaseShowCommand, self).get_parser(prog_name=prog_name)
# parser.add_argument('--id', dest='object_id', required=True)
# return parser
#
# class BaseListCommand(BaseCommand, Lister):
# def get_parser(self, prog_name):
# parser = super(BaseListCommand, self).get_parser(prog_name=prog_name)
# return parser
#
# @property
# def formatter_default(self):
# return 'paginated_table'
#
# Path: raxcli/apps/registry/constants.py
# SERVICE_EVENTS = ['service.join', 'service.timeout', 'service.remove']
. Output only the next line. | 'format_timestamp', |
Continue the code snippet: <|code_start|>
class BaseRegistryShowCommand(BaseRegistryCommand, BaseShowCommand):
pass
class BaseRegistryListCommand(BaseRegistryCommand, BaseListCommand):
def get_parser(self, prog_name):
parser = super(BaseRegistryListCommand, self) \
.get_parser(prog_name=prog_name)
parser.add_argument('--limit', dest='limit')
parser.add_argument('--marker', dest='marker')
return parser
def get_config():
return get_base_config(app='registry')
def get_client(parsed_args):
config = get_config()
username = config['username']
api_key = config['api_key']
if parsed_args.username:
username = parsed_args.username
if parsed_args.api_key:
api_key = parsed_args.api_key
<|code_end|>
. Use current file imports:
from datetime import datetime
from service_registry.client import Client
from raxcli.config import get_config as get_base_config
from raxcli.commands import BaseCommand, BaseShowCommand, BaseListCommand
from raxcli.apps.registry.constants import SERVICE_EVENTS
and context (classes, functions, or code) from other files:
# Path: raxcli/config.py
# def get_config(app, default_values=None, config_path=DEFAULT_CONFIG_PATH,
# env_prefix=DEFAULT_ENV_PREFIX, env_dict=None):
# """
# Return dictionary with configuration values for a provided app.
#
# @param app: Name of the app configuration is being retrieved for.
# @type app: C{str}
#
# @param default_values: Default configuration values.
# @type default_values: C{dict}
#
# @param config_path: Path to the config file.
# @type config_path: C{str}
#
# @param env_prefix: Environment variables prefix.
# @type env_prefix: C{str}
#
# @param env_dict: Dictionary with environment variables. If not provided,
# os.environ is used.
# @type env_dict: C{dict}
#
# @return Configuration values.
# @rtype: C{dict}
# """
# result = {}
#
# if env_dict is None:
# env_dict = os.environ
#
# if default_values is None:
# default_values = {}
#
# keys = [
# ['global', 'username', 'username'],
# ['global', 'api_key', 'api_key'],
# ['global', 'verify_ssl', 'verify_ssl'],
# ['global', 'auth_url', 'auth_url'],
# ]
#
# env_keys = ['username', 'api_key', 'api_url', 'auth_url', 'verify_ssl']
#
# for key in env_keys:
# env_key = env_prefix + key
# env_key = env_key.upper()
#
# if env_key in env_dict:
# result[key] = env_dict[env_key]
#
# config_path = env_dict.get(env_prefix + 'RAXRC', config_path)
#
# config = ConfigParser.ConfigParser()
# config.read(config_path)
#
# for (config_section, config_key, key) in keys:
# if key in result:
# # Already specified as an env variable
# continue
#
# # global section
# try:
# value = config.get(config_section, config_key)
# except ConfigParser.Error:
# pass
# else:
# result[key] = value
#
# # app specific section
# try:
# value = config.get(app, config_key)
# except ConfigParser.Error:
# pass
# else:
# result[key] = value
#
# if 'verify_ssl' in result:
# result['verify_ssl'] = to_bolean(result['verify_ssl'],
# default_value=True)
#
# for key, value in default_values.items():
# if key not in result:
# result[key] = value
#
# return result
#
# Path: raxcli/commands.py
# class BaseCommand(Command):
# def get_parser(self, prog_name):
# parser = super(BaseCommand, self).get_parser(prog_name=prog_name)
# parser.add_argument('--username', dest='username')
# parser.add_argument('--api-key', dest='api_key')
# parser.add_argument('--api-url', dest='api_url')
# parser.add_argument('--json', dest='json_options')
# return parser
#
# class BaseShowCommand(BaseCommand, ShowOne):
# def get_parser(self, prog_name):
# parser = super(BaseShowCommand, self).get_parser(prog_name=prog_name)
# parser.add_argument('--id', dest='object_id', required=True)
# return parser
#
# class BaseListCommand(BaseCommand, Lister):
# def get_parser(self, prog_name):
# parser = super(BaseListCommand, self).get_parser(prog_name=prog_name)
# return parser
#
# @property
# def formatter_default(self):
# return 'paginated_table'
#
# Path: raxcli/apps/registry/constants.py
# SERVICE_EVENTS = ['service.join', 'service.timeout', 'service.remove']
. Output only the next line. | api_url = parsed_args.api_url |
Given the code snippet: <|code_start|> api_url = parsed_args.api_url
region = parsed_args.region
if not username:
raise ValueError('Missing required argument: username')
if not api_key:
raise ValueError('Missing required argument: api-key')
kwargs = {}
if api_url is not None:
kwargs['base_url'] = api_url
if region is not None:
kwargs['region'] = region
c = Client(username=username, api_key=api_key, **kwargs)
return c
def format_metadata(metadata_dict):
metadata_str = ''
count = len(metadata_dict)
i = 0
for key, value in metadata_dict.items():
i += 1
metadata_str += '%s: %s' % (key, value)
<|code_end|>
, generate the next line using the imports in this file:
from datetime import datetime
from service_registry.client import Client
from raxcli.config import get_config as get_base_config
from raxcli.commands import BaseCommand, BaseShowCommand, BaseListCommand
from raxcli.apps.registry.constants import SERVICE_EVENTS
and context (functions, classes, or occasionally code) from other files:
# Path: raxcli/config.py
# def get_config(app, default_values=None, config_path=DEFAULT_CONFIG_PATH,
# env_prefix=DEFAULT_ENV_PREFIX, env_dict=None):
# """
# Return dictionary with configuration values for a provided app.
#
# @param app: Name of the app configuration is being retrieved for.
# @type app: C{str}
#
# @param default_values: Default configuration values.
# @type default_values: C{dict}
#
# @param config_path: Path to the config file.
# @type config_path: C{str}
#
# @param env_prefix: Environment variables prefix.
# @type env_prefix: C{str}
#
# @param env_dict: Dictionary with environment variables. If not provided,
# os.environ is used.
# @type env_dict: C{dict}
#
# @return Configuration values.
# @rtype: C{dict}
# """
# result = {}
#
# if env_dict is None:
# env_dict = os.environ
#
# if default_values is None:
# default_values = {}
#
# keys = [
# ['global', 'username', 'username'],
# ['global', 'api_key', 'api_key'],
# ['global', 'verify_ssl', 'verify_ssl'],
# ['global', 'auth_url', 'auth_url'],
# ]
#
# env_keys = ['username', 'api_key', 'api_url', 'auth_url', 'verify_ssl']
#
# for key in env_keys:
# env_key = env_prefix + key
# env_key = env_key.upper()
#
# if env_key in env_dict:
# result[key] = env_dict[env_key]
#
# config_path = env_dict.get(env_prefix + 'RAXRC', config_path)
#
# config = ConfigParser.ConfigParser()
# config.read(config_path)
#
# for (config_section, config_key, key) in keys:
# if key in result:
# # Already specified as an env variable
# continue
#
# # global section
# try:
# value = config.get(config_section, config_key)
# except ConfigParser.Error:
# pass
# else:
# result[key] = value
#
# # app specific section
# try:
# value = config.get(app, config_key)
# except ConfigParser.Error:
# pass
# else:
# result[key] = value
#
# if 'verify_ssl' in result:
# result['verify_ssl'] = to_bolean(result['verify_ssl'],
# default_value=True)
#
# for key, value in default_values.items():
# if key not in result:
# result[key] = value
#
# return result
#
# Path: raxcli/commands.py
# class BaseCommand(Command):
# def get_parser(self, prog_name):
# parser = super(BaseCommand, self).get_parser(prog_name=prog_name)
# parser.add_argument('--username', dest='username')
# parser.add_argument('--api-key', dest='api_key')
# parser.add_argument('--api-url', dest='api_url')
# parser.add_argument('--json', dest='json_options')
# return parser
#
# class BaseShowCommand(BaseCommand, ShowOne):
# def get_parser(self, prog_name):
# parser = super(BaseShowCommand, self).get_parser(prog_name=prog_name)
# parser.add_argument('--id', dest='object_id', required=True)
# return parser
#
# class BaseListCommand(BaseCommand, Lister):
# def get_parser(self, prog_name):
# parser = super(BaseListCommand, self).get_parser(prog_name=prog_name)
# return parser
#
# @property
# def formatter_default(self):
# return 'paginated_table'
#
# Path: raxcli/apps/registry/constants.py
# SERVICE_EVENTS = ['service.join', 'service.timeout', 'service.remove']
. Output only the next line. | if i < count: |
Predict the next line for this snippet: <|code_start|>class TestUtils(unittest.TestCase):
def test_get_enum_as_dict(self):
class EnumClass1(object):
KEY1 = 0
KEY_TWO_TWO = 1
SOME_KEY_SOME_SOME = 2
result1 = get_enum_as_dict(EnumClass1, friendly_names=False)
result2 = get_enum_as_dict(EnumClass1, friendly_names=True)
result1_reversed = get_enum_as_dict(EnumClass1, reverse=True,
friendly_names=False)
expected1 = {
'KEY1': 0,
'KEY_TWO_TWO': 1,
'SOME_KEY_SOME_SOME': 2
}
expected2 = {
'Key1': 0,
'Key Two Two': 1,
'Some Key Some Some': 2
}
expected3 = {
0: 'KEY1',
1: 'KEY_TWO_TWO',
2: 'SOME_KEY_SOME_SOME'
}
self.assertDictEqual(result1, expected1)
<|code_end|>
with the help of current file imports:
import sys
import unittest2 as unittest
from raxcli.utils import get_enum_as_dict
and context from other files:
# Path: raxcli/utils.py
# def get_enum_as_dict(cls, reverse=False, friendly_names=False):
# """
# Convert an "enum" class to a dict key is the enum name and value is an enum
# value.
#
# @param cls: Enum class to operate on.
# @type cls: C{class}
#
# @param reverse: True to reverse the key and value so the dict key will be
# enum value and the dict value will be enum key.
# @type reverse: C{bool}
#
# @param friendly_names: True to make enum name value "user friendly".
# @type friendly_names: C{bool}
# """
# result = {}
# for key, value in cls.__dict__.items():
# if key.startswith('__'):
# continue
#
# if key[0] != key[0].upper():
# continue
#
# name = key
#
# if friendly_names:
# name = name.replace('_', ' ').lower().title()
#
# if reverse:
# result[value] = name
# else:
# result[name] = value
#
# return result
, which may contain function names, class names, or code. Output only the next line. | self.assertDictEqual(result2, expected2) |
Given the following code snippet before the placeholder: <|code_start|> config = get_config(app=None, config_path=path1)
self.assertEqual(config['username'], 'username1')
self.assertEqual(config['api_key'], 'api_key1')
self.assertEqual(config['verify_ssl'], True)
self.assertEqual(config['auth_url'], 'http://www.foo.com/1')
def test_config_from_file_global_section_2(self):
path1 = os.path.join(FIXTURES_DIR, 'config2.ini')
config = get_config(app=None, config_path=path1)
self.assertEqual(config['username'], 'username2')
self.assertEqual(config['api_key'], 'api_key2')
self.assertEqual(config['verify_ssl'], False)
self.assertEqual(config['auth_url'], 'http://www.foo.com/2')
def test_from_file_global_with_app_section_precedence(self):
path1 = os.path.join(FIXTURES_DIR, 'config3.ini')
config = get_config(app='registry', config_path=path1)
self.assertEqual(config['username'], 'username_registry')
self.assertEqual(config['api_key'], 'api_key_registry')
self.assertEqual(config['verify_ssl'], True)
self.assertEqual(config['auth_url'], 'http://www.foo.com/2')
def test_config_from_file_only_app_section(self):
path1 = os.path.join(FIXTURES_DIR, 'config4.ini')
config = get_config(app='monitoring', config_path=path1)
<|code_end|>
, predict the next line using imports from the current file:
import os
import sys
import unittest2 as unittest
from os.path import join as pjoin
from raxcli.config import get_config, DEFAULT_ENV_PREFIX
and context including class names, function names, and sometimes code from other files:
# Path: raxcli/config.py
# def get_config(app, default_values=None, config_path=DEFAULT_CONFIG_PATH,
# env_prefix=DEFAULT_ENV_PREFIX, env_dict=None):
# """
# Return dictionary with configuration values for a provided app.
#
# @param app: Name of the app configuration is being retrieved for.
# @type app: C{str}
#
# @param default_values: Default configuration values.
# @type default_values: C{dict}
#
# @param config_path: Path to the config file.
# @type config_path: C{str}
#
# @param env_prefix: Environment variables prefix.
# @type env_prefix: C{str}
#
# @param env_dict: Dictionary with environment variables. If not provided,
# os.environ is used.
# @type env_dict: C{dict}
#
# @return Configuration values.
# @rtype: C{dict}
# """
# result = {}
#
# if env_dict is None:
# env_dict = os.environ
#
# if default_values is None:
# default_values = {}
#
# keys = [
# ['global', 'username', 'username'],
# ['global', 'api_key', 'api_key'],
# ['global', 'verify_ssl', 'verify_ssl'],
# ['global', 'auth_url', 'auth_url'],
# ]
#
# env_keys = ['username', 'api_key', 'api_url', 'auth_url', 'verify_ssl']
#
# for key in env_keys:
# env_key = env_prefix + key
# env_key = env_key.upper()
#
# if env_key in env_dict:
# result[key] = env_dict[env_key]
#
# config_path = env_dict.get(env_prefix + 'RAXRC', config_path)
#
# config = ConfigParser.ConfigParser()
# config.read(config_path)
#
# for (config_section, config_key, key) in keys:
# if key in result:
# # Already specified as an env variable
# continue
#
# # global section
# try:
# value = config.get(config_section, config_key)
# except ConfigParser.Error:
# pass
# else:
# result[key] = value
#
# # app specific section
# try:
# value = config.get(app, config_key)
# except ConfigParser.Error:
# pass
# else:
# result[key] = value
#
# if 'verify_ssl' in result:
# result['verify_ssl'] = to_bolean(result['verify_ssl'],
# default_value=True)
#
# for key, value in default_values.items():
# if key not in result:
# result[key] = value
#
# return result
#
# DEFAULT_ENV_PREFIX = 'RAXCLI_'
. Output only the next line. | self.assertEqual(config['username'], 'username_mon') |
Predict the next line after this snippet: <|code_start|># the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
FIXTURES_DIR = pjoin(os.path.dirname(os.path.abspath(__file__)), 'fixtures/')
class TestConfigParsing(unittest.TestCase):
def test_config_from_file_global_section_1(self):
path1 = os.path.join(FIXTURES_DIR, 'config1.ini')
config = get_config(app=None, config_path=path1)
self.assertEqual(config['username'], 'username1')
self.assertEqual(config['api_key'], 'api_key1')
self.assertEqual(config['verify_ssl'], True)
self.assertEqual(config['auth_url'], 'http://www.foo.com/1')
def test_config_from_file_global_section_2(self):
path1 = os.path.join(FIXTURES_DIR, 'config2.ini')
config = get_config(app=None, config_path=path1)
<|code_end|>
using the current file's imports:
import os
import sys
import unittest2 as unittest
from os.path import join as pjoin
from raxcli.config import get_config, DEFAULT_ENV_PREFIX
and any relevant context from other files:
# Path: raxcli/config.py
# def get_config(app, default_values=None, config_path=DEFAULT_CONFIG_PATH,
# env_prefix=DEFAULT_ENV_PREFIX, env_dict=None):
# """
# Return dictionary with configuration values for a provided app.
#
# @param app: Name of the app configuration is being retrieved for.
# @type app: C{str}
#
# @param default_values: Default configuration values.
# @type default_values: C{dict}
#
# @param config_path: Path to the config file.
# @type config_path: C{str}
#
# @param env_prefix: Environment variables prefix.
# @type env_prefix: C{str}
#
# @param env_dict: Dictionary with environment variables. If not provided,
# os.environ is used.
# @type env_dict: C{dict}
#
# @return Configuration values.
# @rtype: C{dict}
# """
# result = {}
#
# if env_dict is None:
# env_dict = os.environ
#
# if default_values is None:
# default_values = {}
#
# keys = [
# ['global', 'username', 'username'],
# ['global', 'api_key', 'api_key'],
# ['global', 'verify_ssl', 'verify_ssl'],
# ['global', 'auth_url', 'auth_url'],
# ]
#
# env_keys = ['username', 'api_key', 'api_url', 'auth_url', 'verify_ssl']
#
# for key in env_keys:
# env_key = env_prefix + key
# env_key = env_key.upper()
#
# if env_key in env_dict:
# result[key] = env_dict[env_key]
#
# config_path = env_dict.get(env_prefix + 'RAXRC', config_path)
#
# config = ConfigParser.ConfigParser()
# config.read(config_path)
#
# for (config_section, config_key, key) in keys:
# if key in result:
# # Already specified as an env variable
# continue
#
# # global section
# try:
# value = config.get(config_section, config_key)
# except ConfigParser.Error:
# pass
# else:
# result[key] = value
#
# # app specific section
# try:
# value = config.get(app, config_key)
# except ConfigParser.Error:
# pass
# else:
# result[key] = value
#
# if 'verify_ssl' in result:
# result['verify_ssl'] = to_bolean(result['verify_ssl'],
# default_value=True)
#
# for key, value in default_values.items():
# if key not in result:
# result[key] = value
#
# return result
#
# DEFAULT_ENV_PREFIX = 'RAXCLI_'
. Output only the next line. | self.assertEqual(config['username'], 'username2') |
Here is a snippet: <|code_start|># Copyright 2013 Rackspace
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__all__ = [
'Balancer',
'Member',
'Algorithm'
]
STATES = get_enum_as_dict(State, reverse=True)
<|code_end|>
. Write the next line using the current file imports:
from libcloud.loadbalancer.types import State
from raxcli.utils import get_enum_as_dict
from raxcli.models import Attribute, Model
and context from other files:
# Path: raxcli/utils.py
# def get_enum_as_dict(cls, reverse=False, friendly_names=False):
# """
# Convert an "enum" class to a dict key is the enum name and value is an enum
# value.
#
# @param cls: Enum class to operate on.
# @type cls: C{class}
#
# @param reverse: True to reverse the key and value so the dict key will be
# enum value and the dict value will be enum key.
# @type reverse: C{bool}
#
# @param friendly_names: True to make enum name value "user friendly".
# @type friendly_names: C{bool}
# """
# result = {}
# for key, value in cls.__dict__.items():
# if key.startswith('__'):
# continue
#
# if key[0] != key[0].upper():
# continue
#
# name = key
#
# if friendly_names:
# name = name.replace('_', ' ').lower().title()
#
# if reverse:
# result[value] = name
# else:
# result[name] = value
#
# return result
#
# Path: raxcli/models.py
# class Attribute(object):
# """
# Generic attribute that represents a field on a resource.
# """
# _creation_count = 0
#
# def __init__(self, src=None, transform_func=None, view_single=True,
# view_list=True):
# """
# @keyword src: Optional name of the field on the object which acts as a
# source for this attribute.
# @keyword src: C{str}
# """
# self.src = src
# self.transform_func = transform_func
# self.view_single = view_single
# self.view_list = view_list
#
# # Keep a count that is incremented on instantiation so we can iterate
# # in the same order that attributes are delcared on an Object.
# self._creation_count = Attribute._creation_count + 1
# Attribute._creation_count = self._creation_count
#
# def get_value(self):
# if self.transform_func:
# return self.transform_func(self.value)
# else:
# return self.value
#
# class Model(object):
# """
# Generic object that allows you to declaratively define how resources
# should be presented.
# """
# def get_attrs(self, view_type=None):
# """
# Get model attributes for the provided view_type.
# """
# attrs = []
# for attr, _ in getmembers(self):
# field = getattr(self, attr)
#
# if not isinstance(field, Attribute):
# continue
#
# if not view_type or getattr(field, view_type):
# src = field.src if field.src else attr
# attrs.append((field._creation_count, [attr, src]))
#
# return [attr for field, attr in sorted(attrs, key=itemgetter(0))]
#
# def __init__(self, obj):
# self._obj_type = 'dict' if isinstance(obj, dict) else 'cls'
#
# for name, source in self.get_attrs():
# field = getattr(self, name)
#
# if self._obj_type == 'dict':
# field.value = obj[source]
# elif self._obj_type == 'cls':
# field.value = getattr(obj, source)
#
# setattr(self, name, copy.copy(field))
#
# def generate_output(self):
# columns = [attr for attr, _ in self.get_attrs(view_type='view_single')]
# data = [getattr(self, attr).get_value() for attr in columns]
# return (columns, data)
, which may include functions, classes, or code. Output only the next line. | def state_to_string(value): |
Using the snippet: <|code_start|> 'Algorithm'
]
STATES = get_enum_as_dict(State, reverse=True)
def state_to_string(value):
return STATES[value]
class Balancer(Model):
id = Attribute()
name = Attribute()
state = Attribute(transform_func=state_to_string)
ip = Attribute()
port = Attribute()
class Member(Model):
id = Attribute()
ip = Attribute()
port = Attribute()
class Algorithm(Model):
id = Attribute()
algorithm = Attribute()
<|code_end|>
, determine the next line of code. You have imports:
from libcloud.loadbalancer.types import State
from raxcli.utils import get_enum_as_dict
from raxcli.models import Attribute, Model
and context (class names, function names, or code) available:
# Path: raxcli/utils.py
# def get_enum_as_dict(cls, reverse=False, friendly_names=False):
# """
# Convert an "enum" class to a dict key is the enum name and value is an enum
# value.
#
# @param cls: Enum class to operate on.
# @type cls: C{class}
#
# @param reverse: True to reverse the key and value so the dict key will be
# enum value and the dict value will be enum key.
# @type reverse: C{bool}
#
# @param friendly_names: True to make enum name value "user friendly".
# @type friendly_names: C{bool}
# """
# result = {}
# for key, value in cls.__dict__.items():
# if key.startswith('__'):
# continue
#
# if key[0] != key[0].upper():
# continue
#
# name = key
#
# if friendly_names:
# name = name.replace('_', ' ').lower().title()
#
# if reverse:
# result[value] = name
# else:
# result[name] = value
#
# return result
#
# Path: raxcli/models.py
# class Attribute(object):
# """
# Generic attribute that represents a field on a resource.
# """
# _creation_count = 0
#
# def __init__(self, src=None, transform_func=None, view_single=True,
# view_list=True):
# """
# @keyword src: Optional name of the field on the object which acts as a
# source for this attribute.
# @keyword src: C{str}
# """
# self.src = src
# self.transform_func = transform_func
# self.view_single = view_single
# self.view_list = view_list
#
# # Keep a count that is incremented on instantiation so we can iterate
# # in the same order that attributes are delcared on an Object.
# self._creation_count = Attribute._creation_count + 1
# Attribute._creation_count = self._creation_count
#
# def get_value(self):
# if self.transform_func:
# return self.transform_func(self.value)
# else:
# return self.value
#
# class Model(object):
# """
# Generic object that allows you to declaratively define how resources
# should be presented.
# """
# def get_attrs(self, view_type=None):
# """
# Get model attributes for the provided view_type.
# """
# attrs = []
# for attr, _ in getmembers(self):
# field = getattr(self, attr)
#
# if not isinstance(field, Attribute):
# continue
#
# if not view_type or getattr(field, view_type):
# src = field.src if field.src else attr
# attrs.append((field._creation_count, [attr, src]))
#
# return [attr for field, attr in sorted(attrs, key=itemgetter(0))]
#
# def __init__(self, obj):
# self._obj_type = 'dict' if isinstance(obj, dict) else 'cls'
#
# for name, source in self.get_attrs():
# field = getattr(self, name)
#
# if self._obj_type == 'dict':
# field.value = obj[source]
# elif self._obj_type == 'cls':
# field.value = getattr(obj, source)
#
# setattr(self, name, copy.copy(field))
#
# def generate_output(self):
# columns = [attr for attr, _ in self.get_attrs(view_type='view_single')]
# data = [getattr(self, attr).get_value() for attr in columns]
# return (columns, data)
. Output only the next line. | def __cmp__(self, other): |
Continue the code snippet: <|code_start|># Copyright 2013 Rackspace
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__all__ = [
'Balancer',
'Member',
<|code_end|>
. Use current file imports:
from libcloud.loadbalancer.types import State
from raxcli.utils import get_enum_as_dict
from raxcli.models import Attribute, Model
and context (classes, functions, or code) from other files:
# Path: raxcli/utils.py
# def get_enum_as_dict(cls, reverse=False, friendly_names=False):
# """
# Convert an "enum" class to a dict key is the enum name and value is an enum
# value.
#
# @param cls: Enum class to operate on.
# @type cls: C{class}
#
# @param reverse: True to reverse the key and value so the dict key will be
# enum value and the dict value will be enum key.
# @type reverse: C{bool}
#
# @param friendly_names: True to make enum name value "user friendly".
# @type friendly_names: C{bool}
# """
# result = {}
# for key, value in cls.__dict__.items():
# if key.startswith('__'):
# continue
#
# if key[0] != key[0].upper():
# continue
#
# name = key
#
# if friendly_names:
# name = name.replace('_', ' ').lower().title()
#
# if reverse:
# result[value] = name
# else:
# result[name] = value
#
# return result
#
# Path: raxcli/models.py
# class Attribute(object):
# """
# Generic attribute that represents a field on a resource.
# """
# _creation_count = 0
#
# def __init__(self, src=None, transform_func=None, view_single=True,
# view_list=True):
# """
# @keyword src: Optional name of the field on the object which acts as a
# source for this attribute.
# @keyword src: C{str}
# """
# self.src = src
# self.transform_func = transform_func
# self.view_single = view_single
# self.view_list = view_list
#
# # Keep a count that is incremented on instantiation so we can iterate
# # in the same order that attributes are delcared on an Object.
# self._creation_count = Attribute._creation_count + 1
# Attribute._creation_count = self._creation_count
#
# def get_value(self):
# if self.transform_func:
# return self.transform_func(self.value)
# else:
# return self.value
#
# class Model(object):
# """
# Generic object that allows you to declaratively define how resources
# should be presented.
# """
# def get_attrs(self, view_type=None):
# """
# Get model attributes for the provided view_type.
# """
# attrs = []
# for attr, _ in getmembers(self):
# field = getattr(self, attr)
#
# if not isinstance(field, Attribute):
# continue
#
# if not view_type or getattr(field, view_type):
# src = field.src if field.src else attr
# attrs.append((field._creation_count, [attr, src]))
#
# return [attr for field, attr in sorted(attrs, key=itemgetter(0))]
#
# def __init__(self, obj):
# self._obj_type = 'dict' if isinstance(obj, dict) else 'cls'
#
# for name, source in self.get_attrs():
# field = getattr(self, name)
#
# if self._obj_type == 'dict':
# field.value = obj[source]
# elif self._obj_type == 'cls':
# field.value = getattr(obj, source)
#
# setattr(self, name, copy.copy(field))
#
# def generate_output(self):
# columns = [attr for attr, _ in self.get_attrs(view_type='view_single')]
# data = [getattr(self, attr).get_value() for attr in columns]
# return (columns, data)
. Output only the next line. | 'Algorithm' |
Given the following code snippet before the placeholder: <|code_start|>class FakeEntity1(object):
key = 'key1'
ip = '127.0.0.1'
label = 'test label'
state = 'unknown1'
class FakeEntity2(object):
key = 'key2'
ip = '127.0.0.1'
label = 'label2'
state = 'unknown2'
class TestModels(unittest.TestCase):
def test_generate_output(self):
en1 = Entity(FakeEntity1())
en2 = Entity(FakeEntity2())
collection = Collection([en1, en2])
result1 = en1.generate_output()
expected1 = (
['id', 'label', 'state'],
['key1', 'test label', 'unknown1-foo']
)
result2 = collection.generate_output()
expected2 = (
['id', 'label', 'state'],
<|code_end|>
, predict the next line using imports from the current file:
import sys
import unittest2 as unittest
from raxcli.models import Attribute, Model, Collection
and context including class names, function names, and sometimes code from other files:
# Path: raxcli/models.py
# class Attribute(object):
# """
# Generic attribute that represents a field on a resource.
# """
# _creation_count = 0
#
# def __init__(self, src=None, transform_func=None, view_single=True,
# view_list=True):
# """
# @keyword src: Optional name of the field on the object which acts as a
# source for this attribute.
# @keyword src: C{str}
# """
# self.src = src
# self.transform_func = transform_func
# self.view_single = view_single
# self.view_list = view_list
#
# # Keep a count that is incremented on instantiation so we can iterate
# # in the same order that attributes are delcared on an Object.
# self._creation_count = Attribute._creation_count + 1
# Attribute._creation_count = self._creation_count
#
# def get_value(self):
# if self.transform_func:
# return self.transform_func(self.value)
# else:
# return self.value
#
# class Model(object):
# """
# Generic object that allows you to declaratively define how resources
# should be presented.
# """
# def get_attrs(self, view_type=None):
# """
# Get model attributes for the provided view_type.
# """
# attrs = []
# for attr, _ in getmembers(self):
# field = getattr(self, attr)
#
# if not isinstance(field, Attribute):
# continue
#
# if not view_type or getattr(field, view_type):
# src = field.src if field.src else attr
# attrs.append((field._creation_count, [attr, src]))
#
# return [attr for field, attr in sorted(attrs, key=itemgetter(0))]
#
# def __init__(self, obj):
# self._obj_type = 'dict' if isinstance(obj, dict) else 'cls'
#
# for name, source in self.get_attrs():
# field = getattr(self, name)
#
# if self._obj_type == 'dict':
# field.value = obj[source]
# elif self._obj_type == 'cls':
# field.value = getattr(obj, source)
#
# setattr(self, name, copy.copy(field))
#
# def generate_output(self):
# columns = [attr for attr, _ in self.get_attrs(view_type='view_single')]
# data = [getattr(self, attr).get_value() for attr in columns]
# return (columns, data)
#
# class Collection(object):
# """
# A collection of resources for outputting to a list.
# """
# def __init__(self, objs):
# self.objs = objs
#
# def generate_output(self):
# columns = []
# data = []
# for obj in self.objs:
# if not columns:
# columns = [attr for attr, _ in
# obj.get_attrs(view_type='view_list')]
#
# values = []
# for key in columns:
# attr = getattr(obj, key)
# value = attr.get_value()
# values.append(value)
#
# data.append(values)
#
# return (columns, data)
. Output only the next line. | [ |
Continue the code snippet: <|code_start|> state = 'unknown2'
class TestModels(unittest.TestCase):
def test_generate_output(self):
en1 = Entity(FakeEntity1())
en2 = Entity(FakeEntity2())
collection = Collection([en1, en2])
result1 = en1.generate_output()
expected1 = (
['id', 'label', 'state'],
['key1', 'test label', 'unknown1-foo']
)
result2 = collection.generate_output()
expected2 = (
['id', 'label', 'state'],
[
['key1', 'test label', 'unknown1-foo'],
['key2', 'label2', 'unknown2-foo']
]
)
self.assertSequenceEqual(result1, expected1)
self.assertSequenceEqual(result2, expected2)
if __name__ == '__main__':
<|code_end|>
. Use current file imports:
import sys
import unittest2 as unittest
from raxcli.models import Attribute, Model, Collection
and context (classes, functions, or code) from other files:
# Path: raxcli/models.py
# class Attribute(object):
# """
# Generic attribute that represents a field on a resource.
# """
# _creation_count = 0
#
# def __init__(self, src=None, transform_func=None, view_single=True,
# view_list=True):
# """
# @keyword src: Optional name of the field on the object which acts as a
# source for this attribute.
# @keyword src: C{str}
# """
# self.src = src
# self.transform_func = transform_func
# self.view_single = view_single
# self.view_list = view_list
#
# # Keep a count that is incremented on instantiation so we can iterate
# # in the same order that attributes are delcared on an Object.
# self._creation_count = Attribute._creation_count + 1
# Attribute._creation_count = self._creation_count
#
# def get_value(self):
# if self.transform_func:
# return self.transform_func(self.value)
# else:
# return self.value
#
# class Model(object):
# """
# Generic object that allows you to declaratively define how resources
# should be presented.
# """
# def get_attrs(self, view_type=None):
# """
# Get model attributes for the provided view_type.
# """
# attrs = []
# for attr, _ in getmembers(self):
# field = getattr(self, attr)
#
# if not isinstance(field, Attribute):
# continue
#
# if not view_type or getattr(field, view_type):
# src = field.src if field.src else attr
# attrs.append((field._creation_count, [attr, src]))
#
# return [attr for field, attr in sorted(attrs, key=itemgetter(0))]
#
# def __init__(self, obj):
# self._obj_type = 'dict' if isinstance(obj, dict) else 'cls'
#
# for name, source in self.get_attrs():
# field = getattr(self, name)
#
# if self._obj_type == 'dict':
# field.value = obj[source]
# elif self._obj_type == 'cls':
# field.value = getattr(obj, source)
#
# setattr(self, name, copy.copy(field))
#
# def generate_output(self):
# columns = [attr for attr, _ in self.get_attrs(view_type='view_single')]
# data = [getattr(self, attr).get_value() for attr in columns]
# return (columns, data)
#
# class Collection(object):
# """
# A collection of resources for outputting to a list.
# """
# def __init__(self, objs):
# self.objs = objs
#
# def generate_output(self):
# columns = []
# data = []
# for obj in self.objs:
# if not columns:
# columns = [attr for attr, _ in
# obj.get_attrs(view_type='view_list')]
#
# values = []
# for key in columns:
# attr = getattr(obj, key)
# value = attr.get_value()
# values.append(value)
#
# data.append(values)
#
# return (columns, data)
. Output only the next line. | sys.exit(unittest.main()) |
Given the following code snippet before the placeholder: <|code_start|> state = 'unknown2'
class TestModels(unittest.TestCase):
def test_generate_output(self):
en1 = Entity(FakeEntity1())
en2 = Entity(FakeEntity2())
collection = Collection([en1, en2])
result1 = en1.generate_output()
expected1 = (
['id', 'label', 'state'],
['key1', 'test label', 'unknown1-foo']
)
result2 = collection.generate_output()
expected2 = (
['id', 'label', 'state'],
[
['key1', 'test label', 'unknown1-foo'],
['key2', 'label2', 'unknown2-foo']
]
)
self.assertSequenceEqual(result1, expected1)
self.assertSequenceEqual(result2, expected2)
if __name__ == '__main__':
<|code_end|>
, predict the next line using imports from the current file:
import sys
import unittest2 as unittest
from raxcli.models import Attribute, Model, Collection
and context including class names, function names, and sometimes code from other files:
# Path: raxcli/models.py
# class Attribute(object):
# """
# Generic attribute that represents a field on a resource.
# """
# _creation_count = 0
#
# def __init__(self, src=None, transform_func=None, view_single=True,
# view_list=True):
# """
# @keyword src: Optional name of the field on the object which acts as a
# source for this attribute.
# @keyword src: C{str}
# """
# self.src = src
# self.transform_func = transform_func
# self.view_single = view_single
# self.view_list = view_list
#
# # Keep a count that is incremented on instantiation so we can iterate
# # in the same order that attributes are delcared on an Object.
# self._creation_count = Attribute._creation_count + 1
# Attribute._creation_count = self._creation_count
#
# def get_value(self):
# if self.transform_func:
# return self.transform_func(self.value)
# else:
# return self.value
#
# class Model(object):
# """
# Generic object that allows you to declaratively define how resources
# should be presented.
# """
# def get_attrs(self, view_type=None):
# """
# Get model attributes for the provided view_type.
# """
# attrs = []
# for attr, _ in getmembers(self):
# field = getattr(self, attr)
#
# if not isinstance(field, Attribute):
# continue
#
# if not view_type or getattr(field, view_type):
# src = field.src if field.src else attr
# attrs.append((field._creation_count, [attr, src]))
#
# return [attr for field, attr in sorted(attrs, key=itemgetter(0))]
#
# def __init__(self, obj):
# self._obj_type = 'dict' if isinstance(obj, dict) else 'cls'
#
# for name, source in self.get_attrs():
# field = getattr(self, name)
#
# if self._obj_type == 'dict':
# field.value = obj[source]
# elif self._obj_type == 'cls':
# field.value = getattr(obj, source)
#
# setattr(self, name, copy.copy(field))
#
# def generate_output(self):
# columns = [attr for attr, _ in self.get_attrs(view_type='view_single')]
# data = [getattr(self, attr).get_value() for attr in columns]
# return (columns, data)
#
# class Collection(object):
# """
# A collection of resources for outputting to a list.
# """
# def __init__(self, objs):
# self.objs = objs
#
# def generate_output(self):
# columns = []
# data = []
# for obj in self.objs:
# if not columns:
# columns = [attr for attr, _ in
# obj.get_attrs(view_type='view_list')]
#
# values = []
# for key in columns:
# attr = getattr(obj, key)
# value = attr.get_value()
# values.append(value)
#
# data.append(values)
#
# return (columns, data)
. Output only the next line. | sys.exit(unittest.main()) |
Next line prediction: <|code_start|>
class MonitoringCommand(BaseCommand):
def get_parser(self, prog_name):
parser = super(MonitoringCommand, self).\
get_parser(prog_name=prog_name)
parser.add_argument('--auth-url', dest='auth_url')
return parser
class MonitoringEntityCommand(MonitoringCommand):
def get_parser(self, prog_name):
parser = super(MonitoringEntityCommand, self).\
get_parser(prog_name=prog_name)
parser.add_argument('--entity-id', dest='entity_id', required=True)
return parser
class MonitoringCheckCommand(MonitoringEntityCommand):
def get_parser(self, prog_name):
parser = super(MonitoringCheckCommand, self).\
get_parser(prog_name=prog_name)
parser.add_argument('--check-id', dest='check_id', required=True)
return parser
class MonitoringListCommand(MonitoringCommand, BaseListCommand):
def get_parser(self, prog_name):
parser = super(MonitoringListCommand, self).\
get_parser(prog_name=prog_name)
parser.add_argument('--marker', dest='marker')
<|code_end|>
. Use current file imports:
(import os
import libcloud.security
from raxcli.commands import BaseCommand, BaseListCommand
from raxcli.config import get_config as get_base_config
from rackspace_monitoring.providers import get_driver
from rackspace_monitoring.types import Provider)
and context including class names, function names, or small code snippets from other files:
# Path: raxcli/commands.py
# class BaseCommand(Command):
# def get_parser(self, prog_name):
# parser = super(BaseCommand, self).get_parser(prog_name=prog_name)
# parser.add_argument('--username', dest='username')
# parser.add_argument('--api-key', dest='api_key')
# parser.add_argument('--api-url', dest='api_url')
# parser.add_argument('--json', dest='json_options')
# return parser
#
# class BaseListCommand(BaseCommand, Lister):
# def get_parser(self, prog_name):
# parser = super(BaseListCommand, self).get_parser(prog_name=prog_name)
# return parser
#
# @property
# def formatter_default(self):
# return 'paginated_table'
#
# Path: raxcli/config.py
# def get_config(app, default_values=None, config_path=DEFAULT_CONFIG_PATH,
# env_prefix=DEFAULT_ENV_PREFIX, env_dict=None):
# """
# Return dictionary with configuration values for a provided app.
#
# @param app: Name of the app configuration is being retrieved for.
# @type app: C{str}
#
# @param default_values: Default configuration values.
# @type default_values: C{dict}
#
# @param config_path: Path to the config file.
# @type config_path: C{str}
#
# @param env_prefix: Environment variables prefix.
# @type env_prefix: C{str}
#
# @param env_dict: Dictionary with environment variables. If not provided,
# os.environ is used.
# @type env_dict: C{dict}
#
# @return Configuration values.
# @rtype: C{dict}
# """
# result = {}
#
# if env_dict is None:
# env_dict = os.environ
#
# if default_values is None:
# default_values = {}
#
# keys = [
# ['global', 'username', 'username'],
# ['global', 'api_key', 'api_key'],
# ['global', 'verify_ssl', 'verify_ssl'],
# ['global', 'auth_url', 'auth_url'],
# ]
#
# env_keys = ['username', 'api_key', 'api_url', 'auth_url', 'verify_ssl']
#
# for key in env_keys:
# env_key = env_prefix + key
# env_key = env_key.upper()
#
# if env_key in env_dict:
# result[key] = env_dict[env_key]
#
# config_path = env_dict.get(env_prefix + 'RAXRC', config_path)
#
# config = ConfigParser.ConfigParser()
# config.read(config_path)
#
# for (config_section, config_key, key) in keys:
# if key in result:
# # Already specified as an env variable
# continue
#
# # global section
# try:
# value = config.get(config_section, config_key)
# except ConfigParser.Error:
# pass
# else:
# result[key] = value
#
# # app specific section
# try:
# value = config.get(app, config_key)
# except ConfigParser.Error:
# pass
# else:
# result[key] = value
#
# if 'verify_ssl' in result:
# result['verify_ssl'] = to_bolean(result['verify_ssl'],
# default_value=True)
#
# for key, value in default_values.items():
# if key not in result:
# result[key] = value
#
# return result
. Output only the next line. | return parser |
Based on the snippet: <|code_start|> parser.add_argument('--marker', dest='marker')
return parser
class MonitoringEntityListCommand(MonitoringListCommand):
def get_parser(self, prog_name):
parser = super(MonitoringEntityListCommand, self).\
get_parser(prog_name=prog_name)
parser.add_argument('--entity-id', dest='entity_id', required=True)
return parser
class MonitoringCheckListCommand(MonitoringEntityListCommand):
def get_parser(self, prog_name):
parser = super(MonitoringCheckListCommand, self).\
get_parser(prog_name=prog_name)
parser.add_argument('--check-id', dest='check_id', required=True)
return parser
def get_config():
return get_base_config(app='monitoring')
def get_client(parsed_args):
config = get_config()
driver = get_driver(Provider.RACKSPACE)
username = config['username']
api_key = config['api_key']
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import libcloud.security
from raxcli.commands import BaseCommand, BaseListCommand
from raxcli.config import get_config as get_base_config
from rackspace_monitoring.providers import get_driver
from rackspace_monitoring.types import Provider
and context (classes, functions, sometimes code) from other files:
# Path: raxcli/commands.py
# class BaseCommand(Command):
# def get_parser(self, prog_name):
# parser = super(BaseCommand, self).get_parser(prog_name=prog_name)
# parser.add_argument('--username', dest='username')
# parser.add_argument('--api-key', dest='api_key')
# parser.add_argument('--api-url', dest='api_url')
# parser.add_argument('--json', dest='json_options')
# return parser
#
# class BaseListCommand(BaseCommand, Lister):
# def get_parser(self, prog_name):
# parser = super(BaseListCommand, self).get_parser(prog_name=prog_name)
# return parser
#
# @property
# def formatter_default(self):
# return 'paginated_table'
#
# Path: raxcli/config.py
# def get_config(app, default_values=None, config_path=DEFAULT_CONFIG_PATH,
# env_prefix=DEFAULT_ENV_PREFIX, env_dict=None):
# """
# Return dictionary with configuration values for a provided app.
#
# @param app: Name of the app configuration is being retrieved for.
# @type app: C{str}
#
# @param default_values: Default configuration values.
# @type default_values: C{dict}
#
# @param config_path: Path to the config file.
# @type config_path: C{str}
#
# @param env_prefix: Environment variables prefix.
# @type env_prefix: C{str}
#
# @param env_dict: Dictionary with environment variables. If not provided,
# os.environ is used.
# @type env_dict: C{dict}
#
# @return Configuration values.
# @rtype: C{dict}
# """
# result = {}
#
# if env_dict is None:
# env_dict = os.environ
#
# if default_values is None:
# default_values = {}
#
# keys = [
# ['global', 'username', 'username'],
# ['global', 'api_key', 'api_key'],
# ['global', 'verify_ssl', 'verify_ssl'],
# ['global', 'auth_url', 'auth_url'],
# ]
#
# env_keys = ['username', 'api_key', 'api_url', 'auth_url', 'verify_ssl']
#
# for key in env_keys:
# env_key = env_prefix + key
# env_key = env_key.upper()
#
# if env_key in env_dict:
# result[key] = env_dict[env_key]
#
# config_path = env_dict.get(env_prefix + 'RAXRC', config_path)
#
# config = ConfigParser.ConfigParser()
# config.read(config_path)
#
# for (config_section, config_key, key) in keys:
# if key in result:
# # Already specified as an env variable
# continue
#
# # global section
# try:
# value = config.get(config_section, config_key)
# except ConfigParser.Error:
# pass
# else:
# result[key] = value
#
# # app specific section
# try:
# value = config.get(app, config_key)
# except ConfigParser.Error:
# pass
# else:
# result[key] = value
#
# if 'verify_ssl' in result:
# result['verify_ssl'] = to_bolean(result['verify_ssl'],
# default_value=True)
#
# for key, value in default_values.items():
# if key not in result:
# result[key] = value
#
# return result
. Output only the next line. | if parsed_args.username: |
Continue the code snippet: <|code_start|> return parser
def get_config():
return get_base_config(app='monitoring')
def get_client(parsed_args):
config = get_config()
driver = get_driver(Provider.RACKSPACE)
username = config['username']
api_key = config['api_key']
if parsed_args.username:
username = parsed_args.username
if parsed_args.api_key:
api_key = parsed_args.api_key
api_url = parsed_args.api_url
auth_url = parsed_args.auth_url
if not username:
raise ValueError('Missing required argument: username')
if not api_key:
raise ValueError('Missing required argument: api-key')
options = {}
if api_url is not None:
<|code_end|>
. Use current file imports:
import os
import libcloud.security
from raxcli.commands import BaseCommand, BaseListCommand
from raxcli.config import get_config as get_base_config
from rackspace_monitoring.providers import get_driver
from rackspace_monitoring.types import Provider
and context (classes, functions, or code) from other files:
# Path: raxcli/commands.py
# class BaseCommand(Command):
# def get_parser(self, prog_name):
# parser = super(BaseCommand, self).get_parser(prog_name=prog_name)
# parser.add_argument('--username', dest='username')
# parser.add_argument('--api-key', dest='api_key')
# parser.add_argument('--api-url', dest='api_url')
# parser.add_argument('--json', dest='json_options')
# return parser
#
# class BaseListCommand(BaseCommand, Lister):
# def get_parser(self, prog_name):
# parser = super(BaseListCommand, self).get_parser(prog_name=prog_name)
# return parser
#
# @property
# def formatter_default(self):
# return 'paginated_table'
#
# Path: raxcli/config.py
# def get_config(app, default_values=None, config_path=DEFAULT_CONFIG_PATH,
# env_prefix=DEFAULT_ENV_PREFIX, env_dict=None):
# """
# Return dictionary with configuration values for a provided app.
#
# @param app: Name of the app configuration is being retrieved for.
# @type app: C{str}
#
# @param default_values: Default configuration values.
# @type default_values: C{dict}
#
# @param config_path: Path to the config file.
# @type config_path: C{str}
#
# @param env_prefix: Environment variables prefix.
# @type env_prefix: C{str}
#
# @param env_dict: Dictionary with environment variables. If not provided,
# os.environ is used.
# @type env_dict: C{dict}
#
# @return Configuration values.
# @rtype: C{dict}
# """
# result = {}
#
# if env_dict is None:
# env_dict = os.environ
#
# if default_values is None:
# default_values = {}
#
# keys = [
# ['global', 'username', 'username'],
# ['global', 'api_key', 'api_key'],
# ['global', 'verify_ssl', 'verify_ssl'],
# ['global', 'auth_url', 'auth_url'],
# ]
#
# env_keys = ['username', 'api_key', 'api_url', 'auth_url', 'verify_ssl']
#
# for key in env_keys:
# env_key = env_prefix + key
# env_key = env_key.upper()
#
# if env_key in env_dict:
# result[key] = env_dict[env_key]
#
# config_path = env_dict.get(env_prefix + 'RAXRC', config_path)
#
# config = ConfigParser.ConfigParser()
# config.read(config_path)
#
# for (config_section, config_key, key) in keys:
# if key in result:
# # Already specified as an env variable
# continue
#
# # global section
# try:
# value = config.get(config_section, config_key)
# except ConfigParser.Error:
# pass
# else:
# result[key] = value
#
# # app specific section
# try:
# value = config.get(app, config_key)
# except ConfigParser.Error:
# pass
# else:
# result[key] = value
#
# if 'verify_ssl' in result:
# result['verify_ssl'] = to_bolean(result['verify_ssl'],
# default_value=True)
#
# for key, value in default_values.items():
# if key not in result:
# result[key] = value
#
# return result
. Output only the next line. | options['ex_force_base_url'] = api_url |
Using the snippet: <|code_start|># See the License for the specific language governing permissions and
# limitations under the License.
__all__ = [
'for_all_regions'
]
CA_CERT_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)),
'../data/cacert.pem')
libcloud.security.CA_CERTS_PATH.insert(0, CA_CERT_PATH)
class LoadBalancerCommand(BaseCommand):
def get_parser(self, prog_name):
parser = super(LoadBalancerCommand, self).\
get_parser(prog_name=prog_name)
parser.add_argument('--auth-url', dest='auth_url')
parser.add_argument('--region', dest='region')
return parser
class LoadBalancerBalancerListCommand(LoadBalancerCommand, BaseListCommand):
def get_parser(self, prog_name):
parser = super(LoadBalancerBalancerListCommand, self).\
get_parser(prog_name=prog_name)
<|code_end|>
, determine the next line of code. You have imports:
import os
import libcloud.security
from raxcli.commands import BaseCommand, BaseListCommand
from raxcli.config import get_config as get_base_config
from raxcli.apps.utils import for_all_regions as base_get_all_regions
from raxcli.apps.loadbalancer.constants import SERVICE_CATALOG_ENTRY_NAME
from libcloud.loadbalancer.providers import get_driver
from libcloud.loadbalancer.types import Provider
and context (class names, function names, or code) available:
# Path: raxcli/commands.py
# class BaseCommand(Command):
# def get_parser(self, prog_name):
# parser = super(BaseCommand, self).get_parser(prog_name=prog_name)
# parser.add_argument('--username', dest='username')
# parser.add_argument('--api-key', dest='api_key')
# parser.add_argument('--api-url', dest='api_url')
# parser.add_argument('--json', dest='json_options')
# return parser
#
# class BaseListCommand(BaseCommand, Lister):
# def get_parser(self, prog_name):
# parser = super(BaseListCommand, self).get_parser(prog_name=prog_name)
# return parser
#
# @property
# def formatter_default(self):
# return 'paginated_table'
#
# Path: raxcli/config.py
# def get_config(app, default_values=None, config_path=DEFAULT_CONFIG_PATH,
# env_prefix=DEFAULT_ENV_PREFIX, env_dict=None):
# """
# Return dictionary with configuration values for a provided app.
#
# @param app: Name of the app configuration is being retrieved for.
# @type app: C{str}
#
# @param default_values: Default configuration values.
# @type default_values: C{dict}
#
# @param config_path: Path to the config file.
# @type config_path: C{str}
#
# @param env_prefix: Environment variables prefix.
# @type env_prefix: C{str}
#
# @param env_dict: Dictionary with environment variables. If not provided,
# os.environ is used.
# @type env_dict: C{dict}
#
# @return Configuration values.
# @rtype: C{dict}
# """
# result = {}
#
# if env_dict is None:
# env_dict = os.environ
#
# if default_values is None:
# default_values = {}
#
# keys = [
# ['global', 'username', 'username'],
# ['global', 'api_key', 'api_key'],
# ['global', 'verify_ssl', 'verify_ssl'],
# ['global', 'auth_url', 'auth_url'],
# ]
#
# env_keys = ['username', 'api_key', 'api_url', 'auth_url', 'verify_ssl']
#
# for key in env_keys:
# env_key = env_prefix + key
# env_key = env_key.upper()
#
# if env_key in env_dict:
# result[key] = env_dict[env_key]
#
# config_path = env_dict.get(env_prefix + 'RAXRC', config_path)
#
# config = ConfigParser.ConfigParser()
# config.read(config_path)
#
# for (config_section, config_key, key) in keys:
# if key in result:
# # Already specified as an env variable
# continue
#
# # global section
# try:
# value = config.get(config_section, config_key)
# except ConfigParser.Error:
# pass
# else:
# result[key] = value
#
# # app specific section
# try:
# value = config.get(app, config_key)
# except ConfigParser.Error:
# pass
# else:
# result[key] = value
#
# if 'verify_ssl' in result:
# result['verify_ssl'] = to_bolean(result['verify_ssl'],
# default_value=True)
#
# for key, value in default_values.items():
# if key not in result:
# result[key] = value
#
# return result
#
# Path: raxcli/apps/utils.py
# def for_all_regions(get_client_func, catalog_entry, action_func, parsed_args):
# """
# Run the provided function on all the available regions.
#
# Available regions are determined based on the user service catalog entries.
# """
#
# result = []
#
# cache_key = 'todo'
#
# cache_item = CACHE.get(cache_key, None)
#
# if cache_item is None:
# client = get_client_func(parsed_args)
# CACHE[cache_key] = client
# else:
# client = cache_item
#
# catalog = client.connection.get_service_catalog()
#
# urls = catalog.get_public_urls(service_type=catalog_entry,
# name=catalog_entry)
# auth_connection = client.connection.get_auth_connection_instance()
#
# driver_kwargs = {'ex_auth_connection': auth_connection}
#
# def run_in_pool(client):
# item = action_func(client)
# result.extend(item)
#
# for api_url in urls:
# parsed_args.api_url = api_url
# client = get_client_func(parsed_args, driver_kwargs=driver_kwargs)
# run_function(pool, run_in_pool, client)
#
# join_pool(pool)
#
# return result
#
# Path: raxcli/apps/loadbalancer/constants.py
# SERVICE_CATALOG_ENTRY_NAME = 'cloudLoadBalancers'
. Output only the next line. | parser.add_argument('--balancer-id', dest='balancer_id', required=True) |
Next line prediction: <|code_start|> return parser
class LoadBalancerBalancerListCommand(LoadBalancerCommand, BaseListCommand):
def get_parser(self, prog_name):
parser = super(LoadBalancerBalancerListCommand, self).\
get_parser(prog_name=prog_name)
parser.add_argument('--balancer-id', dest='balancer_id', required=True)
return parser
def get_config():
return get_base_config(app='loadbalancer')
def get_client(parsed_args, driver_kwargs=None):
config = get_config()
# TODO: regions/uk
driver = get_driver(Provider.RACKSPACE_US)
username = config['username']
api_key = config['api_key']
if parsed_args.username:
username = parsed_args.username
if parsed_args.api_key:
api_key = parsed_args.api_key
api_url = parsed_args.api_url
auth_url = parsed_args.auth_url
<|code_end|>
. Use current file imports:
(import os
import libcloud.security
from raxcli.commands import BaseCommand, BaseListCommand
from raxcli.config import get_config as get_base_config
from raxcli.apps.utils import for_all_regions as base_get_all_regions
from raxcli.apps.loadbalancer.constants import SERVICE_CATALOG_ENTRY_NAME
from libcloud.loadbalancer.providers import get_driver
from libcloud.loadbalancer.types import Provider)
and context including class names, function names, or small code snippets from other files:
# Path: raxcli/commands.py
# class BaseCommand(Command):
# def get_parser(self, prog_name):
# parser = super(BaseCommand, self).get_parser(prog_name=prog_name)
# parser.add_argument('--username', dest='username')
# parser.add_argument('--api-key', dest='api_key')
# parser.add_argument('--api-url', dest='api_url')
# parser.add_argument('--json', dest='json_options')
# return parser
#
# class BaseListCommand(BaseCommand, Lister):
# def get_parser(self, prog_name):
# parser = super(BaseListCommand, self).get_parser(prog_name=prog_name)
# return parser
#
# @property
# def formatter_default(self):
# return 'paginated_table'
#
# Path: raxcli/config.py
# def get_config(app, default_values=None, config_path=DEFAULT_CONFIG_PATH,
# env_prefix=DEFAULT_ENV_PREFIX, env_dict=None):
# """
# Return dictionary with configuration values for a provided app.
#
# @param app: Name of the app configuration is being retrieved for.
# @type app: C{str}
#
# @param default_values: Default configuration values.
# @type default_values: C{dict}
#
# @param config_path: Path to the config file.
# @type config_path: C{str}
#
# @param env_prefix: Environment variables prefix.
# @type env_prefix: C{str}
#
# @param env_dict: Dictionary with environment variables. If not provided,
# os.environ is used.
# @type env_dict: C{dict}
#
# @return Configuration values.
# @rtype: C{dict}
# """
# result = {}
#
# if env_dict is None:
# env_dict = os.environ
#
# if default_values is None:
# default_values = {}
#
# keys = [
# ['global', 'username', 'username'],
# ['global', 'api_key', 'api_key'],
# ['global', 'verify_ssl', 'verify_ssl'],
# ['global', 'auth_url', 'auth_url'],
# ]
#
# env_keys = ['username', 'api_key', 'api_url', 'auth_url', 'verify_ssl']
#
# for key in env_keys:
# env_key = env_prefix + key
# env_key = env_key.upper()
#
# if env_key in env_dict:
# result[key] = env_dict[env_key]
#
# config_path = env_dict.get(env_prefix + 'RAXRC', config_path)
#
# config = ConfigParser.ConfigParser()
# config.read(config_path)
#
# for (config_section, config_key, key) in keys:
# if key in result:
# # Already specified as an env variable
# continue
#
# # global section
# try:
# value = config.get(config_section, config_key)
# except ConfigParser.Error:
# pass
# else:
# result[key] = value
#
# # app specific section
# try:
# value = config.get(app, config_key)
# except ConfigParser.Error:
# pass
# else:
# result[key] = value
#
# if 'verify_ssl' in result:
# result['verify_ssl'] = to_bolean(result['verify_ssl'],
# default_value=True)
#
# for key, value in default_values.items():
# if key not in result:
# result[key] = value
#
# return result
#
# Path: raxcli/apps/utils.py
# def for_all_regions(get_client_func, catalog_entry, action_func, parsed_args):
# """
# Run the provided function on all the available regions.
#
# Available regions are determined based on the user service catalog entries.
# """
#
# result = []
#
# cache_key = 'todo'
#
# cache_item = CACHE.get(cache_key, None)
#
# if cache_item is None:
# client = get_client_func(parsed_args)
# CACHE[cache_key] = client
# else:
# client = cache_item
#
# catalog = client.connection.get_service_catalog()
#
# urls = catalog.get_public_urls(service_type=catalog_entry,
# name=catalog_entry)
# auth_connection = client.connection.get_auth_connection_instance()
#
# driver_kwargs = {'ex_auth_connection': auth_connection}
#
# def run_in_pool(client):
# item = action_func(client)
# result.extend(item)
#
# for api_url in urls:
# parsed_args.api_url = api_url
# client = get_client_func(parsed_args, driver_kwargs=driver_kwargs)
# run_function(pool, run_in_pool, client)
#
# join_pool(pool)
#
# return result
#
# Path: raxcli/apps/loadbalancer/constants.py
# SERVICE_CATALOG_ENTRY_NAME = 'cloudLoadBalancers'
. Output only the next line. | if not username: |
Continue the code snippet: <|code_start|>
class LoadBalancerBalancerListCommand(LoadBalancerCommand, BaseListCommand):
def get_parser(self, prog_name):
parser = super(LoadBalancerBalancerListCommand, self).\
get_parser(prog_name=prog_name)
parser.add_argument('--balancer-id', dest='balancer_id', required=True)
return parser
def get_config():
return get_base_config(app='loadbalancer')
def get_client(parsed_args, driver_kwargs=None):
config = get_config()
# TODO: regions/uk
driver = get_driver(Provider.RACKSPACE_US)
username = config['username']
api_key = config['api_key']
if parsed_args.username:
username = parsed_args.username
if parsed_args.api_key:
api_key = parsed_args.api_key
api_url = parsed_args.api_url
auth_url = parsed_args.auth_url
if not username:
<|code_end|>
. Use current file imports:
import os
import libcloud.security
from raxcli.commands import BaseCommand, BaseListCommand
from raxcli.config import get_config as get_base_config
from raxcli.apps.utils import for_all_regions as base_get_all_regions
from raxcli.apps.loadbalancer.constants import SERVICE_CATALOG_ENTRY_NAME
from libcloud.loadbalancer.providers import get_driver
from libcloud.loadbalancer.types import Provider
and context (classes, functions, or code) from other files:
# Path: raxcli/commands.py
# class BaseCommand(Command):
# def get_parser(self, prog_name):
# parser = super(BaseCommand, self).get_parser(prog_name=prog_name)
# parser.add_argument('--username', dest='username')
# parser.add_argument('--api-key', dest='api_key')
# parser.add_argument('--api-url', dest='api_url')
# parser.add_argument('--json', dest='json_options')
# return parser
#
# class BaseListCommand(BaseCommand, Lister):
# def get_parser(self, prog_name):
# parser = super(BaseListCommand, self).get_parser(prog_name=prog_name)
# return parser
#
# @property
# def formatter_default(self):
# return 'paginated_table'
#
# Path: raxcli/config.py
# def get_config(app, default_values=None, config_path=DEFAULT_CONFIG_PATH,
# env_prefix=DEFAULT_ENV_PREFIX, env_dict=None):
# """
# Return dictionary with configuration values for a provided app.
#
# @param app: Name of the app configuration is being retrieved for.
# @type app: C{str}
#
# @param default_values: Default configuration values.
# @type default_values: C{dict}
#
# @param config_path: Path to the config file.
# @type config_path: C{str}
#
# @param env_prefix: Environment variables prefix.
# @type env_prefix: C{str}
#
# @param env_dict: Dictionary with environment variables. If not provided,
# os.environ is used.
# @type env_dict: C{dict}
#
# @return Configuration values.
# @rtype: C{dict}
# """
# result = {}
#
# if env_dict is None:
# env_dict = os.environ
#
# if default_values is None:
# default_values = {}
#
# keys = [
# ['global', 'username', 'username'],
# ['global', 'api_key', 'api_key'],
# ['global', 'verify_ssl', 'verify_ssl'],
# ['global', 'auth_url', 'auth_url'],
# ]
#
# env_keys = ['username', 'api_key', 'api_url', 'auth_url', 'verify_ssl']
#
# for key in env_keys:
# env_key = env_prefix + key
# env_key = env_key.upper()
#
# if env_key in env_dict:
# result[key] = env_dict[env_key]
#
# config_path = env_dict.get(env_prefix + 'RAXRC', config_path)
#
# config = ConfigParser.ConfigParser()
# config.read(config_path)
#
# for (config_section, config_key, key) in keys:
# if key in result:
# # Already specified as an env variable
# continue
#
# # global section
# try:
# value = config.get(config_section, config_key)
# except ConfigParser.Error:
# pass
# else:
# result[key] = value
#
# # app specific section
# try:
# value = config.get(app, config_key)
# except ConfigParser.Error:
# pass
# else:
# result[key] = value
#
# if 'verify_ssl' in result:
# result['verify_ssl'] = to_bolean(result['verify_ssl'],
# default_value=True)
#
# for key, value in default_values.items():
# if key not in result:
# result[key] = value
#
# return result
#
# Path: raxcli/apps/utils.py
# def for_all_regions(get_client_func, catalog_entry, action_func, parsed_args):
# """
# Run the provided function on all the available regions.
#
# Available regions are determined based on the user service catalog entries.
# """
#
# result = []
#
# cache_key = 'todo'
#
# cache_item = CACHE.get(cache_key, None)
#
# if cache_item is None:
# client = get_client_func(parsed_args)
# CACHE[cache_key] = client
# else:
# client = cache_item
#
# catalog = client.connection.get_service_catalog()
#
# urls = catalog.get_public_urls(service_type=catalog_entry,
# name=catalog_entry)
# auth_connection = client.connection.get_auth_connection_instance()
#
# driver_kwargs = {'ex_auth_connection': auth_connection}
#
# def run_in_pool(client):
# item = action_func(client)
# result.extend(item)
#
# for api_url in urls:
# parsed_args.api_url = api_url
# client = get_client_func(parsed_args, driver_kwargs=driver_kwargs)
# run_function(pool, run_in_pool, client)
#
# join_pool(pool)
#
# return result
#
# Path: raxcli/apps/loadbalancer/constants.py
# SERVICE_CATALOG_ENTRY_NAME = 'cloudLoadBalancers'
. Output only the next line. | raise ValueError('Missing required argument: username') |
Here is a snippet: <|code_start|># distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__all__ = [
'for_all_regions'
]
CA_CERT_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)),
'../data/cacert.pem')
libcloud.security.CA_CERTS_PATH.insert(0, CA_CERT_PATH)
class LoadBalancerCommand(BaseCommand):
def get_parser(self, prog_name):
parser = super(LoadBalancerCommand, self).\
get_parser(prog_name=prog_name)
parser.add_argument('--auth-url', dest='auth_url')
parser.add_argument('--region', dest='region')
return parser
class LoadBalancerBalancerListCommand(LoadBalancerCommand, BaseListCommand):
def get_parser(self, prog_name):
<|code_end|>
. Write the next line using the current file imports:
import os
import libcloud.security
from raxcli.commands import BaseCommand, BaseListCommand
from raxcli.config import get_config as get_base_config
from raxcli.apps.utils import for_all_regions as base_get_all_regions
from raxcli.apps.loadbalancer.constants import SERVICE_CATALOG_ENTRY_NAME
from libcloud.loadbalancer.providers import get_driver
from libcloud.loadbalancer.types import Provider
and context from other files:
# Path: raxcli/commands.py
# class BaseCommand(Command):
# def get_parser(self, prog_name):
# parser = super(BaseCommand, self).get_parser(prog_name=prog_name)
# parser.add_argument('--username', dest='username')
# parser.add_argument('--api-key', dest='api_key')
# parser.add_argument('--api-url', dest='api_url')
# parser.add_argument('--json', dest='json_options')
# return parser
#
# class BaseListCommand(BaseCommand, Lister):
# def get_parser(self, prog_name):
# parser = super(BaseListCommand, self).get_parser(prog_name=prog_name)
# return parser
#
# @property
# def formatter_default(self):
# return 'paginated_table'
#
# Path: raxcli/config.py
# def get_config(app, default_values=None, config_path=DEFAULT_CONFIG_PATH,
# env_prefix=DEFAULT_ENV_PREFIX, env_dict=None):
# """
# Return dictionary with configuration values for a provided app.
#
# @param app: Name of the app configuration is being retrieved for.
# @type app: C{str}
#
# @param default_values: Default configuration values.
# @type default_values: C{dict}
#
# @param config_path: Path to the config file.
# @type config_path: C{str}
#
# @param env_prefix: Environment variables prefix.
# @type env_prefix: C{str}
#
# @param env_dict: Dictionary with environment variables. If not provided,
# os.environ is used.
# @type env_dict: C{dict}
#
# @return Configuration values.
# @rtype: C{dict}
# """
# result = {}
#
# if env_dict is None:
# env_dict = os.environ
#
# if default_values is None:
# default_values = {}
#
# keys = [
# ['global', 'username', 'username'],
# ['global', 'api_key', 'api_key'],
# ['global', 'verify_ssl', 'verify_ssl'],
# ['global', 'auth_url', 'auth_url'],
# ]
#
# env_keys = ['username', 'api_key', 'api_url', 'auth_url', 'verify_ssl']
#
# for key in env_keys:
# env_key = env_prefix + key
# env_key = env_key.upper()
#
# if env_key in env_dict:
# result[key] = env_dict[env_key]
#
# config_path = env_dict.get(env_prefix + 'RAXRC', config_path)
#
# config = ConfigParser.ConfigParser()
# config.read(config_path)
#
# for (config_section, config_key, key) in keys:
# if key in result:
# # Already specified as an env variable
# continue
#
# # global section
# try:
# value = config.get(config_section, config_key)
# except ConfigParser.Error:
# pass
# else:
# result[key] = value
#
# # app specific section
# try:
# value = config.get(app, config_key)
# except ConfigParser.Error:
# pass
# else:
# result[key] = value
#
# if 'verify_ssl' in result:
# result['verify_ssl'] = to_bolean(result['verify_ssl'],
# default_value=True)
#
# for key, value in default_values.items():
# if key not in result:
# result[key] = value
#
# return result
#
# Path: raxcli/apps/utils.py
# def for_all_regions(get_client_func, catalog_entry, action_func, parsed_args):
# """
# Run the provided function on all the available regions.
#
# Available regions are determined based on the user service catalog entries.
# """
#
# result = []
#
# cache_key = 'todo'
#
# cache_item = CACHE.get(cache_key, None)
#
# if cache_item is None:
# client = get_client_func(parsed_args)
# CACHE[cache_key] = client
# else:
# client = cache_item
#
# catalog = client.connection.get_service_catalog()
#
# urls = catalog.get_public_urls(service_type=catalog_entry,
# name=catalog_entry)
# auth_connection = client.connection.get_auth_connection_instance()
#
# driver_kwargs = {'ex_auth_connection': auth_connection}
#
# def run_in_pool(client):
# item = action_func(client)
# result.extend(item)
#
# for api_url in urls:
# parsed_args.api_url = api_url
# client = get_client_func(parsed_args, driver_kwargs=driver_kwargs)
# run_function(pool, run_in_pool, client)
#
# join_pool(pool)
#
# return result
#
# Path: raxcli/apps/loadbalancer/constants.py
# SERVICE_CATALOG_ENTRY_NAME = 'cloudLoadBalancers'
, which may include functions, classes, or code. Output only the next line. | parser = super(LoadBalancerBalancerListCommand, self).\ |
Given the code snippet: <|code_start|>def get_client(parsed_args, driver_kwargs=None):
config = get_config()
# TODO: regions/uk
driver = get_driver(Provider.RACKSPACE_US)
username = config['username']
api_key = config['api_key']
if parsed_args.username:
username = parsed_args.username
if parsed_args.api_key:
api_key = parsed_args.api_key
api_url = parsed_args.api_url
auth_url = parsed_args.auth_url
if not username:
raise ValueError('Missing required argument: username')
if not api_key:
raise ValueError('Missing required argument: api-key')
if driver_kwargs:
options = driver_kwargs.copy()
else:
options = {}
if api_url is not None:
options['ex_force_base_url'] = api_url
if auth_url is not None:
<|code_end|>
, generate the next line using the imports in this file:
import os
import libcloud.security
from raxcli.commands import BaseCommand, BaseListCommand
from raxcli.config import get_config as get_base_config
from raxcli.apps.utils import for_all_regions as base_get_all_regions
from raxcli.apps.loadbalancer.constants import SERVICE_CATALOG_ENTRY_NAME
from libcloud.loadbalancer.providers import get_driver
from libcloud.loadbalancer.types import Provider
and context (functions, classes, or occasionally code) from other files:
# Path: raxcli/commands.py
# class BaseCommand(Command):
# def get_parser(self, prog_name):
# parser = super(BaseCommand, self).get_parser(prog_name=prog_name)
# parser.add_argument('--username', dest='username')
# parser.add_argument('--api-key', dest='api_key')
# parser.add_argument('--api-url', dest='api_url')
# parser.add_argument('--json', dest='json_options')
# return parser
#
# class BaseListCommand(BaseCommand, Lister):
# def get_parser(self, prog_name):
# parser = super(BaseListCommand, self).get_parser(prog_name=prog_name)
# return parser
#
# @property
# def formatter_default(self):
# return 'paginated_table'
#
# Path: raxcli/config.py
# def get_config(app, default_values=None, config_path=DEFAULT_CONFIG_PATH,
# env_prefix=DEFAULT_ENV_PREFIX, env_dict=None):
# """
# Return dictionary with configuration values for a provided app.
#
# @param app: Name of the app configuration is being retrieved for.
# @type app: C{str}
#
# @param default_values: Default configuration values.
# @type default_values: C{dict}
#
# @param config_path: Path to the config file.
# @type config_path: C{str}
#
# @param env_prefix: Environment variables prefix.
# @type env_prefix: C{str}
#
# @param env_dict: Dictionary with environment variables. If not provided,
# os.environ is used.
# @type env_dict: C{dict}
#
# @return Configuration values.
# @rtype: C{dict}
# """
# result = {}
#
# if env_dict is None:
# env_dict = os.environ
#
# if default_values is None:
# default_values = {}
#
# keys = [
# ['global', 'username', 'username'],
# ['global', 'api_key', 'api_key'],
# ['global', 'verify_ssl', 'verify_ssl'],
# ['global', 'auth_url', 'auth_url'],
# ]
#
# env_keys = ['username', 'api_key', 'api_url', 'auth_url', 'verify_ssl']
#
# for key in env_keys:
# env_key = env_prefix + key
# env_key = env_key.upper()
#
# if env_key in env_dict:
# result[key] = env_dict[env_key]
#
# config_path = env_dict.get(env_prefix + 'RAXRC', config_path)
#
# config = ConfigParser.ConfigParser()
# config.read(config_path)
#
# for (config_section, config_key, key) in keys:
# if key in result:
# # Already specified as an env variable
# continue
#
# # global section
# try:
# value = config.get(config_section, config_key)
# except ConfigParser.Error:
# pass
# else:
# result[key] = value
#
# # app specific section
# try:
# value = config.get(app, config_key)
# except ConfigParser.Error:
# pass
# else:
# result[key] = value
#
# if 'verify_ssl' in result:
# result['verify_ssl'] = to_bolean(result['verify_ssl'],
# default_value=True)
#
# for key, value in default_values.items():
# if key not in result:
# result[key] = value
#
# return result
#
# Path: raxcli/apps/utils.py
# def for_all_regions(get_client_func, catalog_entry, action_func, parsed_args):
# """
# Run the provided function on all the available regions.
#
# Available regions are determined based on the user service catalog entries.
# """
#
# result = []
#
# cache_key = 'todo'
#
# cache_item = CACHE.get(cache_key, None)
#
# if cache_item is None:
# client = get_client_func(parsed_args)
# CACHE[cache_key] = client
# else:
# client = cache_item
#
# catalog = client.connection.get_service_catalog()
#
# urls = catalog.get_public_urls(service_type=catalog_entry,
# name=catalog_entry)
# auth_connection = client.connection.get_auth_connection_instance()
#
# driver_kwargs = {'ex_auth_connection': auth_connection}
#
# def run_in_pool(client):
# item = action_func(client)
# result.extend(item)
#
# for api_url in urls:
# parsed_args.api_url = api_url
# client = get_client_func(parsed_args, driver_kwargs=driver_kwargs)
# run_function(pool, run_in_pool, client)
#
# join_pool(pool)
#
# return result
#
# Path: raxcli/apps/loadbalancer/constants.py
# SERVICE_CATALOG_ENTRY_NAME = 'cloudLoadBalancers'
. Output only the next line. | options['ex_force_auth_url'] = auth_url |
Given the code snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class CachedPropertyTest(test.TestCase):
def test_attribute_caching(self):
class A(object):
def __init__(self):
self.call_counter = 0
@misc.cachedproperty
def b(self):
self.call_counter += 1
return 'b'
a = A()
self.assertEqual('b', a.b)
<|code_end|>
, generate the next line using the imports in this file:
import collections
import inspect
import random
import string
import time
import six
import testscenarios
from taskflow import test
from taskflow.utils import misc
from taskflow.utils import threading_utils
and context (functions, classes, or occasionally code) from other files:
# Path: taskflow/test.py
# class GreaterThanEqual(object):
# class FailureRegexpMatcher(object):
# class ItemsEqual(object):
# class TestCase(base.BaseTestCase):
# class ReRaiseOtherTypes(object):
# class CaptureMatchee(object):
# class MockTestCase(TestCase):
# class CapturingLoggingHandler(logging.Handler):
# def __init__(self, source):
# def match(self, other):
# def __init__(self, exc_class, pattern):
# def match(self, failure):
# def __init__(self, seq):
# def match(self, other):
# def makeTmpDir(self):
# def assertDictEqual(self, expected, check):
# def assertRaisesAttrAccess(self, exc_class, obj, attr_name):
# def access_func():
# def assertRaisesRegex(self, exc_class, pattern, callable_obj,
# *args, **kwargs):
# def match(self, matchee):
# def match(self, matchee):
# def assertGreater(self, first, second):
# def assertGreaterEqual(self, first, second):
# def assertRegexpMatches(self, text, pattern):
# def assertIsSuperAndSubsequence(self, super_seq, sub_seq, msg=None):
# def assertFailuresRegexp(self, exc_class, pattern, callable_obj, *args,
# **kwargs):
# def assertCountEqual(self, seq1, seq2, msg=None):
# def setUp(self):
# def patch(self, target, autospec=True, **kwargs):
# def patchClass(self, module, name, autospec=True, attach_as=None):
# def resetMasterMock(self):
# def __init__(self, level=logging.DEBUG):
# def counts(self):
# def messages(self):
# def exc_infos(self):
# def emit(self, record):
# def reset(self):
# def close(self):
#
# Path: taskflow/utils/misc.py
# UNKNOWN_HOSTNAME = "<unknown>"
# NUMERIC_TYPES = six.integer_types + (float,)
# _SCHEME_REGEX = re.compile(r"^([A-Za-z][A-Za-z0-9+.-]*):")
# class StrEnum(str, enum.Enum):
# class StringIO(six.StringIO):
# class BytesIO(six.BytesIO):
# class cachedproperty(object):
# def __new__(cls, *args, **kwargs):
# def write_nl(self, value, linesep=os.linesep):
# def reset(self):
# def get_hostname(unknown_hostname=UNKNOWN_HOSTNAME):
# def match_type(obj, matchers):
# def countdown_iter(start_at, decr=1):
# def extract_driver_and_conf(conf, conf_key):
# def reverse_enumerate(items):
# def merge_uri(uri, conf):
# def find_subclasses(locations, base_cls, exclude_hidden=True):
# def pick_first_not_none(*values):
# def parse_uri(uri):
# def disallow_when_frozen(excp_cls):
# def decorator(f):
# def wrapper(self, *args, **kwargs):
# def clamp(value, minimum, maximum, on_clamped=None):
# def fix_newlines(text, replacement=os.linesep):
# def binary_encode(text, encoding='utf-8', errors='strict'):
# def binary_decode(data, encoding='utf-8', errors='strict'):
# def _check_decoded_type(data, root_types=(dict,)):
# def decode_msgpack(raw_data, root_types=(dict,)):
# def decode_json(raw_data, root_types=(dict,)):
# def __init__(self, fget=None, require_lock=True):
# def __call__(self, fget):
# def __set__(self, instance, value):
# def __delete__(self, instance):
# def __get__(self, instance, owner):
# def millis_to_datetime(milliseconds):
# def get_version_string(obj):
# def sequence_minus(seq1, seq2):
# def as_int(obj, quiet=False):
# def capture_failure():
# def is_iterable(obj):
# def safe_copy_dict(obj):
. Output only the next line. | self.assertEqual('b', a.b) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
# Copyright (C) 2013 Yahoo! Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class MakeCompletedFutureTest(test.TestCase):
def test_make_completed_future(self):
result = object()
future = au.make_completed_future(result)
self.assertTrue(future.done())
<|code_end|>
, predict the next line using imports from the current file:
from taskflow import test
from taskflow.utils import async_utils as au
and context including class names, function names, and sometimes code from other files:
# Path: taskflow/test.py
# class GreaterThanEqual(object):
# class FailureRegexpMatcher(object):
# class ItemsEqual(object):
# class TestCase(base.BaseTestCase):
# class ReRaiseOtherTypes(object):
# class CaptureMatchee(object):
# class MockTestCase(TestCase):
# class CapturingLoggingHandler(logging.Handler):
# def __init__(self, source):
# def match(self, other):
# def __init__(self, exc_class, pattern):
# def match(self, failure):
# def __init__(self, seq):
# def match(self, other):
# def makeTmpDir(self):
# def assertDictEqual(self, expected, check):
# def assertRaisesAttrAccess(self, exc_class, obj, attr_name):
# def access_func():
# def assertRaisesRegex(self, exc_class, pattern, callable_obj,
# *args, **kwargs):
# def match(self, matchee):
# def match(self, matchee):
# def assertGreater(self, first, second):
# def assertGreaterEqual(self, first, second):
# def assertRegexpMatches(self, text, pattern):
# def assertIsSuperAndSubsequence(self, super_seq, sub_seq, msg=None):
# def assertFailuresRegexp(self, exc_class, pattern, callable_obj, *args,
# **kwargs):
# def assertCountEqual(self, seq1, seq2, msg=None):
# def setUp(self):
# def patch(self, target, autospec=True, **kwargs):
# def patchClass(self, module, name, autospec=True, attach_as=None):
# def resetMasterMock(self):
# def __init__(self, level=logging.DEBUG):
# def counts(self):
# def messages(self):
# def exc_infos(self):
# def emit(self, record):
# def reset(self):
# def close(self):
. Output only the next line. | self.assertIs(future.result(), result) |
Predict the next line after this snippet: <|code_start|> routing_key = 'routing-key'
task_uuid = 'task-uuid'
p = self.proxy(reset_master_mock=True)
p.publish(msg_mock, routing_key, correlation_id=task_uuid)
mock_producer = mock.call.connection.Producer()
master_mock_calls = self.proxy_publish_calls([
mock_producer.__enter__().publish(body=msg_data,
routing_key=routing_key,
exchange=self.exchange_inst_mock,
correlation_id=task_uuid,
declare=[self.queue_inst_mock],
type=msg_mock.TYPE,
reply_to=None)
], routing_key)
self.master_mock.assert_has_calls(master_mock_calls)
def test_start(self):
try:
# KeyboardInterrupt will be raised after two iterations
self.proxy(reset_master_mock=True).start()
except KeyboardInterrupt:
pass
master_calls = self.proxy_start_calls([
mock.call.connection.drain_events(timeout=self.de_period),
mock.call.connection.drain_events(timeout=self.de_period),
mock.call.connection.drain_events(timeout=self.de_period),
], exc_type=KeyboardInterrupt)
<|code_end|>
using the current file's imports:
import socket
from unittest import mock
from taskflow.engines.worker_based import proxy
from taskflow import test
from taskflow.utils import threading_utils
and any relevant context from other files:
# Path: taskflow/test.py
# class GreaterThanEqual(object):
# class FailureRegexpMatcher(object):
# class ItemsEqual(object):
# class TestCase(base.BaseTestCase):
# class ReRaiseOtherTypes(object):
# class CaptureMatchee(object):
# class MockTestCase(TestCase):
# class CapturingLoggingHandler(logging.Handler):
# def __init__(self, source):
# def match(self, other):
# def __init__(self, exc_class, pattern):
# def match(self, failure):
# def __init__(self, seq):
# def match(self, other):
# def makeTmpDir(self):
# def assertDictEqual(self, expected, check):
# def assertRaisesAttrAccess(self, exc_class, obj, attr_name):
# def access_func():
# def assertRaisesRegex(self, exc_class, pattern, callable_obj,
# *args, **kwargs):
# def match(self, matchee):
# def match(self, matchee):
# def assertGreater(self, first, second):
# def assertGreaterEqual(self, first, second):
# def assertRegexpMatches(self, text, pattern):
# def assertIsSuperAndSubsequence(self, super_seq, sub_seq, msg=None):
# def assertFailuresRegexp(self, exc_class, pattern, callable_obj, *args,
# **kwargs):
# def assertCountEqual(self, seq1, seq2, msg=None):
# def setUp(self):
# def patch(self, target, autospec=True, **kwargs):
# def patchClass(self, module, name, autospec=True, attach_as=None):
# def resetMasterMock(self):
# def __init__(self, level=logging.DEBUG):
# def counts(self):
# def messages(self):
# def exc_infos(self):
# def emit(self, record):
# def reset(self):
# def close(self):
. Output only the next line. | self.master_mock.assert_has_calls(master_calls) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
# Copyright (C) 2014 Yahoo! Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class TimingTest(test.TestCase):
def test_convert_fail(self):
for baddie in ["abc123", "-1", "", object()]:
self.assertRaises(ValueError,
timing.convert_to_timeout, baddie)
def test_convert_noop(self):
t = timing.convert_to_timeout(1.0)
t2 = timing.convert_to_timeout(t)
self.assertEqual(t, t2)
<|code_end|>
, generate the next line using the imports in this file:
import networkx as nx
from six.moves import cPickle as pickle
from taskflow import test
from taskflow.types import graph
from taskflow.types import sets
from taskflow.types import timing
from taskflow.types import tree
and context (functions, classes, or occasionally code) from other files:
# Path: taskflow/test.py
# class GreaterThanEqual(object):
# class FailureRegexpMatcher(object):
# class ItemsEqual(object):
# class TestCase(base.BaseTestCase):
# class ReRaiseOtherTypes(object):
# class CaptureMatchee(object):
# class MockTestCase(TestCase):
# class CapturingLoggingHandler(logging.Handler):
# def __init__(self, source):
# def match(self, other):
# def __init__(self, exc_class, pattern):
# def match(self, failure):
# def __init__(self, seq):
# def match(self, other):
# def makeTmpDir(self):
# def assertDictEqual(self, expected, check):
# def assertRaisesAttrAccess(self, exc_class, obj, attr_name):
# def access_func():
# def assertRaisesRegex(self, exc_class, pattern, callable_obj,
# *args, **kwargs):
# def match(self, matchee):
# def match(self, matchee):
# def assertGreater(self, first, second):
# def assertGreaterEqual(self, first, second):
# def assertRegexpMatches(self, text, pattern):
# def assertIsSuperAndSubsequence(self, super_seq, sub_seq, msg=None):
# def assertFailuresRegexp(self, exc_class, pattern, callable_obj, *args,
# **kwargs):
# def assertCountEqual(self, seq1, seq2, msg=None):
# def setUp(self):
# def patch(self, target, autospec=True, **kwargs):
# def patchClass(self, module, name, autospec=True, attach_as=None):
# def resetMasterMock(self):
# def __init__(self, level=logging.DEBUG):
# def counts(self):
# def messages(self):
# def exc_infos(self):
# def emit(self, record):
# def reset(self):
# def close(self):
#
# Path: taskflow/types/graph.py
# def _common_format(g, edge_notation):
# def __init__(self, incoming_graph_data=None, name=''):
# def freeze(self):
# def export_to_dot(self):
# def pformat(self):
# def add_edge(self, u, v, attr_dict=None, **attr):
# def add_node(self, n, attr_dict=None, **attr):
# def fresh_copy(self):
# def __init__(self, incoming_graph_data=None, name=''):
# def freeze(self):
# def get_edge_data(self, u, v, default=None):
# def topological_sort(self):
# def pformat(self):
# def export_to_dot(self):
# def is_directed_acyclic(self):
# def no_successors_iter(self):
# def no_predecessors_iter(self):
# def bfs_predecessors_iter(self, n):
# def add_edge(self, u, v, attr_dict=None, **attr):
# def add_node(self, n, attr_dict=None, **attr):
# def fresh_copy(self):
# def fresh_copy(self):
# def fresh_copy(self):
# def merge_graphs(graph, *graphs, **kwargs):
# class Graph(nx.Graph):
# class DiGraph(nx.DiGraph):
# class OrderedDiGraph(DiGraph):
# class OrderedGraph(Graph):
#
# Path: taskflow/types/sets.py
# def _merge_in(target, iterable=None, sentinel=_sentinel):
# def __init__(self, iterable=None):
# def __hash__(self):
# def __contains__(self, value):
# def __len__(self):
# def __iter__(self):
# def __setstate__(self, items):
# def __getstate__(self):
# def __repr__(self):
# def copy(self):
# def intersection(self, *sets):
# def absorb_it(sets):
# def issuperset(self, other):
# def issubset(self, other):
# def difference(self, *sets):
# def absorb_it(sets):
# def union(self, *sets):
# class OrderedSet(abc.Set, abc.Hashable):
. Output only the next line. | def test_interrupt(self): |
Predict the next line for this snippet: <|code_start|>CEO
|__Infra
| |__Infra.1
|__Mail
|__Search
|__Search.1
"""
self.assertEqual(expected.strip(), root.pformat())
root[-1].add(tree.Node("Search.2"))
expected = """
CEO
|__Infra
| |__Infra.1
|__Mail
|__Search
|__Search.1
|__Search.2
"""
self.assertEqual(expected.strip(), root.pformat())
root[0].add(tree.Node("Infra.2"))
expected = """
CEO
|__Infra
| |__Infra.1
| |__Infra.2
|__Mail
|__Search
|__Search.1
<|code_end|>
with the help of current file imports:
import networkx as nx
from six.moves import cPickle as pickle
from taskflow import test
from taskflow.types import graph
from taskflow.types import sets
from taskflow.types import timing
from taskflow.types import tree
and context from other files:
# Path: taskflow/test.py
# class GreaterThanEqual(object):
# class FailureRegexpMatcher(object):
# class ItemsEqual(object):
# class TestCase(base.BaseTestCase):
# class ReRaiseOtherTypes(object):
# class CaptureMatchee(object):
# class MockTestCase(TestCase):
# class CapturingLoggingHandler(logging.Handler):
# def __init__(self, source):
# def match(self, other):
# def __init__(self, exc_class, pattern):
# def match(self, failure):
# def __init__(self, seq):
# def match(self, other):
# def makeTmpDir(self):
# def assertDictEqual(self, expected, check):
# def assertRaisesAttrAccess(self, exc_class, obj, attr_name):
# def access_func():
# def assertRaisesRegex(self, exc_class, pattern, callable_obj,
# *args, **kwargs):
# def match(self, matchee):
# def match(self, matchee):
# def assertGreater(self, first, second):
# def assertGreaterEqual(self, first, second):
# def assertRegexpMatches(self, text, pattern):
# def assertIsSuperAndSubsequence(self, super_seq, sub_seq, msg=None):
# def assertFailuresRegexp(self, exc_class, pattern, callable_obj, *args,
# **kwargs):
# def assertCountEqual(self, seq1, seq2, msg=None):
# def setUp(self):
# def patch(self, target, autospec=True, **kwargs):
# def patchClass(self, module, name, autospec=True, attach_as=None):
# def resetMasterMock(self):
# def __init__(self, level=logging.DEBUG):
# def counts(self):
# def messages(self):
# def exc_infos(self):
# def emit(self, record):
# def reset(self):
# def close(self):
#
# Path: taskflow/types/graph.py
# def _common_format(g, edge_notation):
# def __init__(self, incoming_graph_data=None, name=''):
# def freeze(self):
# def export_to_dot(self):
# def pformat(self):
# def add_edge(self, u, v, attr_dict=None, **attr):
# def add_node(self, n, attr_dict=None, **attr):
# def fresh_copy(self):
# def __init__(self, incoming_graph_data=None, name=''):
# def freeze(self):
# def get_edge_data(self, u, v, default=None):
# def topological_sort(self):
# def pformat(self):
# def export_to_dot(self):
# def is_directed_acyclic(self):
# def no_successors_iter(self):
# def no_predecessors_iter(self):
# def bfs_predecessors_iter(self, n):
# def add_edge(self, u, v, attr_dict=None, **attr):
# def add_node(self, n, attr_dict=None, **attr):
# def fresh_copy(self):
# def fresh_copy(self):
# def fresh_copy(self):
# def merge_graphs(graph, *graphs, **kwargs):
# class Graph(nx.Graph):
# class DiGraph(nx.DiGraph):
# class OrderedDiGraph(DiGraph):
# class OrderedGraph(Graph):
#
# Path: taskflow/types/sets.py
# def _merge_in(target, iterable=None, sentinel=_sentinel):
# def __init__(self, iterable=None):
# def __hash__(self):
# def __contains__(self, value):
# def __len__(self):
# def __iter__(self):
# def __setstate__(self, items):
# def __getstate__(self):
# def __repr__(self):
# def copy(self):
# def intersection(self, *sets):
# def absorb_it(sets):
# def issuperset(self, other):
# def issubset(self, other):
# def difference(self, *sets):
# def absorb_it(sets):
# def union(self, *sets):
# class OrderedSet(abc.Set, abc.Hashable):
, which may contain function names, class names, or code. Output only the next line. | |__Search.2 |
Based on the snippet: <|code_start|>class TimingTest(test.TestCase):
def test_convert_fail(self):
for baddie in ["abc123", "-1", "", object()]:
self.assertRaises(ValueError,
timing.convert_to_timeout, baddie)
def test_convert_noop(self):
t = timing.convert_to_timeout(1.0)
t2 = timing.convert_to_timeout(t)
self.assertEqual(t, t2)
def test_interrupt(self):
t = timing.convert_to_timeout(1.0)
self.assertFalse(t.is_stopped())
t.interrupt()
self.assertTrue(t.is_stopped())
def test_reset(self):
t = timing.convert_to_timeout(1.0)
t.interrupt()
self.assertTrue(t.is_stopped())
t.reset()
self.assertFalse(t.is_stopped())
def test_values(self):
for v, e_v in [("1.0", 1.0), (1, 1.0),
("2.0", 2.0)]:
t = timing.convert_to_timeout(v)
self.assertEqual(e_v, t.value)
<|code_end|>
, predict the immediate next line with the help of imports:
import networkx as nx
from six.moves import cPickle as pickle
from taskflow import test
from taskflow.types import graph
from taskflow.types import sets
from taskflow.types import timing
from taskflow.types import tree
and context (classes, functions, sometimes code) from other files:
# Path: taskflow/test.py
# class GreaterThanEqual(object):
# class FailureRegexpMatcher(object):
# class ItemsEqual(object):
# class TestCase(base.BaseTestCase):
# class ReRaiseOtherTypes(object):
# class CaptureMatchee(object):
# class MockTestCase(TestCase):
# class CapturingLoggingHandler(logging.Handler):
# def __init__(self, source):
# def match(self, other):
# def __init__(self, exc_class, pattern):
# def match(self, failure):
# def __init__(self, seq):
# def match(self, other):
# def makeTmpDir(self):
# def assertDictEqual(self, expected, check):
# def assertRaisesAttrAccess(self, exc_class, obj, attr_name):
# def access_func():
# def assertRaisesRegex(self, exc_class, pattern, callable_obj,
# *args, **kwargs):
# def match(self, matchee):
# def match(self, matchee):
# def assertGreater(self, first, second):
# def assertGreaterEqual(self, first, second):
# def assertRegexpMatches(self, text, pattern):
# def assertIsSuperAndSubsequence(self, super_seq, sub_seq, msg=None):
# def assertFailuresRegexp(self, exc_class, pattern, callable_obj, *args,
# **kwargs):
# def assertCountEqual(self, seq1, seq2, msg=None):
# def setUp(self):
# def patch(self, target, autospec=True, **kwargs):
# def patchClass(self, module, name, autospec=True, attach_as=None):
# def resetMasterMock(self):
# def __init__(self, level=logging.DEBUG):
# def counts(self):
# def messages(self):
# def exc_infos(self):
# def emit(self, record):
# def reset(self):
# def close(self):
#
# Path: taskflow/types/graph.py
# def _common_format(g, edge_notation):
# def __init__(self, incoming_graph_data=None, name=''):
# def freeze(self):
# def export_to_dot(self):
# def pformat(self):
# def add_edge(self, u, v, attr_dict=None, **attr):
# def add_node(self, n, attr_dict=None, **attr):
# def fresh_copy(self):
# def __init__(self, incoming_graph_data=None, name=''):
# def freeze(self):
# def get_edge_data(self, u, v, default=None):
# def topological_sort(self):
# def pformat(self):
# def export_to_dot(self):
# def is_directed_acyclic(self):
# def no_successors_iter(self):
# def no_predecessors_iter(self):
# def bfs_predecessors_iter(self, n):
# def add_edge(self, u, v, attr_dict=None, **attr):
# def add_node(self, n, attr_dict=None, **attr):
# def fresh_copy(self):
# def fresh_copy(self):
# def fresh_copy(self):
# def merge_graphs(graph, *graphs, **kwargs):
# class Graph(nx.Graph):
# class DiGraph(nx.DiGraph):
# class OrderedDiGraph(DiGraph):
# class OrderedGraph(Graph):
#
# Path: taskflow/types/sets.py
# def _merge_in(target, iterable=None, sentinel=_sentinel):
# def __init__(self, iterable=None):
# def __hash__(self):
# def __contains__(self, value):
# def __len__(self):
# def __iter__(self):
# def __setstate__(self, items):
# def __getstate__(self):
# def __repr__(self):
# def copy(self):
# def intersection(self, *sets):
# def absorb_it(sets):
# def issuperset(self, other):
# def issubset(self, other):
# def difference(self, *sets):
# def absorb_it(sets):
# def union(self, *sets):
# class OrderedSet(abc.Set, abc.Hashable):
. Output only the next line. | def test_fail(self): |
Based on the snippet: <|code_start|>
else:
val = self.__get_bool('no' + backend)
if val:
snap.config.options.target_backends[backend] = False
of = self.__get_string('outputformat')
sf = self.__get_string('snapfile')
ll = self.__get_string('loglevel')
enp = self.__get_string('encryption_password')
if of != None:
snap.config.options.outputformat = of
if sf != None:
snap.config.options.snapfile = sf
if ll != None:
snap.config.options.log_level = ll
if enp != None:
snap.config.options.encryption_password = enp
services = self.__get_array('services')
if services:
for k, v in services:
snap.config.options.service_options[k] = v
class Config:
"""The configuration manager, used to set and verify snap config values
from the config file and command line. Primary interface to the
Configuration System"""
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import os.path
import optparse, ConfigParser
import snap
from snap.options import *
from snap.snapshottarget import SnapshotTarget
from snap.exceptions import ArgError
and context (classes, functions, sometimes code) from other files:
# Path: snap/snapshottarget.py
# class SnapshotTarget:
# """Abstract entity on which to perform and restore a snapshot"""
#
# # actual target backends snap implements (in the order which they are to execute)
# BACKENDS = ['repos', 'packages', 'files', 'services']
#
# def backup(self, basedir):
# '''Take a snapshot of the target
#
# @param - basedir - directory which to store snapshot data in'''
# raise NotImplementedError()
#
# def restore(self, basedir):
# '''Restore any package management files previously backed up
#
# @param - basedir - directory which to restore snapshot from'''
# raise NotImplementedError()
#
# Path: snap/exceptions.py
# class ArgError(SnapError):
# """An illegal arguement to the system was specified or an invalid
# option set was detected in ConfigManager.verify_integrity()"""
#
# def __init__(self,message = ''):
# SnapError.__init__(self, message)
. Output only the next line. | configoptions = None |
Given the following code snippet before the placeholder: <|code_start|>
else:
val = self.__get_bool('no' + backend)
if val:
snap.config.options.target_backends[backend] = False
of = self.__get_string('outputformat')
sf = self.__get_string('snapfile')
ll = self.__get_string('loglevel')
enp = self.__get_string('encryption_password')
if of != None:
snap.config.options.outputformat = of
if sf != None:
snap.config.options.snapfile = sf
if ll != None:
snap.config.options.log_level = ll
if enp != None:
snap.config.options.encryption_password = enp
services = self.__get_array('services')
if services:
for k, v in services:
snap.config.options.service_options[k] = v
class Config:
"""The configuration manager, used to set and verify snap config values
from the config file and command line. Primary interface to the
Configuration System"""
<|code_end|>
, predict the next line using imports from the current file:
import os
import os.path
import optparse, ConfigParser
import snap
from snap.options import *
from snap.snapshottarget import SnapshotTarget
from snap.exceptions import ArgError
and context including class names, function names, and sometimes code from other files:
# Path: snap/snapshottarget.py
# class SnapshotTarget:
# """Abstract entity on which to perform and restore a snapshot"""
#
# # actual target backends snap implements (in the order which they are to execute)
# BACKENDS = ['repos', 'packages', 'files', 'services']
#
# def backup(self, basedir):
# '''Take a snapshot of the target
#
# @param - basedir - directory which to store snapshot data in'''
# raise NotImplementedError()
#
# def restore(self, basedir):
# '''Restore any package management files previously backed up
#
# @param - basedir - directory which to restore snapshot from'''
# raise NotImplementedError()
#
# Path: snap/exceptions.py
# class ArgError(SnapError):
# """An illegal arguement to the system was specified or an invalid
# option set was detected in ConfigManager.verify_integrity()"""
#
# def __init__(self,message = ''):
# SnapError.__init__(self, message)
. Output only the next line. | configoptions = None |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/python
#
# test/tdltest.py unit test suite for snap.metadata.tdl
#
# (C) Copyright 2012 Mo Morsi (mo@morsi.org)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, Version 3,
# as published by the Free Software Foundation
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
class TDLFileTest(unittest.TestCase):
def testInvalidSnapdirectoryShouldRaiseError(self):
with self.assertRaises(MissingDirError) as context:
TDLFile('foo', '/invalid/dir')
self.assertEqual(context.exception.message, '/invalid/dir is an invalid snap working directory ')
def testWriteTDLFile(self):
snapdir = os.path.join(os.path.dirname(__file__), "data")
tdlfile = TDLFile(os.path.join(snapdir, "test.tdl"), snapdir)
tdlfile.write()
tf = open(os.path.join(snapdir, "test.tdl"), 'r')
<|code_end|>
with the help of current file imports:
import os
import unittest
from snap.exceptions import MissingDirError
from snap.metadata.tdl import TDLFile
and context from other files:
# Path: snap/exceptions.py
# class MissingDirError(FilesystemError):
# """A required directory was not found"""
#
# def __init__(self,message = ''):
# FilesystemError.__init__(self, message)
#
# Path: snap/metadata/tdl.py
# class TDLFile:
# """The tdl, the end result of the backup operation.
# This can be processed with imagefactory/oz"""
#
#
# def __init__(self, tdlfile, snapdirectory):
# '''initialize the tdl
#
# @param tdlfile - the path to the tdlfile to write
# @param snapdirectory - the path to the directory to compress/extract
# @raises - MissingDirError - if the snapdirectory is invalid
# '''
# if not os.path.isdir(snapdirectory):
# raise MissingDirError(snapdirectory + " is an invalid snap working directory ")
# self.tdlfile = tdlfile
# self.snapdirectory = snapdirectory
#
# def write(self):
# '''create a tdl from the snapdirectory
#
# @raises - MissingFileError - if the tdl cannot be created
# '''
# # contents of the tdl
# contents = "<template>\n"
# contents += " <name>snap-</name>\n"
# contents += " <description>snap generated tdl</description>\n"
#
# # temp store the working directory, before changing to the snapdirectory
# cwd = os.getcwd()
# os.chdir(self.snapdirectory)
#
# # TODO store generic operating system information
# contents += " <os>\n"
# contents += " <name></name>\n"
# contents += " <version></version>\n"
# contents += " <arch></arch>\n"
#
# # populate repo list in tdl
# record = ReposRecordFile(self.snapdirectory + "/repos.xml")
# repos = record.read()
# for repo in repos:
# contents += " <install type='url'>\n"
# contents += " <url>"+repo.url+"</url>\n"
# contents += " </install>\n"
#
# contents += " </os>\n"
#
# # populate package list in tdl
# contents += " <packages>\n"
#
# record = PackagesRecordFile(self.snapdirectory + "/packages.xml")
# packages = record.read()
# for pkg in packages:
# # TODO decode package (need to use package subsystem type from snapshot metadata)
# contents += " <package>" + pkg.name + "</package>\n"
#
# contents += " </packages>\n"
#
# # TODO populate service list + config in tdl
#
# # TODO populate file list in tdl (how to make those files available for image creation?)
#
# contents += "</template>"
#
# # create the tdl
# tdl = open(self.tdlfile, "w")
# tdl.write(contents)
# tdl.close()
#
# if snap.config.options.log_level_at_least('normal'):
# snap.callback.snapcallback.message("TDL " + self.tdlfile + " created")
#
# # restore the working directory
# os.chdir(cwd)
, which may contain function names, class names, or code. Output only the next line. | contents = tf.read() |
Predict the next line after this snippet: <|code_start|> self.assertEqual('C:\\', OS.get_root('windows'))
@unittest.skipUnless(OS.is_windows(), "only relevant for windows")
def testWindowsRoot(self):
self.assertEqual('C:\\', OS.get_root())
@unittest.skipUnless(OS.is_linux(), "only relevant for linux")
def testLinuxRoot(self):
self.assertEqual('/', OS.get_root())
def testPathSeperator(self):
self.assertEqual('/', OS.get_path_seperator('fedora'))
self.assertEqual('/', OS.get_path_seperator('ubuntu'))
self.assertEqual('\\', OS.get_path_seperator('windows'))
@unittest.skipUnless(OS.is_windows(), "only relevant for windows")
def testWindowsPathSeperator(self):
self.assertEqual('\\', OS.get_path_seperator())
@unittest.skipUnless(OS.is_linux(), "only relevant for linux")
def testLinuxPathSeperator(self):
self.assertEqual('/', OS.get_path_seperator())
#def testDefaultBackendForTarget(self):
@unittest.skipUnless(OS.is_windows(), "only relevant for windows")
def testWindowsNullFile(self):
self.assertEqual("nul", OSUtils.null_file())
@unittest.skipUnless(OS.is_linux(), "only relevant for linux")
<|code_end|>
using the current file's imports:
import os
import re
import shutil
import unittest
import tempfile
import subprocess
import pwd
from snap.osregistry import OS, OSUtils
and any relevant context from other files:
# Path: snap/osregistry.py
# class OS:
# '''helper methods to perform OS level operations'''
#
# current_os = lookup()
#
# def is_linux(operating_system=None):
# '''return true if we're running a linux system'''
# if operating_system == None:
# operating_system = OS.current_os
# return operating_system in ['fedora', 'rhel', 'centos', 'ubuntu', 'debian', 'mock']
# is_linux = staticmethod(is_linux)
#
# def is_windows(operating_system=None):
# '''return true if we're running an apt based system'''
# if operating_system == None:
# operating_system = OS.current_os
# return operating_system in ['windows', 'mock_windows']
# is_windows = staticmethod(is_windows)
#
# def apt_based(operating_system=None):
# '''return true if we're running an apt based system'''
# if operating_system == None:
# operating_system = OS.current_os
# return operating_system in ['ubuntu', 'debian']
# apt_based = staticmethod(apt_based)
#
# def yum_based(operating_system=None):
# '''return true if we're running an yum based system'''
# if operating_system == None:
# operating_system = OS.current_os
# return operating_system in ['fedora', 'rhel', 'centos']
# yum_based = staticmethod(yum_based)
#
# def get_root(operating_system=None):
# '''return the root directory for the specified os'''
# return 'C:\\' if OS.is_windows(operating_system) else '/'
# get_root = staticmethod(get_root)
#
# def get_path_seperator(operating_system=None):
# return '\\' if OS.is_windows(operating_system) else '/'
# get_path_seperator = staticmethod(get_path_seperator)
#
# def default_backend_for_target(target, operating_system=None):
# '''return the default backend configured for the given os / snapshot target'''
# if operating_system == None:
# operating_system = OS.current_os
# return DEFAULT_BACKENDS[operating_system][target]
# default_backend_for_target = staticmethod(default_backend_for_target)
#
# class OSUtils:
#
# def null_file():
# if OS.is_windows():
# return 'nul'
# else:
# return '/dev/null'
# null_file = staticmethod(null_file)
#
# def chown(cfile, uid=None, gid=None, username=None):
# if os.path.isdir(cfile):
# for f in os.listdir(cfile):
# OSUtils.chown(os.path.join(cfile, f),
# uid=uid, gid=gid, username=username)
#
# if OS.is_windows() and username != None:
# # we don't actually change owner, just assign the user full permissions
# null_file = open(OSUtils.null_file(), 'w')
# popen = subprocess.Popen(["icacls", cfile, "/grant:r", username + ":F"],
# stdout=null_file, stderr=null_file)
# popen.wait()
# elif OS.is_linux():
# if (uid == None or gid == None) and username != None:
# import pwd
# user = pwd.getpwnam(username)
# uid = user.pw_uid
# gid = user.pw_gid
# if uid != None and gid != None:
# os.chown(cfile, uid, gid)
# chown = staticmethod(chown)
#
# def is_superuser():
# if OS.is_windows():
# # checks if snap is running under elevated privileges
# # Note this means more than running it as a user in the admin group. You must launch
# # snaptool, the snap gui, or the development environment (cmd terminal, eclipse, or other)
# # by right clicking the program and selecting 'run as administrator',
# # even if your user is marked as an admin in the windows users control panel
#
# # XXX hacky way of doing this, but simplest way I could find outside of using the win32 api
# try:
# file("C:\Windows\snap-check", "w")
# except IOError, e:
# return False
#
# # We also check to see if the current user is in the admin group
# user_name = os.environ["USERNAME"]
# process = subprocess.Popen(["net", "localgroup", "administrators"], stdout=subprocess.PIPE)
# while True:
# line = process.stdout.readline()
# if not line:
# return False
# if re.match("^.*" + user_name + ".*$", line):
# return True
# else:
# return os.geteuid() == 0
# is_superuser = staticmethod(is_superuser)
. Output only the next line. | def testLinuxNullFile(self): |
Here is a snippet: <|code_start|> basefile = os.path.join(self.basedir, "foo")
f = open(basefile, "w")
f.write("foo")
f.close
OSUtils.chown(self.basedir, uid=100, gid=100)
st = os.stat(self.basedir)
self.assertEqual(100, st.st_uid)
self.assertEqual(100, st.st_gid)
st = os.stat(basefile)
self.assertEqual(100, st.st_uid)
self.assertEqual(100, st.st_gid)
pwo = pwd.getpwnam("nobody")
uid = pwo.pw_uid
gid = pwo.pw_gid
OSUtils.chown(self.basedir, username="nobody")
st = os.stat(self.basedir)
self.assertEqual(uid, st.st_uid)
self.assertEqual(gid, st.st_gid)
st = os.stat(basefile)
self.assertEqual(uid, st.st_uid)
self.assertEqual(gid, st.st_gid)
#@unittest.skipUnless(OS.is_windows(), "only relevant for windows")
#def testWindowsIsSuperUser(self):
# not sure how to switch users on windows to test this
@unittest.skipUnless(OS.is_linux(), "only relevant for linux")
def testLinuxIsSuperUser(self):
<|code_end|>
. Write the next line using the current file imports:
import os
import re
import shutil
import unittest
import tempfile
import subprocess
import pwd
from snap.osregistry import OS, OSUtils
and context from other files:
# Path: snap/osregistry.py
# class OS:
# '''helper methods to perform OS level operations'''
#
# current_os = lookup()
#
# def is_linux(operating_system=None):
# '''return true if we're running a linux system'''
# if operating_system == None:
# operating_system = OS.current_os
# return operating_system in ['fedora', 'rhel', 'centos', 'ubuntu', 'debian', 'mock']
# is_linux = staticmethod(is_linux)
#
# def is_windows(operating_system=None):
# '''return true if we're running an apt based system'''
# if operating_system == None:
# operating_system = OS.current_os
# return operating_system in ['windows', 'mock_windows']
# is_windows = staticmethod(is_windows)
#
# def apt_based(operating_system=None):
# '''return true if we're running an apt based system'''
# if operating_system == None:
# operating_system = OS.current_os
# return operating_system in ['ubuntu', 'debian']
# apt_based = staticmethod(apt_based)
#
# def yum_based(operating_system=None):
# '''return true if we're running an yum based system'''
# if operating_system == None:
# operating_system = OS.current_os
# return operating_system in ['fedora', 'rhel', 'centos']
# yum_based = staticmethod(yum_based)
#
# def get_root(operating_system=None):
# '''return the root directory for the specified os'''
# return 'C:\\' if OS.is_windows(operating_system) else '/'
# get_root = staticmethod(get_root)
#
# def get_path_seperator(operating_system=None):
# return '\\' if OS.is_windows(operating_system) else '/'
# get_path_seperator = staticmethod(get_path_seperator)
#
# def default_backend_for_target(target, operating_system=None):
# '''return the default backend configured for the given os / snapshot target'''
# if operating_system == None:
# operating_system = OS.current_os
# return DEFAULT_BACKENDS[operating_system][target]
# default_backend_for_target = staticmethod(default_backend_for_target)
#
# class OSUtils:
#
# def null_file():
# if OS.is_windows():
# return 'nul'
# else:
# return '/dev/null'
# null_file = staticmethod(null_file)
#
# def chown(cfile, uid=None, gid=None, username=None):
# if os.path.isdir(cfile):
# for f in os.listdir(cfile):
# OSUtils.chown(os.path.join(cfile, f),
# uid=uid, gid=gid, username=username)
#
# if OS.is_windows() and username != None:
# # we don't actually change owner, just assign the user full permissions
# null_file = open(OSUtils.null_file(), 'w')
# popen = subprocess.Popen(["icacls", cfile, "/grant:r", username + ":F"],
# stdout=null_file, stderr=null_file)
# popen.wait()
# elif OS.is_linux():
# if (uid == None or gid == None) and username != None:
# import pwd
# user = pwd.getpwnam(username)
# uid = user.pw_uid
# gid = user.pw_gid
# if uid != None and gid != None:
# os.chown(cfile, uid, gid)
# chown = staticmethod(chown)
#
# def is_superuser():
# if OS.is_windows():
# # checks if snap is running under elevated privileges
# # Note this means more than running it as a user in the admin group. You must launch
# # snaptool, the snap gui, or the development environment (cmd terminal, eclipse, or other)
# # by right clicking the program and selecting 'run as administrator',
# # even if your user is marked as an admin in the windows users control panel
#
# # XXX hacky way of doing this, but simplest way I could find outside of using the win32 api
# try:
# file("C:\Windows\snap-check", "w")
# except IOError, e:
# return False
#
# # We also check to see if the current user is in the admin group
# user_name = os.environ["USERNAME"]
# process = subprocess.Popen(["net", "localgroup", "administrators"], stdout=subprocess.PIPE)
# while True:
# line = process.stdout.readline()
# if not line:
# return False
# if re.match("^.*" + user_name + ".*$", line):
# return True
# else:
# return os.geteuid() == 0
# is_superuser = staticmethod(is_superuser)
, which may include functions, classes, or code. Output only the next line. | ouid = os.geteuid() |
Predict the next line after this snippet: <|code_start|> for target in backends.keys():
backend_classes.append(backends[target].__class__)
self.assertEqual('mock', snap.config.options.target_backends['repos'])
self.assertEqual('mock', snap.config.options.target_backends['packages'])
self.assertEqual('mock', snap.config.options.target_backends['files'])
self.assertEqual('mock', snap.config.options.target_backends['services'])
self.assertIn(snap.backends.repos.mock.Mock, backend_classes)
self.assertIn(snap.backends.packages.mock.Mock, backend_classes)
self.assertIn(snap.backends.files.mock.Mock, backend_classes)
self.assertIn(snap.backends.services.mock.Mock, backend_classes)
def testBackup(self):
self.snapbase.backup()
self.assertTrue(snap.backends.repos.mock.Mock.backup_called)
self.assertTrue(snap.backends.packages.mock.Mock.backup_called)
self.assertTrue(snap.backends.files.mock.Mock.backup_called)
self.assertTrue(snap.backends.services.mock.Mock.backup_called)
self.assertTrue(os.path.exists(snap.config.options.snapfile))
os.remove(snap.config.options.snapfile)
def testRestore(self):
# to generate the snapfile
self.snapbase.backup()
<|code_end|>
using the current file's imports:
import os
import types
import unittest
import tempfile
import snap
from snap.exceptions import InsufficientPermissionError
and any relevant context from other files:
# Path: snap/exceptions.py
# class InsufficientPermissionError(SnapError):
# """The user does not have permission to perform the requested operation"""
#
# def __init__(self,message = ''):
# SnapError.__init__(self, message)
. Output only the next line. | self.snapbase.restore() |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/python
#
# test/aptbackendtest.py unit test suite for apt snap backends
#
# (C) Copyright 2011 Mo Morsi (mo@morsi.org)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, Version 3,
# as published by the Free Software Foundation
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
class AptBackendTest(unittest.TestCase):
def setUp(self):
self.fs_root = os.path.join(os.path.dirname(__file__), "data/fs_root")
if os.path.isdir(self.fs_root):
shutil.rmtree(self.fs_root)
<|code_end|>
using the current file's imports:
import os
import shutil
import unittest
import apt
import snap
import snap.backends.files.sapt
import snap.backends.repos.sapt
import snap.backends.packages.sapt
from snap.metadata.sfile import FilesRecordFile
from snap.metadata.package import PackagesRecordFile
from snap.metadata.repo import ReposRecordFile
from snap.packageregistry import PackageRegistry
and any relevant context from other files:
# Path: snap/metadata/sfile.py
# class FilesRecordFile:
# '''a snap files record file, contains list of files modified, to restore'''
#
# def __init__(self, recordfile):
# self.recordfile = recordfile
#
# def write(self, sfiles=[]):
# '''generate file containing record of specified files
#
# @param files - the list of SFiles to record
# '''
# f = open(self.recordfile, 'w')
# f.write('<files>')
# for sfile in sfiles:
# f.write('<file>' + xml.sax.saxutils.escape(sfile.path) + '</file>')
# f.write('</files>')
# f.close()
#
# def read(self):
# '''restore the files stored in and tracked by the record file in the targetdir'''
# parser = xml.sax.make_parser()
# parser.setFeature(xml.sax.handler.feature_namespaces, 0)
# handler = _FilesRecordFileParser()
# parser.setContentHandler(handler)
# parser.parse(self.recordfile)
# return handler.files
#
# Path: snap/metadata/package.py
# class PackagesRecordFile:
# '''a snap package record file, contains list of packages installed, to restore'''
#
# def __init__(self, filename):
# '''initialize the file
#
# @param filename - path to the file
# '''
#
# self.packagefile = filename
#
# def write(self, packages):
# '''generate file containing record of packages
#
# @param packages - list of Packages to record
# '''
# f=open(self.packagefile, 'w')
# f.write("<packages>")
# for package in packages:
# f.write('<package>' + xml.sax.saxutils.escape(package.name) + '</package>');
# f.write("</packages>")
# f.close()
#
# def read(self):
# '''
# read packages from the file
#
# @returns - list of instances of Package
# '''
# parser = xml.sax.make_parser()
# parser.setFeature(xml.sax.handler.feature_namespaces, 0)
# handler = _PackagesRecordFileParser()
# parser.setContentHandler(handler)
# parser.parse(self.packagefile)
# return handler.packages
#
# Path: snap/metadata/repo.py
# class ReposRecordFile:
# '''a snap repo record file'''
#
# def __init__(self, filename):
# '''initialize the file
#
# @param filename - path to the file
# '''
#
# self.repofile = filename
#
# def write(self, repos):
# '''generate file containing record of repositories
#
# @param repos - list of Repos to record
# '''
# f=open(self.repofile, 'w')
# f.write("<repos>")
# for repo in repos:
# f.write('<repo>')
# f.write(xml.sax.saxutils.escape(repo.url))
# f.write('</repo>');
# f.write("</repos>")
# f.close()
#
# def read(self):
# '''
# read repos from the file
#
# @returns - list of instances of Repo
# '''
# parser = xml.sax.make_parser()
# parser.setFeature(xml.sax.handler.feature_namespaces, 0)
# handler = _ReposRecordFileParser()
# parser.setContentHandler(handler)
# parser.parse(self.repofile)
# return handler.repos
#
# Path: snap/packageregistry.py
# class PackageRegistry:
# PACKAGE_REGISTRY = {
# 'mysql-server' : { 'yum' : 'mysql-server',
# 'apt' : 'mysql-server' },
#
# 'mysql-client' : { 'yum' : 'mysql',
# 'apt' : 'mysql-client' },
#
# 'postgresql-server' : { 'yum' : 'postgresql-server',
# 'apt' : 'postgresql' },
#
# 'postgresql-client' : { 'yum' : 'postgresql',
# 'apt' : 'postgresql-client' },
#
# 'httpd' : { 'yum' : 'postgresql',
# 'apt' : 'postgresql-client' }
# }
#
# PACKAGE_SYSTEM_REGISTRY = { 'yum' : {}, 'apt' : {} }
# for pkg in PACKAGE_REGISTRY:
# PACKAGE_SYSTEM_REGISTRY['yum'][PACKAGE_REGISTRY[pkg]['yum']] = pkg
#
# def encode(package_system, package):
# if package in PackageRegistry.PACKAGE_SYSTEM_REGISTRY[package_system]:
# return PackageRegistry.PACKAGE_SYSTEM_REGISTRY[package_system][package]
# return package
# encode=staticmethod(encode)
#
# def decode(package_system, package):
# if package in PackageRegistry.PACKAGE_REGISTRY:
# return PackageRegistry.PACKAGE_REGISTRY[package][package_system]
# return package
# decode=staticmethod(decode)
. Output only the next line. | os.mkdir(self.fs_root) |
Given snippet: <|code_start|>
class Operation():
def __init__(self, op):
if isinstance(op, list) and len(op) == 2:
if isinstance(op[0], int):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from collections import OrderedDict
from graphenebase.types import (
Uint8, Int16, Uint16, Uint32, Uint64,
Varint32, Int64, String, Bytes, Void,
Array, PointInTime, Signature, Bool,
Set, Fixed_array, Optional, Static_variant,
Map, Id, VoteId, ObjectId,
JsonObj
)
from .chains import known_chains
from .objecttypes import object_type
from .account import PublicKey
from .chains import default_prefix
from .operationids import operations
import json
and context:
# Path: python3-src/graphenebase/chains.py
#
# Path: python3-src/graphenebase/objecttypes.py
#
# Path: python3-src/graphenebase/account.py
# class PublicKey(Address):
# """ This class deals with Public Keys and inherits ``Address``.
#
# :param str pk: Base58 encoded public key
# :param str prefix: Network prefix (defaults to ``GPH``)
#
# Example:::
#
# PublicKey("GPH6UtYWWs3rkZGV8JA86qrgkG6tyFksgECefKE1MiH4HkLD8PFGL")
#
# .. note:: By default, graphene-based networks deal with **compressed**
# public keys. If an **uncompressed** key is required, the
# method ``unCompressed`` can be used::
#
# PublicKey("xxxxx").unCompressed()
#
# """
# def __init__(self, pk, prefix="GPH"):
# self.prefix = prefix
# self._pk = Base58(pk, prefix=prefix)
# self.address = Address(pubkey=pk, prefix=prefix)
# self.pubkey = self._pk
#
# def _derive_y_from_x(self, x, is_even):
# """ Derive y point from x point """
# curve = ecdsa.SECP256k1.curve
# # The curve equation over F_p is:
# # y^2 = x^3 + ax + b
# a, b, p = curve.a(), curve.b(), curve.p()
# alpha = (pow(x, 3, p) + a * x + b) % p
# beta = ecdsa.numbertheory.square_root_mod_prime(alpha, p)
# if (beta % 2) == is_even:
# beta = p - beta
# return beta
#
# def compressed(self):
# """ Derive compressed public key """
# order = ecdsa.SECP256k1.generator.order()
# p = ecdsa.VerifyingKey.from_string(bytes(self), curve=ecdsa.SECP256k1).pubkey.point
# x_str = ecdsa.util.number_to_string(p.x(), order)
# # y_str = ecdsa.util.number_to_string(p.y(), order)
# compressed = hexlify(bytes(chr(2 + (p.y() & 1)), 'ascii') + x_str).decode('ascii')
# return(compressed)
#
# def unCompressed(self):
# """ Derive uncompressed key """
# public_key = repr(self._pk)
# prefix = public_key[0:2]
# if prefix == "04":
# return public_key
# assert prefix == "02" or prefix == "03"
# x = int(public_key[2:], 16)
# y = self._derive_y_from_x(x, (prefix == "02"))
# key = '04' + '%064x' % x + '%064x' % y
# return key
#
# def point(self):
# """ Return the point for the public key """
# string = unhexlify(self.unCompressed())
# return ecdsa.VerifyingKey.from_string(string[1:], curve=ecdsa.SECP256k1).pubkey.point
#
# def __repr__(self):
# """ Gives the hex representation of the Graphene public key. """
# return repr(self._pk)
#
# def __str__(self):
# """ Returns the readable Graphene public key. This call is equivalent to
# ``format(PublicKey, "GPH")``
# """
# return format(self._pk, self.prefix)
#
# def __format__(self, _format):
# """ Formats the instance of:doc:`Base58 <base58>` according to ``_format`` """
# return format(self._pk, _format)
#
# def __bytes__(self):
# """ Returns the raw public key (has length 33)"""
# return bytes(self._pk)
#
# Path: python3-src/graphenebase/chains.py
#
# Path: python3-src/graphenebase/operationids.py
which might include code, classes, or functions. Output only the next line. | self.opId = op[0] |
Continue the code snippet: <|code_start|> else:
if len(args) == 1 and len(kwargs) == 0:
kwargs = args[0]
prefix = kwargs.pop("prefix", default_prefix)
meta = ""
if "json_metadata" in kwargs and kwargs["json_metadata"]:
if isinstance(kwargs["json_metadata"], dict):
meta = json.dumps(kwargs["json_metadata"])
else:
meta = kwargs["json_metadata"]
owner = Permission(kwargs["owner"], prefix=prefix) if "owner" in kwargs else None
active = Permission(kwargs["active"], prefix=prefix) if "active" in kwargs else None
posting = Permission(kwargs["posting"], prefix=prefix) if "posting" in kwargs else None
super().__init__(OrderedDict([
('account', String(kwargs["account"])),
('owner', Optional(owner)),
('active', Optional(active)),
('posting', Optional(posting)),
('memo_key', PublicKey(kwargs["memo_key"], prefix=prefix)),
('json_metadata', String(meta)),
]))
class Transfer(GrapheneObject):
def __init__(self, *args, **kwargs):
if isArgsThisClass(self, args):
self.data = args[0].data
<|code_end|>
. Use current file imports:
import struct
import json
from collections import OrderedDict
from graphenebase.types import (
Uint8, Int16, Uint16, Uint32, Uint64,
Varint32, Int64, String, Bytes, Void,
Array, PointInTime, Signature, Bool,
Set, Fixed_array, Optional, Static_variant,
Map, Id, VoteId, ObjectId,
)
from graphenebase.objects import GrapheneObject, isArgsThisClass
from graphenebase.account import PublicKey
from graphenebase.operations import (
Operation as GrapheneOperation
)
from .operationids import operations
and context (classes, functions, or code) from other files:
# Path: python3-src/steembase/operationids.py
. Output only the next line. | else: |
Predict the next line after this snippet: <|code_start|> pk_url_kwarg = 'image_key'
# def view_full_image(request, image_key):
#
# li = LeafletImage.objects.filter(pk=image_key)
# if li.count() == 1:
# li = get_object_or_404(LeafletImage, image_key=image_key)
# else:
# # Should not do this, we'll need to fix it
# # probably and upload artifact
# li = li.all()[0]
#
# return render_to_response('leaflets/full.html',
# {
# 'image': li,
# 'leaflet': li.leaflet,
# },
# context_instance=RequestContext(request), )
def view_all_full_images(request, leafletid):
leaflet = get_object_or_404(Leaflet, pk=leafletid)
images = LeafletImage.objects.filter(leaflet=leaflet)
return render_to_response('leaflets/full_all.html',
{
'images': images,
'leaflet': leaflet,
},
<|code_end|>
using the current file's imports:
import os
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.contrib.formtools.wizard.views import NamedUrlSessionWizardView
from django.core.urlresolvers import reverse
from django.conf import settings
from django.views.generic import DetailView, ListView, DetailView
from django.core.files.storage import FileSystemStorage
from .models import Leaflet, LeafletImage
from leaflets.models import Leaflet, LeafletImage
and any relevant context from other files:
# Path: electionleaflets/apps/leaflets/models.py
# class Leaflet(models.Model):
# title = models.CharField(blank=True, max_length=765)
# description = models.TextField(blank=True, null=True)
# publisher_party = models.ForeignKey(Party, blank=True, null=True)
# constituency = models.ForeignKey(Constituency, blank=True, null=True)
#
# attacks = models.ManyToManyField(Party, related_name='attacks',
# null=True, blank=True)
# tags = models.ManyToManyField(Tag, through='LeafletTag')
# categories = models.ManyToManyField(Category, through='LeafletCategory')
# imprint = models.TextField(blank=True, null=True)
# postcode = models.CharField(max_length=150, blank=True)
# lng = models.FloatField(blank=True, null=True)
# lat = models.FloatField(blank=True, null=True)
# name = models.CharField(blank=True, max_length=300)
# email = models.CharField(blank=True, max_length=300)
# date_uploaded = models.DateTimeField(auto_now_add=True)
# date_delivered = models.DateTimeField(blank=True, null=True)
# status = models.CharField(choices=constants.LEAFLET_STATUSES,
# null=True, blank=True, max_length=255)
#
# def __unicode__(self):
# return self.title
#
# class Meta:
# ordering = ('date_uploaded',)
#
# def get_absolute_url(self):
# from django.contrib.sites.models import Site
# return 'http://%s/leaflets/%s/' % (Site.objects.get_current().domain,
# self.id)
#
# def get_first_image(self):
# try:
# return self.images.all()[0]
# except IndexError:
# # TODO: Set image_key to value for 'empty' image
# return None
#
# def get_title(self):
# if self.title and len(self.title):
# return self.title
# elif self.publisher_party:
# return '%s leaflet' % self.party.name
# else:
# "Untitled leaflet"
#
# class LeafletImage(models.Model):
# leaflet = models.ForeignKey(Leaflet, related_name='images')
# image = ImageField(upload_to="leaflets")
# legacy_image_key = models.CharField(max_length=255)
# image_type = models.CharField(choices=constants.IMAGE_TYPES,
# null=True, blank=True, max_length=255)
# image_text = models.TextField(blank=True)
#
# class Meta:
# ordering = ['image_type']
#
# def ocr(self):
# if not self.image:
# return ""
#
# from PIL import ImageFilter
#
# image_path = self.image.path
# tmp_image_path = "/tmp/leaflet_image-%s.jpg" % self.legacy_image_key
# # image_file = Image.open(image_path) # open colour image
# # image_file = image_file.filter(ImageFilter.EDGE_ENHANCE)
# # image_file = image_file.filter(ImageFilter.SMOOTH_MORE)
# # image_file = image_file.filter(ImageFilter.FIND_EDGES)
# # image_file = image_file.filter(ImageFilter.DETAIL)
# # image_file = image_file.filter(ImageFilter.MinFilter(3))
# # image_file = image_file.convert('L') # convert image to black and white
# # image_file = ImageEnhance.Contrast(image_file)
# # image_file = image_file.enhance(1.5)
#
# # image_file.save(tmp_image_path, dpi=(300,300))
#
# text = pytesser.image_to_string(image_path)
# text = os.linesep.join([s for s in text.splitlines() if s])
# self.image_text = text
# self.save()
# os.remove(image_path)
# return text
. Output only the next line. | context_instance=RequestContext(request), ) |
Given snippet: <|code_start|># context_instance=RequestContext(request), )
def view_all_full_images(request, leafletid):
leaflet = get_object_or_404(Leaflet, pk=leafletid)
images = LeafletImage.objects.filter(leaflet=leaflet)
return render_to_response('leaflets/full_all.html',
{
'images': images,
'leaflet': leaflet,
},
context_instance=RequestContext(request), )
class LatestLeaflets(ListView):
model = Leaflet
template_name = 'leaflets/index.html'
paginate_by = 60
class LeafletView(DetailView):
template_name = 'leaflets/leaflet.html'
queryset = Leaflet.objects.all()
class LeafletUploadWizzard(NamedUrlSessionWizardView):
TEMPLATES = {
"front": "leaflets/upload_form/image_form.html",
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.contrib.formtools.wizard.views import NamedUrlSessionWizardView
from django.core.urlresolvers import reverse
from django.conf import settings
from django.views.generic import DetailView, ListView, DetailView
from django.core.files.storage import FileSystemStorage
from .models import Leaflet, LeafletImage
from leaflets.models import Leaflet, LeafletImage
and context:
# Path: electionleaflets/apps/leaflets/models.py
# class Leaflet(models.Model):
# title = models.CharField(blank=True, max_length=765)
# description = models.TextField(blank=True, null=True)
# publisher_party = models.ForeignKey(Party, blank=True, null=True)
# constituency = models.ForeignKey(Constituency, blank=True, null=True)
#
# attacks = models.ManyToManyField(Party, related_name='attacks',
# null=True, blank=True)
# tags = models.ManyToManyField(Tag, through='LeafletTag')
# categories = models.ManyToManyField(Category, through='LeafletCategory')
# imprint = models.TextField(blank=True, null=True)
# postcode = models.CharField(max_length=150, blank=True)
# lng = models.FloatField(blank=True, null=True)
# lat = models.FloatField(blank=True, null=True)
# name = models.CharField(blank=True, max_length=300)
# email = models.CharField(blank=True, max_length=300)
# date_uploaded = models.DateTimeField(auto_now_add=True)
# date_delivered = models.DateTimeField(blank=True, null=True)
# status = models.CharField(choices=constants.LEAFLET_STATUSES,
# null=True, blank=True, max_length=255)
#
# def __unicode__(self):
# return self.title
#
# class Meta:
# ordering = ('date_uploaded',)
#
# def get_absolute_url(self):
# from django.contrib.sites.models import Site
# return 'http://%s/leaflets/%s/' % (Site.objects.get_current().domain,
# self.id)
#
# def get_first_image(self):
# try:
# return self.images.all()[0]
# except IndexError:
# # TODO: Set image_key to value for 'empty' image
# return None
#
# def get_title(self):
# if self.title and len(self.title):
# return self.title
# elif self.publisher_party:
# return '%s leaflet' % self.party.name
# else:
# "Untitled leaflet"
#
# class LeafletImage(models.Model):
# leaflet = models.ForeignKey(Leaflet, related_name='images')
# image = ImageField(upload_to="leaflets")
# legacy_image_key = models.CharField(max_length=255)
# image_type = models.CharField(choices=constants.IMAGE_TYPES,
# null=True, blank=True, max_length=255)
# image_text = models.TextField(blank=True)
#
# class Meta:
# ordering = ['image_type']
#
# def ocr(self):
# if not self.image:
# return ""
#
# from PIL import ImageFilter
#
# image_path = self.image.path
# tmp_image_path = "/tmp/leaflet_image-%s.jpg" % self.legacy_image_key
# # image_file = Image.open(image_path) # open colour image
# # image_file = image_file.filter(ImageFilter.EDGE_ENHANCE)
# # image_file = image_file.filter(ImageFilter.SMOOTH_MORE)
# # image_file = image_file.filter(ImageFilter.FIND_EDGES)
# # image_file = image_file.filter(ImageFilter.DETAIL)
# # image_file = image_file.filter(ImageFilter.MinFilter(3))
# # image_file = image_file.convert('L') # convert image to black and white
# # image_file = ImageEnhance.Contrast(image_file)
# # image_file = image_file.enhance(1.5)
#
# # image_file.save(tmp_image_path, dpi=(300,300))
#
# text = pytesser.image_to_string(image_path)
# text = os.linesep.join([s for s in text.splitlines() if s])
# self.image_text = text
# self.save()
# os.remove(image_path)
# return text
which might include code, classes, or functions. Output only the next line. | "postcode": "leaflets/upload_form/postcode.html", |
Here is a snippet: <|code_start|>
class ConstituencyViewSet(viewsets.ModelViewSet):
queryset = Constituency.objects.all()
serializer_class = ConstituencySerializer
<|code_end|>
. Write the next line using the current file imports:
from django.http import HttpResponse
from django.contrib.sites.models import Site
from django.utils.html import escape
from leaflets.models import Leaflet, LeafletImage
from constituencies.models import Constituency
from uk_political_parties.models import Party
from rest_framework import viewsets
from .serializers import (ConstituencySerializer, PartySerializer,
LeafletSerializer, LeafletImageSerializer)
from leaflets.models import Leaflet
and context from other files:
# Path: electionleaflets/apps/api/serializers.py
# class ConstituencySerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# model = Constituency
# fields = (
# 'name',
# )
#
# class PartySerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# model = Party
# fields = (
# 'pk',
# 'party_name',
# 'party_type',
# 'status',
# )
#
# class LeafletSerializer(serializers.HyperlinkedModelSerializer):
# # images = LeafletImageSerializer(many=True, required=False)
# # constituency = ConstituencySerializer(many=True, required=False)
# # publisher_party = PartySerializer(required=False)
#
# def validate(self, data):
# if not data.get('status') or not data.get('images'):
# data['status'] = 'draft'
# return data
#
#
#
# class Meta:
# model = Leaflet
# depth = 1
# fields = (
# 'pk',
# 'title',
# 'description',
# 'publisher_party',
# 'constituency',
# 'images',
# 'date_uploaded',
# 'date_delivered',
# 'status',
# )
#
# class LeafletImageSerializer(serializers.ModelSerializer):
# class Meta:
# model = LeafletImage
# fields = (
# 'leaflet',
# 'image',
# )
# image = serializers.ImageField()
, which may include functions, classes, or code. Output only the next line. | class PartyViewSet(viewsets.ModelViewSet): |
Next line prediction: <|code_start|>class ConstituencyViewSet(viewsets.ModelViewSet):
queryset = Constituency.objects.all()
serializer_class = ConstituencySerializer
class PartyViewSet(viewsets.ModelViewSet):
queryset = Party.objects.all()
serializer_class = PartySerializer
class LeafletImageViewSet(viewsets.ModelViewSet):
queryset = LeafletImage.objects.all()
serializer_class = LeafletImageSerializer
class LeafletViewSet(viewsets.ModelViewSet):
queryset = Leaflet.objects.all()
serializer_class = LeafletSerializer
def latest(request, format):
# TODO: Fix this to work properly
domain = Site.objects.get_current().domain
leaflets = Leaflet.objects.order_by('-id').all()[0:20]
resp = []
for leaflet in leaflets:
d = {}
d['constituency'] = leaflet.constituency() or 'Unknown'
d['constituency'] = str(d['constituency'])
<|code_end|>
. Use current file imports:
(from django.http import HttpResponse
from django.contrib.sites.models import Site
from django.utils.html import escape
from leaflets.models import Leaflet, LeafletImage
from constituencies.models import Constituency
from uk_political_parties.models import Party
from rest_framework import viewsets
from .serializers import (ConstituencySerializer, PartySerializer,
LeafletSerializer, LeafletImageSerializer)
from leaflets.models import Leaflet)
and context including class names, function names, or small code snippets from other files:
# Path: electionleaflets/apps/api/serializers.py
# class ConstituencySerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# model = Constituency
# fields = (
# 'name',
# )
#
# class PartySerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# model = Party
# fields = (
# 'pk',
# 'party_name',
# 'party_type',
# 'status',
# )
#
# class LeafletSerializer(serializers.HyperlinkedModelSerializer):
# # images = LeafletImageSerializer(many=True, required=False)
# # constituency = ConstituencySerializer(many=True, required=False)
# # publisher_party = PartySerializer(required=False)
#
# def validate(self, data):
# if not data.get('status') or not data.get('images'):
# data['status'] = 'draft'
# return data
#
#
#
# class Meta:
# model = Leaflet
# depth = 1
# fields = (
# 'pk',
# 'title',
# 'description',
# 'publisher_party',
# 'constituency',
# 'images',
# 'date_uploaded',
# 'date_delivered',
# 'status',
# )
#
# class LeafletImageSerializer(serializers.ModelSerializer):
# class Meta:
# model = LeafletImage
# fields = (
# 'leaflet',
# 'image',
# )
# image = serializers.ImageField()
. Output only the next line. | d['uploaded_date'] = str(leaflet.date_uploaded) |
Predict the next line for this snippet: <|code_start|>
class ConstituencyViewSet(viewsets.ModelViewSet):
queryset = Constituency.objects.all()
serializer_class = ConstituencySerializer
class PartyViewSet(viewsets.ModelViewSet):
queryset = Party.objects.all()
serializer_class = PartySerializer
class LeafletImageViewSet(viewsets.ModelViewSet):
queryset = LeafletImage.objects.all()
serializer_class = LeafletImageSerializer
class LeafletViewSet(viewsets.ModelViewSet):
queryset = Leaflet.objects.all()
serializer_class = LeafletSerializer
def latest(request, format):
# TODO: Fix this to work properly
domain = Site.objects.get_current().domain
leaflets = Leaflet.objects.order_by('-id').all()[0:20]
resp = []
for leaflet in leaflets:
d = {}
d['constituency'] = leaflet.constituency() or 'Unknown'
<|code_end|>
with the help of current file imports:
from django.http import HttpResponse
from django.contrib.sites.models import Site
from django.utils.html import escape
from leaflets.models import Leaflet, LeafletImage
from constituencies.models import Constituency
from uk_political_parties.models import Party
from rest_framework import viewsets
from .serializers import (ConstituencySerializer, PartySerializer,
LeafletSerializer, LeafletImageSerializer)
from leaflets.models import Leaflet
and context from other files:
# Path: electionleaflets/apps/api/serializers.py
# class ConstituencySerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# model = Constituency
# fields = (
# 'name',
# )
#
# class PartySerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# model = Party
# fields = (
# 'pk',
# 'party_name',
# 'party_type',
# 'status',
# )
#
# class LeafletSerializer(serializers.HyperlinkedModelSerializer):
# # images = LeafletImageSerializer(many=True, required=False)
# # constituency = ConstituencySerializer(many=True, required=False)
# # publisher_party = PartySerializer(required=False)
#
# def validate(self, data):
# if not data.get('status') or not data.get('images'):
# data['status'] = 'draft'
# return data
#
#
#
# class Meta:
# model = Leaflet
# depth = 1
# fields = (
# 'pk',
# 'title',
# 'description',
# 'publisher_party',
# 'constituency',
# 'images',
# 'date_uploaded',
# 'date_delivered',
# 'status',
# )
#
# class LeafletImageSerializer(serializers.ModelSerializer):
# class Meta:
# model = LeafletImage
# fields = (
# 'leaflet',
# 'image',
# )
# image = serializers.ImageField()
, which may contain function names, class names, or code. Output only the next line. | d['constituency'] = str(d['constituency']) |
Predict the next line for this snippet: <|code_start|> domain = Site.objects.get_current().domain
leaflets = Leaflet.objects.order_by('-id').all()[0:20]
resp = []
for leaflet in leaflets:
d = {}
d['constituency'] = leaflet.constituency() or 'Unknown'
d['constituency'] = str(d['constituency'])
d['uploaded_date'] = str(leaflet.date_uploaded)
d['delivery_date'] = str(leaflet.date_delivered)
d['title'] = escape(leaflet.title)
d['description'] = escape(leaflet.description)
d['party'] = escape( leaflet.publisher_party.name )
i = leaflet.get_first_image()
if not isinstance(i, dict):
d['small_image'] = 'http://%s%s' % (domain, i.get_small(),)
d['medium_image'] = 'http://%s%s' % (domain, i.get_medium(),)
d['link'] = leaflet.get_absolute_url()
resp.append( d )
output = '<?xml version="1.0" ?>\n'
output += "<leaflets>"
for d in resp:
output += "<leaflet>"
for k,v in d.iteritems():
output += "<" + k + ">"
output += v
output += "</" + k + ">"
output += "</leaflet>"
<|code_end|>
with the help of current file imports:
from django.http import HttpResponse
from django.contrib.sites.models import Site
from django.utils.html import escape
from leaflets.models import Leaflet, LeafletImage
from constituencies.models import Constituency
from uk_political_parties.models import Party
from rest_framework import viewsets
from .serializers import (ConstituencySerializer, PartySerializer,
LeafletSerializer, LeafletImageSerializer)
from leaflets.models import Leaflet
and context from other files:
# Path: electionleaflets/apps/api/serializers.py
# class ConstituencySerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# model = Constituency
# fields = (
# 'name',
# )
#
# class PartySerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# model = Party
# fields = (
# 'pk',
# 'party_name',
# 'party_type',
# 'status',
# )
#
# class LeafletSerializer(serializers.HyperlinkedModelSerializer):
# # images = LeafletImageSerializer(many=True, required=False)
# # constituency = ConstituencySerializer(many=True, required=False)
# # publisher_party = PartySerializer(required=False)
#
# def validate(self, data):
# if not data.get('status') or not data.get('images'):
# data['status'] = 'draft'
# return data
#
#
#
# class Meta:
# model = Leaflet
# depth = 1
# fields = (
# 'pk',
# 'title',
# 'description',
# 'publisher_party',
# 'constituency',
# 'images',
# 'date_uploaded',
# 'date_delivered',
# 'status',
# )
#
# class LeafletImageSerializer(serializers.ModelSerializer):
# class Meta:
# model = LeafletImage
# fields = (
# 'leaflet',
# 'image',
# )
# image = serializers.ImageField()
, which may contain function names, class names, or code. Output only the next line. | output += "</leaflets>" |
Here is a snippet: <|code_start|>
named_form_list = [
('front', FrontPageImageForm),
('postcode', PostcodeForm),
# ('back', BackPageImageForm),
# ('inside', InsidePageImageForm),
]
upload_form_wizzard = LeafletUploadWizzard.as_view(named_form_list,
url_name='upload_step', done_step_name='finished')
urlpatterns = patterns(
'',
url(r'/add/(?P<step>.+)/$', upload_form_wizzard, name='upload_step'),
url(r'/add/', upload_form_wizzard, name='upload_leaflet'),
<|code_end|>
. Write the next line using the current file imports:
from django.conf.urls import patterns, url
from leaflets.views import (ImageView, LatestLeaflets,
view_all_full_images, LeafletView, LeafletUploadWizzard)
from .forms import (FrontPageImageForm, BackPageImageForm,
InsidePageImageForm, PostcodeForm)
and context from other files:
# Path: electionleaflets/apps/leaflets/forms.py
# class FrontPageImageForm(ImageForm):
# pass
#
# class BackPageImageForm(ImageForm):
# pass
#
# class InsidePageImageForm(ImageForm):
# pass
#
# class PostcodeForm(forms.Form):
# postcode = GBPostcodeField()
, which may include functions, classes, or code. Output only the next line. | url(r'^/full/(?P<image_key>.+)/$', ImageView.as_view(), name='full_image'), |
Given the following code snippet before the placeholder: <|code_start|>
named_form_list = [
('front', FrontPageImageForm),
('postcode', PostcodeForm),
# ('back', BackPageImageForm),
# ('inside', InsidePageImageForm),
]
upload_form_wizzard = LeafletUploadWizzard.as_view(named_form_list,
<|code_end|>
, predict the next line using imports from the current file:
from django.conf.urls import patterns, url
from leaflets.views import (ImageView, LatestLeaflets,
view_all_full_images, LeafletView, LeafletUploadWizzard)
from .forms import (FrontPageImageForm, BackPageImageForm,
InsidePageImageForm, PostcodeForm)
and context including class names, function names, and sometimes code from other files:
# Path: electionleaflets/apps/leaflets/forms.py
# class FrontPageImageForm(ImageForm):
# pass
#
# class BackPageImageForm(ImageForm):
# pass
#
# class InsidePageImageForm(ImageForm):
# pass
#
# class PostcodeForm(forms.Form):
# postcode = GBPostcodeField()
. Output only the next line. | url_name='upload_step', done_step_name='finished') |
Predict the next line after this snippet: <|code_start|> b.extend([astate,bstate])
# catch errors
elif 'D' in B and 'D' in A:
print 'Error: fake bond %s-%s (%s-%s -> %s-%s)' % (a1.name,a2.name,a1.atomtype,a2.atomtype, a1.atomtypeB,a2.atomtypeB)
sys.exit(1)
if astate == None:
print 'Error A: No bond entry found for astate %s-%s (%s-%s -> %s-%s)' % (a1.name,a2.name,a1.atomtype,a2.atomtype, a1.type,a2.type)
print 'Resi = %s' % a1.resname
error_occured = True
if bstate == None:
print 'Error B: No bond entry found for bstate %s-%s (%s-%s -> %s-%s)' % (a1.name,a2.name,a1.atomtypeB,a2.atomtypeB, a1.typeB,a2.typeB)
error_occured = True
if error_occured:
sys.exit(1)
print 'log_> Making bonds for state B -> %d bonds with perturbed atoms' % count
def find_angle_entries(topol):
count = 0
for a in topol.angles:
a1,a2,a3,func = a
astate = None
bstate = None
if a1.atomtypeB is not None or \
a2.atomtypeB is not None or \
a3.atomtypeB is not None:
A, B = check_case([a1,a2,a3])
count+=1
if 'D' in A and 'D' in B: # fake angle
if func==5 :
<|code_end|>
using the current file's imports:
import sys, os, copy
from pmx import *
from pmx.forcefield2 import Topology
from pmx.mutdb import read_mtp_entry
from pmx.parser import kickOutComments
and any relevant context from other files:
# Path: pmx/forcefield2.py
# class Topology( TopolBase ):
#
# # def __init__(self, filename, topfile = None, assign_types = True, cpp_path = [os.environ.get('GMXDATA')+'/top'], cpp_defs = [], version = 'old', ff = 'amber' ):
# def __init__(self, filename, topfile = None, assign_types = True, cpp_path = [os.environ.get('GMXLIB')], cpp_defs = [], version = 'old', ff = 'amber', ffpath=None ):
# TopolBase.__init__(self, filename, version)
# bItp = False
# if not topfile:
# topfile = filename
# bItp = True
# if assign_types:
# l = cpp_parse_file(topfile, cpp_defs = cpp_defs, cpp_path = cpp_path, itp = bItp, ffpath = ffpath)
# l = kickOutComments(l,'#')
# l = kickOutComments(l,';')
# self.BondedParams = BondedParser( l )
# self.NBParams = NBParser( l, version, ff = ff )
# self.assign_fftypes()
#
#
# def set_molecule(self, molname, n):
# mol_exists = False
# for i, mol in enumerate(self.molecules):
# if mol[0] == molname:
# self.molecules[i][1] = n
# mol_exists = True
# if not mol_exists:
# self.molecules.append([molname,n])
#
# def del_molecule(self, molname):
# if not hasattr(molname,"append"):
# molname = [molname]
# new = []
# for m in self.molecules:
# if m[0] not in molname:
# new.append(m)
# self.molecules = new
#
#
# def assign_fftypes(self):
# for atom in self.atoms:
# atom.type = self.NBParams.atomtypes[atom.atomtype]['bond_type']
# if atom.atomtypeB is not None:
# atom.typeB = self.NBParams.atomtypes[atom.atomtypeB]['bond_type']
# else:
# atom.typeB = atom.type
#
# def make_bond_params(self):
# for i, (at1,at2,func) in enumerate(self.bonds):
# param = self.BondedParams.get_bond_param(at1.type,at2.type)
# if param is None:
# print 'Error! No bonded parameters found! (%s-%s)' % \
# (at1.type, at2.type)
# sys.exit(1)
# self.bonds[i].append(param[1:])
#
# def make_angle_params(self):
# for i, (at1, at2, at3, func) in enumerate(self.angles):
# param = self.BondedParams.get_angle_param(at1.type, at2.type, at3.type)
# if param is None:
# print 'Error! No angle parameters found! (%s-%s-%s)' % \
# (at1.type, at2.type, at3.type)
# sys.exit(1)
# self.angles[i].append(param[1:])
#
# def make_dihedral_params(self):
# for i, d in enumerate(self.dihedrals):
# if d[5]!='': # we have a prefefined dihedral
# continue
# else:
# at1, at2, at3, at4, func, dih = d
# param = self.BondedParams.get_dihedral_param(at1.type, at2.type, \
# at3.type, at4.type, \
# func)
# if param is None:
# print 'Error! No dihedral parameters found! (%s-%s-%s-%s)' % \
# (at1.type, at2.type, at3.type, at4.type)
# print func, dih
# sys.exit(1)
# del self.dihedrals[i][-1]
# self.dihedrals[i].append(param[1:])
. Output only the next line. | astate = [1,0,0,0,0] |
Next line prediction: <|code_start|>
def list_path(path):
assert not os.path.isabs(path)
abs_path = os.path.join(app.root_path, path)
return [
os.path.join(abs_path, f)
for f in os.listdir(abs_path)
]
def all():
for insight_path in list_path("insights"):
try:
insight = dict(
id = os.path.splitext(os.path.basename(insight_path))[0],
content=open(insight_path).read(),
limit = 10,
columns = ""
)
yield insight
<|code_end|>
. Use current file imports:
(import os
import json
from .app import app)
and context including class names, function names, or small code snippets from other files:
# Path: web/app.py
# def sort(iter, col, dir="ASC"):
# def execute(q_str, col=1):
# def ensure_dir(path):
# def value(k):
# def commas(val):
# def index():
# def schema():
# def query_endpoint():
# def query_from(insight):
# def sideload(records):
# def list_insights():
# def get_insight(id):
. Output only the next line. | except GeneratorExit: |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
if __name__ == '__main__':
app.run(
debug=True
<|code_end|>
with the help of current file imports:
from web import app
and context from other files:
# Path: web/app.py
# def sort(iter, col, dir="ASC"):
# def execute(q_str, col=1):
# def ensure_dir(path):
# def value(k):
# def commas(val):
# def index():
# def schema():
# def query_endpoint():
# def query_from(insight):
# def sideload(records):
# def list_insights():
# def get_insight(id):
, which may contain function names, class names, or code. Output only the next line. | ) |
Based on the snippet: <|code_start|>
class TestDBWrapper(TestCase):
def setUp(self):
self._old_db_path = os.environ['DATA_DB_PATH']
self.tmp_dir = os.environ['DATA_DB_PATH'] = tempfile.mkdtemp()
def tearDown(self):
shutil.rmtree(self.tmp_dir)
os.environ['DATA_DB_PATH'] = self._old_db_path
def create_db(self, name, data):
db_path = os.path.join(os.environ['DATA_DB_PATH'], name + '.db')
data = DiscoDB(data)
data.dump(open(db_path, 'w'))
return db_path
def create_db2(self, name, fields, data):
db_path = os.path.join(os.environ['DATA_DB_PATH'], name + '.db')
schema = dict(
name=name,
fields=fields
)
db = splicer_discodb.create(db_path, schema, data)
db.dump(open(db_path, 'w'))
def test_scan_database_dir(self):
state = dict(
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import shutil
import tempfile
import splicer_discodb
from unittest import TestCase
from discodb import DiscoDB
from nose.tools import *
from web import tasks
and context (classes, functions, sometimes code) from other files:
# Path: web/tasks.py
# MAX_LOCK_AGE = 10 * 60
# def ensure_dir(path):
# def progress(fname, downloaded, size):
# def sync_dbs():
# def lock_watch():
# def download_dbs():
# def cached_db(state):
# def scan_database_dir(state):
# def relations():
# def schema(relation_name):
# def query(statement):
# def execute(cols=None, where=None, limit=100, offset=0, order_by=[]):
# def ticks():
. Output only the next line. | dbs={}, |
Predict the next line for this snippet: <|code_start|> (
ConcreteTemplate({'content': '((1)) ((2)) ((3))'}),
ConcreteTemplate({'content': '((1)) ((2)) ((3))'}),
False
),
(
ConcreteTemplate({'content': '((1)) ((2)) ((3))'}),
ConcreteTemplate({'content': '((3)) ((2)) ((1))'}),
False
),
(
ConcreteTemplate({'content': '((1)) ((2)) ((3))'}),
ConcreteTemplate({'content': '((1)) ((1)) ((2)) ((2)) ((3)) ((3))'}),
False
),
(
ConcreteTemplate({'content': '((1))'}),
ConcreteTemplate({'content': '((1)) ((2))'}),
True
),
(
ConcreteTemplate({'content': '((1)) ((2))'}),
ConcreteTemplate({'content': '((1))'}),
True
),
(
ConcreteTemplate({'content': '((a)) ((b))'}),
ConcreteTemplate({'content': '((A)) (( B_ ))'}),
False
),
<|code_end|>
with the help of current file imports:
import pytest
from notifications_utils.template_change import TemplateChange
from tests.test_base_template import ConcreteTemplate
and context from other files:
# Path: notifications_utils/template_change.py
# class TemplateChange():
#
# def __init__(self, old_template, new_template):
# self.old_placeholders = InsensitiveDict.from_keys(old_template.placeholders)
# self.new_placeholders = InsensitiveDict.from_keys(new_template.placeholders)
#
# @property
# def has_different_placeholders(self):
# return bool(self.new_placeholders.keys() ^ self.old_placeholders.keys())
#
# @property
# def placeholders_added(self):
# return OrderedSet([
# self.new_placeholders.get(key)
# for key in self.new_placeholders.keys() - self.old_placeholders.keys()
# ])
#
# @property
# def placeholders_removed(self):
# return OrderedSet([
# self.old_placeholders.get(key)
# for key in self.old_placeholders.keys() - self.new_placeholders.keys()
# ])
#
# Path: tests/test_base_template.py
# class ConcreteTemplate(ConcreteImplementation, Template):
# pass
, which may contain function names, class names, or code. Output only the next line. | ] |
Here is a snippet: <|code_start|> assert TemplateChange(old_template, new_template).has_different_placeholders == should_differ
@pytest.mark.parametrize(
"old_template, new_template, placeholders_added", [
(
ConcreteTemplate({'content': '((1)) ((2)) ((3))'}),
ConcreteTemplate({'content': '((1)) ((2)) ((3))'}),
set()
),
(
ConcreteTemplate({'content': '((1)) ((2)) ((3))'}),
ConcreteTemplate({'content': '((1)) ((1)) ((2)) ((2)) ((3)) ((3))'}),
set()
),
(
ConcreteTemplate({'content': '((1)) ((2)) ((3))'}),
ConcreteTemplate({'content': '((1))'}),
set()
),
(
ConcreteTemplate({'content': '((1))'}),
ConcreteTemplate({'content': '((1)) ((2)) ((3))'}),
set(['2', '3'])
),
(
ConcreteTemplate({'content': '((a))'}),
ConcreteTemplate({'content': '((A)) ((B)) ((C))'}),
set(['B', 'C'])
),
<|code_end|>
. Write the next line using the current file imports:
import pytest
from notifications_utils.template_change import TemplateChange
from tests.test_base_template import ConcreteTemplate
and context from other files:
# Path: notifications_utils/template_change.py
# class TemplateChange():
#
# def __init__(self, old_template, new_template):
# self.old_placeholders = InsensitiveDict.from_keys(old_template.placeholders)
# self.new_placeholders = InsensitiveDict.from_keys(new_template.placeholders)
#
# @property
# def has_different_placeholders(self):
# return bool(self.new_placeholders.keys() ^ self.old_placeholders.keys())
#
# @property
# def placeholders_added(self):
# return OrderedSet([
# self.new_placeholders.get(key)
# for key in self.new_placeholders.keys() - self.old_placeholders.keys()
# ])
#
# @property
# def placeholders_removed(self):
# return OrderedSet([
# self.old_placeholders.get(key)
# for key in self.old_placeholders.keys() - self.new_placeholders.keys()
# ])
#
# Path: tests/test_base_template.py
# class ConcreteTemplate(ConcreteImplementation, Template):
# pass
, which may include functions, classes, or code. Output only the next line. | ] |
Next line prediction: <|code_start|> def foo(self):
raise AttributeError('Something has gone wrong')
with pytest.raises(AttributeError) as e:
Custom(json_response).foo
assert str(e.value) == 'Something has gone wrong'
def test_dynamic_properties_are_introspectable():
class Custom(SerialisedModel):
ALLOWED_PROPERTIES = {'foo', 'bar', 'baz'}
instance = Custom({'foo': '', 'bar': '', 'baz': ''})
assert dir(instance)[-3:] == ['bar', 'baz', 'foo']
def test_empty_serialised_model_collection():
class CustomCollection(SerialisedModelCollection):
model = None
instance = CustomCollection([])
assert not instance
assert len(instance) == 0
<|code_end|>
. Use current file imports:
(import sys
import pytest
from notifications_utils.serialised_model import (
SerialisedModel,
SerialisedModelCollection,
))
and context including class names, function names, or small code snippets from other files:
# Path: notifications_utils/serialised_model.py
# class SerialisedModel(ABC):
#
# """
# A SerialisedModel takes a dictionary, typically created by
# serialising a database object. It then takes the value of specified
# keys from the dictionary and adds them to itself as properties, so
# that it can be interacted with like any other object. It is cleaner
# and safer than dealing with dictionaries directly because it
# guarantees that:
# - all of the ALLOWED_PROPERTIES are present in the underlying
# dictionary
# - any other abritrary properties of the underlying dictionary can’t
# be accessed
#
# If you are adding a new field to a model, you should ensure that
# all sources of the cache data are updated to return that new field,
# then clear the cache, before adding that field to the
# ALLOWED_PROPERTIES list.
# """
#
# @property
# @abstractmethod
# def ALLOWED_PROPERTIES(self):
# pass
#
# def __init__(self, _dict):
# for property in self.ALLOWED_PROPERTIES:
# setattr(self, property, _dict[property])
#
# class SerialisedModelCollection(ABC):
#
# """
# A SerialisedModelCollection takes a list of dictionaries, typically
# created by serialising database objects. When iterated over it
# returns a model instance for each of the items in the list.
# """
#
# @property
# @abstractmethod
# def model(self):
# pass
#
# def __init__(self, items):
# self.items = items
#
# def __bool__(self):
# return bool(self.items)
#
# def __getitem__(self, index):
# return self.model(self.items[index])
#
# def __len__(self):
# return len(self.items)
#
# def __add__(self, other):
# return list(self) + list(other)
#
# def __radd__(self, other):
# return list(other) + list(self)
. Output only the next line. | def test_serialised_model_collection_returns_models_from_list(): |
Given the following code snippet before the placeholder: <|code_start|> "Can't instantiate abstract class CustomCollection with abstract method model"
)
def test_looks_up_from_dict():
class Custom(SerialisedModel):
ALLOWED_PROPERTIES = {'foo'}
assert Custom({'foo': 'bar'}).foo == 'bar'
def test_cant_override_custom_property_from_dict():
class Custom(SerialisedModel):
ALLOWED_PROPERTIES = {'foo'}
@property
def foo(self):
return 'bar'
with pytest.raises(AttributeError) as e:
assert Custom({'foo': 'NOPE'}).foo == 'bar'
assert str(e.value) == "can't set attribute"
@pytest.mark.parametrize('json_response', (
{},
<|code_end|>
, predict the next line using imports from the current file:
import sys
import pytest
from notifications_utils.serialised_model import (
SerialisedModel,
SerialisedModelCollection,
)
and context including class names, function names, and sometimes code from other files:
# Path: notifications_utils/serialised_model.py
# class SerialisedModel(ABC):
#
# """
# A SerialisedModel takes a dictionary, typically created by
# serialising a database object. It then takes the value of specified
# keys from the dictionary and adds them to itself as properties, so
# that it can be interacted with like any other object. It is cleaner
# and safer than dealing with dictionaries directly because it
# guarantees that:
# - all of the ALLOWED_PROPERTIES are present in the underlying
# dictionary
# - any other abritrary properties of the underlying dictionary can’t
# be accessed
#
# If you are adding a new field to a model, you should ensure that
# all sources of the cache data are updated to return that new field,
# then clear the cache, before adding that field to the
# ALLOWED_PROPERTIES list.
# """
#
# @property
# @abstractmethod
# def ALLOWED_PROPERTIES(self):
# pass
#
# def __init__(self, _dict):
# for property in self.ALLOWED_PROPERTIES:
# setattr(self, property, _dict[property])
#
# class SerialisedModelCollection(ABC):
#
# """
# A SerialisedModelCollection takes a list of dictionaries, typically
# created by serialising database objects. When iterated over it
# returns a model instance for each of the items in the list.
# """
#
# @property
# @abstractmethod
# def model(self):
# pass
#
# def __init__(self, items):
# self.items = items
#
# def __bool__(self):
# return bool(self.items)
#
# def __getitem__(self, index):
# return self.model(self.items[index])
#
# def __len__(self):
# return len(self.items)
#
# def __add__(self, other):
# return list(self) + list(other)
#
# def __radd__(self, other):
# return list(other) + list(self)
. Output only the next line. | {'foo': 'bar'}, # Should still raise an exception |
Predict the next line for this snippet: <|code_start|>
class TemplateChange():
def __init__(self, old_template, new_template):
self.old_placeholders = InsensitiveDict.from_keys(old_template.placeholders)
self.new_placeholders = InsensitiveDict.from_keys(new_template.placeholders)
@property
<|code_end|>
with the help of current file imports:
from orderedset import OrderedSet
from notifications_utils.insensitive_dict import InsensitiveDict
and context from other files:
# Path: notifications_utils/insensitive_dict.py
# class InsensitiveDict(OrderedDict):
#
# """
# `InsensitiveDict` behaves like an ordered dictionary, except it normalises
# case, whitespace, hypens and underscores in keys.
#
# In other words,
# InsensitiveDict({'FIRST_NAME': 'example'}) == InsensitiveDict({'first name': 'example'})
# >>> True
# """
#
# KEY_TRANSLATION_TABLE = {
# ord(c): None for c in ' _-'
# }
#
# def __init__(self, row_dict):
# for key, value in row_dict.items():
# self[key] = value
#
# @classmethod
# def from_keys(cls, keys):
# """
# This behaves like `dict.from_keys`, except:
# - it normalises the keys to ignore case, whitespace, hypens and
# underscores
# - it stores the original, unnormalised key as the value of the
# item so it can be retrieved later
# """
# return cls(OrderedDict([(key, key) for key in keys]))
#
# def keys(self):
# return OrderedSet(super().keys())
#
# def __getitem__(self, key):
# return super().__getitem__(self.make_key(key))
#
# def __setitem__(self, key, value):
# super().__setitem__(self.make_key(key), value)
#
# def __contains__(self, key):
# return super().__contains__(self.make_key(key))
#
# def get(self, key, default=None):
# return self[key] if key in self else default
#
# def copy(self):
# return self.__class__(super().copy())
#
# def as_dict_with_keys(self, keys):
# return {
# key: self.get(key) for key in keys
# }
#
# @staticmethod
# @lru_cache(maxsize=32, typed=False)
# def make_key(original_key):
# if original_key is None:
# return None
# return original_key.translate(InsensitiveDict.KEY_TRANSLATION_TABLE).lower()
, which may contain function names, class names, or code. Output only the next line. | def has_different_placeholders(self): |
Given the following code snippet before the placeholder: <|code_start|>
def test_request_id_is_set_on_response(app):
request_helper.init_app(app)
client = app.test_client()
<|code_end|>
, predict the next line using imports from the current file:
from notifications_utils import request_helper
and context including class names, function names, and sometimes code from other files:
# Path: notifications_utils/request_helper.py
# class NotifyRequest(Request):
# class ResponseHeaderMiddleware(object):
# def request_id(self):
# def trace_id(self):
# def span_id(self):
# def parent_span_id(self):
# def _get_header_value(self, header_name):
# def __init__(self, app, trace_id_header, span_id_header):
# def __call__(self, environ, start_response):
# def rewrite_response_headers(status, headers, exc_info=None):
# def init_app(app):
# def check_proxy_header_before_request():
# def _check_proxy_header_secret(request, secrets, header='X-Custom-Forwarder'):
. Output only the next line. | with app.app_context(): |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
version_parts = ('major', 'minor', 'patch')
parser = argparse.ArgumentParser()
parser.add_argument('version_part', choices=version_parts)
version_part = parser.parse_args().version_part
current_major, current_minor, current_patch = map(int, __version__.split('.'))
new_major, new_minor, new_patch = {
'major': (current_major + 1, 0, 0),
<|code_end|>
using the current file's imports:
import argparse
import hashlib
import subprocess
from pathlib import Path
from notifications_utils.version import __version__
and any relevant context from other files:
# Path: notifications_utils/version.py
. Output only the next line. | 'minor': (current_major, current_minor + 1, 0), |
Predict the next line after this snippet: <|code_start|> {'placeholder': '<em>without</em>'},
'string without html',
'string <em>without</em> html',
'string <em>without</em> html',
),
(
'string ((<em>conditional</em>??<em>placeholder</em>)) html',
{},
'string <span class=\'placeholder-conditional\'>((conditional??</span>placeholder)) html',
(
'string '
'<span class=\'placeholder-conditional\'>'
'((<em>conditional</em>??</span>'
'<em>placeholder</em>)) '
'html'
),
(
'string '
'<span class=\'placeholder-conditional\'>'
'((<em>conditional</em>??</span>'
'<em>placeholder</em>)) '
'html'
),
),
(
'string ((conditional??<em>placeholder</em>)) html',
{'conditional': True},
'string placeholder html',
'string <em>placeholder</em> html',
'string <em>placeholder</em> html',
<|code_end|>
using the current file's imports:
import pytest
from notifications_utils.field import Field
and any relevant context from other files:
# Path: notifications_utils/field.py
# class Field:
#
# """
# An instance of Field represents a string of text which may contain
# placeholders.
#
# If values are provided the field replaces the placeholders with the
# corresponding values. If a value for a placeholder is missing then
# the field will highlight the placeholder by wrapping it in some HTML.
#
# A template can have several fields, for example an email template
# has a field for the body and a field for the subject.
# """
#
# placeholder_pattern = re.compile(
# r'\({2}' # opening ((
# r'([^()]+)' # body of placeholder - potentially standard or conditional.
# r'\){2}' # closing ))
# )
# placeholder_tag = "<span class='placeholder'>(({}))</span>"
# conditional_placeholder_tag = "<span class='placeholder-conditional'>(({}??</span>{}))"
# placeholder_tag_no_brackets = "<span class='placeholder-no-brackets'>{}</span>"
# placeholder_tag_redacted = "<span class='placeholder-redacted'>hidden</span>"
#
# def __init__(
# self,
# content,
# values=None,
# with_brackets=True,
# html='strip',
# markdown_lists=False,
# redact_missing_personalisation=False,
# ):
# self.content = content
# self.values = values
# self.markdown_lists = markdown_lists
# if not with_brackets:
# self.placeholder_tag = self.placeholder_tag_no_brackets
# self.sanitizer = {
# 'strip': strip_html,
# 'escape': escape_html,
# 'passthrough': str,
# }[html]
# self.redact_missing_personalisation = redact_missing_personalisation
#
# def __str__(self):
# if self.values:
# return self.replaced
# return self.formatted
#
# def __repr__(self):
# return "{}(\"{}\", {})".format(self.__class__.__name__, self.content, self.values) # TODO: more real
#
# def splitlines(self):
# return str(self).splitlines()
#
# @property
# def values(self):
# return self._values
#
# @values.setter
# def values(self, value):
# self._values = InsensitiveDict(value) if value else {}
#
# def format_match(self, match):
# placeholder = Placeholder.from_match(match)
#
# if self.redact_missing_personalisation:
# return self.placeholder_tag_redacted
#
# if placeholder.is_conditional():
# return self.conditional_placeholder_tag.format(
# placeholder.name,
# placeholder.conditional_text
# )
#
# return self.placeholder_tag.format(
# placeholder.name
# )
#
# def replace_match(self, match):
# placeholder = Placeholder.from_match(match)
# replacement = self.values.get(placeholder.name)
#
# if placeholder.is_conditional() and replacement is not None:
# return placeholder.get_conditional_body(replacement)
#
# replaced_value = self.get_replacement(placeholder)
# if replaced_value is not None:
# return self.get_replacement(placeholder)
#
# return self.format_match(match)
#
# def get_replacement(self, placeholder):
# replacement = self.values.get(placeholder.name)
# if replacement is None:
# return None
#
# if isinstance(replacement, list):
# vals = (
# strip_and_remove_obscure_whitespace(str(val))
# for val in replacement if val is not None
# )
# vals = list(filter(None, vals))
# if not vals:
# return ''
# return self.sanitizer(self.get_replacement_as_list(vals))
#
# return self.sanitizer(str(replacement))
#
# def get_replacement_as_list(self, replacement):
# if self.markdown_lists:
# return '\n\n' + '\n'.join(
# '* {}'.format(item) for item in replacement
# )
# return unescaped_formatted_list(replacement, before_each='', after_each='')
#
# @property
# def _raw_formatted(self):
# return re.sub(
# self.placeholder_pattern, self.format_match, self.sanitizer(self.content)
# )
#
# @property
# def formatted(self):
# return Markup(self._raw_formatted)
#
# @property
# def placeholders(self):
# if not getattr(self, 'content', ''):
# return set()
# return OrderedSet(
# Placeholder(body).name for body in re.findall(
# self.placeholder_pattern, self.content
# )
# )
#
# @property
# def replaced(self):
# return re.sub(
# self.placeholder_pattern, self.replace_match, self.sanitizer(self.content)
# )
. Output only the next line. | ), |
Based on the snippet: <|code_start|> "values", [[], False]
)
def test_errors_for_invalid_values(values):
with pytest.raises(TypeError):
ConcreteTemplate({"content": ''}, values)
def test_matches_keys_to_placeholder_names():
template = ConcreteTemplate({"content": "hello ((name))"})
template.values = {'NAME': 'Chris'}
assert template.values == {'name': 'Chris'}
template.values = {'NAME': 'Chris', 'Town': 'London'}
assert template.values == {'name': 'Chris', 'Town': 'London'}
assert template.additional_data == {'Town'}
template.values = None
assert template.missing_data == ['name']
@pytest.mark.parametrize(
"template_content, template_subject, expected", [
(
"the quick brown fox",
"jumps",
[]
),
(
<|code_end|>
, predict the immediate next line with the help of imports:
from unittest.mock import patch
from notifications_utils.template import SubjectMixin, Template
import pytest
and context (classes, functions, sometimes code) from other files:
# Path: notifications_utils/template.py
# class SubjectMixin():
#
# def __init__(
# self,
# template,
# values=None,
# **kwargs
# ):
# self._subject = template['subject']
# super().__init__(template, values, **kwargs)
#
# @property
# def subject(self):
# return Markup(Take(Field(
# self._subject,
# self.values,
# html='escape',
# redact_missing_personalisation=self.redact_missing_personalisation,
# )).then(
# do_nice_typography
# ).then(
# normalise_whitespace
# ))
#
# @property
# def placeholders(self):
# return get_placeholders(self._subject) | super().placeholders
#
# class Template(ABC):
#
# encoding = "utf-8"
#
# def __init__(
# self,
# template,
# values=None,
# redact_missing_personalisation=False,
# ):
# if not isinstance(template, dict):
# raise TypeError('Template must be a dict')
# if values is not None and not isinstance(values, dict):
# raise TypeError('Values must be a dict')
# if template.get('template_type') != self.template_type:
# raise TypeError(
# f'Cannot initialise {self.__class__.__name__} '
# f'with {template.get("template_type")} template_type'
# )
# self.id = template.get("id", None)
# self.name = template.get("name", None)
# self.content = template["content"]
# self.values = values
# self._template = template
# self.redact_missing_personalisation = redact_missing_personalisation
#
# def __repr__(self):
# return "{}(\"{}\", {})".format(self.__class__.__name__, self.content, self.values)
#
# @abstractmethod
# def __str__(self):
# pass
#
# @property
# def content_with_placeholders_filled_in(self):
# return str(Field(
# self.content,
# self.values,
# html='passthrough',
# redact_missing_personalisation=self.redact_missing_personalisation,
# markdown_lists=True,
# )).strip()
#
# @property
# def values(self):
# if hasattr(self, '_values'):
# return self._values
# return {}
#
# @values.setter
# def values(self, value):
# if not value:
# self._values = {}
# else:
# placeholders = InsensitiveDict.from_keys(self.placeholders)
# self._values = InsensitiveDict(value).as_dict_with_keys(
# self.placeholders | set(
# key for key in value.keys()
# if InsensitiveDict.make_key(key) not in placeholders.keys()
# )
# )
#
# @property
# def placeholders(self):
# return get_placeholders(self.content)
#
# @property
# def missing_data(self):
# return list(
# placeholder for placeholder in self.placeholders
# if self.values.get(placeholder) is None
# )
#
# @property
# def additional_data(self):
# return self.values.keys() - self.placeholders
#
# def get_raw(self, key, default=None):
# return self._template.get(key, default)
#
# def compare_to(self, new):
# return TemplateChange(self, new)
#
# @property
# def content_count(self):
# return len(self.content_with_placeholders_filled_in)
#
# def is_message_empty(self):
#
# if not self.content:
# return True
#
# if not self.content.startswith('((') or not self.content.endswith('))'):
# # If the content doesn’t start or end with a placeholder we
# # can guarantee it’s not empty, no matter what
# # personalisation has been provided.
# return False
#
# return self.content_count == 0
#
# def is_message_too_long(self):
# return False
. Output only the next line. | "the quick ((colour)) fox", |
Given the code snippet: <|code_start|> template.values = {'NAME': 'Chris', 'Town': 'London'}
assert template.values == {'name': 'Chris', 'Town': 'London'}
assert template.additional_data == {'Town'}
template.values = None
assert template.missing_data == ['name']
@pytest.mark.parametrize(
"template_content, template_subject, expected", [
(
"the quick brown fox",
"jumps",
[]
),
(
"the quick ((colour)) fox",
"jumps",
["colour"]
),
(
"the quick ((colour)) ((animal))",
"jumps",
["colour", "animal"]
),
(
"((colour)) ((animal)) ((colour)) ((animal))",
"jumps",
["colour", "animal"]
),
<|code_end|>
, generate the next line using the imports in this file:
from unittest.mock import patch
from notifications_utils.template import SubjectMixin, Template
import pytest
and context (functions, classes, or occasionally code) from other files:
# Path: notifications_utils/template.py
# class SubjectMixin():
#
# def __init__(
# self,
# template,
# values=None,
# **kwargs
# ):
# self._subject = template['subject']
# super().__init__(template, values, **kwargs)
#
# @property
# def subject(self):
# return Markup(Take(Field(
# self._subject,
# self.values,
# html='escape',
# redact_missing_personalisation=self.redact_missing_personalisation,
# )).then(
# do_nice_typography
# ).then(
# normalise_whitespace
# ))
#
# @property
# def placeholders(self):
# return get_placeholders(self._subject) | super().placeholders
#
# class Template(ABC):
#
# encoding = "utf-8"
#
# def __init__(
# self,
# template,
# values=None,
# redact_missing_personalisation=False,
# ):
# if not isinstance(template, dict):
# raise TypeError('Template must be a dict')
# if values is not None and not isinstance(values, dict):
# raise TypeError('Values must be a dict')
# if template.get('template_type') != self.template_type:
# raise TypeError(
# f'Cannot initialise {self.__class__.__name__} '
# f'with {template.get("template_type")} template_type'
# )
# self.id = template.get("id", None)
# self.name = template.get("name", None)
# self.content = template["content"]
# self.values = values
# self._template = template
# self.redact_missing_personalisation = redact_missing_personalisation
#
# def __repr__(self):
# return "{}(\"{}\", {})".format(self.__class__.__name__, self.content, self.values)
#
# @abstractmethod
# def __str__(self):
# pass
#
# @property
# def content_with_placeholders_filled_in(self):
# return str(Field(
# self.content,
# self.values,
# html='passthrough',
# redact_missing_personalisation=self.redact_missing_personalisation,
# markdown_lists=True,
# )).strip()
#
# @property
# def values(self):
# if hasattr(self, '_values'):
# return self._values
# return {}
#
# @values.setter
# def values(self, value):
# if not value:
# self._values = {}
# else:
# placeholders = InsensitiveDict.from_keys(self.placeholders)
# self._values = InsensitiveDict(value).as_dict_with_keys(
# self.placeholders | set(
# key for key in value.keys()
# if InsensitiveDict.make_key(key) not in placeholders.keys()
# )
# )
#
# @property
# def placeholders(self):
# return get_placeholders(self.content)
#
# @property
# def missing_data(self):
# return list(
# placeholder for placeholder in self.placeholders
# if self.values.get(placeholder) is None
# )
#
# @property
# def additional_data(self):
# return self.values.keys() - self.placeholders
#
# def get_raw(self, key, default=None):
# return self._template.get(key, default)
#
# def compare_to(self, new):
# return TemplateChange(self, new)
#
# @property
# def content_count(self):
# return len(self.content_with_placeholders_filled_in)
#
# def is_message_empty(self):
#
# if not self.content:
# return True
#
# if not self.content.startswith('((') or not self.content.endswith('))'):
# # If the content doesn’t start or end with a placeholder we
# # can guarantee it’s not empty, no matter what
# # personalisation has been provided.
# return False
#
# return self.content_count == 0
#
# def is_message_too_long(self):
# return False
. Output only the next line. | ( |
Next line prediction: <|code_start|> mocked_put.assert_called_once_with(
Body=contents,
ServerSideEncryption='AES256',
ContentType=content_type,
)
def test_s3upload_save_file_to_bucket_with_contenttype(mocker):
content_type = 'image/png'
mocked = mocker.patch('notifications_utils.s3.resource')
s3upload(filedata=contents,
region=region,
bucket_name=bucket,
file_location=location,
content_type=content_type)
mocked_put = mocked.return_value.Object.return_value.put
mocked_put.assert_called_once_with(
Body=contents,
ServerSideEncryption='AES256',
ContentType=content_type,
)
def test_s3upload_raises_exception(app, mocker):
mocked = mocker.patch('notifications_utils.s3.resource')
response = {'Error': {'Code': 500}}
exception = botocore.exceptions.ClientError(response, 'Bad exception')
mocked.return_value.Object.return_value.put.side_effect = exception
with pytest.raises(botocore.exceptions.ClientError):
s3upload(filedata=contents,
<|code_end|>
. Use current file imports:
(from urllib.parse import parse_qs
from notifications_utils.s3 import S3ObjectNotFound, s3download, s3upload
import botocore
import pytest)
and context including class names, function names, or small code snippets from other files:
# Path: notifications_utils/s3.py
# class S3ObjectNotFound(botocore.exceptions.ClientError):
# pass
#
# def s3download(bucket_name, filename):
# try:
# s3 = resource('s3')
# key = s3.Object(bucket_name, filename)
# return key.get()['Body']
# except botocore.exceptions.ClientError as error:
# raise S3ObjectNotFound(error.response, error.operation_name)
#
# def s3upload(
# filedata,
# region,
# bucket_name,
# file_location,
# content_type='binary/octet-stream',
# tags=None,
# metadata=None,
# ):
# _s3 = resource('s3')
#
# key = _s3.Object(bucket_name, file_location)
#
# put_args = {
# 'Body': filedata,
# 'ServerSideEncryption': 'AES256',
# 'ContentType': content_type
# }
#
# if tags:
# tags = urllib.parse.urlencode(tags)
# put_args['Tagging'] = tags
#
# if metadata:
# metadata = put_args['Metadata'] = metadata
#
# try:
# key.put(**put_args)
# except botocore.exceptions.ClientError as e:
# current_app.logger.error(
# "Unable to upload file to S3 bucket {}".format(bucket_name)
# )
# raise e
. Output only the next line. | region=region, |
Here is a snippet: <|code_start|> region=region,
bucket_name=bucket,
file_location=location,
tags={'a': '1/2', 'b': 'x y'},
)
mocked_put = mocked.return_value.Object.return_value.put
# make sure tags were a urlencoded query string
encoded_tags = mocked_put.call_args[1]['Tagging']
assert parse_qs(encoded_tags) == {'a': ['1/2'], 'b': ['x y']}
def test_s3upload_save_file_to_bucket_with_metadata(mocker):
mocked = mocker.patch('notifications_utils.s3.resource')
s3upload(
filedata=contents,
region=region,
bucket_name=bucket,
file_location=location,
metadata={'status': 'valid', 'pages': '5'}
)
mocked_put = mocked.return_value.Object.return_value.put
metadata = mocked_put.call_args[1]['Metadata']
assert metadata == {'status': 'valid', 'pages': '5'}
def test_s3download_gets_file(mocker):
mocked = mocker.patch('notifications_utils.s3.resource')
mocked_object = mocked.return_value.Object
<|code_end|>
. Write the next line using the current file imports:
from urllib.parse import parse_qs
from notifications_utils.s3 import S3ObjectNotFound, s3download, s3upload
import botocore
import pytest
and context from other files:
# Path: notifications_utils/s3.py
# class S3ObjectNotFound(botocore.exceptions.ClientError):
# pass
#
# def s3download(bucket_name, filename):
# try:
# s3 = resource('s3')
# key = s3.Object(bucket_name, filename)
# return key.get()['Body']
# except botocore.exceptions.ClientError as error:
# raise S3ObjectNotFound(error.response, error.operation_name)
#
# def s3upload(
# filedata,
# region,
# bucket_name,
# file_location,
# content_type='binary/octet-stream',
# tags=None,
# metadata=None,
# ):
# _s3 = resource('s3')
#
# key = _s3.Object(bucket_name, file_location)
#
# put_args = {
# 'Body': filedata,
# 'ServerSideEncryption': 'AES256',
# 'ContentType': content_type
# }
#
# if tags:
# tags = urllib.parse.urlencode(tags)
# put_args['Tagging'] = tags
#
# if metadata:
# metadata = put_args['Metadata'] = metadata
#
# try:
# key.put(**put_args)
# except botocore.exceptions.ClientError as e:
# current_app.logger.error(
# "Unable to upload file to S3 bucket {}".format(bucket_name)
# )
# raise e
, which may include functions, classes, or code. Output only the next line. | mocked_get = mocked.return_value.Object.return_value.get |
Continue the code snippet: <|code_start|> s3upload(filedata=contents,
region=region,
bucket_name=bucket,
file_location=location,
content_type=content_type)
mocked_put = mocked.return_value.Object.return_value.put
mocked_put.assert_called_once_with(
Body=contents,
ServerSideEncryption='AES256',
ContentType=content_type,
)
def test_s3upload_raises_exception(app, mocker):
mocked = mocker.patch('notifications_utils.s3.resource')
response = {'Error': {'Code': 500}}
exception = botocore.exceptions.ClientError(response, 'Bad exception')
mocked.return_value.Object.return_value.put.side_effect = exception
with pytest.raises(botocore.exceptions.ClientError):
s3upload(filedata=contents,
region=region,
bucket_name=bucket,
file_location="location")
def test_s3upload_save_file_to_bucket_with_urlencoded_tags(mocker):
mocked = mocker.patch('notifications_utils.s3.resource')
s3upload(
filedata=contents,
region=region,
<|code_end|>
. Use current file imports:
from urllib.parse import parse_qs
from notifications_utils.s3 import S3ObjectNotFound, s3download, s3upload
import botocore
import pytest
and context (classes, functions, or code) from other files:
# Path: notifications_utils/s3.py
# class S3ObjectNotFound(botocore.exceptions.ClientError):
# pass
#
# def s3download(bucket_name, filename):
# try:
# s3 = resource('s3')
# key = s3.Object(bucket_name, filename)
# return key.get()['Body']
# except botocore.exceptions.ClientError as error:
# raise S3ObjectNotFound(error.response, error.operation_name)
#
# def s3upload(
# filedata,
# region,
# bucket_name,
# file_location,
# content_type='binary/octet-stream',
# tags=None,
# metadata=None,
# ):
# _s3 = resource('s3')
#
# key = _s3.Object(bucket_name, file_location)
#
# put_args = {
# 'Body': filedata,
# 'ServerSideEncryption': 'AES256',
# 'ContentType': content_type
# }
#
# if tags:
# tags = urllib.parse.urlencode(tags)
# put_args['Tagging'] = tags
#
# if metadata:
# metadata = put_args['Metadata'] = metadata
#
# try:
# key.put(**put_args)
# except botocore.exceptions.ClientError as e:
# current_app.logger.error(
# "Unable to upload file to S3 bucket {}".format(bucket_name)
# )
# raise e
. Output only the next line. | bucket_name=bucket, |
Based on the snippet: <|code_start|>
class FakeService():
id = "1234"
@pytest.fixture
def app():
flask_app = Flask(__name__)
ctx = flask_app.app_context()
ctx.push()
yield flask_app
ctx.pop()
@pytest.fixture
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
import requests_mock
from flask import Flask
from notifications_utils import request_helper
and context (classes, functions, sometimes code) from other files:
# Path: notifications_utils/request_helper.py
# class NotifyRequest(Request):
# class ResponseHeaderMiddleware(object):
# def request_id(self):
# def trace_id(self):
# def span_id(self):
# def parent_span_id(self):
# def _get_header_value(self, header_name):
# def __init__(self, app, trace_id_header, span_id_header):
# def __call__(self, environ, start_response):
# def rewrite_response_headers(status, headers, exc_info=None):
# def init_app(app):
# def check_proxy_header_before_request():
# def _check_proxy_header_secret(request, secrets, header='X-Custom-Forwarder'):
. Output only the next line. | def celery_app(mocker): |
Based on the snippet: <|code_start|>
@pytest.mark.parametrize('unsafe_string, expected_safe', [
('name with spaces', 'name.with.spaces'),
('singleword', 'singleword'),
('UPPER CASE', 'upper.case'),
('Service - with dash', 'service.with.dash'),
('lots of spaces', 'lots.of.spaces'),
('name.with.dots', 'name.with.dots'),
('name-with-other-delimiters', 'namewithotherdelimiters'),
('.leading', 'leading'),
('trailing.', 'trailing'),
('üńïçödë wördś', 'unicode.words'),
])
def test_email_safe_return_dot_separated_email_local_part(unsafe_string, expected_safe):
assert make_string_safe_for_email_local_part(unsafe_string) == expected_safe
@pytest.mark.parametrize('unsafe_string, expected_safe', [
('name with spaces', 'name-with-spaces'),
('singleword', 'singleword'),
('UPPER CASE', 'upper-case'),
('Service - with dash', 'service---with-dash'),
('lots of spaces', 'lots-of-spaces'),
('name.with.dots', 'namewithdots'),
('name-with-dashes', 'name-with-dashes'),
('N. London', 'n-london'),
('.leading', 'leading'),
('-leading', '-leading'),
('trailing.', 'trailing'),
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
from notifications_utils.safe_string import (
make_string_safe_for_email_local_part,
make_string_safe_for_id,
)
and context (classes, functions, sometimes code) from other files:
# Path: notifications_utils/safe_string.py
# def make_string_safe_for_email_local_part(string):
# return make_string_safe(string, whitespace='.')
#
# def make_string_safe_for_id(string):
# return make_string_safe(string, whitespace='-')
. Output only the next line. | ('trailing-', 'trailing-'), |
Predict the next line after this snippet: <|code_start|>
@pytest.mark.parametrize('unsafe_string, expected_safe', [
('name with spaces', 'name.with.spaces'),
('singleword', 'singleword'),
('UPPER CASE', 'upper.case'),
('Service - with dash', 'service.with.dash'),
('lots of spaces', 'lots.of.spaces'),
('name.with.dots', 'name.with.dots'),
('name-with-other-delimiters', 'namewithotherdelimiters'),
('.leading', 'leading'),
('trailing.', 'trailing'),
('üńïçödë wördś', 'unicode.words'),
])
def test_email_safe_return_dot_separated_email_local_part(unsafe_string, expected_safe):
assert make_string_safe_for_email_local_part(unsafe_string) == expected_safe
@pytest.mark.parametrize('unsafe_string, expected_safe', [
('name with spaces', 'name-with-spaces'),
('singleword', 'singleword'),
<|code_end|>
using the current file's imports:
import pytest
from notifications_utils.safe_string import (
make_string_safe_for_email_local_part,
make_string_safe_for_id,
)
and any relevant context from other files:
# Path: notifications_utils/safe_string.py
# def make_string_safe_for_email_local_part(string):
# return make_string_safe(string, whitespace='.')
#
# def make_string_safe_for_id(string):
# return make_string_safe(string, whitespace='-')
. Output only the next line. | ('UPPER CASE', 'upper-case'), |
Given snippet: <|code_start|>
@pytest.mark.parametrize('header,secrets,expected', [
({'X-Custom-Forwarder': 'right_key'}, ['right_key', 'old_key'], (True, 'Key used: 1')),
({'X-Custom-Forwarder': 'right_key'}, ['right_key'], (True, 'Key used: 1')),
({'X-Custom-Forwarder': 'right_key'}, ['right_key', ''], (True, 'Key used: 1')),
({'My-New-Header': 'right_key'}, ['right_key', ''], (True, 'Key used: 1')),
({'X-Custom-Forwarder': 'right_key'}, ['', 'right_key'], (True, 'Key used: 2')),
({'X-Custom-Forwarder': 'right_key'}, ['', 'old_key', 'right_key'], (True, 'Key used: 3')),
({'X-Custom-Forwarder': ''}, ['right_key', 'old_key'], (False, 'Header exists but is empty')),
({'X-Custom-Forwarder': 'right_key'}, ['', None], (False, 'Secrets are not configured')),
({'X-Custom-Forwarder': 'wrong_key'}, ['right_key', 'old_key'], (False, "Header didn't match any keys")),
])
def test_request_header_authorization(header, secrets, expected):
builder = EnvironBuilder()
builder.headers.extend(header)
request = NotifyRequest(builder.get_environ())
res = _check_proxy_header_secret(request, secrets, list(header.keys())[0])
assert res == expected
@pytest.mark.parametrize('secrets,expected', [
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from unittest import mock # noqa
from werkzeug.test import EnvironBuilder
from notifications_utils.request_helper import (
NotifyRequest,
_check_proxy_header_secret,
)
import pytest
and context:
# Path: notifications_utils/request_helper.py
# class NotifyRequest(Request):
# """
# A custom Request class, implementing extraction of zipkin headers used to trace request through cloudfoundry
# as described here: https://docs.cloudfoundry.org/concepts/http-routing.html#zipkin-headers
# """
#
# @property
# def request_id(self):
# return self.trace_id
#
# @property
# def trace_id(self):
# """
# The "trace id" (in zipkin terms) assigned to this request, if present (None otherwise)
# """
# if not hasattr(self, "_trace_id"):
# self._trace_id = self._get_header_value(current_app.config['NOTIFY_TRACE_ID_HEADER'])
# return self._trace_id
#
# @property
# def span_id(self):
# """
# The "span id" (in zipkin terms) set in this request's header, if present (None otherwise)
# """
# if not hasattr(self, "_span_id"):
# # note how we don't generate an id of our own. not being supplied a span id implies that we are running in
# # an environment with no span-id-aware request router, and thus would have no intermediary to prevent the
# # propagation of our span id all the way through all our onwards requests much like trace id. and the point
# # of span id is to assign identifiers to each individual request.
# self._span_id = self._get_header_value(current_app.config['NOTIFY_SPAN_ID_HEADER'])
# return self._span_id
#
# @property
# def parent_span_id(self):
# """
# The "parent span id" (in zipkin terms) set in this request's header, if present (None otherwise)
# """
# if not hasattr(self, "_parent_span_id"):
# self._parent_span_id = self._get_header_value(current_app.config['NOTIFY_PARENT_SPAN_ID_HEADER'])
# return self._parent_span_id
#
# def _get_header_value(self, header_name):
# """
# Returns value of the given header
# """
# if header_name in self.headers and self.headers[header_name]:
# return self.headers[header_name]
#
# return None
#
# def _check_proxy_header_secret(request, secrets, header='X-Custom-Forwarder'):
# if header not in request.headers:
# return False, "Header missing"
#
# header_secret = request.headers.get(header)
# if not header_secret:
# return False, "Header exists but is empty"
#
# # if there isn't any non-empty secret configured we fail closed
# if not any(secrets):
# return False, "Secrets are not configured"
#
# for i, secret in enumerate(secrets):
# if header_secret == secret:
# return True, "Key used: {}".format(i + 1) # add 1 to make it human-compatible
#
# return False, "Header didn't match any keys"
which might include code, classes, or functions. Output only the next line. | (['old_key', 'right_key'], (False, 'Header missing')), |
Using the snippet: <|code_start|>
@pytest.mark.parametrize('header,secrets,expected', [
({'X-Custom-Forwarder': 'right_key'}, ['right_key', 'old_key'], (True, 'Key used: 1')),
({'X-Custom-Forwarder': 'right_key'}, ['right_key'], (True, 'Key used: 1')),
({'X-Custom-Forwarder': 'right_key'}, ['right_key', ''], (True, 'Key used: 1')),
({'My-New-Header': 'right_key'}, ['right_key', ''], (True, 'Key used: 1')),
({'X-Custom-Forwarder': 'right_key'}, ['', 'right_key'], (True, 'Key used: 2')),
({'X-Custom-Forwarder': 'right_key'}, ['', 'old_key', 'right_key'], (True, 'Key used: 3')),
({'X-Custom-Forwarder': ''}, ['right_key', 'old_key'], (False, 'Header exists but is empty')),
({'X-Custom-Forwarder': 'right_key'}, ['', None], (False, 'Secrets are not configured')),
({'X-Custom-Forwarder': 'wrong_key'}, ['right_key', 'old_key'], (False, "Header didn't match any keys")),
<|code_end|>
, determine the next line of code. You have imports:
from unittest import mock # noqa
from werkzeug.test import EnvironBuilder
from notifications_utils.request_helper import (
NotifyRequest,
_check_proxy_header_secret,
)
import pytest
and context (class names, function names, or code) available:
# Path: notifications_utils/request_helper.py
# class NotifyRequest(Request):
# """
# A custom Request class, implementing extraction of zipkin headers used to trace request through cloudfoundry
# as described here: https://docs.cloudfoundry.org/concepts/http-routing.html#zipkin-headers
# """
#
# @property
# def request_id(self):
# return self.trace_id
#
# @property
# def trace_id(self):
# """
# The "trace id" (in zipkin terms) assigned to this request, if present (None otherwise)
# """
# if not hasattr(self, "_trace_id"):
# self._trace_id = self._get_header_value(current_app.config['NOTIFY_TRACE_ID_HEADER'])
# return self._trace_id
#
# @property
# def span_id(self):
# """
# The "span id" (in zipkin terms) set in this request's header, if present (None otherwise)
# """
# if not hasattr(self, "_span_id"):
# # note how we don't generate an id of our own. not being supplied a span id implies that we are running in
# # an environment with no span-id-aware request router, and thus would have no intermediary to prevent the
# # propagation of our span id all the way through all our onwards requests much like trace id. and the point
# # of span id is to assign identifiers to each individual request.
# self._span_id = self._get_header_value(current_app.config['NOTIFY_SPAN_ID_HEADER'])
# return self._span_id
#
# @property
# def parent_span_id(self):
# """
# The "parent span id" (in zipkin terms) set in this request's header, if present (None otherwise)
# """
# if not hasattr(self, "_parent_span_id"):
# self._parent_span_id = self._get_header_value(current_app.config['NOTIFY_PARENT_SPAN_ID_HEADER'])
# return self._parent_span_id
#
# def _get_header_value(self, header_name):
# """
# Returns value of the given header
# """
# if header_name in self.headers and self.headers[header_name]:
# return self.headers[header_name]
#
# return None
#
# def _check_proxy_header_secret(request, secrets, header='X-Custom-Forwarder'):
# if header not in request.headers:
# return False, "Header missing"
#
# header_secret = request.headers.get(header)
# if not header_secret:
# return False, "Header exists but is empty"
#
# # if there isn't any non-empty secret configured we fail closed
# if not any(secrets):
# return False, "Secrets are not configured"
#
# for i, secret in enumerate(secrets):
# if header_secret == secret:
# return True, "Key used: {}".format(i + 1) # add 1 to make it human-compatible
#
# return False, "Header didn't match any keys"
. Output only the next line. | ]) |
Continue the code snippet: <|code_start|> notify_celery,
):
super_apply = mocker.patch('celery.Celery.send_task')
g.request_id = '1234'
notify_celery.send_task(
'some-task',
None, # args
None, # kwargs
headers=None, # other kwargs (task retry set headers to "None")
)
super_apply.assert_called_with(
'some-task', # name
None, # args
None, # kwargs
headers={'notify_request_id': '1234'} # other kwargs
)
def test_send_task_injects_id_from_request(
mocker,
notify_celery,
celery_app,
):
super_apply = mocker.patch('celery.Celery.send_task')
request_id_header = celery_app.config['NOTIFY_TRACE_ID_HEADER']
request_headers = {request_id_header: '1234'}
with celery_app.test_request_context(headers=request_headers):
<|code_end|>
. Use current file imports:
import uuid
import pytest
from flask import g
from freezegun import freeze_time
from notifications_utils.celery import NotifyCelery
and context (classes, functions, or code) from other files:
# Path: notifications_utils/celery.py
# class NotifyCelery(Celery):
# def init_app(self, app):
# super().__init__(
# task_cls=make_task(app),
# )
#
# # Make sure this is present upfront to avoid errors later on.
# assert app.statsd_client
#
# # Configure Celery app with options from the main app config.
# self.conf.update(app.config['CELERY'])
#
# def send_task(self, name, args=None, kwargs=None, **other_kwargs):
# other_kwargs['headers'] = other_kwargs.get('headers') or {}
#
# if has_request_context() and hasattr(request, 'request_id'):
# other_kwargs['headers']['notify_request_id'] = request.request_id
#
# elif has_app_context() and 'request_id' in g:
# other_kwargs['headers']['notify_request_id'] = g.request_id
#
# return super().send_task(name, args, kwargs, **other_kwargs)
. Output only the next line. | notify_celery.send_task('some-task') |
Given the following code snippet before the placeholder: <|code_start|>
def test_bytes_to_base64_to_bytes():
b = os.urandom(32)
b64 = bytes_to_base64(b)
assert base64_to_bytes(b64) == b
@pytest.mark.parametrize('url_val', [
'AAAAAAAAAAAAAAAAAAAAAQ',
'AAAAAAAAAAAAAAAAAAAAAQ=', # even though this has invalid padding we put extra =s on the end so this is okay
'AAAAAAAAAAAAAAAAAAAAAQ==',
])
def test_base64_converter_to_python(url_val):
assert base64_to_uuid(url_val) == UUID(int=1)
@pytest.mark.parametrize('python_val', [
UUID(int=1),
'00000000-0000-0000-0000-000000000001'
])
def test_base64_converter_to_url(python_val):
assert uuid_to_base64(python_val) == 'AAAAAAAAAAAAAAAAAAAAAQ'
@pytest.mark.parametrize('url_val', [
'this_is_valid_base64_but_is_too_long_to_be_a_uuid',
'this_one_has_emoji_➕➕➕',
<|code_end|>
, predict the next line using imports from the current file:
import os
import pytest
from uuid import UUID
from notifications_utils.base64_uuid import (
base64_to_bytes,
base64_to_uuid,
bytes_to_base64,
uuid_to_base64,
)
and context including class names, function names, and sometimes code from other files:
# Path: notifications_utils/base64_uuid.py
# def base64_to_bytes(key):
# return urlsafe_b64decode(key + '==')
#
# def base64_to_uuid(value):
# # uuids are 16 bytes, and will always have two ==s of padding
# return UUID(bytes=urlsafe_b64decode(value.encode('ascii') + b'=='))
#
# def bytes_to_base64(bytes):
# # remove trailing = to save precious bytes
# return urlsafe_b64encode(bytes).decode('ascii').rstrip('=')
#
# def uuid_to_base64(value):
# if not isinstance(value, UUID):
# value = UUID(value)
# return bytes_to_base64(value.bytes)
. Output only the next line. | ]) |
Predict the next line after this snippet: <|code_start|> assert base64_to_bytes(b64) == b
@pytest.mark.parametrize('url_val', [
'AAAAAAAAAAAAAAAAAAAAAQ',
'AAAAAAAAAAAAAAAAAAAAAQ=', # even though this has invalid padding we put extra =s on the end so this is okay
'AAAAAAAAAAAAAAAAAAAAAQ==',
])
def test_base64_converter_to_python(url_val):
assert base64_to_uuid(url_val) == UUID(int=1)
@pytest.mark.parametrize('python_val', [
UUID(int=1),
'00000000-0000-0000-0000-000000000001'
])
def test_base64_converter_to_url(python_val):
assert uuid_to_base64(python_val) == 'AAAAAAAAAAAAAAAAAAAAAQ'
@pytest.mark.parametrize('url_val', [
'this_is_valid_base64_but_is_too_long_to_be_a_uuid',
'this_one_has_emoji_➕➕➕',
])
def test_base64_converter_to_python_raises_validation_error(url_val):
with pytest.raises(Exception):
base64_to_uuid(url_val)
def test_base64_converter_to_url_raises_validation_error():
<|code_end|>
using the current file's imports:
import os
import pytest
from uuid import UUID
from notifications_utils.base64_uuid import (
base64_to_bytes,
base64_to_uuid,
bytes_to_base64,
uuid_to_base64,
)
and any relevant context from other files:
# Path: notifications_utils/base64_uuid.py
# def base64_to_bytes(key):
# return urlsafe_b64decode(key + '==')
#
# def base64_to_uuid(value):
# # uuids are 16 bytes, and will always have two ==s of padding
# return UUID(bytes=urlsafe_b64decode(value.encode('ascii') + b'=='))
#
# def bytes_to_base64(bytes):
# # remove trailing = to save precious bytes
# return urlsafe_b64encode(bytes).decode('ascii').rstrip('=')
#
# def uuid_to_base64(value):
# if not isinstance(value, UUID):
# value = UUID(value)
# return bytes_to_base64(value.bytes)
. Output only the next line. | with pytest.raises(Exception): |
Predict the next line for this snippet: <|code_start|>
def test_bytes_to_base64_to_bytes():
b = os.urandom(32)
b64 = bytes_to_base64(b)
assert base64_to_bytes(b64) == b
@pytest.mark.parametrize('url_val', [
'AAAAAAAAAAAAAAAAAAAAAQ',
'AAAAAAAAAAAAAAAAAAAAAQ=', # even though this has invalid padding we put extra =s on the end so this is okay
'AAAAAAAAAAAAAAAAAAAAAQ==',
])
def test_base64_converter_to_python(url_val):
assert base64_to_uuid(url_val) == UUID(int=1)
@pytest.mark.parametrize('python_val', [
UUID(int=1),
'00000000-0000-0000-0000-000000000001'
<|code_end|>
with the help of current file imports:
import os
import pytest
from uuid import UUID
from notifications_utils.base64_uuid import (
base64_to_bytes,
base64_to_uuid,
bytes_to_base64,
uuid_to_base64,
)
and context from other files:
# Path: notifications_utils/base64_uuid.py
# def base64_to_bytes(key):
# return urlsafe_b64decode(key + '==')
#
# def base64_to_uuid(value):
# # uuids are 16 bytes, and will always have two ==s of padding
# return UUID(bytes=urlsafe_b64decode(value.encode('ascii') + b'=='))
#
# def bytes_to_base64(bytes):
# # remove trailing = to save precious bytes
# return urlsafe_b64encode(bytes).decode('ascii').rstrip('=')
#
# def uuid_to_base64(value):
# if not isinstance(value, UUID):
# value = UUID(value)
# return bytes_to_base64(value.bytes)
, which may contain function names, class names, or code. Output only the next line. | ]) |
Using the snippet: <|code_start|>
def test_bytes_to_base64_to_bytes():
b = os.urandom(32)
b64 = bytes_to_base64(b)
assert base64_to_bytes(b64) == b
@pytest.mark.parametrize('url_val', [
'AAAAAAAAAAAAAAAAAAAAAQ',
'AAAAAAAAAAAAAAAAAAAAAQ=', # even though this has invalid padding we put extra =s on the end so this is okay
'AAAAAAAAAAAAAAAAAAAAAQ==',
])
def test_base64_converter_to_python(url_val):
assert base64_to_uuid(url_val) == UUID(int=1)
@pytest.mark.parametrize('python_val', [
UUID(int=1),
'00000000-0000-0000-0000-000000000001'
])
def test_base64_converter_to_url(python_val):
assert uuid_to_base64(python_val) == 'AAAAAAAAAAAAAAAAAAAAAQ'
@pytest.mark.parametrize('url_val', [
'this_is_valid_base64_but_is_too_long_to_be_a_uuid',
'this_one_has_emoji_➕➕➕',
<|code_end|>
, determine the next line of code. You have imports:
import os
import pytest
from uuid import UUID
from notifications_utils.base64_uuid import (
base64_to_bytes,
base64_to_uuid,
bytes_to_base64,
uuid_to_base64,
)
and context (class names, function names, or code) available:
# Path: notifications_utils/base64_uuid.py
# def base64_to_bytes(key):
# return urlsafe_b64decode(key + '==')
#
# def base64_to_uuid(value):
# # uuids are 16 bytes, and will always have two ==s of padding
# return UUID(bytes=urlsafe_b64decode(value.encode('ascii') + b'=='))
#
# def bytes_to_base64(bytes):
# # remove trailing = to save precious bytes
# return urlsafe_b64encode(bytes).decode('ascii').rstrip('=')
#
# def uuid_to_base64(value):
# if not isinstance(value, UUID):
# value = UUID(value)
# return bytes_to_base64(value.bytes)
. Output only the next line. | ]) |
Here is a snippet: <|code_start|>
@pytest.fixture(scope='function')
def antivirus(app, mocker):
client = AntivirusClient()
app.config['ANTIVIRUS_API_HOST'] = 'https://antivirus'
app.config['ANTIVIRUS_API_KEY'] = 'test-antivirus-key'
<|code_end|>
. Write the next line using the current file imports:
import io
import pytest
import requests
from notifications_utils.clients.antivirus.antivirus_client import (
AntivirusClient,
AntivirusError,
)
and context from other files:
# Path: notifications_utils/clients/antivirus/antivirus_client.py
# class AntivirusClient:
# def __init__(self, api_host=None, auth_token=None):
# self.api_host = api_host
# self.auth_token = auth_token
#
# def init_app(self, app):
# self.api_host = app.config['ANTIVIRUS_API_HOST']
# self.auth_token = app.config['ANTIVIRUS_API_KEY']
#
# def scan(self, document_stream):
# try:
# response = requests.post(
# "{}/scan".format(self.api_host),
# headers={
# 'Authorization': "Bearer {}".format(self.auth_token),
# },
# files={
# 'document': document_stream
# }
# )
#
# response.raise_for_status()
#
# except requests.RequestException as e:
# error = AntivirusError.from_exception(e)
# current_app.logger.warning(
# 'Notify Antivirus API request failed with error: {}'.format(error.message)
# )
#
# raise error
# finally:
# document_stream.seek(0)
#
# return response.json()['ok']
#
# class AntivirusError(Exception):
# def __init__(self, message=None, status_code=None):
# self.message = message
# self.status_code = status_code
#
# @classmethod
# def from_exception(cls, e):
# try:
# message = e.response.json()['error']
# status_code = e.response.status_code
# except (TypeError, ValueError, AttributeError, KeyError):
# message = 'connection error'
# status_code = 503
#
# return cls(message, status_code)
, which may include functions, classes, or code. Output only the next line. | client.init_app(app) |
Given the following code snippet before the placeholder: <|code_start|> client = AntivirusClient()
app.config['ANTIVIRUS_API_HOST'] = 'https://antivirus'
app.config['ANTIVIRUS_API_KEY'] = 'test-antivirus-key'
client.init_app(app)
return client
def test_scan_document(antivirus, rmock):
document = io.BytesIO(b'filecontents')
rmock.request('POST', 'https://antivirus/scan', json={
'ok': True
}, request_headers={
'Authorization': 'Bearer test-antivirus-key',
}, status_code=200)
resp = antivirus.scan(document)
assert resp
assert 'filecontents' in rmock.last_request.text
assert document.tell() == 0
def test_should_raise_for_status(antivirus, rmock):
with pytest.raises(AntivirusError) as excinfo:
rmock.request('POST', 'https://antivirus/scan', json={
'error': 'Antivirus error'
}, status_code=400)
antivirus.scan(io.BytesIO(b'document'))
<|code_end|>
, predict the next line using imports from the current file:
import io
import pytest
import requests
from notifications_utils.clients.antivirus.antivirus_client import (
AntivirusClient,
AntivirusError,
)
and context including class names, function names, and sometimes code from other files:
# Path: notifications_utils/clients/antivirus/antivirus_client.py
# class AntivirusClient:
# def __init__(self, api_host=None, auth_token=None):
# self.api_host = api_host
# self.auth_token = auth_token
#
# def init_app(self, app):
# self.api_host = app.config['ANTIVIRUS_API_HOST']
# self.auth_token = app.config['ANTIVIRUS_API_KEY']
#
# def scan(self, document_stream):
# try:
# response = requests.post(
# "{}/scan".format(self.api_host),
# headers={
# 'Authorization': "Bearer {}".format(self.auth_token),
# },
# files={
# 'document': document_stream
# }
# )
#
# response.raise_for_status()
#
# except requests.RequestException as e:
# error = AntivirusError.from_exception(e)
# current_app.logger.warning(
# 'Notify Antivirus API request failed with error: {}'.format(error.message)
# )
#
# raise error
# finally:
# document_stream.seek(0)
#
# return response.json()['ok']
#
# class AntivirusError(Exception):
# def __init__(self, message=None, status_code=None):
# self.message = message
# self.status_code = status_code
#
# @classmethod
# def from_exception(cls, e):
# try:
# message = e.response.json()['error']
# status_code = e.response.status_code
# except (TypeError, ValueError, AttributeError, KeyError):
# message = 'connection error'
# status_code = 503
#
# return cls(message, status_code)
. Output only the next line. | assert excinfo.value.message == 'Antivirus error' |
Predict the next line for this snippet: <|code_start|>
class Placeholder:
def __init__(self, body):
# body shouldn’t include leading/trailing brackets, like (( and ))
self.body = body.lstrip('(').rstrip(')')
@classmethod
def from_match(cls, match):
return cls(match.group(0))
def is_conditional(self):
return '??' in self.body
<|code_end|>
with the help of current file imports:
import re
from markupsafe import Markup
from orderedset import OrderedSet
from notifications_utils.formatters import (
escape_html,
strip_and_remove_obscure_whitespace,
strip_html,
unescaped_formatted_list,
)
from notifications_utils.insensitive_dict import InsensitiveDict
and context from other files:
# Path: notifications_utils/formatters.py
# def escape_html(value):
# if not value:
# return value
# value = str(value)
#
# for entity, temporary_replacement in HTML_ENTITY_MAPPING:
# value = value.replace(entity, temporary_replacement)
#
# value = escape(unescape_strict(value), quote=False)
#
# for entity, temporary_replacement in HTML_ENTITY_MAPPING:
# value = value.replace(temporary_replacement, entity)
#
# return value
#
# def strip_and_remove_obscure_whitespace(value):
# if value == '':
# # Return early to avoid making multiple, slow calls to
# # str.replace on an empty string
# return ''
#
# for character in OBSCURE_ZERO_WIDTH_WHITESPACE + OBSCURE_FULL_WIDTH_WHITESPACE:
# value = value.replace(character, '')
#
# return value.strip(string.whitespace)
#
# def strip_html(value):
# return bleach.clean(value, tags=[], strip=True)
#
# def unescaped_formatted_list(
# items,
# conjunction='and',
# before_each='‘',
# after_each='’',
# separator=', ',
# prefix='',
# prefix_plural=''
# ):
# if prefix:
# prefix += ' '
# if prefix_plural:
# prefix_plural += ' '
#
# if len(items) == 1:
# return '{prefix}{before_each}{items[0]}{after_each}'.format(**locals())
# elif items:
# formatted_items = ['{}{}{}'.format(before_each, item, after_each) for item in items]
#
# first_items = separator.join(formatted_items[:-1])
# last_item = formatted_items[-1]
# return (
# '{prefix_plural}{first_items} {conjunction} {last_item}'
# ).format(**locals())
#
# Path: notifications_utils/insensitive_dict.py
# class InsensitiveDict(OrderedDict):
#
# """
# `InsensitiveDict` behaves like an ordered dictionary, except it normalises
# case, whitespace, hypens and underscores in keys.
#
# In other words,
# InsensitiveDict({'FIRST_NAME': 'example'}) == InsensitiveDict({'first name': 'example'})
# >>> True
# """
#
# KEY_TRANSLATION_TABLE = {
# ord(c): None for c in ' _-'
# }
#
# def __init__(self, row_dict):
# for key, value in row_dict.items():
# self[key] = value
#
# @classmethod
# def from_keys(cls, keys):
# """
# This behaves like `dict.from_keys`, except:
# - it normalises the keys to ignore case, whitespace, hypens and
# underscores
# - it stores the original, unnormalised key as the value of the
# item so it can be retrieved later
# """
# return cls(OrderedDict([(key, key) for key in keys]))
#
# def keys(self):
# return OrderedSet(super().keys())
#
# def __getitem__(self, key):
# return super().__getitem__(self.make_key(key))
#
# def __setitem__(self, key, value):
# super().__setitem__(self.make_key(key), value)
#
# def __contains__(self, key):
# return super().__contains__(self.make_key(key))
#
# def get(self, key, default=None):
# return self[key] if key in self else default
#
# def copy(self):
# return self.__class__(super().copy())
#
# def as_dict_with_keys(self, keys):
# return {
# key: self.get(key) for key in keys
# }
#
# @staticmethod
# @lru_cache(maxsize=32, typed=False)
# def make_key(original_key):
# if original_key is None:
# return None
# return original_key.translate(InsensitiveDict.KEY_TRANSLATION_TABLE).lower()
, which may contain function names, class names, or code. Output only the next line. | @property |
Predict the next line after this snippet: <|code_start|>
class Placeholder:
def __init__(self, body):
# body shouldn’t include leading/trailing brackets, like (( and ))
self.body = body.lstrip('(').rstrip(')')
@classmethod
def from_match(cls, match):
return cls(match.group(0))
def is_conditional(self):
return '??' in self.body
@property
<|code_end|>
using the current file's imports:
import re
from markupsafe import Markup
from orderedset import OrderedSet
from notifications_utils.formatters import (
escape_html,
strip_and_remove_obscure_whitespace,
strip_html,
unescaped_formatted_list,
)
from notifications_utils.insensitive_dict import InsensitiveDict
and any relevant context from other files:
# Path: notifications_utils/formatters.py
# def escape_html(value):
# if not value:
# return value
# value = str(value)
#
# for entity, temporary_replacement in HTML_ENTITY_MAPPING:
# value = value.replace(entity, temporary_replacement)
#
# value = escape(unescape_strict(value), quote=False)
#
# for entity, temporary_replacement in HTML_ENTITY_MAPPING:
# value = value.replace(temporary_replacement, entity)
#
# return value
#
# def strip_and_remove_obscure_whitespace(value):
# if value == '':
# # Return early to avoid making multiple, slow calls to
# # str.replace on an empty string
# return ''
#
# for character in OBSCURE_ZERO_WIDTH_WHITESPACE + OBSCURE_FULL_WIDTH_WHITESPACE:
# value = value.replace(character, '')
#
# return value.strip(string.whitespace)
#
# def strip_html(value):
# return bleach.clean(value, tags=[], strip=True)
#
# def unescaped_formatted_list(
# items,
# conjunction='and',
# before_each='‘',
# after_each='’',
# separator=', ',
# prefix='',
# prefix_plural=''
# ):
# if prefix:
# prefix += ' '
# if prefix_plural:
# prefix_plural += ' '
#
# if len(items) == 1:
# return '{prefix}{before_each}{items[0]}{after_each}'.format(**locals())
# elif items:
# formatted_items = ['{}{}{}'.format(before_each, item, after_each) for item in items]
#
# first_items = separator.join(formatted_items[:-1])
# last_item = formatted_items[-1]
# return (
# '{prefix_plural}{first_items} {conjunction} {last_item}'
# ).format(**locals())
#
# Path: notifications_utils/insensitive_dict.py
# class InsensitiveDict(OrderedDict):
#
# """
# `InsensitiveDict` behaves like an ordered dictionary, except it normalises
# case, whitespace, hypens and underscores in keys.
#
# In other words,
# InsensitiveDict({'FIRST_NAME': 'example'}) == InsensitiveDict({'first name': 'example'})
# >>> True
# """
#
# KEY_TRANSLATION_TABLE = {
# ord(c): None for c in ' _-'
# }
#
# def __init__(self, row_dict):
# for key, value in row_dict.items():
# self[key] = value
#
# @classmethod
# def from_keys(cls, keys):
# """
# This behaves like `dict.from_keys`, except:
# - it normalises the keys to ignore case, whitespace, hypens and
# underscores
# - it stores the original, unnormalised key as the value of the
# item so it can be retrieved later
# """
# return cls(OrderedDict([(key, key) for key in keys]))
#
# def keys(self):
# return OrderedSet(super().keys())
#
# def __getitem__(self, key):
# return super().__getitem__(self.make_key(key))
#
# def __setitem__(self, key, value):
# super().__setitem__(self.make_key(key), value)
#
# def __contains__(self, key):
# return super().__contains__(self.make_key(key))
#
# def get(self, key, default=None):
# return self[key] if key in self else default
#
# def copy(self):
# return self.__class__(super().copy())
#
# def as_dict_with_keys(self, keys):
# return {
# key: self.get(key) for key in keys
# }
#
# @staticmethod
# @lru_cache(maxsize=32, typed=False)
# def make_key(original_key):
# if original_key is None:
# return None
# return original_key.translate(InsensitiveDict.KEY_TRANSLATION_TABLE).lower()
. Output only the next line. | def name(self): |
Predict the next line after this snippet: <|code_start|>
class Placeholder:
def __init__(self, body):
# body shouldn’t include leading/trailing brackets, like (( and ))
self.body = body.lstrip('(').rstrip(')')
@classmethod
def from_match(cls, match):
return cls(match.group(0))
def is_conditional(self):
return '??' in self.body
@property
def name(self):
# for non conditionals, name equals body
return self.body.split('??')[0]
@property
def conditional_text(self):
if self.is_conditional():
# ((a?? b??c)) returns " b??c"
return '??'.join(self.body.split('??')[1:])
else:
raise ValueError('{} not conditional'.format(self))
def get_conditional_body(self, show_conditional):
# note: unsanitised/converted
<|code_end|>
using the current file's imports:
import re
from markupsafe import Markup
from orderedset import OrderedSet
from notifications_utils.formatters import (
escape_html,
strip_and_remove_obscure_whitespace,
strip_html,
unescaped_formatted_list,
)
from notifications_utils.insensitive_dict import InsensitiveDict
and any relevant context from other files:
# Path: notifications_utils/formatters.py
# def escape_html(value):
# if not value:
# return value
# value = str(value)
#
# for entity, temporary_replacement in HTML_ENTITY_MAPPING:
# value = value.replace(entity, temporary_replacement)
#
# value = escape(unescape_strict(value), quote=False)
#
# for entity, temporary_replacement in HTML_ENTITY_MAPPING:
# value = value.replace(temporary_replacement, entity)
#
# return value
#
# def strip_and_remove_obscure_whitespace(value):
# if value == '':
# # Return early to avoid making multiple, slow calls to
# # str.replace on an empty string
# return ''
#
# for character in OBSCURE_ZERO_WIDTH_WHITESPACE + OBSCURE_FULL_WIDTH_WHITESPACE:
# value = value.replace(character, '')
#
# return value.strip(string.whitespace)
#
# def strip_html(value):
# return bleach.clean(value, tags=[], strip=True)
#
# def unescaped_formatted_list(
# items,
# conjunction='and',
# before_each='‘',
# after_each='’',
# separator=', ',
# prefix='',
# prefix_plural=''
# ):
# if prefix:
# prefix += ' '
# if prefix_plural:
# prefix_plural += ' '
#
# if len(items) == 1:
# return '{prefix}{before_each}{items[0]}{after_each}'.format(**locals())
# elif items:
# formatted_items = ['{}{}{}'.format(before_each, item, after_each) for item in items]
#
# first_items = separator.join(formatted_items[:-1])
# last_item = formatted_items[-1]
# return (
# '{prefix_plural}{first_items} {conjunction} {last_item}'
# ).format(**locals())
#
# Path: notifications_utils/insensitive_dict.py
# class InsensitiveDict(OrderedDict):
#
# """
# `InsensitiveDict` behaves like an ordered dictionary, except it normalises
# case, whitespace, hypens and underscores in keys.
#
# In other words,
# InsensitiveDict({'FIRST_NAME': 'example'}) == InsensitiveDict({'first name': 'example'})
# >>> True
# """
#
# KEY_TRANSLATION_TABLE = {
# ord(c): None for c in ' _-'
# }
#
# def __init__(self, row_dict):
# for key, value in row_dict.items():
# self[key] = value
#
# @classmethod
# def from_keys(cls, keys):
# """
# This behaves like `dict.from_keys`, except:
# - it normalises the keys to ignore case, whitespace, hypens and
# underscores
# - it stores the original, unnormalised key as the value of the
# item so it can be retrieved later
# """
# return cls(OrderedDict([(key, key) for key in keys]))
#
# def keys(self):
# return OrderedSet(super().keys())
#
# def __getitem__(self, key):
# return super().__getitem__(self.make_key(key))
#
# def __setitem__(self, key, value):
# super().__setitem__(self.make_key(key), value)
#
# def __contains__(self, key):
# return super().__contains__(self.make_key(key))
#
# def get(self, key, default=None):
# return self[key] if key in self else default
#
# def copy(self):
# return self.__class__(super().copy())
#
# def as_dict_with_keys(self, keys):
# return {
# key: self.get(key) for key in keys
# }
#
# @staticmethod
# @lru_cache(maxsize=32, typed=False)
# def make_key(original_key):
# if original_key is None:
# return None
# return original_key.translate(InsensitiveDict.KEY_TRANSLATION_TABLE).lower()
. Output only the next line. | if self.is_conditional(): |
Next line prediction: <|code_start|>class Placeholder:
def __init__(self, body):
# body shouldn’t include leading/trailing brackets, like (( and ))
self.body = body.lstrip('(').rstrip(')')
@classmethod
def from_match(cls, match):
return cls(match.group(0))
def is_conditional(self):
return '??' in self.body
@property
def name(self):
# for non conditionals, name equals body
return self.body.split('??')[0]
@property
def conditional_text(self):
if self.is_conditional():
# ((a?? b??c)) returns " b??c"
return '??'.join(self.body.split('??')[1:])
else:
raise ValueError('{} not conditional'.format(self))
def get_conditional_body(self, show_conditional):
# note: unsanitised/converted
if self.is_conditional():
return self.conditional_text if str2bool(show_conditional) else ''
else:
<|code_end|>
. Use current file imports:
(import re
from markupsafe import Markup
from orderedset import OrderedSet
from notifications_utils.formatters import (
escape_html,
strip_and_remove_obscure_whitespace,
strip_html,
unescaped_formatted_list,
)
from notifications_utils.insensitive_dict import InsensitiveDict)
and context including class names, function names, or small code snippets from other files:
# Path: notifications_utils/formatters.py
# def escape_html(value):
# if not value:
# return value
# value = str(value)
#
# for entity, temporary_replacement in HTML_ENTITY_MAPPING:
# value = value.replace(entity, temporary_replacement)
#
# value = escape(unescape_strict(value), quote=False)
#
# for entity, temporary_replacement in HTML_ENTITY_MAPPING:
# value = value.replace(temporary_replacement, entity)
#
# return value
#
# def strip_and_remove_obscure_whitespace(value):
# if value == '':
# # Return early to avoid making multiple, slow calls to
# # str.replace on an empty string
# return ''
#
# for character in OBSCURE_ZERO_WIDTH_WHITESPACE + OBSCURE_FULL_WIDTH_WHITESPACE:
# value = value.replace(character, '')
#
# return value.strip(string.whitespace)
#
# def strip_html(value):
# return bleach.clean(value, tags=[], strip=True)
#
# def unescaped_formatted_list(
# items,
# conjunction='and',
# before_each='‘',
# after_each='’',
# separator=', ',
# prefix='',
# prefix_plural=''
# ):
# if prefix:
# prefix += ' '
# if prefix_plural:
# prefix_plural += ' '
#
# if len(items) == 1:
# return '{prefix}{before_each}{items[0]}{after_each}'.format(**locals())
# elif items:
# formatted_items = ['{}{}{}'.format(before_each, item, after_each) for item in items]
#
# first_items = separator.join(formatted_items[:-1])
# last_item = formatted_items[-1]
# return (
# '{prefix_plural}{first_items} {conjunction} {last_item}'
# ).format(**locals())
#
# Path: notifications_utils/insensitive_dict.py
# class InsensitiveDict(OrderedDict):
#
# """
# `InsensitiveDict` behaves like an ordered dictionary, except it normalises
# case, whitespace, hypens and underscores in keys.
#
# In other words,
# InsensitiveDict({'FIRST_NAME': 'example'}) == InsensitiveDict({'first name': 'example'})
# >>> True
# """
#
# KEY_TRANSLATION_TABLE = {
# ord(c): None for c in ' _-'
# }
#
# def __init__(self, row_dict):
# for key, value in row_dict.items():
# self[key] = value
#
# @classmethod
# def from_keys(cls, keys):
# """
# This behaves like `dict.from_keys`, except:
# - it normalises the keys to ignore case, whitespace, hypens and
# underscores
# - it stores the original, unnormalised key as the value of the
# item so it can be retrieved later
# """
# return cls(OrderedDict([(key, key) for key in keys]))
#
# def keys(self):
# return OrderedSet(super().keys())
#
# def __getitem__(self, key):
# return super().__getitem__(self.make_key(key))
#
# def __setitem__(self, key, value):
# super().__setitem__(self.make_key(key), value)
#
# def __contains__(self, key):
# return super().__contains__(self.make_key(key))
#
# def get(self, key, default=None):
# return self[key] if key in self else default
#
# def copy(self):
# return self.__class__(super().copy())
#
# def as_dict_with_keys(self, keys):
# return {
# key: self.get(key) for key in keys
# }
#
# @staticmethod
# @lru_cache(maxsize=32, typed=False)
# def make_key(original_key):
# if original_key is None:
# return None
# return original_key.translate(InsensitiveDict.KEY_TRANSLATION_TABLE).lower()
. Output only the next line. | raise ValueError('{} not conditional'.format(self)) |
Given snippet: <|code_start|>
def test_international_billing_rates_exists():
assert INTERNATIONAL_BILLING_RATES['1']['names'][0] == 'Canada'
@pytest.mark.parametrize('country_prefix, values', sorted(INTERNATIONAL_BILLING_RATES.items()))
def test_international_billing_rates_are_in_correct_format(country_prefix, values):
assert isinstance(country_prefix, str)
# we don't want the prefixes to have + at the beginning for instance
assert country_prefix.isdigit()
assert set(values.keys()) == {'attributes', 'billable_units', 'names'}
assert isinstance(values['billable_units'], int)
assert 1 <= values['billable_units'] <= 3
assert isinstance(values['names'], list)
assert all(isinstance(country, str) for country in values['names'])
assert isinstance(values['attributes'], dict)
assert values['attributes']['dlr'] is None or isinstance(values['attributes']['dlr'], str)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
from notifications_utils.international_billing_rates import (
COUNTRY_PREFIXES,
INTERNATIONAL_BILLING_RATES,
)
from notifications_utils.recipients import use_numeric_sender
and context:
# Path: notifications_utils/international_billing_rates.py
# COUNTRY_PREFIXES = list(reversed(sorted(INTERNATIONAL_BILLING_RATES.keys(), key=len)))
#
# INTERNATIONAL_BILLING_RATES = yaml.safe_load(f)
#
# Path: notifications_utils/recipients.py
# def use_numeric_sender(number):
# prefix = get_international_prefix(normalise_phone_number(number))
# return INTERNATIONAL_BILLING_RATES[prefix]['attributes']['alpha'] == 'NO'
which might include code, classes, or functions. Output only the next line. | def test_country_codes(): |
Based on the snippet: <|code_start|>
def test_international_billing_rates_exists():
assert INTERNATIONAL_BILLING_RATES['1']['names'][0] == 'Canada'
@pytest.mark.parametrize('country_prefix, values', sorted(INTERNATIONAL_BILLING_RATES.items()))
def test_international_billing_rates_are_in_correct_format(country_prefix, values):
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
from notifications_utils.international_billing_rates import (
COUNTRY_PREFIXES,
INTERNATIONAL_BILLING_RATES,
)
from notifications_utils.recipients import use_numeric_sender
and context (classes, functions, sometimes code) from other files:
# Path: notifications_utils/international_billing_rates.py
# COUNTRY_PREFIXES = list(reversed(sorted(INTERNATIONAL_BILLING_RATES.keys(), key=len)))
#
# INTERNATIONAL_BILLING_RATES = yaml.safe_load(f)
#
# Path: notifications_utils/recipients.py
# def use_numeric_sender(number):
# prefix = get_international_prefix(normalise_phone_number(number))
# return INTERNATIONAL_BILLING_RATES[prefix]['attributes']['alpha'] == 'NO'
. Output only the next line. | assert isinstance(country_prefix, str) |
Given the code snippet: <|code_start|>
def test_international_billing_rates_exists():
assert INTERNATIONAL_BILLING_RATES['1']['names'][0] == 'Canada'
@pytest.mark.parametrize('country_prefix, values', sorted(INTERNATIONAL_BILLING_RATES.items()))
<|code_end|>
, generate the next line using the imports in this file:
import pytest
from notifications_utils.international_billing_rates import (
COUNTRY_PREFIXES,
INTERNATIONAL_BILLING_RATES,
)
from notifications_utils.recipients import use_numeric_sender
and context (functions, classes, or occasionally code) from other files:
# Path: notifications_utils/international_billing_rates.py
# COUNTRY_PREFIXES = list(reversed(sorted(INTERNATIONAL_BILLING_RATES.keys(), key=len)))
#
# INTERNATIONAL_BILLING_RATES = yaml.safe_load(f)
#
# Path: notifications_utils/recipients.py
# def use_numeric_sender(number):
# prefix = get_international_prefix(normalise_phone_number(number))
# return INTERNATIONAL_BILLING_RATES[prefix]['attributes']['alpha'] == 'NO'
. Output only the next line. | def test_international_billing_rates_are_in_correct_format(country_prefix, values): |
Predict the next line after this snippet: <|code_start|>
class AnyStringWith(str):
def __eq__(self, other):
return self in other
def test_should_call_statsd(app, mocker):
app.config['NOTIFY_ENVIRONMENT'] = "test"
app.config['NOTIFY_APP_NAME'] = "api"
app.config['STATSD_HOST'] = "localhost"
app.config['STATSD_PORT'] = "8000"
app.config['STATSD_PREFIX'] = "prefix"
app.statsd_client = Mock()
mock_logger = mocker.patch.object(app.logger, 'debug')
@statsd(namespace="test")
def test_function():
return True
<|code_end|>
using the current file's imports:
from unittest.mock import ANY, Mock
from notifications_utils.statsd_decorators import statsd
and any relevant context from other files:
# Path: notifications_utils/statsd_decorators.py
# def statsd(namespace):
# def time_function(func):
# @functools.wraps(func)
# def wrapper(*args, **kwargs):
# start_time = time.monotonic()
# try:
# res = func(*args, **kwargs)
# elapsed_time = time.monotonic() - start_time
# current_app.statsd_client.incr('{namespace}.{func}'.format(
# namespace=namespace, func=func.__name__)
# )
# current_app.statsd_client.timing('{namespace}.{func}'.format(
# namespace=namespace, func=func.__name__), elapsed_time
# )
#
# except Exception as e:
# raise e
# else:
# current_app.logger.debug(
# "{namespace} call {func} took {time}".format(
# namespace=namespace, func=func.__name__, time="{0:.4f}".format(elapsed_time)
# )
# )
# return res
# wrapper.__wrapped__.__name__ = func.__name__
# return wrapper
#
# return time_function
. Output only the next line. | assert test_function() |
Given the following code snippet before the placeholder: <|code_start|>
def test_should_return_payload_from_signed_token():
payload = 'email@something.com'
token = generate_token(payload, 'secret-key', 'dangerous-salt')
token = urllib.parse.unquote(token)
assert payload == check_token(token, 'secret-key', 'dangerous-salt', 30)
def test_should_throw_exception_when_token_is_tampered_with():
token = generate_token(str(uuid.uuid4()), 'secret-key', 'dangerous-salt')
try:
check_token(token + 'qerqwer', 'secret-key', 'dangerous-salt', 30)
fail()
except BadSignature:
<|code_end|>
, predict the next line using imports from the current file:
import urllib
import uuid
from itsdangerous import BadSignature, SignatureExpired
from pytest import fail
from notifications_utils.url_safe_token import check_token, generate_token
and context including class names, function names, and sometimes code from other files:
# Path: notifications_utils/url_safe_token.py
# def check_token(token, secret, salt, max_age_seconds):
# ser = URLSafeTimedSerializer(secret)
# payload = ser.loads(token, max_age=max_age_seconds,
# salt=salt)
# return payload
#
# def generate_token(payload, secret, salt):
# return url_encode_full_stops(
# URLSafeTimedSerializer(secret).dumps(payload, salt)
# )
. Output only the next line. | pass |
Continue the code snippet: <|code_start|>
def test_should_return_payload_from_signed_token():
payload = 'email@something.com'
token = generate_token(payload, 'secret-key', 'dangerous-salt')
token = urllib.parse.unquote(token)
assert payload == check_token(token, 'secret-key', 'dangerous-salt', 30)
def test_should_throw_exception_when_token_is_tampered_with():
token = generate_token(str(uuid.uuid4()), 'secret-key', 'dangerous-salt')
try:
check_token(token + 'qerqwer', 'secret-key', 'dangerous-salt', 30)
fail()
except BadSignature:
pass
def test_return_none_when_token_is_expired():
max_age = -1000
payload = 'some_payload'
token = generate_token(payload, 'secret-key', 'dangerous-salt')
token = urllib.parse.unquote(token)
try:
assert check_token(token, 'secret-key', 'dangerous-salt', max_age) is None
<|code_end|>
. Use current file imports:
import urllib
import uuid
from itsdangerous import BadSignature, SignatureExpired
from pytest import fail
from notifications_utils.url_safe_token import check_token, generate_token
and context (classes, functions, or code) from other files:
# Path: notifications_utils/url_safe_token.py
# def check_token(token, secret, salt, max_age_seconds):
# ser = URLSafeTimedSerializer(secret)
# payload = ser.loads(token, max_age=max_age_seconds,
# salt=salt)
# return payload
#
# def generate_token(payload, secret, salt):
# return url_encode_full_stops(
# URLSafeTimedSerializer(secret).dumps(payload, salt)
# )
. Output only the next line. | fail('Expected a SignatureExpired exception') |
Predict the next line for this snippet: <|code_start|>
def _uppercase(value):
return value.upper()
def _append(value, to_append):
return value + to_append
def _prepend_with_service_name(value, service_name=None):
return '{}: {}'.format(service_name, value)
def test_take():
assert 'Service name: HELLO WORLD!' == Take(
'hello world'
).then(
_uppercase
).then(
<|code_end|>
with the help of current file imports:
from notifications_utils.take import Take
and context from other files:
# Path: notifications_utils/take.py
# class Take(str):
#
# def then(self, func, *args, **kwargs):
# return self.__class__(func(self, *args, **kwargs))
, which may contain function names, class names, or code. Output only the next line. | _append, '!' |
Given snippet: <|code_start|>
handlers = logging.get_handlers(app)
assert len(handlers) == 1
assert type(handlers[0]) == builtin_logging.StreamHandler
assert type(handlers[0].formatter) == logging.CustomLogFormatter
assert not (tmpdir / 'foo').exists()
def test_get_handlers_sets_up_logging_appropriately_without_debug(tmpdir):
class App:
config = {
# make a tempfile called foo
'NOTIFY_LOG_PATH': str(tmpdir / 'foo'),
'NOTIFY_APP_NAME': 'bar',
'NOTIFY_LOG_LEVEL': 'ERROR'
}
debug = False
app = App()
handlers = logging.get_handlers(app)
assert len(handlers) == 2
assert type(handlers[0]) == builtin_logging.StreamHandler
assert type(handlers[0].formatter) == logging.JSONFormatter
assert type(handlers[1]) == builtin_logging_handlers.WatchedFileHandler
assert type(handlers[1].formatter) == logging.JSONFormatter
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import json
import logging as builtin_logging
import logging.handlers as builtin_logging_handlers
from notifications_utils import logging
and context:
# Path: notifications_utils/logging.py
# LOG_FORMAT = '%(asctime)s %(app_name)s %(name)s %(levelname)s ' \
# '%(request_id)s "%(message)s" [in %(pathname)s:%(lineno)d]'
# TIME_FORMAT = '%Y-%m-%dT%H:%M:%S'
# FORMAT_STRING_FIELDS_PATTERN = re.compile(r'\((.+?)\)', re.IGNORECASE)
# def init_app(app, statsd_client=None):
# def ensure_log_path_exists(path):
# def get_handlers(app):
# def is_200_static_log(log):
# def configure_handler(handler, app, formatter):
# def __init__(self, app_name):
# def filter(self, record):
# def request_id(self):
# def filter(self, record):
# def service_id(self):
# def filter(self, record):
# def add_fields(self, record):
# def format(self, record):
# def process_log_record(self, log_record):
# class AppNameFilter(logging.Filter):
# class RequestIdFilter(logging.Filter):
# class ServiceIdFilter(logging.Filter):
# class CustomLogFormatter(logging.Formatter):
# class JSONFormatter(BaseJSONFormatter):
which might include code, classes, or functions. Output only the next line. | dir_contents = tmpdir.listdir() |
Given the code snippet: <|code_start|>
@pytest.mark.parametrize('input_value', [
'foo',
100,
True,
False,
None,
])
def test_utc_string_to_aware_gmt_datetime_rejects_bad_input(input_value):
with pytest.raises(Exception):
utc_string_to_aware_gmt_datetime(input_value)
def test_utc_string_to_aware_gmt_datetime_accepts_datetime_objects():
input_value = datetime(2017, 5, 12, 14, 0)
expected = '2017-05-12T15:00:00+01:00'
assert utc_string_to_aware_gmt_datetime(input_value).isoformat() == expected
@pytest.mark.parametrize('naive_time, expected_aware_hour', [
('2000-12-1 20:01', '20:01'),
('2000-06-1 20:01', '21:01'),
<|code_end|>
, generate the next line using the imports in this file:
from datetime import datetime
from notifications_utils.timezones import (
convert_bst_to_utc,
convert_utc_to_bst,
utc_string_to_aware_gmt_datetime,
)
import pytest
and context (functions, classes, or occasionally code) from other files:
# Path: notifications_utils/timezones.py
# def convert_bst_to_utc(date):
# """
# Takes a naive London datetime and returns a naive UTC datetime
# """
# return local_timezone.localize(date).astimezone(pytz.UTC).replace(tzinfo=None)
#
# def convert_utc_to_bst(utc_dt):
# """
# Takes a naive UTC datetime and returns a naive London datetime
# """
# return pytz.utc.localize(utc_dt).astimezone(local_timezone).replace(tzinfo=None)
#
# def utc_string_to_aware_gmt_datetime(date):
# """
# Date can either be a string, naive UTC datetime or an aware UTC datetime
# Returns an aware London datetime, essentially the time you'd see on your clock
# """
# if not isinstance(date, datetime):
# date = parser.parse(date)
#
# forced_utc = date.replace(tzinfo=pytz.utc)
# return forced_utc.astimezone(local_timezone)
. Output only the next line. | ('2000-06-1T20:01+00:00', '21:01'), |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.