Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Predict the next line after this snippet: <|code_start|>class PostgresModelPartitioningPlan: """Describes the partitions that are going to be created/deleted for a particular partitioning config. A "partitioning config" applies to one model. """ config: PostgresPartitioningConfig creations: List[PostgresPartition] = field(default_factory=list) deletions: List[PostgresPartition] = field(default_factory=list) def apply(self, using: Optional[str]) -> None: """Applies this partitioning plan by creating and deleting the planned partitions. Applying the plan runs in a transaction. Arguments: using: Name of the database connection to use. """ connection = connections[using or "default"] with transaction.atomic(): with connection.schema_editor() as schema_editor: for partition in self.creations: partition.create( self.config.model, schema_editor, <|code_end|> using the current file's imports: from dataclasses import dataclass, field from typing import List, Optional from django.db import connections, transaction from .config import PostgresPartitioningConfig from .constants import AUTO_PARTITIONED_COMMENT from .partition import PostgresPartition and any relevant context from other files: # Path: psqlextra/partitioning/config.py # class PostgresPartitioningConfig: # """Configuration for partitioning a specific model according to the # specified strategy.""" # # def __init__( # self, # model: PostgresPartitionedModel, # strategy: PostgresPartitioningStrategy, # ) -> None: # self.model = model # self.strategy = strategy # # Path: psqlextra/partitioning/constants.py # AUTO_PARTITIONED_COMMENT = "psqlextra_auto_partitioned" # # Path: psqlextra/partitioning/partition.py # class PostgresPartition: # """Base class for a PostgreSQL table partition.""" # # @abstractmethod # def name(self) -> str: # """Generates/computes the name for this partition.""" # # @abstractmethod # def create( # self, # model: PostgresPartitionedModel, # schema_editor: PostgresSchemaEditor, # comment: Optional[str] = None, # ) -> None: # """Creates this partition in the database.""" # # @abstractmethod # def delete( # self, # model: PostgresPartitionedModel, # schema_editor: PostgresSchemaEditor, # ) -> None: # """Deletes this partition from the database.""" # # def deconstruct(self) -> dict: # """Deconstructs this partition into a dict of attributes/fields.""" # # return {"name": self.name()} . Output only the next line.
comment=AUTO_PARTITIONED_COMMENT,
Based on the snippet: <|code_start|> @dataclass class PostgresModelPartitioningPlan: """Describes the partitions that are going to be created/deleted for a particular partitioning config. A "partitioning config" applies to one model. """ config: PostgresPartitioningConfig <|code_end|> , predict the immediate next line with the help of imports: from dataclasses import dataclass, field from typing import List, Optional from django.db import connections, transaction from .config import PostgresPartitioningConfig from .constants import AUTO_PARTITIONED_COMMENT from .partition import PostgresPartition and context (classes, functions, sometimes code) from other files: # Path: psqlextra/partitioning/config.py # class PostgresPartitioningConfig: # """Configuration for partitioning a specific model according to the # specified strategy.""" # # def __init__( # self, # model: PostgresPartitionedModel, # strategy: PostgresPartitioningStrategy, # ) -> None: # self.model = model # self.strategy = strategy # # Path: psqlextra/partitioning/constants.py # AUTO_PARTITIONED_COMMENT = "psqlextra_auto_partitioned" # # Path: psqlextra/partitioning/partition.py # class PostgresPartition: # """Base class for a PostgreSQL table partition.""" # # @abstractmethod # def name(self) -> str: # """Generates/computes the name for this partition.""" # # @abstractmethod # def create( # self, # model: PostgresPartitionedModel, # schema_editor: PostgresSchemaEditor, # comment: Optional[str] = None, # ) -> None: # """Creates this partition in the database.""" # # @abstractmethod # def delete( # self, # model: PostgresPartitionedModel, # schema_editor: PostgresSchemaEditor, # ) -> None: # """Deletes this partition from the database.""" # # def deconstruct(self) -> dict: # """Deconstructs this partition into a dict of attributes/fields.""" # # return {"name": self.name()} . Output only the next line.
creations: List[PostgresPartition] = field(default_factory=list)
Using the snippet: <|code_start|> index_1 = CaseInsensitiveUniqueIndex( fields=["name", "other_name"], name="index1" ) ops = [ CreateModel( name="mymodel", fields=[ ("name", models.CharField(max_length=255)), ("other_name", models.CharField(max_length=255)), ], ), AddIndex(model_name="mymodel", index=index_1), ] with filtered_schema_editor("CREATE UNIQUE INDEX") as calls: apply_migration(ops) sql = str([call[0] for _, call, _ in calls["CREATE UNIQUE INDEX"]][0]) expected_sql = 'CREATE UNIQUE INDEX "index1" ON "tests_mymodel" (LOWER("name"), LOWER("other_name"))' assert sql == expected_sql def test_ciui(): """Tests whether the case insensitive unique index works as expected.""" index_1 = CaseInsensitiveUniqueIndex(fields=["name"], name="index1") model = get_fake_model( <|code_end|> , determine the next line of code. You have imports: import pytest from django.db import IntegrityError, connection, models from django.db.migrations import AddIndex, CreateModel from psqlextra.indexes import CaseInsensitiveUniqueIndex from psqlextra.models import PostgresModel from .fake_model import get_fake_model from .migrations import apply_migration, filtered_schema_editor and context (class names, function names, or code) available: # Path: psqlextra/indexes/case_insensitive_unique_index.py # class CaseInsensitiveUniqueIndex(Index): # sql_create_unique_index = ( # "CREATE UNIQUE INDEX %(name)s ON %(table)s (%(columns)s)%(extra)s" # ) # # def create_sql(self, model, schema_editor, using="", **kwargs): # statement = super().create_sql(model, schema_editor, using) # statement.template = self.sql_create_unique_index # # column_collection = statement.parts["columns"] # statement.parts["columns"] = ", ".join( # [ # "LOWER(%s)" % self._quote_column(column_collection, column, idx) # for idx, column in enumerate(column_collection.columns) # ] # ) # # return statement # # def deconstruct(self): # """Serializes the :see:CaseInsensitiveUniqueIndex for the migrations # file.""" # _, args, kwargs = super().deconstruct() # path = "%s.%s" % (self.__class__.__module__, self.__class__.__name__) # path = path.replace("django.db.models.indexes", "django.db.models") # # return path, args, kwargs # # @staticmethod # def _quote_column(column_collection, column, idx): # quoted_name = column_collection.quote_name(column) # try: # return quoted_name + column_collection.col_suffixes[idx] # except IndexError: # return column_collection.quote_name(column) # # Path: psqlextra/models/base.py # class PostgresModel(models.Model): # """Base class for for taking advantage of PostgreSQL specific features.""" # # class Meta: # abstract = True # base_manager_name = "objects" # # objects = PostgresManager() # # Path: tests/fake_model.py # def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}): # """Defines a fake model and creates it in the database.""" # # model = define_fake_model(fields, model_base, meta_options) # # with connection.schema_editor() as schema_editor: # schema_editor.create_model(model) # # return model # # Path: tests/migrations.py # def apply_migration(operations, state=None, backwards: bool = False): # """Executes the specified migration operations using the specified schema # editor. # # Arguments: # operations: # The migration operations to execute. # # state: # The state state to use during the # migrations. # # backwards: # Whether to apply the operations # in reverse (backwards). # """ # # state = state or migrations.state.ProjectState.from_apps(apps) # # class Migration(migrations.Migration): # pass # # Migration.operations = operations # # migration = Migration("migration", "tests") # executor = MigrationExecutor(connection) # # if not backwards: # executor.apply_migration(state, migration) # else: # executor.unapply_migration(state, migration) # # return migration # # @contextmanager # def filtered_schema_editor(*filters: List[str]): # """Gets a schema editor, but filters executed SQL statements based on the # specified text filters. # # Arguments: # filters: # List of strings to filter SQL # statements on. # """ # # with connection.schema_editor() as schema_editor: # wrapper_for = schema_editor.execute # with mock.patch.object( # PostgresSchemaEditor, "execute", wraps=wrapper_for # ) as execute: # filter_results = {} # yield filter_results # # for filter_text in filters: # filter_results[filter_text] = [ # call for call in execute.mock_calls if filter_text in str(call) # ] . Output only the next line.
{"name": models.CharField(max_length=255)}, PostgresModel
Continue the code snippet: <|code_start|> expected.""" index_1 = CaseInsensitiveUniqueIndex( fields=["name", "other_name"], name="index1" ) ops = [ CreateModel( name="mymodel", fields=[ ("name", models.CharField(max_length=255)), ("other_name", models.CharField(max_length=255)), ], ), AddIndex(model_name="mymodel", index=index_1), ] with filtered_schema_editor("CREATE UNIQUE INDEX") as calls: apply_migration(ops) sql = str([call[0] for _, call, _ in calls["CREATE UNIQUE INDEX"]][0]) expected_sql = 'CREATE UNIQUE INDEX "index1" ON "tests_mymodel" (LOWER("name"), LOWER("other_name"))' assert sql == expected_sql def test_ciui(): """Tests whether the case insensitive unique index works as expected.""" index_1 = CaseInsensitiveUniqueIndex(fields=["name"], name="index1") <|code_end|> . Use current file imports: import pytest from django.db import IntegrityError, connection, models from django.db.migrations import AddIndex, CreateModel from psqlextra.indexes import CaseInsensitiveUniqueIndex from psqlextra.models import PostgresModel from .fake_model import get_fake_model from .migrations import apply_migration, filtered_schema_editor and context (classes, functions, or code) from other files: # Path: psqlextra/indexes/case_insensitive_unique_index.py # class CaseInsensitiveUniqueIndex(Index): # sql_create_unique_index = ( # "CREATE UNIQUE INDEX %(name)s ON %(table)s (%(columns)s)%(extra)s" # ) # # def create_sql(self, model, schema_editor, using="", **kwargs): # statement = super().create_sql(model, schema_editor, using) # statement.template = self.sql_create_unique_index # # column_collection = statement.parts["columns"] # statement.parts["columns"] = ", ".join( # [ # "LOWER(%s)" % self._quote_column(column_collection, column, idx) # for idx, column in enumerate(column_collection.columns) # ] # ) # # return statement # # def deconstruct(self): # """Serializes the :see:CaseInsensitiveUniqueIndex for the migrations # file.""" # _, args, kwargs = super().deconstruct() # path = "%s.%s" % (self.__class__.__module__, self.__class__.__name__) # path = path.replace("django.db.models.indexes", "django.db.models") # # return path, args, kwargs # # @staticmethod # def _quote_column(column_collection, column, idx): # quoted_name = column_collection.quote_name(column) # try: # return quoted_name + column_collection.col_suffixes[idx] # except IndexError: # return column_collection.quote_name(column) # # Path: psqlextra/models/base.py # class PostgresModel(models.Model): # """Base class for for taking advantage of PostgreSQL specific features.""" # # class Meta: # abstract = True # base_manager_name = "objects" # # objects = PostgresManager() # # Path: tests/fake_model.py # def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}): # """Defines a fake model and creates it in the database.""" # # model = define_fake_model(fields, model_base, meta_options) # # with connection.schema_editor() as schema_editor: # schema_editor.create_model(model) # # return model # # Path: tests/migrations.py # def apply_migration(operations, state=None, backwards: bool = False): # """Executes the specified migration operations using the specified schema # editor. # # Arguments: # operations: # The migration operations to execute. # # state: # The state state to use during the # migrations. # # backwards: # Whether to apply the operations # in reverse (backwards). # """ # # state = state or migrations.state.ProjectState.from_apps(apps) # # class Migration(migrations.Migration): # pass # # Migration.operations = operations # # migration = Migration("migration", "tests") # executor = MigrationExecutor(connection) # # if not backwards: # executor.apply_migration(state, migration) # else: # executor.unapply_migration(state, migration) # # return migration # # @contextmanager # def filtered_schema_editor(*filters: List[str]): # """Gets a schema editor, but filters executed SQL statements based on the # specified text filters. # # Arguments: # filters: # List of strings to filter SQL # statements on. # """ # # with connection.schema_editor() as schema_editor: # wrapper_for = schema_editor.execute # with mock.patch.object( # PostgresSchemaEditor, "execute", wraps=wrapper_for # ) as execute: # filter_results = {} # yield filter_results # # for filter_text in filters: # filter_results[filter_text] = [ # call for call in execute.mock_calls if filter_text in str(call) # ] . Output only the next line.
model = get_fake_model(
Given snippet: <|code_start|> def test_ciui_migrations(): """Tests whether migrations for case sensitive indexes are being created as expected.""" index_1 = CaseInsensitiveUniqueIndex( fields=["name", "other_name"], name="index1" ) ops = [ CreateModel( name="mymodel", fields=[ ("name", models.CharField(max_length=255)), ("other_name", models.CharField(max_length=255)), ], ), AddIndex(model_name="mymodel", index=index_1), ] with filtered_schema_editor("CREATE UNIQUE INDEX") as calls: <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest from django.db import IntegrityError, connection, models from django.db.migrations import AddIndex, CreateModel from psqlextra.indexes import CaseInsensitiveUniqueIndex from psqlextra.models import PostgresModel from .fake_model import get_fake_model from .migrations import apply_migration, filtered_schema_editor and context: # Path: psqlextra/indexes/case_insensitive_unique_index.py # class CaseInsensitiveUniqueIndex(Index): # sql_create_unique_index = ( # "CREATE UNIQUE INDEX %(name)s ON %(table)s (%(columns)s)%(extra)s" # ) # # def create_sql(self, model, schema_editor, using="", **kwargs): # statement = super().create_sql(model, schema_editor, using) # statement.template = self.sql_create_unique_index # # column_collection = statement.parts["columns"] # statement.parts["columns"] = ", ".join( # [ # "LOWER(%s)" % self._quote_column(column_collection, column, idx) # for idx, column in enumerate(column_collection.columns) # ] # ) # # return statement # # def deconstruct(self): # """Serializes the :see:CaseInsensitiveUniqueIndex for the migrations # file.""" # _, args, kwargs = super().deconstruct() # path = "%s.%s" % (self.__class__.__module__, self.__class__.__name__) # path = path.replace("django.db.models.indexes", "django.db.models") # # return path, args, kwargs # # @staticmethod # def _quote_column(column_collection, column, idx): # quoted_name = column_collection.quote_name(column) # try: # return quoted_name + column_collection.col_suffixes[idx] # except IndexError: # return column_collection.quote_name(column) # # Path: psqlextra/models/base.py # class PostgresModel(models.Model): # """Base class for for taking advantage of PostgreSQL specific features.""" # # class Meta: # abstract = True # base_manager_name = "objects" # # objects = PostgresManager() # # Path: tests/fake_model.py # def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}): # """Defines a fake model and creates it in the database.""" # # model = define_fake_model(fields, model_base, meta_options) # # with connection.schema_editor() as schema_editor: # schema_editor.create_model(model) # # return model # # Path: tests/migrations.py # def apply_migration(operations, state=None, backwards: bool = False): # """Executes the specified migration operations using the specified schema # editor. # # Arguments: # operations: # The migration operations to execute. # # state: # The state state to use during the # migrations. # # backwards: # Whether to apply the operations # in reverse (backwards). # """ # # state = state or migrations.state.ProjectState.from_apps(apps) # # class Migration(migrations.Migration): # pass # # Migration.operations = operations # # migration = Migration("migration", "tests") # executor = MigrationExecutor(connection) # # if not backwards: # executor.apply_migration(state, migration) # else: # executor.unapply_migration(state, migration) # # return migration # # @contextmanager # def filtered_schema_editor(*filters: List[str]): # """Gets a schema editor, but filters executed SQL statements based on the # specified text filters. # # Arguments: # filters: # List of strings to filter SQL # statements on. # """ # # with connection.schema_editor() as schema_editor: # wrapper_for = schema_editor.execute # with mock.patch.object( # PostgresSchemaEditor, "execute", wraps=wrapper_for # ) as execute: # filter_results = {} # yield filter_results # # for filter_text in filters: # filter_results[filter_text] = [ # call for call in execute.mock_calls if filter_text in str(call) # ] which might include code, classes, or functions. Output only the next line.
apply_migration(ops)
Given snippet: <|code_start|> def test_ciui_migrations(): """Tests whether migrations for case sensitive indexes are being created as expected.""" index_1 = CaseInsensitiveUniqueIndex( fields=["name", "other_name"], name="index1" ) ops = [ CreateModel( name="mymodel", fields=[ ("name", models.CharField(max_length=255)), ("other_name", models.CharField(max_length=255)), ], ), AddIndex(model_name="mymodel", index=index_1), ] <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest from django.db import IntegrityError, connection, models from django.db.migrations import AddIndex, CreateModel from psqlextra.indexes import CaseInsensitiveUniqueIndex from psqlextra.models import PostgresModel from .fake_model import get_fake_model from .migrations import apply_migration, filtered_schema_editor and context: # Path: psqlextra/indexes/case_insensitive_unique_index.py # class CaseInsensitiveUniqueIndex(Index): # sql_create_unique_index = ( # "CREATE UNIQUE INDEX %(name)s ON %(table)s (%(columns)s)%(extra)s" # ) # # def create_sql(self, model, schema_editor, using="", **kwargs): # statement = super().create_sql(model, schema_editor, using) # statement.template = self.sql_create_unique_index # # column_collection = statement.parts["columns"] # statement.parts["columns"] = ", ".join( # [ # "LOWER(%s)" % self._quote_column(column_collection, column, idx) # for idx, column in enumerate(column_collection.columns) # ] # ) # # return statement # # def deconstruct(self): # """Serializes the :see:CaseInsensitiveUniqueIndex for the migrations # file.""" # _, args, kwargs = super().deconstruct() # path = "%s.%s" % (self.__class__.__module__, self.__class__.__name__) # path = path.replace("django.db.models.indexes", "django.db.models") # # return path, args, kwargs # # @staticmethod # def _quote_column(column_collection, column, idx): # quoted_name = column_collection.quote_name(column) # try: # return quoted_name + column_collection.col_suffixes[idx] # except IndexError: # return column_collection.quote_name(column) # # Path: psqlextra/models/base.py # class PostgresModel(models.Model): # """Base class for for taking advantage of PostgreSQL specific features.""" # # class Meta: # abstract = True # base_manager_name = "objects" # # objects = PostgresManager() # # Path: tests/fake_model.py # def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}): # """Defines a fake model and creates it in the database.""" # # model = define_fake_model(fields, model_base, meta_options) # # with connection.schema_editor() as schema_editor: # schema_editor.create_model(model) # # return model # # Path: tests/migrations.py # def apply_migration(operations, state=None, backwards: bool = False): # """Executes the specified migration operations using the specified schema # editor. # # Arguments: # operations: # The migration operations to execute. # # state: # The state state to use during the # migrations. # # backwards: # Whether to apply the operations # in reverse (backwards). # """ # # state = state or migrations.state.ProjectState.from_apps(apps) # # class Migration(migrations.Migration): # pass # # Migration.operations = operations # # migration = Migration("migration", "tests") # executor = MigrationExecutor(connection) # # if not backwards: # executor.apply_migration(state, migration) # else: # executor.unapply_migration(state, migration) # # return migration # # @contextmanager # def filtered_schema_editor(*filters: List[str]): # """Gets a schema editor, but filters executed SQL statements based on the # specified text filters. # # Arguments: # filters: # List of strings to filter SQL # statements on. # """ # # with connection.schema_editor() as schema_editor: # wrapper_for = schema_editor.execute # with mock.patch.object( # PostgresSchemaEditor, "execute", wraps=wrapper_for # ) as execute: # filter_results = {} # yield filter_results # # for filter_text in filters: # filter_results[filter_text] = [ # call for call in execute.mock_calls if filter_text in str(call) # ] which might include code, classes, or functions. Output only the next line.
with filtered_schema_editor("CREATE UNIQUE INDEX") as calls:
Given snippet: <|code_start|> class PostgresTimePartitioningStrategy(PostgresCurrentTimePartitioningStrategy): def __init__( self, start_datetime: datetime, <|code_end|> , continue by predicting the next line. Consider current file imports: from datetime import datetime from typing import Optional from dateutil.relativedelta import relativedelta from .current_time_strategy import PostgresCurrentTimePartitioningStrategy from .time_partition_size import PostgresTimePartitionSize and context: # Path: psqlextra/partitioning/current_time_strategy.py # class PostgresCurrentTimePartitioningStrategy( # PostgresRangePartitioningStrategy # ): # """Implments a time based partitioning strategy where each partition # contains values for a specific time period. # # All buckets will be equal in size and start at the start of the # unit. With monthly partitioning, partitions start on the 1st and # with weekly partitioning, partitions start on monday. # """ # # def __init__( # self, # size: PostgresTimePartitionSize, # count: int, # max_age: Optional[relativedelta] = None, # ) -> None: # """Initializes a new instance of :see:PostgresTimePartitioningStrategy. # # Arguments: # size: # The size of each partition. # # count: # The amount of partitions to create ahead # from the current date/time. # # max_age: # Maximum age of a partition. Partitions # older than this are deleted during # auto cleanup. # """ # # self.size = size # self.count = count # self.max_age = max_age # # def to_create(self) -> Generator[PostgresTimePartition, None, None]: # current_datetime = self.size.start(self.get_start_datetime()) # # for _ in range(self.count): # yield PostgresTimePartition( # start_datetime=current_datetime, size=self.size # ) # # current_datetime += self.size.as_delta() # # def to_delete(self) -> Generator[PostgresTimePartition, None, None]: # if not self.max_age: # return # # current_datetime = self.size.start( # self.get_start_datetime() - self.max_age # ) # # while True: # yield PostgresTimePartition( # start_datetime=current_datetime, size=self.size # ) # # current_datetime -= self.size.as_delta() # # def get_start_datetime(self) -> datetime: # return datetime.now(timezone.utc) # # Path: psqlextra/partitioning/time_partition_size.py # class PostgresTimePartitionSize: # """Size of a time-based range partition table.""" # # unit: PostgresTimePartitionUnit # value: int # # def __init__( # self, # years: Optional[int] = None, # months: Optional[int] = None, # weeks: Optional[int] = None, # days: Optional[int] = None, # ) -> None: # sizes = [years, months, weeks, days] # # if not any(sizes): # raise PostgresPartitioningError("Partition cannot be 0 in size.") # # if len([size for size in sizes if size and size > 0]) > 1: # raise PostgresPartitioningError( # "Partition can only have on size unit." # ) # # if years: # self.unit = PostgresTimePartitionUnit.YEARS # self.value = years # elif months: # self.unit = PostgresTimePartitionUnit.MONTHS # self.value = months # elif weeks: # self.unit = PostgresTimePartitionUnit.WEEKS # self.value = weeks # elif days: # self.unit = PostgresTimePartitionUnit.DAYS # self.value = days # else: # raise PostgresPartitioningError( # "Unsupported time partitioning unit" # ) # # def as_delta(self) -> relativedelta: # if self.unit == PostgresTimePartitionUnit.YEARS: # return relativedelta(years=self.value) # # if self.unit == PostgresTimePartitionUnit.MONTHS: # return relativedelta(months=self.value) # # if self.unit == PostgresTimePartitionUnit.WEEKS: # return relativedelta(weeks=self.value) # # if self.unit == PostgresTimePartitionUnit.DAYS: # return relativedelta(days=self.value) # # raise PostgresPartitioningError( # "Unsupported time partitioning unit: %s" % self.unit # ) # # def start(self, dt: datetime) -> datetime: # if self.unit == PostgresTimePartitionUnit.YEARS: # return self._ensure_datetime(dt.replace(month=1, day=1)) # # if self.unit == PostgresTimePartitionUnit.MONTHS: # return self._ensure_datetime(dt.replace(day=1)) # # if self.unit == PostgresTimePartitionUnit.WEEKS: # return self._ensure_datetime(dt - relativedelta(days=dt.weekday())) # # return self._ensure_datetime(dt) # # @staticmethod # def _ensure_datetime(dt: Union[date, datetime]) -> datetime: # return datetime(year=dt.year, month=dt.month, day=dt.day) # # def __repr__(self) -> str: # return "PostgresTimePartitionSize<%s, %s>" % (self.unit, self.value) which might include code, classes, or functions. Output only the next line.
size: PostgresTimePartitionSize,
Given the code snippet: <|code_start|> @contextmanager def postgres_manager(model): """Allows you to use the :see:PostgresManager with the specified model instance on the fly. Arguments: model: The model or model instance to use this on. """ <|code_end|> , generate the next line using the imports in this file: from contextlib import contextmanager from .manager import PostgresManager and context (functions, classes, or occasionally code) from other files: # Path: psqlextra/manager/manager.py # class PostgresManager(Manager.from_queryset(PostgresQuerySet)): # """Adds support for PostgreSQL specifics.""" # # use_in_migrations = True # # def __init__(self, *args, **kwargs): # """Initializes a new instance of :see:PostgresManager.""" # # super().__init__(*args, **kwargs) # # # make sure our back-end is set in at least one db and refuse to proceed # has_psqlextra_backend = any( # [ # db_settings # for db_settings in settings.DATABASES.values() # if "psqlextra" in db_settings["ENGINE"] # ] # ) # # if not has_psqlextra_backend: # raise ImproperlyConfigured( # ( # "Could not locate the 'psqlextra.backend'. " # "django-postgres-extra cannot function without " # "the 'psqlextra.backend'. Set DATABASES.ENGINE." # ) # ) # # def truncate( # self, cascade: bool = False, using: Optional[str] = None # ) -> None: # """Truncates this model/table using the TRUNCATE statement. # # This DELETES ALL ROWS. No signals will be fired. # # See: https://www.postgresql.org/docs/9.1/sql-truncate.html # # Arguments: # cascade: # Whether to delete dependent rows. If set to # False, an error will be raised if there # are rows in other tables referencing # the rows you're trying to delete. # """ # # connection = connections[using or "default"] # table_name = connection.ops.quote_name(self.model._meta.db_table) # # with connection.cursor() as cursor: # sql = "TRUNCATE TABLE %s" % table_name # if cascade: # sql += " CASCADE" # # cursor.execute(sql) . Output only the next line.
manager = PostgresManager()
Predict the next line after this snippet: <|code_start|> def test_query_annotate_hstore_key_ref(): """Tests whether annotating using a :see:HStoreRef expression works correctly. This allows you to select an individual hstore key. """ model_fk = get_fake_model({"title": HStoreField()}) model = get_fake_model( {"fk": models.ForeignKey(model_fk, on_delete=models.CASCADE)} ) fk = model_fk.objects.create(title={"en": "english", "ar": "arabic"}) model.objects.create(fk=fk) queryset = ( <|code_end|> using the current file's imports: from django.db import models from django.db.models import Case, F, Q, Value, When from psqlextra.expressions import HStoreRef from psqlextra.fields import HStoreField from .fake_model import get_fake_model and any relevant context from other files: # Path: psqlextra/expressions.py # class HStoreRef(expressions.F): # """Inline reference to a HStore key. # # Allows selecting individual keys in annotations. # """ # # def __init__(self, name: str, key: str): # """Initializes a new instance of :see:HStoreRef. # # Arguments: # name: # The name of the column/field to resolve. # # key: # The name of the HStore key to select. # """ # # super().__init__(name) # self.key = key # # def resolve_expression(self, *args, **kwargs): # """Resolves the expression into a :see:HStoreColumn expression.""" # # original_expression: expressions.Col = super().resolve_expression( # *args, **kwargs # ) # expression = HStoreColumn( # original_expression.alias, original_expression.target, self.key # ) # return expression # # Path: psqlextra/fields/hstore_field.py # class HStoreField(DjangoHStoreField): # """Improved version of Django's :see:HStoreField that adds support for # database-level constraints. # # Notes: # - For the implementation of uniqueness, see the # custom database back-end. # """ # # def __init__( # self, # *args, # uniqueness: Optional[List[Union[str, Tuple[str, ...]]]] = None, # required: Optional[List[str]] = None, # **kwargs # ): # """Initializes a new instance of :see:HStoreField. # # Arguments: # uniqueness: # List of keys to enforce as unique. Use tuples # to enforce multiple keys together to be unique. # # required: # List of keys that should be enforced as required. # """ # # super(HStoreField, self).__init__(*args, **kwargs) # # self.uniqueness = uniqueness # self.required = required # # def get_prep_value(self, value): # """Override the base class so it doesn't cast all values to strings. # # psqlextra supports expressions in hstore fields, so casting all # values to strings is a bad idea. # """ # # value = Field.get_prep_value(self, value) # # if isinstance(value, dict): # prep_value = {} # for key, val in value.items(): # if isinstance(val, Expression): # prep_value[key] = val # elif val is not None: # prep_value[key] = str(val) # else: # prep_value[key] = val # # value = prep_value # # if isinstance(value, list): # value = [str(item) for item in value] # # return value # # def deconstruct(self): # """Gets the values to pass to :see:__init__ when re-creating this # object.""" # # name, path, args, kwargs = super(HStoreField, self).deconstruct() # # if self.uniqueness is not None: # kwargs["uniqueness"] = self.uniqueness # # if self.required is not None: # kwargs["required"] = self.required # # return name, path, args, kwargs # # Path: tests/fake_model.py # def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}): # """Defines a fake model and creates it in the database.""" # # model = define_fake_model(fields, model_base, meta_options) # # with connection.schema_editor() as schema_editor: # schema_editor.create_model(model) # # return model . Output only the next line.
model.objects.annotate(english_title=HStoreRef("fk__title", "en"))
Given the following code snippet before the placeholder: <|code_start|> def test_query_annotate_hstore_key_ref(): """Tests whether annotating using a :see:HStoreRef expression works correctly. This allows you to select an individual hstore key. """ <|code_end|> , predict the next line using imports from the current file: from django.db import models from django.db.models import Case, F, Q, Value, When from psqlextra.expressions import HStoreRef from psqlextra.fields import HStoreField from .fake_model import get_fake_model and context including class names, function names, and sometimes code from other files: # Path: psqlextra/expressions.py # class HStoreRef(expressions.F): # """Inline reference to a HStore key. # # Allows selecting individual keys in annotations. # """ # # def __init__(self, name: str, key: str): # """Initializes a new instance of :see:HStoreRef. # # Arguments: # name: # The name of the column/field to resolve. # # key: # The name of the HStore key to select. # """ # # super().__init__(name) # self.key = key # # def resolve_expression(self, *args, **kwargs): # """Resolves the expression into a :see:HStoreColumn expression.""" # # original_expression: expressions.Col = super().resolve_expression( # *args, **kwargs # ) # expression = HStoreColumn( # original_expression.alias, original_expression.target, self.key # ) # return expression # # Path: psqlextra/fields/hstore_field.py # class HStoreField(DjangoHStoreField): # """Improved version of Django's :see:HStoreField that adds support for # database-level constraints. # # Notes: # - For the implementation of uniqueness, see the # custom database back-end. # """ # # def __init__( # self, # *args, # uniqueness: Optional[List[Union[str, Tuple[str, ...]]]] = None, # required: Optional[List[str]] = None, # **kwargs # ): # """Initializes a new instance of :see:HStoreField. # # Arguments: # uniqueness: # List of keys to enforce as unique. Use tuples # to enforce multiple keys together to be unique. # # required: # List of keys that should be enforced as required. # """ # # super(HStoreField, self).__init__(*args, **kwargs) # # self.uniqueness = uniqueness # self.required = required # # def get_prep_value(self, value): # """Override the base class so it doesn't cast all values to strings. # # psqlextra supports expressions in hstore fields, so casting all # values to strings is a bad idea. # """ # # value = Field.get_prep_value(self, value) # # if isinstance(value, dict): # prep_value = {} # for key, val in value.items(): # if isinstance(val, Expression): # prep_value[key] = val # elif val is not None: # prep_value[key] = str(val) # else: # prep_value[key] = val # # value = prep_value # # if isinstance(value, list): # value = [str(item) for item in value] # # return value # # def deconstruct(self): # """Gets the values to pass to :see:__init__ when re-creating this # object.""" # # name, path, args, kwargs = super(HStoreField, self).deconstruct() # # if self.uniqueness is not None: # kwargs["uniqueness"] = self.uniqueness # # if self.required is not None: # kwargs["required"] = self.required # # return name, path, args, kwargs # # Path: tests/fake_model.py # def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}): # """Defines a fake model and creates it in the database.""" # # model = define_fake_model(fields, model_base, meta_options) # # with connection.schema_editor() as schema_editor: # schema_editor.create_model(model) # # return model . Output only the next line.
model_fk = get_fake_model({"title": HStoreField()})
Next line prediction: <|code_start|> def test_query_annotate_hstore_key_ref(): """Tests whether annotating using a :see:HStoreRef expression works correctly. This allows you to select an individual hstore key. """ <|code_end|> . Use current file imports: (from django.db import models from django.db.models import Case, F, Q, Value, When from psqlextra.expressions import HStoreRef from psqlextra.fields import HStoreField from .fake_model import get_fake_model) and context including class names, function names, or small code snippets from other files: # Path: psqlextra/expressions.py # class HStoreRef(expressions.F): # """Inline reference to a HStore key. # # Allows selecting individual keys in annotations. # """ # # def __init__(self, name: str, key: str): # """Initializes a new instance of :see:HStoreRef. # # Arguments: # name: # The name of the column/field to resolve. # # key: # The name of the HStore key to select. # """ # # super().__init__(name) # self.key = key # # def resolve_expression(self, *args, **kwargs): # """Resolves the expression into a :see:HStoreColumn expression.""" # # original_expression: expressions.Col = super().resolve_expression( # *args, **kwargs # ) # expression = HStoreColumn( # original_expression.alias, original_expression.target, self.key # ) # return expression # # Path: psqlextra/fields/hstore_field.py # class HStoreField(DjangoHStoreField): # """Improved version of Django's :see:HStoreField that adds support for # database-level constraints. # # Notes: # - For the implementation of uniqueness, see the # custom database back-end. # """ # # def __init__( # self, # *args, # uniqueness: Optional[List[Union[str, Tuple[str, ...]]]] = None, # required: Optional[List[str]] = None, # **kwargs # ): # """Initializes a new instance of :see:HStoreField. # # Arguments: # uniqueness: # List of keys to enforce as unique. Use tuples # to enforce multiple keys together to be unique. # # required: # List of keys that should be enforced as required. # """ # # super(HStoreField, self).__init__(*args, **kwargs) # # self.uniqueness = uniqueness # self.required = required # # def get_prep_value(self, value): # """Override the base class so it doesn't cast all values to strings. # # psqlextra supports expressions in hstore fields, so casting all # values to strings is a bad idea. # """ # # value = Field.get_prep_value(self, value) # # if isinstance(value, dict): # prep_value = {} # for key, val in value.items(): # if isinstance(val, Expression): # prep_value[key] = val # elif val is not None: # prep_value[key] = str(val) # else: # prep_value[key] = val # # value = prep_value # # if isinstance(value, list): # value = [str(item) for item in value] # # return value # # def deconstruct(self): # """Gets the values to pass to :see:__init__ when re-creating this # object.""" # # name, path, args, kwargs = super(HStoreField, self).deconstruct() # # if self.uniqueness is not None: # kwargs["uniqueness"] = self.uniqueness # # if self.required is not None: # kwargs["required"] = self.required # # return name, path, args, kwargs # # Path: tests/fake_model.py # def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}): # """Defines a fake model and creates it in the database.""" # # model = define_fake_model(fields, model_base, meta_options) # # with connection.schema_editor() as schema_editor: # schema_editor.create_model(model) # # return model . Output only the next line.
model_fk = get_fake_model({"title": HStoreField()})
Given the following code snippet before the placeholder: <|code_start|> def test_cui_deconstruct(): """Tests whether the :see:ConditionalUniqueIndex's deconstruct() method works properly.""" original_kwargs = dict( condition="field IS NULL", name="great_index", fields=["field", "build"] ) <|code_end|> , predict the next line using imports from the current file: import pytest from django.db import IntegrityError, models, transaction from django.db.migrations import AddIndex, CreateModel from psqlextra.indexes import ConditionalUniqueIndex from .fake_model import get_fake_model from .migrations import apply_migration, filtered_schema_editor and context including class names, function names, and sometimes code from other files: # Path: psqlextra/indexes/conditional_unique_index.py # class ConditionalUniqueIndex(Index): # """Creates a partial unique index based on a given condition. # # Useful, for example, if you need unique combination of foreign keys, but you might want to include # NULL as a valid value. In that case, you can just use: # # >>> class Meta: # >>> indexes = [ # >>> ConditionalUniqueIndex(fields=['a', 'b', 'c'], condition='"c" IS NOT NULL'), # >>> ConditionalUniqueIndex(fields=['a', 'b'], condition='"c" IS NULL') # >>> ] # """ # # sql_create_index = "CREATE UNIQUE INDEX %(name)s ON %(table)s (%(columns)s)%(extra)s WHERE %(condition)s" # # def __init__(self, condition: str, fields=[], name=None): # """Initializes a new instance of :see:ConditionalUniqueIndex.""" # # super().__init__(fields=fields, name=name) # # self._condition = condition # # def create_sql(self, model, schema_editor, using="", **kwargs): # """Creates the actual SQL used when applying the migration.""" # if django.VERSION >= (2, 0): # statement = super().create_sql(model, schema_editor, using) # statement.template = self.sql_create_index # statement.parts["condition"] = self._condition # return statement # else: # sql_create_index = self.sql_create_index # sql_parameters = { # **Index.get_sql_create_template_values( # self, model, schema_editor, using # ), # "condition": self._condition, # } # return sql_create_index % sql_parameters # # def deconstruct(self): # """Serializes the :see:ConditionalUniqueIndex for the migrations # file.""" # path = "%s.%s" % (self.__class__.__module__, self.__class__.__name__) # path = path.replace("django.db.models.indexes", "django.db.models") # return ( # path, # (), # { # "fields": self.fields, # "name": self.name, # "condition": self._condition, # }, # ) # # Path: tests/fake_model.py # def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}): # """Defines a fake model and creates it in the database.""" # # model = define_fake_model(fields, model_base, meta_options) # # with connection.schema_editor() as schema_editor: # schema_editor.create_model(model) # # return model # # Path: tests/migrations.py # def apply_migration(operations, state=None, backwards: bool = False): # """Executes the specified migration operations using the specified schema # editor. # # Arguments: # operations: # The migration operations to execute. # # state: # The state state to use during the # migrations. # # backwards: # Whether to apply the operations # in reverse (backwards). # """ # # state = state or migrations.state.ProjectState.from_apps(apps) # # class Migration(migrations.Migration): # pass # # Migration.operations = operations # # migration = Migration("migration", "tests") # executor = MigrationExecutor(connection) # # if not backwards: # executor.apply_migration(state, migration) # else: # executor.unapply_migration(state, migration) # # return migration # # @contextmanager # def filtered_schema_editor(*filters: List[str]): # """Gets a schema editor, but filters executed SQL statements based on the # specified text filters. # # Arguments: # filters: # List of strings to filter SQL # statements on. # """ # # with connection.schema_editor() as schema_editor: # wrapper_for = schema_editor.execute # with mock.patch.object( # PostgresSchemaEditor, "execute", wraps=wrapper_for # ) as execute: # filter_results = {} # yield filter_results # # for filter_text in filters: # filter_results[filter_text] = [ # call for call in execute.mock_calls if filter_text in str(call) # ] . Output only the next line.
_, _, new_kwargs = ConditionalUniqueIndex(**original_kwargs).deconstruct()
Continue the code snippet: <|code_start|> CreateModel( name="mymodel", fields=[ ("id", models.IntegerField(primary_key=True)), ("name", models.CharField(max_length=255, null=True)), ("other_name", models.CharField(max_length=255)), ], options={ # "indexes": [index_1, index_2], }, ), AddIndex(model_name="mymodel", index=index_1), AddIndex(model_name="mymodel", index=index_2), ] with filtered_schema_editor("CREATE UNIQUE INDEX") as calls: apply_migration(ops) calls = [call[0] for _, call, _ in calls["CREATE UNIQUE INDEX"]] db_table = "tests_mymodel" query = 'CREATE UNIQUE INDEX "index1" ON "{0}" ("name", "other_name") WHERE "name" IS NOT NULL' assert str(calls[0]) == query.format(db_table) query = 'CREATE UNIQUE INDEX "index2" ON "{0}" ("other_name") WHERE "name" IS NULL' assert str(calls[1]) == query.format(db_table) def test_cui_upserting(): """Tests upserting respects the :see:ConditionalUniqueIndex rules.""" <|code_end|> . Use current file imports: import pytest from django.db import IntegrityError, models, transaction from django.db.migrations import AddIndex, CreateModel from psqlextra.indexes import ConditionalUniqueIndex from .fake_model import get_fake_model from .migrations import apply_migration, filtered_schema_editor and context (classes, functions, or code) from other files: # Path: psqlextra/indexes/conditional_unique_index.py # class ConditionalUniqueIndex(Index): # """Creates a partial unique index based on a given condition. # # Useful, for example, if you need unique combination of foreign keys, but you might want to include # NULL as a valid value. In that case, you can just use: # # >>> class Meta: # >>> indexes = [ # >>> ConditionalUniqueIndex(fields=['a', 'b', 'c'], condition='"c" IS NOT NULL'), # >>> ConditionalUniqueIndex(fields=['a', 'b'], condition='"c" IS NULL') # >>> ] # """ # # sql_create_index = "CREATE UNIQUE INDEX %(name)s ON %(table)s (%(columns)s)%(extra)s WHERE %(condition)s" # # def __init__(self, condition: str, fields=[], name=None): # """Initializes a new instance of :see:ConditionalUniqueIndex.""" # # super().__init__(fields=fields, name=name) # # self._condition = condition # # def create_sql(self, model, schema_editor, using="", **kwargs): # """Creates the actual SQL used when applying the migration.""" # if django.VERSION >= (2, 0): # statement = super().create_sql(model, schema_editor, using) # statement.template = self.sql_create_index # statement.parts["condition"] = self._condition # return statement # else: # sql_create_index = self.sql_create_index # sql_parameters = { # **Index.get_sql_create_template_values( # self, model, schema_editor, using # ), # "condition": self._condition, # } # return sql_create_index % sql_parameters # # def deconstruct(self): # """Serializes the :see:ConditionalUniqueIndex for the migrations # file.""" # path = "%s.%s" % (self.__class__.__module__, self.__class__.__name__) # path = path.replace("django.db.models.indexes", "django.db.models") # return ( # path, # (), # { # "fields": self.fields, # "name": self.name, # "condition": self._condition, # }, # ) # # Path: tests/fake_model.py # def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}): # """Defines a fake model and creates it in the database.""" # # model = define_fake_model(fields, model_base, meta_options) # # with connection.schema_editor() as schema_editor: # schema_editor.create_model(model) # # return model # # Path: tests/migrations.py # def apply_migration(operations, state=None, backwards: bool = False): # """Executes the specified migration operations using the specified schema # editor. # # Arguments: # operations: # The migration operations to execute. # # state: # The state state to use during the # migrations. # # backwards: # Whether to apply the operations # in reverse (backwards). # """ # # state = state or migrations.state.ProjectState.from_apps(apps) # # class Migration(migrations.Migration): # pass # # Migration.operations = operations # # migration = Migration("migration", "tests") # executor = MigrationExecutor(connection) # # if not backwards: # executor.apply_migration(state, migration) # else: # executor.unapply_migration(state, migration) # # return migration # # @contextmanager # def filtered_schema_editor(*filters: List[str]): # """Gets a schema editor, but filters executed SQL statements based on the # specified text filters. # # Arguments: # filters: # List of strings to filter SQL # statements on. # """ # # with connection.schema_editor() as schema_editor: # wrapper_for = schema_editor.execute # with mock.patch.object( # PostgresSchemaEditor, "execute", wraps=wrapper_for # ) as execute: # filter_results = {} # yield filter_results # # for filter_text in filters: # filter_results[filter_text] = [ # call for call in execute.mock_calls if filter_text in str(call) # ] . Output only the next line.
model = get_fake_model(
Continue the code snippet: <|code_start|>def test_cui_migrations(): """Tests whether the migrations are properly generated and executed.""" index_1 = ConditionalUniqueIndex( fields=["name", "other_name"], condition='"name" IS NOT NULL', name="index1", ) index_2 = ConditionalUniqueIndex( fields=["other_name"], condition='"name" IS NULL', name="index2" ) ops = [ CreateModel( name="mymodel", fields=[ ("id", models.IntegerField(primary_key=True)), ("name", models.CharField(max_length=255, null=True)), ("other_name", models.CharField(max_length=255)), ], options={ # "indexes": [index_1, index_2], }, ), AddIndex(model_name="mymodel", index=index_1), AddIndex(model_name="mymodel", index=index_2), ] with filtered_schema_editor("CREATE UNIQUE INDEX") as calls: <|code_end|> . Use current file imports: import pytest from django.db import IntegrityError, models, transaction from django.db.migrations import AddIndex, CreateModel from psqlextra.indexes import ConditionalUniqueIndex from .fake_model import get_fake_model from .migrations import apply_migration, filtered_schema_editor and context (classes, functions, or code) from other files: # Path: psqlextra/indexes/conditional_unique_index.py # class ConditionalUniqueIndex(Index): # """Creates a partial unique index based on a given condition. # # Useful, for example, if you need unique combination of foreign keys, but you might want to include # NULL as a valid value. In that case, you can just use: # # >>> class Meta: # >>> indexes = [ # >>> ConditionalUniqueIndex(fields=['a', 'b', 'c'], condition='"c" IS NOT NULL'), # >>> ConditionalUniqueIndex(fields=['a', 'b'], condition='"c" IS NULL') # >>> ] # """ # # sql_create_index = "CREATE UNIQUE INDEX %(name)s ON %(table)s (%(columns)s)%(extra)s WHERE %(condition)s" # # def __init__(self, condition: str, fields=[], name=None): # """Initializes a new instance of :see:ConditionalUniqueIndex.""" # # super().__init__(fields=fields, name=name) # # self._condition = condition # # def create_sql(self, model, schema_editor, using="", **kwargs): # """Creates the actual SQL used when applying the migration.""" # if django.VERSION >= (2, 0): # statement = super().create_sql(model, schema_editor, using) # statement.template = self.sql_create_index # statement.parts["condition"] = self._condition # return statement # else: # sql_create_index = self.sql_create_index # sql_parameters = { # **Index.get_sql_create_template_values( # self, model, schema_editor, using # ), # "condition": self._condition, # } # return sql_create_index % sql_parameters # # def deconstruct(self): # """Serializes the :see:ConditionalUniqueIndex for the migrations # file.""" # path = "%s.%s" % (self.__class__.__module__, self.__class__.__name__) # path = path.replace("django.db.models.indexes", "django.db.models") # return ( # path, # (), # { # "fields": self.fields, # "name": self.name, # "condition": self._condition, # }, # ) # # Path: tests/fake_model.py # def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}): # """Defines a fake model and creates it in the database.""" # # model = define_fake_model(fields, model_base, meta_options) # # with connection.schema_editor() as schema_editor: # schema_editor.create_model(model) # # return model # # Path: tests/migrations.py # def apply_migration(operations, state=None, backwards: bool = False): # """Executes the specified migration operations using the specified schema # editor. # # Arguments: # operations: # The migration operations to execute. # # state: # The state state to use during the # migrations. # # backwards: # Whether to apply the operations # in reverse (backwards). # """ # # state = state or migrations.state.ProjectState.from_apps(apps) # # class Migration(migrations.Migration): # pass # # Migration.operations = operations # # migration = Migration("migration", "tests") # executor = MigrationExecutor(connection) # # if not backwards: # executor.apply_migration(state, migration) # else: # executor.unapply_migration(state, migration) # # return migration # # @contextmanager # def filtered_schema_editor(*filters: List[str]): # """Gets a schema editor, but filters executed SQL statements based on the # specified text filters. # # Arguments: # filters: # List of strings to filter SQL # statements on. # """ # # with connection.schema_editor() as schema_editor: # wrapper_for = schema_editor.execute # with mock.patch.object( # PostgresSchemaEditor, "execute", wraps=wrapper_for # ) as execute: # filter_results = {} # yield filter_results # # for filter_text in filters: # filter_results[filter_text] = [ # call for call in execute.mock_calls if filter_text in str(call) # ] . Output only the next line.
apply_migration(ops)
Given snippet: <|code_start|> def test_cui_migrations(): """Tests whether the migrations are properly generated and executed.""" index_1 = ConditionalUniqueIndex( fields=["name", "other_name"], condition='"name" IS NOT NULL', name="index1", ) index_2 = ConditionalUniqueIndex( fields=["other_name"], condition='"name" IS NULL', name="index2" ) ops = [ CreateModel( name="mymodel", fields=[ ("id", models.IntegerField(primary_key=True)), ("name", models.CharField(max_length=255, null=True)), ("other_name", models.CharField(max_length=255)), ], options={ # "indexes": [index_1, index_2], }, ), AddIndex(model_name="mymodel", index=index_1), AddIndex(model_name="mymodel", index=index_2), ] <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest from django.db import IntegrityError, models, transaction from django.db.migrations import AddIndex, CreateModel from psqlextra.indexes import ConditionalUniqueIndex from .fake_model import get_fake_model from .migrations import apply_migration, filtered_schema_editor and context: # Path: psqlextra/indexes/conditional_unique_index.py # class ConditionalUniqueIndex(Index): # """Creates a partial unique index based on a given condition. # # Useful, for example, if you need unique combination of foreign keys, but you might want to include # NULL as a valid value. In that case, you can just use: # # >>> class Meta: # >>> indexes = [ # >>> ConditionalUniqueIndex(fields=['a', 'b', 'c'], condition='"c" IS NOT NULL'), # >>> ConditionalUniqueIndex(fields=['a', 'b'], condition='"c" IS NULL') # >>> ] # """ # # sql_create_index = "CREATE UNIQUE INDEX %(name)s ON %(table)s (%(columns)s)%(extra)s WHERE %(condition)s" # # def __init__(self, condition: str, fields=[], name=None): # """Initializes a new instance of :see:ConditionalUniqueIndex.""" # # super().__init__(fields=fields, name=name) # # self._condition = condition # # def create_sql(self, model, schema_editor, using="", **kwargs): # """Creates the actual SQL used when applying the migration.""" # if django.VERSION >= (2, 0): # statement = super().create_sql(model, schema_editor, using) # statement.template = self.sql_create_index # statement.parts["condition"] = self._condition # return statement # else: # sql_create_index = self.sql_create_index # sql_parameters = { # **Index.get_sql_create_template_values( # self, model, schema_editor, using # ), # "condition": self._condition, # } # return sql_create_index % sql_parameters # # def deconstruct(self): # """Serializes the :see:ConditionalUniqueIndex for the migrations # file.""" # path = "%s.%s" % (self.__class__.__module__, self.__class__.__name__) # path = path.replace("django.db.models.indexes", "django.db.models") # return ( # path, # (), # { # "fields": self.fields, # "name": self.name, # "condition": self._condition, # }, # ) # # Path: tests/fake_model.py # def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}): # """Defines a fake model and creates it in the database.""" # # model = define_fake_model(fields, model_base, meta_options) # # with connection.schema_editor() as schema_editor: # schema_editor.create_model(model) # # return model # # Path: tests/migrations.py # def apply_migration(operations, state=None, backwards: bool = False): # """Executes the specified migration operations using the specified schema # editor. # # Arguments: # operations: # The migration operations to execute. # # state: # The state state to use during the # migrations. # # backwards: # Whether to apply the operations # in reverse (backwards). # """ # # state = state or migrations.state.ProjectState.from_apps(apps) # # class Migration(migrations.Migration): # pass # # Migration.operations = operations # # migration = Migration("migration", "tests") # executor = MigrationExecutor(connection) # # if not backwards: # executor.apply_migration(state, migration) # else: # executor.unapply_migration(state, migration) # # return migration # # @contextmanager # def filtered_schema_editor(*filters: List[str]): # """Gets a schema editor, but filters executed SQL statements based on the # specified text filters. # # Arguments: # filters: # List of strings to filter SQL # statements on. # """ # # with connection.schema_editor() as schema_editor: # wrapper_for = schema_editor.execute # with mock.patch.object( # PostgresSchemaEditor, "execute", wraps=wrapper_for # ) as execute: # filter_results = {} # yield filter_results # # for filter_text in filters: # filter_results[filter_text] = [ # call for call in execute.mock_calls if filter_text in str(call) # ] which might include code, classes, or functions. Output only the next line.
with filtered_schema_editor("CREATE UNIQUE INDEX") as calls:
Given the following code snippet before the placeholder: <|code_start|> obj1.refresh_from_db() obj2.refresh_from_db() # assert both objects are the same assert obj1.pk == obj2.pk assert obj1.name == "the-object" assert obj1.cookies == "second-boo" assert obj2.name == "the-object" assert obj2.cookies == "second-boo" def test_upsert_with_update_condition(): """Tests that an expression can be used as an upsert update condition.""" model = get_fake_model( { "name": models.TextField(unique=True), "priority": models.IntegerField(), "active": models.BooleanField(), } ) obj1 = model.objects.create(name="joe", priority=1, active=False) # should not return anything because no rows were affected assert not model.objects.upsert( conflict_target=["name"], update_condition=CombinedExpression( model._meta.get_field("active").get_col(model._meta.db_table), "=", <|code_end|> , predict the next line using imports from the current file: import django import pytest from django.db import models from django.db.models import Q from django.db.models.expressions import CombinedExpression, Value from psqlextra.expressions import ExcludedCol from psqlextra.fields import HStoreField from .fake_model import get_fake_model and context including class names, function names, and sometimes code from other files: # Path: psqlextra/expressions.py # class ExcludedCol(expressions.Expression): # """References a column in PostgreSQL's special EXCLUDED column, which is # used in upserts to refer to the data about to be inserted/updated. # # See: https://www.postgresql.org/docs/9.5/sql-insert.html#SQL-ON-CONFLICT # """ # # def __init__(self, name: str): # self.name = name # # def as_sql(self, compiler, connection): # quoted_name = connection.ops.quote_name(self.name) # return f"EXCLUDED.{quoted_name}", tuple() # # Path: psqlextra/fields/hstore_field.py # class HStoreField(DjangoHStoreField): # """Improved version of Django's :see:HStoreField that adds support for # database-level constraints. # # Notes: # - For the implementation of uniqueness, see the # custom database back-end. # """ # # def __init__( # self, # *args, # uniqueness: Optional[List[Union[str, Tuple[str, ...]]]] = None, # required: Optional[List[str]] = None, # **kwargs # ): # """Initializes a new instance of :see:HStoreField. # # Arguments: # uniqueness: # List of keys to enforce as unique. Use tuples # to enforce multiple keys together to be unique. # # required: # List of keys that should be enforced as required. # """ # # super(HStoreField, self).__init__(*args, **kwargs) # # self.uniqueness = uniqueness # self.required = required # # def get_prep_value(self, value): # """Override the base class so it doesn't cast all values to strings. # # psqlextra supports expressions in hstore fields, so casting all # values to strings is a bad idea. # """ # # value = Field.get_prep_value(self, value) # # if isinstance(value, dict): # prep_value = {} # for key, val in value.items(): # if isinstance(val, Expression): # prep_value[key] = val # elif val is not None: # prep_value[key] = str(val) # else: # prep_value[key] = val # # value = prep_value # # if isinstance(value, list): # value = [str(item) for item in value] # # return value # # def deconstruct(self): # """Gets the values to pass to :see:__init__ when re-creating this # object.""" # # name, path, args, kwargs = super(HStoreField, self).deconstruct() # # if self.uniqueness is not None: # kwargs["uniqueness"] = self.uniqueness # # if self.required is not None: # kwargs["required"] = self.required # # return name, path, args, kwargs # # Path: tests/fake_model.py # def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}): # """Defines a fake model and creates it in the database.""" # # model = define_fake_model(fields, model_base, meta_options) # # with connection.schema_editor() as schema_editor: # schema_editor.create_model(model) # # return model . Output only the next line.
ExcludedCol("active"),
Here is a snippet: <|code_start|> def test_upsert(): """Tests whether simple upserts works correctly.""" model = get_fake_model( { <|code_end|> . Write the next line using the current file imports: import django import pytest from django.db import models from django.db.models import Q from django.db.models.expressions import CombinedExpression, Value from psqlextra.expressions import ExcludedCol from psqlextra.fields import HStoreField from .fake_model import get_fake_model and context from other files: # Path: psqlextra/expressions.py # class ExcludedCol(expressions.Expression): # """References a column in PostgreSQL's special EXCLUDED column, which is # used in upserts to refer to the data about to be inserted/updated. # # See: https://www.postgresql.org/docs/9.5/sql-insert.html#SQL-ON-CONFLICT # """ # # def __init__(self, name: str): # self.name = name # # def as_sql(self, compiler, connection): # quoted_name = connection.ops.quote_name(self.name) # return f"EXCLUDED.{quoted_name}", tuple() # # Path: psqlextra/fields/hstore_field.py # class HStoreField(DjangoHStoreField): # """Improved version of Django's :see:HStoreField that adds support for # database-level constraints. # # Notes: # - For the implementation of uniqueness, see the # custom database back-end. # """ # # def __init__( # self, # *args, # uniqueness: Optional[List[Union[str, Tuple[str, ...]]]] = None, # required: Optional[List[str]] = None, # **kwargs # ): # """Initializes a new instance of :see:HStoreField. # # Arguments: # uniqueness: # List of keys to enforce as unique. Use tuples # to enforce multiple keys together to be unique. # # required: # List of keys that should be enforced as required. # """ # # super(HStoreField, self).__init__(*args, **kwargs) # # self.uniqueness = uniqueness # self.required = required # # def get_prep_value(self, value): # """Override the base class so it doesn't cast all values to strings. # # psqlextra supports expressions in hstore fields, so casting all # values to strings is a bad idea. # """ # # value = Field.get_prep_value(self, value) # # if isinstance(value, dict): # prep_value = {} # for key, val in value.items(): # if isinstance(val, Expression): # prep_value[key] = val # elif val is not None: # prep_value[key] = str(val) # else: # prep_value[key] = val # # value = prep_value # # if isinstance(value, list): # value = [str(item) for item in value] # # return value # # def deconstruct(self): # """Gets the values to pass to :see:__init__ when re-creating this # object.""" # # name, path, args, kwargs = super(HStoreField, self).deconstruct() # # if self.uniqueness is not None: # kwargs["uniqueness"] = self.uniqueness # # if self.required is not None: # kwargs["required"] = self.required # # return name, path, args, kwargs # # Path: tests/fake_model.py # def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}): # """Defines a fake model and creates it in the database.""" # # model = define_fake_model(fields, model_base, meta_options) # # with connection.schema_editor() as schema_editor: # schema_editor.create_model(model) # # return model , which may include functions, classes, or code. Output only the next line.
"title": HStoreField(uniqueness=["key1"]),
Continue the code snippet: <|code_start|> partition key divided by the specified modulus will produce the specified remainder. """ def __init__( self, model_name: str, name: str, modulus: int, remainder: int ): """Initializes new instance of :see:AddHashPartition. Arguments: model_name: The name of the :see:PartitionedPostgresModel. name: The name to give to the new partition table. modulus: Integer value by which the key is divided. remainder: The remainder of the hash value when divided by modulus. """ super().__init__(model_name, name) self.modulus = modulus self.remainder = remainder def state_forwards(self, app_label, state): model = state.models[(app_label, self.model_name_lower)] model.add_partition( <|code_end|> . Use current file imports: from psqlextra.backend.migrations.state import PostgresHashPartitionState from .partition import PostgresPartitionOperation and context (classes, functions, or code) from other files: # Path: psqlextra/backend/migrations/state/partitioning.py # class PostgresHashPartitionState(PostgresPartitionState): # """Represents the state of a hash partition for a # :see:PostgresPartitionedModel during a migration.""" # # def __init__( # self, # app_label: str, # model_name: str, # name: str, # modulus: int, # remainder: int, # ): # super().__init__(app_label, model_name, name) # # self.modulus = modulus # self.remainder = remainder # # Path: psqlextra/backend/migrations/operations/partition.py # class PostgresPartitionOperation(Operation): # def __init__(self, model_name: str, name: str) -> None: # """Initializes new instance of :see:AddDefaultPartition. # # Arguments: # model_name: # The name of the :see:PartitionedPostgresModel. # # name: # The name to give to the new partition table. # """ # # self.model_name = model_name # self.model_name_lower = model_name.lower() # self.name = name # # def deconstruct(self): # kwargs = {"model_name": self.model_name, "name": self.name} # return (self.__class__.__qualname__, [], kwargs) # # def state_forwards(self, *args, **kwargs): # pass # # def state_backwards(self, *args, **kwargs): # pass # # def reduce(self, *args, **kwargs): # # PartitionOperation doesn't break migrations optimizations # return True . Output only the next line.
PostgresHashPartitionState(
Predict the next line after this snippet: <|code_start|> class PostgresAddDefaultPartition(PostgresPartitionOperation): """Adds a new default partition to a :see:PartitionedPostgresModel.""" def state_forwards(self, app_label, state): model_state = state.models[(app_label, self.model_name_lower)] model_state.add_partition( <|code_end|> using the current file's imports: from psqlextra.backend.migrations.state import PostgresPartitionState from .partition import PostgresPartitionOperation and any relevant context from other files: # Path: psqlextra/backend/migrations/state/partitioning.py # class PostgresPartitionState: # """Represents the state of a partition for a :see:PostgresPartitionedModel # during a migration.""" # # def __init__(self, app_label: str, model_name: str, name: str) -> None: # self.app_label = app_label # self.model_name = model_name # self.name = name # # Path: psqlextra/backend/migrations/operations/partition.py # class PostgresPartitionOperation(Operation): # def __init__(self, model_name: str, name: str) -> None: # """Initializes new instance of :see:AddDefaultPartition. # # Arguments: # model_name: # The name of the :see:PartitionedPostgresModel. # # name: # The name to give to the new partition table. # """ # # self.model_name = model_name # self.model_name_lower = model_name.lower() # self.name = name # # def deconstruct(self): # kwargs = {"model_name": self.model_name, "name": self.name} # return (self.__class__.__qualname__, [], kwargs) # # def state_forwards(self, *args, **kwargs): # pass # # def state_backwards(self, *args, **kwargs): # pass # # def reduce(self, *args, **kwargs): # # PartitionOperation doesn't break migrations optimizations # return True . Output only the next line.
PostgresPartitionState(
Given the code snippet: <|code_start|> def __init__(self, model_name: str, name: str, from_values, to_values): """Initializes new instance of :see:AddRangePartition. Arguments: model_name: The name of the :see:PartitionedPostgresModel. name: The name to give to the new partition table. from_values: Start of the partitioning key range of values that need to be stored in this partition. to_values: End of the partitioning key range of values that need to be stored in this partition. """ super().__init__(model_name, name) self.from_values = from_values self.to_values = to_values def state_forwards(self, app_label, state): model = state.models[(app_label, self.model_name_lower)] model.add_partition( <|code_end|> , generate the next line using the imports in this file: from psqlextra.backend.migrations.state import PostgresRangePartitionState from .partition import PostgresPartitionOperation and context (functions, classes, or occasionally code) from other files: # Path: psqlextra/backend/migrations/state/partitioning.py # class PostgresRangePartitionState(PostgresPartitionState): # """Represents the state of a range partition for a # :see:PostgresPartitionedModel during a migration.""" # # def __init__( # self, app_label: str, model_name: str, name: str, from_values, to_values # ): # super().__init__(app_label, model_name, name) # # self.from_values = from_values # self.to_values = to_values # # Path: psqlextra/backend/migrations/operations/partition.py # class PostgresPartitionOperation(Operation): # def __init__(self, model_name: str, name: str) -> None: # """Initializes new instance of :see:AddDefaultPartition. # # Arguments: # model_name: # The name of the :see:PartitionedPostgresModel. # # name: # The name to give to the new partition table. # """ # # self.model_name = model_name # self.model_name_lower = model_name.lower() # self.name = name # # def deconstruct(self): # kwargs = {"model_name": self.model_name, "name": self.name} # return (self.__class__.__qualname__, [], kwargs) # # def state_forwards(self, *args, **kwargs): # pass # # def state_backwards(self, *args, **kwargs): # pass # # def reduce(self, *args, **kwargs): # # PartitionOperation doesn't break migrations optimizations # return True . Output only the next line.
PostgresRangePartitionState(
Given the following code snippet before the placeholder: <|code_start|> class PostgresModelState(ModelState): """Base for custom model states. We need this base class to create some hooks into rendering models, creating new states and cloning state. Most of the logic resides here in the base class. Our derived classes implement the `_pre_*` methods. """ @classmethod def from_model( <|code_end|> , predict the next line using imports from the current file: from collections.abc import Mapping from typing import Type from django.db.migrations.state import ModelState from django.db.models import Model from psqlextra.models import PostgresModel and context including class names, function names, and sometimes code from other files: # Path: psqlextra/models/base.py # class PostgresModel(models.Model): # """Base class for for taking advantage of PostgreSQL specific features.""" # # class Meta: # abstract = True # base_manager_name = "objects" # # objects = PostgresManager() . Output only the next line.
cls, model: PostgresModel, *args, **kwargs
Using the snippet: <|code_start|> @pytest.mark.parametrize( "databases", [ {"default": {"ENGINE": "psqlextra.backend"}}, { "default": {"ENGINE": "django.db.backends.postgresql"}, "other": {"ENGINE": "psqlextra.backend"}, }, { "default": {"ENGINE": "psqlextra.backend"}, "other": {"ENGINE": "psqlextra.backend"}, }, ], ) def test_manager_backend_set(databases): """Tests that creating a new instance of :see:PostgresManager succeseeds without any errors if one or more databases are configured with `psqlextra.backend` as its ENGINE.""" with override_settings(DATABASES=databases): <|code_end|> , determine the next line of code. You have imports: import pytest from django.core.exceptions import ImproperlyConfigured from django.db import models from django.test import override_settings from psqlextra.manager import PostgresManager from psqlextra.models import PostgresModel from .fake_model import get_fake_model and context (class names, function names, or code) available: # Path: psqlextra/manager/manager.py # class PostgresManager(Manager.from_queryset(PostgresQuerySet)): # """Adds support for PostgreSQL specifics.""" # # use_in_migrations = True # # def __init__(self, *args, **kwargs): # """Initializes a new instance of :see:PostgresManager.""" # # super().__init__(*args, **kwargs) # # # make sure our back-end is set in at least one db and refuse to proceed # has_psqlextra_backend = any( # [ # db_settings # for db_settings in settings.DATABASES.values() # if "psqlextra" in db_settings["ENGINE"] # ] # ) # # if not has_psqlextra_backend: # raise ImproperlyConfigured( # ( # "Could not locate the 'psqlextra.backend'. " # "django-postgres-extra cannot function without " # "the 'psqlextra.backend'. Set DATABASES.ENGINE." # ) # ) # # def truncate( # self, cascade: bool = False, using: Optional[str] = None # ) -> None: # """Truncates this model/table using the TRUNCATE statement. # # This DELETES ALL ROWS. No signals will be fired. # # See: https://www.postgresql.org/docs/9.1/sql-truncate.html # # Arguments: # cascade: # Whether to delete dependent rows. If set to # False, an error will be raised if there # are rows in other tables referencing # the rows you're trying to delete. # """ # # connection = connections[using or "default"] # table_name = connection.ops.quote_name(self.model._meta.db_table) # # with connection.cursor() as cursor: # sql = "TRUNCATE TABLE %s" % table_name # if cascade: # sql += " CASCADE" # # cursor.execute(sql) # # Path: psqlextra/models/base.py # class PostgresModel(models.Model): # """Base class for for taking advantage of PostgreSQL specific features.""" # # class Meta: # abstract = True # base_manager_name = "objects" # # objects = PostgresManager() # # Path: tests/fake_model.py # def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}): # """Defines a fake model and creates it in the database.""" # # model = define_fake_model(fields, model_base, meta_options) # # with connection.schema_editor() as schema_editor: # schema_editor.create_model(model) # # return model . Output only the next line.
assert PostgresManager()
Predict the next line after this snippet: <|code_start|> """Tests whether truncating a table with cascade works.""" model_1 = get_fake_model({"name": models.CharField(max_length=255)}) model_2 = get_fake_model( { "name": models.CharField(max_length=255), "model_1": models.ForeignKey( model_1, on_delete=models.CASCADE, null=True ), } ) obj_1 = model_1.objects.create(name="henk1") model_2.objects.create(name="henk1", model_1_id=obj_1.id) assert model_1.objects.count() == 1 assert model_2.objects.count() == 1 model_1.objects.truncate(cascade=True) assert model_1.objects.count() == 0 assert model_2.objects.count() == 0 def test_manager_truncate_quote_name(): """Tests whether the truncate statement properly quotes the table name.""" model = get_fake_model( {"name": models.CharField(max_length=255)}, <|code_end|> using the current file's imports: import pytest from django.core.exceptions import ImproperlyConfigured from django.db import models from django.test import override_settings from psqlextra.manager import PostgresManager from psqlextra.models import PostgresModel from .fake_model import get_fake_model and any relevant context from other files: # Path: psqlextra/manager/manager.py # class PostgresManager(Manager.from_queryset(PostgresQuerySet)): # """Adds support for PostgreSQL specifics.""" # # use_in_migrations = True # # def __init__(self, *args, **kwargs): # """Initializes a new instance of :see:PostgresManager.""" # # super().__init__(*args, **kwargs) # # # make sure our back-end is set in at least one db and refuse to proceed # has_psqlextra_backend = any( # [ # db_settings # for db_settings in settings.DATABASES.values() # if "psqlextra" in db_settings["ENGINE"] # ] # ) # # if not has_psqlextra_backend: # raise ImproperlyConfigured( # ( # "Could not locate the 'psqlextra.backend'. " # "django-postgres-extra cannot function without " # "the 'psqlextra.backend'. Set DATABASES.ENGINE." # ) # ) # # def truncate( # self, cascade: bool = False, using: Optional[str] = None # ) -> None: # """Truncates this model/table using the TRUNCATE statement. # # This DELETES ALL ROWS. No signals will be fired. # # See: https://www.postgresql.org/docs/9.1/sql-truncate.html # # Arguments: # cascade: # Whether to delete dependent rows. If set to # False, an error will be raised if there # are rows in other tables referencing # the rows you're trying to delete. # """ # # connection = connections[using or "default"] # table_name = connection.ops.quote_name(self.model._meta.db_table) # # with connection.cursor() as cursor: # sql = "TRUNCATE TABLE %s" % table_name # if cascade: # sql += " CASCADE" # # cursor.execute(sql) # # Path: psqlextra/models/base.py # class PostgresModel(models.Model): # """Base class for for taking advantage of PostgreSQL specific features.""" # # class Meta: # abstract = True # base_manager_name = "objects" # # objects = PostgresManager() # # Path: tests/fake_model.py # def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}): # """Defines a fake model and creates it in the database.""" # # model = define_fake_model(fields, model_base, meta_options) # # with connection.schema_editor() as schema_editor: # schema_editor.create_model(model) # # return model . Output only the next line.
PostgresModel,
Continue the code snippet: <|code_start|> "default": {"ENGINE": "psqlextra.backend"}, "other": {"ENGINE": "psqlextra.backend"}, }, ], ) def test_manager_backend_set(databases): """Tests that creating a new instance of :see:PostgresManager succeseeds without any errors if one or more databases are configured with `psqlextra.backend` as its ENGINE.""" with override_settings(DATABASES=databases): assert PostgresManager() def test_manager_backend_not_set(): """Tests whether creating a new instance of :see:PostgresManager fails if no database has `psqlextra.backend` configured as its ENGINE.""" with override_settings( DATABASES={"default": {"ENGINE": "django.db.backends.postgresql"}} ): with pytest.raises(ImproperlyConfigured): PostgresManager() def test_manager_truncate(): """Tests whether truncating a table works.""" <|code_end|> . Use current file imports: import pytest from django.core.exceptions import ImproperlyConfigured from django.db import models from django.test import override_settings from psqlextra.manager import PostgresManager from psqlextra.models import PostgresModel from .fake_model import get_fake_model and context (classes, functions, or code) from other files: # Path: psqlextra/manager/manager.py # class PostgresManager(Manager.from_queryset(PostgresQuerySet)): # """Adds support for PostgreSQL specifics.""" # # use_in_migrations = True # # def __init__(self, *args, **kwargs): # """Initializes a new instance of :see:PostgresManager.""" # # super().__init__(*args, **kwargs) # # # make sure our back-end is set in at least one db and refuse to proceed # has_psqlextra_backend = any( # [ # db_settings # for db_settings in settings.DATABASES.values() # if "psqlextra" in db_settings["ENGINE"] # ] # ) # # if not has_psqlextra_backend: # raise ImproperlyConfigured( # ( # "Could not locate the 'psqlextra.backend'. " # "django-postgres-extra cannot function without " # "the 'psqlextra.backend'. Set DATABASES.ENGINE." # ) # ) # # def truncate( # self, cascade: bool = False, using: Optional[str] = None # ) -> None: # """Truncates this model/table using the TRUNCATE statement. # # This DELETES ALL ROWS. No signals will be fired. # # See: https://www.postgresql.org/docs/9.1/sql-truncate.html # # Arguments: # cascade: # Whether to delete dependent rows. If set to # False, an error will be raised if there # are rows in other tables referencing # the rows you're trying to delete. # """ # # connection = connections[using or "default"] # table_name = connection.ops.quote_name(self.model._meta.db_table) # # with connection.cursor() as cursor: # sql = "TRUNCATE TABLE %s" % table_name # if cascade: # sql += " CASCADE" # # cursor.execute(sql) # # Path: psqlextra/models/base.py # class PostgresModel(models.Model): # """Base class for for taking advantage of PostgreSQL specific features.""" # # class Meta: # abstract = True # base_manager_name = "objects" # # objects = PostgresManager() # # Path: tests/fake_model.py # def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}): # """Defines a fake model and creates it in the database.""" # # model = define_fake_model(fields, model_base, meta_options) # # with connection.schema_editor() as schema_editor: # schema_editor.create_model(model) # # return model . Output only the next line.
model = get_fake_model({"name": models.CharField(max_length=255)})
Given snippet: <|code_start|> .update(name=dict(en=F('test'))) """ def as_sql(self): self._prepare_query_values() return super().as_sql() def _prepare_query_values(self): """Extra prep on query values by converting dictionaries into. :see:HStoreValue expressions. This allows putting expressions in a dictionary. The :see:HStoreValue will take care of resolving the expressions inside the dictionary. """ if not self.query.values: return new_query_values = [] for field, model, val in self.query.values: if not isinstance(val, dict): new_query_values.append((field, model, val)) continue if not self._does_dict_contain_expression(val): new_query_values.append((field, model, val)) continue <|code_end|> , continue by predicting the next line. Consider current file imports: from collections.abc import Iterable from typing import Tuple, Union from django.core.exceptions import SuspiciousOperation from django.db.models import Expression, Model, Q from django.db.models.fields.related import RelatedField from django.db.models.sql.compiler import SQLInsertCompiler, SQLUpdateCompiler from django.db.utils import ProgrammingError from .expressions import HStoreValue from .types import ConflictAction import django and context: # Path: psqlextra/expressions.py # class HStoreValue(expressions.Expression): # """Represents a HStore value. # # The base PostgreSQL implementation Django provides, always # represents HStore values as dictionaries, but this doesn't work if # you want to use expressions inside hstore values. # """ # # def __init__(self, value): # """Initializes a new instance.""" # # self.value = value # # def resolve_expression(self, *args, **kwargs): # """Resolves expressions inside the dictionary.""" # # result = dict() # for key, value in self.value.items(): # if hasattr(value, "resolve_expression"): # result[key] = value.resolve_expression(*args, **kwargs) # else: # result[key] = value # # return HStoreValue(result) # # def as_sql(self, compiler, connection): # """Compiles the HStore value into SQL. # # Compiles expressions contained in the values # of HStore entries as well. # # Given a dictionary like: # # dict(key1='val1', key2='val2') # # The resulting SQL will be: # # hstore(hstore('key1', 'val1'), hstore('key2', 'val2')) # """ # # sql = [] # params = [] # # for key, value in self.value.items(): # if hasattr(value, "as_sql"): # inner_sql, inner_params = value.as_sql(compiler, connection) # sql.append(f"hstore(%s, {inner_sql})") # params.append(key) # params.extend(inner_params) # elif value is not None: # sql.append("hstore(%s, %s)") # params.append(key) # params.append(str(value)) # else: # sql.append("hstore(%s, NULL)") # params.append(key) # # return " || ".join(sql), params # # Path: psqlextra/types.py # class ConflictAction(Enum): # """Possible actions to take on a conflict.""" # # NOTHING = "NOTHING" # UPDATE = "UPDATE" # # @classmethod # def all(cls) -> List["ConflictAction"]: # return [choice for choice in cls] which might include code, classes, or functions. Output only the next line.
expression = HStoreValue(dict(val))
Based on the snippet: <|code_start|> ] def _rewrite_insert(self, sql, params, return_id=False): """Rewrites a formed SQL INSERT query to include the ON CONFLICT clause. Arguments: sql: The SQL INSERT query to rewrite. params: The parameters passed to the query. returning: What to put in the `RETURNING` clause of the resulting query. Returns: A tuple of the rewritten SQL query and new params. """ returning = ( self.qn(self.query.model._meta.pk.attname) if return_id else "*" ) return self._rewrite_insert_on_conflict( sql, params, self.query.conflict_action.value, returning ) def _rewrite_insert_on_conflict( <|code_end|> , predict the immediate next line with the help of imports: from collections.abc import Iterable from typing import Tuple, Union from django.core.exceptions import SuspiciousOperation from django.db.models import Expression, Model, Q from django.db.models.fields.related import RelatedField from django.db.models.sql.compiler import SQLInsertCompiler, SQLUpdateCompiler from django.db.utils import ProgrammingError from .expressions import HStoreValue from .types import ConflictAction import django and context (classes, functions, sometimes code) from other files: # Path: psqlextra/expressions.py # class HStoreValue(expressions.Expression): # """Represents a HStore value. # # The base PostgreSQL implementation Django provides, always # represents HStore values as dictionaries, but this doesn't work if # you want to use expressions inside hstore values. # """ # # def __init__(self, value): # """Initializes a new instance.""" # # self.value = value # # def resolve_expression(self, *args, **kwargs): # """Resolves expressions inside the dictionary.""" # # result = dict() # for key, value in self.value.items(): # if hasattr(value, "resolve_expression"): # result[key] = value.resolve_expression(*args, **kwargs) # else: # result[key] = value # # return HStoreValue(result) # # def as_sql(self, compiler, connection): # """Compiles the HStore value into SQL. # # Compiles expressions contained in the values # of HStore entries as well. # # Given a dictionary like: # # dict(key1='val1', key2='val2') # # The resulting SQL will be: # # hstore(hstore('key1', 'val1'), hstore('key2', 'val2')) # """ # # sql = [] # params = [] # # for key, value in self.value.items(): # if hasattr(value, "as_sql"): # inner_sql, inner_params = value.as_sql(compiler, connection) # sql.append(f"hstore(%s, {inner_sql})") # params.append(key) # params.extend(inner_params) # elif value is not None: # sql.append("hstore(%s, %s)") # params.append(key) # params.append(str(value)) # else: # sql.append("hstore(%s, NULL)") # params.append(key) # # return " || ".join(sql), params # # Path: psqlextra/types.py # class ConflictAction(Enum): # """Possible actions to take on a conflict.""" # # NOTHING = "NOTHING" # UPDATE = "UPDATE" # # @classmethod # def all(cls) -> List["ConflictAction"]: # return [choice for choice in cls] . Output only the next line.
self, sql, params, conflict_action: ConflictAction, returning
Predict the next line after this snippet: <|code_start|> class Command(makemigrations.Command): help = "Creates new PostgreSQL specific migration(s) for apps." def handle(self, *app_labels, **options): <|code_end|> using the current file's imports: from django.core.management.commands import makemigrations from psqlextra.backend.migrations import postgres_patched_migrations and any relevant context from other files: # Path: psqlextra/backend/migrations/patched_migrations.py # @contextmanager # def postgres_patched_migrations(): # """Patches migration related classes/functions to extend how Django # generates and applies migrations. # # This adds support for automatically detecting changes in Postgres # specific models. # """ # # with patched_project_state(): # with patched_autodetector(): # yield . Output only the next line.
with postgres_patched_migrations():
Here is a snippet: <|code_start|> class SMA(TechnicalAnalysis): """ Simple Moving Average: Average closing price over a period SMA = avg(closes) = sum(closes) / len(closes) """ def eval_algorithm(closes): """ Evaluates the SMA algorithm Args: closes: List of price closes. Returns: Float average of closes. """ <|code_end|> . Write the next line using the current file imports: from speculator.features.TechnicalAnalysis import TechnicalAnalysis from speculator.utils import poloniex from speculator.utils import stats and context from other files: # Path: speculator/features/TechnicalAnalysis.py # class TechnicalAnalysis(abc.ABC): # """ Abstract class for calculating technical analysis indicators """ # # @staticmethod # @abc.abstractmethod # def eval_algorithm(*args, **kwargs): # """ Evaluates TA algorithm """ # # @staticmethod # @abc.abstractmethod # def eval_from_json(json): # """ Evaluates TA algorithm from JSON # # Args: # json: List of dates where each entry is a dict of raw market data. # """ # # Path: speculator/utils/poloniex.py # def json_to_url(json, symbol): # def chart_json(start, end, period, symbol): # def parse_changes(json): # def get_gains_losses(changes): # def get_attribute(json, attr): # def get_json_shift(year, month, day, unit, count, period, symbol): # # Path: speculator/utils/stats.py # def avg(vals, count=None): , which may include functions, classes, or code. Output only the next line.
return stats.avg(closes)
Given the following code snippet before the placeholder: <|code_start|> '=returnChartData&currencyPair={0}&start={1}' '&end={2}&period={3}').format(symbol, start, end, period) logger.debug(' HTTP Request URL:\n{0}'.format(url)) json = requests.get(url).json() logger.debug(' JSON:\n{0}'.format(json)) if 'error' in json: logger.error(' Invalid parameters in URL for HTTP response') raise SystemExit elif all(val == 0 for val in json[0]): logger.error(' Bad HTTP response. Time unit too short?') raise SystemExit elif len(json) < 1: # time to short logger.error(' Not enough dates to calculate changes') raise SystemExit return json, url def parse_changes(json): """ Gets price changes from JSON Args: json: JSON data as a list of dict dates, where the keys are the raw market statistics. Returns: List of floats of price changes between entries in JSON. """ changes = [] dates = len(json) <|code_end|> , predict the next line using imports from the current file: import logging import requests from speculator.utils import date and context including class names, function names, and sometimes code from other files: # Path: speculator/utils/date.py # def date_to_delorean(year, month, day): # def date_to_epoch(year, month, day): # def now_delorean(): # def shift_epoch(delorean, direction, unit, count): # def generate_epochs(delorean, direction, unit, count): # def get_end_start_epochs(year, month, day, direction, unit, count): . Output only the next line.
for date in range(1, dates):
Using the snippet: <|code_start|> EXPECTED_RESPONSE = [{'close': 999.36463982, 'date': 1483228800, 'high': 1008.54999326, 'low': 957.02, 'open': 965.00000055, 'quoteVolume': 1207.33863593, 'volume': 1196868.2615889, 'weightedAverage': 991.32772361}, {'close': 1019.00000076, 'date': 1483315200, 'high': 1034.32896003, 'low': 994.00000044, 'open': 999.92218873, 'quoteVolume': 1818.58703006, 'volume': 1847781.3863449, 'weightedAverage': 1016.0533182}] EXPECTED_CHANGES = ([EXPECTED_RESPONSE[1]['close'] - EXPECTED_RESPONSE[0]['close']]) YEAR = 2017 MONTH = 1 DAY = 1 UNIT = 'day' COUNT = 3 PERIOD = 86400 SYMBOL = 'USDT_BTC' EPOCH1 = 1483228800 # 01/01/2017, 00:00 epoch EPOCH2 = 1483315200 # 01/02/2017, 00:00 epoch <|code_end|> , determine the next line of code. You have imports: from speculator.utils import poloniex import unittest and context (class names, function names, or code) available: # Path: speculator/utils/poloniex.py # def json_to_url(json, symbol): # def chart_json(start, end, period, symbol): # def parse_changes(json): # def get_gains_losses(changes): # def get_attribute(json, attr): # def get_json_shift(year, month, day, unit, count, period, symbol): . Output only the next line.
HTTP_RESPONSE = poloniex.chart_json(EPOCH1, EPOCH2, PERIOD, SYMBOL)[0]
Here is a snippet: <|code_start|> %K follows the speed/momentum of a price in a market """ def eval_algorithm(closing, low, high): """ Evaluates the SO algorithm Args: closing: Float of current closing price. low: Float of lowest low closing price throughout some duration. high: Float of highest high closing price throughout some duration. Returns: Float SO between 0 and 100. """ if high - low == 0: # High and low are the same, zero division error return 100 * (closing - low) else: return 100 * (closing - low) / (high - low) def eval_from_json(json): """ Evaluates SO from JSON (typically Poloniex API response) Args: json: List of dates where each entry is a dict of raw market data. Returns: Float SO between 0 and 100. """ close = json[-1]['close'] # Latest closing price <|code_end|> . Write the next line using the current file imports: from speculator.features.TechnicalAnalysis import TechnicalAnalysis from speculator.utils import poloniex and context from other files: # Path: speculator/features/TechnicalAnalysis.py # class TechnicalAnalysis(abc.ABC): # """ Abstract class for calculating technical analysis indicators """ # # @staticmethod # @abc.abstractmethod # def eval_algorithm(*args, **kwargs): # """ Evaluates TA algorithm """ # # @staticmethod # @abc.abstractmethod # def eval_from_json(json): # """ Evaluates TA algorithm from JSON # # Args: # json: List of dates where each entry is a dict of raw market data. # """ # # Path: speculator/utils/poloniex.py # def json_to_url(json, symbol): # def chart_json(start, end, period, symbol): # def parse_changes(json): # def get_gains_losses(changes): # def get_attribute(json, attr): # def get_json_shift(year, month, day, unit, count, period, symbol): , which may include functions, classes, or code. Output only the next line.
low = min(poloniex.get_attribute(json, 'low')) # Lowest low
Continue the code snippet: <|code_start|> def eval_rs(gains, losses): """ Evaluates the RS variable in RSI algorithm Args: gains: List of price gains. losses: List of prices losses. Returns: Float of average gains over average losses. """ # Number of days that the data was collected through count = len(gains) + len(losses) avg_gains = stats.avg(gains, count=count) if gains else 1 avg_losses = stats.avg(losses,count=count) if losses else 1 if avg_losses == 0: return avg_gains else: return avg_gains / avg_losses def eval_from_json(json): """ Evaluates RSI from JSON (typically Poloniex API response) Args: json: List of dates where each entry is a dict of raw market data. Returns: Float between 0 and 100, momentum indicator of a market measuring the speed and change of price movements. """ <|code_end|> . Use current file imports: from speculator.features.TechnicalAnalysis import TechnicalAnalysis from speculator.utils import poloniex from speculator.utils import stats and context (classes, functions, or code) from other files: # Path: speculator/features/TechnicalAnalysis.py # class TechnicalAnalysis(abc.ABC): # """ Abstract class for calculating technical analysis indicators """ # # @staticmethod # @abc.abstractmethod # def eval_algorithm(*args, **kwargs): # """ Evaluates TA algorithm """ # # @staticmethod # @abc.abstractmethod # def eval_from_json(json): # """ Evaluates TA algorithm from JSON # # Args: # json: List of dates where each entry is a dict of raw market data. # """ # # Path: speculator/utils/poloniex.py # def json_to_url(json, symbol): # def chart_json(start, end, period, symbol): # def parse_changes(json): # def get_gains_losses(changes): # def get_attribute(json, attr): # def get_json_shift(year, month, day, unit, count, period, symbol): # # Path: speculator/utils/stats.py # def avg(vals, count=None): . Output only the next line.
changes = poloniex.get_gains_losses(poloniex.parse_changes(json))
Based on the snippet: <|code_start|> such that, RS = avg(t-period gain) / avg(t-period loss) """ def eval_algorithm(gains, losses): """ Evaluates the RSI algorithm Args: gains: List of price gains. losses: List of prices losses. Returns: Float between 0 and 100, momentum indicator of a market measuring the speed and change of price movements. """ return 100 - (100 / (1 + RSI.eval_rs(gains, losses))) def eval_rs(gains, losses): """ Evaluates the RS variable in RSI algorithm Args: gains: List of price gains. losses: List of prices losses. Returns: Float of average gains over average losses. """ # Number of days that the data was collected through count = len(gains) + len(losses) <|code_end|> , predict the immediate next line with the help of imports: from speculator.features.TechnicalAnalysis import TechnicalAnalysis from speculator.utils import poloniex from speculator.utils import stats and context (classes, functions, sometimes code) from other files: # Path: speculator/features/TechnicalAnalysis.py # class TechnicalAnalysis(abc.ABC): # """ Abstract class for calculating technical analysis indicators """ # # @staticmethod # @abc.abstractmethod # def eval_algorithm(*args, **kwargs): # """ Evaluates TA algorithm """ # # @staticmethod # @abc.abstractmethod # def eval_from_json(json): # """ Evaluates TA algorithm from JSON # # Args: # json: List of dates where each entry is a dict of raw market data. # """ # # Path: speculator/utils/poloniex.py # def json_to_url(json, symbol): # def chart_json(start, end, period, symbol): # def parse_changes(json): # def get_gains_losses(changes): # def get_attribute(json, attr): # def get_json_shift(year, month, day, unit, count, period, symbol): # # Path: speculator/utils/stats.py # def avg(vals, count=None): . Output only the next line.
avg_gains = stats.avg(gains, count=count) if gains else 1
Next line prediction: <|code_start|>tf.logging.set_verbosity(tf.logging.ERROR) class DeepNeuralNetwork(tf.estimator.DNNClassifier): def __init__(self, features, targets, **kwargs): feature_columns = [tf.feature_column.numeric_column(k) \ for k in features.train.columns] super().__init__(feature_columns=feature_columns, hidden_units=[10, 20, 10], <|code_end|> . Use current file imports: (import numpy as np import pandas as pd import tensorflow as tf from speculator import market) and context including class names, function names, or small code snippets from other files: # Path: speculator/market.py # TARGET_CODES = {'bearish': 0, 'neutral': 1, 'bullish': 2} # DIRECTION = 'last' # TARGET_NAMES = {v: k for k, v in TARGET_CODES.items()} # class Market: # def __init__(self, json=None, symbol='USDT_BTC', unit='month', count=6, period=86400): # def get_json(self): # def set_features(self, partition=1): # def set_long_features(self, features, columns_to_set=[], partition=2): # def set_targets(x, delta=10): # def eval_features(json): # def target_code_to_name(code): # def setup_model(x, y, model_type='random_forest', seed=None, **kwargs): . Output only the next line.
n_classes=len(market.TARGET_CODES))
Continue the code snippet: <|code_start|> v = -volume if close < close_prev """ def eval_algorithm(curr, prev): """ Evaluates OBV Args: curr: Dict of current volume and close prev: Dict of previous OBV and close Returns: Float of OBV """ if curr['close'] > prev['close']: v = curr['volume'] elif curr['close'] < prev['close']: v = curr['volume'] * -1 else: v = 0 return prev['obv'] + v def eval_from_json(json): """ Evaluates OBV from JSON (typically Poloniex API response) Args: json: List of dates where each entry is a dict of raw market data. Returns: Float of OBV """ <|code_end|> . Use current file imports: from speculator.features.TechnicalAnalysis import TechnicalAnalysis from speculator.utils import poloniex and context (classes, functions, or code) from other files: # Path: speculator/features/TechnicalAnalysis.py # class TechnicalAnalysis(abc.ABC): # """ Abstract class for calculating technical analysis indicators """ # # @staticmethod # @abc.abstractmethod # def eval_algorithm(*args, **kwargs): # """ Evaluates TA algorithm """ # # @staticmethod # @abc.abstractmethod # def eval_from_json(json): # """ Evaluates TA algorithm from JSON # # Args: # json: List of dates where each entry is a dict of raw market data. # """ # # Path: speculator/utils/poloniex.py # def json_to_url(json, symbol): # def chart_json(start, end, period, symbol): # def parse_changes(json): # def get_gains_losses(changes): # def get_attribute(json, attr): # def get_json_shift(year, month, day, unit, count, period, symbol): . Output only the next line.
closes = poloniex.get_attribute(json, 'close')
Using the snippet: <|code_start|> class SMATest(unittest.TestCase): def test_eval_algorithm(self): closes = [11, 12, 13, 14, 15, 16, 17] <|code_end|> , determine the next line of code. You have imports: from speculator.features.SMA import SMA import unittest and context (class names, function names, or code) available: # Path: speculator/features/SMA.py # class SMA(TechnicalAnalysis): # """ # Simple Moving Average: # Average closing price over a period # SMA = avg(closes) = sum(closes) / len(closes) # """ # # def eval_algorithm(closes): # """ Evaluates the SMA algorithm # # Args: # closes: List of price closes. # # Returns: # Float average of closes. # """ # return stats.avg(closes) # # def eval_from_json(json): # """ Evaluates SMA from JSON (typically Poloniex API response) # # Args: # json: List of dates where each entry is a dict of raw market data. # # Returns: # Float average of closes. # """ # closes = [date['close'] for date in json] # return SMA.eval_algorithm(closes) . Output only the next line.
self.assertEqual(SMA.eval_algorithm(closes), 14)
Next line prediction: <|code_start|> 'technical analysis calculation')) parser.add_argument('-sy', '--symbol', default='USDT_BTC', help=('Currency pair, symbol, or ticker, from Poloniex' 'Examples: USDT_BTC, ETH_ZRX, BTC_XRP')) parser.add_argument('-sd', '--seed', default=None, type=int, help=('Random state seed to be used when generating ' 'the Random Forest and training/test sets')) parser.add_argument('-l', '--long', nargs='*', help=('List of features to enable longer calculations. ' 'Example "--long rsi": 14 day RSI -> 28 day RSI')) parser.add_argument('-d', '--delta', default=25, type=int, help=('Price buffer in the neutral zone before' 'classifying a trend as bullish or bearish')) parser.add_argument('-t', '--trees', default=10, type=int, help=('Number of trees (estimators) to generate in ' 'the Random Forest, higher is usually better')) parser.add_argument('-j', '--jobs', default=1, type=int, help=('Number of jobs (CPUs for multithreading) when ' 'processing model fits and predictions')) parser.add_argument('--proba', default=False, action='store_true', help='Display probabilities of the predicted trend') parser.add_argument('--proba_log', default=False, action='store_true', help=('Display logarithmic probabilities of the ' 'predicted trend')) return parser.parse_args() def main(): args = get_args() assert args.partition > 0, 'The data must be partitioned!' <|code_end|> . Use current file imports: (import argparse import pandas as pd from datetime import datetime as dt from speculator import market from speculator import models) and context including class names, function names, or small code snippets from other files: # Path: speculator/market.py # TARGET_CODES = {'bearish': 0, 'neutral': 1, 'bullish': 2} # DIRECTION = 'last' # TARGET_NAMES = {v: k for k, v in TARGET_CODES.items()} # class Market: # def __init__(self, json=None, symbol='USDT_BTC', unit='month', count=6, period=86400): # def get_json(self): # def set_features(self, partition=1): # def set_long_features(self, features, columns_to_set=[], partition=2): # def set_targets(x, delta=10): # def eval_features(json): # def target_code_to_name(code): # def setup_model(x, y, model_type='random_forest', seed=None, **kwargs): . Output only the next line.
m = market.Market(symbol=args.symbol, unit=args.unit,
Given the code snippet: <|code_start|> class SOTest(unittest.TestCase): def test_eval_algorithm(self): closing = 127.29 low = 124.56 high = 128.43 <|code_end|> , generate the next line using the imports in this file: from speculator.features.SO import SO import unittest and context (functions, classes, or occasionally code) from other files: # Path: speculator/features/SO.py # class SO(TechnicalAnalysis): # """ # Stochastic Oscillator: # %K = 100 * (C - L(t)) / (H14 - L(t)) # such that, # C = Current closing Price # L(t) = Lowest Low over some duration t # H(t) = Highest High over some duration t # * t is usually 14 days # # %K follows the speed/momentum of a price in a market # """ # # def eval_algorithm(closing, low, high): # """ Evaluates the SO algorithm # # Args: # closing: Float of current closing price. # low: Float of lowest low closing price throughout some duration. # high: Float of highest high closing price throughout some duration. # # Returns: # Float SO between 0 and 100. # """ # if high - low == 0: # High and low are the same, zero division error # return 100 * (closing - low) # else: # return 100 * (closing - low) / (high - low) # # def eval_from_json(json): # """ Evaluates SO from JSON (typically Poloniex API response) # # Args: # json: List of dates where each entry is a dict of raw market data. # # Returns: # Float SO between 0 and 100. # """ # close = json[-1]['close'] # Latest closing price # low = min(poloniex.get_attribute(json, 'low')) # Lowest low # high = max(poloniex.get_attribute(json, 'high')) # Highest high # return SO.eval_algorithm(close, low, high) . Output only the next line.
self.assertAlmostEqual(SO.eval_algorithm(closing, low, high),
Predict the next line after this snippet: <|code_start|> class RSITest(unittest.TestCase): def test_eval_rs(self): gains = [0.07, 0.73, 0.51, 0.28, 0.34, 0.43, 0.25, 0.15, 0.68, 0.24] losses = [0.23, 0.53, 0.18, 0.40] <|code_end|> using the current file's imports: from speculator.features.RSI import RSI import unittest and any relevant context from other files: # Path: speculator/features/RSI.py # class RSI(TechnicalAnalysis): # """ # Relative Strength Index: # RSI = 100 - (100 / (1 + RS)) # such that, # RS = avg(t-period gain) / avg(t-period loss) # """ # # def eval_algorithm(gains, losses): # """ Evaluates the RSI algorithm # # Args: # gains: List of price gains. # losses: List of prices losses. # # Returns: # Float between 0 and 100, momentum indicator # of a market measuring the speed and change of price movements. # """ # return 100 - (100 / (1 + RSI.eval_rs(gains, losses))) # # def eval_rs(gains, losses): # """ Evaluates the RS variable in RSI algorithm # # Args: # gains: List of price gains. # losses: List of prices losses. # # Returns: # Float of average gains over average losses. # """ # # Number of days that the data was collected through # count = len(gains) + len(losses) # # avg_gains = stats.avg(gains, count=count) if gains else 1 # avg_losses = stats.avg(losses,count=count) if losses else 1 # if avg_losses == 0: # return avg_gains # else: # return avg_gains / avg_losses # # def eval_from_json(json): # """ Evaluates RSI from JSON (typically Poloniex API response) # # Args: # json: List of dates where each entry is a dict of raw market data. # # Returns: # Float between 0 and 100, momentum indicator # of a market measuring the speed and change of price movements. # """ # changes = poloniex.get_gains_losses(poloniex.parse_changes(json)) # return RSI.eval_algorithm(changes['gains'], changes['losses']) . Output only the next line.
self.assertAlmostEqual(RSI.eval_rs(gains, losses), 2.746, places=3)
Predict the next line for this snippet: <|code_start|> class StatsTest(unittest.TestCase): def test_avg(self): nums = [0.24, 0.62, 0.15, 0.83, 0.12345] <|code_end|> with the help of current file imports: from speculator.utils import stats import unittest and context from other files: # Path: speculator/utils/stats.py # def avg(vals, count=None): , which may contain function names, class names, or code. Output only the next line.
self.assertEqual(stats.avg(nums), 0.39269)
Given the following code snippet before the placeholder: <|code_start|> 'high': 1008.54999326, 'low': 957.02, 'open': 965.00000055, 'quoteVolume': 1207.33863593, 'volume': 1196868.2615889, 'weightedAverage': 991.32772361}, {'close': 1019.00000076, 'date': 1483315200, 'high': 1034.32896003, 'low': 994.00000044, 'open': 999.92218873, 'quoteVolume': 1818.58703006, 'volume': 1847781.3863449, 'weightedAverage': 1016.0533182}] EXPECTED_CHANGES = ([EXPECTED_RESPONSE[1]['close'] - EXPECTED_RESPONSE[0]['close']]) YEAR = 2017 MONTH = 1 DAY = 1 UNIT = 'day' COUNT = 3 PERIOD = 86400 # width of Candlesticks in seconds SYMBOL = 'USDT_BTC' EPOCH1 = 1483228800 # 01/01/2017, 00:00 epoch EPOCH2 = 1483315200 # 01/02/2017, 00:00 epoch class PoloniexTest(unittest.TestCase): def test_chart_json(self): <|code_end|> , predict the next line using imports from the current file: from speculator.utils import poloniex import unittest and context including class names, function names, and sometimes code from other files: # Path: speculator/utils/poloniex.py # def json_to_url(json, symbol): # def chart_json(start, end, period, symbol): # def parse_changes(json): # def get_gains_losses(changes): # def get_attribute(json, attr): # def get_json_shift(year, month, day, unit, count, period, symbol): . Output only the next line.
http_response = poloniex.chart_json(EPOCH1, EPOCH2, PERIOD, SYMBOL)[0]
Next line prediction: <|code_start|> class OBVTest(unittest.TestCase): def test_eval_algorithm_case1(self): # Case 1: close > close_prev, return obv + volume curr = {'close': 5, 'volume': 1} prev = {'close': 4, 'obv': 2} <|code_end|> . Use current file imports: (from speculator.features.OBV import OBV import unittest) and context including class names, function names, or small code snippets from other files: # Path: speculator/features/OBV.py # class OBV(TechnicalAnalysis): # """ # On Balance Volume: # OBV = OBV_prev + v # such that, # v = volume if close > close_prev # v = 0 if close == close_prev # v = -volume if close < close_prev # """ # # def eval_algorithm(curr, prev): # """ Evaluates OBV # # Args: # curr: Dict of current volume and close # prev: Dict of previous OBV and close # # Returns: # Float of OBV # """ # if curr['close'] > prev['close']: # v = curr['volume'] # elif curr['close'] < prev['close']: # v = curr['volume'] * -1 # else: # v = 0 # return prev['obv'] + v # # def eval_from_json(json): # """ Evaluates OBV from JSON (typically Poloniex API response) # # Args: # json: List of dates where each entry is a dict of raw market data. # # Returns: # Float of OBV # """ # closes = poloniex.get_attribute(json, 'close') # volumes = poloniex.get_attribute(json, 'volume') # obv = 0 # for date in range(1, len(json)): # curr = {'close': closes[date], 'volume': volumes[date]} # prev = {'close': closes[date - 1], 'obv': obv} # obv = OBV.eval_algorithm(curr, prev) # return obv . Output only the next line.
self.assertEqual(OBV.eval_algorithm(curr, prev), 3)
Given the following code snippet before the placeholder: <|code_start|> roles = [] # Check whether the current user is the creator of the current object. try: if user == self.creator: roles.append(Role.objects.get(name="Owner").id) except (AttributeError, Role.DoesNotExist): pass return super(Portal, self).has_permission(user, codename, roles) def check_permission(self, user, codename): """ Overwrites django-permissions' check_permission in order to add LFC specific groups. """ if not self.has_permission(user, codename): raise Unauthorized("'%s' doesn't have permission '%s' for portal." % (user, codename)) class AbstractBaseContent(models.Model, WorkflowBase, PermissionBase): """The root of all content types. It provides the inheritable BaseContentManager. **Attributes:** objects The default content manager of LFC. Provides a restricted method which takes care of the current user's permissions. """ <|code_end|> , predict the next line using imports from the current file: import datetime import re import workflows.utils import lfc.utils from django import template from django.conf import settings from django.contrib.auth.models import User from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.core.cache import cache from django.core.urlresolvers import reverse from django.db import models from django.template import RequestContext from django.template.loader import render_to_string from django.utils import translation from django.utils.translation import ugettext_lazy as _ from tagging import fields from tagging.models import Tag from tagging.models import TaggedItem from portlets.models import PortletAssignment from portlets.models import PortletBlocking from workflows import WorkflowBase from workflows.models import Workflow from workflows.models import State from workflows.models import StateObjectRelation from permissions import PermissionBase from permissions.exceptions import Unauthorized from permissions.models import Role from permissions.models import ObjectPermission from permissions.models import ObjectPermissionInheritanceBlock from lfc.fields.thumbs import ImageWithThumbsField from lfc.managers import BaseContentManager from lfc.settings import ALLOW_COMMENTS_CHOICES from lfc.settings import ALLOW_COMMENTS_DEFAULT from lfc.settings import ALLOW_COMMENTS_TRUE from lfc.settings import LANGUAGE_CHOICES from lfc.settings import ORDER_BY_CHOICES from lfc.settings import IMAGE_SIZES from lfc.settings import UPLOAD_FOLDER from lfc.manage.forms import AddForm and context including class names, function names, and sometimes code from other files: # Path: lfc/managers.py # class BaseContentManager(models.Manager): # """Custom manager for BaseContent. # """ # def get_queryset(self): # """Overwritten to return BaseContentQuerySet. # """ # return BaseContentQuerySet(self.model) # # Path: lfc/settings.py # ALLOW_COMMENTS_CHOICES = ( # (ALLOW_COMMENTS_DEFAULT, _(u"Default")), # (ALLOW_COMMENTS_TRUE, _(u"Yes")), # (ALLOW_COMMENTS_FALSE, _(u"No")), # ) # # Path: lfc/settings.py # ALLOW_COMMENTS_DEFAULT = 1 # # Path: lfc/settings.py # ALLOW_COMMENTS_TRUE = 2 # # Path: lfc/settings.py # LANGUAGE_CHOICES = [("0", _(u"Neutral"),)] # # Path: lfc/settings.py # ORDER_BY_CHOICES = ( # ("position", _(u"Position ascending")), # ("-position", _(u"Position descending")), # ("publication_date", _(u"Publication date ascending")), # ("-publication_date", _(u"Publication date descending")), # ) # # Path: lfc/settings.py # IMAGE_SIZES = getattr(settings, 'LFC_IMAGE_SIZES', ((60, 60), (100, 100), (200, 200), (400, 400), (600, 600), (800, 800))) # # Path: lfc/settings.py # UPLOAD_FOLDER = getattr(settings, 'LFC_UPLOAD_FOLDER', 'uploads') . Output only the next line.
objects = BaseContentManager()
Given the code snippet: <|code_start|> canonical = models.ForeignKey("self", verbose_name=_(u"Canonical"), related_name="translations", blank=True, null=True, on_delete=models.SET_NULL) tags = fields.TagField(_(u"Tags")) parent = models.ForeignKey("self", verbose_name=_(u"Parent"), blank=True, null=True, related_name="children") template = models.ForeignKey("Template", verbose_name=_(u"Template"), blank=True, null=True) standard = models.ForeignKey("self", verbose_name=_(u"Standard"), blank=True, null=True, on_delete=models.SET_NULL) order_by = models.CharField(_(u"Order by"), max_length=20, default="position", choices=ORDER_BY_CHOICES) exclude_from_navigation = models.BooleanField(_(u"Exclude from navigation"), default=False) exclude_from_search = models.BooleanField(_(u"Exclude from search results"), default=False) creator = models.ForeignKey(User, verbose_name=_(u"Creator"), null=True) creation_date = models.DateTimeField(_(u"Creation date"), auto_now_add=True) modification_date = models.DateTimeField(_(u"Modification date"), auto_now=True) publication_date = models.DateTimeField(_(u"Publication date"), null=True, blank=True) start_date = models.DateTimeField(_(u"Start date"), null=True, blank=True) end_date = models.DateTimeField(_(u"End date"), null=True, blank=True) meta_title = models.CharField(_(u"Meta title"), max_length=100, default="<portal_title> - <title>") meta_keywords = models.TextField(_(u"Meta keywords"), blank=True, default="<tags>") meta_description = models.TextField(_(u"Meta description"), blank=True, default="<description>") images = generic.GenericRelation("Image", verbose_name=_(u"Images"), object_id_field="content_id", content_type_field="content_type") files = generic.GenericRelation("File", verbose_name=_(u"Files"), object_id_field="content_id", content_type_field="content_type") allow_comments = models.PositiveSmallIntegerField(_(u"Commentable"), <|code_end|> , generate the next line using the imports in this file: import datetime import re import workflows.utils import lfc.utils from django import template from django.conf import settings from django.contrib.auth.models import User from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.core.cache import cache from django.core.urlresolvers import reverse from django.db import models from django.template import RequestContext from django.template.loader import render_to_string from django.utils import translation from django.utils.translation import ugettext_lazy as _ from tagging import fields from tagging.models import Tag from tagging.models import TaggedItem from portlets.models import PortletAssignment from portlets.models import PortletBlocking from workflows import WorkflowBase from workflows.models import Workflow from workflows.models import State from workflows.models import StateObjectRelation from permissions import PermissionBase from permissions.exceptions import Unauthorized from permissions.models import Role from permissions.models import ObjectPermission from permissions.models import ObjectPermissionInheritanceBlock from lfc.fields.thumbs import ImageWithThumbsField from lfc.managers import BaseContentManager from lfc.settings import ALLOW_COMMENTS_CHOICES from lfc.settings import ALLOW_COMMENTS_DEFAULT from lfc.settings import ALLOW_COMMENTS_TRUE from lfc.settings import LANGUAGE_CHOICES from lfc.settings import ORDER_BY_CHOICES from lfc.settings import IMAGE_SIZES from lfc.settings import UPLOAD_FOLDER from lfc.manage.forms import AddForm and context (functions, classes, or occasionally code) from other files: # Path: lfc/managers.py # class BaseContentManager(models.Manager): # """Custom manager for BaseContent. # """ # def get_queryset(self): # """Overwritten to return BaseContentQuerySet. # """ # return BaseContentQuerySet(self.model) # # Path: lfc/settings.py # ALLOW_COMMENTS_CHOICES = ( # (ALLOW_COMMENTS_DEFAULT, _(u"Default")), # (ALLOW_COMMENTS_TRUE, _(u"Yes")), # (ALLOW_COMMENTS_FALSE, _(u"No")), # ) # # Path: lfc/settings.py # ALLOW_COMMENTS_DEFAULT = 1 # # Path: lfc/settings.py # ALLOW_COMMENTS_TRUE = 2 # # Path: lfc/settings.py # LANGUAGE_CHOICES = [("0", _(u"Neutral"),)] # # Path: lfc/settings.py # ORDER_BY_CHOICES = ( # ("position", _(u"Position ascending")), # ("-position", _(u"Position descending")), # ("publication_date", _(u"Publication date ascending")), # ("-publication_date", _(u"Publication date descending")), # ) # # Path: lfc/settings.py # IMAGE_SIZES = getattr(settings, 'LFC_IMAGE_SIZES', ((60, 60), (100, 100), (200, 200), (400, 400), (600, 600), (800, 800))) # # Path: lfc/settings.py # UPLOAD_FOLDER = getattr(settings, 'LFC_UPLOAD_FOLDER', 'uploads') . Output only the next line.
choices=ALLOW_COMMENTS_CHOICES, default=ALLOW_COMMENTS_DEFAULT)
Given snippet: <|code_start|> canonical = models.ForeignKey("self", verbose_name=_(u"Canonical"), related_name="translations", blank=True, null=True, on_delete=models.SET_NULL) tags = fields.TagField(_(u"Tags")) parent = models.ForeignKey("self", verbose_name=_(u"Parent"), blank=True, null=True, related_name="children") template = models.ForeignKey("Template", verbose_name=_(u"Template"), blank=True, null=True) standard = models.ForeignKey("self", verbose_name=_(u"Standard"), blank=True, null=True, on_delete=models.SET_NULL) order_by = models.CharField(_(u"Order by"), max_length=20, default="position", choices=ORDER_BY_CHOICES) exclude_from_navigation = models.BooleanField(_(u"Exclude from navigation"), default=False) exclude_from_search = models.BooleanField(_(u"Exclude from search results"), default=False) creator = models.ForeignKey(User, verbose_name=_(u"Creator"), null=True) creation_date = models.DateTimeField(_(u"Creation date"), auto_now_add=True) modification_date = models.DateTimeField(_(u"Modification date"), auto_now=True) publication_date = models.DateTimeField(_(u"Publication date"), null=True, blank=True) start_date = models.DateTimeField(_(u"Start date"), null=True, blank=True) end_date = models.DateTimeField(_(u"End date"), null=True, blank=True) meta_title = models.CharField(_(u"Meta title"), max_length=100, default="<portal_title> - <title>") meta_keywords = models.TextField(_(u"Meta keywords"), blank=True, default="<tags>") meta_description = models.TextField(_(u"Meta description"), blank=True, default="<description>") images = generic.GenericRelation("Image", verbose_name=_(u"Images"), object_id_field="content_id", content_type_field="content_type") files = generic.GenericRelation("File", verbose_name=_(u"Files"), object_id_field="content_id", content_type_field="content_type") allow_comments = models.PositiveSmallIntegerField(_(u"Commentable"), <|code_end|> , continue by predicting the next line. Consider current file imports: import datetime import re import workflows.utils import lfc.utils from django import template from django.conf import settings from django.contrib.auth.models import User from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.core.cache import cache from django.core.urlresolvers import reverse from django.db import models from django.template import RequestContext from django.template.loader import render_to_string from django.utils import translation from django.utils.translation import ugettext_lazy as _ from tagging import fields from tagging.models import Tag from tagging.models import TaggedItem from portlets.models import PortletAssignment from portlets.models import PortletBlocking from workflows import WorkflowBase from workflows.models import Workflow from workflows.models import State from workflows.models import StateObjectRelation from permissions import PermissionBase from permissions.exceptions import Unauthorized from permissions.models import Role from permissions.models import ObjectPermission from permissions.models import ObjectPermissionInheritanceBlock from lfc.fields.thumbs import ImageWithThumbsField from lfc.managers import BaseContentManager from lfc.settings import ALLOW_COMMENTS_CHOICES from lfc.settings import ALLOW_COMMENTS_DEFAULT from lfc.settings import ALLOW_COMMENTS_TRUE from lfc.settings import LANGUAGE_CHOICES from lfc.settings import ORDER_BY_CHOICES from lfc.settings import IMAGE_SIZES from lfc.settings import UPLOAD_FOLDER from lfc.manage.forms import AddForm and context: # Path: lfc/managers.py # class BaseContentManager(models.Manager): # """Custom manager for BaseContent. # """ # def get_queryset(self): # """Overwritten to return BaseContentQuerySet. # """ # return BaseContentQuerySet(self.model) # # Path: lfc/settings.py # ALLOW_COMMENTS_CHOICES = ( # (ALLOW_COMMENTS_DEFAULT, _(u"Default")), # (ALLOW_COMMENTS_TRUE, _(u"Yes")), # (ALLOW_COMMENTS_FALSE, _(u"No")), # ) # # Path: lfc/settings.py # ALLOW_COMMENTS_DEFAULT = 1 # # Path: lfc/settings.py # ALLOW_COMMENTS_TRUE = 2 # # Path: lfc/settings.py # LANGUAGE_CHOICES = [("0", _(u"Neutral"),)] # # Path: lfc/settings.py # ORDER_BY_CHOICES = ( # ("position", _(u"Position ascending")), # ("-position", _(u"Position descending")), # ("publication_date", _(u"Publication date ascending")), # ("-publication_date", _(u"Publication date descending")), # ) # # Path: lfc/settings.py # IMAGE_SIZES = getattr(settings, 'LFC_IMAGE_SIZES', ((60, 60), (100, 100), (200, 200), (400, 400), (600, 600), (800, 800))) # # Path: lfc/settings.py # UPLOAD_FOLDER = getattr(settings, 'LFC_UPLOAD_FOLDER', 'uploads') which might include code, classes, or functions. Output only the next line.
choices=ALLOW_COMMENTS_CHOICES, default=ALLOW_COMMENTS_DEFAULT)
Using the snippet: <|code_start|> def get_translation(self, request, language): """Returns connected translation for requested language. Returns None if the requested language doesn't exist. """ # TODO: Should there a instance be returned even if the instance is a # translation? if self.is_translation(): return None try: translation = self.translations.get(language=language).get_content_object() if translation.has_permission(request.user, "view"): return translation else: return None except BaseContent.DoesNotExist: return None def are_comments_allowed(self): """Returns true if comments for this instance are allowed. Takes also the setup of parent objects into account (if the instance' comments setup is set to "default"). """ if self.allow_comments == ALLOW_COMMENTS_DEFAULT: if self.parent: return self.parent.are_comments_allowed() else: return lfc.utils.get_portal().are_comments_allowed() else: <|code_end|> , determine the next line of code. You have imports: import datetime import re import workflows.utils import lfc.utils from django import template from django.conf import settings from django.contrib.auth.models import User from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.core.cache import cache from django.core.urlresolvers import reverse from django.db import models from django.template import RequestContext from django.template.loader import render_to_string from django.utils import translation from django.utils.translation import ugettext_lazy as _ from tagging import fields from tagging.models import Tag from tagging.models import TaggedItem from portlets.models import PortletAssignment from portlets.models import PortletBlocking from workflows import WorkflowBase from workflows.models import Workflow from workflows.models import State from workflows.models import StateObjectRelation from permissions import PermissionBase from permissions.exceptions import Unauthorized from permissions.models import Role from permissions.models import ObjectPermission from permissions.models import ObjectPermissionInheritanceBlock from lfc.fields.thumbs import ImageWithThumbsField from lfc.managers import BaseContentManager from lfc.settings import ALLOW_COMMENTS_CHOICES from lfc.settings import ALLOW_COMMENTS_DEFAULT from lfc.settings import ALLOW_COMMENTS_TRUE from lfc.settings import LANGUAGE_CHOICES from lfc.settings import ORDER_BY_CHOICES from lfc.settings import IMAGE_SIZES from lfc.settings import UPLOAD_FOLDER from lfc.manage.forms import AddForm and context (class names, function names, or code) available: # Path: lfc/managers.py # class BaseContentManager(models.Manager): # """Custom manager for BaseContent. # """ # def get_queryset(self): # """Overwritten to return BaseContentQuerySet. # """ # return BaseContentQuerySet(self.model) # # Path: lfc/settings.py # ALLOW_COMMENTS_CHOICES = ( # (ALLOW_COMMENTS_DEFAULT, _(u"Default")), # (ALLOW_COMMENTS_TRUE, _(u"Yes")), # (ALLOW_COMMENTS_FALSE, _(u"No")), # ) # # Path: lfc/settings.py # ALLOW_COMMENTS_DEFAULT = 1 # # Path: lfc/settings.py # ALLOW_COMMENTS_TRUE = 2 # # Path: lfc/settings.py # LANGUAGE_CHOICES = [("0", _(u"Neutral"),)] # # Path: lfc/settings.py # ORDER_BY_CHOICES = ( # ("position", _(u"Position ascending")), # ("-position", _(u"Position descending")), # ("publication_date", _(u"Publication date ascending")), # ("-publication_date", _(u"Publication date descending")), # ) # # Path: lfc/settings.py # IMAGE_SIZES = getattr(settings, 'LFC_IMAGE_SIZES', ((60, 60), (100, 100), (200, 200), (400, 400), (600, 600), (800, 800))) # # Path: lfc/settings.py # UPLOAD_FOLDER = getattr(settings, 'LFC_UPLOAD_FOLDER', 'uploads') . Output only the next line.
if self.allow_comments == ALLOW_COMMENTS_TRUE:
Based on the snippet: <|code_start|> meta_description The meta description of the object. This is displayed within the meta description tag of the rendered HTML. images The images of the object. files The files of the object. allow_comments If set to true, the visitor of the object can leave a comment. If set to default the allow_comments state of the parent object is overtaken. searchable_text The content which is searched for this object. This attribute should not get directly. Rather the get_searchable_text method should be used. """ content_type = models.CharField(_(u"Content type"), max_length=100, blank=True) title = models.CharField(_(u"Title"), max_length=100) display_title = models.BooleanField(_(u"Display title"), default=True) slug = models.SlugField(_(u"Slug"), max_length=100) description = models.TextField(_(u"Description"), blank=True) position = models.PositiveSmallIntegerField(_(u"Position"), default=1) <|code_end|> , predict the immediate next line with the help of imports: import datetime import re import workflows.utils import lfc.utils from django import template from django.conf import settings from django.contrib.auth.models import User from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.core.cache import cache from django.core.urlresolvers import reverse from django.db import models from django.template import RequestContext from django.template.loader import render_to_string from django.utils import translation from django.utils.translation import ugettext_lazy as _ from tagging import fields from tagging.models import Tag from tagging.models import TaggedItem from portlets.models import PortletAssignment from portlets.models import PortletBlocking from workflows import WorkflowBase from workflows.models import Workflow from workflows.models import State from workflows.models import StateObjectRelation from permissions import PermissionBase from permissions.exceptions import Unauthorized from permissions.models import Role from permissions.models import ObjectPermission from permissions.models import ObjectPermissionInheritanceBlock from lfc.fields.thumbs import ImageWithThumbsField from lfc.managers import BaseContentManager from lfc.settings import ALLOW_COMMENTS_CHOICES from lfc.settings import ALLOW_COMMENTS_DEFAULT from lfc.settings import ALLOW_COMMENTS_TRUE from lfc.settings import LANGUAGE_CHOICES from lfc.settings import ORDER_BY_CHOICES from lfc.settings import IMAGE_SIZES from lfc.settings import UPLOAD_FOLDER from lfc.manage.forms import AddForm and context (classes, functions, sometimes code) from other files: # Path: lfc/managers.py # class BaseContentManager(models.Manager): # """Custom manager for BaseContent. # """ # def get_queryset(self): # """Overwritten to return BaseContentQuerySet. # """ # return BaseContentQuerySet(self.model) # # Path: lfc/settings.py # ALLOW_COMMENTS_CHOICES = ( # (ALLOW_COMMENTS_DEFAULT, _(u"Default")), # (ALLOW_COMMENTS_TRUE, _(u"Yes")), # (ALLOW_COMMENTS_FALSE, _(u"No")), # ) # # Path: lfc/settings.py # ALLOW_COMMENTS_DEFAULT = 1 # # Path: lfc/settings.py # ALLOW_COMMENTS_TRUE = 2 # # Path: lfc/settings.py # LANGUAGE_CHOICES = [("0", _(u"Neutral"),)] # # Path: lfc/settings.py # ORDER_BY_CHOICES = ( # ("position", _(u"Position ascending")), # ("-position", _(u"Position descending")), # ("publication_date", _(u"Publication date ascending")), # ("-publication_date", _(u"Publication date descending")), # ) # # Path: lfc/settings.py # IMAGE_SIZES = getattr(settings, 'LFC_IMAGE_SIZES', ((60, 60), (100, 100), (200, 200), (400, 400), (600, 600), (800, 800))) # # Path: lfc/settings.py # UPLOAD_FOLDER = getattr(settings, 'LFC_UPLOAD_FOLDER', 'uploads') . Output only the next line.
language = models.CharField(_(u"Language"), max_length=10, choices=LANGUAGE_CHOICES, default="0")
Here is a snippet: <|code_start|> files The files of the object. allow_comments If set to true, the visitor of the object can leave a comment. If set to default the allow_comments state of the parent object is overtaken. searchable_text The content which is searched for this object. This attribute should not get directly. Rather the get_searchable_text method should be used. """ content_type = models.CharField(_(u"Content type"), max_length=100, blank=True) title = models.CharField(_(u"Title"), max_length=100) display_title = models.BooleanField(_(u"Display title"), default=True) slug = models.SlugField(_(u"Slug"), max_length=100) description = models.TextField(_(u"Description"), blank=True) position = models.PositiveSmallIntegerField(_(u"Position"), default=1) language = models.CharField(_(u"Language"), max_length=10, choices=LANGUAGE_CHOICES, default="0") canonical = models.ForeignKey("self", verbose_name=_(u"Canonical"), related_name="translations", blank=True, null=True, on_delete=models.SET_NULL) tags = fields.TagField(_(u"Tags")) parent = models.ForeignKey("self", verbose_name=_(u"Parent"), blank=True, null=True, related_name="children") template = models.ForeignKey("Template", verbose_name=_(u"Template"), blank=True, null=True) standard = models.ForeignKey("self", verbose_name=_(u"Standard"), blank=True, null=True, on_delete=models.SET_NULL) <|code_end|> . Write the next line using the current file imports: import datetime import re import workflows.utils import lfc.utils from django import template from django.conf import settings from django.contrib.auth.models import User from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.core.cache import cache from django.core.urlresolvers import reverse from django.db import models from django.template import RequestContext from django.template.loader import render_to_string from django.utils import translation from django.utils.translation import ugettext_lazy as _ from tagging import fields from tagging.models import Tag from tagging.models import TaggedItem from portlets.models import PortletAssignment from portlets.models import PortletBlocking from workflows import WorkflowBase from workflows.models import Workflow from workflows.models import State from workflows.models import StateObjectRelation from permissions import PermissionBase from permissions.exceptions import Unauthorized from permissions.models import Role from permissions.models import ObjectPermission from permissions.models import ObjectPermissionInheritanceBlock from lfc.fields.thumbs import ImageWithThumbsField from lfc.managers import BaseContentManager from lfc.settings import ALLOW_COMMENTS_CHOICES from lfc.settings import ALLOW_COMMENTS_DEFAULT from lfc.settings import ALLOW_COMMENTS_TRUE from lfc.settings import LANGUAGE_CHOICES from lfc.settings import ORDER_BY_CHOICES from lfc.settings import IMAGE_SIZES from lfc.settings import UPLOAD_FOLDER from lfc.manage.forms import AddForm and context from other files: # Path: lfc/managers.py # class BaseContentManager(models.Manager): # """Custom manager for BaseContent. # """ # def get_queryset(self): # """Overwritten to return BaseContentQuerySet. # """ # return BaseContentQuerySet(self.model) # # Path: lfc/settings.py # ALLOW_COMMENTS_CHOICES = ( # (ALLOW_COMMENTS_DEFAULT, _(u"Default")), # (ALLOW_COMMENTS_TRUE, _(u"Yes")), # (ALLOW_COMMENTS_FALSE, _(u"No")), # ) # # Path: lfc/settings.py # ALLOW_COMMENTS_DEFAULT = 1 # # Path: lfc/settings.py # ALLOW_COMMENTS_TRUE = 2 # # Path: lfc/settings.py # LANGUAGE_CHOICES = [("0", _(u"Neutral"),)] # # Path: lfc/settings.py # ORDER_BY_CHOICES = ( # ("position", _(u"Position ascending")), # ("-position", _(u"Position descending")), # ("publication_date", _(u"Publication date ascending")), # ("-publication_date", _(u"Publication date descending")), # ) # # Path: lfc/settings.py # IMAGE_SIZES = getattr(settings, 'LFC_IMAGE_SIZES', ((60, 60), (100, 100), (200, 200), (400, 400), (600, 600), (800, 800))) # # Path: lfc/settings.py # UPLOAD_FOLDER = getattr(settings, 'LFC_UPLOAD_FOLDER', 'uploads') , which may include functions, classes, or code. Output only the next line.
order_by = models.CharField(_(u"Order by"), max_length=20, default="position", choices=ORDER_BY_CHOICES)
Continue the code snippet: <|code_start|> slug The URL of the image content The content object the image belongs to (optional) position The ord number within the content object caption The caption of the image. Can be used within the content (optional) description A description of the image. Can be used within the content (optional) image The image file. """ title = models.CharField(_(u"Title"), blank=True, max_length=100) slug = models.SlugField(_(u"Slug"), max_length=100) content_type = models.ForeignKey(ContentType, verbose_name=_(u"Content type"), related_name="images", blank=True, null=True) content_id = models.PositiveIntegerField(_(u"Content id"), blank=True, null=True) content = generic.GenericForeignKey(ct_field="content_type", fk_field="content_id") position = models.SmallIntegerField(_(u"Position"), default=999) caption = models.CharField(_(u"Caption"), blank=True, max_length=100) description = models.TextField(_(u"Description"), blank=True) creation_date = models.DateTimeField(_(u"Creation date"), auto_now_add=True) <|code_end|> . Use current file imports: import datetime import re import workflows.utils import lfc.utils from django import template from django.conf import settings from django.contrib.auth.models import User from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.core.cache import cache from django.core.urlresolvers import reverse from django.db import models from django.template import RequestContext from django.template.loader import render_to_string from django.utils import translation from django.utils.translation import ugettext_lazy as _ from tagging import fields from tagging.models import Tag from tagging.models import TaggedItem from portlets.models import PortletAssignment from portlets.models import PortletBlocking from workflows import WorkflowBase from workflows.models import Workflow from workflows.models import State from workflows.models import StateObjectRelation from permissions import PermissionBase from permissions.exceptions import Unauthorized from permissions.models import Role from permissions.models import ObjectPermission from permissions.models import ObjectPermissionInheritanceBlock from lfc.fields.thumbs import ImageWithThumbsField from lfc.managers import BaseContentManager from lfc.settings import ALLOW_COMMENTS_CHOICES from lfc.settings import ALLOW_COMMENTS_DEFAULT from lfc.settings import ALLOW_COMMENTS_TRUE from lfc.settings import LANGUAGE_CHOICES from lfc.settings import ORDER_BY_CHOICES from lfc.settings import IMAGE_SIZES from lfc.settings import UPLOAD_FOLDER from lfc.manage.forms import AddForm and context (classes, functions, or code) from other files: # Path: lfc/managers.py # class BaseContentManager(models.Manager): # """Custom manager for BaseContent. # """ # def get_queryset(self): # """Overwritten to return BaseContentQuerySet. # """ # return BaseContentQuerySet(self.model) # # Path: lfc/settings.py # ALLOW_COMMENTS_CHOICES = ( # (ALLOW_COMMENTS_DEFAULT, _(u"Default")), # (ALLOW_COMMENTS_TRUE, _(u"Yes")), # (ALLOW_COMMENTS_FALSE, _(u"No")), # ) # # Path: lfc/settings.py # ALLOW_COMMENTS_DEFAULT = 1 # # Path: lfc/settings.py # ALLOW_COMMENTS_TRUE = 2 # # Path: lfc/settings.py # LANGUAGE_CHOICES = [("0", _(u"Neutral"),)] # # Path: lfc/settings.py # ORDER_BY_CHOICES = ( # ("position", _(u"Position ascending")), # ("-position", _(u"Position descending")), # ("publication_date", _(u"Publication date ascending")), # ("-publication_date", _(u"Publication date descending")), # ) # # Path: lfc/settings.py # IMAGE_SIZES = getattr(settings, 'LFC_IMAGE_SIZES', ((60, 60), (100, 100), (200, 200), (400, 400), (600, 600), (800, 800))) # # Path: lfc/settings.py # UPLOAD_FOLDER = getattr(settings, 'LFC_UPLOAD_FOLDER', 'uploads') . Output only the next line.
image = ImageWithThumbsField(_(u"Image"), upload_to=UPLOAD_FOLDER, sizes=IMAGE_SIZES)
Using the snippet: <|code_start|> slug The URL of the image content The content object the image belongs to (optional) position The ord number within the content object caption The caption of the image. Can be used within the content (optional) description A description of the image. Can be used within the content (optional) image The image file. """ title = models.CharField(_(u"Title"), blank=True, max_length=100) slug = models.SlugField(_(u"Slug"), max_length=100) content_type = models.ForeignKey(ContentType, verbose_name=_(u"Content type"), related_name="images", blank=True, null=True) content_id = models.PositiveIntegerField(_(u"Content id"), blank=True, null=True) content = generic.GenericForeignKey(ct_field="content_type", fk_field="content_id") position = models.SmallIntegerField(_(u"Position"), default=999) caption = models.CharField(_(u"Caption"), blank=True, max_length=100) description = models.TextField(_(u"Description"), blank=True) creation_date = models.DateTimeField(_(u"Creation date"), auto_now_add=True) <|code_end|> , determine the next line of code. You have imports: import datetime import re import workflows.utils import lfc.utils from django import template from django.conf import settings from django.contrib.auth.models import User from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.core.cache import cache from django.core.urlresolvers import reverse from django.db import models from django.template import RequestContext from django.template.loader import render_to_string from django.utils import translation from django.utils.translation import ugettext_lazy as _ from tagging import fields from tagging.models import Tag from tagging.models import TaggedItem from portlets.models import PortletAssignment from portlets.models import PortletBlocking from workflows import WorkflowBase from workflows.models import Workflow from workflows.models import State from workflows.models import StateObjectRelation from permissions import PermissionBase from permissions.exceptions import Unauthorized from permissions.models import Role from permissions.models import ObjectPermission from permissions.models import ObjectPermissionInheritanceBlock from lfc.fields.thumbs import ImageWithThumbsField from lfc.managers import BaseContentManager from lfc.settings import ALLOW_COMMENTS_CHOICES from lfc.settings import ALLOW_COMMENTS_DEFAULT from lfc.settings import ALLOW_COMMENTS_TRUE from lfc.settings import LANGUAGE_CHOICES from lfc.settings import ORDER_BY_CHOICES from lfc.settings import IMAGE_SIZES from lfc.settings import UPLOAD_FOLDER from lfc.manage.forms import AddForm and context (class names, function names, or code) available: # Path: lfc/managers.py # class BaseContentManager(models.Manager): # """Custom manager for BaseContent. # """ # def get_queryset(self): # """Overwritten to return BaseContentQuerySet. # """ # return BaseContentQuerySet(self.model) # # Path: lfc/settings.py # ALLOW_COMMENTS_CHOICES = ( # (ALLOW_COMMENTS_DEFAULT, _(u"Default")), # (ALLOW_COMMENTS_TRUE, _(u"Yes")), # (ALLOW_COMMENTS_FALSE, _(u"No")), # ) # # Path: lfc/settings.py # ALLOW_COMMENTS_DEFAULT = 1 # # Path: lfc/settings.py # ALLOW_COMMENTS_TRUE = 2 # # Path: lfc/settings.py # LANGUAGE_CHOICES = [("0", _(u"Neutral"),)] # # Path: lfc/settings.py # ORDER_BY_CHOICES = ( # ("position", _(u"Position ascending")), # ("-position", _(u"Position descending")), # ("publication_date", _(u"Publication date ascending")), # ("-publication_date", _(u"Publication date descending")), # ) # # Path: lfc/settings.py # IMAGE_SIZES = getattr(settings, 'LFC_IMAGE_SIZES', ((60, 60), (100, 100), (200, 200), (400, 400), (600, 600), (800, 800))) # # Path: lfc/settings.py # UPLOAD_FOLDER = getattr(settings, 'LFC_UPLOAD_FOLDER', 'uploads') . Output only the next line.
image = ImageWithThumbsField(_(u"Image"), upload_to=UPLOAD_FOLDER, sizes=IMAGE_SIZES)
Given the following code snippet before the placeholder: <|code_start|> # lfc imports # lfc_page imports class WorkingCopyTestCase(TestCase): """ Tests related to working copy. """ def setUp(self): self.user = User.objects.create(username="admin", is_active=True, is_superuser=True) call_command('lfc_init_simple') self.p1 = Page.objects.create(title="Page 1", slug="page-1") def test_working_cycle(self): request = create_request() self.assertEqual(Page.objects.count(), 2) checkout(request, self.p1.id) self.assertEqual(Page.objects.count(), 3) self.assertTrue(self.p1.has_working_copy()) self.assertFalse(self.p1.is_working_copy()) wc = self.p1.get_working_copy() self.assertFalse(wc.has_working_copy()) self.assertTrue(wc.is_working_copy()) <|code_end|> , predict the next line using imports from the current file: from django.contrib.auth.models import User from django.core.management import call_command from django.test import TestCase from lfc.manage.views import checkin from lfc.manage.views import checkout from lfc.tests.utils import create_request from lfc_page.models import Page and context including class names, function names, and sometimes code from other files: # Path: lfc/manage/views.py # def checkin(request, id): # """ # Checks in the working copy with passed id. # """ # working_copy = lfc.utils.get_content_object(pk=id) # # if not working_copy.is_working_copy(): # url = reverse("lfc_manage_object", kwargs={"id": working_copy.id}) # return MessageHttpResponseRedirect(url, _(u"Object is not a working copy.")) # # working_copy.check_permission(request.user, "checkin") # # # Save some values of the base for later use. # base = working_copy.working_copy_base # base_id = base.id # base_slug = base.slug # base_parent = base.parent # base_parent_standard = base.parent.standard if base.parent else None # base_state = base.get_content_object().get_state() # base_position = base.position # base.delete() # # # Set default values # working_copy.slug = base_slug # working_copy.set_state(base_state) # working_copy.position = base_position # working_copy.save() # # # Point to wc if the base was standard object of the parent # if not base_parent: # base_parent = lfc.utils.get_portal() # # if base_parent_standard and (base_parent_standard.id == base_id): # base_parent.standard = working_copy.basecontent_ptr # base_parent.save() # lfc.utils.clear_cache() # # _update_positions(working_copy.parent) # # return HttpResponseRedirect(reverse("lfc_manage_object", kwargs={"id": working_copy.id})) # # Path: lfc/manage/views.py # def checkout(request, id): # """ # Checks out a working copy for the object with the passed id. # # **Parameters:** # # id # The id of the object for which a working copy is created. # """ # source_obj = lfc.utils.get_content_object(pk=id) # source_obj.check_permission(request.user, "checkout") # # if source_obj.has_working_copy(): # url = reverse("lfc_manage_object", kwargs={"id": source_obj.id}) # return MessageHttpResponseRedirect(url, _(u"Object has already a working copy.")) # # new_obj = copy.deepcopy(source_obj) # new_obj.pk = None # new_obj.id = None # new_obj.parent = source_obj.parent # new_obj.position = source_obj.position + 1 # # new_obj.slug = _generate_slug(new_obj, source_obj.parent) # # # Workaround for django-tagging # try: # new_obj.save() # except IntegrityError: # pass # # _copy_images(source_obj, new_obj) # _copy_files(source_obj, new_obj) # _copy_portlets(source_obj, new_obj) # _copy_translations(source_obj, new_obj) # _copy_history(source_obj, new_obj) # # # Prevent recursion # if (new_obj not in source_obj.get_descendants()) and (new_obj != source_obj): # _copy_descendants(source_obj, new_obj) # # new_obj.working_copy_base = source_obj # new_obj.save() # # _update_positions(new_obj.parent) # # return HttpResponseRedirect(reverse("lfc_manage_object", kwargs={"id": new_obj.id})) # # Path: lfc/tests/utils.py # def create_request(path="/", params=None): # """ # """ # if params is None: # params = {} # # rf = RequestFactory() # request = rf.get(path, params) # request.session = SessionStore() # # user = User() # user.is_superuser = True # user.save() # request.user = user # # return request . Output only the next line.
checkin(request, wc.id)
Based on the snippet: <|code_start|># django imports # lfc imports # lfc_page imports class WorkingCopyTestCase(TestCase): """ Tests related to working copy. """ def setUp(self): self.user = User.objects.create(username="admin", is_active=True, is_superuser=True) call_command('lfc_init_simple') self.p1 = Page.objects.create(title="Page 1", slug="page-1") def test_working_cycle(self): request = create_request() self.assertEqual(Page.objects.count(), 2) <|code_end|> , predict the immediate next line with the help of imports: from django.contrib.auth.models import User from django.core.management import call_command from django.test import TestCase from lfc.manage.views import checkin from lfc.manage.views import checkout from lfc.tests.utils import create_request from lfc_page.models import Page and context (classes, functions, sometimes code) from other files: # Path: lfc/manage/views.py # def checkin(request, id): # """ # Checks in the working copy with passed id. # """ # working_copy = lfc.utils.get_content_object(pk=id) # # if not working_copy.is_working_copy(): # url = reverse("lfc_manage_object", kwargs={"id": working_copy.id}) # return MessageHttpResponseRedirect(url, _(u"Object is not a working copy.")) # # working_copy.check_permission(request.user, "checkin") # # # Save some values of the base for later use. # base = working_copy.working_copy_base # base_id = base.id # base_slug = base.slug # base_parent = base.parent # base_parent_standard = base.parent.standard if base.parent else None # base_state = base.get_content_object().get_state() # base_position = base.position # base.delete() # # # Set default values # working_copy.slug = base_slug # working_copy.set_state(base_state) # working_copy.position = base_position # working_copy.save() # # # Point to wc if the base was standard object of the parent # if not base_parent: # base_parent = lfc.utils.get_portal() # # if base_parent_standard and (base_parent_standard.id == base_id): # base_parent.standard = working_copy.basecontent_ptr # base_parent.save() # lfc.utils.clear_cache() # # _update_positions(working_copy.parent) # # return HttpResponseRedirect(reverse("lfc_manage_object", kwargs={"id": working_copy.id})) # # Path: lfc/manage/views.py # def checkout(request, id): # """ # Checks out a working copy for the object with the passed id. # # **Parameters:** # # id # The id of the object for which a working copy is created. # """ # source_obj = lfc.utils.get_content_object(pk=id) # source_obj.check_permission(request.user, "checkout") # # if source_obj.has_working_copy(): # url = reverse("lfc_manage_object", kwargs={"id": source_obj.id}) # return MessageHttpResponseRedirect(url, _(u"Object has already a working copy.")) # # new_obj = copy.deepcopy(source_obj) # new_obj.pk = None # new_obj.id = None # new_obj.parent = source_obj.parent # new_obj.position = source_obj.position + 1 # # new_obj.slug = _generate_slug(new_obj, source_obj.parent) # # # Workaround for django-tagging # try: # new_obj.save() # except IntegrityError: # pass # # _copy_images(source_obj, new_obj) # _copy_files(source_obj, new_obj) # _copy_portlets(source_obj, new_obj) # _copy_translations(source_obj, new_obj) # _copy_history(source_obj, new_obj) # # # Prevent recursion # if (new_obj not in source_obj.get_descendants()) and (new_obj != source_obj): # _copy_descendants(source_obj, new_obj) # # new_obj.working_copy_base = source_obj # new_obj.save() # # _update_positions(new_obj.parent) # # return HttpResponseRedirect(reverse("lfc_manage_object", kwargs={"id": new_obj.id})) # # Path: lfc/tests/utils.py # def create_request(path="/", params=None): # """ # """ # if params is None: # params = {} # # rf = RequestFactory() # request = rf.get(path, params) # request.session = SessionStore() # # user = User() # user.is_superuser = True # user.save() # request.user = user # # return request . Output only the next line.
checkout(request, self.p1.id)
Given the following code snippet before the placeholder: <|code_start|># django imports # lfc imports # lfc_page imports class WorkingCopyTestCase(TestCase): """ Tests related to working copy. """ def setUp(self): self.user = User.objects.create(username="admin", is_active=True, is_superuser=True) call_command('lfc_init_simple') self.p1 = Page.objects.create(title="Page 1", slug="page-1") def test_working_cycle(self): <|code_end|> , predict the next line using imports from the current file: from django.contrib.auth.models import User from django.core.management import call_command from django.test import TestCase from lfc.manage.views import checkin from lfc.manage.views import checkout from lfc.tests.utils import create_request from lfc_page.models import Page and context including class names, function names, and sometimes code from other files: # Path: lfc/manage/views.py # def checkin(request, id): # """ # Checks in the working copy with passed id. # """ # working_copy = lfc.utils.get_content_object(pk=id) # # if not working_copy.is_working_copy(): # url = reverse("lfc_manage_object", kwargs={"id": working_copy.id}) # return MessageHttpResponseRedirect(url, _(u"Object is not a working copy.")) # # working_copy.check_permission(request.user, "checkin") # # # Save some values of the base for later use. # base = working_copy.working_copy_base # base_id = base.id # base_slug = base.slug # base_parent = base.parent # base_parent_standard = base.parent.standard if base.parent else None # base_state = base.get_content_object().get_state() # base_position = base.position # base.delete() # # # Set default values # working_copy.slug = base_slug # working_copy.set_state(base_state) # working_copy.position = base_position # working_copy.save() # # # Point to wc if the base was standard object of the parent # if not base_parent: # base_parent = lfc.utils.get_portal() # # if base_parent_standard and (base_parent_standard.id == base_id): # base_parent.standard = working_copy.basecontent_ptr # base_parent.save() # lfc.utils.clear_cache() # # _update_positions(working_copy.parent) # # return HttpResponseRedirect(reverse("lfc_manage_object", kwargs={"id": working_copy.id})) # # Path: lfc/manage/views.py # def checkout(request, id): # """ # Checks out a working copy for the object with the passed id. # # **Parameters:** # # id # The id of the object for which a working copy is created. # """ # source_obj = lfc.utils.get_content_object(pk=id) # source_obj.check_permission(request.user, "checkout") # # if source_obj.has_working_copy(): # url = reverse("lfc_manage_object", kwargs={"id": source_obj.id}) # return MessageHttpResponseRedirect(url, _(u"Object has already a working copy.")) # # new_obj = copy.deepcopy(source_obj) # new_obj.pk = None # new_obj.id = None # new_obj.parent = source_obj.parent # new_obj.position = source_obj.position + 1 # # new_obj.slug = _generate_slug(new_obj, source_obj.parent) # # # Workaround for django-tagging # try: # new_obj.save() # except IntegrityError: # pass # # _copy_images(source_obj, new_obj) # _copy_files(source_obj, new_obj) # _copy_portlets(source_obj, new_obj) # _copy_translations(source_obj, new_obj) # _copy_history(source_obj, new_obj) # # # Prevent recursion # if (new_obj not in source_obj.get_descendants()) and (new_obj != source_obj): # _copy_descendants(source_obj, new_obj) # # new_obj.working_copy_base = source_obj # new_obj.save() # # _update_positions(new_obj.parent) # # return HttpResponseRedirect(reverse("lfc_manage_object", kwargs={"id": new_obj.id})) # # Path: lfc/tests/utils.py # def create_request(path="/", params=None): # """ # """ # if params is None: # params = {} # # rf = RequestFactory() # request = rf.get(path, params) # request.session = SessionStore() # # user = User() # user.is_superuser = True # user.save() # request.user = user # # return request . Output only the next line.
request = create_request()
Predict the next line after this snippet: <|code_start|># django import # lfc imports register = template.Library() @register.inclusion_tag('lfc/manage/templates.html', takes_context=True) def templates(context): """Displays a selection box to select a available template for context on the fly. """ lfc_context = context.get("lfc_context") if lfc_context is None: return { "display": False, } <|code_end|> using the current file's imports: from django import template from django.conf import settings from django.core.cache import cache from django.core.exceptions import ObjectDoesNotExist from django.forms import ChoiceField from django.forms import FileField from django.forms import CharField from django.forms import Textarea from django.forms import BooleanField from django.http import Http404 from django.template import Node, TemplateSyntaxError from django.template.loader import render_to_string from django.utils import translation from django.utils.translation import ugettext_lazy as _ from lfc.utils import registration import lfc.utils and any relevant context from other files: # Path: lfc/utils/registration.py # def get_info(obj_or_type): # def get_allowed_subtypes(obj_or_type=None): # def register_sub_type(klass, name): # def register_content_type(klass, name, sub_types=[], templates=[], default_template=None, global_addable=True, workflow=None): # def unregister_content_type(name): # def register_template(name, path, children_columns=0, images_columns=0): # def unregister_template(name): # def get_default_template(obj_or_type): # def get_templates(obj_or_type): . Output only the next line.
templates = registration.get_templates(lfc_context)
Based on the snippet: <|code_start|># portlets imports # lfc imports def initialize(): """Registers default portlets, templates and content types. """ # Portlets register_portlet(NavigationPortlet, u"Navigation") register_portlet(ContentPortlet, u"Content") register_portlet(RandomPortlet, u"Random") register_portlet(TextPortlet, u"Text") # Register Templates <|code_end|> , predict the immediate next line with the help of imports: from portlets.utils import register_portlet from lfc.utils.registration import register_template from lfc_portlets.models import NavigationPortlet from lfc_portlets.models import ContentPortlet from lfc_portlets.models import RandomPortlet from lfc_portlets.models import TextPortlet and context (classes, functions, sometimes code) from other files: # Path: lfc/utils/registration.py # def register_template(name, path, children_columns=0, images_columns=0): # """Registers a template. # # **Parameters:** # # name # The name of the template. # # path # The path to the template file. # # children_columns # The amount of columns for sub pages. This can be used within templates # to structure children. # # images_columns # The amount of columns for images. This can be used within templates # to structure images. # """ # try: # name = name._proxy____str_cast() # except AttributeError: # pass # try: # Template.objects.create(name=name, path=path, # children_columns=children_columns, images_columns=images_columns) # except IntegrityError: # pass . Output only the next line.
register_template(name=u"Plain", path=u"lfc/templates/plain.html")
Using the snippet: <|code_start|># django imports # lfc imports # lfc_page imports class HistoryTestCase(TestCase): """ Tests related to the object history. """ def setUp(self): self.user = User.objects.create(username="admin", is_active=True, is_superuser=True) call_command('lfc_init_simple') self.p1 = Page.objects.create(title="Page 1", slug="page-1") def test_change_workflow_state(self): """ For each change a history object should be created. """ request = RequestFactory().get("/", {"transition": 1}) request.user = self.user request.session = SessionStore() <|code_end|> , determine the next line of code. You have imports: from django.contrib.auth.models import User from django.contrib.sessions.backends.file import SessionStore from django.core.management import call_command from django.test import TestCase from lfc.manage.views import do_transition from lfc.manage.views import lfc_copy from lfc.models import History from lfc.tests.utils import RequestFactory from lfc_page.models import Page and context (class names, function names, or code) available: # Path: lfc/manage/views.py # def do_transition(request, id): # """Processes passed transition for object with passed id. # # **Parameters:** # # id # The id of the object for which the transition should be done. # # **Query String:** # # transition # The id of the transition which should be performed. # """ # transition = request.REQUEST.get("transition") # try: # transition = Transition.objects.get(pk=transition) # except Transition.DoesNotExist: # pass # else: # obj = lfc.utils.get_content_object(pk=id) # # if transition.permission: # obj.check_permission(request.user, transition.permission.codename) # # workflows.utils.do_transition(obj, transition, request.user) # # # CACHE # cache_key_1 = "%s-obj-%s" % (settings.CACHE_MIDDLEWARE_KEY_PREFIX, obj.get_absolute_url()[1:]) # lfc.utils.delete_cache([cache_key_1]) # # # Set publication date # if obj.publication_date is None: # public_states = [wst.state for wst in WorkflowStatesInformation.objects.filter(public=True)] # if obj.get_state() in public_states: # obj.publication_date = datetime.datetime.now() # obj.save() # # # Add history entry # obj.add_history(request, action="Workflow state changes to: %s" % obj.get_state().name) # # html = ( # ("#menu", object_menu(request, obj)), # ("#navigation", navigation(request, obj)), # ("#tabs-inline", object_tabs(request, obj)), # ) # # return HttpJsonResponse( # content=html, # message=_(u"The state has been changed."), # tabs=True, # content_type="text/plain", # ) # # Path: lfc/manage/views.py # def lfc_copy(request, id): # """Puts the object with passed id to the clipboard and marks it as copied. # # **Parameters:** # # id # The id of the object which should be copied to the clipboard # # **Permission:** # # add # """ # obj = lfc.utils.get_content_object(pk=id) # obj.check_permission(request.user, "add") # # request.session["clipboard"] = [id] # request.session["clipboard_action"] = COPY # # obj = lfc.utils.get_content_object(pk=id) # # html = ( # ("#menu", object_menu(request, obj)), # ) # # return return_as_json(html, _(u"The object has been put to the clipboard.")) # # Path: lfc/models.py # class History(models.Model): # """ # Stores some history about a content object. # """ # obj = models.ForeignKey(BaseContent, verbose_name=_(u"Content object"), related_name="content_objects") # action = models.CharField(_(u"Action"), max_length=100) # user = models.ForeignKey(User, verbose_name=_(u"User"), related_name="user") # creation_date = models.DateTimeField(_(u"Creation date"), auto_now_add=True) # # class Meta: # ordering = ("-creation_date", ) # # Path: lfc/tests/utils.py # class RequestFactory(Client): # """ # Class that lets you create mock Request objects for use in testing. # # Usage: # # rf = RequestFactory() # get_request = rf.get('/hello/') # post_request = rf.post('/submit/', {'foo': 'bar'}) # # This class re-uses the django.test.client.Client interface, docs here: # http://www.djangoproject.com/documentation/testing/#the-test-client # # Once you have a request object you can pass it to any view function, # just as if that view had been hooked up using a URLconf. # # """ # def request(self, **request): # """ # Similar to parent class, but returns the request object as soon as it # has created it. # """ # environ = { # 'HTTP_COOKIE': self.cookies, # 'PATH_INFO': '/', # 'QUERY_STRING': '', # 'REQUEST_METHOD': 'GET', # 'SCRIPT_NAME': '', # 'SERVER_NAME': 'testserver', # 'SERVER_PORT': 80, # 'SERVER_PROTOCOL': 'HTTP/1.1', # 'wsgi.input': StringIO(""), # } # environ.update(self.defaults) # environ.update(request) # return WSGIRequest(environ) . Output only the next line.
do_transition(request, self.p1.id)
Given the code snippet: <|code_start|> def test_change_workflow_state(self): """ For each change a history object should be created. """ request = RequestFactory().get("/", {"transition": 1}) request.user = self.user request.session = SessionStore() do_transition(request, self.p1.id) self.assertEqual(History.objects.count(), 1) do_transition(request, self.p1.id) self.assertEqual(History.objects.count(), 2) # Delete content object self.p1.delete() self.assertEqual(History.objects.count(), 0) def test_copy(self): """ Tests the history after an object has been copied. """ request = RequestFactory().get("/", {"transition": 1}) request.user = self.user request.session = SessionStore() do_transition(request, self.p1.id) self.assertEqual(History.objects.count(), 1) <|code_end|> , generate the next line using the imports in this file: from django.contrib.auth.models import User from django.contrib.sessions.backends.file import SessionStore from django.core.management import call_command from django.test import TestCase from lfc.manage.views import do_transition from lfc.manage.views import lfc_copy from lfc.models import History from lfc.tests.utils import RequestFactory from lfc_page.models import Page and context (functions, classes, or occasionally code) from other files: # Path: lfc/manage/views.py # def do_transition(request, id): # """Processes passed transition for object with passed id. # # **Parameters:** # # id # The id of the object for which the transition should be done. # # **Query String:** # # transition # The id of the transition which should be performed. # """ # transition = request.REQUEST.get("transition") # try: # transition = Transition.objects.get(pk=transition) # except Transition.DoesNotExist: # pass # else: # obj = lfc.utils.get_content_object(pk=id) # # if transition.permission: # obj.check_permission(request.user, transition.permission.codename) # # workflows.utils.do_transition(obj, transition, request.user) # # # CACHE # cache_key_1 = "%s-obj-%s" % (settings.CACHE_MIDDLEWARE_KEY_PREFIX, obj.get_absolute_url()[1:]) # lfc.utils.delete_cache([cache_key_1]) # # # Set publication date # if obj.publication_date is None: # public_states = [wst.state for wst in WorkflowStatesInformation.objects.filter(public=True)] # if obj.get_state() in public_states: # obj.publication_date = datetime.datetime.now() # obj.save() # # # Add history entry # obj.add_history(request, action="Workflow state changes to: %s" % obj.get_state().name) # # html = ( # ("#menu", object_menu(request, obj)), # ("#navigation", navigation(request, obj)), # ("#tabs-inline", object_tabs(request, obj)), # ) # # return HttpJsonResponse( # content=html, # message=_(u"The state has been changed."), # tabs=True, # content_type="text/plain", # ) # # Path: lfc/manage/views.py # def lfc_copy(request, id): # """Puts the object with passed id to the clipboard and marks it as copied. # # **Parameters:** # # id # The id of the object which should be copied to the clipboard # # **Permission:** # # add # """ # obj = lfc.utils.get_content_object(pk=id) # obj.check_permission(request.user, "add") # # request.session["clipboard"] = [id] # request.session["clipboard_action"] = COPY # # obj = lfc.utils.get_content_object(pk=id) # # html = ( # ("#menu", object_menu(request, obj)), # ) # # return return_as_json(html, _(u"The object has been put to the clipboard.")) # # Path: lfc/models.py # class History(models.Model): # """ # Stores some history about a content object. # """ # obj = models.ForeignKey(BaseContent, verbose_name=_(u"Content object"), related_name="content_objects") # action = models.CharField(_(u"Action"), max_length=100) # user = models.ForeignKey(User, verbose_name=_(u"User"), related_name="user") # creation_date = models.DateTimeField(_(u"Creation date"), auto_now_add=True) # # class Meta: # ordering = ("-creation_date", ) # # Path: lfc/tests/utils.py # class RequestFactory(Client): # """ # Class that lets you create mock Request objects for use in testing. # # Usage: # # rf = RequestFactory() # get_request = rf.get('/hello/') # post_request = rf.post('/submit/', {'foo': 'bar'}) # # This class re-uses the django.test.client.Client interface, docs here: # http://www.djangoproject.com/documentation/testing/#the-test-client # # Once you have a request object you can pass it to any view function, # just as if that view had been hooked up using a URLconf. # # """ # def request(self, **request): # """ # Similar to parent class, but returns the request object as soon as it # has created it. # """ # environ = { # 'HTTP_COOKIE': self.cookies, # 'PATH_INFO': '/', # 'QUERY_STRING': '', # 'REQUEST_METHOD': 'GET', # 'SCRIPT_NAME': '', # 'SERVER_NAME': 'testserver', # 'SERVER_PORT': 80, # 'SERVER_PROTOCOL': 'HTTP/1.1', # 'wsgi.input': StringIO(""), # } # environ.update(self.defaults) # environ.update(request) # return WSGIRequest(environ) . Output only the next line.
lfc_copy(request, self.p1.id)
Predict the next line after this snippet: <|code_start|># django imports # lfc imports # lfc_page imports class HistoryTestCase(TestCase): """ Tests related to the object history. """ def setUp(self): self.user = User.objects.create(username="admin", is_active=True, is_superuser=True) call_command('lfc_init_simple') self.p1 = Page.objects.create(title="Page 1", slug="page-1") def test_change_workflow_state(self): """ For each change a history object should be created. """ request = RequestFactory().get("/", {"transition": 1}) request.user = self.user request.session = SessionStore() do_transition(request, self.p1.id) <|code_end|> using the current file's imports: from django.contrib.auth.models import User from django.contrib.sessions.backends.file import SessionStore from django.core.management import call_command from django.test import TestCase from lfc.manage.views import do_transition from lfc.manage.views import lfc_copy from lfc.models import History from lfc.tests.utils import RequestFactory from lfc_page.models import Page and any relevant context from other files: # Path: lfc/manage/views.py # def do_transition(request, id): # """Processes passed transition for object with passed id. # # **Parameters:** # # id # The id of the object for which the transition should be done. # # **Query String:** # # transition # The id of the transition which should be performed. # """ # transition = request.REQUEST.get("transition") # try: # transition = Transition.objects.get(pk=transition) # except Transition.DoesNotExist: # pass # else: # obj = lfc.utils.get_content_object(pk=id) # # if transition.permission: # obj.check_permission(request.user, transition.permission.codename) # # workflows.utils.do_transition(obj, transition, request.user) # # # CACHE # cache_key_1 = "%s-obj-%s" % (settings.CACHE_MIDDLEWARE_KEY_PREFIX, obj.get_absolute_url()[1:]) # lfc.utils.delete_cache([cache_key_1]) # # # Set publication date # if obj.publication_date is None: # public_states = [wst.state for wst in WorkflowStatesInformation.objects.filter(public=True)] # if obj.get_state() in public_states: # obj.publication_date = datetime.datetime.now() # obj.save() # # # Add history entry # obj.add_history(request, action="Workflow state changes to: %s" % obj.get_state().name) # # html = ( # ("#menu", object_menu(request, obj)), # ("#navigation", navigation(request, obj)), # ("#tabs-inline", object_tabs(request, obj)), # ) # # return HttpJsonResponse( # content=html, # message=_(u"The state has been changed."), # tabs=True, # content_type="text/plain", # ) # # Path: lfc/manage/views.py # def lfc_copy(request, id): # """Puts the object with passed id to the clipboard and marks it as copied. # # **Parameters:** # # id # The id of the object which should be copied to the clipboard # # **Permission:** # # add # """ # obj = lfc.utils.get_content_object(pk=id) # obj.check_permission(request.user, "add") # # request.session["clipboard"] = [id] # request.session["clipboard_action"] = COPY # # obj = lfc.utils.get_content_object(pk=id) # # html = ( # ("#menu", object_menu(request, obj)), # ) # # return return_as_json(html, _(u"The object has been put to the clipboard.")) # # Path: lfc/models.py # class History(models.Model): # """ # Stores some history about a content object. # """ # obj = models.ForeignKey(BaseContent, verbose_name=_(u"Content object"), related_name="content_objects") # action = models.CharField(_(u"Action"), max_length=100) # user = models.ForeignKey(User, verbose_name=_(u"User"), related_name="user") # creation_date = models.DateTimeField(_(u"Creation date"), auto_now_add=True) # # class Meta: # ordering = ("-creation_date", ) # # Path: lfc/tests/utils.py # class RequestFactory(Client): # """ # Class that lets you create mock Request objects for use in testing. # # Usage: # # rf = RequestFactory() # get_request = rf.get('/hello/') # post_request = rf.post('/submit/', {'foo': 'bar'}) # # This class re-uses the django.test.client.Client interface, docs here: # http://www.djangoproject.com/documentation/testing/#the-test-client # # Once you have a request object you can pass it to any view function, # just as if that view had been hooked up using a URLconf. # # """ # def request(self, **request): # """ # Similar to parent class, but returns the request object as soon as it # has created it. # """ # environ = { # 'HTTP_COOKIE': self.cookies, # 'PATH_INFO': '/', # 'QUERY_STRING': '', # 'REQUEST_METHOD': 'GET', # 'SCRIPT_NAME': '', # 'SERVER_NAME': 'testserver', # 'SERVER_PORT': 80, # 'SERVER_PROTOCOL': 'HTTP/1.1', # 'wsgi.input': StringIO(""), # } # environ.update(self.defaults) # environ.update(request) # return WSGIRequest(environ) . Output only the next line.
self.assertEqual(History.objects.count(), 1)
Here is a snippet: <|code_start|># django imports # lfc imports # lfc_page imports class HistoryTestCase(TestCase): """ Tests related to the object history. """ def setUp(self): self.user = User.objects.create(username="admin", is_active=True, is_superuser=True) call_command('lfc_init_simple') self.p1 = Page.objects.create(title="Page 1", slug="page-1") def test_change_workflow_state(self): """ For each change a history object should be created. """ <|code_end|> . Write the next line using the current file imports: from django.contrib.auth.models import User from django.contrib.sessions.backends.file import SessionStore from django.core.management import call_command from django.test import TestCase from lfc.manage.views import do_transition from lfc.manage.views import lfc_copy from lfc.models import History from lfc.tests.utils import RequestFactory from lfc_page.models import Page and context from other files: # Path: lfc/manage/views.py # def do_transition(request, id): # """Processes passed transition for object with passed id. # # **Parameters:** # # id # The id of the object for which the transition should be done. # # **Query String:** # # transition # The id of the transition which should be performed. # """ # transition = request.REQUEST.get("transition") # try: # transition = Transition.objects.get(pk=transition) # except Transition.DoesNotExist: # pass # else: # obj = lfc.utils.get_content_object(pk=id) # # if transition.permission: # obj.check_permission(request.user, transition.permission.codename) # # workflows.utils.do_transition(obj, transition, request.user) # # # CACHE # cache_key_1 = "%s-obj-%s" % (settings.CACHE_MIDDLEWARE_KEY_PREFIX, obj.get_absolute_url()[1:]) # lfc.utils.delete_cache([cache_key_1]) # # # Set publication date # if obj.publication_date is None: # public_states = [wst.state for wst in WorkflowStatesInformation.objects.filter(public=True)] # if obj.get_state() in public_states: # obj.publication_date = datetime.datetime.now() # obj.save() # # # Add history entry # obj.add_history(request, action="Workflow state changes to: %s" % obj.get_state().name) # # html = ( # ("#menu", object_menu(request, obj)), # ("#navigation", navigation(request, obj)), # ("#tabs-inline", object_tabs(request, obj)), # ) # # return HttpJsonResponse( # content=html, # message=_(u"The state has been changed."), # tabs=True, # content_type="text/plain", # ) # # Path: lfc/manage/views.py # def lfc_copy(request, id): # """Puts the object with passed id to the clipboard and marks it as copied. # # **Parameters:** # # id # The id of the object which should be copied to the clipboard # # **Permission:** # # add # """ # obj = lfc.utils.get_content_object(pk=id) # obj.check_permission(request.user, "add") # # request.session["clipboard"] = [id] # request.session["clipboard_action"] = COPY # # obj = lfc.utils.get_content_object(pk=id) # # html = ( # ("#menu", object_menu(request, obj)), # ) # # return return_as_json(html, _(u"The object has been put to the clipboard.")) # # Path: lfc/models.py # class History(models.Model): # """ # Stores some history about a content object. # """ # obj = models.ForeignKey(BaseContent, verbose_name=_(u"Content object"), related_name="content_objects") # action = models.CharField(_(u"Action"), max_length=100) # user = models.ForeignKey(User, verbose_name=_(u"User"), related_name="user") # creation_date = models.DateTimeField(_(u"Creation date"), auto_now_add=True) # # class Meta: # ordering = ("-creation_date", ) # # Path: lfc/tests/utils.py # class RequestFactory(Client): # """ # Class that lets you create mock Request objects for use in testing. # # Usage: # # rf = RequestFactory() # get_request = rf.get('/hello/') # post_request = rf.post('/submit/', {'foo': 'bar'}) # # This class re-uses the django.test.client.Client interface, docs here: # http://www.djangoproject.com/documentation/testing/#the-test-client # # Once you have a request object you can pass it to any view function, # just as if that view had been hooked up using a URLconf. # # """ # def request(self, **request): # """ # Similar to parent class, but returns the request object as soon as it # has created it. # """ # environ = { # 'HTTP_COOKIE': self.cookies, # 'PATH_INFO': '/', # 'QUERY_STRING': '', # 'REQUEST_METHOD': 'GET', # 'SCRIPT_NAME': '', # 'SERVER_NAME': 'testserver', # 'SERVER_PORT': 80, # 'SERVER_PROTOCOL': 'HTTP/1.1', # 'wsgi.input': StringIO(""), # } # environ.update(self.defaults) # environ.update(request) # return WSGIRequest(environ) , which may include functions, classes, or code. Output only the next line.
request = RequestFactory().get("/", {"transition": 1})
Continue the code snippet: <|code_start|># django imports # permissions imports # lfc imports class Command(BaseCommand): args = '' help = """Creates test users for roles: author, editor, manager, reviewer""" def handle(self, *args, **options): User.objects.exclude(username="admin").delete() author = User.objects.create(username="author", is_active=True) <|code_end|> . Use current file imports: from django.contrib.auth.models import User from django.core.management.base import BaseCommand from lfc.models import Role import permissions.utils and context (classes, functions, or code) from other files: # Path: lfc/models.py # class Application(models.Model): # class WorkflowStatesInformation(models.Model): # class Template(models.Model): # class Meta: # class ContentTypeRegistration(models.Model): # class Meta: # class Portal(models.Model, PermissionBase): # class AbstractBaseContent(models.Model, WorkflowBase, PermissionBase): # class Meta: # class BaseContent(AbstractBaseContent): # class Meta: # class Image(models.Model): # class Meta: # class File(models.Model): # class Meta: # class History(models.Model): # class Meta: # def __unicode__(self): # def __unicode__(self): # def __unicode__(self): # def get_subtypes(self): # def get_templates(self): # def __unicode__(self): # def content_type(self): # def get_content_type(self): # def get_absolute_url(self): # def get_notification_emails(self): # def are_comments_allowed(self): # def get_parent_for_permissions(self): # def get_parent_for_portlets(self): # def get_template(self): # def get_children(self, request=None, *args, **kwargs): # def has_permission(self, user, codename): # def check_permission(self, user, codename): # def __unicode__(self): # def has_meta_data_tab(self): # def has_children_tab(self): # def has_images_tab(self): # def has_files_tab(self): # def has_portlets_tab(self): # def has_comments_tab(self): # def has_seo_tab(self): # def has_history_tab(self): # def has_permissions_tab(self): # def get_tabs(self, request): # def save(self, *args, **kwargs): # def delete(self, *args, **kwargs): # def get_absolute_url(self): # def add_history(self, request, action): # def get_content_object(self): # def get_base_object(self): # def get_searchable_text(self): # def edit_form(self, **kwargs): # def add_form(self, **kwargs): # def get_ancestors(self): # def get_ancestors_reverse(self): # def get_content_type(self): # def get_descendants(self, request=None, result=None): # def has_children(self, request=None, *args, **kwargs): # def get_children(self, request=None, *args, **kwargs): # def get_image(self): # def get_meta_title(self): # def get_meta_keywords(self): # def get_meta_description(self): # def get_template(self): # def get_title(self): # def is_canonical(self): # def get_canonical(self, request): # def is_translation(self): # def has_language(self, request, language): # def get_translation(self, request, language): # def are_comments_allowed(self): # def get_parent_for_portlets(self): # def set_context(self, request): # def get_context(self, request): # def render(self, request): # def get_parent_for_permissions(self): # def has_permission(self, user, codename): # def check_permission(self, user, codename): # def is_active(self, user): # def reindex(self): # def is_working_copy(self): # def has_working_copy(self): # def get_working_copy(self): # def get_allowed_transitions(self, user): # def __unicode__(self): # def get_absolute_url(self): # def __unicode__(self): # def get_absolute_url(self): . Output only the next line.
permissions.utils.add_role(author, Role.objects.get(name="Author"))
Continue the code snippet: <|code_start|># django imports # lfc imports # Tags urlpatterns = patterns("lfc.views", url(r'tag/(?P<slug>[-\w]+)/(?P<tag>[^/]+)/$', "lfc_tagged_object_list", name="page_tag_detail"), ) # Comments urlpatterns += patterns("", (r'^comments/', include('django_comments.urls')), ) # Login / Logout urlpatterns += patterns('django.contrib.auth.views', url('^login/?$', "login", {"template_name": "lfc/login.html"}, name='lfc_login'), url('^logout/?$', "logout", {"template_name": "lfc/logged_out.html"}, name='lfc_logout'), ) urlpatterns += patterns('', <|code_end|> . Use current file imports: from django.conf.urls import include, patterns, url from django.views.generic import TemplateView from lfc.feeds import PageTagFeed from lfc.sitemap import PageSitemap and context (classes, functions, or code) from other files: # Path: lfc/feeds.py # class PageTagFeed(Feed): # """Provides a feed for a given object restricted by given tags url, e.g. # # http://www.lfcproject.com/rss/<path/to/obj>[?tags=python] # """ # def get_object(self, request, url): # self.request = request # return lfc.utils.traverse_object(request, url) # # def title(self, obj): # portal = lfc.utils.get_portal() # return "%s - %s" % (portal.title, obj.title) # # def link(self, obj): # return obj.get_absolute_url() # # def description(self, obj): # return obj.description # # def items(self, obj): # paths_objs = obj.get_descendants() # # tags = self.request.GET.getlist("tags") # if not tags: # return paths_objs # else: # objs = [] # tagged_objs = ModelTaggedItemManager().with_all(tags, BaseContent.objects.all()) # for obj in tagged_objs: # if obj.get_content_object() in paths_objs: # objs.append(obj.get_content_object()) # return objs # # Path: lfc/sitemap.py # class PageSitemap(Sitemap): # """Google's XML sitemap for pages. # """ # changefreq = "daily" # priority = 0.5 # # def items(self): # anon = AnonymousUser() # objects = [] # for obj in BaseContent.objects.all(): # if obj.get_content_object().has_permission(anon, "view"): # objects.append(obj) # # return objects # # def lastmod(self, obj): # return obj.modification_date . Output only the next line.
url(r'(?P<url>.*)/rss$', PageTagFeed(), name="feed"),
Based on the snippet: <|code_start|># django imports # lfc imports # Tags urlpatterns = patterns("lfc.views", url(r'tag/(?P<slug>[-\w]+)/(?P<tag>[^/]+)/$', "lfc_tagged_object_list", name="page_tag_detail"), ) # Comments urlpatterns += patterns("", (r'^comments/', include('django_comments.urls')), ) # Login / Logout urlpatterns += patterns('django.contrib.auth.views', url('^login/?$', "login", {"template_name": "lfc/login.html"}, name='lfc_login'), url('^logout/?$', "logout", {"template_name": "lfc/logged_out.html"}, name='lfc_logout'), ) urlpatterns += patterns('', url(r'(?P<url>.*)/rss$', PageTagFeed(), name="feed"), ) # Sitemaps urlpatterns += patterns("django.contrib.sitemaps.views", <|code_end|> , predict the immediate next line with the help of imports: from django.conf.urls import include, patterns, url from django.views.generic import TemplateView from lfc.feeds import PageTagFeed from lfc.sitemap import PageSitemap and context (classes, functions, sometimes code) from other files: # Path: lfc/feeds.py # class PageTagFeed(Feed): # """Provides a feed for a given object restricted by given tags url, e.g. # # http://www.lfcproject.com/rss/<path/to/obj>[?tags=python] # """ # def get_object(self, request, url): # self.request = request # return lfc.utils.traverse_object(request, url) # # def title(self, obj): # portal = lfc.utils.get_portal() # return "%s - %s" % (portal.title, obj.title) # # def link(self, obj): # return obj.get_absolute_url() # # def description(self, obj): # return obj.description # # def items(self, obj): # paths_objs = obj.get_descendants() # # tags = self.request.GET.getlist("tags") # if not tags: # return paths_objs # else: # objs = [] # tagged_objs = ModelTaggedItemManager().with_all(tags, BaseContent.objects.all()) # for obj in tagged_objs: # if obj.get_content_object() in paths_objs: # objs.append(obj.get_content_object()) # return objs # # Path: lfc/sitemap.py # class PageSitemap(Sitemap): # """Google's XML sitemap for pages. # """ # changefreq = "daily" # priority = 0.5 # # def items(self): # anon = AnonymousUser() # objects = [] # for obj in BaseContent.objects.all(): # if obj.get_content_object().has_permission(anon, "view"): # objects.append(obj) # # return objects # # def lastmod(self, obj): # return obj.modification_date . Output only the next line.
url(r'^sitemap.xml', 'sitemap', {'sitemaps': {"pages": PageSitemap}})
Given the code snippet: <|code_start|># django imports # lfc imports def main(request): """context processor for LFC. """ current_language = translation.get_language() default_language = settings.LANGUAGE_CODE is_default_language = default_language == current_language if current_language == "0" or is_default_language: link_language = "" else: link_language = current_language return { "PORTAL": lfc.utils.get_portal(), "LFC_MULTILANGUAGE": getattr(settings, "LFC_MULTILANGUAGE", True), "LFC_MANAGE_WORKFLOWS": getattr(settings, "LFC_MANAGE_WORKFLOWS", True), "LFC_MANAGE_APPLICATIONS": getattr(settings, "LFC_MANAGE_APPLICATIONS", True), "LFC_MANAGE_COMMENTS": getattr(settings, "LFC_MANAGE_COMMENTS", True), "LFC_MANAGE_USERS": getattr(settings, "LFC_MANAGE_USERS", True), "LFC_MANAGE_PERMISSIONS": getattr(settings, "LFC_MANAGE_PERMISSIONS", True), "LFC_MANAGE_SEO": getattr(settings, "LFC_MANAGE_SEO", True), "LFC_MANAGE_UTILS": getattr(settings, "LFC_MANAGE_UTILS", True), <|code_end|> , generate the next line using the imports in this file: from django.conf import settings from django.utils import translation from lfc.settings import LANGUAGES_DICT import lfc.utils and context (functions, classes, or occasionally code) from other files: # Path: lfc/settings.py # LANGUAGES_DICT = [] . Output only the next line.
"LANGUAGES_DICT": LANGUAGES_DICT,
Predict the next line for this snippet: <|code_start|> Add a new user if they don't already exist. """ with ignore_unique_violation(): db.execute( users.insert().values(id=user_id), ) def purge_user(db, user_id): """ Delete a user and all of their resources. """ db.execute(files.delete().where( files.c.user_id == user_id )) db.execute(directories.delete().where( directories.c.user_id == user_id )) db.execute(users.delete().where( users.c.id == user_id )) # =========== # Directories # =========== def create_directory(db, user_id, api_path): """ Create a directory. """ <|code_end|> with the help of current file imports: from sqlalchemy import ( and_, cast, desc, func, null, select, Unicode, ) from sqlalchemy.exc import IntegrityError from .api_utils import ( from_api_dirname, from_api_filename, reads_base64, split_api_filepath, to_api_path, ) from .constants import UNLIMITED from .db_utils import ( ignore_unique_violation, is_unique_violation, is_foreign_key_violation, to_dict_no_content, to_dict_with_content, ) from .error import ( CorruptedFile, DirectoryNotEmpty, FileExists, DirectoryExists, FileTooLarge, NoSuchCheckpoint, NoSuchDirectory, NoSuchFile, RenameRoot, ) from .schema import ( directories, files, remote_checkpoints, users, ) and context from other files: # Path: pgcontents/api_utils.py # def from_api_dirname(api_dirname): # """ # Convert API-style directory name into a db-style directory name. # """ # normalized = normalize_api_path(api_dirname) # if normalized == '': # return '/' # return '/' + normalized + '/' # # def from_api_filename(api_path): # """ # Convert an API-style path into a db-style path. # """ # normalized = normalize_api_path(api_path) # assert len(normalized), "Empty path in from_api_filename" # return '/' + normalized # # def reads_base64(nb, as_version=NBFORMAT_VERSION): # """ # Read a notebook from base64. # """ # try: # return reads(b64decode(nb).decode('utf-8'), as_version=as_version) # except Exception as e: # raise CorruptedFile(e) # # def split_api_filepath(path): # """ # Split an API file path into directory and name. # """ # parts = path.rsplit('/', 1) # if len(parts) == 1: # name = parts[0] # dirname = '/' # else: # name = parts[1] # dirname = parts[0] + '/' # # return from_api_dirname(dirname), name # # def to_api_path(db_path): # """ # Convert database path into API-style path. # """ # return db_path.strip('/') # # Path: pgcontents/constants.py # UNLIMITED = 0 # # Path: pgcontents/db_utils.py # @contextmanager # def ignore_unique_violation(): # """ # Context manager for gobbling unique violations. # # NOTE: If a unique violation is raised, the existing psql connection will # not accept new commands. This just silences the python-level error. If # you need emit another command after possibly ignoring a unique violation, # you should explicitly use savepoints. # """ # try: # yield # except IntegrityError as error: # if not is_unique_violation(error): # raise # # def is_unique_violation(error): # return error.orig.pgcode == UNIQUE_VIOLATION # # def is_foreign_key_violation(error): # return error.orig.pgcode == FOREIGN_KEY_VIOLATION # # def to_dict_no_content(fields, row): # """ # Convert a SQLAlchemy row that does not contain a 'content' field to a dict. # # If row is None, return None. # # Raises AssertionError if there is a field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' not in field_names, "Unexpected content field." # # return dict(zip(field_names, row)) # # def to_dict_with_content(fields, row, decrypt_func): # """ # Convert a SQLAlchemy row that contains a 'content' field to a dict. # # ``decrypt_func`` will be applied to the ``content`` field of the row. # # If row is None, return None. # # Raises AssertionError if there is no field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' in field_names, "Missing content field." # # result = dict(zip(field_names, row)) # result['content'] = decrypt_func(result['content']) # return result # # Path: pgcontents/error.py # class CorruptedFile(Exception): # pass # # class DirectoryNotEmpty(Exception): # pass # # class FileExists(Exception): # pass # # class DirectoryExists(Exception): # pass # # class FileTooLarge(Exception): # pass # # class NoSuchCheckpoint(Exception): # pass # # class NoSuchDirectory(Exception): # pass # # class NoSuchFile(Exception): # pass # # class RenameRoot(Exception): # pass # # Path: pgcontents/schema.py , which may contain function names, class names, or code. Output only the next line.
name = from_api_dirname(api_path)
Given the following code snippet before the placeholder: <|code_start|> Parameters ---------- engine : SQLAlchemy.engine Engine encapsulating database connections. crypto_factory : function[str -> Any] A function from user_id to an object providing the interface required by PostgresContentsManager.crypto. Results of this will be used for decryption of the selected notebooks. min_dt : datetime.datetime, optional Minimum last modified datetime at which a file will be included. max_dt : datetime.datetime, optional Last modified datetime at and after which a file will be excluded. logger : Logger, optional """ return _generate_notebooks(files, files.c.created_at, engine, crypto_factory, min_dt, max_dt, logger) # ======================================= # Checkpoints (PostgresCheckpoints) # ======================================= def _remote_checkpoint_default_fields(): return [ cast(remote_checkpoints.c.id, Unicode), remote_checkpoints.c.last_modified, ] def delete_single_remote_checkpoint(db, user_id, api_path, checkpoint_id): <|code_end|> , predict the next line using imports from the current file: from sqlalchemy import ( and_, cast, desc, func, null, select, Unicode, ) from sqlalchemy.exc import IntegrityError from .api_utils import ( from_api_dirname, from_api_filename, reads_base64, split_api_filepath, to_api_path, ) from .constants import UNLIMITED from .db_utils import ( ignore_unique_violation, is_unique_violation, is_foreign_key_violation, to_dict_no_content, to_dict_with_content, ) from .error import ( CorruptedFile, DirectoryNotEmpty, FileExists, DirectoryExists, FileTooLarge, NoSuchCheckpoint, NoSuchDirectory, NoSuchFile, RenameRoot, ) from .schema import ( directories, files, remote_checkpoints, users, ) and context including class names, function names, and sometimes code from other files: # Path: pgcontents/api_utils.py # def from_api_dirname(api_dirname): # """ # Convert API-style directory name into a db-style directory name. # """ # normalized = normalize_api_path(api_dirname) # if normalized == '': # return '/' # return '/' + normalized + '/' # # def from_api_filename(api_path): # """ # Convert an API-style path into a db-style path. # """ # normalized = normalize_api_path(api_path) # assert len(normalized), "Empty path in from_api_filename" # return '/' + normalized # # def reads_base64(nb, as_version=NBFORMAT_VERSION): # """ # Read a notebook from base64. # """ # try: # return reads(b64decode(nb).decode('utf-8'), as_version=as_version) # except Exception as e: # raise CorruptedFile(e) # # def split_api_filepath(path): # """ # Split an API file path into directory and name. # """ # parts = path.rsplit('/', 1) # if len(parts) == 1: # name = parts[0] # dirname = '/' # else: # name = parts[1] # dirname = parts[0] + '/' # # return from_api_dirname(dirname), name # # def to_api_path(db_path): # """ # Convert database path into API-style path. # """ # return db_path.strip('/') # # Path: pgcontents/constants.py # UNLIMITED = 0 # # Path: pgcontents/db_utils.py # @contextmanager # def ignore_unique_violation(): # """ # Context manager for gobbling unique violations. # # NOTE: If a unique violation is raised, the existing psql connection will # not accept new commands. This just silences the python-level error. If # you need emit another command after possibly ignoring a unique violation, # you should explicitly use savepoints. # """ # try: # yield # except IntegrityError as error: # if not is_unique_violation(error): # raise # # def is_unique_violation(error): # return error.orig.pgcode == UNIQUE_VIOLATION # # def is_foreign_key_violation(error): # return error.orig.pgcode == FOREIGN_KEY_VIOLATION # # def to_dict_no_content(fields, row): # """ # Convert a SQLAlchemy row that does not contain a 'content' field to a dict. # # If row is None, return None. # # Raises AssertionError if there is a field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' not in field_names, "Unexpected content field." # # return dict(zip(field_names, row)) # # def to_dict_with_content(fields, row, decrypt_func): # """ # Convert a SQLAlchemy row that contains a 'content' field to a dict. # # ``decrypt_func`` will be applied to the ``content`` field of the row. # # If row is None, return None. # # Raises AssertionError if there is no field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' in field_names, "Missing content field." # # result = dict(zip(field_names, row)) # result['content'] = decrypt_func(result['content']) # return result # # Path: pgcontents/error.py # class CorruptedFile(Exception): # pass # # class DirectoryNotEmpty(Exception): # pass # # class FileExists(Exception): # pass # # class DirectoryExists(Exception): # pass # # class FileTooLarge(Exception): # pass # # class NoSuchCheckpoint(Exception): # pass # # class NoSuchDirectory(Exception): # pass # # class NoSuchFile(Exception): # pass # # class RenameRoot(Exception): # pass # # Path: pgcontents/schema.py . Output only the next line.
db_path = from_api_filename(api_path)
Given snippet: <|code_start|> # Only select files that are notebooks where_conds.append(files.c.name.like(u'%.ipynb')) # Query for notebooks satisfying the conditions. query = select([table]).order_by(timestamp_column) for cond in where_conds: query = query.where(cond) result = engine.execute(query) # Decrypt each notebook and yield the result. for nb_row in result: try: # The decrypt function depends on the user user_id = nb_row['user_id'] decrypt_func = crypto_factory(user_id).decrypt nb_dict = to_dict_with_content(table.c, nb_row, decrypt_func) if table is files: # Correct for files schema differing somewhat from checkpoints. nb_dict['path'] = nb_dict['parent_name'] + nb_dict['name'] nb_dict['last_modified'] = nb_dict['created_at'] # For 'content', we use `reads_base64` directly. If the db content # format is changed from base64, the decoding should be changed # here as well. yield { 'id': nb_dict['id'], 'user_id': user_id, 'path': to_api_path(nb_dict['path']), 'last_modified': nb_dict['last_modified'], <|code_end|> , continue by predicting the next line. Consider current file imports: from sqlalchemy import ( and_, cast, desc, func, null, select, Unicode, ) from sqlalchemy.exc import IntegrityError from .api_utils import ( from_api_dirname, from_api_filename, reads_base64, split_api_filepath, to_api_path, ) from .constants import UNLIMITED from .db_utils import ( ignore_unique_violation, is_unique_violation, is_foreign_key_violation, to_dict_no_content, to_dict_with_content, ) from .error import ( CorruptedFile, DirectoryNotEmpty, FileExists, DirectoryExists, FileTooLarge, NoSuchCheckpoint, NoSuchDirectory, NoSuchFile, RenameRoot, ) from .schema import ( directories, files, remote_checkpoints, users, ) and context: # Path: pgcontents/api_utils.py # def from_api_dirname(api_dirname): # """ # Convert API-style directory name into a db-style directory name. # """ # normalized = normalize_api_path(api_dirname) # if normalized == '': # return '/' # return '/' + normalized + '/' # # def from_api_filename(api_path): # """ # Convert an API-style path into a db-style path. # """ # normalized = normalize_api_path(api_path) # assert len(normalized), "Empty path in from_api_filename" # return '/' + normalized # # def reads_base64(nb, as_version=NBFORMAT_VERSION): # """ # Read a notebook from base64. # """ # try: # return reads(b64decode(nb).decode('utf-8'), as_version=as_version) # except Exception as e: # raise CorruptedFile(e) # # def split_api_filepath(path): # """ # Split an API file path into directory and name. # """ # parts = path.rsplit('/', 1) # if len(parts) == 1: # name = parts[0] # dirname = '/' # else: # name = parts[1] # dirname = parts[0] + '/' # # return from_api_dirname(dirname), name # # def to_api_path(db_path): # """ # Convert database path into API-style path. # """ # return db_path.strip('/') # # Path: pgcontents/constants.py # UNLIMITED = 0 # # Path: pgcontents/db_utils.py # @contextmanager # def ignore_unique_violation(): # """ # Context manager for gobbling unique violations. # # NOTE: If a unique violation is raised, the existing psql connection will # not accept new commands. This just silences the python-level error. If # you need emit another command after possibly ignoring a unique violation, # you should explicitly use savepoints. # """ # try: # yield # except IntegrityError as error: # if not is_unique_violation(error): # raise # # def is_unique_violation(error): # return error.orig.pgcode == UNIQUE_VIOLATION # # def is_foreign_key_violation(error): # return error.orig.pgcode == FOREIGN_KEY_VIOLATION # # def to_dict_no_content(fields, row): # """ # Convert a SQLAlchemy row that does not contain a 'content' field to a dict. # # If row is None, return None. # # Raises AssertionError if there is a field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' not in field_names, "Unexpected content field." # # return dict(zip(field_names, row)) # # def to_dict_with_content(fields, row, decrypt_func): # """ # Convert a SQLAlchemy row that contains a 'content' field to a dict. # # ``decrypt_func`` will be applied to the ``content`` field of the row. # # If row is None, return None. # # Raises AssertionError if there is no field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' in field_names, "Missing content field." # # result = dict(zip(field_names, row)) # result['content'] = decrypt_func(result['content']) # return result # # Path: pgcontents/error.py # class CorruptedFile(Exception): # pass # # class DirectoryNotEmpty(Exception): # pass # # class FileExists(Exception): # pass # # class DirectoryExists(Exception): # pass # # class FileTooLarge(Exception): # pass # # class NoSuchCheckpoint(Exception): # pass # # class NoSuchDirectory(Exception): # pass # # class NoSuchFile(Exception): # pass # # class RenameRoot(Exception): # pass # # Path: pgcontents/schema.py which might include code, classes, or functions. Output only the next line.
'content': reads_base64(nb_dict['content']),
Based on the snippet: <|code_start|> raise NoSuchDirectory(api_dirname) if content: files = files_in_directory( db, user_id, db_dirname, ) subdirectories = directories_in_directory( db, user_id, db_dirname, ) else: files, subdirectories = None, None # TODO: Consider using namedtuples for these return values. return { 'name': db_dirname, 'files': files, 'subdirs': subdirectories, } # ===== # Files # ===== def _file_where(user_id, api_path): """ Return a WHERE clause matching the given API path and user_id. """ <|code_end|> , predict the immediate next line with the help of imports: from sqlalchemy import ( and_, cast, desc, func, null, select, Unicode, ) from sqlalchemy.exc import IntegrityError from .api_utils import ( from_api_dirname, from_api_filename, reads_base64, split_api_filepath, to_api_path, ) from .constants import UNLIMITED from .db_utils import ( ignore_unique_violation, is_unique_violation, is_foreign_key_violation, to_dict_no_content, to_dict_with_content, ) from .error import ( CorruptedFile, DirectoryNotEmpty, FileExists, DirectoryExists, FileTooLarge, NoSuchCheckpoint, NoSuchDirectory, NoSuchFile, RenameRoot, ) from .schema import ( directories, files, remote_checkpoints, users, ) and context (classes, functions, sometimes code) from other files: # Path: pgcontents/api_utils.py # def from_api_dirname(api_dirname): # """ # Convert API-style directory name into a db-style directory name. # """ # normalized = normalize_api_path(api_dirname) # if normalized == '': # return '/' # return '/' + normalized + '/' # # def from_api_filename(api_path): # """ # Convert an API-style path into a db-style path. # """ # normalized = normalize_api_path(api_path) # assert len(normalized), "Empty path in from_api_filename" # return '/' + normalized # # def reads_base64(nb, as_version=NBFORMAT_VERSION): # """ # Read a notebook from base64. # """ # try: # return reads(b64decode(nb).decode('utf-8'), as_version=as_version) # except Exception as e: # raise CorruptedFile(e) # # def split_api_filepath(path): # """ # Split an API file path into directory and name. # """ # parts = path.rsplit('/', 1) # if len(parts) == 1: # name = parts[0] # dirname = '/' # else: # name = parts[1] # dirname = parts[0] + '/' # # return from_api_dirname(dirname), name # # def to_api_path(db_path): # """ # Convert database path into API-style path. # """ # return db_path.strip('/') # # Path: pgcontents/constants.py # UNLIMITED = 0 # # Path: pgcontents/db_utils.py # @contextmanager # def ignore_unique_violation(): # """ # Context manager for gobbling unique violations. # # NOTE: If a unique violation is raised, the existing psql connection will # not accept new commands. This just silences the python-level error. If # you need emit another command after possibly ignoring a unique violation, # you should explicitly use savepoints. # """ # try: # yield # except IntegrityError as error: # if not is_unique_violation(error): # raise # # def is_unique_violation(error): # return error.orig.pgcode == UNIQUE_VIOLATION # # def is_foreign_key_violation(error): # return error.orig.pgcode == FOREIGN_KEY_VIOLATION # # def to_dict_no_content(fields, row): # """ # Convert a SQLAlchemy row that does not contain a 'content' field to a dict. # # If row is None, return None. # # Raises AssertionError if there is a field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' not in field_names, "Unexpected content field." # # return dict(zip(field_names, row)) # # def to_dict_with_content(fields, row, decrypt_func): # """ # Convert a SQLAlchemy row that contains a 'content' field to a dict. # # ``decrypt_func`` will be applied to the ``content`` field of the row. # # If row is None, return None. # # Raises AssertionError if there is no field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' in field_names, "Missing content field." # # result = dict(zip(field_names, row)) # result['content'] = decrypt_func(result['content']) # return result # # Path: pgcontents/error.py # class CorruptedFile(Exception): # pass # # class DirectoryNotEmpty(Exception): # pass # # class FileExists(Exception): # pass # # class DirectoryExists(Exception): # pass # # class FileTooLarge(Exception): # pass # # class NoSuchCheckpoint(Exception): # pass # # class NoSuchDirectory(Exception): # pass # # class NoSuchFile(Exception): # pass # # class RenameRoot(Exception): # pass # # Path: pgcontents/schema.py . Output only the next line.
directory, name = split_api_filepath(api_path)
Based on the snippet: <|code_start|> where_conds.append(timestamp_column < max_dt) if table is files: # Only select files that are notebooks where_conds.append(files.c.name.like(u'%.ipynb')) # Query for notebooks satisfying the conditions. query = select([table]).order_by(timestamp_column) for cond in where_conds: query = query.where(cond) result = engine.execute(query) # Decrypt each notebook and yield the result. for nb_row in result: try: # The decrypt function depends on the user user_id = nb_row['user_id'] decrypt_func = crypto_factory(user_id).decrypt nb_dict = to_dict_with_content(table.c, nb_row, decrypt_func) if table is files: # Correct for files schema differing somewhat from checkpoints. nb_dict['path'] = nb_dict['parent_name'] + nb_dict['name'] nb_dict['last_modified'] = nb_dict['created_at'] # For 'content', we use `reads_base64` directly. If the db content # format is changed from base64, the decoding should be changed # here as well. yield { 'id': nb_dict['id'], 'user_id': user_id, <|code_end|> , predict the immediate next line with the help of imports: from sqlalchemy import ( and_, cast, desc, func, null, select, Unicode, ) from sqlalchemy.exc import IntegrityError from .api_utils import ( from_api_dirname, from_api_filename, reads_base64, split_api_filepath, to_api_path, ) from .constants import UNLIMITED from .db_utils import ( ignore_unique_violation, is_unique_violation, is_foreign_key_violation, to_dict_no_content, to_dict_with_content, ) from .error import ( CorruptedFile, DirectoryNotEmpty, FileExists, DirectoryExists, FileTooLarge, NoSuchCheckpoint, NoSuchDirectory, NoSuchFile, RenameRoot, ) from .schema import ( directories, files, remote_checkpoints, users, ) and context (classes, functions, sometimes code) from other files: # Path: pgcontents/api_utils.py # def from_api_dirname(api_dirname): # """ # Convert API-style directory name into a db-style directory name. # """ # normalized = normalize_api_path(api_dirname) # if normalized == '': # return '/' # return '/' + normalized + '/' # # def from_api_filename(api_path): # """ # Convert an API-style path into a db-style path. # """ # normalized = normalize_api_path(api_path) # assert len(normalized), "Empty path in from_api_filename" # return '/' + normalized # # def reads_base64(nb, as_version=NBFORMAT_VERSION): # """ # Read a notebook from base64. # """ # try: # return reads(b64decode(nb).decode('utf-8'), as_version=as_version) # except Exception as e: # raise CorruptedFile(e) # # def split_api_filepath(path): # """ # Split an API file path into directory and name. # """ # parts = path.rsplit('/', 1) # if len(parts) == 1: # name = parts[0] # dirname = '/' # else: # name = parts[1] # dirname = parts[0] + '/' # # return from_api_dirname(dirname), name # # def to_api_path(db_path): # """ # Convert database path into API-style path. # """ # return db_path.strip('/') # # Path: pgcontents/constants.py # UNLIMITED = 0 # # Path: pgcontents/db_utils.py # @contextmanager # def ignore_unique_violation(): # """ # Context manager for gobbling unique violations. # # NOTE: If a unique violation is raised, the existing psql connection will # not accept new commands. This just silences the python-level error. If # you need emit another command after possibly ignoring a unique violation, # you should explicitly use savepoints. # """ # try: # yield # except IntegrityError as error: # if not is_unique_violation(error): # raise # # def is_unique_violation(error): # return error.orig.pgcode == UNIQUE_VIOLATION # # def is_foreign_key_violation(error): # return error.orig.pgcode == FOREIGN_KEY_VIOLATION # # def to_dict_no_content(fields, row): # """ # Convert a SQLAlchemy row that does not contain a 'content' field to a dict. # # If row is None, return None. # # Raises AssertionError if there is a field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' not in field_names, "Unexpected content field." # # return dict(zip(field_names, row)) # # def to_dict_with_content(fields, row, decrypt_func): # """ # Convert a SQLAlchemy row that contains a 'content' field to a dict. # # ``decrypt_func`` will be applied to the ``content`` field of the row. # # If row is None, return None. # # Raises AssertionError if there is no field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' in field_names, "Missing content field." # # result = dict(zip(field_names, row)) # result['content'] = decrypt_func(result['content']) # return result # # Path: pgcontents/error.py # class CorruptedFile(Exception): # pass # # class DirectoryNotEmpty(Exception): # pass # # class FileExists(Exception): # pass # # class DirectoryExists(Exception): # pass # # class FileTooLarge(Exception): # pass # # class NoSuchCheckpoint(Exception): # pass # # class NoSuchDirectory(Exception): # pass # # class NoSuchFile(Exception): # pass # # class RenameRoot(Exception): # pass # # Path: pgcontents/schema.py . Output only the next line.
'path': to_api_path(nb_dict['path']),
Continue the code snippet: <|code_start|>""" Database Queries for PostgresContentsManager. """ # =============================== # Encryption/Decryption Utilities # =============================== def preprocess_incoming_content(content, encrypt_func, max_size_bytes): """ Apply preprocessing steps to file/notebook content that we're going to write to the database. Applies ``encrypt_func`` to ``content`` and checks that the result is smaller than ``max_size_bytes``. """ encrypted = encrypt_func(content) <|code_end|> . Use current file imports: from sqlalchemy import ( and_, cast, desc, func, null, select, Unicode, ) from sqlalchemy.exc import IntegrityError from .api_utils import ( from_api_dirname, from_api_filename, reads_base64, split_api_filepath, to_api_path, ) from .constants import UNLIMITED from .db_utils import ( ignore_unique_violation, is_unique_violation, is_foreign_key_violation, to_dict_no_content, to_dict_with_content, ) from .error import ( CorruptedFile, DirectoryNotEmpty, FileExists, DirectoryExists, FileTooLarge, NoSuchCheckpoint, NoSuchDirectory, NoSuchFile, RenameRoot, ) from .schema import ( directories, files, remote_checkpoints, users, ) and context (classes, functions, or code) from other files: # Path: pgcontents/api_utils.py # def from_api_dirname(api_dirname): # """ # Convert API-style directory name into a db-style directory name. # """ # normalized = normalize_api_path(api_dirname) # if normalized == '': # return '/' # return '/' + normalized + '/' # # def from_api_filename(api_path): # """ # Convert an API-style path into a db-style path. # """ # normalized = normalize_api_path(api_path) # assert len(normalized), "Empty path in from_api_filename" # return '/' + normalized # # def reads_base64(nb, as_version=NBFORMAT_VERSION): # """ # Read a notebook from base64. # """ # try: # return reads(b64decode(nb).decode('utf-8'), as_version=as_version) # except Exception as e: # raise CorruptedFile(e) # # def split_api_filepath(path): # """ # Split an API file path into directory and name. # """ # parts = path.rsplit('/', 1) # if len(parts) == 1: # name = parts[0] # dirname = '/' # else: # name = parts[1] # dirname = parts[0] + '/' # # return from_api_dirname(dirname), name # # def to_api_path(db_path): # """ # Convert database path into API-style path. # """ # return db_path.strip('/') # # Path: pgcontents/constants.py # UNLIMITED = 0 # # Path: pgcontents/db_utils.py # @contextmanager # def ignore_unique_violation(): # """ # Context manager for gobbling unique violations. # # NOTE: If a unique violation is raised, the existing psql connection will # not accept new commands. This just silences the python-level error. If # you need emit another command after possibly ignoring a unique violation, # you should explicitly use savepoints. # """ # try: # yield # except IntegrityError as error: # if not is_unique_violation(error): # raise # # def is_unique_violation(error): # return error.orig.pgcode == UNIQUE_VIOLATION # # def is_foreign_key_violation(error): # return error.orig.pgcode == FOREIGN_KEY_VIOLATION # # def to_dict_no_content(fields, row): # """ # Convert a SQLAlchemy row that does not contain a 'content' field to a dict. # # If row is None, return None. # # Raises AssertionError if there is a field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' not in field_names, "Unexpected content field." # # return dict(zip(field_names, row)) # # def to_dict_with_content(fields, row, decrypt_func): # """ # Convert a SQLAlchemy row that contains a 'content' field to a dict. # # ``decrypt_func`` will be applied to the ``content`` field of the row. # # If row is None, return None. # # Raises AssertionError if there is no field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' in field_names, "Missing content field." # # result = dict(zip(field_names, row)) # result['content'] = decrypt_func(result['content']) # return result # # Path: pgcontents/error.py # class CorruptedFile(Exception): # pass # # class DirectoryNotEmpty(Exception): # pass # # class FileExists(Exception): # pass # # class DirectoryExists(Exception): # pass # # class FileTooLarge(Exception): # pass # # class NoSuchCheckpoint(Exception): # pass # # class NoSuchDirectory(Exception): # pass # # class NoSuchFile(Exception): # pass # # class RenameRoot(Exception): # pass # # Path: pgcontents/schema.py . Output only the next line.
if max_size_bytes != UNLIMITED and len(encrypted) > max_size_bytes:
Predict the next line for this snippet: <|code_start|> Applies ``encrypt_func`` to ``content`` and checks that the result is smaller than ``max_size_bytes``. """ encrypted = encrypt_func(content) if max_size_bytes != UNLIMITED and len(encrypted) > max_size_bytes: raise FileTooLarge() return encrypted def unused_decrypt_func(s): """ Used by invocations of ``get_file`` that don't expect decrypt_func to be called. """ raise AssertionError("Unexpected decrypt call.") # ===== # Users # ===== def list_users(db): return db.execute(select([users.c.id])) def ensure_db_user(db, user_id): """ Add a new user if they don't already exist. """ <|code_end|> with the help of current file imports: from sqlalchemy import ( and_, cast, desc, func, null, select, Unicode, ) from sqlalchemy.exc import IntegrityError from .api_utils import ( from_api_dirname, from_api_filename, reads_base64, split_api_filepath, to_api_path, ) from .constants import UNLIMITED from .db_utils import ( ignore_unique_violation, is_unique_violation, is_foreign_key_violation, to_dict_no_content, to_dict_with_content, ) from .error import ( CorruptedFile, DirectoryNotEmpty, FileExists, DirectoryExists, FileTooLarge, NoSuchCheckpoint, NoSuchDirectory, NoSuchFile, RenameRoot, ) from .schema import ( directories, files, remote_checkpoints, users, ) and context from other files: # Path: pgcontents/api_utils.py # def from_api_dirname(api_dirname): # """ # Convert API-style directory name into a db-style directory name. # """ # normalized = normalize_api_path(api_dirname) # if normalized == '': # return '/' # return '/' + normalized + '/' # # def from_api_filename(api_path): # """ # Convert an API-style path into a db-style path. # """ # normalized = normalize_api_path(api_path) # assert len(normalized), "Empty path in from_api_filename" # return '/' + normalized # # def reads_base64(nb, as_version=NBFORMAT_VERSION): # """ # Read a notebook from base64. # """ # try: # return reads(b64decode(nb).decode('utf-8'), as_version=as_version) # except Exception as e: # raise CorruptedFile(e) # # def split_api_filepath(path): # """ # Split an API file path into directory and name. # """ # parts = path.rsplit('/', 1) # if len(parts) == 1: # name = parts[0] # dirname = '/' # else: # name = parts[1] # dirname = parts[0] + '/' # # return from_api_dirname(dirname), name # # def to_api_path(db_path): # """ # Convert database path into API-style path. # """ # return db_path.strip('/') # # Path: pgcontents/constants.py # UNLIMITED = 0 # # Path: pgcontents/db_utils.py # @contextmanager # def ignore_unique_violation(): # """ # Context manager for gobbling unique violations. # # NOTE: If a unique violation is raised, the existing psql connection will # not accept new commands. This just silences the python-level error. If # you need emit another command after possibly ignoring a unique violation, # you should explicitly use savepoints. # """ # try: # yield # except IntegrityError as error: # if not is_unique_violation(error): # raise # # def is_unique_violation(error): # return error.orig.pgcode == UNIQUE_VIOLATION # # def is_foreign_key_violation(error): # return error.orig.pgcode == FOREIGN_KEY_VIOLATION # # def to_dict_no_content(fields, row): # """ # Convert a SQLAlchemy row that does not contain a 'content' field to a dict. # # If row is None, return None. # # Raises AssertionError if there is a field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' not in field_names, "Unexpected content field." # # return dict(zip(field_names, row)) # # def to_dict_with_content(fields, row, decrypt_func): # """ # Convert a SQLAlchemy row that contains a 'content' field to a dict. # # ``decrypt_func`` will be applied to the ``content`` field of the row. # # If row is None, return None. # # Raises AssertionError if there is no field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' in field_names, "Missing content field." # # result = dict(zip(field_names, row)) # result['content'] = decrypt_func(result['content']) # return result # # Path: pgcontents/error.py # class CorruptedFile(Exception): # pass # # class DirectoryNotEmpty(Exception): # pass # # class FileExists(Exception): # pass # # class DirectoryExists(Exception): # pass # # class FileTooLarge(Exception): # pass # # class NoSuchCheckpoint(Exception): # pass # # class NoSuchDirectory(Exception): # pass # # class NoSuchFile(Exception): # pass # # class RenameRoot(Exception): # pass # # Path: pgcontents/schema.py , which may contain function names, class names, or code. Output only the next line.
with ignore_unique_violation():
Given snippet: <|code_start|> ), ) ) def save_file(db, user_id, path, content, encrypt_func, max_size_bytes): """ Save a file. TODO: Update-then-insert is probably cheaper than insert-then-update. """ content = preprocess_incoming_content( content, encrypt_func, max_size_bytes, ) directory, name = split_api_filepath(path) with db.begin_nested() as savepoint: try: res = db.execute( files.insert().values( name=name, user_id=user_id, parent_name=directory, content=content, ) ) except IntegrityError as error: # The file already exists, so overwrite its content with the newer # version. <|code_end|> , continue by predicting the next line. Consider current file imports: from sqlalchemy import ( and_, cast, desc, func, null, select, Unicode, ) from sqlalchemy.exc import IntegrityError from .api_utils import ( from_api_dirname, from_api_filename, reads_base64, split_api_filepath, to_api_path, ) from .constants import UNLIMITED from .db_utils import ( ignore_unique_violation, is_unique_violation, is_foreign_key_violation, to_dict_no_content, to_dict_with_content, ) from .error import ( CorruptedFile, DirectoryNotEmpty, FileExists, DirectoryExists, FileTooLarge, NoSuchCheckpoint, NoSuchDirectory, NoSuchFile, RenameRoot, ) from .schema import ( directories, files, remote_checkpoints, users, ) and context: # Path: pgcontents/api_utils.py # def from_api_dirname(api_dirname): # """ # Convert API-style directory name into a db-style directory name. # """ # normalized = normalize_api_path(api_dirname) # if normalized == '': # return '/' # return '/' + normalized + '/' # # def from_api_filename(api_path): # """ # Convert an API-style path into a db-style path. # """ # normalized = normalize_api_path(api_path) # assert len(normalized), "Empty path in from_api_filename" # return '/' + normalized # # def reads_base64(nb, as_version=NBFORMAT_VERSION): # """ # Read a notebook from base64. # """ # try: # return reads(b64decode(nb).decode('utf-8'), as_version=as_version) # except Exception as e: # raise CorruptedFile(e) # # def split_api_filepath(path): # """ # Split an API file path into directory and name. # """ # parts = path.rsplit('/', 1) # if len(parts) == 1: # name = parts[0] # dirname = '/' # else: # name = parts[1] # dirname = parts[0] + '/' # # return from_api_dirname(dirname), name # # def to_api_path(db_path): # """ # Convert database path into API-style path. # """ # return db_path.strip('/') # # Path: pgcontents/constants.py # UNLIMITED = 0 # # Path: pgcontents/db_utils.py # @contextmanager # def ignore_unique_violation(): # """ # Context manager for gobbling unique violations. # # NOTE: If a unique violation is raised, the existing psql connection will # not accept new commands. This just silences the python-level error. If # you need emit another command after possibly ignoring a unique violation, # you should explicitly use savepoints. # """ # try: # yield # except IntegrityError as error: # if not is_unique_violation(error): # raise # # def is_unique_violation(error): # return error.orig.pgcode == UNIQUE_VIOLATION # # def is_foreign_key_violation(error): # return error.orig.pgcode == FOREIGN_KEY_VIOLATION # # def to_dict_no_content(fields, row): # """ # Convert a SQLAlchemy row that does not contain a 'content' field to a dict. # # If row is None, return None. # # Raises AssertionError if there is a field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' not in field_names, "Unexpected content field." # # return dict(zip(field_names, row)) # # def to_dict_with_content(fields, row, decrypt_func): # """ # Convert a SQLAlchemy row that contains a 'content' field to a dict. # # ``decrypt_func`` will be applied to the ``content`` field of the row. # # If row is None, return None. # # Raises AssertionError if there is no field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' in field_names, "Missing content field." # # result = dict(zip(field_names, row)) # result['content'] = decrypt_func(result['content']) # return result # # Path: pgcontents/error.py # class CorruptedFile(Exception): # pass # # class DirectoryNotEmpty(Exception): # pass # # class FileExists(Exception): # pass # # class DirectoryExists(Exception): # pass # # class FileTooLarge(Exception): # pass # # class NoSuchCheckpoint(Exception): # pass # # class NoSuchDirectory(Exception): # pass # # class NoSuchFile(Exception): # pass # # class RenameRoot(Exception): # pass # # Path: pgcontents/schema.py which might include code, classes, or functions. Output only the next line.
if is_unique_violation(error):
Continue the code snippet: <|code_start|> return and_( table.c.parent_name == db_dirname, table.c.user_id == user_id, ) def _directory_default_fields(): """ Default fields returned by a directory query. """ return [ directories.c.name, ] def delete_directory(db, user_id, api_path): """ Delete a directory. """ db_dirname = from_api_dirname(api_path) try: result = db.execute( directories.delete().where( and_( directories.c.user_id == user_id, directories.c.name == db_dirname, ) ) ) except IntegrityError as error: <|code_end|> . Use current file imports: from sqlalchemy import ( and_, cast, desc, func, null, select, Unicode, ) from sqlalchemy.exc import IntegrityError from .api_utils import ( from_api_dirname, from_api_filename, reads_base64, split_api_filepath, to_api_path, ) from .constants import UNLIMITED from .db_utils import ( ignore_unique_violation, is_unique_violation, is_foreign_key_violation, to_dict_no_content, to_dict_with_content, ) from .error import ( CorruptedFile, DirectoryNotEmpty, FileExists, DirectoryExists, FileTooLarge, NoSuchCheckpoint, NoSuchDirectory, NoSuchFile, RenameRoot, ) from .schema import ( directories, files, remote_checkpoints, users, ) and context (classes, functions, or code) from other files: # Path: pgcontents/api_utils.py # def from_api_dirname(api_dirname): # """ # Convert API-style directory name into a db-style directory name. # """ # normalized = normalize_api_path(api_dirname) # if normalized == '': # return '/' # return '/' + normalized + '/' # # def from_api_filename(api_path): # """ # Convert an API-style path into a db-style path. # """ # normalized = normalize_api_path(api_path) # assert len(normalized), "Empty path in from_api_filename" # return '/' + normalized # # def reads_base64(nb, as_version=NBFORMAT_VERSION): # """ # Read a notebook from base64. # """ # try: # return reads(b64decode(nb).decode('utf-8'), as_version=as_version) # except Exception as e: # raise CorruptedFile(e) # # def split_api_filepath(path): # """ # Split an API file path into directory and name. # """ # parts = path.rsplit('/', 1) # if len(parts) == 1: # name = parts[0] # dirname = '/' # else: # name = parts[1] # dirname = parts[0] + '/' # # return from_api_dirname(dirname), name # # def to_api_path(db_path): # """ # Convert database path into API-style path. # """ # return db_path.strip('/') # # Path: pgcontents/constants.py # UNLIMITED = 0 # # Path: pgcontents/db_utils.py # @contextmanager # def ignore_unique_violation(): # """ # Context manager for gobbling unique violations. # # NOTE: If a unique violation is raised, the existing psql connection will # not accept new commands. This just silences the python-level error. If # you need emit another command after possibly ignoring a unique violation, # you should explicitly use savepoints. # """ # try: # yield # except IntegrityError as error: # if not is_unique_violation(error): # raise # # def is_unique_violation(error): # return error.orig.pgcode == UNIQUE_VIOLATION # # def is_foreign_key_violation(error): # return error.orig.pgcode == FOREIGN_KEY_VIOLATION # # def to_dict_no_content(fields, row): # """ # Convert a SQLAlchemy row that does not contain a 'content' field to a dict. # # If row is None, return None. # # Raises AssertionError if there is a field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' not in field_names, "Unexpected content field." # # return dict(zip(field_names, row)) # # def to_dict_with_content(fields, row, decrypt_func): # """ # Convert a SQLAlchemy row that contains a 'content' field to a dict. # # ``decrypt_func`` will be applied to the ``content`` field of the row. # # If row is None, return None. # # Raises AssertionError if there is no field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' in field_names, "Missing content field." # # result = dict(zip(field_names, row)) # result['content'] = decrypt_func(result['content']) # return result # # Path: pgcontents/error.py # class CorruptedFile(Exception): # pass # # class DirectoryNotEmpty(Exception): # pass # # class FileExists(Exception): # pass # # class DirectoryExists(Exception): # pass # # class FileTooLarge(Exception): # pass # # class NoSuchCheckpoint(Exception): # pass # # class NoSuchDirectory(Exception): # pass # # class NoSuchFile(Exception): # pass # # class RenameRoot(Exception): # pass # # Path: pgcontents/schema.py . Output only the next line.
if is_foreign_key_violation(error):
Using the snippet: <|code_start|> select( [func.count(directories.c.name)], ).where( and_( directories.c.user_id == user_id, directories.c.name == db_dirname, ), ) ).scalar() != 0 def files_in_directory(db, user_id, db_dirname): """ Return files in a directory. """ fields = _file_default_fields() rows = db.execute( select( fields, ).where( _is_in_directory(files, user_id, db_dirname), ).order_by( files.c.user_id, files.c.parent_name, files.c.name, files.c.created_at, ).distinct( files.c.user_id, files.c.parent_name, files.c.name, ) ) <|code_end|> , determine the next line of code. You have imports: from sqlalchemy import ( and_, cast, desc, func, null, select, Unicode, ) from sqlalchemy.exc import IntegrityError from .api_utils import ( from_api_dirname, from_api_filename, reads_base64, split_api_filepath, to_api_path, ) from .constants import UNLIMITED from .db_utils import ( ignore_unique_violation, is_unique_violation, is_foreign_key_violation, to_dict_no_content, to_dict_with_content, ) from .error import ( CorruptedFile, DirectoryNotEmpty, FileExists, DirectoryExists, FileTooLarge, NoSuchCheckpoint, NoSuchDirectory, NoSuchFile, RenameRoot, ) from .schema import ( directories, files, remote_checkpoints, users, ) and context (class names, function names, or code) available: # Path: pgcontents/api_utils.py # def from_api_dirname(api_dirname): # """ # Convert API-style directory name into a db-style directory name. # """ # normalized = normalize_api_path(api_dirname) # if normalized == '': # return '/' # return '/' + normalized + '/' # # def from_api_filename(api_path): # """ # Convert an API-style path into a db-style path. # """ # normalized = normalize_api_path(api_path) # assert len(normalized), "Empty path in from_api_filename" # return '/' + normalized # # def reads_base64(nb, as_version=NBFORMAT_VERSION): # """ # Read a notebook from base64. # """ # try: # return reads(b64decode(nb).decode('utf-8'), as_version=as_version) # except Exception as e: # raise CorruptedFile(e) # # def split_api_filepath(path): # """ # Split an API file path into directory and name. # """ # parts = path.rsplit('/', 1) # if len(parts) == 1: # name = parts[0] # dirname = '/' # else: # name = parts[1] # dirname = parts[0] + '/' # # return from_api_dirname(dirname), name # # def to_api_path(db_path): # """ # Convert database path into API-style path. # """ # return db_path.strip('/') # # Path: pgcontents/constants.py # UNLIMITED = 0 # # Path: pgcontents/db_utils.py # @contextmanager # def ignore_unique_violation(): # """ # Context manager for gobbling unique violations. # # NOTE: If a unique violation is raised, the existing psql connection will # not accept new commands. This just silences the python-level error. If # you need emit another command after possibly ignoring a unique violation, # you should explicitly use savepoints. # """ # try: # yield # except IntegrityError as error: # if not is_unique_violation(error): # raise # # def is_unique_violation(error): # return error.orig.pgcode == UNIQUE_VIOLATION # # def is_foreign_key_violation(error): # return error.orig.pgcode == FOREIGN_KEY_VIOLATION # # def to_dict_no_content(fields, row): # """ # Convert a SQLAlchemy row that does not contain a 'content' field to a dict. # # If row is None, return None. # # Raises AssertionError if there is a field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' not in field_names, "Unexpected content field." # # return dict(zip(field_names, row)) # # def to_dict_with_content(fields, row, decrypt_func): # """ # Convert a SQLAlchemy row that contains a 'content' field to a dict. # # ``decrypt_func`` will be applied to the ``content`` field of the row. # # If row is None, return None. # # Raises AssertionError if there is no field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' in field_names, "Missing content field." # # result = dict(zip(field_names, row)) # result['content'] = decrypt_func(result['content']) # return result # # Path: pgcontents/error.py # class CorruptedFile(Exception): # pass # # class DirectoryNotEmpty(Exception): # pass # # class FileExists(Exception): # pass # # class DirectoryExists(Exception): # pass # # class FileTooLarge(Exception): # pass # # class NoSuchCheckpoint(Exception): # pass # # class NoSuchDirectory(Exception): # pass # # class NoSuchFile(Exception): # pass # # class RenameRoot(Exception): # pass # # Path: pgcontents/schema.py . Output only the next line.
return [to_dict_no_content(fields, row) for row in rows]
Predict the next line after this snippet: <|code_start|> query = query.limit(limit) return query def _file_default_fields(): """ Default fields returned by a file query. """ return [ files.c.name, files.c.created_at, files.c.parent_name, ] def _get_file(db, user_id, api_path, query_fields, decrypt_func): """ Get file data for the given user_id, path, and query_fields. The query_fields parameter specifies which database fields should be included in the returned file data. """ result = db.execute( _select_file(user_id, api_path, query_fields, limit=1), ).first() if result is None: raise NoSuchFile(api_path) if files.c.content in query_fields: <|code_end|> using the current file's imports: from sqlalchemy import ( and_, cast, desc, func, null, select, Unicode, ) from sqlalchemy.exc import IntegrityError from .api_utils import ( from_api_dirname, from_api_filename, reads_base64, split_api_filepath, to_api_path, ) from .constants import UNLIMITED from .db_utils import ( ignore_unique_violation, is_unique_violation, is_foreign_key_violation, to_dict_no_content, to_dict_with_content, ) from .error import ( CorruptedFile, DirectoryNotEmpty, FileExists, DirectoryExists, FileTooLarge, NoSuchCheckpoint, NoSuchDirectory, NoSuchFile, RenameRoot, ) from .schema import ( directories, files, remote_checkpoints, users, ) and any relevant context from other files: # Path: pgcontents/api_utils.py # def from_api_dirname(api_dirname): # """ # Convert API-style directory name into a db-style directory name. # """ # normalized = normalize_api_path(api_dirname) # if normalized == '': # return '/' # return '/' + normalized + '/' # # def from_api_filename(api_path): # """ # Convert an API-style path into a db-style path. # """ # normalized = normalize_api_path(api_path) # assert len(normalized), "Empty path in from_api_filename" # return '/' + normalized # # def reads_base64(nb, as_version=NBFORMAT_VERSION): # """ # Read a notebook from base64. # """ # try: # return reads(b64decode(nb).decode('utf-8'), as_version=as_version) # except Exception as e: # raise CorruptedFile(e) # # def split_api_filepath(path): # """ # Split an API file path into directory and name. # """ # parts = path.rsplit('/', 1) # if len(parts) == 1: # name = parts[0] # dirname = '/' # else: # name = parts[1] # dirname = parts[0] + '/' # # return from_api_dirname(dirname), name # # def to_api_path(db_path): # """ # Convert database path into API-style path. # """ # return db_path.strip('/') # # Path: pgcontents/constants.py # UNLIMITED = 0 # # Path: pgcontents/db_utils.py # @contextmanager # def ignore_unique_violation(): # """ # Context manager for gobbling unique violations. # # NOTE: If a unique violation is raised, the existing psql connection will # not accept new commands. This just silences the python-level error. If # you need emit another command after possibly ignoring a unique violation, # you should explicitly use savepoints. # """ # try: # yield # except IntegrityError as error: # if not is_unique_violation(error): # raise # # def is_unique_violation(error): # return error.orig.pgcode == UNIQUE_VIOLATION # # def is_foreign_key_violation(error): # return error.orig.pgcode == FOREIGN_KEY_VIOLATION # # def to_dict_no_content(fields, row): # """ # Convert a SQLAlchemy row that does not contain a 'content' field to a dict. # # If row is None, return None. # # Raises AssertionError if there is a field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' not in field_names, "Unexpected content field." # # return dict(zip(field_names, row)) # # def to_dict_with_content(fields, row, decrypt_func): # """ # Convert a SQLAlchemy row that contains a 'content' field to a dict. # # ``decrypt_func`` will be applied to the ``content`` field of the row. # # If row is None, return None. # # Raises AssertionError if there is no field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' in field_names, "Missing content field." # # result = dict(zip(field_names, row)) # result['content'] = decrypt_func(result['content']) # return result # # Path: pgcontents/error.py # class CorruptedFile(Exception): # pass # # class DirectoryNotEmpty(Exception): # pass # # class FileExists(Exception): # pass # # class DirectoryExists(Exception): # pass # # class FileTooLarge(Exception): # pass # # class NoSuchCheckpoint(Exception): # pass # # class NoSuchDirectory(Exception): # pass # # class NoSuchFile(Exception): # pass # # class RenameRoot(Exception): # pass # # Path: pgcontents/schema.py . Output only the next line.
return to_dict_with_content(query_fields, result, decrypt_func)
Here is a snippet: <|code_start|> # Query for notebooks satisfying the conditions. query = select([table]).order_by(timestamp_column) for cond in where_conds: query = query.where(cond) result = engine.execute(query) # Decrypt each notebook and yield the result. for nb_row in result: try: # The decrypt function depends on the user user_id = nb_row['user_id'] decrypt_func = crypto_factory(user_id).decrypt nb_dict = to_dict_with_content(table.c, nb_row, decrypt_func) if table is files: # Correct for files schema differing somewhat from checkpoints. nb_dict['path'] = nb_dict['parent_name'] + nb_dict['name'] nb_dict['last_modified'] = nb_dict['created_at'] # For 'content', we use `reads_base64` directly. If the db content # format is changed from base64, the decoding should be changed # here as well. yield { 'id': nb_dict['id'], 'user_id': user_id, 'path': to_api_path(nb_dict['path']), 'last_modified': nb_dict['last_modified'], 'content': reads_base64(nb_dict['content']), } <|code_end|> . Write the next line using the current file imports: from sqlalchemy import ( and_, cast, desc, func, null, select, Unicode, ) from sqlalchemy.exc import IntegrityError from .api_utils import ( from_api_dirname, from_api_filename, reads_base64, split_api_filepath, to_api_path, ) from .constants import UNLIMITED from .db_utils import ( ignore_unique_violation, is_unique_violation, is_foreign_key_violation, to_dict_no_content, to_dict_with_content, ) from .error import ( CorruptedFile, DirectoryNotEmpty, FileExists, DirectoryExists, FileTooLarge, NoSuchCheckpoint, NoSuchDirectory, NoSuchFile, RenameRoot, ) from .schema import ( directories, files, remote_checkpoints, users, ) and context from other files: # Path: pgcontents/api_utils.py # def from_api_dirname(api_dirname): # """ # Convert API-style directory name into a db-style directory name. # """ # normalized = normalize_api_path(api_dirname) # if normalized == '': # return '/' # return '/' + normalized + '/' # # def from_api_filename(api_path): # """ # Convert an API-style path into a db-style path. # """ # normalized = normalize_api_path(api_path) # assert len(normalized), "Empty path in from_api_filename" # return '/' + normalized # # def reads_base64(nb, as_version=NBFORMAT_VERSION): # """ # Read a notebook from base64. # """ # try: # return reads(b64decode(nb).decode('utf-8'), as_version=as_version) # except Exception as e: # raise CorruptedFile(e) # # def split_api_filepath(path): # """ # Split an API file path into directory and name. # """ # parts = path.rsplit('/', 1) # if len(parts) == 1: # name = parts[0] # dirname = '/' # else: # name = parts[1] # dirname = parts[0] + '/' # # return from_api_dirname(dirname), name # # def to_api_path(db_path): # """ # Convert database path into API-style path. # """ # return db_path.strip('/') # # Path: pgcontents/constants.py # UNLIMITED = 0 # # Path: pgcontents/db_utils.py # @contextmanager # def ignore_unique_violation(): # """ # Context manager for gobbling unique violations. # # NOTE: If a unique violation is raised, the existing psql connection will # not accept new commands. This just silences the python-level error. If # you need emit another command after possibly ignoring a unique violation, # you should explicitly use savepoints. # """ # try: # yield # except IntegrityError as error: # if not is_unique_violation(error): # raise # # def is_unique_violation(error): # return error.orig.pgcode == UNIQUE_VIOLATION # # def is_foreign_key_violation(error): # return error.orig.pgcode == FOREIGN_KEY_VIOLATION # # def to_dict_no_content(fields, row): # """ # Convert a SQLAlchemy row that does not contain a 'content' field to a dict. # # If row is None, return None. # # Raises AssertionError if there is a field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' not in field_names, "Unexpected content field." # # return dict(zip(field_names, row)) # # def to_dict_with_content(fields, row, decrypt_func): # """ # Convert a SQLAlchemy row that contains a 'content' field to a dict. # # ``decrypt_func`` will be applied to the ``content`` field of the row. # # If row is None, return None. # # Raises AssertionError if there is no field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' in field_names, "Missing content field." # # result = dict(zip(field_names, row)) # result['content'] = decrypt_func(result['content']) # return result # # Path: pgcontents/error.py # class CorruptedFile(Exception): # pass # # class DirectoryNotEmpty(Exception): # pass # # class FileExists(Exception): # pass # # class DirectoryExists(Exception): # pass # # class FileTooLarge(Exception): # pass # # class NoSuchCheckpoint(Exception): # pass # # class NoSuchDirectory(Exception): # pass # # class NoSuchFile(Exception): # pass # # class RenameRoot(Exception): # pass # # Path: pgcontents/schema.py , which may include functions, classes, or code. Output only the next line.
except CorruptedFile:
Predict the next line for this snippet: <|code_start|> table.c.parent_name == db_dirname, table.c.user_id == user_id, ) def _directory_default_fields(): """ Default fields returned by a directory query. """ return [ directories.c.name, ] def delete_directory(db, user_id, api_path): """ Delete a directory. """ db_dirname = from_api_dirname(api_path) try: result = db.execute( directories.delete().where( and_( directories.c.user_id == user_id, directories.c.name == db_dirname, ) ) ) except IntegrityError as error: if is_foreign_key_violation(error): <|code_end|> with the help of current file imports: from sqlalchemy import ( and_, cast, desc, func, null, select, Unicode, ) from sqlalchemy.exc import IntegrityError from .api_utils import ( from_api_dirname, from_api_filename, reads_base64, split_api_filepath, to_api_path, ) from .constants import UNLIMITED from .db_utils import ( ignore_unique_violation, is_unique_violation, is_foreign_key_violation, to_dict_no_content, to_dict_with_content, ) from .error import ( CorruptedFile, DirectoryNotEmpty, FileExists, DirectoryExists, FileTooLarge, NoSuchCheckpoint, NoSuchDirectory, NoSuchFile, RenameRoot, ) from .schema import ( directories, files, remote_checkpoints, users, ) and context from other files: # Path: pgcontents/api_utils.py # def from_api_dirname(api_dirname): # """ # Convert API-style directory name into a db-style directory name. # """ # normalized = normalize_api_path(api_dirname) # if normalized == '': # return '/' # return '/' + normalized + '/' # # def from_api_filename(api_path): # """ # Convert an API-style path into a db-style path. # """ # normalized = normalize_api_path(api_path) # assert len(normalized), "Empty path in from_api_filename" # return '/' + normalized # # def reads_base64(nb, as_version=NBFORMAT_VERSION): # """ # Read a notebook from base64. # """ # try: # return reads(b64decode(nb).decode('utf-8'), as_version=as_version) # except Exception as e: # raise CorruptedFile(e) # # def split_api_filepath(path): # """ # Split an API file path into directory and name. # """ # parts = path.rsplit('/', 1) # if len(parts) == 1: # name = parts[0] # dirname = '/' # else: # name = parts[1] # dirname = parts[0] + '/' # # return from_api_dirname(dirname), name # # def to_api_path(db_path): # """ # Convert database path into API-style path. # """ # return db_path.strip('/') # # Path: pgcontents/constants.py # UNLIMITED = 0 # # Path: pgcontents/db_utils.py # @contextmanager # def ignore_unique_violation(): # """ # Context manager for gobbling unique violations. # # NOTE: If a unique violation is raised, the existing psql connection will # not accept new commands. This just silences the python-level error. If # you need emit another command after possibly ignoring a unique violation, # you should explicitly use savepoints. # """ # try: # yield # except IntegrityError as error: # if not is_unique_violation(error): # raise # # def is_unique_violation(error): # return error.orig.pgcode == UNIQUE_VIOLATION # # def is_foreign_key_violation(error): # return error.orig.pgcode == FOREIGN_KEY_VIOLATION # # def to_dict_no_content(fields, row): # """ # Convert a SQLAlchemy row that does not contain a 'content' field to a dict. # # If row is None, return None. # # Raises AssertionError if there is a field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' not in field_names, "Unexpected content field." # # return dict(zip(field_names, row)) # # def to_dict_with_content(fields, row, decrypt_func): # """ # Convert a SQLAlchemy row that contains a 'content' field to a dict. # # ``decrypt_func`` will be applied to the ``content`` field of the row. # # If row is None, return None. # # Raises AssertionError if there is no field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' in field_names, "Missing content field." # # result = dict(zip(field_names, row)) # result['content'] = decrypt_func(result['content']) # return result # # Path: pgcontents/error.py # class CorruptedFile(Exception): # pass # # class DirectoryNotEmpty(Exception): # pass # # class FileExists(Exception): # pass # # class DirectoryExists(Exception): # pass # # class FileTooLarge(Exception): # pass # # class NoSuchCheckpoint(Exception): # pass # # class NoSuchDirectory(Exception): # pass # # class NoSuchFile(Exception): # pass # # class RenameRoot(Exception): # pass # # Path: pgcontents/schema.py , which may contain function names, class names, or code. Output only the next line.
raise DirectoryNotEmpty(api_path)
Based on the snippet: <|code_start|> rowcount = result.rowcount if not rowcount: raise NoSuchFile(api_path) return rowcount def file_exists(db, user_id, path): """ Check if a file exists. """ try: get_file( db, user_id, path, include_content=False, decrypt_func=unused_decrypt_func, ) return True except NoSuchFile: return False def rename_file(db, user_id, old_api_path, new_api_path): """ Rename a file. """ # Overwriting existing files is disallowed. if file_exists(db, user_id, new_api_path): <|code_end|> , predict the immediate next line with the help of imports: from sqlalchemy import ( and_, cast, desc, func, null, select, Unicode, ) from sqlalchemy.exc import IntegrityError from .api_utils import ( from_api_dirname, from_api_filename, reads_base64, split_api_filepath, to_api_path, ) from .constants import UNLIMITED from .db_utils import ( ignore_unique_violation, is_unique_violation, is_foreign_key_violation, to_dict_no_content, to_dict_with_content, ) from .error import ( CorruptedFile, DirectoryNotEmpty, FileExists, DirectoryExists, FileTooLarge, NoSuchCheckpoint, NoSuchDirectory, NoSuchFile, RenameRoot, ) from .schema import ( directories, files, remote_checkpoints, users, ) and context (classes, functions, sometimes code) from other files: # Path: pgcontents/api_utils.py # def from_api_dirname(api_dirname): # """ # Convert API-style directory name into a db-style directory name. # """ # normalized = normalize_api_path(api_dirname) # if normalized == '': # return '/' # return '/' + normalized + '/' # # def from_api_filename(api_path): # """ # Convert an API-style path into a db-style path. # """ # normalized = normalize_api_path(api_path) # assert len(normalized), "Empty path in from_api_filename" # return '/' + normalized # # def reads_base64(nb, as_version=NBFORMAT_VERSION): # """ # Read a notebook from base64. # """ # try: # return reads(b64decode(nb).decode('utf-8'), as_version=as_version) # except Exception as e: # raise CorruptedFile(e) # # def split_api_filepath(path): # """ # Split an API file path into directory and name. # """ # parts = path.rsplit('/', 1) # if len(parts) == 1: # name = parts[0] # dirname = '/' # else: # name = parts[1] # dirname = parts[0] + '/' # # return from_api_dirname(dirname), name # # def to_api_path(db_path): # """ # Convert database path into API-style path. # """ # return db_path.strip('/') # # Path: pgcontents/constants.py # UNLIMITED = 0 # # Path: pgcontents/db_utils.py # @contextmanager # def ignore_unique_violation(): # """ # Context manager for gobbling unique violations. # # NOTE: If a unique violation is raised, the existing psql connection will # not accept new commands. This just silences the python-level error. If # you need emit another command after possibly ignoring a unique violation, # you should explicitly use savepoints. # """ # try: # yield # except IntegrityError as error: # if not is_unique_violation(error): # raise # # def is_unique_violation(error): # return error.orig.pgcode == UNIQUE_VIOLATION # # def is_foreign_key_violation(error): # return error.orig.pgcode == FOREIGN_KEY_VIOLATION # # def to_dict_no_content(fields, row): # """ # Convert a SQLAlchemy row that does not contain a 'content' field to a dict. # # If row is None, return None. # # Raises AssertionError if there is a field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' not in field_names, "Unexpected content field." # # return dict(zip(field_names, row)) # # def to_dict_with_content(fields, row, decrypt_func): # """ # Convert a SQLAlchemy row that contains a 'content' field to a dict. # # ``decrypt_func`` will be applied to the ``content`` field of the row. # # If row is None, return None. # # Raises AssertionError if there is no field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' in field_names, "Missing content field." # # result = dict(zip(field_names, row)) # result['content'] = decrypt_func(result['content']) # return result # # Path: pgcontents/error.py # class CorruptedFile(Exception): # pass # # class DirectoryNotEmpty(Exception): # pass # # class FileExists(Exception): # pass # # class DirectoryExists(Exception): # pass # # class FileTooLarge(Exception): # pass # # class NoSuchCheckpoint(Exception): # pass # # class NoSuchDirectory(Exception): # pass # # class NoSuchFile(Exception): # pass # # class RenameRoot(Exception): # pass # # Path: pgcontents/schema.py . Output only the next line.
raise FileExists(new_api_path)
Here is a snippet: <|code_start|> """ # Overwriting existing files is disallowed. if file_exists(db, user_id, new_api_path): raise FileExists(new_api_path) new_dir, new_name = split_api_filepath(new_api_path) db.execute( files.update().where( _file_where(user_id, old_api_path), ).values( name=new_name, parent_name=new_dir, created_at=func.now(), ) ) def rename_directory(db, user_id, old_api_path, new_api_path): """ Rename a directory. """ old_db_path = from_api_dirname(old_api_path) new_db_path = from_api_dirname(new_api_path) if old_db_path == '/': raise RenameRoot('Renaming the root directory is not permitted.') # Overwriting existing directories is disallowed. if _dir_exists(db, user_id, new_db_path): <|code_end|> . Write the next line using the current file imports: from sqlalchemy import ( and_, cast, desc, func, null, select, Unicode, ) from sqlalchemy.exc import IntegrityError from .api_utils import ( from_api_dirname, from_api_filename, reads_base64, split_api_filepath, to_api_path, ) from .constants import UNLIMITED from .db_utils import ( ignore_unique_violation, is_unique_violation, is_foreign_key_violation, to_dict_no_content, to_dict_with_content, ) from .error import ( CorruptedFile, DirectoryNotEmpty, FileExists, DirectoryExists, FileTooLarge, NoSuchCheckpoint, NoSuchDirectory, NoSuchFile, RenameRoot, ) from .schema import ( directories, files, remote_checkpoints, users, ) and context from other files: # Path: pgcontents/api_utils.py # def from_api_dirname(api_dirname): # """ # Convert API-style directory name into a db-style directory name. # """ # normalized = normalize_api_path(api_dirname) # if normalized == '': # return '/' # return '/' + normalized + '/' # # def from_api_filename(api_path): # """ # Convert an API-style path into a db-style path. # """ # normalized = normalize_api_path(api_path) # assert len(normalized), "Empty path in from_api_filename" # return '/' + normalized # # def reads_base64(nb, as_version=NBFORMAT_VERSION): # """ # Read a notebook from base64. # """ # try: # return reads(b64decode(nb).decode('utf-8'), as_version=as_version) # except Exception as e: # raise CorruptedFile(e) # # def split_api_filepath(path): # """ # Split an API file path into directory and name. # """ # parts = path.rsplit('/', 1) # if len(parts) == 1: # name = parts[0] # dirname = '/' # else: # name = parts[1] # dirname = parts[0] + '/' # # return from_api_dirname(dirname), name # # def to_api_path(db_path): # """ # Convert database path into API-style path. # """ # return db_path.strip('/') # # Path: pgcontents/constants.py # UNLIMITED = 0 # # Path: pgcontents/db_utils.py # @contextmanager # def ignore_unique_violation(): # """ # Context manager for gobbling unique violations. # # NOTE: If a unique violation is raised, the existing psql connection will # not accept new commands. This just silences the python-level error. If # you need emit another command after possibly ignoring a unique violation, # you should explicitly use savepoints. # """ # try: # yield # except IntegrityError as error: # if not is_unique_violation(error): # raise # # def is_unique_violation(error): # return error.orig.pgcode == UNIQUE_VIOLATION # # def is_foreign_key_violation(error): # return error.orig.pgcode == FOREIGN_KEY_VIOLATION # # def to_dict_no_content(fields, row): # """ # Convert a SQLAlchemy row that does not contain a 'content' field to a dict. # # If row is None, return None. # # Raises AssertionError if there is a field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' not in field_names, "Unexpected content field." # # return dict(zip(field_names, row)) # # def to_dict_with_content(fields, row, decrypt_func): # """ # Convert a SQLAlchemy row that contains a 'content' field to a dict. # # ``decrypt_func`` will be applied to the ``content`` field of the row. # # If row is None, return None. # # Raises AssertionError if there is no field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' in field_names, "Missing content field." # # result = dict(zip(field_names, row)) # result['content'] = decrypt_func(result['content']) # return result # # Path: pgcontents/error.py # class CorruptedFile(Exception): # pass # # class DirectoryNotEmpty(Exception): # pass # # class FileExists(Exception): # pass # # class DirectoryExists(Exception): # pass # # class FileTooLarge(Exception): # pass # # class NoSuchCheckpoint(Exception): # pass # # class NoSuchDirectory(Exception): # pass # # class NoSuchFile(Exception): # pass # # class RenameRoot(Exception): # pass # # Path: pgcontents/schema.py , which may include functions, classes, or code. Output only the next line.
raise DirectoryExists(new_api_path)
Given the code snippet: <|code_start|>""" Database Queries for PostgresContentsManager. """ # =============================== # Encryption/Decryption Utilities # =============================== def preprocess_incoming_content(content, encrypt_func, max_size_bytes): """ Apply preprocessing steps to file/notebook content that we're going to write to the database. Applies ``encrypt_func`` to ``content`` and checks that the result is smaller than ``max_size_bytes``. """ encrypted = encrypt_func(content) if max_size_bytes != UNLIMITED and len(encrypted) > max_size_bytes: <|code_end|> , generate the next line using the imports in this file: from sqlalchemy import ( and_, cast, desc, func, null, select, Unicode, ) from sqlalchemy.exc import IntegrityError from .api_utils import ( from_api_dirname, from_api_filename, reads_base64, split_api_filepath, to_api_path, ) from .constants import UNLIMITED from .db_utils import ( ignore_unique_violation, is_unique_violation, is_foreign_key_violation, to_dict_no_content, to_dict_with_content, ) from .error import ( CorruptedFile, DirectoryNotEmpty, FileExists, DirectoryExists, FileTooLarge, NoSuchCheckpoint, NoSuchDirectory, NoSuchFile, RenameRoot, ) from .schema import ( directories, files, remote_checkpoints, users, ) and context (functions, classes, or occasionally code) from other files: # Path: pgcontents/api_utils.py # def from_api_dirname(api_dirname): # """ # Convert API-style directory name into a db-style directory name. # """ # normalized = normalize_api_path(api_dirname) # if normalized == '': # return '/' # return '/' + normalized + '/' # # def from_api_filename(api_path): # """ # Convert an API-style path into a db-style path. # """ # normalized = normalize_api_path(api_path) # assert len(normalized), "Empty path in from_api_filename" # return '/' + normalized # # def reads_base64(nb, as_version=NBFORMAT_VERSION): # """ # Read a notebook from base64. # """ # try: # return reads(b64decode(nb).decode('utf-8'), as_version=as_version) # except Exception as e: # raise CorruptedFile(e) # # def split_api_filepath(path): # """ # Split an API file path into directory and name. # """ # parts = path.rsplit('/', 1) # if len(parts) == 1: # name = parts[0] # dirname = '/' # else: # name = parts[1] # dirname = parts[0] + '/' # # return from_api_dirname(dirname), name # # def to_api_path(db_path): # """ # Convert database path into API-style path. # """ # return db_path.strip('/') # # Path: pgcontents/constants.py # UNLIMITED = 0 # # Path: pgcontents/db_utils.py # @contextmanager # def ignore_unique_violation(): # """ # Context manager for gobbling unique violations. # # NOTE: If a unique violation is raised, the existing psql connection will # not accept new commands. This just silences the python-level error. If # you need emit another command after possibly ignoring a unique violation, # you should explicitly use savepoints. # """ # try: # yield # except IntegrityError as error: # if not is_unique_violation(error): # raise # # def is_unique_violation(error): # return error.orig.pgcode == UNIQUE_VIOLATION # # def is_foreign_key_violation(error): # return error.orig.pgcode == FOREIGN_KEY_VIOLATION # # def to_dict_no_content(fields, row): # """ # Convert a SQLAlchemy row that does not contain a 'content' field to a dict. # # If row is None, return None. # # Raises AssertionError if there is a field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' not in field_names, "Unexpected content field." # # return dict(zip(field_names, row)) # # def to_dict_with_content(fields, row, decrypt_func): # """ # Convert a SQLAlchemy row that contains a 'content' field to a dict. # # ``decrypt_func`` will be applied to the ``content`` field of the row. # # If row is None, return None. # # Raises AssertionError if there is no field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' in field_names, "Missing content field." # # result = dict(zip(field_names, row)) # result['content'] = decrypt_func(result['content']) # return result # # Path: pgcontents/error.py # class CorruptedFile(Exception): # pass # # class DirectoryNotEmpty(Exception): # pass # # class FileExists(Exception): # pass # # class DirectoryExists(Exception): # pass # # class FileTooLarge(Exception): # pass # # class NoSuchCheckpoint(Exception): # pass # # class NoSuchDirectory(Exception): # pass # # class NoSuchFile(Exception): # pass # # class RenameRoot(Exception): # pass # # Path: pgcontents/schema.py . Output only the next line.
raise FileTooLarge()
Based on the snippet: <|code_start|> Last modified datetime at and after which a file will be excluded. logger : Logger, optional """ return _generate_notebooks(files, files.c.created_at, engine, crypto_factory, min_dt, max_dt, logger) # ======================================= # Checkpoints (PostgresCheckpoints) # ======================================= def _remote_checkpoint_default_fields(): return [ cast(remote_checkpoints.c.id, Unicode), remote_checkpoints.c.last_modified, ] def delete_single_remote_checkpoint(db, user_id, api_path, checkpoint_id): db_path = from_api_filename(api_path) result = db.execute( remote_checkpoints.delete().where( and_( remote_checkpoints.c.user_id == user_id, remote_checkpoints.c.path == db_path, remote_checkpoints.c.id == int(checkpoint_id), ), ), ) if not result.rowcount: <|code_end|> , predict the immediate next line with the help of imports: from sqlalchemy import ( and_, cast, desc, func, null, select, Unicode, ) from sqlalchemy.exc import IntegrityError from .api_utils import ( from_api_dirname, from_api_filename, reads_base64, split_api_filepath, to_api_path, ) from .constants import UNLIMITED from .db_utils import ( ignore_unique_violation, is_unique_violation, is_foreign_key_violation, to_dict_no_content, to_dict_with_content, ) from .error import ( CorruptedFile, DirectoryNotEmpty, FileExists, DirectoryExists, FileTooLarge, NoSuchCheckpoint, NoSuchDirectory, NoSuchFile, RenameRoot, ) from .schema import ( directories, files, remote_checkpoints, users, ) and context (classes, functions, sometimes code) from other files: # Path: pgcontents/api_utils.py # def from_api_dirname(api_dirname): # """ # Convert API-style directory name into a db-style directory name. # """ # normalized = normalize_api_path(api_dirname) # if normalized == '': # return '/' # return '/' + normalized + '/' # # def from_api_filename(api_path): # """ # Convert an API-style path into a db-style path. # """ # normalized = normalize_api_path(api_path) # assert len(normalized), "Empty path in from_api_filename" # return '/' + normalized # # def reads_base64(nb, as_version=NBFORMAT_VERSION): # """ # Read a notebook from base64. # """ # try: # return reads(b64decode(nb).decode('utf-8'), as_version=as_version) # except Exception as e: # raise CorruptedFile(e) # # def split_api_filepath(path): # """ # Split an API file path into directory and name. # """ # parts = path.rsplit('/', 1) # if len(parts) == 1: # name = parts[0] # dirname = '/' # else: # name = parts[1] # dirname = parts[0] + '/' # # return from_api_dirname(dirname), name # # def to_api_path(db_path): # """ # Convert database path into API-style path. # """ # return db_path.strip('/') # # Path: pgcontents/constants.py # UNLIMITED = 0 # # Path: pgcontents/db_utils.py # @contextmanager # def ignore_unique_violation(): # """ # Context manager for gobbling unique violations. # # NOTE: If a unique violation is raised, the existing psql connection will # not accept new commands. This just silences the python-level error. If # you need emit another command after possibly ignoring a unique violation, # you should explicitly use savepoints. # """ # try: # yield # except IntegrityError as error: # if not is_unique_violation(error): # raise # # def is_unique_violation(error): # return error.orig.pgcode == UNIQUE_VIOLATION # # def is_foreign_key_violation(error): # return error.orig.pgcode == FOREIGN_KEY_VIOLATION # # def to_dict_no_content(fields, row): # """ # Convert a SQLAlchemy row that does not contain a 'content' field to a dict. # # If row is None, return None. # # Raises AssertionError if there is a field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' not in field_names, "Unexpected content field." # # return dict(zip(field_names, row)) # # def to_dict_with_content(fields, row, decrypt_func): # """ # Convert a SQLAlchemy row that contains a 'content' field to a dict. # # ``decrypt_func`` will be applied to the ``content`` field of the row. # # If row is None, return None. # # Raises AssertionError if there is no field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' in field_names, "Missing content field." # # result = dict(zip(field_names, row)) # result['content'] = decrypt_func(result['content']) # return result # # Path: pgcontents/error.py # class CorruptedFile(Exception): # pass # # class DirectoryNotEmpty(Exception): # pass # # class FileExists(Exception): # pass # # class DirectoryExists(Exception): # pass # # class FileTooLarge(Exception): # pass # # class NoSuchCheckpoint(Exception): # pass # # class NoSuchDirectory(Exception): # pass # # class NoSuchFile(Exception): # pass # # class RenameRoot(Exception): # pass # # Path: pgcontents/schema.py . Output only the next line.
raise NoSuchCheckpoint(api_path, checkpoint_id)
Predict the next line after this snippet: <|code_start|> """ Default fields returned by a directory query. """ return [ directories.c.name, ] def delete_directory(db, user_id, api_path): """ Delete a directory. """ db_dirname = from_api_dirname(api_path) try: result = db.execute( directories.delete().where( and_( directories.c.user_id == user_id, directories.c.name == db_dirname, ) ) ) except IntegrityError as error: if is_foreign_key_violation(error): raise DirectoryNotEmpty(api_path) else: raise rowcount = result.rowcount if not rowcount: <|code_end|> using the current file's imports: from sqlalchemy import ( and_, cast, desc, func, null, select, Unicode, ) from sqlalchemy.exc import IntegrityError from .api_utils import ( from_api_dirname, from_api_filename, reads_base64, split_api_filepath, to_api_path, ) from .constants import UNLIMITED from .db_utils import ( ignore_unique_violation, is_unique_violation, is_foreign_key_violation, to_dict_no_content, to_dict_with_content, ) from .error import ( CorruptedFile, DirectoryNotEmpty, FileExists, DirectoryExists, FileTooLarge, NoSuchCheckpoint, NoSuchDirectory, NoSuchFile, RenameRoot, ) from .schema import ( directories, files, remote_checkpoints, users, ) and any relevant context from other files: # Path: pgcontents/api_utils.py # def from_api_dirname(api_dirname): # """ # Convert API-style directory name into a db-style directory name. # """ # normalized = normalize_api_path(api_dirname) # if normalized == '': # return '/' # return '/' + normalized + '/' # # def from_api_filename(api_path): # """ # Convert an API-style path into a db-style path. # """ # normalized = normalize_api_path(api_path) # assert len(normalized), "Empty path in from_api_filename" # return '/' + normalized # # def reads_base64(nb, as_version=NBFORMAT_VERSION): # """ # Read a notebook from base64. # """ # try: # return reads(b64decode(nb).decode('utf-8'), as_version=as_version) # except Exception as e: # raise CorruptedFile(e) # # def split_api_filepath(path): # """ # Split an API file path into directory and name. # """ # parts = path.rsplit('/', 1) # if len(parts) == 1: # name = parts[0] # dirname = '/' # else: # name = parts[1] # dirname = parts[0] + '/' # # return from_api_dirname(dirname), name # # def to_api_path(db_path): # """ # Convert database path into API-style path. # """ # return db_path.strip('/') # # Path: pgcontents/constants.py # UNLIMITED = 0 # # Path: pgcontents/db_utils.py # @contextmanager # def ignore_unique_violation(): # """ # Context manager for gobbling unique violations. # # NOTE: If a unique violation is raised, the existing psql connection will # not accept new commands. This just silences the python-level error. If # you need emit another command after possibly ignoring a unique violation, # you should explicitly use savepoints. # """ # try: # yield # except IntegrityError as error: # if not is_unique_violation(error): # raise # # def is_unique_violation(error): # return error.orig.pgcode == UNIQUE_VIOLATION # # def is_foreign_key_violation(error): # return error.orig.pgcode == FOREIGN_KEY_VIOLATION # # def to_dict_no_content(fields, row): # """ # Convert a SQLAlchemy row that does not contain a 'content' field to a dict. # # If row is None, return None. # # Raises AssertionError if there is a field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' not in field_names, "Unexpected content field." # # return dict(zip(field_names, row)) # # def to_dict_with_content(fields, row, decrypt_func): # """ # Convert a SQLAlchemy row that contains a 'content' field to a dict. # # ``decrypt_func`` will be applied to the ``content`` field of the row. # # If row is None, return None. # # Raises AssertionError if there is no field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' in field_names, "Missing content field." # # result = dict(zip(field_names, row)) # result['content'] = decrypt_func(result['content']) # return result # # Path: pgcontents/error.py # class CorruptedFile(Exception): # pass # # class DirectoryNotEmpty(Exception): # pass # # class FileExists(Exception): # pass # # class DirectoryExists(Exception): # pass # # class FileTooLarge(Exception): # pass # # class NoSuchCheckpoint(Exception): # pass # # class NoSuchDirectory(Exception): # pass # # class NoSuchFile(Exception): # pass # # class RenameRoot(Exception): # pass # # Path: pgcontents/schema.py . Output only the next line.
raise NoSuchDirectory(api_path)
Next line prediction: <|code_start|> _file_creation_order(), ) if limit is not None: query = query.limit(limit) return query def _file_default_fields(): """ Default fields returned by a file query. """ return [ files.c.name, files.c.created_at, files.c.parent_name, ] def _get_file(db, user_id, api_path, query_fields, decrypt_func): """ Get file data for the given user_id, path, and query_fields. The query_fields parameter specifies which database fields should be included in the returned file data. """ result = db.execute( _select_file(user_id, api_path, query_fields, limit=1), ).first() if result is None: <|code_end|> . Use current file imports: (from sqlalchemy import ( and_, cast, desc, func, null, select, Unicode, ) from sqlalchemy.exc import IntegrityError from .api_utils import ( from_api_dirname, from_api_filename, reads_base64, split_api_filepath, to_api_path, ) from .constants import UNLIMITED from .db_utils import ( ignore_unique_violation, is_unique_violation, is_foreign_key_violation, to_dict_no_content, to_dict_with_content, ) from .error import ( CorruptedFile, DirectoryNotEmpty, FileExists, DirectoryExists, FileTooLarge, NoSuchCheckpoint, NoSuchDirectory, NoSuchFile, RenameRoot, ) from .schema import ( directories, files, remote_checkpoints, users, )) and context including class names, function names, or small code snippets from other files: # Path: pgcontents/api_utils.py # def from_api_dirname(api_dirname): # """ # Convert API-style directory name into a db-style directory name. # """ # normalized = normalize_api_path(api_dirname) # if normalized == '': # return '/' # return '/' + normalized + '/' # # def from_api_filename(api_path): # """ # Convert an API-style path into a db-style path. # """ # normalized = normalize_api_path(api_path) # assert len(normalized), "Empty path in from_api_filename" # return '/' + normalized # # def reads_base64(nb, as_version=NBFORMAT_VERSION): # """ # Read a notebook from base64. # """ # try: # return reads(b64decode(nb).decode('utf-8'), as_version=as_version) # except Exception as e: # raise CorruptedFile(e) # # def split_api_filepath(path): # """ # Split an API file path into directory and name. # """ # parts = path.rsplit('/', 1) # if len(parts) == 1: # name = parts[0] # dirname = '/' # else: # name = parts[1] # dirname = parts[0] + '/' # # return from_api_dirname(dirname), name # # def to_api_path(db_path): # """ # Convert database path into API-style path. # """ # return db_path.strip('/') # # Path: pgcontents/constants.py # UNLIMITED = 0 # # Path: pgcontents/db_utils.py # @contextmanager # def ignore_unique_violation(): # """ # Context manager for gobbling unique violations. # # NOTE: If a unique violation is raised, the existing psql connection will # not accept new commands. This just silences the python-level error. If # you need emit another command after possibly ignoring a unique violation, # you should explicitly use savepoints. # """ # try: # yield # except IntegrityError as error: # if not is_unique_violation(error): # raise # # def is_unique_violation(error): # return error.orig.pgcode == UNIQUE_VIOLATION # # def is_foreign_key_violation(error): # return error.orig.pgcode == FOREIGN_KEY_VIOLATION # # def to_dict_no_content(fields, row): # """ # Convert a SQLAlchemy row that does not contain a 'content' field to a dict. # # If row is None, return None. # # Raises AssertionError if there is a field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' not in field_names, "Unexpected content field." # # return dict(zip(field_names, row)) # # def to_dict_with_content(fields, row, decrypt_func): # """ # Convert a SQLAlchemy row that contains a 'content' field to a dict. # # ``decrypt_func`` will be applied to the ``content`` field of the row. # # If row is None, return None. # # Raises AssertionError if there is no field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' in field_names, "Missing content field." # # result = dict(zip(field_names, row)) # result['content'] = decrypt_func(result['content']) # return result # # Path: pgcontents/error.py # class CorruptedFile(Exception): # pass # # class DirectoryNotEmpty(Exception): # pass # # class FileExists(Exception): # pass # # class DirectoryExists(Exception): # pass # # class FileTooLarge(Exception): # pass # # class NoSuchCheckpoint(Exception): # pass # # class NoSuchDirectory(Exception): # pass # # class NoSuchFile(Exception): # pass # # class RenameRoot(Exception): # pass # # Path: pgcontents/schema.py . Output only the next line.
raise NoSuchFile(api_path)
Based on the snippet: <|code_start|> def rename_file(db, user_id, old_api_path, new_api_path): """ Rename a file. """ # Overwriting existing files is disallowed. if file_exists(db, user_id, new_api_path): raise FileExists(new_api_path) new_dir, new_name = split_api_filepath(new_api_path) db.execute( files.update().where( _file_where(user_id, old_api_path), ).values( name=new_name, parent_name=new_dir, created_at=func.now(), ) ) def rename_directory(db, user_id, old_api_path, new_api_path): """ Rename a directory. """ old_db_path = from_api_dirname(old_api_path) new_db_path = from_api_dirname(new_api_path) if old_db_path == '/': <|code_end|> , predict the immediate next line with the help of imports: from sqlalchemy import ( and_, cast, desc, func, null, select, Unicode, ) from sqlalchemy.exc import IntegrityError from .api_utils import ( from_api_dirname, from_api_filename, reads_base64, split_api_filepath, to_api_path, ) from .constants import UNLIMITED from .db_utils import ( ignore_unique_violation, is_unique_violation, is_foreign_key_violation, to_dict_no_content, to_dict_with_content, ) from .error import ( CorruptedFile, DirectoryNotEmpty, FileExists, DirectoryExists, FileTooLarge, NoSuchCheckpoint, NoSuchDirectory, NoSuchFile, RenameRoot, ) from .schema import ( directories, files, remote_checkpoints, users, ) and context (classes, functions, sometimes code) from other files: # Path: pgcontents/api_utils.py # def from_api_dirname(api_dirname): # """ # Convert API-style directory name into a db-style directory name. # """ # normalized = normalize_api_path(api_dirname) # if normalized == '': # return '/' # return '/' + normalized + '/' # # def from_api_filename(api_path): # """ # Convert an API-style path into a db-style path. # """ # normalized = normalize_api_path(api_path) # assert len(normalized), "Empty path in from_api_filename" # return '/' + normalized # # def reads_base64(nb, as_version=NBFORMAT_VERSION): # """ # Read a notebook from base64. # """ # try: # return reads(b64decode(nb).decode('utf-8'), as_version=as_version) # except Exception as e: # raise CorruptedFile(e) # # def split_api_filepath(path): # """ # Split an API file path into directory and name. # """ # parts = path.rsplit('/', 1) # if len(parts) == 1: # name = parts[0] # dirname = '/' # else: # name = parts[1] # dirname = parts[0] + '/' # # return from_api_dirname(dirname), name # # def to_api_path(db_path): # """ # Convert database path into API-style path. # """ # return db_path.strip('/') # # Path: pgcontents/constants.py # UNLIMITED = 0 # # Path: pgcontents/db_utils.py # @contextmanager # def ignore_unique_violation(): # """ # Context manager for gobbling unique violations. # # NOTE: If a unique violation is raised, the existing psql connection will # not accept new commands. This just silences the python-level error. If # you need emit another command after possibly ignoring a unique violation, # you should explicitly use savepoints. # """ # try: # yield # except IntegrityError as error: # if not is_unique_violation(error): # raise # # def is_unique_violation(error): # return error.orig.pgcode == UNIQUE_VIOLATION # # def is_foreign_key_violation(error): # return error.orig.pgcode == FOREIGN_KEY_VIOLATION # # def to_dict_no_content(fields, row): # """ # Convert a SQLAlchemy row that does not contain a 'content' field to a dict. # # If row is None, return None. # # Raises AssertionError if there is a field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' not in field_names, "Unexpected content field." # # return dict(zip(field_names, row)) # # def to_dict_with_content(fields, row, decrypt_func): # """ # Convert a SQLAlchemy row that contains a 'content' field to a dict. # # ``decrypt_func`` will be applied to the ``content`` field of the row. # # If row is None, return None. # # Raises AssertionError if there is no field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' in field_names, "Missing content field." # # result = dict(zip(field_names, row)) # result['content'] = decrypt_func(result['content']) # return result # # Path: pgcontents/error.py # class CorruptedFile(Exception): # pass # # class DirectoryNotEmpty(Exception): # pass # # class FileExists(Exception): # pass # # class DirectoryExists(Exception): # pass # # class FileTooLarge(Exception): # pass # # class NoSuchCheckpoint(Exception): # pass # # class NoSuchDirectory(Exception): # pass # # class NoSuchFile(Exception): # pass # # class RenameRoot(Exception): # pass # # Path: pgcontents/schema.py . Output only the next line.
raise RenameRoot('Renaming the root directory is not permitted.')
Here is a snippet: <|code_start|> called. """ raise AssertionError("Unexpected decrypt call.") # ===== # Users # ===== def list_users(db): return db.execute(select([users.c.id])) def ensure_db_user(db, user_id): """ Add a new user if they don't already exist. """ with ignore_unique_violation(): db.execute( users.insert().values(id=user_id), ) def purge_user(db, user_id): """ Delete a user and all of their resources. """ db.execute(files.delete().where( files.c.user_id == user_id )) <|code_end|> . Write the next line using the current file imports: from sqlalchemy import ( and_, cast, desc, func, null, select, Unicode, ) from sqlalchemy.exc import IntegrityError from .api_utils import ( from_api_dirname, from_api_filename, reads_base64, split_api_filepath, to_api_path, ) from .constants import UNLIMITED from .db_utils import ( ignore_unique_violation, is_unique_violation, is_foreign_key_violation, to_dict_no_content, to_dict_with_content, ) from .error import ( CorruptedFile, DirectoryNotEmpty, FileExists, DirectoryExists, FileTooLarge, NoSuchCheckpoint, NoSuchDirectory, NoSuchFile, RenameRoot, ) from .schema import ( directories, files, remote_checkpoints, users, ) and context from other files: # Path: pgcontents/api_utils.py # def from_api_dirname(api_dirname): # """ # Convert API-style directory name into a db-style directory name. # """ # normalized = normalize_api_path(api_dirname) # if normalized == '': # return '/' # return '/' + normalized + '/' # # def from_api_filename(api_path): # """ # Convert an API-style path into a db-style path. # """ # normalized = normalize_api_path(api_path) # assert len(normalized), "Empty path in from_api_filename" # return '/' + normalized # # def reads_base64(nb, as_version=NBFORMAT_VERSION): # """ # Read a notebook from base64. # """ # try: # return reads(b64decode(nb).decode('utf-8'), as_version=as_version) # except Exception as e: # raise CorruptedFile(e) # # def split_api_filepath(path): # """ # Split an API file path into directory and name. # """ # parts = path.rsplit('/', 1) # if len(parts) == 1: # name = parts[0] # dirname = '/' # else: # name = parts[1] # dirname = parts[0] + '/' # # return from_api_dirname(dirname), name # # def to_api_path(db_path): # """ # Convert database path into API-style path. # """ # return db_path.strip('/') # # Path: pgcontents/constants.py # UNLIMITED = 0 # # Path: pgcontents/db_utils.py # @contextmanager # def ignore_unique_violation(): # """ # Context manager for gobbling unique violations. # # NOTE: If a unique violation is raised, the existing psql connection will # not accept new commands. This just silences the python-level error. If # you need emit another command after possibly ignoring a unique violation, # you should explicitly use savepoints. # """ # try: # yield # except IntegrityError as error: # if not is_unique_violation(error): # raise # # def is_unique_violation(error): # return error.orig.pgcode == UNIQUE_VIOLATION # # def is_foreign_key_violation(error): # return error.orig.pgcode == FOREIGN_KEY_VIOLATION # # def to_dict_no_content(fields, row): # """ # Convert a SQLAlchemy row that does not contain a 'content' field to a dict. # # If row is None, return None. # # Raises AssertionError if there is a field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' not in field_names, "Unexpected content field." # # return dict(zip(field_names, row)) # # def to_dict_with_content(fields, row, decrypt_func): # """ # Convert a SQLAlchemy row that contains a 'content' field to a dict. # # ``decrypt_func`` will be applied to the ``content`` field of the row. # # If row is None, return None. # # Raises AssertionError if there is no field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' in field_names, "Missing content field." # # result = dict(zip(field_names, row)) # result['content'] = decrypt_func(result['content']) # return result # # Path: pgcontents/error.py # class CorruptedFile(Exception): # pass # # class DirectoryNotEmpty(Exception): # pass # # class FileExists(Exception): # pass # # class DirectoryExists(Exception): # pass # # class FileTooLarge(Exception): # pass # # class NoSuchCheckpoint(Exception): # pass # # class NoSuchDirectory(Exception): # pass # # class NoSuchFile(Exception): # pass # # class RenameRoot(Exception): # pass # # Path: pgcontents/schema.py , which may include functions, classes, or code. Output only the next line.
db.execute(directories.delete().where(
Predict the next line for this snippet: <|code_start|>def unused_decrypt_func(s): """ Used by invocations of ``get_file`` that don't expect decrypt_func to be called. """ raise AssertionError("Unexpected decrypt call.") # ===== # Users # ===== def list_users(db): return db.execute(select([users.c.id])) def ensure_db_user(db, user_id): """ Add a new user if they don't already exist. """ with ignore_unique_violation(): db.execute( users.insert().values(id=user_id), ) def purge_user(db, user_id): """ Delete a user and all of their resources. """ <|code_end|> with the help of current file imports: from sqlalchemy import ( and_, cast, desc, func, null, select, Unicode, ) from sqlalchemy.exc import IntegrityError from .api_utils import ( from_api_dirname, from_api_filename, reads_base64, split_api_filepath, to_api_path, ) from .constants import UNLIMITED from .db_utils import ( ignore_unique_violation, is_unique_violation, is_foreign_key_violation, to_dict_no_content, to_dict_with_content, ) from .error import ( CorruptedFile, DirectoryNotEmpty, FileExists, DirectoryExists, FileTooLarge, NoSuchCheckpoint, NoSuchDirectory, NoSuchFile, RenameRoot, ) from .schema import ( directories, files, remote_checkpoints, users, ) and context from other files: # Path: pgcontents/api_utils.py # def from_api_dirname(api_dirname): # """ # Convert API-style directory name into a db-style directory name. # """ # normalized = normalize_api_path(api_dirname) # if normalized == '': # return '/' # return '/' + normalized + '/' # # def from_api_filename(api_path): # """ # Convert an API-style path into a db-style path. # """ # normalized = normalize_api_path(api_path) # assert len(normalized), "Empty path in from_api_filename" # return '/' + normalized # # def reads_base64(nb, as_version=NBFORMAT_VERSION): # """ # Read a notebook from base64. # """ # try: # return reads(b64decode(nb).decode('utf-8'), as_version=as_version) # except Exception as e: # raise CorruptedFile(e) # # def split_api_filepath(path): # """ # Split an API file path into directory and name. # """ # parts = path.rsplit('/', 1) # if len(parts) == 1: # name = parts[0] # dirname = '/' # else: # name = parts[1] # dirname = parts[0] + '/' # # return from_api_dirname(dirname), name # # def to_api_path(db_path): # """ # Convert database path into API-style path. # """ # return db_path.strip('/') # # Path: pgcontents/constants.py # UNLIMITED = 0 # # Path: pgcontents/db_utils.py # @contextmanager # def ignore_unique_violation(): # """ # Context manager for gobbling unique violations. # # NOTE: If a unique violation is raised, the existing psql connection will # not accept new commands. This just silences the python-level error. If # you need emit another command after possibly ignoring a unique violation, # you should explicitly use savepoints. # """ # try: # yield # except IntegrityError as error: # if not is_unique_violation(error): # raise # # def is_unique_violation(error): # return error.orig.pgcode == UNIQUE_VIOLATION # # def is_foreign_key_violation(error): # return error.orig.pgcode == FOREIGN_KEY_VIOLATION # # def to_dict_no_content(fields, row): # """ # Convert a SQLAlchemy row that does not contain a 'content' field to a dict. # # If row is None, return None. # # Raises AssertionError if there is a field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' not in field_names, "Unexpected content field." # # return dict(zip(field_names, row)) # # def to_dict_with_content(fields, row, decrypt_func): # """ # Convert a SQLAlchemy row that contains a 'content' field to a dict. # # ``decrypt_func`` will be applied to the ``content`` field of the row. # # If row is None, return None. # # Raises AssertionError if there is no field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' in field_names, "Missing content field." # # result = dict(zip(field_names, row)) # result['content'] = decrypt_func(result['content']) # return result # # Path: pgcontents/error.py # class CorruptedFile(Exception): # pass # # class DirectoryNotEmpty(Exception): # pass # # class FileExists(Exception): # pass # # class DirectoryExists(Exception): # pass # # class FileTooLarge(Exception): # pass # # class NoSuchCheckpoint(Exception): # pass # # class NoSuchDirectory(Exception): # pass # # class NoSuchFile(Exception): # pass # # class RenameRoot(Exception): # pass # # Path: pgcontents/schema.py , which may contain function names, class names, or code. Output only the next line.
db.execute(files.delete().where(
Given snippet: <|code_start|> Files are yielded in ascending order of their timestamp. This function selects all current notebooks (optionally, falling within a datetime range), decrypts them, and returns a generator yielding dicts, each containing a decoded notebook and metadata including the user, filepath, and timestamp. Parameters ---------- engine : SQLAlchemy.engine Engine encapsulating database connections. crypto_factory : function[str -> Any] A function from user_id to an object providing the interface required by PostgresContentsManager.crypto. Results of this will be used for decryption of the selected notebooks. min_dt : datetime.datetime, optional Minimum last modified datetime at which a file will be included. max_dt : datetime.datetime, optional Last modified datetime at and after which a file will be excluded. logger : Logger, optional """ return _generate_notebooks(files, files.c.created_at, engine, crypto_factory, min_dt, max_dt, logger) # ======================================= # Checkpoints (PostgresCheckpoints) # ======================================= def _remote_checkpoint_default_fields(): return [ <|code_end|> , continue by predicting the next line. Consider current file imports: from sqlalchemy import ( and_, cast, desc, func, null, select, Unicode, ) from sqlalchemy.exc import IntegrityError from .api_utils import ( from_api_dirname, from_api_filename, reads_base64, split_api_filepath, to_api_path, ) from .constants import UNLIMITED from .db_utils import ( ignore_unique_violation, is_unique_violation, is_foreign_key_violation, to_dict_no_content, to_dict_with_content, ) from .error import ( CorruptedFile, DirectoryNotEmpty, FileExists, DirectoryExists, FileTooLarge, NoSuchCheckpoint, NoSuchDirectory, NoSuchFile, RenameRoot, ) from .schema import ( directories, files, remote_checkpoints, users, ) and context: # Path: pgcontents/api_utils.py # def from_api_dirname(api_dirname): # """ # Convert API-style directory name into a db-style directory name. # """ # normalized = normalize_api_path(api_dirname) # if normalized == '': # return '/' # return '/' + normalized + '/' # # def from_api_filename(api_path): # """ # Convert an API-style path into a db-style path. # """ # normalized = normalize_api_path(api_path) # assert len(normalized), "Empty path in from_api_filename" # return '/' + normalized # # def reads_base64(nb, as_version=NBFORMAT_VERSION): # """ # Read a notebook from base64. # """ # try: # return reads(b64decode(nb).decode('utf-8'), as_version=as_version) # except Exception as e: # raise CorruptedFile(e) # # def split_api_filepath(path): # """ # Split an API file path into directory and name. # """ # parts = path.rsplit('/', 1) # if len(parts) == 1: # name = parts[0] # dirname = '/' # else: # name = parts[1] # dirname = parts[0] + '/' # # return from_api_dirname(dirname), name # # def to_api_path(db_path): # """ # Convert database path into API-style path. # """ # return db_path.strip('/') # # Path: pgcontents/constants.py # UNLIMITED = 0 # # Path: pgcontents/db_utils.py # @contextmanager # def ignore_unique_violation(): # """ # Context manager for gobbling unique violations. # # NOTE: If a unique violation is raised, the existing psql connection will # not accept new commands. This just silences the python-level error. If # you need emit another command after possibly ignoring a unique violation, # you should explicitly use savepoints. # """ # try: # yield # except IntegrityError as error: # if not is_unique_violation(error): # raise # # def is_unique_violation(error): # return error.orig.pgcode == UNIQUE_VIOLATION # # def is_foreign_key_violation(error): # return error.orig.pgcode == FOREIGN_KEY_VIOLATION # # def to_dict_no_content(fields, row): # """ # Convert a SQLAlchemy row that does not contain a 'content' field to a dict. # # If row is None, return None. # # Raises AssertionError if there is a field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' not in field_names, "Unexpected content field." # # return dict(zip(field_names, row)) # # def to_dict_with_content(fields, row, decrypt_func): # """ # Convert a SQLAlchemy row that contains a 'content' field to a dict. # # ``decrypt_func`` will be applied to the ``content`` field of the row. # # If row is None, return None. # # Raises AssertionError if there is no field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' in field_names, "Missing content field." # # result = dict(zip(field_names, row)) # result['content'] = decrypt_func(result['content']) # return result # # Path: pgcontents/error.py # class CorruptedFile(Exception): # pass # # class DirectoryNotEmpty(Exception): # pass # # class FileExists(Exception): # pass # # class DirectoryExists(Exception): # pass # # class FileTooLarge(Exception): # pass # # class NoSuchCheckpoint(Exception): # pass # # class NoSuchDirectory(Exception): # pass # # class NoSuchFile(Exception): # pass # # class RenameRoot(Exception): # pass # # Path: pgcontents/schema.py which might include code, classes, or functions. Output only the next line.
cast(remote_checkpoints.c.id, Unicode),
Here is a snippet: <|code_start|># =============================== def preprocess_incoming_content(content, encrypt_func, max_size_bytes): """ Apply preprocessing steps to file/notebook content that we're going to write to the database. Applies ``encrypt_func`` to ``content`` and checks that the result is smaller than ``max_size_bytes``. """ encrypted = encrypt_func(content) if max_size_bytes != UNLIMITED and len(encrypted) > max_size_bytes: raise FileTooLarge() return encrypted def unused_decrypt_func(s): """ Used by invocations of ``get_file`` that don't expect decrypt_func to be called. """ raise AssertionError("Unexpected decrypt call.") # ===== # Users # ===== def list_users(db): <|code_end|> . Write the next line using the current file imports: from sqlalchemy import ( and_, cast, desc, func, null, select, Unicode, ) from sqlalchemy.exc import IntegrityError from .api_utils import ( from_api_dirname, from_api_filename, reads_base64, split_api_filepath, to_api_path, ) from .constants import UNLIMITED from .db_utils import ( ignore_unique_violation, is_unique_violation, is_foreign_key_violation, to_dict_no_content, to_dict_with_content, ) from .error import ( CorruptedFile, DirectoryNotEmpty, FileExists, DirectoryExists, FileTooLarge, NoSuchCheckpoint, NoSuchDirectory, NoSuchFile, RenameRoot, ) from .schema import ( directories, files, remote_checkpoints, users, ) and context from other files: # Path: pgcontents/api_utils.py # def from_api_dirname(api_dirname): # """ # Convert API-style directory name into a db-style directory name. # """ # normalized = normalize_api_path(api_dirname) # if normalized == '': # return '/' # return '/' + normalized + '/' # # def from_api_filename(api_path): # """ # Convert an API-style path into a db-style path. # """ # normalized = normalize_api_path(api_path) # assert len(normalized), "Empty path in from_api_filename" # return '/' + normalized # # def reads_base64(nb, as_version=NBFORMAT_VERSION): # """ # Read a notebook from base64. # """ # try: # return reads(b64decode(nb).decode('utf-8'), as_version=as_version) # except Exception as e: # raise CorruptedFile(e) # # def split_api_filepath(path): # """ # Split an API file path into directory and name. # """ # parts = path.rsplit('/', 1) # if len(parts) == 1: # name = parts[0] # dirname = '/' # else: # name = parts[1] # dirname = parts[0] + '/' # # return from_api_dirname(dirname), name # # def to_api_path(db_path): # """ # Convert database path into API-style path. # """ # return db_path.strip('/') # # Path: pgcontents/constants.py # UNLIMITED = 0 # # Path: pgcontents/db_utils.py # @contextmanager # def ignore_unique_violation(): # """ # Context manager for gobbling unique violations. # # NOTE: If a unique violation is raised, the existing psql connection will # not accept new commands. This just silences the python-level error. If # you need emit another command after possibly ignoring a unique violation, # you should explicitly use savepoints. # """ # try: # yield # except IntegrityError as error: # if not is_unique_violation(error): # raise # # def is_unique_violation(error): # return error.orig.pgcode == UNIQUE_VIOLATION # # def is_foreign_key_violation(error): # return error.orig.pgcode == FOREIGN_KEY_VIOLATION # # def to_dict_no_content(fields, row): # """ # Convert a SQLAlchemy row that does not contain a 'content' field to a dict. # # If row is None, return None. # # Raises AssertionError if there is a field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' not in field_names, "Unexpected content field." # # return dict(zip(field_names, row)) # # def to_dict_with_content(fields, row, decrypt_func): # """ # Convert a SQLAlchemy row that contains a 'content' field to a dict. # # ``decrypt_func`` will be applied to the ``content`` field of the row. # # If row is None, return None. # # Raises AssertionError if there is no field named 'content' in ``fields``. # """ # assert(len(fields) == len(row)) # # field_names = list(map(_get_name, fields)) # assert 'content' in field_names, "Missing content field." # # result = dict(zip(field_names, row)) # result['content'] = decrypt_func(result['content']) # return result # # Path: pgcontents/error.py # class CorruptedFile(Exception): # pass # # class DirectoryNotEmpty(Exception): # pass # # class FileExists(Exception): # pass # # class DirectoryExists(Exception): # pass # # class FileTooLarge(Exception): # pass # # class NoSuchCheckpoint(Exception): # pass # # class NoSuchDirectory(Exception): # pass # # class NoSuchFile(Exception): # pass # # class RenameRoot(Exception): # pass # # Path: pgcontents/schema.py , which may include functions, classes, or code. Output only the next line.
return db.execute(select([users.c.id]))
Given snippet: <|code_start|>""" class PostgresManagerMixin(HasTraits): """ Shared behavior for Postgres-backed ContentsManagers. """ db_url = Unicode( default_value="postgresql://{user}@/pgcontents".format( user=getuser(), ), config=True, help="Connection string for the database.", ) user_id = Unicode( default_value=getuser(), allow_none=True, config=True, help="Name for the user whose contents we're managing.", ) create_user_on_startup = Bool( default_value=True, config=True, help="Create a user for user_id automatically?", ) max_file_size_bytes = Integer( <|code_end|> , continue by predicting the next line. Consider current file imports: from getpass import getuser from sqlalchemy import ( create_engine, ) from sqlalchemy.engine.base import Engine from tornado.web import HTTPError from .constants import UNLIMITED from .crypto import NoEncryption from .query import ensure_db_user from .utils.ipycompat import Any, Bool, Instance, Integer, HasTraits, Unicode and context: # Path: pgcontents/constants.py # UNLIMITED = 0 # # Path: pgcontents/crypto.py # class NoEncryption(object): # """ # No-op encryption backend. # # encrypt() and decrypt() simply return their inputs. # # Methods # ------- # encrypt : callable[bytes -> bytes] # decrypt : callable[bytes -> bytes] # """ # def encrypt(self, b): # return b # # def decrypt(self, b): # return b # # Path: pgcontents/query.py # def ensure_db_user(db, user_id): # """ # Add a new user if they don't already exist. # """ # with ignore_unique_violation(): # db.execute( # users.insert().values(id=user_id), # ) # # Path: pgcontents/utils/ipycompat.py which might include code, classes, or functions. Output only the next line.
default_value=UNLIMITED,
Based on the snippet: <|code_start|> Shared behavior for Postgres-backed ContentsManagers. """ db_url = Unicode( default_value="postgresql://{user}@/pgcontents".format( user=getuser(), ), config=True, help="Connection string for the database.", ) user_id = Unicode( default_value=getuser(), allow_none=True, config=True, help="Name for the user whose contents we're managing.", ) create_user_on_startup = Bool( default_value=True, config=True, help="Create a user for user_id automatically?", ) max_file_size_bytes = Integer( default_value=UNLIMITED, config=True, help="Maximum size in bytes of a file that will be saved.", ) crypto = Any( <|code_end|> , predict the immediate next line with the help of imports: from getpass import getuser from sqlalchemy import ( create_engine, ) from sqlalchemy.engine.base import Engine from tornado.web import HTTPError from .constants import UNLIMITED from .crypto import NoEncryption from .query import ensure_db_user from .utils.ipycompat import Any, Bool, Instance, Integer, HasTraits, Unicode and context (classes, functions, sometimes code) from other files: # Path: pgcontents/constants.py # UNLIMITED = 0 # # Path: pgcontents/crypto.py # class NoEncryption(object): # """ # No-op encryption backend. # # encrypt() and decrypt() simply return their inputs. # # Methods # ------- # encrypt : callable[bytes -> bytes] # decrypt : callable[bytes -> bytes] # """ # def encrypt(self, b): # return b # # def decrypt(self, b): # return b # # Path: pgcontents/query.py # def ensure_db_user(db, user_id): # """ # Add a new user if they don't already exist. # """ # with ignore_unique_violation(): # db.execute( # users.insert().values(id=user_id), # ) # # Path: pgcontents/utils/ipycompat.py . Output only the next line.
default_value=NoEncryption(),
Here is a snippet: <|code_start|> ) max_file_size_bytes = Integer( default_value=UNLIMITED, config=True, help="Maximum size in bytes of a file that will be saved.", ) crypto = Any( default_value=NoEncryption(), allow_none=False, config=True, help=( "Object with encrypt() and decrypt() methods to " "call on data entering/exiting the database.", ) ) engine = Instance(Engine) def _engine_default(self): return create_engine(self.db_url, echo=False) def __init__(self, *args, **kwargs): super(PostgresManagerMixin, self).__init__(*args, **kwargs) if self.create_user_on_startup: self.ensure_user() def ensure_user(self): with self.engine.begin() as db: <|code_end|> . Write the next line using the current file imports: from getpass import getuser from sqlalchemy import ( create_engine, ) from sqlalchemy.engine.base import Engine from tornado.web import HTTPError from .constants import UNLIMITED from .crypto import NoEncryption from .query import ensure_db_user from .utils.ipycompat import Any, Bool, Instance, Integer, HasTraits, Unicode and context from other files: # Path: pgcontents/constants.py # UNLIMITED = 0 # # Path: pgcontents/crypto.py # class NoEncryption(object): # """ # No-op encryption backend. # # encrypt() and decrypt() simply return their inputs. # # Methods # ------- # encrypt : callable[bytes -> bytes] # decrypt : callable[bytes -> bytes] # """ # def encrypt(self, b): # return b # # def decrypt(self, b): # return b # # Path: pgcontents/query.py # def ensure_db_user(db, user_id): # """ # Add a new user if they don't already exist. # """ # with ignore_unique_violation(): # db.execute( # users.insert().values(id=user_id), # ) # # Path: pgcontents/utils/ipycompat.py , which may include functions, classes, or code. Output only the next line.
ensure_db_user(db, self.user_id)
Using the snippet: <|code_start|> """ Shared behavior for Postgres-backed ContentsManagers. """ db_url = Unicode( default_value="postgresql://{user}@/pgcontents".format( user=getuser(), ), config=True, help="Connection string for the database.", ) user_id = Unicode( default_value=getuser(), allow_none=True, config=True, help="Name for the user whose contents we're managing.", ) create_user_on_startup = Bool( default_value=True, config=True, help="Create a user for user_id automatically?", ) max_file_size_bytes = Integer( default_value=UNLIMITED, config=True, help="Maximum size in bytes of a file that will be saved.", ) <|code_end|> , determine the next line of code. You have imports: from getpass import getuser from sqlalchemy import ( create_engine, ) from sqlalchemy.engine.base import Engine from tornado.web import HTTPError from .constants import UNLIMITED from .crypto import NoEncryption from .query import ensure_db_user from .utils.ipycompat import Any, Bool, Instance, Integer, HasTraits, Unicode and context (class names, function names, or code) available: # Path: pgcontents/constants.py # UNLIMITED = 0 # # Path: pgcontents/crypto.py # class NoEncryption(object): # """ # No-op encryption backend. # # encrypt() and decrypt() simply return their inputs. # # Methods # ------- # encrypt : callable[bytes -> bytes] # decrypt : callable[bytes -> bytes] # """ # def encrypt(self, b): # return b # # def decrypt(self, b): # return b # # Path: pgcontents/query.py # def ensure_db_user(db, user_id): # """ # Add a new user if they don't already exist. # """ # with ignore_unique_violation(): # db.execute( # users.insert().values(id=user_id), # ) # # Path: pgcontents/utils/ipycompat.py . Output only the next line.
crypto = Any(
Based on the snippet: <|code_start|>""" Mixin for classes interacting with the pgcontents database. """ class PostgresManagerMixin(HasTraits): """ Shared behavior for Postgres-backed ContentsManagers. """ db_url = Unicode( default_value="postgresql://{user}@/pgcontents".format( user=getuser(), ), config=True, help="Connection string for the database.", ) user_id = Unicode( default_value=getuser(), allow_none=True, config=True, help="Name for the user whose contents we're managing.", ) <|code_end|> , predict the immediate next line with the help of imports: from getpass import getuser from sqlalchemy import ( create_engine, ) from sqlalchemy.engine.base import Engine from tornado.web import HTTPError from .constants import UNLIMITED from .crypto import NoEncryption from .query import ensure_db_user from .utils.ipycompat import Any, Bool, Instance, Integer, HasTraits, Unicode and context (classes, functions, sometimes code) from other files: # Path: pgcontents/constants.py # UNLIMITED = 0 # # Path: pgcontents/crypto.py # class NoEncryption(object): # """ # No-op encryption backend. # # encrypt() and decrypt() simply return their inputs. # # Methods # ------- # encrypt : callable[bytes -> bytes] # decrypt : callable[bytes -> bytes] # """ # def encrypt(self, b): # return b # # def decrypt(self, b): # return b # # Path: pgcontents/query.py # def ensure_db_user(db, user_id): # """ # Add a new user if they don't already exist. # """ # with ignore_unique_violation(): # db.execute( # users.insert().values(id=user_id), # ) # # Path: pgcontents/utils/ipycompat.py . Output only the next line.
create_user_on_startup = Bool(
Next line prediction: <|code_start|> user_id = Unicode( default_value=getuser(), allow_none=True, config=True, help="Name for the user whose contents we're managing.", ) create_user_on_startup = Bool( default_value=True, config=True, help="Create a user for user_id automatically?", ) max_file_size_bytes = Integer( default_value=UNLIMITED, config=True, help="Maximum size in bytes of a file that will be saved.", ) crypto = Any( default_value=NoEncryption(), allow_none=False, config=True, help=( "Object with encrypt() and decrypt() methods to " "call on data entering/exiting the database.", ) ) <|code_end|> . Use current file imports: (from getpass import getuser from sqlalchemy import ( create_engine, ) from sqlalchemy.engine.base import Engine from tornado.web import HTTPError from .constants import UNLIMITED from .crypto import NoEncryption from .query import ensure_db_user from .utils.ipycompat import Any, Bool, Instance, Integer, HasTraits, Unicode) and context including class names, function names, or small code snippets from other files: # Path: pgcontents/constants.py # UNLIMITED = 0 # # Path: pgcontents/crypto.py # class NoEncryption(object): # """ # No-op encryption backend. # # encrypt() and decrypt() simply return their inputs. # # Methods # ------- # encrypt : callable[bytes -> bytes] # decrypt : callable[bytes -> bytes] # """ # def encrypt(self, b): # return b # # def decrypt(self, b): # return b # # Path: pgcontents/query.py # def ensure_db_user(db, user_id): # """ # Add a new user if they don't already exist. # """ # with ignore_unique_violation(): # db.execute( # users.insert().values(id=user_id), # ) # # Path: pgcontents/utils/ipycompat.py . Output only the next line.
engine = Instance(Engine)
Given the code snippet: <|code_start|>Mixin for classes interacting with the pgcontents database. """ class PostgresManagerMixin(HasTraits): """ Shared behavior for Postgres-backed ContentsManagers. """ db_url = Unicode( default_value="postgresql://{user}@/pgcontents".format( user=getuser(), ), config=True, help="Connection string for the database.", ) user_id = Unicode( default_value=getuser(), allow_none=True, config=True, help="Name for the user whose contents we're managing.", ) create_user_on_startup = Bool( default_value=True, config=True, help="Create a user for user_id automatically?", ) <|code_end|> , generate the next line using the imports in this file: from getpass import getuser from sqlalchemy import ( create_engine, ) from sqlalchemy.engine.base import Engine from tornado.web import HTTPError from .constants import UNLIMITED from .crypto import NoEncryption from .query import ensure_db_user from .utils.ipycompat import Any, Bool, Instance, Integer, HasTraits, Unicode and context (functions, classes, or occasionally code) from other files: # Path: pgcontents/constants.py # UNLIMITED = 0 # # Path: pgcontents/crypto.py # class NoEncryption(object): # """ # No-op encryption backend. # # encrypt() and decrypt() simply return their inputs. # # Methods # ------- # encrypt : callable[bytes -> bytes] # decrypt : callable[bytes -> bytes] # """ # def encrypt(self, b): # return b # # def decrypt(self, b): # return b # # Path: pgcontents/query.py # def ensure_db_user(db, user_id): # """ # Add a new user if they don't already exist. # """ # with ignore_unique_violation(): # db.execute( # users.insert().values(id=user_id), # ) # # Path: pgcontents/utils/ipycompat.py . Output only the next line.
max_file_size_bytes = Integer(
Continue the code snippet: <|code_start|>""" Mixin for classes interacting with the pgcontents database. """ class PostgresManagerMixin(HasTraits): """ Shared behavior for Postgres-backed ContentsManagers. """ <|code_end|> . Use current file imports: from getpass import getuser from sqlalchemy import ( create_engine, ) from sqlalchemy.engine.base import Engine from tornado.web import HTTPError from .constants import UNLIMITED from .crypto import NoEncryption from .query import ensure_db_user from .utils.ipycompat import Any, Bool, Instance, Integer, HasTraits, Unicode and context (classes, functions, or code) from other files: # Path: pgcontents/constants.py # UNLIMITED = 0 # # Path: pgcontents/crypto.py # class NoEncryption(object): # """ # No-op encryption backend. # # encrypt() and decrypt() simply return their inputs. # # Methods # ------- # encrypt : callable[bytes -> bytes] # decrypt : callable[bytes -> bytes] # """ # def encrypt(self, b): # return b # # def decrypt(self, b): # return b # # Path: pgcontents/query.py # def ensure_db_user(db, user_id): # """ # Add a new user if they don't already exist. # """ # with ignore_unique_violation(): # db.execute( # users.insert().values(id=user_id), # ) # # Path: pgcontents/utils/ipycompat.py . Output only the next line.
db_url = Unicode(
Predict the next line after this snippet: <|code_start|> def split_api_filepath(path): """ Split an API file path into directory and name. """ parts = path.rsplit('/', 1) if len(parts) == 1: name = parts[0] dirname = '/' else: name = parts[1] dirname = parts[0] + '/' return from_api_dirname(dirname), name def writes_base64(nb, version=NBFORMAT_VERSION): """ Write a notebook as base64. """ return b64encode(writes(nb, version=version).encode('utf-8')) def reads_base64(nb, as_version=NBFORMAT_VERSION): """ Read a notebook from base64. """ try: return reads(b64decode(nb).decode('utf-8'), as_version=as_version) except Exception as e: <|code_end|> using the current file's imports: from base64 import ( b64decode, b64encode, ) from datetime import datetime from functools import wraps from tornado.web import HTTPError from .error import CorruptedFile, PathOutsideRoot from .utils.ipycompat import reads, writes import mimetypes import posixpath and any relevant context from other files: # Path: pgcontents/error.py # class CorruptedFile(Exception): # pass # # class PathOutsideRoot(Exception): # pass # # Path: pgcontents/utils/ipycompat.py . Output only the next line.
raise CorruptedFile(e)
Continue the code snippet: <|code_start|> "mimetype": None, } def base_directory_model(path): m = base_model(path) m.update( type='directory', last_modified=DUMMY_CREATED_DATE, created=DUMMY_CREATED_DATE, ) return m def api_path_join(*paths): """ Join API-style paths. """ return posixpath.join(*paths).strip('/') def normalize_api_path(api_path): """ Resolve paths with '..' to normalized paths, raising an error if the final result is outside root. """ normalized = posixpath.normpath(api_path.strip('/')) if normalized == '.': normalized = '' elif normalized.startswith('..'): <|code_end|> . Use current file imports: from base64 import ( b64decode, b64encode, ) from datetime import datetime from functools import wraps from tornado.web import HTTPError from .error import CorruptedFile, PathOutsideRoot from .utils.ipycompat import reads, writes import mimetypes import posixpath and context (classes, functions, or code) from other files: # Path: pgcontents/error.py # class CorruptedFile(Exception): # pass # # class PathOutsideRoot(Exception): # pass # # Path: pgcontents/utils/ipycompat.py . Output only the next line.
raise PathOutsideRoot(normalized)
Based on the snippet: <|code_start|> return db_path.strip('/') def split_api_filepath(path): """ Split an API file path into directory and name. """ parts = path.rsplit('/', 1) if len(parts) == 1: name = parts[0] dirname = '/' else: name = parts[1] dirname = parts[0] + '/' return from_api_dirname(dirname), name def writes_base64(nb, version=NBFORMAT_VERSION): """ Write a notebook as base64. """ return b64encode(writes(nb, version=version).encode('utf-8')) def reads_base64(nb, as_version=NBFORMAT_VERSION): """ Read a notebook from base64. """ try: <|code_end|> , predict the immediate next line with the help of imports: from base64 import ( b64decode, b64encode, ) from datetime import datetime from functools import wraps from tornado.web import HTTPError from .error import CorruptedFile, PathOutsideRoot from .utils.ipycompat import reads, writes import mimetypes import posixpath and context (classes, functions, sometimes code) from other files: # Path: pgcontents/error.py # class CorruptedFile(Exception): # pass # # class PathOutsideRoot(Exception): # pass # # Path: pgcontents/utils/ipycompat.py . Output only the next line.
return reads(b64decode(nb).decode('utf-8'), as_version=as_version)
Using the snippet: <|code_start|> assert len(normalized), "Empty path in from_api_filename" return '/' + normalized def to_api_path(db_path): """ Convert database path into API-style path. """ return db_path.strip('/') def split_api_filepath(path): """ Split an API file path into directory and name. """ parts = path.rsplit('/', 1) if len(parts) == 1: name = parts[0] dirname = '/' else: name = parts[1] dirname = parts[0] + '/' return from_api_dirname(dirname), name def writes_base64(nb, version=NBFORMAT_VERSION): """ Write a notebook as base64. """ <|code_end|> , determine the next line of code. You have imports: from base64 import ( b64decode, b64encode, ) from datetime import datetime from functools import wraps from tornado.web import HTTPError from .error import CorruptedFile, PathOutsideRoot from .utils.ipycompat import reads, writes import mimetypes import posixpath and context (class names, function names, or code) available: # Path: pgcontents/error.py # class CorruptedFile(Exception): # pass # # class PathOutsideRoot(Exception): # pass # # Path: pgcontents/utils/ipycompat.py . Output only the next line.
return b64encode(writes(nb, version=version).encode('utf-8'))
Given the following code snippet before the placeholder: <|code_start|> managers = Dict(help=("Dict mapping root dir -> ContentsManager.")) def _managers_default(self): return { key: mgr_cls( parent=self, log=self.log, **self.manager_kwargs.get(key, {}) ) for key, mgr_cls in iteritems(self.manager_classes) } def _managers_changed(self, name, old, new): """ Strip slashes from directories before updating. """ for key in new: if '/' in key: raise ValueError( "Expected directory names w/o slashes. Got [%s]" % key ) self.managers = {k.strip('/'): v for k, v in new.items()} @property def root_manager(self): return self.managers.get('') def _extra_root_dirs(self): return [ <|code_end|> , predict the next line using imports from the current file: from six import iteritems from tornado.web import HTTPError from .api_utils import ( base_directory_model, normalize_api_path, outside_root_to_404, ) from .utils.ipycompat import ContentsManager, Dict and context including class names, function names, and sometimes code from other files: # Path: pgcontents/api_utils.py # def base_directory_model(path): # m = base_model(path) # m.update( # type='directory', # last_modified=DUMMY_CREATED_DATE, # created=DUMMY_CREATED_DATE, # ) # return m # # def normalize_api_path(api_path): # """ # Resolve paths with '..' to normalized paths, raising an error if the final # result is outside root. # """ # normalized = posixpath.normpath(api_path.strip('/')) # if normalized == '.': # normalized = '' # elif normalized.startswith('..'): # raise PathOutsideRoot(normalized) # return normalized # # def outside_root_to_404(fn): # """ # Decorator for converting PathOutsideRoot errors to 404s. # """ # @wraps(fn) # def wrapped(*args, **kwargs): # try: # return fn(*args, **kwargs) # except PathOutsideRoot as e: # raise HTTPError(404, "Path outside root: [%s]" % e.args[0]) # return wrapped # # Path: pgcontents/utils/ipycompat.py . Output only the next line.
base_directory_model(path)