Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the code snippet: <|code_start|># Copyright © 2014 Tim Pederick.
#
# This file is part of Pegl.
#
# Pegl is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your opt... | class OpenCLSync(FenceSync): |
Here is a snippet: <|code_start|>
Note that, because it puts an OpenCL event handle into an attribute list
where (especially on 64-bit systems) it is not guaranteed to fit, this
extension is deprecated and replaced by khr_clevent2.
http://www.khronos.org/registry/egl/extensions/KHR/EGL_KHR_cl_event.txt
'''
# Copyrigh... | SyncAttribs.extend('CL_EVENT_HANDLE', 0x309C, c_int, None) |
Next line prediction: <|code_start|>http://www.khronos.org/registry/egl/extensions/EXT/EGL_EXT_create_context_robustness.txt
'''
# Copyright © 2012-13 Tim Pederick.
#
# This file is part of Pegl.
#
# Pegl is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as ... | ContextAttribs.extend('OPENGL_ROBUST_ACCESS', 0x30BF, bool, False) |
Next line prediction: <|code_start|>
@csrf_exempt
def store(request):
"""
Main API method storing pushed data.
TODO: Needs a lot of work, security, validation etc.
"""
if request.method == 'POST':
data = request.raw_post_data
data = json.loads(base64.b64decode(data).decode('zlib'))... | metric = Metric.objects.get(api_key=data['api_key']) |
Given the code snippet: <|code_start|>
@csrf_exempt
def store(request):
"""
Main API method storing pushed data.
TODO: Needs a lot of work, security, validation etc.
"""
if request.method == 'POST':
data = request.raw_post_data
data = json.loads(base64.b64decode(data).decode('zlib'... | sample_obj, created = Sample.objects.get_or_create( |
Using the snippet: <|code_start|>
register = template.Library()
@register.inclusion_tag('holodeck/inclusion_tags/dashboard_dropdown.html', takes_context=True)
def dashboard_dropdown(context):
context.update({
<|code_end|>
, determine the next line of code. You have imports:
from copy import copy
from django imp... | 'dashboard_list': Dashboard.objects.all().order_by('name') |
Predict the next line for this snippet: <|code_start|> 'dashboard_list': Dashboard.objects.all().order_by('name')
})
return context
@register.inclusion_tag('holodeck/inclusion_tags/render_metric.html', takes_context=True)
def render_metric(context, metric, minimal=False):
context = copy(context)
... | chart_context = LineChart().get_context(sampled_metric) |
Predict the next line for this snippet: <|code_start|> return context
@register.inclusion_tag('holodeck/inclusion_tags/render_metric.html', takes_context=True)
def render_metric(context, metric, minimal=False):
context = copy(context)
return {'result': metric.render(context, minimal)}
@register.inclusion... | deviation_context = SampleDeviation().get_context(sampled_metric) |
Next line prediction: <|code_start|>
class Dashboard(models.Model):
name = models.CharField(max_length=255)
owner = models.ForeignKey(User, null=True)
share_key = models.CharField(
max_length=32,
unique=True,
blank=True,
null=True
)
def save(self, *args, **kwargs):
... | choices=get_widget_type_choices() |
Given the following code snippet before the placeholder: <|code_start|> blank=True,
null=True,
)
dashboard = models.ForeignKey('holodeck.Dashboard')
widget_type = models.CharField(
max_length=64,
choices=get_widget_type_choices()
)
api_key = models.CharField(
m... | return load_class_by_string(self.widget_type)() |
Based on the snippet: <|code_start|>
admin.autodiscover()
urlpatterns = patterns('',
# Accounts.
url(r'^login/$', views.login, name='holodeck-login'),
url(r'^logout/$', views.logout, name='holodeck-logout'),
# Dashboards.
url(r'^dashboards/new/$', views.new_dashboard, name='holodeck-new-dashboard'... | url(r'^api/store/$', api.store, name='holodeck-api-store'), |
Given snippet: <|code_start|>
def load_class_by_string(class_path):
"""
Returns a class when given its full name in
Python dot notation, including modules.
"""
parts = class_path.split('.')
module_name = '.'.join(parts[:-1])
class_name = parts[-1]
__import__(module_name)
mod = sys.m... | for name, member in inspect.getmembers(widgets, inspect.isclass): |
Given the code snippet: <|code_start|>
class NewDashboardForm(forms.ModelForm):
name = forms.CharField(
max_length=200,
widget=forms.TextInput(attrs={
'placeholder': _('e.g. My Dashboard Name')
})
)
class Meta:
fields = ('name', 'owner')
<|code_end|>
, generate ... | model = Dashboard |
Continue the code snippet: <|code_start|>
class NewDashboardForm(forms.ModelForm):
name = forms.CharField(
max_length=200,
widget=forms.TextInput(attrs={
'placeholder': _('e.g. My Dashboard Name')
})
)
class Meta:
fields = ('name', 'owner')
model = Dashbo... | model = Metric |
Predict the next line for this snippet: <|code_start|>
def login_required(func):
@wraps(func)
def wrapped(request, *args, **kwargs):
if not request.user.is_authenticated():
request.session['_next'] = request.build_absolute_uri()
return HttpResponseRedirect(reverse('holodeck-logi... | Dashboard.objects.get(id=dashboard_id, share_key=share_key) |
Here is a snippet: <|code_start|>
SKIP_REASON_PYTHON_3 = 'MySQLdb is not compatible with Python 3'
SKIP_REASON_CONNECTION = 'MySQL is not running or cannot connect'
MYSQL_CONNECTION_STRING = 'mysql://root@127.0.0.1/test'
@pytest.fixture
def session():
Session = sessionmaker()
engine = create_engine(MYSQL_... | mysqldb_hooks.install_patches() |
Given snippet: <|code_start|> yield
finally:
mysqldb_hooks.reset_patches()
def is_mysql_running():
try:
with MySQLdb.connect(host='127.0.0.1', user='root'):
pass
return True
except:
return False
def assert_span(span, operation, parent=None):
assert ... | with span_in_context(root_span): |
Using the snippet: <|code_start|>
SKIP_REASON_PYTHON_3 = 'MySQLdb is not compatible with Python 3'
SKIP_REASON_CONNECTION = 'MySQL is not running or cannot connect'
MYSQL_CONNECTION_STRING = 'mysql://root@127.0.0.1/test'
@pytest.fixture
def session():
Session = sessionmaker()
engine = create_engine(MYSQL_... | metadata.create_all(engine) |
Given snippet: <|code_start|> finally:
mysqldb_hooks.reset_patches()
def is_mysql_running():
try:
with MySQLdb.connect(host='127.0.0.1', user='root'):
pass
return True
except:
return False
def assert_span(span, operation, parent=None):
assert span.operation... | user = User(name='user', fullname='User', password='password') |
Next line prediction: <|code_start|> try:
dynamodb.Table('users').delete()
except ClientError as error:
# you can not just use ResourceNotFoundException class
# to catch an error since it doesn't exist until it's raised
if error.__class__.__name__ != 'ResourceNotFoundException':
... | boto3_hooks.install_patches() |
Predict the next line for this snippet: <|code_start|>
@pytest.fixture
def session():
Session = sessionmaker()
engine = create_engine("sqlite://")
Session.configure(bind=engine)
metadata.create_all(engine)
try:
yield Session()
except:
pass
@pytest.fixture(autouse=True, scope=... | sqlalchemy_hooks.install_patches() |
Predict the next line for this snippet: <|code_start|>
@pytest.fixture
def session():
Session = sessionmaker()
engine = create_engine("sqlite://")
Session.configure(bind=engine)
<|code_end|>
with the help of current file imports:
import pytest
import sqlalchemy.engine.url
from opentracing.ext import tag... | metadata.create_all(engine) |
Continue the code snippet: <|code_start|>@pytest.fixture
def session():
Session = sessionmaker()
engine = create_engine("sqlite://")
Session.configure(bind=engine)
metadata.create_all(engine)
try:
yield Session()
except:
pass
@pytest.fixture(autouse=True, scope='module')
def pa... | user = User(name='user', fullname='User', password='password') |
Given the code snippet: <|code_start|>
def _get_client_make_api_call_wrapper(self):
def make_api_call_wrapper(client, operation_name, api_params):
"""Wraps BaseClient._make_api_call"""
service_name = client._service_model.service_name
formatted_operation_name = xform_nam... | span = utils.start_child_span( |
Given the code snippet: <|code_start|>
service_name = client._service_model.service_name
formatted_operation_name = xform_name(operation_name)
return self.perform_call(
_client_make_api_call, 'client',
service_name, formatted_operation_name,
... | parent=get_current_span() |
Next line prediction: <|code_start|> client, operation_name, api_params
)
return make_api_call_wrapper
def _get_s3_call_wrapper(self, original_func):
operation_name = original_func.__name__
def s3_call_wrapper(*args, **kwargs):
"""Wraps __call__ of S... | with span, span_in_stack_context(span): |
Based on the snippet: <|code_start|>from __future__ import absolute_import
try:
except ImportError:
pass
else:
_service_action_call = ServiceAction.__call__
_client_make_api_call = BaseClient._make_api_call
_Executor = BoundedExecutor.EXECUTOR_CLS
logger = logging.getLogger(__name__)
<|code_end|>... | class Boto3Patcher(Patcher): |
Here is a snippet: <|code_start|># in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#... | request = WSGIRequestWrapper.from_wsgi_environ(wsgi_environ) |
Predict the next line after this snippet: <|code_start|># The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES... | patcher.install_patches() |
Next line prediction: <|code_start|> # In python 3+ we should make ioloop in new thread explicitly.
asyncio.set_event_loop(asyncio.new_event_loop())
io_loop = tornado.ioloop.IOLoop.current()
http_server = tornado.httpserver.HTTPServer(app)
http_server.add_socket(_unused_po... | with span_in_context(span=root_span): |
Predict the next line for this snippet: <|code_start|>from __future__ import absolute_import
try:
except ImportError:
pass
else:
_task_apply_async = Task.apply_async
def task_apply_async_wrapper(task, args=None, kwargs=None, **other_kwargs):
operation_name = 'Celery:apply_async:{}'.format(task.name)
... | child_of=get_current_span()) |
Using the snippet: <|code_start|>from __future__ import absolute_import
try:
except ImportError:
pass
else:
_task_apply_async = Task.apply_async
def task_apply_async_wrapper(task, args=None, kwargs=None, **other_kwargs):
operation_name = 'Celery:apply_async:{}'.format(task.name)
span = opentracing... | with span_in_context(span), span: |
Given the following code snippet before the placeholder: <|code_start|>
task.request.span = span = opentracing.tracer.start_span(
operation_name=operation_name,
child_of=child_of,
)
set_common_tags(span, task, tags.SPAN_KIND_RPC_SERVER)
span.set_tag('celery.task_id', task_id)
reques... | class CeleryPatcher(Patcher): |
Here is a snippet: <|code_start|>
log = logging.getLogger(__name__)
@singleton
def install_patches():
def build_handler(base_type, base_cls=None):
"""Build a urrllib2 handler from a base_type."""
class DerivedHandler(base_type):
"""The class derived from base_type."""
de... | class Urllib2RequestWrapper(AbstractRequestWrapper): |
Continue the code snippet: <|code_start|>#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR AN... | span = before_http_request( |
Based on the snippet: <|code_start|> span.set_tag(ext_tags.HTTP_STATUS_CODE, resp.code)
return resp
return DerivedHandler
class Urllib2RequestWrapper(AbstractRequestWrapper):
def __init__(self, request):
self.request = request
self._no... | return split_host_and_port(host_string=host_string, |
Based on the snippet: <|code_start|># Copyright (c) 2015 Uber Technologies, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights... | @singleton |
Given the following code snippet before the placeholder: <|code_start|># IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN... | current_span_extractor=current_span_func) |
Predict the next line after this snippet: <|code_start|># copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
... | conn_wrapper_ctor=ConnectionWrapper) |
Continue the code snippet: <|code_start|># in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following condi... | factory = ConnectionFactory(connect_func=MySQLdb.connect, |
Given the code snippet: <|code_start|># Copyright (c) 2015,2019 Uber Technologies, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the... | class MySQLdbPatcher(Patcher): |
Based on the snippet: <|code_start|> It must have a signature `(response, span)`,
where `response` and `span` are positional arguments,
so you can use different names for them if needed.
"""
self.response_handler_hook = response_handler_hook
def _install_patches(... | class RequestWrapper(AbstractRequestWrapper): |
Next line prediction: <|code_start|>
class RequestsPatcher(Patcher):
applicable = '_HTTPAdapter_send' in globals()
response_handler_hook = None
def set_response_handler_hook(self, response_handler_hook):
"""
Set a hook that will be called when a response is received.
The hook can b... | span = before_http_request(request=request_wrapper, |
Next line prediction: <|code_start|> return response
return send_wrapper
class RequestWrapper(AbstractRequestWrapper):
def __init__(self, request):
self.request = request
self.scheme, rest = urllib.parse.splittype(request.url)
if self.scheme and rest:... | return split_host_and_port(host_string=self.host_str, |
Predict the next line after this snippet: <|code_start|># copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
... | class RequestsPatcher(Patcher): |
Given the following code snippet before the placeholder: <|code_start|>class RequestsPatcher(Patcher):
applicable = '_HTTPAdapter_send' in globals()
response_handler_hook = None
def set_response_handler_hook(self, response_handler_hook):
"""
Set a hook that will be called when a response is... | current_span_extractor=current_span_func |
Continue the code snippet: <|code_start|># FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR T... | urllib2_hooks.install_patches.__original_func() |
Predict the next line for this snippet: <|code_start|>#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE ... | old_callee_headers = CONFIG.callee_name_headers |
Predict the next line after this snippet: <|code_start|>
if module is None:
pytest.skip('Skipping %s on Py3' % urllibver)
class Response(object):
def __init__(self):
self.code = 200
self.msg = ''
def info(self):
return None
if root_span:
... | with p_do_open, span_in_context(span=root_span): |
Continue the code snippet: <|code_start|># LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
SKIP_REASON = 'Postgres is not running or cannot connect'
POSTGRES_CONNECTION_STRING = 'postgresql://pos... | psycopg2.install_patches() |
Given snippet: <|code_start|>def session():
Session = sessionmaker()
Session.configure(bind=engine)
try:
yield Session()
except:
pass
@pytest.fixture(autouse=True)
def patch_postgres():
psycopg2.install_patches()
@pytest.fixture()
def connection():
return psycopg2_client.conn... | metadata.create_all(engine) |
Using the snippet: <|code_start|> Session = sessionmaker()
Session.configure(bind=engine)
try:
yield Session()
except:
pass
@pytest.fixture(autouse=True)
def patch_postgres():
psycopg2.install_patches()
@pytest.fixture()
def connection():
return psycopg2_client.connect(POSTGRE... | user1 = User(name='user1', fullname='User 1', password='password') |
Given the following code snippet before the placeholder: <|code_start|># Copyright (c) 2016 Uber Technologies, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, incl... | strict_redis.install_patches() |
Predict the next line after this snippet: <|code_start|>
CELERY_3 = celery_module.__version__.split('.', 1)[0] == '3'
@pytest.fixture(autouse=True, scope='module')
def patch_celery():
<|code_end|>
using the current file's imports:
import celery as celery_module
import mock
import pytest
from celery import Celery... | celery_hooks.install_patches() |
Given the following code snippet before the placeholder: <|code_start|> builder = TracedPatcherBuilder()
builder.patch()
def reset_patchers():
try:
except ImportError:
pass
else:
setattr(
simple.SimpleAsyncHTTPClient,
'fetch_impl',
_SimpleAsyncHTT... | span = before_http_request(request=request_wrapper, |
Given the following code snippet before the placeholder: <|code_start|> span.finish()
return callback(response)
real_fetch_impl(self, request, new_callback)
return new_fetch_impl
class TornadoRequestWrapper(AbstractRequestWrapper):
def __init__(self, request):
self.re... | return split_host_and_port(host_string=res.netloc, |
Given the code snippet: <|code_start|> builder.patch()
def reset_patchers():
try:
except ImportError:
pass
else:
setattr(
simple.SimpleAsyncHTTPClient,
'fetch_impl',
_SimpleAsyncHTTPClient_fetch_impl,
)
try:
except ImportError:
... | current_span_extractor=get_current_span) |
Based on the snippet: <|code_start|> for obj, attr, repl in self._tornado():
self._build_patcher(obj, attr, repl)
@staticmethod
def _build_patcher(obj, patched_attribute, replacement):
if not hasattr(obj, patched_attribute):
return
return setattr(obj, patched_attr... | @singleton |
Continue the code snippet: <|code_start|># IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT O... | assert get_current_span() is not None |
Next line prediction: <|code_start|> This test illustrates that the default Tornado's StackContext
is not thread-safe. The test can be made to fail by commenting
out these lines in the ThreadSafeStackContext constructor:
if hasattr(self, 'contexts'):
# only patch if context exists
... | with span_in_stack_context(span='span'): |
Predict the next line after this snippet: <|code_start|># in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the ... | assert get_current_span() == span_to_check |
Next line prediction: <|code_start|> @gen_test
def test_request_context_manager_backwards_compatible(self):
span = opentracing.tracer.start_span(operation_name='test')
@gen.coroutine
def check():
assert get_current_span() == span
# Bypass ScopeManager/span_in_stack_c... | with span_in_stack_context(span): |
Given snippet: <|code_start|>
@patch('opentracing.tracer', new=opentracing.Tracer(TornadoScopeManager()))
class TornadoTraceContextTest(AsyncTestCase):
@gen_test
def test_http_fetch(self):
span1 = 'Bender is great!'
span2 = 'Fry is dumb!'
@gen.coroutine
def check(span_to_check)... | ctx = RequestContextManager(context=RequestContext(span='x')) |
Given the following code snippet before the placeholder: <|code_start|>
@patch('opentracing.tracer', new=opentracing.Tracer(TornadoScopeManager()))
class TornadoTraceContextTest(AsyncTestCase):
@gen_test
def test_http_fetch(self):
span1 = 'Bender is great!'
span2 = 'Fry is dumb!'
@gen.... | ctx = RequestContextManager(context=RequestContext(span='x')) |
Using the snippet: <|code_start|>parser.add_option("-w", "--width", action="store", dest="image_width", type="int", help="image width in pixels (default %default)")
parser.add_option("-h", "--height", action="store", dest="image_height", type="int", help="image height in pixels (default %default)")
parser.add_option("-... | create_wave_images(*args) |
Based on the snippet: <|code_start|>
class MakamTagTest(unittest.TestCase):
def test_usul(self):
t = "usul: something"
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest
from compmusic import tags
and context (classes, functions, sometimes code) from other files:
#... | self.assertEqual(True, tags.has_usul(t)) |
Here is a snippet: <|code_start|> if not isinstance(collections, list):
raise ValueError('`collections` must be a list')
COLLECTIONS = collections
def _get_collections():
extra_headers = None
if COLLECTIONS:
extra_headers = {}
extra_headers['Dunya-Collection'] = ','.join(COLLECT... | return conn._get_paged_json("api/carnatic/recording", extra_headers=extra_headers, **args) |
Given the following code snippet before the placeholder: <|code_start|> return localscore
##########################################################################################
def hanning(n):
window = 0.5 - 0.5 * np.cos(2 * math.pi * np.arange(n) / (n - 1));
return window
###########################... | logger = log.get_logger("rhythm") |
Continue the code snippet: <|code_start|> COLLECTIONS = collections
def _get_collections():
extra_headers = None
if COLLECTIONS:
extra_headers = {}
extra_headers['Dunya-Collection'] = ','.join(COLLECTIONS)
return extra_headers
def get_recordings(recording_detail=False):
""" Get a ... | return conn._get_paged_json("api/jingju/recording", extra_headers=extra_headers, **args) |
Predict the next line for this snippet: <|code_start|>
class ConnTest(unittest.TestCase):
def test_make_url(self):
params = {"first": "%^grtà"}
<|code_end|>
with the help of current file imports:
import unittest
from compmusic.dunya.conn import _make_url
and context from other files:
# Path: compmusi... | url = _make_url("path", **params) |
Given snippet: <|code_start|>
mb.set_useragent("Dunya", "0.1")
mb.set_rate_limit(False)
mb.set_hostname("musicbrainz.sb.upf.edu")
MUSICBRAINZ_COLLECTION_CARNATIC = ""
MUSICBRAINZ_COLLECTION_HINDUSTANI = ""
MUSICBRAINZ_COLLECTION_MAKAM = ""
headers = {"User-Agent": "Dunya/0.1 python-musicbrainzngs"}
requests_session... | log.debug("offset", offset) |
Given the following code snippet before the placeholder: <|code_start|>
class TechGetSerializer(serializers.ModelSerializer):
user = UserSerializer(many=False, read_only=True)
class Meta:
model = Tech
fields = ['id', 'experience', 'job_title', 'shop', 'user',
'tech_rating']
... | model = Vote |
Continue the code snippet: <|code_start|> model = Vote
fields = "__all__"
class SolutionGetSerializer(serializers.ModelSerializer):
votes = VoteSerializer(many=True, read_only=True)
commits = CommitSerializer(many=True, read_only=True)
tech = TechGetSerializer(many=False, read_only=True)
... | model = Problem |
Given the code snippet: <|code_start|>
class TechPostSerializer(serializers.ModelSerializer):
class Meta:
model = Tech
fields = ['id', 'experience', 'job_title', 'shop', 'user',
'tech_rating']
class CommitSerializer(serializers.ModelSerializer):
class Meta:
model =... | model = Solution |
Here is a snippet: <|code_start|>class SystemSerializer(serializers.ModelSerializer):
class Meta:
model = System
fields = ['id', 'name', 'url']
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
def create(self, validated_data):
u... | model = Tech |
Using the snippet: <|code_start|>class SolutionPostSerializer(serializers.ModelSerializer):
class Meta:
model = Solution
fields = ['id', 'description', 'time_required', 'parts_cost',
'problem', 'tech', 'posted', 'score', 'url']
class ProblemGetSerializer(serializers.ModelSeriali... | model = Rating |
Here is a snippet: <|code_start|>
class ProblemGetSerializer(serializers.ModelSerializer):
solutions = SolutionGetSerializer(many=True, read_only=True)
tech = TechGetSerializer(many=False, read_only=True)
system = SystemSerializer(many=False, read_only=True)
class Meta:
model = Problem
... | model = Brand |
Given snippet: <|code_start|> fields = ['id', 'title', 'system', 'description', 'tech',
'model', 'posted', 'url', 'solutions']
class ProblemPostSerializer(serializers.ModelSerializer):
class Meta:
model = Problem
fields = ['id', 'title', 'system', 'description', 'tech',
... | model = Model |
Based on the snippet: <|code_start|> return user
class Meta:
model = User
fields = ['id', 'password', 'email', 'username']
read_only_fields = ['is_staff', 'is_superuser', 'is_active',
'date_joined',]
class TechGetSerializer(serializers.ModelSerializer):
... | model = Commit |
Based on the snippet: <|code_start|> model = Problem
fields = ['id', 'title', 'system', 'description', 'tech',
'model', 'posted', 'url']
class RatingSerializer(serializers.ModelSerializer):
class Meta:
model = Rating
fields = "__all__"
class BrandSerializer(seri... | model = Notification |
Next line prediction: <|code_start|>
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'password', 'email']
class TechForm(forms.ModelForm):
class Meta:
<|code_end|>
. Use current file imports:
(from d... | model = Tech |
Predict the next line after this snippet: <|code_start|> for chunk in chunks(items, chunk_size):
yield dict(chunk)
def alexa_top_million():
"""Returns an iterable of objects describing the top million domains from Alexa
It turns out this list can be used as a set and held in memory fairly
easil... | pipe = redis_db["master"].pipeline() |
Predict the next line after this snippet: <|code_start|> list.append(to_unicode(e.title))
return list
titleList = []
for url in urlList:
l = rssParse(url)
titleList = titleList + l
return titleList
ASPELL_KEY = "aspell"
def load_aspell():
dump = subprocess.Popen(
... | pipe = redis_db["master"].pipeline(use_transaction=True) |
Predict the next line for this snippet: <|code_start|># def route_for_task(self, task, args=None, kwargs=None):
# if task == 'malware_crawl.scan.capture_hpc.chpc_malware_scan':
# return {'queue': 'capturehpc',
# 'routing_key': 'capturehpc.scan'}
# return None
def redis_cache... | pipe = redis_db["master"].pipeline() |
Continue the code snippet: <|code_start|> cache_length
)
pipe.execute()
return [total_response[item] for item in items]
@task(base=Batches, flush_every=500, flush_interval=((timedelta(minutes=30).seconds, 0.1)[settings.DEBUG]))
def chpc_malware_scan(requests):
sig = lambda url: url
... | CaptureUrl.objects.using('capture').all().delete() |
Continue the code snippet: <|code_start|>
requests = REQUESTS_SESSIONS["api"]
wot_api_target = "https://api.mywot.com/0.4/public_link_json"
def redis_cache(key_prefix, prepare, request, items):
items = list(map(prepare, items))
unique_items = list(set(items))
total_response = {}
# get all the ite... | pipe = redis_db["slave"].pipeline() |
Predict the next line after this snippet: <|code_start|>from __future__ import division
_mal_list = []
def read_from_database_to_dict():
"""
Reads the malwares from the database and returns a mal_dict
"""
<|code_end|>
using the current file's imports:
from pebl.util import levenshtein
from malwar... | malwares = Malicouse_sites.objects.all() |
Predict the next line for this snippet: <|code_start|># Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unles... | datacatalog_synchronizer.DataCatalogSynchronizer( |
Next line prediction: <|code_start|>def uuidstr():
return str(uuid.uuid4())
def uuid2int(uuidv):
return uuid.UUID(uuidv).int
def int2uuid(n):
return str(uuid.UUID(int=n))
# Geodal utils
def geoPoint(x, y):
return "POINT (%f %f)" % (x, y)
def geoLine(*line):
return "LINESTRING (%s)" % ",".joi... | if not PY2 and isinstance(value, bytes): |
Given the following code snippet before the placeholder: <|code_start|>
def int2uuid(n):
return str(uuid.UUID(int=n))
# Geodal utils
def geoPoint(x, y):
return "POINT (%f %f)" % (x, y)
def geoLine(*line):
return "LINESTRING (%s)" % ",".join("%f %f" % item for item in line)
def geoPolygon(*line):
... | stream = BytesIO(to_bytes(value["data"])) |
Predict the next line after this snippet: <|code_start|>def bar_unescape(item):
item = item.replace("||", "|")
if item.startswith(UNIT_SEPARATOR):
item = item[1:]
if item.endswith(UNIT_SEPARATOR):
item = item[:-1]
return item
def bar_encode(items):
return "|%s|" % "|".join(bar_esca... | for k, v in iteritems(fs): |
Given the following code snippet before the placeholder: <|code_start|> raise ValueError("Name conflict in table list: %s" % key)
# Merge
big.update(small)
ret = big
return ret
def bar_escape(item):
item = str(item).replace("|", "||")
if item.startswith("||"):
... | long = integer_types[-1] |
Next line prediction: <|code_start|>
def uuidstr():
return str(uuid.uuid4())
def uuid2int(uuidv):
return uuid.UUID(uuidv).int
def int2uuid(n):
return str(uuid.UUID(int=n))
# Geodal utils
def geoPoint(x, y):
return "POINT (%f %f)" % (x, y)
def geoLine(*line):
return "LINESTRING (%s)" % ",".jo... | if not (value is None or isinstance(value, string_types)): |
Given the code snippet: <|code_start|>
def int2uuid(n):
return str(uuid.UUID(int=n))
# Geodal utils
def geoPoint(x, y):
return "POINT (%f %f)" % (x, y)
def geoLine(*line):
return "LINESTRING (%s)" % ",".join("%f %f" % item for item in line)
def geoPolygon(*line):
return "POLYGON ((%s))" % ",".joi... | stream = BytesIO(to_bytes(value["data"])) |
Given the following code snippet before the placeholder: <|code_start|> # Explicitly add compute upload fields (ex: thumbnail)
fields += [f for f in table.fields if table[f].compute is not None]
else:
fields = table.fields
fields = [
f
for f in fields
if table[f].t... | uploadfolder = pjoin(dbset.db._adapter.folder, "..", "uploads") |
Given the following code snippet before the placeholder: <|code_start|> and table[f].autodelete
]
if not fields:
return False
for record in dbset.select(*[table[f] for f in fields]):
for fieldname in fields:
field = table[fieldname]
oldname = record.get(fieldna... | if field.uploadfs.exists(oldname): |
Using the snippet: <|code_start|> and table[f].uploadfield == True
and table[f].autodelete
]
if not fields:
return False
for record in dbset.select(*[table[f] for f in fields]):
for fieldname in fields:
field = table[fieldname]
oldname = record.get(fiel... | oldname = text_type(oldname) |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
UNIT_SEPARATOR = "\x1f" # ASCII unit separater for delimiting data
def hide_password(uri):
if isinstance(uri, (list, tuple)):
return [hide_password(item) for item in uri]
<|code_end|>
. Use current file imports:
import os
import re
impor... | return re.sub(REGEX_CREDENTIALS, "******", uri) |
Here is a snippet: <|code_start|>def bar_escape(item):
item = str(item).replace("|", "||")
if item.startswith("||"):
item = "%s%s" % (UNIT_SEPARATOR, item)
if item.endswith("||"):
item = "%s%s" % (item, UNIT_SEPARATOR)
return item
def bar_unescape(item):
item = item.replace("||", "... | return [bar_unescape(x) for x in re.split(REGEX_UNPACK, value[1:-1]) if x.strip()] |
Based on the snippet: <|code_start|> archive_table.insert(**fields)
break
return False
def smart_query(fields, text):
if not isinstance(fields, (list, tuple)):
fields = [fields]
new_fields = []
for field in fields:
if isinstance(field, Field):
... | m = re.search(REGEX_CONST_STRING, text) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.