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: Li...
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...
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.Char...
{"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)), (...
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...
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...
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 Option...
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 ...
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()}) mode...
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...
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.d...
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"] ) <...
_, _, 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)), ...
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 = ConditionalUni...
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( ...
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 ...
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....
"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: ...
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)] ...
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: ...
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. ...
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": {"E...
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.Fo...
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 o...
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. ...
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: ...
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...
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 c...
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}'...
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, ...
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 du...
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. """ ...
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: ...
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] s...
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 ...
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 co...
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')) p...
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 ...
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 impo...
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...
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, ...
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...
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, ...
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, r...
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_na...
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 # translati...
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 ...
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...
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 ...
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 ...
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) ca...
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_in...
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...
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. """ ...
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"R...
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_ini...
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_transit...
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) ...
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_ini...
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() ...
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')), ) # ...
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...
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 == ...
"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. """ ...
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 Postg...
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 = e...
'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, ...
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_c...
'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/...
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() ret...
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_f...
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, us...
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_dirn...
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, us...
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: ...
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_i...
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, ...
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...
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/not...
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) # ==============================...
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: res...
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...
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...
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_v...
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([use...
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, ...
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 resu...
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 ...
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 =...
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=...
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...
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( us...
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 us...
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...
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 ( ...
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] + ...
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-s...
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 = ...
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 dire...
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.ge...
base_directory_model(path)