Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Using the snippet: <|code_start|> rx = range(0, len(value), 30)
refs = reduce(lambda a, b: a & b, [count(value[i : i + 30]) for i in rx])
else:
refs = db(id.belongs(value)).select(id)
return refs and ", ".join(_fieldformat(self.ref, x) for x in value) or ""
def auto_represent(field):
if field.represent:
return field.represent
if (
field.db
and field.type.startswith("reference")
and field.type.find(".") < 0
and field.type[10:] in field.db.tables
):
referenced = field.db[field.type[10:]]
return _repr_ref(referenced)
elif (
field.db
and field.type.startswith("list:reference")
and field.type.find(".") < 0
and field.type[15:] in field.db.tables
):
referenced = field.db[field.type[15:]]
return _repr_ref_list(referenced)
return field.represent
def varquote_aux(name, quotestr="%s"):
<|code_end|>
, determine the next line of code. You have imports:
import os
import re
import uuid
from .._compat import (
PY2,
BytesIO,
iteritems,
integer_types,
string_types,
to_bytes,
pjoin,
exists,
text_type,
)
from .regex import REGEX_CREDENTIALS, REGEX_UNPACK, REGEX_CONST_STRING, REGEX_W
from .classes import SQLCustomType
from ..objects import Field, Table
and context (class names, function names, or code) available:
# Path: pydal/_compat.py
# PY2 = sys.version_info[0] == 2
# def implements_bool(cls):
# def implements_iterator(cls):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def with_metaclass(meta, *bases):
# def __new__(cls, name, this_bases, d):
# def to_unicode(obj, charset="utf-8", errors="strict"):
# class metaclass(meta):
#
# Path: pydal/helpers/regex.py
# REGEX_CREDENTIALS = r"(?<=//)[\w.-]+([:/][^@]*)?(?=@)"
#
# REGEX_UNPACK = r"(?<!\|)\|(?!\|)"
#
# REGEX_CONST_STRING = '("[^"]*")|' "('[^']*')"
#
# REGEX_W = re.compile(r"^\w+$")
#
# Path: pydal/helpers/classes.py
# class SQLCustomType(object):
# """
# Allows defining of custom SQL types
#
# Args:
# type: the web2py type (default = 'string')
# native: the backend type
# encoder: how to encode the value to store it in the backend
# decoder: how to decode the value retrieved from the backend
# validator: what validators to use ( default = None, will use the
# default validator for type)
#
# Example::
# Define as:
#
# decimal = SQLCustomType(
# type ='double',
# native ='integer',
# encoder =(lambda x: int(float(x) * 100)),
# decoder = (lambda x: Decimal("0.00") + Decimal(str(float(x)/100)) )
# )
#
# db.define_table(
# 'example',
# Field('value', type=decimal)
# )
#
# """
#
# def __init__(
# self,
# type="string",
# native=None,
# encoder=None,
# decoder=None,
# validator=None,
# _class=None,
# widget=None,
# represent=None,
# ):
# self.type = type
# self.native = native
# self.encoder = encoder or (lambda x: x)
# self.decoder = decoder or (lambda x: x)
# self.validator = validator
# self._class = _class or type
# self.widget = widget
# self.represent = represent
#
# def startswith(self, text=None):
# try:
# return self.type.startswith(self, text)
# except TypeError:
# return False
#
# def endswith(self, text=None):
# try:
# return self.type.endswith(self, text)
# except TypeError:
# return False
#
# def __getslice__(self, a=0, b=100):
# return None
#
# def __getitem__(self, i):
# return None
#
# def __str__(self):
# return self._class
. Output only the next line. | return name if REGEX_W.match(name) else quotestr % name |
Given the code snippet: <|code_start|> new_query = field.endswith(value)
else:
raise RuntimeError("Invalid operation")
elif field._db._adapter.dbengine == "google:datastore" and field.type in (
"list:integer",
"list:string",
"list:reference",
):
if op == "contains":
new_query = field.contains(value)
else:
raise RuntimeError("Invalid operation")
else:
raise RuntimeError("Invalid operation")
if neg:
new_query = ~new_query
if query is None:
query = new_query
elif logic == "and":
query &= new_query
elif logic == "or":
query |= new_query
field = op = neg = logic = None
return query
def auto_validators(field):
db = field.db
field_type = field.type
#: don't apply default validation on custom types
<|code_end|>
, generate the next line using the imports in this file:
import os
import re
import uuid
from .._compat import (
PY2,
BytesIO,
iteritems,
integer_types,
string_types,
to_bytes,
pjoin,
exists,
text_type,
)
from .regex import REGEX_CREDENTIALS, REGEX_UNPACK, REGEX_CONST_STRING, REGEX_W
from .classes import SQLCustomType
from ..objects import Field, Table
and context (functions, classes, or occasionally code) from other files:
# Path: pydal/_compat.py
# PY2 = sys.version_info[0] == 2
# def implements_bool(cls):
# def implements_iterator(cls):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def with_metaclass(meta, *bases):
# def __new__(cls, name, this_bases, d):
# def to_unicode(obj, charset="utf-8", errors="strict"):
# class metaclass(meta):
#
# Path: pydal/helpers/regex.py
# REGEX_CREDENTIALS = r"(?<=//)[\w.-]+([:/][^@]*)?(?=@)"
#
# REGEX_UNPACK = r"(?<!\|)\|(?!\|)"
#
# REGEX_CONST_STRING = '("[^"]*")|' "('[^']*')"
#
# REGEX_W = re.compile(r"^\w+$")
#
# Path: pydal/helpers/classes.py
# class SQLCustomType(object):
# """
# Allows defining of custom SQL types
#
# Args:
# type: the web2py type (default = 'string')
# native: the backend type
# encoder: how to encode the value to store it in the backend
# decoder: how to decode the value retrieved from the backend
# validator: what validators to use ( default = None, will use the
# default validator for type)
#
# Example::
# Define as:
#
# decimal = SQLCustomType(
# type ='double',
# native ='integer',
# encoder =(lambda x: int(float(x) * 100)),
# decoder = (lambda x: Decimal("0.00") + Decimal(str(float(x)/100)) )
# )
#
# db.define_table(
# 'example',
# Field('value', type=decimal)
# )
#
# """
#
# def __init__(
# self,
# type="string",
# native=None,
# encoder=None,
# decoder=None,
# validator=None,
# _class=None,
# widget=None,
# represent=None,
# ):
# self.type = type
# self.native = native
# self.encoder = encoder or (lambda x: x)
# self.decoder = decoder or (lambda x: x)
# self.validator = validator
# self._class = _class or type
# self.widget = widget
# self.represent = represent
#
# def startswith(self, text=None):
# try:
# return self.type.startswith(self, text)
# except TypeError:
# return False
#
# def endswith(self, text=None):
# try:
# return self.type.endswith(self, text)
# except TypeError:
# return False
#
# def __getslice__(self, a=0, b=100):
# return None
#
# def __getitem__(self, i):
# return None
#
# def __str__(self):
# return self._class
. Output only the next line. | if isinstance(field_type, SQLCustomType): |
Given snippet: <|code_start|>
def tearDownModule():
if os.path.isfile("test.txt"):
os.unlink("test.txt")
class testPortalocker(unittest.TestCase):
def test_LockedFile(self):
f = LockedFile("test.txt", mode="wb")
f.write(to_bytes("test ok"))
f.close()
f = LockedFile("test.txt", mode="rb")
self.assertEqual(f.read(), to_bytes("test ok"))
f.close()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import threading
import time
from ._compat import unittest
from ._adapt import IS_GAE
from pydal._compat import to_bytes
from pydal.contrib.portalocker import lock, unlock, read_locked, write_locked
from pydal.contrib.portalocker import LockedFile, LOCK_EX
and context:
# Path: tests/_adapt.py
# IS_GAE = "datastore" in DEFAULT_URI
#
# Path: pydal/_compat.py
# def to_bytes(obj, charset="utf-8", errors="strict"):
# if obj is None:
# return None
# if isinstance(obj, (bytes, bytearray, buffer)):
# return bytes(obj)
# if isinstance(obj, unicode):
# return obj.encode(charset, errors)
# raise TypeError("Expected bytes")
#
# Path: pydal/contrib/portalocker.py
# def lock(file, flags):
# hfile = msvcrt.get_osfhandle(file.fileno())
# overlapped = OVERLAPPED()
# LockFileEx(hfile, flags, 0, 0, 0xFFFF0000, ctypes.byref(overlapped))
#
# def unlock(file):
# hfile = msvcrt.get_osfhandle(file.fileno())
# overlapped = OVERLAPPED()
# UnlockFileEx(hfile, 0, 0, 0xFFFF0000, ctypes.byref(overlapped))
#
# def read_locked(filename):
# fp = LockedFile(filename, "rb")
# data = fp.read()
# fp.close()
# return data
#
# def write_locked(filename, data):
# fp = LockedFile(filename, "wb")
# data = fp.write(data)
# fp.close()
#
# Path: pydal/contrib/portalocker.py
# class LockedFile(object):
# def __init__(self, filename, mode="rb"):
# self.filename = filename
# self.mode = mode
# self.file = None
# if "r" in mode:
# self.file = open_file(filename, mode)
# lock(self.file, LOCK_SH)
# elif "w" in mode or "a" in mode:
# self.file = open_file(filename, mode.replace("w", "a"))
# lock(self.file, LOCK_EX)
# if "a" not in mode:
# self.file.seek(0)
# self.file.truncate(0)
# else:
# raise RuntimeError("invalid LockedFile(...,mode)")
#
# def read(self, size=None):
# return self.file.read() if size is None else self.file.read(size)
#
# def readinto(self, b):
# b[:] = self.file.read()
#
# def readline(self):
# return self.file.readline()
#
# def readlines(self):
# return self.file.readlines()
#
# def write(self, data):
# self.file.write(data)
# self.file.flush()
#
# def close(self):
# if self.file is not None:
# unlock(self.file)
# self.file.close()
# self.file = None
#
# def __del__(self):
# if self.file is not None:
# self.close()
#
# LOCK_EX = 0x2 # LOCKFILE_EXCLUSIVE_LOCK
which might include code, classes, or functions. Output only the next line. | @unittest.skipIf(IS_GAE, "GAE has no locks") |
Based on the snippet: <|code_start|>
def tearDownModule():
if os.path.isfile("test.txt"):
os.unlink("test.txt")
class testPortalocker(unittest.TestCase):
def test_LockedFile(self):
f = LockedFile("test.txt", mode="wb")
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import threading
import time
from ._compat import unittest
from ._adapt import IS_GAE
from pydal._compat import to_bytes
from pydal.contrib.portalocker import lock, unlock, read_locked, write_locked
from pydal.contrib.portalocker import LockedFile, LOCK_EX
and context (classes, functions, sometimes code) from other files:
# Path: tests/_adapt.py
# IS_GAE = "datastore" in DEFAULT_URI
#
# Path: pydal/_compat.py
# def to_bytes(obj, charset="utf-8", errors="strict"):
# if obj is None:
# return None
# if isinstance(obj, (bytes, bytearray, buffer)):
# return bytes(obj)
# if isinstance(obj, unicode):
# return obj.encode(charset, errors)
# raise TypeError("Expected bytes")
#
# Path: pydal/contrib/portalocker.py
# def lock(file, flags):
# hfile = msvcrt.get_osfhandle(file.fileno())
# overlapped = OVERLAPPED()
# LockFileEx(hfile, flags, 0, 0, 0xFFFF0000, ctypes.byref(overlapped))
#
# def unlock(file):
# hfile = msvcrt.get_osfhandle(file.fileno())
# overlapped = OVERLAPPED()
# UnlockFileEx(hfile, 0, 0, 0xFFFF0000, ctypes.byref(overlapped))
#
# def read_locked(filename):
# fp = LockedFile(filename, "rb")
# data = fp.read()
# fp.close()
# return data
#
# def write_locked(filename, data):
# fp = LockedFile(filename, "wb")
# data = fp.write(data)
# fp.close()
#
# Path: pydal/contrib/portalocker.py
# class LockedFile(object):
# def __init__(self, filename, mode="rb"):
# self.filename = filename
# self.mode = mode
# self.file = None
# if "r" in mode:
# self.file = open_file(filename, mode)
# lock(self.file, LOCK_SH)
# elif "w" in mode or "a" in mode:
# self.file = open_file(filename, mode.replace("w", "a"))
# lock(self.file, LOCK_EX)
# if "a" not in mode:
# self.file.seek(0)
# self.file.truncate(0)
# else:
# raise RuntimeError("invalid LockedFile(...,mode)")
#
# def read(self, size=None):
# return self.file.read() if size is None else self.file.read(size)
#
# def readinto(self, b):
# b[:] = self.file.read()
#
# def readline(self):
# return self.file.readline()
#
# def readlines(self):
# return self.file.readlines()
#
# def write(self, data):
# self.file.write(data)
# self.file.flush()
#
# def close(self):
# if self.file is not None:
# unlock(self.file)
# self.file.close()
# self.file = None
#
# def __del__(self):
# if self.file is not None:
# self.close()
#
# LOCK_EX = 0x2 # LOCKFILE_EXCLUSIVE_LOCK
. Output only the next line. | f.write(to_bytes("test ok")) |
Predict the next line after this snippet: <|code_start|> t1 = threading.Thread(target=worker1)
th.append(t1)
t1.start()
for t in th:
t.join()
with open("test.txt") as g:
content = g.read()
results = [line.strip().split("\t") for line in content.split("\n") if line]
# all started at more or less the same time
starts = [1 for line in results if float(line[0]) - t0 < 1]
ends = [line[1] for line in results]
self.assertEqual(sum(starts), len(starts))
# end - start is at least 2
for line in results:
self.assertTrue(float(line[1]) - float(line[0]) >= 2)
# ends are not the same
self.assertTrue(len(ends) == len(ends))
@unittest.skipIf(IS_GAE, "GAE has no locks")
def test_lock_unlock(self):
def worker1(fh):
time.sleep(2)
unlock(fh)
def worker2(fh):
time.sleep(2)
fh.close()
f = open("test.txt", mode="wb")
<|code_end|>
using the current file's imports:
import os
import threading
import time
from ._compat import unittest
from ._adapt import IS_GAE
from pydal._compat import to_bytes
from pydal.contrib.portalocker import lock, unlock, read_locked, write_locked
from pydal.contrib.portalocker import LockedFile, LOCK_EX
and any relevant context from other files:
# Path: tests/_adapt.py
# IS_GAE = "datastore" in DEFAULT_URI
#
# Path: pydal/_compat.py
# def to_bytes(obj, charset="utf-8", errors="strict"):
# if obj is None:
# return None
# if isinstance(obj, (bytes, bytearray, buffer)):
# return bytes(obj)
# if isinstance(obj, unicode):
# return obj.encode(charset, errors)
# raise TypeError("Expected bytes")
#
# Path: pydal/contrib/portalocker.py
# def lock(file, flags):
# hfile = msvcrt.get_osfhandle(file.fileno())
# overlapped = OVERLAPPED()
# LockFileEx(hfile, flags, 0, 0, 0xFFFF0000, ctypes.byref(overlapped))
#
# def unlock(file):
# hfile = msvcrt.get_osfhandle(file.fileno())
# overlapped = OVERLAPPED()
# UnlockFileEx(hfile, 0, 0, 0xFFFF0000, ctypes.byref(overlapped))
#
# def read_locked(filename):
# fp = LockedFile(filename, "rb")
# data = fp.read()
# fp.close()
# return data
#
# def write_locked(filename, data):
# fp = LockedFile(filename, "wb")
# data = fp.write(data)
# fp.close()
#
# Path: pydal/contrib/portalocker.py
# class LockedFile(object):
# def __init__(self, filename, mode="rb"):
# self.filename = filename
# self.mode = mode
# self.file = None
# if "r" in mode:
# self.file = open_file(filename, mode)
# lock(self.file, LOCK_SH)
# elif "w" in mode or "a" in mode:
# self.file = open_file(filename, mode.replace("w", "a"))
# lock(self.file, LOCK_EX)
# if "a" not in mode:
# self.file.seek(0)
# self.file.truncate(0)
# else:
# raise RuntimeError("invalid LockedFile(...,mode)")
#
# def read(self, size=None):
# return self.file.read() if size is None else self.file.read(size)
#
# def readinto(self, b):
# b[:] = self.file.read()
#
# def readline(self):
# return self.file.readline()
#
# def readlines(self):
# return self.file.readlines()
#
# def write(self, data):
# self.file.write(data)
# self.file.flush()
#
# def close(self):
# if self.file is not None:
# unlock(self.file)
# self.file.close()
# self.file = None
#
# def __del__(self):
# if self.file is not None:
# self.close()
#
# LOCK_EX = 0x2 # LOCKFILE_EXCLUSIVE_LOCK
. Output only the next line. | lock(f, LOCK_EX) |
Given the code snippet: <|code_start|> f1.close()
f = LockedFile("test.txt", mode="wb")
f.write(to_bytes(""))
f.close()
th = []
for x in range(10):
t1 = threading.Thread(target=worker1)
th.append(t1)
t1.start()
for t in th:
t.join()
with open("test.txt") as g:
content = g.read()
results = [line.strip().split("\t") for line in content.split("\n") if line]
# all started at more or less the same time
starts = [1 for line in results if float(line[0]) - t0 < 1]
ends = [line[1] for line in results]
self.assertEqual(sum(starts), len(starts))
# end - start is at least 2
for line in results:
self.assertTrue(float(line[1]) - float(line[0]) >= 2)
# ends are not the same
self.assertTrue(len(ends) == len(ends))
@unittest.skipIf(IS_GAE, "GAE has no locks")
def test_lock_unlock(self):
def worker1(fh):
time.sleep(2)
<|code_end|>
, generate the next line using the imports in this file:
import os
import threading
import time
from ._compat import unittest
from ._adapt import IS_GAE
from pydal._compat import to_bytes
from pydal.contrib.portalocker import lock, unlock, read_locked, write_locked
from pydal.contrib.portalocker import LockedFile, LOCK_EX
and context (functions, classes, or occasionally code) from other files:
# Path: tests/_adapt.py
# IS_GAE = "datastore" in DEFAULT_URI
#
# Path: pydal/_compat.py
# def to_bytes(obj, charset="utf-8", errors="strict"):
# if obj is None:
# return None
# if isinstance(obj, (bytes, bytearray, buffer)):
# return bytes(obj)
# if isinstance(obj, unicode):
# return obj.encode(charset, errors)
# raise TypeError("Expected bytes")
#
# Path: pydal/contrib/portalocker.py
# def lock(file, flags):
# hfile = msvcrt.get_osfhandle(file.fileno())
# overlapped = OVERLAPPED()
# LockFileEx(hfile, flags, 0, 0, 0xFFFF0000, ctypes.byref(overlapped))
#
# def unlock(file):
# hfile = msvcrt.get_osfhandle(file.fileno())
# overlapped = OVERLAPPED()
# UnlockFileEx(hfile, 0, 0, 0xFFFF0000, ctypes.byref(overlapped))
#
# def read_locked(filename):
# fp = LockedFile(filename, "rb")
# data = fp.read()
# fp.close()
# return data
#
# def write_locked(filename, data):
# fp = LockedFile(filename, "wb")
# data = fp.write(data)
# fp.close()
#
# Path: pydal/contrib/portalocker.py
# class LockedFile(object):
# def __init__(self, filename, mode="rb"):
# self.filename = filename
# self.mode = mode
# self.file = None
# if "r" in mode:
# self.file = open_file(filename, mode)
# lock(self.file, LOCK_SH)
# elif "w" in mode or "a" in mode:
# self.file = open_file(filename, mode.replace("w", "a"))
# lock(self.file, LOCK_EX)
# if "a" not in mode:
# self.file.seek(0)
# self.file.truncate(0)
# else:
# raise RuntimeError("invalid LockedFile(...,mode)")
#
# def read(self, size=None):
# return self.file.read() if size is None else self.file.read(size)
#
# def readinto(self, b):
# b[:] = self.file.read()
#
# def readline(self):
# return self.file.readline()
#
# def readlines(self):
# return self.file.readlines()
#
# def write(self, data):
# self.file.write(data)
# self.file.flush()
#
# def close(self):
# if self.file is not None:
# unlock(self.file)
# self.file.close()
# self.file = None
#
# def __del__(self):
# if self.file is not None:
# self.close()
#
# LOCK_EX = 0x2 # LOCKFILE_EXCLUSIVE_LOCK
. Output only the next line. | unlock(fh) |
Based on the snippet: <|code_start|> with open("test.txt") as g:
content = g.read()
results = [line.strip().split("\t") for line in content.split("\n") if line]
# all started at more or less the same time
starts = [1 for line in results if float(line[0]) - t0 < 1]
ends = [line[1] for line in results]
self.assertEqual(sum(starts), len(starts))
# end - start is at least 2
for line in results:
self.assertTrue(float(line[1]) - float(line[0]) >= 2)
# ends are not the same
self.assertTrue(len(ends) == len(ends))
@unittest.skipIf(IS_GAE, "GAE has no locks")
def test_lock_unlock(self):
def worker1(fh):
time.sleep(2)
unlock(fh)
def worker2(fh):
time.sleep(2)
fh.close()
f = open("test.txt", mode="wb")
lock(f, LOCK_EX)
f.write(to_bytes("test ok"))
t1 = threading.Thread(target=worker1, args=(f,))
t1.start()
start = int(time.time())
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import threading
import time
from ._compat import unittest
from ._adapt import IS_GAE
from pydal._compat import to_bytes
from pydal.contrib.portalocker import lock, unlock, read_locked, write_locked
from pydal.contrib.portalocker import LockedFile, LOCK_EX
and context (classes, functions, sometimes code) from other files:
# Path: tests/_adapt.py
# IS_GAE = "datastore" in DEFAULT_URI
#
# Path: pydal/_compat.py
# def to_bytes(obj, charset="utf-8", errors="strict"):
# if obj is None:
# return None
# if isinstance(obj, (bytes, bytearray, buffer)):
# return bytes(obj)
# if isinstance(obj, unicode):
# return obj.encode(charset, errors)
# raise TypeError("Expected bytes")
#
# Path: pydal/contrib/portalocker.py
# def lock(file, flags):
# hfile = msvcrt.get_osfhandle(file.fileno())
# overlapped = OVERLAPPED()
# LockFileEx(hfile, flags, 0, 0, 0xFFFF0000, ctypes.byref(overlapped))
#
# def unlock(file):
# hfile = msvcrt.get_osfhandle(file.fileno())
# overlapped = OVERLAPPED()
# UnlockFileEx(hfile, 0, 0, 0xFFFF0000, ctypes.byref(overlapped))
#
# def read_locked(filename):
# fp = LockedFile(filename, "rb")
# data = fp.read()
# fp.close()
# return data
#
# def write_locked(filename, data):
# fp = LockedFile(filename, "wb")
# data = fp.write(data)
# fp.close()
#
# Path: pydal/contrib/portalocker.py
# class LockedFile(object):
# def __init__(self, filename, mode="rb"):
# self.filename = filename
# self.mode = mode
# self.file = None
# if "r" in mode:
# self.file = open_file(filename, mode)
# lock(self.file, LOCK_SH)
# elif "w" in mode or "a" in mode:
# self.file = open_file(filename, mode.replace("w", "a"))
# lock(self.file, LOCK_EX)
# if "a" not in mode:
# self.file.seek(0)
# self.file.truncate(0)
# else:
# raise RuntimeError("invalid LockedFile(...,mode)")
#
# def read(self, size=None):
# return self.file.read() if size is None else self.file.read(size)
#
# def readinto(self, b):
# b[:] = self.file.read()
#
# def readline(self):
# return self.file.readline()
#
# def readlines(self):
# return self.file.readlines()
#
# def write(self, data):
# self.file.write(data)
# self.file.flush()
#
# def close(self):
# if self.file is not None:
# unlock(self.file)
# self.file.close()
# self.file = None
#
# def __del__(self):
# if self.file is not None:
# self.close()
#
# LOCK_EX = 0x2 # LOCKFILE_EXCLUSIVE_LOCK
. Output only the next line. | content = read_locked("test.txt") |
Predict the next line for this snippet: <|code_start|>
@unittest.skipIf(IS_GAE, "GAE has no locks")
def test_read_locked(self):
def worker(fh):
time.sleep(2)
fh.close()
f = LockedFile("test.txt", mode="wb")
f.write(to_bytes("test ok"))
t1 = threading.Thread(target=worker, args=(f,))
t1.start()
start = int(time.time())
content = read_locked("test.txt")
end = int(time.time())
t1.join()
# it took at least 2 seconds to read
self.assertTrue(end - start >= 2)
self.assertEqual(content, to_bytes("test ok"))
@unittest.skipIf(IS_GAE, "GAE has no locks")
def test_write_locked(self):
def worker(fh):
time.sleep(2)
fh.close()
f = open("test.txt", mode="wb")
lock(f, LOCK_EX)
t1 = threading.Thread(target=worker, args=(f,))
t1.start()
start = int(time.time())
<|code_end|>
with the help of current file imports:
import os
import threading
import time
from ._compat import unittest
from ._adapt import IS_GAE
from pydal._compat import to_bytes
from pydal.contrib.portalocker import lock, unlock, read_locked, write_locked
from pydal.contrib.portalocker import LockedFile, LOCK_EX
and context from other files:
# Path: tests/_adapt.py
# IS_GAE = "datastore" in DEFAULT_URI
#
# Path: pydal/_compat.py
# def to_bytes(obj, charset="utf-8", errors="strict"):
# if obj is None:
# return None
# if isinstance(obj, (bytes, bytearray, buffer)):
# return bytes(obj)
# if isinstance(obj, unicode):
# return obj.encode(charset, errors)
# raise TypeError("Expected bytes")
#
# Path: pydal/contrib/portalocker.py
# def lock(file, flags):
# hfile = msvcrt.get_osfhandle(file.fileno())
# overlapped = OVERLAPPED()
# LockFileEx(hfile, flags, 0, 0, 0xFFFF0000, ctypes.byref(overlapped))
#
# def unlock(file):
# hfile = msvcrt.get_osfhandle(file.fileno())
# overlapped = OVERLAPPED()
# UnlockFileEx(hfile, 0, 0, 0xFFFF0000, ctypes.byref(overlapped))
#
# def read_locked(filename):
# fp = LockedFile(filename, "rb")
# data = fp.read()
# fp.close()
# return data
#
# def write_locked(filename, data):
# fp = LockedFile(filename, "wb")
# data = fp.write(data)
# fp.close()
#
# Path: pydal/contrib/portalocker.py
# class LockedFile(object):
# def __init__(self, filename, mode="rb"):
# self.filename = filename
# self.mode = mode
# self.file = None
# if "r" in mode:
# self.file = open_file(filename, mode)
# lock(self.file, LOCK_SH)
# elif "w" in mode or "a" in mode:
# self.file = open_file(filename, mode.replace("w", "a"))
# lock(self.file, LOCK_EX)
# if "a" not in mode:
# self.file.seek(0)
# self.file.truncate(0)
# else:
# raise RuntimeError("invalid LockedFile(...,mode)")
#
# def read(self, size=None):
# return self.file.read() if size is None else self.file.read(size)
#
# def readinto(self, b):
# b[:] = self.file.read()
#
# def readline(self):
# return self.file.readline()
#
# def readlines(self):
# return self.file.readlines()
#
# def write(self, data):
# self.file.write(data)
# self.file.flush()
#
# def close(self):
# if self.file is not None:
# unlock(self.file)
# self.file.close()
# self.file = None
#
# def __del__(self):
# if self.file is not None:
# self.close()
#
# LOCK_EX = 0x2 # LOCKFILE_EXCLUSIVE_LOCK
, which may contain function names, class names, or code. Output only the next line. | write_locked("test.txt", to_bytes("test ok")) |
Given snippet: <|code_start|>
def tearDownModule():
if os.path.isfile("test.txt"):
os.unlink("test.txt")
class testPortalocker(unittest.TestCase):
def test_LockedFile(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import threading
import time
from ._compat import unittest
from ._adapt import IS_GAE
from pydal._compat import to_bytes
from pydal.contrib.portalocker import lock, unlock, read_locked, write_locked
from pydal.contrib.portalocker import LockedFile, LOCK_EX
and context:
# Path: tests/_adapt.py
# IS_GAE = "datastore" in DEFAULT_URI
#
# Path: pydal/_compat.py
# def to_bytes(obj, charset="utf-8", errors="strict"):
# if obj is None:
# return None
# if isinstance(obj, (bytes, bytearray, buffer)):
# return bytes(obj)
# if isinstance(obj, unicode):
# return obj.encode(charset, errors)
# raise TypeError("Expected bytes")
#
# Path: pydal/contrib/portalocker.py
# def lock(file, flags):
# hfile = msvcrt.get_osfhandle(file.fileno())
# overlapped = OVERLAPPED()
# LockFileEx(hfile, flags, 0, 0, 0xFFFF0000, ctypes.byref(overlapped))
#
# def unlock(file):
# hfile = msvcrt.get_osfhandle(file.fileno())
# overlapped = OVERLAPPED()
# UnlockFileEx(hfile, 0, 0, 0xFFFF0000, ctypes.byref(overlapped))
#
# def read_locked(filename):
# fp = LockedFile(filename, "rb")
# data = fp.read()
# fp.close()
# return data
#
# def write_locked(filename, data):
# fp = LockedFile(filename, "wb")
# data = fp.write(data)
# fp.close()
#
# Path: pydal/contrib/portalocker.py
# class LockedFile(object):
# def __init__(self, filename, mode="rb"):
# self.filename = filename
# self.mode = mode
# self.file = None
# if "r" in mode:
# self.file = open_file(filename, mode)
# lock(self.file, LOCK_SH)
# elif "w" in mode or "a" in mode:
# self.file = open_file(filename, mode.replace("w", "a"))
# lock(self.file, LOCK_EX)
# if "a" not in mode:
# self.file.seek(0)
# self.file.truncate(0)
# else:
# raise RuntimeError("invalid LockedFile(...,mode)")
#
# def read(self, size=None):
# return self.file.read() if size is None else self.file.read(size)
#
# def readinto(self, b):
# b[:] = self.file.read()
#
# def readline(self):
# return self.file.readline()
#
# def readlines(self):
# return self.file.readlines()
#
# def write(self, data):
# self.file.write(data)
# self.file.flush()
#
# def close(self):
# if self.file is not None:
# unlock(self.file)
# self.file.close()
# self.file = None
#
# def __del__(self):
# if self.file is not None:
# self.close()
#
# LOCK_EX = 0x2 # LOCKFILE_EXCLUSIVE_LOCK
which might include code, classes, or functions. Output only the next line. | f = LockedFile("test.txt", mode="wb") |
Given the following code snippet before the placeholder: <|code_start|> t1 = threading.Thread(target=worker1)
th.append(t1)
t1.start()
for t in th:
t.join()
with open("test.txt") as g:
content = g.read()
results = [line.strip().split("\t") for line in content.split("\n") if line]
# all started at more or less the same time
starts = [1 for line in results if float(line[0]) - t0 < 1]
ends = [line[1] for line in results]
self.assertEqual(sum(starts), len(starts))
# end - start is at least 2
for line in results:
self.assertTrue(float(line[1]) - float(line[0]) >= 2)
# ends are not the same
self.assertTrue(len(ends) == len(ends))
@unittest.skipIf(IS_GAE, "GAE has no locks")
def test_lock_unlock(self):
def worker1(fh):
time.sleep(2)
unlock(fh)
def worker2(fh):
time.sleep(2)
fh.close()
f = open("test.txt", mode="wb")
<|code_end|>
, predict the next line using imports from the current file:
import os
import threading
import time
from ._compat import unittest
from ._adapt import IS_GAE
from pydal._compat import to_bytes
from pydal.contrib.portalocker import lock, unlock, read_locked, write_locked
from pydal.contrib.portalocker import LockedFile, LOCK_EX
and context including class names, function names, and sometimes code from other files:
# Path: tests/_adapt.py
# IS_GAE = "datastore" in DEFAULT_URI
#
# Path: pydal/_compat.py
# def to_bytes(obj, charset="utf-8", errors="strict"):
# if obj is None:
# return None
# if isinstance(obj, (bytes, bytearray, buffer)):
# return bytes(obj)
# if isinstance(obj, unicode):
# return obj.encode(charset, errors)
# raise TypeError("Expected bytes")
#
# Path: pydal/contrib/portalocker.py
# def lock(file, flags):
# hfile = msvcrt.get_osfhandle(file.fileno())
# overlapped = OVERLAPPED()
# LockFileEx(hfile, flags, 0, 0, 0xFFFF0000, ctypes.byref(overlapped))
#
# def unlock(file):
# hfile = msvcrt.get_osfhandle(file.fileno())
# overlapped = OVERLAPPED()
# UnlockFileEx(hfile, 0, 0, 0xFFFF0000, ctypes.byref(overlapped))
#
# def read_locked(filename):
# fp = LockedFile(filename, "rb")
# data = fp.read()
# fp.close()
# return data
#
# def write_locked(filename, data):
# fp = LockedFile(filename, "wb")
# data = fp.write(data)
# fp.close()
#
# Path: pydal/contrib/portalocker.py
# class LockedFile(object):
# def __init__(self, filename, mode="rb"):
# self.filename = filename
# self.mode = mode
# self.file = None
# if "r" in mode:
# self.file = open_file(filename, mode)
# lock(self.file, LOCK_SH)
# elif "w" in mode or "a" in mode:
# self.file = open_file(filename, mode.replace("w", "a"))
# lock(self.file, LOCK_EX)
# if "a" not in mode:
# self.file.seek(0)
# self.file.truncate(0)
# else:
# raise RuntimeError("invalid LockedFile(...,mode)")
#
# def read(self, size=None):
# return self.file.read() if size is None else self.file.read(size)
#
# def readinto(self, b):
# b[:] = self.file.read()
#
# def readline(self):
# return self.file.readline()
#
# def readlines(self):
# return self.file.readlines()
#
# def write(self, data):
# self.file.write(data)
# self.file.flush()
#
# def close(self):
# if self.file is not None:
# unlock(self.file)
# self.file.close()
# self.file = None
#
# def __del__(self):
# if self.file is not None:
# self.close()
#
# LOCK_EX = 0x2 # LOCKFILE_EXCLUSIVE_LOCK
. Output only the next line. | lock(f, LOCK_EX) |
Predict the next line for this snippet: <|code_start|> REGEX_SQUARE_BRACKETS, tokens[-1]
):
new_patterns = self.auto_table(
tokens[-1][tokens[-1].find("[") + 1 : -1], "/".join(tokens[:-1])
)
patterns = patterns[:i] + new_patterns + patterns[i + 1 :]
i += len(new_patterns)
else:
i += 1
if "/".join(args) == "patterns":
return self.db.Row(
{"status": 200, "pattern": "list", "error": None, "response": patterns}
)
for pattern in patterns:
basequery, exposedfields = None, []
if isinstance(pattern, tuple):
if len(pattern) == 2:
pattern, basequery = pattern
elif len(pattern) > 2:
pattern, basequery, exposedfields = pattern[0:3]
otable = table = None
if not isinstance(queries, dict):
dbset = self.db(queries)
if basequery is not None:
dbset = dbset(basequery)
i = 0
tags = pattern[1:].split("/")
if len(tags) != len(args):
continue
for tag in tags:
<|code_end|>
with the help of current file imports:
import re
from .regex import REGEX_SEARCH_PATTERN, REGEX_SQUARE_BRACKETS
from .._compat import long
and context from other files:
# Path: pydal/helpers/regex.py
# REGEX_SEARCH_PATTERN = r"^{[^.]+\.[^.]+(\.(lt|gt|le|ge|eq|ne|contains|startswith|year|month|day|hour|minute|second))?(\.not)?}$"
#
# REGEX_SQUARE_BRACKETS = r"^.+\[.+\]$"
#
# Path: pydal/_compat.py
# PY2 = sys.version_info[0] == 2
# def implements_bool(cls):
# def implements_iterator(cls):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def with_metaclass(meta, *bases):
# def __new__(cls, name, this_bases, d):
# def to_unicode(obj, charset="utf-8", errors="strict"):
# class metaclass(meta):
, which may contain function names, class names, or code. Output only the next line. | if re.match(REGEX_SEARCH_PATTERN, tag): |
Given the code snippet: <|code_start|> parser = db.parse_as_rest(patterns,args,vars)
if parser.status == 200:
return dict(content=parser.response)
else:
raise HTTP(parser.status,parser.error)
def POST(table_name,**vars):
if table_name == 'person':
return db.person.validate_and_insert(**vars)
elif table_name == 'pet':
return db.pet.validate_and_insert(**vars)
else:
raise HTTP(400)
return locals()
"""
if patterns == "auto":
patterns = []
for table in self.db.tables:
if not table.startswith("auth_"):
patterns.append("/%s[%s]" % (table, table))
patterns += self.auto_table(table, base="", depth=1)
else:
i = 0
while i < len(patterns):
pattern = patterns[i]
if not isinstance(pattern, str):
pattern = pattern[0]
tokens = pattern.split("/")
if tokens[-1].startswith(":auto") and re.match(
<|code_end|>
, generate the next line using the imports in this file:
import re
from .regex import REGEX_SEARCH_PATTERN, REGEX_SQUARE_BRACKETS
from .._compat import long
and context (functions, classes, or occasionally code) from other files:
# Path: pydal/helpers/regex.py
# REGEX_SEARCH_PATTERN = r"^{[^.]+\.[^.]+(\.(lt|gt|le|ge|eq|ne|contains|startswith|year|month|day|hour|minute|second))?(\.not)?}$"
#
# REGEX_SQUARE_BRACKETS = r"^.+\[.+\]$"
#
# Path: pydal/_compat.py
# PY2 = sys.version_info[0] == 2
# def implements_bool(cls):
# def implements_iterator(cls):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def with_metaclass(meta, *bases):
# def __new__(cls, name, this_bases, d):
# def to_unicode(obj, charset="utf-8", errors="strict"):
# class metaclass(meta):
. Output only the next line. | REGEX_SQUARE_BRACKETS, tokens[-1] |
Given the following code snippet before the placeholder: <|code_start|>
def to_num(num):
result = 0
try:
<|code_end|>
, predict the next line using imports from the current file:
import re
from .regex import REGEX_SEARCH_PATTERN, REGEX_SQUARE_BRACKETS
from .._compat import long
and context including class names, function names, and sometimes code from other files:
# Path: pydal/helpers/regex.py
# REGEX_SEARCH_PATTERN = r"^{[^.]+\.[^.]+(\.(lt|gt|le|ge|eq|ne|contains|startswith|year|month|day|hour|minute|second))?(\.not)?}$"
#
# REGEX_SQUARE_BRACKETS = r"^.+\[.+\]$"
#
# Path: pydal/_compat.py
# PY2 = sys.version_info[0] == 2
# def implements_bool(cls):
# def implements_iterator(cls):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def with_metaclass(meta, *bases):
# def __new__(cls, name, this_bases, d):
# def to_unicode(obj, charset="utf-8", errors="strict"):
# class metaclass(meta):
. Output only the next line. | result = long(num) |
Based on the snippet: <|code_start|> _custom_ = {}
def _json_parse(self, o):
if hasattr(o, "custom_json") and callable(o.custom_json):
return o.custom_json()
if isinstance(o, (datetime.date, datetime.datetime, datetime.time)):
return o.isoformat()[:19].replace("T", " ")
elif isinstance(o, long):
return int(o)
elif isinstance(o, decimal.Decimal):
return str(o)
elif isinstance(o, set):
return list(o)
elif hasattr(o, "as_list") and callable(o.as_list):
return o.as_list()
elif hasattr(o, "as_dict") and callable(o.as_dict):
return o.as_dict()
if self._custom_.get("json") is not None:
return self._custom_["json"](o)
raise TypeError(repr(o) + " is not JSON serializable")
def __getattr__(self, name):
if self._custom_.get(name) is not None:
return self._custom_[name]
raise NotImplementedError("No " + str(name) + " serializer available.")
def json(self, value):
value = jsonlib.dumps(value, default=self._json_parse)
rep28 = r"\u2028"
rep29 = r"\2029"
<|code_end|>
, predict the immediate next line with the help of imports:
import datetime
import decimal
import json as jsonlib
from .._compat import PY2, integer_types
from yaml import dump
and context (classes, functions, sometimes code) from other files:
# Path: pydal/_compat.py
# PY2 = sys.version_info[0] == 2
# def implements_bool(cls):
# def implements_iterator(cls):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def with_metaclass(meta, *bases):
# def __new__(cls, name, this_bases, d):
# def to_unicode(obj, charset="utf-8", errors="strict"):
# class metaclass(meta):
. Output only the next line. | if PY2: |
Based on the snippet: <|code_start|> colset, db, tablename, id = self.colset, self.db, self.tablename, self.id
table = db[tablename]
newfields = fields or dict(colset)
for fieldname in list(newfields.keys()):
if fieldname not in table.fields or table[fieldname].type == "id":
del newfields[fieldname]
table._db(table._id == id, ignore_common_filters=True).update(**newfields)
colset.update(newfields)
return colset
class RecordDeleter(RecordOperator):
def __call__(self):
return self.db(self.db[self.tablename]._id == self.id).delete()
class MethodAdder(object):
def __init__(self, table):
self.table = table
def __call__(self):
return self.register()
def __getattr__(self, method_name):
return self.register(method_name)
def register(self, method_name=None):
def _decorated(f):
instance = self.table
<|code_end|>
, predict the immediate next line with the help of imports:
import copy
import marshal
import struct
import threading
import time
import traceback
import types
from .._compat import (
PY2,
exists,
copyreg,
implements_bool,
iterkeys,
itervalues,
iteritems,
to_bytes,
long,
)
from .._globals import THREAD_LOCAL
from .serializers import serializers
and context (classes, functions, sometimes code) from other files:
# Path: pydal/_compat.py
# PY2 = sys.version_info[0] == 2
# def implements_bool(cls):
# def implements_iterator(cls):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def with_metaclass(meta, *bases):
# def __new__(cls, name, this_bases, d):
# def to_unicode(obj, charset="utf-8", errors="strict"):
# class metaclass(meta):
#
# Path: pydal/helpers/serializers.py
# class Serializers(object):
# def _json_parse(self, o):
# def __getattr__(self, name):
# def json(self, value):
# def yaml(self, value):
. Output only the next line. | if PY2: |
Continue the code snippet: <|code_start|> @staticmethod
def try_create_web2py_filesystem(db):
if db._uri not in DatabaseStoredFile.web2py_filesystems:
if db._adapter.dbengine not in ("mysql", "postgres", "sqlite"):
raise NotImplementedError(
"DatabaseStoredFile only supported by mysql, potresql, sqlite"
)
sql = "CREATE TABLE IF NOT EXISTS web2py_filesystem (path VARCHAR(255), content BLOB, PRIMARY KEY(path));"
if db._adapter.dbengine == "mysql":
sql = sql[:-1] + " ENGINE=InnoDB;"
db.executesql(sql)
DatabaseStoredFile.web2py_filesystems.add(db._uri)
def __init__(self, db, filename, mode):
if db._adapter.dbengine not in ("mysql", "postgres", "sqlite"):
raise RuntimeError(
"only MySQL/Postgres/SQLite can store metadata .table files"
+ " in database for now"
)
self.db = db
self.filename = filename
self.mode = mode
DatabaseStoredFile.try_create_web2py_filesystem(db)
self.p = 0
self.data = b""
if mode in ("r", "rw", "rb", "a", "ab"):
query = "SELECT content FROM web2py_filesystem WHERE path='%s'" % filename
rows = self.db.executesql(query)
if rows:
self.data = to_bytes(rows[0][0])
<|code_end|>
. Use current file imports:
import copy
import marshal
import struct
import threading
import time
import traceback
import types
from .._compat import (
PY2,
exists,
copyreg,
implements_bool,
iterkeys,
itervalues,
iteritems,
to_bytes,
long,
)
from .._globals import THREAD_LOCAL
from .serializers import serializers
and context (classes, functions, or code) from other files:
# Path: pydal/_compat.py
# PY2 = sys.version_info[0] == 2
# def implements_bool(cls):
# def implements_iterator(cls):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def with_metaclass(meta, *bases):
# def __new__(cls, name, this_bases, d):
# def to_unicode(obj, charset="utf-8", errors="strict"):
# class metaclass(meta):
#
# Path: pydal/helpers/serializers.py
# class Serializers(object):
# def _json_parse(self, o):
# def __getattr__(self, name):
# def json(self, value):
# def yaml(self, value):
. Output only the next line. | elif exists(filename): |
Given snippet: <|code_start|>
def keys(self):
return self.__dict__.keys()
def iterkeys(self):
return iterkeys(self.__dict__)
def values(self):
return self.__dict__.values()
def itervalues(self):
return itervalues(self.__dict__)
def items(self):
return self.__dict__.items()
def iteritems(self):
return iteritems(self.__dict__)
pop = lambda self, *args, **kwargs: self.__dict__.pop(*args, **kwargs)
clear = lambda self, *args, **kwargs: self.__dict__.clear(*args, **kwargs)
copy = lambda self, *args, **kwargs: self.__dict__.copy(*args, **kwargs)
def pickle_basicstorage(s):
return BasicStorage, (dict(s),)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import copy
import marshal
import struct
import threading
import time
import traceback
import types
from .._compat import (
PY2,
exists,
copyreg,
implements_bool,
iterkeys,
itervalues,
iteritems,
to_bytes,
long,
)
from .._globals import THREAD_LOCAL
from .serializers import serializers
and context:
# Path: pydal/_compat.py
# PY2 = sys.version_info[0] == 2
# def implements_bool(cls):
# def implements_iterator(cls):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def with_metaclass(meta, *bases):
# def __new__(cls, name, this_bases, d):
# def to_unicode(obj, charset="utf-8", errors="strict"):
# class metaclass(meta):
#
# Path: pydal/helpers/serializers.py
# class Serializers(object):
# def _json_parse(self, o):
# def __getattr__(self, name):
# def json(self, value):
# def yaml(self, value):
which might include code, classes, or functions. Output only the next line. | copyreg.pickle(BasicStorage, pickle_basicstorage) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
class cachedprop(object):
#: a read-only @property that is only evaluated once.
def __init__(self, fget, doc=None):
self.fget = fget
self.__doc__ = doc or fget.__doc__
self.__name__ = fget.__name__
def __get__(self, obj, cls):
if obj is None:
return self
obj.__dict__[self.__name__] = result = self.fget(obj)
return result
<|code_end|>
, predict the next line using imports from the current file:
import copy
import marshal
import struct
import threading
import time
import traceback
import types
from .._compat import (
PY2,
exists,
copyreg,
implements_bool,
iterkeys,
itervalues,
iteritems,
to_bytes,
long,
)
from .._globals import THREAD_LOCAL
from .serializers import serializers
and context including class names, function names, and sometimes code from other files:
# Path: pydal/_compat.py
# PY2 = sys.version_info[0] == 2
# def implements_bool(cls):
# def implements_iterator(cls):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def with_metaclass(meta, *bases):
# def __new__(cls, name, this_bases, d):
# def to_unicode(obj, charset="utf-8", errors="strict"):
# class metaclass(meta):
#
# Path: pydal/helpers/serializers.py
# class Serializers(object):
# def _json_parse(self, o):
# def __getattr__(self, name):
# def json(self, value):
# def yaml(self, value):
. Output only the next line. | @implements_bool |
Given the code snippet: <|code_start|> return self.__dict__.__getitem__(str(key))
__setitem__ = object.__setattr__
def __delitem__(self, key):
try:
delattr(self, key)
except AttributeError:
raise KeyError(key)
def __bool__(self):
return len(self.__dict__) > 0
__iter__ = lambda self: self.__dict__.__iter__()
__str__ = lambda self: self.__dict__.__str__()
__repr__ = lambda self: self.__dict__.__repr__()
has_key = __contains__ = lambda self, key: key in self.__dict__
def get(self, key, default=None):
return self.__dict__.get(key, default)
def update(self, *args, **kwargs):
return self.__dict__.update(*args, **kwargs)
def keys(self):
return self.__dict__.keys()
<|code_end|>
, generate the next line using the imports in this file:
import copy
import marshal
import struct
import threading
import time
import traceback
import types
from .._compat import (
PY2,
exists,
copyreg,
implements_bool,
iterkeys,
itervalues,
iteritems,
to_bytes,
long,
)
from .._globals import THREAD_LOCAL
from .serializers import serializers
and context (functions, classes, or occasionally code) from other files:
# Path: pydal/_compat.py
# PY2 = sys.version_info[0] == 2
# def implements_bool(cls):
# def implements_iterator(cls):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def with_metaclass(meta, *bases):
# def __new__(cls, name, this_bases, d):
# def to_unicode(obj, charset="utf-8", errors="strict"):
# class metaclass(meta):
#
# Path: pydal/helpers/serializers.py
# class Serializers(object):
# def _json_parse(self, o):
# def __getattr__(self, name):
# def json(self, value):
# def yaml(self, value):
. Output only the next line. | def iterkeys(self): |
Given the following code snippet before the placeholder: <|code_start|> delattr(self, key)
except AttributeError:
raise KeyError(key)
def __bool__(self):
return len(self.__dict__) > 0
__iter__ = lambda self: self.__dict__.__iter__()
__str__ = lambda self: self.__dict__.__str__()
__repr__ = lambda self: self.__dict__.__repr__()
has_key = __contains__ = lambda self, key: key in self.__dict__
def get(self, key, default=None):
return self.__dict__.get(key, default)
def update(self, *args, **kwargs):
return self.__dict__.update(*args, **kwargs)
def keys(self):
return self.__dict__.keys()
def iterkeys(self):
return iterkeys(self.__dict__)
def values(self):
return self.__dict__.values()
<|code_end|>
, predict the next line using imports from the current file:
import copy
import marshal
import struct
import threading
import time
import traceback
import types
from .._compat import (
PY2,
exists,
copyreg,
implements_bool,
iterkeys,
itervalues,
iteritems,
to_bytes,
long,
)
from .._globals import THREAD_LOCAL
from .serializers import serializers
and context including class names, function names, and sometimes code from other files:
# Path: pydal/_compat.py
# PY2 = sys.version_info[0] == 2
# def implements_bool(cls):
# def implements_iterator(cls):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def with_metaclass(meta, *bases):
# def __new__(cls, name, this_bases, d):
# def to_unicode(obj, charset="utf-8", errors="strict"):
# class metaclass(meta):
#
# Path: pydal/helpers/serializers.py
# class Serializers(object):
# def _json_parse(self, o):
# def __getattr__(self, name):
# def json(self, value):
# def yaml(self, value):
. Output only the next line. | def itervalues(self): |
Using the snippet: <|code_start|>
__iter__ = lambda self: self.__dict__.__iter__()
__str__ = lambda self: self.__dict__.__str__()
__repr__ = lambda self: self.__dict__.__repr__()
has_key = __contains__ = lambda self, key: key in self.__dict__
def get(self, key, default=None):
return self.__dict__.get(key, default)
def update(self, *args, **kwargs):
return self.__dict__.update(*args, **kwargs)
def keys(self):
return self.__dict__.keys()
def iterkeys(self):
return iterkeys(self.__dict__)
def values(self):
return self.__dict__.values()
def itervalues(self):
return itervalues(self.__dict__)
def items(self):
return self.__dict__.items()
<|code_end|>
, determine the next line of code. You have imports:
import copy
import marshal
import struct
import threading
import time
import traceback
import types
from .._compat import (
PY2,
exists,
copyreg,
implements_bool,
iterkeys,
itervalues,
iteritems,
to_bytes,
long,
)
from .._globals import THREAD_LOCAL
from .serializers import serializers
and context (class names, function names, or code) available:
# Path: pydal/_compat.py
# PY2 = sys.version_info[0] == 2
# def implements_bool(cls):
# def implements_iterator(cls):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def with_metaclass(meta, *bases):
# def __new__(cls, name, this_bases, d):
# def to_unicode(obj, charset="utf-8", errors="strict"):
# class metaclass(meta):
#
# Path: pydal/helpers/serializers.py
# class Serializers(object):
# def _json_parse(self, o):
# def __getattr__(self, name):
# def json(self, value):
# def yaml(self, value):
. Output only the next line. | def iteritems(self): |
Based on the snippet: <|code_start|>
@staticmethod
def try_create_web2py_filesystem(db):
if db._uri not in DatabaseStoredFile.web2py_filesystems:
if db._adapter.dbengine not in ("mysql", "postgres", "sqlite"):
raise NotImplementedError(
"DatabaseStoredFile only supported by mysql, potresql, sqlite"
)
sql = "CREATE TABLE IF NOT EXISTS web2py_filesystem (path VARCHAR(255), content BLOB, PRIMARY KEY(path));"
if db._adapter.dbengine == "mysql":
sql = sql[:-1] + " ENGINE=InnoDB;"
db.executesql(sql)
DatabaseStoredFile.web2py_filesystems.add(db._uri)
def __init__(self, db, filename, mode):
if db._adapter.dbengine not in ("mysql", "postgres", "sqlite"):
raise RuntimeError(
"only MySQL/Postgres/SQLite can store metadata .table files"
+ " in database for now"
)
self.db = db
self.filename = filename
self.mode = mode
DatabaseStoredFile.try_create_web2py_filesystem(db)
self.p = 0
self.data = b""
if mode in ("r", "rw", "rb", "a", "ab"):
query = "SELECT content FROM web2py_filesystem WHERE path='%s'" % filename
rows = self.db.executesql(query)
if rows:
<|code_end|>
, predict the immediate next line with the help of imports:
import copy
import marshal
import struct
import threading
import time
import traceback
import types
from .._compat import (
PY2,
exists,
copyreg,
implements_bool,
iterkeys,
itervalues,
iteritems,
to_bytes,
long,
)
from .._globals import THREAD_LOCAL
from .serializers import serializers
and context (classes, functions, sometimes code) from other files:
# Path: pydal/_compat.py
# PY2 = sys.version_info[0] == 2
# def implements_bool(cls):
# def implements_iterator(cls):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def with_metaclass(meta, *bases):
# def __new__(cls, name, this_bases, d):
# def to_unicode(obj, charset="utf-8", errors="strict"):
# class metaclass(meta):
#
# Path: pydal/helpers/serializers.py
# class Serializers(object):
# def _json_parse(self, o):
# def __getattr__(self, name):
# def json(self, value):
# def yaml(self, value):
. Output only the next line. | self.data = to_bytes(rows[0][0]) |
Continue the code snippet: <|code_start|> def itervalues(self):
return itervalues(self._values)
def items(self):
return self._values.items()
def iteritems(self):
return iteritems(self._values)
def op_values(self):
return [(self._fields[key], value) for key, value in iteritems(self._values)]
def __repr__(self):
return "<OpRow %s>" % repr(self._values)
class Serializable(object):
def as_dict(self, flat=False, sanitize=True):
return self.__dict__
def as_xml(self, sanitize=True):
return serializers.xml(self.as_dict(flat=True, sanitize=sanitize))
def as_json(self, sanitize=True):
return serializers.json(self.as_dict(flat=True, sanitize=sanitize))
def as_yaml(self, sanitize=True):
return serializers.yaml(self.as_dict(flat=True, sanitize=sanitize))
<|code_end|>
. Use current file imports:
import copy
import marshal
import struct
import threading
import time
import traceback
import types
from .._compat import (
PY2,
exists,
copyreg,
implements_bool,
iterkeys,
itervalues,
iteritems,
to_bytes,
long,
)
from .._globals import THREAD_LOCAL
from .serializers import serializers
and context (classes, functions, or code) from other files:
# Path: pydal/_compat.py
# PY2 = sys.version_info[0] == 2
# def implements_bool(cls):
# def implements_iterator(cls):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def with_metaclass(meta, *bases):
# def __new__(cls, name, this_bases, d):
# def to_unicode(obj, charset="utf-8", errors="strict"):
# class metaclass(meta):
#
# Path: pydal/helpers/serializers.py
# class Serializers(object):
# def _json_parse(self, o):
# def __getattr__(self, name):
# def json(self, value):
# def yaml(self, value):
. Output only the next line. | class Reference(long): |
Given the code snippet: <|code_start|> def keys(self):
return self._values.keys()
def iterkeys(self):
return iterkeys(self._values)
def values(self):
return self._values.values()
def itervalues(self):
return itervalues(self._values)
def items(self):
return self._values.items()
def iteritems(self):
return iteritems(self._values)
def op_values(self):
return [(self._fields[key], value) for key, value in iteritems(self._values)]
def __repr__(self):
return "<OpRow %s>" % repr(self._values)
class Serializable(object):
def as_dict(self, flat=False, sanitize=True):
return self.__dict__
def as_xml(self, sanitize=True):
<|code_end|>
, generate the next line using the imports in this file:
import copy
import marshal
import struct
import threading
import time
import traceback
import types
from .._compat import (
PY2,
exists,
copyreg,
implements_bool,
iterkeys,
itervalues,
iteritems,
to_bytes,
long,
)
from .._globals import THREAD_LOCAL
from .serializers import serializers
and context (functions, classes, or occasionally code) from other files:
# Path: pydal/_compat.py
# PY2 = sys.version_info[0] == 2
# def implements_bool(cls):
# def implements_iterator(cls):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def to_bytes(obj, charset="utf-8", errors="strict"):
# def to_native(obj, charset="utf8", errors="strict"):
# def with_metaclass(meta, *bases):
# def __new__(cls, name, this_bases, d):
# def to_unicode(obj, charset="utf-8", errors="strict"):
# class metaclass(meta):
#
# Path: pydal/helpers/serializers.py
# class Serializers(object):
# def _json_parse(self, o):
# def __getattr__(self, name):
# def json(self, value):
# def yaml(self, value):
. Output only the next line. | return serializers.xml(self.as_dict(flat=True, sanitize=sanitize)) |
Given snippet: <|code_start|> children = list()
for e in node.edges:
children.append(self._conv_etree2tree(nodes.get(e[1]), nodes, e[0], include_edgelabels))
return nltk.Tree(cat, children)
return None
def _cached(obj, filepath, constructor):
if obj is not None:
return obj
new_obj = None
try:
with open(filepath, 'rb') as f:
new_obj = load(f)
except IOError as e:
#print u"Cache: couldn't read from %s" % filepath
#print unicode(e)
pass
if new_obj is None:
new_obj = constructor()
try:
with open(filepath, 'wb') as f:
dump(new_obj, f, -1)
except IOError as e:
#print u"Cache: couldn't write to %s" % filepath
#print unicode(e)
pass
return new_obj
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os.path as op
import nltk
import confopy.config as C
import sys
from cPickle import dump, load
from lxml import etree
from nltk.corpus.reader.api import CorpusReader
from nltk.corpus import BracketParseCorpusReader
from nltk.grammar import CFG, Nonterminal, induce_pcfg
from nltk.tokenize.punkt import PunktTrainer, PunktSentenceTokenizer
from confopy.analysis.corpus import Corpus
from fillers_de import FILLERS_DE
and context:
# Path: confopy/analysis/corpus.py
# class Corpus(Localizable, CorpusReader, Document):
# """A corpus is a body of language data.
# """
#
# def __init__(self, ID, language, brief=u"", description=u""):
# """Initializer.
# Args:
# ID: ID of the corpus (unicode string).
# language: Language code, e.g. u"de" or u"en".
# brief: Brief description of the corpus.
# description: Long/full description of the corpus.
# """
# self.ID = ID
# self.language = language
# self.brief = brief
# self.description = description
#
# def tagger(self):
# """Returns the POS tagger.
# """
# return None
#
# def parser(self):
# """Returns the syntax tree parser.
# """
# return None
#
# def sent_tokenizer(self):
# """Returns the sentence tokenizer.
# """
# return None
#
# def fillers(self):
# """Returns a list of fill words for the corpus language.
# """
# return list()
which might include code, classes, or functions. Output only the next line. | class TigerCorpusReader(Corpus): |
Given the code snippet: <|code_start|># coding: utf-8
'''
File: convenience.py
Author: Oliver Zscheyge
Description:
Convenience functions for handling PDF conversions.
'''
def PDF2XMLstring(filepath):
<|code_end|>
, generate the next line using the imports in this file:
from xml.dom.minidom import parseString
from confopy.pdfextract.pdfminer_wrapper import PDFMinerWrapper
from confopy.pdfextract.pdfminer_xml_bindings import DOM2pages
from confopy.pdfextract.heuristics import HeuristicManager
and context (functions, classes, or occasionally code) from other files:
# Path: confopy/pdfextract/pdfminer_wrapper.py
# class PDFMinerWrapper:
# """ Wrapper for pdfminer package functionality """
#
# def __init__(self):
# pass
#
# def pdf2txt(self, filename, options=Options()):
# result = ""
# with open(filename, "rb") as fp:
# conv = _PDFMiner(options)
# result = conv.to_txt(fp)
# return result
#
# def pdf2html(self, filename, options=Options()):
# result = ""
# with open(filename, "rb") as fp:
# conv = _PDFMiner(options)
# result = conv.to_html(fp)
# return result
#
# def pdf2xml(self, filename, options=Options()):
# result = ""
# with open(filename, "rb") as fp:
# conv = _PDFMiner(options)
# result = conv.to_xml(fp)
# return result
#
# Path: confopy/pdfextract/pdfminer_xml_bindings.py
# def DOM2pages(dom_document):
# dom_pages = dom_document.getElementsByTagName("page")
# # Forget about multiprocessing here.
# # DOM objects seems to have some side effects not allowing this.
# return map(DOM2page, dom_pages)
#
# Path: confopy/pdfextract/heuristics.py
# class HeuristicManager(object):
# """HeuristicManager"""
# def __init__(self):
# super(HeuristicManager, self).__init__()
# self.heuristics = list()
#
# self.heuristics.append(SimpleDocumentHeuristic())
#
# def generate_document(self, dom_pages):
# hints = self._apply_heuristics(dom_pages)
# return self._build_document_hierarchy(dom_pages, hints)
#
# def _apply_heuristics(self, dom_pages):
# hints = dict()
# for heu in self.heuristics:
# hints = heu.apply(pages=dom_pages, hints=hints)
# return hints
#
# def _build_document_hierarchy(self, dom_pages, hints):
# root = Document()
# node = root # current node to add children to
# last_title = u""
# accu_heading_nr = None
#
# for p in dom_pages:
# pagenr = unicode(p.ID)
# for tb in p.textboxes:
# tb_kind = hints.get(tb, TextBoxType.NONE)
# #print str(tb_kind) + " words: " + str(tb.word_count)
# #tb._print()
#
# if tb_kind == TextBoxType.HEADING:
# title = lines2unicode(tb.lines, True, u"\n")
# sec = Section(title=title, pagenr=pagenr)
# relation = HeuristicRegExes.compare_sections(last_title, title)
# if relation is not HeuristicRegExes.ERROR_SECTION_RELATION:
# node.add_child(sec, relation)
# else:
# node.add_child(sec)
# node = sec
# last_title = title
#
# elif tb_kind == TextBoxType.HEADING_PART_NUMBER:
# accu_heading_nr = tb
# elif tb_kind == TextBoxType.HEADING_PART_HEADING:
# if accu_heading_nr:
# title=lines2unicode(tb.lines, True, u"\n")
# number=lines2unicode(accu_heading_nr.lines, True, u"\n")
# sec = Section(title=title, number=number, pagenr=pagenr)
# relation = HeuristicRegExes.compare_sections(last_title, number)
# if relation is not HeuristicRegExes.ERROR_SECTION_RELATION:
# node.add_child(sec, relation)
# else:
# node.add_child(sec)
# node = sec
# last_title = number
# accu_heading_nr = None
#
# elif tb_kind == TextBoxType.FOOTNOTE:
# node.add_child(Footnote(text=lines2unicode(tb.lines, True, u"\n"), pagenr=pagenr))
# elif tb_kind == TextBoxType.PARAGRAPH:
# font = unicode(tb.font[0])
# fontsize = unicode(tb.font[1])
# emph = [unicode(e) for e in tb.emph]
# node.add_child(Paragraph(text=lines2unicode(tb.lines, True, u"\n"), pagenr=pagenr, font=font, fontsize=fontsize, emph=emph))
# elif tb_kind == TextBoxType.PARAGRAPH_WITH_HEADING:
# heading_line_count = lines_using(tb.lines, tb.emph, True)
# heading_lines = tb.lines[:heading_line_count]
# paragraph_lines = tb.lines[heading_line_count:]
# title = lines2unicode(heading_lines, True, u"\n")
# sec = Section(title=title, pagenr=pagenr)
# relation = HeuristicRegExes.compare_sections(last_title, title)
# if relation is not HeuristicRegExes.ERROR_SECTION_RELATION:
# node.add_child(sec, relation)
# else:
# node.add_child(sec)
# node = sec
# last_title = title
# font = unicode(tb.font[0])
# fontsize = unicode(tb.font[1])
# emph = [unicode(e) for e in tb.emph]
# node.add_child(Paragraph(text=lines2unicode(paragraph_lines, True, u"\n"), pagenr=pagenr, font=font, fontsize=fontsize, emph=emph))
#
# elif TextBoxType.is_float(tb_kind):
# node.add_child(Float(text=lines2unicode(tb.lines, True, u"\n"), pagenr=pagenr))
#
# doc_check = DocumentChecker()
# return doc_check.cleanup(root)
. Output only the next line. | pdfminer = PDFMinerWrapper() |
Given the code snippet: <|code_start|> take_from_new_lines = False
while i < len(lines):
l = lines[i].strip()
if take_from_new_lines:
l = new_lines[i]
new_lines.pop()
take_from_new_lines = False
if l.endswith(u"-"):
if i + 1 < len(lines):
next_l = lines[i + 1].strip()
if next_l is not u"":
next_l_words = next_l.split()
if len(next_l_words) > 0:
if next_l[0].islower():
l = l[:-1] + next_l_words[0]
else:
l = l + next_l_words[0]
new_lines.append(l)
l = u" ".join(next_l_words[1:])
take_from_new_lines = True
new_lines.append(l)
else:
new_lines.append(l)
i += 1
return new_lines
def DOM2textgroup(dom_textgroup):
bbox = str2bbox(dom_textgroup.getAttribute("bbox"))
textboxes = map( DOM2textbox
<|code_end|>
, generate the next line using the imports in this file:
import operator
import unicodedata
import random
import sys
from confopy.pdfextract import xml_util
from xml.dom.minidom import parse
and context (functions, classes, or occasionally code) from other files:
# Path: confopy/pdfextract/xml_util.py
# def getChildElementsByTagName(node, tagName):
# def escape(string):
. Output only the next line. | , xml_util.getChildElementsByTagName(dom_textgroup, "textbox")) |
Based on the snippet: <|code_start|># 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.
#
# This program 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 copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class WorldmapLevel(GameObj):
label = "WorldmapLevel"
identifier = "level"
sprite = "images/worldmap/common/leveldot_green.png"
def __init__(self):
super().__init__()
self.objmap_object = make_sprite_object(self, self.sprite)
self.signal_connect()
self.properties = [
StringProperty("Level File", "name", ""),
StringProperty("Extro Script", "extro-script", "", optional=True),
<|code_end|>
, predict the immediate next line with the help of imports:
from flexlay.property import (
BoolProperty,
)
from supertux.property import (
StringProperty,
SpriteProperty,
InlineTilePosProperty,
)
from supertux.gameobj import GameObj, make_sprite_object
and context (classes, functions, sometimes code) from other files:
# Path: flexlay/property.py
# class BoolProperty(Property):
#
# editable = True
#
# def property_dialog(self, dialog):
# dialog.add_bool(self.label, self.value, self.on_value_change)
#
# Path: supertux/property.py
# class DirectionProperty(EnumProperty):
# class InlinePosProperty:
# class InlineTilePosProperty(InlinePosProperty):
# class InlineRectProperty:
# class SpriteProperty(StringProperty):
# class BadGuyProperty(EnumProperty):
# class ImageProperty(StringProperty):
# class SoundProperty(StringProperty):
# class PathProperty:
# class Node:
# class SampleProperty(StringProperty):
# class TilemapProperty(EnumProperty):
# class SectorProperty(StringProperty):
# class ZPosProperty(IntProperty):
# def __init__(self, label, identifier, default):
# def __init__(self):
# def read(self, sexpr, obj):
# def write(self, writer, obj):
# def property_dialog(self, dialog):
# def read(self, sexpr, obj):
# def write(self, writer, obj):
# def __init__(self):
# def read(self, sexpr, obj):
# def write(self, writer, obj):
# def property_dialog(self, dialog):
# def write(self, writer, obj):
# def __init__(self, label, identifier, supertux_gameobj_factory):
# def __init__(self, *args, **kwargs):
# def __init__(self, label, identifier, default=""):
# def property_dialog(self, dialog):
# def __init__(self, x, y, time):
# def __init__(self, label, identifier):
# def read(self, sexpr, obj):
# def write(self, writer, obj):
# def property_dialog(self, dialog):
# def __init__(self, label, identifier, default):
# def __init__(self, label, identifier, optional, placeholder=None):
# def property_dialog(self, dialog):
# def _get_tilemaps(self):
# def __init__(self, label, identifier, default, optional):
# def __init__(self, default=0):
#
# Path: supertux/gameobj.py
# class GameObj:
#
# label: Optional[str] = None
# identifier: Optional[str] = None
# properties: List[Property] = []
# constraints: List[Constraint] = []
# factory = None
#
# def __init__(self):
# self.objmap_object = None
#
# def signal_connect(self):
# """Connect the objmap_object signals to the on_select and on_deselect
#
# Used, for example, to display properties in PropertiesWidget.
# """
# if not self.objmap_object:
# return
# self.objmap_object.sig_select.connect(self.on_select)
# self.objmap_object.sig_deselect.connect(self.on_deselect)
#
# def on_select(self, manager):
# if manager:
# props_widget = manager.properties_widget
# props_widget.set_properties(self.properties)
# props_widget.add_callback(self.on_callback)
#
# def on_deselect(self, manager):
# if manager:
# props_widget = manager.properties_widget
# props_widget.clear_properties()
# props_widget.call_signal.clear()
#
# def add_property(self, prop):
# self.properties.append(prop)
#
# def read(self, sexpr):
# for prop in self.properties:
# prop.read(sexpr, self.objmap_object)
#
# def write(self, writer, obj):
# writer.begin_list(self.identifier)
# for prop in self.properties:
# prop.write(writer, obj)
# writer.end_list()
#
# def property_dialog(self, gui=None):
# dialog = GenericDialog(self.label + " Property Dialog", gui)
# for prop in self.properties:
# prop.property_dialog(dialog)
#
# dialog.add_callback(self.on_callback)
#
# def find_property(self, identifier):
# for prop in self.properties:
# if prop.identifier == identifier:
# return prop
#
# def on_callback(self, *args):
# """Called when "Apply" or "Okay" hit"""
# print(args)
# prop_diff = []
# i = 0
# for property in self.properties:
# if property.editable:
# if args[i] == property.value:
# continue
# prop_diff.append((i, args[i], property.value))
# i += 1
# command = GameObjPropsChangeCommand(self, prop_diff)
# Workspace.current.get_map().execute(command)
#
# def update(self):
# """Called after properties read, and optionally at any other time"""
# pass
#
# def make_sprite_object(metadata, filename, pos=None):
# pos = Point(0, 0) if pos is None else pos
# sprite = SuperTuxSprite.from_file(os.path.join(Config.current.datadir, filename))
# obj = ObjMapSpriteObject(sprite.get_sprite(), pos, metadata)
# return obj
. Output only the next line. | BoolProperty("auto-play", "auto-play", False, optional=True), |
Predict the next line after this snippet: <|code_start|>#
# This program 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.
#
# This program 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 copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class WorldmapLevel(GameObj):
label = "WorldmapLevel"
identifier = "level"
sprite = "images/worldmap/common/leveldot_green.png"
def __init__(self):
super().__init__()
self.objmap_object = make_sprite_object(self, self.sprite)
self.signal_connect()
self.properties = [
<|code_end|>
using the current file's imports:
from flexlay.property import (
BoolProperty,
)
from supertux.property import (
StringProperty,
SpriteProperty,
InlineTilePosProperty,
)
from supertux.gameobj import GameObj, make_sprite_object
and any relevant context from other files:
# Path: flexlay/property.py
# class BoolProperty(Property):
#
# editable = True
#
# def property_dialog(self, dialog):
# dialog.add_bool(self.label, self.value, self.on_value_change)
#
# Path: supertux/property.py
# class DirectionProperty(EnumProperty):
# class InlinePosProperty:
# class InlineTilePosProperty(InlinePosProperty):
# class InlineRectProperty:
# class SpriteProperty(StringProperty):
# class BadGuyProperty(EnumProperty):
# class ImageProperty(StringProperty):
# class SoundProperty(StringProperty):
# class PathProperty:
# class Node:
# class SampleProperty(StringProperty):
# class TilemapProperty(EnumProperty):
# class SectorProperty(StringProperty):
# class ZPosProperty(IntProperty):
# def __init__(self, label, identifier, default):
# def __init__(self):
# def read(self, sexpr, obj):
# def write(self, writer, obj):
# def property_dialog(self, dialog):
# def read(self, sexpr, obj):
# def write(self, writer, obj):
# def __init__(self):
# def read(self, sexpr, obj):
# def write(self, writer, obj):
# def property_dialog(self, dialog):
# def write(self, writer, obj):
# def __init__(self, label, identifier, supertux_gameobj_factory):
# def __init__(self, *args, **kwargs):
# def __init__(self, label, identifier, default=""):
# def property_dialog(self, dialog):
# def __init__(self, x, y, time):
# def __init__(self, label, identifier):
# def read(self, sexpr, obj):
# def write(self, writer, obj):
# def property_dialog(self, dialog):
# def __init__(self, label, identifier, default):
# def __init__(self, label, identifier, optional, placeholder=None):
# def property_dialog(self, dialog):
# def _get_tilemaps(self):
# def __init__(self, label, identifier, default, optional):
# def __init__(self, default=0):
#
# Path: supertux/gameobj.py
# class GameObj:
#
# label: Optional[str] = None
# identifier: Optional[str] = None
# properties: List[Property] = []
# constraints: List[Constraint] = []
# factory = None
#
# def __init__(self):
# self.objmap_object = None
#
# def signal_connect(self):
# """Connect the objmap_object signals to the on_select and on_deselect
#
# Used, for example, to display properties in PropertiesWidget.
# """
# if not self.objmap_object:
# return
# self.objmap_object.sig_select.connect(self.on_select)
# self.objmap_object.sig_deselect.connect(self.on_deselect)
#
# def on_select(self, manager):
# if manager:
# props_widget = manager.properties_widget
# props_widget.set_properties(self.properties)
# props_widget.add_callback(self.on_callback)
#
# def on_deselect(self, manager):
# if manager:
# props_widget = manager.properties_widget
# props_widget.clear_properties()
# props_widget.call_signal.clear()
#
# def add_property(self, prop):
# self.properties.append(prop)
#
# def read(self, sexpr):
# for prop in self.properties:
# prop.read(sexpr, self.objmap_object)
#
# def write(self, writer, obj):
# writer.begin_list(self.identifier)
# for prop in self.properties:
# prop.write(writer, obj)
# writer.end_list()
#
# def property_dialog(self, gui=None):
# dialog = GenericDialog(self.label + " Property Dialog", gui)
# for prop in self.properties:
# prop.property_dialog(dialog)
#
# dialog.add_callback(self.on_callback)
#
# def find_property(self, identifier):
# for prop in self.properties:
# if prop.identifier == identifier:
# return prop
#
# def on_callback(self, *args):
# """Called when "Apply" or "Okay" hit"""
# print(args)
# prop_diff = []
# i = 0
# for property in self.properties:
# if property.editable:
# if args[i] == property.value:
# continue
# prop_diff.append((i, args[i], property.value))
# i += 1
# command = GameObjPropsChangeCommand(self, prop_diff)
# Workspace.current.get_map().execute(command)
#
# def update(self):
# """Called after properties read, and optionally at any other time"""
# pass
#
# def make_sprite_object(metadata, filename, pos=None):
# pos = Point(0, 0) if pos is None else pos
# sprite = SuperTuxSprite.from_file(os.path.join(Config.current.datadir, filename))
# obj = ObjMapSpriteObject(sprite.get_sprite(), pos, metadata)
# return obj
. Output only the next line. | StringProperty("Level File", "name", ""), |
Predict the next line after this snippet: <|code_start|># the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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 copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class WorldmapLevel(GameObj):
label = "WorldmapLevel"
identifier = "level"
sprite = "images/worldmap/common/leveldot_green.png"
def __init__(self):
super().__init__()
self.objmap_object = make_sprite_object(self, self.sprite)
self.signal_connect()
self.properties = [
StringProperty("Level File", "name", ""),
StringProperty("Extro Script", "extro-script", "", optional=True),
BoolProperty("auto-play", "auto-play", False, optional=True),
<|code_end|>
using the current file's imports:
from flexlay.property import (
BoolProperty,
)
from supertux.property import (
StringProperty,
SpriteProperty,
InlineTilePosProperty,
)
from supertux.gameobj import GameObj, make_sprite_object
and any relevant context from other files:
# Path: flexlay/property.py
# class BoolProperty(Property):
#
# editable = True
#
# def property_dialog(self, dialog):
# dialog.add_bool(self.label, self.value, self.on_value_change)
#
# Path: supertux/property.py
# class DirectionProperty(EnumProperty):
# class InlinePosProperty:
# class InlineTilePosProperty(InlinePosProperty):
# class InlineRectProperty:
# class SpriteProperty(StringProperty):
# class BadGuyProperty(EnumProperty):
# class ImageProperty(StringProperty):
# class SoundProperty(StringProperty):
# class PathProperty:
# class Node:
# class SampleProperty(StringProperty):
# class TilemapProperty(EnumProperty):
# class SectorProperty(StringProperty):
# class ZPosProperty(IntProperty):
# def __init__(self, label, identifier, default):
# def __init__(self):
# def read(self, sexpr, obj):
# def write(self, writer, obj):
# def property_dialog(self, dialog):
# def read(self, sexpr, obj):
# def write(self, writer, obj):
# def __init__(self):
# def read(self, sexpr, obj):
# def write(self, writer, obj):
# def property_dialog(self, dialog):
# def write(self, writer, obj):
# def __init__(self, label, identifier, supertux_gameobj_factory):
# def __init__(self, *args, **kwargs):
# def __init__(self, label, identifier, default=""):
# def property_dialog(self, dialog):
# def __init__(self, x, y, time):
# def __init__(self, label, identifier):
# def read(self, sexpr, obj):
# def write(self, writer, obj):
# def property_dialog(self, dialog):
# def __init__(self, label, identifier, default):
# def __init__(self, label, identifier, optional, placeholder=None):
# def property_dialog(self, dialog):
# def _get_tilemaps(self):
# def __init__(self, label, identifier, default, optional):
# def __init__(self, default=0):
#
# Path: supertux/gameobj.py
# class GameObj:
#
# label: Optional[str] = None
# identifier: Optional[str] = None
# properties: List[Property] = []
# constraints: List[Constraint] = []
# factory = None
#
# def __init__(self):
# self.objmap_object = None
#
# def signal_connect(self):
# """Connect the objmap_object signals to the on_select and on_deselect
#
# Used, for example, to display properties in PropertiesWidget.
# """
# if not self.objmap_object:
# return
# self.objmap_object.sig_select.connect(self.on_select)
# self.objmap_object.sig_deselect.connect(self.on_deselect)
#
# def on_select(self, manager):
# if manager:
# props_widget = manager.properties_widget
# props_widget.set_properties(self.properties)
# props_widget.add_callback(self.on_callback)
#
# def on_deselect(self, manager):
# if manager:
# props_widget = manager.properties_widget
# props_widget.clear_properties()
# props_widget.call_signal.clear()
#
# def add_property(self, prop):
# self.properties.append(prop)
#
# def read(self, sexpr):
# for prop in self.properties:
# prop.read(sexpr, self.objmap_object)
#
# def write(self, writer, obj):
# writer.begin_list(self.identifier)
# for prop in self.properties:
# prop.write(writer, obj)
# writer.end_list()
#
# def property_dialog(self, gui=None):
# dialog = GenericDialog(self.label + " Property Dialog", gui)
# for prop in self.properties:
# prop.property_dialog(dialog)
#
# dialog.add_callback(self.on_callback)
#
# def find_property(self, identifier):
# for prop in self.properties:
# if prop.identifier == identifier:
# return prop
#
# def on_callback(self, *args):
# """Called when "Apply" or "Okay" hit"""
# print(args)
# prop_diff = []
# i = 0
# for property in self.properties:
# if property.editable:
# if args[i] == property.value:
# continue
# prop_diff.append((i, args[i], property.value))
# i += 1
# command = GameObjPropsChangeCommand(self, prop_diff)
# Workspace.current.get_map().execute(command)
#
# def update(self):
# """Called after properties read, and optionally at any other time"""
# pass
#
# def make_sprite_object(metadata, filename, pos=None):
# pos = Point(0, 0) if pos is None else pos
# sprite = SuperTuxSprite.from_file(os.path.join(Config.current.datadir, filename))
# obj = ObjMapSpriteObject(sprite.get_sprite(), pos, metadata)
# return obj
. Output only the next line. | SpriteProperty("Sprite", "sprite"), |
Given the code snippet: <|code_start|># (at your option) any later version.
#
# This program 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 copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class WorldmapLevel(GameObj):
label = "WorldmapLevel"
identifier = "level"
sprite = "images/worldmap/common/leveldot_green.png"
def __init__(self):
super().__init__()
self.objmap_object = make_sprite_object(self, self.sprite)
self.signal_connect()
self.properties = [
StringProperty("Level File", "name", ""),
StringProperty("Extro Script", "extro-script", "", optional=True),
BoolProperty("auto-play", "auto-play", False, optional=True),
SpriteProperty("Sprite", "sprite"),
<|code_end|>
, generate the next line using the imports in this file:
from flexlay.property import (
BoolProperty,
)
from supertux.property import (
StringProperty,
SpriteProperty,
InlineTilePosProperty,
)
from supertux.gameobj import GameObj, make_sprite_object
and context (functions, classes, or occasionally code) from other files:
# Path: flexlay/property.py
# class BoolProperty(Property):
#
# editable = True
#
# def property_dialog(self, dialog):
# dialog.add_bool(self.label, self.value, self.on_value_change)
#
# Path: supertux/property.py
# class DirectionProperty(EnumProperty):
# class InlinePosProperty:
# class InlineTilePosProperty(InlinePosProperty):
# class InlineRectProperty:
# class SpriteProperty(StringProperty):
# class BadGuyProperty(EnumProperty):
# class ImageProperty(StringProperty):
# class SoundProperty(StringProperty):
# class PathProperty:
# class Node:
# class SampleProperty(StringProperty):
# class TilemapProperty(EnumProperty):
# class SectorProperty(StringProperty):
# class ZPosProperty(IntProperty):
# def __init__(self, label, identifier, default):
# def __init__(self):
# def read(self, sexpr, obj):
# def write(self, writer, obj):
# def property_dialog(self, dialog):
# def read(self, sexpr, obj):
# def write(self, writer, obj):
# def __init__(self):
# def read(self, sexpr, obj):
# def write(self, writer, obj):
# def property_dialog(self, dialog):
# def write(self, writer, obj):
# def __init__(self, label, identifier, supertux_gameobj_factory):
# def __init__(self, *args, **kwargs):
# def __init__(self, label, identifier, default=""):
# def property_dialog(self, dialog):
# def __init__(self, x, y, time):
# def __init__(self, label, identifier):
# def read(self, sexpr, obj):
# def write(self, writer, obj):
# def property_dialog(self, dialog):
# def __init__(self, label, identifier, default):
# def __init__(self, label, identifier, optional, placeholder=None):
# def property_dialog(self, dialog):
# def _get_tilemaps(self):
# def __init__(self, label, identifier, default, optional):
# def __init__(self, default=0):
#
# Path: supertux/gameobj.py
# class GameObj:
#
# label: Optional[str] = None
# identifier: Optional[str] = None
# properties: List[Property] = []
# constraints: List[Constraint] = []
# factory = None
#
# def __init__(self):
# self.objmap_object = None
#
# def signal_connect(self):
# """Connect the objmap_object signals to the on_select and on_deselect
#
# Used, for example, to display properties in PropertiesWidget.
# """
# if not self.objmap_object:
# return
# self.objmap_object.sig_select.connect(self.on_select)
# self.objmap_object.sig_deselect.connect(self.on_deselect)
#
# def on_select(self, manager):
# if manager:
# props_widget = manager.properties_widget
# props_widget.set_properties(self.properties)
# props_widget.add_callback(self.on_callback)
#
# def on_deselect(self, manager):
# if manager:
# props_widget = manager.properties_widget
# props_widget.clear_properties()
# props_widget.call_signal.clear()
#
# def add_property(self, prop):
# self.properties.append(prop)
#
# def read(self, sexpr):
# for prop in self.properties:
# prop.read(sexpr, self.objmap_object)
#
# def write(self, writer, obj):
# writer.begin_list(self.identifier)
# for prop in self.properties:
# prop.write(writer, obj)
# writer.end_list()
#
# def property_dialog(self, gui=None):
# dialog = GenericDialog(self.label + " Property Dialog", gui)
# for prop in self.properties:
# prop.property_dialog(dialog)
#
# dialog.add_callback(self.on_callback)
#
# def find_property(self, identifier):
# for prop in self.properties:
# if prop.identifier == identifier:
# return prop
#
# def on_callback(self, *args):
# """Called when "Apply" or "Okay" hit"""
# print(args)
# prop_diff = []
# i = 0
# for property in self.properties:
# if property.editable:
# if args[i] == property.value:
# continue
# prop_diff.append((i, args[i], property.value))
# i += 1
# command = GameObjPropsChangeCommand(self, prop_diff)
# Workspace.current.get_map().execute(command)
#
# def update(self):
# """Called after properties read, and optionally at any other time"""
# pass
#
# def make_sprite_object(metadata, filename, pos=None):
# pos = Point(0, 0) if pos is None else pos
# sprite = SuperTuxSprite.from_file(os.path.join(Config.current.datadir, filename))
# obj = ObjMapSpriteObject(sprite.get_sprite(), pos, metadata)
# return obj
. Output only the next line. | InlineTilePosProperty() |
Given snippet: <|code_start|># Flexlay - A Generic 2D Game Editor
# Copyright (C) 2015 Karkus476 <karkus476@yahoo.com>
#
# This program 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.
#
# This program 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 copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class WorldmapLevel(GameObj):
label = "WorldmapLevel"
identifier = "level"
sprite = "images/worldmap/common/leveldot_green.png"
def __init__(self):
super().__init__()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from flexlay.property import (
BoolProperty,
)
from supertux.property import (
StringProperty,
SpriteProperty,
InlineTilePosProperty,
)
from supertux.gameobj import GameObj, make_sprite_object
and context:
# Path: flexlay/property.py
# class BoolProperty(Property):
#
# editable = True
#
# def property_dialog(self, dialog):
# dialog.add_bool(self.label, self.value, self.on_value_change)
#
# Path: supertux/property.py
# class DirectionProperty(EnumProperty):
# class InlinePosProperty:
# class InlineTilePosProperty(InlinePosProperty):
# class InlineRectProperty:
# class SpriteProperty(StringProperty):
# class BadGuyProperty(EnumProperty):
# class ImageProperty(StringProperty):
# class SoundProperty(StringProperty):
# class PathProperty:
# class Node:
# class SampleProperty(StringProperty):
# class TilemapProperty(EnumProperty):
# class SectorProperty(StringProperty):
# class ZPosProperty(IntProperty):
# def __init__(self, label, identifier, default):
# def __init__(self):
# def read(self, sexpr, obj):
# def write(self, writer, obj):
# def property_dialog(self, dialog):
# def read(self, sexpr, obj):
# def write(self, writer, obj):
# def __init__(self):
# def read(self, sexpr, obj):
# def write(self, writer, obj):
# def property_dialog(self, dialog):
# def write(self, writer, obj):
# def __init__(self, label, identifier, supertux_gameobj_factory):
# def __init__(self, *args, **kwargs):
# def __init__(self, label, identifier, default=""):
# def property_dialog(self, dialog):
# def __init__(self, x, y, time):
# def __init__(self, label, identifier):
# def read(self, sexpr, obj):
# def write(self, writer, obj):
# def property_dialog(self, dialog):
# def __init__(self, label, identifier, default):
# def __init__(self, label, identifier, optional, placeholder=None):
# def property_dialog(self, dialog):
# def _get_tilemaps(self):
# def __init__(self, label, identifier, default, optional):
# def __init__(self, default=0):
#
# Path: supertux/gameobj.py
# class GameObj:
#
# label: Optional[str] = None
# identifier: Optional[str] = None
# properties: List[Property] = []
# constraints: List[Constraint] = []
# factory = None
#
# def __init__(self):
# self.objmap_object = None
#
# def signal_connect(self):
# """Connect the objmap_object signals to the on_select and on_deselect
#
# Used, for example, to display properties in PropertiesWidget.
# """
# if not self.objmap_object:
# return
# self.objmap_object.sig_select.connect(self.on_select)
# self.objmap_object.sig_deselect.connect(self.on_deselect)
#
# def on_select(self, manager):
# if manager:
# props_widget = manager.properties_widget
# props_widget.set_properties(self.properties)
# props_widget.add_callback(self.on_callback)
#
# def on_deselect(self, manager):
# if manager:
# props_widget = manager.properties_widget
# props_widget.clear_properties()
# props_widget.call_signal.clear()
#
# def add_property(self, prop):
# self.properties.append(prop)
#
# def read(self, sexpr):
# for prop in self.properties:
# prop.read(sexpr, self.objmap_object)
#
# def write(self, writer, obj):
# writer.begin_list(self.identifier)
# for prop in self.properties:
# prop.write(writer, obj)
# writer.end_list()
#
# def property_dialog(self, gui=None):
# dialog = GenericDialog(self.label + " Property Dialog", gui)
# for prop in self.properties:
# prop.property_dialog(dialog)
#
# dialog.add_callback(self.on_callback)
#
# def find_property(self, identifier):
# for prop in self.properties:
# if prop.identifier == identifier:
# return prop
#
# def on_callback(self, *args):
# """Called when "Apply" or "Okay" hit"""
# print(args)
# prop_diff = []
# i = 0
# for property in self.properties:
# if property.editable:
# if args[i] == property.value:
# continue
# prop_diff.append((i, args[i], property.value))
# i += 1
# command = GameObjPropsChangeCommand(self, prop_diff)
# Workspace.current.get_map().execute(command)
#
# def update(self):
# """Called after properties read, and optionally at any other time"""
# pass
#
# def make_sprite_object(metadata, filename, pos=None):
# pos = Point(0, 0) if pos is None else pos
# sprite = SuperTuxSprite.from_file(os.path.join(Config.current.datadir, filename))
# obj = ObjMapSpriteObject(sprite.get_sprite(), pos, metadata)
# return obj
which might include code, classes, or functions. Output only the next line. | self.objmap_object = make_sprite_object(self, self.sprite) |
Predict the next line for this snippet: <|code_start|># Flexlay - A Generic 2D Game Editor
# Copyright (C) 2014 Ingo Ruhnke <grumbel@gmail.com>
#
# This program 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.
#
# This program 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 copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class PixelBuffer:
cache: Dict[str, QImage] = {}
@staticmethod
def subregion_from_file(filename, x, y, w, h):
source = PixelBuffer.from_file(filename)
target = PixelBuffer(w, h)
<|code_end|>
with the help of current file imports:
from typing import Dict
from PyQt5.QtCore import QSize
from PyQt5.QtGui import QImage
from flexlay.blitter import blit_clear, blit_opaque
and context from other files:
# Path: flexlay/blitter.py
# def blit_clear(canvas):
# pass
# # print("clear(PixelBuffer canvas) not implemented", canvas)
# # canvas.lock()
# # buffer = static_cast<unsigned char*>(canvas.get_data())
# # memset(buffer, 0, sizeof(unsigned char) * canvas.get_pitch() * canvas.height)
# # canvas.unlock()
#
# def blit_opaque(target, brush, x, y):
# painter = QPainter(target.get_qimage())
# painter.setCompositionMode(QPainter.CompositionMode_Source)
# painter.drawImage(QPoint(x, y), brush.get_qimage())
, which may contain function names, class names, or code. Output only the next line. | blit_clear(target) |
Here is a snippet: <|code_start|># Flexlay - A Generic 2D Game Editor
# Copyright (C) 2014 Ingo Ruhnke <grumbel@gmail.com>
#
# This program 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.
#
# This program 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 copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class PixelBuffer:
cache: Dict[str, QImage] = {}
@staticmethod
def subregion_from_file(filename, x, y, w, h):
source = PixelBuffer.from_file(filename)
target = PixelBuffer(w, h)
blit_clear(target)
<|code_end|>
. Write the next line using the current file imports:
from typing import Dict
from PyQt5.QtCore import QSize
from PyQt5.QtGui import QImage
from flexlay.blitter import blit_clear, blit_opaque
and context from other files:
# Path: flexlay/blitter.py
# def blit_clear(canvas):
# pass
# # print("clear(PixelBuffer canvas) not implemented", canvas)
# # canvas.lock()
# # buffer = static_cast<unsigned char*>(canvas.get_data())
# # memset(buffer, 0, sizeof(unsigned char) * canvas.get_pitch() * canvas.height)
# # canvas.unlock()
#
# def blit_opaque(target, brush, x, y):
# painter = QPainter(target.get_qimage())
# painter.setCompositionMode(QPainter.CompositionMode_Source)
# painter.drawImage(QPoint(x, y), brush.get_qimage())
, which may include functions, classes, or code. Output only the next line. | blit_opaque(target, source, -x, -y) |
Using the snippet: <|code_start|>#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class InputEvent:
MOUSE_LEFT = 1
MOUSE_RIGHT = 2
MOUSE_MIDDLE = 3
MOUSE_WHEEL_UP = 4
MOUSE_WHEEL_DOWN = 5
MOUSE_NO_BUTTON = 6
MOD_SHIFT = (1 << 0)
MOD_CTRL = (1 << 1)
MOD_ALT = (1 << 2)
def __init__(self):
self.kind = InputEvent.MOUSE_NO_BUTTON
self.mouse_pos = None
self.mod = 0
@staticmethod
def from_qt(event):
result = InputEvent()
<|code_end|>
, determine the next line of code. You have imports:
import logging
from PyQt5.QtCore import Qt
from flexlay.math import Point
and context (class names, function names, or code) available:
# Path: flexlay/math/point.py
# class Point:
#
# @staticmethod
# def from_qt(qpoint):
# return Point(qpoint.x(), qpoint.y())
#
# def __init__(self, arg1=None, arg2=None):
# if arg1 is None and arg2 is None:
# self.x = 0
# self.y = 0
# elif arg2 is None:
# self.x = arg1.x
# self.y = arg1.y
# else:
# self.x = arg1
# self.y = arg2
#
# def copy(self):
# return Point(self.x, self.y)
#
# def __add__(self, rhs):
# return Point(self.x + rhs.x, self.y + rhs.y)
#
# def __sub__(self, rhs):
# return Point(self.x - rhs.x, self.y - rhs.y)
#
# def __mul__(self, rhs):
# return Point(self.x * rhs, self.y * rhs)
#
# def __rmul__(self, rhs):
# return Point(self.x * rhs, self.y * rhs)
#
# def __eq__(self, rhs):
# return self.x == rhs.x and self.y == rhs.y
#
# def __ne__(self, rhs):
# return not self.__eq__(rhs)
#
# def to_qt(self):
# return QPoint(self.x, self.y)
#
# def __str__(self):
# return "Point({}, {})".format(self.x, self.y)
. Output only the next line. | result.mouse_pos = Point(event.x(), event.y()) |
Continue the code snippet: <|code_start|># Flexlay - A Generic 2D Game Editor
# Copyright (C) 2015 Karkus476 <karkus476@yahoo.com>
#
# This program 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.
#
# This program 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 copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class OpenAddonDialog(OpenFileDialog):
def __init__(self, title):
super().__init__(title, ("SuperTux Add-ons (*.zip)",
"All Files (*)"))
<|code_end|>
. Use current file imports:
from flexlay.gui.file_dialog import OpenFileDialog, SaveDirectoryDialog
and context (classes, functions, or code) from other files:
# Path: flexlay/gui/file_dialog.py
# class OpenFileDialog(FileDialog):
#
# def __init__(self, title, filters=("All Files (*)",)):
# super().__init__(title)
#
# self.file_dialog.setNameFilters(filters)
#
# self.file_dialog.setAcceptMode(QFileDialog.AcceptOpen)
# self.file_dialog.setFileMode(QFileDialog.ExistingFile)
#
# class SaveDirectoryDialog(SaveFileDialog):
#
# def __init__(self, title):
# super().__init__(title)
# self.file_dialog.setFileMode(QFileDialog.Directory)
. Output only the next line. | class SaveAddonDialog(SaveDirectoryDialog): |
Using the snippet: <|code_start|># Flexlay - A Generic 2D Game Editor
# Copyright (C) 2014 Ingo Ruhnke <grumbel@gmail.com>
#
# This program 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.
#
# This program 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 copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
def load_lisp(filename, root_symbol):
"""Convenience function that loads a lisp file from disk and checks for a root symbol"""
tree = sexpr_read_from_file(filename)[0]
if tree is None:
raise Exception("Error: Couldn't load '%s'" % filename)
else:
if tree[0] != root_symbol:
<|code_end|>
, determine the next line of code. You have imports:
from flexlay.util import sexpr_read_from_file, SExprParseError
and context (class names, function names, or code) available:
# Path: flexlay/util/sexpr.py
# def sexpr_read_from_file(filename):
# with open(filename, "rt") as fin:
# content = fin.read()
# return parse(content, filename)
#
# class SExprParseError(Exception):
# def __init__(self, context, line, column, message):
# super().__init__("%s:%d:%d: error: %s" % (context, line, column, message))
# self.context = context
# self.line = line
# self.column = column
. Output only the next line. | raise SExprParseError("Error: '%s' is not a '%s' file" % (filename, root_symbol)) |
Given the following code snippet before the placeholder: <|code_start|># Flexlay - A Generic 2D Game Editor
# Copyright (C) 2014 Ingo Ruhnke <grumbel@gmail.com>
#
# This program 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.
#
# This program 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 copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class ObjMapObject:
def __init__(self, pos, metadata):
self.to_draw = True
self.pos = pos
self.metadata = metadata
<|code_end|>
, predict the next line using imports from the current file:
from flexlay.util import Signal
and context including class names, function names, and sometimes code from other files:
# Path: flexlay/util/signal.py
# class Signal:
# def __init__(self):
# self.subscribers = []
#
# def connect(self, callback, ignore_repeats=True):
# if not ignore_repeats and callback in self.subscribers:
# return
# self.subscribers.append(callback)
#
# def disconnect(self, callback):
# self.subscribers.remove(callback)
#
# def clear(self):
# self.subscribers = []
#
# def __call__(self, *args):
# for sub in self.subscribers:
# sub(*args)
. Output only the next line. | self.sig_select = Signal() |
Based on the snippet: <|code_start|># Flexlay - A Generic 2D Game Editor
# Copyright (C) 2015 Karkus476 <karkus476@yahoo.com>
#
# This program 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.
#
# This program 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 copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class OpenLevelFileDialog(OpenFileDialog):
def __init__(self, title):
super().__init__(title, ("SuperTux Files (*.stl *.stwm)",
"SuperTux Levels (*.stl)",
"SuperTux Worldmaps (*.stwm)",
"All Files (*)"))
<|code_end|>
, predict the immediate next line with the help of imports:
from flexlay.gui.file_dialog import OpenFileDialog, SaveFileDialog
and context (classes, functions, sometimes code) from other files:
# Path: flexlay/gui/file_dialog.py
# class OpenFileDialog(FileDialog):
#
# def __init__(self, title, filters=("All Files (*)",)):
# super().__init__(title)
#
# self.file_dialog.setNameFilters(filters)
#
# self.file_dialog.setAcceptMode(QFileDialog.AcceptOpen)
# self.file_dialog.setFileMode(QFileDialog.ExistingFile)
#
# class SaveFileDialog(FileDialog):
#
# def __init__(self, title, default_suffix=""):
# super().__init__(title)
#
# # FIXME: Not working!?
# self.file_dialog.setDefaultSuffix(default_suffix)
#
# self.file_dialog.setAcceptMode(QFileDialog.AcceptSave)
# self.file_dialog.setFileMode(QFileDialog.AnyFile)
. Output only the next line. | class SaveLevelFileDialog(SaveFileDialog): |
Predict the next line for this snippet: <|code_start|># Flexlay - A Generic 2D Game Editor
# Copyright (C) 2014 Ingo Ruhnke <grumbel@gmail.com>
#
# This program 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.
#
# This program 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 copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class ToolContext:
current = None
def __init__(self):
ToolContext.current = self
<|code_end|>
with the help of current file imports:
from flexlay.gui.tile_selection import TileSelection
from flexlay.tile_brush import TileBrush
and context from other files:
# Path: flexlay/gui/tile_selection.py
# class TileSelection:
#
# def __init__(self):
# self.tilemap = None
# self.start_pos = None
# self.selection = None
# self.active = False
#
# def start(self, tilemap, pos):
# self.tilemap = tilemap
# self.active = True
# self.start_pos = pos
# self.update(self.start_pos)
#
# def update(self, pos):
# self.selection = Rect(min(self.start_pos.x, pos.x),
# min(self.start_pos.y, pos.y),
# max(self.start_pos.x, pos.x) + 1,
# max(self.start_pos.y, pos.y) + 1)
#
# def is_active(self):
# return self.active
#
# def clear(self):
# self.selection = Rect()
# self.active = False
#
# def draw(self, gc, color=Color(255, 255, 255, 100)):
# tile_size = self.tilemap.get_tileset().get_tile_size()
#
# gc.fill_rect(Rect(self.selection.left * tile_size,
# self.selection.top * tile_size,
# self.selection.right * tile_size,
# self.selection.bottom * tile_size),
# color)
#
# def get_brush(self, field):
# sel = self.selection.copy()
#
# sel.normalize()
#
# if sel.left > field.width - 1 or \
# sel.top > field.height - 1 or \
# sel.right <= 0 or \
# sel.bottom <= 0:
#
# # Selection is empty
# logging.error("Error: Invalid selection")
# brush = TileBrush(1, 1)
# brush.put(0, 0, 0)
# brush.set_opaque()
# return brush
# else:
# # Selection is valid
# # Cut the selection to the field size
# sel.left = max(0, sel.left)
# sel.top = max(0, sel.top)
#
# sel.right = min(sel.right, field.width)
# sel.bottom = min(sel.bottom, field.height)
#
# brush = TileBrush(sel.width, sel.height)
#
# for y in range(sel.top, sel.bottom):
# for x in range(sel.left, sel.right):
# brush.put(x - sel.left, y - sel.top,
# field.at(x, y))
#
# return brush
#
# def get_rect(self):
# sel = self.selection.copy()
# sel.normalize()
# return sel
#
# Path: flexlay/tile_brush.py
# class TileBrush:
#
# @staticmethod
# def from_field(field, w, h, pos_x, pos_y):
# return TileBrush(w, h, field.copy_region(pos_x, pos_y, w, h))
#
# def __init__(self, w, h, field=None):
# self.opaque = False
# if field is None:
# self.field = Field.from_size(w, h)
# else:
# self.field = field
#
# @property
# def width(self):
# return self.field.width
#
# @property
# def height(self):
# return self.field.height
#
# def set_data(self, data):
# self.field.set_data(data)
#
# def get_data(self, data):
# return self.field.get_data(data)
#
# def at(self, x, y):
# return self.field.at(x, y)
#
# def put(self, x, y, value):
# assert isinstance(value, int)
# return self.field.put(x, y, value)
#
# def resize(self, w, h, pos_x=0, pos_y=0):
# self.field.resize(w, h, pos_x, pos_y)
#
# def set_opaque(self):
# self.opaque = True
#
# def set_transparent(self):
# self.opaque = False
#
# def is_opaque(self):
# return self.opaque
#
# def auto_crop(self):
# rect = Rect(0, 0, 0, 0)
#
# for y, x in itertools.product(range(0, self.field.height),
# range(0, self.field.width)):
# if self.field.at(x, y) != 0:
# rect.top = y
# break
#
# for y, x in itertools.product(reversed(range(0, self.field.height)),
# range(0, self.field.width)):
# if self.field.at(x, y) != 0:
# rect.bottom = y + 1
# break
#
# for x, y in itertools.product(range(0, self.field.width),
# range(0, self.field.height)):
# if self.field.at(x, y) != 0:
# rect.left = x
# break
#
# for x, y in itertools.product(reversed(range(0, self.field.width)),
# range(0, self.field.height)):
# if self.field.at(x, y) != 0:
# rect.right = x + 1
# break
#
# if rect.width != 0:
# self.resize(rect.width, rect.height,
# -rect.left, -rect.top)
# else:
# self.field = Field.from_size(1, 1)
# self.field.put(0, 0, 0)
# self.set_opaque()
, which may contain function names, class names, or code. Output only the next line. | self.tile_brush = TileBrush(1, 1) |
Continue the code snippet: <|code_start|>
self.tree_view = QTreeView()
self.vbox.addWidget(self.toolbar)
self.model = QFileSystemModel()
# self.data = [
# ("SuperTux addon", [
# ("levels", []),
# ("images", []),
# ("sounds", []),
# ("music", []),
# ("scripts", []),
# ("metadata", [])
# ])]
# self.model = QStandardItemModel()
# self.add_items(self.model, self.data)
self.tree_view.setModel(self.model)
self.tree_view.doubleClicked.connect(self.on_tree_view_double_click)
self.tree_view.setContextMenuPolicy(Qt.CustomContextMenu)
self.tree_view.customContextMenuRequested.connect(self.on_context_menu)
self.vbox.addWidget(self.tree_view)
self.layout = QFormLayout()
self.vbox.addLayout(self.layout)
self.setLayout(self.vbox)
self.setMinimumWidth(300)
# Called in many cases. This should have functions connected
# which cause the changes in the widget to be applied
# Called by hitting "Apply", "Ok" or "Finish"
<|code_end|>
. Use current file imports:
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIcon, QStandardItem
from PyQt5.QtWidgets import (
QFileSystemModel,
QFormLayout,
QLabel,
QMenu,
QToolBar,
QTreeView,
QVBoxLayout,
QWidget,
)
from flexlay.util import Signal
and context (classes, functions, or code) from other files:
# Path: flexlay/util/signal.py
# class Signal:
# def __init__(self):
# self.subscribers = []
#
# def connect(self, callback, ignore_repeats=True):
# if not ignore_repeats and callback in self.subscribers:
# return
# self.subscribers.append(callback)
#
# def disconnect(self, callback):
# self.subscribers.remove(callback)
#
# def clear(self):
# self.subscribers = []
#
# def __call__(self, *args):
# for sub in self.subscribers:
# sub(*args)
. Output only the next line. | self.call_signal = Signal() |
Given snippet: <|code_start|> def draw_line(self, x1, y1, x2, y2, color):
self.painter.setPen(color.to_qt())
self.painter.drawLine(QLineF(x1, y1, x2, y2))
def push_modelview(self):
self.painter.save()
def pop_modelview(self):
self.painter.restore()
def translate(self, x, y):
self.painter.setViewTransformEnabled(True)
self.painter.translate(x, y)
def scale(self, x, y):
self.painter.setViewTransformEnabled(True)
self.painter.scale(x, y)
def rotate(self, angle):
self.painter.setViewTransformEnabled(True)
self.painter.rotate(angle)
def get_clip_rect(self):
"""
If it's not obvious, this is rect containing all
which is visible
"""
if self.state:
return self.state.get_clip_rect()
else:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from PyQt5.QtCore import QLineF
from PyQt5.QtGui import QPainterPath
from flexlay.math import Rectf
and context:
# Path: flexlay/math/rect.py
# class Rectf(Rect):
#
# def __init__(self, arg1=None, arg2=None, arg3=None, arg4=None):
# super().__init__()
#
# if arg1 is None and arg2 is None and arg3 is None and arg4 is None:
# self.left = 0.0
# self.top = 0.0
# self.right = 0.0
# self.bottom = 0.0
# elif arg2 is None and arg3 is None and arg4 is None:
# self.left = arg1.left
# self.top = arg1.top
# self.right = arg1.right
# self.bottom = arg1.bottom
# elif arg3 is None and arg4 is None:
# self.left = arg1.x
# self.top = arg1.y
# self.right = arg1.x + arg2.width
# self.bottom = arg1.y + arg2.height
# else:
# self.left = arg1
# self.top = arg2
# self.right = arg3
# self.bottom = arg4
which might include code, classes, or functions. Output only the next line. | return Rectf() |
Here is a snippet: <|code_start|># the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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 copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
class GenericWizard(QWizard):
"""A Wizard which can display properties easily
You must use new_property_page to create pages which
are made up of a PropertyWidget.
Use add_callback to add a function which will be called
when "Finish" is pressed. See that function for more details
"""
def __init__(self, parent, title):
super().__init__(parent)
self.setWindowTitle(title)
self.pages = []
<|code_end|>
. Write the next line using the current file imports:
from PyQt5.QtWidgets import QWizardPage, QWizard, QVBoxLayout
from flexlay.util import Signal
and context from other files:
# Path: flexlay/util/signal.py
# class Signal:
# def __init__(self):
# self.subscribers = []
#
# def connect(self, callback, ignore_repeats=True):
# if not ignore_repeats and callback in self.subscribers:
# return
# self.subscribers.append(callback)
#
# def disconnect(self, callback):
# self.subscribers.remove(callback)
#
# def clear(self):
# self.subscribers = []
#
# def __call__(self, *args):
# for sub in self.subscribers:
# sub(*args)
, which may include functions, classes, or code. Output only the next line. | self.finish_callback = Signal() |
Predict the next line after this snippet: <|code_start|>#
# This program 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.
#
# This program 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 copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class ObjectSelector:
current = None
def __init__(self, obj_w, obj_h, parent):
ObjectSelector.current = self
self.scroll_area = QScrollArea(parent)
self.scroll_area.setWidgetResizable(True)
self.scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
self.scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
<|code_end|>
using the current file's imports:
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QScrollArea
from flexlay.gui.object_selector_widget import ObjectSelectorWidget
and any relevant context from other files:
# Path: flexlay/gui/object_selector_widget.py
# class ObjectSelectorWidget(QWidget):
#
# def __init__(self, cell_w, cell_h, viewport, parent=None):
# super().__init__(parent)
#
# self.viewport = viewport
# self.cell_width = cell_w
# self.cell_height = cell_h
# self.brushes = []
# self.has_focus = False
#
# self.index = 0
#
# self.mouse_pos = None
# self.click_pos = None
#
# self.mouse_over_tile = -1
# self.scale = 1.0
# self.drag_obj = -1
#
# self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding)
# self.setMouseTracking(True)
#
# def minimumSizeHint(self):
# columns = self.get_columns()
# min_rows = (len(self.brushes) + columns - 1) / columns
# return QSize(self.cell_width * self.get_columns(),
# self.cell_height * min_rows)
#
# def resizeEvent(self, event):
# pass
#
# def get_columns(self):
# return int(self.viewport.width() // self.cell_width)
#
# def mousePressEvent(self, event):
# if event.button() == Qt.LeftButton:
# if self.mouse_over_tile != -1:
# self.drag_obj = self.mouse_over_tile
#
# if self.drag_obj != -1:
# drag = QDrag(self)
# mime_data = QMimeData()
# # GRUMBEL obj = SuperTuxBadGuyData()
# data = QByteArray(pickle.dumps(self.drag_obj))
# mime_data.setData("application/x-supertux-badguy", data)
# drag.setMimeData(mime_data)
#
# pixmap = QPixmap.fromImage(self.brushes[self.drag_obj].get_sprite().get_pixelbuffer().get_qimage())
# drag.setPixmap(pixmap)
# drag.setHotSpot(QPoint(self.brushes[self.drag_obj].get_sprite().width / 2,
# self.brushes[self.drag_obj].get_sprite().height / 2))
# drag.exec()
# self.drag_obj = -1
#
# def mouseReleaseEvent(self, event):
# if event.button() == Qt.LeftButton:
# if self.drag_obj != -1:
# # releaseMouse()
# self.drag_obj = -1
#
# def mouseMoveEvent(self, event):
# self.mouse_pos = Point.from_qt(event.pos())
#
# cell_w = self.width() / self.get_columns()
# x = int(event.x() // cell_w)
# y = int(event.y() // self.cell_height)
#
# self.mouse_over_tile = y * self.get_columns() + x
#
# if self.mouse_over_tile < 0 or self.mouse_over_tile >= len(self.brushes):
# self.mouse_over_tile = -1
#
# if self.mouse_over_tile > -1:
# self.setToolTip(self.brushes[self.mouse_over_tile].get_data())
#
# self.repaint()
#
# def paintEvent(self, event):
# painter = QPainter(self)
# gc = GraphicContext(painter)
#
# for i in range(len(self.brushes)):
# x = i % self.get_columns()
# y = i // self.get_columns()
#
# cell_w = self.width() / self.get_columns()
# rect = Rectf(x * cell_w, y * self.cell_height,
# (x + 1) * cell_w, (y + 1) * self.cell_height)
#
# if (x + y - 1) % 2 == 0:
# gc.fill_rect(rect, Color(224, 224, 224))
# else:
# gc.fill_rect(rect, Color(192, 192, 192))
#
# sprite = self.brushes[i].get_sprite()
# sprite.set_alignment(Origin.center, 0, 0)
# sprite.set_scale(min(1.0, self.cell_width / sprite.width),
# min(1.0, self.cell_height / sprite.height))
# sprite.draw(rect.left + rect.width / 2,
# rect.top + rect.height / 2,
# gc)
#
# # highlight the current selection
# if self.mouse_over_tile == i and self.has_focus:
# gc.fill_rect(rect, Color(0, 0, 255, 20))
#
# def enterEvent(self, event):
# self.has_focus = True
#
# def leaveEvent(self, event):
# self.has_focus = False
# self.repaint()
#
# def add_brush(self, brush):
# self.brushes.append(brush)
. Output only the next line. | self.widget = ObjectSelectorWidget(obj_w, obj_h, self.scroll_area.viewport()) |
Given the code snippet: <|code_start|> height = 0
start = 0
reverse = False
def __init__(self, id, name, width, height, max_width, max_height, start, reverse):
self.id = id
self.name = name
self.width = width
self.height = height
self.max_width = max_width
self.max_height = max_height
self.min_width = width
self.min_height = height
self.start = start
self.reverse = reverse
self.top_left_ids = []
self.top_ids = []
self.top_right_ids = []
self.right_ids = []
self.bottom_right_ids = []
self.bottom_ids = []
self.bottom_left_ids = []
self.left_ids = []
self.other_ids = []
self.has_mappings = False
self.brush = None
def as_brush(self):
<|code_end|>
, generate the next line using the imports in this file:
from typing import List
from PyQt5.QtWidgets import QLabel, QListWidget, QHBoxLayout, QVBoxLayout, QSpinBox, QWidget
from flexlay.tile_brush import TileBrush
from flexlay.tool_context import ToolContext
import csv
import random
and context (functions, classes, or occasionally code) from other files:
# Path: flexlay/tile_brush.py
# class TileBrush:
#
# @staticmethod
# def from_field(field, w, h, pos_x, pos_y):
# return TileBrush(w, h, field.copy_region(pos_x, pos_y, w, h))
#
# def __init__(self, w, h, field=None):
# self.opaque = False
# if field is None:
# self.field = Field.from_size(w, h)
# else:
# self.field = field
#
# @property
# def width(self):
# return self.field.width
#
# @property
# def height(self):
# return self.field.height
#
# def set_data(self, data):
# self.field.set_data(data)
#
# def get_data(self, data):
# return self.field.get_data(data)
#
# def at(self, x, y):
# return self.field.at(x, y)
#
# def put(self, x, y, value):
# assert isinstance(value, int)
# return self.field.put(x, y, value)
#
# def resize(self, w, h, pos_x=0, pos_y=0):
# self.field.resize(w, h, pos_x, pos_y)
#
# def set_opaque(self):
# self.opaque = True
#
# def set_transparent(self):
# self.opaque = False
#
# def is_opaque(self):
# return self.opaque
#
# def auto_crop(self):
# rect = Rect(0, 0, 0, 0)
#
# for y, x in itertools.product(range(0, self.field.height),
# range(0, self.field.width)):
# if self.field.at(x, y) != 0:
# rect.top = y
# break
#
# for y, x in itertools.product(reversed(range(0, self.field.height)),
# range(0, self.field.width)):
# if self.field.at(x, y) != 0:
# rect.bottom = y + 1
# break
#
# for x, y in itertools.product(range(0, self.field.width),
# range(0, self.field.height)):
# if self.field.at(x, y) != 0:
# rect.left = x
# break
#
# for x, y in itertools.product(reversed(range(0, self.field.width)),
# range(0, self.field.height)):
# if self.field.at(x, y) != 0:
# rect.right = x + 1
# break
#
# if rect.width != 0:
# self.resize(rect.width, rect.height,
# -rect.left, -rect.top)
# else:
# self.field = Field.from_size(1, 1)
# self.field.put(0, 0, 0)
# self.set_opaque()
#
# Path: flexlay/tool_context.py
# class ToolContext:
#
# current = None
#
# def __init__(self):
# ToolContext.current = self
# self.tile_brush = TileBrush(1, 1)
# self.tile_brush.put(0, 0, 0)
# self.tile_brush.set_opaque()
#
# self.tile_selection = TileSelection()
#
# self.object_selection = []
#
# self.tilemap_layer = None
# self.object_layer = None
. Output only the next line. | brush = TileBrush(self.width, self.height) |
Based on the snippet: <|code_start|>
self.width_label = QLabel("Width: ")
self.width_input = QSpinBox(self)
self.height_label = QLabel("Height: ")
self.height_input = QSpinBox(self)
self.width_box = QHBoxLayout()
self.width_box.addWidget(self.width_label)
self.width_box.addWidget(self.width_input)
self.height_box = QHBoxLayout()
self.height_box.addWidget(self.height_label)
self.height_box.addWidget(self.height_input)
self.layout.addWidget(self.list_widget)
self.layout.addLayout(self.width_box)
self.layout.addLayout(self.height_box)
self.setLayout(self.layout)
self.current = None
self.list_widget.currentItemChanged.connect(self.item_changed)
self.width_input.valueChanged.connect(self.set_brush)
self.height_input.valueChanged.connect(self.set_brush)
self.viewport = viewport
def set_brush(self):
current = self.get_current()
# if current.has_mappings:
self.brush = current.as_smart_brush(self.width_input.value(), self.height_input.value(), self.mappings)
# else:
# self.brush = current.as_brush()
if self.brush is not None:
<|code_end|>
, predict the immediate next line with the help of imports:
from typing import List
from PyQt5.QtWidgets import QLabel, QListWidget, QHBoxLayout, QVBoxLayout, QSpinBox, QWidget
from flexlay.tile_brush import TileBrush
from flexlay.tool_context import ToolContext
import csv
import random
and context (classes, functions, sometimes code) from other files:
# Path: flexlay/tile_brush.py
# class TileBrush:
#
# @staticmethod
# def from_field(field, w, h, pos_x, pos_y):
# return TileBrush(w, h, field.copy_region(pos_x, pos_y, w, h))
#
# def __init__(self, w, h, field=None):
# self.opaque = False
# if field is None:
# self.field = Field.from_size(w, h)
# else:
# self.field = field
#
# @property
# def width(self):
# return self.field.width
#
# @property
# def height(self):
# return self.field.height
#
# def set_data(self, data):
# self.field.set_data(data)
#
# def get_data(self, data):
# return self.field.get_data(data)
#
# def at(self, x, y):
# return self.field.at(x, y)
#
# def put(self, x, y, value):
# assert isinstance(value, int)
# return self.field.put(x, y, value)
#
# def resize(self, w, h, pos_x=0, pos_y=0):
# self.field.resize(w, h, pos_x, pos_y)
#
# def set_opaque(self):
# self.opaque = True
#
# def set_transparent(self):
# self.opaque = False
#
# def is_opaque(self):
# return self.opaque
#
# def auto_crop(self):
# rect = Rect(0, 0, 0, 0)
#
# for y, x in itertools.product(range(0, self.field.height),
# range(0, self.field.width)):
# if self.field.at(x, y) != 0:
# rect.top = y
# break
#
# for y, x in itertools.product(reversed(range(0, self.field.height)),
# range(0, self.field.width)):
# if self.field.at(x, y) != 0:
# rect.bottom = y + 1
# break
#
# for x, y in itertools.product(range(0, self.field.width),
# range(0, self.field.height)):
# if self.field.at(x, y) != 0:
# rect.left = x
# break
#
# for x, y in itertools.product(reversed(range(0, self.field.width)),
# range(0, self.field.height)):
# if self.field.at(x, y) != 0:
# rect.right = x + 1
# break
#
# if rect.width != 0:
# self.resize(rect.width, rect.height,
# -rect.left, -rect.top)
# else:
# self.field = Field.from_size(1, 1)
# self.field.put(0, 0, 0)
# self.set_opaque()
#
# Path: flexlay/tool_context.py
# class ToolContext:
#
# current = None
#
# def __init__(self):
# ToolContext.current = self
# self.tile_brush = TileBrush(1, 1)
# self.tile_brush.put(0, 0, 0)
# self.tile_brush.set_opaque()
#
# self.tile_selection = TileSelection()
#
# self.object_selection = []
#
# self.tilemap_layer = None
# self.object_layer = None
. Output only the next line. | ToolContext.current.tile_brush = self.brush |
Next line prediction: <|code_start|># Flexlay - A Generic 2D Game Editor
# Copyright (C) 2015 Karkus476 <karkus476@yahoo.com>
#
# This program 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.
#
# This program 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 copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class FlexlayGenericDialogTestCase(unittest.TestCase):
"""A set of test cases for GenericDialog
In all cases, press okay to have the values entered printed
Please note some of these features are still WIP.
"""
def simple_test(self):
test_app = QApplication(sys.argv) # noqa: F841
<|code_end|>
. Use current file imports:
(import sys
import unittest
from PyQt5.QtWidgets import QApplication
from flexlay.gui.generic_dialog import GenericDialog)
and context including class names, function names, or small code snippets from other files:
# Path: flexlay/gui/generic_dialog.py
# class GenericDialog(PropertiesWidget):
# """A PropertiesWidget in a QDialog."""
#
# def __init__(self, title, parent=None):
# super().__init__(parent)
#
# self.ok_callback = None
#
# self.dialog = QDialog(parent)
#
# self.dialog.setModal(True)
# self.dialog.setWindowTitle(title)
# self.buttonbox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
#
# vbox = QVBoxLayout()
# self.layout = QFormLayout()
# vbox.addLayout(self.layout)
# vbox.addWidget(self)
# vbox.addWidget(self.buttonbox)
#
# self.dialog.setLayout(vbox)
# self.dialog.setMinimumWidth(300)
# self.dialog.show()
#
# # "Ok" and "Cancel" signals
#
# def on_accept():
# self.call()
# self.dialog.hide()
#
# def on_rejected():
# self.dialog.hide()
#
# self.buttonbox.accepted.connect(on_accept)
# self.buttonbox.rejected.connect(on_rejected)
. Output only the next line. | GenericDialog("Generic Dialog Test") |
Predict the next line after this snippet: <|code_start|># Copyright (C) 2014 Ingo Ruhnke <grumbel@gmail.com>
#
# This program 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.
#
# This program 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 copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class ButtonPanel:
def __init__(self, toolbar):
self.toolbar = toolbar
def add_icon(self, filename, callback, hover="Hover Text", shortcut=None):
action = self.toolbar.addAction(QIcon(filename), hover)
if shortcut:
action.setShortcut(shortcut)
if callback:
action.triggered.connect(callback)
<|code_end|>
using the current file's imports:
from PyQt5.QtGui import QIcon
from flexlay.gui.icon import Icon
and any relevant context from other files:
# Path: flexlay/gui/icon.py
# class Icon:
#
# def __init__(self, action):
# self.action = action
#
# def disable(self):
# self.action.setEnabled(False)
#
# def enable(self):
# self.action.setEnabled(True)
#
# def set_up(self):
# self.action.setCheckable(True)
# self.action.setChecked(False)
#
# def set_down(self):
# self.action.setCheckable(True)
# self.action.setChecked(True)
. Output only the next line. | return Icon(action) |
Predict the next line after this snippet: <|code_start|>"""
Tests for ESMTP extension parsing.
"""
def test_basic_extension_parsing():
response = """size.does.matter.af.MIL offers FIFTEEN extensions:
8BITMIME
PIPELINING
DSN
ENHANCEDSTATUSCODES
EXPN
HELP
SAML
SEND
SOML
TURN
XADR
XSTA
ETRN
XGEN
SIZE 51200000
"""
<|code_end|>
using the current file's imports:
from aiosmtplib.esmtp import parse_esmtp_extensions
and any relevant context from other files:
# Path: aiosmtplib/esmtp.py
# def parse_esmtp_extensions(message: str) -> Tuple[Dict[str, str], List[str]]:
# """
# Parse an EHLO response from the server into a dict of {extension: params}
# and a list of auth method names.
#
# It might look something like:
#
# 220 size.does.matter.af.MIL (More ESMTP than Crappysoft!)
# EHLO heaven.af.mil
# 250-size.does.matter.af.MIL offers FIFTEEN extensions:
# 250-8BITMIME
# 250-PIPELINING
# 250-DSN
# 250-ENHANCEDSTATUSCODES
# 250-EXPN
# 250-HELP
# 250-SAML
# 250-SEND
# 250-SOML
# 250-TURN
# 250-XADR
# 250-XSTA
# 250-ETRN
# 250-XGEN
# 250 SIZE 51200000
# """
# esmtp_extensions = {}
# auth_types = [] # type: List[str]
#
# response_lines = message.split("\n")
#
# # ignore the first line
# for line in response_lines[1:]:
# # To be able to communicate with as many SMTP servers as possible,
# # we have to take the old-style auth advertisement into account,
# # because:
# # 1) Else our SMTP feature parser gets confused.
# # 2) There are some servers that only advertise the auth methods we
# # support using the old style.
# auth_match = OLDSTYLE_AUTH_REGEX.match(line)
# if auth_match is not None:
# auth_type = auth_match.group("auth")
# auth_types.append(auth_type.lower().strip())
#
# # RFC 1869 requires a space between ehlo keyword and parameters.
# # It's actually stricter, in that only spaces are allowed between
# # parameters, but were not going to check for that here. Note
# # that the space isn't present if there are no parameters.
# extensions = EXTENSIONS_REGEX.match(line)
# if extensions is not None:
# extension = extensions.group("ext").lower()
# params = extensions.string[extensions.end("ext") :].strip()
# esmtp_extensions[extension] = params
#
# if extension == "auth":
# auth_types.extend([param.strip().lower() for param in params.split()])
#
# return esmtp_extensions, auth_types
. Output only the next line. | extensions, auth_types = parse_esmtp_extensions(response) |
Next line prediction: <|code_start|>"""
Compat method tests.
"""
@pytest.mark.asyncio
async def test_get_running_loop(event_loop):
running_loop = get_running_loop()
assert running_loop is event_loop
def test_get_running_loop_runtime_error(event_loop):
with pytest.raises(RuntimeError):
get_running_loop()
@pytest.mark.asyncio
async def test_all_tasks(event_loop):
tasks = all_tasks(event_loop)
<|code_end|>
. Use current file imports:
(import asyncio
import pytest
from aiosmtplib.compat import PY37_OR_LATER, all_tasks, get_running_loop)
and context including class names, function names, or small code snippets from other files:
# Path: aiosmtplib/compat.py
# PY37_OR_LATER = sys.version_info[:2] >= (3, 7)
#
# def all_tasks(loop: asyncio.AbstractEventLoop = None):
# if PY37_OR_LATER:
# return asyncio.all_tasks(loop=loop)
#
# return asyncio.Task.all_tasks(loop=loop) # type: ignore
#
# def get_running_loop() -> asyncio.AbstractEventLoop:
# if PY37_OR_LATER:
# return asyncio.get_running_loop()
#
# loop = asyncio.get_event_loop()
# if not loop.is_running():
# raise RuntimeError("no running event loop")
#
# return loop
. Output only the next line. | if PY37_OR_LATER: |
Given the code snippet: <|code_start|>"""
Compat method tests.
"""
@pytest.mark.asyncio
async def test_get_running_loop(event_loop):
running_loop = get_running_loop()
assert running_loop is event_loop
def test_get_running_loop_runtime_error(event_loop):
with pytest.raises(RuntimeError):
get_running_loop()
@pytest.mark.asyncio
async def test_all_tasks(event_loop):
<|code_end|>
, generate the next line using the imports in this file:
import asyncio
import pytest
from aiosmtplib.compat import PY37_OR_LATER, all_tasks, get_running_loop
and context (functions, classes, or occasionally code) from other files:
# Path: aiosmtplib/compat.py
# PY37_OR_LATER = sys.version_info[:2] >= (3, 7)
#
# def all_tasks(loop: asyncio.AbstractEventLoop = None):
# if PY37_OR_LATER:
# return asyncio.all_tasks(loop=loop)
#
# return asyncio.Task.all_tasks(loop=loop) # type: ignore
#
# def get_running_loop() -> asyncio.AbstractEventLoop:
# if PY37_OR_LATER:
# return asyncio.get_running_loop()
#
# loop = asyncio.get_event_loop()
# if not loop.is_running():
# raise RuntimeError("no running event loop")
#
# return loop
. Output only the next line. | tasks = all_tasks(event_loop) |
Given the following code snippet before the placeholder: <|code_start|>"""
Compat method tests.
"""
@pytest.mark.asyncio
async def test_get_running_loop(event_loop):
<|code_end|>
, predict the next line using imports from the current file:
import asyncio
import pytest
from aiosmtplib.compat import PY37_OR_LATER, all_tasks, get_running_loop
and context including class names, function names, and sometimes code from other files:
# Path: aiosmtplib/compat.py
# PY37_OR_LATER = sys.version_info[:2] >= (3, 7)
#
# def all_tasks(loop: asyncio.AbstractEventLoop = None):
# if PY37_OR_LATER:
# return asyncio.all_tasks(loop=loop)
#
# return asyncio.Task.all_tasks(loop=loop) # type: ignore
#
# def get_running_loop() -> asyncio.AbstractEventLoop:
# if PY37_OR_LATER:
# return asyncio.get_running_loop()
#
# loop = asyncio.get_event_loop()
# if not loop.is_running():
# raise RuntimeError("no running event loop")
#
# return loop
. Output only the next line. | running_loop = get_running_loop() |
Continue the code snippet: <|code_start|> ) -> SMTPResponse:
"""
Sends an SMTP DATA command to the server, followed by encoded message content.
Automatically quotes lines beginning with a period per RFC821.
Lone \\\\r and \\\\n characters are converted to \\\\r\\\\n
characters.
"""
if self._command_lock is None:
raise SMTPServerDisconnected("Server not connected")
message = LINE_ENDINGS_REGEX.sub(b"\r\n", message)
message = PERIOD_REGEX.sub(b"..", message)
if not message.endswith(b"\r\n"):
message += b"\r\n"
message += b".\r\n"
async with self._command_lock:
self.write(b"DATA\r\n")
start_response = await self.read_response(timeout=timeout)
if start_response.code != SMTPStatus.start_input:
raise SMTPDataError(start_response.code, start_response.message)
self.write(message)
response = await self.read_response(timeout=timeout)
if response.code != SMTPStatus.completed:
raise SMTPDataError(response.code, response.message)
return response
<|code_end|>
. Use current file imports:
import asyncio
import re
import ssl
from typing import Callable, Optional, cast
from .compat import start_tls
from .errors import (
SMTPDataError,
SMTPReadTimeoutError,
SMTPResponseException,
SMTPServerDisconnected,
SMTPTimeoutError,
)
from .response import SMTPResponse
from .status import SMTPStatus
and context (classes, functions, or code) from other files:
# Path: aiosmtplib/compat.py
# async def start_tls(
# loop: asyncio.AbstractEventLoop,
# transport: asyncio.Transport,
# protocol: asyncio.Protocol,
# sslcontext: ssl.SSLContext,
# server_side: bool = False,
# server_hostname: Optional[str] = None,
# ssl_handshake_timeout: Optional[Union[float, int]] = None,
# ) -> asyncio.Transport:
# # We use hasattr here, as uvloop also supports start_tls.
# if hasattr(loop, "start_tls"):
# return await loop.start_tls( # type: ignore
# transport,
# protocol,
# sslcontext,
# server_side=server_side,
# server_hostname=server_hostname,
# ssl_handshake_timeout=ssl_handshake_timeout,
# )
#
# waiter = loop.create_future()
# ssl_protocol = SSLProtocol(
# loop, protocol, sslcontext, waiter, server_side, server_hostname
# )
#
# # Pause early so that "ssl_protocol.data_received()" doesn't
# # have a chance to get called before "ssl_protocol.connection_made()".
# transport.pause_reading()
#
# # Use set_protocol if we can
# if hasattr(transport, "set_protocol"):
# transport.set_protocol(ssl_protocol)
# else:
# transport._protocol = ssl_protocol # type: ignore
#
# conmade_cb = loop.call_soon(ssl_protocol.connection_made, transport)
# resume_cb = loop.call_soon(transport.resume_reading)
#
# try:
# await asyncio.wait_for(waiter, timeout=ssl_handshake_timeout)
# except Exception:
# transport.close()
# conmade_cb.cancel()
# resume_cb.cancel()
# raise
#
# return ssl_protocol._app_transport
#
# Path: aiosmtplib/errors.py
# class SMTPDataError(SMTPResponseException):
# """
# Server refused DATA content.
# """
#
# class SMTPReadTimeoutError(SMTPTimeoutError):
# """
# A timeout occurred while waiting for a response from the SMTP server.
# """
#
# class SMTPResponseException(SMTPException):
# """
# Base class for all server responses with error codes.
# """
#
# def __init__(self, code: int, message: str) -> None:
# self.code = code
# self.message = message
# self.args = (code, message)
#
# class SMTPServerDisconnected(SMTPException, ConnectionError):
# """
# The connection was lost unexpectedly, or a command was run that requires
# a connection.
# """
#
# class SMTPTimeoutError(SMTPException, TimeoutError):
# """
# A timeout occurred while performing a network operation.
# """
#
# Path: aiosmtplib/response.py
# class SMTPResponse(BaseResponse):
# """
# NamedTuple of server response code and server response message.
#
# ``code`` and ``message`` can be accessed via attributes or indexes:
#
# >>> response = SMTPResponse(200, "OK")
# >>> response.message
# 'OK'
# >>> response[0]
# 200
# >>> response.code
# 200
#
# """
#
# __slots__ = ()
#
# def __repr__(self) -> str:
# return "({self.code}, {self.message})".format(self=self)
#
# def __str__(self) -> str:
# return "{self.code} {self.message}".format(self=self)
#
# Path: aiosmtplib/status.py
# class SMTPStatus(enum.IntEnum):
# """
# Defines SMTP statuses for code readability.
#
# See also: http://www.greenend.org.uk/rjk/tech/smtpreplies.html
# """
#
# invalid_response = -1
# system_status_ok = 211
# help_message = 214
# ready = 220
# closing = 221
# auth_successful = 235
# completed = 250
# will_forward = 251
# cannot_vrfy = 252
# auth_continue = 334
# start_input = 354
# domain_unavailable = 421
# mailbox_unavailable = 450
# error_processing = 451
# insufficient_storage = 452
# tls_not_available = 454
# unrecognized_command = 500
# unrecognized_parameters = 501
# command_not_implemented = 502
# bad_command_sequence = 503
# parameter_not_implemented = 504
# domain_does_not_accept_mail = 521
# access_denied = 530 # Sendmail specific
# auth_failed = 535
# mailbox_does_not_exist = 550
# user_not_local = 551
# storage_exceeded = 552
# mailbox_name_invalid = 553
# transaction_failed = 554
# syntax_error = 555
. Output only the next line. | async def start_tls( |
Based on the snippet: <|code_start|>
async with self._command_lock:
self.write(command)
response = await self.read_response(timeout=timeout)
return response
async def execute_data_command(
self, message: bytes, timeout: Optional[float] = None
) -> SMTPResponse:
"""
Sends an SMTP DATA command to the server, followed by encoded message content.
Automatically quotes lines beginning with a period per RFC821.
Lone \\\\r and \\\\n characters are converted to \\\\r\\\\n
characters.
"""
if self._command_lock is None:
raise SMTPServerDisconnected("Server not connected")
message = LINE_ENDINGS_REGEX.sub(b"\r\n", message)
message = PERIOD_REGEX.sub(b"..", message)
if not message.endswith(b"\r\n"):
message += b"\r\n"
message += b".\r\n"
async with self._command_lock:
self.write(b"DATA\r\n")
start_response = await self.read_response(timeout=timeout)
if start_response.code != SMTPStatus.start_input:
<|code_end|>
, predict the immediate next line with the help of imports:
import asyncio
import re
import ssl
from typing import Callable, Optional, cast
from .compat import start_tls
from .errors import (
SMTPDataError,
SMTPReadTimeoutError,
SMTPResponseException,
SMTPServerDisconnected,
SMTPTimeoutError,
)
from .response import SMTPResponse
from .status import SMTPStatus
and context (classes, functions, sometimes code) from other files:
# Path: aiosmtplib/compat.py
# async def start_tls(
# loop: asyncio.AbstractEventLoop,
# transport: asyncio.Transport,
# protocol: asyncio.Protocol,
# sslcontext: ssl.SSLContext,
# server_side: bool = False,
# server_hostname: Optional[str] = None,
# ssl_handshake_timeout: Optional[Union[float, int]] = None,
# ) -> asyncio.Transport:
# # We use hasattr here, as uvloop also supports start_tls.
# if hasattr(loop, "start_tls"):
# return await loop.start_tls( # type: ignore
# transport,
# protocol,
# sslcontext,
# server_side=server_side,
# server_hostname=server_hostname,
# ssl_handshake_timeout=ssl_handshake_timeout,
# )
#
# waiter = loop.create_future()
# ssl_protocol = SSLProtocol(
# loop, protocol, sslcontext, waiter, server_side, server_hostname
# )
#
# # Pause early so that "ssl_protocol.data_received()" doesn't
# # have a chance to get called before "ssl_protocol.connection_made()".
# transport.pause_reading()
#
# # Use set_protocol if we can
# if hasattr(transport, "set_protocol"):
# transport.set_protocol(ssl_protocol)
# else:
# transport._protocol = ssl_protocol # type: ignore
#
# conmade_cb = loop.call_soon(ssl_protocol.connection_made, transport)
# resume_cb = loop.call_soon(transport.resume_reading)
#
# try:
# await asyncio.wait_for(waiter, timeout=ssl_handshake_timeout)
# except Exception:
# transport.close()
# conmade_cb.cancel()
# resume_cb.cancel()
# raise
#
# return ssl_protocol._app_transport
#
# Path: aiosmtplib/errors.py
# class SMTPDataError(SMTPResponseException):
# """
# Server refused DATA content.
# """
#
# class SMTPReadTimeoutError(SMTPTimeoutError):
# """
# A timeout occurred while waiting for a response from the SMTP server.
# """
#
# class SMTPResponseException(SMTPException):
# """
# Base class for all server responses with error codes.
# """
#
# def __init__(self, code: int, message: str) -> None:
# self.code = code
# self.message = message
# self.args = (code, message)
#
# class SMTPServerDisconnected(SMTPException, ConnectionError):
# """
# The connection was lost unexpectedly, or a command was run that requires
# a connection.
# """
#
# class SMTPTimeoutError(SMTPException, TimeoutError):
# """
# A timeout occurred while performing a network operation.
# """
#
# Path: aiosmtplib/response.py
# class SMTPResponse(BaseResponse):
# """
# NamedTuple of server response code and server response message.
#
# ``code`` and ``message`` can be accessed via attributes or indexes:
#
# >>> response = SMTPResponse(200, "OK")
# >>> response.message
# 'OK'
# >>> response[0]
# 200
# >>> response.code
# 200
#
# """
#
# __slots__ = ()
#
# def __repr__(self) -> str:
# return "({self.code}, {self.message})".format(self=self)
#
# def __str__(self) -> str:
# return "{self.code} {self.message}".format(self=self)
#
# Path: aiosmtplib/status.py
# class SMTPStatus(enum.IntEnum):
# """
# Defines SMTP statuses for code readability.
#
# See also: http://www.greenend.org.uk/rjk/tech/smtpreplies.html
# """
#
# invalid_response = -1
# system_status_ok = 211
# help_message = 214
# ready = 220
# closing = 221
# auth_successful = 235
# completed = 250
# will_forward = 251
# cannot_vrfy = 252
# auth_continue = 334
# start_input = 354
# domain_unavailable = 421
# mailbox_unavailable = 450
# error_processing = 451
# insufficient_storage = 452
# tls_not_available = 454
# unrecognized_command = 500
# unrecognized_parameters = 501
# command_not_implemented = 502
# bad_command_sequence = 503
# parameter_not_implemented = 504
# domain_does_not_accept_mail = 521
# access_denied = 530 # Sendmail specific
# auth_failed = 535
# mailbox_does_not_exist = 550
# user_not_local = 551
# storage_exceeded = 552
# mailbox_name_invalid = 553
# transaction_failed = 554
# syntax_error = 555
. Output only the next line. | raise SMTPDataError(start_response.code, start_response.message) |
Next line prediction: <|code_start|>
if message_complete:
response = SMTPResponse(
code, bytes(message).decode("utf-8", "surrogateescape")
)
del self._buffer[:offset]
return response
else:
return None
async def read_response(self, timeout: Optional[float] = None) -> SMTPResponse:
"""
Get a status response from the server.
This method must be awaited once per command sent; if multiple commands
are written to the transport without awaiting, response data will be lost.
Returns an :class:`.response.SMTPResponse` namedtuple consisting of:
- server response code (e.g. 250, or such, if all goes well)
- server response string (multiline responses are converted to a
single, multiline string).
"""
if self._response_waiter is None:
raise SMTPServerDisconnected("Connection lost")
try:
result = await asyncio.wait_for(
self._response_waiter, timeout
) # type: SMTPResponse
except asyncio.TimeoutError as exc:
<|code_end|>
. Use current file imports:
(import asyncio
import re
import ssl
from typing import Callable, Optional, cast
from .compat import start_tls
from .errors import (
SMTPDataError,
SMTPReadTimeoutError,
SMTPResponseException,
SMTPServerDisconnected,
SMTPTimeoutError,
)
from .response import SMTPResponse
from .status import SMTPStatus)
and context including class names, function names, or small code snippets from other files:
# Path: aiosmtplib/compat.py
# async def start_tls(
# loop: asyncio.AbstractEventLoop,
# transport: asyncio.Transport,
# protocol: asyncio.Protocol,
# sslcontext: ssl.SSLContext,
# server_side: bool = False,
# server_hostname: Optional[str] = None,
# ssl_handshake_timeout: Optional[Union[float, int]] = None,
# ) -> asyncio.Transport:
# # We use hasattr here, as uvloop also supports start_tls.
# if hasattr(loop, "start_tls"):
# return await loop.start_tls( # type: ignore
# transport,
# protocol,
# sslcontext,
# server_side=server_side,
# server_hostname=server_hostname,
# ssl_handshake_timeout=ssl_handshake_timeout,
# )
#
# waiter = loop.create_future()
# ssl_protocol = SSLProtocol(
# loop, protocol, sslcontext, waiter, server_side, server_hostname
# )
#
# # Pause early so that "ssl_protocol.data_received()" doesn't
# # have a chance to get called before "ssl_protocol.connection_made()".
# transport.pause_reading()
#
# # Use set_protocol if we can
# if hasattr(transport, "set_protocol"):
# transport.set_protocol(ssl_protocol)
# else:
# transport._protocol = ssl_protocol # type: ignore
#
# conmade_cb = loop.call_soon(ssl_protocol.connection_made, transport)
# resume_cb = loop.call_soon(transport.resume_reading)
#
# try:
# await asyncio.wait_for(waiter, timeout=ssl_handshake_timeout)
# except Exception:
# transport.close()
# conmade_cb.cancel()
# resume_cb.cancel()
# raise
#
# return ssl_protocol._app_transport
#
# Path: aiosmtplib/errors.py
# class SMTPDataError(SMTPResponseException):
# """
# Server refused DATA content.
# """
#
# class SMTPReadTimeoutError(SMTPTimeoutError):
# """
# A timeout occurred while waiting for a response from the SMTP server.
# """
#
# class SMTPResponseException(SMTPException):
# """
# Base class for all server responses with error codes.
# """
#
# def __init__(self, code: int, message: str) -> None:
# self.code = code
# self.message = message
# self.args = (code, message)
#
# class SMTPServerDisconnected(SMTPException, ConnectionError):
# """
# The connection was lost unexpectedly, or a command was run that requires
# a connection.
# """
#
# class SMTPTimeoutError(SMTPException, TimeoutError):
# """
# A timeout occurred while performing a network operation.
# """
#
# Path: aiosmtplib/response.py
# class SMTPResponse(BaseResponse):
# """
# NamedTuple of server response code and server response message.
#
# ``code`` and ``message`` can be accessed via attributes or indexes:
#
# >>> response = SMTPResponse(200, "OK")
# >>> response.message
# 'OK'
# >>> response[0]
# 200
# >>> response.code
# 200
#
# """
#
# __slots__ = ()
#
# def __repr__(self) -> str:
# return "({self.code}, {self.message})".format(self=self)
#
# def __str__(self) -> str:
# return "{self.code} {self.message}".format(self=self)
#
# Path: aiosmtplib/status.py
# class SMTPStatus(enum.IntEnum):
# """
# Defines SMTP statuses for code readability.
#
# See also: http://www.greenend.org.uk/rjk/tech/smtpreplies.html
# """
#
# invalid_response = -1
# system_status_ok = 211
# help_message = 214
# ready = 220
# closing = 221
# auth_successful = 235
# completed = 250
# will_forward = 251
# cannot_vrfy = 252
# auth_continue = 334
# start_input = 354
# domain_unavailable = 421
# mailbox_unavailable = 450
# error_processing = 451
# insufficient_storage = 452
# tls_not_available = 454
# unrecognized_command = 500
# unrecognized_parameters = 501
# command_not_implemented = 502
# bad_command_sequence = 503
# parameter_not_implemented = 504
# domain_does_not_accept_mail = 521
# access_denied = 530 # Sendmail specific
# auth_failed = 535
# mailbox_does_not_exist = 550
# user_not_local = 551
# storage_exceeded = 552
# mailbox_name_invalid = 553
# transaction_failed = 554
# syntax_error = 555
. Output only the next line. | raise SMTPReadTimeoutError("Timed out waiting for server response") from exc |
Predict the next line after this snippet: <|code_start|> self._response_waiter.set_exception(exc)
else:
if response is not None:
self._response_waiter.set_result(response)
def eof_received(self) -> bool:
exc = SMTPServerDisconnected("Unexpected EOF received")
if self._response_waiter and not self._response_waiter.done():
self._response_waiter.set_exception(exc)
if self._connection_lost_waiter and not self._connection_lost_waiter.done():
self._connection_lost_waiter.set_exception(exc)
# Returning false closes the transport
return False
def _read_response_from_buffer(self) -> Optional[SMTPResponse]:
"""Parse the actual response (if any) from the data buffer"""
code = -1
message = bytearray()
offset = 0
message_complete = False
while True:
line_end_index = self._buffer.find(b"\n", offset)
if line_end_index == -1:
break
line = bytes(self._buffer[offset : line_end_index + 1])
if len(line) > MAX_LINE_LENGTH:
<|code_end|>
using the current file's imports:
import asyncio
import re
import ssl
from typing import Callable, Optional, cast
from .compat import start_tls
from .errors import (
SMTPDataError,
SMTPReadTimeoutError,
SMTPResponseException,
SMTPServerDisconnected,
SMTPTimeoutError,
)
from .response import SMTPResponse
from .status import SMTPStatus
and any relevant context from other files:
# Path: aiosmtplib/compat.py
# async def start_tls(
# loop: asyncio.AbstractEventLoop,
# transport: asyncio.Transport,
# protocol: asyncio.Protocol,
# sslcontext: ssl.SSLContext,
# server_side: bool = False,
# server_hostname: Optional[str] = None,
# ssl_handshake_timeout: Optional[Union[float, int]] = None,
# ) -> asyncio.Transport:
# # We use hasattr here, as uvloop also supports start_tls.
# if hasattr(loop, "start_tls"):
# return await loop.start_tls( # type: ignore
# transport,
# protocol,
# sslcontext,
# server_side=server_side,
# server_hostname=server_hostname,
# ssl_handshake_timeout=ssl_handshake_timeout,
# )
#
# waiter = loop.create_future()
# ssl_protocol = SSLProtocol(
# loop, protocol, sslcontext, waiter, server_side, server_hostname
# )
#
# # Pause early so that "ssl_protocol.data_received()" doesn't
# # have a chance to get called before "ssl_protocol.connection_made()".
# transport.pause_reading()
#
# # Use set_protocol if we can
# if hasattr(transport, "set_protocol"):
# transport.set_protocol(ssl_protocol)
# else:
# transport._protocol = ssl_protocol # type: ignore
#
# conmade_cb = loop.call_soon(ssl_protocol.connection_made, transport)
# resume_cb = loop.call_soon(transport.resume_reading)
#
# try:
# await asyncio.wait_for(waiter, timeout=ssl_handshake_timeout)
# except Exception:
# transport.close()
# conmade_cb.cancel()
# resume_cb.cancel()
# raise
#
# return ssl_protocol._app_transport
#
# Path: aiosmtplib/errors.py
# class SMTPDataError(SMTPResponseException):
# """
# Server refused DATA content.
# """
#
# class SMTPReadTimeoutError(SMTPTimeoutError):
# """
# A timeout occurred while waiting for a response from the SMTP server.
# """
#
# class SMTPResponseException(SMTPException):
# """
# Base class for all server responses with error codes.
# """
#
# def __init__(self, code: int, message: str) -> None:
# self.code = code
# self.message = message
# self.args = (code, message)
#
# class SMTPServerDisconnected(SMTPException, ConnectionError):
# """
# The connection was lost unexpectedly, or a command was run that requires
# a connection.
# """
#
# class SMTPTimeoutError(SMTPException, TimeoutError):
# """
# A timeout occurred while performing a network operation.
# """
#
# Path: aiosmtplib/response.py
# class SMTPResponse(BaseResponse):
# """
# NamedTuple of server response code and server response message.
#
# ``code`` and ``message`` can be accessed via attributes or indexes:
#
# >>> response = SMTPResponse(200, "OK")
# >>> response.message
# 'OK'
# >>> response[0]
# 200
# >>> response.code
# 200
#
# """
#
# __slots__ = ()
#
# def __repr__(self) -> str:
# return "({self.code}, {self.message})".format(self=self)
#
# def __str__(self) -> str:
# return "{self.code} {self.message}".format(self=self)
#
# Path: aiosmtplib/status.py
# class SMTPStatus(enum.IntEnum):
# """
# Defines SMTP statuses for code readability.
#
# See also: http://www.greenend.org.uk/rjk/tech/smtpreplies.html
# """
#
# invalid_response = -1
# system_status_ok = 211
# help_message = 214
# ready = 220
# closing = 221
# auth_successful = 235
# completed = 250
# will_forward = 251
# cannot_vrfy = 252
# auth_continue = 334
# start_input = 354
# domain_unavailable = 421
# mailbox_unavailable = 450
# error_processing = 451
# insufficient_storage = 452
# tls_not_available = 454
# unrecognized_command = 500
# unrecognized_parameters = 501
# command_not_implemented = 502
# bad_command_sequence = 503
# parameter_not_implemented = 504
# domain_does_not_accept_mail = 521
# access_denied = 530 # Sendmail specific
# auth_failed = 535
# mailbox_does_not_exist = 550
# user_not_local = 551
# storage_exceeded = 552
# mailbox_name_invalid = 553
# transaction_failed = 554
# syntax_error = 555
. Output only the next line. | raise SMTPResponseException( |
Predict the next line after this snippet: <|code_start|> for waiter in filter(None, waiters):
if waiter.done() and not waiter.cancelled():
# Avoid 'Future exception was never retrieved' warnings
waiter.exception()
def _get_close_waiter(self, stream: asyncio.StreamWriter) -> asyncio.Future:
return self._closed
@property
def is_connected(self) -> bool:
"""
Check if our transport is still connected.
"""
return bool(self.transport is not None and not self.transport.is_closing())
def connection_made(self, transport: asyncio.BaseTransport) -> None:
self.transport = cast(asyncio.Transport, transport)
self._over_ssl = transport.get_extra_info("sslcontext") is not None
self._response_waiter = self._loop.create_future()
self._command_lock = asyncio.Lock()
if self._connection_lost_callback is not None:
self._connection_lost_waiter = self._loop.create_future()
self._connection_lost_waiter.add_done_callback(
self._connection_lost_callback
)
def connection_lost(self, exc: Optional[Exception]) -> None:
super().connection_lost(exc)
<|code_end|>
using the current file's imports:
import asyncio
import re
import ssl
from typing import Callable, Optional, cast
from .compat import start_tls
from .errors import (
SMTPDataError,
SMTPReadTimeoutError,
SMTPResponseException,
SMTPServerDisconnected,
SMTPTimeoutError,
)
from .response import SMTPResponse
from .status import SMTPStatus
and any relevant context from other files:
# Path: aiosmtplib/compat.py
# async def start_tls(
# loop: asyncio.AbstractEventLoop,
# transport: asyncio.Transport,
# protocol: asyncio.Protocol,
# sslcontext: ssl.SSLContext,
# server_side: bool = False,
# server_hostname: Optional[str] = None,
# ssl_handshake_timeout: Optional[Union[float, int]] = None,
# ) -> asyncio.Transport:
# # We use hasattr here, as uvloop also supports start_tls.
# if hasattr(loop, "start_tls"):
# return await loop.start_tls( # type: ignore
# transport,
# protocol,
# sslcontext,
# server_side=server_side,
# server_hostname=server_hostname,
# ssl_handshake_timeout=ssl_handshake_timeout,
# )
#
# waiter = loop.create_future()
# ssl_protocol = SSLProtocol(
# loop, protocol, sslcontext, waiter, server_side, server_hostname
# )
#
# # Pause early so that "ssl_protocol.data_received()" doesn't
# # have a chance to get called before "ssl_protocol.connection_made()".
# transport.pause_reading()
#
# # Use set_protocol if we can
# if hasattr(transport, "set_protocol"):
# transport.set_protocol(ssl_protocol)
# else:
# transport._protocol = ssl_protocol # type: ignore
#
# conmade_cb = loop.call_soon(ssl_protocol.connection_made, transport)
# resume_cb = loop.call_soon(transport.resume_reading)
#
# try:
# await asyncio.wait_for(waiter, timeout=ssl_handshake_timeout)
# except Exception:
# transport.close()
# conmade_cb.cancel()
# resume_cb.cancel()
# raise
#
# return ssl_protocol._app_transport
#
# Path: aiosmtplib/errors.py
# class SMTPDataError(SMTPResponseException):
# """
# Server refused DATA content.
# """
#
# class SMTPReadTimeoutError(SMTPTimeoutError):
# """
# A timeout occurred while waiting for a response from the SMTP server.
# """
#
# class SMTPResponseException(SMTPException):
# """
# Base class for all server responses with error codes.
# """
#
# def __init__(self, code: int, message: str) -> None:
# self.code = code
# self.message = message
# self.args = (code, message)
#
# class SMTPServerDisconnected(SMTPException, ConnectionError):
# """
# The connection was lost unexpectedly, or a command was run that requires
# a connection.
# """
#
# class SMTPTimeoutError(SMTPException, TimeoutError):
# """
# A timeout occurred while performing a network operation.
# """
#
# Path: aiosmtplib/response.py
# class SMTPResponse(BaseResponse):
# """
# NamedTuple of server response code and server response message.
#
# ``code`` and ``message`` can be accessed via attributes or indexes:
#
# >>> response = SMTPResponse(200, "OK")
# >>> response.message
# 'OK'
# >>> response[0]
# 200
# >>> response.code
# 200
#
# """
#
# __slots__ = ()
#
# def __repr__(self) -> str:
# return "({self.code}, {self.message})".format(self=self)
#
# def __str__(self) -> str:
# return "{self.code} {self.message}".format(self=self)
#
# Path: aiosmtplib/status.py
# class SMTPStatus(enum.IntEnum):
# """
# Defines SMTP statuses for code readability.
#
# See also: http://www.greenend.org.uk/rjk/tech/smtpreplies.html
# """
#
# invalid_response = -1
# system_status_ok = 211
# help_message = 214
# ready = 220
# closing = 221
# auth_successful = 235
# completed = 250
# will_forward = 251
# cannot_vrfy = 252
# auth_continue = 334
# start_input = 354
# domain_unavailable = 421
# mailbox_unavailable = 450
# error_processing = 451
# insufficient_storage = 452
# tls_not_available = 454
# unrecognized_command = 500
# unrecognized_parameters = 501
# command_not_implemented = 502
# bad_command_sequence = 503
# parameter_not_implemented = 504
# domain_does_not_accept_mail = 521
# access_denied = 530 # Sendmail specific
# auth_failed = 535
# mailbox_does_not_exist = 550
# user_not_local = 551
# storage_exceeded = 552
# mailbox_name_invalid = 553
# transaction_failed = 554
# syntax_error = 555
. Output only the next line. | smtp_exc = SMTPServerDisconnected("Connection lost") |
Predict the next line for this snippet: <|code_start|> ) -> SMTPResponse:
"""
Puts the connection to the SMTP server into TLS mode.
"""
if self._over_ssl:
raise RuntimeError("Already using TLS.")
if self._command_lock is None:
raise SMTPServerDisconnected("Server not connected")
async with self._command_lock:
self.write(b"STARTTLS\r\n")
response = await self.read_response(timeout=timeout)
if response.code != SMTPStatus.ready:
raise SMTPResponseException(response.code, response.message)
# Check for disconnect after response
if self.transport is None or self.transport.is_closing():
raise SMTPServerDisconnected("Connection lost")
try:
tls_transport = await start_tls(
self._loop,
self.transport,
self,
tls_context,
server_side=False,
server_hostname=server_hostname,
ssl_handshake_timeout=timeout,
)
except asyncio.TimeoutError as exc:
<|code_end|>
with the help of current file imports:
import asyncio
import re
import ssl
from typing import Callable, Optional, cast
from .compat import start_tls
from .errors import (
SMTPDataError,
SMTPReadTimeoutError,
SMTPResponseException,
SMTPServerDisconnected,
SMTPTimeoutError,
)
from .response import SMTPResponse
from .status import SMTPStatus
and context from other files:
# Path: aiosmtplib/compat.py
# async def start_tls(
# loop: asyncio.AbstractEventLoop,
# transport: asyncio.Transport,
# protocol: asyncio.Protocol,
# sslcontext: ssl.SSLContext,
# server_side: bool = False,
# server_hostname: Optional[str] = None,
# ssl_handshake_timeout: Optional[Union[float, int]] = None,
# ) -> asyncio.Transport:
# # We use hasattr here, as uvloop also supports start_tls.
# if hasattr(loop, "start_tls"):
# return await loop.start_tls( # type: ignore
# transport,
# protocol,
# sslcontext,
# server_side=server_side,
# server_hostname=server_hostname,
# ssl_handshake_timeout=ssl_handshake_timeout,
# )
#
# waiter = loop.create_future()
# ssl_protocol = SSLProtocol(
# loop, protocol, sslcontext, waiter, server_side, server_hostname
# )
#
# # Pause early so that "ssl_protocol.data_received()" doesn't
# # have a chance to get called before "ssl_protocol.connection_made()".
# transport.pause_reading()
#
# # Use set_protocol if we can
# if hasattr(transport, "set_protocol"):
# transport.set_protocol(ssl_protocol)
# else:
# transport._protocol = ssl_protocol # type: ignore
#
# conmade_cb = loop.call_soon(ssl_protocol.connection_made, transport)
# resume_cb = loop.call_soon(transport.resume_reading)
#
# try:
# await asyncio.wait_for(waiter, timeout=ssl_handshake_timeout)
# except Exception:
# transport.close()
# conmade_cb.cancel()
# resume_cb.cancel()
# raise
#
# return ssl_protocol._app_transport
#
# Path: aiosmtplib/errors.py
# class SMTPDataError(SMTPResponseException):
# """
# Server refused DATA content.
# """
#
# class SMTPReadTimeoutError(SMTPTimeoutError):
# """
# A timeout occurred while waiting for a response from the SMTP server.
# """
#
# class SMTPResponseException(SMTPException):
# """
# Base class for all server responses with error codes.
# """
#
# def __init__(self, code: int, message: str) -> None:
# self.code = code
# self.message = message
# self.args = (code, message)
#
# class SMTPServerDisconnected(SMTPException, ConnectionError):
# """
# The connection was lost unexpectedly, or a command was run that requires
# a connection.
# """
#
# class SMTPTimeoutError(SMTPException, TimeoutError):
# """
# A timeout occurred while performing a network operation.
# """
#
# Path: aiosmtplib/response.py
# class SMTPResponse(BaseResponse):
# """
# NamedTuple of server response code and server response message.
#
# ``code`` and ``message`` can be accessed via attributes or indexes:
#
# >>> response = SMTPResponse(200, "OK")
# >>> response.message
# 'OK'
# >>> response[0]
# 200
# >>> response.code
# 200
#
# """
#
# __slots__ = ()
#
# def __repr__(self) -> str:
# return "({self.code}, {self.message})".format(self=self)
#
# def __str__(self) -> str:
# return "{self.code} {self.message}".format(self=self)
#
# Path: aiosmtplib/status.py
# class SMTPStatus(enum.IntEnum):
# """
# Defines SMTP statuses for code readability.
#
# See also: http://www.greenend.org.uk/rjk/tech/smtpreplies.html
# """
#
# invalid_response = -1
# system_status_ok = 211
# help_message = 214
# ready = 220
# closing = 221
# auth_successful = 235
# completed = 250
# will_forward = 251
# cannot_vrfy = 252
# auth_continue = 334
# start_input = 354
# domain_unavailable = 421
# mailbox_unavailable = 450
# error_processing = 451
# insufficient_storage = 452
# tls_not_available = 454
# unrecognized_command = 500
# unrecognized_parameters = 501
# command_not_implemented = 502
# bad_command_sequence = 503
# parameter_not_implemented = 504
# domain_does_not_accept_mail = 521
# access_denied = 530 # Sendmail specific
# auth_failed = 535
# mailbox_does_not_exist = 550
# user_not_local = 551
# storage_exceeded = 552
# mailbox_name_invalid = 553
# transaction_failed = 554
# syntax_error = 555
, which may contain function names, class names, or code. Output only the next line. | raise SMTPTimeoutError("Timed out while upgrading transport") from exc |
Given the code snippet: <|code_start|> return
self._buffer.extend(data)
# If we got an obvious partial message, don't try to parse the buffer
last_linebreak = data.rfind(b"\n")
if (
last_linebreak == -1
or data[last_linebreak + 3 : last_linebreak + 4] == b"-"
):
return
try:
response = self._read_response_from_buffer()
except Exception as exc:
self._response_waiter.set_exception(exc)
else:
if response is not None:
self._response_waiter.set_result(response)
def eof_received(self) -> bool:
exc = SMTPServerDisconnected("Unexpected EOF received")
if self._response_waiter and not self._response_waiter.done():
self._response_waiter.set_exception(exc)
if self._connection_lost_waiter and not self._connection_lost_waiter.done():
self._connection_lost_waiter.set_exception(exc)
# Returning false closes the transport
return False
<|code_end|>
, generate the next line using the imports in this file:
import asyncio
import re
import ssl
from typing import Callable, Optional, cast
from .compat import start_tls
from .errors import (
SMTPDataError,
SMTPReadTimeoutError,
SMTPResponseException,
SMTPServerDisconnected,
SMTPTimeoutError,
)
from .response import SMTPResponse
from .status import SMTPStatus
and context (functions, classes, or occasionally code) from other files:
# Path: aiosmtplib/compat.py
# async def start_tls(
# loop: asyncio.AbstractEventLoop,
# transport: asyncio.Transport,
# protocol: asyncio.Protocol,
# sslcontext: ssl.SSLContext,
# server_side: bool = False,
# server_hostname: Optional[str] = None,
# ssl_handshake_timeout: Optional[Union[float, int]] = None,
# ) -> asyncio.Transport:
# # We use hasattr here, as uvloop also supports start_tls.
# if hasattr(loop, "start_tls"):
# return await loop.start_tls( # type: ignore
# transport,
# protocol,
# sslcontext,
# server_side=server_side,
# server_hostname=server_hostname,
# ssl_handshake_timeout=ssl_handshake_timeout,
# )
#
# waiter = loop.create_future()
# ssl_protocol = SSLProtocol(
# loop, protocol, sslcontext, waiter, server_side, server_hostname
# )
#
# # Pause early so that "ssl_protocol.data_received()" doesn't
# # have a chance to get called before "ssl_protocol.connection_made()".
# transport.pause_reading()
#
# # Use set_protocol if we can
# if hasattr(transport, "set_protocol"):
# transport.set_protocol(ssl_protocol)
# else:
# transport._protocol = ssl_protocol # type: ignore
#
# conmade_cb = loop.call_soon(ssl_protocol.connection_made, transport)
# resume_cb = loop.call_soon(transport.resume_reading)
#
# try:
# await asyncio.wait_for(waiter, timeout=ssl_handshake_timeout)
# except Exception:
# transport.close()
# conmade_cb.cancel()
# resume_cb.cancel()
# raise
#
# return ssl_protocol._app_transport
#
# Path: aiosmtplib/errors.py
# class SMTPDataError(SMTPResponseException):
# """
# Server refused DATA content.
# """
#
# class SMTPReadTimeoutError(SMTPTimeoutError):
# """
# A timeout occurred while waiting for a response from the SMTP server.
# """
#
# class SMTPResponseException(SMTPException):
# """
# Base class for all server responses with error codes.
# """
#
# def __init__(self, code: int, message: str) -> None:
# self.code = code
# self.message = message
# self.args = (code, message)
#
# class SMTPServerDisconnected(SMTPException, ConnectionError):
# """
# The connection was lost unexpectedly, or a command was run that requires
# a connection.
# """
#
# class SMTPTimeoutError(SMTPException, TimeoutError):
# """
# A timeout occurred while performing a network operation.
# """
#
# Path: aiosmtplib/response.py
# class SMTPResponse(BaseResponse):
# """
# NamedTuple of server response code and server response message.
#
# ``code`` and ``message`` can be accessed via attributes or indexes:
#
# >>> response = SMTPResponse(200, "OK")
# >>> response.message
# 'OK'
# >>> response[0]
# 200
# >>> response.code
# 200
#
# """
#
# __slots__ = ()
#
# def __repr__(self) -> str:
# return "({self.code}, {self.message})".format(self=self)
#
# def __str__(self) -> str:
# return "{self.code} {self.message}".format(self=self)
#
# Path: aiosmtplib/status.py
# class SMTPStatus(enum.IntEnum):
# """
# Defines SMTP statuses for code readability.
#
# See also: http://www.greenend.org.uk/rjk/tech/smtpreplies.html
# """
#
# invalid_response = -1
# system_status_ok = 211
# help_message = 214
# ready = 220
# closing = 221
# auth_successful = 235
# completed = 250
# will_forward = 251
# cannot_vrfy = 252
# auth_continue = 334
# start_input = 354
# domain_unavailable = 421
# mailbox_unavailable = 450
# error_processing = 451
# insufficient_storage = 452
# tls_not_available = 454
# unrecognized_command = 500
# unrecognized_parameters = 501
# command_not_implemented = 502
# bad_command_sequence = 503
# parameter_not_implemented = 504
# domain_does_not_accept_mail = 521
# access_denied = 530 # Sendmail specific
# auth_failed = 535
# mailbox_does_not_exist = 550
# user_not_local = 551
# storage_exceeded = 552
# mailbox_name_invalid = 553
# transaction_failed = 554
# syntax_error = 555
. Output only the next line. | def _read_response_from_buffer(self) -> Optional[SMTPResponse]: |
Given the code snippet: <|code_start|> else:
if response is not None:
self._response_waiter.set_result(response)
def eof_received(self) -> bool:
exc = SMTPServerDisconnected("Unexpected EOF received")
if self._response_waiter and not self._response_waiter.done():
self._response_waiter.set_exception(exc)
if self._connection_lost_waiter and not self._connection_lost_waiter.done():
self._connection_lost_waiter.set_exception(exc)
# Returning false closes the transport
return False
def _read_response_from_buffer(self) -> Optional[SMTPResponse]:
"""Parse the actual response (if any) from the data buffer"""
code = -1
message = bytearray()
offset = 0
message_complete = False
while True:
line_end_index = self._buffer.find(b"\n", offset)
if line_end_index == -1:
break
line = bytes(self._buffer[offset : line_end_index + 1])
if len(line) > MAX_LINE_LENGTH:
raise SMTPResponseException(
<|code_end|>
, generate the next line using the imports in this file:
import asyncio
import re
import ssl
from typing import Callable, Optional, cast
from .compat import start_tls
from .errors import (
SMTPDataError,
SMTPReadTimeoutError,
SMTPResponseException,
SMTPServerDisconnected,
SMTPTimeoutError,
)
from .response import SMTPResponse
from .status import SMTPStatus
and context (functions, classes, or occasionally code) from other files:
# Path: aiosmtplib/compat.py
# async def start_tls(
# loop: asyncio.AbstractEventLoop,
# transport: asyncio.Transport,
# protocol: asyncio.Protocol,
# sslcontext: ssl.SSLContext,
# server_side: bool = False,
# server_hostname: Optional[str] = None,
# ssl_handshake_timeout: Optional[Union[float, int]] = None,
# ) -> asyncio.Transport:
# # We use hasattr here, as uvloop also supports start_tls.
# if hasattr(loop, "start_tls"):
# return await loop.start_tls( # type: ignore
# transport,
# protocol,
# sslcontext,
# server_side=server_side,
# server_hostname=server_hostname,
# ssl_handshake_timeout=ssl_handshake_timeout,
# )
#
# waiter = loop.create_future()
# ssl_protocol = SSLProtocol(
# loop, protocol, sslcontext, waiter, server_side, server_hostname
# )
#
# # Pause early so that "ssl_protocol.data_received()" doesn't
# # have a chance to get called before "ssl_protocol.connection_made()".
# transport.pause_reading()
#
# # Use set_protocol if we can
# if hasattr(transport, "set_protocol"):
# transport.set_protocol(ssl_protocol)
# else:
# transport._protocol = ssl_protocol # type: ignore
#
# conmade_cb = loop.call_soon(ssl_protocol.connection_made, transport)
# resume_cb = loop.call_soon(transport.resume_reading)
#
# try:
# await asyncio.wait_for(waiter, timeout=ssl_handshake_timeout)
# except Exception:
# transport.close()
# conmade_cb.cancel()
# resume_cb.cancel()
# raise
#
# return ssl_protocol._app_transport
#
# Path: aiosmtplib/errors.py
# class SMTPDataError(SMTPResponseException):
# """
# Server refused DATA content.
# """
#
# class SMTPReadTimeoutError(SMTPTimeoutError):
# """
# A timeout occurred while waiting for a response from the SMTP server.
# """
#
# class SMTPResponseException(SMTPException):
# """
# Base class for all server responses with error codes.
# """
#
# def __init__(self, code: int, message: str) -> None:
# self.code = code
# self.message = message
# self.args = (code, message)
#
# class SMTPServerDisconnected(SMTPException, ConnectionError):
# """
# The connection was lost unexpectedly, or a command was run that requires
# a connection.
# """
#
# class SMTPTimeoutError(SMTPException, TimeoutError):
# """
# A timeout occurred while performing a network operation.
# """
#
# Path: aiosmtplib/response.py
# class SMTPResponse(BaseResponse):
# """
# NamedTuple of server response code and server response message.
#
# ``code`` and ``message`` can be accessed via attributes or indexes:
#
# >>> response = SMTPResponse(200, "OK")
# >>> response.message
# 'OK'
# >>> response[0]
# 200
# >>> response.code
# 200
#
# """
#
# __slots__ = ()
#
# def __repr__(self) -> str:
# return "({self.code}, {self.message})".format(self=self)
#
# def __str__(self) -> str:
# return "{self.code} {self.message}".format(self=self)
#
# Path: aiosmtplib/status.py
# class SMTPStatus(enum.IntEnum):
# """
# Defines SMTP statuses for code readability.
#
# See also: http://www.greenend.org.uk/rjk/tech/smtpreplies.html
# """
#
# invalid_response = -1
# system_status_ok = 211
# help_message = 214
# ready = 220
# closing = 221
# auth_successful = 235
# completed = 250
# will_forward = 251
# cannot_vrfy = 252
# auth_continue = 334
# start_input = 354
# domain_unavailable = 421
# mailbox_unavailable = 450
# error_processing = 451
# insufficient_storage = 452
# tls_not_available = 454
# unrecognized_command = 500
# unrecognized_parameters = 501
# command_not_implemented = 502
# bad_command_sequence = 503
# parameter_not_implemented = 504
# domain_does_not_accept_mail = 521
# access_denied = 530 # Sendmail specific
# auth_failed = 535
# mailbox_does_not_exist = 550
# user_not_local = 551
# storage_exceeded = 552
# mailbox_name_invalid = 553
# transaction_failed = 554
# syntax_error = 555
. Output only the next line. | SMTPStatus.unrecognized_command, "Response too long" |
Given the following code snippet before the placeholder: <|code_start|>async def test_send_compat32_message_smtputf8_recipient(
smtp_client_smtputf8,
smtpd_server_smtputf8,
compat32_message,
received_commands,
received_messages,
):
recipient_bytes = bytes("reçipïént@exåmple.com", "utf-8")
compat32_message["To"] = email.header.Header(recipient_bytes, "utf-8")
async with smtp_client_smtputf8:
errors, response = await smtp_client_smtputf8.send_message(compat32_message)
assert not errors
assert response != ""
assert received_commands[2][0] == "RCPT"
assert received_commands[2][1] == compat32_message["To"]
assert len(received_messages) == 1
assert (
received_messages[0]["X-RcptTo"]
== "recipient@example.com, reçipïént@exåmple.com"
)
async def test_send_message_smtputf8_not_supported(smtp_client, smtpd_server, message):
message["To"] = "reçipïént2@exåmple.com"
async with smtp_client:
<|code_end|>
, predict the next line using imports from the current file:
import copy
import email.generator
import email.header
import pytest
from aiosmtplib import (
SMTPNotSupported,
SMTPRecipientsRefused,
SMTPResponseException,
SMTPStatus,
)
from aiosmtplib.email import formataddr
and context including class names, function names, and sometimes code from other files:
# Path: aiosmtplib/errors.py
# class SMTPNotSupported(SMTPException):
# """
# A command or argument sent to the SMTP server is not supported.
# """
#
# class SMTPRecipientsRefused(SMTPException):
# """
# SMTP server refused multiple recipients.
# """
#
# def __init__(self, recipients: List[SMTPRecipientRefused]) -> None:
# self.recipients = recipients
# self.args = (recipients,)
#
# class SMTPResponseException(SMTPException):
# """
# Base class for all server responses with error codes.
# """
#
# def __init__(self, code: int, message: str) -> None:
# self.code = code
# self.message = message
# self.args = (code, message)
#
# Path: aiosmtplib/status.py
# class SMTPStatus(enum.IntEnum):
# """
# Defines SMTP statuses for code readability.
#
# See also: http://www.greenend.org.uk/rjk/tech/smtpreplies.html
# """
#
# invalid_response = -1
# system_status_ok = 211
# help_message = 214
# ready = 220
# closing = 221
# auth_successful = 235
# completed = 250
# will_forward = 251
# cannot_vrfy = 252
# auth_continue = 334
# start_input = 354
# domain_unavailable = 421
# mailbox_unavailable = 450
# error_processing = 451
# insufficient_storage = 452
# tls_not_available = 454
# unrecognized_command = 500
# unrecognized_parameters = 501
# command_not_implemented = 502
# bad_command_sequence = 503
# parameter_not_implemented = 504
# domain_does_not_accept_mail = 521
# access_denied = 530 # Sendmail specific
# auth_failed = 535
# mailbox_does_not_exist = 550
# user_not_local = 551
# storage_exceeded = 552
# mailbox_name_invalid = 553
# transaction_failed = 554
# syntax_error = 555
#
# Path: aiosmtplib/email.py
# def formataddr(pair: Tuple[str, str]) -> str:
# """
# Copied from the standard library, and modified to handle international (UTF-8)
# email addresses.
#
# The inverse of parseaddr(), this takes a 2-tuple of the form
# (realname, email_address) and returns the string value suitable
# for an RFC 2822 From, To or Cc header.
# If the first element of pair is false, then the second element is
# returned unmodified.
# """
# name, address = pair
# if name:
# encoded_name = UTF8_CHARSET.header_encode(name)
# return "{} <{}>".format(encoded_name, address)
# else:
# quotes = ""
# if SPECIALS_REGEX.search(name):
# quotes = '"'
# name = ESCAPES_REGEX.sub(r"\\\g<0>", name)
# return "{}{}{} <{}>".format(quotes, name, quotes, address)
#
# return address
. Output only the next line. | with pytest.raises(SMTPNotSupported): |
Here is a snippet: <|code_start|> monkeypatch.setattr(smtpd_class, "smtp_EHLO", response_handler)
async with smtp_client:
errors, response = await smtp_client.sendmail(
sender_str, [recipient_str], message_str
)
assert not errors
assert response != ""
async def test_sendmail_with_invalid_mail_option(
smtp_client, smtpd_server, sender_str, recipient_str, message_str
):
async with smtp_client:
with pytest.raises(SMTPResponseException) as excinfo:
await smtp_client.sendmail(
sender_str,
[recipient_str],
message_str,
mail_options=["BADDATA=0x00000000"],
)
assert excinfo.value.code == SMTPStatus.syntax_error
async def test_sendmail_with_rcpt_option(
smtp_client, smtpd_server, sender_str, recipient_str, message_str
):
async with smtp_client:
<|code_end|>
. Write the next line using the current file imports:
import copy
import email.generator
import email.header
import pytest
from aiosmtplib import (
SMTPNotSupported,
SMTPRecipientsRefused,
SMTPResponseException,
SMTPStatus,
)
from aiosmtplib.email import formataddr
and context from other files:
# Path: aiosmtplib/errors.py
# class SMTPNotSupported(SMTPException):
# """
# A command or argument sent to the SMTP server is not supported.
# """
#
# class SMTPRecipientsRefused(SMTPException):
# """
# SMTP server refused multiple recipients.
# """
#
# def __init__(self, recipients: List[SMTPRecipientRefused]) -> None:
# self.recipients = recipients
# self.args = (recipients,)
#
# class SMTPResponseException(SMTPException):
# """
# Base class for all server responses with error codes.
# """
#
# def __init__(self, code: int, message: str) -> None:
# self.code = code
# self.message = message
# self.args = (code, message)
#
# Path: aiosmtplib/status.py
# class SMTPStatus(enum.IntEnum):
# """
# Defines SMTP statuses for code readability.
#
# See also: http://www.greenend.org.uk/rjk/tech/smtpreplies.html
# """
#
# invalid_response = -1
# system_status_ok = 211
# help_message = 214
# ready = 220
# closing = 221
# auth_successful = 235
# completed = 250
# will_forward = 251
# cannot_vrfy = 252
# auth_continue = 334
# start_input = 354
# domain_unavailable = 421
# mailbox_unavailable = 450
# error_processing = 451
# insufficient_storage = 452
# tls_not_available = 454
# unrecognized_command = 500
# unrecognized_parameters = 501
# command_not_implemented = 502
# bad_command_sequence = 503
# parameter_not_implemented = 504
# domain_does_not_accept_mail = 521
# access_denied = 530 # Sendmail specific
# auth_failed = 535
# mailbox_does_not_exist = 550
# user_not_local = 551
# storage_exceeded = 552
# mailbox_name_invalid = 553
# transaction_failed = 554
# syntax_error = 555
#
# Path: aiosmtplib/email.py
# def formataddr(pair: Tuple[str, str]) -> str:
# """
# Copied from the standard library, and modified to handle international (UTF-8)
# email addresses.
#
# The inverse of parseaddr(), this takes a 2-tuple of the form
# (realname, email_address) and returns the string value suitable
# for an RFC 2822 From, To or Cc header.
# If the first element of pair is false, then the second element is
# returned unmodified.
# """
# name, address = pair
# if name:
# encoded_name = UTF8_CHARSET.header_encode(name)
# return "{} <{}>".format(encoded_name, address)
# else:
# quotes = ""
# if SPECIALS_REGEX.search(name):
# quotes = '"'
# name = ESCAPES_REGEX.sub(r"\\\g<0>", name)
# return "{}{}{} <{}>".format(quotes, name, quotes, address)
#
# return address
, which may include functions, classes, or code. Output only the next line. | with pytest.raises(SMTPRecipientsRefused) as excinfo: |
Continue the code snippet: <|code_start|>
async def test_sendmail_without_size_option(
smtp_client,
smtpd_server,
smtpd_class,
smtpd_response_handler_factory,
monkeypatch,
sender_str,
recipient_str,
message_str,
received_commands,
):
response_handler = smtpd_response_handler_factory(
"{} done".format(SMTPStatus.completed)
)
monkeypatch.setattr(smtpd_class, "smtp_EHLO", response_handler)
async with smtp_client:
errors, response = await smtp_client.sendmail(
sender_str, [recipient_str], message_str
)
assert not errors
assert response != ""
async def test_sendmail_with_invalid_mail_option(
smtp_client, smtpd_server, sender_str, recipient_str, message_str
):
async with smtp_client:
<|code_end|>
. Use current file imports:
import copy
import email.generator
import email.header
import pytest
from aiosmtplib import (
SMTPNotSupported,
SMTPRecipientsRefused,
SMTPResponseException,
SMTPStatus,
)
from aiosmtplib.email import formataddr
and context (classes, functions, or code) from other files:
# Path: aiosmtplib/errors.py
# class SMTPNotSupported(SMTPException):
# """
# A command or argument sent to the SMTP server is not supported.
# """
#
# class SMTPRecipientsRefused(SMTPException):
# """
# SMTP server refused multiple recipients.
# """
#
# def __init__(self, recipients: List[SMTPRecipientRefused]) -> None:
# self.recipients = recipients
# self.args = (recipients,)
#
# class SMTPResponseException(SMTPException):
# """
# Base class for all server responses with error codes.
# """
#
# def __init__(self, code: int, message: str) -> None:
# self.code = code
# self.message = message
# self.args = (code, message)
#
# Path: aiosmtplib/status.py
# class SMTPStatus(enum.IntEnum):
# """
# Defines SMTP statuses for code readability.
#
# See also: http://www.greenend.org.uk/rjk/tech/smtpreplies.html
# """
#
# invalid_response = -1
# system_status_ok = 211
# help_message = 214
# ready = 220
# closing = 221
# auth_successful = 235
# completed = 250
# will_forward = 251
# cannot_vrfy = 252
# auth_continue = 334
# start_input = 354
# domain_unavailable = 421
# mailbox_unavailable = 450
# error_processing = 451
# insufficient_storage = 452
# tls_not_available = 454
# unrecognized_command = 500
# unrecognized_parameters = 501
# command_not_implemented = 502
# bad_command_sequence = 503
# parameter_not_implemented = 504
# domain_does_not_accept_mail = 521
# access_denied = 530 # Sendmail specific
# auth_failed = 535
# mailbox_does_not_exist = 550
# user_not_local = 551
# storage_exceeded = 552
# mailbox_name_invalid = 553
# transaction_failed = 554
# syntax_error = 555
#
# Path: aiosmtplib/email.py
# def formataddr(pair: Tuple[str, str]) -> str:
# """
# Copied from the standard library, and modified to handle international (UTF-8)
# email addresses.
#
# The inverse of parseaddr(), this takes a 2-tuple of the form
# (realname, email_address) and returns the string value suitable
# for an RFC 2822 From, To or Cc header.
# If the first element of pair is false, then the second element is
# returned unmodified.
# """
# name, address = pair
# if name:
# encoded_name = UTF8_CHARSET.header_encode(name)
# return "{} <{}>".format(encoded_name, address)
# else:
# quotes = ""
# if SPECIALS_REGEX.search(name):
# quotes = '"'
# name = ESCAPES_REGEX.sub(r"\\\g<0>", name)
# return "{}{}{} <{}>".format(quotes, name, quotes, address)
#
# return address
. Output only the next line. | with pytest.raises(SMTPResponseException) as excinfo: |
Given snippet: <|code_start|> )
assert not errors
assert response != ""
async def test_sendmail_with_mail_option(
smtp_client, smtpd_server, sender_str, recipient_str, message_str
):
async with smtp_client:
errors, response = await smtp_client.sendmail(
sender_str, [recipient_str], message_str, mail_options=["BODY=8BITMIME"]
)
assert not errors
assert response != ""
async def test_sendmail_without_size_option(
smtp_client,
smtpd_server,
smtpd_class,
smtpd_response_handler_factory,
monkeypatch,
sender_str,
recipient_str,
message_str,
received_commands,
):
response_handler = smtpd_response_handler_factory(
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import copy
import email.generator
import email.header
import pytest
from aiosmtplib import (
SMTPNotSupported,
SMTPRecipientsRefused,
SMTPResponseException,
SMTPStatus,
)
from aiosmtplib.email import formataddr
and context:
# Path: aiosmtplib/errors.py
# class SMTPNotSupported(SMTPException):
# """
# A command or argument sent to the SMTP server is not supported.
# """
#
# class SMTPRecipientsRefused(SMTPException):
# """
# SMTP server refused multiple recipients.
# """
#
# def __init__(self, recipients: List[SMTPRecipientRefused]) -> None:
# self.recipients = recipients
# self.args = (recipients,)
#
# class SMTPResponseException(SMTPException):
# """
# Base class for all server responses with error codes.
# """
#
# def __init__(self, code: int, message: str) -> None:
# self.code = code
# self.message = message
# self.args = (code, message)
#
# Path: aiosmtplib/status.py
# class SMTPStatus(enum.IntEnum):
# """
# Defines SMTP statuses for code readability.
#
# See also: http://www.greenend.org.uk/rjk/tech/smtpreplies.html
# """
#
# invalid_response = -1
# system_status_ok = 211
# help_message = 214
# ready = 220
# closing = 221
# auth_successful = 235
# completed = 250
# will_forward = 251
# cannot_vrfy = 252
# auth_continue = 334
# start_input = 354
# domain_unavailable = 421
# mailbox_unavailable = 450
# error_processing = 451
# insufficient_storage = 452
# tls_not_available = 454
# unrecognized_command = 500
# unrecognized_parameters = 501
# command_not_implemented = 502
# bad_command_sequence = 503
# parameter_not_implemented = 504
# domain_does_not_accept_mail = 521
# access_denied = 530 # Sendmail specific
# auth_failed = 535
# mailbox_does_not_exist = 550
# user_not_local = 551
# storage_exceeded = 552
# mailbox_name_invalid = 553
# transaction_failed = 554
# syntax_error = 555
#
# Path: aiosmtplib/email.py
# def formataddr(pair: Tuple[str, str]) -> str:
# """
# Copied from the standard library, and modified to handle international (UTF-8)
# email addresses.
#
# The inverse of parseaddr(), this takes a 2-tuple of the form
# (realname, email_address) and returns the string value suitable
# for an RFC 2822 From, To or Cc header.
# If the first element of pair is false, then the second element is
# returned unmodified.
# """
# name, address = pair
# if name:
# encoded_name = UTF8_CHARSET.header_encode(name)
# return "{} <{}>".format(encoded_name, address)
# else:
# quotes = ""
# if SPECIALS_REGEX.search(name):
# quotes = '"'
# name = ESCAPES_REGEX.sub(r"\\\g<0>", name)
# return "{}{}{} <{}>".format(quotes, name, quotes, address)
#
# return address
which might include code, classes, or functions. Output only the next line. | "{} done".format(SMTPStatus.completed) |
Predict the next line for this snippet: <|code_start|> received_messages,
):
recipient_bytes = bytes("reçipïént@exåmple.com", "utf-8")
compat32_message["To"] = email.header.Header(recipient_bytes, "utf-8")
async with smtp_client_smtputf8:
errors, response = await smtp_client_smtputf8.send_message(compat32_message)
assert not errors
assert response != ""
assert received_commands[2][0] == "RCPT"
assert received_commands[2][1] == compat32_message["To"]
assert len(received_messages) == 1
assert (
received_messages[0]["X-RcptTo"]
== "recipient@example.com, reçipïént@exåmple.com"
)
async def test_send_message_smtputf8_not_supported(smtp_client, smtpd_server, message):
message["To"] = "reçipïént2@exåmple.com"
async with smtp_client:
with pytest.raises(SMTPNotSupported):
await smtp_client.send_message(message)
async def test_send_message_with_formataddr(smtp_client, smtpd_server, message):
<|code_end|>
with the help of current file imports:
import copy
import email.generator
import email.header
import pytest
from aiosmtplib import (
SMTPNotSupported,
SMTPRecipientsRefused,
SMTPResponseException,
SMTPStatus,
)
from aiosmtplib.email import formataddr
and context from other files:
# Path: aiosmtplib/errors.py
# class SMTPNotSupported(SMTPException):
# """
# A command or argument sent to the SMTP server is not supported.
# """
#
# class SMTPRecipientsRefused(SMTPException):
# """
# SMTP server refused multiple recipients.
# """
#
# def __init__(self, recipients: List[SMTPRecipientRefused]) -> None:
# self.recipients = recipients
# self.args = (recipients,)
#
# class SMTPResponseException(SMTPException):
# """
# Base class for all server responses with error codes.
# """
#
# def __init__(self, code: int, message: str) -> None:
# self.code = code
# self.message = message
# self.args = (code, message)
#
# Path: aiosmtplib/status.py
# class SMTPStatus(enum.IntEnum):
# """
# Defines SMTP statuses for code readability.
#
# See also: http://www.greenend.org.uk/rjk/tech/smtpreplies.html
# """
#
# invalid_response = -1
# system_status_ok = 211
# help_message = 214
# ready = 220
# closing = 221
# auth_successful = 235
# completed = 250
# will_forward = 251
# cannot_vrfy = 252
# auth_continue = 334
# start_input = 354
# domain_unavailable = 421
# mailbox_unavailable = 450
# error_processing = 451
# insufficient_storage = 452
# tls_not_available = 454
# unrecognized_command = 500
# unrecognized_parameters = 501
# command_not_implemented = 502
# bad_command_sequence = 503
# parameter_not_implemented = 504
# domain_does_not_accept_mail = 521
# access_denied = 530 # Sendmail specific
# auth_failed = 535
# mailbox_does_not_exist = 550
# user_not_local = 551
# storage_exceeded = 552
# mailbox_name_invalid = 553
# transaction_failed = 554
# syntax_error = 555
#
# Path: aiosmtplib/email.py
# def formataddr(pair: Tuple[str, str]) -> str:
# """
# Copied from the standard library, and modified to handle international (UTF-8)
# email addresses.
#
# The inverse of parseaddr(), this takes a 2-tuple of the form
# (realname, email_address) and returns the string value suitable
# for an RFC 2822 From, To or Cc header.
# If the first element of pair is false, then the second element is
# returned unmodified.
# """
# name, address = pair
# if name:
# encoded_name = UTF8_CHARSET.header_encode(name)
# return "{} <{}>".format(encoded_name, address)
# else:
# quotes = ""
# if SPECIALS_REGEX.search(name):
# quotes = '"'
# name = ESCAPES_REGEX.sub(r"\\\g<0>", name)
# return "{}{}{} <{}>".format(quotes, name, quotes, address)
#
# return address
, which may contain function names, class names, or code. Output only the next line. | message["To"] = formataddr(("æøå", "someotheruser@example.com")) |
Using the snippet: <|code_start|>"""
send coroutine testing.
"""
pytestmark = pytest.mark.asyncio()
async def test_send(hostname, smtpd_server_port, message, received_messages):
<|code_end|>
, determine the next line of code. You have imports:
import pytest
from aiosmtplib import send
and context (class names, function names, or code) available:
# Path: aiosmtplib/api.py
# @overload
# async def send(
# message: Union[email.message.EmailMessage, email.message.Message],
# sender: Optional[str] = ...,
# recipients: Optional[Union[str, Sequence[str]]] = ...,
# hostname: str = ...,
# port: Optional[int] = ...,
# username: Optional[Union[str, bytes]] = ...,
# password: Optional[Union[str, bytes]] = ...,
# mail_options: Optional[List[str]] = ...,
# rcpt_options: Optional[List[str]] = ...,
# timeout: Optional[float] = ...,
# source_address: Optional[str] = ...,
# use_tls: bool = ...,
# start_tls: bool = ...,
# validate_certs: bool = ...,
# client_cert: Optional[str] = ...,
# client_key: Optional[str] = ...,
# tls_context: None = ...,
# cert_bundle: Optional[str] = ...,
# socket_path: None = ...,
# sock: None = ...,
# ) -> Tuple[Dict[str, SMTPResponse], str]:
# ...
. Output only the next line. | errors, response = await send(message, hostname=hostname, port=smtpd_server_port) |
Using the snippet: <|code_start|> self.server = self.loop.run_until_complete(
self.loop.create_server(
self.factory,
host=self.hostname,
port=self.port,
ssl=self.ssl_context,
family=socket.AF_INET,
)
)
except Exception as error:
self._thread_exception = error
return
self.loop.call_soon(ready_event.set)
self.loop.run_forever()
self.server.close()
self.loop.run_until_complete(self.server.wait_closed())
self.server = None
def start(self):
ready_event = threading.Event()
self._thread = threading.Thread(target=self._run, args=(ready_event,))
self._thread.daemon = True
self._thread.start()
# Wait a while until the server is responding.
ready_event.wait(self.ready_timeout)
if self._thread_exception is not None:
raise self._thread_exception
def _stop(self):
self.loop.stop()
<|code_end|>
, determine the next line of code. You have imports:
import asyncio
import base64
import logging
import socket
import threading
from email.errors import HeaderParseError
from email.message import Message
from aiosmtpd.handlers import Message as MessageHandler
from aiosmtpd.smtp import MISSING
from aiosmtpd.smtp import SMTP as SMTPD
from aiosmtplib.sync import shutdown_loop
and context (class names, function names, or code) available:
# Path: aiosmtplib/sync.py
# def shutdown_loop(loop: asyncio.AbstractEventLoop, timeout: float = 1.0) -> None:
# """
# Do the various dances to gently shutdown an event loop.
# """
# tasks = all_tasks(loop=loop)
# if tasks:
# for task in tasks:
# task.cancel()
# try:
# loop.run_until_complete(asyncio.wait(tasks, timeout=timeout))
# except RuntimeError:
# pass
#
# if not loop.is_closed():
# if PY36_OR_LATER:
# loop.run_until_complete(loop.shutdown_asyncgens())
#
# loop.call_soon(loop.stop)
# loop.run_forever()
# loop.close()
. Output only the next line. | shutdown_loop(self.loop) |
Next line prediction: <|code_start|> loop.run_until_complete(_await_with_future(coro, result))
finally:
shutdown_loop(loop)
return result.result()
async def _await_with_future(coro: Awaitable, future: asyncio.Future) -> None:
try:
result = await coro
except Exception as exc:
future.set_exception(exc)
else:
future.set_result(result)
def shutdown_loop(loop: asyncio.AbstractEventLoop, timeout: float = 1.0) -> None:
"""
Do the various dances to gently shutdown an event loop.
"""
tasks = all_tasks(loop=loop)
if tasks:
for task in tasks:
task.cancel()
try:
loop.run_until_complete(asyncio.wait(tasks, timeout=timeout))
except RuntimeError:
pass
if not loop.is_closed():
<|code_end|>
. Use current file imports:
(import asyncio
from typing import Any, Awaitable, Optional
from .compat import PY36_OR_LATER, all_tasks)
and context including class names, function names, or small code snippets from other files:
# Path: aiosmtplib/compat.py
# PY36_OR_LATER = sys.version_info[:2] >= (3, 6)
#
# def all_tasks(loop: asyncio.AbstractEventLoop = None):
# if PY37_OR_LATER:
# return asyncio.all_tasks(loop=loop)
#
# return asyncio.Task.all_tasks(loop=loop) # type: ignore
. Output only the next line. | if PY36_OR_LATER: |
Continue the code snippet: <|code_start|>) -> Any:
if loop is None:
loop = asyncio.get_event_loop()
if loop.is_running():
raise RuntimeError("Event loop is already running.")
result = loop.create_future()
try:
loop.run_until_complete(_await_with_future(coro, result))
finally:
shutdown_loop(loop)
return result.result()
async def _await_with_future(coro: Awaitable, future: asyncio.Future) -> None:
try:
result = await coro
except Exception as exc:
future.set_exception(exc)
else:
future.set_result(result)
def shutdown_loop(loop: asyncio.AbstractEventLoop, timeout: float = 1.0) -> None:
"""
Do the various dances to gently shutdown an event loop.
"""
<|code_end|>
. Use current file imports:
import asyncio
from typing import Any, Awaitable, Optional
from .compat import PY36_OR_LATER, all_tasks
and context (classes, functions, or code) from other files:
# Path: aiosmtplib/compat.py
# PY36_OR_LATER = sys.version_info[:2] >= (3, 6)
#
# def all_tasks(loop: asyncio.AbstractEventLoop = None):
# if PY37_OR_LATER:
# return asyncio.all_tasks(loop=loop)
#
# return asyncio.Task.all_tasks(loop=loop) # type: ignore
. Output only the next line. | tasks = all_tasks(loop=loop) |
Based on the snippet: <|code_start|> ["alice@example.com", "Bob@example.com"],
),
(
Address(display_name="ålice Smith", username="ålice", domain="example.com"),
Address(display_name="Bøb", username="Bøb", domain="example.com"),
Header("ålice Smith <ålice@example.com>"),
Header("Bøb <Bøb@example.com>"),
["ålice@example.com", "Bøb@example.com"],
),
(
Address(display_name="ålice Smith", username="alice", domain="example.com"),
Address(display_name="Bøb", username="Bob", domain="example.com"),
Header("ålice Smith <alice@example.com>"),
Header("Bøb <Bob@example.com>"),
["alice@example.com", "Bob@example.com"],
),
),
ids=("str", "ascii", "utf8_address", "utf8_display_name"),
)
def test_extract_recipients(
mime_to_header,
mime_cc_header,
compat32_to_header,
compat32_cc_header,
expected_recipients,
):
mime_message = EmailMessage()
mime_message["To"] = mime_to_header
mime_message["Cc"] = mime_cc_header
<|code_end|>
, predict the immediate next line with the help of imports:
from email.header import Header
from email.headerregistry import Address
from email.message import EmailMessage, Message
from hypothesis import example, given
from hypothesis.strategies import emails
from aiosmtplib.email import (
extract_recipients,
extract_sender,
flatten_message,
parse_address,
quote_address,
)
import pytest
and context (classes, functions, sometimes code) from other files:
# Path: aiosmtplib/email.py
# def extract_recipients(
# message: Union[email.message.EmailMessage, email.message.Message]
# ) -> List[str]:
# """
# Extract the recipients from the message object given.
# """
# recipients = [] # type: List[str]
#
# resent_dates = message.get_all("Resent-Date")
#
# if resent_dates is not None and len(resent_dates) > 1:
# raise ValueError("Message has more than one 'Resent-' header block")
# elif resent_dates:
# recipient_headers = ("Resent-To", "Resent-Cc", "Resent-Bcc")
# else:
# recipient_headers = ("To", "Cc", "Bcc")
#
# for header in recipient_headers:
# for recipient in message.get_all(header, failobj=[]):
# recipients.extend(extract_addresses(recipient))
#
# return recipients
#
# def extract_sender(
# message: Union[email.message.EmailMessage, email.message.Message]
# ) -> Optional[str]:
# """
# Extract the sender from the message object given.
# """
# resent_dates = message.get_all("Resent-Date")
#
# if resent_dates is not None and len(resent_dates) > 1:
# raise ValueError("Message has more than one 'Resent-' header block")
# elif resent_dates:
# sender_header_name = "Resent-Sender"
# from_header_name = "Resent-From"
# else:
# sender_header_name = "Sender"
# from_header_name = "From"
#
# # Prefer the sender field per RFC 2822:3.6.2.
# if sender_header_name in message:
# sender_header = message[sender_header_name]
# else:
# sender_header = message[from_header_name]
#
# if sender_header is None:
# return None
#
# return extract_addresses(sender_header)[0]
#
# def flatten_message(
# message: Union[email.message.EmailMessage, email.message.Message],
# utf8: bool = False,
# cte_type: str = "8bit",
# ) -> bytes:
# # Make a local copy so we can delete the bcc headers.
# message_copy = copy.copy(message)
# del message_copy["Bcc"]
# del message_copy["Resent-Bcc"]
#
# if isinstance(message.policy, email.policy.Compat32): # type: ignore
# # Compat32 cannot use UTF8
# policy = message.policy.clone( # type: ignore
# linesep=LINE_SEP, cte_type=cte_type
# )
# else:
# policy = message.policy.clone( # type: ignore
# linesep=LINE_SEP, utf8=utf8, cte_type=cte_type
# )
#
# with io.BytesIO() as messageio:
# generator = email.generator.BytesGenerator(messageio, policy=policy)
# generator.flatten(message_copy)
# flat_message = messageio.getvalue()
#
# return flat_message
#
# def parse_address(address: str) -> str:
# """
# Parse an email address, falling back to the raw string given.
# """
# display_name, parsed_address = email.utils.parseaddr(address)
#
# return parsed_address or address.strip()
#
# def quote_address(address: str) -> str:
# """
# Quote a subset of the email addresses defined by RFC 821.
# """
# parsed_address = parse_address(address)
# return "<{}>".format(parsed_address)
. Output only the next line. | mime_recipients = extract_recipients(mime_message) |
Based on the snippet: <|code_start|>@pytest.mark.parametrize(
"mime_header,compat32_header,expected_sender",
(
(
"Alice Smith <alice@example.com>",
"Alice Smith <alice@example.com>",
"alice@example.com",
),
(
Address(display_name="Alice Smith", username="alice", domain="example.com"),
Header("Alice Smith <alice@example.com>"),
"alice@example.com",
),
(
Address(display_name="ålice Smith", username="ålice", domain="example.com"),
Header("ålice Smith <ålice@example.com>", "utf-8"),
"ålice@example.com",
),
(
Address(display_name="ålice Smith", username="alice", domain="example.com"),
Header("ålice Smith <alice@example.com>", "utf-8"),
"alice@example.com",
),
),
ids=("str", "ascii", "utf8_address", "utf8_display_name"),
)
def test_extract_sender(mime_header, compat32_header, expected_sender):
mime_message = EmailMessage()
mime_message["From"] = mime_header
<|code_end|>
, predict the immediate next line with the help of imports:
from email.header import Header
from email.headerregistry import Address
from email.message import EmailMessage, Message
from hypothesis import example, given
from hypothesis.strategies import emails
from aiosmtplib.email import (
extract_recipients,
extract_sender,
flatten_message,
parse_address,
quote_address,
)
import pytest
and context (classes, functions, sometimes code) from other files:
# Path: aiosmtplib/email.py
# def extract_recipients(
# message: Union[email.message.EmailMessage, email.message.Message]
# ) -> List[str]:
# """
# Extract the recipients from the message object given.
# """
# recipients = [] # type: List[str]
#
# resent_dates = message.get_all("Resent-Date")
#
# if resent_dates is not None and len(resent_dates) > 1:
# raise ValueError("Message has more than one 'Resent-' header block")
# elif resent_dates:
# recipient_headers = ("Resent-To", "Resent-Cc", "Resent-Bcc")
# else:
# recipient_headers = ("To", "Cc", "Bcc")
#
# for header in recipient_headers:
# for recipient in message.get_all(header, failobj=[]):
# recipients.extend(extract_addresses(recipient))
#
# return recipients
#
# def extract_sender(
# message: Union[email.message.EmailMessage, email.message.Message]
# ) -> Optional[str]:
# """
# Extract the sender from the message object given.
# """
# resent_dates = message.get_all("Resent-Date")
#
# if resent_dates is not None and len(resent_dates) > 1:
# raise ValueError("Message has more than one 'Resent-' header block")
# elif resent_dates:
# sender_header_name = "Resent-Sender"
# from_header_name = "Resent-From"
# else:
# sender_header_name = "Sender"
# from_header_name = "From"
#
# # Prefer the sender field per RFC 2822:3.6.2.
# if sender_header_name in message:
# sender_header = message[sender_header_name]
# else:
# sender_header = message[from_header_name]
#
# if sender_header is None:
# return None
#
# return extract_addresses(sender_header)[0]
#
# def flatten_message(
# message: Union[email.message.EmailMessage, email.message.Message],
# utf8: bool = False,
# cte_type: str = "8bit",
# ) -> bytes:
# # Make a local copy so we can delete the bcc headers.
# message_copy = copy.copy(message)
# del message_copy["Bcc"]
# del message_copy["Resent-Bcc"]
#
# if isinstance(message.policy, email.policy.Compat32): # type: ignore
# # Compat32 cannot use UTF8
# policy = message.policy.clone( # type: ignore
# linesep=LINE_SEP, cte_type=cte_type
# )
# else:
# policy = message.policy.clone( # type: ignore
# linesep=LINE_SEP, utf8=utf8, cte_type=cte_type
# )
#
# with io.BytesIO() as messageio:
# generator = email.generator.BytesGenerator(messageio, policy=policy)
# generator.flatten(message_copy)
# flat_message = messageio.getvalue()
#
# return flat_message
#
# def parse_address(address: str) -> str:
# """
# Parse an email address, falling back to the raw string given.
# """
# display_name, parsed_address = email.utils.parseaddr(address)
#
# return parsed_address or address.strip()
#
# def quote_address(address: str) -> str:
# """
# Quote a subset of the email addresses defined by RFC 821.
# """
# parsed_address = parse_address(address)
# return "<{}>".format(parsed_address)
. Output only the next line. | mime_sender = extract_sender(mime_message) |
Next line prediction: <|code_start|> "address, expected_address",
(
('"A.Smith" <asmith+foo@example.com>', "<asmith+foo@example.com>"),
("Pepé Le Pew <pépe@example.com>", "<pépe@example.com>"),
("<a@new.topleveldomain>", "<a@new.topleveldomain>"),
("email@[123.123.123.123]", "<email@[123.123.123.123]>"),
("_______@example.com", "<_______@example.com>"),
("B. Smith <b@example.com", "<b@example.com>"),
),
ids=("quotes", "nonascii", "newtld", "ipaddr", "underscores", "missing_end_quote"),
)
def test_quote_address_with_display_names(address, expected_address):
quoted_address = quote_address(address)
assert quoted_address == expected_address
@given(emails())
@example("email@[123.123.123.123]")
@example("_______@example.com")
def test_quote_address(email):
assert quote_address(email) == "<{}>".format(email)
def test_flatten_message():
message = EmailMessage()
message["To"] = "bob@example.com"
message["Subject"] = "Hello, World."
message["From"] = "alice@example.com"
message.set_content("This is a test")
<|code_end|>
. Use current file imports:
(from email.header import Header
from email.headerregistry import Address
from email.message import EmailMessage, Message
from hypothesis import example, given
from hypothesis.strategies import emails
from aiosmtplib.email import (
extract_recipients,
extract_sender,
flatten_message,
parse_address,
quote_address,
)
import pytest)
and context including class names, function names, or small code snippets from other files:
# Path: aiosmtplib/email.py
# def extract_recipients(
# message: Union[email.message.EmailMessage, email.message.Message]
# ) -> List[str]:
# """
# Extract the recipients from the message object given.
# """
# recipients = [] # type: List[str]
#
# resent_dates = message.get_all("Resent-Date")
#
# if resent_dates is not None and len(resent_dates) > 1:
# raise ValueError("Message has more than one 'Resent-' header block")
# elif resent_dates:
# recipient_headers = ("Resent-To", "Resent-Cc", "Resent-Bcc")
# else:
# recipient_headers = ("To", "Cc", "Bcc")
#
# for header in recipient_headers:
# for recipient in message.get_all(header, failobj=[]):
# recipients.extend(extract_addresses(recipient))
#
# return recipients
#
# def extract_sender(
# message: Union[email.message.EmailMessage, email.message.Message]
# ) -> Optional[str]:
# """
# Extract the sender from the message object given.
# """
# resent_dates = message.get_all("Resent-Date")
#
# if resent_dates is not None and len(resent_dates) > 1:
# raise ValueError("Message has more than one 'Resent-' header block")
# elif resent_dates:
# sender_header_name = "Resent-Sender"
# from_header_name = "Resent-From"
# else:
# sender_header_name = "Sender"
# from_header_name = "From"
#
# # Prefer the sender field per RFC 2822:3.6.2.
# if sender_header_name in message:
# sender_header = message[sender_header_name]
# else:
# sender_header = message[from_header_name]
#
# if sender_header is None:
# return None
#
# return extract_addresses(sender_header)[0]
#
# def flatten_message(
# message: Union[email.message.EmailMessage, email.message.Message],
# utf8: bool = False,
# cte_type: str = "8bit",
# ) -> bytes:
# # Make a local copy so we can delete the bcc headers.
# message_copy = copy.copy(message)
# del message_copy["Bcc"]
# del message_copy["Resent-Bcc"]
#
# if isinstance(message.policy, email.policy.Compat32): # type: ignore
# # Compat32 cannot use UTF8
# policy = message.policy.clone( # type: ignore
# linesep=LINE_SEP, cte_type=cte_type
# )
# else:
# policy = message.policy.clone( # type: ignore
# linesep=LINE_SEP, utf8=utf8, cte_type=cte_type
# )
#
# with io.BytesIO() as messageio:
# generator = email.generator.BytesGenerator(messageio, policy=policy)
# generator.flatten(message_copy)
# flat_message = messageio.getvalue()
#
# return flat_message
#
# def parse_address(address: str) -> str:
# """
# Parse an email address, falling back to the raw string given.
# """
# display_name, parsed_address = email.utils.parseaddr(address)
#
# return parsed_address or address.strip()
#
# def quote_address(address: str) -> str:
# """
# Quote a subset of the email addresses defined by RFC 821.
# """
# parsed_address = parse_address(address)
# return "<{}>".format(parsed_address)
. Output only the next line. | flat_message = flatten_message(message) |
Continue the code snippet: <|code_start|>"""
Test message and address parsing/formatting functions.
"""
@pytest.mark.parametrize(
"address, expected_address",
(
('"A.Smith" <asmith+foo@example.com>', "asmith+foo@example.com"),
("Pepé Le Pew <pépe@example.com>", "pépe@example.com"),
("<a@new.topleveldomain>", "a@new.topleveldomain"),
("B. Smith <b@example.com", "b@example.com"),
),
ids=("quotes", "nonascii", "newtld", "missing_end_<"),
)
def test_parse_address_with_display_names(address, expected_address):
<|code_end|>
. Use current file imports:
from email.header import Header
from email.headerregistry import Address
from email.message import EmailMessage, Message
from hypothesis import example, given
from hypothesis.strategies import emails
from aiosmtplib.email import (
extract_recipients,
extract_sender,
flatten_message,
parse_address,
quote_address,
)
import pytest
and context (classes, functions, or code) from other files:
# Path: aiosmtplib/email.py
# def extract_recipients(
# message: Union[email.message.EmailMessage, email.message.Message]
# ) -> List[str]:
# """
# Extract the recipients from the message object given.
# """
# recipients = [] # type: List[str]
#
# resent_dates = message.get_all("Resent-Date")
#
# if resent_dates is not None and len(resent_dates) > 1:
# raise ValueError("Message has more than one 'Resent-' header block")
# elif resent_dates:
# recipient_headers = ("Resent-To", "Resent-Cc", "Resent-Bcc")
# else:
# recipient_headers = ("To", "Cc", "Bcc")
#
# for header in recipient_headers:
# for recipient in message.get_all(header, failobj=[]):
# recipients.extend(extract_addresses(recipient))
#
# return recipients
#
# def extract_sender(
# message: Union[email.message.EmailMessage, email.message.Message]
# ) -> Optional[str]:
# """
# Extract the sender from the message object given.
# """
# resent_dates = message.get_all("Resent-Date")
#
# if resent_dates is not None and len(resent_dates) > 1:
# raise ValueError("Message has more than one 'Resent-' header block")
# elif resent_dates:
# sender_header_name = "Resent-Sender"
# from_header_name = "Resent-From"
# else:
# sender_header_name = "Sender"
# from_header_name = "From"
#
# # Prefer the sender field per RFC 2822:3.6.2.
# if sender_header_name in message:
# sender_header = message[sender_header_name]
# else:
# sender_header = message[from_header_name]
#
# if sender_header is None:
# return None
#
# return extract_addresses(sender_header)[0]
#
# def flatten_message(
# message: Union[email.message.EmailMessage, email.message.Message],
# utf8: bool = False,
# cte_type: str = "8bit",
# ) -> bytes:
# # Make a local copy so we can delete the bcc headers.
# message_copy = copy.copy(message)
# del message_copy["Bcc"]
# del message_copy["Resent-Bcc"]
#
# if isinstance(message.policy, email.policy.Compat32): # type: ignore
# # Compat32 cannot use UTF8
# policy = message.policy.clone( # type: ignore
# linesep=LINE_SEP, cte_type=cte_type
# )
# else:
# policy = message.policy.clone( # type: ignore
# linesep=LINE_SEP, utf8=utf8, cte_type=cte_type
# )
#
# with io.BytesIO() as messageio:
# generator = email.generator.BytesGenerator(messageio, policy=policy)
# generator.flatten(message_copy)
# flat_message = messageio.getvalue()
#
# return flat_message
#
# def parse_address(address: str) -> str:
# """
# Parse an email address, falling back to the raw string given.
# """
# display_name, parsed_address = email.utils.parseaddr(address)
#
# return parsed_address or address.strip()
#
# def quote_address(address: str) -> str:
# """
# Quote a subset of the email addresses defined by RFC 821.
# """
# parsed_address = parse_address(address)
# return "<{}>".format(parsed_address)
. Output only the next line. | parsed_address = parse_address(address) |
Predict the next line after this snippet: <|code_start|> ("<a@new.topleveldomain>", "a@new.topleveldomain"),
("B. Smith <b@example.com", "b@example.com"),
),
ids=("quotes", "nonascii", "newtld", "missing_end_<"),
)
def test_parse_address_with_display_names(address, expected_address):
parsed_address = parse_address(address)
assert parsed_address == expected_address
@given(emails())
@example("email@[123.123.123.123]")
@example("_______@example.com")
def test_parse_address(email):
assert parse_address(email) == email
@pytest.mark.parametrize(
"address, expected_address",
(
('"A.Smith" <asmith+foo@example.com>', "<asmith+foo@example.com>"),
("Pepé Le Pew <pépe@example.com>", "<pépe@example.com>"),
("<a@new.topleveldomain>", "<a@new.topleveldomain>"),
("email@[123.123.123.123]", "<email@[123.123.123.123]>"),
("_______@example.com", "<_______@example.com>"),
("B. Smith <b@example.com", "<b@example.com>"),
),
ids=("quotes", "nonascii", "newtld", "ipaddr", "underscores", "missing_end_quote"),
)
def test_quote_address_with_display_names(address, expected_address):
<|code_end|>
using the current file's imports:
from email.header import Header
from email.headerregistry import Address
from email.message import EmailMessage, Message
from hypothesis import example, given
from hypothesis.strategies import emails
from aiosmtplib.email import (
extract_recipients,
extract_sender,
flatten_message,
parse_address,
quote_address,
)
import pytest
and any relevant context from other files:
# Path: aiosmtplib/email.py
# def extract_recipients(
# message: Union[email.message.EmailMessage, email.message.Message]
# ) -> List[str]:
# """
# Extract the recipients from the message object given.
# """
# recipients = [] # type: List[str]
#
# resent_dates = message.get_all("Resent-Date")
#
# if resent_dates is not None and len(resent_dates) > 1:
# raise ValueError("Message has more than one 'Resent-' header block")
# elif resent_dates:
# recipient_headers = ("Resent-To", "Resent-Cc", "Resent-Bcc")
# else:
# recipient_headers = ("To", "Cc", "Bcc")
#
# for header in recipient_headers:
# for recipient in message.get_all(header, failobj=[]):
# recipients.extend(extract_addresses(recipient))
#
# return recipients
#
# def extract_sender(
# message: Union[email.message.EmailMessage, email.message.Message]
# ) -> Optional[str]:
# """
# Extract the sender from the message object given.
# """
# resent_dates = message.get_all("Resent-Date")
#
# if resent_dates is not None and len(resent_dates) > 1:
# raise ValueError("Message has more than one 'Resent-' header block")
# elif resent_dates:
# sender_header_name = "Resent-Sender"
# from_header_name = "Resent-From"
# else:
# sender_header_name = "Sender"
# from_header_name = "From"
#
# # Prefer the sender field per RFC 2822:3.6.2.
# if sender_header_name in message:
# sender_header = message[sender_header_name]
# else:
# sender_header = message[from_header_name]
#
# if sender_header is None:
# return None
#
# return extract_addresses(sender_header)[0]
#
# def flatten_message(
# message: Union[email.message.EmailMessage, email.message.Message],
# utf8: bool = False,
# cte_type: str = "8bit",
# ) -> bytes:
# # Make a local copy so we can delete the bcc headers.
# message_copy = copy.copy(message)
# del message_copy["Bcc"]
# del message_copy["Resent-Bcc"]
#
# if isinstance(message.policy, email.policy.Compat32): # type: ignore
# # Compat32 cannot use UTF8
# policy = message.policy.clone( # type: ignore
# linesep=LINE_SEP, cte_type=cte_type
# )
# else:
# policy = message.policy.clone( # type: ignore
# linesep=LINE_SEP, utf8=utf8, cte_type=cte_type
# )
#
# with io.BytesIO() as messageio:
# generator = email.generator.BytesGenerator(messageio, policy=policy)
# generator.flatten(message_copy)
# flat_message = messageio.getvalue()
#
# return flat_message
#
# def parse_address(address: str) -> str:
# """
# Parse an email address, falling back to the raw string given.
# """
# display_name, parsed_address = email.utils.parseaddr(address)
#
# return parsed_address or address.strip()
#
# def quote_address(address: str) -> str:
# """
# Quote a subset of the email addresses defined by RFC 821.
# """
# parsed_address = parse_address(address)
# return "<{}>".format(parsed_address)
. Output only the next line. | quoted_address = quote_address(address) |
Based on the snippet: <|code_start|> await smtp_client.mail("j@example.com")
with pytest.raises(UnicodeEncodeError):
await smtp_client.rcpt("tést@exåmple.com", options=["SMTPUTF8"])
async def test_data_ok(smtp_client, smtpd_server):
async with smtp_client:
await smtp_client.mail("j@example.com")
await smtp_client.rcpt("test@example.com")
response = await smtp_client.data("HELLO WORLD")
assert response.code == SMTPStatus.completed
assert response.message == "OK"
async def test_data_error_on_start_input(
smtp_client,
smtpd_server,
smtpd_class,
smtpd_response_handler_factory,
monkeypatch,
error_code,
):
response_handler = smtpd_response_handler_factory("{} error".format(error_code))
monkeypatch.setattr(smtpd_class, "smtp_DATA", response_handler)
async with smtp_client:
await smtp_client.mail("admin@example.com")
await smtp_client.rcpt("test@example.com")
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
from aiosmtplib import (
SMTPDataError,
SMTPHeloError,
SMTPNotSupported,
SMTPResponseException,
SMTPStatus,
)
and context (classes, functions, sometimes code) from other files:
# Path: aiosmtplib/errors.py
# class SMTPDataError(SMTPResponseException):
# """
# Server refused DATA content.
# """
#
# class SMTPHeloError(SMTPResponseException):
# """
# Server refused HELO or EHLO.
# """
#
# class SMTPNotSupported(SMTPException):
# """
# A command or argument sent to the SMTP server is not supported.
# """
#
# class SMTPResponseException(SMTPException):
# """
# Base class for all server responses with error codes.
# """
#
# def __init__(self, code: int, message: str) -> None:
# self.code = code
# self.message = message
# self.args = (code, message)
#
# Path: aiosmtplib/status.py
# class SMTPStatus(enum.IntEnum):
# """
# Defines SMTP statuses for code readability.
#
# See also: http://www.greenend.org.uk/rjk/tech/smtpreplies.html
# """
#
# invalid_response = -1
# system_status_ok = 211
# help_message = 214
# ready = 220
# closing = 221
# auth_successful = 235
# completed = 250
# will_forward = 251
# cannot_vrfy = 252
# auth_continue = 334
# start_input = 354
# domain_unavailable = 421
# mailbox_unavailable = 450
# error_processing = 451
# insufficient_storage = 452
# tls_not_available = 454
# unrecognized_command = 500
# unrecognized_parameters = 501
# command_not_implemented = 502
# bad_command_sequence = 503
# parameter_not_implemented = 504
# domain_does_not_accept_mail = 521
# access_denied = 530 # Sendmail specific
# auth_failed = 535
# mailbox_does_not_exist = 550
# user_not_local = 551
# storage_exceeded = 552
# mailbox_name_invalid = 553
# transaction_failed = 554
# syntax_error = 555
. Output only the next line. | with pytest.raises(SMTPDataError) as exception_info: |
Given the following code snippet before the placeholder: <|code_start|>
return bad_data_response
async def test_helo_ok(smtp_client, smtpd_server):
async with smtp_client:
response = await smtp_client.helo()
assert response.code == SMTPStatus.completed
async def test_helo_with_hostname(smtp_client, smtpd_server):
async with smtp_client:
response = await smtp_client.helo(hostname="example.com")
assert response.code == SMTPStatus.completed
async def test_helo_error(
smtp_client,
smtpd_server,
smtpd_class,
smtpd_response_handler_factory,
monkeypatch,
error_code,
):
response_handler = smtpd_response_handler_factory("{} error".format(error_code))
monkeypatch.setattr(smtpd_class, "smtp_HELO", response_handler)
async with smtp_client:
<|code_end|>
, predict the next line using imports from the current file:
import pytest
from aiosmtplib import (
SMTPDataError,
SMTPHeloError,
SMTPNotSupported,
SMTPResponseException,
SMTPStatus,
)
and context including class names, function names, and sometimes code from other files:
# Path: aiosmtplib/errors.py
# class SMTPDataError(SMTPResponseException):
# """
# Server refused DATA content.
# """
#
# class SMTPHeloError(SMTPResponseException):
# """
# Server refused HELO or EHLO.
# """
#
# class SMTPNotSupported(SMTPException):
# """
# A command or argument sent to the SMTP server is not supported.
# """
#
# class SMTPResponseException(SMTPException):
# """
# Base class for all server responses with error codes.
# """
#
# def __init__(self, code: int, message: str) -> None:
# self.code = code
# self.message = message
# self.args = (code, message)
#
# Path: aiosmtplib/status.py
# class SMTPStatus(enum.IntEnum):
# """
# Defines SMTP statuses for code readability.
#
# See also: http://www.greenend.org.uk/rjk/tech/smtpreplies.html
# """
#
# invalid_response = -1
# system_status_ok = 211
# help_message = 214
# ready = 220
# closing = 221
# auth_successful = 235
# completed = 250
# will_forward = 251
# cannot_vrfy = 252
# auth_continue = 334
# start_input = 354
# domain_unavailable = 421
# mailbox_unavailable = 450
# error_processing = 451
# insufficient_storage = 452
# tls_not_available = 454
# unrecognized_command = 500
# unrecognized_parameters = 501
# command_not_implemented = 502
# bad_command_sequence = 503
# parameter_not_implemented = 504
# domain_does_not_accept_mail = 521
# access_denied = 530 # Sendmail specific
# auth_failed = 535
# mailbox_does_not_exist = 550
# user_not_local = 551
# storage_exceeded = 552
# mailbox_name_invalid = 553
# transaction_failed = 554
# syntax_error = 555
. Output only the next line. | with pytest.raises(SMTPHeloError) as exception_info: |
Next line prediction: <|code_start|> await smtp_client.noop()
assert exception_info.value.code == error_code
async def test_vrfy_ok(smtp_client, smtpd_server):
nice_address = "test@example.com"
async with smtp_client:
response = await smtp_client.vrfy(nice_address)
assert response.code == SMTPStatus.cannot_vrfy
async def test_vrfy_with_blank_address(smtp_client, smtpd_server):
bad_address = ""
async with smtp_client:
with pytest.raises(SMTPResponseException):
await smtp_client.vrfy(bad_address)
async def test_vrfy_smtputf8_supported(smtp_client_smtputf8, smtpd_server_smtputf8):
async with smtp_client_smtputf8:
response = await smtp_client_smtputf8.vrfy(
"tést@exåmple.com", options=["SMTPUTF8"]
)
assert response.code == SMTPStatus.cannot_vrfy
async def test_vrfy_smtputf8_not_supported(smtp_client, smtpd_server):
async with smtp_client:
<|code_end|>
. Use current file imports:
(import pytest
from aiosmtplib import (
SMTPDataError,
SMTPHeloError,
SMTPNotSupported,
SMTPResponseException,
SMTPStatus,
))
and context including class names, function names, or small code snippets from other files:
# Path: aiosmtplib/errors.py
# class SMTPDataError(SMTPResponseException):
# """
# Server refused DATA content.
# """
#
# class SMTPHeloError(SMTPResponseException):
# """
# Server refused HELO or EHLO.
# """
#
# class SMTPNotSupported(SMTPException):
# """
# A command or argument sent to the SMTP server is not supported.
# """
#
# class SMTPResponseException(SMTPException):
# """
# Base class for all server responses with error codes.
# """
#
# def __init__(self, code: int, message: str) -> None:
# self.code = code
# self.message = message
# self.args = (code, message)
#
# Path: aiosmtplib/status.py
# class SMTPStatus(enum.IntEnum):
# """
# Defines SMTP statuses for code readability.
#
# See also: http://www.greenend.org.uk/rjk/tech/smtpreplies.html
# """
#
# invalid_response = -1
# system_status_ok = 211
# help_message = 214
# ready = 220
# closing = 221
# auth_successful = 235
# completed = 250
# will_forward = 251
# cannot_vrfy = 252
# auth_continue = 334
# start_input = 354
# domain_unavailable = 421
# mailbox_unavailable = 450
# error_processing = 451
# insufficient_storage = 452
# tls_not_available = 454
# unrecognized_command = 500
# unrecognized_parameters = 501
# command_not_implemented = 502
# bad_command_sequence = 503
# parameter_not_implemented = 504
# domain_does_not_accept_mail = 521
# access_denied = 530 # Sendmail specific
# auth_failed = 535
# mailbox_does_not_exist = 550
# user_not_local = 551
# storage_exceeded = 552
# mailbox_name_invalid = 553
# transaction_failed = 554
# syntax_error = 555
. Output only the next line. | with pytest.raises(SMTPNotSupported): |
Continue the code snippet: <|code_start|> response_handler = smtpd_response_handler_factory(
"{} retry in 5 minutes".format(SMTPStatus.domain_unavailable), close_after=True
)
monkeypatch.setattr(smtpd_class, "smtp_EHLO", response_handler)
async with smtp_client:
with pytest.raises(SMTPHeloError):
await smtp_client._ehlo_or_helo_if_needed()
async def test_rset_ok(smtp_client, smtpd_server):
async with smtp_client:
response = await smtp_client.rset()
assert response.code == SMTPStatus.completed
assert response.message == "OK"
async def test_rset_error(
smtp_client,
smtpd_server,
smtpd_class,
smtpd_response_handler_factory,
monkeypatch,
error_code,
):
response_handler = smtpd_response_handler_factory("{} error".format(error_code))
monkeypatch.setattr(smtpd_class, "smtp_RSET", response_handler)
async with smtp_client:
<|code_end|>
. Use current file imports:
import pytest
from aiosmtplib import (
SMTPDataError,
SMTPHeloError,
SMTPNotSupported,
SMTPResponseException,
SMTPStatus,
)
and context (classes, functions, or code) from other files:
# Path: aiosmtplib/errors.py
# class SMTPDataError(SMTPResponseException):
# """
# Server refused DATA content.
# """
#
# class SMTPHeloError(SMTPResponseException):
# """
# Server refused HELO or EHLO.
# """
#
# class SMTPNotSupported(SMTPException):
# """
# A command or argument sent to the SMTP server is not supported.
# """
#
# class SMTPResponseException(SMTPException):
# """
# Base class for all server responses with error codes.
# """
#
# def __init__(self, code: int, message: str) -> None:
# self.code = code
# self.message = message
# self.args = (code, message)
#
# Path: aiosmtplib/status.py
# class SMTPStatus(enum.IntEnum):
# """
# Defines SMTP statuses for code readability.
#
# See also: http://www.greenend.org.uk/rjk/tech/smtpreplies.html
# """
#
# invalid_response = -1
# system_status_ok = 211
# help_message = 214
# ready = 220
# closing = 221
# auth_successful = 235
# completed = 250
# will_forward = 251
# cannot_vrfy = 252
# auth_continue = 334
# start_input = 354
# domain_unavailable = 421
# mailbox_unavailable = 450
# error_processing = 451
# insufficient_storage = 452
# tls_not_available = 454
# unrecognized_command = 500
# unrecognized_parameters = 501
# command_not_implemented = 502
# bad_command_sequence = 503
# parameter_not_implemented = 504
# domain_does_not_accept_mail = 521
# access_denied = 530 # Sendmail specific
# auth_failed = 535
# mailbox_does_not_exist = 550
# user_not_local = 551
# storage_exceeded = 552
# mailbox_name_invalid = 553
# transaction_failed = 554
# syntax_error = 555
. Output only the next line. | with pytest.raises(SMTPResponseException) as exception_info: |
Continue the code snippet: <|code_start|>"""
Lower level SMTP command tests.
"""
pytestmark = pytest.mark.asyncio()
@pytest.fixture(scope="session")
def bad_data_response_handler(request):
async def bad_data_response(smtpd, *args, **kwargs):
smtpd._writer.write(b"250 \xFF\xFF\xFF\xFF\r\n")
await smtpd._writer.drain()
return bad_data_response
async def test_helo_ok(smtp_client, smtpd_server):
async with smtp_client:
response = await smtp_client.helo()
<|code_end|>
. Use current file imports:
import pytest
from aiosmtplib import (
SMTPDataError,
SMTPHeloError,
SMTPNotSupported,
SMTPResponseException,
SMTPStatus,
)
and context (classes, functions, or code) from other files:
# Path: aiosmtplib/errors.py
# class SMTPDataError(SMTPResponseException):
# """
# Server refused DATA content.
# """
#
# class SMTPHeloError(SMTPResponseException):
# """
# Server refused HELO or EHLO.
# """
#
# class SMTPNotSupported(SMTPException):
# """
# A command or argument sent to the SMTP server is not supported.
# """
#
# class SMTPResponseException(SMTPException):
# """
# Base class for all server responses with error codes.
# """
#
# def __init__(self, code: int, message: str) -> None:
# self.code = code
# self.message = message
# self.args = (code, message)
#
# Path: aiosmtplib/status.py
# class SMTPStatus(enum.IntEnum):
# """
# Defines SMTP statuses for code readability.
#
# See also: http://www.greenend.org.uk/rjk/tech/smtpreplies.html
# """
#
# invalid_response = -1
# system_status_ok = 211
# help_message = 214
# ready = 220
# closing = 221
# auth_successful = 235
# completed = 250
# will_forward = 251
# cannot_vrfy = 252
# auth_continue = 334
# start_input = 354
# domain_unavailable = 421
# mailbox_unavailable = 450
# error_processing = 451
# insufficient_storage = 452
# tls_not_available = 454
# unrecognized_command = 500
# unrecognized_parameters = 501
# command_not_implemented = 502
# bad_command_sequence = 503
# parameter_not_implemented = 504
# domain_does_not_accept_mail = 521
# access_denied = 530 # Sendmail specific
# auth_failed = 535
# mailbox_does_not_exist = 550
# user_not_local = 551
# storage_exceeded = 552
# mailbox_name_invalid = 553
# transaction_failed = 554
# syntax_error = 555
. Output only the next line. | assert response.code == SMTPStatus.completed |
Predict the next line after this snippet: <|code_start|> sender_str, [recipient_str], message_str
)
assert not errors
assert isinstance(errors, dict)
assert response != ""
def test_send_message_sync(event_loop, smtp_client_threaded, message):
errors, response = smtp_client_threaded.send_message_sync(message)
assert not errors
assert isinstance(errors, dict)
assert response != ""
def test_send_message_sync_when_connected(event_loop, smtp_client_threaded, message):
event_loop.run_until_complete(smtp_client_threaded.connect())
errors, response = smtp_client_threaded.send_message_sync(message)
assert not errors
assert isinstance(errors, dict)
assert response != ""
def test_async_to_sync_without_loop(event_loop):
async def test_func():
return 7
<|code_end|>
using the current file's imports:
import pytest
from aiosmtplib.sync import async_to_sync
and any relevant context from other files:
# Path: aiosmtplib/sync.py
# def async_to_sync(
# coro: Awaitable, loop: Optional[asyncio.AbstractEventLoop] = None
# ) -> Any:
# if loop is None:
# loop = asyncio.get_event_loop()
#
# if loop.is_running():
# raise RuntimeError("Event loop is already running.")
#
# result = loop.create_future()
#
# try:
# loop.run_until_complete(_await_with_future(coro, result))
# finally:
# shutdown_loop(loop)
#
# return result.result()
. Output only the next line. | result = async_to_sync(test_func()) |
Next line prediction: <|code_start|> assert excinfo.value.message == message
@pytest.mark.parametrize(
"error_class", (SMTPServerDisconnected, SMTPConnectError, SMTPConnectTimeoutError)
)
@given(message=text())
def test_connection_exceptions(message, error_class):
with pytest.raises(error_class) as excinfo:
raise error_class(message)
assert issubclass(excinfo.type, SMTPException)
assert issubclass(excinfo.type, ConnectionError)
assert excinfo.value.message == message
@pytest.mark.parametrize(
"error_class", (SMTPTimeoutError, SMTPConnectTimeoutError, SMTPReadTimeoutError)
)
@given(message=text())
def test_timeout_exceptions(message, error_class):
with pytest.raises(error_class) as excinfo:
raise error_class(message)
assert issubclass(excinfo.type, SMTPException)
assert issubclass(excinfo.type, asyncio.TimeoutError)
assert excinfo.value.message == message
@pytest.mark.parametrize(
<|code_end|>
. Use current file imports:
(import asyncio
import pytest
from hypothesis import given
from hypothesis.strategies import integers, lists, text
from aiosmtplib import (
SMTPAuthenticationError,
SMTPConnectError,
SMTPConnectTimeoutError,
SMTPDataError,
SMTPException,
SMTPHeloError,
SMTPNotSupported,
SMTPReadTimeoutError,
SMTPRecipientRefused,
SMTPRecipientsRefused,
SMTPResponseException,
SMTPSenderRefused,
SMTPServerDisconnected,
SMTPTimeoutError,
))
and context including class names, function names, or small code snippets from other files:
# Path: aiosmtplib/errors.py
# class SMTPAuthenticationError(SMTPResponseException):
# """
# Server refused our AUTH request; may be caused by invalid credentials.
# """
#
# class SMTPConnectError(SMTPException, ConnectionError):
# """
# An error occurred while connecting to the SMTP server.
# """
#
# class SMTPConnectTimeoutError(SMTPTimeoutError, SMTPConnectError):
# """
# A timeout occurred while connecting to the SMTP server.
# """
#
# class SMTPDataError(SMTPResponseException):
# """
# Server refused DATA content.
# """
#
# class SMTPException(Exception):
# """
# Base class for all SMTP exceptions.
# """
#
# def __init__(self, message: str) -> None:
# self.message = message
# self.args = (message,)
#
# class SMTPHeloError(SMTPResponseException):
# """
# Server refused HELO or EHLO.
# """
#
# class SMTPNotSupported(SMTPException):
# """
# A command or argument sent to the SMTP server is not supported.
# """
#
# class SMTPReadTimeoutError(SMTPTimeoutError):
# """
# A timeout occurred while waiting for a response from the SMTP server.
# """
#
# class SMTPRecipientRefused(SMTPResponseException):
# """
# SMTP server refused a message recipient.
# """
#
# def __init__(self, code: int, message: str, recipient: str) -> None:
# self.code = code
# self.message = message
# self.recipient = recipient
# self.args = (code, message, recipient)
#
# class SMTPRecipientsRefused(SMTPException):
# """
# SMTP server refused multiple recipients.
# """
#
# def __init__(self, recipients: List[SMTPRecipientRefused]) -> None:
# self.recipients = recipients
# self.args = (recipients,)
#
# class SMTPResponseException(SMTPException):
# """
# Base class for all server responses with error codes.
# """
#
# def __init__(self, code: int, message: str) -> None:
# self.code = code
# self.message = message
# self.args = (code, message)
#
# class SMTPSenderRefused(SMTPResponseException):
# """
# SMTP server refused the message sender.
# """
#
# def __init__(self, code: int, message: str, sender: str) -> None:
# self.code = code
# self.message = message
# self.sender = sender
# self.args = (code, message, sender)
#
# class SMTPServerDisconnected(SMTPException, ConnectionError):
# """
# The connection was lost unexpectedly, or a command was run that requires
# a connection.
# """
#
# class SMTPTimeoutError(SMTPException, TimeoutError):
# """
# A timeout occurred while performing a network operation.
# """
. Output only the next line. | "error_class", (SMTPHeloError, SMTPDataError, SMTPAuthenticationError) |
Here is a snippet: <|code_start|>"""
Test error class imports, arguments, and inheritance.
"""
@given(text())
def test_raise_smtp_exception(message):
with pytest.raises(SMTPException) as excinfo:
raise SMTPException(message)
assert excinfo.value.message == message
@given(integers(), text())
def test_raise_smtp_response_exception(code, message):
with pytest.raises(SMTPResponseException) as excinfo:
raise SMTPResponseException(code, message)
assert issubclass(excinfo.type, SMTPException)
assert excinfo.value.code == code
assert excinfo.value.message == message
@pytest.mark.parametrize(
<|code_end|>
. Write the next line using the current file imports:
import asyncio
import pytest
from hypothesis import given
from hypothesis.strategies import integers, lists, text
from aiosmtplib import (
SMTPAuthenticationError,
SMTPConnectError,
SMTPConnectTimeoutError,
SMTPDataError,
SMTPException,
SMTPHeloError,
SMTPNotSupported,
SMTPReadTimeoutError,
SMTPRecipientRefused,
SMTPRecipientsRefused,
SMTPResponseException,
SMTPSenderRefused,
SMTPServerDisconnected,
SMTPTimeoutError,
)
and context from other files:
# Path: aiosmtplib/errors.py
# class SMTPAuthenticationError(SMTPResponseException):
# """
# Server refused our AUTH request; may be caused by invalid credentials.
# """
#
# class SMTPConnectError(SMTPException, ConnectionError):
# """
# An error occurred while connecting to the SMTP server.
# """
#
# class SMTPConnectTimeoutError(SMTPTimeoutError, SMTPConnectError):
# """
# A timeout occurred while connecting to the SMTP server.
# """
#
# class SMTPDataError(SMTPResponseException):
# """
# Server refused DATA content.
# """
#
# class SMTPException(Exception):
# """
# Base class for all SMTP exceptions.
# """
#
# def __init__(self, message: str) -> None:
# self.message = message
# self.args = (message,)
#
# class SMTPHeloError(SMTPResponseException):
# """
# Server refused HELO or EHLO.
# """
#
# class SMTPNotSupported(SMTPException):
# """
# A command or argument sent to the SMTP server is not supported.
# """
#
# class SMTPReadTimeoutError(SMTPTimeoutError):
# """
# A timeout occurred while waiting for a response from the SMTP server.
# """
#
# class SMTPRecipientRefused(SMTPResponseException):
# """
# SMTP server refused a message recipient.
# """
#
# def __init__(self, code: int, message: str, recipient: str) -> None:
# self.code = code
# self.message = message
# self.recipient = recipient
# self.args = (code, message, recipient)
#
# class SMTPRecipientsRefused(SMTPException):
# """
# SMTP server refused multiple recipients.
# """
#
# def __init__(self, recipients: List[SMTPRecipientRefused]) -> None:
# self.recipients = recipients
# self.args = (recipients,)
#
# class SMTPResponseException(SMTPException):
# """
# Base class for all server responses with error codes.
# """
#
# def __init__(self, code: int, message: str) -> None:
# self.code = code
# self.message = message
# self.args = (code, message)
#
# class SMTPSenderRefused(SMTPResponseException):
# """
# SMTP server refused the message sender.
# """
#
# def __init__(self, code: int, message: str, sender: str) -> None:
# self.code = code
# self.message = message
# self.sender = sender
# self.args = (code, message, sender)
#
# class SMTPServerDisconnected(SMTPException, ConnectionError):
# """
# The connection was lost unexpectedly, or a command was run that requires
# a connection.
# """
#
# class SMTPTimeoutError(SMTPException, TimeoutError):
# """
# A timeout occurred while performing a network operation.
# """
, which may include functions, classes, or code. Output only the next line. | "error_class", (SMTPServerDisconnected, SMTPConnectError, SMTPConnectTimeoutError) |
Given snippet: <|code_start|>"""
Test error class imports, arguments, and inheritance.
"""
@given(text())
def test_raise_smtp_exception(message):
with pytest.raises(SMTPException) as excinfo:
raise SMTPException(message)
assert excinfo.value.message == message
@given(integers(), text())
def test_raise_smtp_response_exception(code, message):
with pytest.raises(SMTPResponseException) as excinfo:
raise SMTPResponseException(code, message)
assert issubclass(excinfo.type, SMTPException)
assert excinfo.value.code == code
assert excinfo.value.message == message
@pytest.mark.parametrize(
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import asyncio
import pytest
from hypothesis import given
from hypothesis.strategies import integers, lists, text
from aiosmtplib import (
SMTPAuthenticationError,
SMTPConnectError,
SMTPConnectTimeoutError,
SMTPDataError,
SMTPException,
SMTPHeloError,
SMTPNotSupported,
SMTPReadTimeoutError,
SMTPRecipientRefused,
SMTPRecipientsRefused,
SMTPResponseException,
SMTPSenderRefused,
SMTPServerDisconnected,
SMTPTimeoutError,
)
and context:
# Path: aiosmtplib/errors.py
# class SMTPAuthenticationError(SMTPResponseException):
# """
# Server refused our AUTH request; may be caused by invalid credentials.
# """
#
# class SMTPConnectError(SMTPException, ConnectionError):
# """
# An error occurred while connecting to the SMTP server.
# """
#
# class SMTPConnectTimeoutError(SMTPTimeoutError, SMTPConnectError):
# """
# A timeout occurred while connecting to the SMTP server.
# """
#
# class SMTPDataError(SMTPResponseException):
# """
# Server refused DATA content.
# """
#
# class SMTPException(Exception):
# """
# Base class for all SMTP exceptions.
# """
#
# def __init__(self, message: str) -> None:
# self.message = message
# self.args = (message,)
#
# class SMTPHeloError(SMTPResponseException):
# """
# Server refused HELO or EHLO.
# """
#
# class SMTPNotSupported(SMTPException):
# """
# A command or argument sent to the SMTP server is not supported.
# """
#
# class SMTPReadTimeoutError(SMTPTimeoutError):
# """
# A timeout occurred while waiting for a response from the SMTP server.
# """
#
# class SMTPRecipientRefused(SMTPResponseException):
# """
# SMTP server refused a message recipient.
# """
#
# def __init__(self, code: int, message: str, recipient: str) -> None:
# self.code = code
# self.message = message
# self.recipient = recipient
# self.args = (code, message, recipient)
#
# class SMTPRecipientsRefused(SMTPException):
# """
# SMTP server refused multiple recipients.
# """
#
# def __init__(self, recipients: List[SMTPRecipientRefused]) -> None:
# self.recipients = recipients
# self.args = (recipients,)
#
# class SMTPResponseException(SMTPException):
# """
# Base class for all server responses with error codes.
# """
#
# def __init__(self, code: int, message: str) -> None:
# self.code = code
# self.message = message
# self.args = (code, message)
#
# class SMTPSenderRefused(SMTPResponseException):
# """
# SMTP server refused the message sender.
# """
#
# def __init__(self, code: int, message: str, sender: str) -> None:
# self.code = code
# self.message = message
# self.sender = sender
# self.args = (code, message, sender)
#
# class SMTPServerDisconnected(SMTPException, ConnectionError):
# """
# The connection was lost unexpectedly, or a command was run that requires
# a connection.
# """
#
# class SMTPTimeoutError(SMTPException, TimeoutError):
# """
# A timeout occurred while performing a network operation.
# """
which might include code, classes, or functions. Output only the next line. | "error_class", (SMTPServerDisconnected, SMTPConnectError, SMTPConnectTimeoutError) |
Continue the code snippet: <|code_start|> assert excinfo.value.message == message
@pytest.mark.parametrize(
"error_class", (SMTPServerDisconnected, SMTPConnectError, SMTPConnectTimeoutError)
)
@given(message=text())
def test_connection_exceptions(message, error_class):
with pytest.raises(error_class) as excinfo:
raise error_class(message)
assert issubclass(excinfo.type, SMTPException)
assert issubclass(excinfo.type, ConnectionError)
assert excinfo.value.message == message
@pytest.mark.parametrize(
"error_class", (SMTPTimeoutError, SMTPConnectTimeoutError, SMTPReadTimeoutError)
)
@given(message=text())
def test_timeout_exceptions(message, error_class):
with pytest.raises(error_class) as excinfo:
raise error_class(message)
assert issubclass(excinfo.type, SMTPException)
assert issubclass(excinfo.type, asyncio.TimeoutError)
assert excinfo.value.message == message
@pytest.mark.parametrize(
<|code_end|>
. Use current file imports:
import asyncio
import pytest
from hypothesis import given
from hypothesis.strategies import integers, lists, text
from aiosmtplib import (
SMTPAuthenticationError,
SMTPConnectError,
SMTPConnectTimeoutError,
SMTPDataError,
SMTPException,
SMTPHeloError,
SMTPNotSupported,
SMTPReadTimeoutError,
SMTPRecipientRefused,
SMTPRecipientsRefused,
SMTPResponseException,
SMTPSenderRefused,
SMTPServerDisconnected,
SMTPTimeoutError,
)
and context (classes, functions, or code) from other files:
# Path: aiosmtplib/errors.py
# class SMTPAuthenticationError(SMTPResponseException):
# """
# Server refused our AUTH request; may be caused by invalid credentials.
# """
#
# class SMTPConnectError(SMTPException, ConnectionError):
# """
# An error occurred while connecting to the SMTP server.
# """
#
# class SMTPConnectTimeoutError(SMTPTimeoutError, SMTPConnectError):
# """
# A timeout occurred while connecting to the SMTP server.
# """
#
# class SMTPDataError(SMTPResponseException):
# """
# Server refused DATA content.
# """
#
# class SMTPException(Exception):
# """
# Base class for all SMTP exceptions.
# """
#
# def __init__(self, message: str) -> None:
# self.message = message
# self.args = (message,)
#
# class SMTPHeloError(SMTPResponseException):
# """
# Server refused HELO or EHLO.
# """
#
# class SMTPNotSupported(SMTPException):
# """
# A command or argument sent to the SMTP server is not supported.
# """
#
# class SMTPReadTimeoutError(SMTPTimeoutError):
# """
# A timeout occurred while waiting for a response from the SMTP server.
# """
#
# class SMTPRecipientRefused(SMTPResponseException):
# """
# SMTP server refused a message recipient.
# """
#
# def __init__(self, code: int, message: str, recipient: str) -> None:
# self.code = code
# self.message = message
# self.recipient = recipient
# self.args = (code, message, recipient)
#
# class SMTPRecipientsRefused(SMTPException):
# """
# SMTP server refused multiple recipients.
# """
#
# def __init__(self, recipients: List[SMTPRecipientRefused]) -> None:
# self.recipients = recipients
# self.args = (recipients,)
#
# class SMTPResponseException(SMTPException):
# """
# Base class for all server responses with error codes.
# """
#
# def __init__(self, code: int, message: str) -> None:
# self.code = code
# self.message = message
# self.args = (code, message)
#
# class SMTPSenderRefused(SMTPResponseException):
# """
# SMTP server refused the message sender.
# """
#
# def __init__(self, code: int, message: str, sender: str) -> None:
# self.code = code
# self.message = message
# self.sender = sender
# self.args = (code, message, sender)
#
# class SMTPServerDisconnected(SMTPException, ConnectionError):
# """
# The connection was lost unexpectedly, or a command was run that requires
# a connection.
# """
#
# class SMTPTimeoutError(SMTPException, TimeoutError):
# """
# A timeout occurred while performing a network operation.
# """
. Output only the next line. | "error_class", (SMTPHeloError, SMTPDataError, SMTPAuthenticationError) |
Given the following code snippet before the placeholder: <|code_start|>"""
Test error class imports, arguments, and inheritance.
"""
@given(text())
def test_raise_smtp_exception(message):
<|code_end|>
, predict the next line using imports from the current file:
import asyncio
import pytest
from hypothesis import given
from hypothesis.strategies import integers, lists, text
from aiosmtplib import (
SMTPAuthenticationError,
SMTPConnectError,
SMTPConnectTimeoutError,
SMTPDataError,
SMTPException,
SMTPHeloError,
SMTPNotSupported,
SMTPReadTimeoutError,
SMTPRecipientRefused,
SMTPRecipientsRefused,
SMTPResponseException,
SMTPSenderRefused,
SMTPServerDisconnected,
SMTPTimeoutError,
)
and context including class names, function names, and sometimes code from other files:
# Path: aiosmtplib/errors.py
# class SMTPAuthenticationError(SMTPResponseException):
# """
# Server refused our AUTH request; may be caused by invalid credentials.
# """
#
# class SMTPConnectError(SMTPException, ConnectionError):
# """
# An error occurred while connecting to the SMTP server.
# """
#
# class SMTPConnectTimeoutError(SMTPTimeoutError, SMTPConnectError):
# """
# A timeout occurred while connecting to the SMTP server.
# """
#
# class SMTPDataError(SMTPResponseException):
# """
# Server refused DATA content.
# """
#
# class SMTPException(Exception):
# """
# Base class for all SMTP exceptions.
# """
#
# def __init__(self, message: str) -> None:
# self.message = message
# self.args = (message,)
#
# class SMTPHeloError(SMTPResponseException):
# """
# Server refused HELO or EHLO.
# """
#
# class SMTPNotSupported(SMTPException):
# """
# A command or argument sent to the SMTP server is not supported.
# """
#
# class SMTPReadTimeoutError(SMTPTimeoutError):
# """
# A timeout occurred while waiting for a response from the SMTP server.
# """
#
# class SMTPRecipientRefused(SMTPResponseException):
# """
# SMTP server refused a message recipient.
# """
#
# def __init__(self, code: int, message: str, recipient: str) -> None:
# self.code = code
# self.message = message
# self.recipient = recipient
# self.args = (code, message, recipient)
#
# class SMTPRecipientsRefused(SMTPException):
# """
# SMTP server refused multiple recipients.
# """
#
# def __init__(self, recipients: List[SMTPRecipientRefused]) -> None:
# self.recipients = recipients
# self.args = (recipients,)
#
# class SMTPResponseException(SMTPException):
# """
# Base class for all server responses with error codes.
# """
#
# def __init__(self, code: int, message: str) -> None:
# self.code = code
# self.message = message
# self.args = (code, message)
#
# class SMTPSenderRefused(SMTPResponseException):
# """
# SMTP server refused the message sender.
# """
#
# def __init__(self, code: int, message: str, sender: str) -> None:
# self.code = code
# self.message = message
# self.sender = sender
# self.args = (code, message, sender)
#
# class SMTPServerDisconnected(SMTPException, ConnectionError):
# """
# The connection was lost unexpectedly, or a command was run that requires
# a connection.
# """
#
# class SMTPTimeoutError(SMTPException, TimeoutError):
# """
# A timeout occurred while performing a network operation.
# """
. Output only the next line. | with pytest.raises(SMTPException) as excinfo: |
Based on the snippet: <|code_start|> assert excinfo.value.message == message
@pytest.mark.parametrize(
"error_class", (SMTPServerDisconnected, SMTPConnectError, SMTPConnectTimeoutError)
)
@given(message=text())
def test_connection_exceptions(message, error_class):
with pytest.raises(error_class) as excinfo:
raise error_class(message)
assert issubclass(excinfo.type, SMTPException)
assert issubclass(excinfo.type, ConnectionError)
assert excinfo.value.message == message
@pytest.mark.parametrize(
"error_class", (SMTPTimeoutError, SMTPConnectTimeoutError, SMTPReadTimeoutError)
)
@given(message=text())
def test_timeout_exceptions(message, error_class):
with pytest.raises(error_class) as excinfo:
raise error_class(message)
assert issubclass(excinfo.type, SMTPException)
assert issubclass(excinfo.type, asyncio.TimeoutError)
assert excinfo.value.message == message
@pytest.mark.parametrize(
<|code_end|>
, predict the immediate next line with the help of imports:
import asyncio
import pytest
from hypothesis import given
from hypothesis.strategies import integers, lists, text
from aiosmtplib import (
SMTPAuthenticationError,
SMTPConnectError,
SMTPConnectTimeoutError,
SMTPDataError,
SMTPException,
SMTPHeloError,
SMTPNotSupported,
SMTPReadTimeoutError,
SMTPRecipientRefused,
SMTPRecipientsRefused,
SMTPResponseException,
SMTPSenderRefused,
SMTPServerDisconnected,
SMTPTimeoutError,
)
and context (classes, functions, sometimes code) from other files:
# Path: aiosmtplib/errors.py
# class SMTPAuthenticationError(SMTPResponseException):
# """
# Server refused our AUTH request; may be caused by invalid credentials.
# """
#
# class SMTPConnectError(SMTPException, ConnectionError):
# """
# An error occurred while connecting to the SMTP server.
# """
#
# class SMTPConnectTimeoutError(SMTPTimeoutError, SMTPConnectError):
# """
# A timeout occurred while connecting to the SMTP server.
# """
#
# class SMTPDataError(SMTPResponseException):
# """
# Server refused DATA content.
# """
#
# class SMTPException(Exception):
# """
# Base class for all SMTP exceptions.
# """
#
# def __init__(self, message: str) -> None:
# self.message = message
# self.args = (message,)
#
# class SMTPHeloError(SMTPResponseException):
# """
# Server refused HELO or EHLO.
# """
#
# class SMTPNotSupported(SMTPException):
# """
# A command or argument sent to the SMTP server is not supported.
# """
#
# class SMTPReadTimeoutError(SMTPTimeoutError):
# """
# A timeout occurred while waiting for a response from the SMTP server.
# """
#
# class SMTPRecipientRefused(SMTPResponseException):
# """
# SMTP server refused a message recipient.
# """
#
# def __init__(self, code: int, message: str, recipient: str) -> None:
# self.code = code
# self.message = message
# self.recipient = recipient
# self.args = (code, message, recipient)
#
# class SMTPRecipientsRefused(SMTPException):
# """
# SMTP server refused multiple recipients.
# """
#
# def __init__(self, recipients: List[SMTPRecipientRefused]) -> None:
# self.recipients = recipients
# self.args = (recipients,)
#
# class SMTPResponseException(SMTPException):
# """
# Base class for all server responses with error codes.
# """
#
# def __init__(self, code: int, message: str) -> None:
# self.code = code
# self.message = message
# self.args = (code, message)
#
# class SMTPSenderRefused(SMTPResponseException):
# """
# SMTP server refused the message sender.
# """
#
# def __init__(self, code: int, message: str, sender: str) -> None:
# self.code = code
# self.message = message
# self.sender = sender
# self.args = (code, message, sender)
#
# class SMTPServerDisconnected(SMTPException, ConnectionError):
# """
# The connection was lost unexpectedly, or a command was run that requires
# a connection.
# """
#
# class SMTPTimeoutError(SMTPException, TimeoutError):
# """
# A timeout occurred while performing a network operation.
# """
. Output only the next line. | "error_class", (SMTPHeloError, SMTPDataError, SMTPAuthenticationError) |
Here is a snippet: <|code_start|> raise SMTPSenderRefused(code, message, sender)
assert issubclass(excinfo.type, SMTPResponseException)
assert excinfo.value.code == code
assert excinfo.value.message == message
assert excinfo.value.sender == sender
@given(integers(), text(), text())
def test_raise_smtp_recipient_refused(code, message, recipient):
with pytest.raises(SMTPRecipientRefused) as excinfo:
raise SMTPRecipientRefused(code, message, recipient)
assert issubclass(excinfo.type, SMTPResponseException)
assert excinfo.value.code == code
assert excinfo.value.message == message
assert excinfo.value.recipient == recipient
@given(lists(elements=text()))
def test_raise_smtp_recipients_refused(addresses):
with pytest.raises(SMTPRecipientsRefused) as excinfo:
raise SMTPRecipientsRefused(addresses)
assert issubclass(excinfo.type, SMTPException)
assert excinfo.value.recipients == addresses
@given(message=text())
def test_raise_smtp_not_supported(message):
<|code_end|>
. Write the next line using the current file imports:
import asyncio
import pytest
from hypothesis import given
from hypothesis.strategies import integers, lists, text
from aiosmtplib import (
SMTPAuthenticationError,
SMTPConnectError,
SMTPConnectTimeoutError,
SMTPDataError,
SMTPException,
SMTPHeloError,
SMTPNotSupported,
SMTPReadTimeoutError,
SMTPRecipientRefused,
SMTPRecipientsRefused,
SMTPResponseException,
SMTPSenderRefused,
SMTPServerDisconnected,
SMTPTimeoutError,
)
and context from other files:
# Path: aiosmtplib/errors.py
# class SMTPAuthenticationError(SMTPResponseException):
# """
# Server refused our AUTH request; may be caused by invalid credentials.
# """
#
# class SMTPConnectError(SMTPException, ConnectionError):
# """
# An error occurred while connecting to the SMTP server.
# """
#
# class SMTPConnectTimeoutError(SMTPTimeoutError, SMTPConnectError):
# """
# A timeout occurred while connecting to the SMTP server.
# """
#
# class SMTPDataError(SMTPResponseException):
# """
# Server refused DATA content.
# """
#
# class SMTPException(Exception):
# """
# Base class for all SMTP exceptions.
# """
#
# def __init__(self, message: str) -> None:
# self.message = message
# self.args = (message,)
#
# class SMTPHeloError(SMTPResponseException):
# """
# Server refused HELO or EHLO.
# """
#
# class SMTPNotSupported(SMTPException):
# """
# A command or argument sent to the SMTP server is not supported.
# """
#
# class SMTPReadTimeoutError(SMTPTimeoutError):
# """
# A timeout occurred while waiting for a response from the SMTP server.
# """
#
# class SMTPRecipientRefused(SMTPResponseException):
# """
# SMTP server refused a message recipient.
# """
#
# def __init__(self, code: int, message: str, recipient: str) -> None:
# self.code = code
# self.message = message
# self.recipient = recipient
# self.args = (code, message, recipient)
#
# class SMTPRecipientsRefused(SMTPException):
# """
# SMTP server refused multiple recipients.
# """
#
# def __init__(self, recipients: List[SMTPRecipientRefused]) -> None:
# self.recipients = recipients
# self.args = (recipients,)
#
# class SMTPResponseException(SMTPException):
# """
# Base class for all server responses with error codes.
# """
#
# def __init__(self, code: int, message: str) -> None:
# self.code = code
# self.message = message
# self.args = (code, message)
#
# class SMTPSenderRefused(SMTPResponseException):
# """
# SMTP server refused the message sender.
# """
#
# def __init__(self, code: int, message: str, sender: str) -> None:
# self.code = code
# self.message = message
# self.sender = sender
# self.args = (code, message, sender)
#
# class SMTPServerDisconnected(SMTPException, ConnectionError):
# """
# The connection was lost unexpectedly, or a command was run that requires
# a connection.
# """
#
# class SMTPTimeoutError(SMTPException, TimeoutError):
# """
# A timeout occurred while performing a network operation.
# """
, which may include functions, classes, or code. Output only the next line. | with pytest.raises(SMTPNotSupported) as excinfo: |
Given the following code snippet before the placeholder: <|code_start|> with pytest.raises(SMTPException) as excinfo:
raise SMTPException(message)
assert excinfo.value.message == message
@given(integers(), text())
def test_raise_smtp_response_exception(code, message):
with pytest.raises(SMTPResponseException) as excinfo:
raise SMTPResponseException(code, message)
assert issubclass(excinfo.type, SMTPException)
assert excinfo.value.code == code
assert excinfo.value.message == message
@pytest.mark.parametrize(
"error_class", (SMTPServerDisconnected, SMTPConnectError, SMTPConnectTimeoutError)
)
@given(message=text())
def test_connection_exceptions(message, error_class):
with pytest.raises(error_class) as excinfo:
raise error_class(message)
assert issubclass(excinfo.type, SMTPException)
assert issubclass(excinfo.type, ConnectionError)
assert excinfo.value.message == message
@pytest.mark.parametrize(
<|code_end|>
, predict the next line using imports from the current file:
import asyncio
import pytest
from hypothesis import given
from hypothesis.strategies import integers, lists, text
from aiosmtplib import (
SMTPAuthenticationError,
SMTPConnectError,
SMTPConnectTimeoutError,
SMTPDataError,
SMTPException,
SMTPHeloError,
SMTPNotSupported,
SMTPReadTimeoutError,
SMTPRecipientRefused,
SMTPRecipientsRefused,
SMTPResponseException,
SMTPSenderRefused,
SMTPServerDisconnected,
SMTPTimeoutError,
)
and context including class names, function names, and sometimes code from other files:
# Path: aiosmtplib/errors.py
# class SMTPAuthenticationError(SMTPResponseException):
# """
# Server refused our AUTH request; may be caused by invalid credentials.
# """
#
# class SMTPConnectError(SMTPException, ConnectionError):
# """
# An error occurred while connecting to the SMTP server.
# """
#
# class SMTPConnectTimeoutError(SMTPTimeoutError, SMTPConnectError):
# """
# A timeout occurred while connecting to the SMTP server.
# """
#
# class SMTPDataError(SMTPResponseException):
# """
# Server refused DATA content.
# """
#
# class SMTPException(Exception):
# """
# Base class for all SMTP exceptions.
# """
#
# def __init__(self, message: str) -> None:
# self.message = message
# self.args = (message,)
#
# class SMTPHeloError(SMTPResponseException):
# """
# Server refused HELO or EHLO.
# """
#
# class SMTPNotSupported(SMTPException):
# """
# A command or argument sent to the SMTP server is not supported.
# """
#
# class SMTPReadTimeoutError(SMTPTimeoutError):
# """
# A timeout occurred while waiting for a response from the SMTP server.
# """
#
# class SMTPRecipientRefused(SMTPResponseException):
# """
# SMTP server refused a message recipient.
# """
#
# def __init__(self, code: int, message: str, recipient: str) -> None:
# self.code = code
# self.message = message
# self.recipient = recipient
# self.args = (code, message, recipient)
#
# class SMTPRecipientsRefused(SMTPException):
# """
# SMTP server refused multiple recipients.
# """
#
# def __init__(self, recipients: List[SMTPRecipientRefused]) -> None:
# self.recipients = recipients
# self.args = (recipients,)
#
# class SMTPResponseException(SMTPException):
# """
# Base class for all server responses with error codes.
# """
#
# def __init__(self, code: int, message: str) -> None:
# self.code = code
# self.message = message
# self.args = (code, message)
#
# class SMTPSenderRefused(SMTPResponseException):
# """
# SMTP server refused the message sender.
# """
#
# def __init__(self, code: int, message: str, sender: str) -> None:
# self.code = code
# self.message = message
# self.sender = sender
# self.args = (code, message, sender)
#
# class SMTPServerDisconnected(SMTPException, ConnectionError):
# """
# The connection was lost unexpectedly, or a command was run that requires
# a connection.
# """
#
# class SMTPTimeoutError(SMTPException, TimeoutError):
# """
# A timeout occurred while performing a network operation.
# """
. Output only the next line. | "error_class", (SMTPTimeoutError, SMTPConnectTimeoutError, SMTPReadTimeoutError) |
Predict the next line after this snippet: <|code_start|> assert issubclass(excinfo.type, asyncio.TimeoutError)
assert excinfo.value.message == message
@pytest.mark.parametrize(
"error_class", (SMTPHeloError, SMTPDataError, SMTPAuthenticationError)
)
@given(code=integers(), message=text())
def test_simple_response_exceptions(code, message, error_class):
with pytest.raises(error_class) as excinfo:
raise error_class(code, message)
assert issubclass(excinfo.type, SMTPResponseException)
assert excinfo.value.code == code
assert excinfo.value.message == message
@given(integers(), text(), text())
def test_raise_smtp_sender_refused(code, message, sender):
with pytest.raises(SMTPSenderRefused) as excinfo:
raise SMTPSenderRefused(code, message, sender)
assert issubclass(excinfo.type, SMTPResponseException)
assert excinfo.value.code == code
assert excinfo.value.message == message
assert excinfo.value.sender == sender
@given(integers(), text(), text())
def test_raise_smtp_recipient_refused(code, message, recipient):
<|code_end|>
using the current file's imports:
import asyncio
import pytest
from hypothesis import given
from hypothesis.strategies import integers, lists, text
from aiosmtplib import (
SMTPAuthenticationError,
SMTPConnectError,
SMTPConnectTimeoutError,
SMTPDataError,
SMTPException,
SMTPHeloError,
SMTPNotSupported,
SMTPReadTimeoutError,
SMTPRecipientRefused,
SMTPRecipientsRefused,
SMTPResponseException,
SMTPSenderRefused,
SMTPServerDisconnected,
SMTPTimeoutError,
)
and any relevant context from other files:
# Path: aiosmtplib/errors.py
# class SMTPAuthenticationError(SMTPResponseException):
# """
# Server refused our AUTH request; may be caused by invalid credentials.
# """
#
# class SMTPConnectError(SMTPException, ConnectionError):
# """
# An error occurred while connecting to the SMTP server.
# """
#
# class SMTPConnectTimeoutError(SMTPTimeoutError, SMTPConnectError):
# """
# A timeout occurred while connecting to the SMTP server.
# """
#
# class SMTPDataError(SMTPResponseException):
# """
# Server refused DATA content.
# """
#
# class SMTPException(Exception):
# """
# Base class for all SMTP exceptions.
# """
#
# def __init__(self, message: str) -> None:
# self.message = message
# self.args = (message,)
#
# class SMTPHeloError(SMTPResponseException):
# """
# Server refused HELO or EHLO.
# """
#
# class SMTPNotSupported(SMTPException):
# """
# A command or argument sent to the SMTP server is not supported.
# """
#
# class SMTPReadTimeoutError(SMTPTimeoutError):
# """
# A timeout occurred while waiting for a response from the SMTP server.
# """
#
# class SMTPRecipientRefused(SMTPResponseException):
# """
# SMTP server refused a message recipient.
# """
#
# def __init__(self, code: int, message: str, recipient: str) -> None:
# self.code = code
# self.message = message
# self.recipient = recipient
# self.args = (code, message, recipient)
#
# class SMTPRecipientsRefused(SMTPException):
# """
# SMTP server refused multiple recipients.
# """
#
# def __init__(self, recipients: List[SMTPRecipientRefused]) -> None:
# self.recipients = recipients
# self.args = (recipients,)
#
# class SMTPResponseException(SMTPException):
# """
# Base class for all server responses with error codes.
# """
#
# def __init__(self, code: int, message: str) -> None:
# self.code = code
# self.message = message
# self.args = (code, message)
#
# class SMTPSenderRefused(SMTPResponseException):
# """
# SMTP server refused the message sender.
# """
#
# def __init__(self, code: int, message: str, sender: str) -> None:
# self.code = code
# self.message = message
# self.sender = sender
# self.args = (code, message, sender)
#
# class SMTPServerDisconnected(SMTPException, ConnectionError):
# """
# The connection was lost unexpectedly, or a command was run that requires
# a connection.
# """
#
# class SMTPTimeoutError(SMTPException, TimeoutError):
# """
# A timeout occurred while performing a network operation.
# """
. Output only the next line. | with pytest.raises(SMTPRecipientRefused) as excinfo: |
Here is a snippet: <|code_start|>
assert issubclass(excinfo.type, SMTPResponseException)
assert excinfo.value.code == code
assert excinfo.value.message == message
@given(integers(), text(), text())
def test_raise_smtp_sender_refused(code, message, sender):
with pytest.raises(SMTPSenderRefused) as excinfo:
raise SMTPSenderRefused(code, message, sender)
assert issubclass(excinfo.type, SMTPResponseException)
assert excinfo.value.code == code
assert excinfo.value.message == message
assert excinfo.value.sender == sender
@given(integers(), text(), text())
def test_raise_smtp_recipient_refused(code, message, recipient):
with pytest.raises(SMTPRecipientRefused) as excinfo:
raise SMTPRecipientRefused(code, message, recipient)
assert issubclass(excinfo.type, SMTPResponseException)
assert excinfo.value.code == code
assert excinfo.value.message == message
assert excinfo.value.recipient == recipient
@given(lists(elements=text()))
def test_raise_smtp_recipients_refused(addresses):
<|code_end|>
. Write the next line using the current file imports:
import asyncio
import pytest
from hypothesis import given
from hypothesis.strategies import integers, lists, text
from aiosmtplib import (
SMTPAuthenticationError,
SMTPConnectError,
SMTPConnectTimeoutError,
SMTPDataError,
SMTPException,
SMTPHeloError,
SMTPNotSupported,
SMTPReadTimeoutError,
SMTPRecipientRefused,
SMTPRecipientsRefused,
SMTPResponseException,
SMTPSenderRefused,
SMTPServerDisconnected,
SMTPTimeoutError,
)
and context from other files:
# Path: aiosmtplib/errors.py
# class SMTPAuthenticationError(SMTPResponseException):
# """
# Server refused our AUTH request; may be caused by invalid credentials.
# """
#
# class SMTPConnectError(SMTPException, ConnectionError):
# """
# An error occurred while connecting to the SMTP server.
# """
#
# class SMTPConnectTimeoutError(SMTPTimeoutError, SMTPConnectError):
# """
# A timeout occurred while connecting to the SMTP server.
# """
#
# class SMTPDataError(SMTPResponseException):
# """
# Server refused DATA content.
# """
#
# class SMTPException(Exception):
# """
# Base class for all SMTP exceptions.
# """
#
# def __init__(self, message: str) -> None:
# self.message = message
# self.args = (message,)
#
# class SMTPHeloError(SMTPResponseException):
# """
# Server refused HELO or EHLO.
# """
#
# class SMTPNotSupported(SMTPException):
# """
# A command or argument sent to the SMTP server is not supported.
# """
#
# class SMTPReadTimeoutError(SMTPTimeoutError):
# """
# A timeout occurred while waiting for a response from the SMTP server.
# """
#
# class SMTPRecipientRefused(SMTPResponseException):
# """
# SMTP server refused a message recipient.
# """
#
# def __init__(self, code: int, message: str, recipient: str) -> None:
# self.code = code
# self.message = message
# self.recipient = recipient
# self.args = (code, message, recipient)
#
# class SMTPRecipientsRefused(SMTPException):
# """
# SMTP server refused multiple recipients.
# """
#
# def __init__(self, recipients: List[SMTPRecipientRefused]) -> None:
# self.recipients = recipients
# self.args = (recipients,)
#
# class SMTPResponseException(SMTPException):
# """
# Base class for all server responses with error codes.
# """
#
# def __init__(self, code: int, message: str) -> None:
# self.code = code
# self.message = message
# self.args = (code, message)
#
# class SMTPSenderRefused(SMTPResponseException):
# """
# SMTP server refused the message sender.
# """
#
# def __init__(self, code: int, message: str, sender: str) -> None:
# self.code = code
# self.message = message
# self.sender = sender
# self.args = (code, message, sender)
#
# class SMTPServerDisconnected(SMTPException, ConnectionError):
# """
# The connection was lost unexpectedly, or a command was run that requires
# a connection.
# """
#
# class SMTPTimeoutError(SMTPException, TimeoutError):
# """
# A timeout occurred while performing a network operation.
# """
, which may include functions, classes, or code. Output only the next line. | with pytest.raises(SMTPRecipientsRefused) as excinfo: |
Given snippet: <|code_start|>"""
Test error class imports, arguments, and inheritance.
"""
@given(text())
def test_raise_smtp_exception(message):
with pytest.raises(SMTPException) as excinfo:
raise SMTPException(message)
assert excinfo.value.message == message
@given(integers(), text())
def test_raise_smtp_response_exception(code, message):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import asyncio
import pytest
from hypothesis import given
from hypothesis.strategies import integers, lists, text
from aiosmtplib import (
SMTPAuthenticationError,
SMTPConnectError,
SMTPConnectTimeoutError,
SMTPDataError,
SMTPException,
SMTPHeloError,
SMTPNotSupported,
SMTPReadTimeoutError,
SMTPRecipientRefused,
SMTPRecipientsRefused,
SMTPResponseException,
SMTPSenderRefused,
SMTPServerDisconnected,
SMTPTimeoutError,
)
and context:
# Path: aiosmtplib/errors.py
# class SMTPAuthenticationError(SMTPResponseException):
# """
# Server refused our AUTH request; may be caused by invalid credentials.
# """
#
# class SMTPConnectError(SMTPException, ConnectionError):
# """
# An error occurred while connecting to the SMTP server.
# """
#
# class SMTPConnectTimeoutError(SMTPTimeoutError, SMTPConnectError):
# """
# A timeout occurred while connecting to the SMTP server.
# """
#
# class SMTPDataError(SMTPResponseException):
# """
# Server refused DATA content.
# """
#
# class SMTPException(Exception):
# """
# Base class for all SMTP exceptions.
# """
#
# def __init__(self, message: str) -> None:
# self.message = message
# self.args = (message,)
#
# class SMTPHeloError(SMTPResponseException):
# """
# Server refused HELO or EHLO.
# """
#
# class SMTPNotSupported(SMTPException):
# """
# A command or argument sent to the SMTP server is not supported.
# """
#
# class SMTPReadTimeoutError(SMTPTimeoutError):
# """
# A timeout occurred while waiting for a response from the SMTP server.
# """
#
# class SMTPRecipientRefused(SMTPResponseException):
# """
# SMTP server refused a message recipient.
# """
#
# def __init__(self, code: int, message: str, recipient: str) -> None:
# self.code = code
# self.message = message
# self.recipient = recipient
# self.args = (code, message, recipient)
#
# class SMTPRecipientsRefused(SMTPException):
# """
# SMTP server refused multiple recipients.
# """
#
# def __init__(self, recipients: List[SMTPRecipientRefused]) -> None:
# self.recipients = recipients
# self.args = (recipients,)
#
# class SMTPResponseException(SMTPException):
# """
# Base class for all server responses with error codes.
# """
#
# def __init__(self, code: int, message: str) -> None:
# self.code = code
# self.message = message
# self.args = (code, message)
#
# class SMTPSenderRefused(SMTPResponseException):
# """
# SMTP server refused the message sender.
# """
#
# def __init__(self, code: int, message: str, sender: str) -> None:
# self.code = code
# self.message = message
# self.sender = sender
# self.args = (code, message, sender)
#
# class SMTPServerDisconnected(SMTPException, ConnectionError):
# """
# The connection was lost unexpectedly, or a command was run that requires
# a connection.
# """
#
# class SMTPTimeoutError(SMTPException, TimeoutError):
# """
# A timeout occurred while performing a network operation.
# """
which might include code, classes, or functions. Output only the next line. | with pytest.raises(SMTPResponseException) as excinfo: |
Next line prediction: <|code_start|>
@pytest.mark.parametrize(
"error_class", (SMTPTimeoutError, SMTPConnectTimeoutError, SMTPReadTimeoutError)
)
@given(message=text())
def test_timeout_exceptions(message, error_class):
with pytest.raises(error_class) as excinfo:
raise error_class(message)
assert issubclass(excinfo.type, SMTPException)
assert issubclass(excinfo.type, asyncio.TimeoutError)
assert excinfo.value.message == message
@pytest.mark.parametrize(
"error_class", (SMTPHeloError, SMTPDataError, SMTPAuthenticationError)
)
@given(code=integers(), message=text())
def test_simple_response_exceptions(code, message, error_class):
with pytest.raises(error_class) as excinfo:
raise error_class(code, message)
assert issubclass(excinfo.type, SMTPResponseException)
assert excinfo.value.code == code
assert excinfo.value.message == message
@given(integers(), text(), text())
def test_raise_smtp_sender_refused(code, message, sender):
<|code_end|>
. Use current file imports:
(import asyncio
import pytest
from hypothesis import given
from hypothesis.strategies import integers, lists, text
from aiosmtplib import (
SMTPAuthenticationError,
SMTPConnectError,
SMTPConnectTimeoutError,
SMTPDataError,
SMTPException,
SMTPHeloError,
SMTPNotSupported,
SMTPReadTimeoutError,
SMTPRecipientRefused,
SMTPRecipientsRefused,
SMTPResponseException,
SMTPSenderRefused,
SMTPServerDisconnected,
SMTPTimeoutError,
))
and context including class names, function names, or small code snippets from other files:
# Path: aiosmtplib/errors.py
# class SMTPAuthenticationError(SMTPResponseException):
# """
# Server refused our AUTH request; may be caused by invalid credentials.
# """
#
# class SMTPConnectError(SMTPException, ConnectionError):
# """
# An error occurred while connecting to the SMTP server.
# """
#
# class SMTPConnectTimeoutError(SMTPTimeoutError, SMTPConnectError):
# """
# A timeout occurred while connecting to the SMTP server.
# """
#
# class SMTPDataError(SMTPResponseException):
# """
# Server refused DATA content.
# """
#
# class SMTPException(Exception):
# """
# Base class for all SMTP exceptions.
# """
#
# def __init__(self, message: str) -> None:
# self.message = message
# self.args = (message,)
#
# class SMTPHeloError(SMTPResponseException):
# """
# Server refused HELO or EHLO.
# """
#
# class SMTPNotSupported(SMTPException):
# """
# A command or argument sent to the SMTP server is not supported.
# """
#
# class SMTPReadTimeoutError(SMTPTimeoutError):
# """
# A timeout occurred while waiting for a response from the SMTP server.
# """
#
# class SMTPRecipientRefused(SMTPResponseException):
# """
# SMTP server refused a message recipient.
# """
#
# def __init__(self, code: int, message: str, recipient: str) -> None:
# self.code = code
# self.message = message
# self.recipient = recipient
# self.args = (code, message, recipient)
#
# class SMTPRecipientsRefused(SMTPException):
# """
# SMTP server refused multiple recipients.
# """
#
# def __init__(self, recipients: List[SMTPRecipientRefused]) -> None:
# self.recipients = recipients
# self.args = (recipients,)
#
# class SMTPResponseException(SMTPException):
# """
# Base class for all server responses with error codes.
# """
#
# def __init__(self, code: int, message: str) -> None:
# self.code = code
# self.message = message
# self.args = (code, message)
#
# class SMTPSenderRefused(SMTPResponseException):
# """
# SMTP server refused the message sender.
# """
#
# def __init__(self, code: int, message: str, sender: str) -> None:
# self.code = code
# self.message = message
# self.sender = sender
# self.args = (code, message, sender)
#
# class SMTPServerDisconnected(SMTPException, ConnectionError):
# """
# The connection was lost unexpectedly, or a command was run that requires
# a connection.
# """
#
# class SMTPTimeoutError(SMTPException, TimeoutError):
# """
# A timeout occurred while performing a network operation.
# """
. Output only the next line. | with pytest.raises(SMTPSenderRefused) as excinfo: |
Next line prediction: <|code_start|>"""
Test error class imports, arguments, and inheritance.
"""
@given(text())
def test_raise_smtp_exception(message):
with pytest.raises(SMTPException) as excinfo:
raise SMTPException(message)
assert excinfo.value.message == message
@given(integers(), text())
def test_raise_smtp_response_exception(code, message):
with pytest.raises(SMTPResponseException) as excinfo:
raise SMTPResponseException(code, message)
assert issubclass(excinfo.type, SMTPException)
assert excinfo.value.code == code
assert excinfo.value.message == message
@pytest.mark.parametrize(
<|code_end|>
. Use current file imports:
(import asyncio
import pytest
from hypothesis import given
from hypothesis.strategies import integers, lists, text
from aiosmtplib import (
SMTPAuthenticationError,
SMTPConnectError,
SMTPConnectTimeoutError,
SMTPDataError,
SMTPException,
SMTPHeloError,
SMTPNotSupported,
SMTPReadTimeoutError,
SMTPRecipientRefused,
SMTPRecipientsRefused,
SMTPResponseException,
SMTPSenderRefused,
SMTPServerDisconnected,
SMTPTimeoutError,
))
and context including class names, function names, or small code snippets from other files:
# Path: aiosmtplib/errors.py
# class SMTPAuthenticationError(SMTPResponseException):
# """
# Server refused our AUTH request; may be caused by invalid credentials.
# """
#
# class SMTPConnectError(SMTPException, ConnectionError):
# """
# An error occurred while connecting to the SMTP server.
# """
#
# class SMTPConnectTimeoutError(SMTPTimeoutError, SMTPConnectError):
# """
# A timeout occurred while connecting to the SMTP server.
# """
#
# class SMTPDataError(SMTPResponseException):
# """
# Server refused DATA content.
# """
#
# class SMTPException(Exception):
# """
# Base class for all SMTP exceptions.
# """
#
# def __init__(self, message: str) -> None:
# self.message = message
# self.args = (message,)
#
# class SMTPHeloError(SMTPResponseException):
# """
# Server refused HELO or EHLO.
# """
#
# class SMTPNotSupported(SMTPException):
# """
# A command or argument sent to the SMTP server is not supported.
# """
#
# class SMTPReadTimeoutError(SMTPTimeoutError):
# """
# A timeout occurred while waiting for a response from the SMTP server.
# """
#
# class SMTPRecipientRefused(SMTPResponseException):
# """
# SMTP server refused a message recipient.
# """
#
# def __init__(self, code: int, message: str, recipient: str) -> None:
# self.code = code
# self.message = message
# self.recipient = recipient
# self.args = (code, message, recipient)
#
# class SMTPRecipientsRefused(SMTPException):
# """
# SMTP server refused multiple recipients.
# """
#
# def __init__(self, recipients: List[SMTPRecipientRefused]) -> None:
# self.recipients = recipients
# self.args = (recipients,)
#
# class SMTPResponseException(SMTPException):
# """
# Base class for all server responses with error codes.
# """
#
# def __init__(self, code: int, message: str) -> None:
# self.code = code
# self.message = message
# self.args = (code, message)
#
# class SMTPSenderRefused(SMTPResponseException):
# """
# SMTP server refused the message sender.
# """
#
# def __init__(self, code: int, message: str, sender: str) -> None:
# self.code = code
# self.message = message
# self.sender = sender
# self.args = (code, message, sender)
#
# class SMTPServerDisconnected(SMTPException, ConnectionError):
# """
# The connection was lost unexpectedly, or a command was run that requires
# a connection.
# """
#
# class SMTPTimeoutError(SMTPException, TimeoutError):
# """
# A timeout occurred while performing a network operation.
# """
. Output only the next line. | "error_class", (SMTPServerDisconnected, SMTPConnectError, SMTPConnectTimeoutError) |
Given the following code snippet before the placeholder: <|code_start|> with pytest.raises(SMTPException) as excinfo:
raise SMTPException(message)
assert excinfo.value.message == message
@given(integers(), text())
def test_raise_smtp_response_exception(code, message):
with pytest.raises(SMTPResponseException) as excinfo:
raise SMTPResponseException(code, message)
assert issubclass(excinfo.type, SMTPException)
assert excinfo.value.code == code
assert excinfo.value.message == message
@pytest.mark.parametrize(
"error_class", (SMTPServerDisconnected, SMTPConnectError, SMTPConnectTimeoutError)
)
@given(message=text())
def test_connection_exceptions(message, error_class):
with pytest.raises(error_class) as excinfo:
raise error_class(message)
assert issubclass(excinfo.type, SMTPException)
assert issubclass(excinfo.type, ConnectionError)
assert excinfo.value.message == message
@pytest.mark.parametrize(
<|code_end|>
, predict the next line using imports from the current file:
import asyncio
import pytest
from hypothesis import given
from hypothesis.strategies import integers, lists, text
from aiosmtplib import (
SMTPAuthenticationError,
SMTPConnectError,
SMTPConnectTimeoutError,
SMTPDataError,
SMTPException,
SMTPHeloError,
SMTPNotSupported,
SMTPReadTimeoutError,
SMTPRecipientRefused,
SMTPRecipientsRefused,
SMTPResponseException,
SMTPSenderRefused,
SMTPServerDisconnected,
SMTPTimeoutError,
)
and context including class names, function names, and sometimes code from other files:
# Path: aiosmtplib/errors.py
# class SMTPAuthenticationError(SMTPResponseException):
# """
# Server refused our AUTH request; may be caused by invalid credentials.
# """
#
# class SMTPConnectError(SMTPException, ConnectionError):
# """
# An error occurred while connecting to the SMTP server.
# """
#
# class SMTPConnectTimeoutError(SMTPTimeoutError, SMTPConnectError):
# """
# A timeout occurred while connecting to the SMTP server.
# """
#
# class SMTPDataError(SMTPResponseException):
# """
# Server refused DATA content.
# """
#
# class SMTPException(Exception):
# """
# Base class for all SMTP exceptions.
# """
#
# def __init__(self, message: str) -> None:
# self.message = message
# self.args = (message,)
#
# class SMTPHeloError(SMTPResponseException):
# """
# Server refused HELO or EHLO.
# """
#
# class SMTPNotSupported(SMTPException):
# """
# A command or argument sent to the SMTP server is not supported.
# """
#
# class SMTPReadTimeoutError(SMTPTimeoutError):
# """
# A timeout occurred while waiting for a response from the SMTP server.
# """
#
# class SMTPRecipientRefused(SMTPResponseException):
# """
# SMTP server refused a message recipient.
# """
#
# def __init__(self, code: int, message: str, recipient: str) -> None:
# self.code = code
# self.message = message
# self.recipient = recipient
# self.args = (code, message, recipient)
#
# class SMTPRecipientsRefused(SMTPException):
# """
# SMTP server refused multiple recipients.
# """
#
# def __init__(self, recipients: List[SMTPRecipientRefused]) -> None:
# self.recipients = recipients
# self.args = (recipients,)
#
# class SMTPResponseException(SMTPException):
# """
# Base class for all server responses with error codes.
# """
#
# def __init__(self, code: int, message: str) -> None:
# self.code = code
# self.message = message
# self.args = (code, message)
#
# class SMTPSenderRefused(SMTPResponseException):
# """
# SMTP server refused the message sender.
# """
#
# def __init__(self, code: int, message: str, sender: str) -> None:
# self.code = code
# self.message = message
# self.sender = sender
# self.args = (code, message, sender)
#
# class SMTPServerDisconnected(SMTPException, ConnectionError):
# """
# The connection was lost unexpectedly, or a command was run that requires
# a connection.
# """
#
# class SMTPTimeoutError(SMTPException, TimeoutError):
# """
# A timeout occurred while performing a network operation.
# """
. Output only the next line. | "error_class", (SMTPTimeoutError, SMTPConnectTimeoutError, SMTPReadTimeoutError) |
Predict the next line for this snippet: <|code_start|> field_module = 'models'
django_kwargs = {}
if self.node_attrs['model'] == 'CharField':
django_kwargs['max_length'] = 255
django_kwargs['blank'] = not self.node_attrs['required']
try:
django_kwargs['default'] = self.node_attrs['value']
except KeyError:
pass
return u'{0} = {1}.{2}({3})'.format(self.node_attrs['name'], field_module, self.node_attrs['model'],
', '.join(['{0}={1}'.format(i,v) for i,v in six.iteritems(django_kwargs)]),)
class ArgParseNodeBuilder(object):
def __init__(self, script_path=None, script_name=None):
self.valid = False
self.error = ''
parsers = []
try:
module = imp.load_source(script_name, script_path)
except:
sys.stderr.write('Error while loading {0}:\n'.format(script_path))
self.error = '{0}\n'.format(traceback.format_exc())
sys.stderr.write(self.error)
else:
main_module = module.main.__globals__ if hasattr(module, 'main') else globals()
parsers = [v for i, v in chain(six.iteritems(main_module), six.iteritems(vars(module)))
if issubclass(type(v), argparse.ArgumentParser)]
if not parsers:
f = tempfile.NamedTemporaryFile()
<|code_end|>
with the help of current file imports:
import argparse
import sys
import json
import imp
import traceback
import tempfile
import six
import copy
import io
from collections import OrderedDict
from .ast import source_parser
from itertools import chain
and context from other files:
# Path: djangui/backend/ast/source_parser.py
# def parse_source_file(file_name):
# def read_client_module(filename):
# def get_node_args_and_keywords(assigned_objs, assignments, selector=None):
# def get_nodes_by_instance_type(nodes, object_type):
# def get_nodes_by_containing_attr(nodes, attr):
# def walk_tree(node):
# def convert_to_python(ast_source):
, which may contain function names, class names, or code. Output only the next line. | ast_source = source_parser.parse_source_file(script_path) |
Given snippet: <|code_start|> field_kwargs['initial'] = initial
field = getattr(forms, field)
return field(**field_kwargs)
def get_group_forms(self, model=None, pk=None, initial=None):
pk = int(pk) if pk is not None else pk
if pk is not None and pk in self.djangui_forms:
if 'groups' in self.djangui_forms[pk]:
return copy.deepcopy(self.djangui_forms[pk]['groups'])
params = ScriptParameter.objects.filter(script=model).order_by('pk')
# set a reference to the object type for POST methods to use
script_id_field = forms.CharField(widget=forms.HiddenInput)
group_map = {}
for param in params:
field = self.get_field(param, initial=initial.get(param.slug) if initial else None)
group_id = -1 if param.required else param.parameter_group.pk
group_name = 'Required' if param.required else param.parameter_group.group_name
group = group_map.get(group_id, {
'group': group_name,
'fields': OrderedDict()
})
group['fields'][param.slug] = field
group_map[group_id] = group
# create individual forms for each group
group_map = OrderedDict([(i, group_map[i]) for i in sorted(group_map.keys())])
d = {'action': model.get_url()}
d['groups'] = []
pk = model.pk
for group_index, group in enumerate(six.iteritems(group_map)):
group_pk, group_info = group
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import copy
import json
import six
from collections import OrderedDict
from django import forms
from .scripts import DjanguiForm
from ..backend import utils
from ..models import ScriptParameter
and context:
# Path: djangui/forms/scripts.py
# class DjanguiForm(forms.Form):
#
# def add_djangui_fields(self):
# # This adds fields such as job name, description that we like to validate on but don't want to include in
# # form rendering
# self.fields['job_name'] = forms.CharField()
# self.fields['job_description'] = forms.CharField(required=False)
#
# Path: djangui/backend/utils.py
# def sanitize_name(name):
# def sanitize_string(value):
# def get_storage(local=True):
# def get_job_commands(job=None):
# def create_djangui_job(user=None, script_pk=None, data=None):
# def get_master_form(model=None, pk=None):
# def get_form_groups(model=None, pk=None, initial=None):
# def validate_form(form=None, data=None, files=None):
# def load_scripts():
# def get_storage_object(path, local=False):
# def add_djangui_script(script=None, group=None):
# def valid_user(obj, user):
# def mkdirs(path):
# def get_file_info(filepath):
# def test_delimited(filepath):
# def test_fastx(filepath):
# def create_job_fileinfo(job):
# def get_file_previews(job):
# CHOICE_MAPPING = {
#
# }
which might include code, classes, or functions. Output only the next line. | form = DjanguiForm() |
Given snippet: <|code_start|>from __future__ import absolute_import
__author__ = 'chris'
class DjanguiFormFactory(object):
djangui_forms = {}
@staticmethod
def get_field(param, initial=None):
field = param.form_field
choices = json.loads(param.choices)
field_kwargs = {'label': param.script_param.title(),
'required': param.required,
'help_text': param.param_help,
}
if choices:
field = 'ChoiceField'
base_choices = [(None, '----')] if not param.required else []
field_kwargs['choices'] = base_choices+[(str(i), str(i).title()) for i in choices]
if field == 'FileField':
if param.is_output:
field = 'CharField'
initial = None
else:
if initial is not None:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import copy
import json
import six
from collections import OrderedDict
from django import forms
from .scripts import DjanguiForm
from ..backend import utils
from ..models import ScriptParameter
and context:
# Path: djangui/forms/scripts.py
# class DjanguiForm(forms.Form):
#
# def add_djangui_fields(self):
# # This adds fields such as job name, description that we like to validate on but don't want to include in
# # form rendering
# self.fields['job_name'] = forms.CharField()
# self.fields['job_description'] = forms.CharField(required=False)
#
# Path: djangui/backend/utils.py
# def sanitize_name(name):
# def sanitize_string(value):
# def get_storage(local=True):
# def get_job_commands(job=None):
# def create_djangui_job(user=None, script_pk=None, data=None):
# def get_master_form(model=None, pk=None):
# def get_form_groups(model=None, pk=None, initial=None):
# def validate_form(form=None, data=None, files=None):
# def load_scripts():
# def get_storage_object(path, local=False):
# def add_djangui_script(script=None, group=None):
# def valid_user(obj, user):
# def mkdirs(path):
# def get_file_info(filepath):
# def test_delimited(filepath):
# def test_fastx(filepath):
# def create_job_fileinfo(job):
# def get_file_previews(job):
# CHOICE_MAPPING = {
#
# }
which might include code, classes, or functions. Output only the next line. | initial = utils.get_storage_object(initial) if not hasattr(initial, 'path') else initial |
Based on the snippet: <|code_start|>from __future__ import absolute_import
__author__ = 'chris'
class DjanguiOutputFileField(models.FileField):
def formfield(self, **kwargs):
# TODO: Make this from an app that is plugged in
<|code_end|>
, predict the immediate next line with the help of imports:
from django.db import models
from ..forms import fields as djangui_form_fields
and context (classes, functions, sometimes code) from other files:
# Path: djangui/forms/fields.py
# class DjanguiOutputFileField(FileField):
# class DjanguiUploadFileField(FileField):
# def __init__(self, *args, **kwargs):
. Output only the next line. | defaults = {'form_class': djangui_form_fields.DjanguiOutputFileField} |
Predict the next line for this snippet: <|code_start|>
class FileCleanupMixin(object):
def tearDown(self):
for i in DjanguiFile.objects.all():
<|code_end|>
with the help of current file imports:
import shutil
from ..models import Script, DjanguiFile, DjanguiJob
from ..backend import utils
and context from other files:
# Path: djangui/backend/utils.py
# def sanitize_name(name):
# def sanitize_string(value):
# def get_storage(local=True):
# def get_job_commands(job=None):
# def create_djangui_job(user=None, script_pk=None, data=None):
# def get_master_form(model=None, pk=None):
# def get_form_groups(model=None, pk=None, initial=None):
# def validate_form(form=None, data=None, files=None):
# def load_scripts():
# def get_storage_object(path, local=False):
# def add_djangui_script(script=None, group=None):
# def valid_user(obj, user):
# def mkdirs(path):
# def get_file_info(filepath):
# def test_delimited(filepath):
# def test_fastx(filepath):
# def create_job_fileinfo(job):
# def get_file_previews(job):
# CHOICE_MAPPING = {
#
# }
, which may contain function names, class names, or code. Output only the next line. | utils.get_storage().delete(i.filepath.path) |
Given snippet: <|code_start|> A Corpus is built from a directory that contains the text files
that become `WitnessText` objects.
"""
def __init__(self, path, tokenizer):
self._logger = logging.getLogger(__name__)
self._path = os.path.abspath(path)
self._tokenizer = tokenizer
@property
def path(self):
"""Returns the absolute path to this corpus.
:rtype: `str`
"""
return self._path
def get_sigla(self, work):
"""Returns a list of all of the sigla for `work`.
:param work: name of work
:type work: `str`
:rtype: `list` of `str`
"""
return [os.path.splitext(os.path.basename(path))[0]
for path in glob.glob(os.path.join(self._path, work, '*.txt'))]
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import glob
import logging
import os
from .text import WitnessText
and context:
# Path: tacl/text.py
# class WitnessText (Text):
#
# """Class for the text of a witness. A witness has a work name and a
# siglum, and has a corresponding filename."""
#
# def __init__(self, work, siglum, content, tokenizer):
# super().__init__(content, tokenizer)
# self._work = work
# self._siglum = siglum
# self._filename = self.assemble_filename(work, siglum)
#
# @staticmethod
# def assemble_filename(work, siglum):
# return os.path.join(work, siglum + '.txt')
#
# def get_checksum(self):
# """Returns the checksum for the content of this text.
#
# :rtype: `str`
#
# """
# return hashlib.md5(self._content.encode('utf-8')).hexdigest()
#
# def get_filename(self):
# """Returns the filename of this text.
#
# :rtype: `str`
#
# """
# return self._filename
#
# @property
# def siglum(self):
# return self._siglum
#
# @property
# def work(self):
# return self._work
which might include code, classes, or functions. Output only the next line. | def get_witness(self, work, siglum, text_class=WitnessText): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.