Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the following code snippet before the placeholder: <|code_start|> max_list_size=1,
port=161,
timeout=DEFAULT_TIMEOUT,
version=Version.V2C,
):
# type: (str, str, List[str], List[str], int, int, int, int) -> BulkResult
# pylint: disable=unused-argument
"""
Delegates to :py:func:`~puresnmp.api.raw.mulkget` but returns simple
Python types.
See the "raw" equivalent for detailed documentation & examples.
"""
raw_output = raw.bulkget(
ip,
community,
scalar_oids,
repeating_oids,
max_list_size=max_list_size,
port=port,
timeout=timeout,
version=version,
)
pythonized_scalars = {
oid: value.pythonize() for oid, value in raw_output.scalars.items()
}
pythonized_list = OrderedDict(
[(oid, value.pythonize()) for oid, value in raw_output.listing.items()]
)
<|code_end|>
, predict the next line using imports from the current file:
import logging
from collections import OrderedDict
from datetime import timedelta
from typing import TYPE_CHECKING, Generator, List, TypeVar
from warnings import warn
from x690.types import ObjectIdentifier, Type # type: ignore
from ..const import DEFAULT_TIMEOUT, Version
from ..pdu import Trap
from ..snmp import VarBind
from ..util import BulkResult
from . import raw
from typing import Any, Callable, Dict, Tuple, Union
from puresnmp.typevars import PyType
and context including class names, function names, and sometimes code from other files:
# Path: puresnmp/const.py
# DEFAULT_TIMEOUT = 6
#
# class Version:
# """
# The SNMP Version identifier. This is used in the SNMP :term:`PDU`.
# """
#
# V2C = 0x01
# V1 = 0x00
#
# Path: puresnmp/pdu.py
# class Trap(PDU):
# """
# Represents an SNMP Trap
# """
#
# TAG = 7
#
# def __init__(self, *args, **kwargs):
# # type: (Any, Any) -> None
# super().__init__(*args, **kwargs)
# self.source = None # type: Optional[SocketInfo]
#
# Path: puresnmp/snmp.py
# class VarBind:
# """
# A "VarBind" is a 2-tuple containing an object-identifier and the
# corresponding value.
# """
#
# # TODO: This class should be split in two for both the raw and pythonic
# # API, that would simplify the typing of both "oid" and "value"a lot
# # and keep things explicit
# oid: ObjectIdentifier = ObjectIdentifier(0)
# value: Union[PyType, Type, None] = None
#
# def __init__(self, oid, value):
# # type: (Union[ObjectIdentifier, str], PyType) -> None
# if not isinstance(oid, (ObjectIdentifier, str)):
# raise TypeError(
# "OIDs for VarBinds must be ObjectIdentifier or str"
# " instances! Your value: %r" % oid
# )
# if isinstance(oid, str):
# oid = ObjectIdentifier.from_string(oid)
# self.oid = oid
# self.value = value
#
# def __iter__(self) -> Iterator[Union[ObjectIdentifier, PyType]]:
# return iter([self.oid, self.value])
#
# def __getitem__(self, idx: int) -> Union[PyType, Type, None]:
# return list(self)[idx]
#
# def __lt__(self, other):
# # type: (Any) -> bool
# return (self.oid, self.value) < (other.oid, other.value)
#
# def __eq__(self, other):
# # type: (Any) -> bool
# return (self.oid, self.value) == (other.oid, other.value)
#
# def __hash__(self):
# # type: () -> int
# return hash((self.oid, self.value))
#
# def __repr__(self):
# # type: () -> str
# return "VarBind(%r, %r)" % (self.oid, self.value)
#
# Path: puresnmp/util.py
# class BulkResult:
# """
# A representation for results of a "bulk" request.
#
# These requests get both "non-repeating values" (scalars) and "repeating
# values" (lists). This wrapper makes these terms a bit friendlier to use.
# """
#
# scalars: Dict[str, Any]
# listing: Dict[str, Any]
. Output only the next line. | return BulkResult(pythonized_scalars, pythonized_list) |
Given snippet: <|code_start|> Receive the data and close the connection.
"""
if LOG.isEnabledFor(logging.DEBUG) and isinstance(data, bytes):
hexdump = visible_octets(data)
LOG.debug("Received packet:\n%s", hexdump)
self.future.set_result(data)
if self.transport:
self.transport.close()
def error_received(self, exc):
# type: (Exception) -> None
"""
Pass the exception along if there is an error.
"""
if LOG.isEnabledFor(logging.DEBUG):
LOG.debug("Error received: %s", exc)
self.future.set_exception(exc)
async def get_data(self, timeout):
# type: (int) -> bytes
"""
Retrieve the response data back into the calling coroutine.
"""
try:
return await asyncio.wait_for(self.future, timeout, loop=self.loop)
except asyncio.TimeoutError as exc:
if self.transport:
self.transport.abort()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import asyncio
import logging
from asyncio.events import AbstractEventLoop
from typing import Optional, Tuple, Union
from x690.util import visible_octets # type: ignore
from ..exc import Timeout
from ..transport import Transport as SyncTransport
and context:
# Path: puresnmp/exc.py
# class Timeout(socket.timeout):
# """
# Wrapper for network timeouts.
#
# This wraps both "socket.timeout" and "asyncio.TimeoutError"
# """
#
# def __init__(self, message: str) -> None:
# super().__init__()
# self.message = message
#
# Path: puresnmp/transport.py
# class Transport:
# """
# A simple UDP transport.
#
# Calling ``send`` will attempt to send a packet as many times as specified
# in *retries* (default=3). If it fails after those attemps, a
# py:exc:`puresnmp.Timeout` exception is raised.
#
# :param timeout: How long to wait on the socket before retrying
# :param retries: The number of retries attempted if a low-level
# socket-timeout occurs. If set to ``None`` it will use
# :py:data:`puresnmp.transport.RETRIES` as default.
# :param buffer_size: How much data to read from the socket. If this is too
# small, it may result in incomplete (corrupt) packages. This should be
# kept as low as possible (see ``man(2) recv``). If set to ``None`` it
# will use :py:data:`puresnmp.transport.BUFFER_SIZE` as default.
# """
#
# def __init__(self, timeout=2, retries=None, buffer_size=None):
# # type: (int, Optional[int], Optional[int]) -> None
# self.timeout = timeout
# self.retries = retries or RETRIES
# self.buffer_size = buffer_size or BUFFER_SIZE
#
# def send(self, ip, port, packet, timeout=2): # pragma: no cover
# # type: ( str, int, bytes, int ) -> bytes
# """
# Opens a TCP connection to *ip:port*, sends a packet with *bytes* and
# returns the raw bytes as returned from the remote host.
# """
# checked_ip = ip_address(ip)
# if checked_ip.version == 4:
# address_family = socket.AF_INET
# else:
# address_family = socket.AF_INET6
#
# sock = socket.socket(address_family, socket.SOCK_DGRAM)
# sock.settimeout(timeout or self.timeout)
#
# for num_retry in range(self.retries):
# try:
# if LOG.isEnabledFor(logging.DEBUG):
# hexdump = visible_octets(packet)
# LOG.debug(
# "Sending packet to %s:%s (attempt %d/%d)\n%s",
# ip,
# port,
# (num_retry + 1),
# self.retries,
# hexdump,
# )
# sock.sendto(packet, (ip, port))
# response = sock.recv(self.buffer_size)
# break
# except socket.timeout:
# LOG.debug(
# "Timeout during attempt #%d", (num_retry + 1)
# ) # TODO add detail
# continue
# else:
# sock.close()
# raise Timeout("Max of %d retries reached" % self.retries)
# sock.close()
#
# if LOG.isEnabledFor(logging.DEBUG):
# hexdump = visible_octets(response)
# LOG.debug("Received packet:\n%s", hexdump)
#
# return response
#
# def listen(self, bind_address="0.0.0.0", port=162): # pragma: no cover
# # type: (str, int) -> Generator[SocketResponse, None, None]
# """
# Sets up a listening UDP socket and returns a generator over recevied
# packets::
#
# >>> transport = Transport()
# >>> for seq, packet in enumerate(transport.listen()):
# ... print(seq, repr(packet))
# 0, b'...'
# 1, b'...'
# 2, b'...'
#
# .. note::
#
# This defaults to the standard SNMP Trap port 162. This is a
# privileged port so processes using this port must run as root!
# """
# with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
# sock.bind((bind_address, port))
# while True:
# request, addr = sock.recvfrom(self.buffer_size)
# if LOG.isEnabledFor(logging.DEBUG):
# hexdump = visible_octets(request)
# LOG.debug("Received packet:\n%s", hexdump)
#
# yield SocketResponse(request, SocketInfo(addr[0], addr[1]))
#
# def get_request_id(self): # pragma: no cover
# # type: () -> int
# # pylint: disable=no-self-use
# """
# Generates a SNMP request ID. This value should be unique for each
# request.
# """
# # TODO check if this is good enough. My gut tells me "no"! Depends if
# # it has to be unique across all clients, or just one client. If it's
# # just one client it *may* be enough.
#
# return int(time())
which might include code, classes, or functions. Output only the next line. | raise Timeout(f"{timeout} second timeout exceeded") from exc |
Given the code snippet: <|code_start|> hexdump = visible_octets(data)
LOG.debug("Received packet:\n%s", hexdump)
self.future.set_result(data)
if self.transport:
self.transport.close()
def error_received(self, exc):
# type: (Exception) -> None
"""
Pass the exception along if there is an error.
"""
if LOG.isEnabledFor(logging.DEBUG):
LOG.debug("Error received: %s", exc)
self.future.set_exception(exc)
async def get_data(self, timeout):
# type: (int) -> bytes
"""
Retrieve the response data back into the calling coroutine.
"""
try:
return await asyncio.wait_for(self.future, timeout, loop=self.loop)
except asyncio.TimeoutError as exc:
if self.transport:
self.transport.abort()
raise Timeout(f"{timeout} second timeout exceeded") from exc
<|code_end|>
, generate the next line using the imports in this file:
import asyncio
import logging
from asyncio.events import AbstractEventLoop
from typing import Optional, Tuple, Union
from x690.util import visible_octets # type: ignore
from ..exc import Timeout
from ..transport import Transport as SyncTransport
and context (functions, classes, or occasionally code) from other files:
# Path: puresnmp/exc.py
# class Timeout(socket.timeout):
# """
# Wrapper for network timeouts.
#
# This wraps both "socket.timeout" and "asyncio.TimeoutError"
# """
#
# def __init__(self, message: str) -> None:
# super().__init__()
# self.message = message
#
# Path: puresnmp/transport.py
# class Transport:
# """
# A simple UDP transport.
#
# Calling ``send`` will attempt to send a packet as many times as specified
# in *retries* (default=3). If it fails after those attemps, a
# py:exc:`puresnmp.Timeout` exception is raised.
#
# :param timeout: How long to wait on the socket before retrying
# :param retries: The number of retries attempted if a low-level
# socket-timeout occurs. If set to ``None`` it will use
# :py:data:`puresnmp.transport.RETRIES` as default.
# :param buffer_size: How much data to read from the socket. If this is too
# small, it may result in incomplete (corrupt) packages. This should be
# kept as low as possible (see ``man(2) recv``). If set to ``None`` it
# will use :py:data:`puresnmp.transport.BUFFER_SIZE` as default.
# """
#
# def __init__(self, timeout=2, retries=None, buffer_size=None):
# # type: (int, Optional[int], Optional[int]) -> None
# self.timeout = timeout
# self.retries = retries or RETRIES
# self.buffer_size = buffer_size or BUFFER_SIZE
#
# def send(self, ip, port, packet, timeout=2): # pragma: no cover
# # type: ( str, int, bytes, int ) -> bytes
# """
# Opens a TCP connection to *ip:port*, sends a packet with *bytes* and
# returns the raw bytes as returned from the remote host.
# """
# checked_ip = ip_address(ip)
# if checked_ip.version == 4:
# address_family = socket.AF_INET
# else:
# address_family = socket.AF_INET6
#
# sock = socket.socket(address_family, socket.SOCK_DGRAM)
# sock.settimeout(timeout or self.timeout)
#
# for num_retry in range(self.retries):
# try:
# if LOG.isEnabledFor(logging.DEBUG):
# hexdump = visible_octets(packet)
# LOG.debug(
# "Sending packet to %s:%s (attempt %d/%d)\n%s",
# ip,
# port,
# (num_retry + 1),
# self.retries,
# hexdump,
# )
# sock.sendto(packet, (ip, port))
# response = sock.recv(self.buffer_size)
# break
# except socket.timeout:
# LOG.debug(
# "Timeout during attempt #%d", (num_retry + 1)
# ) # TODO add detail
# continue
# else:
# sock.close()
# raise Timeout("Max of %d retries reached" % self.retries)
# sock.close()
#
# if LOG.isEnabledFor(logging.DEBUG):
# hexdump = visible_octets(response)
# LOG.debug("Received packet:\n%s", hexdump)
#
# return response
#
# def listen(self, bind_address="0.0.0.0", port=162): # pragma: no cover
# # type: (str, int) -> Generator[SocketResponse, None, None]
# """
# Sets up a listening UDP socket and returns a generator over recevied
# packets::
#
# >>> transport = Transport()
# >>> for seq, packet in enumerate(transport.listen()):
# ... print(seq, repr(packet))
# 0, b'...'
# 1, b'...'
# 2, b'...'
#
# .. note::
#
# This defaults to the standard SNMP Trap port 162. This is a
# privileged port so processes using this port must run as root!
# """
# with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
# sock.bind((bind_address, port))
# while True:
# request, addr = sock.recvfrom(self.buffer_size)
# if LOG.isEnabledFor(logging.DEBUG):
# hexdump = visible_octets(request)
# LOG.debug("Received packet:\n%s", hexdump)
#
# yield SocketResponse(request, SocketInfo(addr[0], addr[1]))
#
# def get_request_id(self): # pragma: no cover
# # type: () -> int
# # pylint: disable=no-self-use
# """
# Generates a SNMP request ID. This value should be unique for each
# request.
# """
# # TODO check if this is good enough. My gut tells me "no"! Depends if
# # it has to be unique across all clients, or just one client. If it's
# # just one client it *may* be enough.
#
# return int(time())
. Output only the next line. | class Transport(SyncTransport): |
Using the snippet: <|code_start|>"""
Unit-tests for utility functions
"""
OID = ObjectIdentifier.from_string
def test_group_varbinds():
"""
"group_varbinds" should convert an interleaved list of OIDs into a more
usable dictionary.
"""
varbinds = [
<|code_end|>
, determine the next line of code. You have imports:
from x690.types import Null, ObjectIdentifier
from puresnmp.pdu import VarBind
from puresnmp.util import WalkRow, get_unfinished_walk_oids, group_varbinds
and context (class names, function names, or code) available:
# Path: puresnmp/pdu.py
# class PDU(Type): # type: ignore
# class EndOfMibView(PDU):
# class GetRequest(PDU):
# class GetResponse(PDU):
# class GetNextRequest(GetRequest):
# class SetRequest(PDU):
# class BulkGetRequest(Type): # type: ignore
# class InformRequest(PDU):
# class Trap(PDU):
# TYPECLASS = TypeInfo.CONTEXT
# TAG = 0
# END_OF_MIB_VIEW = EndOfMibView()
# TAG = 0
# TAG = 2
# TAG = 1
# TAG = 3
# TYPECLASS = TypeInfo.CONTEXT
# TAG = 5
# TAG = 6
# TAG = 7
# def decode(cls, data: bytes) -> "PDU":
# def __init__(
# self,
# request_id: int,
# varbinds: Union[VarBind, List[VarBind]],
# error_status: int = 0,
# error_index: int = 0,
# ) -> None:
# def __bytes__(self) -> bytes:
# def __repr__(self) -> str:
# def __eq__(self, other: Any) -> bool:
# def pretty(self) -> str: # pragma: no cover
# def __init__(self) -> None:
# def __init__(
# self, request_id: int, *oids: Union[str, ObjectIdentifier]
# ) -> None:
# def decode(cls, data):
# def __init__(self, request_id, non_repeaters, max_repeaters, *oids):
# def __bytes__(self) -> bytes:
# def __repr__(self):
# def __eq__(self, other):
# def pretty(self): # pragma: no cover
# def __init__(self, *args, **kwargs):
#
# Path: puresnmp/util.py
# class WalkRow:
# """
# A wrapper around an SNMP Walk item.
#
# This also keeps track whether this walk result should be considered the
# last row or not.
# """
#
# value: Any
# unfinished: bool
#
# def get_unfinished_walk_oids(grouped_oids):
# # type: (Dict[ObjectIdentifier, List[VarBind]]) -> List[Tuple[ObjectIdentifier, WalkRow]]
# """
# :param grouped_oids: A dictionary containing VarBinds as values. The keys
# are the base OID of those VarBinds as requested by the user. We need to
# keep track of the base to be able to tell when a walk over OIDs is
# finished (that is, when we hit the first OID outside the base).
# """
#
# # grouped_oids contains a list of values for each requested OID. We need to
# # determine if we need to continue fetching: Inspect the last item of each
# # list if those OIDs are still children of the requested IDs we need to
# # continue fetching using *those* IDs (as we're using GetNext behaviour).
# # If they are *not* children of the requested OIDs, we went too far (in the
# # case of a bulk operation) and need to remove all outliers.
# #
# # The above behaviour is the same for both bulk and simple operations. For
# # simple operations we simply have a list of 1 element per OID, but the
# # behaviour is identical
#
# # Build a mapping from the originally requested OID to the last fetched OID
# # from that tree.
# last_received_oids = {
# k: WalkRow(v[-1], v[-1].oid in k) for k, v in grouped_oids.items() if v
# }
#
# output = [
# item
# for item in sorted(last_received_oids.items())
# if item[1].unfinished
# ]
# return output
#
# def group_varbinds(varbinds, effective_roots, user_roots=None):
# # type: (List[VarBind], List[ObjectIdentifier], Optional[List[ObjectIdentifier]]) -> Dict[ObjectIdentifier, List[VarBind]]
# """
# Takes a list of varbinds and a list of base OIDs and returns a mapping from
# those base IDs to lists of varbinds.
#
# Varbinds returned from a walk operation which targets multiple OIDs is
# returned as "interleaved" list. This functions extracts these interleaved
# items into a more usable dictionary.
#
# :param varbinds: A list of VarBind instances.
# :param effective_roots: The list of OIDs that were requested from the SNMP
# agent.
# :param user_roots: The set of VarBind instances that were requested by the
# user. This is used internally for walk requests. On each request
# following the first, the requested OIDs will differ from the OIDs
# requested by the user. This list will keep track of the original OIDs
# to determine when the walk needs to terminate.
# """
# user_roots = user_roots or []
# n = len(effective_roots)
#
# results = {}
# for i in range(n):
# results[effective_roots[i]] = varbinds[i::n]
#
# if user_roots:
# new_results = {}
# for key, value in results.items():
# containment = [base for base in user_roots if key in base]
# if len(containment) > 1:
# raise RuntimeError(
# "Unexpected OID result. A value was "
# "contained in more than one base than "
# "should be possible!"
# )
# if not containment:
# continue
# new_results[containment[0]] = value
# results = new_results
#
# return results
. Output only the next line. | VarBind(OID("1.1.1"), Null()), |
Given the following code snippet before the placeholder: <|code_start|> VarBind(OID("3.3.1"), Null()),
VarBind(OID("3.3.2"), Null()),
VarBind(OID("3.3.3"), Null()),
],
}
assert result == expected
def test_get_unfinished_walk_oids():
"""
Using get_unfinished_walk_oids should tell us which OIDs are not yet
completed in the existing OID groups (by looking at the OIDs)
"""
oid_groups = {
OID("1.1"): [
VarBind(OID("1.1.1"), Null()),
VarBind(OID("1.1.2"), Null()),
],
OID("2.2"): [
VarBind(OID("2.2.1"), Null()),
VarBind(OID("2.2.2"), Null()),
],
OID("3.3"): [
VarBind(OID("3.3.1"), Null()),
VarBind(OID("3.4.2"), Null()),
],
}
result = get_unfinished_walk_oids(oid_groups)
expected = [
<|code_end|>
, predict the next line using imports from the current file:
from x690.types import Null, ObjectIdentifier
from puresnmp.pdu import VarBind
from puresnmp.util import WalkRow, get_unfinished_walk_oids, group_varbinds
and context including class names, function names, and sometimes code from other files:
# Path: puresnmp/pdu.py
# class PDU(Type): # type: ignore
# class EndOfMibView(PDU):
# class GetRequest(PDU):
# class GetResponse(PDU):
# class GetNextRequest(GetRequest):
# class SetRequest(PDU):
# class BulkGetRequest(Type): # type: ignore
# class InformRequest(PDU):
# class Trap(PDU):
# TYPECLASS = TypeInfo.CONTEXT
# TAG = 0
# END_OF_MIB_VIEW = EndOfMibView()
# TAG = 0
# TAG = 2
# TAG = 1
# TAG = 3
# TYPECLASS = TypeInfo.CONTEXT
# TAG = 5
# TAG = 6
# TAG = 7
# def decode(cls, data: bytes) -> "PDU":
# def __init__(
# self,
# request_id: int,
# varbinds: Union[VarBind, List[VarBind]],
# error_status: int = 0,
# error_index: int = 0,
# ) -> None:
# def __bytes__(self) -> bytes:
# def __repr__(self) -> str:
# def __eq__(self, other: Any) -> bool:
# def pretty(self) -> str: # pragma: no cover
# def __init__(self) -> None:
# def __init__(
# self, request_id: int, *oids: Union[str, ObjectIdentifier]
# ) -> None:
# def decode(cls, data):
# def __init__(self, request_id, non_repeaters, max_repeaters, *oids):
# def __bytes__(self) -> bytes:
# def __repr__(self):
# def __eq__(self, other):
# def pretty(self): # pragma: no cover
# def __init__(self, *args, **kwargs):
#
# Path: puresnmp/util.py
# class WalkRow:
# """
# A wrapper around an SNMP Walk item.
#
# This also keeps track whether this walk result should be considered the
# last row or not.
# """
#
# value: Any
# unfinished: bool
#
# def get_unfinished_walk_oids(grouped_oids):
# # type: (Dict[ObjectIdentifier, List[VarBind]]) -> List[Tuple[ObjectIdentifier, WalkRow]]
# """
# :param grouped_oids: A dictionary containing VarBinds as values. The keys
# are the base OID of those VarBinds as requested by the user. We need to
# keep track of the base to be able to tell when a walk over OIDs is
# finished (that is, when we hit the first OID outside the base).
# """
#
# # grouped_oids contains a list of values for each requested OID. We need to
# # determine if we need to continue fetching: Inspect the last item of each
# # list if those OIDs are still children of the requested IDs we need to
# # continue fetching using *those* IDs (as we're using GetNext behaviour).
# # If they are *not* children of the requested OIDs, we went too far (in the
# # case of a bulk operation) and need to remove all outliers.
# #
# # The above behaviour is the same for both bulk and simple operations. For
# # simple operations we simply have a list of 1 element per OID, but the
# # behaviour is identical
#
# # Build a mapping from the originally requested OID to the last fetched OID
# # from that tree.
# last_received_oids = {
# k: WalkRow(v[-1], v[-1].oid in k) for k, v in grouped_oids.items() if v
# }
#
# output = [
# item
# for item in sorted(last_received_oids.items())
# if item[1].unfinished
# ]
# return output
#
# def group_varbinds(varbinds, effective_roots, user_roots=None):
# # type: (List[VarBind], List[ObjectIdentifier], Optional[List[ObjectIdentifier]]) -> Dict[ObjectIdentifier, List[VarBind]]
# """
# Takes a list of varbinds and a list of base OIDs and returns a mapping from
# those base IDs to lists of varbinds.
#
# Varbinds returned from a walk operation which targets multiple OIDs is
# returned as "interleaved" list. This functions extracts these interleaved
# items into a more usable dictionary.
#
# :param varbinds: A list of VarBind instances.
# :param effective_roots: The list of OIDs that were requested from the SNMP
# agent.
# :param user_roots: The set of VarBind instances that were requested by the
# user. This is used internally for walk requests. On each request
# following the first, the requested OIDs will differ from the OIDs
# requested by the user. This list will keep track of the original OIDs
# to determine when the walk needs to terminate.
# """
# user_roots = user_roots or []
# n = len(effective_roots)
#
# results = {}
# for i in range(n):
# results[effective_roots[i]] = varbinds[i::n]
#
# if user_roots:
# new_results = {}
# for key, value in results.items():
# containment = [base for base in user_roots if key in base]
# if len(containment) > 1:
# raise RuntimeError(
# "Unexpected OID result. A value was "
# "contained in more than one base than "
# "should be possible!"
# )
# if not containment:
# continue
# new_results[containment[0]] = value
# results = new_results
#
# return results
. Output only the next line. | (OID("1.1"), WalkRow(VarBind(OID("1.1.2"), Null()), unfinished=True)), |
Predict the next line after this snippet: <|code_start|> ],
OID("3.3"): [
VarBind(OID("3.3.1"), Null()),
VarBind(OID("3.3.2"), Null()),
VarBind(OID("3.3.3"), Null()),
],
}
assert result == expected
def test_get_unfinished_walk_oids():
"""
Using get_unfinished_walk_oids should tell us which OIDs are not yet
completed in the existing OID groups (by looking at the OIDs)
"""
oid_groups = {
OID("1.1"): [
VarBind(OID("1.1.1"), Null()),
VarBind(OID("1.1.2"), Null()),
],
OID("2.2"): [
VarBind(OID("2.2.1"), Null()),
VarBind(OID("2.2.2"), Null()),
],
OID("3.3"): [
VarBind(OID("3.3.1"), Null()),
VarBind(OID("3.4.2"), Null()),
],
}
<|code_end|>
using the current file's imports:
from x690.types import Null, ObjectIdentifier
from puresnmp.pdu import VarBind
from puresnmp.util import WalkRow, get_unfinished_walk_oids, group_varbinds
and any relevant context from other files:
# Path: puresnmp/pdu.py
# class PDU(Type): # type: ignore
# class EndOfMibView(PDU):
# class GetRequest(PDU):
# class GetResponse(PDU):
# class GetNextRequest(GetRequest):
# class SetRequest(PDU):
# class BulkGetRequest(Type): # type: ignore
# class InformRequest(PDU):
# class Trap(PDU):
# TYPECLASS = TypeInfo.CONTEXT
# TAG = 0
# END_OF_MIB_VIEW = EndOfMibView()
# TAG = 0
# TAG = 2
# TAG = 1
# TAG = 3
# TYPECLASS = TypeInfo.CONTEXT
# TAG = 5
# TAG = 6
# TAG = 7
# def decode(cls, data: bytes) -> "PDU":
# def __init__(
# self,
# request_id: int,
# varbinds: Union[VarBind, List[VarBind]],
# error_status: int = 0,
# error_index: int = 0,
# ) -> None:
# def __bytes__(self) -> bytes:
# def __repr__(self) -> str:
# def __eq__(self, other: Any) -> bool:
# def pretty(self) -> str: # pragma: no cover
# def __init__(self) -> None:
# def __init__(
# self, request_id: int, *oids: Union[str, ObjectIdentifier]
# ) -> None:
# def decode(cls, data):
# def __init__(self, request_id, non_repeaters, max_repeaters, *oids):
# def __bytes__(self) -> bytes:
# def __repr__(self):
# def __eq__(self, other):
# def pretty(self): # pragma: no cover
# def __init__(self, *args, **kwargs):
#
# Path: puresnmp/util.py
# class WalkRow:
# """
# A wrapper around an SNMP Walk item.
#
# This also keeps track whether this walk result should be considered the
# last row or not.
# """
#
# value: Any
# unfinished: bool
#
# def get_unfinished_walk_oids(grouped_oids):
# # type: (Dict[ObjectIdentifier, List[VarBind]]) -> List[Tuple[ObjectIdentifier, WalkRow]]
# """
# :param grouped_oids: A dictionary containing VarBinds as values. The keys
# are the base OID of those VarBinds as requested by the user. We need to
# keep track of the base to be able to tell when a walk over OIDs is
# finished (that is, when we hit the first OID outside the base).
# """
#
# # grouped_oids contains a list of values for each requested OID. We need to
# # determine if we need to continue fetching: Inspect the last item of each
# # list if those OIDs are still children of the requested IDs we need to
# # continue fetching using *those* IDs (as we're using GetNext behaviour).
# # If they are *not* children of the requested OIDs, we went too far (in the
# # case of a bulk operation) and need to remove all outliers.
# #
# # The above behaviour is the same for both bulk and simple operations. For
# # simple operations we simply have a list of 1 element per OID, but the
# # behaviour is identical
#
# # Build a mapping from the originally requested OID to the last fetched OID
# # from that tree.
# last_received_oids = {
# k: WalkRow(v[-1], v[-1].oid in k) for k, v in grouped_oids.items() if v
# }
#
# output = [
# item
# for item in sorted(last_received_oids.items())
# if item[1].unfinished
# ]
# return output
#
# def group_varbinds(varbinds, effective_roots, user_roots=None):
# # type: (List[VarBind], List[ObjectIdentifier], Optional[List[ObjectIdentifier]]) -> Dict[ObjectIdentifier, List[VarBind]]
# """
# Takes a list of varbinds and a list of base OIDs and returns a mapping from
# those base IDs to lists of varbinds.
#
# Varbinds returned from a walk operation which targets multiple OIDs is
# returned as "interleaved" list. This functions extracts these interleaved
# items into a more usable dictionary.
#
# :param varbinds: A list of VarBind instances.
# :param effective_roots: The list of OIDs that were requested from the SNMP
# agent.
# :param user_roots: The set of VarBind instances that were requested by the
# user. This is used internally for walk requests. On each request
# following the first, the requested OIDs will differ from the OIDs
# requested by the user. This list will keep track of the original OIDs
# to determine when the walk needs to terminate.
# """
# user_roots = user_roots or []
# n = len(effective_roots)
#
# results = {}
# for i in range(n):
# results[effective_roots[i]] = varbinds[i::n]
#
# if user_roots:
# new_results = {}
# for key, value in results.items():
# containment = [base for base in user_roots if key in base]
# if len(containment) > 1:
# raise RuntimeError(
# "Unexpected OID result. A value was "
# "contained in more than one base than "
# "should be possible!"
# )
# if not containment:
# continue
# new_results[containment[0]] = value
# results = new_results
#
# return results
. Output only the next line. | result = get_unfinished_walk_oids(oid_groups) |
Given the following code snippet before the placeholder: <|code_start|>"""
Unit-tests for utility functions
"""
OID = ObjectIdentifier.from_string
def test_group_varbinds():
"""
"group_varbinds" should convert an interleaved list of OIDs into a more
usable dictionary.
"""
varbinds = [
VarBind(OID("1.1.1"), Null()),
VarBind(OID("2.2.1"), Null()),
VarBind(OID("3.3.1"), Null()),
VarBind(OID("1.1.2"), Null()),
VarBind(OID("2.2.2"), Null()),
VarBind(OID("3.3.2"), Null()),
VarBind(OID("1.1.3"), Null()),
VarBind(OID("2.2.3"), Null()),
VarBind(OID("3.3.3"), Null()),
]
effective_roots = [
OID("1.1"),
OID("2.2"),
OID("3.3"),
]
<|code_end|>
, predict the next line using imports from the current file:
from x690.types import Null, ObjectIdentifier
from puresnmp.pdu import VarBind
from puresnmp.util import WalkRow, get_unfinished_walk_oids, group_varbinds
and context including class names, function names, and sometimes code from other files:
# Path: puresnmp/pdu.py
# class PDU(Type): # type: ignore
# class EndOfMibView(PDU):
# class GetRequest(PDU):
# class GetResponse(PDU):
# class GetNextRequest(GetRequest):
# class SetRequest(PDU):
# class BulkGetRequest(Type): # type: ignore
# class InformRequest(PDU):
# class Trap(PDU):
# TYPECLASS = TypeInfo.CONTEXT
# TAG = 0
# END_OF_MIB_VIEW = EndOfMibView()
# TAG = 0
# TAG = 2
# TAG = 1
# TAG = 3
# TYPECLASS = TypeInfo.CONTEXT
# TAG = 5
# TAG = 6
# TAG = 7
# def decode(cls, data: bytes) -> "PDU":
# def __init__(
# self,
# request_id: int,
# varbinds: Union[VarBind, List[VarBind]],
# error_status: int = 0,
# error_index: int = 0,
# ) -> None:
# def __bytes__(self) -> bytes:
# def __repr__(self) -> str:
# def __eq__(self, other: Any) -> bool:
# def pretty(self) -> str: # pragma: no cover
# def __init__(self) -> None:
# def __init__(
# self, request_id: int, *oids: Union[str, ObjectIdentifier]
# ) -> None:
# def decode(cls, data):
# def __init__(self, request_id, non_repeaters, max_repeaters, *oids):
# def __bytes__(self) -> bytes:
# def __repr__(self):
# def __eq__(self, other):
# def pretty(self): # pragma: no cover
# def __init__(self, *args, **kwargs):
#
# Path: puresnmp/util.py
# class WalkRow:
# """
# A wrapper around an SNMP Walk item.
#
# This also keeps track whether this walk result should be considered the
# last row or not.
# """
#
# value: Any
# unfinished: bool
#
# def get_unfinished_walk_oids(grouped_oids):
# # type: (Dict[ObjectIdentifier, List[VarBind]]) -> List[Tuple[ObjectIdentifier, WalkRow]]
# """
# :param grouped_oids: A dictionary containing VarBinds as values. The keys
# are the base OID of those VarBinds as requested by the user. We need to
# keep track of the base to be able to tell when a walk over OIDs is
# finished (that is, when we hit the first OID outside the base).
# """
#
# # grouped_oids contains a list of values for each requested OID. We need to
# # determine if we need to continue fetching: Inspect the last item of each
# # list if those OIDs are still children of the requested IDs we need to
# # continue fetching using *those* IDs (as we're using GetNext behaviour).
# # If they are *not* children of the requested OIDs, we went too far (in the
# # case of a bulk operation) and need to remove all outliers.
# #
# # The above behaviour is the same for both bulk and simple operations. For
# # simple operations we simply have a list of 1 element per OID, but the
# # behaviour is identical
#
# # Build a mapping from the originally requested OID to the last fetched OID
# # from that tree.
# last_received_oids = {
# k: WalkRow(v[-1], v[-1].oid in k) for k, v in grouped_oids.items() if v
# }
#
# output = [
# item
# for item in sorted(last_received_oids.items())
# if item[1].unfinished
# ]
# return output
#
# def group_varbinds(varbinds, effective_roots, user_roots=None):
# # type: (List[VarBind], List[ObjectIdentifier], Optional[List[ObjectIdentifier]]) -> Dict[ObjectIdentifier, List[VarBind]]
# """
# Takes a list of varbinds and a list of base OIDs and returns a mapping from
# those base IDs to lists of varbinds.
#
# Varbinds returned from a walk operation which targets multiple OIDs is
# returned as "interleaved" list. This functions extracts these interleaved
# items into a more usable dictionary.
#
# :param varbinds: A list of VarBind instances.
# :param effective_roots: The list of OIDs that were requested from the SNMP
# agent.
# :param user_roots: The set of VarBind instances that were requested by the
# user. This is used internally for walk requests. On each request
# following the first, the requested OIDs will differ from the OIDs
# requested by the user. This list will keep track of the original OIDs
# to determine when the walk needs to terminate.
# """
# user_roots = user_roots or []
# n = len(effective_roots)
#
# results = {}
# for i in range(n):
# results[effective_roots[i]] = varbinds[i::n]
#
# if user_roots:
# new_results = {}
# for key, value in results.items():
# containment = [base for base in user_roots if key in base]
# if len(containment) > 1:
# raise RuntimeError(
# "Unexpected OID result. A value was "
# "contained in more than one base than "
# "should be possible!"
# )
# if not containment:
# continue
# new_results[containment[0]] = value
# results = new_results
#
# return results
. Output only the next line. | result = group_varbinds(varbinds, effective_roots) |
Given the following code snippet before the placeholder: <|code_start|> if checked_ip.version == 4:
address_family = socket.AF_INET
else:
address_family = socket.AF_INET6
sock = socket.socket(address_family, socket.SOCK_DGRAM)
sock.settimeout(timeout or self.timeout)
for num_retry in range(self.retries):
try:
if LOG.isEnabledFor(logging.DEBUG):
hexdump = visible_octets(packet)
LOG.debug(
"Sending packet to %s:%s (attempt %d/%d)\n%s",
ip,
port,
(num_retry + 1),
self.retries,
hexdump,
)
sock.sendto(packet, (ip, port))
response = sock.recv(self.buffer_size)
break
except socket.timeout:
LOG.debug(
"Timeout during attempt #%d", (num_retry + 1)
) # TODO add detail
continue
else:
sock.close()
<|code_end|>
, predict the next line using imports from the current file:
import logging
import socket
from ipaddress import ip_address
from time import time
from typing import TYPE_CHECKING, Generator
from x690.util import visible_octets # type: ignore
from .exc import Timeout
from .typevars import SocketInfo, SocketResponse
from typing import Optional
and context including class names, function names, and sometimes code from other files:
# Path: puresnmp/exc.py
# class Timeout(socket.timeout):
# """
# Wrapper for network timeouts.
#
# This wraps both "socket.timeout" and "asyncio.TimeoutError"
# """
#
# def __init__(self, message: str) -> None:
# super().__init__()
# self.message = message
#
# Path: puresnmp/typevars.py
# class SocketInfo:
# """
# A simple tuple containing an IP address and port number
# """
#
# address: str
# port: int
#
# class SocketResponse:
# """
# Metadata for socket responses
# """
#
# data: bytes
# info: SocketInfo
. Output only the next line. | raise Timeout("Max of %d retries reached" % self.retries) |
Given snippet: <|code_start|> LOG.debug("Received packet:\n%s", hexdump)
return response
def listen(self, bind_address="0.0.0.0", port=162): # pragma: no cover
# type: (str, int) -> Generator[SocketResponse, None, None]
"""
Sets up a listening UDP socket and returns a generator over recevied
packets::
>>> transport = Transport()
>>> for seq, packet in enumerate(transport.listen()):
... print(seq, repr(packet))
0, b'...'
1, b'...'
2, b'...'
.. note::
This defaults to the standard SNMP Trap port 162. This is a
privileged port so processes using this port must run as root!
"""
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.bind((bind_address, port))
while True:
request, addr = sock.recvfrom(self.buffer_size)
if LOG.isEnabledFor(logging.DEBUG):
hexdump = visible_octets(request)
LOG.debug("Received packet:\n%s", hexdump)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
import socket
from ipaddress import ip_address
from time import time
from typing import TYPE_CHECKING, Generator
from x690.util import visible_octets # type: ignore
from .exc import Timeout
from .typevars import SocketInfo, SocketResponse
from typing import Optional
and context:
# Path: puresnmp/exc.py
# class Timeout(socket.timeout):
# """
# Wrapper for network timeouts.
#
# This wraps both "socket.timeout" and "asyncio.TimeoutError"
# """
#
# def __init__(self, message: str) -> None:
# super().__init__()
# self.message = message
#
# Path: puresnmp/typevars.py
# class SocketInfo:
# """
# A simple tuple containing an IP address and port number
# """
#
# address: str
# port: int
#
# class SocketResponse:
# """
# Metadata for socket responses
# """
#
# data: bytes
# info: SocketInfo
which might include code, classes, or functions. Output only the next line. | yield SocketResponse(request, SocketInfo(addr[0], addr[1])) |
Given snippet: <|code_start|> LOG.debug("Received packet:\n%s", hexdump)
return response
def listen(self, bind_address="0.0.0.0", port=162): # pragma: no cover
# type: (str, int) -> Generator[SocketResponse, None, None]
"""
Sets up a listening UDP socket and returns a generator over recevied
packets::
>>> transport = Transport()
>>> for seq, packet in enumerate(transport.listen()):
... print(seq, repr(packet))
0, b'...'
1, b'...'
2, b'...'
.. note::
This defaults to the standard SNMP Trap port 162. This is a
privileged port so processes using this port must run as root!
"""
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.bind((bind_address, port))
while True:
request, addr = sock.recvfrom(self.buffer_size)
if LOG.isEnabledFor(logging.DEBUG):
hexdump = visible_octets(request)
LOG.debug("Received packet:\n%s", hexdump)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
import socket
from ipaddress import ip_address
from time import time
from typing import TYPE_CHECKING, Generator
from x690.util import visible_octets # type: ignore
from .exc import Timeout
from .typevars import SocketInfo, SocketResponse
from typing import Optional
and context:
# Path: puresnmp/exc.py
# class Timeout(socket.timeout):
# """
# Wrapper for network timeouts.
#
# This wraps both "socket.timeout" and "asyncio.TimeoutError"
# """
#
# def __init__(self, message: str) -> None:
# super().__init__()
# self.message = message
#
# Path: puresnmp/typevars.py
# class SocketInfo:
# """
# A simple tuple containing an IP address and port number
# """
#
# address: str
# port: int
#
# class SocketResponse:
# """
# Metadata for socket responses
# """
#
# data: bytes
# info: SocketInfo
which might include code, classes, or functions. Output only the next line. | yield SocketResponse(request, SocketInfo(addr[0], addr[1])) |
Next line prediction: <|code_start|>class GenErr(ErrorResponse):
"""
This error is returned for any error which is not covered in the previous
error classes.
"""
DEFAULT_MESSAGE = "General Error (genErr)"
def __init__(self, offending_oid, message=""):
# type: (Optional[ObjectIdentifier], str) -> None
super().__init__(5, offending_oid, message)
class EmptyMessage(SnmpError):
"""
Raised when trying to decode an SNMP-Message with no content.
"""
class TooManyVarbinds(SnmpError):
"""
Exception which is raised when the number of VarBinds exceeds the limit
defined in RFC3416.
device.
"""
def __init__(self, num_oids):
# type: (int) -> None
super().__init__(
"Too many VarBinds (%d) in one request!"
<|code_end|>
. Use current file imports:
(import socket
from typing import Optional
from x690.types import ObjectIdentifier # type: ignore
from puresnmp.const import MAX_VARBINDS)
and context including class names, function names, or small code snippets from other files:
# Path: puresnmp/const.py
# MAX_VARBINDS = 2147483647
. Output only the next line. | " RFC3416 limits requests to %d!" % (num_oids, MAX_VARBINDS) |
Predict the next line for this snippet: <|code_start|># Copyright 2017 The TensorFlow Agents Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for the attribute dictionary."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class AttrDictTest(tf.test.TestCase):
def test_construct_from_dict(self):
initial = dict(foo=13, bar=42)
<|code_end|>
with the help of current file imports:
import tensorflow as tf
from agents.tools import attr_dict
and context from other files:
# Path: agents/tools/attr_dict.py
# class AttrDict(dict):
# def __init__(self, *args, **kwargs):
# def __getattr__(self, key):
# def __setattr__(self, key, value):
# def unlocked(self):
# def copy(self):
, which may contain function names, class names, or code. Output only the next line. | obj = attr_dict.AttrDict(initial) |
Given snippet: <|code_start|># Copyright 2017 The TensorFlow Agents Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for the weight counting utility."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class CountWeightsTest(tf.test.TestCase):
def test_count_trainable(self):
tf.Variable(tf.zeros((5, 3)), trainable=True)
tf.Variable(tf.zeros((1, 1)), trainable=True)
tf.Variable(tf.zeros((5,)), trainable=True)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import tensorflow as tf
from agents.tools import count_weights
and context:
# Path: agents/tools/count_weights.py
# def count_weights(scope=None, exclude=None, graph=None):
# """Count learnable parameters.
#
# Args:
# scope: Restrict the count to a variable scope.
# exclude: Regex to match variable names to exclude.
# graph: Operate on a graph other than the current default graph.
#
# Returns:
# Number of learnable parameters as integer.
# """
# if scope:
# scope = scope if scope.endswith('/') else scope + '/'
# graph = graph or tf.get_default_graph()
# vars_ = graph.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)
# if scope:
# vars_ = [var for var in vars_ if var.name.startswith(scope)]
# if exclude:
# exclude = re.compile(exclude)
# vars_ = [var for var in vars_ if not exclude.match(var.name)]
# shapes = [var.get_shape().as_list() for var in vars_]
# return int(sum(np.prod(shape) for shape in shapes))
which might include code, classes, or functions. Output only the next line. | self.assertEqual(15 + 1 + 5, count_weights()) |
Given the code snippet: <|code_start|># Copyright 2017 The TensorFlow Agents Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests of tools for managing nested structures."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class ZipTest(tf.test.TestCase):
def test_scalar(self):
<|code_end|>
, generate the next line using the imports in this file:
import collections
import tensorflow as tf
from agents.tools import nested
and context (functions, classes, or occasionally code) from other files:
# Path: agents/tools/nested.py
# def zip_(*structures, **kwargs):
# def map_(function, *structures, **kwargs):
# def impl(function, *structures):
# def flatten_(structure):
# def filter_(predicate, *structures, **kwargs):
# def impl(predicate, *structures):
. Output only the next line. | self.assertEqual(42, nested.zip(42)) |
Based on the snippet: <|code_start|>
class CodeBlock(idaapi.BasicBlock):
def __init__(self, id_ea=None, bb=None, fc=None):
if bb is None and fc is None:
if id_ea is None:
id_ea = idaapi.get_screen_ea()
temp_codeblock = get_codeblock(id_ea)
self.__dict__.update(temp_codeblock.__dict__)
else:
super(CodeBlock, self).__init__(id=id_ea, bb=bb, fc=fc)
@property
<|code_end|>
, predict the immediate next line with the help of imports:
import networkx
import idaapi
from .code import lines, functions
from .core import get_func, fix_addresses
and context (classes, functions, sometimes code) from other files:
# Path: sark/code/line.py
# def lines(start=None, end=None, reverse=False, selection=False):
# """Iterate lines in range.
#
# Args:
# start: Starting address, start of IDB if `None`.
# end: End address, end of IDB if `None`.
# reverse: Set to true to iterate in reverse order.
# selection: If set to True, replaces start and end with current selection.
#
# Returns:
# iterator of `Line` objects.
# """
# if selection:
# start, end = get_selection()
#
# else:
# start, end = fix_addresses(start, end)
#
# if not reverse:
# item = idaapi.get_item_head(start)
# while item < end:
# yield Line(item)
# item += idaapi.get_item_size(item)
#
# else: # if reverse:
# item = idaapi.get_item_head(end - 1)
# while item >= start:
# yield Line(item)
# item = idaapi.get_item_head(item - 1)
#
# Path: sark/code/function.py
# def functions(start=None, end=None):
# """Get all functions in range.
#
# Args:
# start: Start address of the range. Defaults to IDB start.
# end: End address of the range. Defaults to IDB end.
#
# Returns:
# This is a generator that iterates over all the functions in the IDB.
# """
# start, end = fix_addresses(start, end)
#
# for func_t in idautils.Functions(start, end):
# yield Function(func_t)
#
# Path: sark/core.py
# def get_func(func_ea):
# """get_func(func_t or ea) -> func_t
#
# Take an IDA function (``idaapi.func_t``) or an address (EA) and return
# an IDA function object.
#
# Use this when APIs can take either a function or an address.
#
# Args:
# func_ea: ``idaapi.func_t`` or ea of the function.
#
# Returns:
# An ``idaapi.func_t`` object for the given address. If a ``func_t`` is
# provided, it is returned.
# """
# if isinstance(func_ea, idaapi.func_t):
# return func_ea
# func = idaapi.get_func(func_ea)
# if func is None:
# raise exceptions.SarkNoFunction("No function at 0x{:08X}".format(func_ea))
#
# return func
#
# def fix_addresses(start=None, end=None):
# """Set missing addresses to start and end of IDB.
#
# Take a start and end addresses. If an address is None or `BADADDR`,
# return start or end addresses of the IDB instead.
#
# Args
# start: Start EA. Use `None` to get IDB start.
# end: End EA. Use `None` to get IDB end.
#
# Returns:
# (start, end)
# """
# if start in (None, idaapi.BADADDR):
# start = idaapi.cvar.inf.minEA
#
# if end in (None, idaapi.BADADDR):
# end = idaapi.cvar.inf.maxEA
#
# return start, end
. Output only the next line. | def lines(self): |
Continue the code snippet: <|code_start|> """Get the start address of an IDA Graph block."""
return get_codeblock(ea).start_ea
def get_nx_graph(ea, ignore_external=False):
"""Convert an IDA flowchart to a NetworkX graph."""
nx_graph = networkx.DiGraph()
func = idaapi.get_func(ea)
flowchart = FlowChart(func, ignore_external=ignore_external)
for block in flowchart:
# Make sure all nodes are added (including edge-less nodes)
nx_graph.add_node(block.start_ea)
for pred in block.preds():
nx_graph.add_edge(pred.start_ea, block.start_ea)
for succ in block.succs():
nx_graph.add_edge(block.start_ea, succ.start_ea)
return nx_graph
def codeblocks(start=None, end=None, full=True):
"""Get all `CodeBlock`s in a given range.
Args:
start - start address of the range. If `None` uses IDB start.
end - end address of the range. If `None` uses IDB end.
full - `True` is required to change node info (e.g. color). `False` causes faster iteration.
"""
if full:
<|code_end|>
. Use current file imports:
import networkx
import idaapi
from .code import lines, functions
from .core import get_func, fix_addresses
and context (classes, functions, or code) from other files:
# Path: sark/code/line.py
# def lines(start=None, end=None, reverse=False, selection=False):
# """Iterate lines in range.
#
# Args:
# start: Starting address, start of IDB if `None`.
# end: End address, end of IDB if `None`.
# reverse: Set to true to iterate in reverse order.
# selection: If set to True, replaces start and end with current selection.
#
# Returns:
# iterator of `Line` objects.
# """
# if selection:
# start, end = get_selection()
#
# else:
# start, end = fix_addresses(start, end)
#
# if not reverse:
# item = idaapi.get_item_head(start)
# while item < end:
# yield Line(item)
# item += idaapi.get_item_size(item)
#
# else: # if reverse:
# item = idaapi.get_item_head(end - 1)
# while item >= start:
# yield Line(item)
# item = idaapi.get_item_head(item - 1)
#
# Path: sark/code/function.py
# def functions(start=None, end=None):
# """Get all functions in range.
#
# Args:
# start: Start address of the range. Defaults to IDB start.
# end: End address of the range. Defaults to IDB end.
#
# Returns:
# This is a generator that iterates over all the functions in the IDB.
# """
# start, end = fix_addresses(start, end)
#
# for func_t in idautils.Functions(start, end):
# yield Function(func_t)
#
# Path: sark/core.py
# def get_func(func_ea):
# """get_func(func_t or ea) -> func_t
#
# Take an IDA function (``idaapi.func_t``) or an address (EA) and return
# an IDA function object.
#
# Use this when APIs can take either a function or an address.
#
# Args:
# func_ea: ``idaapi.func_t`` or ea of the function.
#
# Returns:
# An ``idaapi.func_t`` object for the given address. If a ``func_t`` is
# provided, it is returned.
# """
# if isinstance(func_ea, idaapi.func_t):
# return func_ea
# func = idaapi.get_func(func_ea)
# if func is None:
# raise exceptions.SarkNoFunction("No function at 0x{:08X}".format(func_ea))
#
# return func
#
# def fix_addresses(start=None, end=None):
# """Set missing addresses to start and end of IDB.
#
# Take a start and end addresses. If an address is None or `BADADDR`,
# return start or end addresses of the IDB instead.
#
# Args
# start: Start EA. Use `None` to get IDB start.
# end: End EA. Use `None` to get IDB end.
#
# Returns:
# (start, end)
# """
# if start in (None, idaapi.BADADDR):
# start = idaapi.cvar.inf.minEA
#
# if end in (None, idaapi.BADADDR):
# end = idaapi.cvar.inf.maxEA
#
# return start, end
. Output only the next line. | for function in functions(start, end): |
Predict the next line after this snippet: <|code_start|>
@property
def color(self):
node_info = idaapi.node_info_t()
success = idaapi.get_node_info(node_info, self._fc._q.bounds.start_ea, self.id)
if not success:
return None
if not node_info.valid_bg_color():
return None
return node_info.bg_color
@color.setter
def color(self, color):
self.set_color(color)
def __repr__(self):
return "<CodeBlock(start_ea=0x{:08X}, end_ea=0x{:08X})>".format(self.start_ea, self.end_ea)
def __eq__(self, other):
return self.start_ea == other.start_ea
class FlowChart(idaapi.FlowChart):
def __init__(self, f=None, bounds=None, flags=idaapi.FC_PREDS, ignore_external=False):
if f is None and bounds is None:
f = idaapi.get_screen_ea()
if f is not None:
<|code_end|>
using the current file's imports:
import networkx
import idaapi
from .code import lines, functions
from .core import get_func, fix_addresses
and any relevant context from other files:
# Path: sark/code/line.py
# def lines(start=None, end=None, reverse=False, selection=False):
# """Iterate lines in range.
#
# Args:
# start: Starting address, start of IDB if `None`.
# end: End address, end of IDB if `None`.
# reverse: Set to true to iterate in reverse order.
# selection: If set to True, replaces start and end with current selection.
#
# Returns:
# iterator of `Line` objects.
# """
# if selection:
# start, end = get_selection()
#
# else:
# start, end = fix_addresses(start, end)
#
# if not reverse:
# item = idaapi.get_item_head(start)
# while item < end:
# yield Line(item)
# item += idaapi.get_item_size(item)
#
# else: # if reverse:
# item = idaapi.get_item_head(end - 1)
# while item >= start:
# yield Line(item)
# item = idaapi.get_item_head(item - 1)
#
# Path: sark/code/function.py
# def functions(start=None, end=None):
# """Get all functions in range.
#
# Args:
# start: Start address of the range. Defaults to IDB start.
# end: End address of the range. Defaults to IDB end.
#
# Returns:
# This is a generator that iterates over all the functions in the IDB.
# """
# start, end = fix_addresses(start, end)
#
# for func_t in idautils.Functions(start, end):
# yield Function(func_t)
#
# Path: sark/core.py
# def get_func(func_ea):
# """get_func(func_t or ea) -> func_t
#
# Take an IDA function (``idaapi.func_t``) or an address (EA) and return
# an IDA function object.
#
# Use this when APIs can take either a function or an address.
#
# Args:
# func_ea: ``idaapi.func_t`` or ea of the function.
#
# Returns:
# An ``idaapi.func_t`` object for the given address. If a ``func_t`` is
# provided, it is returned.
# """
# if isinstance(func_ea, idaapi.func_t):
# return func_ea
# func = idaapi.get_func(func_ea)
# if func is None:
# raise exceptions.SarkNoFunction("No function at 0x{:08X}".format(func_ea))
#
# return func
#
# def fix_addresses(start=None, end=None):
# """Set missing addresses to start and end of IDB.
#
# Take a start and end addresses. If an address is None or `BADADDR`,
# return start or end addresses of the IDB instead.
#
# Args
# start: Start EA. Use `None` to get IDB start.
# end: End EA. Use `None` to get IDB end.
#
# Returns:
# (start, end)
# """
# if start in (None, idaapi.BADADDR):
# start = idaapi.cvar.inf.minEA
#
# if end in (None, idaapi.BADADDR):
# end = idaapi.cvar.inf.maxEA
#
# return start, end
. Output only the next line. | f = get_func(f) |
Given snippet: <|code_start|> nx_graph = networkx.DiGraph()
func = idaapi.get_func(ea)
flowchart = FlowChart(func, ignore_external=ignore_external)
for block in flowchart:
# Make sure all nodes are added (including edge-less nodes)
nx_graph.add_node(block.start_ea)
for pred in block.preds():
nx_graph.add_edge(pred.start_ea, block.start_ea)
for succ in block.succs():
nx_graph.add_edge(block.start_ea, succ.start_ea)
return nx_graph
def codeblocks(start=None, end=None, full=True):
"""Get all `CodeBlock`s in a given range.
Args:
start - start address of the range. If `None` uses IDB start.
end - end address of the range. If `None` uses IDB end.
full - `True` is required to change node info (e.g. color). `False` causes faster iteration.
"""
if full:
for function in functions(start, end):
fc = FlowChart(f=function.func_t)
for block in fc:
yield block
else:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import networkx
import idaapi
from .code import lines, functions
from .core import get_func, fix_addresses
and context:
# Path: sark/code/line.py
# def lines(start=None, end=None, reverse=False, selection=False):
# """Iterate lines in range.
#
# Args:
# start: Starting address, start of IDB if `None`.
# end: End address, end of IDB if `None`.
# reverse: Set to true to iterate in reverse order.
# selection: If set to True, replaces start and end with current selection.
#
# Returns:
# iterator of `Line` objects.
# """
# if selection:
# start, end = get_selection()
#
# else:
# start, end = fix_addresses(start, end)
#
# if not reverse:
# item = idaapi.get_item_head(start)
# while item < end:
# yield Line(item)
# item += idaapi.get_item_size(item)
#
# else: # if reverse:
# item = idaapi.get_item_head(end - 1)
# while item >= start:
# yield Line(item)
# item = idaapi.get_item_head(item - 1)
#
# Path: sark/code/function.py
# def functions(start=None, end=None):
# """Get all functions in range.
#
# Args:
# start: Start address of the range. Defaults to IDB start.
# end: End address of the range. Defaults to IDB end.
#
# Returns:
# This is a generator that iterates over all the functions in the IDB.
# """
# start, end = fix_addresses(start, end)
#
# for func_t in idautils.Functions(start, end):
# yield Function(func_t)
#
# Path: sark/core.py
# def get_func(func_ea):
# """get_func(func_t or ea) -> func_t
#
# Take an IDA function (``idaapi.func_t``) or an address (EA) and return
# an IDA function object.
#
# Use this when APIs can take either a function or an address.
#
# Args:
# func_ea: ``idaapi.func_t`` or ea of the function.
#
# Returns:
# An ``idaapi.func_t`` object for the given address. If a ``func_t`` is
# provided, it is returned.
# """
# if isinstance(func_ea, idaapi.func_t):
# return func_ea
# func = idaapi.get_func(func_ea)
# if func is None:
# raise exceptions.SarkNoFunction("No function at 0x{:08X}".format(func_ea))
#
# return func
#
# def fix_addresses(start=None, end=None):
# """Set missing addresses to start and end of IDB.
#
# Take a start and end addresses. If an address is None or `BADADDR`,
# return start or end addresses of the IDB instead.
#
# Args
# start: Start EA. Use `None` to get IDB start.
# end: End EA. Use `None` to get IDB end.
#
# Returns:
# (start, end)
# """
# if start in (None, idaapi.BADADDR):
# start = idaapi.cvar.inf.minEA
#
# if end in (None, idaapi.BADADDR):
# end = idaapi.cvar.inf.maxEA
#
# return start, end
which might include code, classes, or functions. Output only the next line. | start, end = fix_addresses(start, end) |
Given the code snippet: <|code_start|> if function.ea == ea:
name = function.demangled
except:
pass
if not name:
name = idc.Name(ea)
if not name:
raise NoName("No named for address 0x{:08X}".format(ea))
return name
def show_meaningful_in_function(function):
idaapi.msg("\n\nMeaningful References in {!r} : 0x{:08X}\n".format(function.demangled, function.start_ea))
idaapi.msg("Type Usage Address Object\n")
idaapi.msg("------------------------------------------\n")
for xref in function.xrefs_from:
if xref.type.is_code:
try:
name = get_name(xref.to)
except NoName:
continue
idaapi.msg("code 0x{:08X} 0x{:08X} {}\n".format(xref.frm, xref.to, name))
else:
try:
<|code_end|>
, generate the next line using the imports in this file:
import idaapi
import idc
import sark
import sark.ui
from sark.data import get_string
from sark import exceptions
and context (functions, classes, or occasionally code) from other files:
# Path: sark/data.py
# def get_string(ea):
# """Read the string at the given ea.
#
# This function uses IDA's string APIs and does not implement any special logic.
# """
# # We get the item-head because the `GetStringType` function only works on the head of an item.
# string_type = idc.get_str_type(idaapi.get_item_head(ea))
#
# if string_type is None:
# raise exceptions.SarkNoString("No string at 0x{:08X}".format(ea))
#
# string = idc.get_strlit_contents(ea, strtype=string_type)
#
# if not string:
# raise exceptions.SarkNoString("No string at 0x{:08X}".format(ea))
#
# return string
#
# Path: sark/exceptions.py
# class SarkException(Exception):
# class SarkError(SarkException):
# class SarkNoSelection(SarkError):
# class SarkNoFunction(SarkError):
# class SarkAddFunctionFailed(SarkError):
# class SarkFunctionExists(SarkError):
# class SarkStructError(SarkError):
# class SarkInvalidRegisterName(SarkError):
# class SarkStructAlreadyExists(SarkStructError):
# class SarkStructCreationFailed(SarkStructError):
# class SarkStructNotFound(SarkStructError):
# class SarkErrorAddStructMemeberFailed(SarkStructError):
# class SarkErrorStructMemberName(SarkErrorAddStructMemeberFailed):
# class SarkErrorStructMemberOffset(SarkErrorAddStructMemeberFailed):
# class SarkErrorStructMemberSize(SarkErrorAddStructMemeberFailed):
# class SarkErrorStructMemberTinfo(SarkErrorAddStructMemeberFailed):
# class SarkErrorStructMemberStruct(SarkErrorAddStructMemeberFailed):
# class SarkErrorStructMemberUnivar(SarkErrorAddStructMemeberFailed):
# class SarkErrorStructMemberVarlast(SarkErrorAddStructMemeberFailed):
# class SarkEnumError(SarkError):
# class SarkErrorAddEnumMemeberFailed(SarkEnumError):
# class SarkErrorEnumMemberName(SarkErrorAddEnumMemeberFailed):
# class SarkErrorEnumMemberValue(SarkErrorAddEnumMemeberFailed):
# class SarkErrorEnumMemberEnum(SarkErrorAddEnumMemeberFailed):
# class SarkErrorEnumMemberMask(SarkErrorAddEnumMemeberFailed):
# class SarkErrorEnumMemberIllv(SarkErrorAddEnumMemeberFailed):
# class EnumNotFound(SarkEnumError):
# class EnumCreationFailed(SarkEnumError):
# class EnumAlreadyExists(SarkEnumError):
# class CantRenameEnumMember(SarkEnumError):
# class CantSetEnumMemberComment(SarkEnumError):
# class SarkErrorNameAlreadyExists(SarkError):
# class SarkSetNameFailed(SarkError):
# class SarkSwitchError(SarkError):
# class SarkNotASwitch(SarkSwitchError):
# class SarkNoInstruction(SarkError):
# class SarkOperandError(SarkError):
# class SarkOperandWithoutReg(SarkOperandError):
# class CantSetEnumComment(SarkEnumError):
# class CantDeleteEnumMember(SarkEnumError):
# class CantSetEnumBitfield(SarkEnumError):
# class CantRenameEnum(SarkEnumError):
# class SarkGuiError(SarkError):
# class SarkMenuError(SarkGuiError):
# class MenuAlreadyExists(SarkMenuError):
# class MenuNotFound(SarkMenuError):
# class FormNotFound(SarkGuiError):
# class InvalidStructOffset(SarkStructError):
# class SegmentError(SarkError):
# class NoMoreSegments(SegmentError):
# class InvalidBitness(SegmentError):
# class NoFileOffset(SarkError):
# class SarkNoString(SarkError):
# class SarkExpectedPatchedByte(SarkError):
# class PhraseError(SarkOperandError):
# class OperandNotPhrase(PhraseError):
# class PhraseNotSupported(PhraseError):
# class PhraseProcessorNotSupported(PhraseNotSupported):
# class SetTypeFailed(SarkError):
# def __init__(self, ea, c_signature):
. Output only the next line. | string = get_string(xref.to) |
Continue the code snippet: <|code_start|> name = function.demangled
except:
pass
if not name:
name = idc.Name(ea)
if not name:
raise NoName("No named for address 0x{:08X}".format(ea))
return name
def show_meaningful_in_function(function):
idaapi.msg("\n\nMeaningful References in {!r} : 0x{:08X}\n".format(function.demangled, function.start_ea))
idaapi.msg("Type Usage Address Object\n")
idaapi.msg("------------------------------------------\n")
for xref in function.xrefs_from:
if xref.type.is_code:
try:
name = get_name(xref.to)
except NoName:
continue
idaapi.msg("code 0x{:08X} 0x{:08X} {}\n".format(xref.frm, xref.to, name))
else:
try:
string = get_string(xref.to)
<|code_end|>
. Use current file imports:
import idaapi
import idc
import sark
import sark.ui
from sark.data import get_string
from sark import exceptions
and context (classes, functions, or code) from other files:
# Path: sark/data.py
# def get_string(ea):
# """Read the string at the given ea.
#
# This function uses IDA's string APIs and does not implement any special logic.
# """
# # We get the item-head because the `GetStringType` function only works on the head of an item.
# string_type = idc.get_str_type(idaapi.get_item_head(ea))
#
# if string_type is None:
# raise exceptions.SarkNoString("No string at 0x{:08X}".format(ea))
#
# string = idc.get_strlit_contents(ea, strtype=string_type)
#
# if not string:
# raise exceptions.SarkNoString("No string at 0x{:08X}".format(ea))
#
# return string
#
# Path: sark/exceptions.py
# class SarkException(Exception):
# class SarkError(SarkException):
# class SarkNoSelection(SarkError):
# class SarkNoFunction(SarkError):
# class SarkAddFunctionFailed(SarkError):
# class SarkFunctionExists(SarkError):
# class SarkStructError(SarkError):
# class SarkInvalidRegisterName(SarkError):
# class SarkStructAlreadyExists(SarkStructError):
# class SarkStructCreationFailed(SarkStructError):
# class SarkStructNotFound(SarkStructError):
# class SarkErrorAddStructMemeberFailed(SarkStructError):
# class SarkErrorStructMemberName(SarkErrorAddStructMemeberFailed):
# class SarkErrorStructMemberOffset(SarkErrorAddStructMemeberFailed):
# class SarkErrorStructMemberSize(SarkErrorAddStructMemeberFailed):
# class SarkErrorStructMemberTinfo(SarkErrorAddStructMemeberFailed):
# class SarkErrorStructMemberStruct(SarkErrorAddStructMemeberFailed):
# class SarkErrorStructMemberUnivar(SarkErrorAddStructMemeberFailed):
# class SarkErrorStructMemberVarlast(SarkErrorAddStructMemeberFailed):
# class SarkEnumError(SarkError):
# class SarkErrorAddEnumMemeberFailed(SarkEnumError):
# class SarkErrorEnumMemberName(SarkErrorAddEnumMemeberFailed):
# class SarkErrorEnumMemberValue(SarkErrorAddEnumMemeberFailed):
# class SarkErrorEnumMemberEnum(SarkErrorAddEnumMemeberFailed):
# class SarkErrorEnumMemberMask(SarkErrorAddEnumMemeberFailed):
# class SarkErrorEnumMemberIllv(SarkErrorAddEnumMemeberFailed):
# class EnumNotFound(SarkEnumError):
# class EnumCreationFailed(SarkEnumError):
# class EnumAlreadyExists(SarkEnumError):
# class CantRenameEnumMember(SarkEnumError):
# class CantSetEnumMemberComment(SarkEnumError):
# class SarkErrorNameAlreadyExists(SarkError):
# class SarkSetNameFailed(SarkError):
# class SarkSwitchError(SarkError):
# class SarkNotASwitch(SarkSwitchError):
# class SarkNoInstruction(SarkError):
# class SarkOperandError(SarkError):
# class SarkOperandWithoutReg(SarkOperandError):
# class CantSetEnumComment(SarkEnumError):
# class CantDeleteEnumMember(SarkEnumError):
# class CantSetEnumBitfield(SarkEnumError):
# class CantRenameEnum(SarkEnumError):
# class SarkGuiError(SarkError):
# class SarkMenuError(SarkGuiError):
# class MenuAlreadyExists(SarkMenuError):
# class MenuNotFound(SarkMenuError):
# class FormNotFound(SarkGuiError):
# class InvalidStructOffset(SarkStructError):
# class SegmentError(SarkError):
# class NoMoreSegments(SegmentError):
# class InvalidBitness(SegmentError):
# class NoFileOffset(SarkError):
# class SarkNoString(SarkError):
# class SarkExpectedPatchedByte(SarkError):
# class PhraseError(SarkOperandError):
# class OperandNotPhrase(PhraseError):
# class PhraseNotSupported(PhraseError):
# class PhraseProcessorNotSupported(PhraseNotSupported):
# class SetTypeFailed(SarkError):
# def __init__(self, ea, c_signature):
. Output only the next line. | except exceptions.SarkNoString: |
Based on the snippet: <|code_start|>"""
Pytest configuration module, required to setup fixtures and
other specific test configuration, and allow pytest to find and use them.
"""
@pytest.fixture(autouse=True, name='mockuuid4')
def mock_uuid(mocker):
"""
Fixture to override the default uuid.uuid4 function to return a
deterministic uuid instead of a random one.
"""
<|code_end|>
, predict the immediate next line with the help of imports:
import uuid
import pytest
import models
from tests.test_utils import mock_uuid_generator, MockModelCreate
and context (classes, functions, sometimes code) from other files:
# Path: tests/test_utils.py
# def mock_uuid_generator():
# """
# Returns a generator object that creates UUID instances with a deterministic
# and progressive value in the form of `00000000-0000-0000-0000-000000000001`
# """
# i = 1
# while True:
# yield uuid.UUID('00000000-0000-0000-0000-{:012d}'.format(i))
# i += 1
#
# class MockModelCreate:
# """
# Override callable class that goes in place of the Model.create()
# classmethod and allows extra default custom parameters so test objects can
# be predictable.
# Defaulted attributes are `created_at`, with a static datetime and `uuid`
# with a progressive uuid
# """
#
# def __init__(self, cls):
# self.original = cls.create
# self.uuid_generator = mock_uuid_generator()
#
# def __call__(self, created_at=mock_datetime(), uuid=None, **query):
# query['created_at'] = created_at
# query['uuid'] = uuid or next(self.uuid_generator)
# return self.original(**query)
. Output only the next line. | muuid = mock_uuid_generator() |
Here is a snippet: <|code_start|>
@pytest.fixture(autouse=True, name='mockuuid4')
def mock_uuid(mocker):
"""
Fixture to override the default uuid.uuid4 function to return a
deterministic uuid instead of a random one.
"""
muuid = mock_uuid_generator()
def getuuid():
return next(muuid)
mockuuid = mocker.patch.object(uuid, 'uuid4', autospec=True)
mockuuid.side_effect = getuuid
@pytest.fixture(autouse=True, name='mock_create')
def mock_models_create(mocker):
"""
Fixture to patch the create method of our models to force a default
created_at datetime and a progressive UUID-like UUID object when creating
new instances, but allowing to override with specific values.
"""
for cls in [models.Order]:
mocker.patch(
'models.{}.create'.format(cls.__name__),
<|code_end|>
. Write the next line using the current file imports:
import uuid
import pytest
import models
from tests.test_utils import mock_uuid_generator, MockModelCreate
and context from other files:
# Path: tests/test_utils.py
# def mock_uuid_generator():
# """
# Returns a generator object that creates UUID instances with a deterministic
# and progressive value in the form of `00000000-0000-0000-0000-000000000001`
# """
# i = 1
# while True:
# yield uuid.UUID('00000000-0000-0000-0000-{:012d}'.format(i))
# i += 1
#
# class MockModelCreate:
# """
# Override callable class that goes in place of the Model.create()
# classmethod and allows extra default custom parameters so test objects can
# be predictable.
# Defaulted attributes are `created_at`, with a static datetime and `uuid`
# with a progressive uuid
# """
#
# def __init__(self, cls):
# self.original = cls.create
# self.uuid_generator = mock_uuid_generator()
#
# def __call__(self, created_at=mock_datetime(), uuid=None, **query):
# query['created_at'] = created_at
# query['uuid'] = uuid or next(self.uuid_generator)
# return self.original(**query)
, which may include functions, classes, or code. Output only the next line. | new=MockModelCreate(cls), |
Predict the next line for this snippet: <|code_start|>"""
Items view: this module provides methods to interact
with items resources
"""
SEARCH_FIELDS = ['name', 'description']
class ItemsHandler(Resource):
"""Handler of the collection of items"""
def get(self):
"""Retrieve every item"""
<|code_end|>
with the help of current file imports:
import http.client as client
import uuid
from flask import request
from flask_restful import Resource
from models import Item
from utils import generate_response
and context from other files:
# Path: models.py
# class Item(BaseModel):
# """
# Item describes a product for the e-commerce platform.
#
# Attributes:
# uuid (UUID): Item UUID
# name (str): Name for the product
# price (decimal.Decimal): Price for a single product
# description (str): Product description
# availability (int): Quantity of items available
# category (str): Category group of the item
#
# """
# uuid = UUIDField(unique=True)
# name = CharField()
# price = DecimalField(auto_round=True)
# description = TextField()
# availability = IntegerField()
# category = TextField()
# _schema = ItemSchema
# _search_attributes = ['name', 'category', 'description']
#
# def __str__(self):
# return '{}, {}, {}, {}'.format(
# self.uuid,
# self.name,
# self.price,
# self.description)
#
# def is_favorite(self, item):
# for f in self.favorites:
# if f.item_id == item.id:
# return True
# return False
#
# Path: utils.py
# def generate_response(data, status, mimetype='application/vnd.api+json'):
# """
# Given a resource model that extends from `BaseModel` generate a Reponse
# object to be returned from the application endpoints'
# """
# return Response(
# response=data,
# status=status,
# mimetype=mimetype
# )
, which may contain function names, class names, or code. Output only the next line. | data = Item.json_list(Item.select()) |
Given snippet: <|code_start|>"""
Items view: this module provides methods to interact
with items resources
"""
SEARCH_FIELDS = ['name', 'description']
class ItemsHandler(Resource):
"""Handler of the collection of items"""
def get(self):
"""Retrieve every item"""
data = Item.json_list(Item.select())
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import http.client as client
import uuid
from flask import request
from flask_restful import Resource
from models import Item
from utils import generate_response
and context:
# Path: models.py
# class Item(BaseModel):
# """
# Item describes a product for the e-commerce platform.
#
# Attributes:
# uuid (UUID): Item UUID
# name (str): Name for the product
# price (decimal.Decimal): Price for a single product
# description (str): Product description
# availability (int): Quantity of items available
# category (str): Category group of the item
#
# """
# uuid = UUIDField(unique=True)
# name = CharField()
# price = DecimalField(auto_round=True)
# description = TextField()
# availability = IntegerField()
# category = TextField()
# _schema = ItemSchema
# _search_attributes = ['name', 'category', 'description']
#
# def __str__(self):
# return '{}, {}, {}, {}'.format(
# self.uuid,
# self.name,
# self.price,
# self.description)
#
# def is_favorite(self, item):
# for f in self.favorites:
# if f.item_id == item.id:
# return True
# return False
#
# Path: utils.py
# def generate_response(data, status, mimetype='application/vnd.api+json'):
# """
# Given a resource model that extends from `BaseModel` generate a Reponse
# object to be returned from the application endpoints'
# """
# return Response(
# response=data,
# status=status,
# mimetype=mimetype
# )
which might include code, classes, or functions. Output only the next line. | return generate_response(data, client.OK) |
Predict the next line after this snippet: <|code_start|> and matching `weights`
Args:
values(iterable): Values to average, either `int` or `float`
weights(iterable): Matching weights iterable
Returns:
float: weighted average
"""
if len(values) != len(weights):
raise ValueError(
'Values and Weights length do not match for weighted average')
val = sum(m * w for m, w in zip(values, weights))
weights = sum(weights)
return val / weights
def tokenize(string):
"""
Given a string return a list of segments of the string,
splitted with :any:`config.STR_SPLIT_REGEX`, removing every word <=
:any:`config.MIN_WORD_LENGTH`.
Example:
>>> utils.tokenize('hello there, how are you')
['hello', 'there']
"""
return [
<|code_end|>
using the current file's imports:
import re
from search import config
and any relevant context from other files:
# Path: search/config.py
# MATCH_WEIGHT = 0.2
# DIST_WEIGHT = 0.8
# THRESHOLD = 0.75
# MIN_WORD_LENGTH = 3
# STR_SPLIT_REGEX = r'\W+'
. Output only the next line. | w for w in re.split(config.STR_SPLIT_REGEX, string) |
Predict the next line for this snippet: <|code_start|> """
return current_user._get_current_object()
@staticmethod
def init_app(app):
"""
Wrapper for the flask_login method ``LoginManager::init_app``.
Args:
Flask app (Flask): The Flask app to initialize with the
login manager
"""
return login_manager.init_app(app)
auth = Auth()
@login_manager.user_loader
def load_user(user_id):
"""
Current user loading logic. If the user exists return it, otherwise None.
Args:
user_id (int): Peewee user id
Returns:
models.User: The requested user
"""
try:
<|code_end|>
with the help of current file imports:
from flask_login import login_required, LoginManager
from models import User
from flask_login import current_user
and context from other files:
# Path: models.py
# class User(BaseModel, UserMixin):
# """
# User represents an user for the application.
#
# Attributes:
# first_name (str): User's first name
# last_name (str): User's last name
# email (str): User's **valid** email
# password (str): User's password
# admin (bool): User's admin status. Defaults to ``False``
#
# .. NOTE::
# Each User resource must have an unique `email` field, meaning
# that there cannot be two user's registered with the same email.
#
# For this reason, when checking for user's existence, the server requires
# either the `uuid` of the user or its `email`.
# """
# uuid = UUIDField(unique=True)
# first_name = CharField()
# last_name = CharField()
# email = CharField(unique=True)
# password = CharField()
# admin = BooleanField(default=False)
# _schema = UserSchema
#
# @staticmethod
# def exists(email):
# """
# Check that an user exists by checking the email field.
#
# Args:
# email (str): User's email to check
# """
# try:
# User.get(User.email == email)
# except User.DoesNotExist:
# return False
# return True
#
# @staticmethod
# def hash_password(password):
# """
# Use passlib to get a crypted password.
#
# Args:
# password (str): password to hash
#
# Returns:
# str: hashed password
# """
# return pbkdf2_sha256.hash(password)
#
# def verify_password(self, password):
# """
# Verify a clear password against the stored hashed password of the user
# using passlib.
#
# Args:
# password (str): Password to verify against the hashed stored password
# Returns:
# bool: wether the given email matches the stored one
# """
# return pbkdf2_sha256.verify(password, self.password)
#
# def add_favorite(user, item):
# """Link the favorite item to user."""
# return Favorite.create(
# uuid=uuid4(),
# item=item,
# user=user,
# )
#
# def delete_favorite(self, obj):
# obj.delete_instance()
, which may contain function names, class names, or code. Output only the next line. | return User.get(User.id == user_id) |
Given the following code snippet before the placeholder: <|code_start|>"""
Auth login view: this module provides the login method
"""
class LoginHandler(Resource):
"""Handler of the login authentication"""
@cross_origin(supports_credentials=True)
def post(self):
request_data = request.get_json(force=True)
if 'email' not in request_data or 'password' not in request_data:
abort(client.BAD_REQUEST)
email = request_data['email']
password = request_data['password']
try:
<|code_end|>
, predict the next line using imports from the current file:
from flask import abort, request
from flask_cors import cross_origin
from flask_login import login_user, logout_user
from flask_restful import Resource
from models import User
from utils import generate_response
import http.client as client
and context including class names, function names, and sometimes code from other files:
# Path: models.py
# class User(BaseModel, UserMixin):
# """
# User represents an user for the application.
#
# Attributes:
# first_name (str): User's first name
# last_name (str): User's last name
# email (str): User's **valid** email
# password (str): User's password
# admin (bool): User's admin status. Defaults to ``False``
#
# .. NOTE::
# Each User resource must have an unique `email` field, meaning
# that there cannot be two user's registered with the same email.
#
# For this reason, when checking for user's existence, the server requires
# either the `uuid` of the user or its `email`.
# """
# uuid = UUIDField(unique=True)
# first_name = CharField()
# last_name = CharField()
# email = CharField(unique=True)
# password = CharField()
# admin = BooleanField(default=False)
# _schema = UserSchema
#
# @staticmethod
# def exists(email):
# """
# Check that an user exists by checking the email field.
#
# Args:
# email (str): User's email to check
# """
# try:
# User.get(User.email == email)
# except User.DoesNotExist:
# return False
# return True
#
# @staticmethod
# def hash_password(password):
# """
# Use passlib to get a crypted password.
#
# Args:
# password (str): password to hash
#
# Returns:
# str: hashed password
# """
# return pbkdf2_sha256.hash(password)
#
# def verify_password(self, password):
# """
# Verify a clear password against the stored hashed password of the user
# using passlib.
#
# Args:
# password (str): Password to verify against the hashed stored password
# Returns:
# bool: wether the given email matches the stored one
# """
# return pbkdf2_sha256.verify(password, self.password)
#
# def add_favorite(user, item):
# """Link the favorite item to user."""
# return Favorite.create(
# uuid=uuid4(),
# item=item,
# user=user,
# )
#
# def delete_favorite(self, obj):
# obj.delete_instance()
#
# Path: utils.py
# def generate_response(data, status, mimetype='application/vnd.api+json'):
# """
# Given a resource model that extends from `BaseModel` generate a Reponse
# object to be returned from the application endpoints'
# """
# return Response(
# response=data,
# status=status,
# mimetype=mimetype
# )
. Output only the next line. | user = User.get(User.email == email) |
Given the following code snippet before the placeholder: <|code_start|>"""
Auth login view: this module provides the login method
"""
class LoginHandler(Resource):
"""Handler of the login authentication"""
@cross_origin(supports_credentials=True)
def post(self):
request_data = request.get_json(force=True)
if 'email' not in request_data or 'password' not in request_data:
abort(client.BAD_REQUEST)
email = request_data['email']
password = request_data['password']
try:
user = User.get(User.email == email)
except User.DoesNotExist:
abort(client.BAD_REQUEST)
if not user.verify_password(password):
abort(client.UNAUTHORIZED)
login_user(user)
<|code_end|>
, predict the next line using imports from the current file:
from flask import abort, request
from flask_cors import cross_origin
from flask_login import login_user, logout_user
from flask_restful import Resource
from models import User
from utils import generate_response
import http.client as client
and context including class names, function names, and sometimes code from other files:
# Path: models.py
# class User(BaseModel, UserMixin):
# """
# User represents an user for the application.
#
# Attributes:
# first_name (str): User's first name
# last_name (str): User's last name
# email (str): User's **valid** email
# password (str): User's password
# admin (bool): User's admin status. Defaults to ``False``
#
# .. NOTE::
# Each User resource must have an unique `email` field, meaning
# that there cannot be two user's registered with the same email.
#
# For this reason, when checking for user's existence, the server requires
# either the `uuid` of the user or its `email`.
# """
# uuid = UUIDField(unique=True)
# first_name = CharField()
# last_name = CharField()
# email = CharField(unique=True)
# password = CharField()
# admin = BooleanField(default=False)
# _schema = UserSchema
#
# @staticmethod
# def exists(email):
# """
# Check that an user exists by checking the email field.
#
# Args:
# email (str): User's email to check
# """
# try:
# User.get(User.email == email)
# except User.DoesNotExist:
# return False
# return True
#
# @staticmethod
# def hash_password(password):
# """
# Use passlib to get a crypted password.
#
# Args:
# password (str): password to hash
#
# Returns:
# str: hashed password
# """
# return pbkdf2_sha256.hash(password)
#
# def verify_password(self, password):
# """
# Verify a clear password against the stored hashed password of the user
# using passlib.
#
# Args:
# password (str): Password to verify against the hashed stored password
# Returns:
# bool: wether the given email matches the stored one
# """
# return pbkdf2_sha256.verify(password, self.password)
#
# def add_favorite(user, item):
# """Link the favorite item to user."""
# return Favorite.create(
# uuid=uuid4(),
# item=item,
# user=user,
# )
#
# def delete_favorite(self, obj):
# obj.delete_instance()
#
# Path: utils.py
# def generate_response(data, status, mimetype='application/vnd.api+json'):
# """
# Given a resource model that extends from `BaseModel` generate a Reponse
# object to be returned from the application endpoints'
# """
# return Response(
# response=data,
# status=status,
# mimetype=mimetype
# )
. Output only the next line. | return generate_response({}, client.OK) |
Continue the code snippet: <|code_start|>
init(autoreset=True)
def drops_all_tables(database):
"""Doesn't drop unknown tables."""
tables = database.get_tables()
for table in tables:
if table == 'item':
Item.drop_table()
if table == 'order':
Order.drop_table()
if table == 'user':
<|code_end|>
. Use current file imports:
from colorama import init, Fore, Style
from models import (User, Item, Order, OrderItem,
Address, Picture, database, Favorite)
import sys
and context (classes, functions, or code) from other files:
# Path: models.py
# ENVIRONMENT = os.getenv('ENVIRONMENT', 'dev')
# class BaseModel(Model):
# class Meta:
# class Item(BaseModel):
# class Picture(BaseModel):
# class User(BaseModel, UserMixin):
# class Address(BaseModel):
# class Order(BaseModel):
# class Meta:
# class OrderItem(BaseModel):
# class Favorite(BaseModel):
# def save(self, *args, **kwargs):
# def json_list(cls, objs_list):
# def json(self, include_data=[]):
# def validate_input(cls, data, partial=False):
# def search(cls, query, dataset, limit=-1,
# attributes=None, weights=None,
# threshold=search.config.THRESHOLD):
# def __str__(self):
# def is_favorite(self, item):
# def on_delete_item_handler(model_class, instance):
# def filename(self):
# def __str__(self):
# def on_delete_picture_handler(model_class, instance):
# def exists(email):
# def hash_password(password):
# def verify_password(self, password):
# def add_favorite(user, item):
# def delete_favorite(self, obj):
# def order_items(self):
# def empty_order(self):
# def create_order(user, address, items):
# def update_items(self, items, update_total=True, new_address=None):
# def edit_items_quantity(self, items):
# def delete_items(self, items):
# def create_items(self, items):
# def add_item(self, item, quantity=1):
# def remove_item(self, item, quantity=1):
# def add_item(self, quantity=1):
# def remove_item(self, quantity=1):
# def _calculate_subtotal(self):
. Output only the next line. | User.drop_table() |
Next line prediction: <|code_start|>
init(autoreset=True)
def drops_all_tables(database):
"""Doesn't drop unknown tables."""
tables = database.get_tables()
for table in tables:
if table == 'item':
<|code_end|>
. Use current file imports:
(from colorama import init, Fore, Style
from models import (User, Item, Order, OrderItem,
Address, Picture, database, Favorite)
import sys)
and context including class names, function names, or small code snippets from other files:
# Path: models.py
# ENVIRONMENT = os.getenv('ENVIRONMENT', 'dev')
# class BaseModel(Model):
# class Meta:
# class Item(BaseModel):
# class Picture(BaseModel):
# class User(BaseModel, UserMixin):
# class Address(BaseModel):
# class Order(BaseModel):
# class Meta:
# class OrderItem(BaseModel):
# class Favorite(BaseModel):
# def save(self, *args, **kwargs):
# def json_list(cls, objs_list):
# def json(self, include_data=[]):
# def validate_input(cls, data, partial=False):
# def search(cls, query, dataset, limit=-1,
# attributes=None, weights=None,
# threshold=search.config.THRESHOLD):
# def __str__(self):
# def is_favorite(self, item):
# def on_delete_item_handler(model_class, instance):
# def filename(self):
# def __str__(self):
# def on_delete_picture_handler(model_class, instance):
# def exists(email):
# def hash_password(password):
# def verify_password(self, password):
# def add_favorite(user, item):
# def delete_favorite(self, obj):
# def order_items(self):
# def empty_order(self):
# def create_order(user, address, items):
# def update_items(self, items, update_total=True, new_address=None):
# def edit_items_quantity(self, items):
# def delete_items(self, items):
# def create_items(self, items):
# def add_item(self, item, quantity=1):
# def remove_item(self, item, quantity=1):
# def add_item(self, quantity=1):
# def remove_item(self, quantity=1):
# def _calculate_subtotal(self):
. Output only the next line. | Item.drop_table() |
Given snippet: <|code_start|>
init(autoreset=True)
def drops_all_tables(database):
"""Doesn't drop unknown tables."""
tables = database.get_tables()
for table in tables:
if table == 'item':
Item.drop_table()
if table == 'order':
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from colorama import init, Fore, Style
from models import (User, Item, Order, OrderItem,
Address, Picture, database, Favorite)
import sys
and context:
# Path: models.py
# ENVIRONMENT = os.getenv('ENVIRONMENT', 'dev')
# class BaseModel(Model):
# class Meta:
# class Item(BaseModel):
# class Picture(BaseModel):
# class User(BaseModel, UserMixin):
# class Address(BaseModel):
# class Order(BaseModel):
# class Meta:
# class OrderItem(BaseModel):
# class Favorite(BaseModel):
# def save(self, *args, **kwargs):
# def json_list(cls, objs_list):
# def json(self, include_data=[]):
# def validate_input(cls, data, partial=False):
# def search(cls, query, dataset, limit=-1,
# attributes=None, weights=None,
# threshold=search.config.THRESHOLD):
# def __str__(self):
# def is_favorite(self, item):
# def on_delete_item_handler(model_class, instance):
# def filename(self):
# def __str__(self):
# def on_delete_picture_handler(model_class, instance):
# def exists(email):
# def hash_password(password):
# def verify_password(self, password):
# def add_favorite(user, item):
# def delete_favorite(self, obj):
# def order_items(self):
# def empty_order(self):
# def create_order(user, address, items):
# def update_items(self, items, update_total=True, new_address=None):
# def edit_items_quantity(self, items):
# def delete_items(self, items):
# def create_items(self, items):
# def add_item(self, item, quantity=1):
# def remove_item(self, item, quantity=1):
# def add_item(self, quantity=1):
# def remove_item(self, quantity=1):
# def _calculate_subtotal(self):
which might include code, classes, or functions. Output only the next line. | Order.drop_table() |
Predict the next line for this snippet: <|code_start|>
init(autoreset=True)
def drops_all_tables(database):
"""Doesn't drop unknown tables."""
tables = database.get_tables()
for table in tables:
if table == 'item':
Item.drop_table()
if table == 'order':
Order.drop_table()
if table == 'user':
User.drop_table()
if table == 'orderitem':
<|code_end|>
with the help of current file imports:
from colorama import init, Fore, Style
from models import (User, Item, Order, OrderItem,
Address, Picture, database, Favorite)
import sys
and context from other files:
# Path: models.py
# ENVIRONMENT = os.getenv('ENVIRONMENT', 'dev')
# class BaseModel(Model):
# class Meta:
# class Item(BaseModel):
# class Picture(BaseModel):
# class User(BaseModel, UserMixin):
# class Address(BaseModel):
# class Order(BaseModel):
# class Meta:
# class OrderItem(BaseModel):
# class Favorite(BaseModel):
# def save(self, *args, **kwargs):
# def json_list(cls, objs_list):
# def json(self, include_data=[]):
# def validate_input(cls, data, partial=False):
# def search(cls, query, dataset, limit=-1,
# attributes=None, weights=None,
# threshold=search.config.THRESHOLD):
# def __str__(self):
# def is_favorite(self, item):
# def on_delete_item_handler(model_class, instance):
# def filename(self):
# def __str__(self):
# def on_delete_picture_handler(model_class, instance):
# def exists(email):
# def hash_password(password):
# def verify_password(self, password):
# def add_favorite(user, item):
# def delete_favorite(self, obj):
# def order_items(self):
# def empty_order(self):
# def create_order(user, address, items):
# def update_items(self, items, update_total=True, new_address=None):
# def edit_items_quantity(self, items):
# def delete_items(self, items):
# def create_items(self, items):
# def add_item(self, item, quantity=1):
# def remove_item(self, item, quantity=1):
# def add_item(self, quantity=1):
# def remove_item(self, quantity=1):
# def _calculate_subtotal(self):
, which may contain function names, class names, or code. Output only the next line. | OrderItem.drop_table() |
Using the snippet: <|code_start|>
init(autoreset=True)
def drops_all_tables(database):
"""Doesn't drop unknown tables."""
tables = database.get_tables()
for table in tables:
if table == 'item':
Item.drop_table()
if table == 'order':
Order.drop_table()
if table == 'user':
User.drop_table()
if table == 'orderitem':
OrderItem.drop_table()
if table == 'address':
<|code_end|>
, determine the next line of code. You have imports:
from colorama import init, Fore, Style
from models import (User, Item, Order, OrderItem,
Address, Picture, database, Favorite)
import sys
and context (class names, function names, or code) available:
# Path: models.py
# ENVIRONMENT = os.getenv('ENVIRONMENT', 'dev')
# class BaseModel(Model):
# class Meta:
# class Item(BaseModel):
# class Picture(BaseModel):
# class User(BaseModel, UserMixin):
# class Address(BaseModel):
# class Order(BaseModel):
# class Meta:
# class OrderItem(BaseModel):
# class Favorite(BaseModel):
# def save(self, *args, **kwargs):
# def json_list(cls, objs_list):
# def json(self, include_data=[]):
# def validate_input(cls, data, partial=False):
# def search(cls, query, dataset, limit=-1,
# attributes=None, weights=None,
# threshold=search.config.THRESHOLD):
# def __str__(self):
# def is_favorite(self, item):
# def on_delete_item_handler(model_class, instance):
# def filename(self):
# def __str__(self):
# def on_delete_picture_handler(model_class, instance):
# def exists(email):
# def hash_password(password):
# def verify_password(self, password):
# def add_favorite(user, item):
# def delete_favorite(self, obj):
# def order_items(self):
# def empty_order(self):
# def create_order(user, address, items):
# def update_items(self, items, update_total=True, new_address=None):
# def edit_items_quantity(self, items):
# def delete_items(self, items):
# def create_items(self, items):
# def add_item(self, item, quantity=1):
# def remove_item(self, item, quantity=1):
# def add_item(self, quantity=1):
# def remove_item(self, quantity=1):
# def _calculate_subtotal(self):
. Output only the next line. | Address.drop_table() |
Based on the snippet: <|code_start|>
init(autoreset=True)
def drops_all_tables(database):
"""Doesn't drop unknown tables."""
tables = database.get_tables()
for table in tables:
if table == 'item':
Item.drop_table()
if table == 'order':
Order.drop_table()
if table == 'user':
User.drop_table()
if table == 'orderitem':
OrderItem.drop_table()
if table == 'address':
Address.drop_table()
if table == 'picture':
<|code_end|>
, predict the immediate next line with the help of imports:
from colorama import init, Fore, Style
from models import (User, Item, Order, OrderItem,
Address, Picture, database, Favorite)
import sys
and context (classes, functions, sometimes code) from other files:
# Path: models.py
# ENVIRONMENT = os.getenv('ENVIRONMENT', 'dev')
# class BaseModel(Model):
# class Meta:
# class Item(BaseModel):
# class Picture(BaseModel):
# class User(BaseModel, UserMixin):
# class Address(BaseModel):
# class Order(BaseModel):
# class Meta:
# class OrderItem(BaseModel):
# class Favorite(BaseModel):
# def save(self, *args, **kwargs):
# def json_list(cls, objs_list):
# def json(self, include_data=[]):
# def validate_input(cls, data, partial=False):
# def search(cls, query, dataset, limit=-1,
# attributes=None, weights=None,
# threshold=search.config.THRESHOLD):
# def __str__(self):
# def is_favorite(self, item):
# def on_delete_item_handler(model_class, instance):
# def filename(self):
# def __str__(self):
# def on_delete_picture_handler(model_class, instance):
# def exists(email):
# def hash_password(password):
# def verify_password(self, password):
# def add_favorite(user, item):
# def delete_favorite(self, obj):
# def order_items(self):
# def empty_order(self):
# def create_order(user, address, items):
# def update_items(self, items, update_total=True, new_address=None):
# def edit_items_quantity(self, items):
# def delete_items(self, items):
# def create_items(self, items):
# def add_item(self, item, quantity=1):
# def remove_item(self, item, quantity=1):
# def add_item(self, quantity=1):
# def remove_item(self, quantity=1):
# def _calculate_subtotal(self):
. Output only the next line. | Picture.drop_table() |
Given snippet: <|code_start|>
init(autoreset=True)
def drops_all_tables(database):
"""Doesn't drop unknown tables."""
tables = database.get_tables()
for table in tables:
if table == 'item':
Item.drop_table()
if table == 'order':
Order.drop_table()
if table == 'user':
User.drop_table()
if table == 'orderitem':
OrderItem.drop_table()
if table == 'address':
Address.drop_table()
if table == 'picture':
Picture.drop_table()
if table == 'favorite':
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from colorama import init, Fore, Style
from models import (User, Item, Order, OrderItem,
Address, Picture, database, Favorite)
import sys
and context:
# Path: models.py
# ENVIRONMENT = os.getenv('ENVIRONMENT', 'dev')
# class BaseModel(Model):
# class Meta:
# class Item(BaseModel):
# class Picture(BaseModel):
# class User(BaseModel, UserMixin):
# class Address(BaseModel):
# class Order(BaseModel):
# class Meta:
# class OrderItem(BaseModel):
# class Favorite(BaseModel):
# def save(self, *args, **kwargs):
# def json_list(cls, objs_list):
# def json(self, include_data=[]):
# def validate_input(cls, data, partial=False):
# def search(cls, query, dataset, limit=-1,
# attributes=None, weights=None,
# threshold=search.config.THRESHOLD):
# def __str__(self):
# def is_favorite(self, item):
# def on_delete_item_handler(model_class, instance):
# def filename(self):
# def __str__(self):
# def on_delete_picture_handler(model_class, instance):
# def exists(email):
# def hash_password(password):
# def verify_password(self, password):
# def add_favorite(user, item):
# def delete_favorite(self, obj):
# def order_items(self):
# def empty_order(self):
# def create_order(user, address, items):
# def update_items(self, items, update_total=True, new_address=None):
# def edit_items_quantity(self, items):
# def delete_items(self, items):
# def create_items(self, items):
# def add_item(self, item, quantity=1):
# def remove_item(self, item, quantity=1):
# def add_item(self, quantity=1):
# def remove_item(self, quantity=1):
# def _calculate_subtotal(self):
which might include code, classes, or functions. Output only the next line. | Favorite.drop_table() |
Using the snippet: <|code_start|>
class UsersHandler(Resource):
"""
Handler for main user endpoint.
Implements:
* `get` method to retrieve the list of all the users
* `post` method to add a new user to the database.
"""
<|code_end|>
, determine the next line of code. You have imports:
from flask import request
from flask_restful import Resource
from http.client import (CREATED, NO_CONTENT, OK,
BAD_REQUEST, CONFLICT, UNAUTHORIZED)
from auth import auth
from models import User
from utils import generate_response
from notifications import notify_new_user
import uuid
and context (class names, function names, or code) available:
# Path: auth.py
# class Auth:
# def login_required(*args, **kwargs):
# def current_user(self):
# def init_app(app):
# def load_user(user_id):
# def load_user_from_request(request):
#
# Path: models.py
# class User(BaseModel, UserMixin):
# """
# User represents an user for the application.
#
# Attributes:
# first_name (str): User's first name
# last_name (str): User's last name
# email (str): User's **valid** email
# password (str): User's password
# admin (bool): User's admin status. Defaults to ``False``
#
# .. NOTE::
# Each User resource must have an unique `email` field, meaning
# that there cannot be two user's registered with the same email.
#
# For this reason, when checking for user's existence, the server requires
# either the `uuid` of the user or its `email`.
# """
# uuid = UUIDField(unique=True)
# first_name = CharField()
# last_name = CharField()
# email = CharField(unique=True)
# password = CharField()
# admin = BooleanField(default=False)
# _schema = UserSchema
#
# @staticmethod
# def exists(email):
# """
# Check that an user exists by checking the email field.
#
# Args:
# email (str): User's email to check
# """
# try:
# User.get(User.email == email)
# except User.DoesNotExist:
# return False
# return True
#
# @staticmethod
# def hash_password(password):
# """
# Use passlib to get a crypted password.
#
# Args:
# password (str): password to hash
#
# Returns:
# str: hashed password
# """
# return pbkdf2_sha256.hash(password)
#
# def verify_password(self, password):
# """
# Verify a clear password against the stored hashed password of the user
# using passlib.
#
# Args:
# password (str): Password to verify against the hashed stored password
# Returns:
# bool: wether the given email matches the stored one
# """
# return pbkdf2_sha256.verify(password, self.password)
#
# def add_favorite(user, item):
# """Link the favorite item to user."""
# return Favorite.create(
# uuid=uuid4(),
# item=item,
# user=user,
# )
#
# def delete_favorite(self, obj):
# obj.delete_instance()
#
# Path: utils.py
# def generate_response(data, status, mimetype='application/vnd.api+json'):
# """
# Given a resource model that extends from `BaseModel` generate a Reponse
# object to be returned from the application endpoints'
# """
# return Response(
# response=data,
# status=status,
# mimetype=mimetype
# )
#
# Path: notifications.py
# def notify_new_user(first_name, last_name):
# body = render_template('new_user.html', first_name=first_name, last_name=last_name)
# send_email("Nuovo Utente", body)
. Output only the next line. | @auth.login_required |
Given the code snippet: <|code_start|>
class UsersHandler(Resource):
"""
Handler for main user endpoint.
Implements:
* `get` method to retrieve the list of all the users
* `post` method to add a new user to the database.
"""
@auth.login_required
def get(self):
if not auth.current_user.admin:
return ({'message': "You can't get the list users."}, UNAUTHORIZED)
<|code_end|>
, generate the next line using the imports in this file:
from flask import request
from flask_restful import Resource
from http.client import (CREATED, NO_CONTENT, OK,
BAD_REQUEST, CONFLICT, UNAUTHORIZED)
from auth import auth
from models import User
from utils import generate_response
from notifications import notify_new_user
import uuid
and context (functions, classes, or occasionally code) from other files:
# Path: auth.py
# class Auth:
# def login_required(*args, **kwargs):
# def current_user(self):
# def init_app(app):
# def load_user(user_id):
# def load_user_from_request(request):
#
# Path: models.py
# class User(BaseModel, UserMixin):
# """
# User represents an user for the application.
#
# Attributes:
# first_name (str): User's first name
# last_name (str): User's last name
# email (str): User's **valid** email
# password (str): User's password
# admin (bool): User's admin status. Defaults to ``False``
#
# .. NOTE::
# Each User resource must have an unique `email` field, meaning
# that there cannot be two user's registered with the same email.
#
# For this reason, when checking for user's existence, the server requires
# either the `uuid` of the user or its `email`.
# """
# uuid = UUIDField(unique=True)
# first_name = CharField()
# last_name = CharField()
# email = CharField(unique=True)
# password = CharField()
# admin = BooleanField(default=False)
# _schema = UserSchema
#
# @staticmethod
# def exists(email):
# """
# Check that an user exists by checking the email field.
#
# Args:
# email (str): User's email to check
# """
# try:
# User.get(User.email == email)
# except User.DoesNotExist:
# return False
# return True
#
# @staticmethod
# def hash_password(password):
# """
# Use passlib to get a crypted password.
#
# Args:
# password (str): password to hash
#
# Returns:
# str: hashed password
# """
# return pbkdf2_sha256.hash(password)
#
# def verify_password(self, password):
# """
# Verify a clear password against the stored hashed password of the user
# using passlib.
#
# Args:
# password (str): Password to verify against the hashed stored password
# Returns:
# bool: wether the given email matches the stored one
# """
# return pbkdf2_sha256.verify(password, self.password)
#
# def add_favorite(user, item):
# """Link the favorite item to user."""
# return Favorite.create(
# uuid=uuid4(),
# item=item,
# user=user,
# )
#
# def delete_favorite(self, obj):
# obj.delete_instance()
#
# Path: utils.py
# def generate_response(data, status, mimetype='application/vnd.api+json'):
# """
# Given a resource model that extends from `BaseModel` generate a Reponse
# object to be returned from the application endpoints'
# """
# return Response(
# response=data,
# status=status,
# mimetype=mimetype
# )
#
# Path: notifications.py
# def notify_new_user(first_name, last_name):
# body = render_template('new_user.html', first_name=first_name, last_name=last_name)
# send_email("Nuovo Utente", body)
. Output only the next line. | data = User.json_list(User.select()) |
Here is a snippet: <|code_start|>
class UsersHandler(Resource):
"""
Handler for main user endpoint.
Implements:
* `get` method to retrieve the list of all the users
* `post` method to add a new user to the database.
"""
@auth.login_required
def get(self):
if not auth.current_user.admin:
return ({'message': "You can't get the list users."}, UNAUTHORIZED)
data = User.json_list(User.select())
<|code_end|>
. Write the next line using the current file imports:
from flask import request
from flask_restful import Resource
from http.client import (CREATED, NO_CONTENT, OK,
BAD_REQUEST, CONFLICT, UNAUTHORIZED)
from auth import auth
from models import User
from utils import generate_response
from notifications import notify_new_user
import uuid
and context from other files:
# Path: auth.py
# class Auth:
# def login_required(*args, **kwargs):
# def current_user(self):
# def init_app(app):
# def load_user(user_id):
# def load_user_from_request(request):
#
# Path: models.py
# class User(BaseModel, UserMixin):
# """
# User represents an user for the application.
#
# Attributes:
# first_name (str): User's first name
# last_name (str): User's last name
# email (str): User's **valid** email
# password (str): User's password
# admin (bool): User's admin status. Defaults to ``False``
#
# .. NOTE::
# Each User resource must have an unique `email` field, meaning
# that there cannot be two user's registered with the same email.
#
# For this reason, when checking for user's existence, the server requires
# either the `uuid` of the user or its `email`.
# """
# uuid = UUIDField(unique=True)
# first_name = CharField()
# last_name = CharField()
# email = CharField(unique=True)
# password = CharField()
# admin = BooleanField(default=False)
# _schema = UserSchema
#
# @staticmethod
# def exists(email):
# """
# Check that an user exists by checking the email field.
#
# Args:
# email (str): User's email to check
# """
# try:
# User.get(User.email == email)
# except User.DoesNotExist:
# return False
# return True
#
# @staticmethod
# def hash_password(password):
# """
# Use passlib to get a crypted password.
#
# Args:
# password (str): password to hash
#
# Returns:
# str: hashed password
# """
# return pbkdf2_sha256.hash(password)
#
# def verify_password(self, password):
# """
# Verify a clear password against the stored hashed password of the user
# using passlib.
#
# Args:
# password (str): Password to verify against the hashed stored password
# Returns:
# bool: wether the given email matches the stored one
# """
# return pbkdf2_sha256.verify(password, self.password)
#
# def add_favorite(user, item):
# """Link the favorite item to user."""
# return Favorite.create(
# uuid=uuid4(),
# item=item,
# user=user,
# )
#
# def delete_favorite(self, obj):
# obj.delete_instance()
#
# Path: utils.py
# def generate_response(data, status, mimetype='application/vnd.api+json'):
# """
# Given a resource model that extends from `BaseModel` generate a Reponse
# object to be returned from the application endpoints'
# """
# return Response(
# response=data,
# status=status,
# mimetype=mimetype
# )
#
# Path: notifications.py
# def notify_new_user(first_name, last_name):
# body = render_template('new_user.html', first_name=first_name, last_name=last_name)
# send_email("Nuovo Utente", body)
, which may include functions, classes, or code. Output only the next line. | return generate_response(data, OK) |
Here is a snippet: <|code_start|> def get(self):
if not auth.current_user.admin:
return ({'message': "You can't get the list users."}, UNAUTHORIZED)
data = User.json_list(User.select())
return generate_response(data, OK)
def post(self):
""" Add an user to the database."""
data = request.get_json(force=True)
errors = User.validate_input(data)
if errors:
return errors, BAD_REQUEST
# Extract the user attributes to check and generate the User row
data = data['data']['attributes']
# If email is present in the database return a BAD_REQUEST response.
if User.exists(data['email']):
msg = {'message': 'email already present.'}
return msg, CONFLICT
new_user = User.create(
uuid=uuid.uuid4(),
first_name=data['first_name'],
last_name=data['last_name'],
email=data['email'],
password=User.hash_password(data['password'])
)
<|code_end|>
. Write the next line using the current file imports:
from flask import request
from flask_restful import Resource
from http.client import (CREATED, NO_CONTENT, OK,
BAD_REQUEST, CONFLICT, UNAUTHORIZED)
from auth import auth
from models import User
from utils import generate_response
from notifications import notify_new_user
import uuid
and context from other files:
# Path: auth.py
# class Auth:
# def login_required(*args, **kwargs):
# def current_user(self):
# def init_app(app):
# def load_user(user_id):
# def load_user_from_request(request):
#
# Path: models.py
# class User(BaseModel, UserMixin):
# """
# User represents an user for the application.
#
# Attributes:
# first_name (str): User's first name
# last_name (str): User's last name
# email (str): User's **valid** email
# password (str): User's password
# admin (bool): User's admin status. Defaults to ``False``
#
# .. NOTE::
# Each User resource must have an unique `email` field, meaning
# that there cannot be two user's registered with the same email.
#
# For this reason, when checking for user's existence, the server requires
# either the `uuid` of the user or its `email`.
# """
# uuid = UUIDField(unique=True)
# first_name = CharField()
# last_name = CharField()
# email = CharField(unique=True)
# password = CharField()
# admin = BooleanField(default=False)
# _schema = UserSchema
#
# @staticmethod
# def exists(email):
# """
# Check that an user exists by checking the email field.
#
# Args:
# email (str): User's email to check
# """
# try:
# User.get(User.email == email)
# except User.DoesNotExist:
# return False
# return True
#
# @staticmethod
# def hash_password(password):
# """
# Use passlib to get a crypted password.
#
# Args:
# password (str): password to hash
#
# Returns:
# str: hashed password
# """
# return pbkdf2_sha256.hash(password)
#
# def verify_password(self, password):
# """
# Verify a clear password against the stored hashed password of the user
# using passlib.
#
# Args:
# password (str): Password to verify against the hashed stored password
# Returns:
# bool: wether the given email matches the stored one
# """
# return pbkdf2_sha256.verify(password, self.password)
#
# def add_favorite(user, item):
# """Link the favorite item to user."""
# return Favorite.create(
# uuid=uuid4(),
# item=item,
# user=user,
# )
#
# def delete_favorite(self, obj):
# obj.delete_instance()
#
# Path: utils.py
# def generate_response(data, status, mimetype='application/vnd.api+json'):
# """
# Given a resource model that extends from `BaseModel` generate a Reponse
# object to be returned from the application endpoints'
# """
# return Response(
# response=data,
# status=status,
# mimetype=mimetype
# )
#
# Path: notifications.py
# def notify_new_user(first_name, last_name):
# body = render_template('new_user.html', first_name=first_name, last_name=last_name)
# send_email("Nuovo Utente", body)
, which may include functions, classes, or code. Output only the next line. | notify_new_user(first_name=new_user.first_name, |
Predict the next line after this snippet: <|code_start|>
ALLOWED_EXTENSION = ['jpg', 'jpeg', 'png', 'gif']
class ItemPictureHandler(Resource):
def get(self, item_uuid):
"""Retrieve every picture of an item"""
<|code_end|>
using the current file's imports:
import http.client as client
import os
import uuid
import utils
from flask import request, send_from_directory
from flask_restful import Resource
from models import Item, Picture
from utils import generate_response
and any relevant context from other files:
# Path: models.py
# class Item(BaseModel):
# """
# Item describes a product for the e-commerce platform.
#
# Attributes:
# uuid (UUID): Item UUID
# name (str): Name for the product
# price (decimal.Decimal): Price for a single product
# description (str): Product description
# availability (int): Quantity of items available
# category (str): Category group of the item
#
# """
# uuid = UUIDField(unique=True)
# name = CharField()
# price = DecimalField(auto_round=True)
# description = TextField()
# availability = IntegerField()
# category = TextField()
# _schema = ItemSchema
# _search_attributes = ['name', 'category', 'description']
#
# def __str__(self):
# return '{}, {}, {}, {}'.format(
# self.uuid,
# self.name,
# self.price,
# self.description)
#
# def is_favorite(self, item):
# for f in self.favorites:
# if f.item_id == item.id:
# return True
# return False
#
# class Picture(BaseModel):
# """
# A Picture model describes and points to a stored image file. Allows linkage
# between the image files and one :any:`Item` resource.
#
# Attributes:
# uuid (UUID): Picture's uuid
# extension (str): Extension of the image file the Picture's model refer to
# item (:any:`Item`): Foreign key referencing the Item related to the Picture.
# A ``pictures`` field can be used from ``Item`` to access the Item resource
# pictures
# """
# uuid = UUIDField(unique=True)
# extension = CharField()
# item = ForeignKeyField(Item, related_name='pictures')
# _schema = PictureSchema
#
# @property
# def filename(self):
# """Full name (uuid.ext) of the file that the Picture model reference."""
# return '{}.{}'.format(
# self.uuid,
# self.extension)
#
# def __str__(self):
# return '{}.{} -> item: {}'.format(
# self.uuid,
# self.extension,
# self.item.uuid)
#
# Path: utils.py
# def generate_response(data, status, mimetype='application/vnd.api+json'):
# """
# Given a resource model that extends from `BaseModel` generate a Reponse
# object to be returned from the application endpoints'
# """
# return Response(
# response=data,
# status=status,
# mimetype=mimetype
# )
. Output only the next line. | pictures = Picture.select().join(Item).where(Item.uuid == item_uuid) |
Based on the snippet: <|code_start|>
ALLOWED_EXTENSION = ['jpg', 'jpeg', 'png', 'gif']
class ItemPictureHandler(Resource):
def get(self, item_uuid):
"""Retrieve every picture of an item"""
<|code_end|>
, predict the immediate next line with the help of imports:
import http.client as client
import os
import uuid
import utils
from flask import request, send_from_directory
from flask_restful import Resource
from models import Item, Picture
from utils import generate_response
and context (classes, functions, sometimes code) from other files:
# Path: models.py
# class Item(BaseModel):
# """
# Item describes a product for the e-commerce platform.
#
# Attributes:
# uuid (UUID): Item UUID
# name (str): Name for the product
# price (decimal.Decimal): Price for a single product
# description (str): Product description
# availability (int): Quantity of items available
# category (str): Category group of the item
#
# """
# uuid = UUIDField(unique=True)
# name = CharField()
# price = DecimalField(auto_round=True)
# description = TextField()
# availability = IntegerField()
# category = TextField()
# _schema = ItemSchema
# _search_attributes = ['name', 'category', 'description']
#
# def __str__(self):
# return '{}, {}, {}, {}'.format(
# self.uuid,
# self.name,
# self.price,
# self.description)
#
# def is_favorite(self, item):
# for f in self.favorites:
# if f.item_id == item.id:
# return True
# return False
#
# class Picture(BaseModel):
# """
# A Picture model describes and points to a stored image file. Allows linkage
# between the image files and one :any:`Item` resource.
#
# Attributes:
# uuid (UUID): Picture's uuid
# extension (str): Extension of the image file the Picture's model refer to
# item (:any:`Item`): Foreign key referencing the Item related to the Picture.
# A ``pictures`` field can be used from ``Item`` to access the Item resource
# pictures
# """
# uuid = UUIDField(unique=True)
# extension = CharField()
# item = ForeignKeyField(Item, related_name='pictures')
# _schema = PictureSchema
#
# @property
# def filename(self):
# """Full name (uuid.ext) of the file that the Picture model reference."""
# return '{}.{}'.format(
# self.uuid,
# self.extension)
#
# def __str__(self):
# return '{}.{} -> item: {}'.format(
# self.uuid,
# self.extension,
# self.item.uuid)
#
# Path: utils.py
# def generate_response(data, status, mimetype='application/vnd.api+json'):
# """
# Given a resource model that extends from `BaseModel` generate a Reponse
# object to be returned from the application endpoints'
# """
# return Response(
# response=data,
# status=status,
# mimetype=mimetype
# )
. Output only the next line. | pictures = Picture.select().join(Item).where(Item.uuid == item_uuid) |
Based on the snippet: <|code_start|>
ALLOWED_EXTENSION = ['jpg', 'jpeg', 'png', 'gif']
class ItemPictureHandler(Resource):
def get(self, item_uuid):
"""Retrieve every picture of an item"""
pictures = Picture.select().join(Item).where(Item.uuid == item_uuid)
if pictures:
data = Picture.json_list(pictures)
<|code_end|>
, predict the immediate next line with the help of imports:
import http.client as client
import os
import uuid
import utils
from flask import request, send_from_directory
from flask_restful import Resource
from models import Item, Picture
from utils import generate_response
and context (classes, functions, sometimes code) from other files:
# Path: models.py
# class Item(BaseModel):
# """
# Item describes a product for the e-commerce platform.
#
# Attributes:
# uuid (UUID): Item UUID
# name (str): Name for the product
# price (decimal.Decimal): Price for a single product
# description (str): Product description
# availability (int): Quantity of items available
# category (str): Category group of the item
#
# """
# uuid = UUIDField(unique=True)
# name = CharField()
# price = DecimalField(auto_round=True)
# description = TextField()
# availability = IntegerField()
# category = TextField()
# _schema = ItemSchema
# _search_attributes = ['name', 'category', 'description']
#
# def __str__(self):
# return '{}, {}, {}, {}'.format(
# self.uuid,
# self.name,
# self.price,
# self.description)
#
# def is_favorite(self, item):
# for f in self.favorites:
# if f.item_id == item.id:
# return True
# return False
#
# class Picture(BaseModel):
# """
# A Picture model describes and points to a stored image file. Allows linkage
# between the image files and one :any:`Item` resource.
#
# Attributes:
# uuid (UUID): Picture's uuid
# extension (str): Extension of the image file the Picture's model refer to
# item (:any:`Item`): Foreign key referencing the Item related to the Picture.
# A ``pictures`` field can be used from ``Item`` to access the Item resource
# pictures
# """
# uuid = UUIDField(unique=True)
# extension = CharField()
# item = ForeignKeyField(Item, related_name='pictures')
# _schema = PictureSchema
#
# @property
# def filename(self):
# """Full name (uuid.ext) of the file that the Picture model reference."""
# return '{}.{}'.format(
# self.uuid,
# self.extension)
#
# def __str__(self):
# return '{}.{} -> item: {}'.format(
# self.uuid,
# self.extension,
# self.item.uuid)
#
# Path: utils.py
# def generate_response(data, status, mimetype='application/vnd.api+json'):
# """
# Given a resource model that extends from `BaseModel` generate a Reponse
# object to be returned from the application endpoints'
# """
# return Response(
# response=data,
# status=status,
# mimetype=mimetype
# )
. Output only the next line. | return generate_response(data, client.OK) |
Given the code snippet: <|code_start|>
class FavoritesHandler(Resource):
@auth.login_required
def get(self):
<|code_end|>
, generate the next line using the imports in this file:
from auth import auth
from flask import request
from flask_restful import Resource
from models import Favorite, Item
from http.client import (CREATED, NOT_FOUND, OK, BAD_REQUEST)
from utils import generate_response
and context (functions, classes, or occasionally code) from other files:
# Path: auth.py
# class Auth:
# def login_required(*args, **kwargs):
# def current_user(self):
# def init_app(app):
# def load_user(user_id):
# def load_user_from_request(request):
#
# Path: models.py
# class Favorite(BaseModel):
# """ Many to many table to relate an item with a user."""
# uuid = UUIDField(unique=True)
# user = ForeignKeyField(User, related_name="favorites")
# item = ForeignKeyField(Item, related_name="favorites")
# _schema = FavoriteSchema
#
# class Item(BaseModel):
# """
# Item describes a product for the e-commerce platform.
#
# Attributes:
# uuid (UUID): Item UUID
# name (str): Name for the product
# price (decimal.Decimal): Price for a single product
# description (str): Product description
# availability (int): Quantity of items available
# category (str): Category group of the item
#
# """
# uuid = UUIDField(unique=True)
# name = CharField()
# price = DecimalField(auto_round=True)
# description = TextField()
# availability = IntegerField()
# category = TextField()
# _schema = ItemSchema
# _search_attributes = ['name', 'category', 'description']
#
# def __str__(self):
# return '{}, {}, {}, {}'.format(
# self.uuid,
# self.name,
# self.price,
# self.description)
#
# def is_favorite(self, item):
# for f in self.favorites:
# if f.item_id == item.id:
# return True
# return False
#
# Path: utils.py
# def generate_response(data, status, mimetype='application/vnd.api+json'):
# """
# Given a resource model that extends from `BaseModel` generate a Reponse
# object to be returned from the application endpoints'
# """
# return Response(
# response=data,
# status=status,
# mimetype=mimetype
# )
. Output only the next line. | data = Favorite.json_list(auth.current_user.favorites) |
Continue the code snippet: <|code_start|>
class FavoritesHandler(Resource):
@auth.login_required
def get(self):
data = Favorite.json_list(auth.current_user.favorites)
return generate_response(data, OK)
@auth.login_required
def post(self):
user = auth.current_user
res = request.get_json(force=True)
errors = Favorite.validate_input(res)
if errors:
return errors, BAD_REQUEST
data = res['data']['attributes']
try:
<|code_end|>
. Use current file imports:
from auth import auth
from flask import request
from flask_restful import Resource
from models import Favorite, Item
from http.client import (CREATED, NOT_FOUND, OK, BAD_REQUEST)
from utils import generate_response
and context (classes, functions, or code) from other files:
# Path: auth.py
# class Auth:
# def login_required(*args, **kwargs):
# def current_user(self):
# def init_app(app):
# def load_user(user_id):
# def load_user_from_request(request):
#
# Path: models.py
# class Favorite(BaseModel):
# """ Many to many table to relate an item with a user."""
# uuid = UUIDField(unique=True)
# user = ForeignKeyField(User, related_name="favorites")
# item = ForeignKeyField(Item, related_name="favorites")
# _schema = FavoriteSchema
#
# class Item(BaseModel):
# """
# Item describes a product for the e-commerce platform.
#
# Attributes:
# uuid (UUID): Item UUID
# name (str): Name for the product
# price (decimal.Decimal): Price for a single product
# description (str): Product description
# availability (int): Quantity of items available
# category (str): Category group of the item
#
# """
# uuid = UUIDField(unique=True)
# name = CharField()
# price = DecimalField(auto_round=True)
# description = TextField()
# availability = IntegerField()
# category = TextField()
# _schema = ItemSchema
# _search_attributes = ['name', 'category', 'description']
#
# def __str__(self):
# return '{}, {}, {}, {}'.format(
# self.uuid,
# self.name,
# self.price,
# self.description)
#
# def is_favorite(self, item):
# for f in self.favorites:
# if f.item_id == item.id:
# return True
# return False
#
# Path: utils.py
# def generate_response(data, status, mimetype='application/vnd.api+json'):
# """
# Given a resource model that extends from `BaseModel` generate a Reponse
# object to be returned from the application endpoints'
# """
# return Response(
# response=data,
# status=status,
# mimetype=mimetype
# )
. Output only the next line. | item = Item.get(Item.uuid == data['item_uuid']) |
Based on the snippet: <|code_start|>
class FavoritesHandler(Resource):
@auth.login_required
def get(self):
data = Favorite.json_list(auth.current_user.favorites)
<|code_end|>
, predict the immediate next line with the help of imports:
from auth import auth
from flask import request
from flask_restful import Resource
from models import Favorite, Item
from http.client import (CREATED, NOT_FOUND, OK, BAD_REQUEST)
from utils import generate_response
and context (classes, functions, sometimes code) from other files:
# Path: auth.py
# class Auth:
# def login_required(*args, **kwargs):
# def current_user(self):
# def init_app(app):
# def load_user(user_id):
# def load_user_from_request(request):
#
# Path: models.py
# class Favorite(BaseModel):
# """ Many to many table to relate an item with a user."""
# uuid = UUIDField(unique=True)
# user = ForeignKeyField(User, related_name="favorites")
# item = ForeignKeyField(Item, related_name="favorites")
# _schema = FavoriteSchema
#
# class Item(BaseModel):
# """
# Item describes a product for the e-commerce platform.
#
# Attributes:
# uuid (UUID): Item UUID
# name (str): Name for the product
# price (decimal.Decimal): Price for a single product
# description (str): Product description
# availability (int): Quantity of items available
# category (str): Category group of the item
#
# """
# uuid = UUIDField(unique=True)
# name = CharField()
# price = DecimalField(auto_round=True)
# description = TextField()
# availability = IntegerField()
# category = TextField()
# _schema = ItemSchema
# _search_attributes = ['name', 'category', 'description']
#
# def __str__(self):
# return '{}, {}, {}, {}'.format(
# self.uuid,
# self.name,
# self.price,
# self.description)
#
# def is_favorite(self, item):
# for f in self.favorites:
# if f.item_id == item.id:
# return True
# return False
#
# Path: utils.py
# def generate_response(data, status, mimetype='application/vnd.api+json'):
# """
# Given a resource model that extends from `BaseModel` generate a Reponse
# object to be returned from the application endpoints'
# """
# return Response(
# response=data,
# status=status,
# mimetype=mimetype
# )
. Output only the next line. | return generate_response(data, OK) |
Using the snippet: <|code_start|>
AUTH_API_ENDPOINT = '/auth/login/'
TEST_USER_PASSWORD = 'user_password'
TEST_USER_WRONG_PASSWORD = 'wrong_password'
<|code_end|>
, determine the next line of code. You have imports:
import json
from http.client import BAD_REQUEST, OK, UNAUTHORIZED
from tests.test_case import TestCase
from tests.test_utils import add_user
and context (class names, function names, or code) available:
# Path: tests/test_case.py
# class TestCase:
# """
# Created TestCase to avoid duplicated code in the other tests
# """
# TEST_DB = SqliteDatabase(':memory:')
#
# @classmethod
# def setup_class(cls):
# """
# When a Test is created override the ``database`` attribute for all
# the tables with a SqliteDatabase in memory.
# """
# for table in TABLES:
# table._meta.database = cls.TEST_DB
# table.create_table(fail_silently=True)
#
# cls.app = app.test_client()
#
# def setup_method(self):
# """
# When setting up a new test method clear all the tables
# """
# for table in TABLES:
# table.delete().execute()
#
# Path: tests/test_utils.py
# def add_user(email, password, id=None, first_name='John', last_name='Doe'):
# """
# Create a single user in the test database.
# If an email is provided it will be used, otherwise it will be generated
# by the function before adding the User to the database.
# """
# email = email or 'johndoe{}@email.com'.format(int(random.random() * 100))
#
# return User.create(
# first_name=first_name,
# last_name=last_name,
# email=email,
# password=User.hash_password(password),
# uuid=id or uuid.uuid4(),
# )
. Output only the next line. | class TestAuth(TestCase): |
Next line prediction: <|code_start|>
AUTH_API_ENDPOINT = '/auth/login/'
TEST_USER_PASSWORD = 'user_password'
TEST_USER_WRONG_PASSWORD = 'wrong_password'
class TestAuth(TestCase):
def test_post_auth__success(self):
<|code_end|>
. Use current file imports:
(import json
from http.client import BAD_REQUEST, OK, UNAUTHORIZED
from tests.test_case import TestCase
from tests.test_utils import add_user)
and context including class names, function names, or small code snippets from other files:
# Path: tests/test_case.py
# class TestCase:
# """
# Created TestCase to avoid duplicated code in the other tests
# """
# TEST_DB = SqliteDatabase(':memory:')
#
# @classmethod
# def setup_class(cls):
# """
# When a Test is created override the ``database`` attribute for all
# the tables with a SqliteDatabase in memory.
# """
# for table in TABLES:
# table._meta.database = cls.TEST_DB
# table.create_table(fail_silently=True)
#
# cls.app = app.test_client()
#
# def setup_method(self):
# """
# When setting up a new test method clear all the tables
# """
# for table in TABLES:
# table.delete().execute()
#
# Path: tests/test_utils.py
# def add_user(email, password, id=None, first_name='John', last_name='Doe'):
# """
# Create a single user in the test database.
# If an email is provided it will be used, otherwise it will be generated
# by the function before adding the User to the database.
# """
# email = email or 'johndoe{}@email.com'.format(int(random.random() * 100))
#
# return User.create(
# first_name=first_name,
# last_name=last_name,
# email=email,
# password=User.hash_password(password),
# uuid=id or uuid.uuid4(),
# )
. Output only the next line. | user = add_user('user@email.com', TEST_USER_PASSWORD) |
Predict the next line for this snippet: <|code_start|>
NAMES = [
'scarpe', 'scarpine', 'scarpette', 'scarpe da ballo',
'scarpe da ginnastica', 'scarponi', 'scarpacce',
'sedie', 'sedie deco', 'sedie da cucina', 'set di sedie',
'tavolo con sedie', 'tavolo con set di sedie', 'divano', 'divano letto',
'letto', 'letto singolo', 'letto matrimoniale', 'letto francese',
'poltrona', 'poltrona elettrica', 'sgabello', 'maglietta', 'canottiera',
'pantaloni', 'mutande', 'tavolo', 'tavolo da cucina', 'tavolino', 'tavola',
'tavola di legno', 'legno di tavola',
]
def get_names(objects):
return [r.name for r in objects]
class TestSearchItems(TestCase):
@classmethod
def setup_class(cls):
super(TestSearchItems, cls).setup_class()
<|code_end|>
with the help of current file imports:
import json
import search
from models import Item
from tests import test_utils
from tests.test_case import TestCase
and context from other files:
# Path: models.py
# class Item(BaseModel):
# """
# Item describes a product for the e-commerce platform.
#
# Attributes:
# uuid (UUID): Item UUID
# name (str): Name for the product
# price (decimal.Decimal): Price for a single product
# description (str): Product description
# availability (int): Quantity of items available
# category (str): Category group of the item
#
# """
# uuid = UUIDField(unique=True)
# name = CharField()
# price = DecimalField(auto_round=True)
# description = TextField()
# availability = IntegerField()
# category = TextField()
# _schema = ItemSchema
# _search_attributes = ['name', 'category', 'description']
#
# def __str__(self):
# return '{}, {}, {}, {}'.format(
# self.uuid,
# self.name,
# self.price,
# self.description)
#
# def is_favorite(self, item):
# for f in self.favorites:
# if f.item_id == item.id:
# return True
# return False
#
# Path: tests/test_utils.py
# def mock_uuid_generator():
# def mock_datetime(*args):
# def __init__(self, cls):
# def __call__(self, created_at=mock_datetime(), uuid=None, **query):
# def get_all_models_names():
# def add_user(email, password, id=None, first_name='John', last_name='Doe'):
# def add_admin_user(email, psw, id=None):
# def add_address(user, country='Italy', city='Pistoia', post_code='51100',
# address='Via Verdi 12', phone='3294882773', id=None):
# def add_favorite(user, item, id=None):
# def json_favorite(item):
# def add_item(name='Item Test', price='15.99',
# description='test test test', id=None, category='scarpe'):
# def open_with_auth(app, url, method, username, password, content_type, data):
# def clean_images():
# def setup_images():
# def count_order_items(order):
# def format_jsonapi_request(type_, data):
# def assert_valid_response(data, expected):
# def sort_data_lists(data, attribute, key):
# def included_sorter(i): return i['type']
# def errors_sorter(e): return e['source']['pointer']
# def wrong_dump(data):
# class MockModelCreate:
# AUTH_TYPE = 'Basic'
# RESULTS = json.load(fo)
#
# Path: tests/test_case.py
# class TestCase:
# """
# Created TestCase to avoid duplicated code in the other tests
# """
# TEST_DB = SqliteDatabase(':memory:')
#
# @classmethod
# def setup_class(cls):
# """
# When a Test is created override the ``database`` attribute for all
# the tables with a SqliteDatabase in memory.
# """
# for table in TABLES:
# table._meta.database = cls.TEST_DB
# table.create_table(fail_silently=True)
#
# cls.app = app.test_client()
#
# def setup_method(self):
# """
# When setting up a new test method clear all the tables
# """
# for table in TABLES:
# table.delete().execute()
, which may contain function names, class names, or code. Output only the next line. | Item.delete().execute() |
Using the snippet: <|code_start|>
NAMES = [
'scarpe', 'scarpine', 'scarpette', 'scarpe da ballo',
'scarpe da ginnastica', 'scarponi', 'scarpacce',
'sedie', 'sedie deco', 'sedie da cucina', 'set di sedie',
'tavolo con sedie', 'tavolo con set di sedie', 'divano', 'divano letto',
'letto', 'letto singolo', 'letto matrimoniale', 'letto francese',
'poltrona', 'poltrona elettrica', 'sgabello', 'maglietta', 'canottiera',
'pantaloni', 'mutande', 'tavolo', 'tavolo da cucina', 'tavolino', 'tavola',
'tavola di legno', 'legno di tavola',
]
def get_names(objects):
return [r.name for r in objects]
class TestSearchItems(TestCase):
@classmethod
def setup_class(cls):
super(TestSearchItems, cls).setup_class()
Item.delete().execute()
for name in NAMES:
<|code_end|>
, determine the next line of code. You have imports:
import json
import search
from models import Item
from tests import test_utils
from tests.test_case import TestCase
and context (class names, function names, or code) available:
# Path: models.py
# class Item(BaseModel):
# """
# Item describes a product for the e-commerce platform.
#
# Attributes:
# uuid (UUID): Item UUID
# name (str): Name for the product
# price (decimal.Decimal): Price for a single product
# description (str): Product description
# availability (int): Quantity of items available
# category (str): Category group of the item
#
# """
# uuid = UUIDField(unique=True)
# name = CharField()
# price = DecimalField(auto_round=True)
# description = TextField()
# availability = IntegerField()
# category = TextField()
# _schema = ItemSchema
# _search_attributes = ['name', 'category', 'description']
#
# def __str__(self):
# return '{}, {}, {}, {}'.format(
# self.uuid,
# self.name,
# self.price,
# self.description)
#
# def is_favorite(self, item):
# for f in self.favorites:
# if f.item_id == item.id:
# return True
# return False
#
# Path: tests/test_utils.py
# def mock_uuid_generator():
# def mock_datetime(*args):
# def __init__(self, cls):
# def __call__(self, created_at=mock_datetime(), uuid=None, **query):
# def get_all_models_names():
# def add_user(email, password, id=None, first_name='John', last_name='Doe'):
# def add_admin_user(email, psw, id=None):
# def add_address(user, country='Italy', city='Pistoia', post_code='51100',
# address='Via Verdi 12', phone='3294882773', id=None):
# def add_favorite(user, item, id=None):
# def json_favorite(item):
# def add_item(name='Item Test', price='15.99',
# description='test test test', id=None, category='scarpe'):
# def open_with_auth(app, url, method, username, password, content_type, data):
# def clean_images():
# def setup_images():
# def count_order_items(order):
# def format_jsonapi_request(type_, data):
# def assert_valid_response(data, expected):
# def sort_data_lists(data, attribute, key):
# def included_sorter(i): return i['type']
# def errors_sorter(e): return e['source']['pointer']
# def wrong_dump(data):
# class MockModelCreate:
# AUTH_TYPE = 'Basic'
# RESULTS = json.load(fo)
#
# Path: tests/test_case.py
# class TestCase:
# """
# Created TestCase to avoid duplicated code in the other tests
# """
# TEST_DB = SqliteDatabase(':memory:')
#
# @classmethod
# def setup_class(cls):
# """
# When a Test is created override the ``database`` attribute for all
# the tables with a SqliteDatabase in memory.
# """
# for table in TABLES:
# table._meta.database = cls.TEST_DB
# table.create_table(fail_silently=True)
#
# cls.app = app.test_client()
#
# def setup_method(self):
# """
# When setting up a new test method clear all the tables
# """
# for table in TABLES:
# table.delete().execute()
. Output only the next line. | test_utils.add_item( |
Next line prediction: <|code_start|>
NAMES = [
'scarpe', 'scarpine', 'scarpette', 'scarpe da ballo',
'scarpe da ginnastica', 'scarponi', 'scarpacce',
'sedie', 'sedie deco', 'sedie da cucina', 'set di sedie',
'tavolo con sedie', 'tavolo con set di sedie', 'divano', 'divano letto',
'letto', 'letto singolo', 'letto matrimoniale', 'letto francese',
'poltrona', 'poltrona elettrica', 'sgabello', 'maglietta', 'canottiera',
'pantaloni', 'mutande', 'tavolo', 'tavolo da cucina', 'tavolino', 'tavola',
'tavola di legno', 'legno di tavola',
]
def get_names(objects):
return [r.name for r in objects]
<|code_end|>
. Use current file imports:
(import json
import search
from models import Item
from tests import test_utils
from tests.test_case import TestCase)
and context including class names, function names, or small code snippets from other files:
# Path: models.py
# class Item(BaseModel):
# """
# Item describes a product for the e-commerce platform.
#
# Attributes:
# uuid (UUID): Item UUID
# name (str): Name for the product
# price (decimal.Decimal): Price for a single product
# description (str): Product description
# availability (int): Quantity of items available
# category (str): Category group of the item
#
# """
# uuid = UUIDField(unique=True)
# name = CharField()
# price = DecimalField(auto_round=True)
# description = TextField()
# availability = IntegerField()
# category = TextField()
# _schema = ItemSchema
# _search_attributes = ['name', 'category', 'description']
#
# def __str__(self):
# return '{}, {}, {}, {}'.format(
# self.uuid,
# self.name,
# self.price,
# self.description)
#
# def is_favorite(self, item):
# for f in self.favorites:
# if f.item_id == item.id:
# return True
# return False
#
# Path: tests/test_utils.py
# def mock_uuid_generator():
# def mock_datetime(*args):
# def __init__(self, cls):
# def __call__(self, created_at=mock_datetime(), uuid=None, **query):
# def get_all_models_names():
# def add_user(email, password, id=None, first_name='John', last_name='Doe'):
# def add_admin_user(email, psw, id=None):
# def add_address(user, country='Italy', city='Pistoia', post_code='51100',
# address='Via Verdi 12', phone='3294882773', id=None):
# def add_favorite(user, item, id=None):
# def json_favorite(item):
# def add_item(name='Item Test', price='15.99',
# description='test test test', id=None, category='scarpe'):
# def open_with_auth(app, url, method, username, password, content_type, data):
# def clean_images():
# def setup_images():
# def count_order_items(order):
# def format_jsonapi_request(type_, data):
# def assert_valid_response(data, expected):
# def sort_data_lists(data, attribute, key):
# def included_sorter(i): return i['type']
# def errors_sorter(e): return e['source']['pointer']
# def wrong_dump(data):
# class MockModelCreate:
# AUTH_TYPE = 'Basic'
# RESULTS = json.load(fo)
#
# Path: tests/test_case.py
# class TestCase:
# """
# Created TestCase to avoid duplicated code in the other tests
# """
# TEST_DB = SqliteDatabase(':memory:')
#
# @classmethod
# def setup_class(cls):
# """
# When a Test is created override the ``database`` attribute for all
# the tables with a SqliteDatabase in memory.
# """
# for table in TABLES:
# table._meta.database = cls.TEST_DB
# table.create_table(fail_silently=True)
#
# cls.app = app.test_client()
#
# def setup_method(self):
# """
# When setting up a new test method clear all the tables
# """
# for table in TABLES:
# table.delete().execute()
. Output only the next line. | class TestSearchItems(TestCase): |
Based on the snippet: <|code_start|>"""
Orders-view: this module contains functions for the interaction with the orders.
"""
class OrdersHandler(Resource):
""" Orders endpoint. """
def get(self):
""" Get all the orders."""
data = Order.json_list(Order.select())
return generate_response(data, OK)
<|code_end|>
, predict the immediate next line with the help of imports:
from http.client import (BAD_REQUEST, CREATED, NO_CONTENT, NOT_FOUND, OK,
UNAUTHORIZED)
from flask import abort, request
from flask_restful import Resource
from auth import auth
from models import database, Address, Order, Item, User
from notifications import notify_new_order
from utils import generate_response
from exceptions import InsufficientAvailabilityException
and context (classes, functions, sometimes code) from other files:
# Path: auth.py
# class Auth:
# def login_required(*args, **kwargs):
# def current_user(self):
# def init_app(app):
# def load_user(user_id):
# def load_user_from_request(request):
#
# Path: models.py
# ENVIRONMENT = os.getenv('ENVIRONMENT', 'dev')
# class BaseModel(Model):
# class Meta:
# class Item(BaseModel):
# class Picture(BaseModel):
# class User(BaseModel, UserMixin):
# class Address(BaseModel):
# class Order(BaseModel):
# class Meta:
# class OrderItem(BaseModel):
# class Favorite(BaseModel):
# def save(self, *args, **kwargs):
# def json_list(cls, objs_list):
# def json(self, include_data=[]):
# def validate_input(cls, data, partial=False):
# def search(cls, query, dataset, limit=-1,
# attributes=None, weights=None,
# threshold=search.config.THRESHOLD):
# def __str__(self):
# def is_favorite(self, item):
# def on_delete_item_handler(model_class, instance):
# def filename(self):
# def __str__(self):
# def on_delete_picture_handler(model_class, instance):
# def exists(email):
# def hash_password(password):
# def verify_password(self, password):
# def add_favorite(user, item):
# def delete_favorite(self, obj):
# def order_items(self):
# def empty_order(self):
# def create_order(user, address, items):
# def update_items(self, items, update_total=True, new_address=None):
# def edit_items_quantity(self, items):
# def delete_items(self, items):
# def create_items(self, items):
# def add_item(self, item, quantity=1):
# def remove_item(self, item, quantity=1):
# def add_item(self, quantity=1):
# def remove_item(self, quantity=1):
# def _calculate_subtotal(self):
#
# Path: notifications.py
# def notify_new_order(address, user):
# body = render_template('new_order.html', address=address, user=user)
# send_email("Nuovo Ordine", body)
#
# Path: utils.py
# def generate_response(data, status, mimetype='application/vnd.api+json'):
# """
# Given a resource model that extends from `BaseModel` generate a Reponse
# object to be returned from the application endpoints'
# """
# return Response(
# response=data,
# status=status,
# mimetype=mimetype
# )
#
# Path: exceptions.py
# class InsufficientAvailabilityException(Exception):
#
# def __init__(self, item, requested_quantity):
# super(Exception, self).__init__(
# "Item availability {}, requested {}".format(
# item.availability,
# requested_quantity))
#
# self.item = item
# self.requested_quantity = requested_quantity
. Output only the next line. | @auth.login_required |
Predict the next line after this snippet: <|code_start|> try:
user = User.get(User.uuid == req_user['id'])
except User.DoesNotExist:
abort(BAD_REQUEST)
# get the user from the flask.g global object registered inside the
# auth.py::verify() function, called by @auth.login_required decorator
# and match it against the found user.
# This is to prevent users from creating other users' order.
if auth.current_user != user and auth.current_user.admin is False:
return ({'message': "You can't create a new order for another user"},
UNAUTHORIZED)
# Check that the items exist
item_ids = [req_item['id'] for req_item in req_items]
items = Item.select().where(Item.uuid << item_ids)
if items.count() != len(req_items):
abort(BAD_REQUEST)
# Check that the address exist
try:
address = Address.get(Address.uuid == req_address['id'])
except Address.DoesNotExist:
abort(BAD_REQUEST)
# Generate the dict of {<Item>: <int:quantity>} to call Order.create_order
items_to_add = {}
for req_item in req_items:
item = next(i for i in items if str(i.uuid) == req_item['id'])
items_to_add[item] = req_item['quantity']
<|code_end|>
using the current file's imports:
from http.client import (BAD_REQUEST, CREATED, NO_CONTENT, NOT_FOUND, OK,
UNAUTHORIZED)
from flask import abort, request
from flask_restful import Resource
from auth import auth
from models import database, Address, Order, Item, User
from notifications import notify_new_order
from utils import generate_response
from exceptions import InsufficientAvailabilityException
and any relevant context from other files:
# Path: auth.py
# class Auth:
# def login_required(*args, **kwargs):
# def current_user(self):
# def init_app(app):
# def load_user(user_id):
# def load_user_from_request(request):
#
# Path: models.py
# ENVIRONMENT = os.getenv('ENVIRONMENT', 'dev')
# class BaseModel(Model):
# class Meta:
# class Item(BaseModel):
# class Picture(BaseModel):
# class User(BaseModel, UserMixin):
# class Address(BaseModel):
# class Order(BaseModel):
# class Meta:
# class OrderItem(BaseModel):
# class Favorite(BaseModel):
# def save(self, *args, **kwargs):
# def json_list(cls, objs_list):
# def json(self, include_data=[]):
# def validate_input(cls, data, partial=False):
# def search(cls, query, dataset, limit=-1,
# attributes=None, weights=None,
# threshold=search.config.THRESHOLD):
# def __str__(self):
# def is_favorite(self, item):
# def on_delete_item_handler(model_class, instance):
# def filename(self):
# def __str__(self):
# def on_delete_picture_handler(model_class, instance):
# def exists(email):
# def hash_password(password):
# def verify_password(self, password):
# def add_favorite(user, item):
# def delete_favorite(self, obj):
# def order_items(self):
# def empty_order(self):
# def create_order(user, address, items):
# def update_items(self, items, update_total=True, new_address=None):
# def edit_items_quantity(self, items):
# def delete_items(self, items):
# def create_items(self, items):
# def add_item(self, item, quantity=1):
# def remove_item(self, item, quantity=1):
# def add_item(self, quantity=1):
# def remove_item(self, quantity=1):
# def _calculate_subtotal(self):
#
# Path: notifications.py
# def notify_new_order(address, user):
# body = render_template('new_order.html', address=address, user=user)
# send_email("Nuovo Ordine", body)
#
# Path: utils.py
# def generate_response(data, status, mimetype='application/vnd.api+json'):
# """
# Given a resource model that extends from `BaseModel` generate a Reponse
# object to be returned from the application endpoints'
# """
# return Response(
# response=data,
# status=status,
# mimetype=mimetype
# )
#
# Path: exceptions.py
# class InsufficientAvailabilityException(Exception):
#
# def __init__(self, item, requested_quantity):
# super(Exception, self).__init__(
# "Item availability {}, requested {}".format(
# item.availability,
# requested_quantity))
#
# self.item = item
# self.requested_quantity = requested_quantity
. Output only the next line. | with database.atomic(): |
Given the following code snippet before the placeholder: <|code_start|> if errors:
return errors, BAD_REQUEST
# Extract data to create the new order
req_items = res['data']['relationships']['items']['data']
req_address = res['data']['relationships']['delivery_address']['data']
req_user = res['data']['relationships']['user']['data']
# Check that the address exist
try:
user = User.get(User.uuid == req_user['id'])
except User.DoesNotExist:
abort(BAD_REQUEST)
# get the user from the flask.g global object registered inside the
# auth.py::verify() function, called by @auth.login_required decorator
# and match it against the found user.
# This is to prevent users from creating other users' order.
if auth.current_user != user and auth.current_user.admin is False:
return ({'message': "You can't create a new order for another user"},
UNAUTHORIZED)
# Check that the items exist
item_ids = [req_item['id'] for req_item in req_items]
items = Item.select().where(Item.uuid << item_ids)
if items.count() != len(req_items):
abort(BAD_REQUEST)
# Check that the address exist
try:
<|code_end|>
, predict the next line using imports from the current file:
from http.client import (BAD_REQUEST, CREATED, NO_CONTENT, NOT_FOUND, OK,
UNAUTHORIZED)
from flask import abort, request
from flask_restful import Resource
from auth import auth
from models import database, Address, Order, Item, User
from notifications import notify_new_order
from utils import generate_response
from exceptions import InsufficientAvailabilityException
and context including class names, function names, and sometimes code from other files:
# Path: auth.py
# class Auth:
# def login_required(*args, **kwargs):
# def current_user(self):
# def init_app(app):
# def load_user(user_id):
# def load_user_from_request(request):
#
# Path: models.py
# ENVIRONMENT = os.getenv('ENVIRONMENT', 'dev')
# class BaseModel(Model):
# class Meta:
# class Item(BaseModel):
# class Picture(BaseModel):
# class User(BaseModel, UserMixin):
# class Address(BaseModel):
# class Order(BaseModel):
# class Meta:
# class OrderItem(BaseModel):
# class Favorite(BaseModel):
# def save(self, *args, **kwargs):
# def json_list(cls, objs_list):
# def json(self, include_data=[]):
# def validate_input(cls, data, partial=False):
# def search(cls, query, dataset, limit=-1,
# attributes=None, weights=None,
# threshold=search.config.THRESHOLD):
# def __str__(self):
# def is_favorite(self, item):
# def on_delete_item_handler(model_class, instance):
# def filename(self):
# def __str__(self):
# def on_delete_picture_handler(model_class, instance):
# def exists(email):
# def hash_password(password):
# def verify_password(self, password):
# def add_favorite(user, item):
# def delete_favorite(self, obj):
# def order_items(self):
# def empty_order(self):
# def create_order(user, address, items):
# def update_items(self, items, update_total=True, new_address=None):
# def edit_items_quantity(self, items):
# def delete_items(self, items):
# def create_items(self, items):
# def add_item(self, item, quantity=1):
# def remove_item(self, item, quantity=1):
# def add_item(self, quantity=1):
# def remove_item(self, quantity=1):
# def _calculate_subtotal(self):
#
# Path: notifications.py
# def notify_new_order(address, user):
# body = render_template('new_order.html', address=address, user=user)
# send_email("Nuovo Ordine", body)
#
# Path: utils.py
# def generate_response(data, status, mimetype='application/vnd.api+json'):
# """
# Given a resource model that extends from `BaseModel` generate a Reponse
# object to be returned from the application endpoints'
# """
# return Response(
# response=data,
# status=status,
# mimetype=mimetype
# )
#
# Path: exceptions.py
# class InsufficientAvailabilityException(Exception):
#
# def __init__(self, item, requested_quantity):
# super(Exception, self).__init__(
# "Item availability {}, requested {}".format(
# item.availability,
# requested_quantity))
#
# self.item = item
# self.requested_quantity = requested_quantity
. Output only the next line. | address = Address.get(Address.uuid == req_address['id']) |
Continue the code snippet: <|code_start|>"""
Orders-view: this module contains functions for the interaction with the orders.
"""
class OrdersHandler(Resource):
""" Orders endpoint. """
def get(self):
""" Get all the orders."""
<|code_end|>
. Use current file imports:
from http.client import (BAD_REQUEST, CREATED, NO_CONTENT, NOT_FOUND, OK,
UNAUTHORIZED)
from flask import abort, request
from flask_restful import Resource
from auth import auth
from models import database, Address, Order, Item, User
from notifications import notify_new_order
from utils import generate_response
from exceptions import InsufficientAvailabilityException
and context (classes, functions, or code) from other files:
# Path: auth.py
# class Auth:
# def login_required(*args, **kwargs):
# def current_user(self):
# def init_app(app):
# def load_user(user_id):
# def load_user_from_request(request):
#
# Path: models.py
# ENVIRONMENT = os.getenv('ENVIRONMENT', 'dev')
# class BaseModel(Model):
# class Meta:
# class Item(BaseModel):
# class Picture(BaseModel):
# class User(BaseModel, UserMixin):
# class Address(BaseModel):
# class Order(BaseModel):
# class Meta:
# class OrderItem(BaseModel):
# class Favorite(BaseModel):
# def save(self, *args, **kwargs):
# def json_list(cls, objs_list):
# def json(self, include_data=[]):
# def validate_input(cls, data, partial=False):
# def search(cls, query, dataset, limit=-1,
# attributes=None, weights=None,
# threshold=search.config.THRESHOLD):
# def __str__(self):
# def is_favorite(self, item):
# def on_delete_item_handler(model_class, instance):
# def filename(self):
# def __str__(self):
# def on_delete_picture_handler(model_class, instance):
# def exists(email):
# def hash_password(password):
# def verify_password(self, password):
# def add_favorite(user, item):
# def delete_favorite(self, obj):
# def order_items(self):
# def empty_order(self):
# def create_order(user, address, items):
# def update_items(self, items, update_total=True, new_address=None):
# def edit_items_quantity(self, items):
# def delete_items(self, items):
# def create_items(self, items):
# def add_item(self, item, quantity=1):
# def remove_item(self, item, quantity=1):
# def add_item(self, quantity=1):
# def remove_item(self, quantity=1):
# def _calculate_subtotal(self):
#
# Path: notifications.py
# def notify_new_order(address, user):
# body = render_template('new_order.html', address=address, user=user)
# send_email("Nuovo Ordine", body)
#
# Path: utils.py
# def generate_response(data, status, mimetype='application/vnd.api+json'):
# """
# Given a resource model that extends from `BaseModel` generate a Reponse
# object to be returned from the application endpoints'
# """
# return Response(
# response=data,
# status=status,
# mimetype=mimetype
# )
#
# Path: exceptions.py
# class InsufficientAvailabilityException(Exception):
#
# def __init__(self, item, requested_quantity):
# super(Exception, self).__init__(
# "Item availability {}, requested {}".format(
# item.availability,
# requested_quantity))
#
# self.item = item
# self.requested_quantity = requested_quantity
. Output only the next line. | data = Order.json_list(Order.select()) |
Predict the next line after this snippet: <|code_start|> @auth.login_required
def post(self):
""" Insert a new order."""
res = request.get_json(force=True)
errors = Order.validate_input(res)
if errors:
return errors, BAD_REQUEST
# Extract data to create the new order
req_items = res['data']['relationships']['items']['data']
req_address = res['data']['relationships']['delivery_address']['data']
req_user = res['data']['relationships']['user']['data']
# Check that the address exist
try:
user = User.get(User.uuid == req_user['id'])
except User.DoesNotExist:
abort(BAD_REQUEST)
# get the user from the flask.g global object registered inside the
# auth.py::verify() function, called by @auth.login_required decorator
# and match it against the found user.
# This is to prevent users from creating other users' order.
if auth.current_user != user and auth.current_user.admin is False:
return ({'message': "You can't create a new order for another user"},
UNAUTHORIZED)
# Check that the items exist
item_ids = [req_item['id'] for req_item in req_items]
<|code_end|>
using the current file's imports:
from http.client import (BAD_REQUEST, CREATED, NO_CONTENT, NOT_FOUND, OK,
UNAUTHORIZED)
from flask import abort, request
from flask_restful import Resource
from auth import auth
from models import database, Address, Order, Item, User
from notifications import notify_new_order
from utils import generate_response
from exceptions import InsufficientAvailabilityException
and any relevant context from other files:
# Path: auth.py
# class Auth:
# def login_required(*args, **kwargs):
# def current_user(self):
# def init_app(app):
# def load_user(user_id):
# def load_user_from_request(request):
#
# Path: models.py
# ENVIRONMENT = os.getenv('ENVIRONMENT', 'dev')
# class BaseModel(Model):
# class Meta:
# class Item(BaseModel):
# class Picture(BaseModel):
# class User(BaseModel, UserMixin):
# class Address(BaseModel):
# class Order(BaseModel):
# class Meta:
# class OrderItem(BaseModel):
# class Favorite(BaseModel):
# def save(self, *args, **kwargs):
# def json_list(cls, objs_list):
# def json(self, include_data=[]):
# def validate_input(cls, data, partial=False):
# def search(cls, query, dataset, limit=-1,
# attributes=None, weights=None,
# threshold=search.config.THRESHOLD):
# def __str__(self):
# def is_favorite(self, item):
# def on_delete_item_handler(model_class, instance):
# def filename(self):
# def __str__(self):
# def on_delete_picture_handler(model_class, instance):
# def exists(email):
# def hash_password(password):
# def verify_password(self, password):
# def add_favorite(user, item):
# def delete_favorite(self, obj):
# def order_items(self):
# def empty_order(self):
# def create_order(user, address, items):
# def update_items(self, items, update_total=True, new_address=None):
# def edit_items_quantity(self, items):
# def delete_items(self, items):
# def create_items(self, items):
# def add_item(self, item, quantity=1):
# def remove_item(self, item, quantity=1):
# def add_item(self, quantity=1):
# def remove_item(self, quantity=1):
# def _calculate_subtotal(self):
#
# Path: notifications.py
# def notify_new_order(address, user):
# body = render_template('new_order.html', address=address, user=user)
# send_email("Nuovo Ordine", body)
#
# Path: utils.py
# def generate_response(data, status, mimetype='application/vnd.api+json'):
# """
# Given a resource model that extends from `BaseModel` generate a Reponse
# object to be returned from the application endpoints'
# """
# return Response(
# response=data,
# status=status,
# mimetype=mimetype
# )
#
# Path: exceptions.py
# class InsufficientAvailabilityException(Exception):
#
# def __init__(self, item, requested_quantity):
# super(Exception, self).__init__(
# "Item availability {}, requested {}".format(
# item.availability,
# requested_quantity))
#
# self.item = item
# self.requested_quantity = requested_quantity
. Output only the next line. | items = Item.select().where(Item.uuid << item_ids) |
Predict the next line after this snippet: <|code_start|>
class OrdersHandler(Resource):
""" Orders endpoint. """
def get(self):
""" Get all the orders."""
data = Order.json_list(Order.select())
return generate_response(data, OK)
@auth.login_required
def post(self):
""" Insert a new order."""
res = request.get_json(force=True)
errors = Order.validate_input(res)
if errors:
return errors, BAD_REQUEST
# Extract data to create the new order
req_items = res['data']['relationships']['items']['data']
req_address = res['data']['relationships']['delivery_address']['data']
req_user = res['data']['relationships']['user']['data']
# Check that the address exist
try:
<|code_end|>
using the current file's imports:
from http.client import (BAD_REQUEST, CREATED, NO_CONTENT, NOT_FOUND, OK,
UNAUTHORIZED)
from flask import abort, request
from flask_restful import Resource
from auth import auth
from models import database, Address, Order, Item, User
from notifications import notify_new_order
from utils import generate_response
from exceptions import InsufficientAvailabilityException
and any relevant context from other files:
# Path: auth.py
# class Auth:
# def login_required(*args, **kwargs):
# def current_user(self):
# def init_app(app):
# def load_user(user_id):
# def load_user_from_request(request):
#
# Path: models.py
# ENVIRONMENT = os.getenv('ENVIRONMENT', 'dev')
# class BaseModel(Model):
# class Meta:
# class Item(BaseModel):
# class Picture(BaseModel):
# class User(BaseModel, UserMixin):
# class Address(BaseModel):
# class Order(BaseModel):
# class Meta:
# class OrderItem(BaseModel):
# class Favorite(BaseModel):
# def save(self, *args, **kwargs):
# def json_list(cls, objs_list):
# def json(self, include_data=[]):
# def validate_input(cls, data, partial=False):
# def search(cls, query, dataset, limit=-1,
# attributes=None, weights=None,
# threshold=search.config.THRESHOLD):
# def __str__(self):
# def is_favorite(self, item):
# def on_delete_item_handler(model_class, instance):
# def filename(self):
# def __str__(self):
# def on_delete_picture_handler(model_class, instance):
# def exists(email):
# def hash_password(password):
# def verify_password(self, password):
# def add_favorite(user, item):
# def delete_favorite(self, obj):
# def order_items(self):
# def empty_order(self):
# def create_order(user, address, items):
# def update_items(self, items, update_total=True, new_address=None):
# def edit_items_quantity(self, items):
# def delete_items(self, items):
# def create_items(self, items):
# def add_item(self, item, quantity=1):
# def remove_item(self, item, quantity=1):
# def add_item(self, quantity=1):
# def remove_item(self, quantity=1):
# def _calculate_subtotal(self):
#
# Path: notifications.py
# def notify_new_order(address, user):
# body = render_template('new_order.html', address=address, user=user)
# send_email("Nuovo Ordine", body)
#
# Path: utils.py
# def generate_response(data, status, mimetype='application/vnd.api+json'):
# """
# Given a resource model that extends from `BaseModel` generate a Reponse
# object to be returned from the application endpoints'
# """
# return Response(
# response=data,
# status=status,
# mimetype=mimetype
# )
#
# Path: exceptions.py
# class InsufficientAvailabilityException(Exception):
#
# def __init__(self, item, requested_quantity):
# super(Exception, self).__init__(
# "Item availability {}, requested {}".format(
# item.availability,
# requested_quantity))
#
# self.item = item
# self.requested_quantity = requested_quantity
. Output only the next line. | user = User.get(User.uuid == req_user['id']) |
Given snippet: <|code_start|> item_ids = [req_item['id'] for req_item in req_items]
items = Item.select().where(Item.uuid << item_ids)
if items.count() != len(req_items):
abort(BAD_REQUEST)
# Check that the address exist
try:
address = Address.get(Address.uuid == req_address['id'])
except Address.DoesNotExist:
abort(BAD_REQUEST)
# Generate the dict of {<Item>: <int:quantity>} to call Order.create_order
items_to_add = {}
for req_item in req_items:
item = next(i for i in items if str(i.uuid) == req_item['id'])
items_to_add[item] = req_item['quantity']
with database.atomic():
try:
order = Order.create(
delivery_address=address,
user=auth.current_user,
)
for item in items:
for req_item in req_items:
# if names match add item and quantity, once per
# req_item
if str(item.uuid) == req_item['id']:
order.add_item(item, req_item['quantity'])
break
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from http.client import (BAD_REQUEST, CREATED, NO_CONTENT, NOT_FOUND, OK,
UNAUTHORIZED)
from flask import abort, request
from flask_restful import Resource
from auth import auth
from models import database, Address, Order, Item, User
from notifications import notify_new_order
from utils import generate_response
from exceptions import InsufficientAvailabilityException
and context:
# Path: auth.py
# class Auth:
# def login_required(*args, **kwargs):
# def current_user(self):
# def init_app(app):
# def load_user(user_id):
# def load_user_from_request(request):
#
# Path: models.py
# ENVIRONMENT = os.getenv('ENVIRONMENT', 'dev')
# class BaseModel(Model):
# class Meta:
# class Item(BaseModel):
# class Picture(BaseModel):
# class User(BaseModel, UserMixin):
# class Address(BaseModel):
# class Order(BaseModel):
# class Meta:
# class OrderItem(BaseModel):
# class Favorite(BaseModel):
# def save(self, *args, **kwargs):
# def json_list(cls, objs_list):
# def json(self, include_data=[]):
# def validate_input(cls, data, partial=False):
# def search(cls, query, dataset, limit=-1,
# attributes=None, weights=None,
# threshold=search.config.THRESHOLD):
# def __str__(self):
# def is_favorite(self, item):
# def on_delete_item_handler(model_class, instance):
# def filename(self):
# def __str__(self):
# def on_delete_picture_handler(model_class, instance):
# def exists(email):
# def hash_password(password):
# def verify_password(self, password):
# def add_favorite(user, item):
# def delete_favorite(self, obj):
# def order_items(self):
# def empty_order(self):
# def create_order(user, address, items):
# def update_items(self, items, update_total=True, new_address=None):
# def edit_items_quantity(self, items):
# def delete_items(self, items):
# def create_items(self, items):
# def add_item(self, item, quantity=1):
# def remove_item(self, item, quantity=1):
# def add_item(self, quantity=1):
# def remove_item(self, quantity=1):
# def _calculate_subtotal(self):
#
# Path: notifications.py
# def notify_new_order(address, user):
# body = render_template('new_order.html', address=address, user=user)
# send_email("Nuovo Ordine", body)
#
# Path: utils.py
# def generate_response(data, status, mimetype='application/vnd.api+json'):
# """
# Given a resource model that extends from `BaseModel` generate a Reponse
# object to be returned from the application endpoints'
# """
# return Response(
# response=data,
# status=status,
# mimetype=mimetype
# )
#
# Path: exceptions.py
# class InsufficientAvailabilityException(Exception):
#
# def __init__(self, item, requested_quantity):
# super(Exception, self).__init__(
# "Item availability {}, requested {}".format(
# item.availability,
# requested_quantity))
#
# self.item = item
# self.requested_quantity = requested_quantity
which might include code, classes, or functions. Output only the next line. | notify_new_order(address=order.delivery_address, user=order.user) |
Given snippet: <|code_start|>"""
Orders-view: this module contains functions for the interaction with the orders.
"""
class OrdersHandler(Resource):
""" Orders endpoint. """
def get(self):
""" Get all the orders."""
data = Order.json_list(Order.select())
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from http.client import (BAD_REQUEST, CREATED, NO_CONTENT, NOT_FOUND, OK,
UNAUTHORIZED)
from flask import abort, request
from flask_restful import Resource
from auth import auth
from models import database, Address, Order, Item, User
from notifications import notify_new_order
from utils import generate_response
from exceptions import InsufficientAvailabilityException
and context:
# Path: auth.py
# class Auth:
# def login_required(*args, **kwargs):
# def current_user(self):
# def init_app(app):
# def load_user(user_id):
# def load_user_from_request(request):
#
# Path: models.py
# ENVIRONMENT = os.getenv('ENVIRONMENT', 'dev')
# class BaseModel(Model):
# class Meta:
# class Item(BaseModel):
# class Picture(BaseModel):
# class User(BaseModel, UserMixin):
# class Address(BaseModel):
# class Order(BaseModel):
# class Meta:
# class OrderItem(BaseModel):
# class Favorite(BaseModel):
# def save(self, *args, **kwargs):
# def json_list(cls, objs_list):
# def json(self, include_data=[]):
# def validate_input(cls, data, partial=False):
# def search(cls, query, dataset, limit=-1,
# attributes=None, weights=None,
# threshold=search.config.THRESHOLD):
# def __str__(self):
# def is_favorite(self, item):
# def on_delete_item_handler(model_class, instance):
# def filename(self):
# def __str__(self):
# def on_delete_picture_handler(model_class, instance):
# def exists(email):
# def hash_password(password):
# def verify_password(self, password):
# def add_favorite(user, item):
# def delete_favorite(self, obj):
# def order_items(self):
# def empty_order(self):
# def create_order(user, address, items):
# def update_items(self, items, update_total=True, new_address=None):
# def edit_items_quantity(self, items):
# def delete_items(self, items):
# def create_items(self, items):
# def add_item(self, item, quantity=1):
# def remove_item(self, item, quantity=1):
# def add_item(self, quantity=1):
# def remove_item(self, quantity=1):
# def _calculate_subtotal(self):
#
# Path: notifications.py
# def notify_new_order(address, user):
# body = render_template('new_order.html', address=address, user=user)
# send_email("Nuovo Ordine", body)
#
# Path: utils.py
# def generate_response(data, status, mimetype='application/vnd.api+json'):
# """
# Given a resource model that extends from `BaseModel` generate a Reponse
# object to be returned from the application endpoints'
# """
# return Response(
# response=data,
# status=status,
# mimetype=mimetype
# )
#
# Path: exceptions.py
# class InsufficientAvailabilityException(Exception):
#
# def __init__(self, item, requested_quantity):
# super(Exception, self).__init__(
# "Item availability {}, requested {}".format(
# item.availability,
# requested_quantity))
#
# self.item = item
# self.requested_quantity = requested_quantity
which might include code, classes, or functions. Output only the next line. | return generate_response(data, OK) |
Predict the next line for this snippet: <|code_start|> items = Item.select().where(Item.uuid << item_ids)
if items.count() != len(req_items):
abort(BAD_REQUEST)
# Check that the address exist
try:
address = Address.get(Address.uuid == req_address['id'])
except Address.DoesNotExist:
abort(BAD_REQUEST)
# Generate the dict of {<Item>: <int:quantity>} to call Order.create_order
items_to_add = {}
for req_item in req_items:
item = next(i for i in items if str(i.uuid) == req_item['id'])
items_to_add[item] = req_item['quantity']
with database.atomic():
try:
order = Order.create(
delivery_address=address,
user=auth.current_user,
)
for item in items:
for req_item in req_items:
# if names match add item and quantity, once per
# req_item
if str(item.uuid) == req_item['id']:
order.add_item(item, req_item['quantity'])
break
notify_new_order(address=order.delivery_address, user=order.user)
<|code_end|>
with the help of current file imports:
from http.client import (BAD_REQUEST, CREATED, NO_CONTENT, NOT_FOUND, OK,
UNAUTHORIZED)
from flask import abort, request
from flask_restful import Resource
from auth import auth
from models import database, Address, Order, Item, User
from notifications import notify_new_order
from utils import generate_response
from exceptions import InsufficientAvailabilityException
and context from other files:
# Path: auth.py
# class Auth:
# def login_required(*args, **kwargs):
# def current_user(self):
# def init_app(app):
# def load_user(user_id):
# def load_user_from_request(request):
#
# Path: models.py
# ENVIRONMENT = os.getenv('ENVIRONMENT', 'dev')
# class BaseModel(Model):
# class Meta:
# class Item(BaseModel):
# class Picture(BaseModel):
# class User(BaseModel, UserMixin):
# class Address(BaseModel):
# class Order(BaseModel):
# class Meta:
# class OrderItem(BaseModel):
# class Favorite(BaseModel):
# def save(self, *args, **kwargs):
# def json_list(cls, objs_list):
# def json(self, include_data=[]):
# def validate_input(cls, data, partial=False):
# def search(cls, query, dataset, limit=-1,
# attributes=None, weights=None,
# threshold=search.config.THRESHOLD):
# def __str__(self):
# def is_favorite(self, item):
# def on_delete_item_handler(model_class, instance):
# def filename(self):
# def __str__(self):
# def on_delete_picture_handler(model_class, instance):
# def exists(email):
# def hash_password(password):
# def verify_password(self, password):
# def add_favorite(user, item):
# def delete_favorite(self, obj):
# def order_items(self):
# def empty_order(self):
# def create_order(user, address, items):
# def update_items(self, items, update_total=True, new_address=None):
# def edit_items_quantity(self, items):
# def delete_items(self, items):
# def create_items(self, items):
# def add_item(self, item, quantity=1):
# def remove_item(self, item, quantity=1):
# def add_item(self, quantity=1):
# def remove_item(self, quantity=1):
# def _calculate_subtotal(self):
#
# Path: notifications.py
# def notify_new_order(address, user):
# body = render_template('new_order.html', address=address, user=user)
# send_email("Nuovo Ordine", body)
#
# Path: utils.py
# def generate_response(data, status, mimetype='application/vnd.api+json'):
# """
# Given a resource model that extends from `BaseModel` generate a Reponse
# object to be returned from the application endpoints'
# """
# return Response(
# response=data,
# status=status,
# mimetype=mimetype
# )
#
# Path: exceptions.py
# class InsufficientAvailabilityException(Exception):
#
# def __init__(self, item, requested_quantity):
# super(Exception, self).__init__(
# "Item availability {}, requested {}".format(
# item.availability,
# requested_quantity))
#
# self.item = item
# self.requested_quantity = requested_quantity
, which may contain function names, class names, or code. Output only the next line. | except InsufficientAvailabilityException: |
Predict the next line after this snippet: <|code_start|> return User.create(
first_name=first_name,
last_name=last_name,
email=email,
password=User.hash_password(password),
uuid=id or uuid.uuid4(),
)
def add_admin_user(email, psw, id=None):
"""
Create a single user in the test database.
If an email is provided it will be used, otherwise it will be generated
by the function before adding the User to the database.
"""
email = email or 'johndoe{}@email.com'.format(int(random.random() * 100))
return User.create(
first_name='John Admin',
last_name='Doe',
email=email,
password=User.hash_password(psw),
uuid=id or uuid.uuid4(),
admin=True,
)
def add_address(user, country='Italy', city='Pistoia', post_code='51100',
address='Via Verdi 12', phone='3294882773', id=None):
<|code_end|>
using the current file's imports:
from functools import reduce
from base64 import b64encode
from models import Address, User, Favorite, Item
from utils import get_image_folder
import datetime
import inspect
import json
import os
import random
import shutil
import sys
import uuid
and any relevant context from other files:
# Path: models.py
# class Address(BaseModel):
# """
# The model Address represent a user address.
# Each address is releated to one user, but one user can have
# more addresses.
#
# Attributes:
# uuid (UUID): Address unique uuid
# user (:any:`User`): Foreign key pointing to the user `owner` of the address
# country (str): Country for the address, i.e. ``Italy``
# city (str): City name
# post_code (str): Postal code for the address
# address (str): Full address for the Address resource
# phone (str): Phone number for the Address
# """
# uuid = UUIDField(unique=True)
# user = ForeignKeyField(User, related_name='addresses')
# country = CharField()
# city = CharField()
# post_code = CharField()
# address = CharField()
# phone = CharField()
#
# _schema = AddressSchema
#
# class User(BaseModel, UserMixin):
# """
# User represents an user for the application.
#
# Attributes:
# first_name (str): User's first name
# last_name (str): User's last name
# email (str): User's **valid** email
# password (str): User's password
# admin (bool): User's admin status. Defaults to ``False``
#
# .. NOTE::
# Each User resource must have an unique `email` field, meaning
# that there cannot be two user's registered with the same email.
#
# For this reason, when checking for user's existence, the server requires
# either the `uuid` of the user or its `email`.
# """
# uuid = UUIDField(unique=True)
# first_name = CharField()
# last_name = CharField()
# email = CharField(unique=True)
# password = CharField()
# admin = BooleanField(default=False)
# _schema = UserSchema
#
# @staticmethod
# def exists(email):
# """
# Check that an user exists by checking the email field.
#
# Args:
# email (str): User's email to check
# """
# try:
# User.get(User.email == email)
# except User.DoesNotExist:
# return False
# return True
#
# @staticmethod
# def hash_password(password):
# """
# Use passlib to get a crypted password.
#
# Args:
# password (str): password to hash
#
# Returns:
# str: hashed password
# """
# return pbkdf2_sha256.hash(password)
#
# def verify_password(self, password):
# """
# Verify a clear password against the stored hashed password of the user
# using passlib.
#
# Args:
# password (str): Password to verify against the hashed stored password
# Returns:
# bool: wether the given email matches the stored one
# """
# return pbkdf2_sha256.verify(password, self.password)
#
# def add_favorite(user, item):
# """Link the favorite item to user."""
# return Favorite.create(
# uuid=uuid4(),
# item=item,
# user=user,
# )
#
# def delete_favorite(self, obj):
# obj.delete_instance()
#
# class Favorite(BaseModel):
# """ Many to many table to relate an item with a user."""
# uuid = UUIDField(unique=True)
# user = ForeignKeyField(User, related_name="favorites")
# item = ForeignKeyField(Item, related_name="favorites")
# _schema = FavoriteSchema
#
# class Item(BaseModel):
# """
# Item describes a product for the e-commerce platform.
#
# Attributes:
# uuid (UUID): Item UUID
# name (str): Name for the product
# price (decimal.Decimal): Price for a single product
# description (str): Product description
# availability (int): Quantity of items available
# category (str): Category group of the item
#
# """
# uuid = UUIDField(unique=True)
# name = CharField()
# price = DecimalField(auto_round=True)
# description = TextField()
# availability = IntegerField()
# category = TextField()
# _schema = ItemSchema
# _search_attributes = ['name', 'category', 'description']
#
# def __str__(self):
# return '{}, {}, {}, {}'.format(
# self.uuid,
# self.name,
# self.price,
# self.description)
#
# def is_favorite(self, item):
# for f in self.favorites:
# if f.item_id == item.id:
# return True
# return False
#
# Path: utils.py
# def get_image_folder():
# return os.path.join(get_project_root(), IMAGE_FOLDER)
. Output only the next line. | return Address.create( |
Predict the next line after this snippet: <|code_start|>
def __call__(self, created_at=mock_datetime(), uuid=None, **query):
query['created_at'] = created_at
query['uuid'] = uuid or next(self.uuid_generator)
return self.original(**query)
def get_all_models_names():
"""
Returns the names of all the classes defined inside the 'models' module.
"""
return [name for
(name, cls) in inspect.getmembers(
sys.modules['models'], inspect.isclass)
if cls.__module__ is 'models']
# ###########################################################
# Peewee models helpers
# Functions to create new instances with overridable defaults
def add_user(email, password, id=None, first_name='John', last_name='Doe'):
"""
Create a single user in the test database.
If an email is provided it will be used, otherwise it will be generated
by the function before adding the User to the database.
"""
email = email or 'johndoe{}@email.com'.format(int(random.random() * 100))
<|code_end|>
using the current file's imports:
from functools import reduce
from base64 import b64encode
from models import Address, User, Favorite, Item
from utils import get_image_folder
import datetime
import inspect
import json
import os
import random
import shutil
import sys
import uuid
and any relevant context from other files:
# Path: models.py
# class Address(BaseModel):
# """
# The model Address represent a user address.
# Each address is releated to one user, but one user can have
# more addresses.
#
# Attributes:
# uuid (UUID): Address unique uuid
# user (:any:`User`): Foreign key pointing to the user `owner` of the address
# country (str): Country for the address, i.e. ``Italy``
# city (str): City name
# post_code (str): Postal code for the address
# address (str): Full address for the Address resource
# phone (str): Phone number for the Address
# """
# uuid = UUIDField(unique=True)
# user = ForeignKeyField(User, related_name='addresses')
# country = CharField()
# city = CharField()
# post_code = CharField()
# address = CharField()
# phone = CharField()
#
# _schema = AddressSchema
#
# class User(BaseModel, UserMixin):
# """
# User represents an user for the application.
#
# Attributes:
# first_name (str): User's first name
# last_name (str): User's last name
# email (str): User's **valid** email
# password (str): User's password
# admin (bool): User's admin status. Defaults to ``False``
#
# .. NOTE::
# Each User resource must have an unique `email` field, meaning
# that there cannot be two user's registered with the same email.
#
# For this reason, when checking for user's existence, the server requires
# either the `uuid` of the user or its `email`.
# """
# uuid = UUIDField(unique=True)
# first_name = CharField()
# last_name = CharField()
# email = CharField(unique=True)
# password = CharField()
# admin = BooleanField(default=False)
# _schema = UserSchema
#
# @staticmethod
# def exists(email):
# """
# Check that an user exists by checking the email field.
#
# Args:
# email (str): User's email to check
# """
# try:
# User.get(User.email == email)
# except User.DoesNotExist:
# return False
# return True
#
# @staticmethod
# def hash_password(password):
# """
# Use passlib to get a crypted password.
#
# Args:
# password (str): password to hash
#
# Returns:
# str: hashed password
# """
# return pbkdf2_sha256.hash(password)
#
# def verify_password(self, password):
# """
# Verify a clear password against the stored hashed password of the user
# using passlib.
#
# Args:
# password (str): Password to verify against the hashed stored password
# Returns:
# bool: wether the given email matches the stored one
# """
# return pbkdf2_sha256.verify(password, self.password)
#
# def add_favorite(user, item):
# """Link the favorite item to user."""
# return Favorite.create(
# uuid=uuid4(),
# item=item,
# user=user,
# )
#
# def delete_favorite(self, obj):
# obj.delete_instance()
#
# class Favorite(BaseModel):
# """ Many to many table to relate an item with a user."""
# uuid = UUIDField(unique=True)
# user = ForeignKeyField(User, related_name="favorites")
# item = ForeignKeyField(Item, related_name="favorites")
# _schema = FavoriteSchema
#
# class Item(BaseModel):
# """
# Item describes a product for the e-commerce platform.
#
# Attributes:
# uuid (UUID): Item UUID
# name (str): Name for the product
# price (decimal.Decimal): Price for a single product
# description (str): Product description
# availability (int): Quantity of items available
# category (str): Category group of the item
#
# """
# uuid = UUIDField(unique=True)
# name = CharField()
# price = DecimalField(auto_round=True)
# description = TextField()
# availability = IntegerField()
# category = TextField()
# _schema = ItemSchema
# _search_attributes = ['name', 'category', 'description']
#
# def __str__(self):
# return '{}, {}, {}, {}'.format(
# self.uuid,
# self.name,
# self.price,
# self.description)
#
# def is_favorite(self, item):
# for f in self.favorites:
# if f.item_id == item.id:
# return True
# return False
#
# Path: utils.py
# def get_image_folder():
# return os.path.join(get_project_root(), IMAGE_FOLDER)
. Output only the next line. | return User.create( |
Given snippet: <|code_start|> by the function before adding the User to the database.
"""
email = email or 'johndoe{}@email.com'.format(int(random.random() * 100))
return User.create(
first_name='John Admin',
last_name='Doe',
email=email,
password=User.hash_password(psw),
uuid=id or uuid.uuid4(),
admin=True,
)
def add_address(user, country='Italy', city='Pistoia', post_code='51100',
address='Via Verdi 12', phone='3294882773', id=None):
return Address.create(
uuid=id or uuid.uuid4(),
user=user,
country=country,
city=city,
post_code=post_code,
address=address,
phone=phone,
)
def add_favorite(user, item, id=None):
"""Link the favorite item to user."""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from functools import reduce
from base64 import b64encode
from models import Address, User, Favorite, Item
from utils import get_image_folder
import datetime
import inspect
import json
import os
import random
import shutil
import sys
import uuid
and context:
# Path: models.py
# class Address(BaseModel):
# """
# The model Address represent a user address.
# Each address is releated to one user, but one user can have
# more addresses.
#
# Attributes:
# uuid (UUID): Address unique uuid
# user (:any:`User`): Foreign key pointing to the user `owner` of the address
# country (str): Country for the address, i.e. ``Italy``
# city (str): City name
# post_code (str): Postal code for the address
# address (str): Full address for the Address resource
# phone (str): Phone number for the Address
# """
# uuid = UUIDField(unique=True)
# user = ForeignKeyField(User, related_name='addresses')
# country = CharField()
# city = CharField()
# post_code = CharField()
# address = CharField()
# phone = CharField()
#
# _schema = AddressSchema
#
# class User(BaseModel, UserMixin):
# """
# User represents an user for the application.
#
# Attributes:
# first_name (str): User's first name
# last_name (str): User's last name
# email (str): User's **valid** email
# password (str): User's password
# admin (bool): User's admin status. Defaults to ``False``
#
# .. NOTE::
# Each User resource must have an unique `email` field, meaning
# that there cannot be two user's registered with the same email.
#
# For this reason, when checking for user's existence, the server requires
# either the `uuid` of the user or its `email`.
# """
# uuid = UUIDField(unique=True)
# first_name = CharField()
# last_name = CharField()
# email = CharField(unique=True)
# password = CharField()
# admin = BooleanField(default=False)
# _schema = UserSchema
#
# @staticmethod
# def exists(email):
# """
# Check that an user exists by checking the email field.
#
# Args:
# email (str): User's email to check
# """
# try:
# User.get(User.email == email)
# except User.DoesNotExist:
# return False
# return True
#
# @staticmethod
# def hash_password(password):
# """
# Use passlib to get a crypted password.
#
# Args:
# password (str): password to hash
#
# Returns:
# str: hashed password
# """
# return pbkdf2_sha256.hash(password)
#
# def verify_password(self, password):
# """
# Verify a clear password against the stored hashed password of the user
# using passlib.
#
# Args:
# password (str): Password to verify against the hashed stored password
# Returns:
# bool: wether the given email matches the stored one
# """
# return pbkdf2_sha256.verify(password, self.password)
#
# def add_favorite(user, item):
# """Link the favorite item to user."""
# return Favorite.create(
# uuid=uuid4(),
# item=item,
# user=user,
# )
#
# def delete_favorite(self, obj):
# obj.delete_instance()
#
# class Favorite(BaseModel):
# """ Many to many table to relate an item with a user."""
# uuid = UUIDField(unique=True)
# user = ForeignKeyField(User, related_name="favorites")
# item = ForeignKeyField(Item, related_name="favorites")
# _schema = FavoriteSchema
#
# class Item(BaseModel):
# """
# Item describes a product for the e-commerce platform.
#
# Attributes:
# uuid (UUID): Item UUID
# name (str): Name for the product
# price (decimal.Decimal): Price for a single product
# description (str): Product description
# availability (int): Quantity of items available
# category (str): Category group of the item
#
# """
# uuid = UUIDField(unique=True)
# name = CharField()
# price = DecimalField(auto_round=True)
# description = TextField()
# availability = IntegerField()
# category = TextField()
# _schema = ItemSchema
# _search_attributes = ['name', 'category', 'description']
#
# def __str__(self):
# return '{}, {}, {}, {}'.format(
# self.uuid,
# self.name,
# self.price,
# self.description)
#
# def is_favorite(self, item):
# for f in self.favorites:
# if f.item_id == item.id:
# return True
# return False
#
# Path: utils.py
# def get_image_folder():
# return os.path.join(get_project_root(), IMAGE_FOLDER)
which might include code, classes, or functions. Output only the next line. | return Favorite.create( |
Using the snippet: <|code_start|>
return Address.create(
uuid=id or uuid.uuid4(),
user=user,
country=country,
city=city,
post_code=post_code,
address=address,
phone=phone,
)
def add_favorite(user, item, id=None):
"""Link the favorite item to user."""
return Favorite.create(
uuid=id or uuid.uuid4(),
item=item,
user=user,
)
def json_favorite(item):
"""Link the favorite item to user."""
return {
'item_uuid': item,
}
def add_item(name='Item Test', price='15.99',
description='test test test', id=None, category='scarpe'):
<|code_end|>
, determine the next line of code. You have imports:
from functools import reduce
from base64 import b64encode
from models import Address, User, Favorite, Item
from utils import get_image_folder
import datetime
import inspect
import json
import os
import random
import shutil
import sys
import uuid
and context (class names, function names, or code) available:
# Path: models.py
# class Address(BaseModel):
# """
# The model Address represent a user address.
# Each address is releated to one user, but one user can have
# more addresses.
#
# Attributes:
# uuid (UUID): Address unique uuid
# user (:any:`User`): Foreign key pointing to the user `owner` of the address
# country (str): Country for the address, i.e. ``Italy``
# city (str): City name
# post_code (str): Postal code for the address
# address (str): Full address for the Address resource
# phone (str): Phone number for the Address
# """
# uuid = UUIDField(unique=True)
# user = ForeignKeyField(User, related_name='addresses')
# country = CharField()
# city = CharField()
# post_code = CharField()
# address = CharField()
# phone = CharField()
#
# _schema = AddressSchema
#
# class User(BaseModel, UserMixin):
# """
# User represents an user for the application.
#
# Attributes:
# first_name (str): User's first name
# last_name (str): User's last name
# email (str): User's **valid** email
# password (str): User's password
# admin (bool): User's admin status. Defaults to ``False``
#
# .. NOTE::
# Each User resource must have an unique `email` field, meaning
# that there cannot be two user's registered with the same email.
#
# For this reason, when checking for user's existence, the server requires
# either the `uuid` of the user or its `email`.
# """
# uuid = UUIDField(unique=True)
# first_name = CharField()
# last_name = CharField()
# email = CharField(unique=True)
# password = CharField()
# admin = BooleanField(default=False)
# _schema = UserSchema
#
# @staticmethod
# def exists(email):
# """
# Check that an user exists by checking the email field.
#
# Args:
# email (str): User's email to check
# """
# try:
# User.get(User.email == email)
# except User.DoesNotExist:
# return False
# return True
#
# @staticmethod
# def hash_password(password):
# """
# Use passlib to get a crypted password.
#
# Args:
# password (str): password to hash
#
# Returns:
# str: hashed password
# """
# return pbkdf2_sha256.hash(password)
#
# def verify_password(self, password):
# """
# Verify a clear password against the stored hashed password of the user
# using passlib.
#
# Args:
# password (str): Password to verify against the hashed stored password
# Returns:
# bool: wether the given email matches the stored one
# """
# return pbkdf2_sha256.verify(password, self.password)
#
# def add_favorite(user, item):
# """Link the favorite item to user."""
# return Favorite.create(
# uuid=uuid4(),
# item=item,
# user=user,
# )
#
# def delete_favorite(self, obj):
# obj.delete_instance()
#
# class Favorite(BaseModel):
# """ Many to many table to relate an item with a user."""
# uuid = UUIDField(unique=True)
# user = ForeignKeyField(User, related_name="favorites")
# item = ForeignKeyField(Item, related_name="favorites")
# _schema = FavoriteSchema
#
# class Item(BaseModel):
# """
# Item describes a product for the e-commerce platform.
#
# Attributes:
# uuid (UUID): Item UUID
# name (str): Name for the product
# price (decimal.Decimal): Price for a single product
# description (str): Product description
# availability (int): Quantity of items available
# category (str): Category group of the item
#
# """
# uuid = UUIDField(unique=True)
# name = CharField()
# price = DecimalField(auto_round=True)
# description = TextField()
# availability = IntegerField()
# category = TextField()
# _schema = ItemSchema
# _search_attributes = ['name', 'category', 'description']
#
# def __str__(self):
# return '{}, {}, {}, {}'.format(
# self.uuid,
# self.name,
# self.price,
# self.description)
#
# def is_favorite(self, item):
# for f in self.favorites:
# if f.item_id == item.id:
# return True
# return False
#
# Path: utils.py
# def get_image_folder():
# return os.path.join(get_project_root(), IMAGE_FOLDER)
. Output only the next line. | return Item.create( |
Given the following code snippet before the placeholder: <|code_start|># Flask helpers
# Common operations for flask functionalities
def open_with_auth(app, url, method, username, password, content_type, data):
"""
Generic call to app for http request, required for requests that need
to send a ``Basic Auth`` request to the server.
"""
AUTH_TYPE = 'Basic'
bytes_auth = bytes('{}:{}'.format(username, password), 'ascii')
auth_str = '{} {}'.format(
AUTH_TYPE, b64encode(bytes_auth).decode('ascii'))
return app.open(url,
method=method,
headers={'Authorization': auth_str},
content_type=content_type,
data=data)
# ###########################################################
# Images helpers
def clean_images():
"""
Delete all the images in the IMAGE_FOLDER
"""
<|code_end|>
, predict the next line using imports from the current file:
from functools import reduce
from base64 import b64encode
from models import Address, User, Favorite, Item
from utils import get_image_folder
import datetime
import inspect
import json
import os
import random
import shutil
import sys
import uuid
and context including class names, function names, and sometimes code from other files:
# Path: models.py
# class Address(BaseModel):
# """
# The model Address represent a user address.
# Each address is releated to one user, but one user can have
# more addresses.
#
# Attributes:
# uuid (UUID): Address unique uuid
# user (:any:`User`): Foreign key pointing to the user `owner` of the address
# country (str): Country for the address, i.e. ``Italy``
# city (str): City name
# post_code (str): Postal code for the address
# address (str): Full address for the Address resource
# phone (str): Phone number for the Address
# """
# uuid = UUIDField(unique=True)
# user = ForeignKeyField(User, related_name='addresses')
# country = CharField()
# city = CharField()
# post_code = CharField()
# address = CharField()
# phone = CharField()
#
# _schema = AddressSchema
#
# class User(BaseModel, UserMixin):
# """
# User represents an user for the application.
#
# Attributes:
# first_name (str): User's first name
# last_name (str): User's last name
# email (str): User's **valid** email
# password (str): User's password
# admin (bool): User's admin status. Defaults to ``False``
#
# .. NOTE::
# Each User resource must have an unique `email` field, meaning
# that there cannot be two user's registered with the same email.
#
# For this reason, when checking for user's existence, the server requires
# either the `uuid` of the user or its `email`.
# """
# uuid = UUIDField(unique=True)
# first_name = CharField()
# last_name = CharField()
# email = CharField(unique=True)
# password = CharField()
# admin = BooleanField(default=False)
# _schema = UserSchema
#
# @staticmethod
# def exists(email):
# """
# Check that an user exists by checking the email field.
#
# Args:
# email (str): User's email to check
# """
# try:
# User.get(User.email == email)
# except User.DoesNotExist:
# return False
# return True
#
# @staticmethod
# def hash_password(password):
# """
# Use passlib to get a crypted password.
#
# Args:
# password (str): password to hash
#
# Returns:
# str: hashed password
# """
# return pbkdf2_sha256.hash(password)
#
# def verify_password(self, password):
# """
# Verify a clear password against the stored hashed password of the user
# using passlib.
#
# Args:
# password (str): Password to verify against the hashed stored password
# Returns:
# bool: wether the given email matches the stored one
# """
# return pbkdf2_sha256.verify(password, self.password)
#
# def add_favorite(user, item):
# """Link the favorite item to user."""
# return Favorite.create(
# uuid=uuid4(),
# item=item,
# user=user,
# )
#
# def delete_favorite(self, obj):
# obj.delete_instance()
#
# class Favorite(BaseModel):
# """ Many to many table to relate an item with a user."""
# uuid = UUIDField(unique=True)
# user = ForeignKeyField(User, related_name="favorites")
# item = ForeignKeyField(Item, related_name="favorites")
# _schema = FavoriteSchema
#
# class Item(BaseModel):
# """
# Item describes a product for the e-commerce platform.
#
# Attributes:
# uuid (UUID): Item UUID
# name (str): Name for the product
# price (decimal.Decimal): Price for a single product
# description (str): Product description
# availability (int): Quantity of items available
# category (str): Category group of the item
#
# """
# uuid = UUIDField(unique=True)
# name = CharField()
# price = DecimalField(auto_round=True)
# description = TextField()
# availability = IntegerField()
# category = TextField()
# _schema = ItemSchema
# _search_attributes = ['name', 'category', 'description']
#
# def __str__(self):
# return '{}, {}, {}, {}'.format(
# self.uuid,
# self.name,
# self.price,
# self.description)
#
# def is_favorite(self, item):
# for f in self.favorites:
# if f.item_id == item.id:
# return True
# return False
#
# Path: utils.py
# def get_image_folder():
# return os.path.join(get_project_root(), IMAGE_FOLDER)
. Output only the next line. | shutil.rmtree(get_image_folder(), onerror=None) |
Given snippet: <|code_start|> click.echo('####################\n####################\nADMIN USER SCRIPT\n')
click.echo('####################\n####################\n')
click.echo('Here you can create an admin user. For eachone you have to insert:\n')
click.echo('first name\n-last name\n-email\n-password')
if not first_name:
first_name = click.prompt('Please enter your first name')
if not last_name:
last_name = click.prompt('Please enter your last name')
if not email:
email = click.prompt('Please enter a valid email')
if not password:
password = click.prompt('Please enter your password')
request_data = {
'first_name': first_name,
'last_name': last_name,
'email': email,
'password': password
}
for field in request_data:
try:
value = request_data[field]
non_empty_str(value, field)
except ValueError:
print('ERROR! Some fields are empty or required')
sys.exit(-1)
# If email is present in the database return a ERROR and close the program.
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import click
import sys
import uuid
from models import User
from utils import non_empty_str
and context:
# Path: models.py
# class User(BaseModel, UserMixin):
# """
# User represents an user for the application.
#
# Attributes:
# first_name (str): User's first name
# last_name (str): User's last name
# email (str): User's **valid** email
# password (str): User's password
# admin (bool): User's admin status. Defaults to ``False``
#
# .. NOTE::
# Each User resource must have an unique `email` field, meaning
# that there cannot be two user's registered with the same email.
#
# For this reason, when checking for user's existence, the server requires
# either the `uuid` of the user or its `email`.
# """
# uuid = UUIDField(unique=True)
# first_name = CharField()
# last_name = CharField()
# email = CharField(unique=True)
# password = CharField()
# admin = BooleanField(default=False)
# _schema = UserSchema
#
# @staticmethod
# def exists(email):
# """
# Check that an user exists by checking the email field.
#
# Args:
# email (str): User's email to check
# """
# try:
# User.get(User.email == email)
# except User.DoesNotExist:
# return False
# return True
#
# @staticmethod
# def hash_password(password):
# """
# Use passlib to get a crypted password.
#
# Args:
# password (str): password to hash
#
# Returns:
# str: hashed password
# """
# return pbkdf2_sha256.hash(password)
#
# def verify_password(self, password):
# """
# Verify a clear password against the stored hashed password of the user
# using passlib.
#
# Args:
# password (str): Password to verify against the hashed stored password
# Returns:
# bool: wether the given email matches the stored one
# """
# return pbkdf2_sha256.verify(password, self.password)
#
# def add_favorite(user, item):
# """Link the favorite item to user."""
# return Favorite.create(
# uuid=uuid4(),
# item=item,
# user=user,
# )
#
# def delete_favorite(self, obj):
# obj.delete_instance()
#
# Path: utils.py
# def non_empty_str(val, name):
# """
# Check if a string is empty. If not, raise a ValueError exception.
# """
# if not str(val).strip():
# raise ValueError('The argument {} is not empty'.format(name))
# return str(val)
which might include code, classes, or functions. Output only the next line. | if User.exists(request_data['email']): |
Using the snippet: <|code_start|>@click.command()
@click.option('--first_name')
@click.option('--last_name')
@click.option('--email')
@click.option('--password')
def main(first_name, last_name, email, password):
click.echo('####################\n####################\nADMIN USER SCRIPT\n')
click.echo('####################\n####################\n')
click.echo('Here you can create an admin user. For eachone you have to insert:\n')
click.echo('first name\n-last name\n-email\n-password')
if not first_name:
first_name = click.prompt('Please enter your first name')
if not last_name:
last_name = click.prompt('Please enter your last name')
if not email:
email = click.prompt('Please enter a valid email')
if not password:
password = click.prompt('Please enter your password')
request_data = {
'first_name': first_name,
'last_name': last_name,
'email': email,
'password': password
}
for field in request_data:
try:
value = request_data[field]
<|code_end|>
, determine the next line of code. You have imports:
import click
import sys
import uuid
from models import User
from utils import non_empty_str
and context (class names, function names, or code) available:
# Path: models.py
# class User(BaseModel, UserMixin):
# """
# User represents an user for the application.
#
# Attributes:
# first_name (str): User's first name
# last_name (str): User's last name
# email (str): User's **valid** email
# password (str): User's password
# admin (bool): User's admin status. Defaults to ``False``
#
# .. NOTE::
# Each User resource must have an unique `email` field, meaning
# that there cannot be two user's registered with the same email.
#
# For this reason, when checking for user's existence, the server requires
# either the `uuid` of the user or its `email`.
# """
# uuid = UUIDField(unique=True)
# first_name = CharField()
# last_name = CharField()
# email = CharField(unique=True)
# password = CharField()
# admin = BooleanField(default=False)
# _schema = UserSchema
#
# @staticmethod
# def exists(email):
# """
# Check that an user exists by checking the email field.
#
# Args:
# email (str): User's email to check
# """
# try:
# User.get(User.email == email)
# except User.DoesNotExist:
# return False
# return True
#
# @staticmethod
# def hash_password(password):
# """
# Use passlib to get a crypted password.
#
# Args:
# password (str): password to hash
#
# Returns:
# str: hashed password
# """
# return pbkdf2_sha256.hash(password)
#
# def verify_password(self, password):
# """
# Verify a clear password against the stored hashed password of the user
# using passlib.
#
# Args:
# password (str): Password to verify against the hashed stored password
# Returns:
# bool: wether the given email matches the stored one
# """
# return pbkdf2_sha256.verify(password, self.password)
#
# def add_favorite(user, item):
# """Link the favorite item to user."""
# return Favorite.create(
# uuid=uuid4(),
# item=item,
# user=user,
# )
#
# def delete_favorite(self, obj):
# obj.delete_instance()
#
# Path: utils.py
# def non_empty_str(val, name):
# """
# Check if a string is empty. If not, raise a ValueError exception.
# """
# if not str(val).strip():
# raise ValueError('The argument {} is not empty'.format(name))
# return str(val)
. Output only the next line. | non_empty_str(value, field) |
Here is a snippet: <|code_start|>
class AddressesHandler(Resource):
""" Addresses endpoint. """
@auth.login_required
def get(self):
<|code_end|>
. Write the next line using the current file imports:
from auth import auth
from flask import request
from flask_restful import Resource
from http.client import CREATED, NO_CONTENT, NOT_FOUND, OK, BAD_REQUEST
from models import Address
from utils import generate_response
import uuid
and context from other files:
# Path: auth.py
# class Auth:
# def login_required(*args, **kwargs):
# def current_user(self):
# def init_app(app):
# def load_user(user_id):
# def load_user_from_request(request):
#
# Path: models.py
# class Address(BaseModel):
# """
# The model Address represent a user address.
# Each address is releated to one user, but one user can have
# more addresses.
#
# Attributes:
# uuid (UUID): Address unique uuid
# user (:any:`User`): Foreign key pointing to the user `owner` of the address
# country (str): Country for the address, i.e. ``Italy``
# city (str): City name
# post_code (str): Postal code for the address
# address (str): Full address for the Address resource
# phone (str): Phone number for the Address
# """
# uuid = UUIDField(unique=True)
# user = ForeignKeyField(User, related_name='addresses')
# country = CharField()
# city = CharField()
# post_code = CharField()
# address = CharField()
# phone = CharField()
#
# _schema = AddressSchema
#
# Path: utils.py
# def generate_response(data, status, mimetype='application/vnd.api+json'):
# """
# Given a resource model that extends from `BaseModel` generate a Reponse
# object to be returned from the application endpoints'
# """
# return Response(
# response=data,
# status=status,
# mimetype=mimetype
# )
, which may include functions, classes, or code. Output only the next line. | user_addrs = list(Address.select().where( |
Here is a snippet: <|code_start|>
class AddressesHandler(Resource):
""" Addresses endpoint. """
@auth.login_required
def get(self):
user_addrs = list(Address.select().where(
Address.user == auth.current_user))
<|code_end|>
. Write the next line using the current file imports:
from auth import auth
from flask import request
from flask_restful import Resource
from http.client import CREATED, NO_CONTENT, NOT_FOUND, OK, BAD_REQUEST
from models import Address
from utils import generate_response
import uuid
and context from other files:
# Path: auth.py
# class Auth:
# def login_required(*args, **kwargs):
# def current_user(self):
# def init_app(app):
# def load_user(user_id):
# def load_user_from_request(request):
#
# Path: models.py
# class Address(BaseModel):
# """
# The model Address represent a user address.
# Each address is releated to one user, but one user can have
# more addresses.
#
# Attributes:
# uuid (UUID): Address unique uuid
# user (:any:`User`): Foreign key pointing to the user `owner` of the address
# country (str): Country for the address, i.e. ``Italy``
# city (str): City name
# post_code (str): Postal code for the address
# address (str): Full address for the Address resource
# phone (str): Phone number for the Address
# """
# uuid = UUIDField(unique=True)
# user = ForeignKeyField(User, related_name='addresses')
# country = CharField()
# city = CharField()
# post_code = CharField()
# address = CharField()
# phone = CharField()
#
# _schema = AddressSchema
#
# Path: utils.py
# def generate_response(data, status, mimetype='application/vnd.api+json'):
# """
# Given a resource model that extends from `BaseModel` generate a Reponse
# object to be returned from the application endpoints'
# """
# return Response(
# response=data,
# status=status,
# mimetype=mimetype
# )
, which may include functions, classes, or code. Output only the next line. | return generate_response(Address.json_list(user_addrs), OK) |
Predict the next line for this snippet: <|code_start|>"""
Search API core module
Contains the main functions to get match values and searching
"""
def similarity(query, string):
"""
Calculate the match for the given `query` and `string`.
The match is calculated using the `jaro winkler` for each set of the matrix
(`query` x `string`) and takes into consideration the position difference
into the strings.
Arguments:
query (str): search query
string (str): string to test against
Returns:
float: normalized value indicating the probability of match, where
0 means completely dissimilar and 1 means equal.
"""
# split the two strings cleaning out some stuff
<|code_end|>
with the help of current file imports:
import jellyfish as jf
from search import utils, config
and context from other files:
# Path: search/utils.py
# def _dec(fl):
# def normalize(iterable):
# def scale_to_one(iterable):
# def weighted_average(values, weights):
# def tokenize(string):
# def max_distance(phrase, word_index):
# def position_similarity(token1, token2, phrase1, phrase2):
#
# Path: search/config.py
# MATCH_WEIGHT = 0.2
# DIST_WEIGHT = 0.8
# THRESHOLD = 0.75
# MIN_WORD_LENGTH = 3
# STR_SPLIT_REGEX = r'\W+'
, which may contain function names, class names, or code. Output only the next line. | query = utils.tokenize(query.lower()) |
Continue the code snippet: <|code_start|> query = utils.tokenize(query.lower())
string = utils.tokenize(string.lower())
# if one of the two strings is falsy (no content, or was passed with items
# short enough to be trimmed out), return 0 here to avoid ZeroDivisionError
# later on while processing.
if len(query) == 0 or len(string) == 0:
return 0
shortest, longest = sorted((query, string), key=lambda x: len(x))
# matrix of tuples for each segment of both query and string
matrix = [(s1, s2) for s1 in longest for s2 in shortest]
matches = {}
for string1, string2 in matrix:
# get the jaro winkler equality between the two strings
match = jf.jaro_winkler(string1, string2)
# calculate the distance factor for the position of the segments
# on their respective lists
positional = utils.position_similarity(
string1, string2, longest, shortest)
# get them together and append to the matches dictionary
match = (match, positional)
matches.setdefault(string1, []).append(match)
# get the highest value for each list, the apply the word-distance factor
# the key takes the jaro winkler distance value to get the max value
matches = [max(m, key=lambda x: x[0]) for m in matches.values()]
<|code_end|>
. Use current file imports:
import jellyfish as jf
from search import utils, config
and context (classes, functions, or code) from other files:
# Path: search/utils.py
# def _dec(fl):
# def normalize(iterable):
# def scale_to_one(iterable):
# def weighted_average(values, weights):
# def tokenize(string):
# def max_distance(phrase, word_index):
# def position_similarity(token1, token2, phrase1, phrase2):
#
# Path: search/config.py
# MATCH_WEIGHT = 0.2
# DIST_WEIGHT = 0.8
# THRESHOLD = 0.75
# MIN_WORD_LENGTH = 3
# STR_SPLIT_REGEX = r'\W+'
. Output only the next line. | _weights = (config.MATCH_WEIGHT, config.DIST_WEIGHT) |
Predict the next line after this snippet: <|code_start|> 'uuid': '429994bf-784e-47cc-a823-e0c394b823e8',
'name': 'mario',
'price': 20.20,
'description': 'svariati mariii',
'availability': 1,
'category': 'scarpe',
}
TEST_ITEM2 = {
'uuid': 'd46b13a1-f4bb-4cfb-8076-6953358145f3',
'name': 'GINO',
'price': 30.20,
'description': 'svariati GINIIIII',
'availability': 1,
'category': 'accessori',
}
TEST_PICTURE = {
'uuid': 'df690434-a488-419f-899e-8853cba1a22b',
'extension': 'jpg'
}
TEST_PICTURE2 = {
'uuid': 'c0001a48-10a3-43c1-b87b-eabac0b2d42f',
'extension': 'png'
}
WRONG_UUID = 'e8e42371-46de-4f5e-8927-e2cc34826269'
<|code_end|>
using the current file's imports:
from tests.test_case import TestCase
from io import BytesIO
from models import Item, Picture
from tests import test_utils
import json
import os
import uuid
import http.client as client
import utils
and any relevant context from other files:
# Path: tests/test_case.py
# class TestCase:
# """
# Created TestCase to avoid duplicated code in the other tests
# """
# TEST_DB = SqliteDatabase(':memory:')
#
# @classmethod
# def setup_class(cls):
# """
# When a Test is created override the ``database`` attribute for all
# the tables with a SqliteDatabase in memory.
# """
# for table in TABLES:
# table._meta.database = cls.TEST_DB
# table.create_table(fail_silently=True)
#
# cls.app = app.test_client()
#
# def setup_method(self):
# """
# When setting up a new test method clear all the tables
# """
# for table in TABLES:
# table.delete().execute()
#
# Path: models.py
# class Item(BaseModel):
# """
# Item describes a product for the e-commerce platform.
#
# Attributes:
# uuid (UUID): Item UUID
# name (str): Name for the product
# price (decimal.Decimal): Price for a single product
# description (str): Product description
# availability (int): Quantity of items available
# category (str): Category group of the item
#
# """
# uuid = UUIDField(unique=True)
# name = CharField()
# price = DecimalField(auto_round=True)
# description = TextField()
# availability = IntegerField()
# category = TextField()
# _schema = ItemSchema
# _search_attributes = ['name', 'category', 'description']
#
# def __str__(self):
# return '{}, {}, {}, {}'.format(
# self.uuid,
# self.name,
# self.price,
# self.description)
#
# def is_favorite(self, item):
# for f in self.favorites:
# if f.item_id == item.id:
# return True
# return False
#
# class Picture(BaseModel):
# """
# A Picture model describes and points to a stored image file. Allows linkage
# between the image files and one :any:`Item` resource.
#
# Attributes:
# uuid (UUID): Picture's uuid
# extension (str): Extension of the image file the Picture's model refer to
# item (:any:`Item`): Foreign key referencing the Item related to the Picture.
# A ``pictures`` field can be used from ``Item`` to access the Item resource
# pictures
# """
# uuid = UUIDField(unique=True)
# extension = CharField()
# item = ForeignKeyField(Item, related_name='pictures')
# _schema = PictureSchema
#
# @property
# def filename(self):
# """Full name (uuid.ext) of the file that the Picture model reference."""
# return '{}.{}'.format(
# self.uuid,
# self.extension)
#
# def __str__(self):
# return '{}.{} -> item: {}'.format(
# self.uuid,
# self.extension,
# self.item.uuid)
#
# Path: tests/test_utils.py
# def mock_uuid_generator():
# def mock_datetime(*args):
# def __init__(self, cls):
# def __call__(self, created_at=mock_datetime(), uuid=None, **query):
# def get_all_models_names():
# def add_user(email, password, id=None, first_name='John', last_name='Doe'):
# def add_admin_user(email, psw, id=None):
# def add_address(user, country='Italy', city='Pistoia', post_code='51100',
# address='Via Verdi 12', phone='3294882773', id=None):
# def add_favorite(user, item, id=None):
# def json_favorite(item):
# def add_item(name='Item Test', price='15.99',
# description='test test test', id=None, category='scarpe'):
# def open_with_auth(app, url, method, username, password, content_type, data):
# def clean_images():
# def setup_images():
# def count_order_items(order):
# def format_jsonapi_request(type_, data):
# def assert_valid_response(data, expected):
# def sort_data_lists(data, attribute, key):
# def included_sorter(i): return i['type']
# def errors_sorter(e): return e['source']['pointer']
# def wrong_dump(data):
# class MockModelCreate:
# AUTH_TYPE = 'Basic'
# RESULTS = json.load(fo)
. Output only the next line. | class TestPictures(TestCase): |
Based on the snippet: <|code_start|> 'price': 30.20,
'description': 'svariati GINIIIII',
'availability': 1,
'category': 'accessori',
}
TEST_PICTURE = {
'uuid': 'df690434-a488-419f-899e-8853cba1a22b',
'extension': 'jpg'
}
TEST_PICTURE2 = {
'uuid': 'c0001a48-10a3-43c1-b87b-eabac0b2d42f',
'extension': 'png'
}
WRONG_UUID = 'e8e42371-46de-4f5e-8927-e2cc34826269'
class TestPictures(TestCase):
@classmethod
def setup_class(cls):
super(TestPictures, cls).setup_class()
utils.get_image_folder = lambda: os.path.join(utils.get_project_root(),
TEST_IMAGE_FOLDER)
test_utils.get_image_folder = utils.get_image_folder
def test_get_picture__success(self):
test_utils.setup_images()
<|code_end|>
, predict the immediate next line with the help of imports:
from tests.test_case import TestCase
from io import BytesIO
from models import Item, Picture
from tests import test_utils
import json
import os
import uuid
import http.client as client
import utils
and context (classes, functions, sometimes code) from other files:
# Path: tests/test_case.py
# class TestCase:
# """
# Created TestCase to avoid duplicated code in the other tests
# """
# TEST_DB = SqliteDatabase(':memory:')
#
# @classmethod
# def setup_class(cls):
# """
# When a Test is created override the ``database`` attribute for all
# the tables with a SqliteDatabase in memory.
# """
# for table in TABLES:
# table._meta.database = cls.TEST_DB
# table.create_table(fail_silently=True)
#
# cls.app = app.test_client()
#
# def setup_method(self):
# """
# When setting up a new test method clear all the tables
# """
# for table in TABLES:
# table.delete().execute()
#
# Path: models.py
# class Item(BaseModel):
# """
# Item describes a product for the e-commerce platform.
#
# Attributes:
# uuid (UUID): Item UUID
# name (str): Name for the product
# price (decimal.Decimal): Price for a single product
# description (str): Product description
# availability (int): Quantity of items available
# category (str): Category group of the item
#
# """
# uuid = UUIDField(unique=True)
# name = CharField()
# price = DecimalField(auto_round=True)
# description = TextField()
# availability = IntegerField()
# category = TextField()
# _schema = ItemSchema
# _search_attributes = ['name', 'category', 'description']
#
# def __str__(self):
# return '{}, {}, {}, {}'.format(
# self.uuid,
# self.name,
# self.price,
# self.description)
#
# def is_favorite(self, item):
# for f in self.favorites:
# if f.item_id == item.id:
# return True
# return False
#
# class Picture(BaseModel):
# """
# A Picture model describes and points to a stored image file. Allows linkage
# between the image files and one :any:`Item` resource.
#
# Attributes:
# uuid (UUID): Picture's uuid
# extension (str): Extension of the image file the Picture's model refer to
# item (:any:`Item`): Foreign key referencing the Item related to the Picture.
# A ``pictures`` field can be used from ``Item`` to access the Item resource
# pictures
# """
# uuid = UUIDField(unique=True)
# extension = CharField()
# item = ForeignKeyField(Item, related_name='pictures')
# _schema = PictureSchema
#
# @property
# def filename(self):
# """Full name (uuid.ext) of the file that the Picture model reference."""
# return '{}.{}'.format(
# self.uuid,
# self.extension)
#
# def __str__(self):
# return '{}.{} -> item: {}'.format(
# self.uuid,
# self.extension,
# self.item.uuid)
#
# Path: tests/test_utils.py
# def mock_uuid_generator():
# def mock_datetime(*args):
# def __init__(self, cls):
# def __call__(self, created_at=mock_datetime(), uuid=None, **query):
# def get_all_models_names():
# def add_user(email, password, id=None, first_name='John', last_name='Doe'):
# def add_admin_user(email, psw, id=None):
# def add_address(user, country='Italy', city='Pistoia', post_code='51100',
# address='Via Verdi 12', phone='3294882773', id=None):
# def add_favorite(user, item, id=None):
# def json_favorite(item):
# def add_item(name='Item Test', price='15.99',
# description='test test test', id=None, category='scarpe'):
# def open_with_auth(app, url, method, username, password, content_type, data):
# def clean_images():
# def setup_images():
# def count_order_items(order):
# def format_jsonapi_request(type_, data):
# def assert_valid_response(data, expected):
# def sort_data_lists(data, attribute, key):
# def included_sorter(i): return i['type']
# def errors_sorter(e): return e['source']['pointer']
# def wrong_dump(data):
# class MockModelCreate:
# AUTH_TYPE = 'Basic'
# RESULTS = json.load(fo)
. Output only the next line. | item = Item.create(**TEST_ITEM) |
Given the code snippet: <|code_start|> 'description': 'svariati GINIIIII',
'availability': 1,
'category': 'accessori',
}
TEST_PICTURE = {
'uuid': 'df690434-a488-419f-899e-8853cba1a22b',
'extension': 'jpg'
}
TEST_PICTURE2 = {
'uuid': 'c0001a48-10a3-43c1-b87b-eabac0b2d42f',
'extension': 'png'
}
WRONG_UUID = 'e8e42371-46de-4f5e-8927-e2cc34826269'
class TestPictures(TestCase):
@classmethod
def setup_class(cls):
super(TestPictures, cls).setup_class()
utils.get_image_folder = lambda: os.path.join(utils.get_project_root(),
TEST_IMAGE_FOLDER)
test_utils.get_image_folder = utils.get_image_folder
def test_get_picture__success(self):
test_utils.setup_images()
item = Item.create(**TEST_ITEM)
<|code_end|>
, generate the next line using the imports in this file:
from tests.test_case import TestCase
from io import BytesIO
from models import Item, Picture
from tests import test_utils
import json
import os
import uuid
import http.client as client
import utils
and context (functions, classes, or occasionally code) from other files:
# Path: tests/test_case.py
# class TestCase:
# """
# Created TestCase to avoid duplicated code in the other tests
# """
# TEST_DB = SqliteDatabase(':memory:')
#
# @classmethod
# def setup_class(cls):
# """
# When a Test is created override the ``database`` attribute for all
# the tables with a SqliteDatabase in memory.
# """
# for table in TABLES:
# table._meta.database = cls.TEST_DB
# table.create_table(fail_silently=True)
#
# cls.app = app.test_client()
#
# def setup_method(self):
# """
# When setting up a new test method clear all the tables
# """
# for table in TABLES:
# table.delete().execute()
#
# Path: models.py
# class Item(BaseModel):
# """
# Item describes a product for the e-commerce platform.
#
# Attributes:
# uuid (UUID): Item UUID
# name (str): Name for the product
# price (decimal.Decimal): Price for a single product
# description (str): Product description
# availability (int): Quantity of items available
# category (str): Category group of the item
#
# """
# uuid = UUIDField(unique=True)
# name = CharField()
# price = DecimalField(auto_round=True)
# description = TextField()
# availability = IntegerField()
# category = TextField()
# _schema = ItemSchema
# _search_attributes = ['name', 'category', 'description']
#
# def __str__(self):
# return '{}, {}, {}, {}'.format(
# self.uuid,
# self.name,
# self.price,
# self.description)
#
# def is_favorite(self, item):
# for f in self.favorites:
# if f.item_id == item.id:
# return True
# return False
#
# class Picture(BaseModel):
# """
# A Picture model describes and points to a stored image file. Allows linkage
# between the image files and one :any:`Item` resource.
#
# Attributes:
# uuid (UUID): Picture's uuid
# extension (str): Extension of the image file the Picture's model refer to
# item (:any:`Item`): Foreign key referencing the Item related to the Picture.
# A ``pictures`` field can be used from ``Item`` to access the Item resource
# pictures
# """
# uuid = UUIDField(unique=True)
# extension = CharField()
# item = ForeignKeyField(Item, related_name='pictures')
# _schema = PictureSchema
#
# @property
# def filename(self):
# """Full name (uuid.ext) of the file that the Picture model reference."""
# return '{}.{}'.format(
# self.uuid,
# self.extension)
#
# def __str__(self):
# return '{}.{} -> item: {}'.format(
# self.uuid,
# self.extension,
# self.item.uuid)
#
# Path: tests/test_utils.py
# def mock_uuid_generator():
# def mock_datetime(*args):
# def __init__(self, cls):
# def __call__(self, created_at=mock_datetime(), uuid=None, **query):
# def get_all_models_names():
# def add_user(email, password, id=None, first_name='John', last_name='Doe'):
# def add_admin_user(email, psw, id=None):
# def add_address(user, country='Italy', city='Pistoia', post_code='51100',
# address='Via Verdi 12', phone='3294882773', id=None):
# def add_favorite(user, item, id=None):
# def json_favorite(item):
# def add_item(name='Item Test', price='15.99',
# description='test test test', id=None, category='scarpe'):
# def open_with_auth(app, url, method, username, password, content_type, data):
# def clean_images():
# def setup_images():
# def count_order_items(order):
# def format_jsonapi_request(type_, data):
# def assert_valid_response(data, expected):
# def sort_data_lists(data, attribute, key):
# def included_sorter(i): return i['type']
# def errors_sorter(e): return e['source']['pointer']
# def wrong_dump(data):
# class MockModelCreate:
# AUTH_TYPE = 'Basic'
# RESULTS = json.load(fo)
. Output only the next line. | picture = Picture.create(item=item, **TEST_PICTURE) |
Here is a snippet: <|code_start|> if name == "":
return self
else:
return Resource.getChild(self, name, request)
def render_GET(self, request):
"""Called for all requests to this object"""
log.debug("render_GET")
# Rendering
request.setHeader('content-type',
'application/vnd.mozilla.xul+xml')
xul = u'<?xml version="1.0"?> \n'
xul += u'<?xml-stylesheet href="chrome://global/skin/" '
xul += u'type="text/css"?> \n'
xul += u'<?xml-stylesheet href="/css/aboutDialog.css" '
xul += u'type="text/css"?>\n'
xul += u'<window xmlns:html="http://www.w3.org/1999/xhtml"\n'
xul += u' xmlns="http://www.mozilla.org/keymaster/gatekeeper/'
xul += u'there.is.only.xul"\n'
xul += u' id="aboutDialog"\n'
xul += u' title="About eXe"\n'
xul += u' style="width: 299px">\n'
xul += u' <deck id="modes" flex="1">\n'
xul += u' <vbox flex="1" id="clientBox">\n'
xul += u' <label id="eXeName" \n'
xul += u' value="eLearning XHTML editor"/>\n'
xul += u' <label id="version" \n'
<|code_end|>
. Write the next line using the current file imports:
import logging
from twisted.web.resource import Resource
from exe.webui.renderable import RenderableResource
from exe.engine import version
and context from other files:
# Path: exe/engine/version.py
, which may include functions, classes, or code. Output only the next line. | xul += u' value="eXe Version '+version.release+'"/>\n' |
Here is a snippet: <|code_start|>#!/usr/bin/env python
# another thinly disguised shell script written in Python
# TOPDIR root of RPM build tree typically /usr/src/redhat or /home/xxx/.rpm
#TOPDIR = '/usr/src/redhat'
TOPDIR = os.path.join(os.environ['HOME'], '.rpm')
# where the SVN exe source directory is
#SRCDIR = '/usr/local/src'
SRCDIR = os.path.abspath('../../..')
# get the version/revision
sys.path.insert(0, os.path.join(SRCDIR, 'exe'))
# find the first release that doesn't exist
clrelease = 1
while 1:
files = glob.glob(os.path.join(TOPDIR, 'RPMS/i386',
<|code_end|>
. Write the next line using the current file imports:
import sys
import os
import glob
import subprocess
from exe.engine import version
and context from other files:
# Path: exe/engine/version.py
, which may include functions, classes, or code. Output only the next line. | 'exe-%s-%d.*.i386.rpm' % (version.version, clrelease))) |
Given the following code snippet before the placeholder: <|code_start|><ul>
<li> What learning outcomes are the questions testing</li>
<li> What intellectual skills are being tested</li>
<li> What are the language skills of the audience</li>
<li> Gender and cultural issues</li>
<li> Avoid grammar language and question structures that might provide
clues</li>
</ul>
"""), x_(u"""When building an MCQ consider the following: <ul>
<li> Use phrases that learners are familiar with and have
encountered in their study </li>
<li> Keep responses concise </li>
<li> There should be some consistency between the stem and the responses </li>
<li> Provide enough options to challenge learners to think about their response
</li>
<li> Try to make sure that correct responses are not more detailed than the
distractors </li>
<li> Distractors should be incorrect but plausible </li>
</ul>
"""), u"question")
self.emphasis = Idevice.SomeEmphasis
self.questions = []
self.addQuestion()
self.systemResources += ["common.js"]
def addQuestion(self):
"""
Add a new question to this iDevice.
"""
<|code_end|>
, predict the next line using imports from the current file:
import logging
import re
from exe.engine.persist import Persistable
from exe.engine.idevice import Idevice
from exe.engine.translate import lateTranslate
from exe.engine.field import SelectQuestionField
and context including class names, function names, and sometimes code from other files:
# Path: exe/engine/field.py
# class SelectQuestionField(Field):
# """
# A Question is built up of question and Options.
# Used as part of the Multi-Select iDevice.
# """
#
# persistenceVersion = 1
#
# def __init__(self, idevice, name, instruc=""):
# """
# Initialize
# """
# Field.__init__(self, name, instruc)
#
# self.idevice = idevice
#
# self._questionInstruc = x_(u"""Enter the question stem.
# The question should be clear and unambiguous. Avoid negative premises as these
# can tend to confuse learners.""")
# self.questionTextArea = TextAreaField(x_(u'Question:'),
# self.questionInstruc, u'')
# self.questionTextArea.idevice = idevice
#
# self.options = []
# self._optionInstruc = x_(u"""Enter the available choices here.
# You can add options by clicking the "Add another option" button. Delete options by
# clicking the red X next to the option.""")
#
# self._correctAnswerInstruc = x_(u"""Select as many correct answer
# options as required by clicking the check box beside the option.""")
#
# self.feedbackInstruc = x_(u"""Type in the feedback you want
# to provide the learner with.""")
# self.feedbackTextArea = TextAreaField(x_(u'Feedback:'),
# self.feedbackInstruc, u'')
# self.feedbackTextArea.idevice = idevice
#
#
# # Properties
# questionInstruc = lateTranslate('questionInstruc')
# optionInstruc = lateTranslate('optionInstruc')
# correctAnswerInstruc = lateTranslate('correctAnswerInstruc')
#
# def addOption(self):
# """
# Add a new option to this question.
# """
# option = SelectOptionField(self, self.idevice)
# self.options.append(option)
#
# def getResourcesField(self, this_resource):
# """
# implement the specific resource finding mechanism for this iDevice:
# """
# # be warned that before upgrading, this iDevice field could not exist:
# if hasattr(self, 'questionTextArea')\
# and hasattr(self.questionTextArea, 'images'):
# for this_image in self.questionTextArea.images:
# if hasattr(this_image, '_imageResource') \
# and this_resource == this_image._imageResource:
# return self.questionTextArea
#
# # be warned that before upgrading, this iDevice field could not exist:
# if hasattr(self, 'feedbackTextArea')\
# and hasattr(self.feedbackTextArea, 'images'):
# for this_image in self.feedbackTextArea.images:
# if hasattr(this_image, '_imageResource') \
# and this_resource == this_image._imageResource:
# return self.feedbackTextArea
#
# for this_option in self.options:
# this_field = this_option.getResourcesField(this_resource)
# if this_field is not None:
# return this_field
#
# return None
#
#
# def getRichTextFields(self):
# """
# Like getResourcesField(), a general helper to allow nodes to search
# through all of their fields without having to know the specifics of each
# iDevice type.
# """
# fields_list = []
# if hasattr(self, 'questionTextArea'):
# fields_list.append(self.questionTextArea)
# if hasattr(self, 'feedbackTextArea'):
# fields_list.append(self.feedbackTextArea)
#
# for this_option in self.options:
# fields_list.extend(this_option.getRichTextFields())
#
# return fields_list
#
# def upgradeToVersion1(self):
# """
# Upgrades to somewhere before version 0.25 (post-v0.24)
# to reflect the new TextAreaFields now in use for images.
# """
# self.questionTextArea = TextAreaField(x_(u'Question:'),
# self.questionInstruc, self.question)
# self.questionTextArea.idevice = self.idevice
# self.feedbackTextArea = TextAreaField(x_(u'Feedback:'),
# self.feedbackInstruc, self.feedback)
# self.feedbackTextArea.idevice = self.idevice
. Output only the next line. | question = SelectQuestionField(self, x_(u'Question')) |
Next line prediction: <|code_start|> "different types of activity "
"planned for your resource that "
"will be visually signalled in the "
"content. Avoid using too many "
"different types or classification "
"of activities otherwise learner "
"may become confused. Usually three "
"or four different types are more "
"than adequate for a teaching "
"resource."
"</li>"
"<li>"
"From a visual design "
"perspective, avoid having two "
"iDevices immediately following "
"each other without any text in "
"between. If this is required, "
"rather collapse two questions or "
"events into one iDevice. "
"</li>"
"<li>"
"Think "
"about activities where the "
"perceived benefit of doing the "
"activity outweighs the time and "
"effort it will take to complete "
"the activity. "
"</li>"
"</ol>"))
readingAct.emphasis = Idevice.SomeEmphasis
<|code_end|>
. Use current file imports:
(from exe.engine import persist
from exe.engine.idevice import Idevice
from exe.engine.field import TextAreaField, FeedbackField
from nevow.flat import flatten
from exe.engine.freetextidevice import FreeTextIdevice
from exe.engine.multimediaidevice import MultimediaIdevice
from exe.engine.reflectionidevice import ReflectionIdevice
from exe.engine.casestudyidevice import CasestudyIdevice
from exe.engine.truefalseidevice import TrueFalseIdevice
from exe.engine.wikipediaidevice import WikipediaIdevice
from exe.engine.attachmentidevice import AttachmentIdevice
from exe.engine.titleidevice import TitleIdevice
from exe.engine.galleryidevice import GalleryIdevice
from exe.engine.clozeidevice import ClozeIdevice
from exe.engine.flashwithtextidevice import FlashWithTextIdevice
from exe.engine.externalurlidevice import ExternalUrlIdevice
from exe.engine.imagemagnifieridevice import ImageMagnifierIdevice
from exe.engine.multichoiceidevice import MultichoiceIdevice
from exe.engine.rssidevice import RssIdevice
from exe.engine.multiselectidevice import MultiSelectIdevice
from exe.engine.appletidevice import AppletIdevice
from exe.engine.flashmovieidevice import FlashMovieIdevice
from exe.engine.quiztestidevice import QuizTestIdevice
from exe.engine.genericidevice import GenericIdevice
from exe.engine.genericidevice import GenericIdevice
import imp
import sys
import logging)
and context including class names, function names, or small code snippets from other files:
# Path: exe/engine/field.py
# class TextAreaField(FieldWithResources):
# """
# A Generic iDevice is built up of these fields. Each field can be
# rendered as an XHTML element
#
# Note that TextAreaFields can now hold any number of image resources,
# which will typically be inserted by way of tinyMCE.
# """
# persistenceVersion = 1
#
# # these will be recreated in FieldWithResources' TwistedRePersist:
# nonpersistant = ['content', 'content_wo_resourcePaths']
#
# def __init__(self, name, instruc="", content=""):
# """
# Initialize
# """
# FieldWithResources.__init__(self, name, instruc, content)
#
# def upgradeToVersion1(self):
# """
# Upgrades to somewhere before version 0.25 (post-v0.24)
# to reflect that TextAreaField now inherits from FieldWithResources,
# and will need its corresponding fields populated from content.
# """
# self.content_w_resourcePaths = self.content
# self.content_wo_resourcePaths = self.content
# # NOTE: we don't need to actually process any of those contents for
# # image paths, either, since this is an upgrade from pre-images!
#
# class FeedbackField(FieldWithResources):
# """
# A Generic iDevice is built up of these fields. Each field can be
# rendered as an XHTML element
# """
#
# persistenceVersion = 2
#
# # these will be recreated in FieldWithResources' TwistedRePersist:
# nonpersistant = ['content', 'content_wo_resourcePaths']
#
# def __init__(self, name, instruc=""):
# """
# Initialize
# """
# FieldWithResources.__init__(self, name, instruc)
#
# self._buttonCaption = x_(u"Click Here")
#
# self.feedback = ""
# # Note: now that FeedbackField extends from FieldWithResources,
# # the above feedback attribute will likely be used much less than
# # the following new content attribute, but remains in case needed.
# self.content = ""
#
# # Properties
# buttonCaption = lateTranslate('buttonCaption')
#
# def upgradeToVersion1(self):
# """
# Upgrades to version 0.14
# """
# self.buttonCaption = self.__dict__['buttonCaption']
#
# def upgradeToVersion2(self):
# """
# Upgrades to somewhere before version 0.25 (post-v0.24)
# to reflect that FeedbackField now inherits from FieldWithResources,
# and will need its corresponding fields populated from content.
# [see also the related (and likely redundant) upgrades to FeedbackField
# in: idevicestore.py's __upgradeGeneric() for readingActivity,
# and: genericidevice.py's upgradeToVersion9() for the same]
# """
# self.content = self.feedback
# self.content_w_resourcePaths = self.feedback
# self.content_wo_resourcePaths = self.feedback
# # NOTE: we don't need to actually process any of those contents for
# # image paths, either, since this is an upgrade from pre-images!
. Output only the next line. | readingAct.addField(TextAreaField(_(u"What to read"), |
Given snippet: <|code_start|> self.__upgradeGeneric()
else:
self.__createGeneric()
# generate new ids for these iDevices, to avoid any clashes
for idevice in self.generic:
idevice.id = self.getNewIdeviceId()
def __upgradeGeneric(self):
"""
Upgrades/removes obsolete generic idevices from before
"""
# We may have two reading activites,
# one problably has the wrong title,
# the other is redundant
readingActivitiesFound = 0
for idevice in self.generic:
if idevice.class_ == 'reading':
if readingActivitiesFound == 0:
# Rename the first one we find
idevice.title = x_(u"Reading Activity")
# and also upgrade its feedback field from using a simple
# string, to a subclass of TextAreaField.
# While this will have been initially handled by the
# field itself, and if not, then by the genericidevice's
# upgrade path, this is included here as a possibly
# painfully redundant safety check due to the extra
# special handing of generic idevices w/ generic.dat
for field in idevice.fields:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from exe.engine import persist
from exe.engine.idevice import Idevice
from exe.engine.field import TextAreaField, FeedbackField
from nevow.flat import flatten
from exe.engine.freetextidevice import FreeTextIdevice
from exe.engine.multimediaidevice import MultimediaIdevice
from exe.engine.reflectionidevice import ReflectionIdevice
from exe.engine.casestudyidevice import CasestudyIdevice
from exe.engine.truefalseidevice import TrueFalseIdevice
from exe.engine.wikipediaidevice import WikipediaIdevice
from exe.engine.attachmentidevice import AttachmentIdevice
from exe.engine.titleidevice import TitleIdevice
from exe.engine.galleryidevice import GalleryIdevice
from exe.engine.clozeidevice import ClozeIdevice
from exe.engine.flashwithtextidevice import FlashWithTextIdevice
from exe.engine.externalurlidevice import ExternalUrlIdevice
from exe.engine.imagemagnifieridevice import ImageMagnifierIdevice
from exe.engine.multichoiceidevice import MultichoiceIdevice
from exe.engine.rssidevice import RssIdevice
from exe.engine.multiselectidevice import MultiSelectIdevice
from exe.engine.appletidevice import AppletIdevice
from exe.engine.flashmovieidevice import FlashMovieIdevice
from exe.engine.quiztestidevice import QuizTestIdevice
from exe.engine.genericidevice import GenericIdevice
from exe.engine.genericidevice import GenericIdevice
import imp
import sys
import logging
and context:
# Path: exe/engine/field.py
# class TextAreaField(FieldWithResources):
# """
# A Generic iDevice is built up of these fields. Each field can be
# rendered as an XHTML element
#
# Note that TextAreaFields can now hold any number of image resources,
# which will typically be inserted by way of tinyMCE.
# """
# persistenceVersion = 1
#
# # these will be recreated in FieldWithResources' TwistedRePersist:
# nonpersistant = ['content', 'content_wo_resourcePaths']
#
# def __init__(self, name, instruc="", content=""):
# """
# Initialize
# """
# FieldWithResources.__init__(self, name, instruc, content)
#
# def upgradeToVersion1(self):
# """
# Upgrades to somewhere before version 0.25 (post-v0.24)
# to reflect that TextAreaField now inherits from FieldWithResources,
# and will need its corresponding fields populated from content.
# """
# self.content_w_resourcePaths = self.content
# self.content_wo_resourcePaths = self.content
# # NOTE: we don't need to actually process any of those contents for
# # image paths, either, since this is an upgrade from pre-images!
#
# class FeedbackField(FieldWithResources):
# """
# A Generic iDevice is built up of these fields. Each field can be
# rendered as an XHTML element
# """
#
# persistenceVersion = 2
#
# # these will be recreated in FieldWithResources' TwistedRePersist:
# nonpersistant = ['content', 'content_wo_resourcePaths']
#
# def __init__(self, name, instruc=""):
# """
# Initialize
# """
# FieldWithResources.__init__(self, name, instruc)
#
# self._buttonCaption = x_(u"Click Here")
#
# self.feedback = ""
# # Note: now that FeedbackField extends from FieldWithResources,
# # the above feedback attribute will likely be used much less than
# # the following new content attribute, but remains in case needed.
# self.content = ""
#
# # Properties
# buttonCaption = lateTranslate('buttonCaption')
#
# def upgradeToVersion1(self):
# """
# Upgrades to version 0.14
# """
# self.buttonCaption = self.__dict__['buttonCaption']
#
# def upgradeToVersion2(self):
# """
# Upgrades to somewhere before version 0.25 (post-v0.24)
# to reflect that FeedbackField now inherits from FieldWithResources,
# and will need its corresponding fields populated from content.
# [see also the related (and likely redundant) upgrades to FeedbackField
# in: idevicestore.py's __upgradeGeneric() for readingActivity,
# and: genericidevice.py's upgradeToVersion9() for the same]
# """
# self.content = self.feedback
# self.content_w_resourcePaths = self.feedback
# self.content_wo_resourcePaths = self.feedback
# # NOTE: we don't need to actually process any of those contents for
# # image paths, either, since this is an upgrade from pre-images!
which might include code, classes, or functions. Output only the next line. | if isinstance(field, FeedbackField): |
Using the snippet: <|code_start|># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# ===========================================================================
"""
An RSS Idevice is one built from a RSS feed.
"""
# ===========================================================================
class RssIdevice(Idevice):
"""
An RSS Idevice is one built from a RSS feed.
"""
def __init__(self):
Idevice.__init__(self,
x_(u"RSS"),
x_(u"Auckland University of Technology"),
x_(u"""The RSS iDevice is used
to provide new content to an individual users machine. Using this
iDevice you can provide links from a feed you select for learners to view."""),
u"",
u"")
self.emphasis = Idevice.NoEmphasis
<|code_end|>
, determine the next line of code. You have imports:
import re
from exe.engine import feedparser
from exe.engine.idevice import Idevice
from exe.engine.field import TextAreaField
from exe.engine.translate import lateTranslate
and context (class names, function names, or code) available:
# Path: exe/engine/field.py
# class TextAreaField(FieldWithResources):
# """
# A Generic iDevice is built up of these fields. Each field can be
# rendered as an XHTML element
#
# Note that TextAreaFields can now hold any number of image resources,
# which will typically be inserted by way of tinyMCE.
# """
# persistenceVersion = 1
#
# # these will be recreated in FieldWithResources' TwistedRePersist:
# nonpersistant = ['content', 'content_wo_resourcePaths']
#
# def __init__(self, name, instruc="", content=""):
# """
# Initialize
# """
# FieldWithResources.__init__(self, name, instruc, content)
#
# def upgradeToVersion1(self):
# """
# Upgrades to somewhere before version 0.25 (post-v0.24)
# to reflect that TextAreaField now inherits from FieldWithResources,
# and will need its corresponding fields populated from content.
# """
# self.content_w_resourcePaths = self.content
# self.content_wo_resourcePaths = self.content
# # NOTE: we don't need to actually process any of those contents for
# # image paths, either, since this is an upgrade from pre-images!
. Output only the next line. | self.rss = TextAreaField(x_(u"RSS")) |
Given the following code snippet before the placeholder: <|code_start|> Initialize
"""
RenderableResource.__init__(self, parent)
self.localeNames = []
for locale, translation in self.config.locales.items():
localeName = locale + ": "
langName = translation.info().get('x-exe-language', None)
if langName == None:
langName = translation.info().get('x-poedit-language', 'English')
localeName += langName
self.localeNames.append((localeName, locale))
self.localeNames.sort()
def getChild(self, name, request):
"""
Try and find the child for the name given
"""
if name == "":
return self
else:
return Resource.getChild(self, name, request)
def render_GET(self, request):
"""Render the preferences"""
log.debug("render_GET")
# Rendering
<|code_end|>
, predict the next line using imports from the current file:
import logging
from twisted.web.resource import Resource
from exe.webui import common
from exe.webui.renderable import RenderableResource
and context including class names, function names, and sometimes code from other files:
# Path: exe/webui/common.py
# def newId():
# def docType():
# def header(style=u'default'):
# def footer():
# def hiddenField(name, value=u""):
# def textInput(name, value=u"", size=40, disabled=u"", **kwargs):
# def textArea(name, value="", disabled="", cols="80", rows="8"):
# def richTextArea(name, value="", width="100%", height=100, package=None):
# def image(name, value, width="", height="", alt=None):
# def flash(src, width, height, id_=None, params=None, **kwparams):
# def flashMovie(movie, width, height, resourcesDir='', autoplay='false'):
# def submitButton(name, value, enabled=True, **kwargs):
# def button(name, value, enabled=True, **kwargs):
# def feedbackButton(name, value=None, enabled=True, **kwparams):
# def submitImage(action, object_, imageFile, title=u"", isChanged=1):
# def insertSymbol(name, image, title, string, text ='', num=0):
# def confirmThenSubmitImage(message, action, object_, imageFile,
# title=u"", isChanged=1):
# def option(name, checked, value):
# def checkbox(name, checked, value="", title="", instruction=""):
# def elementInstruc(instruc, imageFile="help.gif", label=None):
# def formField(type_, package, caption, action, object_='', instruction='', \
# *args, **kwargs):
# def select(action, object_='', options=[], selection=None):
# def editModeHeading(text):
# def removeInternalLinks(html, anchor_name=""):
# def removeInternalLinkNodes(html):
# def findLinkedField(package, exe_node_path, anchor_name):
# def findLinkedNode(package, exe_node_path, anchor_name, check_fields=True):
# def getAnchorNameFromLinkName(link_name):
# def renderInternalLinkNodeFilenames(package, html):
# def requestHasCancel(request):
. Output only the next line. | html = common.docType() |
Predict the next line after this snippet: <|code_start|># but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# ===========================================================================
"""
A QuizTest Idevice is one built up from TestQuestions
"""
log = logging.getLogger(__name__)
# ===========================================================================
class AnswerOption(Persistable):
"""
A TestQuestion is built up of question and AnswerOptions. Each
answerOption can be rendered as an XHTML element
"""
def __init__(self, question, idevice, answer="", isCorrect=False):
"""
Initialize
"""
self.question = question
self.idevice = idevice
<|code_end|>
using the current file's imports:
import logging
import re
from exe.engine.persist import Persistable
from exe.engine.idevice import Idevice
from exe.engine.translate import lateTranslate
from exe.engine.field import TextAreaField
and any relevant context from other files:
# Path: exe/engine/field.py
# class TextAreaField(FieldWithResources):
# """
# A Generic iDevice is built up of these fields. Each field can be
# rendered as an XHTML element
#
# Note that TextAreaFields can now hold any number of image resources,
# which will typically be inserted by way of tinyMCE.
# """
# persistenceVersion = 1
#
# # these will be recreated in FieldWithResources' TwistedRePersist:
# nonpersistant = ['content', 'content_wo_resourcePaths']
#
# def __init__(self, name, instruc="", content=""):
# """
# Initialize
# """
# FieldWithResources.__init__(self, name, instruc, content)
#
# def upgradeToVersion1(self):
# """
# Upgrades to somewhere before version 0.25 (post-v0.24)
# to reflect that TextAreaField now inherits from FieldWithResources,
# and will need its corresponding fields populated from content.
# """
# self.content_w_resourcePaths = self.content
# self.content_wo_resourcePaths = self.content
# # NOTE: we don't need to actually process any of those contents for
# # image paths, either, since this is an upgrade from pre-images!
. Output only the next line. | self.answerTextArea = TextAreaField(x_(u'Option'), |
Next line prediction: <|code_start|> html += self.renderEdit(style)
elif self.mode == Block.View:
html += self.renderView(style)
elif self.mode == Block.Preview:
if self.idevice.lastIdevice:
html += u'<a name="currentBlock"></a>\n'
html += self.renderPreview(style)
except Exception, e:
log.error('%s:\n%s' % (str(e), '\n'.join(format_tb(sys.exc_traceback))))
html += broken % str(e)
if self.mode == Block.Edit:
html += self.renderEditButtons()
if self.mode == Block.Preview:
html += self.renderViewButtons()
return html
def renderEdit(self, style):
"""
Returns an XHTML string with the form element for editing this block
"""
log.error(u"renderEdit called directly")
return u"ERROR Block.renderEdit called directly"
def renderEditButtons(self, undo=True):
"""
Returns an XHTML string for the edit buttons
"""
<|code_end|>
. Use current file imports:
(import sys
import logging
from exe.webui import common
from exe.webui.renderable import Renderable
from exe.engine.idevice import Idevice
from traceback import format_tb)
and context including class names, function names, or small code snippets from other files:
# Path: exe/webui/common.py
# def newId():
# def docType():
# def header(style=u'default'):
# def footer():
# def hiddenField(name, value=u""):
# def textInput(name, value=u"", size=40, disabled=u"", **kwargs):
# def textArea(name, value="", disabled="", cols="80", rows="8"):
# def richTextArea(name, value="", width="100%", height=100, package=None):
# def image(name, value, width="", height="", alt=None):
# def flash(src, width, height, id_=None, params=None, **kwparams):
# def flashMovie(movie, width, height, resourcesDir='', autoplay='false'):
# def submitButton(name, value, enabled=True, **kwargs):
# def button(name, value, enabled=True, **kwargs):
# def feedbackButton(name, value=None, enabled=True, **kwparams):
# def submitImage(action, object_, imageFile, title=u"", isChanged=1):
# def insertSymbol(name, image, title, string, text ='', num=0):
# def confirmThenSubmitImage(message, action, object_, imageFile,
# title=u"", isChanged=1):
# def option(name, checked, value):
# def checkbox(name, checked, value="", title="", instruction=""):
# def elementInstruc(instruc, imageFile="help.gif", label=None):
# def formField(type_, package, caption, action, object_='', instruction='', \
# *args, **kwargs):
# def select(action, object_='', options=[], selection=None):
# def editModeHeading(text):
# def removeInternalLinks(html, anchor_name=""):
# def removeInternalLinkNodes(html):
# def findLinkedField(package, exe_node_path, anchor_name):
# def findLinkedNode(package, exe_node_path, anchor_name, check_fields=True):
# def getAnchorNameFromLinkName(link_name):
# def renderInternalLinkNodeFilenames(package, html):
# def requestHasCancel(request):
. Output only the next line. | html = common.submitImage(u"done", self.id, |
Given the following code snippet before the placeholder: <|code_start|>'''
Created on Apr 4, 2014
@author: tangliuxiang
'''
MAX_CHECK_INVOKE_DEEP = 50
class SAutoCom(object):
'''
classdocs
'''
@staticmethod
def autocom(vendorDir, aospDir, bospDir, mergedDir, outdir, comModuleList):
sReplace = Replace.Replace(vendorDir, aospDir, bospDir, mergedDir)
for module in comModuleList:
<|code_end|>
, predict the next line using imports from the current file:
import utils
import Replace
from formatters.log import Paint
and context including class names, function names, and sometimes code from other files:
# Path: formatters/log.py
# class Paint:
#
# @staticmethod
# def bold(s):
# return "%s[01m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def red(s):
# return "%s[33;31m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def green(s):
# return "%s[31;32m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def blue(s):
# return "%s[34;01m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def yellow(s):
# return "%s[31;33m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
. Output only the next line. | print Paint.bold(" Complete missed method in %s") % module |
Predict the next line after this snippet: <|code_start|>
# Increment total conflicts
Error.TOTAL_CONFLICTS += conflictNum;
Error.CONFLICT_FILE_NUM += 1
# Increment conflicts of each part
key = Error.getStatisticKey(target)
if not Error.CONFLICT_STATISTIC.has_key(key):
Error.CONFLICT_STATISTIC[key] = 0
Error.CONFLICT_STATISTIC[key] += conflictNum
@staticmethod
def getStatisticKey(target):
relpath = os.path.relpath(target, Config.PRJ_ROOT)
key = relpath[0:relpath.find("/")]
return key
@staticmethod
def fail(message):
Error.FAILED_LIST.append(message)
@staticmethod
def showStatistic():
for key in Error.FILENOTFOUND_STATISTIC.keys():
print "%3d files not found in %s" % (Error.FILENOTFOUND_STATISTIC[key], key)
if Error.TOTAL_FILENOTFOUND > 0:
<|code_end|>
using the current file's imports:
import os
from config import Config
from formatters.log import Paint
and any relevant context from other files:
# Path: formatters/log.py
# class Paint:
#
# @staticmethod
# def bold(s):
# return "%s[01m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def red(s):
# return "%s[33;31m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def green(s):
# return "%s[31;32m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def blue(s):
# return "%s[34;01m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def yellow(s):
# return "%s[31;33m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
. Output only the next line. | print Paint.bold("%3d files not found totally, they might be removed or moved to other place by vendor?" % Error.TOTAL_FILENOTFOUND) |
Here is a snippet: <|code_start|> return True
else:
print Paint.red("<<< phase %s failed" % action)
return False
# End of CoronStateMachine
class Shell:
""" Subprocess to run shell command
"""
@staticmethod
def run(cmd):
""" Run command in shell.
Set `isMakeCommand` to True if command is a `make` command
"""
subp = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = None
while True:
buff = subp.stdout.readline().strip('\n')
print buff
if buff == '' and subp.poll() != None:
break
output = buff
<|code_end|>
. Write the next line using the current file imports:
import os
import subprocess
import shutil
import re
import xml.etree.cElementTree as ET
import xml.etree.ElementTree as ET
from help import HelpPresenter
from formatters.log import Log, Paint
and context from other files:
# Path: formatters/log.py
# class Log:
#
# DEBUG = False
#
# @staticmethod
# def d(tag, message):
# if Log.DEBUG: print "D/%s: %s" %(tag, message)
#
# @staticmethod
# def i(tag, message):
# print "I/%s: %s" %(tag, message)
#
# @staticmethod
# def w(tag, message):
# print "W/%s: %s" %(tag, message)
#
# @staticmethod
# def e(tag, message):
# print "E/%s: %s" %(tag, message)
#
# class Paint:
#
# @staticmethod
# def bold(s):
# return "%s[01m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def red(s):
# return "%s[33;31m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def green(s):
# return "%s[31;32m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def blue(s):
# return "%s[34;01m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def yellow(s):
# return "%s[31;33m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
, which may include functions, classes, or code. Output only the next line. | Log.d(TAG, "Shell.run() %s return %s" %(cmd, subp.returncode)) |
Given snippet: <|code_start|>
def doAction(self, action):
""" Return True: do action succeed. Otherwise return false
"""
raise Exception("Should be implemented by subclass")
# End of class StateMachine
class CoronStateMachine(StateMachine):
""" Coron State Machine
"""
XML = os.path.join(os.curdir, "workflow.xml")
def __init__(self):
self.createXMLIfNotExist()
StateMachine.__init__(self, Workflow(CoronStateMachine.XML))
def createXMLIfNotExist(self):
if os.path.exists(CoronStateMachine.XML): return
source = os.path.join(os.path.dirname(os.path.realpath(__file__)), "workflow.xml")
shutil.copy(source, CoronStateMachine.XML)
def doAction(self, action):
print "\n"
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import subprocess
import shutil
import re
import xml.etree.cElementTree as ET
import xml.etree.ElementTree as ET
from help import HelpPresenter
from formatters.log import Log, Paint
and context:
# Path: formatters/log.py
# class Log:
#
# DEBUG = False
#
# @staticmethod
# def d(tag, message):
# if Log.DEBUG: print "D/%s: %s" %(tag, message)
#
# @staticmethod
# def i(tag, message):
# print "I/%s: %s" %(tag, message)
#
# @staticmethod
# def w(tag, message):
# print "W/%s: %s" %(tag, message)
#
# @staticmethod
# def e(tag, message):
# print "E/%s: %s" %(tag, message)
#
# class Paint:
#
# @staticmethod
# def bold(s):
# return "%s[01m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def red(s):
# return "%s[33;31m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def green(s):
# return "%s[31;32m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def blue(s):
# return "%s[34;01m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def yellow(s):
# return "%s[31;33m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
which might include code, classes, or functions. Output only the next line. | print Paint.blue(">>> In phase %s" % action) |
Using the snippet: <|code_start|>class pull(object):
'''
classdocs
'''
mPull = None
PROC_PARTITIONS = "/proc/partitions"
BLOCK_DIR = "/dev/block"
MIN_SIZE = 4096
MAX_SIZE = 20480
def __init__(self):
'''
Constructor
'''
self.mWorkdir = tempfile.mkdtemp()
self.mImgDict = {}
self.mOutDir = os.getcwd()
@staticmethod
def getInstance():
if pull.mPull is None:
pull.mPull = pull()
return pull.mPull
def getAdPartitions(self, minsize, maxsize):
adPt = AndroidFile(pull.PROC_PARTITIONS)
assert adPt.exist(), "File %s is not exist in phone!" %(pull.PROC_PARTITIONS)
outAdDict = {}
<|code_end|>
, determine the next line of code. You have imports:
from command import AndroidFile
from formatters.log import Log
import tempfile
import os
import imagetype
import shutil
import string
import sys
and context (class names, function names, or code) available:
# Path: formatters/log.py
# class Log:
#
# DEBUG = False
#
# @staticmethod
# def d(tag, message):
# if Log.DEBUG: print "D/%s: %s" %(tag, message)
#
# @staticmethod
# def i(tag, message):
# print "I/%s: %s" %(tag, message)
#
# @staticmethod
# def w(tag, message):
# print "W/%s: %s" %(tag, message)
#
# @staticmethod
# def e(tag, message):
# print "E/%s: %s" %(tag, message)
. Output only the next line. | Log.i(LOG_TAG, "Try to create block of partitions ...") |
Given the code snippet: <|code_start|>KEY_STATIC = "static"
KEY_FINAL = "final"
KEY_SYNTHETIC = "synthetic"
# only use in methods
KEY_ABSTRACT = "abstract"
KEY_CONSTRUCTOR = "constructor"
KEY_BRIDGE = "bridge"
KEY_DECLARED_SYNCHRONIZED = "declared-synchronized"
KEY_NATIVE = "native"
KEY_SYNCHRONIZED = "synchronized"
KEY_VARARGS = "varargs"
# only use in field
KEY_ENUM = "enum"
KEY_TRANSIENT = "transient"
KEY_VOLATILE = "volatile"
KEY_INTERFACE = "interface"
class SLog():
TAG = "smali-parser"
DEBUG = False
FAILED_LIST = []
SUCCESS_LIST = []
ADVICE = ""
SUCCESS = ""
@staticmethod
def e(s):
<|code_end|>
, generate the next line using the imports in this file:
import os, sys
import re
import Smali
import SmaliEntry
import time
import getpass
from formatters.log import Log, Paint
and context (functions, classes, or occasionally code) from other files:
# Path: formatters/log.py
# class Log:
#
# DEBUG = False
#
# @staticmethod
# def d(tag, message):
# if Log.DEBUG: print "D/%s: %s" %(tag, message)
#
# @staticmethod
# def i(tag, message):
# print "I/%s: %s" %(tag, message)
#
# @staticmethod
# def w(tag, message):
# print "W/%s: %s" %(tag, message)
#
# @staticmethod
# def e(tag, message):
# print "E/%s: %s" %(tag, message)
#
# class Paint:
#
# @staticmethod
# def bold(s):
# return "%s[01m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def red(s):
# return "%s[33;31m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def green(s):
# return "%s[31;32m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def blue(s):
# return "%s[34;01m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def yellow(s):
# return "%s[31;33m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
. Output only the next line. | Log.e(SLog.TAG, s) |
Using the snippet: <|code_start|> SUCCESS_LIST = []
ADVICE = ""
SUCCESS = ""
@staticmethod
def e(s):
Log.e(SLog.TAG, s)
@staticmethod
def w(s):
Log.w(SLog.TAG, s)
@staticmethod
def d(s):
if SLog.DEBUG:
Log.i(SLog.TAG, s)
else:
Log.d(SLog.TAG, s)
@staticmethod
def i(s):
Log.i(SLog.TAG, s)
@staticmethod
def fail(s):
SLog.FAILED_LIST.append(s)
@staticmethod
def ok(s):
SLog.SUCCESS_LIST.append(s)
#Log.i(SLog.TAG, s)
@staticmethod
def conclude():
<|code_end|>
, determine the next line of code. You have imports:
import os, sys
import re
import Smali
import SmaliEntry
import time
import getpass
from formatters.log import Log, Paint
and context (class names, function names, or code) available:
# Path: formatters/log.py
# class Log:
#
# DEBUG = False
#
# @staticmethod
# def d(tag, message):
# if Log.DEBUG: print "D/%s: %s" %(tag, message)
#
# @staticmethod
# def i(tag, message):
# print "I/%s: %s" %(tag, message)
#
# @staticmethod
# def w(tag, message):
# print "W/%s: %s" %(tag, message)
#
# @staticmethod
# def e(tag, message):
# print "E/%s: %s" %(tag, message)
#
# class Paint:
#
# @staticmethod
# def bold(s):
# return "%s[01m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def red(s):
# return "%s[33;31m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def green(s):
# return "%s[31;32m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def blue(s):
# return "%s[34;01m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def yellow(s):
# return "%s[31;33m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
. Output only the next line. | print Paint.red(" ____________________________________________________________________________________") |
Given the code snippet: <|code_start|> def __exit(self):
hasReject = self.hasReject(self.rejSmali.toString())
if hasReject:
self.rejSmali.out()
if hasReject:
self.rejSmali = Smali.Smali(self.rejSmali.getPath())
self.rejSmali.out(self.getOutRejectFilePath())
def getOutRejectFilePath(self):
start = len(os.path.abspath(utils.REJECT))
rejPath = self.rejSmali.getPath()
return "%s/%s" % (utils.OUT_REJECT, rejPath[start:])
def getRealTargetPath(self, tSmali):
return "%s/smali/%s" % (utils.getJarNameFromPath(tSmali.getPath()), utils.getBaseSmaliPath(tSmali.getPath()))
def replaceEntryToBosp(self, entry):
if (entry.getFlag() & reject.FLAG_REPLACED_TO_BAIDU) == 0:
self.mTSLib.replaceEntry(self.mBSLib, entry)
if self.mRejSLib.getSmali(entry.getClassName()) is not None:
self.rejSmali = self.mRejSLib.replaceEntry(self.mBSLib, entry, False, False, True)
rejEntry = self.getRejectEntry(entry)
if rejEntry is not None:
rejEntry.setFlag(reject.FLAG_ENTRY_NORMAL)
entry.addFlag(reject.FLAG_REPLACED_TO_BAIDU)
def handleLightFix(self):
target = os.path.relpath(self.rejSmali.getPath(), utils.REJECT)
print " "
<|code_end|>
, generate the next line using the imports in this file:
import Smali
import utils
import re
import sys
import os
import SmaliEntry
import Replace
import SAutoCom
import tempfile
import LibUtils
from formatters.log import Paint
and context (functions, classes, or occasionally code) from other files:
# Path: formatters/log.py
# class Paint:
#
# @staticmethod
# def bold(s):
# return "%s[01m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def red(s):
# return "%s[33;31m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def green(s):
# return "%s[31;32m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def blue(s):
# return "%s[34;01m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def yellow(s):
# return "%s[31;33m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
. Output only the next line. | print " %s %s" % (Paint.bold("FIX CONFLICTS IN"), target) |
Next line prediction: <|code_start|> "framework2.jar",
"mediatek-framework.jar")
PARTITIONS = ("secondary_framework.jar.out", "secondary-framework.jar.out",
"framework-ext.jar.out", "framework_ext.jar.out",
"framework2.jar.out")
class Options(object):
def __init__(self):
self.prepare = True # Whether to trigger prepare action
self.patchXml = Config.PATCHALL_XML # The patch XML, default to be PATCHALL_XML
self.baseName = "base" # Short base device name, default to be 'base'
self.commit1 = None # The 7 bits lower commit ID
self.commit2 = None # The 7 bits upper commit ID
self.olderRoot = None # The older and newer is a pair of directory for comparing
self.newerRoot = None # Default to be AOSP and BOSP
@staticmethod
def usage():
print __doc__
sys.exit()
def handle(self, argv):
if len(argv) == 1: Options.usage()
try:
(opts, args) = getopt.getopt(argv[1:], "hlputb:c1:c2:", \
[ "help", "loosely", "patchall", "upgrade", "porting", "base=", "commit1=", "commit2=" ])
<|code_end|>
. Use current file imports:
(import shutil
import subprocess
import os, sys
import tempfile
import commands
import getopt
from config import Config
from changelist import ChangeList
from formatters.log import Log, Paint)
and context including class names, function names, or small code snippets from other files:
# Path: formatters/log.py
# class Log:
#
# DEBUG = False
#
# @staticmethod
# def d(tag, message):
# if Log.DEBUG: print "D/%s: %s" %(tag, message)
#
# @staticmethod
# def i(tag, message):
# print "I/%s: %s" %(tag, message)
#
# @staticmethod
# def w(tag, message):
# print "W/%s: %s" %(tag, message)
#
# @staticmethod
# def e(tag, message):
# print "E/%s: %s" %(tag, message)
#
# class Paint:
#
# @staticmethod
# def bold(s):
# return "%s[01m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def red(s):
# return "%s[33;31m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def green(s):
# return "%s[31;32m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def blue(s):
# return "%s[34;01m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def yellow(s):
# return "%s[31;33m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
. Output only the next line. | Log.d(TAG, "Program args = %s" %args) |
Given the following code snippet before the placeholder: <|code_start|>
def upgrade(self):
""" Prepare precondition of upgrade
"""
# Remove last_bosp and bosp
Utils.run(["rm", "-rf", OPTIONS.olderRoot], stdout=subprocess.PIPE).communicate()
Utils.run(["rm", "-rf", OPTIONS.newerRoot], stdout=subprocess.PIPE).communicate()
lastBaiduZip = os.path.join(Config.PRJ_ROOT, "baidu/last_baidu.zip")
baiduZip = os.path.join(Config.PRJ_ROOT, "baidu/baidu.zip")
if os.path.exists(lastBaiduZip) and os.path.exists(baiduZip):
# Phase 1: prepare LAST_BOSP from last_baidu.zip
Utils.decode(lastBaiduZip, OPTIONS.olderRoot)
# Phase 2: prepare BOSP from baidu.zip
Utils.decode(baiduZip, OPTIONS.newerRoot)
# Phase 3: prepare patch XML
ChangeList(OPTIONS.olderRoot, OPTIONS.newerRoot, OPTIONS.patchXml).make(force=True)
else:
if OPTIONS.commit1 != None:
self.baseDevice.setLastHead(OPTIONS.commit1)
# Phase 1: get last and origin head from base device
(lastHead, origHead) = self.baseDevice.getLastAndOrigHead()
if lastHead == origHead:
<|code_end|>
, predict the next line using imports from the current file:
import shutil
import subprocess
import os, sys
import tempfile
import commands
import getopt
from config import Config
from changelist import ChangeList
from formatters.log import Log, Paint
and context including class names, function names, and sometimes code from other files:
# Path: formatters/log.py
# class Log:
#
# DEBUG = False
#
# @staticmethod
# def d(tag, message):
# if Log.DEBUG: print "D/%s: %s" %(tag, message)
#
# @staticmethod
# def i(tag, message):
# print "I/%s: %s" %(tag, message)
#
# @staticmethod
# def w(tag, message):
# print "W/%s: %s" %(tag, message)
#
# @staticmethod
# def e(tag, message):
# print "E/%s: %s" %(tag, message)
#
# class Paint:
#
# @staticmethod
# def bold(s):
# return "%s[01m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def red(s):
# return "%s[33;31m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def green(s):
# return "%s[31;32m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def blue(s):
# return "%s[34;01m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def yellow(s):
# return "%s[31;33m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
. Output only the next line. | Log.w(TAG, Paint.red("Nothing to upgrade. Did you forget to sync the %s ?" %OPTIONS.baseName)) |
Predict the next line after this snippet: <|code_start|>"""
__author__ = 'duanqz@gmail.com'
try:
except ImportError:
#from lxml import etree as ET
TAG="changelist"
class ChangeList:
def __init__(self, olderRoot, newerRoot, patchXML):
ChangeList.OLDER_ROOT = olderRoot
ChangeList.NEWER_ROOT = newerRoot
ChangeList.PATCH_XML = patchXML
def make(self, force=True):
""" Generate the change list into XML.
Set force as False not to generate again if exists.
"""
if not force and os.path.exists(ChangeList.PATCH_XML):
<|code_end|>
using the current file's imports:
import shutil
import os, sys
import subprocess
import tempfile
import xml.dom.minidom
import xml.etree.cElementTree as ET
import xml.etree.ElementTree as ET
from config import Config
from formatters.log import Log
and any relevant context from other files:
# Path: formatters/log.py
# class Log:
#
# DEBUG = False
#
# @staticmethod
# def d(tag, message):
# if Log.DEBUG: print "D/%s: %s" %(tag, message)
#
# @staticmethod
# def i(tag, message):
# print "I/%s: %s" %(tag, message)
#
# @staticmethod
# def w(tag, message):
# print "W/%s: %s" %(tag, message)
#
# @staticmethod
# def e(tag, message):
# print "E/%s: %s" %(tag, message)
. Output only the next line. | Log.d(TAG, "Using the existing %s" % ChangeList.PATCH_XML) |
Predict the next line after this snippet: <|code_start|> if not os.path.isfile(linesPatch):
return
# Patch the lines to no line file
cmd = "patch -f %s -r /dev/null < %s > /dev/null" % \
(commands.mkarg(smaliFile), commands.mkarg(linesPatch))
commands.getstatusoutput(cmd)
os.remove(linesPatch)
origFile = smaliFile + ".orig"
if os.path.exists(origFile): os.remove(origFile)
return smaliFile
@staticmethod
def log(message):
if Format.DEBUG: print message
@staticmethod
def __doJob__(f, job, action):
if job == Format.DO:
f.do(action)
elif job == Format.UNDO_DO:
f.undo()
else:
Format.log("Error Action %s" % action)
@staticmethod
def format(job, libPath, smaliFileList = None, action = ALL_ACTION):
if smaliFileList is None:
<|code_end|>
using the current file's imports:
import commands
import shutil
import os, sys
import getopt
from name2num import NameToNumForOneFile
from num2name import NumToNameForOneFile
from idtoname import idtoname
from nametoid import nametoid
from smaliparser import utils
from smaliparser import SmaliLib
from smaliparser import Smali
and any relevant context from other files:
# Path: smaliparser/utils.py
# KEY_PUBLIC = "public"
# KEY_PRIVATE = "private"
# KEY_PROTECTED = "protected"
# KEY_STATIC = "static"
# KEY_FINAL = "final"
# KEY_SYNTHETIC = "synthetic"
# KEY_ABSTRACT = "abstract"
# KEY_CONSTRUCTOR = "constructor"
# KEY_BRIDGE = "bridge"
# KEY_DECLARED_SYNCHRONIZED = "declared-synchronized"
# KEY_NATIVE = "native"
# KEY_SYNCHRONIZED = "synchronized"
# KEY_VARARGS = "varargs"
# KEY_ENUM = "enum"
# KEY_TRANSIENT = "transient"
# KEY_VOLATILE = "volatile"
# KEY_INTERFACE = "interface"
# TAG = "smali-parser"
# DEBUG = False
# FAILED_LIST = []
# SUCCESS_LIST = []
# ADVICE = ""
# SUCCESS = ""
# PRJ_ROOT = os.getcwd()
# REJECT = '%s/autopatch/reject' %(PRJ_ROOT)
# BOSP = '%s/autopatch/bosp' %(PRJ_ROOT)
# AOSP = '%s/autopatch/aosp' %(PRJ_ROOT)
# TARGET = "%s/out/obj/autofix/target" %(PRJ_ROOT)
# OUT_REJECT = '%s/autopatch/still-reject' %(PRJ_ROOT)
# SMALI_POST_SUFFIX = r'\.smali'
# PART_SMALI_POST_SUFFIX = r'\.smali\.part'
# SMALI_POST_SUFFIX_LEN = 6
# CUR_ACTION = None
# ATTENTION = None
# ENABLE = True
# class SLog():
# class precheck():
# class annotation():
# def e(s):
# def w(s):
# def d(s):
# def i(s):
# def fail(s):
# def ok(s):
# def conclude():
# def setAdviceStr(str):
# def setSuccessStr(str):
# def has(list, item):
# def isSmaliFile(smaliPath):
# def isPartSmaliFile(smaliPath):
# def getSmaliPathList(source, smaliDirMaxDepth = 0):
# def getPackageFromClass(className):
# def getSmaliDict(smaliDir, smaliDirMaxDepth = 0):
# def getJarNameFromPath(smaliPath):
# def getBaseSmaliPath(smaliPath):
# def getClassBaseNameFromPath(smaliPath):
# def getClassFromPath(smaliPath):
# def getReturnType(methodName):
# def getMatchFile(smaliFile, targetDir = BOSP):
# def getSimpleMethodName(methodName):
# def getInstance():
# def setInstance(nInstance):
# def canAddField(field):
# def shouldIgnore(smali):
# def precheck(self, tSmali, bSmali, entry):
# def preCheck(tSmali, bSmali, entry):
# def disable():
# def enable():
# def setAction(action):
# def setAttention(attention):
# def getAppendStr():
# def getReplaceToBospPreContent(entry):
# def getAddToBospPreContent(entry):
. Output only the next line. | smaliFileList = utils.getSmaliPathList(libPath) |
Predict the next line for this snippet: <|code_start|>class SmaliSplitter:
""" Independent splitter of SMALI file
"""
def split(self, origSmali, output=None):
""" Split the original SMALI file into partitions
"""
if output == None: output = os.path.dirname(origSmali)
self.mOrigSmali = origSmali
self.mOutput = output
self.mPartList = Smali(origSmali).split(self.mOutput)
return self
def match(self, part):
basename = os.path.basename(part)
return os.path.join(self.mOutput, basename)
def getAllParts(self):
return self.mPartList
def appendPart(self, part):
""" Append a part to list if not exist
"""
try:
self.mPartList.index(part)
except:
<|code_end|>
with the help of current file imports:
import os
import commands
import shutil
import fnmatch
import tempfile
from config import Config
from smaliparser.Smali import Smali
from formatters.log import Log
and context from other files:
# Path: formatters/log.py
# class Log:
#
# DEBUG = False
#
# @staticmethod
# def d(tag, message):
# if Log.DEBUG: print "D/%s: %s" %(tag, message)
#
# @staticmethod
# def i(tag, message):
# print "I/%s: %s" %(tag, message)
#
# @staticmethod
# def w(tag, message):
# print "W/%s: %s" %(tag, message)
#
# @staticmethod
# def e(tag, message):
# print "E/%s: %s" %(tag, message)
, which may contain function names, class names, or code. Output only the next line. | Log.d(TAG, " [Add new part %s ] " % part) |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/python
'''
Coron
'''
__author__ = "duanqz@gmail.com"
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
def coronUsage():
helpEntry = HelpFactory.createHelp()
<|code_end|>
using the current file's imports:
import os, sys
from workflow import CoronStateMachine
from help import HelpFactory, HelpPresenter
from formatters.log import Paint
and any relevant context from other files:
# Path: formatters/log.py
# class Paint:
#
# @staticmethod
# def bold(s):
# return "%s[01m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def red(s):
# return "%s[33;31m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def green(s):
# return "%s[31;32m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def blue(s):
# return "%s[34;01m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def yellow(s):
# return "%s[31;33m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
. Output only the next line. | print Paint.bold("Coron - an open source project for Android ROM porting.") |
Predict the next line after this snippet: <|code_start|> name = key
code = self.NAME_TO_CODE.get(name)
tag = self.ITEM_TAGS.get(code)
if tag == None:
return None
item = Item(code, name)
for child in tag.getchildren():
if child.tag == "solution":
item.solution = child.text
elif child.tag == "detail":
item.detail = child.text
return item
@staticmethod
def show(item, attrib=None):
""" Show the help item.
"""
if item == None:
return
if attrib == "solution":
if item.solution != None: print item.solution.replace("\t", "")
elif attrib == "detail":
if item.detail != None: print item.detail.replace("\t", "")
else:
<|code_end|>
using the current file's imports:
import os, sys
import types
import xml.etree.cElementTree as ET
import xml.etree.ElementTree as ET
from formatters.log import Paint
and any relevant context from other files:
# Path: formatters/log.py
# class Paint:
#
# @staticmethod
# def bold(s):
# return "%s[01m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def red(s):
# return "%s[33;31m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def green(s):
# return "%s[31;32m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def blue(s):
# return "%s[34;01m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
#
# @staticmethod
# def yellow(s):
# return "%s[31;33m%s%s[0m" % (chr(27), s.rstrip(), chr(27))
. Output only the next line. | print Paint.bold("%s\t%s\n" % (item.code, item.name)) |
Here is a snippet: <|code_start|>
DEFAULT_TIMEOUT = 30
DEFAULT_SHARE = 'data'
class IfcbConnectionError(Exception):
pass
def do_nothing(*args, **kw):
pass
class RemoteIfcb(object):
def __init__(self, addr, username, password, netbios_name=None, timeout=DEFAULT_TIMEOUT,
share=DEFAULT_SHARE, directory='', connect=True):
self.addr = addr
self.username = username
self.password = password
self.timeout = timeout
self.share = share
self.connect = connect
self.netbios_name = netbios_name
self.directory = directory
self._c = None
def open(self):
if self._c is not None:
return
try:
<|code_end|>
. Write the next line using the current file imports:
import os
from collections import defaultdict
from .smb_utils import smb_connect, get_netbios_name, NameError
from smb.base import SharedDevice
and context from other files:
# Path: ifcb/data/transfer/smb_utils.py
# def smb_connect(remote_server, username, password, netbios_name=None, timeout=DEFAULT_TIMEOUT):
#
# if netbios_name is None:
# logging.debug('Querying NetBIOS for name of {}'.format(remote_server))
# netbios_name = get_netbios_name(remote_server, timeout=timeout)
# logging.debug('Name is {}'.format(netbios_name))
#
# logging.debug('Connecting to {}'.format(remote_server))
#
# c = SMBConnection(username, password, 'ignore', netbios_name)
# c.connect(remote_server, timeout=timeout)
#
# return c
#
# def get_netbios_name(remote_addr, timeout=DEFAULT_TIMEOUT):
# nb = NetBIOS()
# names = nb.queryIPForName(remote_addr, timeout=timeout)
# nb.close()
# if names is None or len(names) == 0:
# raise NameError('No NetBIOS name found for {}'.format(remote_addr))
# elif len(names) > 1:
# logging.warn('More than one NetBIOS name for {}'.format(remote_addr))
# return names[0]
#
# class NameError(Exception):
# pass
, which may include functions, classes, or code. Output only the next line. | self._c = smb_connect(self.addr, self.username, self.password, self.netbios_name, self.timeout) |
Given the code snippet: <|code_start|> self.directory = directory
self._c = None
def open(self):
if self._c is not None:
return
try:
self._c = smb_connect(self.addr, self.username, self.password, self.netbios_name, self.timeout)
except:
raise IfcbConnectionError('unable to connect to IFCB')
def close(self):
if self._c is not None:
self._c.close()
self._c = None
def __enter__(self):
if self.connect:
self.open()
return self
def __exit__(self, type, value, traceback):
self.close()
def ensure_connected(self):
if self._c is None:
raise IfcbConnectionError('IFCB is not connected')
def is_responding(self):
# tries to get NetBIOS name to see if IFCB is responding
if self.netbios_name is not None:
return True # FIXME determine connection state
if self._c is not None:
return True
else:
try:
<|code_end|>
, generate the next line using the imports in this file:
import os
from collections import defaultdict
from .smb_utils import smb_connect, get_netbios_name, NameError
from smb.base import SharedDevice
and context (functions, classes, or occasionally code) from other files:
# Path: ifcb/data/transfer/smb_utils.py
# def smb_connect(remote_server, username, password, netbios_name=None, timeout=DEFAULT_TIMEOUT):
#
# if netbios_name is None:
# logging.debug('Querying NetBIOS for name of {}'.format(remote_server))
# netbios_name = get_netbios_name(remote_server, timeout=timeout)
# logging.debug('Name is {}'.format(netbios_name))
#
# logging.debug('Connecting to {}'.format(remote_server))
#
# c = SMBConnection(username, password, 'ignore', netbios_name)
# c.connect(remote_server, timeout=timeout)
#
# return c
#
# def get_netbios_name(remote_addr, timeout=DEFAULT_TIMEOUT):
# nb = NetBIOS()
# names = nb.queryIPForName(remote_addr, timeout=timeout)
# nb.close()
# if names is None or len(names) == 0:
# raise NameError('No NetBIOS name found for {}'.format(remote_addr))
# elif len(names) > 1:
# logging.warn('More than one NetBIOS name for {}'.format(remote_addr))
# return names[0]
#
# class NameError(Exception):
# pass
. Output only the next line. | get_netbios_name(self.addr, timeout=self.timeout) |
Predict the next line for this snippet: <|code_start|>
class TestH5Utils(unittest.TestCase):
@withfile
def test_hdfopen(self, F):
attr = 'test'
v1, v2 = 5, 6
for group in [None, 'g']:
<|code_end|>
with the help of current file imports:
import unittest
import os
import numpy as np
import h5py as h5
import pandas as pd
from contextlib import contextmanager
from pandas.testing import assert_frame_equal
from ifcb.tests.utils import withfile
from ifcb.data.h5utils import hdfopen, clear_h5_group, pd2hdf, hdf2pd
and context from other files:
# Path: ifcb/tests/utils.py
# def withfile(method):
# """decorator that adds a named temporary file argument"""
# @wraps(method)
# def wrapper(*args, **kw):
# with test_file() as f:
# args = args + (f,)
# return method(*args, **kw)
# return wrapper
#
# Path: ifcb/data/h5utils.py
# class hdfopen(object):
# """
# Context manager that opens an ``h5py.Group`` from an ``h5py.File``
# or other group.
#
# Parameters:
#
# * path - path to HDF5 file, or open HDF5 group
# * group - for HDF5 file paths, the path of the group to return (optional)
# for groups, a subgroup to require (optional)
# * replace - whether to replace any existing data
#
# :Example:
#
# >>> with hdfopen('myfile.h5','somegroup') as g:
# ... g.attrs['my_attr'] = 3
#
# """
# def __init__(self, path, group=None, replace=None):
# if isinstance(path, h5.Group):
# if group is not None:
# self.group = path.require_group(group)
# else:
# self.group = path
# if replace:
# clear_h5_group(self.group)
# self._file = None
# else:
# mode = 'w' if replace else 'r+'
# self._file = h5.File(path, mode)
# if group is not None:
# self.group = self._file.require_group(group)
# else:
# self.group = self._file
# def close(self):
# if self._file is not None:
# self._file.close()
# def __enter__(self, *args, **kw):
# return self.group
# def __exit__(self, *args):
# self.close()
# pass
#
# def clear_h5_group(h5group):
# """
# Delete all keys and attrs from an ``h5py.Group``.
#
# :param h5group: the h5py.Group
# """
# for k in h5group.keys(): del h5group[k]
# for k in h5group.attrs.keys(): del h5group.attrs[k]
#
# def pd2hdf(group, df, **kw):
# """
# Write ``pandas.DataFrame`` to HDF5 file. This differs
# from pandas's own HDF5 support by providing a slightly less
# optimized but easier-to-access format. Passes keywords
# through to each ``h5py.create_dataset`` operation.
#
# Layout of Pandas ``DataFrame`` / ``Series`` representation:
#
# * ``{path}`` (group): the group containing the dataframe
# * ``{path}.ptype`` (attribute): '``DataFrame``'
# * ``{path}/columns`` (dataset): 1d array of references to column data
# * ``{path}/columns.names`` (attribute, optional): 1d array of column names
# * ``{path}/{n}`` (dataset): 1d array of data for column n
# * ``{path}/index`` (dataset): 1d array of data for dataframe index
# * ``{path}/index.name`` (attribute, optional): name of index
#
# :param group: the ``h5py.Group`` to write the ``DataFrame`` to
# """
# group.attrs['ptype'] = 'DataFrame'
# refs = []
# for i in range(len(df.columns)):
# c = group.create_dataset(str(i), data=df.iloc[:,i], **kw)
# refs.append(c.ref)
# cols = group.create_dataset('columns', data=refs, dtype=H5_REF_TYPE)
# if df.columns.dtype == np.int64:
# cols.attrs['names'] = [int(col) for col in df.columns]
# else:
# cols.attrs['names'] = [col.encode('utf8') for col in df.columns]
# ix = group.create_dataset('index', data=df.index, **kw)
# if df.index.name is not None:
# ix.attrs['name'] = df.index.name
#
# def hdf2pd(group):
# """
# Read a ``pandas.DataFrame`` from an ``h5py.Group``.
#
# :param group: the ``h5py.Group`` to read from.
# """
# if group.attrs['ptype'] != 'DataFrame':
# raise ValueError('unrecognized HDF format')
# index = group['index']
# index_name = index.attrs.get('name',None)
# col_refs = group['columns']
# col_data = [np.array(group[r]) for r in col_refs]
# col_names = col_refs.attrs.get('names')
# if type(col_names[0]) == np.bytes_:
# col_names = [str(cn,'utf8') for cn in col_names]
# data = { k: v for k, v in zip(col_names, col_data) }
# index = pd.Series(index, name=index_name)
# return pd.DataFrame(data=data, index=index, columns=col_names)
, which may contain function names, class names, or code. Output only the next line. | with hdfopen(F, group, replace=True) as f: |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.