Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the following code snippet before the placeholder: <|code_start|>
class JobsView(browsers.ResourceBrowserView):
browser_class = project_browsers.ContainerBrowser
template_name = "disaster_recovery/jobs/browser.html"
@shield("Unable to get job", redirect='jobs:index')
def get_jobs_data(self):
... | if self.is_update(): |
Given the code snippet: <|code_start|># 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
#
# Unless required by applicable law or agreed to in... | def get_actions_in_job_data(self): |
Continue the code snippet: <|code_start|># -*- encoding: utf-8 -*-
#
# Copyright © 2018 Red Hat, Inc.
#
# 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/L... | measures=10, metrics=10, process=True)) |
Given snippet: <|code_start|># -*- encoding: utf-8 -*-
#
# Copyright © 2018 Red Hat, Inc.
#
# 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
#... | self.incoming, self.coord, self.storage, self.index, |
Continue the code snippet: <|code_start|>
def namedtuplefetchall(cursor):
"Return all rows from a cursor as a namedtuple"
desc = cursor.description
nt_result = namedtuple('Result', [col[0] for col in desc])
return [nt_result(*row) for row in cursor.fetchall()]
# Create your views here.
def weather_query(request,... | return redirect("home:welcome") |
Using the snippet: <|code_start|> messages.success(request, "Crop succesfully registered.")
return redirect("crop:detail")
context_data={
"crop_names" : all_crop_names,
}
return render(request,"register_crop.html",context_data)
def view_crops(request):
check = check_if_auth_user(request)
current_user = None... | return redirect("home:welcome") |
Given the code snippet: <|code_start|>
for person in result:
if person.user_id == temp_id:
if bcrypt.verify(temp_pwd, person.user_pwd):
messages.success(request, "Successful Login")
request = start_user_session(request, temp_id, 'F') # 'F' = Farmer
return redirect("home:welcome")
else:
mes... | if len(pwd) < 6: |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
# Create your views here.
def namedtuplefetchall(cursor):
"Return all rows from a cursor as a namedtuple"
desc = cursor.description
nt_result = namedtuple('Result', [col[0] fo... | messages.error(request, "Log In to see your profile") |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
# Create your views here.
def namedtuplefetchall(cursor):
"Return all rows from a cursor as a namedtuple"
desc = cursor.description
nt_result = namedtuple('Result', [col[0] for col in desc])
return [nt_result(*ro... | query = "SELECT * FROM User_farmer WHERE `User_farmer`.'user_id' = %s" |
Given the code snippet: <|code_start|> messages.error(request, "Perform Login first")
return redirect("home:welcome")
cursor = connection.cursor()
query = "SELECT * FROM post_post WHERE `post_post`.'post_id' = %s"
cursor.execute(query, [id, ])
result = namedtuplefetchall(cursor)
if not result:
messages.erro... | image = None |
Given the code snippet: <|code_start|> return [nt_result(*row) for row in cursor.fetchall()]
def remove_from_dir(dir_path, filename):
full_path = os.path.join(dir_path, filename)
if os.path.isfile(full_path):
os.remove(full_path)
#CRUD implemented here
def posts_create(request):
check = check_if_auth_user(reques... | try: |
Given the following code snippet before the placeholder: <|code_start|> image_read = image.read()
file_content = ContentFile(image_read)
# Iterate through the chunks.
for chunk in file_content.chunks():
fout.write(chunk)
fout.close()
image_64_encode = base64.encodestring(image_read)
cursor ... | return render(request, "create_edit_post.html", context_data) |
Given the code snippet: <|code_start|>
cursor.execute(query, [check, ])
result = namedtuplefetchall(cursor)
current_user = result[0]
if not current_user:
messages.error(request, "Please login first.")
return redirect("home:welcome")
if int(id) > 3:
messages.error(request, "This is not a searchable query... | if int(id) == 3: |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
# Register your models here.
class LocationModelAdmin(admin.ModelAdmin):
class Meta:
model = Location
list_display=["__unicode__"]
class WeatherModelAdmin(admin.ModelAdmin):
class Meta:
mod... | list_display=["__unicode__"] |
Based on the snippet: <|code_start|> u'î': ['I_CIRC'],
u'ï': ['I_UML'],
u'ð': ['ETH'],
u'ñ': ['N_TILDE'],
u'ò': ['O_GRAVE'],
u'ó': ['O_ACUTE'],
u'ô': ['O_CIRC'],
u'õ': ['O_TILDE'],
u'ö': ['O_UML'],
u'÷': ['DIVIDE'],
u'ø': ['O_SLASH'... | u'”': ['DOUBLE_QUOTE_RIGHT'], |
Given snippet: <|code_start|>
# Import common scripts
CWD = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, CWD)
sys.path.insert(0, os.path.normpath(os.path.join(CWD, '..', '..')))
# Import common shortcut mapper library
log = shmaplib.setuplog(os.path.join(CWD, 'output.log'))
def main():
parser = ... | log.setLevel(logging.INFO) |
Next line prediction: <|code_start|>
# Import common scripts
CWD = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, CWD)
sys.path.insert(0, os.path.normpath(os.path.join(CWD, '..', '..')))
# Import common shortcut mapper library
<|code_end|>
. Use current file imports:
(import sys
import os
import glob
i... | log = shmaplib.setuplog(os.path.join(CWD, 'output.log')) |
Next line prediction: <|code_start|>
# Import common scripts
CWD = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, CWD)
sys.path.insert(0, os.path.normpath(os.path.join(CWD, '..', '..')))
# Import common shortcut mapper library
log = shmaplib.setuplog(os.path.join(CWD, 'output.log'))
def main():
pa... | if args.verbose: |
Given snippet: <|code_start|>
# Import common scripts
CWD = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, CWD)
sys.path.insert(0, os.path.normpath(os.path.join(CWD, '..')))
# Import common shortcut mapper library
<|code_end|>
, continue by predicting the next line. Consider current file imports:
impor... | log = shmaplib.setuplog(os.path.join(CWD, 'output.log')) |
Given the following code snippet before the placeholder: <|code_start|>
def basename(self):
return self._path.basename()
def has_extension(self, extension=None):
return self._path.has_extension(extension)
def has_extension_from(self, candidates_extensions):
for any_extension in can... | or str(any_file.path()).startswith(str(path) + ".")] |
Continue the code snippet: <|code_start|> def is_file():
return True
def is_directory(self):
return not self.is_file()
@classmethod
def exists(cls):
return True
def is_missing(self):
return not self.exists()
def contains(self, content):
return self._con... | def has_extension(self, extension=None): |
Predict the next line after this snippet: <|code_start|> self._log("On command:" + str(token))
command = str(token)
command_name = command[1:]
if command_name not in self._definitions:
self._log("Unknown command '{}'.\n"
"\tCandidates are {}"
... | else: # Built-in commands |
Here is a snippet: <|code_start|>#!/usr/bin/env python
#
# This file is part of Flap.
#
# Flap 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 ... | tokens, |
Given the following code snippet before the placeholder: <|code_start|># 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 received a copy of the GNU General Public License
# a... | self.assertNotEqual( |
Using the snippet: <|code_start|>
class TokenTests(TestCase):
def setUp(self):
self._tokens = TokenFactory(SymbolTable.default())
self._token = self._tokens.character(Position(1, 1), "a")
def test_equals_itself(self):
self.assertEqual(self._token, self._token)
def test_equals_a_... | def test_differs_from_an_object_of_another_type(self): |
Predict the next line for this snippet: <|code_start|># (at your option) any later version.
#
# Flap 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 d... | self._token) |
Given the code snippet: <|code_start|> path = Path.fromText("C:\\Users\\franckc\\pub\\JOCC\\main.tex")
self.verify_parts(path, ["C:", "Users", "franckc", "pub",
"JOCC", "main.tex"])
def verify_parts(self, path, expectedParts, ):
parts = [each.fullname() for ... | if __name__ == "__main__": |
Given snippet: <|code_start|> self.assertEqual(path, ROOT / "Users" / "franckc" / "file.txt")
def test_parsing_directory(self):
path = Path.fromText("project/img/")
parts = [each.fullname() for each in path.parts()]
self.assertEqual(parts, ["project", "img"], "Wrong parts!")
de... | def test_is_absolute_on_windows_paths(self): |
Here is a snippet: <|code_start|> self.assertTrue(path.fullname() in gettempdir())
def test_path_to_file(self):
path = (ROOT / "test" / "source.tex")
self.assertEqual(path.container(), ROOT / "test")
self.assertEqual(path.fullname(), "source.tex")
def test_appending_a_path(self)... | def test_basename(self): |
Given snippet: <|code_start|>#
# Flap 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.
#
# Flap is distributed in the hope that it will ... | self.assertTrue(file.exists()) |
Predict the next line for this snippet: <|code_start|># Flap 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 received a c... | self.fileSystem.create_file(path, [1, 2, 3, 4]) |
Given the following code snippet before the placeholder: <|code_start|> self._verify(self._line + 1, 0, self._position.next_line())
def _verify(self, line, column, position):
self.assertEqual(line, position.line)
self.assertEqual(column, position.column)
def test_next_character(self):
... | self._position) |
Given the following code snippet before the placeholder: <|code_start|>#
# This file is part of Flap.
#
# Flap 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... | self.assertTrue(self._stream.is_empty) |
Predict the next line after this snippet: <|code_start|>class OSFileSystemTest(TestCase):
def setUp(self):
self.fileSystem = OSFileSystem()
self.path = TEMP / "flap_os" / "test.txt"
self.content = "blahblah blah"
self.fileSystem.deleteDirectory(TEMP / "flap_os")
self.fileSy... | file = self.createAndOpenTestFile() |
Next line prediction: <|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 Flap. If not, see <http://www.gnu.org/licenses/>.
#
class OSFileSystemTest(TestCase):... | file = self.createAndOpenTestFile() |
Next line prediction: <|code_start|> self._invocation.append_argument(
"options", [each for each in "[this is a text]"])
self._invocation.append([each for each in "----"])
self._invocation.append_argument(
"link", [each for each in "{link/to/a/file.tex}"])
self.ass... | self.assertEqual([r"\foo"], self._invocation.name) |
Given the code snippet: <|code_start|>
collection.put_string('main', """
<%inherit file="layout"/>
<%def name="d()">main_d</%def>
main_body ${parent.d()}
full stack from the top:
${self.name} ${parent.name} ${parent.context['parent'].name} ${parent.context['parent'].context['parent'].name}
""")
... | ${self.name} ${self.context['parent'].name} ${self.context['parent'].context['parent'].name} ${self.context['parent'].context['parent'].context['parent'].name} |
Here is a snippet: <|code_start|>
def test_getattr(self):
collection = lookup.TemplateLookup()
collection.put_string("main.html", """
<%namespace name="foo" file="ns.html"/>
<%
if hasattr(foo, 'lala'):
foo.lala()
if not h... | this is ns.html->bar |
Using the snippet: <|code_start|>
if not os.access('./test_htdocs', os.F_OK):
os.mkdir('./test_htdocs')
file('./test_htdocs/index.html', 'w').write("this is index")
<|code_end|>
, determine the next line of code. You have imports:
from mako.template import Template
from mako import lookup, exceptions
from util im... | file('./test_htdocs/incl.html', 'w').write("this is include 1") |
Next line prediction: <|code_start|>
if not os.access('./test_htdocs', os.F_OK):
os.mkdir('./test_htdocs')
file('./test_htdocs/index.html', 'w').write("this is index")
<|code_end|>
. Use current file imports:
(from mako.template import Template
from mako import lookup, exceptions
from util import flatten_result, ... | file('./test_htdocs/incl.html', 'w').write("this is include 1") |
Here is a snippet: <|code_start|> """)
assert flatten_result(t.render(x=5)) == "b. x is 10. a: x is 5"
def test_scope_nine(self):
"""test that 'enclosing scope' doesnt get exported to other templates"""
l = lookup.TemplateLookup()
l.put_string('main', """
<%
... | <%def name="c()"> |
Based on the snippet: <|code_start|>#! /usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'maxim'
class NamedDictTest(unittest.TestCase):
def test_embedded_dict(self):
spec = hype.spec.new({
'foo': {
<|code_end|>
, predict the immediate next line with the help of imports:
import six
import uni... | 'bar': { |
Given the code snippet: <|code_start|> return {}
if self._accuracy is None:
loss = self._session.run(self._loss, feed_dict=feed_dict)
return {'loss': loss}
if self._loss is None:
accuracy = self._session.run(self._accuracy, feed_dict=feed_dict)
return {'accuracy': accuracy}
loss... | try: |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
__author__ = 'maxim'
class TensorflowRunner(BaseRunner):
def __init__(self, model=None, extra_feed={},
input='input', label='label', mode='mode', loss='loss', accuracy='accuracy', train='minimize'):
super(TensorflowRunner, self).__init_... | self._session = kwargs['session'] |
Here is a snippet: <|code_start|> def __init__(self, model=None, extra_feed={},
input='input', label='label', mode='mode', loss='loss', accuracy='accuracy', train='minimize'):
super(TensorflowRunner, self).__init__()
self._graph = model or tf.get_default_graph()
assert isinstance(self._grap... | feed_dict = self._get_feed_dict(batch_x, batch_y, 'test') |
Predict the next line after this snippet: <|code_start|> def __init__(self, input):
for k, v in input.items():
if isinstance(v, (list, tuple)):
setattr(self, k, [NamedDict(x) if isinstance(x, dict) else x for x in v])
else:
setattr(self, k, NamedDict(v) if isinstance(v, dict) else v)
... | def __repr__(self): |
Given snippet: <|code_start|>#! /usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'maxim'
reducers = {
'max': lambda curve: np.max(curve) if curve else 0,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import inspect
import numpy as np
from ..base import *
from .data_se... | 'avg': lambda curve: np.mean(curve) if curve else 0, |
Here is a snippet: <|code_start|>#! /usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'maxim'
class TensorflowModelIO(ModelIO):
def __init__(self, **params):
super(TensorflowModelIO, self).__init__(**params)
self.saver = tf.train.Saver(defer_build=True)
def save_session(self, session, director... | self.saver.save(session, destination) |
Predict the next line for this snippet: <|code_start|> def test_successful_to_be(self):
expect_object = Expect(self.data)
expect_object.negate = False
try:
expect_object.to_be(self.data)
except ExpectationException:
raise AssertionError
def test_failure_t... | expect_object.to_be(self.data) |
Given snippet: <|code_start|> raise AssertionError
def test_failure_to_be_less_than_or_equal_to(self):
expect_object = Expect(10)
expect_object.negate = False
with self.assertRaises(ExpectationException):
expect_object.to_be_less_than_or_equal_to(9)
def test_suc... | expect_object.negate = False |
Given snippet: <|code_start|> def setUp(self):
self.slow_function_called = False
self.slow_function_called_with = None
def slow_function(context, sleep_time=0.5, fail=False):
time.sleep(sleep_time)
self.slow_function_called = True
self.slow_function_called... | def test_init(self): |
Given the following code snippet before the placeholder: <|code_start|> self.async_slow_function_called_with = {'context': context, 'sleep_time': sleep_time, 'fail': fail}
if fail:
raise Exception
self.slow_function = slow_function
self.async_slow_function = asyn... | self.assertTrue(some_step.passed) |
Predict the next line after this snippet: <|code_start|>
class ExpectationExceptionTestCase(TestCase):
def test_init(self):
expectation_exception = ExpectationException('foo', 'bar', 'some_operator')
self.assertTrue(isinstance(expectation_exception, Exception))
<|code_end|>
using the current fil... | self.assertEqual(expectation_exception.actual, 'foo') |
Based on the snippet: <|code_start|>
class ContextTestCase(TestCase):
def test_empty_init(self):
context = Context()
self.assertEqual(context.__dict__, {'_items': {}})
def test_init_with_kwargs(self):
context = Context(foo='bar', foobar='barfoo')
<|code_end|>
, predict the immediate... | self.assertEqual(context.__dict__, {'_items': {'foo': 'bar', 'foobar': 'barfoo'}}) |
Based on the snippet: <|code_start|>
class JasperTestCase(TestCase):
def setUp(self):
self.test_directory = os.path.abspath('.\mock_features')
@mock.patch('jasper.entrypoints.Display')
@mock.patch('jasper.entrypoints.Runner')
def test_jasper_without_options(self, mock_runner_class, mock_displ... | @mock.patch('jasper.entrypoints.Display') |
Predict the next line after this snippet: <|code_start|> def test_num_scenarios_failed(self):
suite = Suite()
suite.features = [self.passing_feature_mock(), self.failing_feature_mock()]
self.assertEqual(suite.num_scenarios_failed, 1)
def test_add_feature(self):
suite = Suite()
... | self.assertTrue(feature_one.ran) |
Continue the code snippet: <|code_start|> @mock.patch('jasper.runner.Suite')
def test_init(self, mock_suite):
runner = Runner(self.test_directory)
self.assertEqual(runner.test_directory, self.test_directory)
self.assertEqual(runner.test_file_paths, [])
self.assertTrue(isinstance(... | ".\\mock_features\\runner_two\\runner_two_feature.py" |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: iso-8859-1 -*-
r'''
This file is part of orbkit. See the main program or documentation
for information on the license.
It shows two examples of how to use orbkit for evaluating
analytical integrals.
First Part:
Compute the elect... | Second Part: |
Using the snippet: <|code_start|># -*- coding: iso-8859-1 -*-
r'''
This file is part of orbkit. See the main program or documentation
for information on the license.
It shows two examples of how to use orbkit for evaluating
analytical integrals.
First Part:
Compute the electron number analytically using the stan... | <\phi_k|z|\phi_l> = \int dxdydz (z - Z_k)^{k_z} e^{\alpha_k r_k^2} (z - Z_l)^{l_z+1} e^{\alpha_l r_l^2} |
Here is a snippet: <|code_start|># -*- coding: iso-8859-1 -*-
r'''
This file is part of orbkit. See the main program or documentation
for information on the license.
It shows two examples of how to use orbkit for evaluating
analytical integrals.
<|code_end|>
. Write the next line using the current file imports:
fr... | First Part: |
Based on the snippet: <|code_start|>
try:
except:
# search and load libcint from $PATH
libcint = None
for dirname in os.environ['PATH'].split(':'):
if os.path.isfile(os.path.join(dirname, 'lib', 'libcint.so')):
libcint = ctypes.cdll.LoadLibrary(os.path.abspath(os.path.join(dirname, 'lib', 'libcint.so')))
br... | ('rij', ctypes.POINTER(ctypes.POINTER(ctypes.c_double))), |
Predict the next line after this snippet: <|code_start|>
try:
except ImportError:
ao_dict_synonyms = {'atom': 'atom',
'pnum': 'pnum',
'type': 'type',
'coeffs': 'coeffs',
'lxlylz': 'l... | 'lm': 'lm', |
Based on the snippet: <|code_start|>
def each_ao_is_normalized(ao_spec):
is_normalized = []
for sel_ao in range(len(ao_spec)):
is_normalized.append((ao_spec[sel_ao]['pnum'] < 0))
if all(is_normalized) != any(is_normalized):
raise ValueError('Either all or none of the atomic orbitals have to be normaliz... | return False |
Based on the snippet: <|code_start|> or the specified mo_set, respectively.
''')
parser.add_option_group(group)
group = optparse.OptionGroup(parser, "Grid-Related Options")
group.add_option("--adjust_grid",dest="adjust_grid",
type="float",nargs=... | group = optparse.OptionGroup(parser, "Additional Options") |
Based on the snippet: <|code_start|>
tests_home = os.path.dirname(inspect.getfile(inspect.currentframe()))
folder = os.path.join(tests_home, '../outputs_for_testing')
files = {'fchk': 'gaussian/h2o_rhf_cart.fchk',
'gaussian_log': 'gaussian/h2o_rhf_cart.inp.log',
'gamess': 'gamess/formaldehyde.log',
<... | 'molden': 'molpro/h2o_rhf_sph.molden', |
Given snippet: <|code_start|>from __future__ import division
try:
except ImportError:
class DM:
def __init__(self, zero, sing, qc):
zero = numpy.array(zero)
self.qc = qc
self.Tij = numpy.matrix(numpy.zeros((len(self.qc.mo_spec),len(self.qc.mo_spec))))
#build the trace of Tij
zero0 = zero[0].fla... | for imo, it in enumerate(zero1): |
Using the snippet: <|code_start|># ###################################################################
# FILENAME: test_i18n.py
# PROJECT:
# DESCRIPTION: Test internationalization support
#
#
# $Id$
# ###################################################################
# (C)2015 DigiTar Inc.
# Licensed under the MIT Li... | } |
Given the following code snippet before the placeholder: <|code_start|>####################################################################
# FILENAME: auth/test_errors.py
# PROJECT: Shiji API
# DESCRIPTION: Tests auth.errors module.
#
# Requires: TwistedWeb >= 10.0
# (Python 2.5 ... | self.assertEqual(exc.__str__(), "123") |
Predict the next line after this snippet: <|code_start|>#
#
# $Id$
####################################################################
# (C)2015 DigiTar Inc.
# Licensed under the MIT License.
####################################################################
ARG_ERR = -1
MKDIR_ERR = -2
WRITE_FILE_ERR = -3
TEMPLATE_... | in_versions = True |
Continue the code snippet: <|code_start|> @classmethod
def dumps_all(cls):
"write all objects of Model class to a JSON-encoded array"
return cls.__schema__().dumps(cls.query.all(), many=True).data
@classmethod
def dumpf_all(cls, file_handle):
"write all objects of Model class to ... | @classmethod |
Continue the code snippet: <|code_start|>
@pytest.mark.parametrize('event_name, event_type, event_data', [
('low-battery', 'battery', '{"status": "low-charge"}'),
('auto-poweroff', 'battery', '{"status": "automatic-poweroff"}')
])
def test_generate_low_battery_event(event_name, event_type, event_data):
... | 'timezone_offset', |
Predict the next line after this snippet: <|code_start|> events.append(json.loads(events_f.readline()))
assert len(events) == 1
event = events[0]
expected_keys = [
'name',
'language',
'type',
'timezone_offset',
'cpu_id',
'os_version',
'token'... | assert event['data'] == json.loads(event_data) |
Given snippet: <|code_start|>#!/usr/bin/env python
# images.py
#
# Copyright (C) 2014, 2015 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
#
# "Badge", folder_name, file_name, width of image
def get_image(category, subcategory, name, subfolder_str):
# The o... | if not os.path.exists(fullpath): |
Predict the next line for this snippet: <|code_start|>
def __repr__(self):
return 'Tracking Session [Name: {name}, PID: {pid}]: {is_open}'.format(
name=self.name,
pid=self.pid,
is_open='OPEN' if self.is_open() else 'CLOSED'
)
def __str__(self):
return... | def is_open(self): |
Predict the next line for this snippet: <|code_start|> @property
def name(self):
return self._name.encode('utf-8')
@property
def pid(self):
return self._pid or 0
def is_open(self):
return is_pid_running(self.pid)
def open(self, mode):
try:
session_f ... | session_data = json.loads(session.rstrip().lstrip()) |
Given snippet: <|code_start|>#
# tracking_session.py
#
# Copyright (C) 2017 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2
#
# A class to manage tracking session files
#
class TrackingSession(object):
SESSION_FILE_RE = re.compile(r'^(\d+)-(.*).json$')
def __init__(self, ... | 'TrackingSession requires a file or a name/pid combination' |
Next line prediction: <|code_start|># GetData.py
#
# Copyright (C) 2015-2019 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
#
# This contains the RegistrationScreen form component with all the widgets
def is_email(email):
if '@' in parseaddr(email)[1]:
... | else: |
Based on the snippet: <|code_start|># GetData.py
#
# Copyright (C) 2015-2019 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
#
# This contains the RegistrationScreen form component with all the widgets
def is_email(email):
if '@' in parseaddr(email)[1]:
... | else: |
Next line prediction: <|code_start|># GetData.py
#
# Copyright (C) 2015-2019 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
#
# This contains the RegistrationScreen form component with all the widgets
def is_email(email):
if '@' in parseaddr(email)[1]:
... | return False |
Here is a snippet: <|code_start|>#!/usr/bin/env python
# activate_account.py
#
# Copyright (C) 2014, 2015 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
#
#
# TODO: Remove this statement after upgrading to a friendly Python-requests match
requests.packages.urllib... | else: |
Given the code snippet: <|code_start|>
def request_wrapper(method, endpoint, data=None, headers=None,
session=None, files=None, params=None):
if method not in ['put', 'get', 'post', 'delete']:
return False, "Wrong method name!", None
if session:
req_object = session
else... | timeout=(connect_timeout, read_timeout) |
Given the code snippet: <|code_start|>#
# PopUpItemMenu.py
#
# Copyright (C) 2015 - 2018 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2
#
require_version('Gtk', '3.0')
# Having to include the translatable strings here for the time being
# as they are buried in the conf.json file.... | SPECIAL_CATEGORIES = [ |
Given snippet: <|code_start|># ValidationEntry.py
#
# Copyright (C) 2015 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
#
if __name__ == '__main__' and __package__ is None:
dir_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
if dir_p... | if filename: |
Given the code snippet: <|code_start|># tracking_uuids.py
#
# Copyright (C) 2018 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2
#
# Functions for creating namespaced UUIDs for apps.
SECOND = 1
MINUTE = 60 * SECOND
HOUR = 60 * MINUTE
DAY = 24 * HOUR
<|code_end|>
, generate the ... | def get_tracking_uuid(key, expires=3 * DAY): |
Predict the next line after this snippet: <|code_start|> self.get_style_context().add_class('menu_bar_container')
self.height = 110
self.width = win_width
self.set_size_request(self.width, self.height)
self._quests = quests
hbox = Gtk.Box()
self.add(hbox)
... | button.connect('clicked', self.emit_menu_signal, name) |
Using the snippet: <|code_start|> MenuBar.BADGES_STR,
MenuBar.CHARACTER_STR
] # TODO: add MenuBar.QUESTS_STR to enable
for name in name_array:
button = MenuButton(_(name), self._quests)
button.connect('clicked', self.emit_menu_signal, name)
butt... | return label |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
# MenuBar.py
#
# Copyright (C) 2014, 2015 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
#
# This controls the styling of the (pretend) top window bar.
# -*- coding: utf-8... | } |
Based on the snippet: <|code_start|>#!/usr/bin/env python
# image_.py
#
# Copyright (C) 2014, 2015 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
#
# This controls the size and styling of the pictures displayed on the table
# Used for badges, environments and avata... | def get_image_path_at_size(category, name, width, height, locked): |
Given the code snippet: <|code_start|> win_size = '-W 590 -H 600'
def __init__(self, win, dummy=None):
FirstScreenTemplate.__init__(self)
self.win = win
self.win.set_decorated(False)
self.win.set_main_widget(self)
self.kano_button.connect('button_release_event', self.r... | Gtk.main_quit() |
Next line prediction: <|code_start|>
def exit_registration(self, widget, event):
# We are done, clean up
self.win.remove_main_widget()
sys.exit(0)
def repack(self):
self.win.remove_main_widget()
self.win.set_main_widget(self)
class NoInternet(Template):
def __init_... | kano_button_label, orange_button_label) |
Given snippet: <|code_start|>
Gtk.Button.__init__(self)
self.badge_info = badge_info
self.title = badge_info['title']
self.unlocked_description = badge_info['desc_unlocked']
self.locked_description = badge_info['desc_locked']
background_color = badge_info['bg_color']
... | self.set_size_request(self.width, self.height) |
Given snippet: <|code_start|> Gtk.Button.__init__(self)
self.badge_info = badge_info
self.title = badge_info['title']
self.unlocked_description = badge_info['desc_unlocked']
self.locked_description = badge_info['desc_locked']
background_color = badge_info['bg_color']
... | self.connect('enter-notify-event', self.add_hover_style, |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# upload-share.py
#
# Copyright (C) 2014, 2015 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
#
#
if __name__ == '__main__' and __package__ is None:
dir_path = os.path.abspath(os.path.join(os.path.di... | sys.path.insert(1, dir_path) |
Continue the code snippet: <|code_start|>#
# SelectMenu.py
#
# Copyright (C) 2015 - 2018 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2
#
require_version('Gtk', '3.0')
# TODO: try and replace the current structure with the parser?
# the selected functions would then be redundant
... | self._set_items(list_of_names) |
Given the code snippet: <|code_start|>
open_session_path = tracking_sessions.get_session_file_path(
open_session['name'],
open_session['pid']
)
assert os.path.basename(open_session_path) == listed_session.file
assert os.path.abspath(open_session_path) == listed_session.path
assert o... | def test_session_start_with_pid(tracking_session): |
Based on the snippet: <|code_start|>
def test_list_sessions(tracking_session, sample_tracking_sessions):
tracking_session.setup_sessions(sample_tracking_sessions)
tracking_session.setup_paused_sessions(None)
listed_sessions = tracking_sessions.list_sessions()
assert len(listed_sessions) == len(sample... | for session in listed_sessions: |
Predict the next line for this snippet: <|code_start|> self.fixed = Gtk.Fixed()
self.add(self.fixed)
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
self.fixed.add(vbox)
if path and os.path.exists(path):
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
... | self.hover_info.get_style_context().add_class('reward_hover_background') |
Predict the next line after this snippet: <|code_start|> self.get_style_context().add_class('quest_screen_background')
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
self.add(vbox)
self.grid = Gtk.Grid()
self.grid.set_column_spacing(10)
self.grid.set_row_spacing(10... | def create_progress_section(self): |
Next line prediction: <|code_start|> self.grid.set_margin_bottom(10)
self.grid.set_margin_top(10)
vbox.pack_start(self.grid, False, False, 0)
# May be better elsewhere
self.win = keywords['win']
self.quest = keywords['quest_info']
self.win.pack_in_main_content(se... | text_background = Gtk.EventBox() |
Next line prediction: <|code_start|>#!/usr/bin/env python
# logged_in.py
#
# Copyright (C) 2014, 2015 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
#
# UI for login screen
class LoggedIn(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, tit... | orientation=Gtk.Orientation.VERTICAL, spacing=0) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.