Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the following code snippet before the placeholder: <|code_start|># MONGO
#
# ================================================
def get_collection_pairs(db, args):
if args.collection1 and args.collection2:
print_single_pair_info(args.collection1, args.collection2)
return [(a... | mongodb.index(db, c, fields) |
Based on the snippet: <|code_start|># 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.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCL... | zip_files = list_files(input, ['zip']) |
Given snippet: <|code_start|> '''
Converts ABI or AB1 files to FASTA format.
Args:
input (str): Path to a file or directory containing abi/ab1 files or
zip archives of abi/ab1 files
output (str): Path to a directory for the output FASTA files
'''
direcs = [input, ]
... | make_dir(out_path) |
Next line prediction: <|code_start|>
data: Can be one of three things:
1) Path to a single file
2) Path to a directory
3) A list of one or more paths to files or directories
compressed_file (str): Path to the compressed file. Required.
s3_path (str): The ... | logger = log.get_logger('s3') |
Continue the code snippet: <|code_start|>def request(method, url, **kwargs):
try:
kwargs['slug'] = 'Pyston - file download'
except ImportError:
return request(method, url, **kwargs)
class RequestDataTooBig(SuspiciousOperation):
pass
class InvalidResponseStatusCode(SuspiciousOperation):
... | known_extensions = [ext for exts, name in settings.DEFAULT_FILENAMES for ext in exts] |
Next line prediction: <|code_start|> assert_equal(len(self.deserialize(resp)), min(max(int(resp['x-total']) - 2, 0), 5))
querystring = {'_offset': '2', '_base': '-5'}
resp = self.get('%s?%s' % (self.USER_API_URL, urlencode(querystring)))
assert_http_bad_request(resp)
querystring... | user = UserFactory() |
Continue the code snippet: <|code_start|>
querystring = {'_offset': '2', '_base': '-5'}
resp = self.get('%s?%s' % (self.USER_API_URL, urlencode(querystring)))
assert_http_bad_request(resp)
querystring = {'_offset': '-2', '_base': '5'}
resp = self.get('%s?%s' % (self.USER_API_URL... | [issue.watched_by.add(user) for issue in (IssueFactory() for _ in range(10))] |
Continue the code snippet: <|code_start|>
class CompatibilityTestCase(TestCase):
def test_is_relation(self):
assert_true(is_relation(Issue, 'watched_by'))
assert_true(is_relation(Issue, 'created_by'))
assert_true(is_relation(Issue, 'solver'))
assert_true(is_relation(Issue, 'lea... | assert_false(is_one_to_one(Issue, 'watched_by')) |
Here is a snippet: <|code_start|>
def test_is_one_to_one(self):
assert_false(is_one_to_one(Issue, 'watched_by'))
assert_false(is_one_to_one(Issue, 'created_by'))
assert_true(is_one_to_one(Issue, 'solver'))
assert_true(is_one_to_one(Issue, 'leader'))
assert_false(is_one_to_one... | assert_true(is_many_to_many(Issue, 'watched_by')) |
Given the following code snippet before the placeholder: <|code_start|>
def test_is_relation(self):
assert_true(is_relation(Issue, 'watched_by'))
assert_true(is_relation(Issue, 'created_by'))
assert_true(is_relation(Issue, 'solver'))
assert_true(is_relation(Issue, 'leader'))
... | assert_false(is_many_to_one(Issue, 'watched_by')) |
Predict the next line after this snippet: <|code_start|>
def test_is_reverse_one_to_one(self):
assert_false(is_reverse_one_to_one(Issue, 'watched_by'))
assert_false(is_reverse_one_to_one(Issue, 'created_by'))
assert_false(is_reverse_one_to_one(Issue, 'solver'))
assert_false(is_revers... | assert_false(is_reverse_many_to_many(Issue, 'watched_by')) |
Next line prediction: <|code_start|>
def test_is_many_to_many(self):
assert_true(is_many_to_many(Issue, 'watched_by'))
assert_false(is_many_to_many(Issue, 'created_by'))
assert_false(is_many_to_many(Issue, 'solver'))
assert_false(is_many_to_many(Issue, 'leader'))
assert_false... | assert_false(is_reverse_many_to_one(Issue, 'watched_by')) |
Next line prediction: <|code_start|>
def test_is_many_to_one(self):
assert_false(is_many_to_one(Issue, 'watched_by'))
assert_true(is_many_to_one(Issue, 'created_by'))
assert_false(is_many_to_one(Issue, 'solver'))
assert_false(is_many_to_one(Issue, 'leader'))
assert_false(is_m... | assert_false(is_reverse_one_to_one(Issue, 'watched_by')) |
Using the snippet: <|code_start|>
def test_is_reverse_many_to_one(self):
assert_false(is_reverse_many_to_one(Issue, 'watched_by'))
assert_false(is_reverse_many_to_one(Issue, 'created_by'))
assert_false(is_reverse_many_to_one(Issue, 'solver'))
assert_false(is_reverse_many_to_one(Issue... | assert_equal(get_model_from_relation(Issue, 'watched_by'), User) |
Continue the code snippet: <|code_start|>
def test_is_reverse_many_to_many(self):
assert_false(is_reverse_many_to_many(Issue, 'watched_by'))
assert_false(is_reverse_many_to_many(Issue, 'created_by'))
assert_false(is_reverse_many_to_many(Issue, 'solver'))
assert_false(is_reverse_many_... | assert_equal(get_model_from_relation_or_none(Issue, 'watched_by'), User) |
Here is a snippet: <|code_start|>
def test_get_model_from_relation(self):
assert_equal(get_model_from_relation(Issue, 'watched_by'), User)
assert_equal(get_model_from_relation(Issue, 'created_by'), User)
assert_equal(get_model_from_relation(Issue, 'solver'), User)
assert_equal(get_mo... | assert_equal(get_reverse_field_name(Issue, 'watched_by'), 'watched_issues') |
Given the code snippet: <|code_start|>
class DynamoSorter(BaseSorter):
def get_order_term(self):
return self.direction == DIRECTION.ASC
<|code_end|>
, generate the next line using the imports in this file:
from pyston.order.sorters import BaseSorter
from pyston.order.managers import BaseParserModelOrde... | class DynamoOrderManager(BaseParserModelOrderManager): |
Next line prediction: <|code_start|>
class CountIssuesPerUserTable(Serializable):
def serialize(self, serialization_format, **kwargs):
return [
{
'email': user.email,
'created_issues_count': user.created_issues.count(),
}
for user in Use... | class CountWatchersPerIssue(SerializableObj): |
Given snippet: <|code_start|>
class CountIssuesPerUserTable(Serializable):
def serialize(self, serialization_format, **kwargs):
return [
{
'email': user.email,
'created_issues_count': user.created_issues.count(),
}
<|code_end|>
, continue by predict... | for user in User.objects.all() |
Given snippet: <|code_start|>class FilterParser:
"""
Abstract filter parser.
"""
def parse(self, request):
"""
:param request: Django HTTP request.
:return: returns conditions tree or None.
"""
raise NotImplementedError
class DefaultFilterParser(FilterParser):
... | '=': OPERATORS.EQ, |
Using the snippet: <|code_start|> '>=',
'<=',
'>',
'<',
'[a-z]+'
)
OPERATORS_MAPPING = {
'=': OPERATORS.EQ,
'!=': OPERATORS.NEQ,
'<': OPERATORS.LT,
'>': OPERATORS.GT,
'>=': OPERATORS.GTE,
'<=': OPERATORS.LTE,
}
VALUE_... | if len(term) == 2 and term[0] == LOGICAL_OPERATORS.NOT: |
Using the snippet: <|code_start|>
class ModelRequestedFieldsManager:
parser = None
def get_requested_fields(self, resource, request):
try:
parsed_requested_rfs = self.parser.parse(request)
if parsed_requested_rfs is None:
return None
else:
... | except RestException as ex: |
Here is a snippet: <|code_start|>
class ModelRequestedFieldsManager:
parser = None
def get_requested_fields(self, resource, request):
try:
parsed_requested_rfs = self.parser.parse(request)
if parsed_requested_rfs is None:
return None
else:
... | parser = DefaultRequestedFieldsParser() |
Here is a snippet: <|code_start|>
def merge_iterable(a, b):
c = list(a) + list(b)
return sorted(set(c), key=lambda x: c.index(x))
class RestOptions(Options):
model_class = models.Model
meta_class_name = 'RestMeta'
meta_name = '_rest_meta'
attributes = {}
def __init__(self, model):
... | pk_field_name = get_last_parent_pk_field_name(model) |
Predict the next line after this snippet: <|code_start|>
class DirectSerializationTestCase(TestCase):
def test_serialization(self):
for i in range(10):
User.objects.create(is_superuser=True, email='test{}@test.cz'.format(i))
<|code_end|>
using the current file's imports:
import json
im... | assert_true(isinstance(json.loads((serialize(User.objects.all()))), list)) |
Given snippet: <|code_start|>
FOO_DOMAIN = 'http://foo.pyston.net'
BAR_DOMAIN = 'http://bar.pyston.net'
class CorsTestCase(PystonTestCase):
@override_settings(PYSTON_CORS=False)
@data_consumer('get_users_data')
def test_with_turned_off_cors_headers_is_not_included(self, number, data):
resp =... | assert_false(resp.has_header(ACCESS_CONTROL_ALLOW_ORIGIN)) |
Based on the snippet: <|code_start|>
FOO_DOMAIN = 'http://foo.pyston.net'
BAR_DOMAIN = 'http://bar.pyston.net'
class CorsTestCase(PystonTestCase):
@override_settings(PYSTON_CORS=False)
@data_consumer('get_users_data')
def test_with_turned_off_cors_headers_is_not_included(self, number, data):
... | assert_false(resp.has_header(ACCESS_CONTROL_EXPOSE_HEADERS)) |
Given the code snippet: <|code_start|>
FOO_DOMAIN = 'http://foo.pyston.net'
BAR_DOMAIN = 'http://bar.pyston.net'
class CorsTestCase(PystonTestCase):
@override_settings(PYSTON_CORS=False)
@data_consumer('get_users_data')
def test_with_turned_off_cors_headers_is_not_included(self, number, data):
... | assert_false(resp.has_header(ACCESS_CONTROL_ALLOW_CREDENTIALS)) |
Based on the snippet: <|code_start|>
FOO_DOMAIN = 'http://foo.pyston.net'
BAR_DOMAIN = 'http://bar.pyston.net'
class CorsTestCase(PystonTestCase):
@override_settings(PYSTON_CORS=False)
@data_consumer('get_users_data')
def test_with_turned_off_cors_headers_is_not_included(self, number, data):
... | assert_false(resp.has_header(ACCESS_CONTROL_ALLOW_HEADERS)) |
Given the code snippet: <|code_start|>
FOO_DOMAIN = 'http://foo.pyston.net'
BAR_DOMAIN = 'http://bar.pyston.net'
class CorsTestCase(PystonTestCase):
@override_settings(PYSTON_CORS=False)
@data_consumer('get_users_data')
def test_with_turned_off_cors_headers_is_not_included(self, number, data):
... | assert_false(resp.has_header(ACCESS_CONTROL_ALLOW_METHODS)) |
Based on the snippet: <|code_start|>
FOO_DOMAIN = 'http://foo.pyston.net'
BAR_DOMAIN = 'http://bar.pyston.net'
class CorsTestCase(PystonTestCase):
@override_settings(PYSTON_CORS=False)
@data_consumer('get_users_data')
def test_with_turned_off_cors_headers_is_not_included(self, number, data):
... | assert_false(resp.has_header(ACCESS_CONTROL_MAX_AGE)) |
Here is a snippet: <|code_start|>
class ExtraResourceTestCase(PystonTestCase):
def test_not_supported_message_for_put_post_and_delete(self):
resp = self.put(self.EXTRA_API_URL, data={})
assert_http_method_not_allowed(resp)
resp = self.post(self.EXTRA_API_URL, data={})
assert_http... | [IssueFactory(solver=UserFactory()) for _ in range(10)] |
Given snippet: <|code_start|>
class ExtraResourceTestCase(PystonTestCase):
def test_not_supported_message_for_put_post_and_delete(self):
resp = self.put(self.EXTRA_API_URL, data={})
assert_http_method_not_allowed(resp)
resp = self.post(self.EXTRA_API_URL, data={})
assert_http_met... | [IssueFactory(solver=UserFactory()) for _ in range(10)] |
Given the following code snippet before the placeholder: <|code_start|>
class DynamoCursorBasedPaginator(BasePaginator):
def __init__(self, default_base=20, max_base=100):
self.default_base = default_base
self.max_base = max_base
def get_response(self, qs, request):
base = self._get... | raise RestException(ugettext('Base must lower or equal to {}').format(self.max_base)) |
Predict the next line for this snippet: <|code_start|>
class DynamoCursorBasedPaginator(BasePaginator):
def __init__(self, default_base=20, max_base=100):
self.default_base = default_base
self.max_base = max_base
def get_response(self, qs, request):
base = self._get_base(request)
... | return HeadersResponse( |
Using the snippet: <|code_start|> return r
elif isinstance(data, datetime.date):
return data.isoformat()
elif isinstance(data, datetime.time):
if is_aware(data):
raise ValueError("JSON can't represent timezone-aware times.")
r = data.isoformat()
if data.microse... | except FieldDoesNotExist: |
Here is a snippet: <|code_start|>
if header:
for col, head in enumerate(header):
ws.write(row, col, force_text(head))
row += 1
for data_row in data:
for col, val in enumerate(data_row):
if isinstance(val, da... | django_settings.MEDIA_ROOT: settings.MEDIA_URL, |
Using the snippet: <|code_start|>
class OrderTestCase(PystonTestCase):
def test_order_by_decorator(self):
[IssueFactory(description=str(i)) for i in range(10)]
data = self.deserialize(self.get(build_url(self.ISSUE_API_URL, order='short_description')))
assert_equal([v['short_description'] ... | user1 = UserFactory() |
Using the snippet: <|code_start|>
class UserIDFilter(BaseDynamoFilter):
allowed_operators = (OPERATORS.EQ,)
def get_filter_term(self, value, operator_slug, request):
return {'user_id__startswith': value}
<|code_end|>
, determine the next line of code. You have imports:
from pyston.filters.filters... | class CommentDynamoResource(BaseDynamoResource): |
Here is a snippet: <|code_start|>
class UserIDFilter(BaseDynamoFilter):
allowed_operators = (OPERATORS.EQ,)
def get_filter_term(self, value, operator_slug, request):
return {'user_id__startswith': value}
class CommentDynamoResource(BaseDynamoResource):
<|code_end|>
. Write the next line using the... | model = Comment |
Here is a snippet: <|code_start|> assert_equal(len(self.deserialize(resp)), 5)
resp = self.get(
build_url(
self.ISSUE_API_URL,
filter='(created_at__day = "{}" AND created_at__year = "{}") OR (created_at > "{}")'.format(
now.day + 1, now.yea... | user = UserFactory(is_superuser=False) |
Continue the code snippet: <|code_start|>
class FilterTestCase(PystonTestCase):
def test_override_extra_filter_fields(self):
assert_http_bad_request(self.get(build_url(self.USER_API_URL, filter='created_at__gt="1.1.1980"')))
assert_valid_JSON_response(
self.get(build_url(self.USER_AP... | [IssueFactory() for _ in range(5)] |
Given the code snippet: <|code_start|> )
class WatchedIssuesCountMethodFilter(IntegerFilterMixin, SimpleMethodEqualFilter):
def get_filter_term(self, value, operator, request):
return {
'pk__in': User.objects.annotate(
watched_issues_count=Count('watched_issues')
... | @filter_class(WatchedIssuesCountMethodFilter) |
Based on the snippet: <|code_start|>
class WatchedIssuesCountMethodFilter(IntegerFilterMixin, SimpleMethodEqualFilter):
def get_filter_term(self, value, operator, request):
return {
'pk__in': User.objects.annotate(
watched_issues_count=Count('watched_issues')
).filt... | @sorter_class(WatchedIssuesCountSorter) |
Predict the next line for this snippet: <|code_start|>
class OnlyContainsStringFieldFilter(StringFieldFilter):
operators = (
(OPERATORS.CONTAINS, CONTAINS),
)
<|code_end|>
with the help of current file imports:
from django.db import models
from django.db.models import Count
from django.utils.tran... | class WatchedIssuesCountMethodFilter(IntegerFilterMixin, SimpleMethodEqualFilter): |
Based on the snippet: <|code_start|>
class OnlyContainsStringFieldFilter(StringFieldFilter):
operators = (
(OPERATORS.CONTAINS, CONTAINS),
)
<|code_end|>
, predict the immediate next line with the help of imports:
from django.db import models
from django.db.models import Count
from django.utils.tr... | class WatchedIssuesCountMethodFilter(IntegerFilterMixin, SimpleMethodEqualFilter): |
Next line prediction: <|code_start|>
class OnlyContainsStringFieldFilter(StringFieldFilter):
operators = (
(OPERATORS.CONTAINS, CONTAINS),
)
class WatchedIssuesCountMethodFilter(IntegerFilterMixin, SimpleMethodEqualFilter):
def get_filter_term(self, value, operator, request):
return {
... | class WatchedIssuesCountSorter(ExtraDjangoSorter): |
Given the following code snippet before the placeholder: <|code_start|>'''
class Text(object):
template = Template("""&${code} = ${description}
#project: ${project}
#atf: lang ${language}
% for child in children:
${child.serialize()}
% endfor""")
def __init__(self):
self.children = []
self.... | return [x for x in self.children if isinstance(x, OraccObject)] |
Given the code snippet: <|code_start|>(at your option) any later version.
PyORACC 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... | self.texts.append(AtfFile(content, self.atftype)) |
Given snippet: <|code_start|>'''
Copyright 2015, 2016 University College London.
This file is part of PyORACC.
PyORACC 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... | class OraccNamedObject(OraccObject): |
Based on the snippet: <|code_start|>
def check_and_process(pathname, atftype, verbose=False):
mode = os.stat(pathname)[ST_MODE]
if S_ISREG(mode) and pathname.lower().endswith('.atf'):
# It's a file, call the callback function
if verbose:
click.echo('Info: Parsing {0}.'.format(pathn... | check_atf(pathname, atftype, verbose) |
Continue the code snippet: <|code_start|># encoding: utf-8
"""
@author: monitor1379
@contact: yy4f5da2@hotmail.com
@site: www.monitor1379.com
@version: 1.0
@license: GNU General Public License(Version 3)
@file: check_gradient.py
@time: 2016/10/4 9:59
"""
def check_LinearGate():
x = np.random.randn(10, 4).asty... | grad_x = eval_numerical_gradient_array(LinearGate.forward, x, dy) |
Using the snippet: <|code_start|> x = np.random.randn(10, 4).astype(np.double)
dy = np.random.randn(10, 4).astype(np.double)
grad_x = eval_numerical_gradient_array(LinearGate.forward, x, dy)
dx = LinearGate.backward(x, dy)
print grad_x
print dx
print np.sum(np.abs(grad_x - dx))
def check_M... | print sum_abs_err(grad_x, dx) |
Given snippet: <|code_start|>@site: www.monitor1379.com
@version: 1.0
@license: GNU General Public License(Version 3)
@file: objectives.py
@time: 2016/9/11 12:07
损失函数
"""
class MeanSquareError:
@staticmethod
def loss(y_real, y_pred):
return np.mean(np.square(y_real - y_pred))
@staticmethod
... | categorical_y_real = np_utils.to_categorical(y_real) |
Predict the next line for this snippet: <|code_start|># encoding: utf-8
"""
@author: monitor1379
@contact: yy4f5da2@hotmail.com
@site: www.monitor1379.com
@version: 1.0
@license: GNU General Public License(Version 3)
@file: activations.py
@time: 2016/10/9 20:29
"""
<|code_end|>
with the help of current file imp... | _dict = {'sigmoid': SigmoidGate, |
Based on the snippet: <|code_start|># encoding: utf-8
"""
@author: monitor1379
@contact: yy4f5da2@hotmail.com
@site: www.monitor1379.com
@version: 1.0
@license: GNU General Public License(Version 3)
@file: activations.py
@time: 2016/10/9 20:29
"""
_dict = {'sigmoid': SigmoidGate,
<|code_end|>
, predict the immed... | 'tanh': TanhGate, |
Predict the next line after this snippet: <|code_start|># encoding: utf-8
"""
@author: monitor1379
@contact: yy4f5da2@hotmail.com
@site: www.monitor1379.com
@version: 1.0
@license: GNU General Public License(Version 3)
@file: activations.py
@time: 2016/10/9 20:29
"""
_dict = {'sigmoid': SigmoidGate,
'ta... | 'relu': ReLUGate, |
Given snippet: <|code_start|># encoding: utf-8
"""
@author: monitor1379
@contact: yy4f5da2@hotmail.com
@site: www.monitor1379.com
@version: 1.0
@license: GNU General Public License(Version 3)
@file: activations.py
@time: 2016/10/9 20:29
"""
_dict = {'sigmoid': SigmoidGate,
'tanh': TanhGate,
're... | 'linear': LinearGate, |
Here is a snippet: <|code_start|># encoding: utf-8
"""
@author: monitor1379
@contact: yy4f5da2@hotmail.com
@site: www.monitor1379.com
@version: 1.0
@license: GNU General Public License(Version 3)
@file: activations.py
@time: 2016/10/9 20:29
"""
_dict = {'sigmoid': SigmoidGate,
'tanh': TanhGate,
... | 'softmax': SoftmaxGate, |
Predict the next line after this snippet: <|code_start|> plt.scatter(epoch, training_acc, marker='*')
if validation_acc:
plt.plot(epoch, validation_acc, label='validation')
plt.scatter(epoch, validation_acc, marker='*')
plt.legend(loc=0)
# 绘画损失函数值随着训练周期的折线图
... | y = np_utils.to_categorical(y) |
Given the following code snippet before the placeholder: <|code_start|> for i in xrange(batch_times): # 对于每次批量计算
batch_range = random_idx[i * mini_batch_size:(i + 1) * mini_batch_size]
batch_training_x = training_x[batch_range]
batch_training_y = training_y[ba... | bar = ProgressBar(total=n, width=20) |
Predict the next line for this snippet: <|code_start|> # 如果不存在bin文件夹,则解压mnist的gz压缩包
# 创建解压文件夹,存放地点为hamaa/datasets/mnist/bin
mnist_bin_dir = module_path + os.sep + 'mnist' + os.sep + 'bin' + os.sep
# 检查是否缺失解压后的数据文件
miss_bin_file = False
for filename in filenames:
file_path = mnist_bin_dir... | training_x = mnist_decoder.load_train_images(num_data=nb_training) |
Continue the code snippet: <|code_start|># encoding: utf-8
"""
@author: monitor1379
@contact: yy4f5da2@hotmail.com
@site: www.monitor1379.com
@version: 1.0
@license: GNU General Public License(Version 3)
@file: datasets.py
@time: 2016/9/11 9:00
数据集加载文件
"""
def load_or_data(one_hot=True):
x = np.array([[0, 0... | y = np_utils.to_one_hot(y, 2) |
Continue the code snippet: <|code_start|>
class RemoveEntityOnDeath(Leaf):
"""
Will remove the parent from the dungeon when parent Entity dies.
"""
def __init__(self):
super(RemoveEntityOnDeath, self).__init__()
self.component_type = "remove_on_death"
def after_tick(self, time):
... | msg.send_visual_message(self.parent.entity_messages.death, self.parent.position.value) |
Here is a snippet: <|code_start|>
# Arguments:
SOURCE_ENTITY = "source_entity"
TARGET_ENTITY = "target_entity"
GAME_STATE = "game_state"
TARGET_POSITION = "target_position"
EQUIPMENT_SLOT = "equipment_slot"
ACTION = "action"
DESTINATION = "destination" #TODO: Replace with target_position?
<|code_end|>
. Write the n... | class Action(Leaf): |
Based on the snippet: <|code_start|>
class TestComposition(unittest.TestCase):
def setUp(self):
pass
def test_other_side_of_point_direction_should_return_right_when_target_on_left(self):
"""
1, 2, r
.....
.12r.
.....
"""
p1 = (-1, 0)
p2 =... | self.assertEqual(other_side_of_point_direction(p1, p2), expected_r) |
Using the snippet: <|code_start|> """
p1 = (1, -1)
p2 = (0, 0)
expected_r = (-1, 1)
self.assertEqual(other_side_of_point_direction(p1, p2), expected_r)
def test_other_side_of_point_direction_should_return_down_left_when_target_up_right(self):
"""
1, 2, r
... | self.assertEqual(other_side_of_point(p1, p2), expected_r) |
Given the code snippet: <|code_start|>
__author__ = 'co'
def start_accept_reject_prompt(state_stack, game_state, message):
prompt = menu.AcceptRejectPrompt(state_stack, message)
game_state.start_prompt(state.UIState(prompt))
return prompt.result
<|code_end|>
, generate the next line using the imports in... | class PromptPlayer(Leaf): |
Continue the code snippet: <|code_start|>
class TestComposition(unittest.TestCase):
def setUp(self):
pass
def test_get_horizontal_with_same_start_and_destination_is_length_one(self):
<|code_end|>
. Use current file imports:
import unittest
from util import get_path
and context (classes, functions, ... | path = get_path((2, 4), (2, 4)) |
Given snippet: <|code_start|> RING = 3
AMULET = 4
# Weapons
MELEE_WEAPON = 5
RANGED_WEAPON = 6
ALL = [HEADGEAR, ARMOR, BOOTS,
RING, AMULET, MELEE_WEAPON, RANGED_WEAPON]
class EquipmentSlots(object):
# Weapons
MELEE_WEAPON = EquipmentSlot("Melee Weapon", EquipmentTypes.MEL... | class Equipment(Leaf): |
Given the following code snippet before the placeholder: <|code_start|> # Do not shuffle public constants!
directions = list(direction.DIRECTIONS)
random.shuffle(directions)
for d in directions:
destination = geometry.add_2d(d, new_position)
if self.try_move(de... | self.parent.set_child(DungeonLevel()) |
Predict the next line after this snippet: <|code_start|> Moves parent to new position, assumes that it fits there.
"""
self._remove_from_old_tile()
dungeon_level.get_tile(new_position).add(self.parent)
self.parent.position.value = new_position
if not self.has_sibling("dung... | return len(tile.game_pieces[piece_type.value]) < max_instances_of_composite_on_tile(self.parent) |
Here is a snippet: <|code_start|> return False
def try_attack(self, position):
entity = (self.parent.dungeon_level.value.get_tile(position).get_first_entity())
if self.parent.has("melee_attacker") and entity:
return self.parent.melee_attacker.try_hit(entity)
def try_move_or_... | if entity.intelligence.value == IntelligenceLevel.PLANT: |
Predict the next line for this snippet: <|code_start|> self._remove_from_old_tile()
piece_type = self.parent.game_piece_type.value
new_place = new_tile.game_pieces[piece_type]
for piece in new_place:
piece.mover.try_remove_from_dungeon()
return self.try_move(new_positi... | if terrain_to_pass.has("is_chasm") and status_flags.has_status(StatusFlags.FLYING): |
Predict the next line after this snippet: <|code_start|> self.game_state = game_state
def get_dungeon_level(self, depth):
if depth >= self.level_count:
self.game_state.has_won = True
return None
while len(self._dungeon_levels) <= depth:
self._dungeon_level... | monster.set_child(TryPutToSleep()) |
Here is a snippet: <|code_start|>
class Dungeon(object):
def __init__(self, game_state):
self.level_count = 10
self._dungeon_levels = [None]
self.game_state = game_state
def get_dungeon_level(self, depth):
if depth >= self.level_count:
self.game_state.has_won = True... | monsters = from_table_pick_n_items_for_depth(dungeon_table, monsters_to_spawn, |
Predict the next line after this snippet: <|code_start|>
class Dungeon(object):
def __init__(self, game_state):
self.level_count = 10
self._dungeon_levels = [None]
self.game_state = game_state
def get_dungeon_level(self, depth):
if depth >= self.level_count:
self.ga... | monsters = from_table_pick_n_items_for_depth(dungeon_table, monsters_to_spawn, |
Next line prediction: <|code_start|> self.game_state.draw_loading_screen("Generating Dungeon...")
size = 600 + depth * 20
dungeon_level = time_it("dungeon_level_generation",
(lambda: dungeongenerator.generate_dungeon_floor(size, depth)))
minimum_monsters =... | equipments = from_table_pick_n_items_for_depth(dungeon_equipment_table, |
Predict the next line for this snippet: <|code_start|> dungeon_level = time_it("dungeon_level_generation",
(lambda: dungeongenerator.generate_dungeon_floor(size, depth)))
minimum_monsters = int(4 + depth * 1.2)
monsters_to_spawn = random.randrange(minimum_monsters,... | usable_items = from_table_pick_n_items_for_depth(dungeon_usable_item_table, |
Based on the snippet: <|code_start|>
class Dungeon(object):
def __init__(self, game_state):
self.level_count = 10
self._dungeon_levels = [None]
self.game_state = game_state
def get_dungeon_level(self, depth):
if depth >= self.level_count:
self.game_state.has_won = ... | dungeon_level = time_it("dungeon_level_generation", |
Given the code snippet: <|code_start|>
class Tile(object):
def __init__(self):
self.game_pieces = {
<|code_end|>
, generate the next line using the imports in this file:
import colors
import compositecore
import frame
import terrain
from graphic import CharPrinter
from stats import GamePieceTypes, DataPoi... | GamePieceTypes.ENTITY: [], |
Predict the next line for this snippet: <|code_start|>
__author__ = 'co'
def load_first_game():
save_file = open(get_save_files()[0], 'rb')
print save_file
<|code_end|>
with the help of current file imports:
import cPickle as pickle
import os
from genericpath import isfile
from os import getcwd, listdir
fro... | game_state = time_it("load", (lambda: pickle.load(save_file))) |
Predict the next line for this snippet: <|code_start|>
def _get_walkable_neighbors(entity, position, dungeon_level):
result_positions = []
for direction_ in direction.DIRECTIONS:
neighbor_position = geo.add_2d(position, direction_)
try:
neighbor = dungeon_level.get_tile(neighbor_pos... | add_spoof_effect = AddSpoofChild(source_entity, DoNothingActor(), gametime.single_turn) |
Continue the code snippet: <|code_start|> neighbor_position = geo.add_2d(position, direction_)
try:
neighbor = dungeon_level.get_tile(neighbor_position)
if entity.mover.can_pass_terrain(neighbor.get_terrain()):
result_positions.append(neighbor_position)
exc... | add_spoof_effect = AddSpoofChild(source_entity, StunnedActor(), gametime.single_turn) |
Predict the next line for this snippet: <|code_start|>
def _get_walkable_neighbors(entity, position, dungeon_level):
result_positions = []
for direction_ in direction.DIRECTIONS:
neighbor_position = geo.add_2d(position, direction_)
try:
neighbor = dungeon_level.get_tile(neighbor_pos... | add_spoof_effect = AddSpoofChild(source_entity, DoNothingActor(), gametime.single_turn) |
Based on the snippet: <|code_start|> except IndexError:
pass
return result_positions
def _get_walkable_neighbors_or_unseen(position, entity, dungeon_level):
result_positions = []
for direction_ in direction.DIRECTIONS:
neighbor_position = geo.add_2d(position, direction_)
... | add_spoof_effect = AddSpoofChild(source_entity, ImmobileStepper(), gametime.single_turn) |
Using the snippet: <|code_start|>
class StatusDescription(object):
def __init__(self, name, graphic_char, description):
self.graphic_char = graphic_char
self.name = name
self.description = description
<|code_end|>
, determine the next line of code. You have imports:
import colors
import ... | class StatusDescriptionBar(Leaf): |
Using the snippet: <|code_start|>
class StatusDescription(object):
def __init__(self, name, graphic_char, description):
self.graphic_char = graphic_char
self.name = name
self.description = description
class StatusDescriptionBar(Leaf):
def __init__(self):
super(StatusDescriptio... | FIRE_STATUS_DESCRIPTION = StatusDescription("Fire", GraphicChar(None, colors.RED, icon.FIRE), "You are standing in flames, taking heavy fire damage each turn spent in the flames.") |
Given the code snippet: <|code_start|>
__author__ = 'co'
STEP_NEXT_TO_ENEMY_TRIGGER_TAG = "step_next_to_enemy_trigger"
ENEMY_STEPPING_NEXT_TO_ME_TRIGGER_TAG = "enemy_stepping_next_to_me_trigger"
ON_ATTACKED_TRIGGER_TAG = "on_attacked_trigger"
<|code_end|>
, generate the next line using the imports in this file:
fro... | class Trigger(Leaf): |
Given the code snippet: <|code_start|>
class InstantAnimation(object):
def __init__(self, game_state):
self.game_state = game_state
def run_animation(self):
pass
class MissileAnimation(InstantAnimation):
def __init__(self, game_state, symbol, color_fg, path):
super(MissileAnimati... | console.flush() |
Predict the next line for this snippet: <|code_start|> console.flush()
def draw_missile_at_point(self, point):
x, y = self.camera.dungeon_to_screen_position(point)
console.set_color_fg((x, y), self.color_fg)
console.set_symbol((x, y), self.symbol)
def animate_flight(game_st... | GraphicChar(None, color_fg, icon.BIG_CENTER_DOT), |
Next line prediction: <|code_start|> if key in inputhandler.move_controls:
dx, dy = inputhandler.move_controls[key]
self.offset_cursor_position((dx * step_size, dy * step_size))
elif key in inputhandler.vi_move_controls:
dx, dy = inputhandler.vi_move_controls[key]
... | console.set_symbol(position, self.cursor_symbol) |
Using the snippet: <|code_start|> elif len(self._dirty_point_list) > 0:
for point in self._dirty_point_list:
x, y = point
self.update_dungeon_map_point(x, y)
self._dirty_point_list = []
self.update_fov()
def update_dungeon_map_point(self, x... | if message == CompositeMessage.DUNGEON_LEVEL_CHANGED: |
Here is a snippet: <|code_start|> sx, sy = self.parent.position.value
dx, dy = destination
libtcod.path_compute(self.path, sx, sy, dx, dy)
self.clear()
x, y = libtcod.path_walk(self.path, True)
while not x is None:
self.position_list.insert(0, (x, y))
... | console.set_symbol(camera.dungeon_to_screen_position(point), icon.FOOT_STEPS) |
Here is a snippet: <|code_start|>
class HealthModifier(Leaf):
def __init__(self):
super(HealthModifier, self).__init__()
self.component_type = "health_modifier"
def hurt(self, damage, entity=None, damage_types=[]):
"""
Damages the entity by reducing hp by damage.
"""
... | if DamageTypes.POISON in damage_types: |
Given the code snippet: <|code_start|> point_behind = self._get_point_behind_unless_solid(source_entity.position.value, 1, dungeon_level)
shape = shapegenerator.random_explosion_not_through_solid(point_behind, 2, dungeon_level)
for point in shape:
self.put_blood_on_til... | corpse = PoolOfBlood() |
Here is a snippet: <|code_start|> self.parent.health.hp.decrease(damage)
self._animate_hurt(damage_types)
if self.parent.health.is_dead():
self.parent.health.killer = entity
self._call_damage_taken_effect(damage, entity, damage_types)
return damage
def _animate_hu... | heart_graphic_char = GraphicChar(None, colors.RED, icon.HEALTH_GAIN_ICON) |
Continue the code snippet: <|code_start|> def effect(self, damage, source_entity, damage_types=[]):
pass
class ReflectDamageTakenEffect(DamageTakenEffect):
def __init__(self):
super(ReflectDamageTakenEffect, self).__init__()
self.component_type = "reflect_damage"
self.damage = 1... | self.parent.effect_queue.add(entityeffect.EffectRemover(self.parent, "paralyze", message=NO_LONGER_PARALYZED_MESSAGE)) |
Here is a snippet: <|code_start|>
def dungeon_to_screen_position(self, position):
return geo.add_2d(geo.sub_2d(position, self.camera_offset),
self.screen_position)
def screen_to_dungeon_position(self, position):
return geo.sub_2d(geo.add_2d(position, self.camera_offset... | console.set_color_bg((x, self.y_graze_edge[0]), colors.YELLOW) |
Given the code snippet: <|code_start|>
class DungeonCreatorVisualizer(state.State):
def __init__(self):
super(DungeonCreatorVisualizer, self).__init__()
self.dungeon_level = dgen.get_full_wall_dungeon(70, 55, 0)
self.camera = camera.Camera(geo.zero2d(), geo.zero2d(), self)
def fill_dun... | console.flush() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.