Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Based on the snippet: <|code_start|> app = webapp2.WSGIApplication([('/home', MainPage), ('/projects', Projects), ('/experience', Experience), ('/education', Education), ('/contact', Contact), ('/achievements', Achievements), ('/github_activity', GithubActivity), ('/github_archive', GithubArchiveHTML), ('/archive_data', GithubArchiveBigQuery), ('/toprepos', TopRepos), <|code_end|> , predict the immediate next line with the help of imports: import webapp2 from mainhandler import Handler from app.content.index import MainPage from app.content.experience import Experience from app.content.education import Education from app.content.projects import Projects from app.content.contact import Contact from app.content.achievements import Achievements from app.utilities.githubactivity import GithubActivity from app.utilities.githubarchive import GithubArchiveBigQuery, GithubArchiveHTML, TopRepos, TopLanguages, MostActiveUsers and context (classes, functions, sometimes code) from other files: # Path: mainhandler.py # class Handler(webapp2.RequestHandler): # def write(self, *a, **kw): # self.response.out.write(*a, **kw) # # def render_str(self, template, **params): # t = jinja_env.get_template(template) # return t.render(params) # # def render(self, template, **kw): # self.write(self.render_str(template, **kw)) # # def render_front(self, template): # self.render(template) # # Path: app/content/index.py # class MainPage(Handler): # def get(self): # self.render_front("index.html") # # Path: app/content/experience.py # class Experience(Handler): # def get(self): # self.response.headers['Content-Type'] = 'application/json' # self.write(json.dumps(get_gist_data('3735396','experience_data'))) # # Path: app/content/education.py # class Education(Handler): # def get(self): # self.response.headers['Content-Type'] = 'application/json' # self.write(json.dumps(get_gist_data('3735401','education_data'))) # # Path: app/content/projects.py # class Projects(Handler): # def get(self): # self.response.headers['Content-Type'] = 'application/json' # self.write(json.dumps(get_gist_data('3734919','projects_data'))) # # Path: app/content/contact.py # class Contact(Handler): # def get(self): # self.response.headers['Content-Type'] = 'application/json' # self.write(json.dumps(get_gist_data('3785786','contact_data'))) # # Path: app/content/achievements.py # class Achievements(Handler): # def get(self): # self.response.headers['Content-Type'] = 'application/json' # self.write(json.dumps(get_gist_data('3785895','achievements_data'))) # # Path: app/utilities/githubactivity.py # class GithubActivity(Handler): # def get(self): # activity = {} # entries = [] # user = setUser("<username>", "<password>") # entries = entries + getFollowers(user) # entries = entries + getFollowing(user) # entries = entries + getWatchedRepos(user) # activity['activities'] = entries # self.response.headers['Content-Type'] = 'application/json' # self.write(json.dumps(activity)) # # Path: app/utilities/githubarchive.py # class GithubArchiveBigQuery(Handler): # def get(self): # self.response.headers['Content-Type'] = 'application/json' # """Local_parser_result # self.write(json.dumps(local_archive)) # """ # """Remote_parser_result""" # service = build("bigquery", "v2", http=http) # parsed_archive = execute_bigquery_githubarchive(service) # self.write(json.dumps(parsed_archive)) # # class GithubArchiveHTML(Handler): # def get(self): # #self.render_front("timeline.html") # self.render("metro_github_archive.html") # # class TopRepos(Handler): # def get(self): # self.response.headers['Content-Type'] = 'application/json' # service = build("bigquery", "v2", http=http) # parsed_archive = execute_bigquery_toprepos(service) # self.write(json.dumps(parsed_archive)) # # class TopLanguages(Handler): # def get(self): # self.response.headers['Content-Type'] = 'application/json' # service = build("bigquery", "v2", http=http) # parsed_archive = execute_bigquery_toplanguages(service) # self.write(json.dumps(parsed_archive)) # # class MostActiveUsers(Handler): # def get(self): # self.response.headers['Content-Type'] = 'application/json' # service = build("bigquery", "v2", http=http) # parsed_archive = execute_bigquery_mostactive_users(service) # self.write(json.dumps(parsed_archive)) . Output only the next line.
('/toplanguages', TopLanguages),
Predict the next line after this snippet: <|code_start|> app = webapp2.WSGIApplication([('/home', MainPage), ('/projects', Projects), ('/experience', Experience), ('/education', Education), ('/contact', Contact), ('/achievements', Achievements), ('/github_activity', GithubActivity), ('/github_archive', GithubArchiveHTML), ('/archive_data', GithubArchiveBigQuery), ('/toprepos', TopRepos), ('/toplanguages', TopLanguages), <|code_end|> using the current file's imports: import webapp2 from mainhandler import Handler from app.content.index import MainPage from app.content.experience import Experience from app.content.education import Education from app.content.projects import Projects from app.content.contact import Contact from app.content.achievements import Achievements from app.utilities.githubactivity import GithubActivity from app.utilities.githubarchive import GithubArchiveBigQuery, GithubArchiveHTML, TopRepos, TopLanguages, MostActiveUsers and any relevant context from other files: # Path: mainhandler.py # class Handler(webapp2.RequestHandler): # def write(self, *a, **kw): # self.response.out.write(*a, **kw) # # def render_str(self, template, **params): # t = jinja_env.get_template(template) # return t.render(params) # # def render(self, template, **kw): # self.write(self.render_str(template, **kw)) # # def render_front(self, template): # self.render(template) # # Path: app/content/index.py # class MainPage(Handler): # def get(self): # self.render_front("index.html") # # Path: app/content/experience.py # class Experience(Handler): # def get(self): # self.response.headers['Content-Type'] = 'application/json' # self.write(json.dumps(get_gist_data('3735396','experience_data'))) # # Path: app/content/education.py # class Education(Handler): # def get(self): # self.response.headers['Content-Type'] = 'application/json' # self.write(json.dumps(get_gist_data('3735401','education_data'))) # # Path: app/content/projects.py # class Projects(Handler): # def get(self): # self.response.headers['Content-Type'] = 'application/json' # self.write(json.dumps(get_gist_data('3734919','projects_data'))) # # Path: app/content/contact.py # class Contact(Handler): # def get(self): # self.response.headers['Content-Type'] = 'application/json' # self.write(json.dumps(get_gist_data('3785786','contact_data'))) # # Path: app/content/achievements.py # class Achievements(Handler): # def get(self): # self.response.headers['Content-Type'] = 'application/json' # self.write(json.dumps(get_gist_data('3785895','achievements_data'))) # # Path: app/utilities/githubactivity.py # class GithubActivity(Handler): # def get(self): # activity = {} # entries = [] # user = setUser("<username>", "<password>") # entries = entries + getFollowers(user) # entries = entries + getFollowing(user) # entries = entries + getWatchedRepos(user) # activity['activities'] = entries # self.response.headers['Content-Type'] = 'application/json' # self.write(json.dumps(activity)) # # Path: app/utilities/githubarchive.py # class GithubArchiveBigQuery(Handler): # def get(self): # self.response.headers['Content-Type'] = 'application/json' # """Local_parser_result # self.write(json.dumps(local_archive)) # """ # """Remote_parser_result""" # service = build("bigquery", "v2", http=http) # parsed_archive = execute_bigquery_githubarchive(service) # self.write(json.dumps(parsed_archive)) # # class GithubArchiveHTML(Handler): # def get(self): # #self.render_front("timeline.html") # self.render("metro_github_archive.html") # # class TopRepos(Handler): # def get(self): # self.response.headers['Content-Type'] = 'application/json' # service = build("bigquery", "v2", http=http) # parsed_archive = execute_bigquery_toprepos(service) # self.write(json.dumps(parsed_archive)) # # class TopLanguages(Handler): # def get(self): # self.response.headers['Content-Type'] = 'application/json' # service = build("bigquery", "v2", http=http) # parsed_archive = execute_bigquery_toplanguages(service) # self.write(json.dumps(parsed_archive)) # # class MostActiveUsers(Handler): # def get(self): # self.response.headers['Content-Type'] = 'application/json' # service = build("bigquery", "v2", http=http) # parsed_archive = execute_bigquery_mostactive_users(service) # self.write(json.dumps(parsed_archive)) . Output only the next line.
('/mostactiveusers', MostActiveUsers)], debug=True)
Next line prediction: <|code_start|> class Author(models.Model): id = BigHashidAutoField(primary_key=True, prefix="a_", alphabet="0123456789abcdef") name = models.CharField(max_length=40) uid = models.UUIDField(null=True, blank=True) id_str = models.CharField(max_length=15, blank=True) def __str__(self): return self.name def save(self, *args, **kwargs): self.id_str = str(self.id) super().save(*args, **kwargs) class Editor(models.Model): id = HashidAutoField(primary_key=True, salt="A different salt", min_length=20) name = models.CharField(max_length=40) def __str__(self): return self.name class Book(models.Model): name = models.CharField(max_length=40) author = models.ForeignKey(Author, on_delete=models.CASCADE, null=True, blank=True, related_name='books') <|code_end|> . Use current file imports: (from django.db import models from hashid_field import HashidAutoField, HashidField, BigHashidAutoField, BigHashidField from django.urls import reverse) and context including class names, function names, or small code snippets from other files: # Path: hashid_field/field.py # class HashidField(HashidFieldMixin, HashidCharFieldMixin, models.IntegerField): # description = "A Hashids obscured IntegerField" # # class BigHashidField(HashidFieldMixin, HashidCharFieldMixin, models.BigIntegerField): # description = "A Hashids obscured BigIntegerField" # # def __init__(self, min_length=settings.HASHID_FIELD_BIG_MIN_LENGTH, *args, **kwargs): # super().__init__(min_length=min_length, *args, **kwargs) # # class HashidAutoField(HashidFieldMixin, models.AutoField): # description = "A Hashids obscured AutoField" # # class BigHashidAutoField(HashidFieldMixin, models.AutoField): # # This inherits from AutoField instead of BigAutoField so that DEFAULT_AUTO_FIELD doesn't throw an error # description = "A Hashids obscured BigAutoField" # # def get_internal_type(self): # return 'BigAutoField' # # def rel_db_type(self, connection): # return models.BigIntegerField().db_type(connection=connection) # # def __init__(self, min_length=settings.HASHID_FIELD_BIG_MIN_LENGTH, *args, **kwargs): # super().__init__(min_length=min_length, *args, **kwargs) . Output only the next line.
reference_id = HashidField(salt="alternative salt", allow_int_lookup=True, prefix="ref_")
Given snippet: <|code_start|> class Author(models.Model): id = BigHashidAutoField(primary_key=True, prefix="a_", alphabet="0123456789abcdef") name = models.CharField(max_length=40) uid = models.UUIDField(null=True, blank=True) id_str = models.CharField(max_length=15, blank=True) def __str__(self): return self.name def save(self, *args, **kwargs): self.id_str = str(self.id) super().save(*args, **kwargs) class Editor(models.Model): <|code_end|> , continue by predicting the next line. Consider current file imports: from django.db import models from hashid_field import HashidAutoField, HashidField, BigHashidAutoField, BigHashidField from django.urls import reverse and context: # Path: hashid_field/field.py # class HashidField(HashidFieldMixin, HashidCharFieldMixin, models.IntegerField): # description = "A Hashids obscured IntegerField" # # class BigHashidField(HashidFieldMixin, HashidCharFieldMixin, models.BigIntegerField): # description = "A Hashids obscured BigIntegerField" # # def __init__(self, min_length=settings.HASHID_FIELD_BIG_MIN_LENGTH, *args, **kwargs): # super().__init__(min_length=min_length, *args, **kwargs) # # class HashidAutoField(HashidFieldMixin, models.AutoField): # description = "A Hashids obscured AutoField" # # class BigHashidAutoField(HashidFieldMixin, models.AutoField): # # This inherits from AutoField instead of BigAutoField so that DEFAULT_AUTO_FIELD doesn't throw an error # description = "A Hashids obscured BigAutoField" # # def get_internal_type(self): # return 'BigAutoField' # # def rel_db_type(self, connection): # return models.BigIntegerField().db_type(connection=connection) # # def __init__(self, min_length=settings.HASHID_FIELD_BIG_MIN_LENGTH, *args, **kwargs): # super().__init__(min_length=min_length, *args, **kwargs) which might include code, classes, or functions. Output only the next line.
id = HashidAutoField(primary_key=True, salt="A different salt", min_length=20)
Continue the code snippet: <|code_start|> class MockRequest: pass class MockSuperUser: def has_perm(self, perm): return True site = AdminSite() request = MockRequest() request.user = MockSuperUser() class HashidAdminTests(TestCase): def test_admin_widget_is_text(self): <|code_end|> . Use current file imports: from django.contrib.admin import AdminSite from django.test import TestCase from tests.admin import RecordAdmin from tests.models import Record and context (classes, functions, or code) from other files: # Path: tests/admin.py # class RecordAdmin(admin.ModelAdmin): # pass # # Path: tests/models.py # class Record(models.Model): # id = BigHashidAutoField(primary_key=True) # name = models.CharField(max_length=40) # artist = models.ForeignKey(Artist, on_delete=models.CASCADE, null=True, blank=True, related_name="records") # reference_id = HashidField() # prefixed_id = HashidField(null=True, blank=True, prefix="prefix_") # string_id = HashidField(null=True, blank=True, enable_hashid_object=False) # plain_hashid = HashidField(null=True, blank=True, enable_descriptor=False) # plain_id = HashidField(null=True, blank=True, enable_descriptor=False, enable_hashid_object=False) # alternate_id = HashidField(salt="a different salt", null=True, blank=True) # key = BigHashidField(min_length=10, alphabet="abcdlmnotuvwxyz123789", null=True, blank=True) # # def __str__(self): # return "{} ({})".format(self.name, self.reference_id) . Output only the next line.
admin = RecordAdmin(Record, site)
Based on the snippet: <|code_start|> class MockRequest: pass class MockSuperUser: def has_perm(self, perm): return True site = AdminSite() request = MockRequest() request.user = MockSuperUser() class HashidAdminTests(TestCase): def test_admin_widget_is_text(self): <|code_end|> , predict the immediate next line with the help of imports: from django.contrib.admin import AdminSite from django.test import TestCase from tests.admin import RecordAdmin from tests.models import Record and context (classes, functions, sometimes code) from other files: # Path: tests/admin.py # class RecordAdmin(admin.ModelAdmin): # pass # # Path: tests/models.py # class Record(models.Model): # id = BigHashidAutoField(primary_key=True) # name = models.CharField(max_length=40) # artist = models.ForeignKey(Artist, on_delete=models.CASCADE, null=True, blank=True, related_name="records") # reference_id = HashidField() # prefixed_id = HashidField(null=True, blank=True, prefix="prefix_") # string_id = HashidField(null=True, blank=True, enable_hashid_object=False) # plain_hashid = HashidField(null=True, blank=True, enable_descriptor=False) # plain_id = HashidField(null=True, blank=True, enable_descriptor=False, enable_hashid_object=False) # alternate_id = HashidField(salt="a different salt", null=True, blank=True) # key = BigHashidField(min_length=10, alphabet="abcdlmnotuvwxyz123789", null=True, blank=True) # # def __str__(self): # return "{} ({})".format(self.name, self.reference_id) . Output only the next line.
admin = RecordAdmin(Record, site)
Predict the next line after this snippet: <|code_start|> class Artist(models.Model): id = HashidAutoField(primary_key=True, alphabet="1234567890abcdef") name = models.CharField(max_length=40) def __str__(self): return "{} ({})".format(self.name, self.id) class Record(models.Model): id = BigHashidAutoField(primary_key=True) name = models.CharField(max_length=40) artist = models.ForeignKey(Artist, on_delete=models.CASCADE, null=True, blank=True, related_name="records") <|code_end|> using the current file's imports: from django.db import models from hashid_field import HashidField, BigHashidField, HashidAutoField, BigHashidAutoField and any relevant context from other files: # Path: hashid_field/field.py # class HashidField(HashidFieldMixin, HashidCharFieldMixin, models.IntegerField): # description = "A Hashids obscured IntegerField" # # class BigHashidField(HashidFieldMixin, HashidCharFieldMixin, models.BigIntegerField): # description = "A Hashids obscured BigIntegerField" # # def __init__(self, min_length=settings.HASHID_FIELD_BIG_MIN_LENGTH, *args, **kwargs): # super().__init__(min_length=min_length, *args, **kwargs) # # class HashidAutoField(HashidFieldMixin, models.AutoField): # description = "A Hashids obscured AutoField" # # class BigHashidAutoField(HashidFieldMixin, models.AutoField): # # This inherits from AutoField instead of BigAutoField so that DEFAULT_AUTO_FIELD doesn't throw an error # description = "A Hashids obscured BigAutoField" # # def get_internal_type(self): # return 'BigAutoField' # # def rel_db_type(self, connection): # return models.BigIntegerField().db_type(connection=connection) # # def __init__(self, min_length=settings.HASHID_FIELD_BIG_MIN_LENGTH, *args, **kwargs): # super().__init__(min_length=min_length, *args, **kwargs) . Output only the next line.
reference_id = HashidField()
Predict the next line after this snippet: <|code_start|> class Artist(models.Model): id = HashidAutoField(primary_key=True, alphabet="1234567890abcdef") name = models.CharField(max_length=40) def __str__(self): return "{} ({})".format(self.name, self.id) class Record(models.Model): id = BigHashidAutoField(primary_key=True) name = models.CharField(max_length=40) artist = models.ForeignKey(Artist, on_delete=models.CASCADE, null=True, blank=True, related_name="records") reference_id = HashidField() prefixed_id = HashidField(null=True, blank=True, prefix="prefix_") string_id = HashidField(null=True, blank=True, enable_hashid_object=False) plain_hashid = HashidField(null=True, blank=True, enable_descriptor=False) plain_id = HashidField(null=True, blank=True, enable_descriptor=False, enable_hashid_object=False) alternate_id = HashidField(salt="a different salt", null=True, blank=True) <|code_end|> using the current file's imports: from django.db import models from hashid_field import HashidField, BigHashidField, HashidAutoField, BigHashidAutoField and any relevant context from other files: # Path: hashid_field/field.py # class HashidField(HashidFieldMixin, HashidCharFieldMixin, models.IntegerField): # description = "A Hashids obscured IntegerField" # # class BigHashidField(HashidFieldMixin, HashidCharFieldMixin, models.BigIntegerField): # description = "A Hashids obscured BigIntegerField" # # def __init__(self, min_length=settings.HASHID_FIELD_BIG_MIN_LENGTH, *args, **kwargs): # super().__init__(min_length=min_length, *args, **kwargs) # # class HashidAutoField(HashidFieldMixin, models.AutoField): # description = "A Hashids obscured AutoField" # # class BigHashidAutoField(HashidFieldMixin, models.AutoField): # # This inherits from AutoField instead of BigAutoField so that DEFAULT_AUTO_FIELD doesn't throw an error # description = "A Hashids obscured BigAutoField" # # def get_internal_type(self): # return 'BigAutoField' # # def rel_db_type(self, connection): # return models.BigIntegerField().db_type(connection=connection) # # def __init__(self, min_length=settings.HASHID_FIELD_BIG_MIN_LENGTH, *args, **kwargs): # super().__init__(min_length=min_length, *args, **kwargs) . Output only the next line.
key = BigHashidField(min_length=10, alphabet="abcdlmnotuvwxyz123789", null=True, blank=True)
Next line prediction: <|code_start|> class Artist(models.Model): id = HashidAutoField(primary_key=True, alphabet="1234567890abcdef") name = models.CharField(max_length=40) def __str__(self): return "{} ({})".format(self.name, self.id) class Record(models.Model): <|code_end|> . Use current file imports: (from django.db import models from hashid_field import HashidField, BigHashidField, HashidAutoField, BigHashidAutoField) and context including class names, function names, or small code snippets from other files: # Path: hashid_field/field.py # class HashidField(HashidFieldMixin, HashidCharFieldMixin, models.IntegerField): # description = "A Hashids obscured IntegerField" # # class BigHashidField(HashidFieldMixin, HashidCharFieldMixin, models.BigIntegerField): # description = "A Hashids obscured BigIntegerField" # # def __init__(self, min_length=settings.HASHID_FIELD_BIG_MIN_LENGTH, *args, **kwargs): # super().__init__(min_length=min_length, *args, **kwargs) # # class HashidAutoField(HashidFieldMixin, models.AutoField): # description = "A Hashids obscured AutoField" # # class BigHashidAutoField(HashidFieldMixin, models.AutoField): # # This inherits from AutoField instead of BigAutoField so that DEFAULT_AUTO_FIELD doesn't throw an error # description = "A Hashids obscured BigAutoField" # # def get_internal_type(self): # return 'BigAutoField' # # def rel_db_type(self, connection): # return models.BigIntegerField().db_type(connection=connection) # # def __init__(self, min_length=settings.HASHID_FIELD_BIG_MIN_LENGTH, *args, **kwargs): # super().__init__(min_length=min_length, *args, **kwargs) . Output only the next line.
id = BigHashidAutoField(primary_key=True)
Given the following code snippet before the placeholder: <|code_start|> def _is_int_representation(number): """Returns whether a value is an integer or a string representation of an integer.""" try: int(number) except ValueError: return False else: return True def get_id_for_hashid_field(field, value): <|code_end|> , predict the next line using imports from the current file: import itertools from django.db.models.lookups import Lookup, GreaterThan, GreaterThanOrEqual, LessThan, LessThanOrEqual from django.utils.datastructures import OrderedSet from django.core.exceptions import EmptyResultSet from .hashid import Hashid from .conf import settings and context including class names, function names, and sometimes code from other files: # Path: hashid_field/hashid.py # class Hashid(object): # def __init__(self, value, salt="", min_length=0, alphabet=Hashids.ALPHABET, prefix="", hashids=None): # self._salt = salt # self._min_length = min_length # self._alphabet = alphabet # self._prefix = str(prefix) # # # If hashids is provided, it's for optimization only, and should be initialized with the same salt, min_length # # and alphabet, or else we will run into problems # self._hashids = hashids or Hashids(salt=self._salt, min_length=self._min_length, alphabet=self._alphabet) # if not self._valid_hashids_object(): # raise Exception("Invalid hashids.Hashids object") # # if value is None: # raise ValueError("id must be a positive integer or a valid Hashid string") # # # Check if `value` is an integer and encode it. # # This presumes hashids will only ever be strings, even if they are made up entirely of numbers # if _is_uint(value): # self._id = value # self._hashid = self.encode(value) # elif _is_str(value): # # Verify that it begins with the prefix, which could be the default "" # if value.startswith(self._prefix): # value = value[len(self._prefix):] # else: # # Check if the given string is all numbers, and encode without requiring the prefix. # # This is to maintain backwards compatibility, specifically being able to enter numbers in an admin. # # If a hashid is typed in that happens to be all numbers, without the prefix, then it will be # # interpreted as an integer and encoded (again). # try: # value = int(value) # except (TypeError, ValueError): # raise ValueError("value must begin with prefix {}".format(self._prefix)) # # # Check if this string is a valid hashid, even if it's made up entirely of numbers # _id = self.decode(value) # if _id is None: # # The given value is not a hashids string, so see if it's a valid string representation of an integer # try: # value = int(value) # except (TypeError, ValueError): # raise ValueError("value must be a positive integer or a valid Hashid string") # # # Make sure it's positive # if not _is_uint(value): # raise ValueError("value must be a positive integer") # # # We can use it as-is # self._id = value # self._hashid = self.encode(value) # else: # # This is a valid hashid # self._id = _id # self._hashid = value # elif isinstance(value, int) and value < 0: # raise ValueError("value must be a positive integer") # else: # raise ValueError("value must be a positive integer or a valid Hashid string") # # @property # def id(self): # return self._id # # @property # def hashid(self): # return self._hashid # # @property # def prefix(self): # return self._prefix # # @property # def hashids(self): # return self._hashids # # def encode(self, id): # return self._hashids.encode(id) # # def decode(self, hashid): # ret = self._hashids.decode(hashid) # if len(ret) == 1: # return ret[0] # else: # return None # # def _valid_hashids_object(self): # # The hashids.Hashids class randomizes the alphabet and pulls out separators and guards, thus not being # # reversible. So all we can test is that the length of the alphabet, separators and guards are equal to the # # original alphabet we gave it. We could also check that all of the characters we gave it are present, but that # # seems excessive... this test will catch most errors. # return self._salt == self._hashids._salt \ # and self._min_length == self._hashids._min_length \ # and len(self._alphabet) == len(self._hashids._alphabet + self._hashids._separators + self._hashids._guards) # # def __repr__(self): # return "Hashid({}): {}".format(self._id, str(self)) # # def __str__(self): # return self._prefix + self._hashid # # def __int__(self): # return self._id # # def __long__(self): # return int(self._id) # # def __eq__(self, other): # if isinstance(other, self.__class__): # return ( # self._id == other._id and # self._hashid == other._hashid and # self._prefix == other._prefix # ) # if isinstance(other, str): # return str(self) == other # if isinstance(other, int): # return int(self) == other # return NotImplemented # # def __lt__(self, other): # if isinstance(other, self.__class__): # return self._id < other._id # if isinstance(other, type(self._id)): # return self._id < other # return NotImplemented # # def __len__(self): # return len(str(self)) # # def __hash__(self): # return hash(str(self)) # # def __reduce__(self): # return (self.__class__, (self._id, self._salt, self._min_length, self._alphabet, self._prefix, None)) # # Path: hashid_field/conf.py . Output only the next line.
if isinstance(value, Hashid):
Given the code snippet: <|code_start|>@skipUnless(have_drf, "Requires Django REST Framework to be installed") class TestRestFramework(TestCase): def assertSerializerError(self, serializer, field, code): serializer_name = serializer.__class__.__name__ self.assertFalse(serializer.is_valid(), msg="The serializer {} does not contain any errors".format(serializer_name)) def assertCodeInErrors(errors): found_error = False for error_detail in errors: if error_detail.code == code: found_error = True self.assertTrue(found_error, msg="The field '{} in serializer '{}' does not contain the error code {}".format( field, serializer_name, code)) if field: if field in serializer.errors: assertCodeInErrors(serializer.errors[field]) else: self.fail("The field '{}' in serializer '{}' contains no errors".format(field, serializer_name)) else: if 'non_field_errors' in serializer.errors: assertCodeInErrors(serializer.errors['non_field_errors']) else: self.fail("The serializer '{}' does not contain the non-field error {}".format(serializer_name, code)) def test_default_modelserializer_field(self): class ArtistSerializer(serializers.ModelSerializer): class Meta: <|code_end|> , generate the next line using the imports in this file: from unittest import skipUnless from django.core import exceptions from django.test import TestCase from rest_framework.exceptions import ErrorDetail from tests.models import Artist, Record, Track from rest_framework import serializers from rest_framework.renderers import JSONRenderer from hashid_field.rest import UnconfiguredHashidSerialField, HashidSerializerCharField, HashidSerializerIntegerField import hashids and context (functions, classes, or occasionally code) from other files: # Path: tests/models.py # class Artist(models.Model): # id = HashidAutoField(primary_key=True, alphabet="1234567890abcdef") # name = models.CharField(max_length=40) # # def __str__(self): # return "{} ({})".format(self.name, self.id) # # class Record(models.Model): # id = BigHashidAutoField(primary_key=True) # name = models.CharField(max_length=40) # artist = models.ForeignKey(Artist, on_delete=models.CASCADE, null=True, blank=True, related_name="records") # reference_id = HashidField() # prefixed_id = HashidField(null=True, blank=True, prefix="prefix_") # string_id = HashidField(null=True, blank=True, enable_hashid_object=False) # plain_hashid = HashidField(null=True, blank=True, enable_descriptor=False) # plain_id = HashidField(null=True, blank=True, enable_descriptor=False, enable_hashid_object=False) # alternate_id = HashidField(salt="a different salt", null=True, blank=True) # key = BigHashidField(min_length=10, alphabet="abcdlmnotuvwxyz123789", null=True, blank=True) # # def __str__(self): # return "{} ({})".format(self.name, self.reference_id) # # class Track(models.Model): # id = BigHashidAutoField(primary_key=True, allow_int_lookup=True, min_length=10, prefix='albumtrack:', salt="abcd", alphabet="abcdefghijklmnop") . Output only the next line.
model = Artist
Given snippet: <|code_start|> def test_modelserializer_integerfield(self): class ArtistSerializer(serializers.ModelSerializer): id = HashidSerializerIntegerField(source_field=Artist._meta.get_field('id')) class Meta: model = Artist fields = ('id', 'name') artist = Artist.objects.create(id=256, name="Test Artist") orig_id = artist.id s = ArtistSerializer(artist) self.assertTrue(isinstance(s.data['id'], int)) self.assertEqual(artist.id.id, s.data['id']) s2 = ArtistSerializer(artist, data={'id': 256, 'name': "Test Artist Changed"}) self.assertTrue(s2.is_valid()) artist = s2.save() self.assertEqual(artist.id, orig_id) self.assertEqual(artist.name, "Test Artist Changed") def test_int_lookups_on_char_field(self): class RecordSerializer(serializers.ModelSerializer): id = HashidSerializerCharField(source_field='tests.Record.id') artist = serializers.PrimaryKeyRelatedField( pk_field=HashidSerializerCharField(source_field='tests.Artist.id'), queryset=Artist.objects.all(), required=False) reference_id = HashidSerializerCharField(source_field='tests.Record.reference_id') class Meta: <|code_end|> , continue by predicting the next line. Consider current file imports: from unittest import skipUnless from django.core import exceptions from django.test import TestCase from rest_framework.exceptions import ErrorDetail from tests.models import Artist, Record, Track from rest_framework import serializers from rest_framework.renderers import JSONRenderer from hashid_field.rest import UnconfiguredHashidSerialField, HashidSerializerCharField, HashidSerializerIntegerField import hashids and context: # Path: tests/models.py # class Artist(models.Model): # id = HashidAutoField(primary_key=True, alphabet="1234567890abcdef") # name = models.CharField(max_length=40) # # def __str__(self): # return "{} ({})".format(self.name, self.id) # # class Record(models.Model): # id = BigHashidAutoField(primary_key=True) # name = models.CharField(max_length=40) # artist = models.ForeignKey(Artist, on_delete=models.CASCADE, null=True, blank=True, related_name="records") # reference_id = HashidField() # prefixed_id = HashidField(null=True, blank=True, prefix="prefix_") # string_id = HashidField(null=True, blank=True, enable_hashid_object=False) # plain_hashid = HashidField(null=True, blank=True, enable_descriptor=False) # plain_id = HashidField(null=True, blank=True, enable_descriptor=False, enable_hashid_object=False) # alternate_id = HashidField(salt="a different salt", null=True, blank=True) # key = BigHashidField(min_length=10, alphabet="abcdlmnotuvwxyz123789", null=True, blank=True) # # def __str__(self): # return "{} ({})".format(self.name, self.reference_id) # # class Track(models.Model): # id = BigHashidAutoField(primary_key=True, allow_int_lookup=True, min_length=10, prefix='albumtrack:', salt="abcd", alphabet="abcdefghijklmnop") which might include code, classes, or functions. Output only the next line.
model = Record
Predict the next line for this snippet: <|code_start|> 'name': "Test Record 1024", 'artist': 1024, 'reference_id': 2222222222, } s = RecordSerializer(data=data) self.assertTrue(s.is_valid()) r512 = s.save() self.assertEqual(r512.id, 1024) self.assertEqual(r512.name, "Test Record 1024") self.assertEqual(r512.artist, artist) def test_invalid_source_field_strings(self): with self.assertRaises(ValueError): id = HashidSerializerIntegerField(source_field="tests") with self.assertRaises(ValueError): id = HashidSerializerIntegerField(source_field="tests.Artist") with self.assertRaises(ValueError): id = HashidSerializerIntegerField(source_field="Artist.id") with self.assertRaises(LookupError): id = HashidSerializerIntegerField(source_field="foo.Bar.baz") with self.assertRaises(LookupError): id = HashidSerializerIntegerField(source_field="tests.Bar.baz") with self.assertRaises(exceptions.FieldDoesNotExist): id = HashidSerializerIntegerField(source_field="tests.Artist.baz") def test_modelserializer_with_prefix(self): class TrackSerializer(serializers.ModelSerializer): id = HashidSerializerCharField(source_field="tests.Track.id") class Meta: <|code_end|> with the help of current file imports: from unittest import skipUnless from django.core import exceptions from django.test import TestCase from rest_framework.exceptions import ErrorDetail from tests.models import Artist, Record, Track from rest_framework import serializers from rest_framework.renderers import JSONRenderer from hashid_field.rest import UnconfiguredHashidSerialField, HashidSerializerCharField, HashidSerializerIntegerField import hashids and context from other files: # Path: tests/models.py # class Artist(models.Model): # id = HashidAutoField(primary_key=True, alphabet="1234567890abcdef") # name = models.CharField(max_length=40) # # def __str__(self): # return "{} ({})".format(self.name, self.id) # # class Record(models.Model): # id = BigHashidAutoField(primary_key=True) # name = models.CharField(max_length=40) # artist = models.ForeignKey(Artist, on_delete=models.CASCADE, null=True, blank=True, related_name="records") # reference_id = HashidField() # prefixed_id = HashidField(null=True, blank=True, prefix="prefix_") # string_id = HashidField(null=True, blank=True, enable_hashid_object=False) # plain_hashid = HashidField(null=True, blank=True, enable_descriptor=False) # plain_id = HashidField(null=True, blank=True, enable_descriptor=False, enable_hashid_object=False) # alternate_id = HashidField(salt="a different salt", null=True, blank=True) # key = BigHashidField(min_length=10, alphabet="abcdlmnotuvwxyz123789", null=True, blank=True) # # def __str__(self): # return "{} ({})".format(self.name, self.reference_id) # # class Track(models.Model): # id = BigHashidAutoField(primary_key=True, allow_int_lookup=True, min_length=10, prefix='albumtrack:', salt="abcd", alphabet="abcdefghijklmnop") , which may contain function names, class names, or code. Output only the next line.
model = Track
Given snippet: <|code_start|> class AuthorSerializer(serializers.HyperlinkedModelSerializer): id = HashidSerializerCharField(source_field='library.Author.id', read_only=True) class Meta: model = Author fields = ('url', 'id', 'name', 'uid', 'books') class BookSerializer(serializers.HyperlinkedModelSerializer): reference_id = HashidSerializerCharField(salt="alternative salt") <|code_end|> , continue by predicting the next line. Consider current file imports: from rest_framework import serializers from hashid_field.rest import HashidSerializerIntegerField, HashidSerializerCharField from library.models import Author, Book and context: # Path: hashid_field/rest.py # class HashidSerializerIntegerField(HashidSerializerMixin, fields.IntegerField): # def to_representation(self, value): # return int(value) # # class HashidSerializerCharField(HashidSerializerMixin, fields.CharField): # def to_representation(self, value): # return str(value) # # def to_internal_value(self, data): # hashid = super().to_internal_value(data) # if isinstance(data, int) and not self.allow_int_lookup: # self.fail('invalid_hashid', value=data) # if isinstance(data, str) and not self.allow_int_lookup: # # Make sure int lookups are not allowed, even if prefixed, unless the # # given value is actually a hashid made up entirely of numbers. # without_prefix = data[len(self.prefix):] # if _is_int_representation(without_prefix) and without_prefix != hashid.hashid: # self.fail('invalid_hashid', value=data) # return hashid which might include code, classes, or functions. Output only the next line.
key = HashidSerializerIntegerField(source_field="library.Book.key")
Using the snippet: <|code_start|> obj = Spy() theMock = Mock(obj, strict=True, spec=object) mock_registry.register(obj, theMock) return obj def spy2(fn): # type: (...) -> None """Spy usage of given `fn`. Patches the module, class or object `fn` lives in, so that all interactions can be recorded; otherwise executes `fn` as before, so that all side effects happen as before. E.g.:: import time spy2(time.time) do_work(...) # nothing injected, uses global patched `time` module verify(time).time() Note that builtins often cannot be patched because they're read-only. """ if isinstance(fn, str): answer = get_obj(fn) else: answer = fn <|code_end|> , determine the next line of code. You have imports: import inspect from .mockito import when2 from .invocation import RememberedProxyInvocation from .mocking import Mock, _Dummy, mock_registry from .utils import get_obj and context (class names, function names, or code) available: # Path: mockito/mockito.py # def when2(fn, *args, **kwargs): # """Stub a function call with the given arguments # # Exposes a more pythonic interface than :func:`when`. See :func:`when` for # more documentation. # # Returns `AnswerSelector` interface which exposes `thenReturn`, # `thenRaise`, and `thenAnswer` as usual. Always `strict`. # # Usage:: # # # Given `dog` is an instance of a `Dog` # when2(dog.bark, 'Miau').thenReturn('Wuff') # # .. note:: You must :func:`unstub` after stubbing, or use `with` # statement. # # """ # obj, name = get_obj_attr_tuple(fn) # theMock = _get_mock(obj, strict=True) # return invocation.StubbedInvocation(theMock, name)(*args, **kwargs) # # Path: mockito/invocation.py # class RememberedProxyInvocation(Invocation): # '''Remeber params and proxy to method of original object. # # Calls method on original object and returns it's return value. # ''' # def __init__(self, mock, method_name): # super(RememberedProxyInvocation, self).__init__(mock, method_name) # self.verified = False # self.verified_inorder = False # # def __call__(self, *params, **named_params): # self._remember_params(params, named_params) # self.mock.remember(self) # obj = self.mock.spec # try: # method = getattr(obj, self.method_name) # except AttributeError: # raise AttributeError( # "You tried to call method '%s' which '%s' instance does not " # "have." % (self.method_name, obj)) # return method(*params, **named_params) # # Path: mockito/mocking.py # MYPY = False # OMITTED = _OMITTED() # class _Dummy(object): # class Mock(object): # class _OMITTED(object): # class Dummy(_Dummy): # def __call__(self, *args, **kwargs): # def remembered_invocation_builder(mock, method_name, *args, **kwargs): # def __init__(self, mocked_obj, strict=True, spec=None): # def remember(self, invocation): # def finish_stubbing(self, stubbed_invocation): # def clear_invocations(self): # def get_original_method(self, method_name): # def set_method(self, method_name, new_method): # def replace_method(self, method_name, original_method): # def new_mocked_method(*args, **kwargs): # def stub(self, method_name): # def forget_stubbed_invocation(self, invocation): # def restore_method(self, method_name, original_method): # def unstub(self): # def has_method(self, method_name): # def get_signature(self, method_name): # def __repr__(self): # def mock(config_or_spec=None, spec=None, strict=OMITTED): # def __getattr__(self, method_name): # def __repr__(self): # # Path: mockito/utils.py # def get_obj(path): # """Return obj for given dotted path. # # Typical inputs for `path` are 'os' or 'os.path' in which case you get a # module; or 'os.path.exists' in which case you get a function from that # module. # # Just returns the given input in case it is not a str. # # Note: Relative imports not supported. # Raises ImportError or AttributeError as appropriate. # # """ # # Since we usually pass in mocks here; duck typing is not appropriate # # (mocks respond to every attribute). # if not isinstance(path, str): # return path # # if path.startswith('.'): # raise TypeError('relative imports are not supported') # # parts = path.split('.') # head, tail = parts[0], parts[1:] # # obj = importlib.import_module(head) # # # Normally a simple reduce, but we go the extra mile # # for good exception messages. # for i, name in enumerate(tail): # try: # obj = getattr(obj, name) # except AttributeError: # # Note the [:i] instead of [:i+1], so we get the path just # # *before* the AttributeError, t.i. the part of it that went ok. # module = '.'.join([head] + tail[:i]) # try: # importlib.import_module(module) # except ImportError: # raise AttributeError( # "object '%s' has no attribute '%s'" % (module, name)) # else: # raise AttributeError( # "module '%s' has no attribute '%s'" % (module, name)) # return obj . Output only the next line.
when2(fn, Ellipsis).thenAnswer(answer)
Given the code snippet: <|code_start|> Spying means that all functions will behave as before, so they will be side effects, but the interactions can be verified afterwards. Returns Dummy-like, almost empty object as proxy to `object`. The *returned* object must be injected and used by the code under test; after that all interactions can be verified as usual. T.i. the original object **will not be patched**, and has no further knowledge as before. E.g.:: import time time = spy(time) # inject time do_work(..., time) verify(time).time() """ if inspect.isclass(object) or inspect.ismodule(object): class_ = None else: class_ = object.__class__ class Spy(_Dummy): if class_: __class__ = class_ def __getattr__(self, method_name): <|code_end|> , generate the next line using the imports in this file: import inspect from .mockito import when2 from .invocation import RememberedProxyInvocation from .mocking import Mock, _Dummy, mock_registry from .utils import get_obj and context (functions, classes, or occasionally code) from other files: # Path: mockito/mockito.py # def when2(fn, *args, **kwargs): # """Stub a function call with the given arguments # # Exposes a more pythonic interface than :func:`when`. See :func:`when` for # more documentation. # # Returns `AnswerSelector` interface which exposes `thenReturn`, # `thenRaise`, and `thenAnswer` as usual. Always `strict`. # # Usage:: # # # Given `dog` is an instance of a `Dog` # when2(dog.bark, 'Miau').thenReturn('Wuff') # # .. note:: You must :func:`unstub` after stubbing, or use `with` # statement. # # """ # obj, name = get_obj_attr_tuple(fn) # theMock = _get_mock(obj, strict=True) # return invocation.StubbedInvocation(theMock, name)(*args, **kwargs) # # Path: mockito/invocation.py # class RememberedProxyInvocation(Invocation): # '''Remeber params and proxy to method of original object. # # Calls method on original object and returns it's return value. # ''' # def __init__(self, mock, method_name): # super(RememberedProxyInvocation, self).__init__(mock, method_name) # self.verified = False # self.verified_inorder = False # # def __call__(self, *params, **named_params): # self._remember_params(params, named_params) # self.mock.remember(self) # obj = self.mock.spec # try: # method = getattr(obj, self.method_name) # except AttributeError: # raise AttributeError( # "You tried to call method '%s' which '%s' instance does not " # "have." % (self.method_name, obj)) # return method(*params, **named_params) # # Path: mockito/mocking.py # MYPY = False # OMITTED = _OMITTED() # class _Dummy(object): # class Mock(object): # class _OMITTED(object): # class Dummy(_Dummy): # def __call__(self, *args, **kwargs): # def remembered_invocation_builder(mock, method_name, *args, **kwargs): # def __init__(self, mocked_obj, strict=True, spec=None): # def remember(self, invocation): # def finish_stubbing(self, stubbed_invocation): # def clear_invocations(self): # def get_original_method(self, method_name): # def set_method(self, method_name, new_method): # def replace_method(self, method_name, original_method): # def new_mocked_method(*args, **kwargs): # def stub(self, method_name): # def forget_stubbed_invocation(self, invocation): # def restore_method(self, method_name, original_method): # def unstub(self): # def has_method(self, method_name): # def get_signature(self, method_name): # def __repr__(self): # def mock(config_or_spec=None, spec=None, strict=OMITTED): # def __getattr__(self, method_name): # def __repr__(self): # # Path: mockito/utils.py # def get_obj(path): # """Return obj for given dotted path. # # Typical inputs for `path` are 'os' or 'os.path' in which case you get a # module; or 'os.path.exists' in which case you get a function from that # module. # # Just returns the given input in case it is not a str. # # Note: Relative imports not supported. # Raises ImportError or AttributeError as appropriate. # # """ # # Since we usually pass in mocks here; duck typing is not appropriate # # (mocks respond to every attribute). # if not isinstance(path, str): # return path # # if path.startswith('.'): # raise TypeError('relative imports are not supported') # # parts = path.split('.') # head, tail = parts[0], parts[1:] # # obj = importlib.import_module(head) # # # Normally a simple reduce, but we go the extra mile # # for good exception messages. # for i, name in enumerate(tail): # try: # obj = getattr(obj, name) # except AttributeError: # # Note the [:i] instead of [:i+1], so we get the path just # # *before* the AttributeError, t.i. the part of it that went ok. # module = '.'.join([head] + tail[:i]) # try: # importlib.import_module(module) # except ImportError: # raise AttributeError( # "object '%s' has no attribute '%s'" % (module, name)) # else: # raise AttributeError( # "module '%s' has no attribute '%s'" % (module, name)) # return obj . Output only the next line.
return RememberedProxyInvocation(theMock, method_name)
Using the snippet: <|code_start|> E.g.:: import time time = spy(time) # inject time do_work(..., time) verify(time).time() """ if inspect.isclass(object) or inspect.ismodule(object): class_ = None else: class_ = object.__class__ class Spy(_Dummy): if class_: __class__ = class_ def __getattr__(self, method_name): return RememberedProxyInvocation(theMock, method_name) def __repr__(self): name = 'Spied' if class_: name += class_.__name__ return "<%s id=%s>" % (name, id(self)) obj = Spy() <|code_end|> , determine the next line of code. You have imports: import inspect from .mockito import when2 from .invocation import RememberedProxyInvocation from .mocking import Mock, _Dummy, mock_registry from .utils import get_obj and context (class names, function names, or code) available: # Path: mockito/mockito.py # def when2(fn, *args, **kwargs): # """Stub a function call with the given arguments # # Exposes a more pythonic interface than :func:`when`. See :func:`when` for # more documentation. # # Returns `AnswerSelector` interface which exposes `thenReturn`, # `thenRaise`, and `thenAnswer` as usual. Always `strict`. # # Usage:: # # # Given `dog` is an instance of a `Dog` # when2(dog.bark, 'Miau').thenReturn('Wuff') # # .. note:: You must :func:`unstub` after stubbing, or use `with` # statement. # # """ # obj, name = get_obj_attr_tuple(fn) # theMock = _get_mock(obj, strict=True) # return invocation.StubbedInvocation(theMock, name)(*args, **kwargs) # # Path: mockito/invocation.py # class RememberedProxyInvocation(Invocation): # '''Remeber params and proxy to method of original object. # # Calls method on original object and returns it's return value. # ''' # def __init__(self, mock, method_name): # super(RememberedProxyInvocation, self).__init__(mock, method_name) # self.verified = False # self.verified_inorder = False # # def __call__(self, *params, **named_params): # self._remember_params(params, named_params) # self.mock.remember(self) # obj = self.mock.spec # try: # method = getattr(obj, self.method_name) # except AttributeError: # raise AttributeError( # "You tried to call method '%s' which '%s' instance does not " # "have." % (self.method_name, obj)) # return method(*params, **named_params) # # Path: mockito/mocking.py # MYPY = False # OMITTED = _OMITTED() # class _Dummy(object): # class Mock(object): # class _OMITTED(object): # class Dummy(_Dummy): # def __call__(self, *args, **kwargs): # def remembered_invocation_builder(mock, method_name, *args, **kwargs): # def __init__(self, mocked_obj, strict=True, spec=None): # def remember(self, invocation): # def finish_stubbing(self, stubbed_invocation): # def clear_invocations(self): # def get_original_method(self, method_name): # def set_method(self, method_name, new_method): # def replace_method(self, method_name, original_method): # def new_mocked_method(*args, **kwargs): # def stub(self, method_name): # def forget_stubbed_invocation(self, invocation): # def restore_method(self, method_name, original_method): # def unstub(self): # def has_method(self, method_name): # def get_signature(self, method_name): # def __repr__(self): # def mock(config_or_spec=None, spec=None, strict=OMITTED): # def __getattr__(self, method_name): # def __repr__(self): # # Path: mockito/utils.py # def get_obj(path): # """Return obj for given dotted path. # # Typical inputs for `path` are 'os' or 'os.path' in which case you get a # module; or 'os.path.exists' in which case you get a function from that # module. # # Just returns the given input in case it is not a str. # # Note: Relative imports not supported. # Raises ImportError or AttributeError as appropriate. # # """ # # Since we usually pass in mocks here; duck typing is not appropriate # # (mocks respond to every attribute). # if not isinstance(path, str): # return path # # if path.startswith('.'): # raise TypeError('relative imports are not supported') # # parts = path.split('.') # head, tail = parts[0], parts[1:] # # obj = importlib.import_module(head) # # # Normally a simple reduce, but we go the extra mile # # for good exception messages. # for i, name in enumerate(tail): # try: # obj = getattr(obj, name) # except AttributeError: # # Note the [:i] instead of [:i+1], so we get the path just # # *before* the AttributeError, t.i. the part of it that went ok. # module = '.'.join([head] + tail[:i]) # try: # importlib.import_module(module) # except ImportError: # raise AttributeError( # "object '%s' has no attribute '%s'" % (module, name)) # else: # raise AttributeError( # "module '%s' has no attribute '%s'" % (module, name)) # return obj . Output only the next line.
theMock = Mock(obj, strict=True, spec=object)
Given the code snippet: <|code_start|>__all__ = ['spy'] def spy(object): """Spy an object. Spying means that all functions will behave as before, so they will be side effects, but the interactions can be verified afterwards. Returns Dummy-like, almost empty object as proxy to `object`. The *returned* object must be injected and used by the code under test; after that all interactions can be verified as usual. T.i. the original object **will not be patched**, and has no further knowledge as before. E.g.:: import time time = spy(time) # inject time do_work(..., time) verify(time).time() """ if inspect.isclass(object) or inspect.ismodule(object): class_ = None else: class_ = object.__class__ <|code_end|> , generate the next line using the imports in this file: import inspect from .mockito import when2 from .invocation import RememberedProxyInvocation from .mocking import Mock, _Dummy, mock_registry from .utils import get_obj and context (functions, classes, or occasionally code) from other files: # Path: mockito/mockito.py # def when2(fn, *args, **kwargs): # """Stub a function call with the given arguments # # Exposes a more pythonic interface than :func:`when`. See :func:`when` for # more documentation. # # Returns `AnswerSelector` interface which exposes `thenReturn`, # `thenRaise`, and `thenAnswer` as usual. Always `strict`. # # Usage:: # # # Given `dog` is an instance of a `Dog` # when2(dog.bark, 'Miau').thenReturn('Wuff') # # .. note:: You must :func:`unstub` after stubbing, or use `with` # statement. # # """ # obj, name = get_obj_attr_tuple(fn) # theMock = _get_mock(obj, strict=True) # return invocation.StubbedInvocation(theMock, name)(*args, **kwargs) # # Path: mockito/invocation.py # class RememberedProxyInvocation(Invocation): # '''Remeber params and proxy to method of original object. # # Calls method on original object and returns it's return value. # ''' # def __init__(self, mock, method_name): # super(RememberedProxyInvocation, self).__init__(mock, method_name) # self.verified = False # self.verified_inorder = False # # def __call__(self, *params, **named_params): # self._remember_params(params, named_params) # self.mock.remember(self) # obj = self.mock.spec # try: # method = getattr(obj, self.method_name) # except AttributeError: # raise AttributeError( # "You tried to call method '%s' which '%s' instance does not " # "have." % (self.method_name, obj)) # return method(*params, **named_params) # # Path: mockito/mocking.py # MYPY = False # OMITTED = _OMITTED() # class _Dummy(object): # class Mock(object): # class _OMITTED(object): # class Dummy(_Dummy): # def __call__(self, *args, **kwargs): # def remembered_invocation_builder(mock, method_name, *args, **kwargs): # def __init__(self, mocked_obj, strict=True, spec=None): # def remember(self, invocation): # def finish_stubbing(self, stubbed_invocation): # def clear_invocations(self): # def get_original_method(self, method_name): # def set_method(self, method_name, new_method): # def replace_method(self, method_name, original_method): # def new_mocked_method(*args, **kwargs): # def stub(self, method_name): # def forget_stubbed_invocation(self, invocation): # def restore_method(self, method_name, original_method): # def unstub(self): # def has_method(self, method_name): # def get_signature(self, method_name): # def __repr__(self): # def mock(config_or_spec=None, spec=None, strict=OMITTED): # def __getattr__(self, method_name): # def __repr__(self): # # Path: mockito/utils.py # def get_obj(path): # """Return obj for given dotted path. # # Typical inputs for `path` are 'os' or 'os.path' in which case you get a # module; or 'os.path.exists' in which case you get a function from that # module. # # Just returns the given input in case it is not a str. # # Note: Relative imports not supported. # Raises ImportError or AttributeError as appropriate. # # """ # # Since we usually pass in mocks here; duck typing is not appropriate # # (mocks respond to every attribute). # if not isinstance(path, str): # return path # # if path.startswith('.'): # raise TypeError('relative imports are not supported') # # parts = path.split('.') # head, tail = parts[0], parts[1:] # # obj = importlib.import_module(head) # # # Normally a simple reduce, but we go the extra mile # # for good exception messages. # for i, name in enumerate(tail): # try: # obj = getattr(obj, name) # except AttributeError: # # Note the [:i] instead of [:i+1], so we get the path just # # *before* the AttributeError, t.i. the part of it that went ok. # module = '.'.join([head] + tail[:i]) # try: # importlib.import_module(module) # except ImportError: # raise AttributeError( # "object '%s' has no attribute '%s'" % (module, name)) # else: # raise AttributeError( # "module '%s' has no attribute '%s'" % (module, name)) # return obj . Output only the next line.
class Spy(_Dummy):
Next line prediction: <|code_start|> import time time = spy(time) # inject time do_work(..., time) verify(time).time() """ if inspect.isclass(object) or inspect.ismodule(object): class_ = None else: class_ = object.__class__ class Spy(_Dummy): if class_: __class__ = class_ def __getattr__(self, method_name): return RememberedProxyInvocation(theMock, method_name) def __repr__(self): name = 'Spied' if class_: name += class_.__name__ return "<%s id=%s>" % (name, id(self)) obj = Spy() theMock = Mock(obj, strict=True, spec=object) <|code_end|> . Use current file imports: (import inspect from .mockito import when2 from .invocation import RememberedProxyInvocation from .mocking import Mock, _Dummy, mock_registry from .utils import get_obj) and context including class names, function names, or small code snippets from other files: # Path: mockito/mockito.py # def when2(fn, *args, **kwargs): # """Stub a function call with the given arguments # # Exposes a more pythonic interface than :func:`when`. See :func:`when` for # more documentation. # # Returns `AnswerSelector` interface which exposes `thenReturn`, # `thenRaise`, and `thenAnswer` as usual. Always `strict`. # # Usage:: # # # Given `dog` is an instance of a `Dog` # when2(dog.bark, 'Miau').thenReturn('Wuff') # # .. note:: You must :func:`unstub` after stubbing, or use `with` # statement. # # """ # obj, name = get_obj_attr_tuple(fn) # theMock = _get_mock(obj, strict=True) # return invocation.StubbedInvocation(theMock, name)(*args, **kwargs) # # Path: mockito/invocation.py # class RememberedProxyInvocation(Invocation): # '''Remeber params and proxy to method of original object. # # Calls method on original object and returns it's return value. # ''' # def __init__(self, mock, method_name): # super(RememberedProxyInvocation, self).__init__(mock, method_name) # self.verified = False # self.verified_inorder = False # # def __call__(self, *params, **named_params): # self._remember_params(params, named_params) # self.mock.remember(self) # obj = self.mock.spec # try: # method = getattr(obj, self.method_name) # except AttributeError: # raise AttributeError( # "You tried to call method '%s' which '%s' instance does not " # "have." % (self.method_name, obj)) # return method(*params, **named_params) # # Path: mockito/mocking.py # MYPY = False # OMITTED = _OMITTED() # class _Dummy(object): # class Mock(object): # class _OMITTED(object): # class Dummy(_Dummy): # def __call__(self, *args, **kwargs): # def remembered_invocation_builder(mock, method_name, *args, **kwargs): # def __init__(self, mocked_obj, strict=True, spec=None): # def remember(self, invocation): # def finish_stubbing(self, stubbed_invocation): # def clear_invocations(self): # def get_original_method(self, method_name): # def set_method(self, method_name, new_method): # def replace_method(self, method_name, original_method): # def new_mocked_method(*args, **kwargs): # def stub(self, method_name): # def forget_stubbed_invocation(self, invocation): # def restore_method(self, method_name, original_method): # def unstub(self): # def has_method(self, method_name): # def get_signature(self, method_name): # def __repr__(self): # def mock(config_or_spec=None, spec=None, strict=OMITTED): # def __getattr__(self, method_name): # def __repr__(self): # # Path: mockito/utils.py # def get_obj(path): # """Return obj for given dotted path. # # Typical inputs for `path` are 'os' or 'os.path' in which case you get a # module; or 'os.path.exists' in which case you get a function from that # module. # # Just returns the given input in case it is not a str. # # Note: Relative imports not supported. # Raises ImportError or AttributeError as appropriate. # # """ # # Since we usually pass in mocks here; duck typing is not appropriate # # (mocks respond to every attribute). # if not isinstance(path, str): # return path # # if path.startswith('.'): # raise TypeError('relative imports are not supported') # # parts = path.split('.') # head, tail = parts[0], parts[1:] # # obj = importlib.import_module(head) # # # Normally a simple reduce, but we go the extra mile # # for good exception messages. # for i, name in enumerate(tail): # try: # obj = getattr(obj, name) # except AttributeError: # # Note the [:i] instead of [:i+1], so we get the path just # # *before* the AttributeError, t.i. the part of it that went ok. # module = '.'.join([head] + tail[:i]) # try: # importlib.import_module(module) # except ImportError: # raise AttributeError( # "object '%s' has no attribute '%s'" % (module, name)) # else: # raise AttributeError( # "module '%s' has no attribute '%s'" % (module, name)) # return obj . Output only the next line.
mock_registry.register(obj, theMock)
Predict the next line for this snippet: <|code_start|> name += class_.__name__ return "<%s id=%s>" % (name, id(self)) obj = Spy() theMock = Mock(obj, strict=True, spec=object) mock_registry.register(obj, theMock) return obj def spy2(fn): # type: (...) -> None """Spy usage of given `fn`. Patches the module, class or object `fn` lives in, so that all interactions can be recorded; otherwise executes `fn` as before, so that all side effects happen as before. E.g.:: import time spy2(time.time) do_work(...) # nothing injected, uses global patched `time` module verify(time).time() Note that builtins often cannot be patched because they're read-only. """ if isinstance(fn, str): <|code_end|> with the help of current file imports: import inspect from .mockito import when2 from .invocation import RememberedProxyInvocation from .mocking import Mock, _Dummy, mock_registry from .utils import get_obj and context from other files: # Path: mockito/mockito.py # def when2(fn, *args, **kwargs): # """Stub a function call with the given arguments # # Exposes a more pythonic interface than :func:`when`. See :func:`when` for # more documentation. # # Returns `AnswerSelector` interface which exposes `thenReturn`, # `thenRaise`, and `thenAnswer` as usual. Always `strict`. # # Usage:: # # # Given `dog` is an instance of a `Dog` # when2(dog.bark, 'Miau').thenReturn('Wuff') # # .. note:: You must :func:`unstub` after stubbing, or use `with` # statement. # # """ # obj, name = get_obj_attr_tuple(fn) # theMock = _get_mock(obj, strict=True) # return invocation.StubbedInvocation(theMock, name)(*args, **kwargs) # # Path: mockito/invocation.py # class RememberedProxyInvocation(Invocation): # '''Remeber params and proxy to method of original object. # # Calls method on original object and returns it's return value. # ''' # def __init__(self, mock, method_name): # super(RememberedProxyInvocation, self).__init__(mock, method_name) # self.verified = False # self.verified_inorder = False # # def __call__(self, *params, **named_params): # self._remember_params(params, named_params) # self.mock.remember(self) # obj = self.mock.spec # try: # method = getattr(obj, self.method_name) # except AttributeError: # raise AttributeError( # "You tried to call method '%s' which '%s' instance does not " # "have." % (self.method_name, obj)) # return method(*params, **named_params) # # Path: mockito/mocking.py # MYPY = False # OMITTED = _OMITTED() # class _Dummy(object): # class Mock(object): # class _OMITTED(object): # class Dummy(_Dummy): # def __call__(self, *args, **kwargs): # def remembered_invocation_builder(mock, method_name, *args, **kwargs): # def __init__(self, mocked_obj, strict=True, spec=None): # def remember(self, invocation): # def finish_stubbing(self, stubbed_invocation): # def clear_invocations(self): # def get_original_method(self, method_name): # def set_method(self, method_name, new_method): # def replace_method(self, method_name, original_method): # def new_mocked_method(*args, **kwargs): # def stub(self, method_name): # def forget_stubbed_invocation(self, invocation): # def restore_method(self, method_name, original_method): # def unstub(self): # def has_method(self, method_name): # def get_signature(self, method_name): # def __repr__(self): # def mock(config_or_spec=None, spec=None, strict=OMITTED): # def __getattr__(self, method_name): # def __repr__(self): # # Path: mockito/utils.py # def get_obj(path): # """Return obj for given dotted path. # # Typical inputs for `path` are 'os' or 'os.path' in which case you get a # module; or 'os.path.exists' in which case you get a function from that # module. # # Just returns the given input in case it is not a str. # # Note: Relative imports not supported. # Raises ImportError or AttributeError as appropriate. # # """ # # Since we usually pass in mocks here; duck typing is not appropriate # # (mocks respond to every attribute). # if not isinstance(path, str): # return path # # if path.startswith('.'): # raise TypeError('relative imports are not supported') # # parts = path.split('.') # head, tail = parts[0], parts[1:] # # obj = importlib.import_module(head) # # # Normally a simple reduce, but we go the extra mile # # for good exception messages. # for i, name in enumerate(tail): # try: # obj = getattr(obj, name) # except AttributeError: # # Note the [:i] instead of [:i+1], so we get the path just # # *before* the AttributeError, t.i. the part of it that went ok. # module = '.'.join([head] + tail[:i]) # try: # importlib.import_module(module) # except ImportError: # raise AttributeError( # "object '%s' has no attribute '%s'" % (module, name)) # else: # raise AttributeError( # "module '%s' has no attribute '%s'" % (module, name)) # return obj , which may contain function names, class names, or code. Output only the next line.
answer = get_obj(fn)
Here is a snippet: <|code_start|> class TestCustomDictLike: def testAssignKeyValuePair(self): td = _Dict() obj = {} <|code_end|> . Write the next line using the current file imports: import pytest from mockito.mock_registry import _Dict from mockito.mocking import Mock and context from other files: # Path: mockito/mocking.py # class Mock(object): # def __init__(self, mocked_obj, strict=True, spec=None): # self.mocked_obj = mocked_obj # self.strict = strict # self.spec = spec # # self.invocations = deque() # type: Deque[RealInvocation] # self.stubbed_invocations = deque() # type: Deque[invocation.StubbedInvocation] # # self.original_methods = {} # self._signatures_store = {} # # def remember(self, invocation): # self.invocations.appendleft(invocation) # # def finish_stubbing(self, stubbed_invocation): # self.stubbed_invocations.appendleft(stubbed_invocation) # # def clear_invocations(self): # self.invocations = deque() # # # STUBBING # # def get_original_method(self, method_name): # """ # Looks up the original method on the `spec` object and returns it # together with an indication of whether the method is found # "directly" on the `spec` object. # # This is used to decide whether the method should be stored as an # original_method and should therefore be replaced when unstubbing. # """ # if self.spec is None: # return None, False # # try: # return self.spec.__dict__[method_name], True # except (AttributeError, KeyError): # # Classes with defined `__slots__` and then no `__dict__` are not # # patchable but if we catch the `AttributeError` here, we get # # the better error message for the user. # return getattr(self.spec, method_name, None), False # # def set_method(self, method_name, new_method): # setattr(self.mocked_obj, method_name, new_method) # # def replace_method(self, method_name, original_method): # # def new_mocked_method(*args, **kwargs): # # we throw away the first argument, if it's either self or cls # if ( # inspect.ismethod(new_mocked_method) # or inspect.isclass(self.mocked_obj) # and not isinstance(new_mocked_method, staticmethod) # ): # args = args[1:] # # return remembered_invocation_builder( # self, method_name, *args, **kwargs) # # new_mocked_method.__name__ = method_name # if original_method: # new_mocked_method.__doc__ = original_method.__doc__ # new_mocked_method.__wrapped__ = original_method # type: ignore[attr-defined] # try: # new_mocked_method.__module__ = original_method.__module__ # except AttributeError: # pass # # if inspect.ismethod(original_method): # new_mocked_method = utils.newmethod( # new_mocked_method, self.mocked_obj # ) # # if isinstance(original_method, staticmethod): # new_mocked_method = staticmethod(new_mocked_method) # type: ignore[assignment] # elif isinstance(original_method, classmethod): # new_mocked_method = classmethod(new_mocked_method) # type: ignore[assignment] # elif ( # inspect.isclass(self.mocked_obj) # and inspect.isclass(original_method) # TBC: Inner classes # ): # new_mocked_method = staticmethod(new_mocked_method) # type: ignore[assignment] # # self.set_method(method_name, new_mocked_method) # # def stub(self, method_name): # try: # self.original_methods[method_name] # except KeyError: # original_method, was_in_spec = self.get_original_method( # method_name) # if was_in_spec: # # This indicates the original method was found directly on # # the spec object and should therefore be restored by unstub # self.original_methods[method_name] = original_method # else: # self.original_methods[method_name] = None # # self.replace_method(method_name, original_method) # # def forget_stubbed_invocation(self, invocation): # assert invocation in self.stubbed_invocations # # if len(self.stubbed_invocations) == 1: # mock_registry.unstub(self.mocked_obj) # return # # self.stubbed_invocations.remove(invocation) # # if not any( # inv.method_name == invocation.method_name # for inv in self.stubbed_invocations # ): # original_method = self.original_methods.pop(invocation.method_name) # self.restore_method(invocation.method_name, original_method) # # def restore_method(self, method_name, original_method): # # If original_method is None, we *added* it to mocked_obj, so we # # must delete it here. # # If we mocked an instance, our mocked function will actually hide # # the one on its class, so we delete as well. # if ( # not original_method # or not inspect.isclass(self.mocked_obj) # and inspect.ismethod(original_method) # ): # delattr(self.mocked_obj, method_name) # else: # self.set_method(method_name, original_method) # # def unstub(self): # while self.original_methods: # method_name, original_method = self.original_methods.popitem() # self.restore_method(method_name, original_method) # # # SPECCING # # def has_method(self, method_name): # if self.spec is None: # return True # # return hasattr(self.spec, method_name) # # def get_signature(self, method_name): # if self.spec is None: # return None # # try: # return self._signatures_store[method_name] # except KeyError: # sig = signature.get_signature(self.spec, method_name) # self._signatures_store[method_name] = sig # return sig , which may include functions, classes, or code. Output only the next line.
mock = Mock(None)
Given the following code snippet before the placeholder: <|code_start|> pytestmark = pytest.mark.usefixtures("unstub") class Dog(object): def bark(self, sound): return sound def bark_hard(self, sound): return sound + '!' class TestMockito2: def testWhen2(self): rex = Dog() <|code_end|> , predict the next line using imports from the current file: import pytest import os import time from mockito import when2, patch, spy2, verify from mockito.utils import newmethod and context including class names, function names, and sometimes code from other files: # Path: mockito/mockito.py # def when2(fn, *args, **kwargs): # """Stub a function call with the given arguments # # Exposes a more pythonic interface than :func:`when`. See :func:`when` for # more documentation. # # Returns `AnswerSelector` interface which exposes `thenReturn`, # `thenRaise`, and `thenAnswer` as usual. Always `strict`. # # Usage:: # # # Given `dog` is an instance of a `Dog` # when2(dog.bark, 'Miau').thenReturn('Wuff') # # .. note:: You must :func:`unstub` after stubbing, or use `with` # statement. # # """ # obj, name = get_obj_attr_tuple(fn) # theMock = _get_mock(obj, strict=True) # return invocation.StubbedInvocation(theMock, name)(*args, **kwargs) # # def patch(fn, attr_or_replacement, replacement=None): # """Patch/Replace a function. # # This is really like monkeypatching, but *note* that all interactions # will be recorded and can be verified. That is, using `patch` you stay in # the domain of mockito. # # Two ways to call this. Either:: # # patch(os.path.exists, lambda str: True) # two arguments # # OR # patch(os.path, 'exists', lambda str: True) # three arguments # # If called with three arguments, the mode is *not* strict to allow *adding* # methods. If called with two arguments, mode is always `strict`. # # .. note:: You must :func:`unstub` after stubbing, or use `with` # statement. # # """ # if replacement is None: # replacement = attr_or_replacement # return when2(fn, Ellipsis).thenAnswer(replacement) # else: # obj, name = fn, attr_or_replacement # theMock = _get_mock(obj, strict=True) # return invocation.StubbedInvocation( # theMock, name, strict=False)(Ellipsis).thenAnswer(replacement) # # def verify(obj, times=1, atleast=None, atmost=None, between=None, # inorder=False): # """Central interface to verify interactions. # # `verify` uses a fluent interface:: # # verify(<obj>, times=2).<method_name>(<args>) # # `args` can be as concrete as necessary. Often a catch-all is enough, # especially if you're working with strict mocks, bc they throw at call # time on unwanted, unconfigured arguments:: # # from mockito import ANY, ARGS, KWARGS # when(manager).add_tasks(1, 2, 3) # ... # # no need to duplicate the specification; every other argument pattern # # would have raised anyway. # verify(manager).add_tasks(1, 2, 3) # duplicates `when`call # verify(manager).add_tasks(*ARGS) # verify(manager).add_tasks(...) # Py3 # verify(manager).add_tasks(Ellipsis) # Py2 # # """ # # if isinstance(obj, str): # obj = get_obj(obj) # # verification_fn = _get_wanted_verification( # times=times, atleast=atleast, atmost=atmost, between=between) # if inorder: # verification_fn = verification.InOrder(verification_fn) # # theMock = _get_mock_or_raise(obj) # # class Verify(object): # def __getattr__(self, method_name): # return invocation.VerifiableInvocation( # theMock, method_name, verification_fn) # # return Verify() # # Path: mockito/spying.py # def spy2(fn): # type: (...) -> None # """Spy usage of given `fn`. # # Patches the module, class or object `fn` lives in, so that all # interactions can be recorded; otherwise executes `fn` as before, so # that all side effects happen as before. # # E.g.:: # # import time # spy2(time.time) # do_work(...) # nothing injected, uses global patched `time` module # verify(time).time() # # Note that builtins often cannot be patched because they're read-only. # # # """ # if isinstance(fn, str): # answer = get_obj(fn) # else: # answer = fn # # when2(fn, Ellipsis).thenAnswer(answer) # # Path: mockito/utils.py # def newmethod(fn, obj): # return types.MethodType(fn, obj) . Output only the next line.
when2(rex.bark, 'Miau').thenReturn('Wuff')
Predict the next line for this snippet: <|code_start|> pytestmark = pytest.mark.usefixtures("unstub") class Dog(object): def bark(self, sound): return sound def bark_hard(self, sound): return sound + '!' class TestMockito2: def testWhen2(self): rex = Dog() when2(rex.bark, 'Miau').thenReturn('Wuff') when2(rex.bark, 'Miau').thenReturn('Grrr') assert rex.bark('Miau') == 'Grrr' def testPatch(self): rex = Dog() <|code_end|> with the help of current file imports: import pytest import os import time from mockito import when2, patch, spy2, verify from mockito.utils import newmethod and context from other files: # Path: mockito/mockito.py # def when2(fn, *args, **kwargs): # """Stub a function call with the given arguments # # Exposes a more pythonic interface than :func:`when`. See :func:`when` for # more documentation. # # Returns `AnswerSelector` interface which exposes `thenReturn`, # `thenRaise`, and `thenAnswer` as usual. Always `strict`. # # Usage:: # # # Given `dog` is an instance of a `Dog` # when2(dog.bark, 'Miau').thenReturn('Wuff') # # .. note:: You must :func:`unstub` after stubbing, or use `with` # statement. # # """ # obj, name = get_obj_attr_tuple(fn) # theMock = _get_mock(obj, strict=True) # return invocation.StubbedInvocation(theMock, name)(*args, **kwargs) # # def patch(fn, attr_or_replacement, replacement=None): # """Patch/Replace a function. # # This is really like monkeypatching, but *note* that all interactions # will be recorded and can be verified. That is, using `patch` you stay in # the domain of mockito. # # Two ways to call this. Either:: # # patch(os.path.exists, lambda str: True) # two arguments # # OR # patch(os.path, 'exists', lambda str: True) # three arguments # # If called with three arguments, the mode is *not* strict to allow *adding* # methods. If called with two arguments, mode is always `strict`. # # .. note:: You must :func:`unstub` after stubbing, or use `with` # statement. # # """ # if replacement is None: # replacement = attr_or_replacement # return when2(fn, Ellipsis).thenAnswer(replacement) # else: # obj, name = fn, attr_or_replacement # theMock = _get_mock(obj, strict=True) # return invocation.StubbedInvocation( # theMock, name, strict=False)(Ellipsis).thenAnswer(replacement) # # def verify(obj, times=1, atleast=None, atmost=None, between=None, # inorder=False): # """Central interface to verify interactions. # # `verify` uses a fluent interface:: # # verify(<obj>, times=2).<method_name>(<args>) # # `args` can be as concrete as necessary. Often a catch-all is enough, # especially if you're working with strict mocks, bc they throw at call # time on unwanted, unconfigured arguments:: # # from mockito import ANY, ARGS, KWARGS # when(manager).add_tasks(1, 2, 3) # ... # # no need to duplicate the specification; every other argument pattern # # would have raised anyway. # verify(manager).add_tasks(1, 2, 3) # duplicates `when`call # verify(manager).add_tasks(*ARGS) # verify(manager).add_tasks(...) # Py3 # verify(manager).add_tasks(Ellipsis) # Py2 # # """ # # if isinstance(obj, str): # obj = get_obj(obj) # # verification_fn = _get_wanted_verification( # times=times, atleast=atleast, atmost=atmost, between=between) # if inorder: # verification_fn = verification.InOrder(verification_fn) # # theMock = _get_mock_or_raise(obj) # # class Verify(object): # def __getattr__(self, method_name): # return invocation.VerifiableInvocation( # theMock, method_name, verification_fn) # # return Verify() # # Path: mockito/spying.py # def spy2(fn): # type: (...) -> None # """Spy usage of given `fn`. # # Patches the module, class or object `fn` lives in, so that all # interactions can be recorded; otherwise executes `fn` as before, so # that all side effects happen as before. # # E.g.:: # # import time # spy2(time.time) # do_work(...) # nothing injected, uses global patched `time` module # verify(time).time() # # Note that builtins often cannot be patched because they're read-only. # # # """ # if isinstance(fn, str): # answer = get_obj(fn) # else: # answer = fn # # when2(fn, Ellipsis).thenAnswer(answer) # # Path: mockito/utils.py # def newmethod(fn, obj): # return types.MethodType(fn, obj) , which may contain function names, class names, or code. Output only the next line.
patch(rex.bark, lambda sound: sound + '!')
Using the snippet: <|code_start|> class B(object): pass when2(A.B, 'Hi').thenReturn('Ho') assert A.B('Hi') == 'Ho' def testPatch(self): patch(os.path.commonprefix, lambda m: 'yup') patch(os.path.commonprefix, lambda m: 'yep') assert os.path.commonprefix(Ellipsis) == 'yep' def testWithPatchGivenTwoArgs(self): with patch(os.path.exists, lambda m: 'yup'): assert os.path.exists('foo') == 'yup' assert not os.path.exists('foo') def testWithPatchGivenThreeArgs(self): with patch(os.path, 'exists', lambda m: 'yup'): assert os.path.exists('foo') == 'yup' assert not os.path.exists('foo') def testSpy2(self): spy2(os.path.exists) assert os.path.exists('/Foo') is False <|code_end|> , determine the next line of code. You have imports: import pytest import os import time from mockito import when2, patch, spy2, verify from mockito.utils import newmethod and context (class names, function names, or code) available: # Path: mockito/mockito.py # def when2(fn, *args, **kwargs): # """Stub a function call with the given arguments # # Exposes a more pythonic interface than :func:`when`. See :func:`when` for # more documentation. # # Returns `AnswerSelector` interface which exposes `thenReturn`, # `thenRaise`, and `thenAnswer` as usual. Always `strict`. # # Usage:: # # # Given `dog` is an instance of a `Dog` # when2(dog.bark, 'Miau').thenReturn('Wuff') # # .. note:: You must :func:`unstub` after stubbing, or use `with` # statement. # # """ # obj, name = get_obj_attr_tuple(fn) # theMock = _get_mock(obj, strict=True) # return invocation.StubbedInvocation(theMock, name)(*args, **kwargs) # # def patch(fn, attr_or_replacement, replacement=None): # """Patch/Replace a function. # # This is really like monkeypatching, but *note* that all interactions # will be recorded and can be verified. That is, using `patch` you stay in # the domain of mockito. # # Two ways to call this. Either:: # # patch(os.path.exists, lambda str: True) # two arguments # # OR # patch(os.path, 'exists', lambda str: True) # three arguments # # If called with three arguments, the mode is *not* strict to allow *adding* # methods. If called with two arguments, mode is always `strict`. # # .. note:: You must :func:`unstub` after stubbing, or use `with` # statement. # # """ # if replacement is None: # replacement = attr_or_replacement # return when2(fn, Ellipsis).thenAnswer(replacement) # else: # obj, name = fn, attr_or_replacement # theMock = _get_mock(obj, strict=True) # return invocation.StubbedInvocation( # theMock, name, strict=False)(Ellipsis).thenAnswer(replacement) # # def verify(obj, times=1, atleast=None, atmost=None, between=None, # inorder=False): # """Central interface to verify interactions. # # `verify` uses a fluent interface:: # # verify(<obj>, times=2).<method_name>(<args>) # # `args` can be as concrete as necessary. Often a catch-all is enough, # especially if you're working with strict mocks, bc they throw at call # time on unwanted, unconfigured arguments:: # # from mockito import ANY, ARGS, KWARGS # when(manager).add_tasks(1, 2, 3) # ... # # no need to duplicate the specification; every other argument pattern # # would have raised anyway. # verify(manager).add_tasks(1, 2, 3) # duplicates `when`call # verify(manager).add_tasks(*ARGS) # verify(manager).add_tasks(...) # Py3 # verify(manager).add_tasks(Ellipsis) # Py2 # # """ # # if isinstance(obj, str): # obj = get_obj(obj) # # verification_fn = _get_wanted_verification( # times=times, atleast=atleast, atmost=atmost, between=between) # if inorder: # verification_fn = verification.InOrder(verification_fn) # # theMock = _get_mock_or_raise(obj) # # class Verify(object): # def __getattr__(self, method_name): # return invocation.VerifiableInvocation( # theMock, method_name, verification_fn) # # return Verify() # # Path: mockito/spying.py # def spy2(fn): # type: (...) -> None # """Spy usage of given `fn`. # # Patches the module, class or object `fn` lives in, so that all # interactions can be recorded; otherwise executes `fn` as before, so # that all side effects happen as before. # # E.g.:: # # import time # spy2(time.time) # do_work(...) # nothing injected, uses global patched `time` module # verify(time).time() # # Note that builtins often cannot be patched because they're read-only. # # # """ # if isinstance(fn, str): # answer = get_obj(fn) # else: # answer = fn # # when2(fn, Ellipsis).thenAnswer(answer) # # Path: mockito/utils.py # def newmethod(fn, obj): # return types.MethodType(fn, obj) . Output only the next line.
verify(os.path).exists('/Foo')
Given the following code snippet before the placeholder: <|code_start|> when2(A.B.c) def testEnsureToResolveClass(self): class A(object): class B(object): pass when2(A.B, 'Hi').thenReturn('Ho') assert A.B('Hi') == 'Ho' def testPatch(self): patch(os.path.commonprefix, lambda m: 'yup') patch(os.path.commonprefix, lambda m: 'yep') assert os.path.commonprefix(Ellipsis) == 'yep' def testWithPatchGivenTwoArgs(self): with patch(os.path.exists, lambda m: 'yup'): assert os.path.exists('foo') == 'yup' assert not os.path.exists('foo') def testWithPatchGivenThreeArgs(self): with patch(os.path, 'exists', lambda m: 'yup'): assert os.path.exists('foo') == 'yup' assert not os.path.exists('foo') def testSpy2(self): <|code_end|> , predict the next line using imports from the current file: import pytest import os import time from mockito import when2, patch, spy2, verify from mockito.utils import newmethod and context including class names, function names, and sometimes code from other files: # Path: mockito/mockito.py # def when2(fn, *args, **kwargs): # """Stub a function call with the given arguments # # Exposes a more pythonic interface than :func:`when`. See :func:`when` for # more documentation. # # Returns `AnswerSelector` interface which exposes `thenReturn`, # `thenRaise`, and `thenAnswer` as usual. Always `strict`. # # Usage:: # # # Given `dog` is an instance of a `Dog` # when2(dog.bark, 'Miau').thenReturn('Wuff') # # .. note:: You must :func:`unstub` after stubbing, or use `with` # statement. # # """ # obj, name = get_obj_attr_tuple(fn) # theMock = _get_mock(obj, strict=True) # return invocation.StubbedInvocation(theMock, name)(*args, **kwargs) # # def patch(fn, attr_or_replacement, replacement=None): # """Patch/Replace a function. # # This is really like monkeypatching, but *note* that all interactions # will be recorded and can be verified. That is, using `patch` you stay in # the domain of mockito. # # Two ways to call this. Either:: # # patch(os.path.exists, lambda str: True) # two arguments # # OR # patch(os.path, 'exists', lambda str: True) # three arguments # # If called with three arguments, the mode is *not* strict to allow *adding* # methods. If called with two arguments, mode is always `strict`. # # .. note:: You must :func:`unstub` after stubbing, or use `with` # statement. # # """ # if replacement is None: # replacement = attr_or_replacement # return when2(fn, Ellipsis).thenAnswer(replacement) # else: # obj, name = fn, attr_or_replacement # theMock = _get_mock(obj, strict=True) # return invocation.StubbedInvocation( # theMock, name, strict=False)(Ellipsis).thenAnswer(replacement) # # def verify(obj, times=1, atleast=None, atmost=None, between=None, # inorder=False): # """Central interface to verify interactions. # # `verify` uses a fluent interface:: # # verify(<obj>, times=2).<method_name>(<args>) # # `args` can be as concrete as necessary. Often a catch-all is enough, # especially if you're working with strict mocks, bc they throw at call # time on unwanted, unconfigured arguments:: # # from mockito import ANY, ARGS, KWARGS # when(manager).add_tasks(1, 2, 3) # ... # # no need to duplicate the specification; every other argument pattern # # would have raised anyway. # verify(manager).add_tasks(1, 2, 3) # duplicates `when`call # verify(manager).add_tasks(*ARGS) # verify(manager).add_tasks(...) # Py3 # verify(manager).add_tasks(Ellipsis) # Py2 # # """ # # if isinstance(obj, str): # obj = get_obj(obj) # # verification_fn = _get_wanted_verification( # times=times, atleast=atleast, atmost=atmost, between=between) # if inorder: # verification_fn = verification.InOrder(verification_fn) # # theMock = _get_mock_or_raise(obj) # # class Verify(object): # def __getattr__(self, method_name): # return invocation.VerifiableInvocation( # theMock, method_name, verification_fn) # # return Verify() # # Path: mockito/spying.py # def spy2(fn): # type: (...) -> None # """Spy usage of given `fn`. # # Patches the module, class or object `fn` lives in, so that all # interactions can be recorded; otherwise executes `fn` as before, so # that all side effects happen as before. # # E.g.:: # # import time # spy2(time.time) # do_work(...) # nothing injected, uses global patched `time` module # verify(time).time() # # Note that builtins often cannot be patched because they're read-only. # # # """ # if isinstance(fn, str): # answer = get_obj(fn) # else: # answer = fn # # when2(fn, Ellipsis).thenAnswer(answer) # # Path: mockito/utils.py # def newmethod(fn, obj): # return types.MethodType(fn, obj) . Output only the next line.
spy2(os.path.exists)
Here is a snippet: <|code_start|> def bark_hard(self, sound): return sound + '!' class TestMockito2: def testWhen2(self): rex = Dog() when2(rex.bark, 'Miau').thenReturn('Wuff') when2(rex.bark, 'Miau').thenReturn('Grrr') assert rex.bark('Miau') == 'Grrr' def testPatch(self): rex = Dog() patch(rex.bark, lambda sound: sound + '!') assert rex.bark('Miau') == 'Miau!' def testPatch2(self): rex = Dog() patch(rex.bark, rex.bark_hard) assert rex.bark('Miau') == 'Miau!' def testPatch3(self): rex = Dog() def f(self, sound): return self.bark_hard(sound) <|code_end|> . Write the next line using the current file imports: import pytest import os import time from mockito import when2, patch, spy2, verify from mockito.utils import newmethod and context from other files: # Path: mockito/mockito.py # def when2(fn, *args, **kwargs): # """Stub a function call with the given arguments # # Exposes a more pythonic interface than :func:`when`. See :func:`when` for # more documentation. # # Returns `AnswerSelector` interface which exposes `thenReturn`, # `thenRaise`, and `thenAnswer` as usual. Always `strict`. # # Usage:: # # # Given `dog` is an instance of a `Dog` # when2(dog.bark, 'Miau').thenReturn('Wuff') # # .. note:: You must :func:`unstub` after stubbing, or use `with` # statement. # # """ # obj, name = get_obj_attr_tuple(fn) # theMock = _get_mock(obj, strict=True) # return invocation.StubbedInvocation(theMock, name)(*args, **kwargs) # # def patch(fn, attr_or_replacement, replacement=None): # """Patch/Replace a function. # # This is really like monkeypatching, but *note* that all interactions # will be recorded and can be verified. That is, using `patch` you stay in # the domain of mockito. # # Two ways to call this. Either:: # # patch(os.path.exists, lambda str: True) # two arguments # # OR # patch(os.path, 'exists', lambda str: True) # three arguments # # If called with three arguments, the mode is *not* strict to allow *adding* # methods. If called with two arguments, mode is always `strict`. # # .. note:: You must :func:`unstub` after stubbing, or use `with` # statement. # # """ # if replacement is None: # replacement = attr_or_replacement # return when2(fn, Ellipsis).thenAnswer(replacement) # else: # obj, name = fn, attr_or_replacement # theMock = _get_mock(obj, strict=True) # return invocation.StubbedInvocation( # theMock, name, strict=False)(Ellipsis).thenAnswer(replacement) # # def verify(obj, times=1, atleast=None, atmost=None, between=None, # inorder=False): # """Central interface to verify interactions. # # `verify` uses a fluent interface:: # # verify(<obj>, times=2).<method_name>(<args>) # # `args` can be as concrete as necessary. Often a catch-all is enough, # especially if you're working with strict mocks, bc they throw at call # time on unwanted, unconfigured arguments:: # # from mockito import ANY, ARGS, KWARGS # when(manager).add_tasks(1, 2, 3) # ... # # no need to duplicate the specification; every other argument pattern # # would have raised anyway. # verify(manager).add_tasks(1, 2, 3) # duplicates `when`call # verify(manager).add_tasks(*ARGS) # verify(manager).add_tasks(...) # Py3 # verify(manager).add_tasks(Ellipsis) # Py2 # # """ # # if isinstance(obj, str): # obj = get_obj(obj) # # verification_fn = _get_wanted_verification( # times=times, atleast=atleast, atmost=atmost, between=between) # if inorder: # verification_fn = verification.InOrder(verification_fn) # # theMock = _get_mock_or_raise(obj) # # class Verify(object): # def __getattr__(self, method_name): # return invocation.VerifiableInvocation( # theMock, method_name, verification_fn) # # return Verify() # # Path: mockito/spying.py # def spy2(fn): # type: (...) -> None # """Spy usage of given `fn`. # # Patches the module, class or object `fn` lives in, so that all # interactions can be recorded; otherwise executes `fn` as before, so # that all side effects happen as before. # # E.g.:: # # import time # spy2(time.time) # do_work(...) # nothing injected, uses global patched `time` module # verify(time).time() # # Note that builtins often cannot be patched because they're read-only. # # # """ # if isinstance(fn, str): # answer = get_obj(fn) # else: # answer = fn # # when2(fn, Ellipsis).thenAnswer(answer) # # Path: mockito/utils.py # def newmethod(fn, obj): # return types.MethodType(fn, obj) , which may include functions, classes, or code. Output only the next line.
f = newmethod(f, rex)
Given the following code snippet before the placeholder: <|code_start|> class Dog(object): def waggle(self): return 'Unsure' def bark(self, sound='Wuff'): return sound class TestUntub: def testIndependentUnstubbing(self): rex = Dog() mox = Dog() <|code_end|> , predict the next line using imports from the current file: import pytest from mockito import when, unstub, verify, ArgumentError and context including class names, function names, and sometimes code from other files: # Path: mockito/mockito.py # def when(obj, strict=True): # """Central interface to stub functions on a given `obj` # # `obj` should be a module, a class or an instance of a class; it can be # a Dummy you created with :func:`mock`. ``when`` exposes a fluent interface # where you configure a stub in three steps:: # # when(<obj>).<method_name>(<args>).thenReturn(<value>) # # Compared to simple *patching*, stubbing in mockito requires you to specify # conrete `args` for which the stub will answer with a concrete `<value>`. # All invocations that do not match this specific call signature will be # rejected. They usually throw at call time. # # Stubbing in mockito's sense thus means not only to get rid of unwanted # side effects, but effectively to turn function calls into constants. # # E.g.:: # # # Given ``dog`` is an instance of a ``Dog`` # when(dog).bark('Grrr').thenReturn('Wuff') # when(dog).bark('Miau').thenRaise(TypeError()) # # # With this configuration set up: # assert dog.bark('Grrr') == 'Wuff' # dog.bark('Miau') # will throw TypeError # dog.bark('Wuff') # will throw unwanted interaction # # Stubbing can effectively be used as monkeypatching; usage shown with # the `with` context managing:: # # with when(os.path).exists('/foo').thenReturn(True): # ... # # Most of the time verifying your interactions is not necessary, because # your code under tests implicitly verifies the return value by evaluating # it. See :func:`verify` if you need to, see also :func:`expect` to setup # expected call counts up front. # # If your function is pure side effect and does not return something, you # can omit the specific answer. The default then is `None`:: # # when(manager).do_work() # # `when` verifies the method name, the expected argument signature, and the # actual, factual arguments your code under test uses against the original # object and its function so its easier to spot changing interfaces. # # Sometimes it's tedious to spell out all arguments:: # # from mockito import ANY, ARGS, KWARGS # when(requests).get('http://example.com/', **KWARGS).thenReturn(...) # when(os.path).exists(ANY) # when(os.path).exists(ANY(str)) # # .. note:: You must :func:`unstub` after stubbing, or use `with` # statement. # # Set ``strict=False`` to bypass the function signature checks. # # See related :func:`when2` which has a more pythonic interface. # # """ # # if isinstance(obj, str): # obj = get_obj(obj) # # theMock = _get_mock(obj, strict=strict) # # class When(object): # def __getattr__(self, method_name): # return invocation.StubbedInvocation( # theMock, method_name, strict=strict) # # return When() # # def unstub(*objs): # """Unstubs all stubbed methods and functions # # If you don't pass in any argument, *all* registered mocks and # patched modules, classes etc. will be unstubbed. # # Note that additionally, the underlying registry will be cleaned. # After an `unstub` you can't :func:`verify` anymore because all # interactions will be forgotten. # """ # # if objs: # for obj in objs: # mock_registry.unstub(obj) # else: # mock_registry.unstub_all() # # def verify(obj, times=1, atleast=None, atmost=None, between=None, # inorder=False): # """Central interface to verify interactions. # # `verify` uses a fluent interface:: # # verify(<obj>, times=2).<method_name>(<args>) # # `args` can be as concrete as necessary. Often a catch-all is enough, # especially if you're working with strict mocks, bc they throw at call # time on unwanted, unconfigured arguments:: # # from mockito import ANY, ARGS, KWARGS # when(manager).add_tasks(1, 2, 3) # ... # # no need to duplicate the specification; every other argument pattern # # would have raised anyway. # verify(manager).add_tasks(1, 2, 3) # duplicates `when`call # verify(manager).add_tasks(*ARGS) # verify(manager).add_tasks(...) # Py3 # verify(manager).add_tasks(Ellipsis) # Py2 # # """ # # if isinstance(obj, str): # obj = get_obj(obj) # # verification_fn = _get_wanted_verification( # times=times, atleast=atleast, atmost=atmost, between=between) # if inorder: # verification_fn = verification.InOrder(verification_fn) # # theMock = _get_mock_or_raise(obj) # # class Verify(object): # def __getattr__(self, method_name): # return invocation.VerifiableInvocation( # theMock, method_name, verification_fn) # # return Verify() # # class ArgumentError(Exception): # pass . Output only the next line.
when(rex).waggle().thenReturn('Yup')
Based on the snippet: <|code_start|> class Dog(object): def waggle(self): return 'Unsure' def bark(self, sound='Wuff'): return sound class TestUntub: def testIndependentUnstubbing(self): rex = Dog() mox = Dog() when(rex).waggle().thenReturn('Yup') when(mox).waggle().thenReturn('Nope') assert rex.waggle() == 'Yup' assert mox.waggle() == 'Nope' <|code_end|> , predict the immediate next line with the help of imports: import pytest from mockito import when, unstub, verify, ArgumentError and context (classes, functions, sometimes code) from other files: # Path: mockito/mockito.py # def when(obj, strict=True): # """Central interface to stub functions on a given `obj` # # `obj` should be a module, a class or an instance of a class; it can be # a Dummy you created with :func:`mock`. ``when`` exposes a fluent interface # where you configure a stub in three steps:: # # when(<obj>).<method_name>(<args>).thenReturn(<value>) # # Compared to simple *patching*, stubbing in mockito requires you to specify # conrete `args` for which the stub will answer with a concrete `<value>`. # All invocations that do not match this specific call signature will be # rejected. They usually throw at call time. # # Stubbing in mockito's sense thus means not only to get rid of unwanted # side effects, but effectively to turn function calls into constants. # # E.g.:: # # # Given ``dog`` is an instance of a ``Dog`` # when(dog).bark('Grrr').thenReturn('Wuff') # when(dog).bark('Miau').thenRaise(TypeError()) # # # With this configuration set up: # assert dog.bark('Grrr') == 'Wuff' # dog.bark('Miau') # will throw TypeError # dog.bark('Wuff') # will throw unwanted interaction # # Stubbing can effectively be used as monkeypatching; usage shown with # the `with` context managing:: # # with when(os.path).exists('/foo').thenReturn(True): # ... # # Most of the time verifying your interactions is not necessary, because # your code under tests implicitly verifies the return value by evaluating # it. See :func:`verify` if you need to, see also :func:`expect` to setup # expected call counts up front. # # If your function is pure side effect and does not return something, you # can omit the specific answer. The default then is `None`:: # # when(manager).do_work() # # `when` verifies the method name, the expected argument signature, and the # actual, factual arguments your code under test uses against the original # object and its function so its easier to spot changing interfaces. # # Sometimes it's tedious to spell out all arguments:: # # from mockito import ANY, ARGS, KWARGS # when(requests).get('http://example.com/', **KWARGS).thenReturn(...) # when(os.path).exists(ANY) # when(os.path).exists(ANY(str)) # # .. note:: You must :func:`unstub` after stubbing, or use `with` # statement. # # Set ``strict=False`` to bypass the function signature checks. # # See related :func:`when2` which has a more pythonic interface. # # """ # # if isinstance(obj, str): # obj = get_obj(obj) # # theMock = _get_mock(obj, strict=strict) # # class When(object): # def __getattr__(self, method_name): # return invocation.StubbedInvocation( # theMock, method_name, strict=strict) # # return When() # # def unstub(*objs): # """Unstubs all stubbed methods and functions # # If you don't pass in any argument, *all* registered mocks and # patched modules, classes etc. will be unstubbed. # # Note that additionally, the underlying registry will be cleaned. # After an `unstub` you can't :func:`verify` anymore because all # interactions will be forgotten. # """ # # if objs: # for obj in objs: # mock_registry.unstub(obj) # else: # mock_registry.unstub_all() # # def verify(obj, times=1, atleast=None, atmost=None, between=None, # inorder=False): # """Central interface to verify interactions. # # `verify` uses a fluent interface:: # # verify(<obj>, times=2).<method_name>(<args>) # # `args` can be as concrete as necessary. Often a catch-all is enough, # especially if you're working with strict mocks, bc they throw at call # time on unwanted, unconfigured arguments:: # # from mockito import ANY, ARGS, KWARGS # when(manager).add_tasks(1, 2, 3) # ... # # no need to duplicate the specification; every other argument pattern # # would have raised anyway. # verify(manager).add_tasks(1, 2, 3) # duplicates `when`call # verify(manager).add_tasks(*ARGS) # verify(manager).add_tasks(...) # Py3 # verify(manager).add_tasks(Ellipsis) # Py2 # # """ # # if isinstance(obj, str): # obj = get_obj(obj) # # verification_fn = _get_wanted_verification( # times=times, atleast=atleast, atmost=atmost, between=between) # if inorder: # verification_fn = verification.InOrder(verification_fn) # # theMock = _get_mock_or_raise(obj) # # class Verify(object): # def __getattr__(self, method_name): # return invocation.VerifiableInvocation( # theMock, method_name, verification_fn) # # return Verify() # # class ArgumentError(Exception): # pass . Output only the next line.
unstub(rex)
Predict the next line for this snippet: <|code_start|> return sound class TestUntub: def testIndependentUnstubbing(self): rex = Dog() mox = Dog() when(rex).waggle().thenReturn('Yup') when(mox).waggle().thenReturn('Nope') assert rex.waggle() == 'Yup' assert mox.waggle() == 'Nope' unstub(rex) assert rex.waggle() == 'Unsure' assert mox.waggle() == 'Nope' unstub(mox) assert mox.waggle() == 'Unsure' class TestAutomaticUnstubbing: def testWith1(self): rex = Dog() with when(rex).waggle().thenReturn('Yup'): assert rex.waggle() == 'Yup' <|code_end|> with the help of current file imports: import pytest from mockito import when, unstub, verify, ArgumentError and context from other files: # Path: mockito/mockito.py # def when(obj, strict=True): # """Central interface to stub functions on a given `obj` # # `obj` should be a module, a class or an instance of a class; it can be # a Dummy you created with :func:`mock`. ``when`` exposes a fluent interface # where you configure a stub in three steps:: # # when(<obj>).<method_name>(<args>).thenReturn(<value>) # # Compared to simple *patching*, stubbing in mockito requires you to specify # conrete `args` for which the stub will answer with a concrete `<value>`. # All invocations that do not match this specific call signature will be # rejected. They usually throw at call time. # # Stubbing in mockito's sense thus means not only to get rid of unwanted # side effects, but effectively to turn function calls into constants. # # E.g.:: # # # Given ``dog`` is an instance of a ``Dog`` # when(dog).bark('Grrr').thenReturn('Wuff') # when(dog).bark('Miau').thenRaise(TypeError()) # # # With this configuration set up: # assert dog.bark('Grrr') == 'Wuff' # dog.bark('Miau') # will throw TypeError # dog.bark('Wuff') # will throw unwanted interaction # # Stubbing can effectively be used as monkeypatching; usage shown with # the `with` context managing:: # # with when(os.path).exists('/foo').thenReturn(True): # ... # # Most of the time verifying your interactions is not necessary, because # your code under tests implicitly verifies the return value by evaluating # it. See :func:`verify` if you need to, see also :func:`expect` to setup # expected call counts up front. # # If your function is pure side effect and does not return something, you # can omit the specific answer. The default then is `None`:: # # when(manager).do_work() # # `when` verifies the method name, the expected argument signature, and the # actual, factual arguments your code under test uses against the original # object and its function so its easier to spot changing interfaces. # # Sometimes it's tedious to spell out all arguments:: # # from mockito import ANY, ARGS, KWARGS # when(requests).get('http://example.com/', **KWARGS).thenReturn(...) # when(os.path).exists(ANY) # when(os.path).exists(ANY(str)) # # .. note:: You must :func:`unstub` after stubbing, or use `with` # statement. # # Set ``strict=False`` to bypass the function signature checks. # # See related :func:`when2` which has a more pythonic interface. # # """ # # if isinstance(obj, str): # obj = get_obj(obj) # # theMock = _get_mock(obj, strict=strict) # # class When(object): # def __getattr__(self, method_name): # return invocation.StubbedInvocation( # theMock, method_name, strict=strict) # # return When() # # def unstub(*objs): # """Unstubs all stubbed methods and functions # # If you don't pass in any argument, *all* registered mocks and # patched modules, classes etc. will be unstubbed. # # Note that additionally, the underlying registry will be cleaned. # After an `unstub` you can't :func:`verify` anymore because all # interactions will be forgotten. # """ # # if objs: # for obj in objs: # mock_registry.unstub(obj) # else: # mock_registry.unstub_all() # # def verify(obj, times=1, atleast=None, atmost=None, between=None, # inorder=False): # """Central interface to verify interactions. # # `verify` uses a fluent interface:: # # verify(<obj>, times=2).<method_name>(<args>) # # `args` can be as concrete as necessary. Often a catch-all is enough, # especially if you're working with strict mocks, bc they throw at call # time on unwanted, unconfigured arguments:: # # from mockito import ANY, ARGS, KWARGS # when(manager).add_tasks(1, 2, 3) # ... # # no need to duplicate the specification; every other argument pattern # # would have raised anyway. # verify(manager).add_tasks(1, 2, 3) # duplicates `when`call # verify(manager).add_tasks(*ARGS) # verify(manager).add_tasks(...) # Py3 # verify(manager).add_tasks(Ellipsis) # Py2 # # """ # # if isinstance(obj, str): # obj = get_obj(obj) # # verification_fn = _get_wanted_verification( # times=times, atleast=atleast, atmost=atmost, between=between) # if inorder: # verification_fn = verification.InOrder(verification_fn) # # theMock = _get_mock_or_raise(obj) # # class Verify(object): # def __getattr__(self, method_name): # return invocation.VerifiableInvocation( # theMock, method_name, verification_fn) # # return Verify() # # class ArgumentError(Exception): # pass , which may contain function names, class names, or code. Output only the next line.
verify(rex).waggle()
Predict the next line after this snippet: <|code_start|> def testOnlyUnstubTheExactStub(self): rex = Dog() when(rex).bark('Shhh').thenReturn('Nope') with when(rex).bark('Miau').thenReturn('Grrr'): assert rex.bark('Miau') == 'Grrr' assert rex.bark('Shhh') == 'Nope' verify(rex, times=2).bark(Ellipsis) def testOnlyUnstubTheExcatMethod(self): rex = Dog() when(rex).bark('Shhh').thenReturn('Nope') with when(rex).waggle().thenReturn('Yup'): assert rex.waggle() == 'Yup' assert rex.bark('Shhh') == 'Nope' verify(rex, times=1).bark(Ellipsis) verify(rex, times=1).waggle() def testCleanupRegistryAfterLastStub(self): rex = Dog() with when(rex).bark('Shhh').thenReturn('Nope'): with when(rex).bark('Miau').thenReturn('Grrr'): assert rex.bark('Miau') == 'Grrr' assert rex.bark('Shhh') == 'Nope' <|code_end|> using the current file's imports: import pytest from mockito import when, unstub, verify, ArgumentError and any relevant context from other files: # Path: mockito/mockito.py # def when(obj, strict=True): # """Central interface to stub functions on a given `obj` # # `obj` should be a module, a class or an instance of a class; it can be # a Dummy you created with :func:`mock`. ``when`` exposes a fluent interface # where you configure a stub in three steps:: # # when(<obj>).<method_name>(<args>).thenReturn(<value>) # # Compared to simple *patching*, stubbing in mockito requires you to specify # conrete `args` for which the stub will answer with a concrete `<value>`. # All invocations that do not match this specific call signature will be # rejected. They usually throw at call time. # # Stubbing in mockito's sense thus means not only to get rid of unwanted # side effects, but effectively to turn function calls into constants. # # E.g.:: # # # Given ``dog`` is an instance of a ``Dog`` # when(dog).bark('Grrr').thenReturn('Wuff') # when(dog).bark('Miau').thenRaise(TypeError()) # # # With this configuration set up: # assert dog.bark('Grrr') == 'Wuff' # dog.bark('Miau') # will throw TypeError # dog.bark('Wuff') # will throw unwanted interaction # # Stubbing can effectively be used as monkeypatching; usage shown with # the `with` context managing:: # # with when(os.path).exists('/foo').thenReturn(True): # ... # # Most of the time verifying your interactions is not necessary, because # your code under tests implicitly verifies the return value by evaluating # it. See :func:`verify` if you need to, see also :func:`expect` to setup # expected call counts up front. # # If your function is pure side effect and does not return something, you # can omit the specific answer. The default then is `None`:: # # when(manager).do_work() # # `when` verifies the method name, the expected argument signature, and the # actual, factual arguments your code under test uses against the original # object and its function so its easier to spot changing interfaces. # # Sometimes it's tedious to spell out all arguments:: # # from mockito import ANY, ARGS, KWARGS # when(requests).get('http://example.com/', **KWARGS).thenReturn(...) # when(os.path).exists(ANY) # when(os.path).exists(ANY(str)) # # .. note:: You must :func:`unstub` after stubbing, or use `with` # statement. # # Set ``strict=False`` to bypass the function signature checks. # # See related :func:`when2` which has a more pythonic interface. # # """ # # if isinstance(obj, str): # obj = get_obj(obj) # # theMock = _get_mock(obj, strict=strict) # # class When(object): # def __getattr__(self, method_name): # return invocation.StubbedInvocation( # theMock, method_name, strict=strict) # # return When() # # def unstub(*objs): # """Unstubs all stubbed methods and functions # # If you don't pass in any argument, *all* registered mocks and # patched modules, classes etc. will be unstubbed. # # Note that additionally, the underlying registry will be cleaned. # After an `unstub` you can't :func:`verify` anymore because all # interactions will be forgotten. # """ # # if objs: # for obj in objs: # mock_registry.unstub(obj) # else: # mock_registry.unstub_all() # # def verify(obj, times=1, atleast=None, atmost=None, between=None, # inorder=False): # """Central interface to verify interactions. # # `verify` uses a fluent interface:: # # verify(<obj>, times=2).<method_name>(<args>) # # `args` can be as concrete as necessary. Often a catch-all is enough, # especially if you're working with strict mocks, bc they throw at call # time on unwanted, unconfigured arguments:: # # from mockito import ANY, ARGS, KWARGS # when(manager).add_tasks(1, 2, 3) # ... # # no need to duplicate the specification; every other argument pattern # # would have raised anyway. # verify(manager).add_tasks(1, 2, 3) # duplicates `when`call # verify(manager).add_tasks(*ARGS) # verify(manager).add_tasks(...) # Py3 # verify(manager).add_tasks(Ellipsis) # Py2 # # """ # # if isinstance(obj, str): # obj = get_obj(obj) # # verification_fn = _get_wanted_verification( # times=times, atleast=atleast, atmost=atmost, between=between) # if inorder: # verification_fn = verification.InOrder(verification_fn) # # theMock = _get_mock_or_raise(obj) # # class Verify(object): # def __getattr__(self, method_name): # return invocation.VerifiableInvocation( # theMock, method_name, verification_fn) # # return Verify() # # class ArgumentError(Exception): # pass . Output only the next line.
with pytest.raises(ArgumentError):
Continue the code snippet: <|code_start|> pytestmark = pytest.mark.usefixtures("unstub") def xcompare(a, b): if isinstance(a, mockito.matchers.Matcher): return a.matches(b) return np.array_equal(a, b) class TestEnsureNumpyWorks: def testEnsureNumpyArrayAllowedWhenStubbing(self): array = np.array([1, 2, 3]) <|code_end|> . Use current file imports: import mockito import pytest import numpy as np from mockito import when, patch from . import module and context (classes, functions, or code) from other files: # Path: mockito/mockito.py # def when(obj, strict=True): # """Central interface to stub functions on a given `obj` # # `obj` should be a module, a class or an instance of a class; it can be # a Dummy you created with :func:`mock`. ``when`` exposes a fluent interface # where you configure a stub in three steps:: # # when(<obj>).<method_name>(<args>).thenReturn(<value>) # # Compared to simple *patching*, stubbing in mockito requires you to specify # conrete `args` for which the stub will answer with a concrete `<value>`. # All invocations that do not match this specific call signature will be # rejected. They usually throw at call time. # # Stubbing in mockito's sense thus means not only to get rid of unwanted # side effects, but effectively to turn function calls into constants. # # E.g.:: # # # Given ``dog`` is an instance of a ``Dog`` # when(dog).bark('Grrr').thenReturn('Wuff') # when(dog).bark('Miau').thenRaise(TypeError()) # # # With this configuration set up: # assert dog.bark('Grrr') == 'Wuff' # dog.bark('Miau') # will throw TypeError # dog.bark('Wuff') # will throw unwanted interaction # # Stubbing can effectively be used as monkeypatching; usage shown with # the `with` context managing:: # # with when(os.path).exists('/foo').thenReturn(True): # ... # # Most of the time verifying your interactions is not necessary, because # your code under tests implicitly verifies the return value by evaluating # it. See :func:`verify` if you need to, see also :func:`expect` to setup # expected call counts up front. # # If your function is pure side effect and does not return something, you # can omit the specific answer. The default then is `None`:: # # when(manager).do_work() # # `when` verifies the method name, the expected argument signature, and the # actual, factual arguments your code under test uses against the original # object and its function so its easier to spot changing interfaces. # # Sometimes it's tedious to spell out all arguments:: # # from mockito import ANY, ARGS, KWARGS # when(requests).get('http://example.com/', **KWARGS).thenReturn(...) # when(os.path).exists(ANY) # when(os.path).exists(ANY(str)) # # .. note:: You must :func:`unstub` after stubbing, or use `with` # statement. # # Set ``strict=False`` to bypass the function signature checks. # # See related :func:`when2` which has a more pythonic interface. # # """ # # if isinstance(obj, str): # obj = get_obj(obj) # # theMock = _get_mock(obj, strict=strict) # # class When(object): # def __getattr__(self, method_name): # return invocation.StubbedInvocation( # theMock, method_name, strict=strict) # # return When() # # def patch(fn, attr_or_replacement, replacement=None): # """Patch/Replace a function. # # This is really like monkeypatching, but *note* that all interactions # will be recorded and can be verified. That is, using `patch` you stay in # the domain of mockito. # # Two ways to call this. Either:: # # patch(os.path.exists, lambda str: True) # two arguments # # OR # patch(os.path, 'exists', lambda str: True) # three arguments # # If called with three arguments, the mode is *not* strict to allow *adding* # methods. If called with two arguments, mode is always `strict`. # # .. note:: You must :func:`unstub` after stubbing, or use `with` # statement. # # """ # if replacement is None: # replacement = attr_or_replacement # return when2(fn, Ellipsis).thenAnswer(replacement) # else: # obj, name = fn, attr_or_replacement # theMock = _get_mock(obj, strict=True) # return invocation.StubbedInvocation( # theMock, name, strict=False)(Ellipsis).thenAnswer(replacement) . Output only the next line.
when(module).one_arg(array).thenReturn('yep')
Here is a snippet: <|code_start|> pytestmark = pytest.mark.usefixtures("unstub") def xcompare(a, b): if isinstance(a, mockito.matchers.Matcher): return a.matches(b) return np.array_equal(a, b) class TestEnsureNumpyWorks: def testEnsureNumpyArrayAllowedWhenStubbing(self): array = np.array([1, 2, 3]) when(module).one_arg(array).thenReturn('yep') <|code_end|> . Write the next line using the current file imports: import mockito import pytest import numpy as np from mockito import when, patch from . import module and context from other files: # Path: mockito/mockito.py # def when(obj, strict=True): # """Central interface to stub functions on a given `obj` # # `obj` should be a module, a class or an instance of a class; it can be # a Dummy you created with :func:`mock`. ``when`` exposes a fluent interface # where you configure a stub in three steps:: # # when(<obj>).<method_name>(<args>).thenReturn(<value>) # # Compared to simple *patching*, stubbing in mockito requires you to specify # conrete `args` for which the stub will answer with a concrete `<value>`. # All invocations that do not match this specific call signature will be # rejected. They usually throw at call time. # # Stubbing in mockito's sense thus means not only to get rid of unwanted # side effects, but effectively to turn function calls into constants. # # E.g.:: # # # Given ``dog`` is an instance of a ``Dog`` # when(dog).bark('Grrr').thenReturn('Wuff') # when(dog).bark('Miau').thenRaise(TypeError()) # # # With this configuration set up: # assert dog.bark('Grrr') == 'Wuff' # dog.bark('Miau') # will throw TypeError # dog.bark('Wuff') # will throw unwanted interaction # # Stubbing can effectively be used as monkeypatching; usage shown with # the `with` context managing:: # # with when(os.path).exists('/foo').thenReturn(True): # ... # # Most of the time verifying your interactions is not necessary, because # your code under tests implicitly verifies the return value by evaluating # it. See :func:`verify` if you need to, see also :func:`expect` to setup # expected call counts up front. # # If your function is pure side effect and does not return something, you # can omit the specific answer. The default then is `None`:: # # when(manager).do_work() # # `when` verifies the method name, the expected argument signature, and the # actual, factual arguments your code under test uses against the original # object and its function so its easier to spot changing interfaces. # # Sometimes it's tedious to spell out all arguments:: # # from mockito import ANY, ARGS, KWARGS # when(requests).get('http://example.com/', **KWARGS).thenReturn(...) # when(os.path).exists(ANY) # when(os.path).exists(ANY(str)) # # .. note:: You must :func:`unstub` after stubbing, or use `with` # statement. # # Set ``strict=False`` to bypass the function signature checks. # # See related :func:`when2` which has a more pythonic interface. # # """ # # if isinstance(obj, str): # obj = get_obj(obj) # # theMock = _get_mock(obj, strict=strict) # # class When(object): # def __getattr__(self, method_name): # return invocation.StubbedInvocation( # theMock, method_name, strict=strict) # # return When() # # def patch(fn, attr_or_replacement, replacement=None): # """Patch/Replace a function. # # This is really like monkeypatching, but *note* that all interactions # will be recorded and can be verified. That is, using `patch` you stay in # the domain of mockito. # # Two ways to call this. Either:: # # patch(os.path.exists, lambda str: True) # two arguments # # OR # patch(os.path, 'exists', lambda str: True) # three arguments # # If called with three arguments, the mode is *not* strict to allow *adding* # methods. If called with two arguments, mode is always `strict`. # # .. note:: You must :func:`unstub` after stubbing, or use `with` # statement. # # """ # if replacement is None: # replacement = attr_or_replacement # return when2(fn, Ellipsis).thenAnswer(replacement) # else: # obj, name = fn, attr_or_replacement # theMock = _get_mock(obj, strict=True) # return invocation.StubbedInvocation( # theMock, name, strict=False)(Ellipsis).thenAnswer(replacement) , which may include functions, classes, or code. Output only the next line.
with patch(mockito.invocation.MatchingInvocation.compare, xcompare):
Based on the snippet: <|code_start|> PY3 = sys.version_info >= (3,) def foo(): pass class TestLateImports: def testOs(self): <|code_end|> , predict the immediate next line with the help of imports: import pytest import sys import os import os.path import os.path import os import os import os import os from mockito.utils import get_obj, get_obj_attr_tuple and context (classes, functions, sometimes code) from other files: # Path: mockito/utils.py # def get_obj(path): # """Return obj for given dotted path. # # Typical inputs for `path` are 'os' or 'os.path' in which case you get a # module; or 'os.path.exists' in which case you get a function from that # module. # # Just returns the given input in case it is not a str. # # Note: Relative imports not supported. # Raises ImportError or AttributeError as appropriate. # # """ # # Since we usually pass in mocks here; duck typing is not appropriate # # (mocks respond to every attribute). # if not isinstance(path, str): # return path # # if path.startswith('.'): # raise TypeError('relative imports are not supported') # # parts = path.split('.') # head, tail = parts[0], parts[1:] # # obj = importlib.import_module(head) # # # Normally a simple reduce, but we go the extra mile # # for good exception messages. # for i, name in enumerate(tail): # try: # obj = getattr(obj, name) # except AttributeError: # # Note the [:i] instead of [:i+1], so we get the path just # # *before* the AttributeError, t.i. the part of it that went ok. # module = '.'.join([head] + tail[:i]) # try: # importlib.import_module(module) # except ImportError: # raise AttributeError( # "object '%s' has no attribute '%s'" % (module, name)) # else: # raise AttributeError( # "module '%s' has no attribute '%s'" % (module, name)) # return obj # # def get_obj_attr_tuple(path): # """Split path into (obj, attribute) tuple. # # Given `path` is 'os.path.exists' will thus return `(os.path, 'exists')` # # If path is not a str, delegates to `get_function_host(path)` # # """ # if not isinstance(path, str): # return get_function_host(path) # # if path.startswith('.'): # raise TypeError('relative imports are not supported') # # try: # leading, end = path.rsplit('.', 1) # except ValueError: # raise TypeError('path must have dots') # # return get_obj(leading), end . Output only the next line.
assert get_obj('os') is os
Given the code snippet: <|code_start|> "object 'os.path.exists' has no attribute 'forever'" def testUnknownMum(self): with pytest.raises(ImportError) as exc: assert get_obj('mum') is foo if PY3: assert str(exc.value) == "No module named 'mum'" else: assert str(exc.value) == "No module named mum" def testUnknownMumFoo(self): with pytest.raises(ImportError) as exc: assert get_obj('mum.foo') is foo if PY3: assert str(exc.value) == "No module named 'mum'" else: assert str(exc.value) == "No module named mum" def testReturnGivenObject(self): assert get_obj(os) == os assert get_obj(os.path) == os.path assert get_obj(2) == 2 def testDisallowRelativeImports(self): with pytest.raises(TypeError): get_obj('.mum') class TestReturnTuple: def testOs(self): with pytest.raises(TypeError): <|code_end|> , generate the next line using the imports in this file: import pytest import sys import os import os.path import os.path import os import os import os import os from mockito.utils import get_obj, get_obj_attr_tuple and context (functions, classes, or occasionally code) from other files: # Path: mockito/utils.py # def get_obj(path): # """Return obj for given dotted path. # # Typical inputs for `path` are 'os' or 'os.path' in which case you get a # module; or 'os.path.exists' in which case you get a function from that # module. # # Just returns the given input in case it is not a str. # # Note: Relative imports not supported. # Raises ImportError or AttributeError as appropriate. # # """ # # Since we usually pass in mocks here; duck typing is not appropriate # # (mocks respond to every attribute). # if not isinstance(path, str): # return path # # if path.startswith('.'): # raise TypeError('relative imports are not supported') # # parts = path.split('.') # head, tail = parts[0], parts[1:] # # obj = importlib.import_module(head) # # # Normally a simple reduce, but we go the extra mile # # for good exception messages. # for i, name in enumerate(tail): # try: # obj = getattr(obj, name) # except AttributeError: # # Note the [:i] instead of [:i+1], so we get the path just # # *before* the AttributeError, t.i. the part of it that went ok. # module = '.'.join([head] + tail[:i]) # try: # importlib.import_module(module) # except ImportError: # raise AttributeError( # "object '%s' has no attribute '%s'" % (module, name)) # else: # raise AttributeError( # "module '%s' has no attribute '%s'" % (module, name)) # return obj # # def get_obj_attr_tuple(path): # """Split path into (obj, attribute) tuple. # # Given `path` is 'os.path.exists' will thus return `(os.path, 'exists')` # # If path is not a str, delegates to `get_function_host(path)` # # """ # if not isinstance(path, str): # return get_function_host(path) # # if path.startswith('.'): # raise TypeError('relative imports are not supported') # # try: # leading, end = path.rsplit('.', 1) # except ValueError: # raise TypeError('path must have dots') # # return get_obj(leading), end . Output only the next line.
get_obj_attr_tuple('os')
Predict the next line after this snippet: <|code_start|> # master_db_host="192.168.1.175" # master_db_user="zzjr" # master_db_password='zzjr#2015' # master_db_name='zzjr_server' # # def exec_db(db_name,cmd): # res={'status':None,'mod_rows':None} # try: # con = mdb.connect(master_db_host, master_db_user, master_db_password, master_db_name, charset='utf8') # cur = con.cursor() # cur.execute(cmd) # cur.close() # mod_rows = cur.rowcount # print mod_rows # res.update({'status':'ok','mod_rows':mod_rows}) # con.commit() # return res # except mdb.IntegrityError,e: # res.update({'status': e}) # return res # exec_db('zzjr_bank',cmd) def db_list(db_role): <|code_end|> using the current file's imports: import MySQLdb as mdb import os import ConfigParser from dbtool.models import Dblist from warnings import filterwarnings and any relevant context from other files: # Path: dbtool/models.py # class Dblist(models.Model): # """ # asset modle # create_time = models.DateTime(default=datetime.now) # """ # dbname=models.CharField(max_length=20, blank=True, null=True, verbose_name=u"DB_IP") # db_role = models.CharField(max_length=20, blank=True, null=True, verbose_name=u"db_role") # # # def __unicode__(self): # return self.dbname . Output only the next line.
dblist=Dblist.objects.filter(db_role=db_role)
Given snippet: <|code_start|># coding:utf-8 '''# "user_id","db_name","sqllog","create_time","status","comments","type"''' class SqllogForm(forms.ModelForm): class Meta: model = Sqllog ordering = ['-create_time'] fields = [ "user_id","user_name","db_name","sqllog","check_mod_rows","real_mod_rows","create_time","status","comments","type" ] class DblistForm(forms.ModelForm): class Meta: <|code_end|> , continue by predicting the next line. Consider current file imports: from django import forms from dbtool.models import Sqllog,Dblist and context: # Path: dbtool/models.py # class Sqllog(models.Model): # """ # asset modle # create_time = models.DateTime(default=datetime.now) # """ # STATUS = ( # ('0', '已执行'), # ('1', '待执行'), # ('2', '作废'), # ) # # # user_id = models.IntegerField(max_length=128, blank=True, null=True, verbose_name=u"user_id") # user_name = models.CharField(max_length=20, blank=True, null=True, verbose_name=u"user_name") # db_name = models.CharField(max_length=50, blank=True, null=True, verbose_name=u"db_name") # sqllog = models.TextField(max_length=2000, blank = True, null = True, verbose_name = u"sqllog") # create_time=models.DateTimeField(default=datetime.now,blank = True) # check_mod_rows = models.IntegerField(max_length=20, blank=True, null=True, verbose_name=u"check_mod_rows") # real_mod_rows = models.IntegerField(max_length=20, blank=True, null=True, verbose_name=u"real_mod_rows") # status = models.IntegerField(max_length=2, blank=True, null=True, verbose_name=u"status",choices=STATUS) # comments = models.CharField(max_length=20, blank=True, null=True, verbose_name=u"comments") # type = models.IntegerField(max_length=20, blank=True, null=True, verbose_name=u"type") # # # # def __unicode__(self): # return self.user_id # # class Dblist(models.Model): # """ # asset modle # create_time = models.DateTime(default=datetime.now) # """ # dbname=models.CharField(max_length=20, blank=True, null=True, verbose_name=u"DB_IP") # db_role = models.CharField(max_length=20, blank=True, null=True, verbose_name=u"db_role") # # # def __unicode__(self): # return self.dbname which might include code, classes, or functions. Output only the next line.
model = Dblist
Predict the next line after this snippet: <|code_start|> error = e.message return my_render('setting.html', locals(), request) @login_required(login_url='/login') def upload(request): user = request.user assets = get_group_user_perm(user).get('asset').keys() asset_select = [] if request.method == 'POST': remote_ip = request.META.get('REMOTE_ADDR') asset_ids = request.POST.getlist('asset_ids', '') upload_files = request.FILES.getlist('file[]', None) date_now = datetime.datetime.now().strftime("%Y%m%d%H%M%S") upload_dir = get_tmp_dir() # file_dict = {} for asset_id in asset_ids: asset_select.append(get_object(Asset, id=asset_id)) if not set(asset_select).issubset(set(assets)): illegal_asset = set(asset_select).issubset(set(assets)) return HttpResponse('没有权限的服务器 %s' % ','.join([asset.hostname for asset in illegal_asset])) for upload_file in upload_files: file_path = '%s/%s' % (upload_dir, upload_file.name) with open(file_path, 'w') as f: for chunk in upload_file.chunks(): f.write(chunk) res = gen_resource({'user': user, 'asset': asset_select}) <|code_end|> using the current file's imports: import uuid import urllib import paramiko import zipfile from django.db.models import Count from django.shortcuts import render_to_response from django.template import RequestContext from django.http import HttpResponseNotFound from django.http import HttpResponse from jumpserver.api import * from jumpserver.models import Setting from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from jlog.models import Log, FileLog from jperm.perm_api import get_group_user_perm, gen_resource from jasset.models import Asset, IDC from jperm.ansible_api import MyRunner and any relevant context from other files: # Path: jperm/ansible_api.py # class MyRunner(MyInventory): # """ # This is a General object for parallel execute modules. # """ # def __init__(self, *args, **kwargs): # super(MyRunner, self).__init__(*args, **kwargs) # self.results_raw = {} # # def run(self, module_name='shell', module_args='', timeout=10, forks=10, pattern='*', # become=False, become_method='sudo', become_user='root', become_pass='', transport='paramiko'): # """ # run module from andible ad-hoc. # module_name: ansible module_name # module_args: ansible module args # """ # hoc = Runner(module_name=module_name, # module_args=module_args, # timeout=timeout, # inventory=self.inventory, # pattern=pattern, # forks=forks, # become=become, # become_method=become_method, # become_user=become_user, # become_pass=become_pass, # transport=transport # ) # self.results_raw = hoc.run() # logger.debug(self.results_raw) # return self.results_raw # # @property # def results(self): # """ # {'failed': {'localhost': ''}, 'ok': {'jumpserver': ''}} # """ # result = {'failed': {}, 'ok': {}} # dark = self.results_raw.get('dark') # contacted = self.results_raw.get('contacted') # if dark: # for host, info in dark.items(): # result['failed'][host] = info.get('msg') # # if contacted: # for host, info in contacted.items(): # if info.get('invocation').get('module_name') in ['raw', 'shell', 'command', 'script']: # if info.get('rc') == 0: # result['ok'][host] = info.get('stdout') + info.get('stderr') # else: # result['failed'][host] = info.get('stdout') + info.get('stderr') # else: # if info.get('failed'): # result['failed'][host] = info.get('msg') # else: # result['ok'][host] = info.get('changed') # return result . Output only the next line.
runner = MyRunner(res)
Given the code snippet: <|code_start|>#!/usr/bin/env python # coding: utf-8 try: except ImportError: os.environ['DJANGO_SETTINGS_MODULE'] = 'jumpserver.settings' define("port", default=PORT, help="run on the given port", type=int) <|code_end|> , generate the next line using the imports in this file: import time import datetime import json import os import sys import os.path import threading import re import functools import tornado.ioloop import tornado.options import tornado.web import tornado.websocket import tornado.httpserver import tornado.gen import tornado.httpclient import select import simplejson as json import json import time import tornado.wsgi from django.core.signals import request_started, request_finished from tornado.websocket import WebSocketClosedError from tornado.options import define, options from pyinotify import WatchManager, ProcessEvent, IN_DELETE, IN_CREATE, IN_MODIFY, AsyncNotifier from connect import Tty, User, Asset, PermRole, logger, get_object, gen_resource from connect import TtyLog, Log, Session, user_have_perm, get_group_user_perm, MyRunner, ExecLog from jumpserver.settings import IP, PORT from jlog.views import TermLogRecorder from collections import deque from django.core.wsgi import get_wsgi_application and context (functions, classes, or occasionally code) from other files: # Path: jumpserver/settings.py # IP = config.get('base', 'ip') # # PORT = config.get('base', 'port') . Output only the next line.
define("host", default=IP, help="run port on given host", type=str)
Using the snippet: <|code_start|>#!/usr/bin/env python # coding: utf-8 try: except ImportError: os.environ['DJANGO_SETTINGS_MODULE'] = 'jumpserver.settings' <|code_end|> , determine the next line of code. You have imports: import time import datetime import json import os import sys import os.path import threading import re import functools import tornado.ioloop import tornado.options import tornado.web import tornado.websocket import tornado.httpserver import tornado.gen import tornado.httpclient import select import simplejson as json import json import time import tornado.wsgi from django.core.signals import request_started, request_finished from tornado.websocket import WebSocketClosedError from tornado.options import define, options from pyinotify import WatchManager, ProcessEvent, IN_DELETE, IN_CREATE, IN_MODIFY, AsyncNotifier from connect import Tty, User, Asset, PermRole, logger, get_object, gen_resource from connect import TtyLog, Log, Session, user_have_perm, get_group_user_perm, MyRunner, ExecLog from jumpserver.settings import IP, PORT from jlog.views import TermLogRecorder from collections import deque from django.core.wsgi import get_wsgi_application and context (class names, function names, or code) available: # Path: jumpserver/settings.py # IP = config.get('base', 'ip') # # PORT = config.get('base', 'port') . Output only the next line.
define("port", default=PORT, help="run on the given port", type=int)
Next line prediction: <|code_start|># coding: utf-8 db = mysql.connect(user="root", passwd="", \ db="jumpserver", charset="utf8") db.autocommit(True) c = db.cursor() # Create your views here. redis_path='/root/jumpserver-master/redis-3.2.8/src/redis-cli -c ' notallowcmds=["del","flushall","flushdb","set"] # @require_role(role='user') def cachemanage_redislistjson(request): redis_list=[{"id": '请选择数据库', "text": "请选择数据库", "icon": "database.ico", "selected": "true"}] defend_attack(request) <|code_end|> . Use current file imports: (from django.shortcuts import render from juser.user_api import * from cachemanage.models import Redislist import os import MySQLdb as mysql import json) and context including class names, function names, or small code snippets from other files: # Path: cachemanage/models.py # class Redislist(models.Model): # """ # asset modle # create_time = models.DateTime(default=datetime.now) # """ # redis_host=models.CharField(max_length=100, blank=True, null=True, verbose_name=u"redis_host") # redis_role = models.CharField(max_length=20, blank=True, null=True, verbose_name=u"redis_role") # # # def __unicode__(self): # return self.redis_host . Output only the next line.
mylist=Redislist.objects.filter(redis_role="master")
Predict the next line for this snippet: <|code_start|> return HttpResponse(json.dumps(res), content_type="application/json") return my_render('dbtool/check_sql.html', locals(), request) ########submit_sql###### @require_role(role='user') def dbtool_submit_sql(request): defend_attack(request) dblist=Dblist.objects.all() # Sqllog_Form = SqllogForm(request.POST) # print Sqllog_Form # print dblist # db = request.POST.get('db') # cmd = request.POST.get('cmd') # cmd=cmd.replace("\r\n", " ") # res = {} # res['sqltype']=cmd.split()[0] if request.method == 'POST': sf_post = SqllogForm(request.POST) print sf_post db_name = request.POST.get('db') sqllog = request.POST.get('cmd') sqllog = sqllog.replace("\r\n", " ") create_time=datetime.datetime.now() user_id = request.user.id user = get_object(User, id=user_id) print user.username try: <|code_end|> with the help of current file imports: from juser.user_api import * from jperm.perm_api import get_group_user_perm from dbtool.models import Sqllog from dbtool.models import Dblist from dbtool.forms import SqllogForm from django.http import HttpResponse from django.db import connection from django.db.models import Q from warnings import filterwarnings import re import json import MySQLdb as mdb import datetime import re import dbtool_api import os import ConfigParser and context from other files: # Path: dbtool/models.py # class Sqllog(models.Model): # """ # asset modle # create_time = models.DateTime(default=datetime.now) # """ # STATUS = ( # ('0', '已执行'), # ('1', '待执行'), # ('2', '作废'), # ) # # # user_id = models.IntegerField(max_length=128, blank=True, null=True, verbose_name=u"user_id") # user_name = models.CharField(max_length=20, blank=True, null=True, verbose_name=u"user_name") # db_name = models.CharField(max_length=50, blank=True, null=True, verbose_name=u"db_name") # sqllog = models.TextField(max_length=2000, blank = True, null = True, verbose_name = u"sqllog") # create_time=models.DateTimeField(default=datetime.now,blank = True) # check_mod_rows = models.IntegerField(max_length=20, blank=True, null=True, verbose_name=u"check_mod_rows") # real_mod_rows = models.IntegerField(max_length=20, blank=True, null=True, verbose_name=u"real_mod_rows") # status = models.IntegerField(max_length=2, blank=True, null=True, verbose_name=u"status",choices=STATUS) # comments = models.CharField(max_length=20, blank=True, null=True, verbose_name=u"comments") # type = models.IntegerField(max_length=20, blank=True, null=True, verbose_name=u"type") # # # # def __unicode__(self): # return self.user_id # # Path: dbtool/models.py # class Dblist(models.Model): # """ # asset modle # create_time = models.DateTime(default=datetime.now) # """ # dbname=models.CharField(max_length=20, blank=True, null=True, verbose_name=u"DB_IP") # db_role = models.CharField(max_length=20, blank=True, null=True, verbose_name=u"db_role") # # # def __unicode__(self): # return self.dbname # # Path: dbtool/forms.py # class SqllogForm(forms.ModelForm): # # class Meta: # model = Sqllog # ordering = ['-create_time'] # # fields = [ # "user_id","user_name","db_name","sqllog","check_mod_rows","real_mod_rows","create_time","status","comments","type" # ] , which may contain function names, class names, or code. Output only the next line.
if Sqllog.objects.filter(Q(sqllog=unicode(sqllog)) & ~Q(status = 0)):
Using the snippet: <|code_start|> con = mdb.connect(check_db_host, check_db_user, check_db_password, db, charset='utf8') con.autocommit(0) cur = con.cursor() cur.execute(cmd) cur.close() mod_rows= cur.rowcount # con.commit() not commit sql res["cmd"]=cmd res["mod_rows"]=mod_rows con.rollback() return HttpResponse(json.dumps(res), content_type="application/json") except mdb.Error, e: res["err_code"]=e.args[0] res["err_text"] = e.args[1] print "Mysql Error %d: %s" % (e.args[0], e.args[1]) # return HttpResponse(e.args[1]) return HttpResponse(json.dumps(res), content_type="application/json") return my_render('dbtool/check_sql.html', locals(), request) ########submit_sql###### @require_role(role='user') def dbtool_submit_sql(request): defend_attack(request) <|code_end|> , determine the next line of code. You have imports: from juser.user_api import * from jperm.perm_api import get_group_user_perm from dbtool.models import Sqllog from dbtool.models import Dblist from dbtool.forms import SqllogForm from django.http import HttpResponse from django.db import connection from django.db.models import Q from warnings import filterwarnings import re import json import MySQLdb as mdb import datetime import re import dbtool_api import os import ConfigParser and context (class names, function names, or code) available: # Path: dbtool/models.py # class Sqllog(models.Model): # """ # asset modle # create_time = models.DateTime(default=datetime.now) # """ # STATUS = ( # ('0', '已执行'), # ('1', '待执行'), # ('2', '作废'), # ) # # # user_id = models.IntegerField(max_length=128, blank=True, null=True, verbose_name=u"user_id") # user_name = models.CharField(max_length=20, blank=True, null=True, verbose_name=u"user_name") # db_name = models.CharField(max_length=50, blank=True, null=True, verbose_name=u"db_name") # sqllog = models.TextField(max_length=2000, blank = True, null = True, verbose_name = u"sqllog") # create_time=models.DateTimeField(default=datetime.now,blank = True) # check_mod_rows = models.IntegerField(max_length=20, blank=True, null=True, verbose_name=u"check_mod_rows") # real_mod_rows = models.IntegerField(max_length=20, blank=True, null=True, verbose_name=u"real_mod_rows") # status = models.IntegerField(max_length=2, blank=True, null=True, verbose_name=u"status",choices=STATUS) # comments = models.CharField(max_length=20, blank=True, null=True, verbose_name=u"comments") # type = models.IntegerField(max_length=20, blank=True, null=True, verbose_name=u"type") # # # # def __unicode__(self): # return self.user_id # # Path: dbtool/models.py # class Dblist(models.Model): # """ # asset modle # create_time = models.DateTime(default=datetime.now) # """ # dbname=models.CharField(max_length=20, blank=True, null=True, verbose_name=u"DB_IP") # db_role = models.CharField(max_length=20, blank=True, null=True, verbose_name=u"db_role") # # # def __unicode__(self): # return self.dbname # # Path: dbtool/forms.py # class SqllogForm(forms.ModelForm): # # class Meta: # model = Sqllog # ordering = ['-create_time'] # # fields = [ # "user_id","user_name","db_name","sqllog","check_mod_rows","real_mod_rows","create_time","status","comments","type" # ] . Output only the next line.
dblist=Dblist.objects.all()
Given snippet: <|code_start|> con.rollback() return HttpResponse(json.dumps(res), content_type="application/json") except mdb.Error, e: res["err_code"]=e.args[0] res["err_text"] = e.args[1] print "Mysql Error %d: %s" % (e.args[0], e.args[1]) # return HttpResponse(e.args[1]) return HttpResponse(json.dumps(res), content_type="application/json") return my_render('dbtool/check_sql.html', locals(), request) ########submit_sql###### @require_role(role='user') def dbtool_submit_sql(request): defend_attack(request) dblist=Dblist.objects.all() # Sqllog_Form = SqllogForm(request.POST) # print Sqllog_Form # print dblist # db = request.POST.get('db') # cmd = request.POST.get('cmd') # cmd=cmd.replace("\r\n", " ") # res = {} # res['sqltype']=cmd.split()[0] if request.method == 'POST': <|code_end|> , continue by predicting the next line. Consider current file imports: from juser.user_api import * from jperm.perm_api import get_group_user_perm from dbtool.models import Sqllog from dbtool.models import Dblist from dbtool.forms import SqllogForm from django.http import HttpResponse from django.db import connection from django.db.models import Q from warnings import filterwarnings import re import json import MySQLdb as mdb import datetime import re import dbtool_api import os import ConfigParser and context: # Path: dbtool/models.py # class Sqllog(models.Model): # """ # asset modle # create_time = models.DateTime(default=datetime.now) # """ # STATUS = ( # ('0', '已执行'), # ('1', '待执行'), # ('2', '作废'), # ) # # # user_id = models.IntegerField(max_length=128, blank=True, null=True, verbose_name=u"user_id") # user_name = models.CharField(max_length=20, blank=True, null=True, verbose_name=u"user_name") # db_name = models.CharField(max_length=50, blank=True, null=True, verbose_name=u"db_name") # sqllog = models.TextField(max_length=2000, blank = True, null = True, verbose_name = u"sqllog") # create_time=models.DateTimeField(default=datetime.now,blank = True) # check_mod_rows = models.IntegerField(max_length=20, blank=True, null=True, verbose_name=u"check_mod_rows") # real_mod_rows = models.IntegerField(max_length=20, blank=True, null=True, verbose_name=u"real_mod_rows") # status = models.IntegerField(max_length=2, blank=True, null=True, verbose_name=u"status",choices=STATUS) # comments = models.CharField(max_length=20, blank=True, null=True, verbose_name=u"comments") # type = models.IntegerField(max_length=20, blank=True, null=True, verbose_name=u"type") # # # # def __unicode__(self): # return self.user_id # # Path: dbtool/models.py # class Dblist(models.Model): # """ # asset modle # create_time = models.DateTime(default=datetime.now) # """ # dbname=models.CharField(max_length=20, blank=True, null=True, verbose_name=u"DB_IP") # db_role = models.CharField(max_length=20, blank=True, null=True, verbose_name=u"db_role") # # # def __unicode__(self): # return self.dbname # # Path: dbtool/forms.py # class SqllogForm(forms.ModelForm): # # class Meta: # model = Sqllog # ordering = ['-create_time'] # # fields = [ # "user_id","user_name","db_name","sqllog","check_mod_rows","real_mod_rows","create_time","status","comments","type" # ] which might include code, classes, or functions. Output only the next line.
sf_post = SqllogForm(request.POST)
Given the following code snippet before the placeholder: <|code_start|>class Annotation(object): """A name mention and its predicted candidates Parameters ---------- Attributes ---------- TODO is_first : bool or unset Indicates if this annotation is the first in the document for this eid. * : Other attributes are automatically adopted from the top candidate """ __slots__ = ['docid', 'start', 'end', 'candidates', 'is_first'] def __init__(self, docid, start, end, candidates=[]): self.docid = docid self.start = start self.end = end self.candidates = candidates def __unicode__(self): return u'{}\t{}\t{}\t{}'.format( self.docid, self.start, self.end, <|code_end|> , predict the next line using imports from the current file: from collections import Sequence, defaultdict from .utils import unicode from . import coref_metrics import operator import warnings import json import itertools and context including class names, function names, and sometimes code from other files: # Path: neleval/utils.py # WIKI_PREFIX = re.compile('^http://[^.]+.wikipedia.org/wiki/') # def normalise_link(l): # def utf8_open(path, mode='r'): # def json_dumps(obj, sort_keys=True, indent=4): # def default(o): . Output only the next line.
u'\t'.join([unicode(c) for c in self.candidates])
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python class ToWeak(object): """Convert annotations to char-level for weak evaluation A better approach is to use measures with partial overlap support. """ def __init__(self, fname): self.fname = fname def __call__(self): return u'\n'.join(unicode(a) for a in self.annotations()).encode(ENC) def annotations(self): for line in open(self.fname): <|code_end|> with the help of current file imports: from .annotation import Annotation from .document import ENC from .utils import unicode and context from other files: # Path: neleval/annotation.py # class Annotation(object): # """A name mention and its predicted candidates # # Parameters # ---------- # # Attributes # ---------- # TODO # is_first : bool or unset # Indicates if this annotation is the first in the document for this # eid. # # * : # Other attributes are automatically adopted from the top candidate # """ # # __slots__ = ['docid', 'start', 'end', 'candidates', 'is_first'] # # def __init__(self, docid, start, end, candidates=[]): # self.docid = docid # self.start = start # self.end = end # self.candidates = candidates # # def __unicode__(self): # return u'{}\t{}\t{}\t{}'.format( # self.docid, # self.start, # self.end, # u'\t'.join([unicode(c) for c in self.candidates]) # ) # # __str__ = __unicode__ # # def __repr__(self): # return 'Annotation({!r}, {!r}, {!r}, {!r})'.format(self.docid, self.start, self.end, self.candidates) # # def __lt__(self, other): # assert isinstance(other, Annotation) # return (self.start, -self.end) < (other.start, -other.end) # # def compare_spans(self, other): # assert self.start <= self.end, 'End is before start: {!r}'.format(self) # assert other.start <= other.end, 'End is before start: {!r}'.format(self) # if self.docid != other.docid: # return 'different documents' # if self.start > other.end or self.end < other.start: # return 'non-overlapping' # elif self.start == other.start and self.end == other.end: # return 'duplicate' # elif self.start < other.start and self.end >= other.end: # return 'nested' # elif self.start >= other.start and self.end < other.end: # return 'nested' # else: # return 'crossing' # # # Getters # @property # def span(self): # return (self.docid, self.start, self.end) # # @property # def link(self): # "Return top candidate" # if self.candidates: # return self.candidates[0] # # def __getattr__(self, name): # # Generally, return attributes from top candidate # # or None if there are no candidates # if name.startswith('_'): # # AttributeError # super(Annotation, self).__getattr__(name) # link = self.link # if link is not None: # return getattr(link, name) # # # Parsing methods # @classmethod # def from_string(cls, s): # docid, start, end, candidates = None, None, None, [] # cols = s.rstrip('\n\t').split('\t', 3) # if len(cols) < 3: # raise SyntaxError('Annotation must have at least 3 columns. Got {!r}'.format(s)) # if len(cols) >= 3: # docid = cols[0] # start = int(cols[1]) # end = int(cols[2]) # if len(cols) == 4: # candidates = sorted(Candidate.from_string(cols[3]), reverse=True) # return Annotation(docid, start, end, candidates) # # @classmethod # def list_fields(cls): # ann = cls.from_string('a\t0\t1\tabc') # return [f for f in dir(ann) + dir(ann.link) # if not f.startswith('_') # and not callable(getattr(ann, f, None))] # # Path: neleval/document.py # ENC = 'utf8' # # Path: neleval/utils.py # WIKI_PREFIX = re.compile('^http://[^.]+.wikipedia.org/wiki/') # def normalise_link(l): # def utf8_open(path, mode='r'): # def json_dumps(obj, sort_keys=True, indent=4): # def default(o): , which may contain function names, class names, or code. Output only the next line.
a = Annotation.from_string(line.rstrip('\n').decode(ENC))
Given the code snippet: <|code_start|>#!/usr/bin/env python class ToWeak(object): """Convert annotations to char-level for weak evaluation A better approach is to use measures with partial overlap support. """ def __init__(self, fname): self.fname = fname def __call__(self): <|code_end|> , generate the next line using the imports in this file: from .annotation import Annotation from .document import ENC from .utils import unicode and context (functions, classes, or occasionally code) from other files: # Path: neleval/annotation.py # class Annotation(object): # """A name mention and its predicted candidates # # Parameters # ---------- # # Attributes # ---------- # TODO # is_first : bool or unset # Indicates if this annotation is the first in the document for this # eid. # # * : # Other attributes are automatically adopted from the top candidate # """ # # __slots__ = ['docid', 'start', 'end', 'candidates', 'is_first'] # # def __init__(self, docid, start, end, candidates=[]): # self.docid = docid # self.start = start # self.end = end # self.candidates = candidates # # def __unicode__(self): # return u'{}\t{}\t{}\t{}'.format( # self.docid, # self.start, # self.end, # u'\t'.join([unicode(c) for c in self.candidates]) # ) # # __str__ = __unicode__ # # def __repr__(self): # return 'Annotation({!r}, {!r}, {!r}, {!r})'.format(self.docid, self.start, self.end, self.candidates) # # def __lt__(self, other): # assert isinstance(other, Annotation) # return (self.start, -self.end) < (other.start, -other.end) # # def compare_spans(self, other): # assert self.start <= self.end, 'End is before start: {!r}'.format(self) # assert other.start <= other.end, 'End is before start: {!r}'.format(self) # if self.docid != other.docid: # return 'different documents' # if self.start > other.end or self.end < other.start: # return 'non-overlapping' # elif self.start == other.start and self.end == other.end: # return 'duplicate' # elif self.start < other.start and self.end >= other.end: # return 'nested' # elif self.start >= other.start and self.end < other.end: # return 'nested' # else: # return 'crossing' # # # Getters # @property # def span(self): # return (self.docid, self.start, self.end) # # @property # def link(self): # "Return top candidate" # if self.candidates: # return self.candidates[0] # # def __getattr__(self, name): # # Generally, return attributes from top candidate # # or None if there are no candidates # if name.startswith('_'): # # AttributeError # super(Annotation, self).__getattr__(name) # link = self.link # if link is not None: # return getattr(link, name) # # # Parsing methods # @classmethod # def from_string(cls, s): # docid, start, end, candidates = None, None, None, [] # cols = s.rstrip('\n\t').split('\t', 3) # if len(cols) < 3: # raise SyntaxError('Annotation must have at least 3 columns. Got {!r}'.format(s)) # if len(cols) >= 3: # docid = cols[0] # start = int(cols[1]) # end = int(cols[2]) # if len(cols) == 4: # candidates = sorted(Candidate.from_string(cols[3]), reverse=True) # return Annotation(docid, start, end, candidates) # # @classmethod # def list_fields(cls): # ann = cls.from_string('a\t0\t1\tabc') # return [f for f in dir(ann) + dir(ann.link) # if not f.startswith('_') # and not callable(getattr(ann, f, None))] # # Path: neleval/document.py # ENC = 'utf8' # # Path: neleval/utils.py # WIKI_PREFIX = re.compile('^http://[^.]+.wikipedia.org/wiki/') # def normalise_link(l): # def utf8_open(path, mode='r'): # def json_dumps(obj, sort_keys=True, indent=4): # def default(o): . Output only the next line.
return u'\n'.join(unicode(a) for a in self.annotations()).encode(ENC)
Here is a snippet: <|code_start|>#!/usr/bin/env python class ToWeak(object): """Convert annotations to char-level for weak evaluation A better approach is to use measures with partial overlap support. """ def __init__(self, fname): self.fname = fname def __call__(self): <|code_end|> . Write the next line using the current file imports: from .annotation import Annotation from .document import ENC from .utils import unicode and context from other files: # Path: neleval/annotation.py # class Annotation(object): # """A name mention and its predicted candidates # # Parameters # ---------- # # Attributes # ---------- # TODO # is_first : bool or unset # Indicates if this annotation is the first in the document for this # eid. # # * : # Other attributes are automatically adopted from the top candidate # """ # # __slots__ = ['docid', 'start', 'end', 'candidates', 'is_first'] # # def __init__(self, docid, start, end, candidates=[]): # self.docid = docid # self.start = start # self.end = end # self.candidates = candidates # # def __unicode__(self): # return u'{}\t{}\t{}\t{}'.format( # self.docid, # self.start, # self.end, # u'\t'.join([unicode(c) for c in self.candidates]) # ) # # __str__ = __unicode__ # # def __repr__(self): # return 'Annotation({!r}, {!r}, {!r}, {!r})'.format(self.docid, self.start, self.end, self.candidates) # # def __lt__(self, other): # assert isinstance(other, Annotation) # return (self.start, -self.end) < (other.start, -other.end) # # def compare_spans(self, other): # assert self.start <= self.end, 'End is before start: {!r}'.format(self) # assert other.start <= other.end, 'End is before start: {!r}'.format(self) # if self.docid != other.docid: # return 'different documents' # if self.start > other.end or self.end < other.start: # return 'non-overlapping' # elif self.start == other.start and self.end == other.end: # return 'duplicate' # elif self.start < other.start and self.end >= other.end: # return 'nested' # elif self.start >= other.start and self.end < other.end: # return 'nested' # else: # return 'crossing' # # # Getters # @property # def span(self): # return (self.docid, self.start, self.end) # # @property # def link(self): # "Return top candidate" # if self.candidates: # return self.candidates[0] # # def __getattr__(self, name): # # Generally, return attributes from top candidate # # or None if there are no candidates # if name.startswith('_'): # # AttributeError # super(Annotation, self).__getattr__(name) # link = self.link # if link is not None: # return getattr(link, name) # # # Parsing methods # @classmethod # def from_string(cls, s): # docid, start, end, candidates = None, None, None, [] # cols = s.rstrip('\n\t').split('\t', 3) # if len(cols) < 3: # raise SyntaxError('Annotation must have at least 3 columns. Got {!r}'.format(s)) # if len(cols) >= 3: # docid = cols[0] # start = int(cols[1]) # end = int(cols[2]) # if len(cols) == 4: # candidates = sorted(Candidate.from_string(cols[3]), reverse=True) # return Annotation(docid, start, end, candidates) # # @classmethod # def list_fields(cls): # ann = cls.from_string('a\t0\t1\tabc') # return [f for f in dir(ann) + dir(ann.link) # if not f.startswith('_') # and not callable(getattr(ann, f, None))] # # Path: neleval/document.py # ENC = 'utf8' # # Path: neleval/utils.py # WIKI_PREFIX = re.compile('^http://[^.]+.wikipedia.org/wiki/') # def normalise_link(l): # def utf8_open(path, mode='r'): # def json_dumps(obj, sort_keys=True, indent=4): # def default(o): , which may include functions, classes, or code. Output only the next line.
return u'\n'.join(unicode(a) for a in self.annotations()).encode(ENC)
Next line prediction: <|code_start|> def by_mention(annotations): return [("{}//{}..{}".format(a.docid, a.start, a.end), [a]) for a in annotations] # Reading annotations class Reader(object): "Read annotations, grouped into documents" def __init__(self, fh, group=by_document, cls=Document): self.fh = fh self.group = group self.cls = cls def __iter__(self): return self.read() def read(self): try: for groupid, annots in self.group(self.annotations()): yield self.cls(groupid, annots) except Exception: print('ERROR while processing', self.fh, file=sys.stderr) raise def annotations(self): "Yield Annotation objects" for line in self.fh: <|code_end|> . Use current file imports: (from collections import OrderedDict from .annotation import Annotation from .utils import unicode import warnings import sys import argparse) and context including class names, function names, or small code snippets from other files: # Path: neleval/annotation.py # class Annotation(object): # """A name mention and its predicted candidates # # Parameters # ---------- # # Attributes # ---------- # TODO # is_first : bool or unset # Indicates if this annotation is the first in the document for this # eid. # # * : # Other attributes are automatically adopted from the top candidate # """ # # __slots__ = ['docid', 'start', 'end', 'candidates', 'is_first'] # # def __init__(self, docid, start, end, candidates=[]): # self.docid = docid # self.start = start # self.end = end # self.candidates = candidates # # def __unicode__(self): # return u'{}\t{}\t{}\t{}'.format( # self.docid, # self.start, # self.end, # u'\t'.join([unicode(c) for c in self.candidates]) # ) # # __str__ = __unicode__ # # def __repr__(self): # return 'Annotation({!r}, {!r}, {!r}, {!r})'.format(self.docid, self.start, self.end, self.candidates) # # def __lt__(self, other): # assert isinstance(other, Annotation) # return (self.start, -self.end) < (other.start, -other.end) # # def compare_spans(self, other): # assert self.start <= self.end, 'End is before start: {!r}'.format(self) # assert other.start <= other.end, 'End is before start: {!r}'.format(self) # if self.docid != other.docid: # return 'different documents' # if self.start > other.end or self.end < other.start: # return 'non-overlapping' # elif self.start == other.start and self.end == other.end: # return 'duplicate' # elif self.start < other.start and self.end >= other.end: # return 'nested' # elif self.start >= other.start and self.end < other.end: # return 'nested' # else: # return 'crossing' # # # Getters # @property # def span(self): # return (self.docid, self.start, self.end) # # @property # def link(self): # "Return top candidate" # if self.candidates: # return self.candidates[0] # # def __getattr__(self, name): # # Generally, return attributes from top candidate # # or None if there are no candidates # if name.startswith('_'): # # AttributeError # super(Annotation, self).__getattr__(name) # link = self.link # if link is not None: # return getattr(link, name) # # # Parsing methods # @classmethod # def from_string(cls, s): # docid, start, end, candidates = None, None, None, [] # cols = s.rstrip('\n\t').split('\t', 3) # if len(cols) < 3: # raise SyntaxError('Annotation must have at least 3 columns. Got {!r}'.format(s)) # if len(cols) >= 3: # docid = cols[0] # start = int(cols[1]) # end = int(cols[2]) # if len(cols) == 4: # candidates = sorted(Candidate.from_string(cols[3]), reverse=True) # return Annotation(docid, start, end, candidates) # # @classmethod # def list_fields(cls): # ann = cls.from_string('a\t0\t1\tabc') # return [f for f in dir(ann) + dir(ann.link) # if not f.startswith('_') # and not callable(getattr(ann, f, None))] # # Path: neleval/utils.py # WIKI_PREFIX = re.compile('^http://[^.]+.wikipedia.org/wiki/') # def normalise_link(l): # def utf8_open(path, mode='r'): # def json_dumps(obj, sort_keys=True, indent=4): # def default(o): . Output only the next line.
yield Annotation.from_string(line.rstrip('\n'))
Given the code snippet: <|code_start|> VALIDATION = { 'nested': 'ignore', 'crossing': 'ignore', 'duplicate': 'ignore', } def _validate(self, _categories=['nested', 'crossing', 'duplicate']): # XXX: do we nee to ensure start > end for all Annotations first? issues = {cat: [] for cat, val in self.VALIDATION.items() if val != 'ignore'} if not issues: return open_anns = [] tags = sorted([(a.start, 'open', a) for a in self.annotations] + [(a.end + 1, 'close', a) for a in self.annotations]) # use stop, not end for key, op, ann in tags: if op == 'open': open_anns.append(ann) else: open_anns.remove(ann) for other in open_anns: comparison = ann.compare_spans(other) if comparison in issues: issues[comparison].append((other, ann)) for issue, instances in issues.items(): if not instances: continue if self.VALIDATION[issue] == 'error': b, a = instances[0] raise ValueError(u'Found annotations with {} span:\n{}\n{}' <|code_end|> , generate the next line using the imports in this file: from collections import OrderedDict from .annotation import Annotation from .utils import unicode import warnings import sys import argparse and context (functions, classes, or occasionally code) from other files: # Path: neleval/annotation.py # class Annotation(object): # """A name mention and its predicted candidates # # Parameters # ---------- # # Attributes # ---------- # TODO # is_first : bool or unset # Indicates if this annotation is the first in the document for this # eid. # # * : # Other attributes are automatically adopted from the top candidate # """ # # __slots__ = ['docid', 'start', 'end', 'candidates', 'is_first'] # # def __init__(self, docid, start, end, candidates=[]): # self.docid = docid # self.start = start # self.end = end # self.candidates = candidates # # def __unicode__(self): # return u'{}\t{}\t{}\t{}'.format( # self.docid, # self.start, # self.end, # u'\t'.join([unicode(c) for c in self.candidates]) # ) # # __str__ = __unicode__ # # def __repr__(self): # return 'Annotation({!r}, {!r}, {!r}, {!r})'.format(self.docid, self.start, self.end, self.candidates) # # def __lt__(self, other): # assert isinstance(other, Annotation) # return (self.start, -self.end) < (other.start, -other.end) # # def compare_spans(self, other): # assert self.start <= self.end, 'End is before start: {!r}'.format(self) # assert other.start <= other.end, 'End is before start: {!r}'.format(self) # if self.docid != other.docid: # return 'different documents' # if self.start > other.end or self.end < other.start: # return 'non-overlapping' # elif self.start == other.start and self.end == other.end: # return 'duplicate' # elif self.start < other.start and self.end >= other.end: # return 'nested' # elif self.start >= other.start and self.end < other.end: # return 'nested' # else: # return 'crossing' # # # Getters # @property # def span(self): # return (self.docid, self.start, self.end) # # @property # def link(self): # "Return top candidate" # if self.candidates: # return self.candidates[0] # # def __getattr__(self, name): # # Generally, return attributes from top candidate # # or None if there are no candidates # if name.startswith('_'): # # AttributeError # super(Annotation, self).__getattr__(name) # link = self.link # if link is not None: # return getattr(link, name) # # # Parsing methods # @classmethod # def from_string(cls, s): # docid, start, end, candidates = None, None, None, [] # cols = s.rstrip('\n\t').split('\t', 3) # if len(cols) < 3: # raise SyntaxError('Annotation must have at least 3 columns. Got {!r}'.format(s)) # if len(cols) >= 3: # docid = cols[0] # start = int(cols[1]) # end = int(cols[2]) # if len(cols) == 4: # candidates = sorted(Candidate.from_string(cols[3]), reverse=True) # return Annotation(docid, start, end, candidates) # # @classmethod # def list_fields(cls): # ann = cls.from_string('a\t0\t1\tabc') # return [f for f in dir(ann) + dir(ann.link) # if not f.startswith('_') # and not callable(getattr(ann, f, None))] # # Path: neleval/utils.py # WIKI_PREFIX = re.compile('^http://[^.]+.wikipedia.org/wiki/') # def normalise_link(l): # def utf8_open(path, mode='r'): # def json_dumps(obj, sort_keys=True, indent=4): # def default(o): . Output only the next line.
.format(issue, unicode(a), unicode(b)))
Here is a snippet: <|code_start|> """Handle KB ambiguity in the gold standard by modifying it to match system The following back-off strategy applies for each span with gold standard ambiguity: * attempt to match it to the top candidate for that span * attempt to match it to the top candidate for any span in that document * attempt to match it to the top candidate for any span in the collection * default to select the first listed candidate The altered gold standard will be output. """ def __init__(self, system, gold, fields='eid'): self.system = system self.gold = gold self.fields = fields.split(',') if fields != '*' else '*' def _get_key(self, candidate): if self.fields == '*': # avoid comparing on score return (candidate.eid, candidate.__dict__) return tuple(getattr(candidate, field, None) for field in self.fields) def __call__(self): system = self.system if not isinstance(system, list): <|code_end|> . Write the next line using the current file imports: from collections import defaultdict from .document import Reader from .utils import utf8_open import json and context from other files: # Path: neleval/document.py # class Reader(object): # "Read annotations, grouped into documents" # def __init__(self, fh, group=by_document, cls=Document): # self.fh = fh # self.group = group # self.cls = cls # # def __iter__(self): # return self.read() # # def read(self): # try: # for groupid, annots in self.group(self.annotations()): # yield self.cls(groupid, annots) # except Exception: # print('ERROR while processing', self.fh, file=sys.stderr) # raise # # def annotations(self): # "Yield Annotation objects" # for line in self.fh: # yield Annotation.from_string(line.rstrip('\n')) # # Path: neleval/utils.py # def utf8_open(path, mode='r'): # return open(path, mode, encoding='utf8') , which may include functions, classes, or code. Output only the next line.
system = Reader(utf8_open(system))
Given the code snippet: <|code_start|> """Handle KB ambiguity in the gold standard by modifying it to match system The following back-off strategy applies for each span with gold standard ambiguity: * attempt to match it to the top candidate for that span * attempt to match it to the top candidate for any span in that document * attempt to match it to the top candidate for any span in the collection * default to select the first listed candidate The altered gold standard will be output. """ def __init__(self, system, gold, fields='eid'): self.system = system self.gold = gold self.fields = fields.split(',') if fields != '*' else '*' def _get_key(self, candidate): if self.fields == '*': # avoid comparing on score return (candidate.eid, candidate.__dict__) return tuple(getattr(candidate, field, None) for field in self.fields) def __call__(self): system = self.system if not isinstance(system, list): <|code_end|> , generate the next line using the imports in this file: from collections import defaultdict from .document import Reader from .utils import utf8_open import json and context (functions, classes, or occasionally code) from other files: # Path: neleval/document.py # class Reader(object): # "Read annotations, grouped into documents" # def __init__(self, fh, group=by_document, cls=Document): # self.fh = fh # self.group = group # self.cls = cls # # def __iter__(self): # return self.read() # # def read(self): # try: # for groupid, annots in self.group(self.annotations()): # yield self.cls(groupid, annots) # except Exception: # print('ERROR while processing', self.fh, file=sys.stderr) # raise # # def annotations(self): # "Yield Annotation objects" # for line in self.fh: # yield Annotation.from_string(line.rstrip('\n')) # # Path: neleval/utils.py # def utf8_open(path, mode='r'): # return open(path, mode, encoding='utf8') . Output only the next line.
system = Reader(utf8_open(system))
Here is a snippet: <|code_start|> return 'correct link' if self.gold is None: return 'nil-as-link' if self.system is None: return 'link-as-nil' return 'wrong-link' @staticmethod def _str(val, pre): if val is MISSING: return u'' elif val is None: return u'{}NIL'.format(pre) return u'{}"{}"'.format(pre, val) @property def _system_str(self): return self._str(self.system, 's') @property def _gold_str(self): return self._str(self.gold, 'g') def __str__(self): return u'{0.label}\t{0.doc_id}\t{0._gold_str}\t{0._system_str}'.format(self) class Analyze(object): """Analyze errors""" def __init__(self, system, gold=None, unique=False, summary=False, with_correct=False): <|code_end|> . Write the next line using the current file imports: from collections import Counter from collections import namedtuple from .document import Reader from .evaluate import get_measure, Evaluate from .utils import utf8_open, unicode and context from other files: # Path: neleval/document.py # class Reader(object): # "Read annotations, grouped into documents" # def __init__(self, fh, group=by_document, cls=Document): # self.fh = fh # self.group = group # self.cls = cls # # def __iter__(self): # return self.read() # # def read(self): # try: # for groupid, annots in self.group(self.annotations()): # yield self.cls(groupid, annots) # except Exception: # print('ERROR while processing', self.fh, file=sys.stderr) # raise # # def annotations(self): # "Yield Annotation objects" # for line in self.fh: # yield Annotation.from_string(line.rstrip('\n')) # # Path: neleval/evaluate.py # class StrictMetricWarning(Warning): # class Evaluate(object): # class Matrix(object): # METRICS = [ # 'ptp', # 'fp', # 'rtp', # 'fn', # 'precision', # 'recall', # 'fscore', # ] # FMTS = { # 'tab': tab_format, # 'json': json_format, # 'none': no_format, # } # def __init__(self, system, gold=None, # measures=DEFAULT_MEASURE_SET, # fmt='none', group_by=None, overall=False, # type_weights=None): # def iter_pairs(self, system, gold): # def __call__(self, measures=None): # def add_arguments(cls, p): # def count_all(cls, doc_pairs, measures, weighting=None): # def count(cls, measure, doc_pairs, weighting=None): # def tab_format(self, results, num_fmt='{:.3f}', delimiter='\t'): # def _header(delimiter='\t'): # def row(self, results, measure_str, num_fmt): # def read_tab_format(cls, file): # def json_format(self, results): # def no_format(self, results): # def __init__(self, ptp=0, fp=0, rtp=0, fn=0): # def __str__(self): # def __add__(self, other): # def __iadd__(self, other): # def results(self): # def precision(self): # def recall(self): # def div(self, n, d): # def fscore(self): # def macro_average(results_iter): # # Path: neleval/utils.py # WIKI_PREFIX = re.compile('^http://[^.]+.wikipedia.org/wiki/') # def normalise_link(l): # def utf8_open(path, mode='r'): # def json_dumps(obj, sort_keys=True, indent=4): # def default(o): , which may include functions, classes, or code. Output only the next line.
self.system = list(Reader(utf8_open(system)))
Next line prediction: <|code_start|> return 'wrong-link' @staticmethod def _str(val, pre): if val is MISSING: return u'' elif val is None: return u'{}NIL'.format(pre) return u'{}"{}"'.format(pre, val) @property def _system_str(self): return self._str(self.system, 's') @property def _gold_str(self): return self._str(self.gold, 'g') def __str__(self): return u'{0.label}\t{0.doc_id}\t{0._gold_str}\t{0._system_str}'.format(self) class Analyze(object): """Analyze errors""" def __init__(self, system, gold=None, unique=False, summary=False, with_correct=False): self.system = list(Reader(utf8_open(system))) self.gold = list(Reader(utf8_open(gold))) self.unique = unique self.summary = summary self.with_correct = with_correct <|code_end|> . Use current file imports: (from collections import Counter from collections import namedtuple from .document import Reader from .evaluate import get_measure, Evaluate from .utils import utf8_open, unicode) and context including class names, function names, or small code snippets from other files: # Path: neleval/document.py # class Reader(object): # "Read annotations, grouped into documents" # def __init__(self, fh, group=by_document, cls=Document): # self.fh = fh # self.group = group # self.cls = cls # # def __iter__(self): # return self.read() # # def read(self): # try: # for groupid, annots in self.group(self.annotations()): # yield self.cls(groupid, annots) # except Exception: # print('ERROR while processing', self.fh, file=sys.stderr) # raise # # def annotations(self): # "Yield Annotation objects" # for line in self.fh: # yield Annotation.from_string(line.rstrip('\n')) # # Path: neleval/evaluate.py # class StrictMetricWarning(Warning): # class Evaluate(object): # class Matrix(object): # METRICS = [ # 'ptp', # 'fp', # 'rtp', # 'fn', # 'precision', # 'recall', # 'fscore', # ] # FMTS = { # 'tab': tab_format, # 'json': json_format, # 'none': no_format, # } # def __init__(self, system, gold=None, # measures=DEFAULT_MEASURE_SET, # fmt='none', group_by=None, overall=False, # type_weights=None): # def iter_pairs(self, system, gold): # def __call__(self, measures=None): # def add_arguments(cls, p): # def count_all(cls, doc_pairs, measures, weighting=None): # def count(cls, measure, doc_pairs, weighting=None): # def tab_format(self, results, num_fmt='{:.3f}', delimiter='\t'): # def _header(delimiter='\t'): # def row(self, results, measure_str, num_fmt): # def read_tab_format(cls, file): # def json_format(self, results): # def no_format(self, results): # def __init__(self, ptp=0, fp=0, rtp=0, fn=0): # def __str__(self): # def __add__(self, other): # def __iadd__(self, other): # def results(self): # def precision(self): # def recall(self): # def div(self, n, d): # def fscore(self): # def macro_average(results_iter): # # Path: neleval/utils.py # WIKI_PREFIX = re.compile('^http://[^.]+.wikipedia.org/wiki/') # def normalise_link(l): # def utf8_open(path, mode='r'): # def json_dumps(obj, sort_keys=True, indent=4): # def default(o): . Output only the next line.
self.measure = get_measure('strong_mention_match')
Next line prediction: <|code_start|>class Analyze(object): """Analyze errors""" def __init__(self, system, gold=None, unique=False, summary=False, with_correct=False): self.system = list(Reader(utf8_open(system))) self.gold = list(Reader(utf8_open(gold))) self.unique = unique self.summary = summary self.with_correct = with_correct self.measure = get_measure('strong_mention_match') def __call__(self): if self.unique: def _data(): seen = set() for entry in self.iter_errors(): if entry in seen: continue seen.add(entry) yield entry else: _data = self.iter_errors if self.summary: counts = Counter(error.label for error in _data()) return '\n'.join('{1}\t{0}'.format(*tup) for tup in counts.most_common()) else: return u'\n'.join(unicode(error) for error in _data()) def iter_errors(self): <|code_end|> . Use current file imports: (from collections import Counter from collections import namedtuple from .document import Reader from .evaluate import get_measure, Evaluate from .utils import utf8_open, unicode) and context including class names, function names, or small code snippets from other files: # Path: neleval/document.py # class Reader(object): # "Read annotations, grouped into documents" # def __init__(self, fh, group=by_document, cls=Document): # self.fh = fh # self.group = group # self.cls = cls # # def __iter__(self): # return self.read() # # def read(self): # try: # for groupid, annots in self.group(self.annotations()): # yield self.cls(groupid, annots) # except Exception: # print('ERROR while processing', self.fh, file=sys.stderr) # raise # # def annotations(self): # "Yield Annotation objects" # for line in self.fh: # yield Annotation.from_string(line.rstrip('\n')) # # Path: neleval/evaluate.py # class StrictMetricWarning(Warning): # class Evaluate(object): # class Matrix(object): # METRICS = [ # 'ptp', # 'fp', # 'rtp', # 'fn', # 'precision', # 'recall', # 'fscore', # ] # FMTS = { # 'tab': tab_format, # 'json': json_format, # 'none': no_format, # } # def __init__(self, system, gold=None, # measures=DEFAULT_MEASURE_SET, # fmt='none', group_by=None, overall=False, # type_weights=None): # def iter_pairs(self, system, gold): # def __call__(self, measures=None): # def add_arguments(cls, p): # def count_all(cls, doc_pairs, measures, weighting=None): # def count(cls, measure, doc_pairs, weighting=None): # def tab_format(self, results, num_fmt='{:.3f}', delimiter='\t'): # def _header(delimiter='\t'): # def row(self, results, measure_str, num_fmt): # def read_tab_format(cls, file): # def json_format(self, results): # def no_format(self, results): # def __init__(self, ptp=0, fp=0, rtp=0, fn=0): # def __str__(self): # def __add__(self, other): # def __iadd__(self, other): # def results(self): # def precision(self): # def recall(self): # def div(self, n, d): # def fscore(self): # def macro_average(results_iter): # # Path: neleval/utils.py # WIKI_PREFIX = re.compile('^http://[^.]+.wikipedia.org/wiki/') # def normalise_link(l): # def utf8_open(path, mode='r'): # def json_dumps(obj, sort_keys=True, indent=4): # def default(o): . Output only the next line.
for s, g in Evaluate.iter_pairs(self.system, self.gold):
Given the following code snippet before the placeholder: <|code_start|> return 'correct link' if self.gold is None: return 'nil-as-link' if self.system is None: return 'link-as-nil' return 'wrong-link' @staticmethod def _str(val, pre): if val is MISSING: return u'' elif val is None: return u'{}NIL'.format(pre) return u'{}"{}"'.format(pre, val) @property def _system_str(self): return self._str(self.system, 's') @property def _gold_str(self): return self._str(self.gold, 'g') def __str__(self): return u'{0.label}\t{0.doc_id}\t{0._gold_str}\t{0._system_str}'.format(self) class Analyze(object): """Analyze errors""" def __init__(self, system, gold=None, unique=False, summary=False, with_correct=False): <|code_end|> , predict the next line using imports from the current file: from collections import Counter from collections import namedtuple from .document import Reader from .evaluate import get_measure, Evaluate from .utils import utf8_open, unicode and context including class names, function names, and sometimes code from other files: # Path: neleval/document.py # class Reader(object): # "Read annotations, grouped into documents" # def __init__(self, fh, group=by_document, cls=Document): # self.fh = fh # self.group = group # self.cls = cls # # def __iter__(self): # return self.read() # # def read(self): # try: # for groupid, annots in self.group(self.annotations()): # yield self.cls(groupid, annots) # except Exception: # print('ERROR while processing', self.fh, file=sys.stderr) # raise # # def annotations(self): # "Yield Annotation objects" # for line in self.fh: # yield Annotation.from_string(line.rstrip('\n')) # # Path: neleval/evaluate.py # class StrictMetricWarning(Warning): # class Evaluate(object): # class Matrix(object): # METRICS = [ # 'ptp', # 'fp', # 'rtp', # 'fn', # 'precision', # 'recall', # 'fscore', # ] # FMTS = { # 'tab': tab_format, # 'json': json_format, # 'none': no_format, # } # def __init__(self, system, gold=None, # measures=DEFAULT_MEASURE_SET, # fmt='none', group_by=None, overall=False, # type_weights=None): # def iter_pairs(self, system, gold): # def __call__(self, measures=None): # def add_arguments(cls, p): # def count_all(cls, doc_pairs, measures, weighting=None): # def count(cls, measure, doc_pairs, weighting=None): # def tab_format(self, results, num_fmt='{:.3f}', delimiter='\t'): # def _header(delimiter='\t'): # def row(self, results, measure_str, num_fmt): # def read_tab_format(cls, file): # def json_format(self, results): # def no_format(self, results): # def __init__(self, ptp=0, fp=0, rtp=0, fn=0): # def __str__(self): # def __add__(self, other): # def __iadd__(self, other): # def results(self): # def precision(self): # def recall(self): # def div(self, n, d): # def fscore(self): # def macro_average(results_iter): # # Path: neleval/utils.py # WIKI_PREFIX = re.compile('^http://[^.]+.wikipedia.org/wiki/') # def normalise_link(l): # def utf8_open(path, mode='r'): # def json_dumps(obj, sort_keys=True, indent=4): # def default(o): . Output only the next line.
self.system = list(Reader(utf8_open(system)))
Using the snippet: <|code_start|> return u'{0.label}\t{0.doc_id}\t{0._gold_str}\t{0._system_str}'.format(self) class Analyze(object): """Analyze errors""" def __init__(self, system, gold=None, unique=False, summary=False, with_correct=False): self.system = list(Reader(utf8_open(system))) self.gold = list(Reader(utf8_open(gold))) self.unique = unique self.summary = summary self.with_correct = with_correct self.measure = get_measure('strong_mention_match') def __call__(self): if self.unique: def _data(): seen = set() for entry in self.iter_errors(): if entry in seen: continue seen.add(entry) yield entry else: _data = self.iter_errors if self.summary: counts = Counter(error.label for error in _data()) return '\n'.join('{1}\t{0}'.format(*tup) for tup in counts.most_common()) else: <|code_end|> , determine the next line of code. You have imports: from collections import Counter from collections import namedtuple from .document import Reader from .evaluate import get_measure, Evaluate from .utils import utf8_open, unicode and context (class names, function names, or code) available: # Path: neleval/document.py # class Reader(object): # "Read annotations, grouped into documents" # def __init__(self, fh, group=by_document, cls=Document): # self.fh = fh # self.group = group # self.cls = cls # # def __iter__(self): # return self.read() # # def read(self): # try: # for groupid, annots in self.group(self.annotations()): # yield self.cls(groupid, annots) # except Exception: # print('ERROR while processing', self.fh, file=sys.stderr) # raise # # def annotations(self): # "Yield Annotation objects" # for line in self.fh: # yield Annotation.from_string(line.rstrip('\n')) # # Path: neleval/evaluate.py # class StrictMetricWarning(Warning): # class Evaluate(object): # class Matrix(object): # METRICS = [ # 'ptp', # 'fp', # 'rtp', # 'fn', # 'precision', # 'recall', # 'fscore', # ] # FMTS = { # 'tab': tab_format, # 'json': json_format, # 'none': no_format, # } # def __init__(self, system, gold=None, # measures=DEFAULT_MEASURE_SET, # fmt='none', group_by=None, overall=False, # type_weights=None): # def iter_pairs(self, system, gold): # def __call__(self, measures=None): # def add_arguments(cls, p): # def count_all(cls, doc_pairs, measures, weighting=None): # def count(cls, measure, doc_pairs, weighting=None): # def tab_format(self, results, num_fmt='{:.3f}', delimiter='\t'): # def _header(delimiter='\t'): # def row(self, results, measure_str, num_fmt): # def read_tab_format(cls, file): # def json_format(self, results): # def no_format(self, results): # def __init__(self, ptp=0, fp=0, rtp=0, fn=0): # def __str__(self): # def __add__(self, other): # def __iadd__(self, other): # def results(self): # def precision(self): # def recall(self): # def div(self, n, d): # def fscore(self): # def macro_average(results_iter): # # Path: neleval/utils.py # WIKI_PREFIX = re.compile('^http://[^.]+.wikipedia.org/wiki/') # def normalise_link(l): # def utf8_open(path, mode='r'): # def json_dumps(obj, sort_keys=True, indent=4): # def default(o): . Output only the next line.
return u'\n'.join(unicode(error) for error in _data())
Using the snippet: <|code_start|> ('vp', ['vap', 'vapr', 'vap']), ('tas', ['tas']), ('ps', ['ps'])]) unit_names = array([['mj/m^2', 'mj/m2', 'mjm-2', 'mjm-2day-1', 'mjm-2d-1', 'mj/m^2/day', 'mj/m2/day'], ['oc', 'degc', 'degreesc', 'c'], ['oc', 'degc', 'degreesc', 'c'], ['mm', 'mm/day'], ['m/s', 'ms-1'], ['oc', 'degc', 'degreesc', 'c'], ['%'], ['kgkg-1', 'kg/kg'], ['mb'], ['oc', 'degc', 'c'], ['mb']]) unit_names2 = array(['MJ/m^2', 'oC', 'oC', 'mm', 'm/s', 'oC', '%', 'kgkg-1', 'mb', 'oC', 'mb']) var_keys = var_lists.keys() var_names = array(var_keys) nt = len(time) nv = len(var_names) alldata = empty((nv, ns, nt)) found_var = zeros(nv, dtype=bool) for i in range(nv): var_name = var_names[i] var_list = var_lists[var_name] for v in var_list: matchvar = isin(v, variables) if not matchvar: continue matchvar = matchvar[0] if matchvar not in vlist: continue alldata[i] = infile.variables[matchvar][:].squeeze() <|code_end|> , determine the next line of code. You have imports: import datetime import os import re import stat import traceback import warnings from netCDF4 import Dataset from collections import OrderedDict from numpy import empty, array, concatenate, savetxt, zeros, intersect1d, inf, ones, append, resize, \ VisibleDeprecationWarning from ..utils.co2 import CO2 from ..utils.fillgaps import fill from ..utils.dewpoint import dewpoint from .. import translator and context (class names, function names, or code) available: # Path: pysims/translators/utils/fillgaps.py # def fill(data, time, ref, varname): # var = masked_array(data) # # for i in range(len(data)): # isfill = var[i] > 1e10 # var[i] = masked_where(var[i] > 1e10, var[i]) # remove fill values # var[i] = var[i].astype(float) # convert to float # # if isfill.sum(): # # if 100. * isfill.sum() / var[i].size > 1.: # # raise Exception('More than one percent of values for variable %s are masked!' % varname) # if varname in ['RAIN', 'rain']: # var[i, isfill] = 0. # fill with zeros # else: # days = array([int((ref + timedelta(int(t))).strftime('%j')) for t in time]) # fdays = days[isfill] # varave = zeros(len(fdays)) # for j in range(len(fdays)): # ave = var[i, days == fdays[j]].mean() # varave[j] = ave if not is_masked(ave) else 1e20 # var[i, isfill] = varave # fill with daily average # # return var . Output only the next line.
alldata[i] = fill(alldata[i], time, ref, var_name)
Predict the next line for this snippet: <|code_start|> if name.startswith('_'): return object.__getattribute__(self, name) if name in self._shim_cache: return self._shim_cache[name] if self._should_shim(name): meth = self._shim(name) self._shim_cache[name] = meth return meth # local defined in shim class if name in self.__dict__: return object.__getattribute__(self, name) if hasattr(self._manager, name): return getattr(self._manager, name) return object.__getattribute__(self, name) def _should_shim(self, name): return name in API class ContentsNameApiShim(ShimManager): def _shim(self, name): current_api = getattr(ContentsManager, name) legacy = getattr(self._manager, name) def method(self, *args, **kwargs): args = list(args) # make mutable <|code_end|> with the help of current file imports: from notebook.services.contents.manager import ContentsManager from .util import get_invoked_arg, set_invoked_arg, _path_split and context from other files: # Path: nbx/nbmanager/util.py # def get_invoked_arg(func, name, args, kwargs): # var = None # if name in kwargs: # var = kwargs[name] # return var # # # handle functools.wraps functions. specifically the middleware # if hasattr(func, '__wrapped__'): # argspec = inspect.getargspec(func.__wrapped__) # else: # argspec = inspect.getargspec(func) # if name not in argspec.args: # raise Exception('{name} was not found in invoked function'.format(name=name)) # # index = argspec.args.index(name) # # we're assuming self is not in *args for method calls # if argspec.args[0] == 'self': # index -= 1 # var = args[index] # return var # # def set_invoked_arg(func, name, value, args, kwargs): # """ # Based on a target argspec, we try to place the param # value in the correct args/kwargs spot so that it works # in the target. # """ # if isinstance(args, tuple): # raise Exception("args must be a list") # # # handle functools.wraps functions. specifically the middleware # if hasattr(func, '__wrapped__'): # argspec = inspect.getargspec(func.__wrapped__) # else: # argspec = inspect.getargspec(func) # # # assume that if var is in kwargs, it should stay there. # # possible that source func had name in kwargs, but target has # # the name in args (positionally). not handling for now # if name in kwargs or name not in argspec.args: # kwargs[name] = value # return # # index = argspec.args.index(name) # num_args = len(argspec.args) # # we're assuming self is not in args for method calls # if argspec.args[0] == 'self': # index -= 1 # num_args -= 1 # # defaults_len = 0 # if argspec.defaults: # defaults_len = len(argspec.defaults) # # if len(args) == num_args: # args[index] = value # elif len(args) == index: # # args.append(value) # elif len(args) + defaults_len >= num_args: # args[index] = value # else: # args.insert(index, value) # # return args, kwargs # # def _path_split(path): # bits = path.rsplit('/', 1) # path = '' # name = bits.pop() # if bits: # path = bits[0] # return name, path , which may contain function names, class names, or code. Output only the next line.
old_path = path = get_invoked_arg(current_api, 'path', args, kwargs)
Given the following code snippet before the placeholder: <|code_start|> if name in self._shim_cache: return self._shim_cache[name] if self._should_shim(name): meth = self._shim(name) self._shim_cache[name] = meth return meth # local defined in shim class if name in self.__dict__: return object.__getattribute__(self, name) if hasattr(self._manager, name): return getattr(self._manager, name) return object.__getattribute__(self, name) def _should_shim(self, name): return name in API class ContentsNameApiShim(ShimManager): def _shim(self, name): current_api = getattr(ContentsManager, name) legacy = getattr(self._manager, name) def method(self, *args, **kwargs): args = list(args) # make mutable old_path = path = get_invoked_arg(current_api, 'path', args, kwargs) name, path = _path_split(path) <|code_end|> , predict the next line using imports from the current file: from notebook.services.contents.manager import ContentsManager from .util import get_invoked_arg, set_invoked_arg, _path_split and context including class names, function names, and sometimes code from other files: # Path: nbx/nbmanager/util.py # def get_invoked_arg(func, name, args, kwargs): # var = None # if name in kwargs: # var = kwargs[name] # return var # # # handle functools.wraps functions. specifically the middleware # if hasattr(func, '__wrapped__'): # argspec = inspect.getargspec(func.__wrapped__) # else: # argspec = inspect.getargspec(func) # if name not in argspec.args: # raise Exception('{name} was not found in invoked function'.format(name=name)) # # index = argspec.args.index(name) # # we're assuming self is not in *args for method calls # if argspec.args[0] == 'self': # index -= 1 # var = args[index] # return var # # def set_invoked_arg(func, name, value, args, kwargs): # """ # Based on a target argspec, we try to place the param # value in the correct args/kwargs spot so that it works # in the target. # """ # if isinstance(args, tuple): # raise Exception("args must be a list") # # # handle functools.wraps functions. specifically the middleware # if hasattr(func, '__wrapped__'): # argspec = inspect.getargspec(func.__wrapped__) # else: # argspec = inspect.getargspec(func) # # # assume that if var is in kwargs, it should stay there. # # possible that source func had name in kwargs, but target has # # the name in args (positionally). not handling for now # if name in kwargs or name not in argspec.args: # kwargs[name] = value # return # # index = argspec.args.index(name) # num_args = len(argspec.args) # # we're assuming self is not in args for method calls # if argspec.args[0] == 'self': # index -= 1 # num_args -= 1 # # defaults_len = 0 # if argspec.defaults: # defaults_len = len(argspec.defaults) # # if len(args) == num_args: # args[index] = value # elif len(args) == index: # # args.append(value) # elif len(args) + defaults_len >= num_args: # args[index] = value # else: # args.insert(index, value) # # return args, kwargs # # def _path_split(path): # bits = path.rsplit('/', 1) # path = '' # name = bits.pop() # if bits: # path = bits[0] # return name, path . Output only the next line.
set_invoked_arg(legacy, 'name', name, args, kwargs)
Predict the next line after this snippet: <|code_start|> return object.__getattribute__(self, name) if name in self._shim_cache: return self._shim_cache[name] if self._should_shim(name): meth = self._shim(name) self._shim_cache[name] = meth return meth # local defined in shim class if name in self.__dict__: return object.__getattribute__(self, name) if hasattr(self._manager, name): return getattr(self._manager, name) return object.__getattribute__(self, name) def _should_shim(self, name): return name in API class ContentsNameApiShim(ShimManager): def _shim(self, name): current_api = getattr(ContentsManager, name) legacy = getattr(self._manager, name) def method(self, *args, **kwargs): args = list(args) # make mutable old_path = path = get_invoked_arg(current_api, 'path', args, kwargs) <|code_end|> using the current file's imports: from notebook.services.contents.manager import ContentsManager from .util import get_invoked_arg, set_invoked_arg, _path_split and any relevant context from other files: # Path: nbx/nbmanager/util.py # def get_invoked_arg(func, name, args, kwargs): # var = None # if name in kwargs: # var = kwargs[name] # return var # # # handle functools.wraps functions. specifically the middleware # if hasattr(func, '__wrapped__'): # argspec = inspect.getargspec(func.__wrapped__) # else: # argspec = inspect.getargspec(func) # if name not in argspec.args: # raise Exception('{name} was not found in invoked function'.format(name=name)) # # index = argspec.args.index(name) # # we're assuming self is not in *args for method calls # if argspec.args[0] == 'self': # index -= 1 # var = args[index] # return var # # def set_invoked_arg(func, name, value, args, kwargs): # """ # Based on a target argspec, we try to place the param # value in the correct args/kwargs spot so that it works # in the target. # """ # if isinstance(args, tuple): # raise Exception("args must be a list") # # # handle functools.wraps functions. specifically the middleware # if hasattr(func, '__wrapped__'): # argspec = inspect.getargspec(func.__wrapped__) # else: # argspec = inspect.getargspec(func) # # # assume that if var is in kwargs, it should stay there. # # possible that source func had name in kwargs, but target has # # the name in args (positionally). not handling for now # if name in kwargs or name not in argspec.args: # kwargs[name] = value # return # # index = argspec.args.index(name) # num_args = len(argspec.args) # # we're assuming self is not in args for method calls # if argspec.args[0] == 'self': # index -= 1 # num_args -= 1 # # defaults_len = 0 # if argspec.defaults: # defaults_len = len(argspec.defaults) # # if len(args) == num_args: # args[index] = value # elif len(args) == index: # # args.append(value) # elif len(args) + defaults_len >= num_args: # args[index] = value # else: # args.insert(index, value) # # return args, kwargs # # def _path_split(path): # bits = path.rsplit('/', 1) # path = '' # name = bits.pop() # if bits: # path = bits[0] # return name, path . Output only the next line.
name, path = _path_split(path)
Predict the next line for this snippet: <|code_start|> def parse_tags(desc): # real tags and not system-like tags tags = _hashtags(desc) if '#notebook' in tags: tags.remove('#notebook') if '#inactive' in tags: tags.remove('#inactive') return tags class NotebookGist(object): """ A single notebook abstraction over Gist. Normally a gist can have mutliple files. A notebook gist pretends to be a single file. """ # instead of having a bunch of @property getters, define # attrs to grab from .gist here. _gist_attrs = ['id', 'files', 'active', 'edit', 'updated_at', 'created_at', 'public'] <|code_end|> with the help of current file imports: import github import nbformat import nbx.compat as compat from .gisthub import gisthub, _hashtags and context from other files: # Path: nbx/nbmanager/tagged_gist/gisthub.py # def gisthub(user, password): # g = github.Github(user, password, user_agent="nbx") # return GistHub(g) # # def _hashtags(desc): # if not desc: # return [] # tags = [tag for tag in desc.split(" ") if tag.startswith("#")] # return tags , which may contain function names, class names, or code. Output only the next line.
def __init__(self, gist, gisthub):
Here is a snippet: <|code_start|> path : unicode The URL path of the notebooks directory Returns ------- name : unicode A notebook name (with the .ipynb extension) that starts with basename and does not refer to any existing notebook. """ path = path.strip('/') for i in itertools.count(): name = u'{basename}{i}'.format(basename=basename, i=i) if not self.basename_exists(name, path): break return name def save_notebook(self, model, name='', path=''): """Save the notebook model and return the model with no content.""" path = path.strip('/') if 'content' not in model: raise web.HTTPError(400, u'No notebook JSON data provided') if not path: raise web.HTTPError(400, u'We require path for saving.') nb = nbformat.from_dict(model['content']) gist = self._get_gist(name, path) if gist is None: <|code_end|> . Write the next line using the current file imports: import itertools import nbformat from tornado import web from ..nbxmanager import NBXContentsManager from .notebook_gisthub import parse_tags and context from other files: # Path: nbx/nbmanager/nbxmanager.py # class NBXContentsManager(DispatcherMixin, ContentsManager): # def __init__(self, *args, **kwargs): # super(NBXContentsManager, self).__init__(*args, **kwargs) # # def is_dir(self, path): # raise NotImplementedError('must be implemented in a subclass') # # def is_notebook(self, path): # return path.endswith('.ipynb') # # def _base_model(self, path=''): # """Build the common base of a contents model""" # # Create the base model. # model = {} # model['name'] = path.rsplit('/', 1)[-1] # model['path'] = path # model['created'] = datetime.datetime.now() # model['last_modified'] = datetime.datetime.now() # model['content'] = None # model['format'] = None # model['writable'] = None # model['mimetype'] = None # return model # # def get(self, path='', content=True, **kwargs): # """ # backwards compat with get_model rename. fml. # Putting here instead of creating another mixin # """ # return super().get(path=path, content=content, **kwargs) # # # shims to bridge Content service and older notebook apis # def get_dir(self, path='', content=True, **kwargs): # """ # retrofit to use old list_dirs. No notebooks # note that this requires the dispatcher mixin # """ # model = self._base_model(path) # fullpath = path # # model['type'] = 'directory' # model['format'] = 'json' # dirs = self.list_dirs(fullpath) # notebooks = self.list_notebooks(fullpath) # # files = [] # if hasattr(self, 'list_files'): # files = self.list_files(fullpath) # # entries = list(dirs) + list(notebooks) + list(files) # model['content'] = entries # return model # # Path: nbx/nbmanager/tagged_gist/notebook_gisthub.py # def parse_tags(desc): # # real tags and not system-like tags # tags = _hashtags(desc) # if '#notebook' in tags: # tags.remove('#notebook') # if '#inactive' in tags: # tags.remove('#inactive') # return tags , which may include functions, classes, or code. Output only the next line.
tags = parse_tags(name)
Given the code snippet: <|code_start|> current = nbformat.v4 def is_notebook(path): # checks if path follows bundle format if not path.endswith('.ipynb'): return False # if that we have same named ipynb file in directory name = path.rsplit('/', 1)[-1] file_path = os.path.join(path, name) has_file = os.path.isfile(file_path) return has_file def _list_bundles(path): root, dirs, files = next(os.walk(path)) bundles = (os.path.join(root, d) for d in dirs) bundles = filter(lambda path: is_notebook(path), bundles) bundles = list(bundles) return bundles class BundleManager(object): <|code_end|> , generate the next line using the imports in this file: import os import io import shutil import nbformat from .bundle import NotebookBundle from nbformat import sign and context (functions, classes, or occasionally code) from other files: # Path: nbx/nbmanager/bundle/bundle.py # class NotebookBundle(Bundle): # # @property # def notebook_content(self): # filepath = os.path.join(self.path, self.name) # with io.open(filepath, 'r', encoding='utf-8') as f: # try: # nb = nbformat.read(f, as_version=4) # except Exception as e: # nb = None # return nb # # @property # def files(self): # files = super(NotebookBundle, self).files # assert self.name in files # files.remove(self.name) # assert self.name not in files # return files # # def get_model(self, content=True, file_content=True): # os_path = os.path.join(self.path, self.name) # info = os.stat(os_path) # last_modified = tz.utcfromtimestamp(info.st_mtime) # created = tz.utcfromtimestamp(info.st_ctime) # # Create the notebook model. # model = {} # model['name'] = self.name # model['path'] = self.path # model['last_modified'] = last_modified # model['created'] = created # model['type'] = 'notebook' # model['is_bundle'] = True # model['content'] = None # if content: # model['content'] = self.notebook_content # files = {} # for fn in self.files: # with open(os.path.join(self.path, fn), 'rb') as f: # data = None # if file_content: # try: # data = f.read().decode('utf-8') # except UnicodeDecodeError: # # TODO how to deal with binary data? # # right now we skip # continue # files[fn] = data # model['__files'] = files # return model . Output only the next line.
bundle_class = NotebookBundle
Predict the next line for this snippet: <|code_start|> class PathTranslateShim(ShimManager): """ Provide backwards compat to ipython removing name from its api calls This could be done with inspect and a metaclass """ def __init__(self, *args, **kwargs): self._shim_cache = {} self._manager = self.__shim_target__(*args, **kwargs) super().__init__(*args, **kwargs) def _should_shim(self, name): if name in ['get_notebook']: return True return False def _shim(self, name): legacy = getattr(self._manager, name) def method(self, *args, **kwargs): args = list(args) # make mutable <|code_end|> with the help of current file imports: from notebook.services.contents.manager import ContentsManager from .shim import ShimManager from .util import get_invoked_arg, set_invoked_arg, _path_split and context from other files: # Path: nbx/nbmanager/shim.py # class ShimManager(ContentsManager): # """ # Provide backwards compat to ipython removing name from its api calls # # This could be done with inspect and a metaclass # """ # _shim_cache = {} # _manager = None # # def __init__(self, *args, **kwargs): # self._shim_cache = {} # self._manager = self.__shim_target__(*args, **kwargs) # # def __getattribute__(self, name): # if name.startswith('_'): # return object.__getattribute__(self, name) # # if name in self._shim_cache: # return self._shim_cache[name] # # if self._should_shim(name): # meth = self._shim(name) # self._shim_cache[name] = meth # return meth # # # local defined in shim class # if name in self.__dict__: # return object.__getattribute__(self, name) # # if hasattr(self._manager, name): # return getattr(self._manager, name) # # return object.__getattribute__(self, name) # # def _should_shim(self, name): # return name in API # # Path: nbx/nbmanager/util.py # def get_invoked_arg(func, name, args, kwargs): # var = None # if name in kwargs: # var = kwargs[name] # return var # # # handle functools.wraps functions. specifically the middleware # if hasattr(func, '__wrapped__'): # argspec = inspect.getargspec(func.__wrapped__) # else: # argspec = inspect.getargspec(func) # if name not in argspec.args: # raise Exception('{name} was not found in invoked function'.format(name=name)) # # index = argspec.args.index(name) # # we're assuming self is not in *args for method calls # if argspec.args[0] == 'self': # index -= 1 # var = args[index] # return var # # def set_invoked_arg(func, name, value, args, kwargs): # """ # Based on a target argspec, we try to place the param # value in the correct args/kwargs spot so that it works # in the target. # """ # if isinstance(args, tuple): # raise Exception("args must be a list") # # # handle functools.wraps functions. specifically the middleware # if hasattr(func, '__wrapped__'): # argspec = inspect.getargspec(func.__wrapped__) # else: # argspec = inspect.getargspec(func) # # # assume that if var is in kwargs, it should stay there. # # possible that source func had name in kwargs, but target has # # the name in args (positionally). not handling for now # if name in kwargs or name not in argspec.args: # kwargs[name] = value # return # # index = argspec.args.index(name) # num_args = len(argspec.args) # # we're assuming self is not in args for method calls # if argspec.args[0] == 'self': # index -= 1 # num_args -= 1 # # defaults_len = 0 # if argspec.defaults: # defaults_len = len(argspec.defaults) # # if len(args) == num_args: # args[index] = value # elif len(args) == index: # # args.append(value) # elif len(args) + defaults_len >= num_args: # args[index] = value # else: # args.insert(index, value) # # return args, kwargs # # def _path_split(path): # bits = path.rsplit('/', 1) # path = '' # name = bits.pop() # if bits: # path = bits[0] # return name, path , which may contain function names, class names, or code. Output only the next line.
old_name = name = get_invoked_arg(legacy, 'name', args, kwargs)
Next line prediction: <|code_start|> class PathTranslateShim(ShimManager): """ Provide backwards compat to ipython removing name from its api calls This could be done with inspect and a metaclass """ def __init__(self, *args, **kwargs): self._shim_cache = {} self._manager = self.__shim_target__(*args, **kwargs) super().__init__(*args, **kwargs) def _should_shim(self, name): if name in ['get_notebook']: return True return False def _shim(self, name): legacy = getattr(self._manager, name) def method(self, *args, **kwargs): args = list(args) # make mutable old_name = name = get_invoked_arg(legacy, 'name', args, kwargs) name = self.translate_path(name) name, path = _path_split(name) <|code_end|> . Use current file imports: (from notebook.services.contents.manager import ContentsManager from .shim import ShimManager from .util import get_invoked_arg, set_invoked_arg, _path_split) and context including class names, function names, or small code snippets from other files: # Path: nbx/nbmanager/shim.py # class ShimManager(ContentsManager): # """ # Provide backwards compat to ipython removing name from its api calls # # This could be done with inspect and a metaclass # """ # _shim_cache = {} # _manager = None # # def __init__(self, *args, **kwargs): # self._shim_cache = {} # self._manager = self.__shim_target__(*args, **kwargs) # # def __getattribute__(self, name): # if name.startswith('_'): # return object.__getattribute__(self, name) # # if name in self._shim_cache: # return self._shim_cache[name] # # if self._should_shim(name): # meth = self._shim(name) # self._shim_cache[name] = meth # return meth # # # local defined in shim class # if name in self.__dict__: # return object.__getattribute__(self, name) # # if hasattr(self._manager, name): # return getattr(self._manager, name) # # return object.__getattribute__(self, name) # # def _should_shim(self, name): # return name in API # # Path: nbx/nbmanager/util.py # def get_invoked_arg(func, name, args, kwargs): # var = None # if name in kwargs: # var = kwargs[name] # return var # # # handle functools.wraps functions. specifically the middleware # if hasattr(func, '__wrapped__'): # argspec = inspect.getargspec(func.__wrapped__) # else: # argspec = inspect.getargspec(func) # if name not in argspec.args: # raise Exception('{name} was not found in invoked function'.format(name=name)) # # index = argspec.args.index(name) # # we're assuming self is not in *args for method calls # if argspec.args[0] == 'self': # index -= 1 # var = args[index] # return var # # def set_invoked_arg(func, name, value, args, kwargs): # """ # Based on a target argspec, we try to place the param # value in the correct args/kwargs spot so that it works # in the target. # """ # if isinstance(args, tuple): # raise Exception("args must be a list") # # # handle functools.wraps functions. specifically the middleware # if hasattr(func, '__wrapped__'): # argspec = inspect.getargspec(func.__wrapped__) # else: # argspec = inspect.getargspec(func) # # # assume that if var is in kwargs, it should stay there. # # possible that source func had name in kwargs, but target has # # the name in args (positionally). not handling for now # if name in kwargs or name not in argspec.args: # kwargs[name] = value # return # # index = argspec.args.index(name) # num_args = len(argspec.args) # # we're assuming self is not in args for method calls # if argspec.args[0] == 'self': # index -= 1 # num_args -= 1 # # defaults_len = 0 # if argspec.defaults: # defaults_len = len(argspec.defaults) # # if len(args) == num_args: # args[index] = value # elif len(args) == index: # # args.append(value) # elif len(args) + defaults_len >= num_args: # args[index] = value # else: # args.insert(index, value) # # return args, kwargs # # def _path_split(path): # bits = path.rsplit('/', 1) # path = '' # name = bits.pop() # if bits: # path = bits[0] # return name, path . Output only the next line.
set_invoked_arg(legacy, 'name', name, args, kwargs)
Next line prediction: <|code_start|> class PathTranslateShim(ShimManager): """ Provide backwards compat to ipython removing name from its api calls This could be done with inspect and a metaclass """ def __init__(self, *args, **kwargs): self._shim_cache = {} self._manager = self.__shim_target__(*args, **kwargs) super().__init__(*args, **kwargs) def _should_shim(self, name): if name in ['get_notebook']: return True return False def _shim(self, name): legacy = getattr(self._manager, name) def method(self, *args, **kwargs): args = list(args) # make mutable old_name = name = get_invoked_arg(legacy, 'name', args, kwargs) name = self.translate_path(name) <|code_end|> . Use current file imports: (from notebook.services.contents.manager import ContentsManager from .shim import ShimManager from .util import get_invoked_arg, set_invoked_arg, _path_split) and context including class names, function names, or small code snippets from other files: # Path: nbx/nbmanager/shim.py # class ShimManager(ContentsManager): # """ # Provide backwards compat to ipython removing name from its api calls # # This could be done with inspect and a metaclass # """ # _shim_cache = {} # _manager = None # # def __init__(self, *args, **kwargs): # self._shim_cache = {} # self._manager = self.__shim_target__(*args, **kwargs) # # def __getattribute__(self, name): # if name.startswith('_'): # return object.__getattribute__(self, name) # # if name in self._shim_cache: # return self._shim_cache[name] # # if self._should_shim(name): # meth = self._shim(name) # self._shim_cache[name] = meth # return meth # # # local defined in shim class # if name in self.__dict__: # return object.__getattribute__(self, name) # # if hasattr(self._manager, name): # return getattr(self._manager, name) # # return object.__getattribute__(self, name) # # def _should_shim(self, name): # return name in API # # Path: nbx/nbmanager/util.py # def get_invoked_arg(func, name, args, kwargs): # var = None # if name in kwargs: # var = kwargs[name] # return var # # # handle functools.wraps functions. specifically the middleware # if hasattr(func, '__wrapped__'): # argspec = inspect.getargspec(func.__wrapped__) # else: # argspec = inspect.getargspec(func) # if name not in argspec.args: # raise Exception('{name} was not found in invoked function'.format(name=name)) # # index = argspec.args.index(name) # # we're assuming self is not in *args for method calls # if argspec.args[0] == 'self': # index -= 1 # var = args[index] # return var # # def set_invoked_arg(func, name, value, args, kwargs): # """ # Based on a target argspec, we try to place the param # value in the correct args/kwargs spot so that it works # in the target. # """ # if isinstance(args, tuple): # raise Exception("args must be a list") # # # handle functools.wraps functions. specifically the middleware # if hasattr(func, '__wrapped__'): # argspec = inspect.getargspec(func.__wrapped__) # else: # argspec = inspect.getargspec(func) # # # assume that if var is in kwargs, it should stay there. # # possible that source func had name in kwargs, but target has # # the name in args (positionally). not handling for now # if name in kwargs or name not in argspec.args: # kwargs[name] = value # return # # index = argspec.args.index(name) # num_args = len(argspec.args) # # we're assuming self is not in args for method calls # if argspec.args[0] == 'self': # index -= 1 # num_args -= 1 # # defaults_len = 0 # if argspec.defaults: # defaults_len = len(argspec.defaults) # # if len(args) == num_args: # args[index] = value # elif len(args) == index: # # args.append(value) # elif len(args) + defaults_len >= num_args: # args[index] = value # else: # args.insert(index, value) # # return args, kwargs # # def _path_split(path): # bits = path.rsplit('/', 1) # path = '' # name = bits.pop() # if bits: # path = bits[0] # return name, path . Output only the next line.
name, path = _path_split(name)
Predict the next line for this snippet: <|code_start|> def _fullpath(name, path): fullpath = url_path_join(path, name) return fullpath def _path_split(path): bits = path.rsplit('/', 1) path = '' name = bits.pop() if bits: path = bits[0] return name, path <|code_end|> with the help of current file imports: import datetime import os.path from notebook.services.contents.manager import ContentsManager from notebook.utils import url_path_join from .dispatch import DispatcherMixin and context from other files: # Path: nbx/nbmanager/dispatch.py # class DispatcherMixin(object): # """ # This Mixin class handles the dispatching of Contents API calls to # model type specific methods. # # i.e. get_model for a directory would call get_model_dir # """ # # def save(self, model, path=''): # return save(self, model, path, # dispatcher=self.dispatch_method.__func__) # # def update(self, model, path=''): # return update(self, model, path, # dispatcher=self.dispatch_method.__func__) # # def delete(self, path=''): # return delete(self, path, # dispatcher=self.dispatch_method.__func__) # # def get(self, path='', content=True, **kwargs): # return get(self, path, content, # dispatcher=self.dispatch_method.__func__, **kwargs) # # def dispatch_method(self, hook, model_type, *args, **kwargs): # return dispatch_method(self, hook, model_type, *args, **kwargs) , which may contain function names, class names, or code. Output only the next line.
class NBXContentsManager(DispatcherMixin, ContentsManager):
Based on the snippet: <|code_start|>#!/usr/bin/env python # coding=utf8 """ In cases where you want to generate IDs automatically, decorators are available. These should be the outermost decorators, as they change the signature of some of the put methods slightly. >>> from simplekv.memory import DictStore >>> from simplekv.idgen import HashDecorator >>> >>> store = HashDecorator(DictStore()) >>> >>> key = store.put(None, b'my_data') # note the passing of 'None' as key >>> print(key) ab0c15b6029fdffce16b393f2d27ca839a76249e """ <|code_end|> , predict the immediate next line with the help of imports: import hashlib import os import tempfile import uuid from .decorator import StoreDecorator from ._compat import text_type and context (classes, functions, sometimes code) from other files: # Path: simplekv/decorator.py # class StoreDecorator(object): # """Base class for store decorators. # # The default implementation will use :func:`getattr` to pass through all # attribute/method requests to an underlying object stored as # :attr:`_dstore`. It will also pass through the :attr:`__getattr__` and # :attr:`__contains__` python special methods. # """ # # def __init__(self, store): # self._dstore = store # # def __getattr__(self, attr): # store = object.__getattribute__(self, "_dstore") # return getattr(store, attr) # # def __contains__(self, *args, **kwargs): # return self._dstore.__contains__(*args, **kwargs) # # def __iter__(self, *args, **kwargs): # return self._dstore.__iter__(*args, **kwargs) # # Path: simplekv/_compat.py # PY2 = sys.version_info[0] == 2 . Output only the next line.
class HashDecorator(StoreDecorator):
Predict the next line after this snippet: <|code_start|> except OSError as e: if 2 == e.errno: pass # file already gone else: raise return self._dstore.put_file(key, file, *args, **kwargs) class UUIDDecorator(StoreDecorator): """UUID generating decorator Overrides :meth:`.KeyValueStore.put` and :meth:`.KeyValueStore.put_file`. If a key of *None* is passed, a new UUID will be generated as the key. The attribute `uuidfunc` determines which UUID-function to use and defaults to 'uuid1'. .. note:: There seems to be a bug in the uuid module that prevents initializing `uuidfunc` too early. For that reason, it is a string that will be looked up using :func:`getattr` on the :mod:`uuid` module. """ # for strange reasons, this needs to be looked up as late as possible uuidfunc = 'uuid1' def __init__(self, store, template=u'{}'): super(UUIDDecorator, self).__init__(store) self._template = template def put(self, key, data, *args, **kwargs): if not key: <|code_end|> using the current file's imports: import hashlib import os import tempfile import uuid from .decorator import StoreDecorator from ._compat import text_type and any relevant context from other files: # Path: simplekv/decorator.py # class StoreDecorator(object): # """Base class for store decorators. # # The default implementation will use :func:`getattr` to pass through all # attribute/method requests to an underlying object stored as # :attr:`_dstore`. It will also pass through the :attr:`__getattr__` and # :attr:`__contains__` python special methods. # """ # # def __init__(self, store): # self._dstore = store # # def __getattr__(self, attr): # store = object.__getattribute__(self, "_dstore") # return getattr(store, attr) # # def __contains__(self, *args, **kwargs): # return self._dstore.__contains__(*args, **kwargs) # # def __iter__(self, *args, **kwargs): # return self._dstore.__iter__(*args, **kwargs) # # Path: simplekv/_compat.py # PY2 = sys.version_info[0] == 2 . Output only the next line.
key = text_type(getattr(uuid, self.uuidfunc)())
Next line prediction: <|code_start|> offset = len(self.buffer) - self.hm.digest_size rv, self.buffer = self.buffer[:offset], self.buffer[offset:] # update hmac self.hm.update(rv) if finished: # check hash if not self.buffer == self.hm.digest(): raise VerificationException('HMAC verification failed.') return rv def close(self): self.source.close() def __enter__(self): return self def __exit__(self, *args): self.close() class VerificationException(Exception): """This exception is thrown whenever there was an error with an authenticity check performed by any of the decorators in this module.""" pass <|code_end|> . Use current file imports: (import hashlib import hmac import os import tempfile from .decorator import StoreDecorator) and context including class names, function names, or small code snippets from other files: # Path: simplekv/decorator.py # class StoreDecorator(object): # """Base class for store decorators. # # The default implementation will use :func:`getattr` to pass through all # attribute/method requests to an underlying object stored as # :attr:`_dstore`. It will also pass through the :attr:`__getattr__` and # :attr:`__contains__` python special methods. # """ # # def __init__(self, store): # self._dstore = store # # def __getattr__(self, attr): # store = object.__getattribute__(self, "_dstore") # return getattr(store, attr) # # def __contains__(self, *args, **kwargs): # return self._dstore.__contains__(*args, **kwargs) # # def __iter__(self, *args, **kwargs): # return self._dstore.__iter__(*args, **kwargs) . Output only the next line.
class HMACDecorator(StoreDecorator):
Predict the next line after this snippet: <|code_start|>@contextmanager def boto3_bucket(access_key, secret_key, host, bucket_name=None, **kwargs): name = bucket_name or 'testrun-bucket-{}'.format(uuid()) s3_client = boto3.client('s3') s3_client.create_bucket(Bucket=name) s3_resource = boto3.resource('s3') bucket = s3_resource.Bucket(name) yield bucket for key in bucket.objects.all(): key.delete() bucket.delete() def load_boto_credentials(): # loaded from the same place tox.ini. here's a sample # # [my-s3] # access_key=foo # secret_key=bar # connect_func=connect_s3 # # [my-gs] # access_key=foo # secret_key=bar # connect_func=connect_gs cfg_fn = 'boto_credentials.ini' <|code_end|> using the current file's imports: from simplekv._compat import ConfigParser from contextlib import contextmanager from uuid import uuid4 as uuid from boto.s3.connection import OrdinaryCallingFormat import pytest import boto3 and any relevant context from other files: # Path: simplekv/_compat.py # PY2 = sys.version_info[0] == 2 . Output only the next line.
parser = ConfigParser({'host': 's3.amazonaws.com',
Next line prediction: <|code_start|> UUID_REGEXP = re.compile( r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' ) class IDGen(object): @pytest.fixture(params=[ u'constant', u'foo{}bar', u'{}.jpeg', u'prefix-{}.hello', u'justprefix{}', ]) def idgen_template(self, request): return request.param class UUIDGen(IDGen): @pytest.fixture def uuidstore(self, store): <|code_end|> . Use current file imports: (import os import re import tempfile import uuid import pytest from simplekv.idgen import UUIDDecorator, HashDecorator from simplekv._compat import text_type) and context including class names, function names, or small code snippets from other files: # Path: simplekv/idgen.py # class UUIDDecorator(StoreDecorator): # """UUID generating decorator # # Overrides :meth:`.KeyValueStore.put` and :meth:`.KeyValueStore.put_file`. # If a key of *None* is passed, a new UUID will be generated as the key. The # attribute `uuidfunc` determines which UUID-function to use and defaults to # 'uuid1'. # # .. note:: # There seems to be a bug in the uuid module that prevents initializing # `uuidfunc` too early. For that reason, it is a string that will be # looked up using :func:`getattr` on the :mod:`uuid` module. # """ # # for strange reasons, this needs to be looked up as late as possible # uuidfunc = 'uuid1' # # def __init__(self, store, template=u'{}'): # super(UUIDDecorator, self).__init__(store) # self._template = template # # def put(self, key, data, *args, **kwargs): # if not key: # key = text_type(getattr(uuid, self.uuidfunc)()) # # return self._dstore.put( # self._template.format(key), data, *args, **kwargs # ) # # def put_file(self, key, file, *args, **kwargs): # if not key: # key = text_type(getattr(uuid, self.uuidfunc)()) # # return self._dstore.put_file( # self._template.format(key), file, *args, **kwargs # ) # # class HashDecorator(StoreDecorator): # """Hash function decorator # # Overrides :meth:`.KeyValueStore.put` and :meth:`.KeyValueStore.put_file`. # If a key of *None* is passed, the data/file is hashed using # ``hashfunc``, which defaults to *hashlib.sha1*. """ # # def __init__(self, decorated_store, hashfunc=hashlib.sha1, template=u'{}'): # self.hashfunc = hashfunc # self._template = template # super(HashDecorator, self).__init__(decorated_store) # # def put(self, key, data, *args, **kwargs): # if not key: # key = self._template.format(self.hashfunc(data).hexdigest()) # # return self._dstore.put(key, data, *args, **kwargs) # # def put_file(self, key, file, *args, **kwargs): # bufsize = 1024 * 1024 # phash = self.hashfunc() # # if not key: # if isinstance(file, str): # with open(file, 'rb') as source: # while True: # buf = source.read(bufsize) # phash.update(buf) # # if len(buf) < bufsize: # break # # return self._dstore.put_file( # self._template.format(phash.hexdigest()), # file, *args, **kwargs) # else: # tmpfile = tempfile.NamedTemporaryFile(delete=False) # try: # while True: # buf = file.read(bufsize) # phash.update(buf) # tmpfile.write(buf) # # if len(buf) < bufsize: # break # # tmpfile.close() # return self._dstore.put_file( # self._template.format(phash.hexdigest()), # tmpfile.name, *args, **kwargs # ) # finally: # try: # os.unlink(tmpfile.name) # except OSError as e: # if 2 == e.errno: # pass # file already gone # else: # raise # return self._dstore.put_file(key, file, *args, **kwargs) # # Path: simplekv/_compat.py # PY2 = sys.version_info[0] == 2 . Output only the next line.
return UUIDDecorator(store)
Given the following code snippet before the placeholder: <|code_start|> if os.path.exists(tmpfile.name): os.unlink(tmpfile.name) def test_put_generates_valid_uuid(self, uuidstore, value): key = uuidstore.put(None, value) uuid.UUID(hex=key) def test_put_file_generates_valid_uuid(self, uuidstore): key = uuidstore.put_file(None, open('/dev/null', 'rb')) uuid.UUID(hex=key) tmpfile = tempfile.NamedTemporaryFile(delete=False) try: tmpfile.close() key2 = uuidstore.put_file(None, tmpfile.name) uuid.UUID(hex=key2) finally: if os.path.exists(tmpfile.name): os.unlink(tmpfile.name) def test_templates_work(self, templated_uuidstore, value, idgen_template): key = templated_uuidstore.put(None, value) # should not be a valid UUID assert not UUID_REGEXP.match(key) class HashGen(IDGen): @pytest.fixture def hashstore(self, store, hashfunc): <|code_end|> , predict the next line using imports from the current file: import os import re import tempfile import uuid import pytest from simplekv.idgen import UUIDDecorator, HashDecorator from simplekv._compat import text_type and context including class names, function names, and sometimes code from other files: # Path: simplekv/idgen.py # class UUIDDecorator(StoreDecorator): # """UUID generating decorator # # Overrides :meth:`.KeyValueStore.put` and :meth:`.KeyValueStore.put_file`. # If a key of *None* is passed, a new UUID will be generated as the key. The # attribute `uuidfunc` determines which UUID-function to use and defaults to # 'uuid1'. # # .. note:: # There seems to be a bug in the uuid module that prevents initializing # `uuidfunc` too early. For that reason, it is a string that will be # looked up using :func:`getattr` on the :mod:`uuid` module. # """ # # for strange reasons, this needs to be looked up as late as possible # uuidfunc = 'uuid1' # # def __init__(self, store, template=u'{}'): # super(UUIDDecorator, self).__init__(store) # self._template = template # # def put(self, key, data, *args, **kwargs): # if not key: # key = text_type(getattr(uuid, self.uuidfunc)()) # # return self._dstore.put( # self._template.format(key), data, *args, **kwargs # ) # # def put_file(self, key, file, *args, **kwargs): # if not key: # key = text_type(getattr(uuid, self.uuidfunc)()) # # return self._dstore.put_file( # self._template.format(key), file, *args, **kwargs # ) # # class HashDecorator(StoreDecorator): # """Hash function decorator # # Overrides :meth:`.KeyValueStore.put` and :meth:`.KeyValueStore.put_file`. # If a key of *None* is passed, the data/file is hashed using # ``hashfunc``, which defaults to *hashlib.sha1*. """ # # def __init__(self, decorated_store, hashfunc=hashlib.sha1, template=u'{}'): # self.hashfunc = hashfunc # self._template = template # super(HashDecorator, self).__init__(decorated_store) # # def put(self, key, data, *args, **kwargs): # if not key: # key = self._template.format(self.hashfunc(data).hexdigest()) # # return self._dstore.put(key, data, *args, **kwargs) # # def put_file(self, key, file, *args, **kwargs): # bufsize = 1024 * 1024 # phash = self.hashfunc() # # if not key: # if isinstance(file, str): # with open(file, 'rb') as source: # while True: # buf = source.read(bufsize) # phash.update(buf) # # if len(buf) < bufsize: # break # # return self._dstore.put_file( # self._template.format(phash.hexdigest()), # file, *args, **kwargs) # else: # tmpfile = tempfile.NamedTemporaryFile(delete=False) # try: # while True: # buf = file.read(bufsize) # phash.update(buf) # tmpfile.write(buf) # # if len(buf) < bufsize: # break # # tmpfile.close() # return self._dstore.put_file( # self._template.format(phash.hexdigest()), # tmpfile.name, *args, **kwargs # ) # finally: # try: # os.unlink(tmpfile.name) # except OSError as e: # if 2 == e.errno: # pass # file already gone # else: # raise # return self._dstore.put_file(key, file, *args, **kwargs) # # Path: simplekv/_compat.py # PY2 = sys.version_info[0] == 2 . Output only the next line.
return HashDecorator(store, hashfunc)
Predict the next line for this snippet: <|code_start|> @pytest.fixture def validate_hash(self, hashfunc): hash_regexp = re.compile(r'^[0-9a-f]{{{}}}$'.format( hashfunc().digest_size * 2, )) return hash_regexp.match @pytest.fixture def value_hash(self, hashfunc, value): return hashfunc(value).hexdigest() def test_put_generates_valid_form(self, hashstore, validate_hash, value): key = hashstore.put(None, value) assert validate_hash(key) def test_put_file_generates_valid_form(self, hashstore, validate_hash): key = hashstore.put_file(None, open('/dev/null', 'rb')) assert validate_hash(key) # this is not correct according to our interface # /dev/null cannot be claimed by the hashstore # key2 = hashstore.put_file(None, '/dev/null') # assert validate_hash(key2) def test_put_generates_correct_hash(self, hashstore, value_hash, value): key = hashstore.put(None, value) assert value_hash == key <|code_end|> with the help of current file imports: import os import re import tempfile import uuid import pytest from simplekv.idgen import UUIDDecorator, HashDecorator from simplekv._compat import text_type and context from other files: # Path: simplekv/idgen.py # class UUIDDecorator(StoreDecorator): # """UUID generating decorator # # Overrides :meth:`.KeyValueStore.put` and :meth:`.KeyValueStore.put_file`. # If a key of *None* is passed, a new UUID will be generated as the key. The # attribute `uuidfunc` determines which UUID-function to use and defaults to # 'uuid1'. # # .. note:: # There seems to be a bug in the uuid module that prevents initializing # `uuidfunc` too early. For that reason, it is a string that will be # looked up using :func:`getattr` on the :mod:`uuid` module. # """ # # for strange reasons, this needs to be looked up as late as possible # uuidfunc = 'uuid1' # # def __init__(self, store, template=u'{}'): # super(UUIDDecorator, self).__init__(store) # self._template = template # # def put(self, key, data, *args, **kwargs): # if not key: # key = text_type(getattr(uuid, self.uuidfunc)()) # # return self._dstore.put( # self._template.format(key), data, *args, **kwargs # ) # # def put_file(self, key, file, *args, **kwargs): # if not key: # key = text_type(getattr(uuid, self.uuidfunc)()) # # return self._dstore.put_file( # self._template.format(key), file, *args, **kwargs # ) # # class HashDecorator(StoreDecorator): # """Hash function decorator # # Overrides :meth:`.KeyValueStore.put` and :meth:`.KeyValueStore.put_file`. # If a key of *None* is passed, the data/file is hashed using # ``hashfunc``, which defaults to *hashlib.sha1*. """ # # def __init__(self, decorated_store, hashfunc=hashlib.sha1, template=u'{}'): # self.hashfunc = hashfunc # self._template = template # super(HashDecorator, self).__init__(decorated_store) # # def put(self, key, data, *args, **kwargs): # if not key: # key = self._template.format(self.hashfunc(data).hexdigest()) # # return self._dstore.put(key, data, *args, **kwargs) # # def put_file(self, key, file, *args, **kwargs): # bufsize = 1024 * 1024 # phash = self.hashfunc() # # if not key: # if isinstance(file, str): # with open(file, 'rb') as source: # while True: # buf = source.read(bufsize) # phash.update(buf) # # if len(buf) < bufsize: # break # # return self._dstore.put_file( # self._template.format(phash.hexdigest()), # file, *args, **kwargs) # else: # tmpfile = tempfile.NamedTemporaryFile(delete=False) # try: # while True: # buf = file.read(bufsize) # phash.update(buf) # tmpfile.write(buf) # # if len(buf) < bufsize: # break # # tmpfile.close() # return self._dstore.put_file( # self._template.format(phash.hexdigest()), # tmpfile.name, *args, **kwargs # ) # finally: # try: # os.unlink(tmpfile.name) # except OSError as e: # if 2 == e.errno: # pass # file already gone # else: # raise # return self._dstore.put_file(key, file, *args, **kwargs) # # Path: simplekv/_compat.py # PY2 = sys.version_info[0] == 2 , which may contain function names, class names, or code. Output only the next line.
assert isinstance(key, text_type)
Using the snippet: <|code_start|> :param store: The store to pass keys on to. :param prefix: Prefix to add. """ def __init__(self, prefix, store): super(PrefixDecorator, self).__init__(store) self.prefix = prefix def _filter(self, key): return key.startswith(self.prefix) def _map_key(self, key): self._check_valid_key(key) return self.prefix + key def _map_key_prefix(self, key_prefix): return self.prefix + key_prefix def _unmap_key(self, key): assert key.startswith(self.prefix) return key[len(self.prefix):] class URLEncodeKeysDecorator(KeyTransformingDecorator): """URL-encodes keys before passing them on to the underlying store.""" def _map_key(self, key): if not isinstance(key, text_type): raise ValueError('%r is not a unicode string' % key) <|code_end|> , determine the next line of code. You have imports: from ._compat import quote_plus, unquote_plus, text_type, binary_type and context (class names, function names, or code) available: # Path: simplekv/_compat.py # PY2 = sys.version_info[0] == 2 . Output only the next line.
quoted = quote_plus(key.encode('utf-8'))
Next line prediction: <|code_start|> def _filter(self, key): return key.startswith(self.prefix) def _map_key(self, key): self._check_valid_key(key) return self.prefix + key def _map_key_prefix(self, key_prefix): return self.prefix + key_prefix def _unmap_key(self, key): assert key.startswith(self.prefix) return key[len(self.prefix):] class URLEncodeKeysDecorator(KeyTransformingDecorator): """URL-encodes keys before passing them on to the underlying store.""" def _map_key(self, key): if not isinstance(key, text_type): raise ValueError('%r is not a unicode string' % key) quoted = quote_plus(key.encode('utf-8')) if isinstance(quoted, binary_type): quoted = quoted.decode('utf-8') return quoted def _map_key_prefix(self, key_prefix): return self._map_key(key_prefix) def _unmap_key(self, key): <|code_end|> . Use current file imports: (from ._compat import quote_plus, unquote_plus, text_type, binary_type) and context including class names, function names, or small code snippets from other files: # Path: simplekv/_compat.py # PY2 = sys.version_info[0] == 2 . Output only the next line.
return unquote_plus(key)
Next line prediction: <|code_start|> """Prefixes any key with a string before passing it on the decorated store. Automatically strips the prefix upon key retrieval. :param store: The store to pass keys on to. :param prefix: Prefix to add. """ def __init__(self, prefix, store): super(PrefixDecorator, self).__init__(store) self.prefix = prefix def _filter(self, key): return key.startswith(self.prefix) def _map_key(self, key): self._check_valid_key(key) return self.prefix + key def _map_key_prefix(self, key_prefix): return self.prefix + key_prefix def _unmap_key(self, key): assert key.startswith(self.prefix) return key[len(self.prefix):] class URLEncodeKeysDecorator(KeyTransformingDecorator): """URL-encodes keys before passing them on to the underlying store.""" def _map_key(self, key): <|code_end|> . Use current file imports: (from ._compat import quote_plus, unquote_plus, text_type, binary_type) and context including class names, function names, or small code snippets from other files: # Path: simplekv/_compat.py # PY2 = sys.version_info[0] == 2 . Output only the next line.
if not isinstance(key, text_type):
Here is a snippet: <|code_start|> :param store: The store to pass keys on to. :param prefix: Prefix to add. """ def __init__(self, prefix, store): super(PrefixDecorator, self).__init__(store) self.prefix = prefix def _filter(self, key): return key.startswith(self.prefix) def _map_key(self, key): self._check_valid_key(key) return self.prefix + key def _map_key_prefix(self, key_prefix): return self.prefix + key_prefix def _unmap_key(self, key): assert key.startswith(self.prefix) return key[len(self.prefix):] class URLEncodeKeysDecorator(KeyTransformingDecorator): """URL-encodes keys before passing them on to the underlying store.""" def _map_key(self, key): if not isinstance(key, text_type): raise ValueError('%r is not a unicode string' % key) quoted = quote_plus(key.encode('utf-8')) <|code_end|> . Write the next line using the current file imports: from ._compat import quote_plus, unquote_plus, text_type, binary_type and context from other files: # Path: simplekv/_compat.py # PY2 = sys.version_info[0] == 2 , which may include functions, classes, or code. Output only the next line.
if isinstance(quoted, binary_type):
Predict the next line for this snippet: <|code_start|> self.refresh_button.clicked.connect(self.refresh_data) self.buttonbox.addButton( self.refresh_button, QDialogButtonBox.ActionRole) self.layout.addWidget(self.buttonbox) self.refresh_data() def refresh_data(self): self.process_combo.clear() for server in self.servers: self.process_combo.addItem(str(server.process.processId())) self.select_process(0) def select_process(self, index): self.dir_lineedit.setText(self.servers[index].notebook_dir) self.interpreter_lineedit.setText(self.servers[index].interpreter) self.state_lineedit.setText( SERVER_STATE_DESCRIPTIONS[self.servers[index].state]) self.log_textedit.setPlainText(self.servers[index].output) def test(): # pragma: no cover """Display dialog for manual testing.""" class FakeProcess: def __init__(self, pid): self.pid = pid def processId(self): return self.pid <|code_end|> with the help of current file imports: import sys from qtpy.QtWidgets import ( QApplication, QComboBox, QDialogButtonBox, QFormLayout, QLineEdit, QPushButton, QTextEdit, QVBoxLayout) from spyder.plugins.variableexplorer.widgets.basedialog import BaseDialog from spyder_notebook.utils.localization import _ from spyder_notebook.utils.servermanager import ServerProcess, ServerState and context from other files: # Path: spyder_notebook/utils/localization.py # # Path: spyder_notebook/utils/servermanager.py # class ServerProcess(): # """ # Process executing a notebook server. # # This is a data class. # """ # # def __init__(self, process, notebook_dir, interpreter, starttime=None, # state=ServerState.STARTING, server_info=None, output=''): # """ # Construct a ServerProcess. # # Parameters # ---------- # process : QProcess # The process described by this instance. # notebook_dir : str # Directory from which the server can render notebooks. # interpreter : str # File name of Python interpreter used to render notebooks. # starttime : datetime or None, optional # Time at which the process was started. The default is None, # meaning that the current time should be used. # state : ServerState, optional # State of the server process. The default is ServerState.STARTING. # server_info : dict or None, optional # If set, this is a dict with information given by the server in # a JSON file in jupyter_runtime_dir(). It has keys like 'url' and # 'token'. The default is None. # output : str # Output of the server process from stdout and stderr. The default # is ''. # """ # self.process = process # self.notebook_dir = notebook_dir # self.interpreter = interpreter # self.starttime = starttime or datetime.datetime.now() # self.state = state # self.server_info = server_info # self.output = output # # class ServerState(enum.Enum): # """State of a server process.""" # # STARTING = 1 # RUNNING = 2 # FINISHED = 3 # ERROR = 4 # TIMED_OUT = 5 , which may contain function names, class names, or code. Output only the next line.
servers = [ServerProcess(FakeProcess(42), '/my/home/dir',
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- # # Copyright (c) Spyder Project Contributors # Licensed under the terms of the MIT License """Spyder configuration page for notebook plugin.""" # Qt imports # Spyder imports # Local imports class NotebookConfigPage(PluginConfigPage): """Widget with configuration options for notebook plugin.""" def setup_page(self): """Fill configuration page with widgets.""" themes = ['Same as Spyder', 'Light', 'Dark'] theme_choices = list(zip(themes, [theme.lower() for theme in themes])) theme_combo = self.create_combobox( <|code_end|> using the current file's imports: from qtpy.QtWidgets import QGridLayout, QGroupBox, QVBoxLayout from spyder.api.preferences import PluginConfigPage from spyder_notebook.utils.localization import _ and any relevant context from other files: # Path: spyder_notebook/utils/localization.py . Output only the next line.
_('Notebook theme'), theme_choices, 'theme', restart=True)
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- # # Copyright © Spyder Project Contributors # Licensed under the terms of the MIT License # """Tests for serverinfo.py.""" # Third party imports # Local imports class FakeProcess: """Fake for ServerProcess class.""" def __init__(self, pid): self.pid = pid def processId(self): """Member function which needs to be faked.""" return self.pid @pytest.fixture def dialog(qtbot): """Construct and return dialog window for testing.""" <|code_end|> , generate the next line using the imports in this file: import pytest from spyder_notebook.utils.servermanager import ServerProcess, ServerState from spyder_notebook.widgets.serverinfo import ServerInfoDialog and context (functions, classes, or occasionally code) from other files: # Path: spyder_notebook/utils/servermanager.py # class ServerProcess(): # """ # Process executing a notebook server. # # This is a data class. # """ # # def __init__(self, process, notebook_dir, interpreter, starttime=None, # state=ServerState.STARTING, server_info=None, output=''): # """ # Construct a ServerProcess. # # Parameters # ---------- # process : QProcess # The process described by this instance. # notebook_dir : str # Directory from which the server can render notebooks. # interpreter : str # File name of Python interpreter used to render notebooks. # starttime : datetime or None, optional # Time at which the process was started. The default is None, # meaning that the current time should be used. # state : ServerState, optional # State of the server process. The default is ServerState.STARTING. # server_info : dict or None, optional # If set, this is a dict with information given by the server in # a JSON file in jupyter_runtime_dir(). It has keys like 'url' and # 'token'. The default is None. # output : str # Output of the server process from stdout and stderr. The default # is ''. # """ # self.process = process # self.notebook_dir = notebook_dir # self.interpreter = interpreter # self.starttime = starttime or datetime.datetime.now() # self.state = state # self.server_info = server_info # self.output = output # # class ServerState(enum.Enum): # """State of a server process.""" # # STARTING = 1 # RUNNING = 2 # FINISHED = 3 # ERROR = 4 # TIMED_OUT = 5 # # Path: spyder_notebook/widgets/serverinfo.py # class ServerInfoDialog(BaseDialog): # """Dialog window showing information about notebook servers.""" # # def __init__(self, server_info, parent=None): # """ # Construct a RecoveryDialog. # # Parameters # ---------- # servers : list of ServerProcess # Information to be displayed. This parameter is read only. # parent : QWidget, optional # Parent of the dialog window. The default is None. # """ # super().__init__(parent) # self.servers = server_info # # self.setWindowTitle(_('Notebook server info')) # # self.layout = QVBoxLayout(self) # self.formlayout = QFormLayout() # self.layout.addLayout(self.formlayout) # # self.process_combo = QComboBox(self) # self.process_combo.currentIndexChanged.connect(self.select_process) # self.formlayout.addRow(_('Process ID:'), self.process_combo) # # self.dir_lineedit = QLineEdit(self) # self.dir_lineedit.setReadOnly(True) # self.formlayout.addRow(_('Notebook dir:'), self.dir_lineedit) # # self.interpreter_lineedit = QLineEdit(self) # self.interpreter_lineedit.setReadOnly(True) # self.formlayout.addRow(_('Python interpreter:'), # self.interpreter_lineedit) # # self.state_lineedit = QLineEdit(self) # self.state_lineedit.setReadOnly(True) # self.formlayout.addRow(_('State:'), self.state_lineedit) # # self.log_textedit = QTextEdit(self) # self.log_textedit.setReadOnly(True) # self.layout.addWidget(self.log_textedit) # # self.buttonbox = QDialogButtonBox(QDialogButtonBox.Ok, self) # self.buttonbox.accepted.connect(self.accept) # self.refresh_button = QPushButton(_('Refresh'), self) # self.refresh_button.clicked.connect(self.refresh_data) # self.buttonbox.addButton( # self.refresh_button, QDialogButtonBox.ActionRole) # self.layout.addWidget(self.buttonbox) # # self.refresh_data() # # def refresh_data(self): # self.process_combo.clear() # for server in self.servers: # self.process_combo.addItem(str(server.process.processId())) # self.select_process(0) # # def select_process(self, index): # self.dir_lineedit.setText(self.servers[index].notebook_dir) # self.interpreter_lineedit.setText(self.servers[index].interpreter) # self.state_lineedit.setText( # SERVER_STATE_DESCRIPTIONS[self.servers[index].state]) # self.log_textedit.setPlainText(self.servers[index].output) . Output only the next line.
servers = [ServerProcess(FakeProcess(42), '/my/home/dir',
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- # # Copyright © Spyder Project Contributors # Licensed under the terms of the MIT License # """Tests for serverinfo.py.""" # Third party imports # Local imports class FakeProcess: """Fake for ServerProcess class.""" def __init__(self, pid): self.pid = pid def processId(self): """Member function which needs to be faked.""" return self.pid @pytest.fixture def dialog(qtbot): """Construct and return dialog window for testing.""" servers = [ServerProcess(FakeProcess(42), '/my/home/dir', interpreter='/ham/interpreter', <|code_end|> , generate the next line using the imports in this file: import pytest from spyder_notebook.utils.servermanager import ServerProcess, ServerState from spyder_notebook.widgets.serverinfo import ServerInfoDialog and context (functions, classes, or occasionally code) from other files: # Path: spyder_notebook/utils/servermanager.py # class ServerProcess(): # """ # Process executing a notebook server. # # This is a data class. # """ # # def __init__(self, process, notebook_dir, interpreter, starttime=None, # state=ServerState.STARTING, server_info=None, output=''): # """ # Construct a ServerProcess. # # Parameters # ---------- # process : QProcess # The process described by this instance. # notebook_dir : str # Directory from which the server can render notebooks. # interpreter : str # File name of Python interpreter used to render notebooks. # starttime : datetime or None, optional # Time at which the process was started. The default is None, # meaning that the current time should be used. # state : ServerState, optional # State of the server process. The default is ServerState.STARTING. # server_info : dict or None, optional # If set, this is a dict with information given by the server in # a JSON file in jupyter_runtime_dir(). It has keys like 'url' and # 'token'. The default is None. # output : str # Output of the server process from stdout and stderr. The default # is ''. # """ # self.process = process # self.notebook_dir = notebook_dir # self.interpreter = interpreter # self.starttime = starttime or datetime.datetime.now() # self.state = state # self.server_info = server_info # self.output = output # # class ServerState(enum.Enum): # """State of a server process.""" # # STARTING = 1 # RUNNING = 2 # FINISHED = 3 # ERROR = 4 # TIMED_OUT = 5 # # Path: spyder_notebook/widgets/serverinfo.py # class ServerInfoDialog(BaseDialog): # """Dialog window showing information about notebook servers.""" # # def __init__(self, server_info, parent=None): # """ # Construct a RecoveryDialog. # # Parameters # ---------- # servers : list of ServerProcess # Information to be displayed. This parameter is read only. # parent : QWidget, optional # Parent of the dialog window. The default is None. # """ # super().__init__(parent) # self.servers = server_info # # self.setWindowTitle(_('Notebook server info')) # # self.layout = QVBoxLayout(self) # self.formlayout = QFormLayout() # self.layout.addLayout(self.formlayout) # # self.process_combo = QComboBox(self) # self.process_combo.currentIndexChanged.connect(self.select_process) # self.formlayout.addRow(_('Process ID:'), self.process_combo) # # self.dir_lineedit = QLineEdit(self) # self.dir_lineedit.setReadOnly(True) # self.formlayout.addRow(_('Notebook dir:'), self.dir_lineedit) # # self.interpreter_lineedit = QLineEdit(self) # self.interpreter_lineedit.setReadOnly(True) # self.formlayout.addRow(_('Python interpreter:'), # self.interpreter_lineedit) # # self.state_lineedit = QLineEdit(self) # self.state_lineedit.setReadOnly(True) # self.formlayout.addRow(_('State:'), self.state_lineedit) # # self.log_textedit = QTextEdit(self) # self.log_textedit.setReadOnly(True) # self.layout.addWidget(self.log_textedit) # # self.buttonbox = QDialogButtonBox(QDialogButtonBox.Ok, self) # self.buttonbox.accepted.connect(self.accept) # self.refresh_button = QPushButton(_('Refresh'), self) # self.refresh_button.clicked.connect(self.refresh_data) # self.buttonbox.addButton( # self.refresh_button, QDialogButtonBox.ActionRole) # self.layout.addWidget(self.buttonbox) # # self.refresh_data() # # def refresh_data(self): # self.process_combo.clear() # for server in self.servers: # self.process_combo.addItem(str(server.process.processId())) # self.select_process(0) # # def select_process(self, index): # self.dir_lineedit.setText(self.servers[index].notebook_dir) # self.interpreter_lineedit.setText(self.servers[index].interpreter) # self.state_lineedit.setText( # SERVER_STATE_DESCRIPTIONS[self.servers[index].state]) # self.log_textedit.setPlainText(self.servers[index].output) . Output only the next line.
state=ServerState.RUNNING,
Predict the next line for this snippet: <|code_start|> """Tests for serverinfo.py.""" # Third party imports # Local imports class FakeProcess: """Fake for ServerProcess class.""" def __init__(self, pid): self.pid = pid def processId(self): """Member function which needs to be faked.""" return self.pid @pytest.fixture def dialog(qtbot): """Construct and return dialog window for testing.""" servers = [ServerProcess(FakeProcess(42), '/my/home/dir', interpreter='/ham/interpreter', state=ServerState.RUNNING, output='Nicely humming along...\n'), ServerProcess(FakeProcess(404), '/some/other/dir', interpreter='/spam/interpreter', state=ServerState.FINISHED, output='Terminated for some reason...\n')] <|code_end|> with the help of current file imports: import pytest from spyder_notebook.utils.servermanager import ServerProcess, ServerState from spyder_notebook.widgets.serverinfo import ServerInfoDialog and context from other files: # Path: spyder_notebook/utils/servermanager.py # class ServerProcess(): # """ # Process executing a notebook server. # # This is a data class. # """ # # def __init__(self, process, notebook_dir, interpreter, starttime=None, # state=ServerState.STARTING, server_info=None, output=''): # """ # Construct a ServerProcess. # # Parameters # ---------- # process : QProcess # The process described by this instance. # notebook_dir : str # Directory from which the server can render notebooks. # interpreter : str # File name of Python interpreter used to render notebooks. # starttime : datetime or None, optional # Time at which the process was started. The default is None, # meaning that the current time should be used. # state : ServerState, optional # State of the server process. The default is ServerState.STARTING. # server_info : dict or None, optional # If set, this is a dict with information given by the server in # a JSON file in jupyter_runtime_dir(). It has keys like 'url' and # 'token'. The default is None. # output : str # Output of the server process from stdout and stderr. The default # is ''. # """ # self.process = process # self.notebook_dir = notebook_dir # self.interpreter = interpreter # self.starttime = starttime or datetime.datetime.now() # self.state = state # self.server_info = server_info # self.output = output # # class ServerState(enum.Enum): # """State of a server process.""" # # STARTING = 1 # RUNNING = 2 # FINISHED = 3 # ERROR = 4 # TIMED_OUT = 5 # # Path: spyder_notebook/widgets/serverinfo.py # class ServerInfoDialog(BaseDialog): # """Dialog window showing information about notebook servers.""" # # def __init__(self, server_info, parent=None): # """ # Construct a RecoveryDialog. # # Parameters # ---------- # servers : list of ServerProcess # Information to be displayed. This parameter is read only. # parent : QWidget, optional # Parent of the dialog window. The default is None. # """ # super().__init__(parent) # self.servers = server_info # # self.setWindowTitle(_('Notebook server info')) # # self.layout = QVBoxLayout(self) # self.formlayout = QFormLayout() # self.layout.addLayout(self.formlayout) # # self.process_combo = QComboBox(self) # self.process_combo.currentIndexChanged.connect(self.select_process) # self.formlayout.addRow(_('Process ID:'), self.process_combo) # # self.dir_lineedit = QLineEdit(self) # self.dir_lineedit.setReadOnly(True) # self.formlayout.addRow(_('Notebook dir:'), self.dir_lineedit) # # self.interpreter_lineedit = QLineEdit(self) # self.interpreter_lineedit.setReadOnly(True) # self.formlayout.addRow(_('Python interpreter:'), # self.interpreter_lineedit) # # self.state_lineedit = QLineEdit(self) # self.state_lineedit.setReadOnly(True) # self.formlayout.addRow(_('State:'), self.state_lineedit) # # self.log_textedit = QTextEdit(self) # self.log_textedit.setReadOnly(True) # self.layout.addWidget(self.log_textedit) # # self.buttonbox = QDialogButtonBox(QDialogButtonBox.Ok, self) # self.buttonbox.accepted.connect(self.accept) # self.refresh_button = QPushButton(_('Refresh'), self) # self.refresh_button.clicked.connect(self.refresh_data) # self.buttonbox.addButton( # self.refresh_button, QDialogButtonBox.ActionRole) # self.layout.addWidget(self.buttonbox) # # self.refresh_data() # # def refresh_data(self): # self.process_combo.clear() # for server in self.servers: # self.process_combo.addItem(str(server.process.processId())) # self.select_process(0) # # def select_process(self, index): # self.dir_lineedit.setText(self.servers[index].notebook_dir) # self.interpreter_lineedit.setText(self.servers[index].interpreter) # self.state_lineedit.setText( # SERVER_STATE_DESCRIPTIONS[self.servers[index].state]) # self.log_textedit.setPlainText(self.servers[index].output) , which may contain function names, class names, or code. Output only the next line.
res = ServerInfoDialog(servers)
Predict the next line for this snippet: <|code_start|> self.pageAction(QWebEnginePage.Copy), None, self.zoom_in_action, self.zoom_out_action] if not WEBENGINE: settings = self.page().settings() settings.setAttribute(QWebEngineSettings.DeveloperExtrasEnabled, True) actions += [None, self.pageAction(QWebEnginePage.InspectElement)] menu = QMenu(self) add_actions(menu, actions) menu.popup(event.globalPos()) event.accept() def show_blank(self): """Show a blank page.""" self.setHtml(BLANK) def show_kernel_error(self, error): """Show kernel initialization errors.""" # Remove unneeded blank lines at the beginning eol = sourcecode.get_eol_chars(error) if eol: error = error.replace(eol, '<br>') # Don't break lines in hyphens # From http://stackoverflow.com/q/7691569/438386 error = error.replace('-', '&#8209') <|code_end|> with the help of current file imports: import json import os import os.path as osp import sys import requests import webbrowser from string import Template from qtpy.QtCore import QUrl, Qt from qtpy.QtGui import QFontMetrics, QFont from qtpy.QtWebEngineWidgets import (QWebEnginePage, QWebEngineSettings, QWebEngineView, WEBENGINE) from qtpy.QtWidgets import (QApplication, QMenu, QVBoxLayout, QWidget, QMessageBox) from notebook.utils import url_path_join, url_escape from spyder.config.base import get_image_path, get_module_source_path from spyder.utils.qthelpers import add_actions from spyder.utils import sourcecode from spyder.widgets.findreplace import FindReplace from spyder_notebook.utils.localization import _ from spyder_notebook.widgets.dom import DOMWidget from spyder.utils.qthelpers import qapplication and context from other files: # Path: spyder_notebook/utils/localization.py # # Path: spyder_notebook/widgets/dom.py # class DOMWidget(WebView): # """Widget to do DOM manipulations using Javascript.""" # # def __init__(self, parent): # """Constructor.""" # super().__init__(parent) # if WEBENGINE: # self.dom = self.page() # else: # self.dom = self.page().mainFrame() # # def evaluate(self, script): # """ # Evaluate script in page frame. # # :param script: The script to evaluate. # """ # if WEBENGINE: # return self.dom.runJavaScript("{}".format(script)) # else: # return self.dom.evaluateJavaScript("{}".format(script)) # # def mousedown(self, selector, btn=0): # """ # Simulate a mousedown event on the targeted element. # # :param selector: A CSS3 selector to targeted element. # :param btn: The number of mouse button. # 0 - left button, # 1 - middle button, # 2 - right button # """ # return self.evaluate(""" # (function () {{ # var element = document.querySelector({0}); # var evt = document.createEvent("MouseEvents"); # evt.initMouseEvent("mousedown", true, true, window, # 1, 1, 1, 1, 1, false, false, false, false, # {1}, element); # return element.dispatchEvent(evt); # }})(); # """.format(repr(selector), repr(btn))) # # def set_input_value(self, selector, value): # """Set the value of the input matched by given selector.""" # script = 'document.querySelector("%s").setAttribute("value", "%s")' # script = script % (selector, value) # self.evaluate(script) , which may contain function names, class names, or code. Output only the next line.
message = _("An error occurred while starting the kernel")
Given the code snippet: <|code_start|> WebView which opens document in an external browser. This is a subclass of QWebEngineView, which as soon as the URL is set, opens the web page in an external browser and closes itself. It is used in NotebookWidget to open links. """ def __init__(self, parent): """Construct object.""" super().__init__(parent) self.urlChanged.connect(self.open_in_browser) def open_in_browser(self, url): """ Open web page in external browser and close self. Parameters ---------- url : QUrl URL of web page to open in browser """ try: webbrowser.open(url.toString()) except ValueError: # See: spyder-ide/spyder#9849 pass self.stop() self.close() <|code_end|> , generate the next line using the imports in this file: import json import os import os.path as osp import sys import requests import webbrowser from string import Template from qtpy.QtCore import QUrl, Qt from qtpy.QtGui import QFontMetrics, QFont from qtpy.QtWebEngineWidgets import (QWebEnginePage, QWebEngineSettings, QWebEngineView, WEBENGINE) from qtpy.QtWidgets import (QApplication, QMenu, QVBoxLayout, QWidget, QMessageBox) from notebook.utils import url_path_join, url_escape from spyder.config.base import get_image_path, get_module_source_path from spyder.utils.qthelpers import add_actions from spyder.utils import sourcecode from spyder.widgets.findreplace import FindReplace from spyder_notebook.utils.localization import _ from spyder_notebook.widgets.dom import DOMWidget from spyder.utils.qthelpers import qapplication and context (functions, classes, or occasionally code) from other files: # Path: spyder_notebook/utils/localization.py # # Path: spyder_notebook/widgets/dom.py # class DOMWidget(WebView): # """Widget to do DOM manipulations using Javascript.""" # # def __init__(self, parent): # """Constructor.""" # super().__init__(parent) # if WEBENGINE: # self.dom = self.page() # else: # self.dom = self.page().mainFrame() # # def evaluate(self, script): # """ # Evaluate script in page frame. # # :param script: The script to evaluate. # """ # if WEBENGINE: # return self.dom.runJavaScript("{}".format(script)) # else: # return self.dom.evaluateJavaScript("{}".format(script)) # # def mousedown(self, selector, btn=0): # """ # Simulate a mousedown event on the targeted element. # # :param selector: A CSS3 selector to targeted element. # :param btn: The number of mouse button. # 0 - left button, # 1 - middle button, # 2 - right button # """ # return self.evaluate(""" # (function () {{ # var element = document.querySelector({0}); # var evt = document.createEvent("MouseEvents"); # evt.initMouseEvent("mousedown", true, true, window, # 1, 1, 1, 1, 1, false, false, false, false, # {1}, element); # return element.dispatchEvent(evt); # }})(); # """.format(repr(selector), repr(btn))) # # def set_input_value(self, selector, value): # """Set the value of the input matched by given selector.""" # script = 'document.querySelector("%s").setAttribute("value", "%s")' # script = script % (selector, value) # self.evaluate(script) . Output only the next line.
class NotebookWidget(DOMWidget):
Next line prediction: <|code_start|> def usage(argv): cmd = os.path.basename(argv[0]) print('usage: %s <config_uri> [var=value]\n' '(example: "%s development.ini")' % (cmd, cmd)) sys.exit(1) def main(argv=sys.argv): if len(argv) < 2: usage(argv) config_uri = argv[1] options = parse_vars(argv[2:]) setup_logging(config_uri) settings = get_appsettings(config_uri, options=options) engine = engine_from_config(settings, 'sqlalchemy.') <|code_end|> . Use current file imports: (import os import sys import transaction from sqlalchemy import engine_from_config from pyramid.paster import ( get_appsettings, setup_logging, ) from pyramid.scripts.common import parse_vars from ..models import ( DBSession, #MyModel, Base, AgencyTypes, Agencies, )) and context including class names, function names, or small code snippets from other files: # Path: src/mcsafetyfeed-server/mcsafetyfeedserver/models.py # class Users(Base): # class AgencyTypes(Base): # class Agencies(Base): # class DispatchTypes(Base): # class Groups(Base): # class GroupDispatchTypes(Base): # class Statuses(Base): # class Incidents(Base): # class IncidentsDispatches(Base): # class Dispatches(Base): # class APICalls(Base): # class CurrentDispatches(Base): # class Runs(Base): # def get_from_code(cls, session, code): # def create_new_agency_type(cls, session, code, description): # def get_from_guid(cls, session, guid): # def create_new_agency(cls, session, agency_code, agency_name, # type_id, description, website): # def get_all(cls, session): # def get_from_dispatch_text(cls, session, dispatch_text): # def create_new_dispatch_type(cls, session, dispatch_text, description): # def get_all(cls, session): # def get_from_dispatch_text(cls, session, dispatch_text): # def create_new_status(cls, session, status_text, description): # def get_from_status_text(cls, session, status_text): # def create_new_incident(cls, session, dispatch_text): # def get_count(cls, session): # def check_exists(cls, session, guid, status_text): # def add_dispatch(cls, session, run_id, status_text, short_address, # guid, dispatch_text, dispatch_datetime, source_lat, source_lng, # geocode_lat, geocode_lng, full_address, geocode_successful): # def get_by_guid(cls, session, guid): # def close_dispatch(cls, session, run_id, guid): # def get_by_date(cls, session, target_datetime, start, count): # def get_count_by_date(cls, session, target_datetime): # def add_api_call(cls, session, api_key, query_time, api_call, api_version): # def get_count(cls, session): # def add_current_dispatch(cls, session, guid): # def get_current_dispatch_guids(cls, session): # def remove_current_dispatch(cls, session, guid): # def get_count(cls, session): # def new_run(cls, session): # def update_run(cls, session, run, successful, error_text, new_dispatches): . Output only the next line.
DBSession.configure(bind=engine)
Predict the next line after this snippet: <|code_start|> def usage(argv): cmd = os.path.basename(argv[0]) print('usage: %s <config_uri> [var=value]\n' '(example: "%s development.ini")' % (cmd, cmd)) sys.exit(1) def main(argv=sys.argv): if len(argv) < 2: usage(argv) config_uri = argv[1] options = parse_vars(argv[2:]) setup_logging(config_uri) settings = get_appsettings(config_uri, options=options) engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) <|code_end|> using the current file's imports: import os import sys import transaction from sqlalchemy import engine_from_config from pyramid.paster import ( get_appsettings, setup_logging, ) from pyramid.scripts.common import parse_vars from ..models import ( DBSession, #MyModel, Base, AgencyTypes, Agencies, ) and any relevant context from other files: # Path: src/mcsafetyfeed-server/mcsafetyfeedserver/models.py # class Users(Base): # class AgencyTypes(Base): # class Agencies(Base): # class DispatchTypes(Base): # class Groups(Base): # class GroupDispatchTypes(Base): # class Statuses(Base): # class Incidents(Base): # class IncidentsDispatches(Base): # class Dispatches(Base): # class APICalls(Base): # class CurrentDispatches(Base): # class Runs(Base): # def get_from_code(cls, session, code): # def create_new_agency_type(cls, session, code, description): # def get_from_guid(cls, session, guid): # def create_new_agency(cls, session, agency_code, agency_name, # type_id, description, website): # def get_all(cls, session): # def get_from_dispatch_text(cls, session, dispatch_text): # def create_new_dispatch_type(cls, session, dispatch_text, description): # def get_all(cls, session): # def get_from_dispatch_text(cls, session, dispatch_text): # def create_new_status(cls, session, status_text, description): # def get_from_status_text(cls, session, status_text): # def create_new_incident(cls, session, dispatch_text): # def get_count(cls, session): # def check_exists(cls, session, guid, status_text): # def add_dispatch(cls, session, run_id, status_text, short_address, # guid, dispatch_text, dispatch_datetime, source_lat, source_lng, # geocode_lat, geocode_lng, full_address, geocode_successful): # def get_by_guid(cls, session, guid): # def close_dispatch(cls, session, run_id, guid): # def get_by_date(cls, session, target_datetime, start, count): # def get_count_by_date(cls, session, target_datetime): # def add_api_call(cls, session, api_key, query_time, api_call, api_version): # def get_count(cls, session): # def add_current_dispatch(cls, session, guid): # def get_current_dispatch_guids(cls, session): # def remove_current_dispatch(cls, session, guid): # def get_count(cls, session): # def new_run(cls, session): # def update_run(cls, session, run, successful, error_text, new_dispatches): . Output only the next line.
Base.metadata.create_all(engine)
Here is a snippet: <|code_start|> def usage(argv): cmd = os.path.basename(argv[0]) print('usage: %s <config_uri> [var=value]\n' '(example: "%s development.ini")' % (cmd, cmd)) sys.exit(1) def main(argv=sys.argv): if len(argv) < 2: usage(argv) config_uri = argv[1] options = parse_vars(argv[2:]) setup_logging(config_uri) settings = get_appsettings(config_uri, options=options) engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.create_all(engine) #with transaction.manager: # model = MyModel(name='one', value=1) # DBSession.add(model) with transaction.manager: with open('agencies.csv','r') as f: agencies = f.read().split('\n') for agency in agencies: if agency.strip() != '': # agencyid, shortname, longname, type, description, websiteurl parts = agency.split('\t') <|code_end|> . Write the next line using the current file imports: import os import sys import transaction from sqlalchemy import engine_from_config from pyramid.paster import ( get_appsettings, setup_logging, ) from pyramid.scripts.common import parse_vars from ..models import ( DBSession, #MyModel, Base, AgencyTypes, Agencies, ) and context from other files: # Path: src/mcsafetyfeed-server/mcsafetyfeedserver/models.py # class Users(Base): # class AgencyTypes(Base): # class Agencies(Base): # class DispatchTypes(Base): # class Groups(Base): # class GroupDispatchTypes(Base): # class Statuses(Base): # class Incidents(Base): # class IncidentsDispatches(Base): # class Dispatches(Base): # class APICalls(Base): # class CurrentDispatches(Base): # class Runs(Base): # def get_from_code(cls, session, code): # def create_new_agency_type(cls, session, code, description): # def get_from_guid(cls, session, guid): # def create_new_agency(cls, session, agency_code, agency_name, # type_id, description, website): # def get_all(cls, session): # def get_from_dispatch_text(cls, session, dispatch_text): # def create_new_dispatch_type(cls, session, dispatch_text, description): # def get_all(cls, session): # def get_from_dispatch_text(cls, session, dispatch_text): # def create_new_status(cls, session, status_text, description): # def get_from_status_text(cls, session, status_text): # def create_new_incident(cls, session, dispatch_text): # def get_count(cls, session): # def check_exists(cls, session, guid, status_text): # def add_dispatch(cls, session, run_id, status_text, short_address, # guid, dispatch_text, dispatch_datetime, source_lat, source_lng, # geocode_lat, geocode_lng, full_address, geocode_successful): # def get_by_guid(cls, session, guid): # def close_dispatch(cls, session, run_id, guid): # def get_by_date(cls, session, target_datetime, start, count): # def get_count_by_date(cls, session, target_datetime): # def add_api_call(cls, session, api_key, query_time, api_call, api_version): # def get_count(cls, session): # def add_current_dispatch(cls, session, guid): # def get_current_dispatch_guids(cls, session): # def remove_current_dispatch(cls, session, guid): # def get_count(cls, session): # def new_run(cls, session): # def update_run(cls, session, run, successful, error_text, new_dispatches): , which may include functions, classes, or code. Output only the next line.
agency_type = AgencyTypes.get_from_code(DBSession, parts[3])
Given the following code snippet before the placeholder: <|code_start|>def usage(argv): cmd = os.path.basename(argv[0]) print('usage: %s <config_uri> [var=value]\n' '(example: "%s development.ini")' % (cmd, cmd)) sys.exit(1) def main(argv=sys.argv): if len(argv) < 2: usage(argv) config_uri = argv[1] options = parse_vars(argv[2:]) setup_logging(config_uri) settings = get_appsettings(config_uri, options=options) engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.create_all(engine) #with transaction.manager: # model = MyModel(name='one', value=1) # DBSession.add(model) with transaction.manager: with open('agencies.csv','r') as f: agencies = f.read().split('\n') for agency in agencies: if agency.strip() != '': # agencyid, shortname, longname, type, description, websiteurl parts = agency.split('\t') agency_type = AgencyTypes.get_from_code(DBSession, parts[3]) <|code_end|> , predict the next line using imports from the current file: import os import sys import transaction from sqlalchemy import engine_from_config from pyramid.paster import ( get_appsettings, setup_logging, ) from pyramid.scripts.common import parse_vars from ..models import ( DBSession, #MyModel, Base, AgencyTypes, Agencies, ) and context including class names, function names, and sometimes code from other files: # Path: src/mcsafetyfeed-server/mcsafetyfeedserver/models.py # class Users(Base): # class AgencyTypes(Base): # class Agencies(Base): # class DispatchTypes(Base): # class Groups(Base): # class GroupDispatchTypes(Base): # class Statuses(Base): # class Incidents(Base): # class IncidentsDispatches(Base): # class Dispatches(Base): # class APICalls(Base): # class CurrentDispatches(Base): # class Runs(Base): # def get_from_code(cls, session, code): # def create_new_agency_type(cls, session, code, description): # def get_from_guid(cls, session, guid): # def create_new_agency(cls, session, agency_code, agency_name, # type_id, description, website): # def get_all(cls, session): # def get_from_dispatch_text(cls, session, dispatch_text): # def create_new_dispatch_type(cls, session, dispatch_text, description): # def get_all(cls, session): # def get_from_dispatch_text(cls, session, dispatch_text): # def create_new_status(cls, session, status_text, description): # def get_from_status_text(cls, session, status_text): # def create_new_incident(cls, session, dispatch_text): # def get_count(cls, session): # def check_exists(cls, session, guid, status_text): # def add_dispatch(cls, session, run_id, status_text, short_address, # guid, dispatch_text, dispatch_datetime, source_lat, source_lng, # geocode_lat, geocode_lng, full_address, geocode_successful): # def get_by_guid(cls, session, guid): # def close_dispatch(cls, session, run_id, guid): # def get_by_date(cls, session, target_datetime, start, count): # def get_count_by_date(cls, session, target_datetime): # def add_api_call(cls, session, api_key, query_time, api_call, api_version): # def get_count(cls, session): # def add_current_dispatch(cls, session, guid): # def get_current_dispatch_guids(cls, session): # def remove_current_dispatch(cls, session, guid): # def get_count(cls, session): # def new_run(cls, session): # def update_run(cls, session, run, successful, error_text, new_dispatches): . Output only the next line.
a = Agencies(
Continue the code snippet: <|code_start|>} #@view_config(route_name='home') #def home(request): # # return Response('<html><body>hi.</body></html>') @view_config(route_name='home', renderer='templates/index.mak') def home(request): return {} @view_config(route_name='feed', renderer='templates/feed.mak') def feed(request): if True: start = 0 try: start = int(request.GET['start']) except: pass count = 100 try: count = int(request.GET['count']) except: pass dispatches = Dispatches.get_by_date( <|code_end|> . Use current file imports: import os import json import datetime from pyramid.response import Response from pyramid.view import view_config from sqlalchemy.exc import DBAPIError from .models import ( DBSession, Users, AgencyTypes, Agencies, DispatchTypes, Groups, GroupDispatchTypes, Statuses, Incidents, IncidentsDispatches, Dispatches, APICalls, CurrentDispatches, Runs, ) and context (classes, functions, or code) from other files: # Path: src/mcsafetyfeed-server/mcsafetyfeedserver/models.py # class Users(Base): # class AgencyTypes(Base): # class Agencies(Base): # class DispatchTypes(Base): # class Groups(Base): # class GroupDispatchTypes(Base): # class Statuses(Base): # class Incidents(Base): # class IncidentsDispatches(Base): # class Dispatches(Base): # class APICalls(Base): # class CurrentDispatches(Base): # class Runs(Base): # def get_from_code(cls, session, code): # def create_new_agency_type(cls, session, code, description): # def get_from_guid(cls, session, guid): # def create_new_agency(cls, session, agency_code, agency_name, # type_id, description, website): # def get_all(cls, session): # def get_from_dispatch_text(cls, session, dispatch_text): # def create_new_dispatch_type(cls, session, dispatch_text, description): # def get_all(cls, session): # def get_from_dispatch_text(cls, session, dispatch_text): # def create_new_status(cls, session, status_text, description): # def get_from_status_text(cls, session, status_text): # def create_new_incident(cls, session, dispatch_text): # def get_count(cls, session): # def check_exists(cls, session, guid, status_text): # def add_dispatch(cls, session, run_id, status_text, short_address, # guid, dispatch_text, dispatch_datetime, source_lat, source_lng, # geocode_lat, geocode_lng, full_address, geocode_successful): # def get_by_guid(cls, session, guid): # def close_dispatch(cls, session, run_id, guid): # def get_by_date(cls, session, target_datetime, start, count): # def get_count_by_date(cls, session, target_datetime): # def add_api_call(cls, session, api_key, query_time, api_call, api_version): # def get_count(cls, session): # def add_current_dispatch(cls, session, guid): # def get_current_dispatch_guids(cls, session): # def remove_current_dispatch(cls, session, guid): # def get_count(cls, session): # def new_run(cls, session): # def update_run(cls, session, run, successful, error_text, new_dispatches): . Output only the next line.
session = DBSession,
Given the code snippet: <|code_start|> 'geocode_lng': geocode_lng, 'geocode_successful': geocode_successful, 'status_text': status_text, 'status_description': status_description, 'agency_name': agency_name, 'agency_description': agency_description, 'agency_website': agency_website, 'dispatch_id': dispatch_id, 'dispatch_text': dispatch_text, 'dispatch_description': dispatch_description, }) dispatch_count, = Dispatches.get_count_by_date( session = DBSession, target_datetime = datetime.datetime.now(), ) return {'dispatches': ret_dispatches, 'start': start, 'count': count, 'dispatch_count': dispatch_count} @view_config(route_name='accidents', renderer='templates/accidents.mak') def accidents(request): return {} @view_config(route_name='agencies', renderer='templates/agencies.mak') def agencies(request): if True: #try: <|code_end|> , generate the next line using the imports in this file: import os import json import datetime from pyramid.response import Response from pyramid.view import view_config from sqlalchemy.exc import DBAPIError from .models import ( DBSession, Users, AgencyTypes, Agencies, DispatchTypes, Groups, GroupDispatchTypes, Statuses, Incidents, IncidentsDispatches, Dispatches, APICalls, CurrentDispatches, Runs, ) and context (functions, classes, or occasionally code) from other files: # Path: src/mcsafetyfeed-server/mcsafetyfeedserver/models.py # class Users(Base): # class AgencyTypes(Base): # class Agencies(Base): # class DispatchTypes(Base): # class Groups(Base): # class GroupDispatchTypes(Base): # class Statuses(Base): # class Incidents(Base): # class IncidentsDispatches(Base): # class Dispatches(Base): # class APICalls(Base): # class CurrentDispatches(Base): # class Runs(Base): # def get_from_code(cls, session, code): # def create_new_agency_type(cls, session, code, description): # def get_from_guid(cls, session, guid): # def create_new_agency(cls, session, agency_code, agency_name, # type_id, description, website): # def get_all(cls, session): # def get_from_dispatch_text(cls, session, dispatch_text): # def create_new_dispatch_type(cls, session, dispatch_text, description): # def get_all(cls, session): # def get_from_dispatch_text(cls, session, dispatch_text): # def create_new_status(cls, session, status_text, description): # def get_from_status_text(cls, session, status_text): # def create_new_incident(cls, session, dispatch_text): # def get_count(cls, session): # def check_exists(cls, session, guid, status_text): # def add_dispatch(cls, session, run_id, status_text, short_address, # guid, dispatch_text, dispatch_datetime, source_lat, source_lng, # geocode_lat, geocode_lng, full_address, geocode_successful): # def get_by_guid(cls, session, guid): # def close_dispatch(cls, session, run_id, guid): # def get_by_date(cls, session, target_datetime, start, count): # def get_count_by_date(cls, session, target_datetime): # def add_api_call(cls, session, api_key, query_time, api_call, api_version): # def get_count(cls, session): # def add_current_dispatch(cls, session, guid): # def get_current_dispatch_guids(cls, session): # def remove_current_dispatch(cls, session, guid): # def get_count(cls, session): # def new_run(cls, session): # def update_run(cls, session, run, successful, error_text, new_dispatches): . Output only the next line.
_agencies = Agencies.get_all(
Continue the code snippet: <|code_start|> @view_config(route_name='status.json') def status_json(request): """ Returns the status of the system """ response = {'success': False} try: response['dispatch_count'] = Dispatches.get_count(DBSession) response['current_dispatch_count'] = CurrentDispatches.get_count(DBSession) response['run_count'] = Runs.get_count(DBSession) response['system_status'] = system_status response['success'] = True except: pass resp = json.dumps(response) return Response(resp,content_type="application/json") @view_config(route_name='dispatch_types.json') def dispatch_types(request): response = {'success': False} #try: if True: <|code_end|> . Use current file imports: import os import json import datetime from pyramid.response import Response from pyramid.view import view_config from sqlalchemy.exc import DBAPIError from .models import ( DBSession, Users, AgencyTypes, Agencies, DispatchTypes, Groups, GroupDispatchTypes, Statuses, Incidents, IncidentsDispatches, Dispatches, APICalls, CurrentDispatches, Runs, ) and context (classes, functions, or code) from other files: # Path: src/mcsafetyfeed-server/mcsafetyfeedserver/models.py # class Users(Base): # class AgencyTypes(Base): # class Agencies(Base): # class DispatchTypes(Base): # class Groups(Base): # class GroupDispatchTypes(Base): # class Statuses(Base): # class Incidents(Base): # class IncidentsDispatches(Base): # class Dispatches(Base): # class APICalls(Base): # class CurrentDispatches(Base): # class Runs(Base): # def get_from_code(cls, session, code): # def create_new_agency_type(cls, session, code, description): # def get_from_guid(cls, session, guid): # def create_new_agency(cls, session, agency_code, agency_name, # type_id, description, website): # def get_all(cls, session): # def get_from_dispatch_text(cls, session, dispatch_text): # def create_new_dispatch_type(cls, session, dispatch_text, description): # def get_all(cls, session): # def get_from_dispatch_text(cls, session, dispatch_text): # def create_new_status(cls, session, status_text, description): # def get_from_status_text(cls, session, status_text): # def create_new_incident(cls, session, dispatch_text): # def get_count(cls, session): # def check_exists(cls, session, guid, status_text): # def add_dispatch(cls, session, run_id, status_text, short_address, # guid, dispatch_text, dispatch_datetime, source_lat, source_lng, # geocode_lat, geocode_lng, full_address, geocode_successful): # def get_by_guid(cls, session, guid): # def close_dispatch(cls, session, run_id, guid): # def get_by_date(cls, session, target_datetime, start, count): # def get_count_by_date(cls, session, target_datetime): # def add_api_call(cls, session, api_key, query_time, api_call, api_version): # def get_count(cls, session): # def add_current_dispatch(cls, session, guid): # def get_current_dispatch_guids(cls, session): # def remove_current_dispatch(cls, session, guid): # def get_count(cls, session): # def new_run(cls, session): # def update_run(cls, session, run, successful, error_text, new_dispatches): . Output only the next line.
dispatch_types = DispatchTypes.get_all(
Using the snippet: <|code_start|> 'alive': True } #@view_config(route_name='home') #def home(request): # # return Response('<html><body>hi.</body></html>') @view_config(route_name='home', renderer='templates/index.mak') def home(request): return {} @view_config(route_name='feed', renderer='templates/feed.mak') def feed(request): if True: start = 0 try: start = int(request.GET['start']) except: pass count = 100 try: count = int(request.GET['count']) except: pass <|code_end|> , determine the next line of code. You have imports: import os import json import datetime from pyramid.response import Response from pyramid.view import view_config from sqlalchemy.exc import DBAPIError from .models import ( DBSession, Users, AgencyTypes, Agencies, DispatchTypes, Groups, GroupDispatchTypes, Statuses, Incidents, IncidentsDispatches, Dispatches, APICalls, CurrentDispatches, Runs, ) and context (class names, function names, or code) available: # Path: src/mcsafetyfeed-server/mcsafetyfeedserver/models.py # class Users(Base): # class AgencyTypes(Base): # class Agencies(Base): # class DispatchTypes(Base): # class Groups(Base): # class GroupDispatchTypes(Base): # class Statuses(Base): # class Incidents(Base): # class IncidentsDispatches(Base): # class Dispatches(Base): # class APICalls(Base): # class CurrentDispatches(Base): # class Runs(Base): # def get_from_code(cls, session, code): # def create_new_agency_type(cls, session, code, description): # def get_from_guid(cls, session, guid): # def create_new_agency(cls, session, agency_code, agency_name, # type_id, description, website): # def get_all(cls, session): # def get_from_dispatch_text(cls, session, dispatch_text): # def create_new_dispatch_type(cls, session, dispatch_text, description): # def get_all(cls, session): # def get_from_dispatch_text(cls, session, dispatch_text): # def create_new_status(cls, session, status_text, description): # def get_from_status_text(cls, session, status_text): # def create_new_incident(cls, session, dispatch_text): # def get_count(cls, session): # def check_exists(cls, session, guid, status_text): # def add_dispatch(cls, session, run_id, status_text, short_address, # guid, dispatch_text, dispatch_datetime, source_lat, source_lng, # geocode_lat, geocode_lng, full_address, geocode_successful): # def get_by_guid(cls, session, guid): # def close_dispatch(cls, session, run_id, guid): # def get_by_date(cls, session, target_datetime, start, count): # def get_count_by_date(cls, session, target_datetime): # def add_api_call(cls, session, api_key, query_time, api_call, api_version): # def get_count(cls, session): # def add_current_dispatch(cls, session, guid): # def get_current_dispatch_guids(cls, session): # def remove_current_dispatch(cls, session, guid): # def get_count(cls, session): # def new_run(cls, session): # def update_run(cls, session, run, successful, error_text, new_dispatches): . Output only the next line.
dispatches = Dispatches.get_by_date(
Using the snippet: <|code_start|> @view_config(route_name='browse', renderer='templates/browse.mak') def browse(request): return {} @view_config(route_name='search', renderer='templates/search.mak') def search(request): return {} @view_config(route_name='about', renderer='templates/about.mak') def about(request): return {} @view_config(route_name='status', renderer='templates/status.mak') def status(request): return {} @view_config(route_name='status.json') def status_json(request): """ Returns the status of the system """ response = {'success': False} try: response['dispatch_count'] = Dispatches.get_count(DBSession) <|code_end|> , determine the next line of code. You have imports: import os import json import datetime from pyramid.response import Response from pyramid.view import view_config from sqlalchemy.exc import DBAPIError from .models import ( DBSession, Users, AgencyTypes, Agencies, DispatchTypes, Groups, GroupDispatchTypes, Statuses, Incidents, IncidentsDispatches, Dispatches, APICalls, CurrentDispatches, Runs, ) and context (class names, function names, or code) available: # Path: src/mcsafetyfeed-server/mcsafetyfeedserver/models.py # class Users(Base): # class AgencyTypes(Base): # class Agencies(Base): # class DispatchTypes(Base): # class Groups(Base): # class GroupDispatchTypes(Base): # class Statuses(Base): # class Incidents(Base): # class IncidentsDispatches(Base): # class Dispatches(Base): # class APICalls(Base): # class CurrentDispatches(Base): # class Runs(Base): # def get_from_code(cls, session, code): # def create_new_agency_type(cls, session, code, description): # def get_from_guid(cls, session, guid): # def create_new_agency(cls, session, agency_code, agency_name, # type_id, description, website): # def get_all(cls, session): # def get_from_dispatch_text(cls, session, dispatch_text): # def create_new_dispatch_type(cls, session, dispatch_text, description): # def get_all(cls, session): # def get_from_dispatch_text(cls, session, dispatch_text): # def create_new_status(cls, session, status_text, description): # def get_from_status_text(cls, session, status_text): # def create_new_incident(cls, session, dispatch_text): # def get_count(cls, session): # def check_exists(cls, session, guid, status_text): # def add_dispatch(cls, session, run_id, status_text, short_address, # guid, dispatch_text, dispatch_datetime, source_lat, source_lng, # geocode_lat, geocode_lng, full_address, geocode_successful): # def get_by_guid(cls, session, guid): # def close_dispatch(cls, session, run_id, guid): # def get_by_date(cls, session, target_datetime, start, count): # def get_count_by_date(cls, session, target_datetime): # def add_api_call(cls, session, api_key, query_time, api_call, api_version): # def get_count(cls, session): # def add_current_dispatch(cls, session, guid): # def get_current_dispatch_guids(cls, session): # def remove_current_dispatch(cls, session, guid): # def get_count(cls, session): # def new_run(cls, session): # def update_run(cls, session, run, successful, error_text, new_dispatches): . Output only the next line.
response['current_dispatch_count'] = CurrentDispatches.get_count(DBSession)
Using the snippet: <|code_start|>@view_config(route_name='browse', renderer='templates/browse.mak') def browse(request): return {} @view_config(route_name='search', renderer='templates/search.mak') def search(request): return {} @view_config(route_name='about', renderer='templates/about.mak') def about(request): return {} @view_config(route_name='status', renderer='templates/status.mak') def status(request): return {} @view_config(route_name='status.json') def status_json(request): """ Returns the status of the system """ response = {'success': False} try: response['dispatch_count'] = Dispatches.get_count(DBSession) response['current_dispatch_count'] = CurrentDispatches.get_count(DBSession) <|code_end|> , determine the next line of code. You have imports: import os import json import datetime from pyramid.response import Response from pyramid.view import view_config from sqlalchemy.exc import DBAPIError from .models import ( DBSession, Users, AgencyTypes, Agencies, DispatchTypes, Groups, GroupDispatchTypes, Statuses, Incidents, IncidentsDispatches, Dispatches, APICalls, CurrentDispatches, Runs, ) and context (class names, function names, or code) available: # Path: src/mcsafetyfeed-server/mcsafetyfeedserver/models.py # class Users(Base): # class AgencyTypes(Base): # class Agencies(Base): # class DispatchTypes(Base): # class Groups(Base): # class GroupDispatchTypes(Base): # class Statuses(Base): # class Incidents(Base): # class IncidentsDispatches(Base): # class Dispatches(Base): # class APICalls(Base): # class CurrentDispatches(Base): # class Runs(Base): # def get_from_code(cls, session, code): # def create_new_agency_type(cls, session, code, description): # def get_from_guid(cls, session, guid): # def create_new_agency(cls, session, agency_code, agency_name, # type_id, description, website): # def get_all(cls, session): # def get_from_dispatch_text(cls, session, dispatch_text): # def create_new_dispatch_type(cls, session, dispatch_text, description): # def get_all(cls, session): # def get_from_dispatch_text(cls, session, dispatch_text): # def create_new_status(cls, session, status_text, description): # def get_from_status_text(cls, session, status_text): # def create_new_incident(cls, session, dispatch_text): # def get_count(cls, session): # def check_exists(cls, session, guid, status_text): # def add_dispatch(cls, session, run_id, status_text, short_address, # guid, dispatch_text, dispatch_datetime, source_lat, source_lng, # geocode_lat, geocode_lng, full_address, geocode_successful): # def get_by_guid(cls, session, guid): # def close_dispatch(cls, session, run_id, guid): # def get_by_date(cls, session, target_datetime, start, count): # def get_count_by_date(cls, session, target_datetime): # def add_api_call(cls, session, api_key, query_time, api_call, api_version): # def get_count(cls, session): # def add_current_dispatch(cls, session, guid): # def get_current_dispatch_guids(cls, session): # def remove_current_dispatch(cls, session, guid): # def get_count(cls, session): # def new_run(cls, session): # def update_run(cls, session, run, successful, error_text, new_dispatches): . Output only the next line.
response['run_count'] = Runs.get_count(DBSession)
Given the following code snippet before the placeholder: <|code_start|> class TestMyViewSuccessCondition(unittest.TestCase): def setUp(self): self.config = testing.setUp() engine = create_engine('sqlite://') <|code_end|> , predict the next line using imports from the current file: import unittest import transaction from pyramid import testing from .models import DBSession from sqlalchemy import create_engine from .models import ( Base, MyModel, ) from .views import my_view from sqlalchemy import create_engine from .models import ( Base, MyModel, ) from .views import my_view and context including class names, function names, and sometimes code from other files: # Path: src/mcsafetyfeed-server/mcsafetyfeedserver/models.py # class Users(Base): # class AgencyTypes(Base): # class Agencies(Base): # class DispatchTypes(Base): # class Groups(Base): # class GroupDispatchTypes(Base): # class Statuses(Base): # class Incidents(Base): # class IncidentsDispatches(Base): # class Dispatches(Base): # class APICalls(Base): # class CurrentDispatches(Base): # class Runs(Base): # def get_from_code(cls, session, code): # def create_new_agency_type(cls, session, code, description): # def get_from_guid(cls, session, guid): # def create_new_agency(cls, session, agency_code, agency_name, # type_id, description, website): # def get_all(cls, session): # def get_from_dispatch_text(cls, session, dispatch_text): # def create_new_dispatch_type(cls, session, dispatch_text, description): # def get_all(cls, session): # def get_from_dispatch_text(cls, session, dispatch_text): # def create_new_status(cls, session, status_text, description): # def get_from_status_text(cls, session, status_text): # def create_new_incident(cls, session, dispatch_text): # def get_count(cls, session): # def check_exists(cls, session, guid, status_text): # def add_dispatch(cls, session, run_id, status_text, short_address, # guid, dispatch_text, dispatch_datetime, source_lat, source_lng, # geocode_lat, geocode_lng, full_address, geocode_successful): # def get_by_guid(cls, session, guid): # def close_dispatch(cls, session, run_id, guid): # def get_by_date(cls, session, target_datetime, start, count): # def get_count_by_date(cls, session, target_datetime): # def add_api_call(cls, session, api_key, query_time, api_call, api_version): # def get_count(cls, session): # def add_current_dispatch(cls, session, guid): # def get_current_dispatch_guids(cls, session): # def remove_current_dispatch(cls, session, guid): # def get_count(cls, session): # def new_run(cls, session): # def update_run(cls, session, run, successful, error_text, new_dispatches): . Output only the next line.
DBSession.configure(bind=engine)
Continue the code snippet: <|code_start|># All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. 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. # # 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__) def test_call_requests(): try: <|code_end|> . Use current file imports: import logging import ninchat.call from ninchat.call.requests import check_call and context (classes, functions, or code) from other files: # Path: ninchat/call/requests.py # def check_call(params, **kwargs): # # type: (params: Dict[str, Any], *, session: Optional[requests.Session]=None, identity: Optional[Dict[str, str]]=None) -> Dict[str, Any] # """Like call with check set.""" # return call(params, check=True, **kwargs) . Output only the next line.
event = check_call({"action": "nonexistent_action"})
Given the code snippet: <|code_start|># Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. 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. # # 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__) async def async_test(): async with aiohttp.ClientSession() as s: try: <|code_end|> , generate the next line using the imports in this file: import asyncio import logging import aiohttp import ninchat.call from ninchat.call.aiohttp import check_call and context (functions, classes, or occasionally code) from other files: # Path: ninchat/call/aiohttp.py # @asyncio.coroutine # def check_call(session: aiohttp.ClientSession, # params: Dict[str, Any], # *, # identity: Optional[Dict[str, str]] = None # ) -> Dict[str, Any]: # """Like call with check set.""" # return call(session, params, identity=identity, check=True) . Output only the next line.
event = await check_call(s, {"action": "nonexistent_action"})
Given the following code snippet before the placeholder: <|code_start|># notice, this list of conditions and the following disclaimer. # 2. 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. # # 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__) async def async_test(): def on_session_event(params): pass def on_event(params, payload, last_reply): if params["event"] == "message_received": log.debug("received %s", payload[0].decode()) <|code_end|> , predict the next line using imports from the current file: import asyncio import logging from functools import partial from ninchat.client.asyncio import Session and context including class names, function names, and sometimes code from other files: # Path: ninchat/client/asyncio.py # class Session(BaseSession): # """A version of ninchat.client.Session which executes callbacks # in the asyncio event loop. # # .. attribute:: opened # # A future which provides the session_created event's parameters once the # session has been created (for the first time). # # .. attribute:: closed # # A future which will be marked as done once the session closing is # complete. # """ # # def __init__(self, *, loop=None): # # type: (Optional[asyncio.AbstractEventLoop]) -> None # # super().__init__() # # self.loop = loop or asyncio.get_event_loop() # self.opened = _create_future(loop=self.loop) # self.closed = _create_future(loop=self.loop) # self._closing = False # # def __aenter__(self): # if self.state == "uninitialized": # self.open() # return self.opened # # def __aexit__(self, *exc): # if not self._closing: # self.close() # return self.closed # # def open(self, on_reply=None): # # type: (Optional[Callable[[Dict[str, Any]], None]]) -> asyncio.Future # """Like ninchat.client.Session.open(), but returns a # future. The on_reply callback is supported for interface # compatibility.""" # # def callback(params): # if params is None: # self.opened.cancel() # else: # self.opened.set_result(params) # # if on_reply: # on_reply(params) # # super().open(callback) # return self.opened # # def close(self): # # type: () -> asyncio.Future # """Like ninchat.client.Session.close(), but returns a # future.""" # # super().close() # self._closing = True # return self.closed # # def call(self, params, payload=None, on_reply=None): # # type: (Dict[str,Any], Optional[Sequence[ByteString]], Optional[Callable[[Dict[str,Any], List[bytes], bool], None]]) -> asyncio.Future # """An awaitable version of ninchat.client.Session.send(). # Returns the final reply event's params and payload.""" # # f = _create_future(loop=self.loop) # # def callback(params, payload, last_reply): # if params is None: # f.cancel() # else: # try: # if on_reply is not None: # on_reply(params, payload, last_reply) # finally: # if last_reply: # f.set_result((params, payload)) # # self.send(params, payload, callback) # return f # # def _handle_close(self): # try: # super()._handle_close() # finally: # self.closed.set_result(None) # # def _call(self, call, *args): # self.loop.call_soon_threadsafe(call, *args) . Output only the next line.
s = Session()
Using the snippet: <|code_start|> matplotlib.use('Agg') saveflag = True dim = 4 class MSTest(unittest.TestCase): def test_MSstatistics(self): <|code_end|> , determine the next line of code. You have imports: import unittest import numpy as np import matplotlib import matplotlib.pyplot as plt from sprocket.model import MS from sprocket.util import low_pass_filter and context (class names, function names, or code) available: # Path: sprocket/model/ms.py # class MS (object): # """A modulation spectrum (MS) statistics class # Estimate statistics and perform postfilter based on # the MS statistics # # """ # # def __init__(self): # pass # # def estimate(self, datalist): # """Estimate MS statistics from list of data # # Parameters # ---------- # datalist : list, shape ('num_data') # List of several data ([T, dim]) sequence # # Returns # ------- # msstats : array, shape (`dim * 2`, `fftsize // 2 + 1`) # Mean and variance of MS # """ # # # get max length in all data and define fft length # maxlen = np.max(list(map(lambda x: x.shape[0], datalist))) # n_bit = len(bin(maxlen)) - 2 # self.fftsize = 2 ** (n_bit + 1) # # mss = [] # for data in datalist: # logpowerspec = self.logpowerspec(data) # mss.append(logpowerspec) # # # calculate mean and variance in each freq. bin # msm = np.mean(np.array(mss), axis=0) # msv = np.var(np.array(mss), axis=0) # return np.hstack([msm, msv]) # # def postfilter(self, data, msstats, cvmsstats, alpha=1.0, k=0.85, startdim=1): # """Perform postfilter based on MS statistics to data # # Parameters # ---------- # data : array, shape (`T`, `dim`) # Array of data sequence # msstats : array, shape (`dim * 2`, `fftsize // 2 + 1`) # Array of mean and variance for target MS # cvmsstats : array, shape (`dim * 2`, `fftsize // 2 + 1`) # Array of mean and variance for converted MS # This option replaces the mean variance of the given data # into the mean variance estimated from training data. # alpha : float, optional # Morphing coefficient between MS transformed data and data. # .. math:: # alpha * mspf(data) + (1 - alpha) * data # Default set to 1.0 # k : float, optional # Postfilter emphasis coefficient [0 <= k <= 1] # Default set to 1.0 # startdim : int, optional # Start dimension to perform MS postfilter [1 < startdim < dim] # # Returns # ------- # filtered_data : array, shape (`T`, `data`) # Array of MS postfiltered data sequence # """ # # # get length and dimension # T, dim = data.shape # self.fftsize = msstats.shape[0] # assert dim == msstats.shape[1] // 2 # # # create zero padded data # logpowerspec, phasespec = self.logpowerspec(data, phase=True) # msed_logpowerspec = (1 - k) * logpowerspec + \ # k * (np.sqrt((msstats / cvmsstats)[:, dim:]) * # (logpowerspec - cvmsstats[:, :dim]) + msstats[:, :dim]) # # # reconstruct # reconst_complexspec = np.exp(msed_logpowerspec / 2) * (np.cos(phasespec) + # np.sin(phasespec) * 1j) # filtered_data = np.fft.ifftn(reconst_complexspec)[:T].real # # if startdim == 1: # filtered_data[:, 0] = data[:, 0] # # # apply morphing # filtered_data = alpha * filtered_data + (1 - alpha) * data # # return filtered_data # # def logpowerspec(self, data, phase=False): # """Calculate log power spectrum in each dimension # # Parameters # ---------- # data : array, shape (`T`, `dim`) # Array of data sequence # # Returns # ------- # logpowerspec : array, shape (`dim`, `fftsize // 2 + 1`) # Log power spectrum of sequence # phasespec : array, shape (`dim`, `fftsize // 2 + 1`), optional # Phase spectrum of sequences # """ # # # create zero padded data # T, dim = data.shape # padded_data = np.zeros((self.fftsize, dim)) # padded_data[:T] += data # # # calculate log power spectum of data # complex_spec = np.fft.fftn(padded_data, axes=(0, 1)) # logpowerspec = 2 * np.log(np.absolute(complex_spec)) # # if phase: # phasespec = np.angle(complex_spec) # return logpowerspec, phasespec # else: # return logpowerspec # # Path: sprocket/util/filter.py # def low_pass_filter(data, cutoff, fs, n_taps=255): # """Apply low-pass filter # # Parameters # ---------- # data : array, shape (`T`, `dim`) # Array of sequence. # cutoff : int, # Cutoff frequency # fs : int, # Sampling frequency # n_taps : int, optional # Tap number # # Returns # ------- # modified data: array, shape (`T`, `dim`) # Array of modified sequence. # """ # if data.shape[0] < n_taps * 3: # raise ValueError( # 'Length of data should be three times longer than n_taps.') # # fil = firwin(n_taps, cutoff, pass_zero=True, nyq=fs//2) # modified_data = filtfilt(fil, 1, data, axis=0) # return modified_data . Output only the next line.
ms = MS()