Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line for this snippet: <|code_start|>
def parse_linkauth(data):
return proto.EosActionLinkAuth(
account=name_to_number(data['account']),
code=name_to_number(data['code']),
type=name_to_number(data['type']),
requirement=name_to_number(data['requirement'])
)
def p... | address_n=parse_path(key['address_n']) |
Given the following code snippet before the placeholder: <|code_start|> self.setup_mnemonic_nopin_nopassphrase()
# tx: d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882
# input 0: 0.0039 BTC
inp1 = proto_types.TxInputType(address_n=[0], # 14LmW5k4ssUrtbAB4255zdqv3b4w1TuX... | except CallException as e: |
Predict the next line after this snippet: <|code_start|> proto.TxRequest(request_type=proto_types.TXFINISHED),
])
(signatures, serialized_tx) = self.client.sign_tx('Bitcoin', [inp1, ], [out1, ])
# Accepted by network: tx fd79435246dee76b2f159d2db08032d666c95adc544de64c8c... | self.client.set_tx_api(tx_api.TxApiTestnet) |
Given the code snippet: <|code_start|>
DEFAULT_BIP32_PATH = "m/44h/931h/0h/0/0"
class TestMsgThorChainGetAddress(common.KeepKeyTest):
def test_thorchain_get_address(self):
self.requires_firmware("7.0.2")
self.setup_mnemonic_nopin_nopassphrase()
<|code_end|>
, generate the next line using the impo... | address = self.client.thorchain_get_address(parse_path(DEFAULT_BIP32_PATH), testnet=True) |
Given snippet: <|code_start|># This file is part of the Trezor project.
#
# Copyright (C) 2012-2018 SatoshiLabs and contributors
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3
# as published by the Free Software Foundation... | address_n=parse_path("84'/1'/0'/0/0"), # tgrs1qkvwu9g3k2pdxewfqr7syz89r3gj557l3ued7ja |
Here is a snippet: <|code_start|># This file is part of the Trezor project.
#
# Copyright (C) 2012-2018 SatoshiLabs and contributors
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3
# as published by the Free Software Founda... | self.client.set_tx_api(TxApiGroestlcoinTestnet) |
Given the following code snippet before the placeholder: <|code_start|>
def test_xfer_node_error(self):
self.setup_mnemonic_nopin_nopassphrase()
# tx: d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882
# input 0: 0.0039 BTC
inp1 = proto_types.TxInputType(addres... | except CallException as e:
|
Next line prediction: <|code_start|>
class ConfigData(unittest.TestCase):
def test_todict_noconv(self):
for x in ({}, 0, None, 1, "", True, False, 0.0, -1, -1.1, 1.1, {1: 1}):
<|code_end|>
. Use current file imports:
(import copy
import unittest
from ecmcli.commands import base, remote)
and context inc... | self.assertEqual(base.todict(x), copy.deepcopy(x)) |
Using the snippet: <|code_start|> 'Welcome to the ECM shell.',
'Type "help" or "?" to list commands and "exit" to quit.'
])
def verror(self, *args, **kwargs):
msg = ' '.join(map(str, args))
shellish.vtmlprint(msg, file=sys.stderr, **kwargs)
def prompt_info(self):
inf... | class ECMRoot(base.ECMCommand): |
Given the following code snippet before the placeholder: <|code_start|>class ECMRoot(base.ECMCommand):
""" ECM Command Line Interface
This utility represents a collection of sub-commands to perform against
the Cradlepoint ECM service. You must already have a valid ECM
username/password to use this too... | for x in shtools.command_classes: |
Predict the next line after this snippet: <|code_start|>
class ArgSanity(unittest.TestCase):
def setUp(self):
api = unittest.mock.Mock()
fake = dict(name='foo', id='1')
api.get_by_id_or_name.return_value = fake
api.get_pager.return_value = [fake]
<|code_end|>
using the current fil... | self.cmd = routers.Reboot(api=api) |
Predict the next line for this snippet: <|code_start|> __str__ = __ir_json__str__
def __new__(self, *args, **kwargs):
return float.__new__(self, *args, **kwargs)
# Cannot subclass NoneType, so use IRNullType to represent null.
class _IRJsonNull(IRNullType):
def __str__(self):
return 'null'
... | return irNull |
Using the snippet: <|code_start|>
class _IRJsonDict(dict):
__str__ = __ir_json__str__
def __new__(self, *args, **kwargs):
return dict.__new__(self, *args, **kwargs)
_IRJsonObject = _IRJsonDict
class _IRJsonString(str):
__str__ = __ir_json__str__
def __new__(self, *args, **kwargs):
retur... | class _IRJsonNull(IRNullType): |
Continue the code snippet: <|code_start|># Copyright (c) 2016, 2017 Timothy Savannah under LGPL version 2.1. See LICENSE for more information.
#
# FieldValueTypes - Types that can be passed to "valueType" of an IRField for special implicit conversions
#
__all__ = ('IRDatetimeValue', 'IRJsonValue')
try:
unicode... | theArg = to_unicode(args[0]) |
Predict the next line after this snippet: <|code_start|>
class TestTemplateServer(TestCase):
def test_get_cwd(self):
"""
This is a bad test
"""
<|code_end|>
using the current file's imports:
from django.test import TestCase
from isomorphic.server.template_server import TemplateServer
and... | template_server = TemplateServer() |
Given the following code snippet before the placeholder: <|code_start|>
class FakeRequest():
def __init__(self):
self.META = {}
@property
def path(self):
return '/'
def build_absolute_uri(self):
return 'http://localhost:8000/'
class TestJsTemplate(TestCase):
def test_ren... | template = JsTemplate(template_path) |
Next line prediction: <|code_start|>
class FakeRequest():
def __init__(self):
self.META = {}
@property
def path(self):
return '/'
def build_absolute_uri(self):
return 'http://localhost:8000/'
class TestJsTemplate(TestCase):
def test_render_template_without_request(self):... | loader = JsLoader(engine=None) |
Given snippet: <|code_start|>
class MockSock():
def send(self, message):
pass
def recv(self, buffer_size):
return b''
def mock_connect():
return MockSock()
class TestTemplateClient(TestCase):
def test_make_none(self):
"""
Test JSON conversion doesn't fail when objec... | is_none = template_client._make_none(foo) |
Based on the snippet: <|code_start|>
class JsTemplates(BaseEngine):
def __init__(self, params):
params = params.copy()
options = params.pop('OPTIONS').copy()
super(JsTemplates, self).__init__(params)
self.engine = JsEngine(self.dirs, self.app_dirs, **options)
def get_template(... | client = TemplateClient() |
Given the code snippet: <|code_start|>
class JsTemplates(BaseEngine):
def __init__(self, params):
params = params.copy()
options = params.pop('OPTIONS').copy()
super(JsTemplates, self).__init__(params)
<|code_end|>
, generate the next line using the imports in this file:
from django.middl... | self.engine = JsEngine(self.dirs, self.app_dirs, **options) |
Given snippet: <|code_start|>
class TestLoader(TestCase):
def test_render_template(self):
"""
Render a template with the template tag
"""
context = RequestContext(request=None)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.template ... | template = djangojs.include_js(context, template_name='test-component.js') |
Given snippet: <|code_start|>
class TestLoader(TestCase):
def test_render_template(self):
"""
Render a template with the template tag
"""
context = RequestContext(request=None)
template = djangojs.include_js(context, template_name='test-component.js')
self.assertEqua... | with self.assertRaises(JsMissingTemplateDirException): |
Given the code snippet: <|code_start|>
register = template.Library()
loader = JsLoader(engine=None)
class JsMissingTemplateDirException(Exception):
pass
def _get_template_dirs():
for t in settings.TEMPLATES:
if t['BACKEND'] == 'isomorphic.template.backend.JsTemplates':
return t['DIRS']
... | template = JsTemplate(template_path) |
Predict the next line for this snippet: <|code_start|>
class TestEngine(TestCase):
def test_get_template(self):
"""
Get a template by name
"""
params = {
'DIRS': [settings.TEMPLATE_DIR],
'APP_DIRS': False,
'NAME': 'backend',
'OPTIONS':... | templates = JsTemplates(params) |
Here is a snippet: <|code_start|>
class TestEngine(TestCase):
def test_get_template(self):
"""
Get a template by name
"""
params = {
'DIRS': [settings.TEMPLATE_DIR],
'APP_DIRS': False,
'NAME': 'backend',
'OPTIONS': {}
}
... | self.assertIsInstance(template, JsTemplate) |
Continue the code snippet: <|code_start|>
class TestLoader(TestCase):
def test_load_missing_template(self):
engine = JsEngine(dirs=[settings.TEMPLATE_DIR])
<|code_end|>
. Use current file imports:
from django.conf import settings
from django.template import TemplateDoesNotExist
from django.test import Tes... | loader = JsLoader(engine) |
Given the code snippet: <|code_start|> Notes
-----
The ``coords`` attribute will contain the coordinates of each lattice
point determined by the coordinate index and the primitive lattice
vectors. E.g., in 2-dimensions
lattice.coord[i, j] = (i - N1//2) * primitiveVector[0] +... | @lazy_property |
Here is a snippet: <|code_start|> batoid.SellmeierMedium(B1, B2, B3, C1, C2, C3, B1)
wavelengths = rng.uniform(300e-9, 1100e-9, size=1000)
indices = silica.getN(wavelengths)
for w, index in zip(wavelengths, indices):
assert silica.getN(w) == index
# CSV also from refractiveindex.info
... | kbk7 = batoid.SumitaMedium([A0, A1, A2, A3, A4, A5]) |
Next line prediction: <|code_start|>
@timer
def test_ConstMedium():
rng = np.random.default_rng(5)
for i in range(100):
n = rng.uniform(1.0, 2.0)
const_medium = batoid.ConstMedium(n)
wavelengths = rng.uniform(300e-9, 1100e-9, size=100)
for w in wavelengths:
assert co... | table_medium = batoid.TableMedium(ws, ns) |
Given the following code snippet before the placeholder: <|code_start|>
@timer
def test_rSplit():
rng = np.random.default_rng(5)
for _ in range(100):
R = rng.normal(0.7, 0.8)
conic = rng.uniform(-2.0, 1.0)
ncoef = rng.integers(0, 5)
coefs = [rng.normal(0, 1e-10) for i in range(n... | m2 = batoid.ConstMedium(1.1) |
Based on the snippet: <|code_start|> asphere = batoid.Asphere(R, conic, coefs)
theta_x = rng.normal(0.0, 1e-8)
theta_y = rng.normal(0.0, 1e-8)
rays = batoid.RayVector.asPolar(
backDist=10.0, medium=batoid.Air(),
wavelength=500e-9, outer=0.25*R,
theta_x... | batoid.RefractiveInterface( |
Based on the snippet: <|code_start|> optic : batoid.Optic
Optical system
theta_x, theta_y : float
Field angle in radians
wavelength : float
Wavelength in meters
nrad : int, optional
Number of ray radii to use. (see RayVector.asPolar())
naz : int, optional
Appr... | soln = bilinear_fit(ux[w], uy[w], rays.kx[w], rays.ky[w]) |
Given snippet: <|code_start|> optic : batoid.Optic
Optical system
theta_x, theta_y : float
Field angle in radians
wavelength : float
Wavelength in meters
nrad : int, optional
Number of ray radii to use. (see RayVector.asPolar())
naz : int, optional
Approximate... | nominalCos = fieldToDirCos(theta_x, theta_y, projection=projection) |
Given snippet: <|code_start|>
class Repository(CaseClass):
def __init__(self, driver, group_id):
super(Repository, self).__init__(['driver', 'group_id', 'artifacts'])
self.driver = driver
self.group_id = group_id
self.artifacts = defaultdict(list)
def load(self, artifact_id):
... | self.artifacts[artifact_id] = [Artifact.from_dict(x) for x in xs] |
Here is a snippet: <|code_start|> x.file_info.size_format(),
'%s' % x.file_info.mtime,
','.join(x.scm_info.tags) if x.scm_info else '',
x.scm_info.summary if x.scm_info else '',
] for x in arts]
column_len = [max(... | bi = BasicInfo.from_path(self.group_id, path) |
Given the code snippet: <|code_start|>
initialize_empty_form = True
form_data = self.request.session.get(MULTISEEK_SESSION_KEY, {})
if form_data:
form_data = json.loads(form_data)
initialize_empty_form = False
js_init = registry.recreate_form(form_data)
j... | MULTISEEK_REPORT_TYPE=MULTISEEK_REPORT_TYPE, |
Predict the next line after this snippet: <|code_start|> )
)
initialize_empty_form = True
form_data = self.request.session.get(MULTISEEK_SESSION_KEY, {})
if form_data:
form_data = json.loads(form_data)
initialize_empty_form = False
js_init = re... | saved_forms=SearchForm.objects.get_for_user(self.request.user), |
Given snippet: <|code_start|> if callable(values):
return values()
return values
js_value_lists = json.dumps(
dict(
[
(text(field.label), [text(x) for x in get_values(field.values)])
for field in registry... | js_and=AND, |
Given the code snippet: <|code_start|>def user_allowed_to_save_forms(user):
if hasattr(user, "is_staff"):
return user.is_staff
class MultiseekPageMixin:
registry = None
class MultiseekFormPage(MultiseekPageMixin, TemplateView):
"""
This view renders multiseek form and javascript required to ... | for field in registry.field_by_type(AUTOCOMPLETE, self.request) |
Here is a snippet: <|code_start|> )
initialize_empty_form = True
form_data = self.request.session.get(MULTISEEK_SESSION_KEY, {})
if form_data:
form_data = json.loads(form_data)
initialize_empty_form = False
js_init = registry.recreate_form(form_data)
... | MULTISEEK_ORDERING_PREFIX=MULTISEEK_ORDERING_PREFIX, |
Next line prediction: <|code_start|> return values()
return values
js_value_lists = json.dumps(
dict(
[
(text(field.label), [text(x) for x in get_values(field.values)])
for field in registry.field_by_type(VALUE_LIST,... | js_or=OR, |
Predict the next line after this snippet: <|code_start|>
def get_context_data(self):
registry = get_registry(self.registry)
fields = registry.get_fields(self.request)
js_fields = json.dumps([text(x.label) for x in fields])
js_ops = json.dumps(
dict([(text(f.label), [tex... | for field in registry.field_by_type(VALUE_LIST, self.request) |
Given snippet: <|code_start|>
def convert_context_to_json(self, context):
return json.dumps(context)
class MultiseekSaveForm(MultiseekPageMixin, JSONResponseMixin, TemplateView):
def get(self, request, *args, **kw):
if not user_allowed_to_save_forms(request.user):
return HttpRespon... | except (TypeError, UnknownField, ParseError, UnknownOperation): |
Here is a snippet: <|code_start|>
def convert_context_to_json(self, context):
return json.dumps(context)
class MultiseekSaveForm(MultiseekPageMixin, JSONResponseMixin, TemplateView):
def get(self, request, *args, **kw):
if not user_allowed_to_save_forms(request.user):
return HttpRe... | except (TypeError, UnknownField, ParseError, UnknownOperation): |
Given snippet: <|code_start|>
def convert_context_to_json(self, context):
return json.dumps(context)
class MultiseekSaveForm(MultiseekPageMixin, JSONResponseMixin, TemplateView):
def get(self, request, *args, **kw):
if not user_allowed_to_save_forms(request.user):
return HttpRespon... | except (TypeError, UnknownField, ParseError, UnknownOperation): |
Using the snippet: <|code_start|>
MULTISEEK_SESSION_KEY = "multiseek_json"
MULTISEEK_SESSION_KEY_REMOVED = "multiseek_json_removed"
def reverse_or_just_url(s):
if s.startswith("/"):
return s
return reverse(s)
LAST_FIELD_REMOVE_MESSAGE = _("The ability to remove the last field has been disabled.")
... | registry = get_registry(self.registry) |
Next line prediction: <|code_start|># -*- encoding: utf-8 -*-
class TestModels(TransactionTestCase):
def test_search_form_manager(self):
u = baker.make(User)
<|code_end|>
. Use current file imports:
(from django.contrib.auth.models import AnonymousUser, User
from django.test import TransactionTestCase
... | s1 = baker.make(SearchForm, owner=u, public=False, name='A') |
Given the following code snippet before the placeholder: <|code_start|> Zwracana wartość słownika 'value' może być różna dla różnych typów
pól (np dla multiseek.logic.RANGE jest to lista z wartościami z obu pól)
"""
ret = {}
for elem in ['type', 'op', 'prev-op', 'close-button']:
... | elif inner_type == DATE: |
Continue the code snippet: <|code_start|> for elem in ['type', 'op', 'prev-op', 'close-button']:
try:
e = element.find_by_id(elem, wait_time=0)[0]
except ElementDoesNotExist as x:
# prev-op may be None
if elem != 'prev-op':
... | elif inner_type == AUTOCOMPLETE: |
Next line prediction: <|code_start|> następna operacja, przycisk zamknięcia
Z pomocniczych wartości, zwracanych w słowniku mamy 'type' czyli
tekstowy typ, odpowiadający definicjom w bpp.multiseek.logic.fields.keys()
Zwracana wartość słownika 'value' może być różna dla różnych typów
... | elif inner_type == RANGE: |
Predict the next line for this snippet: <|code_start|> formularzu. Pole - czyli wiersz z kolejnymi selectami:
pole przeszukiwane, operacja, wartość wyszukiwana,
następna operacja, przycisk zamknięcia
Z pomocniczych wartości, zwracanych w słowniku mamy 'type' czyli
teksto... | if inner_type in [STRING, VALUE_LIST]: |
Predict the next line after this snippet: <|code_start|> formularzu. Pole - czyli wiersz z kolejnymi selectami:
pole przeszukiwane, operacja, wartość wyszukiwana,
następna operacja, przycisk zamknięcia
Z pomocniczych wartości, zwracanych w słowniku mamy 'type' czyli
teks... | if inner_type in [STRING, VALUE_LIST]: |
Next line prediction: <|code_start|> self.click_save_button()
WebDriverWait(self.browser, 10).until(alert_is_present())
alert = self.browser.driver.switch_to.alert
alert.fill_with(name)
alert.accept()
WebDriverWait(self.browser, 10).until_not(alert_is_present())
def... | registry = get_registry(settings.MULTISEEK_REGISTRY) |
Predict the next line after this snippet: <|code_start|>
@pytest.fixture
def multiseek_page(browser, live_server, initial_data):
browser.visit(live_server + reverse('multiseek:index'))
registry = get_registry(settings.MULTISEEK_REGISTRY)
page = MultiseekWebPage(browser=browser, registry=registry,
... | eng = baker.make(Language, name=_("english"), description="English language") |
Given snippet: <|code_start|>@pytest.fixture
def multiseek_page(browser, live_server, initial_data):
browser.visit(live_server + reverse('multiseek:index'))
registry = get_registry(settings.MULTISEEK_REGISTRY)
page = MultiseekWebPage(browser=browser, registry=registry,
live_serve... | a1 = baker.make(Author, last_name="Smith", first_name="John") |
Here is a snippet: <|code_start|> browser.visit(live_server + reverse('multiseek:index'))
registry = get_registry(settings.MULTISEEK_REGISTRY)
page = MultiseekWebPage(browser=browser, registry=registry,
live_server_url=live_server.url)
yield page
page.browser.quit()
@pyt... | b1 = baker.make(Book, title="A book with a title", year=2013, language=eng, |
Next line prediction: <|code_start|># -*- encoding: utf-8 -*-
class SplinterLoginMixin:
def login(self, username="admin", password="password"):
url = self.browser.url
<|code_end|>
. Use current file imports:
(import json
import pytest
import datetime
from django.conf import settings
from django.urls i... | with wait_for_page_load(self.browser): |
Predict the next line after this snippet: <|code_start|># -*- encoding: utf-8 -*-
urlpatterns = [
url(r'^jsi18n/$',
JavaScriptCatalog.as_view(packages=['multiseek']),
name="js_i18n"),
<|code_end|>
using the current file's imports:
from django.conf.urls import url
from django.conf import set... | url(r'^$', csrf_exempt(views.MultiseekFormPage.as_view( |
Based on the snippet: <|code_start|> )), name="index"),
url(r'^results/$',
csrf_exempt(views.MultiseekResults.as_view(
registry=settings.MULTISEEK_REGISTRY,
template_name="multiseek/results.html"
)), name="results"),
url(r'^save_form/$',
csrf_exempt(views.Mul... | load_form, |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
graph_colors = ['r', 'g', 'b', 'c', 'm', 'y', 'k']
def time_ticks(x, pos):
return "{:10.2f}".format(float(x) / 1.0)
formatter = ticker.FuncFormatter(time_ticks)
def get_total_seconds(td):
return (td.microseconds + (td.seconds + td.days * 24 * 360... | requests = logger.get_log_dicts(user_agent=user_agent) |
Given snippet: <|code_start|> potTemplateFile = 'potTemplate.png'
cv2.imwrite(os.path.join(self.timestreamRootPath, self.settingPath, potTemplateFile), self.potTemplate[:,:,::-1])
potDict['potTemplateFile'] = potTemplateFile
else:
potDict = {}
s... | self.pl = pipeline.ImagePipeline(self.settings) |
Using the snippet: <|code_start|>
class TestValidateTimestreamManfiest(TestCase):
"""Tests for ts.parse.validate.validate_timestream_manifest"""
str_dict = {
"name": "BVZ0022-GC05L-CN650D-Cam07~fullres-orig",
"start_datetime": "2013_10_30_03_00_00",
"end_datetime": "2013_10_30_06_00_0... | self.assertDictEqual(validate_timestream_manifest(self.str_dict), |
Given the code snippet: <|code_start|> "image_type": "jpg",
"extension": "JPG",
"interval": 30,
"missing": [],
}
def test_validate_valid(self):
"""Test validate_timestream_manifest with valid manfests"""
self.assertDictEqual(validate_timestream_manifest(self.str_d... | v_date(date_str) |
Continue the code snippet: <|code_start|> '%Y_%m_%d',
'%Y_%m_%d_%H',
'{tsname:s}_%Y_%m_%d_%H_%M_%S_{n:02d}.{ext:s}',
]
TS_V1_FMT = path.join(*__TS_V1_LEVELS)
TS_MANIFEST_KEYS = [
"name",
"version",
"start_datetime",
"end_datetime",
"image_type",
"extension",
"interval",
]
def v... | Required("start_datetime"): v_datetime, |
Predict the next line after this snippet: <|code_start|> '%Y_%m',
'%Y_%m_%d',
'%Y_%m_%d_%H',
'{tsname:s}_%Y_%m_%d_%H_%M_%S_{n:02d}.{ext:s}',
]
TS_V1_FMT = path.join(*__TS_V1_LEVELS)
TS_MANIFEST_KEYS = [
"name",
"version",
"start_datetime",
"end_datetime",
"image_type",
"extension... | Required("version"): All(v_num_str, Range(min=1, max=2)), |
Given the code snippet: <|code_start|>
CLI_DOC = """
USAGE:
fixChamberPos.py [-n] -c COLUMN -i INPUT
OPTIONS:
-n CSV has no header
-c COLUMN Column to convert.
-i INPUT Input CSV
"""
def main(opts):
ifh = open(opts['-i'])
rdr = csv.reader(ifh)
col = int(opts['-c']) - 1
... | line[col] = str(traypos_to_chamber_index(line[col])) |
Given the code snippet: <|code_start|> ignored_timestamps = list(ts_set)
print('ignored_timestamps = ', ignored_timestamps)
# We put everything else that is not an time series into outputroot.
ctx.setVal("outputroot", os.path.abspath(outputRootPath) + '-results')
if not os.path.exists(ctx.outputroo... | except PCExBrakeInPipeline as bip: |
Given snippet: <|code_start|>
class TestTrayPosToChamberIndex(TestCase):
_multiprocess_can_split_ = True
maxDiff = None
def test_tray_pos_to_chamber_idx(self):
"""Tests for ts.util.traypos_to_chamber_index"""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
fro... | self.assertEqual(layouts.traypos_to_chamber_index("1A1"), 1) |
Given the code snippet: <|code_start|> """
return remove_www(request.get_host().split(":")[0]).lower()
def process_request(self, request):
# Connection needs first to be at the public schema, as this is where
# the tenant metadata is stored.
connection.set_schema_to_public()
... | and request.tenant.schema_name == get_public_schema_name() |
Given the code snippet: <|code_start|>Extend BaseTenantMiddleware for a custom tenant selection strategy,
such as inspecting the header, or extracting it from some OAuth token.
"""
class BaseTenantMiddleware(django.utils.deprecation.MiddlewareMixin):
TENANT_NOT_FOUND_EXCEPTION = Http404
"""
Subclass and ... | TenantModel = get_tenant_model() |
Here is a snippet: <|code_start|>
"""
These middlewares should be placed at the very top of the middleware stack.
Selects the proper database schema using request information. Can fail in
various ways which is better than corrupting or revealing data.
Extend BaseTenantMiddleware for a custom tenant selection strategy... | return remove_www(request.get_host().split(":")[0]).lower() |
Given the code snippet: <|code_start|>
class BaseTestCase(TestCase):
"""
Base test case that comes packed with overloaded INSTALLED_APPS,
custom public tenant, and schemas cleanup on tearDown.
"""
@classmethod
def setUpClass(cls):
settings.TENANT_MODEL = 'tenant_schemas.Tenant'
... | % (get_public_schema_name(), get_public_schema_name())) |
Continue the code snippet: <|code_start|>"""
Adaptations of the cached and filesystem template loader working in a
multi-tenant setting
"""
class CachedLoader(cached.Loader):
def cache_key(self, *args, **kwargs):
key = super(CachedLoader, self).cache_key(*args, **kwargs)
<|code_end|>
. Use current file ... | if not connection.tenant or isinstance(connection.tenant, FakeTenant): |
Next line prediction: <|code_start|> stderr = OutputWrapper(sys.stderr)
stderr.style_func = style_func
if int(options.get('verbosity', 1)) >= 1:
stdout.write(style.NOTICE("=== Running migrate for schema %s" % schema_name))
connection.set_schema(schema_name)
MigrateCommand(stdout=stdout, stde... | public_schema_name = get_public_schema_name() |
Given the following code snippet before the placeholder: <|code_start|>
def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None,
current_app=None):
url = reverse_default(
viewname=viewname,
urlconf=urlconf,
args=args,
kwargs=kwargs,
current_app=cu... | return clean_tenant_url(url) |
Predict the next line for this snippet: <|code_start|>
class TenantTutorialMiddleware(object):
def process_request(self, request):
connection.set_schema_to_public()
hostname_without_port = remove_www_and_dev(request.get_host().split(':')[0])
<|code_end|>
with the help of current file imports:
fr... | TenantModel = get_tenant_model() |
Using the snippet: <|code_start|>
class TenantTutorialMiddleware(object):
def process_request(self, request):
connection.set_schema_to_public()
<|code_end|>
, determine the next line of code. You have imports:
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from... | hostname_without_port = remove_www_and_dev(request.get_host().split(':')[0]) |
Given snippet: <|code_start|>
class TenantTutorialMiddleware(object):
def process_request(self, request):
connection.set_schema_to_public()
hostname_without_port = remove_www_and_dev(request.get_host().split(':')[0])
TenantModel = get_tenant_model()
try:
request.tenant... | if hasattr(settings, 'PUBLIC_SCHEMA_URLCONF') and request.tenant.schema_name == get_public_schema_name(): |
Given the code snippet: <|code_start|>
class Command(BaseCommand):
def handle(self, *args, **options):
database = options.get('database', 'default')
if (settings.DATABASES[database]['ENGINE'] == 'tenant_schemas.postgresql_backend'):
raise CommandError("migrate has been disabled, for d... | if django_is_in_test_mode(): |
Given the code snippet: <|code_start|> for obj in self:
result = obj.delete()
if result is not None:
current_counter, current_counter_dict = result
counter += current_counter
counter_dict.update(current_counter_dict)
if counter:
... | validators=[_check_schema_name]) |
Using the snippet: <|code_start|>
class TenantMixin(models.Model):
"""
All tenant models must inherit this class.
"""
auto_drop_schema = False
"""
USE THIS WITH CAUTION!
Set this flag to true on a parent class if you want the schema to be
automatically deleted if the tenant row gets del... | if is_new and connection.schema_name != get_public_schema_name(): |
Continue the code snippet: <|code_start|> raise Exception("Can't create tenant outside the public schema. "
"Current schema is %s." % connection.schema_name)
elif not is_new and connection.schema_name not in (self.schema_name, get_public_schema_name()):
raise E... | if schema_exists(self.schema_name) and (self.auto_drop_schema or force_drop): |
Predict the next line for this snippet: <|code_start|>
class StandardExecutor(MigrationExecutor):
codename = 'standard'
def run_tenant_migrations(self, tenants):
for schema_name in tenants:
<|code_end|>
with the help of current file imports:
from tenant_schemas.migration_executors.base import Migrat... | run_migrations(self.args, self.options, self.codename, schema_name) |
Given snippet: <|code_start|> obj="django.conf.settings",
hint="This is necessary to overwrite built-in django "
"management commands with their schema-aware "
"implementations.",
id="tenant_schemas.W001"),
... | TenantModel = get_tenant_model() |
Predict the next line for this snippet: <|code_start|> else:
files.append(filename)
return dirs, files
def size(self, name):
return len(self.files[name])
class LocalStorage(MemoryStorage):
"""
Emulates a storage class that stores files on disk.
"""
def ... | foo_storage = get_storage('foo') |
Predict the next line after this snippet: <|code_start|> Utility function to create an image for testing.
"""
im = Image.new(mode, (width, height))
draw = ImageDraw.Draw(im)
draw.rectangle([0, 0, width // 2, height // 2], '#F00')
draw.rectangle([width // 2, 0, width, height // 2], '#0F0')
dr... | def make_thumbnail(self, preset, |
Predict the next line after this snippet: <|code_start|>
def make_image(storage, name, width, height, format='JPEG', mode='RGB'):
"""
Utility function to create an image for testing.
"""
im = Image.new(mode, (width, height))
draw = ImageDraw.Draw(im)
draw.rectangle([0, 0, width // 2, height ... | self.storage = MemoryStorage() |
Given the following code snippet before the placeholder: <|code_start|> def get_previous_in_queryset(self, photos):
if self.date is None:
photos = photos.filter(
date__isnull=True, filename__lt=self.filename)
else:
photos = photos.filter(
Q(date... | make_thumbnail(image_name, thumb_name, preset, |
Using the snippet: <|code_start|> Q(date=self.date, filename__gt=self.filename))
return photos.order_by('date', 'filename')[:1].get()
def get_previous_in_queryset(self, photos):
if self.date is None:
photos = photos.filter(
date__isnull=True, filename__lt=... | photo_storage = get_storage('photo') |
Given the following code snippet before the placeholder: <|code_start|>"""
Bare view implementation of the pet resource.
"""
def find_pets(request, limit=None, tags=()):
pets = Pet.objects.all()[:limit]
if tags:
tags_q = reduce(
lambda q, term: q | Q(tag=term),
tags,
... | return PetSchema().dump(pets, many=True) |
Next line prediction: <|code_start|> if type == 'number' or format in ('float', 'double'):
return float(value)
if format == 'byte': # base64 encoded characters
return base64.b64decode(value)
if format == 'binary': # any sequence of octets
return force_bytes(value)
if format == '... | if value is NO_VALUE: |
Given the following code snippet before the placeholder: <|code_start|>
def read_parameters(request, view_kwargs=None, capture_errors=False): # noqa: C901
"""
:param request: HttpRequest with attached api_info
:type request: HttpRequest
:type view_kwargs: dict[str, object]
:type capture_errors: boo... | raise ErroneousParameters(errors, params) |
Given snippet: <|code_start|> if format == 'binary': # any sequence of octets
return force_bytes(value)
if format == 'date': # ISO8601 date
return iso8601.parse_date(value).date()
if format == 'dateTime': # ISO8601 datetime
return iso8601.parse_date(value)
if type == 'string':
... | errors[param.name] = MissingParameter(f'parameter {param.name} is required but missing') |
Given the code snippet: <|code_start|>
@doc_versions
def test_codegen(doc_version, capsys):
path = os.path.realpath(os.path.join(os.path.dirname(__file__), doc_version, 'petstore-expanded.yaml'))
<|code_end|>
, generate the next line using the imports in this file:
import os
from lepo import codegen
from lepo_te... | codegen.cmdline([path]) |
Based on the snippet: <|code_start|> return self.data['operationId']
@cached_property
def parameters(self):
"""
Combined path-level and operation-level parameters.
Any $refs are resolved here.
Note that this implementation differs from the spec in that we only use
... | source = maybe_resolve(source, self.api.resolve_reference) |
Here is a snippet: <|code_start|> return force_str(value).split(',')
def dot_split(value):
return force_str(value).split('.')
def space_split(value):
return force_str(value).split(' ')
def tab_split(value):
return force_str(value).split('\t')
def pipe_split(value):
return force_str(value).spl... | decoder = get_decoder(request.content_type) |
Given snippet: <|code_start|> return force_str(value).split('.')
def space_split(value):
return force_str(value).split(' ')
def tab_split(value):
return force_str(value).split('\t')
def pipe_split(value):
return force_str(value).split('|')
def read_body(request, parameter=None):
if parameter:... | raise InvalidBodyContent(f'Unable to parse this body as {request.content_type}') from exc |
Given the code snippet: <|code_start|>
def read_body(request, parameter=None):
if parameter:
if parameter.type == 'binary':
return request.body.read()
try:
if request.content_type == 'multipart/form-data':
# TODO: this definitely doesn't handle multiple values for the sa... | schema = maybe_resolve(schema, resolve=api.resolve_reference) |
Next line prediction: <|code_start|> pet1 = Pet.objects.create(name='henlo')
pet2 = Pet.objects.create(name='worl')
assert len(get_data_from_response(client.get('/api/pets'))) == 2
client.delete(f'/api/pets/{pet1.id}')
assert len(get_data_from_response(client.get('/api/pets'))) == 1
@pytest.mark.dj... | with pytest.raises(ErroneousParameters) as ei: |
Predict the next line for this snippet: <|code_start|>
pet_data = get_data_from_response(client.get('/api/pets'))[0]
assert pet_data['name'] == 'worl'
assert pet_data['tag'] == 'bunner'
@pytest.mark.django_db
def test_invalid_operation(client, api_urls):
assert client.patch('/api/pets').status_code ==... | assert isinstance(ei.value.errors['pet'], InvalidBodyContent) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.