Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Here is a snippet: <|code_start|>
try:
except ImportError:
logger = logging.getLogger(__name__)
REDIRECT_URI = getattr(settings, 'REST_SOCIAL_OAUTH_REDIRECT_URI', '/')
DOMAIN_FROM_ORIGIN = getattr(settings, 'REST_SOCIAL_DOMAIN_FROM_ORIGIN', True)
LOG_AUTH_EXCEPTIONS = getattr(settings, 'REST_SOCIAL_LOG_AUTH_EXCEP... | def load_strategy(request=None): |
Continue the code snippet: <|code_start|>
try:
except ImportError:
logger = logging.getLogger(__name__)
REDIRECT_URI = getattr(settings, 'REST_SOCIAL_OAUTH_REDIRECT_URI', '/')
DOMAIN_FROM_ORIGIN = getattr(settings, 'REST_SOCIAL_DOMAIN_FROM_ORIGIN', True)
LOG_AUTH_EXCEPTIONS = getattr(settings, 'REST_SOCIAL_LOG_AU... | return get_strategy(STRATEGY, STORAGE, request) |
Given the following code snippet before the placeholder: <|code_start|>
try:
except ImportError:
logger = logging.getLogger(__name__)
REDIRECT_URI = getattr(settings, 'REST_SOCIAL_OAUTH_REDIRECT_URI', '/')
DOMAIN_FROM_ORIGIN = getattr(settings, 'REST_SOCIAL_DOMAIN_FROM_ORIGIN', True)
LOG_AUTH_EXCEPTIONS = getattr... | STRATEGY = getattr(settings, setting_name('STRATEGY'), 'rest_social_auth.strategy.DRFStrategy') |
Here is a snippet: <|code_start|>
try:
except ImportError:
logger = logging.getLogger(__name__)
REDIRECT_URI = getattr(settings, 'REST_SOCIAL_OAUTH_REDIRECT_URI', '/')
DOMAIN_FROM_ORIGIN = getattr(settings, 'REST_SOCIAL_DOMAIN_FROM_ORIGIN', True)
LOG_AUTH_EXCEPTIONS = getattr(settings, 'REST_SOCIAL_LOG_AUTH_EXCEP... | def decorate_request(request, backend): |
Predict the next line for this snippet: <|code_start|>class TestSocialAuth2Knox(APITestCase, BaseFacebookAPITestCase):
def _check_login_social_knox_only(self, url, data):
resp = self.client.post(url, data)
self.assertEqual(resp.status_code, 200)
# check token valid
knox_auth = KnoxT... | self._check_login_social_knox_user( |
Using the snippet: <|code_start|>
knox_override_settings = dict(
INSTALLED_APPS=[
'django.contrib.contenttypes',
'rest_framework',
'social_django',
'rest_social_auth',
'knox', # For django-rest-knox
'users',
<|code_end|>
, determine the next line of code. You have ... | ], |
Given snippet: <|code_start|> 'django.contrib.contenttypes',
'rest_framework',
'rest_framework.authtoken',
'social_django',
'rest_social_auth',
'users',
],
MIDDLEWARE=[],
)
@override_settings(**token_override_settings)
class TestSocialAuth1Token(APITestCase, Base... | def _check_login_social_token_user(self, url, data): |
Continue the code snippet: <|code_start|>
def _check_login_social_token_only(self, url, data):
resp = self.client.post(url, data)
self.assertEqual(resp.status_code, 200)
# check token exists
token = Token.objects.get(key=resp.data['token'])
# check user is created
sel... | user_data_body = json.loads(self.user_data_body) |
Given snippet: <|code_start|> url_params = dict(parse_qsl(urlparse(HTTPretty.latest_requests[0].path).query))
self.assertEqual('http://manualdomain.com/', url_params['redirect_uri'])
@mock.patch('rest_framework.views.APIView.permission_classes')
def test_login_social_session_model_permission(sel... | reverse('login_social_session'), |
Next line prediction: <|code_start|>
session_modify_settings = dict(
INSTALLED_APPS={
'remove': [
'rest_framework.authtoken',
'knox',
]
},
<|code_end|>
. Use current file imports:
(from unittest import mock
from urllib.parse import parse_qsl, urlparse
from django.urls... | ) |
Here is a snippet: <|code_start|>
# don't run third party tests
for attr in (attr for attr in dir(FacebookOAuth2Test) if attr.startswith('test_')):
delattr(FacebookOAuth2Test, attr)
for attr in (attr for attr in dir(TwitterOAuth1Test) if attr.startswith('test_')):
delattr(TwitterOAuth1Test, attr)
class Res... | def setUp(self): |
Here is a snippet: <|code_start|> "Bitcoin",
"14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e",
bytes.fromhex(
"209e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80"
),
"This is an... | "1cc694f0f23901dfe3603789142f36a3fc582d0d5c0ec7215cf2ccd641e4e37228504f3d4dc3eea28bbdbf5da27c49d4635c097004d9f228750ccd836a8e1460c0" |
Next line prediction: <|code_start|> )
self.client.set_passphrase(passphrase_nfc)
address_nfc = btc.get_address(self.client, "Bitcoin", [])
device.wipe(self.client)
debuglink.load_device_by_mnemonic(
self.client,
mnemonic=words_nfkc,
pin="",
... | assert address_nfkd == address_nfc |
Next line prediction: <|code_start|> passphrase_protection=True,
label="test",
language="english",
skip_checksum=True,
)
self.client.set_passphrase(passphrase_nfc)
address_nfc = btc.get_address(self.client, "Bitcoin", [])
device.wipe(self.c... | ) |
Given snippet: <|code_start|>#!/usr/bin/env python3
def main():
# Use first connected device
client = get_default_client()
# Print out TREZOR's features and settings
print(client.features)
# Get the first address of first BIP44 account
# (should be the same address as shown in wallet.trezor.... | print("Bitcoin address:", address) |
Using the snippet: <|code_start|>#!/usr/bin/env python3
def main():
# Use first connected device
client = get_default_client()
# Print out TREZOR's features and settings
print(client.features)
# Get the first address of first BIP44 account
# (should be the same address as shown in wallet.tre... | print("Bitcoin address:", address) |
Given the code snippet: <|code_start|>#!/usr/bin/env python3
def find_debug():
for device in enumerate_devices():
try:
debug_transport = device.find_debug()
debug = DebugLink(debug_transport, auto_interact=False)
debug.open()
return debug
except Exce... | if __name__ == "__main__": |
Using the snippet: <|code_start|> usb1 = None
INTERFACE = 0
ENDPOINT = 1
DEBUG_INTERFACE = 1
DEBUG_ENDPOINT = 2
class WebUsbHandle:
def __init__(self, device: "usb1.USBDevice", debug: bool = False) -> None:
self.device = device
self.interface = DEBUG_INTERFACE if debug else INTERFACE
s... | self.handle = None |
Using the snippet: <|code_start|>class WebUsbHandle:
def __init__(self, device: "usb1.USBDevice", debug: bool = False) -> None:
self.device = device
self.interface = DEBUG_INTERFACE if debug else INTERFACE
self.endpoint = DEBUG_ENDPOINT if debug else ENDPOINT
self.count = 0
s... | def read_chunk(self) -> bytes: |
Using the snippet: <|code_start|> sig.signature.hex()
== "209e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80"
)
def test_sign_testnet(self):
self.setup_mnemonic_nopin_nopassphrase()
sig = ... | ) |
Continue the code snippet: <|code_start|> for device in enumerate_devices():
try:
debug_transport = device.find_debug()
debug = DebugLink(debug_transport, auto_interact=False)
debug.open()
return debug
except Exception:
continue
else:
... | main() |
Continue the code snippet: <|code_start|># coding: utf-8
from __future__ import absolute_import, division, print_function
SPK_URL = ("http://naif.jpl.nasa.gov/pub/naif/generic_kernels/"
"spk/{category}/{kernel}.bsp")
SPK_OLD_URL = ("http://naif.jpl.nasa.gov/pub/naif/generic_kernels/"
"spk/... | SPK_DIR = Path(appdirs.user_data_dir, 'spk') |
Next line prediction: <|code_start|># coding: utf-8
from __future__ import absolute_import, division, print_function
SPK_URL = ("http://naif.jpl.nasa.gov/pub/naif/generic_kernels/"
"spk/{category}/{kernel}.bsp")
SPK_OLD_URL = ("http://naif.jpl.nasa.gov/pub/naif/generic_kernels/"
"spk/{cate... | appdirs = AppDirs('astrodynamics') |
Here is a snippet: <|code_start|># coding: utf-8
from __future__ import absolute_import, division, print_function
SPK_URL = ("http://naif.jpl.nasa.gov/pub/naif/generic_kernels/"
"spk/{category}/{kernel}.bsp")
SPK_OLD_URL = ("http://naif.jpl.nasa.gov/pub/naif/generic_kernels/"
"spk/{categor... | SPK_DIR = Path(appdirs.user_data_dir, 'spk') |
Here is a snippet: <|code_start|># coding: utf-8
from __future__ import absolute_import, division, print_function
__all__ = (
'Ellipsoid',
<|code_end|>
. Write the next line using the current file imports:
from astropy.units import Quantity
from represent import ReprHelperMixin
from ..constants import (
WGS... | 'ReferenceEllipsoid', |
Predict the next line after this snippet: <|code_start|># coding: utf-8
from __future__ import absolute_import, division, print_function
__all__ = (
'Ellipsoid',
'ReferenceEllipsoid',
'wgs84',
)
<|code_end|>
using the current file's imports:
from astropy.units import Quantity
from represent import Re... | class Ellipsoid(ReprHelperMixin, object): |
Here is a snippet: <|code_start|># coding: utf-8
from __future__ import absolute_import, division, print_function
__all__ = (
'Ellipsoid',
<|code_end|>
. Write the next line using the current file imports:
from astropy.units import Quantity
from represent import ReprHelperMixin
from ..constants import (
WGS... | 'ReferenceEllipsoid', |
Based on the snippet: <|code_start|># coding: utf-8
from __future__ import absolute_import, division, print_function
__all__ = (
'Ellipsoid',
'ReferenceEllipsoid',
<|code_end|>
, predict the immediate next line with the help of imports:
from astropy.units import Quantity
from represent import ReprHelperMixi... | 'wgs84', |
Given snippet: <|code_start|># coding: utf-8
from __future__ import absolute_import, division, print_function
__all__ = (
'Ellipsoid',
'ReferenceEllipsoid',
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from astropy.units import Quantity
from represent import ReprHelper... | 'wgs84', |
Continue the code snippet: <|code_start|># coding: utf-8
from __future__ import absolute_import, division, print_function
__all__ = (
'format_size',
'prefix',
'qisclose',
'read_only_property',
<|code_end|>
. Use current file imports:
import errno
from contextlib import contextmanager
from astropy i... | 'suppress_file_exists_error', |
Here is a snippet: <|code_start|>try:
# Lots of different errors can come from this, including SystemError and
# ImportError.
except Exception:
colorama = None
__all__ = ('DownloadProgressBar', 'DownloadProgressSpinner')
def _select_progress_class(preferred, fallback):
encoding = getattr(preferred.file, "enc... | except UnicodeEncodeError: |
Using the snippet: <|code_start|># coding: utf-8
from __future__ import absolute_import, division, print_function
try:
# Lots of different errors can come from this, including SystemError and
# ImportError.
except Exception:
colorama = None
__all__ = ('DownloadProgressBar', 'DownloadProgressSpinner')
def _se... | getattr(preferred, "fill", six.text_type()), |
Next line prediction: <|code_start|>
@lru_cache()
def uni_formset_template(template_pack=TEMPLATE_PACK):
return get_template("%s/uni_formset.html" % template_pack)
@lru_cache()
def uni_form_template(template_pack=TEMPLATE_PACK):
<|code_end|>
. Use current file imports:
(from functools import lru_cache
from dj... | return get_template("%s/uni_form.html" % template_pack) |
Given the code snippet: <|code_start|>
@lru_cache()
def uni_formset_template(template_pack=TEMPLATE_PACK):
return get_template("%s/uni_formset.html" % template_pack)
@lru_cache()
def uni_form_template(template_pack=TEMPLATE_PACK):
return get_template("%s/uni_form.html" % template_pack)
<|code_end|>
, gen... | register = template.Library() |
Predict the next line after this snippet: <|code_start|>
@register.filter
def is_password(field):
return isinstance(field.field.widget, forms.PasswordInput)
@register.filter
def is_radioselect(field):
return isinstance(field.field.widget, forms.RadioSelect) and not isinstance(
field.field.widget, for... | def is_clearable_file(field): |
Next line prediction: <|code_start|>
class TemplateNameMixin:
def get_template_name(self, template_pack):
if "%s" in self.template:
template = self.template % template_pack
else:
template = self.template
return template
<|code_end|>
. Use current file imports:
(... | class LayoutObject(TemplateNameMixin): |
Predict the next line for this snippet: <|code_start|>
class TemplateNameMixin:
def get_template_name(self, template_pack):
if "%s" in self.template:
<|code_end|>
with the help of current file imports:
from django.template import Template
from django.template.loader import render_to_string
from django.u... | template = self.template % template_pack |
Continue the code snippet: <|code_start|>
class TemplateNameMixin:
def get_template_name(self, template_pack):
if "%s" in self.template:
template = self.template % template_pack
else:
template = self.template
return template
class LayoutObject(TemplateNameMixin):... | return len(self.fields) |
Given snippet: <|code_start|>top
top-left
top-right
move-to-bottom
move-to-bottom-left
move-to-bottom-right
move-to-center
move-to-left
move-to-right
move-to-top
move-to-top-left
move-to-top-right
bordered
bordered
always-above
always-above
always-below
always-below
horizontal-maximize
horizontal-maximize
vertical-m... | all-desktops |
Given the code snippet: <|code_start|>fullscreen
fullscreen
all-desktops
all-desktops
trigger-move
trigger-resize
workspace-send-down
workspace-go-down
workspace-send-up
workspace-go-up
workspace-send-left
workspace-go-left
workspace-send-right
workspace-go-right
workspace-send-next
workspace-go-next
workspace-s... | maximize |
Given the code snippet: <|code_start|>#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT... | def region(self): |
Here is a snippet: <|code_start|>#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of ceph-auto-aws nor the names of its contributors ... | handson.myyaml.load() |
Next line prediction: <|code_start|># and/or other materials provided with the distribution.
#
# * Neither the name of ceph-auto-aws nor the names of its contributors may be
# used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE... | r.region() # loads from cache |
Predict the next line for this snippet: <|code_start|> def create_vpc(self, *_):
return {'id': 'DummyID', 'cidr_block': '10.0.0.0/16'}
def get_all_vpcs(self, *_):
return ['DummyValue']
class TestHandsOn(SetUp, unittest.TestCase):
def test_init(self):
m = main.HandsOn()
wi... | ]) |
Based on the snippet: <|code_start|># AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,... | def create_vpc(self, *_): |
Here is a snippet: <|code_start|># and/or other materials provided with the distribution.
#
# * Neither the name of ceph-auto-aws nor the names of its contributors may be
# used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE CO... | v.vpc_obj() # loads from cache |
Next line prediction: <|code_start|> k_stanza = stanza('keypairs')
log.debug("Keypairs stanza is {!r}".format(k_stanza))
assert type(k_stanza) == dict
d = self._keypair['delegate']
if d in k_stanza:
if 'keyname' in k_stanza[d]:
if k_stanza[d]['keyname']... | return None |
Predict the next line after this snippet: <|code_start|> k_mat = self.get_key_material(k_name)
k_obj = self.ec2().import_key_pair(k_name, k_mat)
log.info("Keypair {} imported to AWS".format(k_name))
self._keypair['keypair_obj'] = k_obj
self._keypair['key_name'] = k_name
k_... | .format(self._keypair['delegate'])) |
Given snippet: <|code_start|> return None
def get_key_material(self, keyname):
fn = "keys/{}.pub".format(keyname)
return get_file_as_string(fn)
def get_keypair_from_aws(self):
keyname_from_yaml = self.get_keyname_from_yaml()
if keyname_from_yaml:
log.debug("G... | k_stanza[d] = {} |
Using the snippet: <|code_start|># * Neither the name of ceph-auto-aws nor the names of its contributors may be
# used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS ... | assert ( |
Given the following code snippet before the placeholder: <|code_start|># * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of ceph-auto-aw... | self.args = args |
Next line prediction: <|code_start|># * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of ceph-auto-aws nor the names of its contributors... | self.args = args |
Given snippet: <|code_start|># used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF M... | def vpc_obj(self, create=False, dry_run=False, quiet=False): |
Next line prediction: <|code_start|> for ob in obs:
ob_eval = ob.evaluated_get(depsgraph)
me = ob_eval.to_mesh()
me.transform(ob.matrix_world)
bm.from_mesh(me)
ob_eval.to_mesh_clear()
bmesh.ops.triangulate(bm, faces=bm.faces)
vol = bm.calc_volume()
bm.free()
... | x = getattr(ob.data, k) |
Predict the next line for this snippet: <|code_start|>
bmesh.ops.triangulate(bm, faces=bm.faces)
vol = bm.calc_volume()
bm.free()
return vol
def est_curve_length(ob: Object) -> float:
if ob.modifiers:
# Reset curve
# ---------------------------
settings = {
... | ob_eval = ob.evaluated_get(depsgraph) |
Predict the next line after this snippet: <|code_start|># ##### BEGIN GPL LICENSE BLOCK #####
#
# JewelCraft jewelry design toolkit for Blender.
# Copyright (C) 2015-2022 Mikhail Rachinskiy
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Licen... | ) |
Given the following code snippet before the placeholder: <|code_start|> app((-x, y, z))
return vs
def _get_heart(detalization: int, mul_1: float, mul_2: float, mul_3: float) -> list[tuple[float, float, float]]:
curve_resolution = detalization + 1
angle = pi / (curve_resolution - 1)
vs = []
... | for co in reversed(vs): |
Predict the next line after this snippet: <|code_start|> f.normal_flip()
verts = [bm.verts.new((*v.co.xy, size.z1)) for v in f.verts]
bm_temp.free()
return verts
def _edge_loop_walk(verts: list[BMVert]) -> Iterator[BMVert]:
v0 = v = next(iter(verts))
e = v.link_edges[1]
ov = e.other_v... | "bv_type", |
Given the following code snippet before the placeholder: <|code_start|>
def requests_get_content(uri, timeout=10):
try:
response = requests.get(uri, timeout=timeout)
response.raise_for_status()
except requests.exceptions.HTTPError:
_handle_http_error(response.status_code)
except re... | return response.content.decode("utf-8") |
Predict the next line after this snippet: <|code_start|>
class TestXMLUtils(TestCase):
def test_node_text_diacritics(self):
xmltree = xml_utils.get_xml_tree("<root><city>São Paulo</city></root>")
expected = "São Paulo"
result = xml_utils.node_text(xmltree.find(".//city"))
self.ass... | "<?xml version='1.0' encoding='utf-8'?>\n" |
Based on the snippet: <|code_start|>
logger = logging.getLogger(__name__)
class SPS_Package:
def __init__(self, xml, original_filename=None):
self.xmltree = xml_utils.get_xml_tree(xml)
self._original_filename = original_filename
self._assets = SPS_Assets(self.xmltree, self.scielo_pid_v3)... | return self._nodes_with_lang( |
Here is a snippet: <|code_start|>
logger = logging.getLogger(__name__)
class SPS_Package:
def __init__(self, xml, original_filename=None):
self.xmltree = xml_utils.get_xml_tree(xml)
self._original_filename = original_filename
self._assets = SPS_Assets(self.xmltree, self.scielo_pid_v3)
... | './/sub-article[@article-type="translation"]' |
Predict the next line after this snippet: <|code_start|>
@unittest.skip("""A caixa de retratação está sendo gerada pela aplicação, caso deseje que seja gerado pelo XSLT descomentar a linha 24 do arquivo article.xsl""")
def test_should_translate_retraction_to_english(self):
sample = u"""<article article-ty... | <article-id pub-id-type="doi">10.1590/2236-8906-34/2018-retratacao</article-id> |
Predict the next line after this snippet: <|code_start|> "a1-gf01.jpg": "a1-gf01.jpg",
"a1-gf02.tiff": "a1-gf02.tiff",
}
pkg1._renditions = {
"en": "a1-en.pdf",
"original": "a1.pdf",
}
xmls = [
"a1.xml", "a11.xml",
]
... | self.assertEqual(pkg1._renditions, result["a1"]._renditions) |
Based on the snippet: <|code_start|>
logger = logging.getLogger(__name__)
class Package:
def __init__(self, source, name):
self._source = source
self._xml = None
self._assets = {}
self._renditions = {}
self._name = name
self.zip_file_path = file_utils.is_zipfile(s... | @property |
Here is a snippet: <|code_start|>
def main():
parser = argparse.ArgumentParser(description="Article package maker CLI utility")
parser.add_argument('--output_dir', default='.', help='Output directory where the package will be generated')
parser.add_argument("--loglevel", default="WARNING")
subparsers ... | elif args.command == 'paths': |
Predict the next line for this snippet: <|code_start|>
LOGGER = logging.getLogger(__name__)
def generate_paths_dict(xml_path, assets_paths, renditions_paths):
return {
'xml': xml_path or '',
'assets': assets_paths or [],
'renditions': renditions_paths or [],
}
def generate_uris_dic... | 'uri': rendition_uri_or_path, |
Next line prediction: <|code_start|>
logger = logging.getLogger(__name__)
def formatted_text(title_node):
if title_node is None:
return
node = deepcopy(title_node)
for xref in node.findall(".//xref"):
parent = xref.getparent()
parent.remove(xref)
return node_text(node)
d... | return fix_namespace_prefix_w(xml_str) |
Given snippet: <|code_start|> f()
def test_noStdoutSideEfects(self):
def foo():
print("bar")
f = Function(foo)
with lib.captureStdout() as stdout:
f()
self.assertTrue(len(stdout.read()) == 0)
class TestFunctionPrintOutput(unittest.TestCase):
... | f() |
Given snippet: <|code_start|> self.assertFalse(path.isPythonFile())
def test_pythonFile(self):
path = Path("/foo/bar/baz.py")
self.assertTrue(path.isPythonFile())
def test_folder(self):
path = Path("/foo/bar/baz/")
self.assertFalse(path.isPythonFile())
path = Pa... | class TestPathWalk(unittest.TestCase): |
Predict the next line for this snippet: <|code_start|> print(msg)
return msg
def displayAdded(fileName):
msg = "{}Added: {}{}".format(_Colors.WARNING, os.path.basename(fileName), _Colors.ENDC)
if not SILENT_MODE:
print(msg)
return msg
def displayCustom(message):
if not SILENT_MODE:
print(message)
return me... | return _Colors.WARNING, _Smileys.CONFUSED |
Given the code snippet: <|code_start|> download(fileName, source)
return
filePath = path.userPath + fileName
if not fileExists(str(filePath)):
raise exception.CheckpyError("Required file {} does not exist".format(fileName))
filePath.copyTo(path.current() + fileName)
def fileExists(fileName):
return path.Pa... | newSource += line |
Predict the next line for this snippet: <|code_start|> raise exception.CheckpyError("Required file {} does not exist".format(fileName))
filePath.copyTo(path.current() + fileName)
def fileExists(fileName):
return path.Path(fileName).exists()
def source(fileName):
source = ""
with open(fileName) as f:
source = ... | else: |
Predict the next line after this snippet: <|code_start|>try:
# Python 2
except:
# Python 3
def require(fileName, source = None):
if source:
download(fileName, source)
return
filePath = path.userPath + fileName
if not fileExists(str(filePath)):
raise exception.CheckpyError("Required file {} does not exist"... | newSource = "" |
Using the snippet: <|code_start|>
class Test(object):
def __init__(self, fileName, priority):
self._fileName = fileName
self._priority = priority
def __lt__(self, other):
return self._priority < other._priority
@property
def fileName(self):
return self._fileName
@caches.cache()
<|code_end|>
, determine ... | def run(self): |
Continue the code snippet: <|code_start|>
def __lt__(self, other):
return self._priority < other._priority
@property
def fileName(self):
return self._fileName
@caches.cache()
def run(self):
try:
result = self.test()
if type(result) == tuple:
hasPassed, info = result
else:
hasPassed, info ... | raise NotImplementedError() |
Given the following code snippet before the placeholder: <|code_start|>
def source(fileName):
with open(fileName) as f:
return f.read()
@caches.cache()
def fullSyntaxTree(fileName):
return fstFromSource(source(fileName))
@caches.cache()
def fstFromSource(source):
return redbaron.RedBaron(source)
@caches.cache()... | return definitions[0] |
Given the following code snippet before the placeholder: <|code_start|>def forEachGithubPath():
for entry in githubTable().all():
yield Path(entry["path"])
def forEachLocalPath():
for entry in localTable().all():
yield Path(entry["path"])
def isKnownGithub(username, repoName):
query = tinydb.Query()
return gi... | table.insert({ |
Here is a snippet: <|code_start|> })
def updateGithubTable(username, repoName, releaseId, releaseTag):
query = tinydb.Query()
path = str(CHECKPYPATH + "tests" + repoName)
githubTable().update({
"user" : username,
"repo" : repoName,
"path" : path,
"release" : releaseId,
"tag" : release... | query = tinydb.Query() |
Using the snippet: <|code_start|>
log = logging.getLogger('pipelines')
class PluginManager():
def __init__(self):
self.plugins = {}
def get_plugin(self, name):
return self.plugins.get(name)
def trigger(self, event_name, *args):
callbacks = self.plugins.get(event_name, [])
... | return results |
Predict the next line for this snippet: <|code_start|> return reduce(lambda counter, p: counter + len(p), self.plugins.values(), 0)
if hook_name in self.plugins:
return len(self.plugins[hook_name])
return 0
def register_plugin(self, plugin_class, conf_dict):
if not i... | if __name__ == '__main__': |
Here is a snippet: <|code_start|> def trigger(self, event_name, *args):
callbacks = self.plugins.get(event_name, [])
results = []
for cb in callbacks:
try:
ret = cb(*args)
results.append(ret)
except Exception:
log.error('... | for k in ['hook_prefix', 'hooks']: |
Given the code snippet: <|code_start|>
log = logging.getLogger('pipelines')
RETRY_COUNT = 2
class SlackExecutor(BaseExecutorPlugin):
hook_prefix = 'slack'
hooks = ('execute',)
# webhook_url = 'https://hooks.slack.com/services/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'
def __init__(self, slack_web... | if not self.slack_webhook: |
Given the following code snippet before the placeholder: <|code_start|> # webhook_url = 'https://hooks.slack.com/services/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'
def __init__(self, slack_webhook):
self.slack_webhook = slack_webhook
def execute(self, args_dict):
if not self.slack_webho... | else: |
Given snippet: <|code_start|>
log = logging.getLogger('pipelines')
RETRY_COUNT = 2
class SlackExecutor(BaseExecutorPlugin):
hook_prefix = 'slack'
hooks = ('execute',)
# webhook_url = 'https://hooks.slack.com/services/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'
def __init__(self, slack_webhook):
... | 'username': 'Pipelines', |
Given the following code snippet before the placeholder: <|code_start|>
log = logging.getLogger('pipelines')
RETRY_COUNT = 2
class SlackExecutor(BaseExecutorPlugin):
hook_prefix = 'slack'
hooks = ('execute',)
# webhook_url = 'https://hooks.slack.com/services/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'
... | if 'message' not in args_dict: |
Continue the code snippet: <|code_start|> message = args_dict['message']
if self.dry_run:
return TaskResult(EXECUTION_SUCCESSFUL)
payload = {
'username': 'Pipelines',
'link_names': 1,
'text': message
}
for i in range(RETRY_COUNT +... | else: |
Next line prediction: <|code_start|>
log = logging.getLogger('pipelines')
VAR_LOG_MAX_LEN = 3000
class StdoutLogger(BasePlugin):
hook_prefix = ''
hooks = (
'on_pipeline_start',
<|code_end|>
. Use current file imports:
(import json
import yaml
import logging
from datetime import datetime
from pipelin... | 'on_task_start', |
Continue the code snippet: <|code_start|>
class BaseExecutorPlugin(BasePlugin):
dry_run = False
def call(self, *args, **kwargs):
result = self.execute(*args, **kwargs)
if not isinstance(result, TaskResult):
raise PipelineError('Executor did not return type ExecutionResult, got {}'.f... | print 'Running executor with command: %s' % command |
Predict the next line for this snippet: <|code_start|>
log = logging.getLogger('pipelines')
def class_name(obj):
if isinstance(obj, type):
return obj.__name__
if hasattr(obj, '__class__') and hasattr(obj.__class__, '__name__'):
<|code_end|>
with the help of current file imports:
import json
import... | return obj.__class__.__name__ |
Next line prediction: <|code_start|>
conf_logging()
class TestPythonExecutor(TestCase):
def test_basic_script(self):
print 'Running test_basic_script'
executor = PythonExecutor()
args = {
'script': 'print "test"'
}
res = executor.execute(args)
self.asse... | } |
Given snippet: <|code_start|>
conf_logging()
class TestPythonExecutor(TestCase):
def test_basic_script(self):
print 'Running test_basic_script'
executor = PythonExecutor()
args = {
'script': 'print "test"'
}
<|code_end|>
, continue by predicting the next line. Consider... | res = executor.execute(args) |
Predict the next line after this snippet: <|code_start|>
conf_logging()
class TestPythonExecutor(TestCase):
def test_basic_script(self):
print 'Running test_basic_script'
executor = PythonExecutor()
args = {
'script': 'print "test"'
}
res = executor.execute(arg... | self.assertEqual(res.message.strip(), 'Execution finished') |
Predict the next line after this snippet: <|code_start|>
conf_logging()
class TestPythonExecutor(TestCase):
def test_basic_script(self):
print 'Running test_basic_script'
executor = PythonExecutor()
args = {
'script': 'print "test"'
}
res = executor.execute(arg... | res = executor.execute(args) |
Given the following code snippet before the placeholder: <|code_start|>
log = logging.getLogger('pipelines')
class StatusLogger(BasePlugin):
hook_prefix = ''
hooks = (
'on_pipeline_start',
'on_pipeline_finish',
)
file_path = None
def __init__(self, file_path=None):
super(... | def on_pipeline_finish(self, pipeline_context): |
Continue the code snippet: <|code_start|>
if self.dry_run:
return TaskResult(EXECUTION_SUCCESSFUL)
try:
output, return_obj = self._run_bash(cmd, timeout)
status = EXECUTION_SUCCESSFUL
msg = 'Bash task finished'
except BashExecuteError as e:
... | output['last_line'] = line |
Continue the code snippet: <|code_start|>DEFAULT_TIMEOUT = 60*60 # Timeout to 1h
class BashExecuteError(PluginError):
def __init__(self, msg, code, data={}):
self.msg = msg
self.code = code
self.data = data
class BashExecutor(BaseExecutorPlugin):
hook_prefix = 'bash'
hooks = ('ex... | return args_dict['cmd'], timeout |
Continue the code snippet: <|code_start|> return TaskResult(EXECUTION_SUCCESSFUL)
try:
output, return_obj = self._run_bash(cmd, timeout)
status = EXECUTION_SUCCESSFUL
msg = 'Bash task finished'
except BashExecuteError as e:
status = EXECUTION_F... | if f: |
Predict the next line after this snippet: <|code_start|>
output = {'stdout': '', 'last_line': ''}
try:
def process_line(line):
log.debug('Got line: %s' % line)
output['stdout'] += line
if line and line.strip():
output['last... | try: |
Here is a snippet: <|code_start|> if line and line.strip():
output['last_line'] = line
if f:
f.write(line)
if self.event_mgr:
if len(line)>0 and line[-1] == '\n':
line = line[:-1]
... | @classmethod |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.