Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Here is a snippet: <|code_start|> try: except ImportError: logger = logging.getLogger(__name__) REDIRECT_URI = getattr(settings, 'REST_SOCIAL_OAUTH_REDIRECT_URI', '/') DOMAIN_FROM_ORIGIN = getattr(settings, 'REST_SOCIAL_DOMAIN_FROM_ORIGIN', True) LOG_AUTH_EXCEPTIONS = getattr(settings, 'REST_SOCIAL_LOG_AUTH_EXCEPTIONS', True) STRATEGY = getattr(settings, setting_name('STRATEGY'), 'rest_social_auth.strategy.DRFStrategy') <|code_end|> . Write the next line using the current file imports: import logging import warnings from urllib.parse import urljoin, urlencode, urlparse # python 3x from urllib import urlencode # python 2x from urlparse import urljoin, urlparse from django.conf import settings from django.http import HttpResponse from django.utils.decorators import method_decorator from django.utils.encoding import iri_to_uri from django.views.decorators.cache import never_cache from django.views.decorators.csrf import csrf_protect from social_django.utils import psa, STORAGE from social_django.views import _do_login as social_auth_login from social_core.backends.oauth import BaseOAuth1 from social_core.utils import get_strategy, parse_qs, user_is_authenticated, setting_name from social_core.exceptions import AuthException from rest_framework.generics import GenericAPIView from rest_framework.response import Response from rest_framework import status from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import AllowAny from requests.exceptions import HTTPError from .serializers import ( JWTPairSerializer, JWTSlidingSerializer, KnoxSerializer, OAuth1InputSerializer, OAuth2InputSerializer, TokenSerializer, UserJWTSlidingSerializer, UserKnoxSerializer, UserJWTPairSerializer, UserSerializer, UserTokenSerializer, ) from knox.auth import TokenAuthentication from rest_framework_simplejwt.authentication import JWTAuthentication and context from other files: # Path: rest_social_auth/serializers.py # class JWTPairSerializer(JWTBaseSerializer): # token = serializers.SerializerMethodField() # refresh = serializers.SerializerMethodField() # # jwt_token_class_name = 'RefreshToken' # # def get_token(self, obj): # return str(self.get_token_instance().access_token) # # def get_refresh(self, obj): # return str(self.get_token_instance()) # # class JWTSlidingSerializer(JWTBaseSerializer): # token = serializers.SerializerMethodField() # # jwt_token_class_name = 'SlidingToken' # # def get_token(self, obj): # return str(self.get_token_instance()) # # class KnoxSerializer(TokenSerializer): # def get_token(self, obj): # try: # from knox.models import AuthToken # except ImportError: # warnings.warn( # 'django-rest-knox must be installed for Knox authentication', # ImportWarning, # ) # raise # # token_instance, token_key = AuthToken.objects.create(obj) # return token_key # # class OAuth1InputSerializer(serializers.Serializer): # # provider = serializers.CharField(required=False) # oauth_token = serializers.CharField() # oauth_verifier = serializers.CharField() # # class OAuth2InputSerializer(serializers.Serializer): # # provider = serializers.CharField(required=False) # code = serializers.CharField() # redirect_uri = serializers.CharField(required=False) # # class TokenSerializer(serializers.Serializer): # # token = serializers.SerializerMethodField() # # def get_token(self, obj): # token, created = Token.objects.get_or_create(user=obj) # return token.key # # class UserJWTSlidingSerializer(JWTSlidingSerializer, UserSerializer): # # def get_token_payload(self, user): # payload = dict(UserSerializer(user).data) # payload.pop('id', None) # return payload # # class UserKnoxSerializer(KnoxSerializer, UserSerializer): # pass # # class UserJWTPairSerializer(JWTPairSerializer, UserSerializer): # # def get_token_payload(self, user): # payload = dict(UserSerializer(user).data) # payload.pop('id', None) # return payload # # class UserSerializer(serializers.ModelSerializer): # # class Meta: # model = get_user_model() # # Custom user model may not have some fields from the list below, # # excluding them based on actual fields # exclude = [ # field for field in ( # 'is_staff', 'is_active', 'date_joined', 'password', 'last_login', # 'user_permissions', 'groups', 'is_superuser', # ) if field in [mfield.name for mfield in get_user_model()._meta.get_fields()] # ] # # class UserTokenSerializer(TokenSerializer, UserSerializer): # pass , which may include functions, classes, or code. Output only the next line.
def load_strategy(request=None):
Continue the code snippet: <|code_start|> try: except ImportError: logger = logging.getLogger(__name__) REDIRECT_URI = getattr(settings, 'REST_SOCIAL_OAUTH_REDIRECT_URI', '/') DOMAIN_FROM_ORIGIN = getattr(settings, 'REST_SOCIAL_DOMAIN_FROM_ORIGIN', True) LOG_AUTH_EXCEPTIONS = getattr(settings, 'REST_SOCIAL_LOG_AUTH_EXCEPTIONS', True) STRATEGY = getattr(settings, setting_name('STRATEGY'), 'rest_social_auth.strategy.DRFStrategy') def load_strategy(request=None): <|code_end|> . Use current file imports: import logging import warnings from urllib.parse import urljoin, urlencode, urlparse # python 3x from urllib import urlencode # python 2x from urlparse import urljoin, urlparse from django.conf import settings from django.http import HttpResponse from django.utils.decorators import method_decorator from django.utils.encoding import iri_to_uri from django.views.decorators.cache import never_cache from django.views.decorators.csrf import csrf_protect from social_django.utils import psa, STORAGE from social_django.views import _do_login as social_auth_login from social_core.backends.oauth import BaseOAuth1 from social_core.utils import get_strategy, parse_qs, user_is_authenticated, setting_name from social_core.exceptions import AuthException from rest_framework.generics import GenericAPIView from rest_framework.response import Response from rest_framework import status from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import AllowAny from requests.exceptions import HTTPError from .serializers import ( JWTPairSerializer, JWTSlidingSerializer, KnoxSerializer, OAuth1InputSerializer, OAuth2InputSerializer, TokenSerializer, UserJWTSlidingSerializer, UserKnoxSerializer, UserJWTPairSerializer, UserSerializer, UserTokenSerializer, ) from knox.auth import TokenAuthentication from rest_framework_simplejwt.authentication import JWTAuthentication and context (classes, functions, or code) from other files: # Path: rest_social_auth/serializers.py # class JWTPairSerializer(JWTBaseSerializer): # token = serializers.SerializerMethodField() # refresh = serializers.SerializerMethodField() # # jwt_token_class_name = 'RefreshToken' # # def get_token(self, obj): # return str(self.get_token_instance().access_token) # # def get_refresh(self, obj): # return str(self.get_token_instance()) # # class JWTSlidingSerializer(JWTBaseSerializer): # token = serializers.SerializerMethodField() # # jwt_token_class_name = 'SlidingToken' # # def get_token(self, obj): # return str(self.get_token_instance()) # # class KnoxSerializer(TokenSerializer): # def get_token(self, obj): # try: # from knox.models import AuthToken # except ImportError: # warnings.warn( # 'django-rest-knox must be installed for Knox authentication', # ImportWarning, # ) # raise # # token_instance, token_key = AuthToken.objects.create(obj) # return token_key # # class OAuth1InputSerializer(serializers.Serializer): # # provider = serializers.CharField(required=False) # oauth_token = serializers.CharField() # oauth_verifier = serializers.CharField() # # class OAuth2InputSerializer(serializers.Serializer): # # provider = serializers.CharField(required=False) # code = serializers.CharField() # redirect_uri = serializers.CharField(required=False) # # class TokenSerializer(serializers.Serializer): # # token = serializers.SerializerMethodField() # # def get_token(self, obj): # token, created = Token.objects.get_or_create(user=obj) # return token.key # # class UserJWTSlidingSerializer(JWTSlidingSerializer, UserSerializer): # # def get_token_payload(self, user): # payload = dict(UserSerializer(user).data) # payload.pop('id', None) # return payload # # class UserKnoxSerializer(KnoxSerializer, UserSerializer): # pass # # class UserJWTPairSerializer(JWTPairSerializer, UserSerializer): # # def get_token_payload(self, user): # payload = dict(UserSerializer(user).data) # payload.pop('id', None) # return payload # # class UserSerializer(serializers.ModelSerializer): # # class Meta: # model = get_user_model() # # Custom user model may not have some fields from the list below, # # excluding them based on actual fields # exclude = [ # field for field in ( # 'is_staff', 'is_active', 'date_joined', 'password', 'last_login', # 'user_permissions', 'groups', 'is_superuser', # ) if field in [mfield.name for mfield in get_user_model()._meta.get_fields()] # ] # # class UserTokenSerializer(TokenSerializer, UserSerializer): # pass . Output only the next line.
return get_strategy(STRATEGY, STORAGE, request)
Given the following code snippet before the placeholder: <|code_start|> try: except ImportError: logger = logging.getLogger(__name__) REDIRECT_URI = getattr(settings, 'REST_SOCIAL_OAUTH_REDIRECT_URI', '/') DOMAIN_FROM_ORIGIN = getattr(settings, 'REST_SOCIAL_DOMAIN_FROM_ORIGIN', True) LOG_AUTH_EXCEPTIONS = getattr(settings, 'REST_SOCIAL_LOG_AUTH_EXCEPTIONS', True) <|code_end|> , predict the next line using imports from the current file: import logging import warnings from urllib.parse import urljoin, urlencode, urlparse # python 3x from urllib import urlencode # python 2x from urlparse import urljoin, urlparse from django.conf import settings from django.http import HttpResponse from django.utils.decorators import method_decorator from django.utils.encoding import iri_to_uri from django.views.decorators.cache import never_cache from django.views.decorators.csrf import csrf_protect from social_django.utils import psa, STORAGE from social_django.views import _do_login as social_auth_login from social_core.backends.oauth import BaseOAuth1 from social_core.utils import get_strategy, parse_qs, user_is_authenticated, setting_name from social_core.exceptions import AuthException from rest_framework.generics import GenericAPIView from rest_framework.response import Response from rest_framework import status from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import AllowAny from requests.exceptions import HTTPError from .serializers import ( JWTPairSerializer, JWTSlidingSerializer, KnoxSerializer, OAuth1InputSerializer, OAuth2InputSerializer, TokenSerializer, UserJWTSlidingSerializer, UserKnoxSerializer, UserJWTPairSerializer, UserSerializer, UserTokenSerializer, ) from knox.auth import TokenAuthentication from rest_framework_simplejwt.authentication import JWTAuthentication and context including class names, function names, and sometimes code from other files: # Path: rest_social_auth/serializers.py # class JWTPairSerializer(JWTBaseSerializer): # token = serializers.SerializerMethodField() # refresh = serializers.SerializerMethodField() # # jwt_token_class_name = 'RefreshToken' # # def get_token(self, obj): # return str(self.get_token_instance().access_token) # # def get_refresh(self, obj): # return str(self.get_token_instance()) # # class JWTSlidingSerializer(JWTBaseSerializer): # token = serializers.SerializerMethodField() # # jwt_token_class_name = 'SlidingToken' # # def get_token(self, obj): # return str(self.get_token_instance()) # # class KnoxSerializer(TokenSerializer): # def get_token(self, obj): # try: # from knox.models import AuthToken # except ImportError: # warnings.warn( # 'django-rest-knox must be installed for Knox authentication', # ImportWarning, # ) # raise # # token_instance, token_key = AuthToken.objects.create(obj) # return token_key # # class OAuth1InputSerializer(serializers.Serializer): # # provider = serializers.CharField(required=False) # oauth_token = serializers.CharField() # oauth_verifier = serializers.CharField() # # class OAuth2InputSerializer(serializers.Serializer): # # provider = serializers.CharField(required=False) # code = serializers.CharField() # redirect_uri = serializers.CharField(required=False) # # class TokenSerializer(serializers.Serializer): # # token = serializers.SerializerMethodField() # # def get_token(self, obj): # token, created = Token.objects.get_or_create(user=obj) # return token.key # # class UserJWTSlidingSerializer(JWTSlidingSerializer, UserSerializer): # # def get_token_payload(self, user): # payload = dict(UserSerializer(user).data) # payload.pop('id', None) # return payload # # class UserKnoxSerializer(KnoxSerializer, UserSerializer): # pass # # class UserJWTPairSerializer(JWTPairSerializer, UserSerializer): # # def get_token_payload(self, user): # payload = dict(UserSerializer(user).data) # payload.pop('id', None) # return payload # # class UserSerializer(serializers.ModelSerializer): # # class Meta: # model = get_user_model() # # Custom user model may not have some fields from the list below, # # excluding them based on actual fields # exclude = [ # field for field in ( # 'is_staff', 'is_active', 'date_joined', 'password', 'last_login', # 'user_permissions', 'groups', 'is_superuser', # ) if field in [mfield.name for mfield in get_user_model()._meta.get_fields()] # ] # # class UserTokenSerializer(TokenSerializer, UserSerializer): # pass . Output only the next line.
STRATEGY = getattr(settings, setting_name('STRATEGY'), 'rest_social_auth.strategy.DRFStrategy')
Here is a snippet: <|code_start|> try: except ImportError: logger = logging.getLogger(__name__) REDIRECT_URI = getattr(settings, 'REST_SOCIAL_OAUTH_REDIRECT_URI', '/') DOMAIN_FROM_ORIGIN = getattr(settings, 'REST_SOCIAL_DOMAIN_FROM_ORIGIN', True) LOG_AUTH_EXCEPTIONS = getattr(settings, 'REST_SOCIAL_LOG_AUTH_EXCEPTIONS', True) STRATEGY = getattr(settings, setting_name('STRATEGY'), 'rest_social_auth.strategy.DRFStrategy') def load_strategy(request=None): return get_strategy(STRATEGY, STORAGE, request) @psa(REDIRECT_URI, load_strategy=load_strategy) <|code_end|> . Write the next line using the current file imports: import logging import warnings from urllib.parse import urljoin, urlencode, urlparse # python 3x from urllib import urlencode # python 2x from urlparse import urljoin, urlparse from django.conf import settings from django.http import HttpResponse from django.utils.decorators import method_decorator from django.utils.encoding import iri_to_uri from django.views.decorators.cache import never_cache from django.views.decorators.csrf import csrf_protect from social_django.utils import psa, STORAGE from social_django.views import _do_login as social_auth_login from social_core.backends.oauth import BaseOAuth1 from social_core.utils import get_strategy, parse_qs, user_is_authenticated, setting_name from social_core.exceptions import AuthException from rest_framework.generics import GenericAPIView from rest_framework.response import Response from rest_framework import status from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import AllowAny from requests.exceptions import HTTPError from .serializers import ( JWTPairSerializer, JWTSlidingSerializer, KnoxSerializer, OAuth1InputSerializer, OAuth2InputSerializer, TokenSerializer, UserJWTSlidingSerializer, UserKnoxSerializer, UserJWTPairSerializer, UserSerializer, UserTokenSerializer, ) from knox.auth import TokenAuthentication from rest_framework_simplejwt.authentication import JWTAuthentication and context from other files: # Path: rest_social_auth/serializers.py # class JWTPairSerializer(JWTBaseSerializer): # token = serializers.SerializerMethodField() # refresh = serializers.SerializerMethodField() # # jwt_token_class_name = 'RefreshToken' # # def get_token(self, obj): # return str(self.get_token_instance().access_token) # # def get_refresh(self, obj): # return str(self.get_token_instance()) # # class JWTSlidingSerializer(JWTBaseSerializer): # token = serializers.SerializerMethodField() # # jwt_token_class_name = 'SlidingToken' # # def get_token(self, obj): # return str(self.get_token_instance()) # # class KnoxSerializer(TokenSerializer): # def get_token(self, obj): # try: # from knox.models import AuthToken # except ImportError: # warnings.warn( # 'django-rest-knox must be installed for Knox authentication', # ImportWarning, # ) # raise # # token_instance, token_key = AuthToken.objects.create(obj) # return token_key # # class OAuth1InputSerializer(serializers.Serializer): # # provider = serializers.CharField(required=False) # oauth_token = serializers.CharField() # oauth_verifier = serializers.CharField() # # class OAuth2InputSerializer(serializers.Serializer): # # provider = serializers.CharField(required=False) # code = serializers.CharField() # redirect_uri = serializers.CharField(required=False) # # class TokenSerializer(serializers.Serializer): # # token = serializers.SerializerMethodField() # # def get_token(self, obj): # token, created = Token.objects.get_or_create(user=obj) # return token.key # # class UserJWTSlidingSerializer(JWTSlidingSerializer, UserSerializer): # # def get_token_payload(self, user): # payload = dict(UserSerializer(user).data) # payload.pop('id', None) # return payload # # class UserKnoxSerializer(KnoxSerializer, UserSerializer): # pass # # class UserJWTPairSerializer(JWTPairSerializer, UserSerializer): # # def get_token_payload(self, user): # payload = dict(UserSerializer(user).data) # payload.pop('id', None) # return payload # # class UserSerializer(serializers.ModelSerializer): # # class Meta: # model = get_user_model() # # Custom user model may not have some fields from the list below, # # excluding them based on actual fields # exclude = [ # field for field in ( # 'is_staff', 'is_active', 'date_joined', 'password', 'last_login', # 'user_permissions', 'groups', 'is_superuser', # ) if field in [mfield.name for mfield in get_user_model()._meta.get_fields()] # ] # # class UserTokenSerializer(TokenSerializer, UserSerializer): # pass , which may include functions, classes, or code. Output only the next line.
def decorate_request(request, backend):
Predict the next line for this snippet: <|code_start|>class TestSocialAuth2Knox(APITestCase, BaseFacebookAPITestCase): def _check_login_social_knox_only(self, url, data): resp = self.client.post(url, data) self.assertEqual(resp.status_code, 200) # check token valid knox_auth = KnoxTokenAuthentication() user, auth_data = knox_auth.authenticate_credentials(resp.data['token'].encode('utf8')) self.assertEqual(user.email, self.email) def _check_login_social_knox_user(self, url, data): resp = self.client.post(url, data) self.assertEqual(resp.status_code, 200) self.assertEqual(resp.data['email'], self.email) # check token valid knox_auth = KnoxTokenAuthentication() user, auth_data = knox_auth.authenticate_credentials(resp.data['token'].encode('utf8')) self.assertEqual(user.email, self.email) def test_login_social_knox_only(self): self._check_login_social_knox_only( reverse('login_social_knox'), data={'provider': 'facebook', 'code': '3D52VoM1uiw94a1ETnGvYlCw'}) def test_login_social_knox_only_provider_in_url(self): self._check_login_social_knox_only( reverse('login_social_knox', kwargs={'provider': 'facebook'}), data={'code': '3D52VoM1uiw94a1ETnGvYlCw'}) def test_login_social_knox_user(self): <|code_end|> with the help of current file imports: from django.test import override_settings from django.urls import reverse from knox.auth import TokenAuthentication as KnoxTokenAuthentication from rest_framework.test import APITestCase from social_core.utils import parse_qs from .base import BaseFacebookAPITestCase, BaseTwitterApiTestCase and context from other files: # Path: tests/base.py # class BaseFacebookAPITestCase(RestSocialMixin, FacebookOAuth2Test): # # def do_rest_login(self): # start_url = self.backend.start().url # self.auth_handlers(start_url) # # class BaseTwitterApiTestCase(RestSocialMixin, TwitterOAuth1Test): # # def do_rest_login(self): # self.request_token_handler() # start_url = self.backend.start().url # self.auth_handlers(start_url) , which may contain function names, class names, or code. Output only the next line.
self._check_login_social_knox_user(
Using the snippet: <|code_start|> knox_override_settings = dict( INSTALLED_APPS=[ 'django.contrib.contenttypes', 'rest_framework', 'social_django', 'rest_social_auth', 'knox', # For django-rest-knox 'users', <|code_end|> , determine the next line of code. You have imports: from django.test import override_settings from django.urls import reverse from knox.auth import TokenAuthentication as KnoxTokenAuthentication from rest_framework.test import APITestCase from social_core.utils import parse_qs from .base import BaseFacebookAPITestCase, BaseTwitterApiTestCase and context (class names, function names, or code) available: # Path: tests/base.py # class BaseFacebookAPITestCase(RestSocialMixin, FacebookOAuth2Test): # # def do_rest_login(self): # start_url = self.backend.start().url # self.auth_handlers(start_url) # # class BaseTwitterApiTestCase(RestSocialMixin, TwitterOAuth1Test): # # def do_rest_login(self): # self.request_token_handler() # start_url = self.backend.start().url # self.auth_handlers(start_url) . Output only the next line.
],
Given snippet: <|code_start|> 'django.contrib.contenttypes', 'rest_framework', 'rest_framework.authtoken', 'social_django', 'rest_social_auth', 'users', ], MIDDLEWARE=[], ) @override_settings(**token_override_settings) class TestSocialAuth1Token(APITestCase, BaseTwitterApiTestCase): def test_login_social_oauth1_token(self): url = reverse('login_social_token_user') resp = self.client.post(url, data={'provider': 'twitter'}) self.assertEqual(resp.status_code, 200) self.assertEqual(resp.data, parse_qs(self.request_token_body)) resp = self.client.post(reverse('login_social_token_user'), data={ 'provider': 'twitter', 'oauth_token': 'foobar', 'oauth_verifier': 'overifier' }) self.assertEqual(resp.status_code, 200) @override_settings(**token_override_settings) class TestSocialAuth2Token(APITestCase, BaseFacebookAPITestCase): <|code_end|> , continue by predicting the next line. Consider current file imports: import json from django.test import override_settings from django.urls import reverse from rest_framework.authtoken.models import Token from rest_framework.test import APITestCase from social_core.utils import parse_qs from .base import BaseFacebookAPITestCase, BaseTwitterApiTestCase and context: # Path: tests/base.py # class BaseFacebookAPITestCase(RestSocialMixin, FacebookOAuth2Test): # # def do_rest_login(self): # start_url = self.backend.start().url # self.auth_handlers(start_url) # # class BaseTwitterApiTestCase(RestSocialMixin, TwitterOAuth1Test): # # def do_rest_login(self): # self.request_token_handler() # start_url = self.backend.start().url # self.auth_handlers(start_url) which might include code, classes, or functions. Output only the next line.
def _check_login_social_token_user(self, url, data):
Continue the code snippet: <|code_start|> def _check_login_social_token_only(self, url, data): resp = self.client.post(url, data) self.assertEqual(resp.status_code, 200) # check token exists token = Token.objects.get(key=resp.data['token']) # check user is created self.assertEqual(token.user.email, self.email) def test_login_social_token_user(self): self._check_login_social_token_user( reverse('login_social_token_user'), {'provider': 'facebook', 'code': '3D52VoM1uiw94a1ETnGvYlCw'}) def test_login_social_token_user_provider_in_url(self): self._check_login_social_token_user( reverse('login_social_token_user', kwargs={'provider': 'facebook'}), {'code': '3D52VoM1uiw94a1ETnGvYlCw'}) def test_login_social_token_only(self): self._check_login_social_token_only( reverse('login_social_token'), data={'provider': 'facebook', 'code': '3D52VoM1uiw94a1ETnGvYlCw'}) def test_login_social_token_only_provider_in_url(self): self._check_login_social_token_only( reverse('login_social_token', kwargs={'provider': 'facebook'}), data={'code': '3D52VoM1uiw94a1ETnGvYlCw'}) def test_user_login_with_no_email(self): <|code_end|> . Use current file imports: import json from django.test import override_settings from django.urls import reverse from rest_framework.authtoken.models import Token from rest_framework.test import APITestCase from social_core.utils import parse_qs from .base import BaseFacebookAPITestCase, BaseTwitterApiTestCase and context (classes, functions, or code) from other files: # Path: tests/base.py # class BaseFacebookAPITestCase(RestSocialMixin, FacebookOAuth2Test): # # def do_rest_login(self): # start_url = self.backend.start().url # self.auth_handlers(start_url) # # class BaseTwitterApiTestCase(RestSocialMixin, TwitterOAuth1Test): # # def do_rest_login(self): # self.request_token_handler() # start_url = self.backend.start().url # self.auth_handlers(start_url) . Output only the next line.
user_data_body = json.loads(self.user_data_body)
Given snippet: <|code_start|> url_params = dict(parse_qsl(urlparse(HTTPretty.latest_requests[0].path).query)) self.assertEqual('http://manualdomain.com/', url_params['redirect_uri']) @mock.patch('rest_framework.views.APIView.permission_classes') def test_login_social_session_model_permission(self, m_permission_classes): setattr( m_permission_classes, '__get__', lambda *args, **kwargs: (DjangoModelPermissionsOrAnonReadOnly,), ) self._check_login_social_session( reverse('login_social_session'), {'provider': 'facebook', 'code': '3D52VoM1uiw94a1ETnGvYlCw'}) class TestSocialAuth2Error(APITestCase, BaseFacebookAPITestCase): access_token_status = 400 def test_login_oauth_provider_error(self): resp = self.client.post( reverse('login_social_session'), data={'provider': 'facebook', 'code': '3D52VoM1uiw94a1ETnGvYlCw'}) self.assertEqual(resp.status_code, 400) class TestSocialAuth2HTTPError(APITestCase, BaseFacebookAPITestCase): access_token_status = 401 def test_login_oauth_provider_http_error(self): resp = self.client.post( <|code_end|> , continue by predicting the next line. Consider current file imports: from unittest import mock from urllib.parse import parse_qsl, urlparse from django.urls import reverse from django.contrib.auth import get_user_model from django.test import modify_settings from django.test.utils import override_settings from rest_framework.test import APITestCase from rest_framework.permissions import DjangoModelPermissionsOrAnonReadOnly from httpretty import HTTPretty from social_core.utils import parse_qs from .base import BaseFacebookAPITestCase, BaseTwitterApiTestCase and context: # Path: tests/base.py # class BaseFacebookAPITestCase(RestSocialMixin, FacebookOAuth2Test): # # def do_rest_login(self): # start_url = self.backend.start().url # self.auth_handlers(start_url) # # class BaseTwitterApiTestCase(RestSocialMixin, TwitterOAuth1Test): # # def do_rest_login(self): # self.request_token_handler() # start_url = self.backend.start().url # self.auth_handlers(start_url) which might include code, classes, or functions. Output only the next line.
reverse('login_social_session'),
Next line prediction: <|code_start|> session_modify_settings = dict( INSTALLED_APPS={ 'remove': [ 'rest_framework.authtoken', 'knox', ] }, <|code_end|> . Use current file imports: (from unittest import mock from urllib.parse import parse_qsl, urlparse from django.urls import reverse from django.contrib.auth import get_user_model from django.test import modify_settings from django.test.utils import override_settings from rest_framework.test import APITestCase from rest_framework.permissions import DjangoModelPermissionsOrAnonReadOnly from httpretty import HTTPretty from social_core.utils import parse_qs from .base import BaseFacebookAPITestCase, BaseTwitterApiTestCase) and context including class names, function names, or small code snippets from other files: # Path: tests/base.py # class BaseFacebookAPITestCase(RestSocialMixin, FacebookOAuth2Test): # # def do_rest_login(self): # start_url = self.backend.start().url # self.auth_handlers(start_url) # # class BaseTwitterApiTestCase(RestSocialMixin, TwitterOAuth1Test): # # def do_rest_login(self): # self.request_token_handler() # start_url = self.backend.start().url # self.auth_handlers(start_url) . Output only the next line.
)
Here is a snippet: <|code_start|> # don't run third party tests for attr in (attr for attr in dir(FacebookOAuth2Test) if attr.startswith('test_')): delattr(FacebookOAuth2Test, attr) for attr in (attr for attr in dir(TwitterOAuth1Test) if attr.startswith('test_')): delattr(TwitterOAuth1Test, attr) class RestSocialMixin(object): <|code_end|> . Write the next line using the current file imports: import json from httpretty import HTTPretty from social_core.backends.utils import load_backends from social_core.tests.backends.test_facebook import FacebookOAuth2Test from social_core.tests.backends.test_twitter import TwitterOAuth1Test from social_core.utils import module_member from rest_social_auth import views and context from other files: # Path: rest_social_auth/views.py # REDIRECT_URI = getattr(settings, 'REST_SOCIAL_OAUTH_REDIRECT_URI', '/') # DOMAIN_FROM_ORIGIN = getattr(settings, 'REST_SOCIAL_DOMAIN_FROM_ORIGIN', True) # LOG_AUTH_EXCEPTIONS = getattr(settings, 'REST_SOCIAL_LOG_AUTH_EXCEPTIONS', True) # STRATEGY = getattr(settings, setting_name('STRATEGY'), 'rest_social_auth.strategy.DRFStrategy') # def load_strategy(request=None): # def decorate_request(request, backend): # def oauth_v1(self): # def get_serializer_class_in(self): # def get_serializer_in(self, *args, **kwargs): # def get_serializer_in_data(self): # def post(self, request, *args, **kwargs): # def get_object(self): # def save_token_param_in_session(self): # def do_login(self, backend, user): # def set_input_data(self, request, auth_data): # def get_redirect_uri(self, manual_redirect_uri): # def get_provider_name(self, input_data): # def respond_error(self, error): # def log_exception(self, error): # def do_login(self, backend, user): # def post(self, request, *args, **kwargs): # def get_authenticators(self): # def get_authenticators(self): # class BaseSocialAuthView(GenericAPIView): # class SocialSessionAuthView(BaseSocialAuthView): # class SocialTokenOnlyAuthView(BaseSocialAuthView): # class SocialTokenUserAuthView(BaseSocialAuthView): # class KnoxAuthMixin(object): # class SocialKnoxOnlyAuthView(KnoxAuthMixin, BaseSocialAuthView): # class SocialKnoxUserAuthView(KnoxAuthMixin, BaseSocialAuthView): # class SimpleJWTAuthMixin(object): # class SocialJWTPairOnlyAuthView(SimpleJWTAuthMixin, BaseSocialAuthView): # class SocialJWTPairUserAuthView(SimpleJWTAuthMixin, BaseSocialAuthView): # class SocialJWTSlidingOnlyAuthView(SimpleJWTAuthMixin, BaseSocialAuthView): # class SocialJWTSlidingUserAuthView(SimpleJWTAuthMixin, BaseSocialAuthView): , which may include functions, classes, or code. Output only the next line.
def setUp(self):
Here is a snippet: <|code_start|> "Bitcoin", "14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e", bytes.fromhex( "209e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80" ), "This is an example of a signed message!", ) assert res is False def test_message_verify_bcash(self): self.setup_mnemonic_nopin_nopassphrase() res = btc.verify_message( self.client, "Bcash", "bitcoincash:qqj22md58nm09vpwsw82fyletkxkq36zxyxh322pru", bytes.fromhex( "209e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80" ), "This is an example of a signed message.", ) assert res is True def test_verify_bitcoind(self): self.setup_mnemonic_nopin_nopassphrase() res = btc.verify_message( self.client, "Bitcoin", "1KzXE97kV7DrpxCViCN3HbGbiKhzzPM7TQ", bytes.fromhex( <|code_end|> . Write the next line using the current file imports: import base64 from trezorlib import btc from .common import TrezorTest and context from other files: # Path: trezorlib/btc.py # def get_public_node( # client, # n, # ecdsa_curve_name=None, # show_display=False, # coin_name=None, # script_type=messages.InputScriptType.SPENDADDRESS, # ): # def get_address( # client, # coin_name, # n, # show_display=False, # multisig=None, # script_type=messages.InputScriptType.SPENDADDRESS, # ): # def sign_message( # client, coin_name, n, message, script_type=messages.InputScriptType.SPENDADDRESS # ): # def verify_message(client, coin_name, address, signature, message): # def sign_tx(client, coin_name, inputs, outputs, details=None, prev_txes=None): # def copy_tx_meta(tx): # R = messages.RequestType , which may include functions, classes, or code. Output only the next line.
"1cc694f0f23901dfe3603789142f36a3fc582d0d5c0ec7215cf2ccd641e4e37228504f3d4dc3eea28bbdbf5da27c49d4635c097004d9f228750ccd836a8e1460c0"
Next line prediction: <|code_start|> ) self.client.set_passphrase(passphrase_nfc) address_nfc = btc.get_address(self.client, "Bitcoin", []) device.wipe(self.client) debuglink.load_device_by_mnemonic( self.client, mnemonic=words_nfkc, pin="", passphrase_protection=True, label="test", language="english", skip_checksum=True, ) self.client.set_passphrase(passphrase_nfkc) address_nfkc = btc.get_address(self.client, "Bitcoin", []) device.wipe(self.client) debuglink.load_device_by_mnemonic( self.client, mnemonic=words_nfd, pin="", passphrase_protection=True, label="test", language="english", skip_checksum=True, ) self.client.set_passphrase(passphrase_nfd) address_nfd = btc.get_address(self.client, "Bitcoin", []) <|code_end|> . Use current file imports: (import pytest from trezorlib import btc, debuglink, device from .common import TrezorTest) and context including class names, function names, or small code snippets from other files: # Path: trezorlib/btc.py # def get_public_node( # client, # n, # ecdsa_curve_name=None, # show_display=False, # coin_name=None, # script_type=messages.InputScriptType.SPENDADDRESS, # ): # def get_address( # client, # coin_name, # n, # show_display=False, # multisig=None, # script_type=messages.InputScriptType.SPENDADDRESS, # ): # def sign_message( # client, coin_name, n, message, script_type=messages.InputScriptType.SPENDADDRESS # ): # def verify_message(client, coin_name, address, signature, message): # def sign_tx(client, coin_name, inputs, outputs, details=None, prev_txes=None): # def copy_tx_meta(tx): # R = messages.RequestType # # Path: trezorlib/debuglink.py # EXPECTED_RESPONSES_CONTEXT_LINES = 3 # INPUT_FLOW_DONE = object() # class DebugLink: # class NullDebugLink(DebugLink): # class DebugUI: # class TrezorClientDebugLink(TrezorClient): # def __init__(self, transport, auto_interact=True): # def open(self): # def close(self): # def _call(self, msg, nowait=False): # def state(self): # def read_pin(self): # def read_pin_encoded(self): # def encode_pin(self, pin, matrix=None): # def read_layout(self): # def read_mnemonic_secret(self): # def read_recovery_word(self): # def read_reset_word(self): # def read_reset_word_pos(self): # def read_reset_entropy(self): # def read_passphrase_protection(self): # def input(self, word=None, button=None, swipe=None): # def press_button(self, yes_no): # def press_yes(self): # def press_no(self): # def swipe_up(self): # def swipe_down(self): # def stop(self): # def memory_read(self, address, length): # def memory_write(self, address, memory, flash=False): # def flash_erase(self, sector): # def __init__(self): # def open(self): # def close(self): # def _call(self, msg, nowait=False): # def __init__(self, debuglink: DebugLink): # def button_request(self, code): # def get_pin(self, code=None): # def get_passphrase(self): # def __init__(self, transport, auto_interact=True): # def open(self): # def close(self): # def set_filter(self, message_type, callback): # def _filter_message(self, msg): # def set_input_flow(self, input_flow): # def __enter__(self): # def __exit__(self, _type, value, traceback): # def set_expected_responses(self, expected): # def setup_debuglink(self, button, pin_correct): # def set_passphrase(self, passphrase): # def set_mnemonic(self, mnemonic): # def _raw_read(self): # def _raw_write(self, msg): # def _raise_unexpected_response(self, msg): # def _check_request(self, msg): # def mnemonic_callback(self, _): # def load_device_by_mnemonic( # client, # mnemonic, # pin, # passphrase_protection, # label, # language="english", # skip_checksum=False, # expand=False, # ): # def load_device_by_xprv(client, xprv, pin, passphrase_protection, label, language): # def self_test(client): # # Path: trezorlib/device.py # RECOVERY_BACK = "\x08" # backspace character, sent literally # class TrezorDevice: # def enumerate(cls): # def find_by_path(cls, path): # def apply_settings( # client, # label=None, # language=None, # use_passphrase=None, # homescreen=None, # passphrase_source=None, # auto_lock_delay_ms=None, # display_rotation=None, # ): # def apply_flags(client, flags): # def change_pin(client, remove=False): # def set_u2f_counter(client, u2f_counter): # def wipe(client): # def recover( # client, # word_count=24, # passphrase_protection=False, # pin_protection=True, # label=None, # language="english", # input_callback=None, # type=proto.RecoveryDeviceType.ScrambledWords, # dry_run=False, # u2f_counter=None, # ): # def reset( # client, # display_random=False, # strength=None, # passphrase_protection=False, # pin_protection=True, # label=None, # language="english", # u2f_counter=0, # skip_backup=False, # no_backup=False, # ): # def backup(client): . Output only the next line.
assert address_nfkd == address_nfc
Next line prediction: <|code_start|> passphrase_protection=True, label="test", language="english", skip_checksum=True, ) self.client.set_passphrase(passphrase_nfc) address_nfc = btc.get_address(self.client, "Bitcoin", []) device.wipe(self.client) debuglink.load_device_by_mnemonic( self.client, mnemonic=words_nfkc, pin="", passphrase_protection=True, label="test", language="english", skip_checksum=True, ) self.client.set_passphrase(passphrase_nfkc) address_nfkc = btc.get_address(self.client, "Bitcoin", []) device.wipe(self.client) debuglink.load_device_by_mnemonic( self.client, mnemonic=words_nfd, pin="", passphrase_protection=True, label="test", language="english", skip_checksum=True, <|code_end|> . Use current file imports: (import pytest from trezorlib import btc, debuglink, device from .common import TrezorTest) and context including class names, function names, or small code snippets from other files: # Path: trezorlib/btc.py # def get_public_node( # client, # n, # ecdsa_curve_name=None, # show_display=False, # coin_name=None, # script_type=messages.InputScriptType.SPENDADDRESS, # ): # def get_address( # client, # coin_name, # n, # show_display=False, # multisig=None, # script_type=messages.InputScriptType.SPENDADDRESS, # ): # def sign_message( # client, coin_name, n, message, script_type=messages.InputScriptType.SPENDADDRESS # ): # def verify_message(client, coin_name, address, signature, message): # def sign_tx(client, coin_name, inputs, outputs, details=None, prev_txes=None): # def copy_tx_meta(tx): # R = messages.RequestType # # Path: trezorlib/debuglink.py # EXPECTED_RESPONSES_CONTEXT_LINES = 3 # INPUT_FLOW_DONE = object() # class DebugLink: # class NullDebugLink(DebugLink): # class DebugUI: # class TrezorClientDebugLink(TrezorClient): # def __init__(self, transport, auto_interact=True): # def open(self): # def close(self): # def _call(self, msg, nowait=False): # def state(self): # def read_pin(self): # def read_pin_encoded(self): # def encode_pin(self, pin, matrix=None): # def read_layout(self): # def read_mnemonic_secret(self): # def read_recovery_word(self): # def read_reset_word(self): # def read_reset_word_pos(self): # def read_reset_entropy(self): # def read_passphrase_protection(self): # def input(self, word=None, button=None, swipe=None): # def press_button(self, yes_no): # def press_yes(self): # def press_no(self): # def swipe_up(self): # def swipe_down(self): # def stop(self): # def memory_read(self, address, length): # def memory_write(self, address, memory, flash=False): # def flash_erase(self, sector): # def __init__(self): # def open(self): # def close(self): # def _call(self, msg, nowait=False): # def __init__(self, debuglink: DebugLink): # def button_request(self, code): # def get_pin(self, code=None): # def get_passphrase(self): # def __init__(self, transport, auto_interact=True): # def open(self): # def close(self): # def set_filter(self, message_type, callback): # def _filter_message(self, msg): # def set_input_flow(self, input_flow): # def __enter__(self): # def __exit__(self, _type, value, traceback): # def set_expected_responses(self, expected): # def setup_debuglink(self, button, pin_correct): # def set_passphrase(self, passphrase): # def set_mnemonic(self, mnemonic): # def _raw_read(self): # def _raw_write(self, msg): # def _raise_unexpected_response(self, msg): # def _check_request(self, msg): # def mnemonic_callback(self, _): # def load_device_by_mnemonic( # client, # mnemonic, # pin, # passphrase_protection, # label, # language="english", # skip_checksum=False, # expand=False, # ): # def load_device_by_xprv(client, xprv, pin, passphrase_protection, label, language): # def self_test(client): # # Path: trezorlib/device.py # RECOVERY_BACK = "\x08" # backspace character, sent literally # class TrezorDevice: # def enumerate(cls): # def find_by_path(cls, path): # def apply_settings( # client, # label=None, # language=None, # use_passphrase=None, # homescreen=None, # passphrase_source=None, # auto_lock_delay_ms=None, # display_rotation=None, # ): # def apply_flags(client, flags): # def change_pin(client, remove=False): # def set_u2f_counter(client, u2f_counter): # def wipe(client): # def recover( # client, # word_count=24, # passphrase_protection=False, # pin_protection=True, # label=None, # language="english", # input_callback=None, # type=proto.RecoveryDeviceType.ScrambledWords, # dry_run=False, # u2f_counter=None, # ): # def reset( # client, # display_random=False, # strength=None, # passphrase_protection=False, # pin_protection=True, # label=None, # language="english", # u2f_counter=0, # skip_backup=False, # no_backup=False, # ): # def backup(client): . Output only the next line.
)
Given snippet: <|code_start|>#!/usr/bin/env python3 def main(): # Use first connected device client = get_default_client() # Print out TREZOR's features and settings print(client.features) # Get the first address of first BIP44 account # (should be the same address as shown in wallet.trezor.io) bip32_path = parse_path("44'/0'/0'/0/0") address = btc.get_address(client, "Bitcoin", bip32_path, True) <|code_end|> , continue by predicting the next line. Consider current file imports: from trezorlib.client import get_default_client from trezorlib.tools import parse_path from trezorlib import btc and context: # Path: trezorlib/client.py # def get_default_client(path=None, ui=None, **kwargs): # """Get a client for a connected Trezor device. # # Returns a TrezorClient instance with minimum fuss. # # If no path is specified, finds first connected Trezor. Otherwise performs # a prefix-search for the specified device. If no UI is supplied, instantiates # the default CLI UI. # """ # from .transport import get_transport # from .ui import ClickUI # # transport = get_transport(path, prefix_search=True) # if ui is None: # ui = ClickUI() # # return TrezorClient(transport, ui, **kwargs) # # Path: trezorlib/btc.py # def get_public_node( # client, # n, # ecdsa_curve_name=None, # show_display=False, # coin_name=None, # script_type=messages.InputScriptType.SPENDADDRESS, # ): # def get_address( # client, # coin_name, # n, # show_display=False, # multisig=None, # script_type=messages.InputScriptType.SPENDADDRESS, # ): # def sign_message( # client, coin_name, n, message, script_type=messages.InputScriptType.SPENDADDRESS # ): # def verify_message(client, coin_name, address, signature, message): # def sign_tx(client, coin_name, inputs, outputs, details=None, prev_txes=None): # def copy_tx_meta(tx): # R = messages.RequestType which might include code, classes, or functions. Output only the next line.
print("Bitcoin address:", address)
Using the snippet: <|code_start|>#!/usr/bin/env python3 def main(): # Use first connected device client = get_default_client() # Print out TREZOR's features and settings print(client.features) # Get the first address of first BIP44 account # (should be the same address as shown in wallet.trezor.io) bip32_path = parse_path("44'/0'/0'/0/0") address = btc.get_address(client, "Bitcoin", bip32_path, True) <|code_end|> , determine the next line of code. You have imports: from trezorlib.client import get_default_client from trezorlib.tools import parse_path from trezorlib import btc and context (class names, function names, or code) available: # Path: trezorlib/client.py # def get_default_client(path=None, ui=None, **kwargs): # """Get a client for a connected Trezor device. # # Returns a TrezorClient instance with minimum fuss. # # If no path is specified, finds first connected Trezor. Otherwise performs # a prefix-search for the specified device. If no UI is supplied, instantiates # the default CLI UI. # """ # from .transport import get_transport # from .ui import ClickUI # # transport = get_transport(path, prefix_search=True) # if ui is None: # ui = ClickUI() # # return TrezorClient(transport, ui, **kwargs) # # Path: trezorlib/btc.py # def get_public_node( # client, # n, # ecdsa_curve_name=None, # show_display=False, # coin_name=None, # script_type=messages.InputScriptType.SPENDADDRESS, # ): # def get_address( # client, # coin_name, # n, # show_display=False, # multisig=None, # script_type=messages.InputScriptType.SPENDADDRESS, # ): # def sign_message( # client, coin_name, n, message, script_type=messages.InputScriptType.SPENDADDRESS # ): # def verify_message(client, coin_name, address, signature, message): # def sign_tx(client, coin_name, inputs, outputs, details=None, prev_txes=None): # def copy_tx_meta(tx): # R = messages.RequestType . Output only the next line.
print("Bitcoin address:", address)
Given the code snippet: <|code_start|>#!/usr/bin/env python3 def find_debug(): for device in enumerate_devices(): try: debug_transport = device.find_debug() debug = DebugLink(debug_transport, auto_interact=False) debug.open() return debug except Exception: continue else: print("No suitable Trezor device found") sys.exit(1) def main(): debug = find_debug() debug.memory_write(int(sys.argv[1], 16), bytes.fromhex(sys.argv[2]), flash=True) <|code_end|> , generate the next line using the imports in this file: from trezorlib.debuglink import DebugLink from trezorlib.transport import enumerate_devices import sys and context (functions, classes, or occasionally code) from other files: # Path: trezorlib/debuglink.py # class DebugLink: # def __init__(self, transport, auto_interact=True): # self.transport = transport # self.allow_interactions = auto_interact # # def open(self): # self.transport.begin_session() # # def close(self): # self.transport.end_session() # # def _call(self, msg, nowait=False): # self.transport.write(msg) # if nowait: # return None # ret = self.transport.read() # return ret # # def state(self): # return self._call(proto.DebugLinkGetState()) # # def read_pin(self): # state = self.state() # return state.pin, state.matrix # # def read_pin_encoded(self): # return self.encode_pin(*self.read_pin()) # # def encode_pin(self, pin, matrix=None): # """Transform correct PIN according to the displayed matrix.""" # if matrix is None: # _, matrix = self.read_pin() # return "".join([str(matrix.index(p) + 1) for p in pin]) # # def read_layout(self): # obj = self._call(proto.DebugLinkGetState()) # return obj.layout # # def read_mnemonic_secret(self): # obj = self._call(proto.DebugLinkGetState()) # return obj.mnemonic_secret # # def read_recovery_word(self): # obj = self._call(proto.DebugLinkGetState()) # return (obj.recovery_fake_word, obj.recovery_word_pos) # # def read_reset_word(self): # obj = self._call(proto.DebugLinkGetState()) # return obj.reset_word # # def read_reset_word_pos(self): # obj = self._call(proto.DebugLinkGetState()) # return obj.reset_word_pos # # def read_reset_entropy(self): # obj = self._call(proto.DebugLinkGetState()) # return obj.reset_entropy # # def read_passphrase_protection(self): # obj = self._call(proto.DebugLinkGetState()) # return obj.passphrase_protection # # def input(self, word=None, button=None, swipe=None): # if not self.allow_interactions: # return # decision = proto.DebugLinkDecision() # if button is not None: # decision.yes_no = button # elif word is not None: # decision.input = word # elif swipe is not None: # decision.up_down = swipe # else: # raise ValueError("You need to provide input data.") # self._call(decision, nowait=True) # # def press_button(self, yes_no): # self._call(proto.DebugLinkDecision(yes_no=yes_no), nowait=True) # # def press_yes(self): # self.input(button=True) # # def press_no(self): # self.input(button=False) # # def swipe_up(self): # self.input(swipe=True) # # def swipe_down(self): # self.input(swipe=False) # # def stop(self): # self._call(proto.DebugLinkStop(), nowait=True) # # @expect(proto.DebugLinkMemory, field="memory") # def memory_read(self, address, length): # return self._call(proto.DebugLinkMemoryRead(address=address, length=length)) # # def memory_write(self, address, memory, flash=False): # self._call( # proto.DebugLinkMemoryWrite(address=address, memory=memory, flash=flash), # nowait=True, # ) # # def flash_erase(self, sector): # self._call(proto.DebugLinkFlashErase(sector=sector), nowait=True) . Output only the next line.
if __name__ == "__main__":
Using the snippet: <|code_start|> usb1 = None INTERFACE = 0 ENDPOINT = 1 DEBUG_INTERFACE = 1 DEBUG_ENDPOINT = 2 class WebUsbHandle: def __init__(self, device: "usb1.USBDevice", debug: bool = False) -> None: self.device = device self.interface = DEBUG_INTERFACE if debug else INTERFACE self.endpoint = DEBUG_ENDPOINT if debug else ENDPOINT self.count = 0 self.handle = None # type: Optional[usb1.USBDeviceHandle] def open(self) -> None: self.handle = self.device.open() if self.handle is None: if sys.platform.startswith("linux"): args = (UDEV_RULES_STR,) else: args = () raise IOError("Cannot open device", *args) self.handle.claimInterface(self.interface) def close(self) -> None: if self.handle is not None: self.handle.releaseInterface(self.interface) self.handle.close() <|code_end|> , determine the next line of code. You have imports: import atexit import logging import sys import time import usb1 from typing import Iterable, Optional from . import TREZORS, UDEV_RULES_STR, TransportException from .protocol import ProtocolBasedTransport, ProtocolV1 and context (class names, function names, or code) available: # Path: trezorlib/transport/protocol.py # class ProtocolBasedTransport(Transport): # """Transport that implements its communications through a Protocol. # # Intended as a base class for implementations that proxy their communication # operations to a Protocol. # """ # # def __init__(self, protocol: Protocol) -> None: # self.protocol = protocol # # def write(self, message: protobuf.MessageType) -> None: # self.protocol.write(message) # # def read(self) -> protobuf.MessageType: # return self.protocol.read() # # def begin_session(self) -> None: # self.protocol.begin_session() # # def end_session(self) -> None: # self.protocol.end_session() # # class ProtocolV1(Protocol): # """Protocol version 1. Currently (11/2018) in use on all Trezors. # Does not understand sessions. # """ # # VERSION = 1 # # def write(self, msg: protobuf.MessageType) -> None: # LOG.debug( # "sending message: {}".format(msg.__class__.__name__), # extra={"protobuf": msg}, # ) # data = BytesIO() # protobuf.dump_message(data, msg) # ser = data.getvalue() # header = struct.pack(">HL", mapping.get_type(msg), len(ser)) # buffer = bytearray(b"##" + header + ser) # # while buffer: # # Report ID, data padded to 63 bytes # chunk = b"?" + buffer[: REPLEN - 1] # chunk = chunk.ljust(REPLEN, b"\x00") # self.handle.write_chunk(chunk) # buffer = buffer[63:] # # def read(self) -> protobuf.MessageType: # buffer = bytearray() # # Read header with first part of message data # msg_type, datalen, first_chunk = self.read_first() # buffer.extend(first_chunk) # # # Read the rest of the message # while len(buffer) < datalen: # buffer.extend(self.read_next()) # # # Strip padding # data = BytesIO(buffer[:datalen]) # # # Parse to protobuf # msg = protobuf.load_message(data, mapping.get_class(msg_type)) # LOG.debug( # "received message: {}".format(msg.__class__.__name__), # extra={"protobuf": msg}, # ) # return msg # # def read_first(self) -> Tuple[int, int, bytes]: # chunk = self.handle.read_chunk() # if chunk[:3] != b"?##": # raise RuntimeError("Unexpected magic characters") # try: # headerlen = struct.calcsize(">HL") # msg_type, datalen = struct.unpack(">HL", chunk[3 : 3 + headerlen]) # except Exception: # raise RuntimeError("Cannot parse header") # # data = chunk[3 + headerlen :] # return msg_type, datalen, data # # def read_next(self) -> bytes: # chunk = self.handle.read_chunk() # if chunk[:1] != b"?": # raise RuntimeError("Unexpected magic characters") # return chunk[1:] . Output only the next line.
self.handle = None
Using the snippet: <|code_start|>class WebUsbHandle: def __init__(self, device: "usb1.USBDevice", debug: bool = False) -> None: self.device = device self.interface = DEBUG_INTERFACE if debug else INTERFACE self.endpoint = DEBUG_ENDPOINT if debug else ENDPOINT self.count = 0 self.handle = None # type: Optional[usb1.USBDeviceHandle] def open(self) -> None: self.handle = self.device.open() if self.handle is None: if sys.platform.startswith("linux"): args = (UDEV_RULES_STR,) else: args = () raise IOError("Cannot open device", *args) self.handle.claimInterface(self.interface) def close(self) -> None: if self.handle is not None: self.handle.releaseInterface(self.interface) self.handle.close() self.handle = None def write_chunk(self, chunk: bytes) -> None: assert self.handle is not None if len(chunk) != 64: raise TransportException("Unexpected chunk size: %d" % len(chunk)) self.handle.interruptWrite(self.endpoint, chunk) <|code_end|> , determine the next line of code. You have imports: import atexit import logging import sys import time import usb1 from typing import Iterable, Optional from . import TREZORS, UDEV_RULES_STR, TransportException from .protocol import ProtocolBasedTransport, ProtocolV1 and context (class names, function names, or code) available: # Path: trezorlib/transport/protocol.py # class ProtocolBasedTransport(Transport): # """Transport that implements its communications through a Protocol. # # Intended as a base class for implementations that proxy their communication # operations to a Protocol. # """ # # def __init__(self, protocol: Protocol) -> None: # self.protocol = protocol # # def write(self, message: protobuf.MessageType) -> None: # self.protocol.write(message) # # def read(self) -> protobuf.MessageType: # return self.protocol.read() # # def begin_session(self) -> None: # self.protocol.begin_session() # # def end_session(self) -> None: # self.protocol.end_session() # # class ProtocolV1(Protocol): # """Protocol version 1. Currently (11/2018) in use on all Trezors. # Does not understand sessions. # """ # # VERSION = 1 # # def write(self, msg: protobuf.MessageType) -> None: # LOG.debug( # "sending message: {}".format(msg.__class__.__name__), # extra={"protobuf": msg}, # ) # data = BytesIO() # protobuf.dump_message(data, msg) # ser = data.getvalue() # header = struct.pack(">HL", mapping.get_type(msg), len(ser)) # buffer = bytearray(b"##" + header + ser) # # while buffer: # # Report ID, data padded to 63 bytes # chunk = b"?" + buffer[: REPLEN - 1] # chunk = chunk.ljust(REPLEN, b"\x00") # self.handle.write_chunk(chunk) # buffer = buffer[63:] # # def read(self) -> protobuf.MessageType: # buffer = bytearray() # # Read header with first part of message data # msg_type, datalen, first_chunk = self.read_first() # buffer.extend(first_chunk) # # # Read the rest of the message # while len(buffer) < datalen: # buffer.extend(self.read_next()) # # # Strip padding # data = BytesIO(buffer[:datalen]) # # # Parse to protobuf # msg = protobuf.load_message(data, mapping.get_class(msg_type)) # LOG.debug( # "received message: {}".format(msg.__class__.__name__), # extra={"protobuf": msg}, # ) # return msg # # def read_first(self) -> Tuple[int, int, bytes]: # chunk = self.handle.read_chunk() # if chunk[:3] != b"?##": # raise RuntimeError("Unexpected magic characters") # try: # headerlen = struct.calcsize(">HL") # msg_type, datalen = struct.unpack(">HL", chunk[3 : 3 + headerlen]) # except Exception: # raise RuntimeError("Cannot parse header") # # data = chunk[3 + headerlen :] # return msg_type, datalen, data # # def read_next(self) -> bytes: # chunk = self.handle.read_chunk() # if chunk[:1] != b"?": # raise RuntimeError("Unexpected magic characters") # return chunk[1:] . Output only the next line.
def read_chunk(self) -> bytes:
Using the snippet: <|code_start|> sig.signature.hex() == "209e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80" ) def test_sign_testnet(self): self.setup_mnemonic_nopin_nopassphrase() sig = btc.sign_message( self.client, "Testnet", [0], "This is an example of a signed message." ) assert sig.address == "mirio8q3gtv7fhdnmb3TpZ4EuafdzSs7zL" assert ( sig.signature.hex() == "209e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80" ) def test_sign_bch(self): self.setup_mnemonic_nopin_nopassphrase() sig = btc.sign_message( self.client, "Bcash", [0], "This is an example of a signed message." ) assert sig.address == "bitcoincash:qqj22md58nm09vpwsw82fyletkxkq36zxyxh322pru" assert ( sig.signature.hex() == "209e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80" ) def test_sign_grs(self): self.setup_mnemonic_allallall() sig = btc.sign_message( self.client, "Groestlcoin", parse_path("44'/17'/0'/0/0"), "test" <|code_end|> , determine the next line of code. You have imports: import base64 from trezorlib import btc from trezorlib.tools import parse_path from .common import TrezorTest and context (class names, function names, or code) available: # Path: trezorlib/btc.py # def get_public_node( # client, # n, # ecdsa_curve_name=None, # show_display=False, # coin_name=None, # script_type=messages.InputScriptType.SPENDADDRESS, # ): # def get_address( # client, # coin_name, # n, # show_display=False, # multisig=None, # script_type=messages.InputScriptType.SPENDADDRESS, # ): # def sign_message( # client, coin_name, n, message, script_type=messages.InputScriptType.SPENDADDRESS # ): # def verify_message(client, coin_name, address, signature, message): # def sign_tx(client, coin_name, inputs, outputs, details=None, prev_txes=None): # def copy_tx_meta(tx): # R = messages.RequestType . Output only the next line.
)
Continue the code snippet: <|code_start|> for device in enumerate_devices(): try: debug_transport = device.find_debug() debug = DebugLink(debug_transport, auto_interact=False) debug.open() return debug except Exception: continue else: print("No suitable Trezor device found") sys.exit(1) def main(): debug = find_debug() arg1 = int(sys.argv[1], 16) arg2 = int(sys.argv[2], 16) step = 0x400 if arg2 >= 0x400 else arg2 f = open("memory.dat", "wb") for addr in range(arg1, arg1 + arg2, step): mem = debug.memory_read(addr, step) f.write(mem) f.close() if __name__ == "__main__": <|code_end|> . Use current file imports: from trezorlib.debuglink import DebugLink from trezorlib.transport import enumerate_devices import sys and context (classes, functions, or code) from other files: # Path: trezorlib/debuglink.py # class DebugLink: # def __init__(self, transport, auto_interact=True): # self.transport = transport # self.allow_interactions = auto_interact # # def open(self): # self.transport.begin_session() # # def close(self): # self.transport.end_session() # # def _call(self, msg, nowait=False): # self.transport.write(msg) # if nowait: # return None # ret = self.transport.read() # return ret # # def state(self): # return self._call(proto.DebugLinkGetState()) # # def read_pin(self): # state = self.state() # return state.pin, state.matrix # # def read_pin_encoded(self): # return self.encode_pin(*self.read_pin()) # # def encode_pin(self, pin, matrix=None): # """Transform correct PIN according to the displayed matrix.""" # if matrix is None: # _, matrix = self.read_pin() # return "".join([str(matrix.index(p) + 1) for p in pin]) # # def read_layout(self): # obj = self._call(proto.DebugLinkGetState()) # return obj.layout # # def read_mnemonic_secret(self): # obj = self._call(proto.DebugLinkGetState()) # return obj.mnemonic_secret # # def read_recovery_word(self): # obj = self._call(proto.DebugLinkGetState()) # return (obj.recovery_fake_word, obj.recovery_word_pos) # # def read_reset_word(self): # obj = self._call(proto.DebugLinkGetState()) # return obj.reset_word # # def read_reset_word_pos(self): # obj = self._call(proto.DebugLinkGetState()) # return obj.reset_word_pos # # def read_reset_entropy(self): # obj = self._call(proto.DebugLinkGetState()) # return obj.reset_entropy # # def read_passphrase_protection(self): # obj = self._call(proto.DebugLinkGetState()) # return obj.passphrase_protection # # def input(self, word=None, button=None, swipe=None): # if not self.allow_interactions: # return # decision = proto.DebugLinkDecision() # if button is not None: # decision.yes_no = button # elif word is not None: # decision.input = word # elif swipe is not None: # decision.up_down = swipe # else: # raise ValueError("You need to provide input data.") # self._call(decision, nowait=True) # # def press_button(self, yes_no): # self._call(proto.DebugLinkDecision(yes_no=yes_no), nowait=True) # # def press_yes(self): # self.input(button=True) # # def press_no(self): # self.input(button=False) # # def swipe_up(self): # self.input(swipe=True) # # def swipe_down(self): # self.input(swipe=False) # # def stop(self): # self._call(proto.DebugLinkStop(), nowait=True) # # @expect(proto.DebugLinkMemory, field="memory") # def memory_read(self, address, length): # return self._call(proto.DebugLinkMemoryRead(address=address, length=length)) # # def memory_write(self, address, memory, flash=False): # self._call( # proto.DebugLinkMemoryWrite(address=address, memory=memory, flash=flash), # nowait=True, # ) # # def flash_erase(self, sector): # self._call(proto.DebugLinkFlashErase(sector=sector), nowait=True) . Output only the next line.
main()
Continue the code snippet: <|code_start|># coding: utf-8 from __future__ import absolute_import, division, print_function SPK_URL = ("http://naif.jpl.nasa.gov/pub/naif/generic_kernels/" "spk/{category}/{kernel}.bsp") SPK_OLD_URL = ("http://naif.jpl.nasa.gov/pub/naif/generic_kernels/" "spk/{category}/a_old_versions/{kernel}.bsp") appdirs = AppDirs('astrodynamics') <|code_end|> . Use current file imports: from pathlib import Path from appdirs import AppDirs from requests import HTTPError from six.moves.urllib.parse import quote from .helper import format_size, prefix, suppress_file_exists_error from .progress import DownloadProgressBar, DownloadProgressSpinner import requests and context (classes, functions, or code) from other files: # Path: src/astrodynamics/utils/helper.py # def format_size(value, binary=False, gnu=False, format='%.1f'): # """Format a number of bytes like a human readable file size (e.g. 10 kB). By # default, decimal suffixes (kB, MB) are used. Passing binary=true will use # binary suffixes (KiB, MiB) are used and the base will be 2**10 instead of # 10**3. If ``gnu`` is True, the binary argument is ignored and GNU-style # (ls -sh style) prefixes are used (K, M) with the 2**10 definition. # Non-gnu modes are compatible with jinja2's ``filesizeformat`` filter. # # Copyright (c) 2010 Jason Moiron and Contributors. # """ # if gnu: # suffix = _size_suffixes['gnu'] # elif binary: # suffix = _size_suffixes['binary'] # else: # suffix = _size_suffixes['decimal'] # # base = 1024 if (gnu or binary) else 1000 # bytes = float(value) # # if bytes == 1 and not gnu: # return '1 Byte' # elif bytes < base and not gnu: # return '%d Bytes' % bytes # elif bytes < base and gnu: # return '%dB' % bytes # # for i, s in enumerate(suffix): # unit = base ** (i + 2) # if bytes < unit and not gnu: # return (format + ' %s') % ((base * bytes / unit), s) # elif bytes < unit and gnu: # return (format + '%s') % ((base * bytes / unit), s) # if gnu: # return (format + '%s') % ((base * bytes / unit), s) # return (format + ' %s') % ((base * bytes / unit), s) # # def prefix(prefix, iterable): # """Prepend items from `iterable` with `prefix` string.""" # for x in iterable: # yield '{prefix}{x}'.format(prefix=prefix, x=x) # # @contextmanager # def suppress_file_exists_error(): # """Compatibility function for catching FileExistsError on Python 2""" # if PY33: # with suppress(FileExistsError): # noqa # yield # else: # try: # yield # except OSError as e: # if e.errno != errno.EEXIST: # raise # # Path: src/astrodynamics/utils/progress.py # class DownloadProgressBar(WindowsMixin, InterruptibleMixin, # DownloadProgressMixin, _BaseBar): # # file = sys.stdout # message = "%(percent)d%%" # suffix = "%(downloaded)s %(download_speed)s %(pretty_eta)s" # # class DownloadProgressSpinner(WindowsMixin, InterruptibleMixin, # DownloadProgressMixin, WritelnMixin, Spinner): # # file = sys.stdout # suffix = "%(downloaded)s %(download_speed)s" # # def next_phase(self): # if not hasattr(self, "_phaser"): # self._phaser = itertools.cycle(self.phases) # return next(self._phaser) # # def update(self): # message = self.message % self # phase = self.next_phase() # suffix = self.suffix % self # line = ''.join([ # message, # " " if message else "", # phase, # " " if suffix else "", # suffix, # ]) # # self.writeln(line) . Output only the next line.
SPK_DIR = Path(appdirs.user_data_dir, 'spk')
Next line prediction: <|code_start|># coding: utf-8 from __future__ import absolute_import, division, print_function SPK_URL = ("http://naif.jpl.nasa.gov/pub/naif/generic_kernels/" "spk/{category}/{kernel}.bsp") SPK_OLD_URL = ("http://naif.jpl.nasa.gov/pub/naif/generic_kernels/" "spk/{category}/a_old_versions/{kernel}.bsp") <|code_end|> . Use current file imports: (from pathlib import Path from appdirs import AppDirs from requests import HTTPError from six.moves.urllib.parse import quote from .helper import format_size, prefix, suppress_file_exists_error from .progress import DownloadProgressBar, DownloadProgressSpinner import requests) and context including class names, function names, or small code snippets from other files: # Path: src/astrodynamics/utils/helper.py # def format_size(value, binary=False, gnu=False, format='%.1f'): # """Format a number of bytes like a human readable file size (e.g. 10 kB). By # default, decimal suffixes (kB, MB) are used. Passing binary=true will use # binary suffixes (KiB, MiB) are used and the base will be 2**10 instead of # 10**3. If ``gnu`` is True, the binary argument is ignored and GNU-style # (ls -sh style) prefixes are used (K, M) with the 2**10 definition. # Non-gnu modes are compatible with jinja2's ``filesizeformat`` filter. # # Copyright (c) 2010 Jason Moiron and Contributors. # """ # if gnu: # suffix = _size_suffixes['gnu'] # elif binary: # suffix = _size_suffixes['binary'] # else: # suffix = _size_suffixes['decimal'] # # base = 1024 if (gnu or binary) else 1000 # bytes = float(value) # # if bytes == 1 and not gnu: # return '1 Byte' # elif bytes < base and not gnu: # return '%d Bytes' % bytes # elif bytes < base and gnu: # return '%dB' % bytes # # for i, s in enumerate(suffix): # unit = base ** (i + 2) # if bytes < unit and not gnu: # return (format + ' %s') % ((base * bytes / unit), s) # elif bytes < unit and gnu: # return (format + '%s') % ((base * bytes / unit), s) # if gnu: # return (format + '%s') % ((base * bytes / unit), s) # return (format + ' %s') % ((base * bytes / unit), s) # # def prefix(prefix, iterable): # """Prepend items from `iterable` with `prefix` string.""" # for x in iterable: # yield '{prefix}{x}'.format(prefix=prefix, x=x) # # @contextmanager # def suppress_file_exists_error(): # """Compatibility function for catching FileExistsError on Python 2""" # if PY33: # with suppress(FileExistsError): # noqa # yield # else: # try: # yield # except OSError as e: # if e.errno != errno.EEXIST: # raise # # Path: src/astrodynamics/utils/progress.py # class DownloadProgressBar(WindowsMixin, InterruptibleMixin, # DownloadProgressMixin, _BaseBar): # # file = sys.stdout # message = "%(percent)d%%" # suffix = "%(downloaded)s %(download_speed)s %(pretty_eta)s" # # class DownloadProgressSpinner(WindowsMixin, InterruptibleMixin, # DownloadProgressMixin, WritelnMixin, Spinner): # # file = sys.stdout # suffix = "%(downloaded)s %(download_speed)s" # # def next_phase(self): # if not hasattr(self, "_phaser"): # self._phaser = itertools.cycle(self.phases) # return next(self._phaser) # # def update(self): # message = self.message % self # phase = self.next_phase() # suffix = self.suffix % self # line = ''.join([ # message, # " " if message else "", # phase, # " " if suffix else "", # suffix, # ]) # # self.writeln(line) . Output only the next line.
appdirs = AppDirs('astrodynamics')
Here is a snippet: <|code_start|># coding: utf-8 from __future__ import absolute_import, division, print_function SPK_URL = ("http://naif.jpl.nasa.gov/pub/naif/generic_kernels/" "spk/{category}/{kernel}.bsp") SPK_OLD_URL = ("http://naif.jpl.nasa.gov/pub/naif/generic_kernels/" "spk/{category}/a_old_versions/{kernel}.bsp") appdirs = AppDirs('astrodynamics') <|code_end|> . Write the next line using the current file imports: from pathlib import Path from appdirs import AppDirs from requests import HTTPError from six.moves.urllib.parse import quote from .helper import format_size, prefix, suppress_file_exists_error from .progress import DownloadProgressBar, DownloadProgressSpinner import requests and context from other files: # Path: src/astrodynamics/utils/helper.py # def format_size(value, binary=False, gnu=False, format='%.1f'): # """Format a number of bytes like a human readable file size (e.g. 10 kB). By # default, decimal suffixes (kB, MB) are used. Passing binary=true will use # binary suffixes (KiB, MiB) are used and the base will be 2**10 instead of # 10**3. If ``gnu`` is True, the binary argument is ignored and GNU-style # (ls -sh style) prefixes are used (K, M) with the 2**10 definition. # Non-gnu modes are compatible with jinja2's ``filesizeformat`` filter. # # Copyright (c) 2010 Jason Moiron and Contributors. # """ # if gnu: # suffix = _size_suffixes['gnu'] # elif binary: # suffix = _size_suffixes['binary'] # else: # suffix = _size_suffixes['decimal'] # # base = 1024 if (gnu or binary) else 1000 # bytes = float(value) # # if bytes == 1 and not gnu: # return '1 Byte' # elif bytes < base and not gnu: # return '%d Bytes' % bytes # elif bytes < base and gnu: # return '%dB' % bytes # # for i, s in enumerate(suffix): # unit = base ** (i + 2) # if bytes < unit and not gnu: # return (format + ' %s') % ((base * bytes / unit), s) # elif bytes < unit and gnu: # return (format + '%s') % ((base * bytes / unit), s) # if gnu: # return (format + '%s') % ((base * bytes / unit), s) # return (format + ' %s') % ((base * bytes / unit), s) # # def prefix(prefix, iterable): # """Prepend items from `iterable` with `prefix` string.""" # for x in iterable: # yield '{prefix}{x}'.format(prefix=prefix, x=x) # # @contextmanager # def suppress_file_exists_error(): # """Compatibility function for catching FileExistsError on Python 2""" # if PY33: # with suppress(FileExistsError): # noqa # yield # else: # try: # yield # except OSError as e: # if e.errno != errno.EEXIST: # raise # # Path: src/astrodynamics/utils/progress.py # class DownloadProgressBar(WindowsMixin, InterruptibleMixin, # DownloadProgressMixin, _BaseBar): # # file = sys.stdout # message = "%(percent)d%%" # suffix = "%(downloaded)s %(download_speed)s %(pretty_eta)s" # # class DownloadProgressSpinner(WindowsMixin, InterruptibleMixin, # DownloadProgressMixin, WritelnMixin, Spinner): # # file = sys.stdout # suffix = "%(downloaded)s %(download_speed)s" # # def next_phase(self): # if not hasattr(self, "_phaser"): # self._phaser = itertools.cycle(self.phases) # return next(self._phaser) # # def update(self): # message = self.message % self # phase = self.next_phase() # suffix = self.suffix % self # line = ''.join([ # message, # " " if message else "", # phase, # " " if suffix else "", # suffix, # ]) # # self.writeln(line) , which may include functions, classes, or code. Output only the next line.
SPK_DIR = Path(appdirs.user_data_dir, 'spk')
Here is a snippet: <|code_start|># coding: utf-8 from __future__ import absolute_import, division, print_function __all__ = ( 'Ellipsoid', <|code_end|> . Write the next line using the current file imports: from astropy.units import Quantity from represent import ReprHelperMixin from ..constants import ( WGS84_ANGULAR_VELOCITY, WGS84_EQUATORIAL_RADIUS, WGS84_FLATTENING, WGS84_MU) from ..utils import read_only_property, verify_unit and context from other files: # Path: src/astrodynamics/constants/wgs84.py # WGS84_EQUATORIAL_RADIUS = Constant( # name='WGS84 semi-major axis', # value=6378137, # unit='m', # uncertainty=0, # reference='World Geodetic System 1984') # # WGS84_FLATTENING = Constant( # name='WGS84 Earth flattening factor', # value=1 / 298.257223563, # unit='', # uncertainty=0, # reference='World Geodetic System 1984') # # WGS84_MU = Constant( # name='WGS84 geocentric gravitational constant', # value=3.986004418e14, # unit='m3 / s2', # uncertainty=0, # reference='World Geodetic System 1984') # # WGS84_ANGULAR_VELOCITY = Constant( # name='WGS84 nominal earth mean angular velocity', # value=7.292115e-5, # unit='rad / s', # uncertainty=0, # reference='World Geodetic System 1984') # # Path: src/astrodynamics/utils/helper.py # def read_only_property(name, docstring=None): # """Return property for accessing attribute with name `name` # # Parameters: # name: Attribute name # docstring: Optional docstring for getter. # # Example: # .. code-block:: python # # class Circle: # def __init__(self, radius): # self._radius = radius # # radius = read_only_property('_radius') # """ # def fget(self): # return getattr(self, name) # # fget.__doc__ = docstring # return property(fget) # # def verify_unit(quantity, unit): # """Verify unit of passed quantity and return it. # # Parameters: # quantity: :py:class:`~astropy.units.Quantity` to be verified. Bare # numbers are valid if the unit is dimensionless. # unit: Equivalent unit, or string parsable by # :py:class:`astropy.units.Unit` # # Raises: # ValueError: Units are not equivalent. # # Returns: # ``quantity`` unchanged. Bare numbers will be converted to a dimensionless # :py:class:`~astropy.units.Quantity`. # # Example: # .. code-block:: python # # def __init__(self, a): # self.a = verify_unit(a, astropy.units.m) # # """ # if not isinstance(unit, UnitBase): # unit = Unit(unit) # # q = quantity * u.one # if unit.is_equivalent(q.unit): # return q # else: # raise ValueError( # "Unit '{}' not equivalent to quantity '{}'.".format(unit, quantity)) , which may include functions, classes, or code. Output only the next line.
'ReferenceEllipsoid',
Predict the next line after this snippet: <|code_start|># coding: utf-8 from __future__ import absolute_import, division, print_function __all__ = ( 'Ellipsoid', 'ReferenceEllipsoid', 'wgs84', ) <|code_end|> using the current file's imports: from astropy.units import Quantity from represent import ReprHelperMixin from ..constants import ( WGS84_ANGULAR_VELOCITY, WGS84_EQUATORIAL_RADIUS, WGS84_FLATTENING, WGS84_MU) from ..utils import read_only_property, verify_unit and any relevant context from other files: # Path: src/astrodynamics/constants/wgs84.py # WGS84_EQUATORIAL_RADIUS = Constant( # name='WGS84 semi-major axis', # value=6378137, # unit='m', # uncertainty=0, # reference='World Geodetic System 1984') # # WGS84_FLATTENING = Constant( # name='WGS84 Earth flattening factor', # value=1 / 298.257223563, # unit='', # uncertainty=0, # reference='World Geodetic System 1984') # # WGS84_MU = Constant( # name='WGS84 geocentric gravitational constant', # value=3.986004418e14, # unit='m3 / s2', # uncertainty=0, # reference='World Geodetic System 1984') # # WGS84_ANGULAR_VELOCITY = Constant( # name='WGS84 nominal earth mean angular velocity', # value=7.292115e-5, # unit='rad / s', # uncertainty=0, # reference='World Geodetic System 1984') # # Path: src/astrodynamics/utils/helper.py # def read_only_property(name, docstring=None): # """Return property for accessing attribute with name `name` # # Parameters: # name: Attribute name # docstring: Optional docstring for getter. # # Example: # .. code-block:: python # # class Circle: # def __init__(self, radius): # self._radius = radius # # radius = read_only_property('_radius') # """ # def fget(self): # return getattr(self, name) # # fget.__doc__ = docstring # return property(fget) # # def verify_unit(quantity, unit): # """Verify unit of passed quantity and return it. # # Parameters: # quantity: :py:class:`~astropy.units.Quantity` to be verified. Bare # numbers are valid if the unit is dimensionless. # unit: Equivalent unit, or string parsable by # :py:class:`astropy.units.Unit` # # Raises: # ValueError: Units are not equivalent. # # Returns: # ``quantity`` unchanged. Bare numbers will be converted to a dimensionless # :py:class:`~astropy.units.Quantity`. # # Example: # .. code-block:: python # # def __init__(self, a): # self.a = verify_unit(a, astropy.units.m) # # """ # if not isinstance(unit, UnitBase): # unit = Unit(unit) # # q = quantity * u.one # if unit.is_equivalent(q.unit): # return q # else: # raise ValueError( # "Unit '{}' not equivalent to quantity '{}'.".format(unit, quantity)) . Output only the next line.
class Ellipsoid(ReprHelperMixin, object):
Here is a snippet: <|code_start|># coding: utf-8 from __future__ import absolute_import, division, print_function __all__ = ( 'Ellipsoid', <|code_end|> . Write the next line using the current file imports: from astropy.units import Quantity from represent import ReprHelperMixin from ..constants import ( WGS84_ANGULAR_VELOCITY, WGS84_EQUATORIAL_RADIUS, WGS84_FLATTENING, WGS84_MU) from ..utils import read_only_property, verify_unit and context from other files: # Path: src/astrodynamics/constants/wgs84.py # WGS84_EQUATORIAL_RADIUS = Constant( # name='WGS84 semi-major axis', # value=6378137, # unit='m', # uncertainty=0, # reference='World Geodetic System 1984') # # WGS84_FLATTENING = Constant( # name='WGS84 Earth flattening factor', # value=1 / 298.257223563, # unit='', # uncertainty=0, # reference='World Geodetic System 1984') # # WGS84_MU = Constant( # name='WGS84 geocentric gravitational constant', # value=3.986004418e14, # unit='m3 / s2', # uncertainty=0, # reference='World Geodetic System 1984') # # WGS84_ANGULAR_VELOCITY = Constant( # name='WGS84 nominal earth mean angular velocity', # value=7.292115e-5, # unit='rad / s', # uncertainty=0, # reference='World Geodetic System 1984') # # Path: src/astrodynamics/utils/helper.py # def read_only_property(name, docstring=None): # """Return property for accessing attribute with name `name` # # Parameters: # name: Attribute name # docstring: Optional docstring for getter. # # Example: # .. code-block:: python # # class Circle: # def __init__(self, radius): # self._radius = radius # # radius = read_only_property('_radius') # """ # def fget(self): # return getattr(self, name) # # fget.__doc__ = docstring # return property(fget) # # def verify_unit(quantity, unit): # """Verify unit of passed quantity and return it. # # Parameters: # quantity: :py:class:`~astropy.units.Quantity` to be verified. Bare # numbers are valid if the unit is dimensionless. # unit: Equivalent unit, or string parsable by # :py:class:`astropy.units.Unit` # # Raises: # ValueError: Units are not equivalent. # # Returns: # ``quantity`` unchanged. Bare numbers will be converted to a dimensionless # :py:class:`~astropy.units.Quantity`. # # Example: # .. code-block:: python # # def __init__(self, a): # self.a = verify_unit(a, astropy.units.m) # # """ # if not isinstance(unit, UnitBase): # unit = Unit(unit) # # q = quantity * u.one # if unit.is_equivalent(q.unit): # return q # else: # raise ValueError( # "Unit '{}' not equivalent to quantity '{}'.".format(unit, quantity)) , which may include functions, classes, or code. Output only the next line.
'ReferenceEllipsoid',
Based on the snippet: <|code_start|># coding: utf-8 from __future__ import absolute_import, division, print_function __all__ = ( 'Ellipsoid', 'ReferenceEllipsoid', <|code_end|> , predict the immediate next line with the help of imports: from astropy.units import Quantity from represent import ReprHelperMixin from ..constants import ( WGS84_ANGULAR_VELOCITY, WGS84_EQUATORIAL_RADIUS, WGS84_FLATTENING, WGS84_MU) from ..utils import read_only_property, verify_unit and context (classes, functions, sometimes code) from other files: # Path: src/astrodynamics/constants/wgs84.py # WGS84_EQUATORIAL_RADIUS = Constant( # name='WGS84 semi-major axis', # value=6378137, # unit='m', # uncertainty=0, # reference='World Geodetic System 1984') # # WGS84_FLATTENING = Constant( # name='WGS84 Earth flattening factor', # value=1 / 298.257223563, # unit='', # uncertainty=0, # reference='World Geodetic System 1984') # # WGS84_MU = Constant( # name='WGS84 geocentric gravitational constant', # value=3.986004418e14, # unit='m3 / s2', # uncertainty=0, # reference='World Geodetic System 1984') # # WGS84_ANGULAR_VELOCITY = Constant( # name='WGS84 nominal earth mean angular velocity', # value=7.292115e-5, # unit='rad / s', # uncertainty=0, # reference='World Geodetic System 1984') # # Path: src/astrodynamics/utils/helper.py # def read_only_property(name, docstring=None): # """Return property for accessing attribute with name `name` # # Parameters: # name: Attribute name # docstring: Optional docstring for getter. # # Example: # .. code-block:: python # # class Circle: # def __init__(self, radius): # self._radius = radius # # radius = read_only_property('_radius') # """ # def fget(self): # return getattr(self, name) # # fget.__doc__ = docstring # return property(fget) # # def verify_unit(quantity, unit): # """Verify unit of passed quantity and return it. # # Parameters: # quantity: :py:class:`~astropy.units.Quantity` to be verified. Bare # numbers are valid if the unit is dimensionless. # unit: Equivalent unit, or string parsable by # :py:class:`astropy.units.Unit` # # Raises: # ValueError: Units are not equivalent. # # Returns: # ``quantity`` unchanged. Bare numbers will be converted to a dimensionless # :py:class:`~astropy.units.Quantity`. # # Example: # .. code-block:: python # # def __init__(self, a): # self.a = verify_unit(a, astropy.units.m) # # """ # if not isinstance(unit, UnitBase): # unit = Unit(unit) # # q = quantity * u.one # if unit.is_equivalent(q.unit): # return q # else: # raise ValueError( # "Unit '{}' not equivalent to quantity '{}'.".format(unit, quantity)) . Output only the next line.
'wgs84',
Given snippet: <|code_start|># coding: utf-8 from __future__ import absolute_import, division, print_function __all__ = ( 'Ellipsoid', 'ReferenceEllipsoid', <|code_end|> , continue by predicting the next line. Consider current file imports: from astropy.units import Quantity from represent import ReprHelperMixin from ..constants import ( WGS84_ANGULAR_VELOCITY, WGS84_EQUATORIAL_RADIUS, WGS84_FLATTENING, WGS84_MU) from ..utils import read_only_property, verify_unit and context: # Path: src/astrodynamics/constants/wgs84.py # WGS84_EQUATORIAL_RADIUS = Constant( # name='WGS84 semi-major axis', # value=6378137, # unit='m', # uncertainty=0, # reference='World Geodetic System 1984') # # WGS84_FLATTENING = Constant( # name='WGS84 Earth flattening factor', # value=1 / 298.257223563, # unit='', # uncertainty=0, # reference='World Geodetic System 1984') # # WGS84_MU = Constant( # name='WGS84 geocentric gravitational constant', # value=3.986004418e14, # unit='m3 / s2', # uncertainty=0, # reference='World Geodetic System 1984') # # WGS84_ANGULAR_VELOCITY = Constant( # name='WGS84 nominal earth mean angular velocity', # value=7.292115e-5, # unit='rad / s', # uncertainty=0, # reference='World Geodetic System 1984') # # Path: src/astrodynamics/utils/helper.py # def read_only_property(name, docstring=None): # """Return property for accessing attribute with name `name` # # Parameters: # name: Attribute name # docstring: Optional docstring for getter. # # Example: # .. code-block:: python # # class Circle: # def __init__(self, radius): # self._radius = radius # # radius = read_only_property('_radius') # """ # def fget(self): # return getattr(self, name) # # fget.__doc__ = docstring # return property(fget) # # def verify_unit(quantity, unit): # """Verify unit of passed quantity and return it. # # Parameters: # quantity: :py:class:`~astropy.units.Quantity` to be verified. Bare # numbers are valid if the unit is dimensionless. # unit: Equivalent unit, or string parsable by # :py:class:`astropy.units.Unit` # # Raises: # ValueError: Units are not equivalent. # # Returns: # ``quantity`` unchanged. Bare numbers will be converted to a dimensionless # :py:class:`~astropy.units.Quantity`. # # Example: # .. code-block:: python # # def __init__(self, a): # self.a = verify_unit(a, astropy.units.m) # # """ # if not isinstance(unit, UnitBase): # unit = Unit(unit) # # q = quantity * u.one # if unit.is_equivalent(q.unit): # return q # else: # raise ValueError( # "Unit '{}' not equivalent to quantity '{}'.".format(unit, quantity)) which might include code, classes, or functions. Output only the next line.
'wgs84',
Continue the code snippet: <|code_start|># coding: utf-8 from __future__ import absolute_import, division, print_function __all__ = ( 'format_size', 'prefix', 'qisclose', 'read_only_property', <|code_end|> . Use current file imports: import errno from contextlib import contextmanager from astropy import units as u from astropy.units import Unit, UnitBase from ..compat.contextlib import suppress from ..compat.math import isclose from .compat import PY33 and context (classes, functions, or code) from other files: # Path: src/astrodynamics/compat/contextlib.py # class _SuppressExceptions: # def __init__(self, *exceptions): # def __enter__(self): # def __exit__(self, exctype, excinst, exctb): # def _suppress(*exceptions): # # Path: src/astrodynamics/compat/math.py # def _isclose(a, b, rel_tol=1e-9, abs_tol=0.0): # # Path: src/astrodynamics/utils/compat.py # PY33 = sys.version_info >= (3, 3) . Output only the next line.
'suppress_file_exists_error',
Here is a snippet: <|code_start|>try: # Lots of different errors can come from this, including SystemError and # ImportError. except Exception: colorama = None __all__ = ('DownloadProgressBar', 'DownloadProgressSpinner') def _select_progress_class(preferred, fallback): encoding = getattr(preferred.file, "encoding", None) # If we don't know what encoding this file is in, then we'll just assume # that it doesn't support unicode and use the ASCII bar. if not encoding: return fallback # Collect all of the possible characters we want to use with the preferred # bar. characters = [ getattr(preferred, "empty_fill", six.text_type()), getattr(preferred, "fill", six.text_type()), ] characters += list(getattr(preferred, "phases", [])) # Try to decode the characters we're using for the bar using the encoding # of the given file, if this works then we'll assume that we can use the # fancier bar and if not we'll fall back to the plaintext bar. try: six.text_type().join(characters).encode(encoding) <|code_end|> . Write the next line using the current file imports: import itertools import sys import six import colorama from signal import SIGINT, default_int_handler, signal from progress.bar import Bar, IncrementalBar from progress.helpers import WritelnMixin from progress.spinner import Spinner from .compat import WINDOWS from .helper import format_size and context from other files: # Path: src/astrodynamics/utils/compat.py # WINDOWS = (sys.platform.startswith("win") or # (sys.platform == 'cli' and os.name == 'nt')) # # Path: src/astrodynamics/utils/helper.py # def format_size(value, binary=False, gnu=False, format='%.1f'): # """Format a number of bytes like a human readable file size (e.g. 10 kB). By # default, decimal suffixes (kB, MB) are used. Passing binary=true will use # binary suffixes (KiB, MiB) are used and the base will be 2**10 instead of # 10**3. If ``gnu`` is True, the binary argument is ignored and GNU-style # (ls -sh style) prefixes are used (K, M) with the 2**10 definition. # Non-gnu modes are compatible with jinja2's ``filesizeformat`` filter. # # Copyright (c) 2010 Jason Moiron and Contributors. # """ # if gnu: # suffix = _size_suffixes['gnu'] # elif binary: # suffix = _size_suffixes['binary'] # else: # suffix = _size_suffixes['decimal'] # # base = 1024 if (gnu or binary) else 1000 # bytes = float(value) # # if bytes == 1 and not gnu: # return '1 Byte' # elif bytes < base and not gnu: # return '%d Bytes' % bytes # elif bytes < base and gnu: # return '%dB' % bytes # # for i, s in enumerate(suffix): # unit = base ** (i + 2) # if bytes < unit and not gnu: # return (format + ' %s') % ((base * bytes / unit), s) # elif bytes < unit and gnu: # return (format + '%s') % ((base * bytes / unit), s) # if gnu: # return (format + '%s') % ((base * bytes / unit), s) # return (format + ' %s') % ((base * bytes / unit), s) , which may include functions, classes, or code. Output only the next line.
except UnicodeEncodeError:
Using the snippet: <|code_start|># coding: utf-8 from __future__ import absolute_import, division, print_function try: # Lots of different errors can come from this, including SystemError and # ImportError. except Exception: colorama = None __all__ = ('DownloadProgressBar', 'DownloadProgressSpinner') def _select_progress_class(preferred, fallback): encoding = getattr(preferred.file, "encoding", None) # If we don't know what encoding this file is in, then we'll just assume # that it doesn't support unicode and use the ASCII bar. if not encoding: return fallback # Collect all of the possible characters we want to use with the preferred # bar. characters = [ getattr(preferred, "empty_fill", six.text_type()), <|code_end|> , determine the next line of code. You have imports: import itertools import sys import six import colorama from signal import SIGINT, default_int_handler, signal from progress.bar import Bar, IncrementalBar from progress.helpers import WritelnMixin from progress.spinner import Spinner from .compat import WINDOWS from .helper import format_size and context (class names, function names, or code) available: # Path: src/astrodynamics/utils/compat.py # WINDOWS = (sys.platform.startswith("win") or # (sys.platform == 'cli' and os.name == 'nt')) # # Path: src/astrodynamics/utils/helper.py # def format_size(value, binary=False, gnu=False, format='%.1f'): # """Format a number of bytes like a human readable file size (e.g. 10 kB). By # default, decimal suffixes (kB, MB) are used. Passing binary=true will use # binary suffixes (KiB, MiB) are used and the base will be 2**10 instead of # 10**3. If ``gnu`` is True, the binary argument is ignored and GNU-style # (ls -sh style) prefixes are used (K, M) with the 2**10 definition. # Non-gnu modes are compatible with jinja2's ``filesizeformat`` filter. # # Copyright (c) 2010 Jason Moiron and Contributors. # """ # if gnu: # suffix = _size_suffixes['gnu'] # elif binary: # suffix = _size_suffixes['binary'] # else: # suffix = _size_suffixes['decimal'] # # base = 1024 if (gnu or binary) else 1000 # bytes = float(value) # # if bytes == 1 and not gnu: # return '1 Byte' # elif bytes < base and not gnu: # return '%d Bytes' % bytes # elif bytes < base and gnu: # return '%dB' % bytes # # for i, s in enumerate(suffix): # unit = base ** (i + 2) # if bytes < unit and not gnu: # return (format + ' %s') % ((base * bytes / unit), s) # elif bytes < unit and gnu: # return (format + '%s') % ((base * bytes / unit), s) # if gnu: # return (format + '%s') % ((base * bytes / unit), s) # return (format + ' %s') % ((base * bytes / unit), s) . Output only the next line.
getattr(preferred, "fill", six.text_type()),
Next line prediction: <|code_start|> @lru_cache() def uni_formset_template(template_pack=TEMPLATE_PACK): return get_template("%s/uni_formset.html" % template_pack) @lru_cache() def uni_form_template(template_pack=TEMPLATE_PACK): <|code_end|> . Use current file imports: (from functools import lru_cache from django import template from django.conf import settings from django.forms import boundfield from django.forms.formsets import BaseFormSet from django.template import Context from django.template.loader import get_template from django.utils.safestring import mark_safe from crispy_forms.exceptions import CrispyError from crispy_forms.utils import TEMPLATE_PACK, flatatt) and context including class names, function names, or small code snippets from other files: # Path: crispy_forms/utils.py # TEMPLATE_PACK = SimpleLazyObject(get_template_pack) # # def flatatt(attrs): # """ # Convert a dictionary of attributes to a single string. # # Passed attributes are redirected to `django.forms.utils.flatatt()` # with replaced "_" (underscores) by "-" (dashes) in their names. # """ # return _flatatt({k.replace("_", "-"): v for k, v in attrs.items()}) . Output only the next line.
return get_template("%s/uni_form.html" % template_pack)
Given the code snippet: <|code_start|> @lru_cache() def uni_formset_template(template_pack=TEMPLATE_PACK): return get_template("%s/uni_formset.html" % template_pack) @lru_cache() def uni_form_template(template_pack=TEMPLATE_PACK): return get_template("%s/uni_form.html" % template_pack) <|code_end|> , generate the next line using the imports in this file: from functools import lru_cache from django import template from django.conf import settings from django.forms import boundfield from django.forms.formsets import BaseFormSet from django.template import Context from django.template.loader import get_template from django.utils.safestring import mark_safe from crispy_forms.exceptions import CrispyError from crispy_forms.utils import TEMPLATE_PACK, flatatt and context (functions, classes, or occasionally code) from other files: # Path: crispy_forms/utils.py # TEMPLATE_PACK = SimpleLazyObject(get_template_pack) # # def flatatt(attrs): # """ # Convert a dictionary of attributes to a single string. # # Passed attributes are redirected to `django.forms.utils.flatatt()` # with replaced "_" (underscores) by "-" (dashes) in their names. # """ # return _flatatt({k.replace("_", "-"): v for k, v in attrs.items()}) . Output only the next line.
register = template.Library()
Predict the next line after this snippet: <|code_start|> @register.filter def is_password(field): return isinstance(field.field.widget, forms.PasswordInput) @register.filter def is_radioselect(field): return isinstance(field.field.widget, forms.RadioSelect) and not isinstance( field.field.widget, forms.CheckboxSelectMultiple ) @register.filter def is_select(field): return isinstance(field.field.widget, forms.Select) @register.filter def is_checkboxselectmultiple(field): return isinstance(field.field.widget, forms.CheckboxSelectMultiple) @register.filter def is_file(field): return isinstance(field.field.widget, forms.FileInput) @register.filter <|code_end|> using the current file's imports: from django import forms, template from django.conf import settings from django.template import Context, Variable, loader from crispy_forms.utils import get_template_pack and any relevant context from other files: # Path: crispy_forms/utils.py # def get_template_pack(): # return getattr(settings, "CRISPY_TEMPLATE_PACK", "bootstrap4") . Output only the next line.
def is_clearable_file(field):
Next line prediction: <|code_start|> class TemplateNameMixin: def get_template_name(self, template_pack): if "%s" in self.template: template = self.template % template_pack else: template = self.template return template <|code_end|> . Use current file imports: (from django.template import Template from django.template.loader import render_to_string from django.utils.html import conditional_escape from django.utils.text import slugify from crispy_forms.utils import TEMPLATE_PACK, flatatt, get_template_pack, render_field) and context including class names, function names, or small code snippets from other files: # Path: crispy_forms/utils.py # TEMPLATE_PACK = SimpleLazyObject(get_template_pack) # # def flatatt(attrs): # """ # Convert a dictionary of attributes to a single string. # # Passed attributes are redirected to `django.forms.utils.flatatt()` # with replaced "_" (underscores) by "-" (dashes) in their names. # """ # return _flatatt({k.replace("_", "-"): v for k, v in attrs.items()}) # # def get_template_pack(): # return getattr(settings, "CRISPY_TEMPLATE_PACK", "bootstrap4") # # def render_field( # noqa: C901 # field, # form, # context, # template=None, # labelclass=None, # layout_object=None, # attrs=None, # template_pack=TEMPLATE_PACK, # extra_context=None, # **kwargs, # ): # """ # Renders a django-crispy-forms field # # :param field: Can be a string or a Layout object like `Row`. If it's a layout # object, we call its render method, otherwise we instantiate a BoundField # and render it using default template 'CRISPY_TEMPLATE_PACK/field.html' # The field is added to a list that the form holds called `rendered_fields` # to avoid double rendering fields. # :param form: The form/formset to which that field belongs to. # :template: Template used for rendering the field. # :layout_object: If passed, it points to the Layout object that is being rendered. # We use it to store its bound fields in a list called `layout_object.bound_fields` # :attrs: Attributes for the field's widget # :template_pack: Name of the template pack to be used for rendering `field` # :extra_context: Dictionary to be added to context, added variables by the layout object # """ # added_keys = [] if extra_context is None else extra_context.keys() # with KeepContext(context, added_keys): # if field is None: # return "" # # FAIL_SILENTLY = getattr(settings, "CRISPY_FAIL_SILENTLY", True) # # if hasattr(field, "render"): # return field.render(form, context, template_pack=template_pack) # # try: # # Injecting HTML attributes into field's widget, Django handles rendering these # bound_field = form[field] # field_instance = bound_field.field # if attrs is not None: # widgets = getattr(field_instance.widget, "widgets", [field_instance.widget]) # # # We use attrs as a dictionary later, so here we make a copy # list_attrs = attrs # if isinstance(attrs, dict): # list_attrs = [attrs] * len(widgets) # # for index, (widget, attr) in enumerate(zip(widgets, list_attrs)): # if hasattr(field_instance.widget, "widgets"): # if "type" in attr and attr["type"] == "hidden": # field_instance.widget.widgets[index] = field_instance.hidden_widget(attr) # # else: # field_instance.widget.widgets[index].attrs.update(attr) # else: # if "type" in attr and attr["type"] == "hidden": # field_instance.widget = field_instance.hidden_widget(attr) # # else: # field_instance.widget.attrs.update(attr) # # except KeyError: # if not FAIL_SILENTLY: # raise Exception("Could not resolve form field '%s'." % field) # else: # field_instance = None # logging.warning("Could not resolve form field '%s'." % field, exc_info=sys.exc_info()) # # if hasattr(form, "rendered_fields"): # if field not in form.rendered_fields: # form.rendered_fields.add(field) # else: # if not FAIL_SILENTLY: # raise Exception("A field should only be rendered once: %s" % field) # else: # logging.warning("A field should only be rendered once: %s" % field, exc_info=sys.exc_info()) # # if field_instance is None: # html = "" # else: # if template is None: # if form.crispy_field_template is None: # template = default_field_template(template_pack) # else: # FormHelper.field_template set # template = get_template(form.crispy_field_template) # else: # template = get_template(template) # # # We save the Layout object's bound fields in the layout object's `bound_fields` list # if layout_object is not None: # if hasattr(layout_object, "bound_fields") and isinstance(layout_object.bound_fields, list): # layout_object.bound_fields.append(bound_field) # else: # layout_object.bound_fields = [bound_field] # # context.update( # { # "field": bound_field, # "labelclass": labelclass, # "flat_attrs": flatatt(attrs if isinstance(attrs, dict) else {}), # } # ) # if extra_context is not None: # context.update(extra_context) # # html = template.render(context.flatten()) # # return html . Output only the next line.
class LayoutObject(TemplateNameMixin):
Predict the next line for this snippet: <|code_start|> class TemplateNameMixin: def get_template_name(self, template_pack): if "%s" in self.template: <|code_end|> with the help of current file imports: from django.template import Template from django.template.loader import render_to_string from django.utils.html import conditional_escape from django.utils.text import slugify from crispy_forms.utils import TEMPLATE_PACK, flatatt, get_template_pack, render_field and context from other files: # Path: crispy_forms/utils.py # TEMPLATE_PACK = SimpleLazyObject(get_template_pack) # # def flatatt(attrs): # """ # Convert a dictionary of attributes to a single string. # # Passed attributes are redirected to `django.forms.utils.flatatt()` # with replaced "_" (underscores) by "-" (dashes) in their names. # """ # return _flatatt({k.replace("_", "-"): v for k, v in attrs.items()}) # # def get_template_pack(): # return getattr(settings, "CRISPY_TEMPLATE_PACK", "bootstrap4") # # def render_field( # noqa: C901 # field, # form, # context, # template=None, # labelclass=None, # layout_object=None, # attrs=None, # template_pack=TEMPLATE_PACK, # extra_context=None, # **kwargs, # ): # """ # Renders a django-crispy-forms field # # :param field: Can be a string or a Layout object like `Row`. If it's a layout # object, we call its render method, otherwise we instantiate a BoundField # and render it using default template 'CRISPY_TEMPLATE_PACK/field.html' # The field is added to a list that the form holds called `rendered_fields` # to avoid double rendering fields. # :param form: The form/formset to which that field belongs to. # :template: Template used for rendering the field. # :layout_object: If passed, it points to the Layout object that is being rendered. # We use it to store its bound fields in a list called `layout_object.bound_fields` # :attrs: Attributes for the field's widget # :template_pack: Name of the template pack to be used for rendering `field` # :extra_context: Dictionary to be added to context, added variables by the layout object # """ # added_keys = [] if extra_context is None else extra_context.keys() # with KeepContext(context, added_keys): # if field is None: # return "" # # FAIL_SILENTLY = getattr(settings, "CRISPY_FAIL_SILENTLY", True) # # if hasattr(field, "render"): # return field.render(form, context, template_pack=template_pack) # # try: # # Injecting HTML attributes into field's widget, Django handles rendering these # bound_field = form[field] # field_instance = bound_field.field # if attrs is not None: # widgets = getattr(field_instance.widget, "widgets", [field_instance.widget]) # # # We use attrs as a dictionary later, so here we make a copy # list_attrs = attrs # if isinstance(attrs, dict): # list_attrs = [attrs] * len(widgets) # # for index, (widget, attr) in enumerate(zip(widgets, list_attrs)): # if hasattr(field_instance.widget, "widgets"): # if "type" in attr and attr["type"] == "hidden": # field_instance.widget.widgets[index] = field_instance.hidden_widget(attr) # # else: # field_instance.widget.widgets[index].attrs.update(attr) # else: # if "type" in attr and attr["type"] == "hidden": # field_instance.widget = field_instance.hidden_widget(attr) # # else: # field_instance.widget.attrs.update(attr) # # except KeyError: # if not FAIL_SILENTLY: # raise Exception("Could not resolve form field '%s'." % field) # else: # field_instance = None # logging.warning("Could not resolve form field '%s'." % field, exc_info=sys.exc_info()) # # if hasattr(form, "rendered_fields"): # if field not in form.rendered_fields: # form.rendered_fields.add(field) # else: # if not FAIL_SILENTLY: # raise Exception("A field should only be rendered once: %s" % field) # else: # logging.warning("A field should only be rendered once: %s" % field, exc_info=sys.exc_info()) # # if field_instance is None: # html = "" # else: # if template is None: # if form.crispy_field_template is None: # template = default_field_template(template_pack) # else: # FormHelper.field_template set # template = get_template(form.crispy_field_template) # else: # template = get_template(template) # # # We save the Layout object's bound fields in the layout object's `bound_fields` list # if layout_object is not None: # if hasattr(layout_object, "bound_fields") and isinstance(layout_object.bound_fields, list): # layout_object.bound_fields.append(bound_field) # else: # layout_object.bound_fields = [bound_field] # # context.update( # { # "field": bound_field, # "labelclass": labelclass, # "flat_attrs": flatatt(attrs if isinstance(attrs, dict) else {}), # } # ) # if extra_context is not None: # context.update(extra_context) # # html = template.render(context.flatten()) # # return html , which may contain function names, class names, or code. Output only the next line.
template = self.template % template_pack
Continue the code snippet: <|code_start|> class TemplateNameMixin: def get_template_name(self, template_pack): if "%s" in self.template: template = self.template % template_pack else: template = self.template return template class LayoutObject(TemplateNameMixin): def __getitem__(self, slice): return self.fields[slice] def __setitem__(self, slice, value): self.fields[slice] = value def __delitem__(self, slice): del self.fields[slice] def __len__(self): <|code_end|> . Use current file imports: from django.template import Template from django.template.loader import render_to_string from django.utils.html import conditional_escape from django.utils.text import slugify from crispy_forms.utils import TEMPLATE_PACK, flatatt, get_template_pack, render_field and context (classes, functions, or code) from other files: # Path: crispy_forms/utils.py # TEMPLATE_PACK = SimpleLazyObject(get_template_pack) # # def flatatt(attrs): # """ # Convert a dictionary of attributes to a single string. # # Passed attributes are redirected to `django.forms.utils.flatatt()` # with replaced "_" (underscores) by "-" (dashes) in their names. # """ # return _flatatt({k.replace("_", "-"): v for k, v in attrs.items()}) # # def get_template_pack(): # return getattr(settings, "CRISPY_TEMPLATE_PACK", "bootstrap4") # # def render_field( # noqa: C901 # field, # form, # context, # template=None, # labelclass=None, # layout_object=None, # attrs=None, # template_pack=TEMPLATE_PACK, # extra_context=None, # **kwargs, # ): # """ # Renders a django-crispy-forms field # # :param field: Can be a string or a Layout object like `Row`. If it's a layout # object, we call its render method, otherwise we instantiate a BoundField # and render it using default template 'CRISPY_TEMPLATE_PACK/field.html' # The field is added to a list that the form holds called `rendered_fields` # to avoid double rendering fields. # :param form: The form/formset to which that field belongs to. # :template: Template used for rendering the field. # :layout_object: If passed, it points to the Layout object that is being rendered. # We use it to store its bound fields in a list called `layout_object.bound_fields` # :attrs: Attributes for the field's widget # :template_pack: Name of the template pack to be used for rendering `field` # :extra_context: Dictionary to be added to context, added variables by the layout object # """ # added_keys = [] if extra_context is None else extra_context.keys() # with KeepContext(context, added_keys): # if field is None: # return "" # # FAIL_SILENTLY = getattr(settings, "CRISPY_FAIL_SILENTLY", True) # # if hasattr(field, "render"): # return field.render(form, context, template_pack=template_pack) # # try: # # Injecting HTML attributes into field's widget, Django handles rendering these # bound_field = form[field] # field_instance = bound_field.field # if attrs is not None: # widgets = getattr(field_instance.widget, "widgets", [field_instance.widget]) # # # We use attrs as a dictionary later, so here we make a copy # list_attrs = attrs # if isinstance(attrs, dict): # list_attrs = [attrs] * len(widgets) # # for index, (widget, attr) in enumerate(zip(widgets, list_attrs)): # if hasattr(field_instance.widget, "widgets"): # if "type" in attr and attr["type"] == "hidden": # field_instance.widget.widgets[index] = field_instance.hidden_widget(attr) # # else: # field_instance.widget.widgets[index].attrs.update(attr) # else: # if "type" in attr and attr["type"] == "hidden": # field_instance.widget = field_instance.hidden_widget(attr) # # else: # field_instance.widget.attrs.update(attr) # # except KeyError: # if not FAIL_SILENTLY: # raise Exception("Could not resolve form field '%s'." % field) # else: # field_instance = None # logging.warning("Could not resolve form field '%s'." % field, exc_info=sys.exc_info()) # # if hasattr(form, "rendered_fields"): # if field not in form.rendered_fields: # form.rendered_fields.add(field) # else: # if not FAIL_SILENTLY: # raise Exception("A field should only be rendered once: %s" % field) # else: # logging.warning("A field should only be rendered once: %s" % field, exc_info=sys.exc_info()) # # if field_instance is None: # html = "" # else: # if template is None: # if form.crispy_field_template is None: # template = default_field_template(template_pack) # else: # FormHelper.field_template set # template = get_template(form.crispy_field_template) # else: # template = get_template(template) # # # We save the Layout object's bound fields in the layout object's `bound_fields` list # if layout_object is not None: # if hasattr(layout_object, "bound_fields") and isinstance(layout_object.bound_fields, list): # layout_object.bound_fields.append(bound_field) # else: # layout_object.bound_fields = [bound_field] # # context.update( # { # "field": bound_field, # "labelclass": labelclass, # "flat_attrs": flatatt(attrs if isinstance(attrs, dict) else {}), # } # ) # if extra_context is not None: # context.update(extra_context) # # html = template.render(context.flatten()) # # return html . Output only the next line.
return len(self.fields)
Given snippet: <|code_start|>top top-left top-right move-to-bottom move-to-bottom-left move-to-bottom-right move-to-center move-to-left move-to-right move-to-top move-to-top-left move-to-top-right bordered bordered always-above always-above always-below always-below horizontal-maximize horizontal-maximize vertical-maximize vertical-maximize shade shade fullscreen fullscreen all-desktops <|code_end|> , continue by predicting the next line. Consider current file imports: import logging, shlex, subprocess # nosec import time from functional_harness.env_general import background_proc from functional_harness.x_server import x_server from argparse import ArgumentParser, RawDescriptionHelpFormatter and context: # Path: functional_harness/env_general.py # @contextmanager # def background_proc(argv, verbose=False, *args: Any, **kwargs: Any # ) -> Generator[None, None, None]: # """Context manager for scoping the lifetime of a ``subprocess.Popen`` call # # :param argv: The command to be executed # :param verbose: If :any:`False`, redirect the X server's ``stdout`` and # ``stderr`` to :file:`/dev/null` # :param args: Positional arguments to pass to :class:`subprocess.Popen` # :param kwargs: Keyword arguments to pass to :class:`subprocess.Popen` # """ # if verbose: # popen_obj = subprocess.Popen(argv, *args, **kwargs) # nosec # else: # popen_obj = subprocess.Popen(argv, # type: ignore # stderr=subprocess.STDOUT, stdout=subprocess.DEVNULL, # *args, **kwargs) # try: # yield # finally: # popen_obj.terminate() # # Path: functional_harness/x_server.py # @contextmanager # def x_server(argv: List[str], screens: Dict[int, str] # ) -> Generator[Dict[str, str], None, None]: # """Context manager to launch and then clean up an X server. # # :param argv: The command to launch the test X server and # any arguments not relating to defining the attached screens. # :param screens: A :any:`dict <dict>` mapping screen numbers to # ``WxHxDEPTH`` strings. (eg. ``{0: '1024x768x32'}``) # # :raises subprocess.CalledProcessError: The X server or :command:`xauth` # failed unexpectedly. # :raises FileNotFoundError: Could not find either the :command:`xauth` # command or ``argv[0]``. # :raises PermissionError: Somehow, we lack write permission inside a # directory created by :func:`tempfile.mkdtemp`. # :raises ValueError: ``argv[0]`` was not an X server binary we know how to # specify monitor rectangles for. # (either :command:`Xvfb` or :command:`Xephyr`) # :raises UnicodeDecodeError: The X server's ``-displayfd`` option wrote # a value to the given FD which could not be decoded as UTF-8 when it # should have been part of the 7-bit ASCII subset of UTF-8. # # .. todo:: Either don't accept an arbitrary ``argv`` string as input to # :func:`x_server` or default to a behaviour likely to work with other X # servers rather than erroring out. # """ # # Check for missing requirements # for cmd in ['xauth', argv[0]]: # if not find_executable(cmd): # # pylint: disable=undefined-variable # raise FileNotFoundError( # NOQA # "Cannot find required command {!r}".format(cmd)) # # x_server = None # tempdir = tempfile.mkdtemp() # try: # # Because random.getrandbits gets interpreted as a variable length, # # *ensure* we've got the right number of hex digits # magic_cookie = b'' # while len(magic_cookie) < 32: # magic_cookie += hex(random.getrandbits(128))[2:34].encode('ascii') # magic_cookie = magic_cookie[:32] # assert len(magic_cookie) == 32, len(magic_cookie) # nosec # xauthfile = os.path.join(tempdir, 'Xauthority') # env = {'XAUTHORITY': xauthfile} # # open(xauthfile, 'w').close() # create empty file # # # Convert `screens` into the format Xorg servers expect # screen_argv = [] # for screen_num, screen_geom in screens.items(): # if 'Xvfb' in argv[0]: # screen_argv.extend(['-screen', '%d' % screen_num, screen_geom]) # elif 'Xephyr' in argv[0]: # screen_argv.extend(['-screen', screen_geom]) # else: # raise ValueError("Unrecognized X server. Cannot infer format " # "for specifying screen geometry.") # # # Initialize an X server on a free display number # x_server, display_num = _init_x_server(argv + screen_argv) # # # Set up the environment and authorization # env['DISPLAY'] = ':%s' % display_num.decode('utf8') # subprocess.check_call( # nosec # ['xauth', 'add', env['DISPLAY'], '.', magic_cookie], # env=env) # # FIXME: This xauth call once had a random failure. Retry. # # with env_vars(env): # yield env # # finally: # if x_server: # x_server.terminate() # shutil.rmtree(tempdir) which might include code, classes, or functions. Output only the next line.
all-desktops
Given the code snippet: <|code_start|>fullscreen fullscreen all-desktops all-desktops trigger-move trigger-resize workspace-send-down workspace-go-down workspace-send-up workspace-go-up workspace-send-left workspace-go-left workspace-send-right workspace-go-right workspace-send-next workspace-go-next workspace-send-prev workspace-go-prev show-desktop show-desktop maximize <|code_end|> , generate the next line using the imports in this file: import logging, shlex, subprocess # nosec import time from functional_harness.env_general import background_proc from functional_harness.x_server import x_server from argparse import ArgumentParser, RawDescriptionHelpFormatter and context (functions, classes, or occasionally code) from other files: # Path: functional_harness/env_general.py # @contextmanager # def background_proc(argv, verbose=False, *args: Any, **kwargs: Any # ) -> Generator[None, None, None]: # """Context manager for scoping the lifetime of a ``subprocess.Popen`` call # # :param argv: The command to be executed # :param verbose: If :any:`False`, redirect the X server's ``stdout`` and # ``stderr`` to :file:`/dev/null` # :param args: Positional arguments to pass to :class:`subprocess.Popen` # :param kwargs: Keyword arguments to pass to :class:`subprocess.Popen` # """ # if verbose: # popen_obj = subprocess.Popen(argv, *args, **kwargs) # nosec # else: # popen_obj = subprocess.Popen(argv, # type: ignore # stderr=subprocess.STDOUT, stdout=subprocess.DEVNULL, # *args, **kwargs) # try: # yield # finally: # popen_obj.terminate() # # Path: functional_harness/x_server.py # @contextmanager # def x_server(argv: List[str], screens: Dict[int, str] # ) -> Generator[Dict[str, str], None, None]: # """Context manager to launch and then clean up an X server. # # :param argv: The command to launch the test X server and # any arguments not relating to defining the attached screens. # :param screens: A :any:`dict <dict>` mapping screen numbers to # ``WxHxDEPTH`` strings. (eg. ``{0: '1024x768x32'}``) # # :raises subprocess.CalledProcessError: The X server or :command:`xauth` # failed unexpectedly. # :raises FileNotFoundError: Could not find either the :command:`xauth` # command or ``argv[0]``. # :raises PermissionError: Somehow, we lack write permission inside a # directory created by :func:`tempfile.mkdtemp`. # :raises ValueError: ``argv[0]`` was not an X server binary we know how to # specify monitor rectangles for. # (either :command:`Xvfb` or :command:`Xephyr`) # :raises UnicodeDecodeError: The X server's ``-displayfd`` option wrote # a value to the given FD which could not be decoded as UTF-8 when it # should have been part of the 7-bit ASCII subset of UTF-8. # # .. todo:: Either don't accept an arbitrary ``argv`` string as input to # :func:`x_server` or default to a behaviour likely to work with other X # servers rather than erroring out. # """ # # Check for missing requirements # for cmd in ['xauth', argv[0]]: # if not find_executable(cmd): # # pylint: disable=undefined-variable # raise FileNotFoundError( # NOQA # "Cannot find required command {!r}".format(cmd)) # # x_server = None # tempdir = tempfile.mkdtemp() # try: # # Because random.getrandbits gets interpreted as a variable length, # # *ensure* we've got the right number of hex digits # magic_cookie = b'' # while len(magic_cookie) < 32: # magic_cookie += hex(random.getrandbits(128))[2:34].encode('ascii') # magic_cookie = magic_cookie[:32] # assert len(magic_cookie) == 32, len(magic_cookie) # nosec # xauthfile = os.path.join(tempdir, 'Xauthority') # env = {'XAUTHORITY': xauthfile} # # open(xauthfile, 'w').close() # create empty file # # # Convert `screens` into the format Xorg servers expect # screen_argv = [] # for screen_num, screen_geom in screens.items(): # if 'Xvfb' in argv[0]: # screen_argv.extend(['-screen', '%d' % screen_num, screen_geom]) # elif 'Xephyr' in argv[0]: # screen_argv.extend(['-screen', screen_geom]) # else: # raise ValueError("Unrecognized X server. Cannot infer format " # "for specifying screen geometry.") # # # Initialize an X server on a free display number # x_server, display_num = _init_x_server(argv + screen_argv) # # # Set up the environment and authorization # env['DISPLAY'] = ':%s' % display_num.decode('utf8') # subprocess.check_call( # nosec # ['xauth', 'add', env['DISPLAY'], '.', magic_cookie], # env=env) # # FIXME: This xauth call once had a random failure. Retry. # # with env_vars(env): # yield env # # finally: # if x_server: # x_server.terminate() # shutil.rmtree(tempdir) . Output only the next line.
maximize
Given the code snippet: <|code_start|># # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # from handson.util import read_user_data log = logging.getLogger(__name__) class Region(object): def __init__(self, args): self.args = args self._region = { 'ec2_conn': None, 'region_str': None, 'vpc_conn': None, 'az': None } <|code_end|> , generate the next line using the imports in this file: import boto.ec2 import boto.vpc import logging from handson.myyaml import stanza and context (functions, classes, or occasionally code) from other files: # Path: handson/myyaml.py # def stanza(k, new_val=None): # global _cache # load() # if new_val is not None: # assert k in tree_stanzas.keys(), ( # "YAML stanza {!r} not permitted".format(k) # ) # _cache[k] = new_val # write() # stanza_is_sane(k) # return _cache[k] . Output only the next line.
def region(self):
Here is a snippet: <|code_start|># # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of ceph-auto-aws nor the names of its contributors may be # used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # import logging class TestRegion(SetUp, unittest.TestCase): def test_region_cache(self): self.reset_yaml() handson.myyaml.yaml_file_name('./aws.yaml') <|code_end|> . Write the next line using the current file imports: import handson.myyaml import unittest from handson.test_setup import SetUp from handson.region import Region and context from other files: # Path: handson/test_setup.py # class SetUp(object): # # def setUp(self): # # try: # # os.remove('./aws.yaml') # # except OSError: # # pass # pass # # def reset_yaml(self): # myyaml.initialize_internal_buffers() # myyaml.yaml_file_name('./aws.yaml') # myyaml.load() # # Path: handson/region.py # class Region(object): # # def __init__(self, args): # self.args = args # self._region = { # 'ec2_conn': None, # 'region_str': None, # 'vpc_conn': None, # 'az': None # } # # def region(self): # """ # gets region from yaml, default to eu-west-1 # """ # if self._region['region_str']: # return self._region['region_str'] # self._region['region_str'] = stanza('region')['region_str'] # log.debug("Region is {}".format(self._region['region_str'])) # return self._region['region_str'] # # def availability_zone(self): # """ # gets availability_zone from yaml, default to None # """ # if self._region['az']: # return self._region['az'] # self._region['az'] = stanza('region')['availability_zone'] # if self._region['az']: # log.debug("Availability zone is {}" # .format(self._region['az'])) # return self._region['az'] # # def ec2(self): # """ # fetch ec2 connection, open if necessary # """ # if self._region['ec2_conn']: # return self._region['ec2_conn'] # region = self.region() # if self._region['ec2_conn'] is None: # log.debug("Connecting to EC2 region {}".format(region)) # self._region['ec2_conn'] = boto.ec2.connect_to_region( # region, # is_secure=False # ) # assert self._region['ec2_conn'] is not None, ( # ("Failed to connect to EC2 service in region {!r}" # .format(region))) # return self._region['ec2_conn'] # # def vpc(self): # """ # fetch vpc connection, open if necessary # """ # if self._region['vpc_conn']: # return self._region['vpc_conn'] # region = self.region() # if self._region['vpc_conn'] is None: # log.debug("Connecting to VPC region {}".format(region)) # self._region['vpc_conn'] = boto.vpc.connect_to_region( # region, # is_secure=False # ) # assert self._region['vpc_conn'] is not None, ( # ("Failed to connect to VPC service in region {!r}" # .format(region))) # return self._region['vpc_conn'] , which may include functions, classes, or code. Output only the next line.
handson.myyaml.load()
Next line prediction: <|code_start|># and/or other materials provided with the distribution. # # * Neither the name of ceph-auto-aws nor the names of its contributors may be # used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # import logging class TestRegion(SetUp, unittest.TestCase): def test_region_cache(self): self.reset_yaml() handson.myyaml.yaml_file_name('./aws.yaml') handson.myyaml.load() r = Region({}) r.region() # loads from yaml <|code_end|> . Use current file imports: (import handson.myyaml import unittest from handson.test_setup import SetUp from handson.region import Region) and context including class names, function names, or small code snippets from other files: # Path: handson/test_setup.py # class SetUp(object): # # def setUp(self): # # try: # # os.remove('./aws.yaml') # # except OSError: # # pass # pass # # def reset_yaml(self): # myyaml.initialize_internal_buffers() # myyaml.yaml_file_name('./aws.yaml') # myyaml.load() # # Path: handson/region.py # class Region(object): # # def __init__(self, args): # self.args = args # self._region = { # 'ec2_conn': None, # 'region_str': None, # 'vpc_conn': None, # 'az': None # } # # def region(self): # """ # gets region from yaml, default to eu-west-1 # """ # if self._region['region_str']: # return self._region['region_str'] # self._region['region_str'] = stanza('region')['region_str'] # log.debug("Region is {}".format(self._region['region_str'])) # return self._region['region_str'] # # def availability_zone(self): # """ # gets availability_zone from yaml, default to None # """ # if self._region['az']: # return self._region['az'] # self._region['az'] = stanza('region')['availability_zone'] # if self._region['az']: # log.debug("Availability zone is {}" # .format(self._region['az'])) # return self._region['az'] # # def ec2(self): # """ # fetch ec2 connection, open if necessary # """ # if self._region['ec2_conn']: # return self._region['ec2_conn'] # region = self.region() # if self._region['ec2_conn'] is None: # log.debug("Connecting to EC2 region {}".format(region)) # self._region['ec2_conn'] = boto.ec2.connect_to_region( # region, # is_secure=False # ) # assert self._region['ec2_conn'] is not None, ( # ("Failed to connect to EC2 service in region {!r}" # .format(region))) # return self._region['ec2_conn'] # # def vpc(self): # """ # fetch vpc connection, open if necessary # """ # if self._region['vpc_conn']: # return self._region['vpc_conn'] # region = self.region() # if self._region['vpc_conn'] is None: # log.debug("Connecting to VPC region {}".format(region)) # self._region['vpc_conn'] = boto.vpc.connect_to_region( # region, # is_secure=False # ) # assert self._region['vpc_conn'] is not None, ( # ("Failed to connect to VPC service in region {!r}" # .format(region))) # return self._region['vpc_conn'] . Output only the next line.
r.region() # loads from cache
Predict the next line for this snippet: <|code_start|> def create_vpc(self, *_): return {'id': 'DummyID', 'cidr_block': '10.0.0.0/16'} def get_all_vpcs(self, *_): return ['DummyValue'] class TestHandsOn(SetUp, unittest.TestCase): def test_init(self): m = main.HandsOn() with self.assertRaises(SystemExit) as cm: m.parser.parse_args([ '-h', ]) self.assertEqual(cm.exception.code, 0) with self.assertRaises(SystemExit) as cm: m.parser.parse_args([ '--version', ]) self.assertEqual(cm.exception.code, 0) def test_install_01(self): m = main.HandsOn() with self.assertRaises(AssertionError): m.run([ '-v', 'install', 'delegates', '1-50', <|code_end|> with the help of current file imports: import logging import unittest from handson import main from handson.test_setup import SetUp from mock import patch from yaml.parser import ParserError and context from other files: # Path: handson/main.py # class HandsOn(object): # def __init__(self): # def run(self, argv): # # Path: handson/test_setup.py # class SetUp(object): # # def setUp(self): # # try: # # os.remove('./aws.yaml') # # except OSError: # # pass # pass # # def reset_yaml(self): # myyaml.initialize_internal_buffers() # myyaml.yaml_file_name('./aws.yaml') # myyaml.load() , which may contain function names, class names, or code. Output only the next line.
])
Based on the snippet: <|code_start|># AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # def mock_connect(*_): return 'DummyValue' def mock_connect_ec2(*_): return 'DummyValue' class MockMyYaml(object): def write(self): return True class MockVPCConnection(object): <|code_end|> , predict the immediate next line with the help of imports: import logging import unittest from handson import main from handson.test_setup import SetUp from mock import patch from yaml.parser import ParserError and context (classes, functions, sometimes code) from other files: # Path: handson/main.py # class HandsOn(object): # def __init__(self): # def run(self, argv): # # Path: handson/test_setup.py # class SetUp(object): # # def setUp(self): # # try: # # os.remove('./aws.yaml') # # except OSError: # # pass # pass # # def reset_yaml(self): # myyaml.initialize_internal_buffers() # myyaml.yaml_file_name('./aws.yaml') # myyaml.load() . Output only the next line.
def create_vpc(self, *_):
Here is a snippet: <|code_start|># and/or other materials provided with the distribution. # # * Neither the name of ceph-auto-aws nor the names of its contributors may be # used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # import logging class TestVPC(SetUp, unittest.TestCase): def test_vpc_cache(self): self.reset_yaml() handson.myyaml.yaml_file_name('./aws.yaml') handson.myyaml.load() v = VPC({}) v.vpc_obj() # loads from yaml <|code_end|> . Write the next line using the current file imports: import handson.myyaml import unittest from handson.test_setup import SetUp from handson.vpc import VPC and context from other files: # Path: handson/test_setup.py # class SetUp(object): # # def setUp(self): # # try: # # os.remove('./aws.yaml') # # except OSError: # # pass # pass # # def reset_yaml(self): # myyaml.initialize_internal_buffers() # myyaml.yaml_file_name('./aws.yaml') # myyaml.load() # # Path: handson/vpc.py # class VPC(Region): # # def __init__(self, args): # super(VPC, self).__init__(args) # self.args = args # self._vpc = { # 'vpc_obj': None # } # # def vpc_obj(self, create=False, dry_run=False, quiet=False): # """ # fetch VPC object, create if necessary # """ # # # # cached VPC object # if self._vpc['vpc_obj'] is not None: # return self._vpc['vpc_obj'] # # # # non-cached # vpc_stanza = stanza('vpc') # vpc_conn = self.vpc() # if len(vpc_stanza) == 0: # pragma: no cover # # # # create VPC # if create: # if dry_run: # log.info("Dry run: do nothing") # vpc_obj = None # else: # log.info("VPC ID not specified in yaml: creating VPC") # vpc_obj = vpc_conn.create_vpc('10.0.0.0/16') # vpc_stanza['id'] = vpc_obj.id # vpc_stanza['cidr_block'] = vpc_obj.cidr_block # log.info("New VPC ID {} created with CIDR block {}".format( # vpc_obj.id, vpc_obj.cidr_block # )) # apply_tag(vpc_obj, tag='Name', val=stanza('nametag')) # self._vpc['vpc_obj'] = vpc_obj # stanza('vpc', { # 'cidr_block': vpc_obj.cidr_block, # 'id': vpc_obj.id # }) # vpc_conn.modify_vpc_attribute( # vpc_obj.id, # enable_dns_support=True, # ) # vpc_conn.modify_vpc_attribute( # vpc_obj.id, # enable_dns_hostnames=True, # ) # else: # log.info("VPC ID not specified in yaml: nothing to do") # vpc_obj = None # return vpc_obj # # # # existing VPC # log.debug("VPD ID specified in yaml: fetching it") # vpc_id = vpc_stanza['id'] # if not quiet: # log.info("VPC ID according to yaml is {}".format(vpc_id)) # vpc_list = vpc_conn.get_all_vpcs(vpc_ids=vpc_id) # assert len(vpc_list) == 1, ( # "VPC ID {} does not exist".format(vpc_id)) # vpc_obj = vpc_list[0] # cidr_block = vpc_obj.cidr_block # assert cidr_block == '10.0.0.0/16', ( # ("VPC ID {} exists, but has wrong CIDR block {} " # "(should be 10.0.0.0/16)").format(vpc_id, cidr_block)) # if not quiet: # log.info("VPC ID is {}, CIDR block is {}".format( # vpc_stanza['id'], vpc_stanza['cidr_block'], # )) # self._vpc['vpc_obj'] = vpc_obj # vpc_conn.modify_vpc_attribute( # vpc_obj.id, # enable_dns_support=True, # ) # vpc_conn.modify_vpc_attribute( # vpc_obj.id, # enable_dns_hostnames=True, # ) # return vpc_obj # # def wipeout(self, dry_run=False): # vpc_obj = self.vpc_obj(create=False, dry_run=dry_run) # if vpc_obj and not dry_run: # log.info("Wiping out VPC ID {}".format(vpc_obj.id)) # self.vpc().delete_vpc(vpc_obj.id) # stanza('vpc', {}) # else: # log.info("No VPC in YAML; nothing to do") # return None , which may include functions, classes, or code. Output only the next line.
v.vpc_obj() # loads from cache
Next line prediction: <|code_start|> k_stanza = stanza('keypairs') log.debug("Keypairs stanza is {!r}".format(k_stanza)) assert type(k_stanza) == dict d = self._keypair['delegate'] if d in k_stanza: if 'keyname' in k_stanza[d]: if k_stanza[d]['keyname']: self._keypair['keyname'] = k_stanza[d]['keyname'] return k_stanza[d]['keyname'] return None def get_key_material(self, keyname): fn = "keys/{}.pub".format(keyname) return get_file_as_string(fn) def get_keypair_from_aws(self): keyname_from_yaml = self.get_keyname_from_yaml() if keyname_from_yaml: log.debug("Getting keypair {} from AWS".format(keyname_from_yaml)) k_list = self.ec2().get_all_key_pairs(keynames=[keyname_from_yaml]) log.info("Keypair object {} fetched from AWS". format(keyname_from_yaml)) self._keypair['keypair_obj'] = k_list[0] return True return False def import_keypair(self, dry_run): d = self._keypair['delegate'] if dry_run: log.info("Dry run: doing nothing") <|code_end|> . Use current file imports: (import logging from handson.myyaml import stanza from handson.region import Region from handson.util import get_file_as_string) and context including class names, function names, or small code snippets from other files: # Path: handson/myyaml.py # def stanza(k, new_val=None): # global _cache # load() # if new_val is not None: # assert k in tree_stanzas.keys(), ( # "YAML stanza {!r} not permitted".format(k) # ) # _cache[k] = new_val # write() # stanza_is_sane(k) # return _cache[k] # # Path: handson/region.py # class Region(object): # # def __init__(self, args): # self.args = args # self._region = { # 'ec2_conn': None, # 'region_str': None, # 'vpc_conn': None, # 'az': None # } # # def region(self): # """ # gets region from yaml, default to eu-west-1 # """ # if self._region['region_str']: # return self._region['region_str'] # self._region['region_str'] = stanza('region')['region_str'] # log.debug("Region is {}".format(self._region['region_str'])) # return self._region['region_str'] # # def availability_zone(self): # """ # gets availability_zone from yaml, default to None # """ # if self._region['az']: # return self._region['az'] # self._region['az'] = stanza('region')['availability_zone'] # if self._region['az']: # log.debug("Availability zone is {}" # .format(self._region['az'])) # return self._region['az'] # # def ec2(self): # """ # fetch ec2 connection, open if necessary # """ # if self._region['ec2_conn']: # return self._region['ec2_conn'] # region = self.region() # if self._region['ec2_conn'] is None: # log.debug("Connecting to EC2 region {}".format(region)) # self._region['ec2_conn'] = boto.ec2.connect_to_region( # region, # is_secure=False # ) # assert self._region['ec2_conn'] is not None, ( # ("Failed to connect to EC2 service in region {!r}" # .format(region))) # return self._region['ec2_conn'] # # def vpc(self): # """ # fetch vpc connection, open if necessary # """ # if self._region['vpc_conn']: # return self._region['vpc_conn'] # region = self.region() # if self._region['vpc_conn'] is None: # log.debug("Connecting to VPC region {}".format(region)) # self._region['vpc_conn'] = boto.vpc.connect_to_region( # region, # is_secure=False # ) # assert self._region['vpc_conn'] is not None, ( # ("Failed to connect to VPC service in region {!r}" # .format(region))) # return self._region['vpc_conn'] # # Path: handson/util.py # def get_file_as_string(fn): # """ # Given a filename, returns the file's contents in a string. # """ # r = '' # with open(fn) as fh: # r = fh.read() # fh.close() # return r . Output only the next line.
return None
Predict the next line after this snippet: <|code_start|> k_mat = self.get_key_material(k_name) k_obj = self.ec2().import_key_pair(k_name, k_mat) log.info("Keypair {} imported to AWS".format(k_name)) self._keypair['keypair_obj'] = k_obj self._keypair['key_name'] = k_name k_stanza = stanza('keypairs') k_stanza[d] = {} k_stanza[d]['keyname'] = k_name stanza('keypairs', k_stanza) def keypair_obj(self, import_ok=False, dry_run=False): if self._keypair['keypair_obj'] is not None: return self._keypair['keypair_obj'] d = self._keypair['delegate'] if self.get_keypair_from_aws(): return self._keypair['keypair_obj'] log.info("Delegate {} keypair not imported yet: importing".format(d)) assert import_ok, ( "Delegate {} keypair should be imported, but import not allowed" .format(d) ) k_obj = self.import_keypair(dry_run) return k_obj def wipeout(self, dry_run=False): k_name = self.get_keyname_from_yaml(self) if k_name: # wipeout pass log.info("Delegate {} has no keypair in YAML: doing nothing" <|code_end|> using the current file's imports: import logging from handson.myyaml import stanza from handson.region import Region from handson.util import get_file_as_string and any relevant context from other files: # Path: handson/myyaml.py # def stanza(k, new_val=None): # global _cache # load() # if new_val is not None: # assert k in tree_stanzas.keys(), ( # "YAML stanza {!r} not permitted".format(k) # ) # _cache[k] = new_val # write() # stanza_is_sane(k) # return _cache[k] # # Path: handson/region.py # class Region(object): # # def __init__(self, args): # self.args = args # self._region = { # 'ec2_conn': None, # 'region_str': None, # 'vpc_conn': None, # 'az': None # } # # def region(self): # """ # gets region from yaml, default to eu-west-1 # """ # if self._region['region_str']: # return self._region['region_str'] # self._region['region_str'] = stanza('region')['region_str'] # log.debug("Region is {}".format(self._region['region_str'])) # return self._region['region_str'] # # def availability_zone(self): # """ # gets availability_zone from yaml, default to None # """ # if self._region['az']: # return self._region['az'] # self._region['az'] = stanza('region')['availability_zone'] # if self._region['az']: # log.debug("Availability zone is {}" # .format(self._region['az'])) # return self._region['az'] # # def ec2(self): # """ # fetch ec2 connection, open if necessary # """ # if self._region['ec2_conn']: # return self._region['ec2_conn'] # region = self.region() # if self._region['ec2_conn'] is None: # log.debug("Connecting to EC2 region {}".format(region)) # self._region['ec2_conn'] = boto.ec2.connect_to_region( # region, # is_secure=False # ) # assert self._region['ec2_conn'] is not None, ( # ("Failed to connect to EC2 service in region {!r}" # .format(region))) # return self._region['ec2_conn'] # # def vpc(self): # """ # fetch vpc connection, open if necessary # """ # if self._region['vpc_conn']: # return self._region['vpc_conn'] # region = self.region() # if self._region['vpc_conn'] is None: # log.debug("Connecting to VPC region {}".format(region)) # self._region['vpc_conn'] = boto.vpc.connect_to_region( # region, # is_secure=False # ) # assert self._region['vpc_conn'] is not None, ( # ("Failed to connect to VPC service in region {!r}" # .format(region))) # return self._region['vpc_conn'] # # Path: handson/util.py # def get_file_as_string(fn): # """ # Given a filename, returns the file's contents in a string. # """ # r = '' # with open(fn) as fh: # r = fh.read() # fh.close() # return r . Output only the next line.
.format(self._keypair['delegate']))
Given snippet: <|code_start|> return None def get_key_material(self, keyname): fn = "keys/{}.pub".format(keyname) return get_file_as_string(fn) def get_keypair_from_aws(self): keyname_from_yaml = self.get_keyname_from_yaml() if keyname_from_yaml: log.debug("Getting keypair {} from AWS".format(keyname_from_yaml)) k_list = self.ec2().get_all_key_pairs(keynames=[keyname_from_yaml]) log.info("Keypair object {} fetched from AWS". format(keyname_from_yaml)) self._keypair['keypair_obj'] = k_list[0] return True return False def import_keypair(self, dry_run): d = self._keypair['delegate'] if dry_run: log.info("Dry run: doing nothing") return None # we pitifully assume the user has already run generate-keys.sh k_name = "{}-d{}".format(stanza('keyname'), d) k_mat = self.get_key_material(k_name) k_obj = self.ec2().import_key_pair(k_name, k_mat) log.info("Keypair {} imported to AWS".format(k_name)) self._keypair['keypair_obj'] = k_obj self._keypair['key_name'] = k_name k_stanza = stanza('keypairs') <|code_end|> , continue by predicting the next line. Consider current file imports: import logging from handson.myyaml import stanza from handson.region import Region from handson.util import get_file_as_string and context: # Path: handson/myyaml.py # def stanza(k, new_val=None): # global _cache # load() # if new_val is not None: # assert k in tree_stanzas.keys(), ( # "YAML stanza {!r} not permitted".format(k) # ) # _cache[k] = new_val # write() # stanza_is_sane(k) # return _cache[k] # # Path: handson/region.py # class Region(object): # # def __init__(self, args): # self.args = args # self._region = { # 'ec2_conn': None, # 'region_str': None, # 'vpc_conn': None, # 'az': None # } # # def region(self): # """ # gets region from yaml, default to eu-west-1 # """ # if self._region['region_str']: # return self._region['region_str'] # self._region['region_str'] = stanza('region')['region_str'] # log.debug("Region is {}".format(self._region['region_str'])) # return self._region['region_str'] # # def availability_zone(self): # """ # gets availability_zone from yaml, default to None # """ # if self._region['az']: # return self._region['az'] # self._region['az'] = stanza('region')['availability_zone'] # if self._region['az']: # log.debug("Availability zone is {}" # .format(self._region['az'])) # return self._region['az'] # # def ec2(self): # """ # fetch ec2 connection, open if necessary # """ # if self._region['ec2_conn']: # return self._region['ec2_conn'] # region = self.region() # if self._region['ec2_conn'] is None: # log.debug("Connecting to EC2 region {}".format(region)) # self._region['ec2_conn'] = boto.ec2.connect_to_region( # region, # is_secure=False # ) # assert self._region['ec2_conn'] is not None, ( # ("Failed to connect to EC2 service in region {!r}" # .format(region))) # return self._region['ec2_conn'] # # def vpc(self): # """ # fetch vpc connection, open if necessary # """ # if self._region['vpc_conn']: # return self._region['vpc_conn'] # region = self.region() # if self._region['vpc_conn'] is None: # log.debug("Connecting to VPC region {}".format(region)) # self._region['vpc_conn'] = boto.vpc.connect_to_region( # region, # is_secure=False # ) # assert self._region['vpc_conn'] is not None, ( # ("Failed to connect to VPC service in region {!r}" # .format(region))) # return self._region['vpc_conn'] # # Path: handson/util.py # def get_file_as_string(fn): # """ # Given a filename, returns the file's contents in a string. # """ # r = '' # with open(fn) as fh: # r = fh.read() # fh.close() # return r which might include code, classes, or functions. Output only the next line.
k_stanza[d] = {}
Using the snippet: <|code_start|># * Neither the name of ceph-auto-aws nor the names of its contributors may be # used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # log = logging.getLogger(__name__) class ClusterOptions(object): def validate_delegate_list(self): dl = self.args.delegate_list if dl is None or len(dl) == 0: return True max_delegates = stanza('delegates') log.debug("Maximum number of delegates is {!r}".format(max_delegates)) <|code_end|> , determine the next line of code. You have imports: import logging from handson.myyaml import stanza and context (class names, function names, or code) available: # Path: handson/myyaml.py # def stanza(k, new_val=None): # global _cache # load() # if new_val is not None: # assert k in tree_stanzas.keys(), ( # "YAML stanza {!r} not permitted".format(k) # ) # _cache[k] = new_val # write() # stanza_is_sane(k) # return _cache[k] . Output only the next line.
assert (
Given the following code snippet before the placeholder: <|code_start|># * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of ceph-auto-aws nor the names of its contributors may be # used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # from handson.util import read_user_data log = logging.getLogger(__name__) class VPC(Region): def __init__(self, args): super(VPC, self).__init__(args) <|code_end|> , predict the next line using imports from the current file: import logging from handson.myyaml import stanza from handson.region import Region from handson.tag import apply_tag and context including class names, function names, and sometimes code from other files: # Path: handson/myyaml.py # def stanza(k, new_val=None): # global _cache # load() # if new_val is not None: # assert k in tree_stanzas.keys(), ( # "YAML stanza {!r} not permitted".format(k) # ) # _cache[k] = new_val # write() # stanza_is_sane(k) # return _cache[k] # # Path: handson/region.py # class Region(object): # # def __init__(self, args): # self.args = args # self._region = { # 'ec2_conn': None, # 'region_str': None, # 'vpc_conn': None, # 'az': None # } # # def region(self): # """ # gets region from yaml, default to eu-west-1 # """ # if self._region['region_str']: # return self._region['region_str'] # self._region['region_str'] = stanza('region')['region_str'] # log.debug("Region is {}".format(self._region['region_str'])) # return self._region['region_str'] # # def availability_zone(self): # """ # gets availability_zone from yaml, default to None # """ # if self._region['az']: # return self._region['az'] # self._region['az'] = stanza('region')['availability_zone'] # if self._region['az']: # log.debug("Availability zone is {}" # .format(self._region['az'])) # return self._region['az'] # # def ec2(self): # """ # fetch ec2 connection, open if necessary # """ # if self._region['ec2_conn']: # return self._region['ec2_conn'] # region = self.region() # if self._region['ec2_conn'] is None: # log.debug("Connecting to EC2 region {}".format(region)) # self._region['ec2_conn'] = boto.ec2.connect_to_region( # region, # is_secure=False # ) # assert self._region['ec2_conn'] is not None, ( # ("Failed to connect to EC2 service in region {!r}" # .format(region))) # return self._region['ec2_conn'] # # def vpc(self): # """ # fetch vpc connection, open if necessary # """ # if self._region['vpc_conn']: # return self._region['vpc_conn'] # region = self.region() # if self._region['vpc_conn'] is None: # log.debug("Connecting to VPC region {}".format(region)) # self._region['vpc_conn'] = boto.vpc.connect_to_region( # region, # is_secure=False # ) # assert self._region['vpc_conn'] is not None, ( # ("Failed to connect to VPC service in region {!r}" # .format(region))) # return self._region['vpc_conn'] # # Path: handson/tag.py # def apply_tag(obj, tag='Name', val=None): # """ # tag an AWS object # """ # for x in [1, 1, 2, 4, 8]: # error = False # try: # obj.add_tag(tag, val) # except: # pragma: no cover # error = True # e = sys.exc_info()[0] # log.info("Huh, trying again ({})".format(e)) # time.sleep(x) # if not error: # log.info("Object {} tagged with {}={}".format(obj, tag, val)) # break # return None . Output only the next line.
self.args = args
Next line prediction: <|code_start|># * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of ceph-auto-aws nor the names of its contributors may be # used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # from handson.util import read_user_data log = logging.getLogger(__name__) class VPC(Region): def __init__(self, args): super(VPC, self).__init__(args) <|code_end|> . Use current file imports: (import logging from handson.myyaml import stanza from handson.region import Region from handson.tag import apply_tag) and context including class names, function names, or small code snippets from other files: # Path: handson/myyaml.py # def stanza(k, new_val=None): # global _cache # load() # if new_val is not None: # assert k in tree_stanzas.keys(), ( # "YAML stanza {!r} not permitted".format(k) # ) # _cache[k] = new_val # write() # stanza_is_sane(k) # return _cache[k] # # Path: handson/region.py # class Region(object): # # def __init__(self, args): # self.args = args # self._region = { # 'ec2_conn': None, # 'region_str': None, # 'vpc_conn': None, # 'az': None # } # # def region(self): # """ # gets region from yaml, default to eu-west-1 # """ # if self._region['region_str']: # return self._region['region_str'] # self._region['region_str'] = stanza('region')['region_str'] # log.debug("Region is {}".format(self._region['region_str'])) # return self._region['region_str'] # # def availability_zone(self): # """ # gets availability_zone from yaml, default to None # """ # if self._region['az']: # return self._region['az'] # self._region['az'] = stanza('region')['availability_zone'] # if self._region['az']: # log.debug("Availability zone is {}" # .format(self._region['az'])) # return self._region['az'] # # def ec2(self): # """ # fetch ec2 connection, open if necessary # """ # if self._region['ec2_conn']: # return self._region['ec2_conn'] # region = self.region() # if self._region['ec2_conn'] is None: # log.debug("Connecting to EC2 region {}".format(region)) # self._region['ec2_conn'] = boto.ec2.connect_to_region( # region, # is_secure=False # ) # assert self._region['ec2_conn'] is not None, ( # ("Failed to connect to EC2 service in region {!r}" # .format(region))) # return self._region['ec2_conn'] # # def vpc(self): # """ # fetch vpc connection, open if necessary # """ # if self._region['vpc_conn']: # return self._region['vpc_conn'] # region = self.region() # if self._region['vpc_conn'] is None: # log.debug("Connecting to VPC region {}".format(region)) # self._region['vpc_conn'] = boto.vpc.connect_to_region( # region, # is_secure=False # ) # assert self._region['vpc_conn'] is not None, ( # ("Failed to connect to VPC service in region {!r}" # .format(region))) # return self._region['vpc_conn'] # # Path: handson/tag.py # def apply_tag(obj, tag='Name', val=None): # """ # tag an AWS object # """ # for x in [1, 1, 2, 4, 8]: # error = False # try: # obj.add_tag(tag, val) # except: # pragma: no cover # error = True # e = sys.exc_info()[0] # log.info("Huh, trying again ({})".format(e)) # time.sleep(x) # if not error: # log.info("Object {} tagged with {}={}".format(obj, tag, val)) # break # return None . Output only the next line.
self.args = args
Given snippet: <|code_start|># used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # from handson.util import read_user_data log = logging.getLogger(__name__) class VPC(Region): def __init__(self, args): super(VPC, self).__init__(args) self.args = args self._vpc = { 'vpc_obj': None } <|code_end|> , continue by predicting the next line. Consider current file imports: import logging from handson.myyaml import stanza from handson.region import Region from handson.tag import apply_tag and context: # Path: handson/myyaml.py # def stanza(k, new_val=None): # global _cache # load() # if new_val is not None: # assert k in tree_stanzas.keys(), ( # "YAML stanza {!r} not permitted".format(k) # ) # _cache[k] = new_val # write() # stanza_is_sane(k) # return _cache[k] # # Path: handson/region.py # class Region(object): # # def __init__(self, args): # self.args = args # self._region = { # 'ec2_conn': None, # 'region_str': None, # 'vpc_conn': None, # 'az': None # } # # def region(self): # """ # gets region from yaml, default to eu-west-1 # """ # if self._region['region_str']: # return self._region['region_str'] # self._region['region_str'] = stanza('region')['region_str'] # log.debug("Region is {}".format(self._region['region_str'])) # return self._region['region_str'] # # def availability_zone(self): # """ # gets availability_zone from yaml, default to None # """ # if self._region['az']: # return self._region['az'] # self._region['az'] = stanza('region')['availability_zone'] # if self._region['az']: # log.debug("Availability zone is {}" # .format(self._region['az'])) # return self._region['az'] # # def ec2(self): # """ # fetch ec2 connection, open if necessary # """ # if self._region['ec2_conn']: # return self._region['ec2_conn'] # region = self.region() # if self._region['ec2_conn'] is None: # log.debug("Connecting to EC2 region {}".format(region)) # self._region['ec2_conn'] = boto.ec2.connect_to_region( # region, # is_secure=False # ) # assert self._region['ec2_conn'] is not None, ( # ("Failed to connect to EC2 service in region {!r}" # .format(region))) # return self._region['ec2_conn'] # # def vpc(self): # """ # fetch vpc connection, open if necessary # """ # if self._region['vpc_conn']: # return self._region['vpc_conn'] # region = self.region() # if self._region['vpc_conn'] is None: # log.debug("Connecting to VPC region {}".format(region)) # self._region['vpc_conn'] = boto.vpc.connect_to_region( # region, # is_secure=False # ) # assert self._region['vpc_conn'] is not None, ( # ("Failed to connect to VPC service in region {!r}" # .format(region))) # return self._region['vpc_conn'] # # Path: handson/tag.py # def apply_tag(obj, tag='Name', val=None): # """ # tag an AWS object # """ # for x in [1, 1, 2, 4, 8]: # error = False # try: # obj.add_tag(tag, val) # except: # pragma: no cover # error = True # e = sys.exc_info()[0] # log.info("Huh, trying again ({})".format(e)) # time.sleep(x) # if not error: # log.info("Object {} tagged with {}={}".format(obj, tag, val)) # break # return None which might include code, classes, or functions. Output only the next line.
def vpc_obj(self, create=False, dry_run=False, quiet=False):
Next line prediction: <|code_start|> for ob in obs: ob_eval = ob.evaluated_get(depsgraph) me = ob_eval.to_mesh() me.transform(ob.matrix_world) bm.from_mesh(me) ob_eval.to_mesh_clear() bmesh.ops.triangulate(bm, faces=bm.faces) vol = bm.calc_volume() bm.free() return vol def est_curve_length(ob: Object) -> float: if ob.modifiers: # Reset curve # --------------------------- settings = { "bevel_object": None, "bevel_depth": 0.0, "extrude": 0.0, } for k, v in settings.items(): <|code_end|> . Use current file imports: (from collections.abc import Iterable from bpy.types import Object from bmesh.types import BMesh, BMVert, BMEdge, BMFace from mathutils import Matrix from .iterutils import pairwise_cyclic, quadwise_cyclic import bpy import bmesh) and context including class names, function names, or small code snippets from other files: # Path: lib/iterutils.py # def pairwise_cyclic(a): # import itertools # b = itertools.cycle(a) # next(b) # return zip(a, b) # # def quadwise_cyclic(a1, b1): # import itertools # a2 = itertools.cycle(a1) # next(a2) # b2 = itertools.cycle(b1) # next(b2) # return zip(a2, a1, b1, b2) . Output only the next line.
x = getattr(ob.data, k)
Predict the next line for this snippet: <|code_start|> bmesh.ops.triangulate(bm, faces=bm.faces) vol = bm.calc_volume() bm.free() return vol def est_curve_length(ob: Object) -> float: if ob.modifiers: # Reset curve # --------------------------- settings = { "bevel_object": None, "bevel_depth": 0.0, "extrude": 0.0, } for k, v in settings.items(): x = getattr(ob.data, k) setattr(ob.data, k, v) settings[k] = x # Calculate length # --------------------------- depsgraph = bpy.context.evaluated_depsgraph_get() <|code_end|> with the help of current file imports: from collections.abc import Iterable from bpy.types import Object from bmesh.types import BMesh, BMVert, BMEdge, BMFace from mathutils import Matrix from .iterutils import pairwise_cyclic, quadwise_cyclic import bpy import bmesh and context from other files: # Path: lib/iterutils.py # def pairwise_cyclic(a): # import itertools # b = itertools.cycle(a) # next(b) # return zip(a, b) # # def quadwise_cyclic(a1, b1): # import itertools # a2 = itertools.cycle(a1) # next(a2) # b2 = itertools.cycle(b1) # next(b2) # return zip(a2, a1, b1, b2) , which may contain function names, class names, or code. Output only the next line.
ob_eval = ob.evaluated_get(depsgraph)
Predict the next line after this snippet: <|code_start|># ##### BEGIN GPL LICENSE BLOCK ##### # # JewelCraft jewelry design toolkit for Blender. # Copyright (C) 2015-2022 Mikhail Rachinskiy # # 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 <https://www.gnu.org/licenses/>. # # ##### END GPL LICENSE BLOCK ##### class Section: __slots__ = ( "detalization", <|code_end|> using the current file's imports: from math import tau, sin, cos from bmesh.types import BMesh, BMVert from ._types import SectionSize and any relevant context from other files: # Path: op_cutter/profiles/_types.py # class SectionSize: # __slots__ = "x", "y", "z1", "z2" # # def __init__(self, x: float, y: float, z1: float, z2: float) -> None: # self.x = x # self.y = y # self.z1 = z1 # self.z2 = z2 # # @property # def xyz(self): # return self.x, self.y, self.z1 . Output only the next line.
)
Given the following code snippet before the placeholder: <|code_start|> app((-x, y, z)) return vs def _get_heart(detalization: int, mul_1: float, mul_2: float, mul_3: float) -> list[tuple[float, float, float]]: curve_resolution = detalization + 1 angle = pi / (curve_resolution - 1) vs = [] app = vs.append z = -mul_3 m1 = -mul_1 basis1 = curve_resolution / 5 basis2 = curve_resolution / 12 for i in range(curve_resolution): x = sin(i * angle) y = cos(i * angle) + m1 + 0.2 app([-x, y, z]) if m1 < 0.0: m1 -= m1 / basis1 if z < 0.0: z -= z / basis2 m2 = -mul_2 basis = curve_resolution / 4 <|code_end|> , predict the next line using imports from the current file: from math import pi, tau, sin, cos from bmesh.types import BMesh, BMVert from ._types import SectionSize and context including class names, function names, and sometimes code from other files: # Path: op_cutter/profiles/_types.py # class SectionSize: # __slots__ = "x", "y", "z1", "z2" # # def __init__(self, x: float, y: float, z1: float, z2: float) -> None: # self.x = x # self.y = y # self.z1 = z1 # self.z2 = z2 # # @property # def xyz(self): # return self.x, self.y, self.z1 . Output only the next line.
for co in reversed(vs):
Predict the next line after this snippet: <|code_start|> f.normal_flip() verts = [bm.verts.new((*v.co.xy, size.z1)) for v in f.verts] bm_temp.free() return verts def _edge_loop_walk(verts: list[BMVert]) -> Iterator[BMVert]: v0 = v = next(iter(verts)) e = v.link_edges[1] ov = e.other_vert(v) yield v while ov is not v0: yield ov v = ov for oe in ov.link_edges: if oe != e: e = oe break ov = e.other_vert(v) class Section: __slots__ = ( <|code_end|> using the current file's imports: from collections.abc import Iterator from bmesh.types import BMesh, BMVert from ...lib import mesh from ._types import SectionSize import bmesh and any relevant context from other files: # Path: op_cutter/profiles/_types.py # class SectionSize: # __slots__ = "x", "y", "z1", "z2" # # def __init__(self, x: float, y: float, z1: float, z2: float) -> None: # self.x = x # self.y = y # self.z1 = z1 # self.z2 = z2 # # @property # def xyz(self): # return self.x, self.y, self.z1 . Output only the next line.
"bv_type",
Given the following code snippet before the placeholder: <|code_start|> def requests_get_content(uri, timeout=10): try: response = requests.get(uri, timeout=timeout) response.raise_for_status() except requests.exceptions.HTTPError: _handle_http_error(response.status_code) except requests.exceptions.ConnectionError: raise exceptions.SPSConnectionError() else: <|code_end|> , predict the next line using imports from the current file: from packtools.sps import exceptions import requests and context including class names, function names, and sometimes code from other files: # Path: packtools/sps/exceptions.py # class NotAllowedtoChangeAttributeValueError(Exception): # class InvalidAttributeValueError(Exception): # class InvalidValueForOrderError(Exception): # class SPSLoadToXMLError(Exception): # class SHA1Error(Exception): # class SPSConnectionError(Exception): # class SPSHTTPError(Exception): # class SPSHTTPForbiddenError(Exception): # class SPSHTTPResourceNotFoundError(Exception): # class SPSHTTPInternalServerError(Exception): # class SPSHTTPBadGatewayError(Exception): # class SPSHTTPServiceUnavailableError(Exception): # class SPSDownloadXMLError(Exception): # class SPSXMLLinkError(Exception): # class SPSXMLContentError(Exception): # class SPSXMLFileError(Exception): # class SPSAssetOrRenditionFileError(Exception): # class SPSMakePackageFromPathsMissingKeyError(Exception): . Output only the next line.
return response.content.decode("utf-8")
Predict the next line after this snippet: <|code_start|> class TestXMLUtils(TestCase): def test_node_text_diacritics(self): xmltree = xml_utils.get_xml_tree("<root><city>São Paulo</city></root>") expected = "São Paulo" result = xml_utils.node_text(xmltree.find(".//city")) self.assertEqual(expected, result) def test_tostring_diacritics_from_root(self): xmltree = xml_utils.get_xml_tree("<root><city>São Paulo</city></root>") expected = ( "<?xml version='1.0' encoding='utf-8'?>\n" "<root><city>São Paulo</city></root>" ) result = xml_utils.tostring(xmltree) self.assertEqual(expected, result) def test_tostring_entity_from_root(self): xmltree = xml_utils.get_xml_tree( "<root><city>S&#227;o Paulo</city></root>") expected = ( <|code_end|> using the current file's imports: from unittest import TestCase from packtools.sps.utils import xml_utils and any relevant context from other files: # Path: packtools/sps/utils/xml_utils.py # def formatted_text(title_node): # def fix_xml(xml_str): # def fix_namespace_prefix_w(content): # def _get_xml_content(xml): # def get_xml_tree(content): # def tostring(node, doctype=None, pretty_print=False): # def node_text(node): # def get_year_month_day(node): # def create_alternatives(node, assets_data): # def parse_value(value): # def parse_issue(issue): # def is_allowed_to_update(xml_sps, attr_name, attr_new_value): # def match_pubdate(node, pubdate_xpaths): . Output only the next line.
"<?xml version='1.0' encoding='utf-8'?>\n"
Based on the snippet: <|code_start|> logger = logging.getLogger(__name__) class SPS_Package: def __init__(self, xml, original_filename=None): self.xmltree = xml_utils.get_xml_tree(xml) self._original_filename = original_filename self._assets = SPS_Assets(self.xmltree, self.scielo_pid_v3) @property def xmltree(self): return self._xmltree @xmltree.setter def xmltree(self, value): self._xmltree = value @property def identity(self): return Identity(self.xmltree) @property def subart_translations(self): <|code_end|> , predict the immediate next line with the help of imports: import logging import os from lxml import etree from packtools import normalizer from packtools.sps.utils import xml_utils and context (classes, functions, sometimes code) from other files: # Path: packtools/normalizer.py # def extract_number_and_supplment_from_issue_element(issue): # # Path: packtools/sps/utils/xml_utils.py # def formatted_text(title_node): # def fix_xml(xml_str): # def fix_namespace_prefix_w(content): # def _get_xml_content(xml): # def get_xml_tree(content): # def tostring(node, doctype=None, pretty_print=False): # def node_text(node): # def get_year_month_day(node): # def create_alternatives(node, assets_data): # def parse_value(value): # def parse_issue(issue): # def is_allowed_to_update(xml_sps, attr_name, attr_new_value): # def match_pubdate(node, pubdate_xpaths): . Output only the next line.
return self._nodes_with_lang(
Here is a snippet: <|code_start|> logger = logging.getLogger(__name__) class SPS_Package: def __init__(self, xml, original_filename=None): self.xmltree = xml_utils.get_xml_tree(xml) self._original_filename = original_filename self._assets = SPS_Assets(self.xmltree, self.scielo_pid_v3) @property def xmltree(self): return self._xmltree @xmltree.setter def xmltree(self, value): self._xmltree = value @property def identity(self): return Identity(self.xmltree) @property def subart_translations(self): return self._nodes_with_lang( <|code_end|> . Write the next line using the current file imports: import logging import os from lxml import etree from packtools import normalizer from packtools.sps.utils import xml_utils and context from other files: # Path: packtools/normalizer.py # def extract_number_and_supplment_from_issue_element(issue): # # Path: packtools/sps/utils/xml_utils.py # def formatted_text(title_node): # def fix_xml(xml_str): # def fix_namespace_prefix_w(content): # def _get_xml_content(xml): # def get_xml_tree(content): # def tostring(node, doctype=None, pretty_print=False): # def node_text(node): # def get_year_month_day(node): # def create_alternatives(node, assets_data): # def parse_value(value): # def parse_issue(issue): # def is_allowed_to_update(xml_sps, attr_name, attr_new_value): # def match_pubdate(node, pubdate_xpaths): , which may include functions, classes, or code. Output only the next line.
'.//sub-article[@article-type="translation"]'
Predict the next line after this snippet: <|code_start|> @unittest.skip("""A caixa de retratação está sendo gerada pela aplicação, caso deseje que seja gerado pelo XSLT descomentar a linha 24 do arquivo article.xsl""") def test_should_translate_retraction_to_english(self): sample = u"""<article article-type="retraction" dtd-version="1.1" specific-use="sps-1.8" xml:lang="en" xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink"> <front> <article-meta> <article-id pub-id-type="doi">10.1590/2236-8906-34/2018-retratacao</article-id> <related-article ext-link-type="doi" id="r01" related-article-type="retracted-article" xlink:href="10.1590/2236-8906-34/2018"/> </article-meta> </front> </article>""" et = get_xml_tree_from_string(sample) html = domain.HTMLGenerator.parse(et, valid_only=False).generate('en') html_string = etree.tostring(html, encoding='unicode', method='html') self.assertIn(u'This retraction retracts the following document', html_string) @unittest.skip("""A caixa de retratação está sendo gerada pela aplicação, caso deseje que seja gerado pelo XSLT descomentar a linha 24 do arquivo article.xsl""") def test_do_not_show_retraction_box_if_article_is_not_a_retraction(self): sample = u"""<article article-type="research-article" dtd-version="1.1" specific-use="sps-1.8" xml:lang="pt" xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink"> <front> <article-meta> <|code_end|> using the current file's imports: import unittest import io import os from tempfile import NamedTemporaryFile from lxml import etree from packtools import domain and any relevant context from other files: # Path: packtools/domain.py # LOGGER = logging.getLogger(__name__) # def _get_public_ids(sps_version): # def _init_sps_version(xml_et, supported_versions=None): # def StdSchematron(schema_name): # def XSLT(xslt_name): # def __init__(self, pipeline=catalogs.StyleCheckingPipeline, label=u''): # def validate(self, xmlfile): # def __init__(self, dtd, label=u''): # def validate(self, xmlfile): # def __init__(self, sch, label=u''): # def from_catalog(cls, ref, **kwargs): # def validate(self, xmlfile): # def iter_schematronvalidators(iterable): # def __init__(self, file, dtd=None, style_validators=None): # def parse(cls, file, no_doctype=False, sps_version=None, # supported_sps_versions=None, extra_sch_schemas=None, **kwargs): # def sps_version(self): # def dtd_validator(self): # def validate(self): # def validate_style(self): # def validate_all(self, fail_fast=False): # def _annotate_error(self, element, error): # def annotate_errors(self, fail_fast=False): # def __repr__(self): # def meta(self): # def assets(self): # def lookup_assets(self, base): # def __init__(self, file, xslt=None, css=None, print_css=None, js=None, # permlink=None, url_article_page=None, url_download_ris=None, # gs_abstract=None, output_style=None): # def parse(cls, file, valid_only=True, **kwargs): # def languages(self): # def language(self): # def abstract_languages(self): # def _is_aop(self): # def _get_issue_label(self): # def _get_bibliographic_legend(self): # def __iter__(self): # def generate(self, lang): # class PyValidator(object): # class DTDValidator(object): # class SchematronValidator(object): # class XMLValidator(object): # class HTMLGenerator(object): . Output only the next line.
<article-id pub-id-type="doi">10.1590/2236-8906-34/2018-retratacao</article-id>
Predict the next line after this snippet: <|code_start|> "a1-gf01.jpg": "a1-gf01.jpg", "a1-gf02.tiff": "a1-gf02.tiff", } pkg1._renditions = { "en": "a1-en.pdf", "original": "a1.pdf", } xmls = [ "a1.xml", "a11.xml", ] files = [ "a1-en.pdf", "a1-gf01.jpg", "a1-gf01.tiff", "a1-gf02.tiff", "a1.pdf", "a1.xml", "a11-es.pdf", "a11-gf01-es.tiff", "a11-gf02-es.tiff", "a11-suppl-es.pdf", "a11.pdf", "a11.xml", ] result = packages._group_files_by_xml_filename("source", xmls, files) self.assertEqual(pkg11.xml, result["a11"].xml) self.assertEqual(pkg11._assets, result["a11"]._assets) self.assertEqual(pkg11._renditions, result["a11"]._renditions) self.assertEqual(pkg1.xml, result["a1"].xml) self.assertEqual(pkg1._assets, result["a1"]._assets) <|code_end|> using the current file's imports: from unittest import TestCase from packtools.sps.models import packages and any relevant context from other files: # Path: packtools/sps/models/packages.py # class Package: # def __init__(self, source, name): # def assets(self): # def name(self): # def file_path(self, file_path): # def add_asset(self, basename, file_path): # def get_asset(self, basename): # def add_rendition(self, lang, file_path): # def get_rendition(self, lang): # def source(self): # def xml(self): # def xml(self, value): # def renditions(self): # def xml_content(self): # def select_filenames_by_prefix(prefix, files): # def match_file_by_prefix(prefix, file_path): # def explore_source(source): # def _explore_folder(folder): # def _explore_zipfile(zip_path): # def _group_files_by_xml_filename(source, xmls, files): # def _eval_file(prefix, file_path): . Output only the next line.
self.assertEqual(pkg1._renditions, result["a1"]._renditions)
Based on the snippet: <|code_start|> logger = logging.getLogger(__name__) class Package: def __init__(self, source, name): self._source = source self._xml = None self._assets = {} self._renditions = {} self._name = name self.zip_file_path = file_utils.is_zipfile(source) and source @property def assets(self): return self._assets <|code_end|> , predict the immediate next line with the help of imports: import logging import os from packtools import file_utils from zipfile import ZipFile and context (classes, functions, sometimes code) from other files: # Path: packtools/file_utils.py # def is_folder(source): # def is_zipfile(source): # def xml_files_list(path): # def files_list(path): # def read_file(path, encoding="utf-8", mode="r"): # def read_from_zipfile(zip_path, filename): # def xml_files_list_from_zipfile(zip_path): # def files_list_from_zipfile(zip_path): # def write_file(path, source, mode="w"): # def create_zip_file(files, zip_name, zip_folder=None): # def delete_folder(path): # def create_temp_file(filename, content=None, mode='w'): # def copy_file(source, target): # def size(file_path): # def get_prefix_by_xml_filename(xml_filename): # def get_file_role(file_path, prefix, pdf_langs): # def extract_issn_from_zip_uri(zip_uri): # def is_valid_file(file_path, check_mimetype=False): # def get_mimetype(file_path): # def get_filename(file_path): . Output only the next line.
@property
Here is a snippet: <|code_start|> def main(): parser = argparse.ArgumentParser(description="Article package maker CLI utility") parser.add_argument('--output_dir', default='.', help='Output directory where the package will be generated') parser.add_argument("--loglevel", default="WARNING") subparsers = parser.add_subparsers(title='Commands', dest='command') uris_parser = subparsers.add_parser('uris', help='Make package from URIs') uris_parser.add_argument('--xml', help='XML URI', required=True) uris_parser.add_argument('--renditions', default=[], nargs='+', help='Renditions URI') paths_parser = subparsers.add_parser('paths', help='Make package from files paths') paths_parser.add_argument('--xml', help='XML file path', required=True) paths_parser.add_argument('--renditions', default=[], nargs='+', help='Renditions file path') paths_parser.add_argument('--assets', default=[], nargs='+', help='Assets file path') args = parser.parse_args() logging.basicConfig(level=getattr(logging, args.loglevel.upper())) if args.command == 'uris': uris_dict = generate_uris_dict(args.xml, args.renditions) sps_maker.make_package_from_uris( uris_dict['xml'], uris_dict['renditions'], args.output_dir, ) <|code_end|> . Write the next line using the current file imports: import argparse import logging from packtools import file_utils from packtools.sps import sps_maker and context from other files: # Path: packtools/file_utils.py # def is_folder(source): # def is_zipfile(source): # def xml_files_list(path): # def files_list(path): # def read_file(path, encoding="utf-8", mode="r"): # def read_from_zipfile(zip_path, filename): # def xml_files_list_from_zipfile(zip_path): # def files_list_from_zipfile(zip_path): # def write_file(path, source, mode="w"): # def create_zip_file(files, zip_name, zip_folder=None): # def delete_folder(path): # def create_temp_file(filename, content=None, mode='w'): # def copy_file(source, target): # def size(file_path): # def get_prefix_by_xml_filename(xml_filename): # def get_file_role(file_path, prefix, pdf_langs): # def extract_issn_from_zip_uri(zip_uri): # def is_valid_file(file_path, check_mimetype=False): # def get_mimetype(file_path): # def get_filename(file_path): # # Path: packtools/sps/sps_maker.py # FILE_PATHS_REQUIRED_KEYS = ['xml', 'assets', 'renditions'] # def get_names_and_packages(path): # def make_package_from_paths(paths, zip_folder=None): # def make_package_from_uris(xml_uri, renditions_uris_and_names=[], zip_folder=None): # def _get_xml_sps_from_uri(xml_uri): # def _get_xml_sps_from_path(xml_path): # def _get_assets_uris_and_names(xml_sps): # def _get_xml_uri_and_name(xml_sps, xml_uri=None): # def _get_zip_filename(xml_sps, output_filename=None): # def _zip_files_from_uris_and_names(zip_name, uris_and_names, zip_folder=None): # def _remove_invalid_uris(uris_and_names): # def _zip_files_from_paths(zip_name, xml_sps, paths, zip_folder=None): # def _check_keys_and_files(paths: dict): # def _get_canonical_files_paths(xml_sps, paths): , which may include functions, classes, or code. Output only the next line.
elif args.command == 'paths':
Predict the next line for this snippet: <|code_start|> LOGGER = logging.getLogger(__name__) def generate_paths_dict(xml_path, assets_paths, renditions_paths): return { 'xml': xml_path or '', 'assets': assets_paths or [], 'renditions': renditions_paths or [], } def generate_uris_dict(xml_uri, renditions_uris): uris_dict = { 'xml': xml_uri or '', 'renditions': renditions_uris or [], } for ru in renditions_uris: ru_dict = _get_rendition_dict(ru) uris_dict['renditions'].append(ru_dict) return uris_dict def _get_rendition_dict(rendition_uri_or_path): return { <|code_end|> with the help of current file imports: import argparse import logging from packtools import file_utils from packtools.sps import sps_maker and context from other files: # Path: packtools/file_utils.py # def is_folder(source): # def is_zipfile(source): # def xml_files_list(path): # def files_list(path): # def read_file(path, encoding="utf-8", mode="r"): # def read_from_zipfile(zip_path, filename): # def xml_files_list_from_zipfile(zip_path): # def files_list_from_zipfile(zip_path): # def write_file(path, source, mode="w"): # def create_zip_file(files, zip_name, zip_folder=None): # def delete_folder(path): # def create_temp_file(filename, content=None, mode='w'): # def copy_file(source, target): # def size(file_path): # def get_prefix_by_xml_filename(xml_filename): # def get_file_role(file_path, prefix, pdf_langs): # def extract_issn_from_zip_uri(zip_uri): # def is_valid_file(file_path, check_mimetype=False): # def get_mimetype(file_path): # def get_filename(file_path): # # Path: packtools/sps/sps_maker.py # FILE_PATHS_REQUIRED_KEYS = ['xml', 'assets', 'renditions'] # def get_names_and_packages(path): # def make_package_from_paths(paths, zip_folder=None): # def make_package_from_uris(xml_uri, renditions_uris_and_names=[], zip_folder=None): # def _get_xml_sps_from_uri(xml_uri): # def _get_xml_sps_from_path(xml_path): # def _get_assets_uris_and_names(xml_sps): # def _get_xml_uri_and_name(xml_sps, xml_uri=None): # def _get_zip_filename(xml_sps, output_filename=None): # def _zip_files_from_uris_and_names(zip_name, uris_and_names, zip_folder=None): # def _remove_invalid_uris(uris_and_names): # def _zip_files_from_paths(zip_name, xml_sps, paths, zip_folder=None): # def _check_keys_and_files(paths: dict): # def _get_canonical_files_paths(xml_sps, paths): , which may contain function names, class names, or code. Output only the next line.
'uri': rendition_uri_or_path,
Next line prediction: <|code_start|> logger = logging.getLogger(__name__) def formatted_text(title_node): if title_node is None: return node = deepcopy(title_node) for xref in node.findall(".//xref"): parent = xref.getparent() parent.remove(xref) return node_text(node) def fix_xml(xml_str): <|code_end|> . Use current file imports: (import logging import re from copy import deepcopy from lxml import etree from packtools import validations from packtools.sps import exceptions from packtools import file_utils) and context including class names, function names, or small code snippets from other files: # Path: packtools/validations.py # def is_valid_value_for_pid_v2(value): # VALIDATE_FUNCTIONS = dict(( # ("scielo_pid_v2", is_valid_value_for_pid_v2), # )) # # Path: packtools/sps/exceptions.py # class NotAllowedtoChangeAttributeValueError(Exception): # class InvalidAttributeValueError(Exception): # class InvalidValueForOrderError(Exception): # class SPSLoadToXMLError(Exception): # class SHA1Error(Exception): # class SPSConnectionError(Exception): # class SPSHTTPError(Exception): # class SPSHTTPForbiddenError(Exception): # class SPSHTTPResourceNotFoundError(Exception): # class SPSHTTPInternalServerError(Exception): # class SPSHTTPBadGatewayError(Exception): # class SPSHTTPServiceUnavailableError(Exception): # class SPSDownloadXMLError(Exception): # class SPSXMLLinkError(Exception): # class SPSXMLContentError(Exception): # class SPSXMLFileError(Exception): # class SPSAssetOrRenditionFileError(Exception): # class SPSMakePackageFromPathsMissingKeyError(Exception): # # Path: packtools/file_utils.py # def is_folder(source): # def is_zipfile(source): # def xml_files_list(path): # def files_list(path): # def read_file(path, encoding="utf-8", mode="r"): # def read_from_zipfile(zip_path, filename): # def xml_files_list_from_zipfile(zip_path): # def files_list_from_zipfile(zip_path): # def write_file(path, source, mode="w"): # def create_zip_file(files, zip_name, zip_folder=None): # def delete_folder(path): # def create_temp_file(filename, content=None, mode='w'): # def copy_file(source, target): # def size(file_path): # def get_prefix_by_xml_filename(xml_filename): # def get_file_role(file_path, prefix, pdf_langs): # def extract_issn_from_zip_uri(zip_uri): # def is_valid_file(file_path, check_mimetype=False): # def get_mimetype(file_path): # def get_filename(file_path): . Output only the next line.
return fix_namespace_prefix_w(xml_str)
Given snippet: <|code_start|> f() def test_noStdoutSideEfects(self): def foo(): print("bar") f = Function(foo) with lib.captureStdout() as stdout: f() self.assertTrue(len(stdout.read()) == 0) class TestFunctionPrintOutput(unittest.TestCase): def test_noOutput(self): def foo(): pass f = Function(foo) f() self.assertEqual(f.printOutput, "") def test_oneLineOutput(self): def foo(): print("bar") f = Function(foo) f() self.assertEqual(f.printOutput, "bar\n") def test_twoLineOutput(self): def foo(): print("bar") print("baz") f = Function(foo) <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest import os import shutil import checkpy.lib as lib import checkpy.entities.exception as exception from checkpy.entities.function import Function and context: # Path: checkpy/entities/function.py # class Function(object): # def __init__(self, function): # self._function = function # self._printOutput = "" # # def __call__(self, *args, **kwargs): # old = sys.stdout # try: # with self._captureStdout() as listener: # outcome = self._function(*args, **kwargs) # self._printOutput = ""#listener.content # return outcome # except Exception as e: # sys.stdout = old # argumentNames = self.arguments # nArgs = len(args) + len(kwargs) # # message = "while trying to execute {}()".format(self.name) # if nArgs > 0: # argsRepr = ", ".join("{}={}".format(argumentNames[i], args[i]) for i in range(len(args))) # kwargsRepr = ", ".join("{}={}".format(kwargName, kwargs[kwargName]) for kwargName in argumentNames[len(args):nArgs]) # representation = ", ".join(s for s in [argsRepr, kwargsRepr] if s) # message = "while trying to execute {}({})".format(self.name, representation) # # raise exception.SourceException(exception = e, message = message) # # @property # def name(self): # """gives the name of the function""" # return self._function.__name__ # # @property # def arguments(self): # """gives the argument names of the function""" # return inspect.getfullargspec(self._function)[0] # # @property # def printOutput(self): # """stateful function that returns the print (stdout) output of the latest function call as a string""" # return self._printOutput # # @contextlib.contextmanager # def _captureStdout(self): # """ # capture sys.stdout in _outStream # (a _Stream that is an instance of StringIO extended with the Observer pattern) # returns a _StreamListener on said stream # """ # outStreamListener = _StreamListener(_outStream) # old = sys.stdout # # outStreamListener.start() # sys.stdout = outStreamListener.stream # # try: # yield outStreamListener # except: # raise # finally: # sys.stdout = old # outStreamListener.stop() which might include code, classes, or functions. Output only the next line.
f()
Given snippet: <|code_start|> self.assertFalse(path.isPythonFile()) def test_pythonFile(self): path = Path("/foo/bar/baz.py") self.assertTrue(path.isPythonFile()) def test_folder(self): path = Path("/foo/bar/baz/") self.assertFalse(path.isPythonFile()) path = Path("/foo/bar/baz") self.assertFalse(path.isPythonFile()) class TestPathExists(unittest.TestCase): def setUp(self): self.fileName = "dummy.py" with open(self.fileName, "w") as f: pass def tearDown(self): os.remove(self.fileName) def test_doesNotExist(self): path = Path("foo/bar/baz.py") self.assertFalse(path.exists()) def test_exists(self): path = Path("dummy.py") self.assertTrue(path.isPythonFile()) <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest import os import shutil import checkpy.entities.exception as exception from checkpy.entities.path import Path and context: # Path: checkpy/entities/path.py # class Path(object): # def __init__(self, path): # path = os.path.normpath(path) # self._drive, path = os.path.splitdrive(path) # # items = str(path).split(os.path.sep) # # if len(items) > 0: # # if path started with root, add root # if items[0] == "": # items[0] = os.path.sep # # # remove any empty items (for instance because of "/") # self._items = [item for item in items if item] # # @property # def fileName(self): # return list(self)[-1] # # @property # def folderName(self): # return list(self)[-2] # # def containingFolder(self): # return Path(self._join(self._drive, list(self)[:-1])) # # def isPythonFile(self): # return self.fileName.endswith(".py") # # def absolutePath(self): # return Path(os.path.abspath(str(self))) # # def exists(self): # return os.path.exists(str(self)) # # def walk(self): # for path, subdirs, files in os.walk(str(self)): # yield Path(path), subdirs, files # # def copyTo(self, destination): # shutil.copyfile(str(self), str(destination)) # # def pathFromFolder(self, folderName): # path = "" # seen = False # items = [] # for item in self: # if seen: # items.append(item) # if item == folderName: # seen = True # # if not seen: # raise exception.PathError(message = "folder {} does not exist in {}".format(folderName, self)) # return Path(self._join(self._drive, items)) # # def __add__(self, other): # if sys.version_info >= (3,0): # supportedTypes = [str, bytes, Path] # else: # supportedTypes = [str, unicode, Path] # # if not any(isinstance(other, t) for t in supportedTypes): # raise exception.PathError(message = "can't add {} to Path only {}".format(type(other), supportedTypes)) # # if not isinstance(other, Path): # other = Path(other) # # # if other path starts with root, throw error # if list(other)[0] == os.path.sep: # raise exception.PathError(message = "can't add {} to Path because it starts at root") # # return Path(self._join(self._drive, list(self) + list(other))) # # def __sub__(self, other): # if sys.version_info >= (3,0): # supportedTypes = [str, bytes, Path] # else: # supportedTypes = [str, unicode, Path] # # if not any(isinstance(other, t) for t in supportedTypes): # raise exception.PathError(message = "can't subtract {} from Path only {}".format(type(other), supportedTypes)) # # if not isinstance(other, Path): # other = Path(other) # # myItems = list(self) # otherItems = list(other) # # for items in (myItems, otherItems): # if len(items) >= 1 and items[0] != os.path.sep and items[0] != ".": # items.insert(0, ".") # # for i in range(min(len(myItems), len(otherItems))): # if myItems[i] != otherItems[i]: # raise exception.PathError(message = "tried subtracting, but subdirs do not match: {} and {}".format(self, other)) # # return Path(self._join(self._drive, myItems[len(otherItems):])) # # def __iter__(self): # for item in self._items: # yield item # # def __hash__(self): # return hash(repr(self)) # # def __eq__(self, other): # return isinstance(other, type(self)) and repr(self) == repr(other) # # def __contains__(self, item): # return str(item) in list(self) # # def __len__(self): # return len(self._items) # # def __str__(self): # return self._join(self._drive, list(self)) # # def __repr__(self): # return "/".join([item for item in self]) # # def _join(self, drive, items): # result = drive # for item in items: # result = os.path.join(result, item) # return result which might include code, classes, or functions. Output only the next line.
class TestPathWalk(unittest.TestCase):
Predict the next line for this snippet: <|code_start|> print(msg) return msg def displayAdded(fileName): msg = "{}Added: {}{}".format(_Colors.WARNING, os.path.basename(fileName), _Colors.ENDC) if not SILENT_MODE: print(msg) return msg def displayCustom(message): if not SILENT_MODE: print(message) return message def displayWarning(message): msg = "{}Warning: {}{}".format(_Colors.WARNING, message, _Colors.ENDC) if not SILENT_MODE: print(msg) return msg def displayError(message): msg = "{}{} {}{}".format(_Colors.WARNING, _Smileys.CONFUSED, message, _Colors.ENDC) if not SILENT_MODE: print(msg) return msg def _selectColorAndSmiley(testResult): if testResult.hasPassed: return _Colors.PASS, _Smileys.HAPPY if type(testResult.message) is exception.SourceException: <|code_end|> with the help of current file imports: from checkpy.entities import exception import os import colorama and context from other files: # Path: checkpy/entities/exception.py # class CheckpyError(Exception): # class SourceException(CheckpyError): # class InputError(CheckpyError): # class TestError(CheckpyError): # class DownloadError(CheckpyError): # class ExitError(CheckpyError): # class PathError(CheckpyError): # def __init__(self, exception = None, message = "", output = "", stacktrace = ""): # def output(self): # def stacktrace(self): # def __str__(self): # def __repr__(self): , which may contain function names, class names, or code. Output only the next line.
return _Colors.WARNING, _Smileys.CONFUSED
Given the code snippet: <|code_start|> download(fileName, source) return filePath = path.userPath + fileName if not fileExists(str(filePath)): raise exception.CheckpyError("Required file {} does not exist".format(fileName)) filePath.copyTo(path.current() + fileName) def fileExists(fileName): return path.Path(fileName).exists() def source(fileName): source = "" with open(fileName) as f: source = f.read() return source def sourceOfDefinitions(fileName): newSource = "" with open(fileName) as f: insideDefinition = False for line in removeComments(f.read()).split("\n"): line += "\n" if not line.strip(): continue if (line.startswith(" ") or line.startswith("\t")) and insideDefinition: <|code_end|> , generate the next line using the imports in this file: import sys import re import StringIO import io as StringIO import contextlib import importlib import imp import tokenize import traceback import requests from checkpy.entities import path from checkpy.entities import exception from checkpy.entities import function from checkpy import caches and context (functions, classes, or occasionally code) from other files: # Path: checkpy/entities/path.py # class Path(object): # def __init__(self, path): # def fileName(self): # def folderName(self): # def containingFolder(self): # def isPythonFile(self): # def absolutePath(self): # def exists(self): # def walk(self): # def copyTo(self, destination): # def pathFromFolder(self, folderName): # def __add__(self, other): # def __sub__(self, other): # def __iter__(self): # def __hash__(self): # def __eq__(self, other): # def __contains__(self, item): # def __len__(self): # def __str__(self): # def __repr__(self): # def _join(self, drive, items): # def current(): # CHECKPYPATH = Path(os.path.abspath(os.path.dirname(__file__))[:-len("/entities")]) # # Path: checkpy/entities/exception.py # class CheckpyError(Exception): # class SourceException(CheckpyError): # class InputError(CheckpyError): # class TestError(CheckpyError): # class DownloadError(CheckpyError): # class ExitError(CheckpyError): # class PathError(CheckpyError): # def __init__(self, exception = None, message = "", output = "", stacktrace = ""): # def output(self): # def stacktrace(self): # def __str__(self): # def __repr__(self): # # Path: checkpy/entities/function.py # class Function(object): # class _Stream(io.StringIO): # class _StreamListener(object): # def __init__(self, function): # def __call__(self, *args, **kwargs): # def name(self): # def arguments(self): # def printOutput(self): # def _captureStdout(self): # def __init__(self, *args, **kwargs): # def register(self, listener): # def unregister(self, listener): # def write(self, text): # def writelines(self, sequence): # def _onUpdate(self, content): # def __init__(self, stream): # def start(self): # def stop(self): # def update(self, content): # def content(self): # def stream(self): # # Path: checkpy/caches.py # class _Cache(dict): # def __init__(self, *args, **kwargs): # def cache(*keys): # def cacheWrapper(func): # def cachedFuncWrapper(*args, **kwargs): # def clearAllCaches(): . Output only the next line.
newSource += line
Predict the next line for this snippet: <|code_start|> raise exception.CheckpyError("Required file {} does not exist".format(fileName)) filePath.copyTo(path.current() + fileName) def fileExists(fileName): return path.Path(fileName).exists() def source(fileName): source = "" with open(fileName) as f: source = f.read() return source def sourceOfDefinitions(fileName): newSource = "" with open(fileName) as f: insideDefinition = False for line in removeComments(f.read()).split("\n"): line += "\n" if not line.strip(): continue if (line.startswith(" ") or line.startswith("\t")) and insideDefinition: newSource += line elif line.startswith("def ") or line.startswith("class "): newSource += line insideDefinition = True elif line.startswith("import ") or line.startswith("from "): newSource += line <|code_end|> with the help of current file imports: import sys import re import StringIO import io as StringIO import contextlib import importlib import imp import tokenize import traceback import requests from checkpy.entities import path from checkpy.entities import exception from checkpy.entities import function from checkpy import caches and context from other files: # Path: checkpy/entities/path.py # class Path(object): # def __init__(self, path): # def fileName(self): # def folderName(self): # def containingFolder(self): # def isPythonFile(self): # def absolutePath(self): # def exists(self): # def walk(self): # def copyTo(self, destination): # def pathFromFolder(self, folderName): # def __add__(self, other): # def __sub__(self, other): # def __iter__(self): # def __hash__(self): # def __eq__(self, other): # def __contains__(self, item): # def __len__(self): # def __str__(self): # def __repr__(self): # def _join(self, drive, items): # def current(): # CHECKPYPATH = Path(os.path.abspath(os.path.dirname(__file__))[:-len("/entities")]) # # Path: checkpy/entities/exception.py # class CheckpyError(Exception): # class SourceException(CheckpyError): # class InputError(CheckpyError): # class TestError(CheckpyError): # class DownloadError(CheckpyError): # class ExitError(CheckpyError): # class PathError(CheckpyError): # def __init__(self, exception = None, message = "", output = "", stacktrace = ""): # def output(self): # def stacktrace(self): # def __str__(self): # def __repr__(self): # # Path: checkpy/entities/function.py # class Function(object): # class _Stream(io.StringIO): # class _StreamListener(object): # def __init__(self, function): # def __call__(self, *args, **kwargs): # def name(self): # def arguments(self): # def printOutput(self): # def _captureStdout(self): # def __init__(self, *args, **kwargs): # def register(self, listener): # def unregister(self, listener): # def write(self, text): # def writelines(self, sequence): # def _onUpdate(self, content): # def __init__(self, stream): # def start(self): # def stop(self): # def update(self, content): # def content(self): # def stream(self): # # Path: checkpy/caches.py # class _Cache(dict): # def __init__(self, *args, **kwargs): # def cache(*keys): # def cacheWrapper(func): # def cachedFuncWrapper(*args, **kwargs): # def clearAllCaches(): , which may contain function names, class names, or code. Output only the next line.
else:
Predict the next line after this snippet: <|code_start|>try: # Python 2 except: # Python 3 def require(fileName, source = None): if source: download(fileName, source) return filePath = path.userPath + fileName if not fileExists(str(filePath)): raise exception.CheckpyError("Required file {} does not exist".format(fileName)) filePath.copyTo(path.current() + fileName) def fileExists(fileName): return path.Path(fileName).exists() def source(fileName): source = "" with open(fileName) as f: source = f.read() return source def sourceOfDefinitions(fileName): <|code_end|> using the current file's imports: import sys import re import StringIO import io as StringIO import contextlib import importlib import imp import tokenize import traceback import requests from checkpy.entities import path from checkpy.entities import exception from checkpy.entities import function from checkpy import caches and any relevant context from other files: # Path: checkpy/entities/path.py # class Path(object): # def __init__(self, path): # def fileName(self): # def folderName(self): # def containingFolder(self): # def isPythonFile(self): # def absolutePath(self): # def exists(self): # def walk(self): # def copyTo(self, destination): # def pathFromFolder(self, folderName): # def __add__(self, other): # def __sub__(self, other): # def __iter__(self): # def __hash__(self): # def __eq__(self, other): # def __contains__(self, item): # def __len__(self): # def __str__(self): # def __repr__(self): # def _join(self, drive, items): # def current(): # CHECKPYPATH = Path(os.path.abspath(os.path.dirname(__file__))[:-len("/entities")]) # # Path: checkpy/entities/exception.py # class CheckpyError(Exception): # class SourceException(CheckpyError): # class InputError(CheckpyError): # class TestError(CheckpyError): # class DownloadError(CheckpyError): # class ExitError(CheckpyError): # class PathError(CheckpyError): # def __init__(self, exception = None, message = "", output = "", stacktrace = ""): # def output(self): # def stacktrace(self): # def __str__(self): # def __repr__(self): # # Path: checkpy/entities/function.py # class Function(object): # class _Stream(io.StringIO): # class _StreamListener(object): # def __init__(self, function): # def __call__(self, *args, **kwargs): # def name(self): # def arguments(self): # def printOutput(self): # def _captureStdout(self): # def __init__(self, *args, **kwargs): # def register(self, listener): # def unregister(self, listener): # def write(self, text): # def writelines(self, sequence): # def _onUpdate(self, content): # def __init__(self, stream): # def start(self): # def stop(self): # def update(self, content): # def content(self): # def stream(self): # # Path: checkpy/caches.py # class _Cache(dict): # def __init__(self, *args, **kwargs): # def cache(*keys): # def cacheWrapper(func): # def cachedFuncWrapper(*args, **kwargs): # def clearAllCaches(): . Output only the next line.
newSource = ""
Using the snippet: <|code_start|> class Test(object): def __init__(self, fileName, priority): self._fileName = fileName self._priority = priority def __lt__(self, other): return self._priority < other._priority @property def fileName(self): return self._fileName @caches.cache() <|code_end|> , determine the next line of code. You have imports: import traceback from functools import wraps from checkpy import caches from checkpy.entities import exception and context (class names, function names, or code) available: # Path: checkpy/caches.py # class _Cache(dict): # def __init__(self, *args, **kwargs): # def cache(*keys): # def cacheWrapper(func): # def cachedFuncWrapper(*args, **kwargs): # def clearAllCaches(): # # Path: checkpy/entities/exception.py # class CheckpyError(Exception): # class SourceException(CheckpyError): # class InputError(CheckpyError): # class TestError(CheckpyError): # class DownloadError(CheckpyError): # class ExitError(CheckpyError): # class PathError(CheckpyError): # def __init__(self, exception = None, message = "", output = "", stacktrace = ""): # def output(self): # def stacktrace(self): # def __str__(self): # def __repr__(self): . Output only the next line.
def run(self):
Continue the code snippet: <|code_start|> def __lt__(self, other): return self._priority < other._priority @property def fileName(self): return self._fileName @caches.cache() def run(self): try: result = self.test() if type(result) == tuple: hasPassed, info = result else: hasPassed, info = result, "" except exception.CheckpyError as e: return TestResult(False, self.description(), self.exception(e), exception = e) except Exception as e: e = exception.TestError( exception = e, message = "while testing", stacktrace = traceback.format_exc()) return TestResult(False, self.description(), self.exception(e), exception = e) return TestResult(hasPassed, self.description(), self.success(info) if hasPassed else self.fail(info)) @staticmethod def test(): <|code_end|> . Use current file imports: import traceback from functools import wraps from checkpy import caches from checkpy.entities import exception and context (classes, functions, or code) from other files: # Path: checkpy/caches.py # class _Cache(dict): # def __init__(self, *args, **kwargs): # def cache(*keys): # def cacheWrapper(func): # def cachedFuncWrapper(*args, **kwargs): # def clearAllCaches(): # # Path: checkpy/entities/exception.py # class CheckpyError(Exception): # class SourceException(CheckpyError): # class InputError(CheckpyError): # class TestError(CheckpyError): # class DownloadError(CheckpyError): # class ExitError(CheckpyError): # class PathError(CheckpyError): # def __init__(self, exception = None, message = "", output = "", stacktrace = ""): # def output(self): # def stacktrace(self): # def __str__(self): # def __repr__(self): . Output only the next line.
raise NotImplementedError()
Given the following code snippet before the placeholder: <|code_start|> def source(fileName): with open(fileName) as f: return f.read() @caches.cache() def fullSyntaxTree(fileName): return fstFromSource(source(fileName)) @caches.cache() def fstFromSource(source): return redbaron.RedBaron(source) @caches.cache() def functionCode(functionName, fileName): definitions = [d for d in fullSyntaxTree(fileName).find_all("def") if d.name == functionName] if definitions: <|code_end|> , predict the next line using imports from the current file: from checkpy import caches import redbaron and context including class names, function names, and sometimes code from other files: # Path: checkpy/caches.py # class _Cache(dict): # def __init__(self, *args, **kwargs): # def cache(*keys): # def cacheWrapper(func): # def cachedFuncWrapper(*args, **kwargs): # def clearAllCaches(): . Output only the next line.
return definitions[0]
Given the following code snippet before the placeholder: <|code_start|>def forEachGithubPath(): for entry in githubTable().all(): yield Path(entry["path"]) def forEachLocalPath(): for entry in localTable().all(): yield Path(entry["path"]) def isKnownGithub(username, repoName): query = tinydb.Query() return githubTable().contains((query.user == username) & (query.repo == repoName)) def addToGithubTable(username, repoName, releaseId, releaseTag): if not isKnownGithub(username, repoName): path = str(CHECKPYPATH + "tests" + repoName) githubTable().insert({ "user" : username, "repo" : repoName, "path" : path, "release" : releaseId, "tag" : releaseTag, "timestamp" : time.time() }) def addToLocalTable(localPath): query = tinydb.Query() table = localTable() if not table.search(query.path == str(localPath)): <|code_end|> , predict the next line using imports from the current file: import tinydb import os import time from checkpy.entities.path import Path, CHECKPYPATH and context including class names, function names, and sometimes code from other files: # Path: checkpy/entities/path.py # class Path(object): # def __init__(self, path): # path = os.path.normpath(path) # self._drive, path = os.path.splitdrive(path) # # items = str(path).split(os.path.sep) # # if len(items) > 0: # # if path started with root, add root # if items[0] == "": # items[0] = os.path.sep # # # remove any empty items (for instance because of "/") # self._items = [item for item in items if item] # # @property # def fileName(self): # return list(self)[-1] # # @property # def folderName(self): # return list(self)[-2] # # def containingFolder(self): # return Path(self._join(self._drive, list(self)[:-1])) # # def isPythonFile(self): # return self.fileName.endswith(".py") # # def absolutePath(self): # return Path(os.path.abspath(str(self))) # # def exists(self): # return os.path.exists(str(self)) # # def walk(self): # for path, subdirs, files in os.walk(str(self)): # yield Path(path), subdirs, files # # def copyTo(self, destination): # shutil.copyfile(str(self), str(destination)) # # def pathFromFolder(self, folderName): # path = "" # seen = False # items = [] # for item in self: # if seen: # items.append(item) # if item == folderName: # seen = True # # if not seen: # raise exception.PathError(message = "folder {} does not exist in {}".format(folderName, self)) # return Path(self._join(self._drive, items)) # # def __add__(self, other): # if sys.version_info >= (3,0): # supportedTypes = [str, bytes, Path] # else: # supportedTypes = [str, unicode, Path] # # if not any(isinstance(other, t) for t in supportedTypes): # raise exception.PathError(message = "can't add {} to Path only {}".format(type(other), supportedTypes)) # # if not isinstance(other, Path): # other = Path(other) # # # if other path starts with root, throw error # if list(other)[0] == os.path.sep: # raise exception.PathError(message = "can't add {} to Path because it starts at root") # # return Path(self._join(self._drive, list(self) + list(other))) # # def __sub__(self, other): # if sys.version_info >= (3,0): # supportedTypes = [str, bytes, Path] # else: # supportedTypes = [str, unicode, Path] # # if not any(isinstance(other, t) for t in supportedTypes): # raise exception.PathError(message = "can't subtract {} from Path only {}".format(type(other), supportedTypes)) # # if not isinstance(other, Path): # other = Path(other) # # myItems = list(self) # otherItems = list(other) # # for items in (myItems, otherItems): # if len(items) >= 1 and items[0] != os.path.sep and items[0] != ".": # items.insert(0, ".") # # for i in range(min(len(myItems), len(otherItems))): # if myItems[i] != otherItems[i]: # raise exception.PathError(message = "tried subtracting, but subdirs do not match: {} and {}".format(self, other)) # # return Path(self._join(self._drive, myItems[len(otherItems):])) # # def __iter__(self): # for item in self._items: # yield item # # def __hash__(self): # return hash(repr(self)) # # def __eq__(self, other): # return isinstance(other, type(self)) and repr(self) == repr(other) # # def __contains__(self, item): # return str(item) in list(self) # # def __len__(self): # return len(self._items) # # def __str__(self): # return self._join(self._drive, list(self)) # # def __repr__(self): # return "/".join([item for item in self]) # # def _join(self, drive, items): # result = drive # for item in items: # result = os.path.join(result, item) # return result # # CHECKPYPATH = Path(os.path.abspath(os.path.dirname(__file__))[:-len("/entities")]) . Output only the next line.
table.insert({
Here is a snippet: <|code_start|> }) def updateGithubTable(username, repoName, releaseId, releaseTag): query = tinydb.Query() path = str(CHECKPYPATH + "tests" + repoName) githubTable().update({ "user" : username, "repo" : repoName, "path" : path, "release" : releaseId, "tag" : releaseTag, "timestamp" : time.time() }, query.user == username and query.repo == repoName) def timestampGithub(username, repoName): query = tinydb.Query() return githubTable().search(query.user == username and query.repo == repoName)[0]["timestamp"] def setTimestampGithub(username, repoName): query = tinydb.Query() githubTable().update(\ { "timestamp" : time.time() }, query.user == username and query.repo == repoName) def githubPath(username, repoName): query = tinydb.Query() return Path(githubTable().search(query.user == username and query.repo == repoName)[0]["path"]) def releaseId(username, repoName): <|code_end|> . Write the next line using the current file imports: import tinydb import os import time from checkpy.entities.path import Path, CHECKPYPATH and context from other files: # Path: checkpy/entities/path.py # class Path(object): # def __init__(self, path): # path = os.path.normpath(path) # self._drive, path = os.path.splitdrive(path) # # items = str(path).split(os.path.sep) # # if len(items) > 0: # # if path started with root, add root # if items[0] == "": # items[0] = os.path.sep # # # remove any empty items (for instance because of "/") # self._items = [item for item in items if item] # # @property # def fileName(self): # return list(self)[-1] # # @property # def folderName(self): # return list(self)[-2] # # def containingFolder(self): # return Path(self._join(self._drive, list(self)[:-1])) # # def isPythonFile(self): # return self.fileName.endswith(".py") # # def absolutePath(self): # return Path(os.path.abspath(str(self))) # # def exists(self): # return os.path.exists(str(self)) # # def walk(self): # for path, subdirs, files in os.walk(str(self)): # yield Path(path), subdirs, files # # def copyTo(self, destination): # shutil.copyfile(str(self), str(destination)) # # def pathFromFolder(self, folderName): # path = "" # seen = False # items = [] # for item in self: # if seen: # items.append(item) # if item == folderName: # seen = True # # if not seen: # raise exception.PathError(message = "folder {} does not exist in {}".format(folderName, self)) # return Path(self._join(self._drive, items)) # # def __add__(self, other): # if sys.version_info >= (3,0): # supportedTypes = [str, bytes, Path] # else: # supportedTypes = [str, unicode, Path] # # if not any(isinstance(other, t) for t in supportedTypes): # raise exception.PathError(message = "can't add {} to Path only {}".format(type(other), supportedTypes)) # # if not isinstance(other, Path): # other = Path(other) # # # if other path starts with root, throw error # if list(other)[0] == os.path.sep: # raise exception.PathError(message = "can't add {} to Path because it starts at root") # # return Path(self._join(self._drive, list(self) + list(other))) # # def __sub__(self, other): # if sys.version_info >= (3,0): # supportedTypes = [str, bytes, Path] # else: # supportedTypes = [str, unicode, Path] # # if not any(isinstance(other, t) for t in supportedTypes): # raise exception.PathError(message = "can't subtract {} from Path only {}".format(type(other), supportedTypes)) # # if not isinstance(other, Path): # other = Path(other) # # myItems = list(self) # otherItems = list(other) # # for items in (myItems, otherItems): # if len(items) >= 1 and items[0] != os.path.sep and items[0] != ".": # items.insert(0, ".") # # for i in range(min(len(myItems), len(otherItems))): # if myItems[i] != otherItems[i]: # raise exception.PathError(message = "tried subtracting, but subdirs do not match: {} and {}".format(self, other)) # # return Path(self._join(self._drive, myItems[len(otherItems):])) # # def __iter__(self): # for item in self._items: # yield item # # def __hash__(self): # return hash(repr(self)) # # def __eq__(self, other): # return isinstance(other, type(self)) and repr(self) == repr(other) # # def __contains__(self, item): # return str(item) in list(self) # # def __len__(self): # return len(self._items) # # def __str__(self): # return self._join(self._drive, list(self)) # # def __repr__(self): # return "/".join([item for item in self]) # # def _join(self, drive, items): # result = drive # for item in items: # result = os.path.join(result, item) # return result # # CHECKPYPATH = Path(os.path.abspath(os.path.dirname(__file__))[:-len("/entities")]) , which may include functions, classes, or code. Output only the next line.
query = tinydb.Query()
Using the snippet: <|code_start|> log = logging.getLogger('pipelines') class PluginManager(): def __init__(self): self.plugins = {} def get_plugin(self, name): return self.plugins.get(name) def trigger(self, event_name, *args): callbacks = self.plugins.get(event_name, []) results = [] for cb in callbacks: try: ret = cb(*args) results.append(ret) except Exception: log.error('Unknown error running callback {} hook {}, aborting.'.format( cb.__name__, event_name) ) raise <|code_end|> , determine the next line of code. You have imports: import logging from pipelines.plugin.base_plugin import BasePlugin from pipelines.plugin.exceptions import PluginError from pipelines.plugin.utils import class_name from pipelineplugins.dummy_executor import DummyExecutor from pipelineplugins.stdout_logger import StdoutLogger and context (class names, function names, or code) available: # Path: pipelines/plugin/base_plugin.py # class BasePlugin(object): # name = 'undefined' # hooks = [] # dry_run = False # # @classmethod # def from_dict(cls, conf_dict, event_mgr=None): # return cls() # # Path: pipelines/plugin/exceptions.py # class PluginError(RuntimeError): # pass # # Path: pipelines/plugin/utils.py # def class_name(obj): # if isinstance(obj, type): # return obj.__name__ # # if hasattr(obj, '__class__') and hasattr(obj.__class__, '__name__'): # return obj.__class__.__name__ # # return str(obj) . Output only the next line.
return results
Predict the next line for this snippet: <|code_start|> return reduce(lambda counter, p: counter + len(p), self.plugins.values(), 0) if hook_name in self.plugins: return len(self.plugins[hook_name]) return 0 def register_plugin(self, plugin_class, conf_dict): if not issubclass(plugin_class, BasePlugin): raise PluginError('Trying to register plugin that is not extending BasePlugin: {}'.format( class_name(plugin_class)) ) plugin = plugin_class.from_dict(conf_dict, self) for k in ['hook_prefix', 'hooks']: if not hasattr(plugin, k): raise PluginError('Plugin is missing "{}" attribute.'.format(k)) prefix = '{}.'.format(plugin.hook_prefix) if plugin.hook_prefix else '' for hook in plugin.hooks: if not hasattr(plugin, hook): raise PluginError('Plugin {} is missing {}-function'.format( class_name(plugin), hook )) hook_key = '{}{}'.format(prefix, hook) if hook_key not in self.plugins: self.plugins[hook_key] = [] self.plugins[hook_key].append(getattr(plugin, hook)) <|code_end|> with the help of current file imports: import logging from pipelines.plugin.base_plugin import BasePlugin from pipelines.plugin.exceptions import PluginError from pipelines.plugin.utils import class_name from pipelineplugins.dummy_executor import DummyExecutor from pipelineplugins.stdout_logger import StdoutLogger and context from other files: # Path: pipelines/plugin/base_plugin.py # class BasePlugin(object): # name = 'undefined' # hooks = [] # dry_run = False # # @classmethod # def from_dict(cls, conf_dict, event_mgr=None): # return cls() # # Path: pipelines/plugin/exceptions.py # class PluginError(RuntimeError): # pass # # Path: pipelines/plugin/utils.py # def class_name(obj): # if isinstance(obj, type): # return obj.__name__ # # if hasattr(obj, '__class__') and hasattr(obj.__class__, '__name__'): # return obj.__class__.__name__ # # return str(obj) , which may contain function names, class names, or code. Output only the next line.
if __name__ == '__main__':
Here is a snippet: <|code_start|> def trigger(self, event_name, *args): callbacks = self.plugins.get(event_name, []) results = [] for cb in callbacks: try: ret = cb(*args) results.append(ret) except Exception: log.error('Unknown error running callback {} hook {}, aborting.'.format( cb.__name__, event_name) ) raise return results def get_plugin_count(self, hook_name=None): if hook_name is None: return reduce(lambda counter, p: counter + len(p), self.plugins.values(), 0) if hook_name in self.plugins: return len(self.plugins[hook_name]) return 0 def register_plugin(self, plugin_class, conf_dict): if not issubclass(plugin_class, BasePlugin): raise PluginError('Trying to register plugin that is not extending BasePlugin: {}'.format( class_name(plugin_class)) ) plugin = plugin_class.from_dict(conf_dict, self) <|code_end|> . Write the next line using the current file imports: import logging from pipelines.plugin.base_plugin import BasePlugin from pipelines.plugin.exceptions import PluginError from pipelines.plugin.utils import class_name from pipelineplugins.dummy_executor import DummyExecutor from pipelineplugins.stdout_logger import StdoutLogger and context from other files: # Path: pipelines/plugin/base_plugin.py # class BasePlugin(object): # name = 'undefined' # hooks = [] # dry_run = False # # @classmethod # def from_dict(cls, conf_dict, event_mgr=None): # return cls() # # Path: pipelines/plugin/exceptions.py # class PluginError(RuntimeError): # pass # # Path: pipelines/plugin/utils.py # def class_name(obj): # if isinstance(obj, type): # return obj.__name__ # # if hasattr(obj, '__class__') and hasattr(obj.__class__, '__name__'): # return obj.__class__.__name__ # # return str(obj) , which may include functions, classes, or code. Output only the next line.
for k in ['hook_prefix', 'hooks']:
Given the code snippet: <|code_start|> log = logging.getLogger('pipelines') RETRY_COUNT = 2 class SlackExecutor(BaseExecutorPlugin): hook_prefix = 'slack' hooks = ('execute',) # webhook_url = 'https://hooks.slack.com/services/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' def __init__(self, slack_webhook): self.slack_webhook = slack_webhook def execute(self, args_dict): <|code_end|> , generate the next line using the imports in this file: import logging import requests from pipelines.plugins.base_executor import BaseExecutorPlugin from pipelines.pipeline.task import TaskResult, EXECUTION_SUCCESSFUL, EXECUTION_FAILED from pipelines.plugin.exceptions import PluginError and context (functions, classes, or occasionally code) from other files: # Path: pipelines/plugins/base_executor.py # class BaseExecutorPlugin(BasePlugin): # dry_run = False # # def call(self, *args, **kwargs): # result = self.execute(*args, **kwargs) # if not isinstance(result, TaskResult): # raise PipelineError('Executor did not return type ExecutionResult, got {}'.format(type(result))) # # return result # # def execute(self, command): # print 'Running executor with command: %s' % command # # Path: pipelines/pipeline/task.py # class TaskResult(dict): # def __init__(self, status, message='', data={}, return_obj={}): # self['status'] = status # self['message'] = message # self['data'] = data # self['return_obj'] = return_obj # # @property # def status(self): # return self.get('status') # # @property # def message(self): # return self.get('message') # # @property # def data(self): # return self.get('data') # # @property # def return_obj(self): # return self.get('return_obj') # # def is_successful(self): # return self.status == EXECUTION_SUCCESSFUL # # EXECUTION_SUCCESSFUL = 0 # # EXECUTION_FAILED = 1 # # Path: pipelines/plugin/exceptions.py # class PluginError(RuntimeError): # pass . Output only the next line.
if not self.slack_webhook:
Given the following code snippet before the placeholder: <|code_start|> # webhook_url = 'https://hooks.slack.com/services/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' def __init__(self, slack_webhook): self.slack_webhook = slack_webhook def execute(self, args_dict): if not self.slack_webhook: raise PluginError('SlackExecutor is missing slack_webhook parameter. Can not execute') if 'message' not in args_dict: raise PluginError('SlackExecutor got incorrect arguments, got: {}'.format( args_dict.keys() )) message = args_dict['message'] if self.dry_run: return TaskResult(EXECUTION_SUCCESSFUL) payload = { 'username': 'Pipelines', 'link_names': 1, 'text': message } for i in range(RETRY_COUNT + 1): resp = requests.post(self.slack_webhook, json=payload) if resp.ok: log.debug('Successfully sent slack message') break log.debug('Problem sending slack message. Status {}'.format(resp.status_code)) <|code_end|> , predict the next line using imports from the current file: import logging import requests from pipelines.plugins.base_executor import BaseExecutorPlugin from pipelines.pipeline.task import TaskResult, EXECUTION_SUCCESSFUL, EXECUTION_FAILED from pipelines.plugin.exceptions import PluginError and context including class names, function names, and sometimes code from other files: # Path: pipelines/plugins/base_executor.py # class BaseExecutorPlugin(BasePlugin): # dry_run = False # # def call(self, *args, **kwargs): # result = self.execute(*args, **kwargs) # if not isinstance(result, TaskResult): # raise PipelineError('Executor did not return type ExecutionResult, got {}'.format(type(result))) # # return result # # def execute(self, command): # print 'Running executor with command: %s' % command # # Path: pipelines/pipeline/task.py # class TaskResult(dict): # def __init__(self, status, message='', data={}, return_obj={}): # self['status'] = status # self['message'] = message # self['data'] = data # self['return_obj'] = return_obj # # @property # def status(self): # return self.get('status') # # @property # def message(self): # return self.get('message') # # @property # def data(self): # return self.get('data') # # @property # def return_obj(self): # return self.get('return_obj') # # def is_successful(self): # return self.status == EXECUTION_SUCCESSFUL # # EXECUTION_SUCCESSFUL = 0 # # EXECUTION_FAILED = 1 # # Path: pipelines/plugin/exceptions.py # class PluginError(RuntimeError): # pass . Output only the next line.
else:
Given snippet: <|code_start|> log = logging.getLogger('pipelines') RETRY_COUNT = 2 class SlackExecutor(BaseExecutorPlugin): hook_prefix = 'slack' hooks = ('execute',) # webhook_url = 'https://hooks.slack.com/services/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' def __init__(self, slack_webhook): self.slack_webhook = slack_webhook def execute(self, args_dict): if not self.slack_webhook: raise PluginError('SlackExecutor is missing slack_webhook parameter. Can not execute') if 'message' not in args_dict: raise PluginError('SlackExecutor got incorrect arguments, got: {}'.format( args_dict.keys() )) message = args_dict['message'] if self.dry_run: return TaskResult(EXECUTION_SUCCESSFUL) payload = { <|code_end|> , continue by predicting the next line. Consider current file imports: import logging import requests from pipelines.plugins.base_executor import BaseExecutorPlugin from pipelines.pipeline.task import TaskResult, EXECUTION_SUCCESSFUL, EXECUTION_FAILED from pipelines.plugin.exceptions import PluginError and context: # Path: pipelines/plugins/base_executor.py # class BaseExecutorPlugin(BasePlugin): # dry_run = False # # def call(self, *args, **kwargs): # result = self.execute(*args, **kwargs) # if not isinstance(result, TaskResult): # raise PipelineError('Executor did not return type ExecutionResult, got {}'.format(type(result))) # # return result # # def execute(self, command): # print 'Running executor with command: %s' % command # # Path: pipelines/pipeline/task.py # class TaskResult(dict): # def __init__(self, status, message='', data={}, return_obj={}): # self['status'] = status # self['message'] = message # self['data'] = data # self['return_obj'] = return_obj # # @property # def status(self): # return self.get('status') # # @property # def message(self): # return self.get('message') # # @property # def data(self): # return self.get('data') # # @property # def return_obj(self): # return self.get('return_obj') # # def is_successful(self): # return self.status == EXECUTION_SUCCESSFUL # # EXECUTION_SUCCESSFUL = 0 # # EXECUTION_FAILED = 1 # # Path: pipelines/plugin/exceptions.py # class PluginError(RuntimeError): # pass which might include code, classes, or functions. Output only the next line.
'username': 'Pipelines',
Given the following code snippet before the placeholder: <|code_start|> log = logging.getLogger('pipelines') RETRY_COUNT = 2 class SlackExecutor(BaseExecutorPlugin): hook_prefix = 'slack' hooks = ('execute',) # webhook_url = 'https://hooks.slack.com/services/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' def __init__(self, slack_webhook): self.slack_webhook = slack_webhook def execute(self, args_dict): if not self.slack_webhook: raise PluginError('SlackExecutor is missing slack_webhook parameter. Can not execute') <|code_end|> , predict the next line using imports from the current file: import logging import requests from pipelines.plugins.base_executor import BaseExecutorPlugin from pipelines.pipeline.task import TaskResult, EXECUTION_SUCCESSFUL, EXECUTION_FAILED from pipelines.plugin.exceptions import PluginError and context including class names, function names, and sometimes code from other files: # Path: pipelines/plugins/base_executor.py # class BaseExecutorPlugin(BasePlugin): # dry_run = False # # def call(self, *args, **kwargs): # result = self.execute(*args, **kwargs) # if not isinstance(result, TaskResult): # raise PipelineError('Executor did not return type ExecutionResult, got {}'.format(type(result))) # # return result # # def execute(self, command): # print 'Running executor with command: %s' % command # # Path: pipelines/pipeline/task.py # class TaskResult(dict): # def __init__(self, status, message='', data={}, return_obj={}): # self['status'] = status # self['message'] = message # self['data'] = data # self['return_obj'] = return_obj # # @property # def status(self): # return self.get('status') # # @property # def message(self): # return self.get('message') # # @property # def data(self): # return self.get('data') # # @property # def return_obj(self): # return self.get('return_obj') # # def is_successful(self): # return self.status == EXECUTION_SUCCESSFUL # # EXECUTION_SUCCESSFUL = 0 # # EXECUTION_FAILED = 1 # # Path: pipelines/plugin/exceptions.py # class PluginError(RuntimeError): # pass . Output only the next line.
if 'message' not in args_dict:
Continue the code snippet: <|code_start|> message = args_dict['message'] if self.dry_run: return TaskResult(EXECUTION_SUCCESSFUL) payload = { 'username': 'Pipelines', 'link_names': 1, 'text': message } for i in range(RETRY_COUNT + 1): resp = requests.post(self.slack_webhook, json=payload) if resp.ok: log.debug('Successfully sent slack message') break log.debug('Problem sending slack message. Status {}'.format(resp.status_code)) else: log.warning('Could not successfully send slack message. Status: {}'.format(resp.status_code)) return TaskResult(EXECUTION_FAILED, 'Sending slack notification failed') return TaskResult(EXECUTION_SUCCESSFUL, 'Sending slack notification successful') def _parse_args_dict(self, args_dict): return args_dict['message'] @classmethod def from_dict(cls, conf_dict, event_mgr=None): if 'slack_webhook' not in conf_dict: log.debug('SlackExecutor is missing slack_webhook parameter') <|code_end|> . Use current file imports: import logging import requests from pipelines.plugins.base_executor import BaseExecutorPlugin from pipelines.pipeline.task import TaskResult, EXECUTION_SUCCESSFUL, EXECUTION_FAILED from pipelines.plugin.exceptions import PluginError and context (classes, functions, or code) from other files: # Path: pipelines/plugins/base_executor.py # class BaseExecutorPlugin(BasePlugin): # dry_run = False # # def call(self, *args, **kwargs): # result = self.execute(*args, **kwargs) # if not isinstance(result, TaskResult): # raise PipelineError('Executor did not return type ExecutionResult, got {}'.format(type(result))) # # return result # # def execute(self, command): # print 'Running executor with command: %s' % command # # Path: pipelines/pipeline/task.py # class TaskResult(dict): # def __init__(self, status, message='', data={}, return_obj={}): # self['status'] = status # self['message'] = message # self['data'] = data # self['return_obj'] = return_obj # # @property # def status(self): # return self.get('status') # # @property # def message(self): # return self.get('message') # # @property # def data(self): # return self.get('data') # # @property # def return_obj(self): # return self.get('return_obj') # # def is_successful(self): # return self.status == EXECUTION_SUCCESSFUL # # EXECUTION_SUCCESSFUL = 0 # # EXECUTION_FAILED = 1 # # Path: pipelines/plugin/exceptions.py # class PluginError(RuntimeError): # pass . Output only the next line.
else:
Next line prediction: <|code_start|> log = logging.getLogger('pipelines') VAR_LOG_MAX_LEN = 3000 class StdoutLogger(BasePlugin): hook_prefix = '' hooks = ( 'on_pipeline_start', <|code_end|> . Use current file imports: (import json import yaml import logging from datetime import datetime from pipelines.plugin.base_plugin import BasePlugin) and context including class names, function names, or small code snippets from other files: # Path: pipelines/plugin/base_plugin.py # class BasePlugin(object): # name = 'undefined' # hooks = [] # dry_run = False # # @classmethod # def from_dict(cls, conf_dict, event_mgr=None): # return cls() . Output only the next line.
'on_task_start',
Continue the code snippet: <|code_start|> class BaseExecutorPlugin(BasePlugin): dry_run = False def call(self, *args, **kwargs): result = self.execute(*args, **kwargs) if not isinstance(result, TaskResult): raise PipelineError('Executor did not return type ExecutionResult, got {}'.format(type(result))) return result def execute(self, command): <|code_end|> . Use current file imports: from pipelines.pipeline.exceptions import PipelineError from pipelines.pipeline.task import TaskResult from pipelines.plugin.base_plugin import BasePlugin and context (classes, functions, or code) from other files: # Path: pipelines/pipeline/exceptions.py # class PipelineError(RuntimeError): # pass # # Path: pipelines/pipeline/task.py # class TaskResult(dict): # def __init__(self, status, message='', data={}, return_obj={}): # self['status'] = status # self['message'] = message # self['data'] = data # self['return_obj'] = return_obj # # @property # def status(self): # return self.get('status') # # @property # def message(self): # return self.get('message') # # @property # def data(self): # return self.get('data') # # @property # def return_obj(self): # return self.get('return_obj') # # def is_successful(self): # return self.status == EXECUTION_SUCCESSFUL # # Path: pipelines/plugin/base_plugin.py # class BasePlugin(object): # name = 'undefined' # hooks = [] # dry_run = False # # @classmethod # def from_dict(cls, conf_dict, event_mgr=None): # return cls() . Output only the next line.
print 'Running executor with command: %s' % command
Predict the next line for this snippet: <|code_start|> log = logging.getLogger('pipelines') def class_name(obj): if isinstance(obj, type): return obj.__name__ if hasattr(obj, '__class__') and hasattr(obj.__class__, '__name__'): <|code_end|> with the help of current file imports: import json import logging from datetime import datetime, timedelta from pipelines.pipeline.task import Task, TaskResult and context from other files: # Path: pipelines/pipeline/task.py # class Task(object): # def __init__(self, name, executor, args, always_run, ignore_errors, timeout): # self.name = name # self.executor = executor # self.args = args # self.always_run = always_run # self.ignore_errors = ignore_errors # self.timeout = timeout # # @staticmethod # def from_dict(task_dict): # task_args = copy(task_dict) # executor = task_args.pop('type') # # name = '' # if 'name' in task_dict: # name = task_dict.pop('name') # # always_run = False # if 'always_run' in task_dict: # always_run = task_dict.pop('always_run') # # ignore_errors = False # if 'ignore_errors' in task_dict: # ignore_errors = task_dict.pop('ignore_errors') # # timeout = False # if 'timeout' in task_dict: # timeout = task_dict.pop('timeout') # # return Task(name, executor, task_args, always_run, ignore_errors, timeout) # # class TaskResult(dict): # def __init__(self, status, message='', data={}, return_obj={}): # self['status'] = status # self['message'] = message # self['data'] = data # self['return_obj'] = return_obj # # @property # def status(self): # return self.get('status') # # @property # def message(self): # return self.get('message') # # @property # def data(self): # return self.get('data') # # @property # def return_obj(self): # return self.get('return_obj') # # def is_successful(self): # return self.status == EXECUTION_SUCCESSFUL , which may contain function names, class names, or code. Output only the next line.
return obj.__class__.__name__
Next line prediction: <|code_start|> conf_logging() class TestPythonExecutor(TestCase): def test_basic_script(self): print 'Running test_basic_script' executor = PythonExecutor() args = { 'script': 'print "test"' } res = executor.execute(args) self.assertIsInstance(res, TaskResult) self.assertEqual(res.status, EXECUTION_SUCCESSFUL) self.assertEqual(res.message.strip(), 'Execution finished') self.assertEqual(res.data['output'], u'test\n') def test_basic_file(self): print 'Running test_basic_script' executor = PythonExecutor() args = { 'file': 'test/files/test_python_file.py' <|code_end|> . Use current file imports: (import os import unittest from unittest.case import TestCase from pipelines.pipeline.task import TaskResult, EXECUTION_SUCCESSFUL from pipelines.plugins.python_executor import PythonExecutor from pipelines.utils import conf_logging) and context including class names, function names, or small code snippets from other files: # Path: pipelines/pipeline/task.py # class TaskResult(dict): # def __init__(self, status, message='', data={}, return_obj={}): # self['status'] = status # self['message'] = message # self['data'] = data # self['return_obj'] = return_obj # # @property # def status(self): # return self.get('status') # # @property # def message(self): # return self.get('message') # # @property # def data(self): # return self.get('data') # # @property # def return_obj(self): # return self.get('return_obj') # # def is_successful(self): # return self.status == EXECUTION_SUCCESSFUL # # EXECUTION_SUCCESSFUL = 0 # # Path: pipelines/plugins/python_executor.py # class PythonExecutor(BashExecutor): # hook_prefix = 'python' # hooks = ('execute',) # # def _validate_args_dict(self, args_dict): # if 'file' not in args_dict and 'script' not in args_dict: # raise PluginError('PythonExecutor requires either "file" or "script" arguments. Given: {}'.format(args_dict)) # # if args_dict.get('file') and args_dict.get('script'): # raise PluginError( # 'PythonExecutor got both "file" and "script" aguments. Only one is supported.') # # if args_dict.get('workspace') and args_dict.get('script'): # raise PluginError('PythonExecutor requires either "file" or "script" arguments. Given: {}'.format(args_dict)) # # def execute(self, args_dict): # self._validate_args_dict(args_dict) # workdir = args_dict.get('workdir') # script = args_dict.get('script') # file = args_dict.get('file') # virtualenv = args_dict.get('virtualenv') # # bash_input = '' # if workdir: # bash_input += 'cd {}\n'.format(workdir) # # if virtualenv: # activate_path = path.join(virtualenv, 'bin', 'activate') # if not path.exists(activate_path) or not path.isfile(activate_path): # raise PluginError('Python virtualenv doesn\'t exist: {}'.format(activate_path)) # # bash_input += 'source {}\n'.format(activate_path) # # filename = file # # if script: # f = NamedTemporaryFile(delete=False) # # f.write(script) # log.debug('Wrote script to file {}, {}'.format(f.name, script)) # filename = f.name # f.close() # # bash_input += 'python {}'.format(filename) # log.debug('Running python script: {}'.format(bash_input)) # # if self.dry_run: # return TaskResult(EXECUTION_SUCCESSFUL) # # return_obj=None # try: # stdout, return_obj = self._run_bash(bash_input) # status = EXECUTION_SUCCESSFUL # except BashExecuteError as e: # status = EXECUTION_FAILED # stdout = e.data.get('stdout') # print 'Finished, stdout: %s' % (stdout) # # return TaskResult(status, 'Execution finished', data={'output': stdout}, return_obj=return_obj) # # Path: pipelines/utils.py # def conf_logging(): # logger = logging.getLogger('pipelines') # logger.setLevel(logging.DEBUG) # formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') # logger.propagate = False # # ch = logging.StreamHandler() # ch.setFormatter(formatter) # ch.setLevel(logging.DEBUG) # # logger.addHandler(ch) . Output only the next line.
}
Given snippet: <|code_start|> conf_logging() class TestPythonExecutor(TestCase): def test_basic_script(self): print 'Running test_basic_script' executor = PythonExecutor() args = { 'script': 'print "test"' } <|code_end|> , continue by predicting the next line. Consider current file imports: import os import unittest from unittest.case import TestCase from pipelines.pipeline.task import TaskResult, EXECUTION_SUCCESSFUL from pipelines.plugins.python_executor import PythonExecutor from pipelines.utils import conf_logging and context: # Path: pipelines/pipeline/task.py # class TaskResult(dict): # def __init__(self, status, message='', data={}, return_obj={}): # self['status'] = status # self['message'] = message # self['data'] = data # self['return_obj'] = return_obj # # @property # def status(self): # return self.get('status') # # @property # def message(self): # return self.get('message') # # @property # def data(self): # return self.get('data') # # @property # def return_obj(self): # return self.get('return_obj') # # def is_successful(self): # return self.status == EXECUTION_SUCCESSFUL # # EXECUTION_SUCCESSFUL = 0 # # Path: pipelines/plugins/python_executor.py # class PythonExecutor(BashExecutor): # hook_prefix = 'python' # hooks = ('execute',) # # def _validate_args_dict(self, args_dict): # if 'file' not in args_dict and 'script' not in args_dict: # raise PluginError('PythonExecutor requires either "file" or "script" arguments. Given: {}'.format(args_dict)) # # if args_dict.get('file') and args_dict.get('script'): # raise PluginError( # 'PythonExecutor got both "file" and "script" aguments. Only one is supported.') # # if args_dict.get('workspace') and args_dict.get('script'): # raise PluginError('PythonExecutor requires either "file" or "script" arguments. Given: {}'.format(args_dict)) # # def execute(self, args_dict): # self._validate_args_dict(args_dict) # workdir = args_dict.get('workdir') # script = args_dict.get('script') # file = args_dict.get('file') # virtualenv = args_dict.get('virtualenv') # # bash_input = '' # if workdir: # bash_input += 'cd {}\n'.format(workdir) # # if virtualenv: # activate_path = path.join(virtualenv, 'bin', 'activate') # if not path.exists(activate_path) or not path.isfile(activate_path): # raise PluginError('Python virtualenv doesn\'t exist: {}'.format(activate_path)) # # bash_input += 'source {}\n'.format(activate_path) # # filename = file # # if script: # f = NamedTemporaryFile(delete=False) # # f.write(script) # log.debug('Wrote script to file {}, {}'.format(f.name, script)) # filename = f.name # f.close() # # bash_input += 'python {}'.format(filename) # log.debug('Running python script: {}'.format(bash_input)) # # if self.dry_run: # return TaskResult(EXECUTION_SUCCESSFUL) # # return_obj=None # try: # stdout, return_obj = self._run_bash(bash_input) # status = EXECUTION_SUCCESSFUL # except BashExecuteError as e: # status = EXECUTION_FAILED # stdout = e.data.get('stdout') # print 'Finished, stdout: %s' % (stdout) # # return TaskResult(status, 'Execution finished', data={'output': stdout}, return_obj=return_obj) # # Path: pipelines/utils.py # def conf_logging(): # logger = logging.getLogger('pipelines') # logger.setLevel(logging.DEBUG) # formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') # logger.propagate = False # # ch = logging.StreamHandler() # ch.setFormatter(formatter) # ch.setLevel(logging.DEBUG) # # logger.addHandler(ch) which might include code, classes, or functions. Output only the next line.
res = executor.execute(args)
Predict the next line after this snippet: <|code_start|> conf_logging() class TestPythonExecutor(TestCase): def test_basic_script(self): print 'Running test_basic_script' executor = PythonExecutor() args = { 'script': 'print "test"' } res = executor.execute(args) self.assertIsInstance(res, TaskResult) self.assertEqual(res.status, EXECUTION_SUCCESSFUL) <|code_end|> using the current file's imports: import os import unittest from unittest.case import TestCase from pipelines.pipeline.task import TaskResult, EXECUTION_SUCCESSFUL from pipelines.plugins.python_executor import PythonExecutor from pipelines.utils import conf_logging and any relevant context from other files: # Path: pipelines/pipeline/task.py # class TaskResult(dict): # def __init__(self, status, message='', data={}, return_obj={}): # self['status'] = status # self['message'] = message # self['data'] = data # self['return_obj'] = return_obj # # @property # def status(self): # return self.get('status') # # @property # def message(self): # return self.get('message') # # @property # def data(self): # return self.get('data') # # @property # def return_obj(self): # return self.get('return_obj') # # def is_successful(self): # return self.status == EXECUTION_SUCCESSFUL # # EXECUTION_SUCCESSFUL = 0 # # Path: pipelines/plugins/python_executor.py # class PythonExecutor(BashExecutor): # hook_prefix = 'python' # hooks = ('execute',) # # def _validate_args_dict(self, args_dict): # if 'file' not in args_dict and 'script' not in args_dict: # raise PluginError('PythonExecutor requires either "file" or "script" arguments. Given: {}'.format(args_dict)) # # if args_dict.get('file') and args_dict.get('script'): # raise PluginError( # 'PythonExecutor got both "file" and "script" aguments. Only one is supported.') # # if args_dict.get('workspace') and args_dict.get('script'): # raise PluginError('PythonExecutor requires either "file" or "script" arguments. Given: {}'.format(args_dict)) # # def execute(self, args_dict): # self._validate_args_dict(args_dict) # workdir = args_dict.get('workdir') # script = args_dict.get('script') # file = args_dict.get('file') # virtualenv = args_dict.get('virtualenv') # # bash_input = '' # if workdir: # bash_input += 'cd {}\n'.format(workdir) # # if virtualenv: # activate_path = path.join(virtualenv, 'bin', 'activate') # if not path.exists(activate_path) or not path.isfile(activate_path): # raise PluginError('Python virtualenv doesn\'t exist: {}'.format(activate_path)) # # bash_input += 'source {}\n'.format(activate_path) # # filename = file # # if script: # f = NamedTemporaryFile(delete=False) # # f.write(script) # log.debug('Wrote script to file {}, {}'.format(f.name, script)) # filename = f.name # f.close() # # bash_input += 'python {}'.format(filename) # log.debug('Running python script: {}'.format(bash_input)) # # if self.dry_run: # return TaskResult(EXECUTION_SUCCESSFUL) # # return_obj=None # try: # stdout, return_obj = self._run_bash(bash_input) # status = EXECUTION_SUCCESSFUL # except BashExecuteError as e: # status = EXECUTION_FAILED # stdout = e.data.get('stdout') # print 'Finished, stdout: %s' % (stdout) # # return TaskResult(status, 'Execution finished', data={'output': stdout}, return_obj=return_obj) # # Path: pipelines/utils.py # def conf_logging(): # logger = logging.getLogger('pipelines') # logger.setLevel(logging.DEBUG) # formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') # logger.propagate = False # # ch = logging.StreamHandler() # ch.setFormatter(formatter) # ch.setLevel(logging.DEBUG) # # logger.addHandler(ch) . Output only the next line.
self.assertEqual(res.message.strip(), 'Execution finished')
Predict the next line after this snippet: <|code_start|> conf_logging() class TestPythonExecutor(TestCase): def test_basic_script(self): print 'Running test_basic_script' executor = PythonExecutor() args = { 'script': 'print "test"' } res = executor.execute(args) self.assertIsInstance(res, TaskResult) self.assertEqual(res.status, EXECUTION_SUCCESSFUL) self.assertEqual(res.message.strip(), 'Execution finished') self.assertEqual(res.data['output'], u'test\n') def test_basic_file(self): print 'Running test_basic_script' executor = PythonExecutor() args = { 'file': 'test/files/test_python_file.py' } <|code_end|> using the current file's imports: import os import unittest from unittest.case import TestCase from pipelines.pipeline.task import TaskResult, EXECUTION_SUCCESSFUL from pipelines.plugins.python_executor import PythonExecutor from pipelines.utils import conf_logging and any relevant context from other files: # Path: pipelines/pipeline/task.py # class TaskResult(dict): # def __init__(self, status, message='', data={}, return_obj={}): # self['status'] = status # self['message'] = message # self['data'] = data # self['return_obj'] = return_obj # # @property # def status(self): # return self.get('status') # # @property # def message(self): # return self.get('message') # # @property # def data(self): # return self.get('data') # # @property # def return_obj(self): # return self.get('return_obj') # # def is_successful(self): # return self.status == EXECUTION_SUCCESSFUL # # EXECUTION_SUCCESSFUL = 0 # # Path: pipelines/plugins/python_executor.py # class PythonExecutor(BashExecutor): # hook_prefix = 'python' # hooks = ('execute',) # # def _validate_args_dict(self, args_dict): # if 'file' not in args_dict and 'script' not in args_dict: # raise PluginError('PythonExecutor requires either "file" or "script" arguments. Given: {}'.format(args_dict)) # # if args_dict.get('file') and args_dict.get('script'): # raise PluginError( # 'PythonExecutor got both "file" and "script" aguments. Only one is supported.') # # if args_dict.get('workspace') and args_dict.get('script'): # raise PluginError('PythonExecutor requires either "file" or "script" arguments. Given: {}'.format(args_dict)) # # def execute(self, args_dict): # self._validate_args_dict(args_dict) # workdir = args_dict.get('workdir') # script = args_dict.get('script') # file = args_dict.get('file') # virtualenv = args_dict.get('virtualenv') # # bash_input = '' # if workdir: # bash_input += 'cd {}\n'.format(workdir) # # if virtualenv: # activate_path = path.join(virtualenv, 'bin', 'activate') # if not path.exists(activate_path) or not path.isfile(activate_path): # raise PluginError('Python virtualenv doesn\'t exist: {}'.format(activate_path)) # # bash_input += 'source {}\n'.format(activate_path) # # filename = file # # if script: # f = NamedTemporaryFile(delete=False) # # f.write(script) # log.debug('Wrote script to file {}, {}'.format(f.name, script)) # filename = f.name # f.close() # # bash_input += 'python {}'.format(filename) # log.debug('Running python script: {}'.format(bash_input)) # # if self.dry_run: # return TaskResult(EXECUTION_SUCCESSFUL) # # return_obj=None # try: # stdout, return_obj = self._run_bash(bash_input) # status = EXECUTION_SUCCESSFUL # except BashExecuteError as e: # status = EXECUTION_FAILED # stdout = e.data.get('stdout') # print 'Finished, stdout: %s' % (stdout) # # return TaskResult(status, 'Execution finished', data={'output': stdout}, return_obj=return_obj) # # Path: pipelines/utils.py # def conf_logging(): # logger = logging.getLogger('pipelines') # logger.setLevel(logging.DEBUG) # formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') # logger.propagate = False # # ch = logging.StreamHandler() # ch.setFormatter(formatter) # ch.setLevel(logging.DEBUG) # # logger.addHandler(ch) . Output only the next line.
res = executor.execute(args)
Given the following code snippet before the placeholder: <|code_start|> log = logging.getLogger('pipelines') class StatusLogger(BasePlugin): hook_prefix = '' hooks = ( 'on_pipeline_start', 'on_pipeline_finish', ) file_path = None def __init__(self, file_path=None): super(StatusLogger, self).__init__() if file_path: self.file_path = file_path @classmethod def from_dict(cls, conf_dict, event_mgr=None): return StatusLogger(conf_dict.get('status_file')) def on_pipeline_start(self, *args): self._write({ 'status': 'running', 'start_time': datetime.utcnow().isoformat() }) <|code_end|> , predict the next line using imports from the current file: import json import logging import os.path from datetime import datetime from pipelines.plugin.base_plugin import BasePlugin and context including class names, function names, and sometimes code from other files: # Path: pipelines/plugin/base_plugin.py # class BasePlugin(object): # name = 'undefined' # hooks = [] # dry_run = False # # @classmethod # def from_dict(cls, conf_dict, event_mgr=None): # return cls() . Output only the next line.
def on_pipeline_finish(self, pipeline_context):
Continue the code snippet: <|code_start|> if self.dry_run: return TaskResult(EXECUTION_SUCCESSFUL) try: output, return_obj = self._run_bash(cmd, timeout) status = EXECUTION_SUCCESSFUL msg = 'Bash task finished' except BashExecuteError as e: status = EXECUTION_FAILED # stdout = e.stderr msg = 'Bash task failed: %s' % e.msg output = e.data['stdout'] return TaskResult(status, msg, data={'output': output}, return_obj=return_obj) def _run_bash(self, bash_input, timeout=DEFAULT_TIMEOUT): log.debug('Running bash command: "{}"'.format(bash_input)) f = None if self.log_file: f = open(self.log_file, 'a+') output = {'stdout': '', 'last_line': ''} try: def process_line(line): log.debug('Got line: %s' % line) output['stdout'] += line if line and line.strip(): <|code_end|> . Use current file imports: import logging import json from pipelines.plugins.base_executor import BaseExecutorPlugin from pipelines.pipeline.task import TaskResult, EXECUTION_SUCCESSFUL, EXECUTION_FAILED from pipelines.plugin.exceptions import PluginError from sh import ErrorReturnCode, TimeoutException from sh import bash and context (classes, functions, or code) from other files: # Path: pipelines/plugins/base_executor.py # class BaseExecutorPlugin(BasePlugin): # dry_run = False # # def call(self, *args, **kwargs): # result = self.execute(*args, **kwargs) # if not isinstance(result, TaskResult): # raise PipelineError('Executor did not return type ExecutionResult, got {}'.format(type(result))) # # return result # # def execute(self, command): # print 'Running executor with command: %s' % command # # Path: pipelines/pipeline/task.py # class TaskResult(dict): # def __init__(self, status, message='', data={}, return_obj={}): # self['status'] = status # self['message'] = message # self['data'] = data # self['return_obj'] = return_obj # # @property # def status(self): # return self.get('status') # # @property # def message(self): # return self.get('message') # # @property # def data(self): # return self.get('data') # # @property # def return_obj(self): # return self.get('return_obj') # # def is_successful(self): # return self.status == EXECUTION_SUCCESSFUL # # EXECUTION_SUCCESSFUL = 0 # # EXECUTION_FAILED = 1 # # Path: pipelines/plugin/exceptions.py # class PluginError(RuntimeError): # pass . Output only the next line.
output['last_line'] = line
Continue the code snippet: <|code_start|>DEFAULT_TIMEOUT = 60*60 # Timeout to 1h class BashExecuteError(PluginError): def __init__(self, msg, code, data={}): self.msg = msg self.code = code self.data = data class BashExecutor(BaseExecutorPlugin): hook_prefix = 'bash' hooks = ('execute',) def __init__(self, log_file=None, event_mgr=None): self.log_file = log_file self.event_mgr = event_mgr log.debug('Bash executor initiated with log_file: %s' % self.log_file) def _parse_args_dict(self, args_dict): if 'cmd' not in args_dict: raise PluginError('BashExecutor got incorrect arguments, got: {}'.format( args_dict.keys() )) timeout = args_dict.get('timeout') or DEFAULT_TIMEOUT if not isinstance(timeout, int): raise PluginError('BashExecutor got incorrect timeout argument type, got: {} expecting int'.format( type(timeout) )) <|code_end|> . Use current file imports: import logging import json from pipelines.plugins.base_executor import BaseExecutorPlugin from pipelines.pipeline.task import TaskResult, EXECUTION_SUCCESSFUL, EXECUTION_FAILED from pipelines.plugin.exceptions import PluginError from sh import ErrorReturnCode, TimeoutException from sh import bash and context (classes, functions, or code) from other files: # Path: pipelines/plugins/base_executor.py # class BaseExecutorPlugin(BasePlugin): # dry_run = False # # def call(self, *args, **kwargs): # result = self.execute(*args, **kwargs) # if not isinstance(result, TaskResult): # raise PipelineError('Executor did not return type ExecutionResult, got {}'.format(type(result))) # # return result # # def execute(self, command): # print 'Running executor with command: %s' % command # # Path: pipelines/pipeline/task.py # class TaskResult(dict): # def __init__(self, status, message='', data={}, return_obj={}): # self['status'] = status # self['message'] = message # self['data'] = data # self['return_obj'] = return_obj # # @property # def status(self): # return self.get('status') # # @property # def message(self): # return self.get('message') # # @property # def data(self): # return self.get('data') # # @property # def return_obj(self): # return self.get('return_obj') # # def is_successful(self): # return self.status == EXECUTION_SUCCESSFUL # # EXECUTION_SUCCESSFUL = 0 # # EXECUTION_FAILED = 1 # # Path: pipelines/plugin/exceptions.py # class PluginError(RuntimeError): # pass . Output only the next line.
return args_dict['cmd'], timeout
Continue the code snippet: <|code_start|> return TaskResult(EXECUTION_SUCCESSFUL) try: output, return_obj = self._run_bash(cmd, timeout) status = EXECUTION_SUCCESSFUL msg = 'Bash task finished' except BashExecuteError as e: status = EXECUTION_FAILED # stdout = e.stderr msg = 'Bash task failed: %s' % e.msg output = e.data['stdout'] return TaskResult(status, msg, data={'output': output}, return_obj=return_obj) def _run_bash(self, bash_input, timeout=DEFAULT_TIMEOUT): log.debug('Running bash command: "{}"'.format(bash_input)) f = None if self.log_file: f = open(self.log_file, 'a+') output = {'stdout': '', 'last_line': ''} try: def process_line(line): log.debug('Got line: %s' % line) output['stdout'] += line if line and line.strip(): output['last_line'] = line <|code_end|> . Use current file imports: import logging import json from pipelines.plugins.base_executor import BaseExecutorPlugin from pipelines.pipeline.task import TaskResult, EXECUTION_SUCCESSFUL, EXECUTION_FAILED from pipelines.plugin.exceptions import PluginError from sh import ErrorReturnCode, TimeoutException from sh import bash and context (classes, functions, or code) from other files: # Path: pipelines/plugins/base_executor.py # class BaseExecutorPlugin(BasePlugin): # dry_run = False # # def call(self, *args, **kwargs): # result = self.execute(*args, **kwargs) # if not isinstance(result, TaskResult): # raise PipelineError('Executor did not return type ExecutionResult, got {}'.format(type(result))) # # return result # # def execute(self, command): # print 'Running executor with command: %s' % command # # Path: pipelines/pipeline/task.py # class TaskResult(dict): # def __init__(self, status, message='', data={}, return_obj={}): # self['status'] = status # self['message'] = message # self['data'] = data # self['return_obj'] = return_obj # # @property # def status(self): # return self.get('status') # # @property # def message(self): # return self.get('message') # # @property # def data(self): # return self.get('data') # # @property # def return_obj(self): # return self.get('return_obj') # # def is_successful(self): # return self.status == EXECUTION_SUCCESSFUL # # EXECUTION_SUCCESSFUL = 0 # # EXECUTION_FAILED = 1 # # Path: pipelines/plugin/exceptions.py # class PluginError(RuntimeError): # pass . Output only the next line.
if f:
Predict the next line after this snippet: <|code_start|> output = {'stdout': '', 'last_line': ''} try: def process_line(line): log.debug('Got line: %s' % line) output['stdout'] += line if line and line.strip(): output['last_line'] = line if f: f.write(line) if self.event_mgr: if len(line)>0 and line[-1] == '\n': line = line[:-1] self.event_mgr.trigger('on_task_event', {'output': line}) proc = bash(_in=bash_input, _out=process_line, _err=process_line, _timeout=timeout) proc.wait() log.debug('Finished: %s, %s, %s' % (proc.exit_code, proc.stdout, proc.stderr)) except ErrorReturnCode as e: log.warning('BashExec failed %s' % e.message) raise BashExecuteError("Execution failed with code: %s" % e.exit_code, e.exit_code, data=output) except TimeoutException as e: log.debug('BashExec timed out after %s seconds' % timeout) raise BashExecuteError("Task Timed Out", 1, data=output) return_obj = None <|code_end|> using the current file's imports: import logging import json from pipelines.plugins.base_executor import BaseExecutorPlugin from pipelines.pipeline.task import TaskResult, EXECUTION_SUCCESSFUL, EXECUTION_FAILED from pipelines.plugin.exceptions import PluginError from sh import ErrorReturnCode, TimeoutException from sh import bash and any relevant context from other files: # Path: pipelines/plugins/base_executor.py # class BaseExecutorPlugin(BasePlugin): # dry_run = False # # def call(self, *args, **kwargs): # result = self.execute(*args, **kwargs) # if not isinstance(result, TaskResult): # raise PipelineError('Executor did not return type ExecutionResult, got {}'.format(type(result))) # # return result # # def execute(self, command): # print 'Running executor with command: %s' % command # # Path: pipelines/pipeline/task.py # class TaskResult(dict): # def __init__(self, status, message='', data={}, return_obj={}): # self['status'] = status # self['message'] = message # self['data'] = data # self['return_obj'] = return_obj # # @property # def status(self): # return self.get('status') # # @property # def message(self): # return self.get('message') # # @property # def data(self): # return self.get('data') # # @property # def return_obj(self): # return self.get('return_obj') # # def is_successful(self): # return self.status == EXECUTION_SUCCESSFUL # # EXECUTION_SUCCESSFUL = 0 # # EXECUTION_FAILED = 1 # # Path: pipelines/plugin/exceptions.py # class PluginError(RuntimeError): # pass . Output only the next line.
try:
Here is a snippet: <|code_start|> if line and line.strip(): output['last_line'] = line if f: f.write(line) if self.event_mgr: if len(line)>0 and line[-1] == '\n': line = line[:-1] self.event_mgr.trigger('on_task_event', {'output': line}) proc = bash(_in=bash_input, _out=process_line, _err=process_line, _timeout=timeout) proc.wait() log.debug('Finished: %s, %s, %s' % (proc.exit_code, proc.stdout, proc.stderr)) except ErrorReturnCode as e: log.warning('BashExec failed %s' % e.message) raise BashExecuteError("Execution failed with code: %s" % e.exit_code, e.exit_code, data=output) except TimeoutException as e: log.debug('BashExec timed out after %s seconds' % timeout) raise BashExecuteError("Task Timed Out", 1, data=output) return_obj = None try: return_obj = json.loads(output['last_line']) except: log.debug('Failed to parse last line of bash as json: "{}"'.format(output['last_line'])) return output['stdout'], return_obj <|code_end|> . Write the next line using the current file imports: import logging import json from pipelines.plugins.base_executor import BaseExecutorPlugin from pipelines.pipeline.task import TaskResult, EXECUTION_SUCCESSFUL, EXECUTION_FAILED from pipelines.plugin.exceptions import PluginError from sh import ErrorReturnCode, TimeoutException from sh import bash and context from other files: # Path: pipelines/plugins/base_executor.py # class BaseExecutorPlugin(BasePlugin): # dry_run = False # # def call(self, *args, **kwargs): # result = self.execute(*args, **kwargs) # if not isinstance(result, TaskResult): # raise PipelineError('Executor did not return type ExecutionResult, got {}'.format(type(result))) # # return result # # def execute(self, command): # print 'Running executor with command: %s' % command # # Path: pipelines/pipeline/task.py # class TaskResult(dict): # def __init__(self, status, message='', data={}, return_obj={}): # self['status'] = status # self['message'] = message # self['data'] = data # self['return_obj'] = return_obj # # @property # def status(self): # return self.get('status') # # @property # def message(self): # return self.get('message') # # @property # def data(self): # return self.get('data') # # @property # def return_obj(self): # return self.get('return_obj') # # def is_successful(self): # return self.status == EXECUTION_SUCCESSFUL # # EXECUTION_SUCCESSFUL = 0 # # EXECUTION_FAILED = 1 # # Path: pipelines/plugin/exceptions.py # class PluginError(RuntimeError): # pass , which may include functions, classes, or code. Output only the next line.
@classmethod