Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line for this snippet: <|code_start|>
# seq_crumbs is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have recei... | @CUESXEL824 2:Y:18:ATCACG |
Given the following code snippet before the placeholder: <|code_start|> # the query name and definition
definition = bio_result.query
if self.use_query_def_as_accession:
items = definition.split(' ', 1)
name = items[0]
if len(items) > 1:
definit... | else: |
Given snippet: <|code_start|> similarity = None
try:
identity = hsp.identities * 100.0 / float(hsp_length)
except TypeError:
identity = None
match_parts.append({'subject_start': subject_start,
... | 'end': match_end, |
Using the snippet: <|code_start|> try:
identity = hsp.identities * 100.0 / float(hsp_length)
except TypeError:
identity = None
match_parts.append({'subject_start': subject_start,
'subject_end': sub... | 'subject_start': match_subject_start, |
Predict the next line for this snippet: <|code_start|> subject_strand = _strand_transform(subject_strand)
score = int(score)
similarity = float(similarity)
# For each line , It creates a match part dict
match_part = {}
match_part['query_start'] = qu... | match['start'] = query_start |
Based on the snippet: <|code_start|> 'subject_end': match_subject_end,
'scores': {'expect': match_parts[0]['scores']['expect']},
'match_parts': match_parts})
result = {'query': query, 'matches': matches}
return result
def _get_blast_meta... | 'It returns the next blast result' |
Given the code snippet: <|code_start|> # TODO - Refactor this and the __init__ method to reduce code
# duplication?
handle = self._handle
handle.seek(offset)
line = handle.readline()
data = line
at_char = _as_bytes("@")
plus_char = _as_bytes("+")
if... | break |
Predict the next line after this snippet: <|code_start|> string."""
# TODO - Refactor this and the __init__ method to reduce code
# duplication?
handle = self._handle
handle.seek(offset)
line = handle.readline()
data = line
at_char = _as_bytes("@")
... | ValueError("Problem with line %s" % repr(line)) |
Given snippet: <|code_start|> ValueError("Problem with line %s" % repr(line))
break
else:
line = handle.readline()
qual_len += len(line.strip())
length += len(line)
if seq_len != qual_len:
... | if line.startswith(plus_char): |
Based on the snippet: <|code_start|> if line and line[0:1] != at_char:
ValueError("Problem with line %s" % repr(line))
break
else:
line = handle.readline()
qual_len += len(line.strip())
... | data += line |
Using the snippet: <|code_start|> while line:
if seq_len == qual_len:
# Should be end of record...
end_offset = handle.tell()
line = handle.readline()
if line and line[0:1] != at_char:
Valu... | raise ValueError("Problem with FASTQ @ line:\n%s" % repr(line)) |
Predict the next line for this snippet: <|code_start|> # duplication?
handle = self._handle
handle.seek(offset)
line = handle.readline()
data = line
at_char = _as_bytes("@")
plus_char = _as_bytes("+")
if line[0:1] != at_char:
raise ValueError("P... | else: |
Given the code snippet: <|code_start|>
SAM = '''@HD\tVN:1.3\tSO:coordinate
@SQ\tSN:ref\tLN:45
r001\t0\tref\t7\t30\t8M2I4M1D3M\t=\t37\t39\tTAAGATAAAGGATACTG\t*
r002\t0\tref\t9\t30\t3S6M1P1I4M\t*\t0\t0\tAAAAGATAAGGATA\t*
<|code_end|>
, generate the next line using the imports in this file:
import unittest
import pysa... | r003\t0\tref\t9\t30\t5H6M\t*\t0\t0\tAGCTAA\t*\tNM:i:1 |
Predict the next line after this snippet: <|code_start|>
# seq_crumbs is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have rec... | conn.commit() |
Using the snippet: <|code_start|> self._conn = sqlite3.connect(self._db_fhand.name)
create = 'CREATE TABLE items(idx INTEGER PRIMARY KEY, item BLOB);'
self._conn.execute(create)
self._conn.commit()
self._last_item_returned = None
def __len__(self):
conn = self._conn
... | idx = self._last_item_returned + 1 |
Next line prediction: <|code_start|> non_A_alleles = list(alleles_snp1.difference(allele_A))
non_B_alleles = list(alleles_snp2.difference(allele_B))
if not non_A_alleles or not non_B_alleles:
return None
allele_a = non_A_alleles[0]
allele_b = non_B_alleles[0]
count_AB = haplo_count.get(... | recomb = recomb_haplos * (tot_haplos - recomb_haplos - 1) |
Predict the next line for this snippet: <|code_start|> p_val=DEF_P_VAL, bonferroni=True, snv_win=DEF_SNV_WIN,
min_phys_dist=MIN_PHYS_DIST, log_fhand=None):
if not snv_win % 2:
msg = 'The window should have an odd number of snvs'
raise ValueError(msg)
ha... | stats_cache = _LDStatsCache() |
Predict the next line for this snippet: <|code_start|>
# seq_crumbs is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have recei... | def test_get_all_segments(): |
Next line prediction: <|code_start|> assert segment == (0, 3) or segment == (10, 13)
@staticmethod
def test_get_all_segments():
'Give a list of discontinious segments we get all segments'
segments = get_all_segments([(0, 10), (15, 20)], 30)
assert segments == [((0, 10), True), ((... | unittest.main() |
Predict the next line for this snippet: <|code_start|>
class SegmentsTest(unittest.TestCase):
'It tests the segments functions'
@staticmethod
def test_get_longest_section():
'It gets the longest section from a list of sections'
segments = [(0, 3), (10, 34)]
assert (10, 34) == get... | def test_non_matched(): |
Given snippet: <|code_start|># You should have received a copy of the GNU General Public License
# along with seq_crumbs. If not, see <http://www.gnu.org/licenses/>.
FILETYPE = 'file'
STRINGIOTYPE = 'stringio'
OTHERTYPE = 'othertype'
def _get_some_qual_and_lengths(fhand, force_file_as_non_seek):
'It returns th... | fhand.seek(0) |
Given the code snippet: <|code_start|># seq_crumbs 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 option) any later version.
# seq_crumbs is distributed in the ... | fhand.seek(0) |
Using the snippet: <|code_start|>STRINGIOTYPE = 'stringio'
OTHERTYPE = 'othertype'
def _get_some_qual_and_lengths(fhand, force_file_as_non_seek):
'It returns the quality characters and the lengths'
seqs_to_peek = get_setting('SEQS_TO_GUESS_FASTQ_VERSION')
chunk_size = get_setting('CHUNK_TO_GUESS_FASTQ_VER... | except ValueError: |
Predict the next line after this snippet: <|code_start|># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with seq_crumbs. If not, see <http://www.gnu.org/licenses/>.
FILETYPE = ... | qual = [ord(char) for char in seq[2]] |
Based on the snippet: <|code_start|>
def _get_some_qual_and_lengths(fhand, force_file_as_non_seek):
'It returns the quality characters and the lengths'
seqs_to_peek = get_setting('SEQS_TO_GUESS_FASTQ_VERSION')
chunk_size = get_setting('CHUNK_TO_GUESS_FASTQ_VERSION')
lengths = array('I')
seqs_analyz... | finally: |
Predict the next line after this snippet: <|code_start|># Copyright 2013 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
# This file is part of seq_crumbs.
# seq_crumbs 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 ... | 'It returns the quality characters and the lengths' |
Here is a snippet: <|code_start|>
def _get_alleles(call, filter_alleles_gt):
alleles = call.int_alleles
if filter_alleles_gt is not None:
alleles = [allele for allele in alleles if allele <= filter_alleles_gt]
return alleles
def _flatten_data(x_data, y_data):
new_x_data = []
new_y_data ... | genotypes = {} |
Here is a snippet: <|code_start|> # draw
n_samples = len(samples)
xsize = len(genotypes[sample]) / 100
if xsize >= 100:
xsize = 100
if xsize <= 8:
xsize = 8
ysize = n_samples * 2
if ysize >= 100:
ysize = 100
# print xsize, ysize
figure_size = (xsize, ysize)
... | axes.tick_params(axis='y', left='on', right='off', labelleft='off') |
Using the snippet: <|code_start|># Copyright 2012 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
# This file is part of seq_crumbs.
# seq_crumbs 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, ei... | assert ordered_set._items == [1, 2, 3, 4, 5, 7, 8, 10] |
Here is a snippet: <|code_start|># GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with seq_crumbs. If not, see <http://www.gnu.org/licenses/>.
class TestCollections(unittest.TestCase):
def test_ordered_set(self):
in_list = [1, 2,... | assert keyed_set.check_add(7) |
Predict the next line for this snippet: <|code_start|># Copyright 2012 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
# This file is part of seq_crumbs.
# seq_crumbs 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 So... | DEF_FILE_BUFFER = 8192*4 |
Based on the snippet: <|code_start|># Copyright 2012 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
# This file is part of seq_crumbs.
# seq_crumbs 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,... | DEF_FILE_BUFFER = 8192*4 |
Here is a snippet: <|code_start|># Copyright 2012 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
# This file is part of seq_crumbs.
# seq_crumbs 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, ei... | DEF_FILE_BUFFER = 8192*4 |
Here is a snippet: <|code_start|> seq = record.seq
if trim:
record.annotations = {}
record = record[clip:]
else:
annots['clip_qual_left'] = clip
annots['clip_adapter_left'] = clip
seq = seq[:clip].lower() + seq[clip:].upper()
... | @property |
Using the snippet: <|code_start|>except ImportError:
class DummyConnection(object):
"Used to detect a failed ConnectionCls import."
pass
try: # Compiled with SSL?
HTTPSConnection = DummyConnection
BaseSSLError = ssl.SSLError
except (ImportError, AttributeError): # Platform-specific: No ... | class HTTPConnection(_HTTPConnection, object):
|
Given snippet: <|code_start|>
try: # Python 3
except ImportError:
class DummyConnection(object):
"Used to detect a failed ConnectionCls import."
pass
try: # Compiled with SSL?
HTTPSConnection = DummyConnection
BaseSSLError = ssl.SSLError
except (ImportError, AttributeError): # Platfo... | }
|
Predict the next line for this snippet: <|code_start|>except ImportError:
class DummyConnection(object):
"Used to detect a failed ConnectionCls import."
pass
try: # Compiled with SSL?
HTTPSConnection = DummyConnection
BaseSSLError = ssl.SSLError
except (ImportError, AttributeError): # P... | class HTTPConnection(_HTTPConnection, object):
|
Using the snippet: <|code_start|>
class DeflateDecoder(object):
def __init__(self):
self._first_try = True
self._data = binary_type()
self._obj = zlib.decompressobj()
def __getattr__(self, name):
return getattr(self._obj, name)
def decompress(self, data):
... | try:
|
Here is a snippet: <|code_start|>
class DeflateDecoder(object):
def __init__(self):
self._first_try = True
self._data = binary_type()
self._obj = zlib.decompressobj()
def __getattr__(self, name):
return getattr(self._obj, name)
def decompress(self, data):
... | except zlib.error:
|
Here is a snippet: <|code_start|># Put libraries such as Divisi in the PYTHONPATH.
sys.path = ['/stuff/openmind'] + sys.path
# Load the OMCS language model
en = Language.get('en')
en_nl=get_nl('en')
# Load OMCS stopwords
sw = open('stopwords.txt', 'r')
swords = [x.strip() for x in sw.readlines()]
# Parameters
factor... | Concept.get(concept, 'en') |
Predict the next line after this snippet: <|code_start|>
## Utilities
def get_shape_for_dict(expected):
if len(expected.keys()) == 0:
return ()
ndim = len(expected.keys()[0])
return tuple(len(set(k[dim] for k in expected.iterkeys()))
for dim in xrange(ndim))
def nones_removed(d):
... | items = d.items() |
Continue the code snippet: <|code_start|>
def cpu():
return (resource.getrusage(resource.RUSAGE_SELF).ru_utime+
resource.getrusage(resource.RUSAGE_SELF).ru_stime)
_proc_status = '/proc/%d/status' % os.getpid()
<|code_end|>
. Use current file imports:
from csc.divisi.labeled_tensor import SparseLabele... | _scale = {'kB': 1024.0, 'mB': 1024.0*1024.0, |
Predict the next line for this snippet: <|code_start|>def test_pt_ordered_set():
tmpdir = tempfile.mkdtemp()
tfile = os.path.join(tmpdir, 'pttensor.h5')
ordered_set = PTOrderedSet.create(tfile, '/', 'labels_0')
eq_(ordered_set.add('apple'), 0)
eq_(ordered_set.add('banana'), 1)
eq_(ordered_set[1... | del ordered_set |
Next line prediction: <|code_start|> n = min(self._iteration, self._remembrance)
if n < self._bootstrap:
w_old = float(n - 1) / n
w_new = 1.0 / n
else:
l = self._amnesia
w_old = float(n - l) / n
w_new = fl... | logger.debug('') |
Using the snippet: <|code_start|>MAG_MAX = 100.0
K=6
# Prepare test vectors
vecs = [numpy.array([random() for i in range(VEC_LEN)]) for j in range(VEC_COUNT)]
vecs = [make_dense_labeled_tensor(v, None).to_sparse() for v in vecs]
mags = sorted([MAG_MAX * random() for i in range(VEC_COUNT)])
print "Vectors prepared:"
v... | v_out = ccipca.smooth(v, k_max=(VEC_COUNT+1), learn=True) |
Next line prediction: <|code_start|>
#os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'csamoa.settings')
def pickledump(filename, obj):
if not isinstance(filename, basestring):
filename, obj = obj, filename
f = gzip.open(filename, 'wb')
pickle.dump(obj, f)
f.close()
def normalize_and_copy(tens... | tensor1 = normalize_and_copy(tensor1) |
Here is a snippet: <|code_start|>
#os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'csamoa.settings')
def pickledump(filename, obj):
if not isinstance(filename, basestring):
filename, obj = obj, filename
<|code_end|>
. Write the next line using the current file imports:
from csc.divisi.cnet import concept... | f = gzip.open(filename, 'wb') |
Based on the snippet: <|code_start|> blend = tensor1*(1-factor) + tensor2*factor
svd = blend.svd(k=50)
#svd.summarize()
return svd
def find_rough_factor(tensor1, tensor2):
# Only first sigmas
t1 = tensor1.svd(k=20)
sigma1 = t1.svals[0:10]
a = sigma1[0]
t2 = tensor2.svd(k=20)
sigm... | if value < 0: |
Using the snippet: <|code_start|> filename, obj = obj, filename
f = gzip.open(filename, 'wb')
pickle.dump(obj, f)
f.close()
def normalize_and_copy(tensor):
newt = SparseLabeledTensor(ndim=2)
newt.update(tensor.normalized())
return newt
def normalize_and_copy_mode_one(tensor):
newt =... | blend2 = blend*(1-factor2) + tensor3*factor2 |
Next line prediction: <|code_start|> thumbnail.allow_tags = True
thumbnail.__name__ = 'Thumbnail'
admin.site.register(Badge, BadgeAdmin)
class AchievementInlineFormSet(BaseInlineFormSet):
model = Achievement
_enrollment_ids = None
@property
def enrollment_ids(self):
if self.instan... | for form in self: |
Next line prediction: <|code_start|> model = Grade
raw_id_fields = ("assignment_task",)
formset = EnrollmentGradeInlineFormSet
ordering = ('assignment_task__assignment_id', 'assignment_task')
def last_login_formatted_for_enrolment(self):
return last_login_formatted(self.student.user)
last_log... | ordering = ('full_name',) |
Using the snippet: <|code_start|> return last_login_formatted(self.student.user)
last_login_formatted_for_enrolment.short_description = _('Last Login')
class EnrollmentAdmin(BasicAdmin):
inlines = [SimpleGradeInline]
list_display = ('student', 'id_number', 'course_class', 'total_score', last_login_form... | ordering = ('course_class_id',) |
Given the following code snippet before the placeholder: <|code_start|>
class CheckPeriodThrottle(BaseThrottle):
def allow_request(self, request, view):
request.server = None
allow = True
<|code_end|>
, predict the next line using imports from the current file:
from rest_framework.throttling... | view_name = view.get_view_name() |
Next line prediction: <|code_start|>
def test_forgotten_password_form(self):
self._cleanup()
url = reverse('forgotten_password')
response = self.c.post(url, {'email': self.email})
assert response.context['form'].errors
# Create user and reset password
... | token = forgotten_pass_tokens_model.collection.find_one()
|
Based on the snippet: <|code_start|>
User = get_user_model()
class TestInvite(TestCase):
def setUp(self):
self.c = Client()
self.user = User.objects.create_user(password='qwerty', email='foo@test.com')
self.c.login(username='foo@test.com', password='qwerty')
<|code_end|>... | def tearDown(self):
|
Given snippet: <|code_start|>register = template.Library()
@register.filter
def format_plugin_value(value, column):
if column in ['size', 'totalIndexSize', 'indexes', 'total', 'bytes']:
try:
value = size(value)
except Exception as e:
pass
<|code_end|>
, continu... | return value |
Based on the snippet: <|code_start|>
@login_required
def data(request):
if request.method == 'POST':
form = DataRetentionForm(request.POST)
if form.is_valid():
form.save()
messages.add_message(request, messages.INFO, 'Data Retention settings updated')
redirect... | "form": form |
Predict the next line for this snippet: <|code_start|>
return redirect(redirect_url)
else:
form = DataRetentionForm()
return render(request, 'settings/data.html', {
"form": form
})
@login_required
def cleanup(request):
if request.method == 'POST':
form = Clean... | @login_required |
Predict the next line for this snippet: <|code_start|> if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
return Response({'ip': ip})
class TestView(APIView):
def get(self, request, server_key):
server = serve... | status = settings.API_RESULTS['not-found'] |
Here is a snippet: <|code_start|>
class CheckIpAddressView(APIView):
def get(self, request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
r... | def get(self, request, server_key): |
Next line prediction: <|code_start|>
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None)
super(InviteForm, self).__init__(*args, **kwargs)
email = forms.EmailField(required=True, widget=forms.TextInput(attrs={'placeholder': 'Email'}))
def clean_email(self... | cleaned_data = self.cleaned_data
|
Predict the next line for this snippet: <|code_start|>
self.c.login(username='foo@test.com', password='qwerty')
def tearDown(self):
self.c.logout()
self.user.delete()
def _cleanup(self):
tags_model.collection.remove()
tag_groups_model.collection.remove()
... | response = self.c.post(url, form_data) |
Here is a snippet: <|code_start|>
assert len(result['sorted_data']) == 10
assert result['sorted_data'][0]['value'] == 23 # 10 + 9 + 4
assert result['sorted_data'][0]['unit'] == '%'
def test_sort_by_iface_data(self):
self._cleanup()
for i in range(10):
... | "i": i + v + 100, |
Given the code snippet: <|code_start|>from __future__ import division
register = template.Library()
@register.filter
def kb_to_mb(value):
<|code_end|>
, generate the next line using the imports in this file:
from django import template
from amon.utils.filesize import size
and context (functions, classes, or occasio... | mb = float(value)/1000 |
Based on the snippet: <|code_start|># from amon.apps.servers.models import server_model
def charts_global_variables(request):
if request.user.is_authenticated:
# all_servers = server_model.get_all(account_itd=request.account_id)
global_variables_dict = {
'duration_form': DurationForm... | } |
Given snippet: <|code_start|># from amon.apps.servers.models import server_model
def charts_global_variables(request):
if request.user.is_authenticated:
# all_servers = server_model.get_all(account_itd=request.account_id)
global_variables_dict = {
'duration_form': DurationForm(),
... | } |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
SQL = {
"sqlite": ["""
CREATE TABLE "vote" (
list_name VARCHAR(255) NOT NULL,
message_id VARCHAR(255) NOT NULL,
user_id VARCHAR(255) NOT NULL,
... | ], |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
SQL = {
"sqlite": [
# no adding of the "description" column because it couln't have been
# remove in the past (SQLite has no REMOVE COLUMN statement)
'ALTER TABLE "list" ADD COLUMN recent_p... | 'ALTER TABLE "list" ADD COLUMN recent_participants_count INTEGER;', |
Given snippet: <|code_start|>
from __future__ import absolute_import
SQL_step_1 = {
"sqlite": ["""
CREATE TABLE "user" (
id VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);""", """
CREATE TABLE "sender" (
email VARCHAR(255) NOT NULL,
name VARCHAR(... | user_id VARCHAR(255), |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
SQL = {
"sqlite": ["""
CREATE TABLE "list_month_activity" (
list_name VARCHAR(255) NOT NULL,
year INTEGER NOT NULL,
month INTEGER NOT NULL,
participants_coun... | threads_count INTEGER, |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
SQL = {
"sqlite": [
'CREATE INDEX "ix_thread_list_name" ON "thread" (list_name);',
],
"postgres": [
'CREATE INDEX "ix_thread_list_name" ON "thread" (list_name);',
],
"mysql": [... | def apply(store): |
Here is a snippet: <|code_start|> # UUIDs yet so it'll error out.
metadata = sa.MetaData()
metadata.bind = connection
User = Base.metadata.tables["user"].tometadata(metadata)
User = sa.Table("user", metadata,
sa.Column("id", sa.Unicode(255), primary_key=True),
... | ALTER COLUMN {col} TYPE UUID USING {col}::uuid |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
SQL = {
"sqlite": ["""
CREATE TABLE "category" (
id INTEGER NOT NULL,
name VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);""",
'ALTER TABL... | CREATE TABLE "category" ( |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
SQL = {
"sqlite": [
'ALTER TABLE "email" ADD COLUMN "timezone" INTEGER NOT NULL DEFAULT 0;',
],
"postgres": [
'ALTER TABLE "email" ADD COLUMN "timezone" INTEGER;',
'UPDATE "emai... | 'ALTER TABLE "email" ALTER COLUMN "timezone" SET NOT NULL;', |
Based on the snippet: <|code_start|> def _generate_public_image(self):
private_file = storage.open(self.private_image.name, 'r')
private_file = Image.open(private_file)
image = private_file.filter(ImageFilter.GaussianBlur(self._determine_blur_radius(private_file)))
private_file.close(... | def get_public_image(self, btc_received): |
Based on the snippet: <|code_start|>
class AssetForm(ModelForm):
btc_address = BCAddressField(label=_("Bitcoin Address"),
help_text=_("Please use an address with no previous transactions."))
class Meta:
model = Asset
fields = ['name', 'btc_address', 'private_i... | } |
Given snippet: <|code_start|>
urlpatterns = patterns('',
url(r'^create/', AssetCreate.as_view(), name='asset-create'),
url(r'^list/', AssetList.as_view(), name='asset-list'),
url(r'^img/(?P<slug>[\w\-\.\~\+&,]+)/', AssetView.as_view(), name='asset-detail'),
<|code_end|>
, continue by predicting the next li... | ) |
Predict the next line for this snippet: <|code_start|>
class AssetList(generics.ListAPIView):
queryset = Asset.objects.filter(blocked=False)
serializer_class = AssetSerializer
permission_classes = (permissions.AllowAny,)
filter_backends = (filters.OrderingFilter,)
ordering_fields = ('created')
... | urlpatterns = patterns('', |
Predict the next line for this snippet: <|code_start|>
class AssetList(generics.ListAPIView):
queryset = Asset.objects.filter(blocked=False)
serializer_class = AssetSerializer
permission_classes = (permissions.AllowAny,)
filter_backends = (filters.OrderingFilter,)
ordering_fields = ('created')
<|... | ordering = ('-created',) |
Continue the code snippet: <|code_start|> self.assertEqual(self.tracks.query.tags, '-ql')
self.assertEqual(self.tracks.query.added, expected)
def test_new_music_single(self):
self.settings['single_track'] = True
self.tracks = Music.MHMusic(self.settings, self.push)
# Check re... | To: |
Continue the code snippet: <|code_start|> self.assertEqual(self.tracks.query.tags, '-ql')
self.assertEqual(self.tracks.query.added, expected)
def test_new_music_single(self):
self.settings['single_track'] = True
self.tracks = Music.MHMusic(self.settings, self.push)
# Check re... | To: |
Given the following code snippet before the placeholder: <|code_start|> expected = r"(Tagging|To)\:\n\s{1,4}(.*)\nURL\:\n\s{1,4}(.*)\n"
self.assertEqual(self.tracks.query.tags, '-ql')
self.assertEqual(self.tracks.query.added, expected)
def test_new_music_single(self):
self.settings['... | Alt-J - This Is All Yours |
Continue the code snippet: <|code_start|> self.assertEqual(self.tracks.query.added, expected)
def test_new_music_single(self):
self.settings['single_track'] = True
self.tracks = Music.MHMusic(self.settings, self.push)
# Check results
expected = r"(Tagging track)\:\s(.*)\nURL\... | alt-J - This Is All Yours |
Given the code snippet: <|code_start|>from __future__ import annotations
@pytest.fixture
def temp_git_dir(tmpdir):
<|code_end|>
, generate the next line using the imports in this file:
import pytest
from pre_commit_hooks.util import cmd_output
and context (functions, classes, or occasionally code) from other file... | git_dir = tmpdir.join('gits') |
Next line prediction: <|code_start|> cmd_output('chmod', '+x', f_path)
cmd_output('git', 'add', f_path)
cmd_output('git', 'update-index', '--chmod=+x', f_path)
files = (f_path,)
assert _check_git_filemode(files) == 0
def test_check_git_filemode_failing(tmpdir):
with tmpdir.... | def test_git_executable_shebang(temp_git_dir, content, mode, expected): |
Based on the snippet: <|code_start|>
def test_check_git_filemode_passing(tmpdir):
with tmpdir.as_cwd():
cmd_output('git', 'init', '.')
f = tmpdir.join('f')
f.write('#!/usr/bin/env bash')
f_path = str(f)
cmd_output('chmod', '+x', f_path)
cmd_output('git', 'add', f_pat... | with tmpdir.as_cwd(): |
Continue the code snippet: <|code_start|>from __future__ import annotations
def test_check_git_filemode_passing(tmpdir):
with tmpdir.as_cwd():
cmd_output('git', 'init', '.')
<|code_end|>
. Use current file imports:
import os
import pytest
from pre_commit_hooks.check_shebang_scripts_are_executable imp... | f = tmpdir.join('f') |
Predict the next line for this snippet: <|code_start|>from __future__ import annotations
TESTS = (
# Base cases
("''", "''", 0),
<|code_end|>
with the help of current file imports:
import textwrap
import pytest
from pre_commit_hooks.string_fixer import main
and context from other files:
# Path: pre_comm... | ('""', "''", 1), |
Predict the next line after this snippet: <|code_start|> 'PRE_COMMIT_TO_REF' in os.environ
):
diff_arg = '...'.join((
os.environ['PRE_COMMIT_FROM_REF'],
os.environ['PRE_COMMIT_TO_REF'],
))
else:
diff_arg = '--staged'
added_diff = cmd_output(
'gi... | if __name__ == '__main__': |
Based on the snippet: <|code_start|>from __future__ import annotations
def test_failure(tmpdir):
f = tmpdir.join('f.txt')
f.write_text('ohai', encoding='utf-8-sig')
assert fix_byte_order_marker.main((str(f),)) == 1
def test_success(tmpdir):
f = tmpdir.join('f.txt')
<|code_end|>
, predict the immedi... | f.write_text('ohai', encoding='utf-8') |
Given snippet: <|code_start|> temp_git_dir.mkdir('dir').join('x').write('foo')
temp_git_dir.join('DIR').write('foo')
cmd_output('git', 'add', '-A')
assert find_conflicting_filenames([]) == 1
def test_added_file_not_in_pre_commits_list(temp_git_dir):
with temp_git_dir.as_cwd():
... | temp_git_dir.mkdir('dir').join('x').write('foo') |
Next line prediction: <|code_start|> temp_git_dir.join('f.py').write("print('hello world')")
cmd_output('git', 'add', 'f.py')
assert find_conflicting_filenames(['f.py']) == 0
def test_adding_something_with_conflict(temp_git_dir):
with temp_git_dir.as_cwd():
temp_git_dir.join('f.py'... | temp_git_dir.join('X').write('foo') |
Using the snippet: <|code_start|>
@skip_win32 # pragma: win32 no cover
def test_adding_files_with_conflicting_deep_directories(temp_git_dir):
with temp_git_dir.as_cwd():
temp_git_dir.mkdir('x').mkdir('y').join('z').write('foo')
temp_git_dir.join('X').write('foo')
cmd_output('git', 'add', '... | def test_file_conflicts_with_committed_file(temp_git_dir): |
Using the snippet: <|code_start|> temp_git_dir.join('X').write('foo')
cmd_output('git', 'add', '-A')
assert find_conflicting_filenames([]) == 1
@skip_win32 # pragma: win32 no cover
def test_adding_file_with_conflicting_directory(temp_git_dir):
with temp_git_dir.as_cwd():
temp_git_... | temp_git_dir.join('F.py').write("print('hello world')") |
Here is a snippet: <|code_start|>
TEST_SYMLINK = 'test_symlink'
TEST_SYMLINK_TARGET = '/doesnt/really/matters'
TEST_FILE = 'test_file'
TEST_FILE_RENAMED = f'{TEST_FILE}_renamed'
@pytest.fixture
def repo_with_destroyed_symlink(tmpdir):
source_repo = tmpdir.join('src')
os.makedirs(source_repo, exist_ok=True)
... | assert not os.path.islink(test_repo.join(TEST_SYMLINK)) |
Predict the next line after this snippet: <|code_start|>from __future__ import annotations
TEST_SYMLINK = 'test_symlink'
TEST_SYMLINK_TARGET = '/doesnt/really/matters'
TEST_FILE = 'test_file'
TEST_FILE_RENAMED = f'{TEST_FILE}_renamed'
@pytest.fixture
def repo_with_destroyed_symlink(tmpdir):
source_repo = tmpd... | os.symlink(TEST_SYMLINK_TARGET, TEST_SYMLINK) |
Continue the code snippet: <|code_start|>from __future__ import annotations
TEST_SYMLINK = 'test_symlink'
TEST_SYMLINK_TARGET = '/doesnt/really/matters'
TEST_FILE = 'test_file'
TEST_FILE_RENAMED = f'{TEST_FILE}_renamed'
@pytest.fixture
def repo_with_destroyed_symlink(tmpdir):
source_repo = tmpdir.join('src')
... | with source_repo.as_cwd(): |
Predict the next line after this snippet: <|code_start|> '{filename}:3 Module docstring appears after code '
'(code seen on line 1).\n',
),
# String literals in expressions are ok.
(b'x = "foo"\n', 0, ''),
)
all_tests = pytest.mark.parametrize(
('contents', 'expected', 'expected_out'), ... | f.write_binary(contents) |
Here is a snippet: <|code_start|>from __future__ import annotations
@pytest.mark.parametrize(
('filename', 'expected_retval'), (
('bad_json.notjson', 1),
('bad_json_latin1.nonjson', 1),
('ok_json.json', 0),
('duplicate_key_json.notjson', 1),
),
<|code_end|>
. Write the next l... | ) |
Based on the snippet: <|code_start|>from __future__ import annotations
@pytest.mark.parametrize(
('filename', 'expected_retval'), (
('bad_json.notjson', 1),
('bad_json_latin1.nonjson', 1),
('ok_json.json', 0),
('duplicate_key_json.notjson', 1),
),
)
def test_main(capsys, file... | def test_non_utf8_file(tmpdir): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.