Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the following code snippet before the placeholder: <|code_start|>
class FunDemo():
def show(self):
print 'funDemo'
def add(self, a, b):
return a + b
@staticmethod
def cmd():
return putils.execute()
class FakeDemo():
<|code_end|>
, predict the next line using imports fr... | def show(self): |
Based on the snippet: <|code_start|>class FunDemo():
def show(self):
print 'funDemo'
def add(self, a, b):
return a + b
@staticmethod
def cmd():
return putils.execute()
class FakeDemo():
def show(self):
print 'FakeDemo'
class TestDemo(base.TestCase):
def setU... | self.assertEqual(1, result) |
Given the code snippet: <|code_start|>
class FunDemo():
def show(self):
print 'funDemo'
def add(self, a, b):
return a + b
@staticmethod
<|code_end|>
, generate the next line using the imports in this file:
import os
import mock
import testtools
from tests import base
from virtman.opensta... | def cmd(): |
Next line prediction: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
__all__ = ["get_best", "best_sample", "get_simple_prior", "sample_prior", "sample_posterior",
"boxplot", "violinplot", "step"]
def get_simple_prior(prior, xlim, num=1000):
<|code_end|>
. Use current file imports:
(import ... | xx = np.linspace(*xlim, num=num) |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
__all__ = ["get_best", "best_sample", "get_simple_prior", "sample_prior", "sample_posterior",
"boxplot", "violinplot", "step"]
def get_simple_prior(prior, xlim, num=1000):
xx = np.linspace(*xlim, nu... | def sample_prior(model, nsample=1e6): |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
__all__ = ["params_to_sfh", "parametric_pset",
"parametric_cmf", "parametric_mwa", "parametric_sfr",
"compute_mass_formed",
"ratios_to_sfrs", "sfh_quantiles",
"sfh_to_cmf", "nonpar_mwa", "... | lookback = time.max() - time |
Given snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
__all__ = ["params_to_sfh", "parametric_pset",
"parametric_cmf", "parametric_mwa", "parametric_sfr",
"compute_mass_formed",
"ratios_to_sfrs", "sfh_quantiles",
"sfh_to_cmf", "nonpar_mwa", "nonpar_re... | sfhs = np.array(sfhs) |
Continue the code snippet: <|code_start|>
try:
except(ImportError):
pass
__all__ = ["BlackBodyDustBasis"]
# cgs constants
<|code_end|>
. Use current file imports:
import numpy as np
from sedpy.observate import getSED
from .constants import lsun, pc, kboltz, hplanck
and context (classes, functions, or code) ... | lightspeed = 29979245800.0 |
Given snippet: <|code_start|>
try:
except(ImportError):
pass
__all__ = ["BlackBodyDustBasis"]
# cgs constants
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
from sedpy.observate import getSED
from .constants import lsun, pc, kboltz, hplanck
and context... | lightspeed = 29979245800.0 |
Based on the snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
except(ImportError):
pass
__all__ = ["get_best", "get_truths", "get_percentiles", "get_stats",
"posterior_samples", "hist_samples", "joint_pdf", "compute_sigma_level",
"trim_walkers", "fill_between", "fig... | except(KeyError): |
Continue the code snippet: <|code_start|>#!/usr/bin/env python3
def main():
# parse orbited body
if len(sys.argv) <= 1:
print(
'Usage: %s BODY [SIZE]\n'
'Give information on possible satellites constellations\n'
'BODY is the primary around which the constellation o... | ('Communotron 32', 5e6), |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python3
def main():
# parse orbited body
if len(sys.argv) <= 1:
print(
'Usage: %s BODY [SIZE]\n'
'Give information on possible satellites constellations\n'
'BODY is the primary ar... | ('Reflectron KR-7', 90e6), |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python3
def main():
# parse orbited body
if len(sys.argv) <= 1:
print(
'Usage: %s BODY [SIZE]\n'
'Give information on possible satellites constellations\n'
'BODY is the primary around which the co... | ('Comms DTS-M1', 50e6), |
Next line prediction: <|code_start|> glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
gspyce.mesh.Sphere(1, 16, 16).draw()
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
def set_and_draw(self):
"""Setup the camera and draw"""
# reset everything
glClear(GL_COLOR_BUFFER_BIT | GL_D... | self.set_shader_matrices() |
Here is a snippet: <|code_start|> self.pick_objects = []
def set_and_draw(self):
"""Setup the camera and draw"""
self.pick_reset()
super().set_and_draw()
self.clear_pick_object()
def shader_set(self, program=None):
super().shader_set(program)
# update un... | self.set_color(*original_color) |
Predict the next line for this snippet: <|code_start|>
def main():
# parse orbited body
if len(sys.argv) <= 1:
print(
'Usage: %s BODY [ALTITUDE]\n'
'Compute the time spent in the dark by a satellite\n'
'If ALTITUDE is not given, the best one is computed\n'
... | semi_major_axis = primary.radius + altitude |
Next line prediction: <|code_start|>#!/usr/bin/env python
def main():
# parse orbited body
if len(sys.argv) <= 1:
print(
'Usage: %s BODY [ALTITUDE]\n'
'Compute the time spent in the dark by a satellite\n'
'If ALTITUDE is not given, the best one is computed\n'
... | return a * (1.5*s - 1) / (.75*s - 2 + 1/x) |
Based on the snippet: <|code_start|> # f''(a) / f'(a)
def ratio(a):
r = R/a
x = 1 - r*r
s = math.asin(r)/r * math.sqrt(x)
return a * (1.5*s - 1) / (.75*s - 2 + 1/x)
if len(sys.argv) > 2:
altitude = float(sys.argv[2])
semi_major_axis = primary.radius + altitude... | main() |
Based on the snippet: <|code_start|>
class OrbitState:
def __init__(self):
raise NotImplementedError
<|code_end|>
, predict the immediate next line with the help of imports:
import math
from spyce.vector import Vec3
and context (classes, functions, sometimes code) from other files:
# Path: spyce/vecto... | def distance_at_true_anomaly(self, true_anomaly): |
Using the snippet: <|code_start|>
class OrbitTarget:
def __init__(self):
raise NotImplementedError
def position_to_target(self, target, time):
return target.position_at_time(time) - self.position_at_time(time)
def distance_to_target(self, target, time):
return self.position_to_ta... | return self.velocity_to_target(target, time).norm() |
Using the snippet: <|code_start|>
class OrbitTarget:
def __init__(self):
raise NotImplementedError
def position_to_target(self, target, time):
return target.position_at_time(time) - self.position_at_time(time)
def distance_to_target(self, target, time):
return self.position_to_ta... | def time_at_next_approach(self, target, t, tolerance=0): |
Given the following code snippet before the placeholder: <|code_start|> # save orbit
body = bodies.setdefault(name, {})
body['orbit'] = {
'primary': primary,
'semi_major_axis': semi_major_axis,
'eccentricity': ecc... | if name == 'diameter': |
Given the code snippet: <|code_start|> 'epoch': epoch,
'mean_anomaly_at_epoch': mean_anomaly_at_epoch,
}
def get_dwarf_planet_data(bodies, name):
"""Get physical and orbital information of dwarf planets"""
# retrieve relevant page
html = urlopen('htt... | epoch = re.search(pattern, html).group(1) |
Based on the snippet: <|code_start|>
def __init__(self, mode):
"""Create a new mesh
A Vertex Buffer Object is filled with data from self.vertices()
A Texcoord Buffer Object is filled with data from self.texcoords()
A Normal Buffer Object is filled with data from self.normals()
... | if Mesh.bound_mesh is not None: |
Here is a snippet: <|code_start|> return True
else:
raise RuntimeError("Another mesh is already bound")
Mesh.bound_mesh = self
program = glGetIntegerv(GL_CURRENT_PROGRAM)
# select vertex buffer object
var = glGetAttribLocation(program, "vertex... | self.normal_buffer.unbind() |
Using the snippet: <|code_start|> gravitational_parameter = 1e20
def __repr__(self):
return 'X'
primary = DummyPrimary()
class TestOrbit(unittest.TestCase):
longMessage = True
def assertIsClose(self, first, second, rel_tol=1e-9, msg=None, abs_tol=0.):
ok = isclose(first, second, rel... | if a.inclination not in (0, math.pi): # gimpbal lock |
Based on the snippet: <|code_start|>
class InvalidElements(Exception):
pass
class OrbitDetermination:
def __init__(self, *args, **kwargs):
raise NotImplementedError
@classmethod
def from_semi_major_axis(
cls, primary, semi_major_axis, eccentricity,
inclination=0, longitude_o... | ): |
Given the code snippet: <|code_start|>
class MissionGUI(gspyce.simulation.SimulationGUI):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
<|code_end|>
, generate the next line using the imports in this file:
import time
import gspyce.simulation
import gspyce.textures
import gspyce... | self.rocket_mesh = gspyce.mesh.Square(1) |
Given snippet: <|code_start|>#import twistedpg
#dbpool = adbapi.ConnectionPool("twistedpg", "host=borch.frikanalen.no port=5433 user=postgres password=SECRET dbname=frikanalen") # fyll inn!
def date_to_cache_filename(date):
"""Return a schedule-pickle filename based on a datetime
Not tested"""
return loo... | cache_schedule(date, 14).addCallback(lambda x: pprint.pprint(get_schedule_by_date(date)[0])).addCallback(lambda x: reactor.stop()) |
Using the snippet: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
# csv.py doesn't do Unicode; encode temporarily as UTF-8:
csv_reader = csv.reader(utf_8_decoder(unicode_csv_data),
dialect=dialect, **kwar... | for line in unicode_csv_data: |
Here is a snippet: <|code_start|> raise RuntimeError(
"No default tenant available in this context. Specify one in "
"'DRIFT_DEFAULT_TENANT' environment variable, or use the --tenant command "
"line argument."
)
def uuid_string():
return str(uuid.uuid4()).split("... | g.client_debug_messages.append(message) |
Predict the next line for this snippet: <|code_start|>
class HTTPMethodTestCase(unittest.TestCase):
def setUp(self):
app = Flask(__name__)
self.app = app
app.config['TESTING'] = True
@app.route('/some-endpoint', methods=['PATCH'])
def some_endpoint():
return '... | self.assertEqual(resp.data.decode("ascii"), 'success') |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
log = logging.getLogger(__name__)
# defaults when making a new tier
TIER_DEFAULTS = {
"server": "<PLEASE FILL IN>",
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
impo... | "database": None, |
Given snippet: <|code_start|> # stamp the db with the latest alembic upgrade version
approot = get_app_root()
ini_path = os.path.join(approot, "alembic.ini")
alembic_cfg = Config(ini_path)
script_path = os.path.join(os.path.split(os.path.abspath(ini_path))[0], "alembic")
alembic_cfg.set_main_opti... | db_name = params["database"] |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
log = logging.getLogger(__name__)
REDIS_DB = 0 # We always use the main redis db for now
# defaults when making a new tier
TIER_DEFAULTS = {
"host": "<PLEASE FILL IN>",
<|code_end|>
. Use current file impor... | "port": 6379, |
Given snippet: <|code_start|>
Set up logging based on config dict.
"""
from __future__ import absolute_import
def get_stream_handler():
"""returns a stream handler with standard formatting for use in local development"""
stream_handler = logging.StreamHandler()
stream_formatter = logging.Formatter... | def get_clean_path_from_url(url): |
Given the following code snippet before the placeholder: <|code_start|>
Set up logging based on config dict.
"""
from __future__ import absolute_import
def get_stream_handler():
"""returns a stream handler with standard formatting for use in local development"""
stream_handler = logging.StreamHandler(... | def get_clean_path_from_url(url): |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
@click.command()
@click.option(
'--tier-name', '-t', help='Tier name.'
)
@click.option('--offline', '-o', is_flag=True, help="Run serverless-offline.")
@click.option('--preview', '-p', is_flag=True, help="Preview, do not run 'sls' comm... | @click.option('--clean', '-c', is_flag=True, help="Clean autogenerated files and folders and exit.") |
Given the code snippet: <|code_start|>#!/usr/bin/env python
@click.command()
@click.option(
'--tier-name', '-t', help='Tier name.'
)
@click.option('--offline', '-o', is_flag=True, help="Run serverless-offline.")
<|code_end|>
, generate the next line using the imports in this file:
import sys
import os
import os... | @click.option('--preview', '-p', is_flag=True, help="Preview, do not run 'sls' command.") |
Predict the next line for this snippet: <|code_start|>
log = logging.getLogger(__name__)
APP_INIT_THRESHOLD = .250 # If app creation takes longer a warning is logged.
MODULE_INIT_THRESHOLD = .050 # If module initialization takes longer a warning is logged.
<|code_end|>
with the help of current file imports:
im... | class AppRootNotFound(RuntimeError): |
Continue the code snippet: <|code_start|>from __future__ import absolute_import
JWT_VERIFY_CLAIMS = ['signature', 'exp', 'iat']
JWT_REQUIRED_CLAIMS = ['exp', 'iat', 'jti']
JWT_ALGORITHM = 'RS256'
JWT_EXPIRATION_DELTA = 60 * 60 * 24
JWT_LEEWAY = 10
# Tis a hack:
JWT_EXPIRATION_DELTA_FOR_SERVICES = 60 * 60 * 24 * 36... | bp = Blueprint('auth', 'Authentication', url_prefix='/auth', description='Authentication endpoints') |
Using the snippet: <|code_start|>JWT_EXPIRATION_DELTA_FOR_SERVICES = 60 * 60 * 24 * 365
# Implicitly trust following issuers:
TRUSTED_ISSUERS = {'drift-base'}
# list of regular expression objects matching endpoint definitions
WHITELIST_ENDPOINTS = [
r"^api-docs\.", # the marshmalloc documentation endpoint
r"... | ts = get_default_drift_config() |
Based on the snippet: <|code_start|># Implicitly trust following issuers:
TRUSTED_ISSUERS = {'drift-base'}
# list of regular expression objects matching endpoint definitions
WHITELIST_ENDPOINTS = [
r"^api-docs\.", # the marshmalloc documentation endpoint
r"^static$", # the marshmalloc documentation endpoint
... | row = public_keys.get({ |
Continue the code snippet: <|code_start|>
def drift_init_extension(app, api, **kwargs):
api.register_blueprint(bp)
api.register_blueprint(bpjwks)
endpoints.init_app(app)
# Flask Secret must be set for cookies and other secret things
# HACK WARNING: It is weirdly difficult to get a drift config at ... | def check_jwt_authorization(): |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
JWT_VERIFY_CLAIMS = ['signature', 'exp', 'iat']
JWT_REQUIRED_CLAIMS = ['exp', 'iat', 'jti']
JWT_ALGORITHM = 'RS256'
JWT_EXPIRATION_DELTA = 60 * 60 * 24
<|code_end|>
, predict the immediate next line with the help of ... | JWT_LEEWAY = 10 |
Predict the next line after this snippet: <|code_start|>MASTER_USERNAME = 'postgres'
MASTER_PASSWORD = 'postgres'
def run_migrations():
conf = get_config()
pick_tenant = context.get_x_argument(as_dictionary=True).get('tenant')
dry_run = context.get_x_argument(as_dictionary=True).get('dry-run')
for t... | context.configure( |
Based on the snippet: <|code_start|> for tenant in conf.tenants:
tenant_name = tenant['tenant_name']
secho("Tenant '{}': ".format(tenant_name), nl=False)
pginfo = tenant.get('postgres')
if not pginfo:
secho("Missing postgres resource info!", fg='red')
continue
... | else: |
Using the snippet: <|code_start|> continue
else:
raise
transaction = connection.begin()
secho("OK", fg="green")
secho("\tRunning migration...", nl=False)
context.configure(
connection=connection,
... | del app |
Given the following code snippet before the placeholder: <|code_start|>
MASTER_USERNAME = 'postgres'
MASTER_PASSWORD = 'postgres'
def run_migrations():
conf = get_config()
pick_tenant = context.get_x_argument(as_dictionary=True).get('tenant')
dry_run = context.get_x_argument(as_dictionary=True).get('dr... | secho("Missing postgres resource info!", fg='red') |
Continue the code snippet: <|code_start|> continue
else:
raise
transaction = connection.begin()
secho("OK", fg="green")
secho("\tRunning migration...", nl=False)
context.configure(
connection=connecti... | del app |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
log = logging.getLogger(__name__)
service_username = "user+pass:$SERVICE$"
service_password = "SERVICE"
local_password = "LOCAL"
AUTH_TEST_PROVIDER = 'unit_test'
<|code_end|>
. Write the next line using the current file imports:
import os
import sys
impor... | big_number = 9999999999 |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
log = logging.getLogger(__name__)
service_username = "user+pass:$SERVICE$"
service_password = "SERVICE"
local_password = "LOCAL"
AUTH_TEST_PROVIDER = 'unit_test'
big_number = 9999999999
<|code_end|>
. Write the next line using the current file imports:
... | def uuid_string(): |
Given snippet: <|code_start|>
class ProjectSerializer(serializers.Serializer):
project_name = serializers.CharField(label='Project name', max_length=50)
overlap = serializers.BooleanField(label='Allow class overlap in this project', default=False)
classes = serializers.MultipleChoiceField(choices=[])
... | def create(self, validated_data): |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
class Analysis(object):
summaries = ["max", "mean", "cumulative", "max_symmetric", "max_shortest", "max_central"]
def __init__(self, parent):
self.parent = parent
self._logger = logging.getLogger("chainconsumer")
<|code_end|>
, deter... | self._summaries = { |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
class Analysis(object):
summaries = ["max", "mean", "cumulative", "max_symmetric", "max_shortest", "max_central"]
def __init__(self, parent):
self.parent = parent
self._logger = logging.getLogger("chainconsumer"... | "max_symmetric": self.get_paramater_summary_max_symmetric, |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
class Analysis(object):
summaries = ["max", "mean", "cumulative", "max_symmetric", "max_shortest", "max_central"]
def __init__(self, parent):
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
import numpy as ... | self.parent = parent |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
class Plotter(object):
def __init__(self, parent):
self.parent = parent
self._logger = logging.getLogger("chainconsumer")
self.usetex_old = matplotlib.rcParams["text.usetex"]
<|code_end|>
, generate the next line using the imp... | self.serif_old = matplotlib.rcParams["font.family"] |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
class Plotter(object):
def __init__(self, parent):
self.parent = parent
self._logger = logging.getLogger("chainconsumer")
self.usetex_old = matplotlib.rcParams["text.usetex"]
self.serif_old = matplotlib.rcParams["font.fa... | self, |
Here is a snippet: <|code_start|>
def test_megkde_1d_basic():
# Draw from normal, fit KDE, see if sampling from kde's pdf recovers norm
np.random.seed(0)
data = np.random.normal(loc=0, scale=1.0, size=2000)
xs = np.linspace(-3, 3, 100)
ys = MegKDE(data).evaluate(xs)
cs = ys.cumsum()
<|code_end... | cs /= cs[-1] |
Given snippet: <|code_start|>def test_colors_rgb2hex_2():
c = np.array([0, 0, 0.5, 1])
colourmap = Colors()
assert colourmap.get_formatted([c])[0] == "#000080"
def test_colors_alias_works():
colourmap = Colors()
assert colourmap.get_formatted(["b"])[0] == colourmap.color_map["blue"]
def test_col... | def test_clamp3(): |
Here is a snippet: <|code_start|>
def test_extents():
xs = np.random.normal(size=1000000)
weights = np.ones(xs.shape)
low, high = get_extents(xs, weights)
<|code_end|>
. Write the next line using the current file imports:
import numpy as np
from scipy.stats import norm
from chainconsumer.helpers import g... | threshold = 0.5 |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
class Comparison(object):
def __init__(self, parent):
self.parent = parent
self._logger = logging.getLogger("chainconsumer")
<|code_end|>
, generate the next line using the imports in this file:
from scipy.interpolate import griddata... | def dic(self): |
Predict the next line for this snippet: <|code_start|> new_vocab_file, new_w2v_file, new_metadata_file, in_new_vocab, \
in_new_w2v, in_new_metadata = self.create_vocab(min_frequency,
tokenizer, downcase,
... | train_batch = self.ds.train.next_batch(100) |
Using the snippet: <|code_start|> assert_equal(len(batch.ner1[0]), 20)
assert_equal(len(batch.ner2[0]), 20)
def test_next_batch_big_with_seq_lens(self):
# batch of 128, rescaled, sequence lengths
batch = self.ds.train.next_batch(
batch_size=128,
... | name = 'test_vocab' |
Based on the snippet: <|code_start|>
class Sick(STS):
def __init__(self, train_validation_split=None, test_split=None,
use_defaults=True, name='sick'):
<|code_end|>
, predict the immediate next line with the help of imports:
from datasets.sts import STS
and context (classes, functions, sometimes... | super().__init__(subset=name) |
Continue the code snippet: <|code_start|>
class SemEval(STS):
def __init__(self, train_validation_split=None, test_split=None,
use_defaults=True, name='semEval'):
<|code_end|>
. Use current file imports:
from datasets.sts import STS
and context (classes, functions, or code) from other files:
# ... | super().__init__(subset=name) |
Given the following code snippet before the placeholder: <|code_start|> pprint (dimension)
if dimension.get('measure_type').startswith('W-'):
continue
attrs = ['name', 'label']
if 'ZI' in dimension.get('measure_type'):
attrs = ['text', 'from', 'until']
dim ... | dimensions.append(dn) |
Given snippet: <|code_start|>
dimensions.append(dn)
if dim.get('dim_measure_type').startswith('ZI-'):
mappings[dn + '.text'] = 'fact_%s.%s' % (cube_name, dn)
mappings[dn + '.from'] = 'fact_%s.%s_from' % (cube_name, dn)
mappings[dn + '.u... | def generate_model(): |
Predict the next line for this snippet: <|code_start|> cubes = []
for cube in get_cubes():
dimensions = []
measures = []
joins = []
mappings = {}
cube_name = cube.get('cube_name')
for dim in get_dimensions(cube_name):
dn = dim.get('dim_name')
... | 'dimensions': dimensions, |
Here is a snippet: <|code_start|>log = logging.getLogger(__name__)
cube_table = engine.get_table('cube')
statistic_table = engine.get_table('statistic')
dimension_table = engine.get_table('dimension')
value_table = engine.get_table('value')
reference_table = engine.get_table('reference')
def get_fact_table(cube_name... | fact_table = get_fact_table(cube.name) |
Continue the code snippet: <|code_start|> params = {}
for dim in dimensions:
name = dim.get('dim_name')
field = name.upper()
title = dim.get('dim_title_de')
if readable:
unit = dim.get('ref_unit_name')
if unit is not None:
field = '%s; %s' ... | wheres.append(vt.c.dimension_name==bindparam(name, value=name)) |
Using the snippet: <|code_start|> q = q.where(rt.c.cube_name==cube_name)
res = engine.query(q)
return list(res)
def get_all_dimensions():
return list(dimension_table)
def get_all_statistics():
return list(statistic_table)
def query_cube(cube_name, readable=True):
cube = get_cube(cube_name)
... | field = '%s; %s' % (field, unit) |
Using the snippet: <|code_start|> if not readable:
selects.append(fact_table.columns[name + "_quality"].label(field + '_QUALITY'))
selects.append(fact_table.columns[name + "_error"].label(field + '_ERROR'))
if type_ == 'time':
selects.append(fact_table.colu... | dims = [(d['dim_name'], d['ref_type']) for d in dimensions] |
Using the snippet: <|code_start|> res = engine.query(q)
return list(res)
def get_all_dimensions():
return list(dimension_table)
def get_all_statistics():
return list(statistic_table)
def query_cube(cube_name, readable=True):
cube = get_cube(cube_name)
dimensions = get_dimensions(cube_name)
... | field = '%s (%s)' % (title, field) |
Given snippet: <|code_start|>def get_dimensions(cube_name):
rt = reference_table.table.alias('ref')
dt = dimension_table.table.alias('dim')
q = rt.join(dt, rt.c.dimension_name==dt.c.name)
q = q.select(use_labels=True)
q = q.where(rt.c.cube_name==cube_name)
res = engine.query(q)
return list(r... | title = dim.get('dim_title_de') |
Given snippet: <|code_start|> for dim in dimensions:
name = dim.get('dim_name')
field = name.upper()
title = dim.get('dim_title_de')
if readable:
unit = dim.get('ref_unit_name')
if unit is not None:
field = '%s; %s' % (field, unit)
... | wheres.append(vt.c.value_id==fact_table.c[name]) |
Next line prediction: <|code_start|>
def cube_path(catalog, cube_name, ext='raw'):
return os.path.join(
app.config.get('DATA_DIRECTORY'),
catalog,
cube_name + '.' + ext
)
def exists_raw(catalog, cube_name):
<|code_end|>
. Use current file imports:
(import os
import ... | return os.path.isfile(cube_path(catalog, cube_name)) |
Next line prediction: <|code_start|>warnings.filterwarnings('ignore', 'Unicode type received non-unicode bind param value.')
warnings.filterwarnings('ignore', category=SAWarning)
app = Flask(__name__)
app.config.from_object(default_settings)
app.config.from_envvar('REGENESIS_SETTINGS', silent=True)
engine = dataset... | catalog['name'] = catalog_name |
Given the following code snippet before the placeholder: <|code_start|>
def find_denormalized():
res = {}
for cube in get_cubes():
statistic = cube.get('statistic_name')
if not statistic in res:
res[statistic] = {}
<|code_end|>
, predict the next line using imports from the current ... | cube_name = cube.get('cube_name') |
Continue the code snippet: <|code_start|>
def find_denormalized():
res = {}
for cube in get_cubes():
statistic = cube.get('statistic_name')
if not statistic in res:
res[statistic] = {}
cube_name = cube.get('cube_name')
dimensions = get_dimensions(cube_name)
#... | dimensions = [d for d in dimensions if not d['dim_measure_type'].startswith('K-REG-MM')] |
Given the code snippet: <|code_start|>@app.context_processor
def set_template_globals():
return {
'slugify': _slugify,
'API': app.config.get('API_ENDPOINT')
}
@app.template_filter()
def dimension_type_text(type_name):
return _dimension_type_text(type_name)
@app.route('/favicon.ico')
def ... | def page_contact(): |
Next line prediction: <|code_start|>#coding: utf-8
app.register_blueprint(dimension_blueprint)
app.register_blueprint(statistic_blueprint)
app.register_blueprint(catalog_blueprint)
@app.template_filter('text')
def text_filter(s):
if s is None:
return ''
if type(s) == 'Markup':
s = s.unescape... | def text_filter_wrapped(s): |
Given the following code snippet before the placeholder: <|code_start|>
@app.template_filter()
def dimension_type_text(type_name):
return _dimension_type_text(type_name)
@app.route('/favicon.ico')
def nop():
return Response(status=404)
@app.route('/api.html')
def page_api():
return render_template('api... | return render_template('index.html') |
Based on the snippet: <|code_start|>#coding: utf-8
app.register_blueprint(dimension_blueprint)
app.register_blueprint(statistic_blueprint)
app.register_blueprint(catalog_blueprint)
@app.template_filter('text')
def text_filter(s):
if s is None:
return ''
if type(s) == 'Markup':
s = s.unescape... | return Markup('<p>' + s + '</p>') |
Given snippet: <|code_start|>#coding: utf-8
app.register_blueprint(dimension_blueprint)
app.register_blueprint(statistic_blueprint)
app.register_blueprint(catalog_blueprint)
@app.template_filter('text')
def text_filter(s):
if s is None:
return ''
if type(s) == 'Markup':
s = s.unescape()
... | if s is None: |
Given the following code snippet before the placeholder: <|code_start|>#coding: utf-8
app.register_blueprint(dimension_blueprint)
app.register_blueprint(statistic_blueprint)
app.register_blueprint(catalog_blueprint)
@app.template_filter('text')
def text_filter(s):
if s is None:
return ''
if type(s) ... | return Markup('<p>' + s + '</p>') |
Next line prediction: <|code_start|>
def make_views():
for cube in get_cubes():
slug = slugify(cube.get('statistic_title_de'))
slug = slug.replace('-', '_')
slug = slug + '_' + cube.get('cube_name')
q = 'DROP VIEW IF EXISTS ' + slug
engine.query(q)
q, params = query_c... | make_views() |
Predict the next line for this snippet: <|code_start|>
def make_views():
for cube in get_cubes():
slug = slugify(cube.get('statistic_title_de'))
slug = slug.replace('-', '_')
slug = slug + '_' + cube.get('cube_name')
q = 'DROP VIEW IF EXISTS ' + slug
engine.query(q)
q... | make_views() |
Given snippet: <|code_start|>
def make_views():
for cube in get_cubes():
slug = slugify(cube.get('statistic_title_de'))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from regenesis.queries import get_cubes, query_cube
from regenesis.core import engine
from regenesis.ut... | slug = slug.replace('-', '_') |
Continue the code snippet: <|code_start|>
def make_views():
for cube in get_cubes():
slug = slugify(cube.get('statistic_title_de'))
slug = slug.replace('-', '_')
slug = slug + '_' + cube.get('cube_name')
q = 'DROP VIEW IF EXISTS ' + slug
engine.query(q)
q, params = qu... | q = 'CREATE VIEW ' + slug + ' AS ' + unicode(q) |
Continue the code snippet: <|code_start|>
blueprint = Blueprint('statistic', __name__)
ADM_RANKS = {
'gemein': 1,
'kreise': 2,
'regbez': 3,
'dland': 4,
<|code_end|>
. Use current file imports:
import re
from flask import Blueprint, render_template
from collections import defaultdict
from regenesis.co... | 'dinsg': 5 |
Here is a snippet: <|code_start|> s = s.strip()
if not len(s) > 2 or s[0] != s[0].upper():
continue
keywords.add(s)
return ', '.join(keywords)
def get_cubes(statistic_name=None):
q = cube_table.table.select()
q = q.where(cube_table.table.c.statistic_name==... | cube['stand'] = cube['provenance'].split('hat am')[-1].split('um')[0].strip() |
Given the following code snippet before the placeholder: <|code_start|> s = s.strip()
if not len(s) > 2 or s[0] != s[0].upper():
continue
keywords.add(s)
return ', '.join(keywords)
def get_cubes(statistic_name=None):
q = cube_table.table.select()
q = q.whe... | cube['stand'] = cube['provenance'].split('hat am')[-1].split('um')[0].strip() |
Next line prediction: <|code_start|> q = q.where(cube_table.table.c.statistic_name==statistic_name)
return list(engine.query(q))
@blueprint.route('/<catalog>/statistics/<slug>.<name>.html')
def view(catalog, slug, name):
catalog = get_catalog(catalog)
statistic = statistic_table.find_one(name=name)
... | commons[dim['dim_name']] = dim |
Here is a snippet: <|code_start|>
blueprint = Blueprint('statistic', __name__)
ADM_RANKS = {
'gemein': 1,
'kreise': 2,
'regbez': 3,
'dland': 4,
'dinsg': 5
}
def make_keywords(titles):
keywords = set()
for t in titles:
t = re.sub('\(.*\)', '', t)
for s in re.split('[\s\.\/]... | @blueprint.route('/<catalog>/statistics/<slug>.<name>.html') |
Using the snippet: <|code_start|>
def get_cubes(statistic_name=None):
q = cube_table.table.select()
q = q.where(cube_table.table.c.statistic_name==statistic_name)
return list(engine.query(q))
@blueprint.route('/<catalog>/statistics/<slug>.<name>.html')
def view(catalog, slug, name):
catalog = get_cata... | for dim in cube['dimensions']: |
Given the code snippet: <|code_start|>
blueprint = Blueprint('statistic', __name__)
ADM_RANKS = {
'gemein': 1,
'kreise': 2,
'regbez': 3,
'dland': 4,
'dinsg': 5
}
def make_keywords(titles):
keywords = set()
for t in titles:
t = re.sub('\(.*\)', '', t)
for s in re.split('[\s... | def get_cubes(statistic_name=None): |
Continue the code snippet: <|code_start|>
client = app.test_client()
def get_output_dir():
return os.path.join( app.root_path, '..', 'build')
#return '/Users/fl/tmp/regenesis'
def freeze_request(req_path):
print "Freezing %s..." % req_path
path = os.path.join(get_output_dir(), req_path.lstrip('/'))
... | res = client.get(req_path) |
Predict the next line after this snippet: <|code_start|>
client = app.test_client()
def get_output_dir():
return os.path.join( app.root_path, '..', 'build')
#return '/Users/fl/tmp/regenesis'
def freeze_request(req_path):
print "Freezing %s..." % req_path
path = os.path.join(get_output_dir(), req_path... | res = client.get(req_path) |
Based on the snippet: <|code_start|> if os.path.isdir(outdir):
shutil.rmtree(outdir)
shutil.copytree(app.static_folder, outdir)
freeze_request('/index.html')
freeze_request('/faq.html')
freeze_request('/api.html')
freeze_request('/contact.html')
for catalog in ['regional']:
fr... | fn = '%s-%s-%s.csv' % (slug, cube['cube_name'], text) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.