Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line for this snippet: <|code_start|>
try:
magic = magic_module.Magic(mime=True)
magic_bufsz = magic.getparam(magic_module.MAGIC_PARAM_BYTES_MAX)
except ImportError:
magic = None
magic_bufsz = None
# we limit to 250 characters as we do not want to accept arbitrarily long
# filenames.... | MAX_FILENAME_LENGTH = 250 |
Here is a snippet: <|code_start|>
try:
magic = magic_module.Magic(mime=True)
magic_bufsz = magic.getparam(magic_module.MAGIC_PARAM_BYTES_MAX)
except ImportError:
magic = None
magic_bufsz = None
# we limit to 250 characters as we do not want to accept arbitrarily long
# filenames. other than that, the... | MAX_FILENAME_LENGTH = 250 |
Predict the next line after this snippet: <|code_start|>
try:
magic = magic_module.Magic(mime=True)
magic_bufsz = magic.getparam(magic_module.MAGIC_PARAM_BYTES_MAX)
except ImportError:
magic = None
<|code_end|>
using the current file's imports:
import re
import time
import mimetypes
import magic as m... | magic_bufsz = None |
Predict the next line after this snippet: <|code_start|>
try:
magic = magic_module.Magic(mime=True)
magic_bufsz = magic.getparam(magic_module.MAGIC_PARAM_BYTES_MAX)
except ImportError:
magic = None
magic_bufsz = None
# we limit to 250 characters as we do not want to accept arbitrarily long
# filename... | _type_re = re.compile(r'[^a-zA-Z0-9/+.-]+') |
Predict the next line for this snippet: <|code_start|>
try:
magic = magic_module.Magic(mime=True)
magic_bufsz = magic.getparam(magic_module.MAGIC_PARAM_BYTES_MAX)
except ImportError:
magic = None
magic_bufsz = None
# we limit to 250 characters as we do not want to accept arbitrarily long
# filenames.... | @classmethod |
Based on the snippet: <|code_start|>
try:
magic = magic_module.Magic(mime=True)
magic_bufsz = magic.getparam(magic_module.MAGIC_PARAM_BYTES_MAX)
except ImportError:
magic = None
magic_bufsz = None
# we limit to 250 characters as we do not want to accept arbitrarily long
# filenames. other than that, ... | MAX_FILENAME_LENGTH = 250 |
Given snippet: <|code_start|>
try:
magic = magic_module.Magic(mime=True)
magic_bufsz = magic.getparam(magic_module.MAGIC_PARAM_BYTES_MAX)
except ImportError:
magic = None
magic_bufsz = None
# we limit to 250 characters as we do not want to accept arbitrarily long
# filenames. other than that, there i... | _type_re = re.compile(r'[^a-zA-Z0-9/+.-]+') |
Here is a snippet: <|code_start|>
try:
magic = magic_module.Magic(mime=True)
magic_bufsz = magic.getparam(magic_module.MAGIC_PARAM_BYTES_MAX)
except ImportError:
magic = None
<|code_end|>
. Write the next line using the current file imports:
import re
import time
import mimetypes
import magic as magic... | magic_bufsz = None |
Given the following code snippet before the placeholder: <|code_start|>
try:
magic = magic_module.Magic(mime=True)
magic_bufsz = magic.getparam(magic_module.MAGIC_PARAM_BYTES_MAX)
except ImportError:
<|code_end|>
, predict the next line using imports from the current file:
import re
import time
import mimetyp... | magic = None |
Based on the snippet: <|code_start|>
try:
magic = magic_module.Magic(mime=True)
magic_bufsz = magic.getparam(magic_module.MAGIC_PARAM_BYTES_MAX)
<|code_end|>
, predict the immediate next line with the help of imports:
import re
import time
import mimetypes
import magic as magic_module
from werkzeug.except... | except ImportError: |
Using the snippet: <|code_start|> raise
try:
need_close = True
if not item.meta[COMPLETE]:
return self.err_incomplete(item, 'Upload incomplete. Try again later.')
if item.meta[LOCKED] and not may(ADMIN):
raise Forbidden()
... | <rect x="1" y="1" width="106" height="106" fill="whitesmoke" stroke-width="2" stroke="blue" /> |
Predict the next line after this snippet: <|code_start|>
try:
need_close = True
if not item.meta[COMPLETE]:
return self.err_incomplete(item, 'Upload incomplete. Try again later.')
if item.meta[LOCKED] and not may(ADMIN):
raise Forbidden()
... | <line x1="1" y1="1" x2="106" y2="106" stroke="blue" stroke-width="2" /> |
Predict the next line after this snippet: <|code_start|> dispo = self.content_disposition
if dispo != 'attachment':
# no simple download, so we must be careful about XSS
if ct.startswith("text/"):
ct = 'text/plain' # only send simple plain text
ret = Resp... | raise Forbidden() |
Next line prediction: <|code_start|> ret = Response(stream_with_context(self.stream(item, 0, item.data.size)))
ret.headers['Content-Disposition'] = '{}; filename="{}"'.format(
dispo, item.meta[FILENAME])
ret.headers['Content-Length'] = item.meta[SIZE]
ret.headers['Content-Type... | if need_close: |
Given the following code snippet before the placeholder: <|code_start|>
if delete_if_lifetime_over(item, name):
raise NotFound()
need_close = False
finally:
if need_close:
item.close()
return self.response(item, name)
class InlineVie... | if PIL is None: |
Given snippet: <|code_start|> def response(self, item, name):
if PIL is None:
# looks like PIL / Pillow is not available
return b'', 501 # not implemented
sz = item.meta[SIZE]
fn = item.meta[FILENAME]
ct = item.meta[TYPE]
if not ct.startswith("image/"... | ret.headers['Content-Type'] = 'image/%s' % self.thumbnail_type |
Using the snippet: <|code_start|>
def get(self, name):
if not may(READ):
raise Forbidden()
try:
item = current_app.storage.openwrite(name)
except OSError as e:
if e.errno == errno.ENOENT:
raise NotFound()
raise
try:
... | content_disposition = 'inline' # to trigger viewing in browser, for some types |
Given snippet: <|code_start|> if ct.startswith("text/"):
ct = 'text/plain' # only send simple plain text
ret = Response(stream_with_context(self.stream(item, 0, item.data.size)))
ret.headers['Content-Disposition'] = '{}; filename="{}"'.format(
dispo, item.meta[FI... | raise NotFound() |
Given the following code snippet before the placeholder: <|code_start|> item = current_app.storage.openwrite(name)
except OSError as e:
if e.errno == errno.ENOENT:
raise NotFound()
raise
try:
need_close = True
if not item.meta[C... | thumbnail_type = 'jpeg' # png, jpeg |
Predict the next line after this snippet: <|code_start|>
class ModifyView(MethodView):
def error(self, item, error):
return render_template('error.html', heading=item.meta[FILENAME], body=error), 409
def response(self, name):
return redirect_next_referrer('bepasty.display', name=name)
d... | def post(self, name): |
Predict the next line after this snippet: <|code_start|>
class ModifyView(MethodView):
def error(self, item, error):
return render_template('error.html', heading=item.meta[FILENAME], body=error), 409
def response(self, name):
return redirect_next_referrer('bepasty.display', name=name)
d... | error = 'Upload incomplete. Try again later.' |
Continue the code snippet: <|code_start|>
class ModifyView(MethodView):
def error(self, item, error):
return render_template('error.html', heading=item.meta[FILENAME], body=error), 409
def response(self, name):
return redirect_next_referrer('bepasty.display', name=name)
def get_params(s... | } |
Predict the next line after this snippet: <|code_start|>
class ModifyView(MethodView):
def error(self, item, error):
return render_template('error.html', heading=item.meta[FILENAME], body=error), 409
def response(self, name):
return redirect_next_referrer('bepasty.display', name=name)
d... | with current_app.storage.openwrite(name) as item: |
Continue the code snippet: <|code_start|>
class ModifyView(MethodView):
def error(self, item, error):
return render_template('error.html', heading=item.meta[FILENAME], body=error), 409
def response(self, name):
return redirect_next_referrer('bepasty.display', name=name)
def get_params(s... | def post(self, name): |
Next line prediction: <|code_start|>
def get_maxlife(data, underscore):
unit_key = 'maxlife_unit' if underscore else 'maxlife-unit'
unit_default = 'MONTHS'
unit = data.get(unit_key, unit_default).upper()
value_key = 'maxlife_value' if underscore else 'maxlife-value'
value_default = '1'
try:
... | try: |
Predict the next line after this snippet: <|code_start|>
def get_maxlife(data, underscore):
unit_key = 'maxlife_unit' if underscore else 'maxlife-unit'
unit_default = 'MONTHS'
<|code_end|>
using the current file's imports:
import time
from flask import current_app
from werkzeug.exceptions import BadRequest
... | unit = data.get(unit_key, unit_default).upper() |
Given snippet: <|code_start|>
sensor_to_node = Table(
'sensor__sensor_to_node',
postgres_base.metadata,
Column('sensor', String, ForeignKey('sensor__sensor_metadata.name')),
Column('network', String),
Column('node', String),
ForeignKeyConstraint(
['network', 'node'],
['sensor__... | Column('network', String, ForeignKey('sensor__network_metadata.name')) |
Continue the code snippet: <|code_start|>feature_to_network = Table(
'sensor__feature_to_network',
postgres_base.metadata,
Column('feature', String, ForeignKey('sensor__feature_metadata.name')),
Column('network', String, ForeignKey('sensor__network_metadata.name'))
)
def knn(lng, lat, k, network, sens... | location, |
Continue the code snippet: <|code_start|>
sensor_to_node = Table(
'sensor__sensor_to_node',
postgres_base.metadata,
Column('sensor', String, ForeignKey('sensor__sensor_metadata.name')),
Column('network', String),
Column('node', String),
ForeignKeyConstraint(
<|code_end|>
. Use current file imp... | ['network', 'node'], |
Given the following code snippet before the placeholder: <|code_start|>
sensor_to_node = Table(
'sensor__sensor_to_node',
postgres_base.metadata,
Column('sensor', String, ForeignKey('sensor__sensor_metadata.name')),
Column('network', String),
Column('node', String),
ForeignKeyConstraint(
... | feature_to_network = Table( |
Using the snippet: <|code_start|># Returns 10 rows.
FLU_FILTER_SIMPLE2 = '{"op": "eq", "col": "day", "val": "Wednesday"}'
# Returns 1 row.
FLU_FILTER_COMPOUND_AND = FLU_BASE + '{"op": "and", "val": [' + \
FLU_FILTER_SIMPLE + ', ' + \
FLU_FILTER_SIMPLE2 + ']}'
# Return... | def get_loop_rect(): |
Given the code snippet: <|code_start|>
class ShapeETL:
def __init__(self, meta, source_path=None):
self.source_path = source_path
self.table_name = meta.dataset_name
self.source_url = meta.source_url
self.meta = meta
def add(self):
staging_name = 'staging_{}'.format(s... | with zipfile.ZipFile(handle) as shapefile_zip: |
Next line prediction: <|code_start|>
class ShapeETL:
def __init__(self, meta, source_path=None):
self.source_path = source_path
self.table_name = meta.dataset_name
self.source_url = meta.source_url
self.meta = meta
def add(self):
staging_name = 'staging_{}'.format(sel... | try: |
Given the code snippet: <|code_start|>
def get_size_in_degrees(meters, latitude):
earth_circumference = 40041000.0 # meters, average circumference
degrees_per_meter = 360.0 / earth_circumference
degrees_at_equator = meters * degrees_per_meter
latitude_correction = 1.0 / math.cos(latitude * (math.p... | degrees_y = degrees_at_equator |
Next line prediction: <|code_start|>
def get_size_in_degrees(meters, latitude):
earth_circumference = 40041000.0 # meters, average circumference
degrees_per_meter = 360.0 / earth_circumference
degrees_at_equator = meters * degrees_per_meter
latitude_correction = 1.0 / math.cos(latitude * (math.pi ... | degrees_y = degrees_at_equator |
Given snippet: <|code_start|>
def get_size_in_degrees(meters, latitude):
earth_circumference = 40041000.0 # meters, average circumference
degrees_per_meter = 360.0 / earth_circumference
degrees_at_equator = meters * degrees_per_meter
latitude_correction = 1.0 / math.cos(latitude * (math.pi / 180.0... | degrees_x = degrees_at_equator * latitude_correction |
Continue the code snippet: <|code_start|>
def get_size_in_degrees(meters, latitude):
earth_circumference = 40041000.0 # meters, average circumference
degrees_per_meter = 360.0 / earth_circumference
degrees_at_equator = meters * degrees_per_meter
latitude_correction = 1.0 / math.cos(latitude * (mat... | def infer_csv_columns(inp): |
Next line prediction: <|code_start|>
def get_size_in_degrees(meters, latitude):
earth_circumference = 40041000.0 # meters, average circumference
degrees_per_meter = 360.0 / earth_circumference
degrees_at_equator = meters * degrees_per_meter
latitude_correction = 1.0 / math.cos(latitude * (math.pi ... | ColumnInfo = namedtuple('ColumnInfo', 'name type_ has_nulls') |
Predict the next line for this snippet: <|code_start|>
bcrypt = Bcrypt()
class ShapeMetadata(postgres_base):
__tablename__ = 'meta_shape'
dataset_name = Column(String, primary_key=True)
human_name = Column(String, nullable=False)
source_url = Column(String)
view_url = Column(String)
date_ad... | contributor_email = Column(String) |
Continue the code snippet: <|code_start|>
dataset_name = Column(String, primary_key=True)
human_name = Column(String, nullable=False)
source_url = Column(String)
view_url = Column(String)
date_added = Column(Date, nullable=False)
# Organization that published this dataset
attribution = Colu... | @classmethod |
Continue the code snippet: <|code_start|> finally:
# Extract every column's info.
fields_list = []
for col in table.columns:
if not isinstance(col.type, NullType):
# Don't report our internal-use columns
... | FROM "{dataset_name}" as g |
Given the code snippet: <|code_start|>
def make_error(msg, status_code):
resp = {
'meta': {
<|code_end|>
, generate the next line using the imports in this file:
import json
from flask import make_response, request
from plenario.api.common import unknown_object_json_handler
and context (functions, clas... | }, |
Predict the next line after this snippet: <|code_start|># TODO: refactor this whole massive kludge into an `auth` package -- too much going on in here
auth = Blueprint('auth', __name__)
login_manager = LoginManager()
csrf = CSRFProtect()
<|code_end|>
using the current file's imports:
import json
from functools... | def check_admin_status(): |
Given snippet: <|code_start|># TODO: refactor this whole massive kludge into an `auth` package -- too much going on in here
auth = Blueprint('auth', __name__)
login_manager = LoginManager()
csrf = CSRFProtect()
def check_admin_status():
<|code_end|>
, continue by predicting the next line. Consider current file i... | def decorator(f): |
Given the following code snippet before the placeholder: <|code_start|>
session = postgres_session()
objects = []
def redshift_table_exists(table_name):
"""Make an inexpensive query to the database. It the table does not exist,
the query will cause a ProgrammingError.
:param table_name: (string) table... | name='foo', |
Predict the next line after this snippet: <|code_start|>
session = postgres_session()
objects = []
def redshift_table_exists(table_name):
"""Make an inexpensive query to the database. It the table does not exist,
the query will cause a ProgrammingError.
:param table_name: (string) table name
:retu... | except ProgrammingError: |
Predict the next line for this snippet: <|code_start|>
session = postgres_session()
objects = []
def redshift_table_exists(table_name):
"""Make an inexpensive query to the database. It the table does not exist,
the query will cause a ProgrammingError.
:param table_name: (string) table name
:return... | name='foo', |
Given the code snippet: <|code_start|>
session = postgres_session()
objects = []
def redshift_table_exists(table_name):
"""Make an inexpensive query to the database. It the table does not exist,
the query will cause a ProgrammingError.
:param table_name: (string) table name
:returns (bool) true if... | try: |
Given the following code snippet before the placeholder: <|code_start|>
class ShapefileError(Exception):
def __init__(self, message):
Exception.__init__(self, message)
<|code_end|>
, predict the next line using imports from the current file:
import os
import shutil
import tempfile
from plenario.utils.ogr... | self.message = message |
Using the snippet: <|code_start|>
class ShapefileError(Exception):
def __init__(self, message):
Exception.__init__(self, message)
self.message = message
<|code_end|>
, determine the next line of code. You have imports:
import os
import shutil
import tempfile
from plenario.utils.ogr2ogr import O... | def import_shapefile(shapefile_zip, table_name): |
Next line prediction: <|code_start|> extend_existing=True
)
stations_table = Table(
'weather_stations',
postgres_base.metadata,
autoload=True,
autoload_with=engine,
extend_existing=True
)
valid_query, query_clauses, resp, status_code = make_query(weather_... | base_query = base_query.order_by( |
Given the following code snippet before the placeholder: <|code_start|>
stations_table = Table(
'weather_stations',
postgres_base.metadata,
autoload=True,
autoload_with=engine,
extend_existing=True
)
valid_query, query_clauses, resp, status_code = make_query(weather_... | ) |
Given snippet: <|code_start|>
for clause in query_clauses:
print(('weather_stations(): filtering on clause', clause))
base_query = base_query.filter(clause)
values = [r for r in base_query.all()]
fieldnames = [f for f in list(stations_table.columns.keys())]
for ... | postgres_base.metadata, |
Given snippet: <|code_start|>
valid_query, query_clauses, resp, status_code = make_query(weather_table,
raw_query_params)
if valid_query:
resp['meta']['status'] = 'ok'
base_query = postgres_session.query(weather_table, stations_tabl... | weather_fields = list(weather_table.columns.keys()) |
Given snippet: <|code_start|> except AttributeError:
base_query = base_query.order_by(
getattr(weather_table.c, 'datetime').desc()
)
base_query = base_query.limit(RESPONSE_LIMIT)
if raw_query_params.get('offset'):
offset = raw_query_params['off... | 'observations': weather_data[station_id], |
Here is a snippet: <|code_start|> stations_table = Table(
'weather_stations',
postgres_base.metadata,
autoload=True,
autoload_with=engine,
extend_existing=True
)
valid_query, query_clauses, resp, status_code = make_query(stations_table, raw_query_params)
if valid_... | status_code |
Predict the next line for this snippet: <|code_start|> values = [r for r in base_query.all()]
weather_fields = list(weather_table.columns.keys())
station_fields = list(stations_table.columns.keys())
weather_data = {}
station_data = {}
for value in values:
wd =... | resp.headers['Content-Type'] = 'application/json' |
Here is a snippet: <|code_start|> )
base_query = base_query.limit(RESPONSE_LIMIT)
if raw_query_params.get('offset'):
offset = raw_query_params['offset']
base_query = base_query.offset(int(offset))
values = [r for r in base_query.all()]
weather_fields ... | resp['meta']['total'] = sum([len(r['observations']) for r in resp['objects']]) |
Based on the snippet: <|code_start|>
@cache.cached(timeout=CACHE_TIMEOUT, key_prefix=make_cache_key)
@crossdomain(origin='*')
def weather_stations():
<|code_end|>
, predict the immediate next line with the help of imports:
import json
import shapely.geometry
import shapely.wkb
import sqlalchemy as sa
from flask imp... | raw_query_params = request.args.copy() |
Given the following code snippet before the placeholder: <|code_start|>
logger = getLogger(__name__)
postgres_engine = create_engine(DATABASE_CONN)
postgres_session = scoped_session(sessionmaker(bind=postgres_engine))
postgres_base = declarative_base(bind=postgres_engine)
postgres_base.query = postgres_session.que... | def create_database(bind: Engine, database: str) -> None: |
Predict the next line for this snippet: <|code_start|>
logger = getLogger(__name__)
postgres_engine = create_engine(DATABASE_CONN)
postgres_session = scoped_session(sessionmaker(bind=postgres_engine))
postgres_base = declarative_base(bind=postgres_engine)
postgres_base.query = postgres_session.query_property()
re... | redshift_base = declarative_base(bind=redshift_engine) |
Predict the next line after this snippet: <|code_start|>
def test_hopeless_url(self):
self.assertRaises(RuntimeError, process_suggestion,
'https://www.google.com/')
class SubmitCSVTests(unittest.TestCase):
def test_socrata_url(self):
sub = process_suggestion('https://... | def test_non_socrata_url(self): |
Given the following code snippet before the placeholder: <|code_start|>
# from http://stackoverflow.com/questions/7490660/converting-wind-direction-in-angles-to-text-words
def degToCardinal(num):
val = int((num / 22.5) + .5)
arr = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W... | return arr[(val % 16)] |
Using the snippet: <|code_start|>
# from http://stackoverflow.com/questions/7490660/converting-wind-direction-in-angles-to-text-words
def degToCardinal(num):
val = int((num / 22.5) + .5)
arr = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"]
return arr[... | def __init__(self, message): |
Given snippet: <|code_start|>
# from http://stackoverflow.com/questions/7490660/converting-wind-direction-in-angles-to-text-words
def degToCardinal(num):
val = int((num / 22.5) + .5)
arr = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"]
return arr[(val... | def __init__(self, message): |
Here is a snippet: <|code_start|> # limited to 50 chars elsewhere
dataset_name = Column(String(100), nullable=False)
human_name = Column(String(255), nullable=False)
description = Column(Text)
source_url = Column(String(255))
source_url_hash = Column(String(32), primary_key=True)
view_url = C... | approved_status=False, update_freq='yearly', |
Using the snippet: <|code_start|> description = Column(Text)
source_url = Column(String(255))
source_url_hash = Column(String(32), primary_key=True)
view_url = Column(String(255))
attribution = Column(String(255))
# Spatial and temporal boundaries of observations in this dataset
obs_from = Co... | column_names=None, |
Given the code snippet: <|code_start|>
bcrypt = Bcrypt()
class MetaTable(postgres_base):
__tablename__ = 'meta_master'
# limited to 50 chars elsewhere
<|code_end|>
, generate the next line using the imports in this file:
import json
import sqlalchemy as sa
from collections import namedtuple
from datetime i... | dataset_name = Column(String(100), nullable=False) |
Based on the snippet: <|code_start|> __tablename__ = 'meta_master'
# limited to 50 chars elsewhere
dataset_name = Column(String(100), nullable=False)
human_name = Column(String(255), nullable=False)
description = Column(Text)
source_url = Column(String(255))
source_url_hash = Column(String(32... | def __init__(self, url, human_name, observed_date, |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
"""Script for migrating the contents of celery_taskmeta into etl_task."""
engine = create_engine(DATABASE_CONN)
def main():
rp = engine.execute("""
<|code_end|>
, predict the next line using imports from the current... | select * from meta_shape as ms natural join celery_taskmeta as ct |
Next line prediction: <|code_start|> name="sensor_03",
observed_properties={"temperature": "temperature.temperature"}
)
node = NodeMeta(
id="test_node",
address='Nichols Bridgeway, Chicago, IL 60601, USA',
sensor_network="test_network",
... | observed_properties=[{"type": "float", "name": "temperature"}], |
Here is a snippet: <|code_start|>
class Fixtures:
def _run_with_connection(self, query):
conn = self.engine.connect()
try:
print(query)
conn.execute("commit")
conn.execute(query)
except ProgrammingError as err:
print(str(err))
final... | "\"meta_id\" DOUBLE PRECISION NOT NULL," |
Using the snippet: <|code_start|> print(query)
conn.execute("commit")
conn.execute(query)
except ProgrammingError as err:
print(str(err))
finally:
conn.close()
def _create_foi_table(self, table_schema):
"""A postgres friendly versio... | def __init__(self): |
Using the snippet: <|code_start|> name="sensor_03",
observed_properties={"temperature": "temperature.temperature"}
)
node = NodeMeta(
id="test_node",
address='Nichols Bridgeway, Chicago, IL 60601, USA',
sensor_network="test_network",
... | observed_properties=[{"type": "float", "name": "temperature"}], |
Based on the snippet: <|code_start|> node = NodeMeta(
id="test_node",
address='Nichols Bridgeway, Chicago, IL 60601, USA',
sensor_network="test_network",
sensors=[sensor_01, sensor_02, sensor_03],
location="0101000020E6100000A4A7C821E2E755C07C48F8DEDFF0... | feature_02 = FeatureMeta( |
Here is a snippet: <|code_start|>
postgres_connection_arg = 'PG:host={} user={} port={} dbname={} password={}'.format(
DB_HOST, DB_USER, DB_PORT, DB_NAME, DB_PASSWORD)
class OgrError(Exception):
def __init__(self, message):
Exception.__init__(self, message)
<|code_end|>
. Write the next line using t... | self.message = message |
Based on the snippet: <|code_start|>
def validate_sensor_properties(observed_properties):
if not observed_properties:
raise ValidationError('No observed properties were provided!')
features = defaultdict(list)
for feature in postgres_session.query(FeatureMeta).all():
for property_dict in... | def assert_json_enclosed_in_brackets(json_list): |
Based on the snippet: <|code_start|>
def validate_sensor_properties(observed_properties):
if not observed_properties:
raise ValidationError('No observed properties were provided!')
features = defaultdict(list)
for feature in postgres_session.query(FeatureMeta).all():
for property_dict in... | feat, prop = feature_property.split('.') |
Given snippet: <|code_start|> return wind_speed_int, wind_direction_int, wind_direction_cardinal, wind_gust_int
def getPressure(obs):
pressure_in = None
if (obs.press):
pressure_in = obs.press.value(units="IN")
return pressure_in
def getPressureSeaLevel(obs):
pressure_in = None
if (ob... | precip_24hr = obs.precip_24hr.value() |
Predict the next line after this snippet: <|code_start|>
logger = logging.getLogger(__name__)
def create_foi_table(foi_name, properties):
"""Create a new foi table
:param foi_name: name of feature
:param properties: list of {'name': name, 'type': type} dictionaries
"""
template = """
... | {props}, |
Continue the code snippet: <|code_start|> assert ub.modpath_to_modname(sub2_main, hide_main=True, hide_init=False) == '_tmproot927.sub1.sub2'
# Non-existent / invalid modules should always be None
for a, b in it.product([True, False], [True, False]):
with pytest.raise... | pytest ubelt/tests/test_import.py |
Using the snippet: <|code_start|>
Example:
>>> from ubelt.util_path import * # NOQA
>>> import ubelt as ub
>>> assert normpath(ub.expandpath('~/foo')) == join(ub.userhome(), 'foo')
>>> assert ub.expandpath('foo') == 'foo'
"""
path = expanduser(path)
path = expandvars(pat... | :func:`ubelt.Path.ensuredir` |
Here is a snippet: <|code_start|> print(' * exc_info = {!r}'.format(exc_info))
print('[test] Create an authorized overwrite link (back to happy)')
ub.symlink(happy_fpath, happy_flink, verbose=verbose, overwrite=True)
def _force_junction(func):
@wraps(func)
def _wrap(*args):
if ... | pytest ubelt/tests/test_links.py -s |
Continue the code snippet: <|code_start|>r"""
Wrappers around hashlib functions to generate hash signatures for common data.
The hashes are deterministic across python versions and operating systems.
This is verified by CI testing on Windows, Linux, Python with 2.7, 3.4, and
greater, and on 32 and 64 bit versions.
<|... | Use Case #1: You have data that you want to hash. If we assume the data is in |
Based on the snippet: <|code_start|> def __init__(self, dataset_path, output_path='./working', file_types=['avi'], face_locations_path=None):
super(MaskAttack, self).__init__(dataset_path, output_path)
self.file_types = file_types
self.face_locations_path = face_locations_path
@staticme... | rand_idxs_pos = rstate.permutation(all_idxs[pos_idxs]) |
Continue the code snippet: <|code_start|> if 'H' in name_video:
video_id = 'H' + name_video.split("_")[1]
else:
if int(name_video) % 2 == 0:
idx = np.where(np.arange(2, 9, 2) == int(name_video))[0]
idx... | test_idxs_3 += [img_idx] |
Predict the next line after this snippet: <|code_start|>
@property
def output_path(self):
return self.__output_path
@output_path.setter
def output_path(self, path):
path = os.path.abspath(path)
self.__output_path = path
@property
def codebook_selection(self):
re... | self.__coding_poling = value |
Given the code snippet: <|code_start|> #params = self.params
print 'doing xy slice'
data = self.data
pixels = self.pixel_mask
# zero out any pixels in the sum that have zero in the pixel count:
data[pixels == 0] = 0
normalization_matrix = ones(data.shape)
... | new_min = y_pixel_max |
Here is a snippet: <|code_start|> self.results = None
self.corrected_results = None
self.anglexvals = None
self.anglezvals = None
return
def BAres(self):
self.results = approximations.BAres(self.feature,self.space,
... | need. |
Predict the next line for this snippet: <|code_start|># The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Off-specular Modeling Software'
copyright = u'2010, Christopher Metting'
# The version info for the project you're documenting, acts as replacement for
... | exclude_trees = ['_build']
|
Given the following code snippet before the placeholder: <|code_start|> 0.8498 -6.478861916;
0.8741 -6.159517513;
0.8061 -6.835647144;
0.846 -6.53165267;
0.8751 -6.224098421;
0.8856 -5.910094889;
0.8919 -5.598599459;
... | 0.8963 -4.811352704; |
Using the snippet: <|code_start|>
ITER = 30
img = loadimg('/home/siqi/ncidata/rivuletpy/tests/data/test-crop.tif')
bimg = (img > 0).astype('int')
dt = skfmm.distance(bimg, dx=1)
sdt = ssm(dt, anisotropic=True, iterations=ITER)
try:
except ImportError:
s_seg = s > filters.threshold_otsu(s)
plt.figure()
plt.title('DT... | plt.title('SSM-DT') |
Here is a snippet: <|code_start|>
class SWC(object):
def __init__(self, soma=None):
self._data = np.zeros((1, 8))
if soma:
self._data[0, :] = np.asarray([0, 1, soma.centroid[0], soma.centroid[
1], soma.centroid[2], soma.radius, -1, 1])
de... | np.vstack((self._data, swc_nodes)) |
Based on the snippet: <|code_start|>
sys.path.append( ".." )
print cvideo.init()
img = np.zeros([720,1280,3], dtype=np.uint8)
missingIFrame = True
filename = sys.argv[1]
pave = PaVE()
pave.append( open( filename, "rb" ).read() )
header,payload = pave.extract()
while len(header) > 0:
w,h = frameEncodedWidth(header... | cv2.imshow('image', img) |
Predict the next line after this snippet: <|code_start|>
sys.path.append( ".." )
print cvideo.init()
img = np.zeros([720,1280,3], dtype=np.uint8)
missingIFrame = True
filename = sys.argv[1]
pave = PaVE()
<|code_end|>
using the current file's imports:
import cvideo
import cv2
import numpy as np
import sys
from pav... | pave.append( open( filename, "rb" ).read() ) |
Next line prediction: <|code_start|>
class CoreTestCase(TestCase):
fixtures = ['test.json']
def setUp(self):
self.factory = RequestFactory()
<|code_end|>
. Use current file imports:
(from django.contrib.auth.models import AnonymousUser
from django.core.urlresolvers import reverse
from django.test.c... | def test_loginrequired_mixin(self): |
Predict the next line for this snippet: <|code_start|>
class CoreTestCase(TestCase):
fixtures = ['test.json']
def setUp(self):
self.factory = RequestFactory()
def test_loginrequired_mixin(self):
request = self.factory.get(reverse('app', args=[2, ]))
request.user = AnonymousUser()... | mixin.kwargs = {'website_id': 1} |
Based on the snippet: <|code_start|>
urlpatterns = patterns('',
url(r'^login/$', LoginView.as_view(), name='login'),
url(r'^logout/$', LogoutView.as_view(), name='logout'),
url(r'^account/$', AccountSettingsView.as_view(), name='settings'),
url(r'^created/$', WebsiteCreatedView.as_view(), name='website_cre... | ) |
Predict the next line after this snippet: <|code_start|>
urlpatterns = patterns('',
url(r'^login/$', LoginView.as_view(), name='login'),
url(r'^logout/$', LogoutView.as_view(), name='logout'),
url(r'^account/$', AccountSettingsView.as_view(), name='settings'),
url(r'^created/$', WebsiteCreatedView.as_view(... | ) |
Using the snippet: <|code_start|>
urlpatterns = patterns('',
url(r'^login/$', LoginView.as_view(), name='login'),
url(r'^logout/$', LogoutView.as_view(), name='logout'),
url(r'^account/$', AccountSettingsView.as_view(), name='settings'),
url(r'^created/$', WebsiteCreatedView.as_view(), name='website_create... | ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.