Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given snippet: <|code_start|> return data[:-2]
def purge(self):
self._buffer.seek(0)
self._buffer.truncate()
self.bytes_written = 0
self.bytes_read = 0
def close(self):
try:
self.purge()
self._buffer.close()
except:
# issue #633 suggests the purge/close somehow raised a
# BadFileDescriptor error. Perhaps the client ran out of
# memory or something else? It's probably OK to ignore
# any error being raised from purge/close since we're
# removing the reference to the instance below.
pass
self._buffer = None
self._sock = None
class BaseParser:
"""Plain Python parsing class"""
EXCEPTION_CLASSES = {
'ERR': {
'max number of clients reached': ConnectionError
},
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import asyncio
import inspect
import os
import socket
import ssl
import sys
import time
import warnings
import aredis.compat
import hiredis
from io import BytesIO
from aredis.exceptions import (ConnectionError, TimeoutError,
RedisError, ExecAbortError,
BusyLoadingError, NoScriptError,
ReadOnlyError, ResponseError,
InvalidResponse, AskError,
MovedError, TryAgainError,
ClusterDownError, ClusterCrossSlotError)
from aredis.utils import b, nativestr, LOOP_DEPRECATED
and context:
# Path: aredis/exceptions.py
# class ConnectionError(RedisError):
# pass
#
# class TimeoutError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class ExecAbortError(ResponseError):
# pass
#
# class BusyLoadingError(ConnectionError):
# pass
#
# class NoScriptError(ResponseError):
# pass
#
# class ReadOnlyError(ResponseError):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class InvalidResponse(RedisError):
# pass
#
# class AskError(ResponseError):
# """
# src node: MIGRATING to dst node
# get > ASK error
# ask dst node > ASKING command
# dst node: IMPORTING from src node
# asking command only affects next command
# any op will be allowed after asking command
# """
#
# def __init__(self, resp):
# """should only redirect to master node"""
# self.args = (resp,)
# self.message = resp
# slot_id, new_node = resp.split(' ')
# host, port = new_node.rsplit(':', 1)
# self.slot_id = int(slot_id)
# self.node_addr = self.host, self.port = host, int(port)
#
# class MovedError(AskError):
# pass
#
# class TryAgainError(ResponseError):
#
# def __init__(self, *args, **kwargs):
# pass
#
# class ClusterDownError(ClusterError, ResponseError):
#
# def __init__(self, resp):
# self.args = (resp,)
# self.message = resp
#
# class ClusterCrossSlotError(ResponseError):
# message = "Keys in request don't hash to the same slot"
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# LOOP_DEPRECATED = sys.version_info >= (3, 8)
which might include code, classes, or functions. Output only the next line. | 'EXECABORT': ExecAbortError, |
Based on the snippet: <|code_start|>
def purge(self):
self._buffer.seek(0)
self._buffer.truncate()
self.bytes_written = 0
self.bytes_read = 0
def close(self):
try:
self.purge()
self._buffer.close()
except:
# issue #633 suggests the purge/close somehow raised a
# BadFileDescriptor error. Perhaps the client ran out of
# memory or something else? It's probably OK to ignore
# any error being raised from purge/close since we're
# removing the reference to the instance below.
pass
self._buffer = None
self._sock = None
class BaseParser:
"""Plain Python parsing class"""
EXCEPTION_CLASSES = {
'ERR': {
'max number of clients reached': ConnectionError
},
'EXECABORT': ExecAbortError,
<|code_end|>
, predict the immediate next line with the help of imports:
import asyncio
import inspect
import os
import socket
import ssl
import sys
import time
import warnings
import aredis.compat
import hiredis
from io import BytesIO
from aredis.exceptions import (ConnectionError, TimeoutError,
RedisError, ExecAbortError,
BusyLoadingError, NoScriptError,
ReadOnlyError, ResponseError,
InvalidResponse, AskError,
MovedError, TryAgainError,
ClusterDownError, ClusterCrossSlotError)
from aredis.utils import b, nativestr, LOOP_DEPRECATED
and context (classes, functions, sometimes code) from other files:
# Path: aredis/exceptions.py
# class ConnectionError(RedisError):
# pass
#
# class TimeoutError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class ExecAbortError(ResponseError):
# pass
#
# class BusyLoadingError(ConnectionError):
# pass
#
# class NoScriptError(ResponseError):
# pass
#
# class ReadOnlyError(ResponseError):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class InvalidResponse(RedisError):
# pass
#
# class AskError(ResponseError):
# """
# src node: MIGRATING to dst node
# get > ASK error
# ask dst node > ASKING command
# dst node: IMPORTING from src node
# asking command only affects next command
# any op will be allowed after asking command
# """
#
# def __init__(self, resp):
# """should only redirect to master node"""
# self.args = (resp,)
# self.message = resp
# slot_id, new_node = resp.split(' ')
# host, port = new_node.rsplit(':', 1)
# self.slot_id = int(slot_id)
# self.node_addr = self.host, self.port = host, int(port)
#
# class MovedError(AskError):
# pass
#
# class TryAgainError(ResponseError):
#
# def __init__(self, *args, **kwargs):
# pass
#
# class ClusterDownError(ClusterError, ResponseError):
#
# def __init__(self, resp):
# self.args = (resp,)
# self.message = resp
#
# class ClusterCrossSlotError(ResponseError):
# message = "Keys in request don't hash to the same slot"
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# LOOP_DEPRECATED = sys.version_info >= (3, 8)
. Output only the next line. | 'LOADING': BusyLoadingError, |
Using the snippet: <|code_start|> def purge(self):
self._buffer.seek(0)
self._buffer.truncate()
self.bytes_written = 0
self.bytes_read = 0
def close(self):
try:
self.purge()
self._buffer.close()
except:
# issue #633 suggests the purge/close somehow raised a
# BadFileDescriptor error. Perhaps the client ran out of
# memory or something else? It's probably OK to ignore
# any error being raised from purge/close since we're
# removing the reference to the instance below.
pass
self._buffer = None
self._sock = None
class BaseParser:
"""Plain Python parsing class"""
EXCEPTION_CLASSES = {
'ERR': {
'max number of clients reached': ConnectionError
},
'EXECABORT': ExecAbortError,
'LOADING': BusyLoadingError,
<|code_end|>
, determine the next line of code. You have imports:
import asyncio
import inspect
import os
import socket
import ssl
import sys
import time
import warnings
import aredis.compat
import hiredis
from io import BytesIO
from aredis.exceptions import (ConnectionError, TimeoutError,
RedisError, ExecAbortError,
BusyLoadingError, NoScriptError,
ReadOnlyError, ResponseError,
InvalidResponse, AskError,
MovedError, TryAgainError,
ClusterDownError, ClusterCrossSlotError)
from aredis.utils import b, nativestr, LOOP_DEPRECATED
and context (class names, function names, or code) available:
# Path: aredis/exceptions.py
# class ConnectionError(RedisError):
# pass
#
# class TimeoutError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class ExecAbortError(ResponseError):
# pass
#
# class BusyLoadingError(ConnectionError):
# pass
#
# class NoScriptError(ResponseError):
# pass
#
# class ReadOnlyError(ResponseError):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class InvalidResponse(RedisError):
# pass
#
# class AskError(ResponseError):
# """
# src node: MIGRATING to dst node
# get > ASK error
# ask dst node > ASKING command
# dst node: IMPORTING from src node
# asking command only affects next command
# any op will be allowed after asking command
# """
#
# def __init__(self, resp):
# """should only redirect to master node"""
# self.args = (resp,)
# self.message = resp
# slot_id, new_node = resp.split(' ')
# host, port = new_node.rsplit(':', 1)
# self.slot_id = int(slot_id)
# self.node_addr = self.host, self.port = host, int(port)
#
# class MovedError(AskError):
# pass
#
# class TryAgainError(ResponseError):
#
# def __init__(self, *args, **kwargs):
# pass
#
# class ClusterDownError(ClusterError, ResponseError):
#
# def __init__(self, resp):
# self.args = (resp,)
# self.message = resp
#
# class ClusterCrossSlotError(ResponseError):
# message = "Keys in request don't hash to the same slot"
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# LOOP_DEPRECATED = sys.version_info >= (3, 8)
. Output only the next line. | 'NOSCRIPT': NoScriptError, |
Here is a snippet: <|code_start|> self._buffer.seek(0)
self._buffer.truncate()
self.bytes_written = 0
self.bytes_read = 0
def close(self):
try:
self.purge()
self._buffer.close()
except:
# issue #633 suggests the purge/close somehow raised a
# BadFileDescriptor error. Perhaps the client ran out of
# memory or something else? It's probably OK to ignore
# any error being raised from purge/close since we're
# removing the reference to the instance below.
pass
self._buffer = None
self._sock = None
class BaseParser:
"""Plain Python parsing class"""
EXCEPTION_CLASSES = {
'ERR': {
'max number of clients reached': ConnectionError
},
'EXECABORT': ExecAbortError,
'LOADING': BusyLoadingError,
'NOSCRIPT': NoScriptError,
<|code_end|>
. Write the next line using the current file imports:
import asyncio
import inspect
import os
import socket
import ssl
import sys
import time
import warnings
import aredis.compat
import hiredis
from io import BytesIO
from aredis.exceptions import (ConnectionError, TimeoutError,
RedisError, ExecAbortError,
BusyLoadingError, NoScriptError,
ReadOnlyError, ResponseError,
InvalidResponse, AskError,
MovedError, TryAgainError,
ClusterDownError, ClusterCrossSlotError)
from aredis.utils import b, nativestr, LOOP_DEPRECATED
and context from other files:
# Path: aredis/exceptions.py
# class ConnectionError(RedisError):
# pass
#
# class TimeoutError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class ExecAbortError(ResponseError):
# pass
#
# class BusyLoadingError(ConnectionError):
# pass
#
# class NoScriptError(ResponseError):
# pass
#
# class ReadOnlyError(ResponseError):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class InvalidResponse(RedisError):
# pass
#
# class AskError(ResponseError):
# """
# src node: MIGRATING to dst node
# get > ASK error
# ask dst node > ASKING command
# dst node: IMPORTING from src node
# asking command only affects next command
# any op will be allowed after asking command
# """
#
# def __init__(self, resp):
# """should only redirect to master node"""
# self.args = (resp,)
# self.message = resp
# slot_id, new_node = resp.split(' ')
# host, port = new_node.rsplit(':', 1)
# self.slot_id = int(slot_id)
# self.node_addr = self.host, self.port = host, int(port)
#
# class MovedError(AskError):
# pass
#
# class TryAgainError(ResponseError):
#
# def __init__(self, *args, **kwargs):
# pass
#
# class ClusterDownError(ClusterError, ResponseError):
#
# def __init__(self, resp):
# self.args = (resp,)
# self.message = resp
#
# class ClusterCrossSlotError(ResponseError):
# message = "Keys in request don't hash to the same slot"
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# LOOP_DEPRECATED = sys.version_info >= (3, 8)
, which may include functions, classes, or code. Output only the next line. | 'READONLY': ReadOnlyError, |
Given snippet: <|code_start|> pass
self._buffer = None
self._sock = None
class BaseParser:
"""Plain Python parsing class"""
EXCEPTION_CLASSES = {
'ERR': {
'max number of clients reached': ConnectionError
},
'EXECABORT': ExecAbortError,
'LOADING': BusyLoadingError,
'NOSCRIPT': NoScriptError,
'READONLY': ReadOnlyError,
'ASK': AskError,
'TRYAGAIN': TryAgainError,
'MOVED': MovedError,
'CLUSTERDOWN': ClusterDownError,
'CROSSSLOT': ClusterCrossSlotError,
}
def parse_error(self, response):
"""Parse an error response"""
error_code = response.split(' ')[0]
if error_code in self.EXCEPTION_CLASSES:
response = response[len(error_code) + 1:]
exception_class = self.EXCEPTION_CLASSES[error_code]
if isinstance(exception_class, dict):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import asyncio
import inspect
import os
import socket
import ssl
import sys
import time
import warnings
import aredis.compat
import hiredis
from io import BytesIO
from aredis.exceptions import (ConnectionError, TimeoutError,
RedisError, ExecAbortError,
BusyLoadingError, NoScriptError,
ReadOnlyError, ResponseError,
InvalidResponse, AskError,
MovedError, TryAgainError,
ClusterDownError, ClusterCrossSlotError)
from aredis.utils import b, nativestr, LOOP_DEPRECATED
and context:
# Path: aredis/exceptions.py
# class ConnectionError(RedisError):
# pass
#
# class TimeoutError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class ExecAbortError(ResponseError):
# pass
#
# class BusyLoadingError(ConnectionError):
# pass
#
# class NoScriptError(ResponseError):
# pass
#
# class ReadOnlyError(ResponseError):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class InvalidResponse(RedisError):
# pass
#
# class AskError(ResponseError):
# """
# src node: MIGRATING to dst node
# get > ASK error
# ask dst node > ASKING command
# dst node: IMPORTING from src node
# asking command only affects next command
# any op will be allowed after asking command
# """
#
# def __init__(self, resp):
# """should only redirect to master node"""
# self.args = (resp,)
# self.message = resp
# slot_id, new_node = resp.split(' ')
# host, port = new_node.rsplit(':', 1)
# self.slot_id = int(slot_id)
# self.node_addr = self.host, self.port = host, int(port)
#
# class MovedError(AskError):
# pass
#
# class TryAgainError(ResponseError):
#
# def __init__(self, *args, **kwargs):
# pass
#
# class ClusterDownError(ClusterError, ResponseError):
#
# def __init__(self, resp):
# self.args = (resp,)
# self.message = resp
#
# class ClusterCrossSlotError(ResponseError):
# message = "Keys in request don't hash to the same slot"
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# LOOP_DEPRECATED = sys.version_info >= (3, 8)
which might include code, classes, or functions. Output only the next line. | exception_class = exception_class.get(response, ResponseError) |
Given the following code snippet before the placeholder: <|code_start|>
def on_connect(self, connection):
"""Called when the stream connects"""
self._stream = connection._reader
self._buffer = SocketBuffer(self._stream, self._read_size)
if connection.decode_responses:
self.encoding = connection.encoding
def on_disconnect(self):
"""Called when the stream disconnects"""
if self._stream is not None:
self._stream = None
if self._buffer is not None:
self._buffer.close()
self._buffer = None
self.encoding = None
def can_read(self):
return self._buffer and bool(self._buffer.length)
async def read_response(self):
if not self._buffer:
raise ConnectionError('Socket closed on remote end')
response = await self._buffer.readline()
if not response:
raise ConnectionError('Socket closed on remote end')
byte, response = chr(response[0]), response[1:]
if byte not in ('-', '+', ':', '$', '*'):
<|code_end|>
, predict the next line using imports from the current file:
import asyncio
import inspect
import os
import socket
import ssl
import sys
import time
import warnings
import aredis.compat
import hiredis
from io import BytesIO
from aredis.exceptions import (ConnectionError, TimeoutError,
RedisError, ExecAbortError,
BusyLoadingError, NoScriptError,
ReadOnlyError, ResponseError,
InvalidResponse, AskError,
MovedError, TryAgainError,
ClusterDownError, ClusterCrossSlotError)
from aredis.utils import b, nativestr, LOOP_DEPRECATED
and context including class names, function names, and sometimes code from other files:
# Path: aredis/exceptions.py
# class ConnectionError(RedisError):
# pass
#
# class TimeoutError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class ExecAbortError(ResponseError):
# pass
#
# class BusyLoadingError(ConnectionError):
# pass
#
# class NoScriptError(ResponseError):
# pass
#
# class ReadOnlyError(ResponseError):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class InvalidResponse(RedisError):
# pass
#
# class AskError(ResponseError):
# """
# src node: MIGRATING to dst node
# get > ASK error
# ask dst node > ASKING command
# dst node: IMPORTING from src node
# asking command only affects next command
# any op will be allowed after asking command
# """
#
# def __init__(self, resp):
# """should only redirect to master node"""
# self.args = (resp,)
# self.message = resp
# slot_id, new_node = resp.split(' ')
# host, port = new_node.rsplit(':', 1)
# self.slot_id = int(slot_id)
# self.node_addr = self.host, self.port = host, int(port)
#
# class MovedError(AskError):
# pass
#
# class TryAgainError(ResponseError):
#
# def __init__(self, *args, **kwargs):
# pass
#
# class ClusterDownError(ClusterError, ResponseError):
#
# def __init__(self, resp):
# self.args = (resp,)
# self.message = resp
#
# class ClusterCrossSlotError(ResponseError):
# message = "Keys in request don't hash to the same slot"
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# LOOP_DEPRECATED = sys.version_info >= (3, 8)
. Output only the next line. | raise InvalidResponse("Protocol Error: %s, %s" % |
Given the following code snippet before the placeholder: <|code_start|> self._buffer.truncate()
self.bytes_written = 0
self.bytes_read = 0
def close(self):
try:
self.purge()
self._buffer.close()
except:
# issue #633 suggests the purge/close somehow raised a
# BadFileDescriptor error. Perhaps the client ran out of
# memory or something else? It's probably OK to ignore
# any error being raised from purge/close since we're
# removing the reference to the instance below.
pass
self._buffer = None
self._sock = None
class BaseParser:
"""Plain Python parsing class"""
EXCEPTION_CLASSES = {
'ERR': {
'max number of clients reached': ConnectionError
},
'EXECABORT': ExecAbortError,
'LOADING': BusyLoadingError,
'NOSCRIPT': NoScriptError,
'READONLY': ReadOnlyError,
<|code_end|>
, predict the next line using imports from the current file:
import asyncio
import inspect
import os
import socket
import ssl
import sys
import time
import warnings
import aredis.compat
import hiredis
from io import BytesIO
from aredis.exceptions import (ConnectionError, TimeoutError,
RedisError, ExecAbortError,
BusyLoadingError, NoScriptError,
ReadOnlyError, ResponseError,
InvalidResponse, AskError,
MovedError, TryAgainError,
ClusterDownError, ClusterCrossSlotError)
from aredis.utils import b, nativestr, LOOP_DEPRECATED
and context including class names, function names, and sometimes code from other files:
# Path: aredis/exceptions.py
# class ConnectionError(RedisError):
# pass
#
# class TimeoutError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class ExecAbortError(ResponseError):
# pass
#
# class BusyLoadingError(ConnectionError):
# pass
#
# class NoScriptError(ResponseError):
# pass
#
# class ReadOnlyError(ResponseError):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class InvalidResponse(RedisError):
# pass
#
# class AskError(ResponseError):
# """
# src node: MIGRATING to dst node
# get > ASK error
# ask dst node > ASKING command
# dst node: IMPORTING from src node
# asking command only affects next command
# any op will be allowed after asking command
# """
#
# def __init__(self, resp):
# """should only redirect to master node"""
# self.args = (resp,)
# self.message = resp
# slot_id, new_node = resp.split(' ')
# host, port = new_node.rsplit(':', 1)
# self.slot_id = int(slot_id)
# self.node_addr = self.host, self.port = host, int(port)
#
# class MovedError(AskError):
# pass
#
# class TryAgainError(ResponseError):
#
# def __init__(self, *args, **kwargs):
# pass
#
# class ClusterDownError(ClusterError, ResponseError):
#
# def __init__(self, resp):
# self.args = (resp,)
# self.message = resp
#
# class ClusterCrossSlotError(ResponseError):
# message = "Keys in request don't hash to the same slot"
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# LOOP_DEPRECATED = sys.version_info >= (3, 8)
. Output only the next line. | 'ASK': AskError, |
Given the code snippet: <|code_start|> self.bytes_read = 0
def close(self):
try:
self.purge()
self._buffer.close()
except:
# issue #633 suggests the purge/close somehow raised a
# BadFileDescriptor error. Perhaps the client ran out of
# memory or something else? It's probably OK to ignore
# any error being raised from purge/close since we're
# removing the reference to the instance below.
pass
self._buffer = None
self._sock = None
class BaseParser:
"""Plain Python parsing class"""
EXCEPTION_CLASSES = {
'ERR': {
'max number of clients reached': ConnectionError
},
'EXECABORT': ExecAbortError,
'LOADING': BusyLoadingError,
'NOSCRIPT': NoScriptError,
'READONLY': ReadOnlyError,
'ASK': AskError,
'TRYAGAIN': TryAgainError,
<|code_end|>
, generate the next line using the imports in this file:
import asyncio
import inspect
import os
import socket
import ssl
import sys
import time
import warnings
import aredis.compat
import hiredis
from io import BytesIO
from aredis.exceptions import (ConnectionError, TimeoutError,
RedisError, ExecAbortError,
BusyLoadingError, NoScriptError,
ReadOnlyError, ResponseError,
InvalidResponse, AskError,
MovedError, TryAgainError,
ClusterDownError, ClusterCrossSlotError)
from aredis.utils import b, nativestr, LOOP_DEPRECATED
and context (functions, classes, or occasionally code) from other files:
# Path: aredis/exceptions.py
# class ConnectionError(RedisError):
# pass
#
# class TimeoutError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class ExecAbortError(ResponseError):
# pass
#
# class BusyLoadingError(ConnectionError):
# pass
#
# class NoScriptError(ResponseError):
# pass
#
# class ReadOnlyError(ResponseError):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class InvalidResponse(RedisError):
# pass
#
# class AskError(ResponseError):
# """
# src node: MIGRATING to dst node
# get > ASK error
# ask dst node > ASKING command
# dst node: IMPORTING from src node
# asking command only affects next command
# any op will be allowed after asking command
# """
#
# def __init__(self, resp):
# """should only redirect to master node"""
# self.args = (resp,)
# self.message = resp
# slot_id, new_node = resp.split(' ')
# host, port = new_node.rsplit(':', 1)
# self.slot_id = int(slot_id)
# self.node_addr = self.host, self.port = host, int(port)
#
# class MovedError(AskError):
# pass
#
# class TryAgainError(ResponseError):
#
# def __init__(self, *args, **kwargs):
# pass
#
# class ClusterDownError(ClusterError, ResponseError):
#
# def __init__(self, resp):
# self.args = (resp,)
# self.message = resp
#
# class ClusterCrossSlotError(ResponseError):
# message = "Keys in request don't hash to the same slot"
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# LOOP_DEPRECATED = sys.version_info >= (3, 8)
. Output only the next line. | 'MOVED': MovedError, |
Given the code snippet: <|code_start|> self.bytes_written = 0
self.bytes_read = 0
def close(self):
try:
self.purge()
self._buffer.close()
except:
# issue #633 suggests the purge/close somehow raised a
# BadFileDescriptor error. Perhaps the client ran out of
# memory or something else? It's probably OK to ignore
# any error being raised from purge/close since we're
# removing the reference to the instance below.
pass
self._buffer = None
self._sock = None
class BaseParser:
"""Plain Python parsing class"""
EXCEPTION_CLASSES = {
'ERR': {
'max number of clients reached': ConnectionError
},
'EXECABORT': ExecAbortError,
'LOADING': BusyLoadingError,
'NOSCRIPT': NoScriptError,
'READONLY': ReadOnlyError,
'ASK': AskError,
<|code_end|>
, generate the next line using the imports in this file:
import asyncio
import inspect
import os
import socket
import ssl
import sys
import time
import warnings
import aredis.compat
import hiredis
from io import BytesIO
from aredis.exceptions import (ConnectionError, TimeoutError,
RedisError, ExecAbortError,
BusyLoadingError, NoScriptError,
ReadOnlyError, ResponseError,
InvalidResponse, AskError,
MovedError, TryAgainError,
ClusterDownError, ClusterCrossSlotError)
from aredis.utils import b, nativestr, LOOP_DEPRECATED
and context (functions, classes, or occasionally code) from other files:
# Path: aredis/exceptions.py
# class ConnectionError(RedisError):
# pass
#
# class TimeoutError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class ExecAbortError(ResponseError):
# pass
#
# class BusyLoadingError(ConnectionError):
# pass
#
# class NoScriptError(ResponseError):
# pass
#
# class ReadOnlyError(ResponseError):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class InvalidResponse(RedisError):
# pass
#
# class AskError(ResponseError):
# """
# src node: MIGRATING to dst node
# get > ASK error
# ask dst node > ASKING command
# dst node: IMPORTING from src node
# asking command only affects next command
# any op will be allowed after asking command
# """
#
# def __init__(self, resp):
# """should only redirect to master node"""
# self.args = (resp,)
# self.message = resp
# slot_id, new_node = resp.split(' ')
# host, port = new_node.rsplit(':', 1)
# self.slot_id = int(slot_id)
# self.node_addr = self.host, self.port = host, int(port)
#
# class MovedError(AskError):
# pass
#
# class TryAgainError(ResponseError):
#
# def __init__(self, *args, **kwargs):
# pass
#
# class ClusterDownError(ClusterError, ResponseError):
#
# def __init__(self, resp):
# self.args = (resp,)
# self.message = resp
#
# class ClusterCrossSlotError(ResponseError):
# message = "Keys in request don't hash to the same slot"
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# LOOP_DEPRECATED = sys.version_info >= (3, 8)
. Output only the next line. | 'TRYAGAIN': TryAgainError, |
Given snippet: <|code_start|>
def close(self):
try:
self.purge()
self._buffer.close()
except:
# issue #633 suggests the purge/close somehow raised a
# BadFileDescriptor error. Perhaps the client ran out of
# memory or something else? It's probably OK to ignore
# any error being raised from purge/close since we're
# removing the reference to the instance below.
pass
self._buffer = None
self._sock = None
class BaseParser:
"""Plain Python parsing class"""
EXCEPTION_CLASSES = {
'ERR': {
'max number of clients reached': ConnectionError
},
'EXECABORT': ExecAbortError,
'LOADING': BusyLoadingError,
'NOSCRIPT': NoScriptError,
'READONLY': ReadOnlyError,
'ASK': AskError,
'TRYAGAIN': TryAgainError,
'MOVED': MovedError,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import asyncio
import inspect
import os
import socket
import ssl
import sys
import time
import warnings
import aredis.compat
import hiredis
from io import BytesIO
from aredis.exceptions import (ConnectionError, TimeoutError,
RedisError, ExecAbortError,
BusyLoadingError, NoScriptError,
ReadOnlyError, ResponseError,
InvalidResponse, AskError,
MovedError, TryAgainError,
ClusterDownError, ClusterCrossSlotError)
from aredis.utils import b, nativestr, LOOP_DEPRECATED
and context:
# Path: aredis/exceptions.py
# class ConnectionError(RedisError):
# pass
#
# class TimeoutError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class ExecAbortError(ResponseError):
# pass
#
# class BusyLoadingError(ConnectionError):
# pass
#
# class NoScriptError(ResponseError):
# pass
#
# class ReadOnlyError(ResponseError):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class InvalidResponse(RedisError):
# pass
#
# class AskError(ResponseError):
# """
# src node: MIGRATING to dst node
# get > ASK error
# ask dst node > ASKING command
# dst node: IMPORTING from src node
# asking command only affects next command
# any op will be allowed after asking command
# """
#
# def __init__(self, resp):
# """should only redirect to master node"""
# self.args = (resp,)
# self.message = resp
# slot_id, new_node = resp.split(' ')
# host, port = new_node.rsplit(':', 1)
# self.slot_id = int(slot_id)
# self.node_addr = self.host, self.port = host, int(port)
#
# class MovedError(AskError):
# pass
#
# class TryAgainError(ResponseError):
#
# def __init__(self, *args, **kwargs):
# pass
#
# class ClusterDownError(ClusterError, ResponseError):
#
# def __init__(self, resp):
# self.args = (resp,)
# self.message = resp
#
# class ClusterCrossSlotError(ResponseError):
# message = "Keys in request don't hash to the same slot"
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# LOOP_DEPRECATED = sys.version_info >= (3, 8)
which might include code, classes, or functions. Output only the next line. | 'CLUSTERDOWN': ClusterDownError, |
Using the snippet: <|code_start|> def close(self):
try:
self.purge()
self._buffer.close()
except:
# issue #633 suggests the purge/close somehow raised a
# BadFileDescriptor error. Perhaps the client ran out of
# memory or something else? It's probably OK to ignore
# any error being raised from purge/close since we're
# removing the reference to the instance below.
pass
self._buffer = None
self._sock = None
class BaseParser:
"""Plain Python parsing class"""
EXCEPTION_CLASSES = {
'ERR': {
'max number of clients reached': ConnectionError
},
'EXECABORT': ExecAbortError,
'LOADING': BusyLoadingError,
'NOSCRIPT': NoScriptError,
'READONLY': ReadOnlyError,
'ASK': AskError,
'TRYAGAIN': TryAgainError,
'MOVED': MovedError,
'CLUSTERDOWN': ClusterDownError,
<|code_end|>
, determine the next line of code. You have imports:
import asyncio
import inspect
import os
import socket
import ssl
import sys
import time
import warnings
import aredis.compat
import hiredis
from io import BytesIO
from aredis.exceptions import (ConnectionError, TimeoutError,
RedisError, ExecAbortError,
BusyLoadingError, NoScriptError,
ReadOnlyError, ResponseError,
InvalidResponse, AskError,
MovedError, TryAgainError,
ClusterDownError, ClusterCrossSlotError)
from aredis.utils import b, nativestr, LOOP_DEPRECATED
and context (class names, function names, or code) available:
# Path: aredis/exceptions.py
# class ConnectionError(RedisError):
# pass
#
# class TimeoutError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class ExecAbortError(ResponseError):
# pass
#
# class BusyLoadingError(ConnectionError):
# pass
#
# class NoScriptError(ResponseError):
# pass
#
# class ReadOnlyError(ResponseError):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class InvalidResponse(RedisError):
# pass
#
# class AskError(ResponseError):
# """
# src node: MIGRATING to dst node
# get > ASK error
# ask dst node > ASKING command
# dst node: IMPORTING from src node
# asking command only affects next command
# any op will be allowed after asking command
# """
#
# def __init__(self, resp):
# """should only redirect to master node"""
# self.args = (resp,)
# self.message = resp
# slot_id, new_node = resp.split(' ')
# host, port = new_node.rsplit(':', 1)
# self.slot_id = int(slot_id)
# self.node_addr = self.host, self.port = host, int(port)
#
# class MovedError(AskError):
# pass
#
# class TryAgainError(ResponseError):
#
# def __init__(self, *args, **kwargs):
# pass
#
# class ClusterDownError(ClusterError, ResponseError):
#
# def __init__(self, resp):
# self.args = (resp,)
# self.message = resp
#
# class ClusterCrossSlotError(ResponseError):
# message = "Keys in request don't hash to the same slot"
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# LOOP_DEPRECATED = sys.version_info >= (3, 8)
. Output only the next line. | 'CROSSSLOT': ClusterCrossSlotError, |
Given the code snippet: <|code_start|>
try:
HIREDIS_AVAILABLE = True
except ImportError:
HIREDIS_AVAILABLE = False
<|code_end|>
, generate the next line using the imports in this file:
import asyncio
import inspect
import os
import socket
import ssl
import sys
import time
import warnings
import aredis.compat
import hiredis
from io import BytesIO
from aredis.exceptions import (ConnectionError, TimeoutError,
RedisError, ExecAbortError,
BusyLoadingError, NoScriptError,
ReadOnlyError, ResponseError,
InvalidResponse, AskError,
MovedError, TryAgainError,
ClusterDownError, ClusterCrossSlotError)
from aredis.utils import b, nativestr, LOOP_DEPRECATED
and context (functions, classes, or occasionally code) from other files:
# Path: aredis/exceptions.py
# class ConnectionError(RedisError):
# pass
#
# class TimeoutError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class ExecAbortError(ResponseError):
# pass
#
# class BusyLoadingError(ConnectionError):
# pass
#
# class NoScriptError(ResponseError):
# pass
#
# class ReadOnlyError(ResponseError):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class InvalidResponse(RedisError):
# pass
#
# class AskError(ResponseError):
# """
# src node: MIGRATING to dst node
# get > ASK error
# ask dst node > ASKING command
# dst node: IMPORTING from src node
# asking command only affects next command
# any op will be allowed after asking command
# """
#
# def __init__(self, resp):
# """should only redirect to master node"""
# self.args = (resp,)
# self.message = resp
# slot_id, new_node = resp.split(' ')
# host, port = new_node.rsplit(':', 1)
# self.slot_id = int(slot_id)
# self.node_addr = self.host, self.port = host, int(port)
#
# class MovedError(AskError):
# pass
#
# class TryAgainError(ResponseError):
#
# def __init__(self, *args, **kwargs):
# pass
#
# class ClusterDownError(ClusterError, ResponseError):
#
# def __init__(self, resp):
# self.args = (resp,)
# self.message = resp
#
# class ClusterCrossSlotError(ResponseError):
# message = "Keys in request don't hash to the same slot"
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# LOOP_DEPRECATED = sys.version_info >= (3, 8)
. Output only the next line. | SYM_STAR = b('*') |
Given snippet: <|code_start|> if not self.is_connected:
await self.connect()
return self._parser.can_read()
async def connect(self):
try:
await self._connect()
except aredis.compat.CancelledError:
raise
except Exception as exc:
raise ConnectionError()
# run any user callbacks. right now the only internal callback
# is for pubsub channel/pattern resubscription
for callback in self._connect_callbacks:
task = callback(self)
# typing.Awaitable is not available in Python3.5
# so use inspect.isawaitable instead
# according to issue https://github.com/NoneGG/aredis/issues/77
if inspect.isawaitable(task):
await task
async def _connect(self):
raise NotImplementedError
async def on_connect(self):
self._parser.on_connect(self)
# if a password is specified, authenticate
if self.password:
await self.send_command('AUTH', self.password)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import asyncio
import inspect
import os
import socket
import ssl
import sys
import time
import warnings
import aredis.compat
import hiredis
from io import BytesIO
from aredis.exceptions import (ConnectionError, TimeoutError,
RedisError, ExecAbortError,
BusyLoadingError, NoScriptError,
ReadOnlyError, ResponseError,
InvalidResponse, AskError,
MovedError, TryAgainError,
ClusterDownError, ClusterCrossSlotError)
from aredis.utils import b, nativestr, LOOP_DEPRECATED
and context:
# Path: aredis/exceptions.py
# class ConnectionError(RedisError):
# pass
#
# class TimeoutError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class ExecAbortError(ResponseError):
# pass
#
# class BusyLoadingError(ConnectionError):
# pass
#
# class NoScriptError(ResponseError):
# pass
#
# class ReadOnlyError(ResponseError):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class InvalidResponse(RedisError):
# pass
#
# class AskError(ResponseError):
# """
# src node: MIGRATING to dst node
# get > ASK error
# ask dst node > ASKING command
# dst node: IMPORTING from src node
# asking command only affects next command
# any op will be allowed after asking command
# """
#
# def __init__(self, resp):
# """should only redirect to master node"""
# self.args = (resp,)
# self.message = resp
# slot_id, new_node = resp.split(' ')
# host, port = new_node.rsplit(':', 1)
# self.slot_id = int(slot_id)
# self.node_addr = self.host, self.port = host, int(port)
#
# class MovedError(AskError):
# pass
#
# class TryAgainError(ResponseError):
#
# def __init__(self, *args, **kwargs):
# pass
#
# class ClusterDownError(ClusterError, ResponseError):
#
# def __init__(self, resp):
# self.args = (resp,)
# self.message = resp
#
# class ClusterCrossSlotError(ResponseError):
# message = "Keys in request don't hash to the same slot"
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# LOOP_DEPRECATED = sys.version_info >= (3, 8)
which might include code, classes, or functions. Output only the next line. | if nativestr(await self.read_response()) != 'OK': |
Given the following code snippet before the placeholder: <|code_start|>
try:
HIREDIS_AVAILABLE = True
except ImportError:
HIREDIS_AVAILABLE = False
SYM_STAR = b('*')
SYM_DOLLAR = b('$')
SYM_CRLF = b('\r\n')
SYM_LF = b('\n')
SYM_EMPTY = b('')
async def exec_with_timeout(coroutine, timeout, *, loop=None):
try:
<|code_end|>
, predict the next line using imports from the current file:
import asyncio
import inspect
import os
import socket
import ssl
import sys
import time
import warnings
import aredis.compat
import hiredis
from io import BytesIO
from aredis.exceptions import (ConnectionError, TimeoutError,
RedisError, ExecAbortError,
BusyLoadingError, NoScriptError,
ReadOnlyError, ResponseError,
InvalidResponse, AskError,
MovedError, TryAgainError,
ClusterDownError, ClusterCrossSlotError)
from aredis.utils import b, nativestr, LOOP_DEPRECATED
and context including class names, function names, and sometimes code from other files:
# Path: aredis/exceptions.py
# class ConnectionError(RedisError):
# pass
#
# class TimeoutError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class ExecAbortError(ResponseError):
# pass
#
# class BusyLoadingError(ConnectionError):
# pass
#
# class NoScriptError(ResponseError):
# pass
#
# class ReadOnlyError(ResponseError):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class InvalidResponse(RedisError):
# pass
#
# class AskError(ResponseError):
# """
# src node: MIGRATING to dst node
# get > ASK error
# ask dst node > ASKING command
# dst node: IMPORTING from src node
# asking command only affects next command
# any op will be allowed after asking command
# """
#
# def __init__(self, resp):
# """should only redirect to master node"""
# self.args = (resp,)
# self.message = resp
# slot_id, new_node = resp.split(' ')
# host, port = new_node.rsplit(':', 1)
# self.slot_id = int(slot_id)
# self.node_addr = self.host, self.port = host, int(port)
#
# class MovedError(AskError):
# pass
#
# class TryAgainError(ResponseError):
#
# def __init__(self, *args, **kwargs):
# pass
#
# class ClusterDownError(ClusterError, ResponseError):
#
# def __init__(self, resp):
# self.args = (resp,)
# self.message = resp
#
# class ClusterCrossSlotError(ResponseError):
# message = "Keys in request don't hash to the same slot"
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# LOOP_DEPRECATED = sys.version_info >= (3, 8)
. Output only the next line. | if LOOP_DEPRECATED: |
Continue the code snippet: <|code_start|> string_keys_to_dict(
'BITCOUNT BITPOS DECRBY GETBIT INCRBY '
'STRLEN SETBIT', int
),
{
'INCRBYFLOAT': float,
'MSET': bool_ok,
'SET': lambda r: r and nativestr(r) == 'OK',
}
)
async def append(self, key, value):
"""
Appends the string ``value`` to the value at ``key``. If ``key``
doesn't already exist, create it with a value of ``value``.
Returns the new length of the value at ``key``.
"""
return await self.execute_command('APPEND', key, value)
async def bitcount(self, key, start=None, end=None):
"""
Returns the count of set bits in the value of ``key``. Optional
``start`` and ``end`` paramaters indicate which bytes to consider
"""
params = [key]
if start is not None and end is not None:
params.append(start)
params.append(end)
elif (start is not None and end is None) or \
(end is not None and start is None):
<|code_end|>
. Use current file imports:
import datetime
from aredis.exceptions import RedisError
from aredis.utils import (NodeFlag, nativestr,
iteritems,
list_or_args,
dict_merge,
bool_ok,
string_keys_to_dict)
and context (classes, functions, or code) from other files:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# def iteritems(x):
# return iter(x.items())
#
# def list_or_args(keys, args):
# # returns a single list combining keys and args
# try:
# iter(keys)
# # a string or bytes instance can be iterated, but indicates
# # keys wasn't passed as a list
# if isinstance(keys, (str, bytes)):
# keys = [keys]
# except TypeError:
# keys = [keys]
# if args:
# keys.extend(args)
# return keys
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
. Output only the next line. | raise RedisError("Both start and end must be specified") |
Continue the code snippet: <|code_start|> return await self.execute_command('SETNX', name, value)
async def setrange(self, name, offset, value):
"""
Overwrite bytes in the value of ``name`` starting at ``offset`` with
``value``. If ``offset`` plus the length of ``value`` exceeds the
length of the original value, the new value will be larger than before.
If ``offset`` exceeds the length of the original value, null bytes
will be used to pad between the end of the previous value and the start
of what's being injected.
Returns the length of the new string.
"""
return await self.execute_command('SETRANGE', name, offset, value)
async def strlen(self, name):
"""Returns the number of bytes stored in the value of ``name``"""
return await self.execute_command('STRLEN', name)
async def substr(self, name, start, end=-1):
"""
Returns a substring of the string at key ``name``. ``start`` and ``end``
are 0-based integers specifying the portion of the string to return.
"""
return await self.execute_command('SUBSTR', name, start, end)
class ClusterStringsCommandMixin(StringsCommandMixin):
NODES_FLAGS = {
<|code_end|>
. Use current file imports:
import datetime
from aredis.exceptions import RedisError
from aredis.utils import (NodeFlag, nativestr,
iteritems,
list_or_args,
dict_merge,
bool_ok,
string_keys_to_dict)
and context (classes, functions, or code) from other files:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# def iteritems(x):
# return iter(x.items())
#
# def list_or_args(keys, args):
# # returns a single list combining keys and args
# try:
# iter(keys)
# # a string or bytes instance can be iterated, but indicates
# # keys wasn't passed as a list
# if isinstance(keys, (str, bytes)):
# keys = [keys]
# except TypeError:
# keys = [keys]
# if args:
# keys.extend(args)
# return keys
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
. Output only the next line. | 'BITOP': NodeFlag.BLOCKED |
Based on the snippet: <|code_start|> self._command_stack.extend(['INCRBY', type, offset, increment])
return self
def overflow(self, type='SAT'):
"""
fine-tune the behavior of the increment or decrement overflow,
have no effect unless used before `incrby`
three types are available: WRAP|SAT|FAIL
"""
self._command_stack.extend(['OVERFLOW', type])
return self
async def exc(self):
"""execute commands in command stack"""
return await self.redis.execute_command(*self._command_stack)
class StringsCommandMixin:
RESPONSE_CALLBACKS = dict_merge(
string_keys_to_dict(
'MSETNX PSETEX SETEX SETNX',
bool
),
string_keys_to_dict(
'BITCOUNT BITPOS DECRBY GETBIT INCRBY '
'STRLEN SETBIT', int
),
{
'INCRBYFLOAT': float,
'MSET': bool_ok,
<|code_end|>
, predict the immediate next line with the help of imports:
import datetime
from aredis.exceptions import RedisError
from aredis.utils import (NodeFlag, nativestr,
iteritems,
list_or_args,
dict_merge,
bool_ok,
string_keys_to_dict)
and context (classes, functions, sometimes code) from other files:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# def iteritems(x):
# return iter(x.items())
#
# def list_or_args(keys, args):
# # returns a single list combining keys and args
# try:
# iter(keys)
# # a string or bytes instance can be iterated, but indicates
# # keys wasn't passed as a list
# if isinstance(keys, (str, bytes)):
# keys = [keys]
# except TypeError:
# keys = [keys]
# if args:
# keys.extend(args)
# return keys
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
. Output only the next line. | 'SET': lambda r: r and nativestr(r) == 'OK', |
Continue the code snippet: <|code_start|> """
# An alias for ``incr()``, because it is already implemented
# as INCRBY redis command.
return await self.incr(name, amount)
async def incrbyfloat(self, name, amount=1.0):
"""
Increments the value at key ``name`` by floating ``amount``.
If no key exists, the value will be initialized as ``amount``
"""
return await self.execute_command('INCRBYFLOAT', name, amount)
async def mget(self, keys, *args):
"""
Returns a list of values ordered identically to ``keys``
"""
args = list_or_args(keys, args)
return await self.execute_command('MGET', *args)
async def mset(self, *args, **kwargs):
"""
Sets key/values based on a mapping. Mapping can be supplied as a single
dictionary argument or as kwargs.
"""
if args:
if len(args) != 1 or not isinstance(args[0], dict):
raise RedisError('MSET requires **kwargs or a single dict arg')
kwargs.update(args[0])
items = []
<|code_end|>
. Use current file imports:
import datetime
from aredis.exceptions import RedisError
from aredis.utils import (NodeFlag, nativestr,
iteritems,
list_or_args,
dict_merge,
bool_ok,
string_keys_to_dict)
and context (classes, functions, or code) from other files:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# def iteritems(x):
# return iter(x.items())
#
# def list_or_args(keys, args):
# # returns a single list combining keys and args
# try:
# iter(keys)
# # a string or bytes instance can be iterated, but indicates
# # keys wasn't passed as a list
# if isinstance(keys, (str, bytes)):
# keys = [keys]
# except TypeError:
# keys = [keys]
# if args:
# keys.extend(args)
# return keys
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
. Output only the next line. | for pair in iteritems(kwargs): |
Here is a snippet: <|code_start|> return await self.execute_command('GETSET', name, value)
async def incr(self, name, amount=1):
"""
Increments the value of ``key`` by ``amount``. If no key exists,
the value will be initialized as ``amount``
"""
return await self.execute_command('INCRBY', name, amount)
async def incrby(self, name, amount=1):
"""
Increments the value of ``key`` by ``amount``. If no key exists,
the value will be initialized as ``amount``
"""
# An alias for ``incr()``, because it is already implemented
# as INCRBY redis command.
return await self.incr(name, amount)
async def incrbyfloat(self, name, amount=1.0):
"""
Increments the value at key ``name`` by floating ``amount``.
If no key exists, the value will be initialized as ``amount``
"""
return await self.execute_command('INCRBYFLOAT', name, amount)
async def mget(self, keys, *args):
"""
Returns a list of values ordered identically to ``keys``
"""
<|code_end|>
. Write the next line using the current file imports:
import datetime
from aredis.exceptions import RedisError
from aredis.utils import (NodeFlag, nativestr,
iteritems,
list_or_args,
dict_merge,
bool_ok,
string_keys_to_dict)
and context from other files:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# def iteritems(x):
# return iter(x.items())
#
# def list_or_args(keys, args):
# # returns a single list combining keys and args
# try:
# iter(keys)
# # a string or bytes instance can be iterated, but indicates
# # keys wasn't passed as a list
# if isinstance(keys, (str, bytes)):
# keys = [keys]
# except TypeError:
# keys = [keys]
# if args:
# keys.extend(args)
# return keys
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
, which may include functions, classes, or code. Output only the next line. | args = list_or_args(keys, args) |
Continue the code snippet: <|code_start|> def get(self, type, offset):
"""
Returns the specified bit field.
"""
self._command_stack.extend(['GET', type, offset])
return self
def incrby(self, type, offset, increment):
"""
Increments or decrements (if a negative increment is given)
the specified bit field and returns the new value.
"""
self._command_stack.extend(['INCRBY', type, offset, increment])
return self
def overflow(self, type='SAT'):
"""
fine-tune the behavior of the increment or decrement overflow,
have no effect unless used before `incrby`
three types are available: WRAP|SAT|FAIL
"""
self._command_stack.extend(['OVERFLOW', type])
return self
async def exc(self):
"""execute commands in command stack"""
return await self.redis.execute_command(*self._command_stack)
class StringsCommandMixin:
<|code_end|>
. Use current file imports:
import datetime
from aredis.exceptions import RedisError
from aredis.utils import (NodeFlag, nativestr,
iteritems,
list_or_args,
dict_merge,
bool_ok,
string_keys_to_dict)
and context (classes, functions, or code) from other files:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# def iteritems(x):
# return iter(x.items())
#
# def list_or_args(keys, args):
# # returns a single list combining keys and args
# try:
# iter(keys)
# # a string or bytes instance can be iterated, but indicates
# # keys wasn't passed as a list
# if isinstance(keys, (str, bytes)):
# keys = [keys]
# except TypeError:
# keys = [keys]
# if args:
# keys.extend(args)
# return keys
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
. Output only the next line. | RESPONSE_CALLBACKS = dict_merge( |
Here is a snippet: <|code_start|> """
self._command_stack.extend(['INCRBY', type, offset, increment])
return self
def overflow(self, type='SAT'):
"""
fine-tune the behavior of the increment or decrement overflow,
have no effect unless used before `incrby`
three types are available: WRAP|SAT|FAIL
"""
self._command_stack.extend(['OVERFLOW', type])
return self
async def exc(self):
"""execute commands in command stack"""
return await self.redis.execute_command(*self._command_stack)
class StringsCommandMixin:
RESPONSE_CALLBACKS = dict_merge(
string_keys_to_dict(
'MSETNX PSETEX SETEX SETNX',
bool
),
string_keys_to_dict(
'BITCOUNT BITPOS DECRBY GETBIT INCRBY '
'STRLEN SETBIT', int
),
{
'INCRBYFLOAT': float,
<|code_end|>
. Write the next line using the current file imports:
import datetime
from aredis.exceptions import RedisError
from aredis.utils import (NodeFlag, nativestr,
iteritems,
list_or_args,
dict_merge,
bool_ok,
string_keys_to_dict)
and context from other files:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# def iteritems(x):
# return iter(x.items())
#
# def list_or_args(keys, args):
# # returns a single list combining keys and args
# try:
# iter(keys)
# # a string or bytes instance can be iterated, but indicates
# # keys wasn't passed as a list
# if isinstance(keys, (str, bytes)):
# keys = [keys]
# except TypeError:
# keys = [keys]
# if args:
# keys.extend(args)
# return keys
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
, which may include functions, classes, or code. Output only the next line. | 'MSET': bool_ok, |
Predict the next line after this snippet: <|code_start|> """
Returns the specified bit field.
"""
self._command_stack.extend(['GET', type, offset])
return self
def incrby(self, type, offset, increment):
"""
Increments or decrements (if a negative increment is given)
the specified bit field and returns the new value.
"""
self._command_stack.extend(['INCRBY', type, offset, increment])
return self
def overflow(self, type='SAT'):
"""
fine-tune the behavior of the increment or decrement overflow,
have no effect unless used before `incrby`
three types are available: WRAP|SAT|FAIL
"""
self._command_stack.extend(['OVERFLOW', type])
return self
async def exc(self):
"""execute commands in command stack"""
return await self.redis.execute_command(*self._command_stack)
class StringsCommandMixin:
RESPONSE_CALLBACKS = dict_merge(
<|code_end|>
using the current file's imports:
import datetime
from aredis.exceptions import RedisError
from aredis.utils import (NodeFlag, nativestr,
iteritems,
list_or_args,
dict_merge,
bool_ok,
string_keys_to_dict)
and any relevant context from other files:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# def iteritems(x):
# return iter(x.items())
#
# def list_or_args(keys, args):
# # returns a single list combining keys and args
# try:
# iter(keys)
# # a string or bytes instance can be iterated, but indicates
# # keys wasn't passed as a list
# if isinstance(keys, (str, bytes)):
# keys = [keys]
# except TypeError:
# keys = [keys]
# if args:
# keys.extend(args)
# return keys
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
. Output only the next line. | string_keys_to_dict( |
Predict the next line for this snippet: <|code_start|>"""Internal messages used by mailbox processors. Do not import or use.
"""
TSource = TypeVar("TSource")
TOther = TypeVar("TOther")
Key = NewType("Key", int)
class Msg(SupportsMatch[TSource], ABC):
"""Message base class."""
@dataclass
<|code_end|>
with the help of current file imports:
from abc import ABC
from dataclasses import dataclass
from typing import Any, Iterable, NewType, TypeVar, get_origin
from expression.core import SupportsMatch
from expression.system import AsyncDisposable
from .notification import Notification
from .types import AsyncObservable
and context from other files:
# Path: aioreactive/notification.py
# class Notification(Generic[TSource], ABC):
# """Represents a message to a mailbox processor."""
#
# def __init__(self, kind: MsgKind):
# self.kind = kind # Message kind
#
# @abstractmethod
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def accept_observer(self, obv: AsyncObserver[TSource]) -> None:
# raise NotImplementedError
#
# def __repr__(self) -> str:
# return str(self)
#
# Path: aioreactive/types.py
# class AsyncObservable(Generic[T_co]):
# __slots__ = ()
#
# @abstractmethod
# async def subscribe_async(self, observer: AsyncObserver[T_co]) -> AsyncDisposable:
# raise NotImplementedError
, which may contain function names, class names, or code. Output only the next line. | class SourceMsg(Msg[Notification[TSource]], SupportsMatch[TSource]): |
Given snippet: <|code_start|>@dataclass
class OtherMsg(Msg[Notification[TOther]], SupportsMatch[TOther]):
value: Notification[TOther]
def __match__(self, pattern: Any) -> Iterable[Notification[TOther]]:
origin: Any = get_origin(pattern)
try:
if isinstance(self, origin or pattern):
return [self.value]
except TypeError:
pass
return []
@dataclass
class DisposableMsg(Msg[AsyncDisposable], SupportsMatch[AsyncDisposable]):
"""Message containing a diposable."""
disposable: AsyncDisposable
def __match__(self, pattern: Any) -> Iterable[AsyncDisposable]:
try:
if isinstance(self, pattern):
return [self.disposable]
except TypeError:
pass
return []
@dataclass
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from abc import ABC
from dataclasses import dataclass
from typing import Any, Iterable, NewType, TypeVar, get_origin
from expression.core import SupportsMatch
from expression.system import AsyncDisposable
from .notification import Notification
from .types import AsyncObservable
and context:
# Path: aioreactive/notification.py
# class Notification(Generic[TSource], ABC):
# """Represents a message to a mailbox processor."""
#
# def __init__(self, kind: MsgKind):
# self.kind = kind # Message kind
#
# @abstractmethod
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def accept_observer(self, obv: AsyncObserver[TSource]) -> None:
# raise NotImplementedError
#
# def __repr__(self) -> str:
# return str(self)
#
# Path: aioreactive/types.py
# class AsyncObservable(Generic[T_co]):
# __slots__ = ()
#
# @abstractmethod
# async def subscribe_async(self, observer: AsyncObserver[T_co]) -> AsyncDisposable:
# raise NotImplementedError
which might include code, classes, or functions. Output only the next line. | class InnerObservableMsg(Msg[AsyncObservable[TSource]], SupportsMatch[AsyncObservable[TSource]]): |
Continue the code snippet: <|code_start|>
class MyException(Exception):
pass
@pytest.yield_fixture() # type:ignore
def event_loop() -> Generator[Any, Any, Any]:
<|code_end|>
. Use current file imports:
import asyncio
import aioreactive as rx
import pytest
from typing import Any, Generator
from aioreactive.testing import VirtualTimeEventLoop
from expression.core import pipe
and context (classes, functions, or code) from other files:
# Path: aioreactive/testing/virtual_events.py
# class VirtualTimeEventLoop(asyncio.BaseEventLoop):
# """Virtual time event loop.
#
# Works the same was as a normal event loop except that time is
# virtual. Time starts at 0 and only advances when something is
# scheduled into the future. Thus the event loops runs as quickly as
# possible while producing the same output as a normal event loop
# would do. This makes it ideal for unit-testing where you want to
# test delays but without spending time in real life.
# """
#
# def __init__(self) -> None:
# super().__init__()
#
# self._ready = collections.deque()
# self._current_handle = None
# self._debug = False
#
# self._time: float = 0.0
#
# def time(self):
# return self._time
#
# def _run_once(self):
# """Run one full iteration of the event loop. This calls all
# currently ready callbacks, polls for I/O, schedules the
# resulting callbacks, and finally schedules 'call_later'
# callbacks.
# """
# # log.debug("run_once()")
#
# sched_count = len(self._scheduled)
# if (
# sched_count > _MIN_SCHEDULED_TIMER_HANDLES
# and self._timer_cancelled_count / sched_count > _MIN_CANCELLED_TIMER_HANDLES_FRACTION
# ):
# # Remove delayed calls that were cancelled if their number
# # is too high
# new_scheduled = []
# for handle in self._scheduled:
# if handle._cancelled:
# handle._scheduled = False
# else:
# new_scheduled.append(handle)
#
# heapq.heapify(new_scheduled)
# self._scheduled = new_scheduled
# self._timer_cancelled_count = 0
# else:
# # Remove delayed calls that were cancelled from head of queue.
# while self._scheduled and self._scheduled[0]._cancelled:
# self._timer_cancelled_count -= 1
# handle = heapq.heappop(self._scheduled)
# handle._scheduled = False
#
# # print("***", self._ready)
# # print("***", self._scheduled)
#
# # Handle 'later' callbacks that are ready.
# while self._scheduled and not self._ready:
# handle = self._scheduled[0]
# handle = heapq.heappop(self._scheduled)
# handle._scheduled = False
# log.debug("Advancing time from %s to %s", self._time, handle._when)
# self._time = max(handle._when, self._time)
# self._ready.append(handle)
#
# # This is the only place where callbacks are actually *called*.
# # All other places just add them to ready. Note: We run all
# # currently scheduled callbacks, but not any callbacks scheduled
# # by callbacks run this time around -- they will be run the next
# # time (after another I/O poll). Use an idiom that is
# # thread-safe without using locks.
# ntodo = len(self._ready)
# for i in range(ntodo):
# handle = self._ready.popleft()
# if handle._cancelled:
# continue
# if self._debug:
# try:
# self._current_handle = handle
# t0 = self.time()
# handle._run()
# dt = self.time() - t0
# if dt >= self.slow_callback_duration:
# logger.warning("Executing %s took %.3f seconds", _format_handle(handle), dt)
# finally:
# self._current_handle = None
# else:
# handle._run()
# handle = None # Needed to break cycles when an exception occurs.
#
# def _write_to_self(self):
# pass
. Output only the next line. | loop = VirtualTimeEventLoop() |
Given the following code snippet before the placeholder: <|code_start|>
await message_loop(running=True)
agent = MailboxProcessor.start(worker)
async def asend(value: TSource) -> None:
agent.post(OnNext(value))
async def athrow(ex: Exception) -> None:
agent.post(OnError(ex))
async def aclose() -> None:
agent.post(OnCompleted)
return AsyncAnonymousObserver(asend, athrow, aclose)
def auto_detach_observer(
obv: AsyncObserver[TSource],
) -> Tuple[AsyncObserver[TSource], Callable[[Awaitable[AsyncDisposable]], Awaitable[AsyncDisposable]]]:
cts = CancellationTokenSource()
token = cts.token
async def worker(inbox: MailboxProcessor[Msg[TSource]]):
@tailrec_async
async def message_loop(disposables: List[AsyncDisposable]):
if token.is_cancellation_requested:
return
cmd = await inbox.receive()
<|code_end|>
, predict the next line using imports from the current file:
import logging
from asyncio import Future, iscoroutinefunction
from typing import Any, AsyncIterable, AsyncIterator, Awaitable, Callable, List, Optional, Tuple, TypeVar, cast
from expression.core import MailboxProcessor, TailCall, tailrec_async
from expression.system import AsyncDisposable, CancellationTokenSource, Disposable
from .msg import DisposableMsg, DisposeMsg, Msg
from .notification import MsgKind, Notification, OnCompleted, OnError, OnNext
from .types import AsyncObservable, AsyncObserver
from .utils import anoop
and context including class names, function names, and sometimes code from other files:
# Path: aioreactive/msg.py
# class Msg(SupportsMatch[TSource], ABC):
# class SourceMsg(Msg[Notification[TSource]], SupportsMatch[TSource]):
# class OtherMsg(Msg[Notification[TOther]], SupportsMatch[TOther]):
# class DisposableMsg(Msg[AsyncDisposable], SupportsMatch[AsyncDisposable]):
# class InnerObservableMsg(Msg[AsyncObservable[TSource]], SupportsMatch[AsyncObservable[TSource]]):
# class InnerCompletedMsg(Msg[TSource]):
# class CompletedMsg_(Msg[Any]):
# class DisposeMsg_(Msg[None]):
# def __match__(self, pattern: Any) -> Iterable[Notification[TSource]]:
# def __match__(self, pattern: Any) -> Iterable[Notification[TOther]]:
# def __match__(self, pattern: Any) -> Iterable[AsyncDisposable]:
# def __match__(self, pattern: Any) -> Iterable[AsyncObservable[TSource]]:
# def __match__(self, pattern: Any) -> Iterable[Key]:
# def __match__(self, pattern: Any) -> Iterable[bool]:
# def __match__(self, pattern: Any) -> Iterable[bool]:
#
# Path: aioreactive/notification.py
# class MsgKind(Enum):
# class Notification(Generic[TSource], ABC):
# class OnNext(Notification[TSource], SupportsMatch[TSource]):
# class OnError(Notification[TSource], SupportsMatch[Exception]):
# class _OnCompleted(Notification[TSource], SupportsMatch[bool]):
# ON_NEXT = 1
# ON_ERROR = 2
# ON_COMPLETED = 3
# def __init__(self, kind: MsgKind):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ) -> None:
# async def accept_observer(self, obv: AsyncObserver[TSource]) -> None:
# def __repr__(self) -> str:
# def __init__(self, value: TSource):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ) -> None:
# async def accept_observer(self, obv: AsyncObserver[TSource]) -> None:
# def __match__(self, pattern: Any) -> Iterable[TSource]:
# def __eq__(self, other: Any) -> bool:
# def __str__(self) -> str:
# def __init__(self, exception: Exception):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ):
# async def accept_observer(self, obv: AsyncObserver[TSource]):
# def __match__(self, pattern: Any) -> Iterable[Exception]:
# def __eq__(self, other: Any) -> bool:
# def __str__(self) -> str:
# def __init__(self):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ):
# async def accept_observer(self, obv: AsyncObserver[TSource]):
# def __match__(self, pattern: Any) -> Iterable[bool]:
# def __eq__(self, other: Any) -> bool:
# def __str__(self) -> str:
#
# Path: aioreactive/types.py
# class AsyncObservable(Generic[T_co]):
# __slots__ = ()
#
# @abstractmethod
# async def subscribe_async(self, observer: AsyncObserver[T_co]) -> AsyncDisposable:
# raise NotImplementedError
#
# class AsyncObserver(Generic[T_contra]):
# """An asynchronous observable."""
#
# __slots__ = ()
#
# @abstractmethod
# async def asend(self, value: T_contra) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def athrow(self, error: Exception) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def aclose(self) -> None:
# raise NotImplementedError
#
# Path: aioreactive/utils.py
# async def anoop(value: Optional[Any] = None):
# """Async no operation. Returns nothing"""
# pass
. Output only the next line. | if isinstance(cmd, DisposableMsg): |
Given the code snippet: <|code_start|> return AsyncAnonymousObserver(asend, athrow, aclose)
def auto_detach_observer(
obv: AsyncObserver[TSource],
) -> Tuple[AsyncObserver[TSource], Callable[[Awaitable[AsyncDisposable]], Awaitable[AsyncDisposable]]]:
cts = CancellationTokenSource()
token = cts.token
async def worker(inbox: MailboxProcessor[Msg[TSource]]):
@tailrec_async
async def message_loop(disposables: List[AsyncDisposable]):
if token.is_cancellation_requested:
return
cmd = await inbox.receive()
if isinstance(cmd, DisposableMsg):
disposables.append(cmd.disposable)
else:
for disp in disposables:
await disp.dispose_async()
return
return TailCall(disposables)
await message_loop([])
agent = MailboxProcessor.start(worker, token)
async def cancel():
cts.cancel()
<|code_end|>
, generate the next line using the imports in this file:
import logging
from asyncio import Future, iscoroutinefunction
from typing import Any, AsyncIterable, AsyncIterator, Awaitable, Callable, List, Optional, Tuple, TypeVar, cast
from expression.core import MailboxProcessor, TailCall, tailrec_async
from expression.system import AsyncDisposable, CancellationTokenSource, Disposable
from .msg import DisposableMsg, DisposeMsg, Msg
from .notification import MsgKind, Notification, OnCompleted, OnError, OnNext
from .types import AsyncObservable, AsyncObserver
from .utils import anoop
and context (functions, classes, or occasionally code) from other files:
# Path: aioreactive/msg.py
# class Msg(SupportsMatch[TSource], ABC):
# class SourceMsg(Msg[Notification[TSource]], SupportsMatch[TSource]):
# class OtherMsg(Msg[Notification[TOther]], SupportsMatch[TOther]):
# class DisposableMsg(Msg[AsyncDisposable], SupportsMatch[AsyncDisposable]):
# class InnerObservableMsg(Msg[AsyncObservable[TSource]], SupportsMatch[AsyncObservable[TSource]]):
# class InnerCompletedMsg(Msg[TSource]):
# class CompletedMsg_(Msg[Any]):
# class DisposeMsg_(Msg[None]):
# def __match__(self, pattern: Any) -> Iterable[Notification[TSource]]:
# def __match__(self, pattern: Any) -> Iterable[Notification[TOther]]:
# def __match__(self, pattern: Any) -> Iterable[AsyncDisposable]:
# def __match__(self, pattern: Any) -> Iterable[AsyncObservable[TSource]]:
# def __match__(self, pattern: Any) -> Iterable[Key]:
# def __match__(self, pattern: Any) -> Iterable[bool]:
# def __match__(self, pattern: Any) -> Iterable[bool]:
#
# Path: aioreactive/notification.py
# class MsgKind(Enum):
# class Notification(Generic[TSource], ABC):
# class OnNext(Notification[TSource], SupportsMatch[TSource]):
# class OnError(Notification[TSource], SupportsMatch[Exception]):
# class _OnCompleted(Notification[TSource], SupportsMatch[bool]):
# ON_NEXT = 1
# ON_ERROR = 2
# ON_COMPLETED = 3
# def __init__(self, kind: MsgKind):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ) -> None:
# async def accept_observer(self, obv: AsyncObserver[TSource]) -> None:
# def __repr__(self) -> str:
# def __init__(self, value: TSource):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ) -> None:
# async def accept_observer(self, obv: AsyncObserver[TSource]) -> None:
# def __match__(self, pattern: Any) -> Iterable[TSource]:
# def __eq__(self, other: Any) -> bool:
# def __str__(self) -> str:
# def __init__(self, exception: Exception):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ):
# async def accept_observer(self, obv: AsyncObserver[TSource]):
# def __match__(self, pattern: Any) -> Iterable[Exception]:
# def __eq__(self, other: Any) -> bool:
# def __str__(self) -> str:
# def __init__(self):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ):
# async def accept_observer(self, obv: AsyncObserver[TSource]):
# def __match__(self, pattern: Any) -> Iterable[bool]:
# def __eq__(self, other: Any) -> bool:
# def __str__(self) -> str:
#
# Path: aioreactive/types.py
# class AsyncObservable(Generic[T_co]):
# __slots__ = ()
#
# @abstractmethod
# async def subscribe_async(self, observer: AsyncObserver[T_co]) -> AsyncDisposable:
# raise NotImplementedError
#
# class AsyncObserver(Generic[T_contra]):
# """An asynchronous observable."""
#
# __slots__ = ()
#
# @abstractmethod
# async def asend(self, value: T_contra) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def athrow(self, error: Exception) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def aclose(self) -> None:
# raise NotImplementedError
#
# Path: aioreactive/utils.py
# async def anoop(value: Optional[Any] = None):
# """Async no operation. Returns nothing"""
# pass
. Output only the next line. | agent.post(DisposeMsg) |
Predict the next line for this snippet: <|code_start|> await disposable.dispose_async()
await msg.accept_observer(obv)
running = False
else:
await disposable.dispose_async()
await obv.aclose()
running = False
await message_loop(running=True)
agent = MailboxProcessor.start(worker)
async def asend(value: TSource) -> None:
agent.post(OnNext(value))
async def athrow(ex: Exception) -> None:
agent.post(OnError(ex))
async def aclose() -> None:
agent.post(OnCompleted)
return AsyncAnonymousObserver(asend, athrow, aclose)
def auto_detach_observer(
obv: AsyncObserver[TSource],
) -> Tuple[AsyncObserver[TSource], Callable[[Awaitable[AsyncDisposable]], Awaitable[AsyncDisposable]]]:
cts = CancellationTokenSource()
token = cts.token
<|code_end|>
with the help of current file imports:
import logging
from asyncio import Future, iscoroutinefunction
from typing import Any, AsyncIterable, AsyncIterator, Awaitable, Callable, List, Optional, Tuple, TypeVar, cast
from expression.core import MailboxProcessor, TailCall, tailrec_async
from expression.system import AsyncDisposable, CancellationTokenSource, Disposable
from .msg import DisposableMsg, DisposeMsg, Msg
from .notification import MsgKind, Notification, OnCompleted, OnError, OnNext
from .types import AsyncObservable, AsyncObserver
from .utils import anoop
and context from other files:
# Path: aioreactive/msg.py
# class Msg(SupportsMatch[TSource], ABC):
# class SourceMsg(Msg[Notification[TSource]], SupportsMatch[TSource]):
# class OtherMsg(Msg[Notification[TOther]], SupportsMatch[TOther]):
# class DisposableMsg(Msg[AsyncDisposable], SupportsMatch[AsyncDisposable]):
# class InnerObservableMsg(Msg[AsyncObservable[TSource]], SupportsMatch[AsyncObservable[TSource]]):
# class InnerCompletedMsg(Msg[TSource]):
# class CompletedMsg_(Msg[Any]):
# class DisposeMsg_(Msg[None]):
# def __match__(self, pattern: Any) -> Iterable[Notification[TSource]]:
# def __match__(self, pattern: Any) -> Iterable[Notification[TOther]]:
# def __match__(self, pattern: Any) -> Iterable[AsyncDisposable]:
# def __match__(self, pattern: Any) -> Iterable[AsyncObservable[TSource]]:
# def __match__(self, pattern: Any) -> Iterable[Key]:
# def __match__(self, pattern: Any) -> Iterable[bool]:
# def __match__(self, pattern: Any) -> Iterable[bool]:
#
# Path: aioreactive/notification.py
# class MsgKind(Enum):
# class Notification(Generic[TSource], ABC):
# class OnNext(Notification[TSource], SupportsMatch[TSource]):
# class OnError(Notification[TSource], SupportsMatch[Exception]):
# class _OnCompleted(Notification[TSource], SupportsMatch[bool]):
# ON_NEXT = 1
# ON_ERROR = 2
# ON_COMPLETED = 3
# def __init__(self, kind: MsgKind):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ) -> None:
# async def accept_observer(self, obv: AsyncObserver[TSource]) -> None:
# def __repr__(self) -> str:
# def __init__(self, value: TSource):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ) -> None:
# async def accept_observer(self, obv: AsyncObserver[TSource]) -> None:
# def __match__(self, pattern: Any) -> Iterable[TSource]:
# def __eq__(self, other: Any) -> bool:
# def __str__(self) -> str:
# def __init__(self, exception: Exception):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ):
# async def accept_observer(self, obv: AsyncObserver[TSource]):
# def __match__(self, pattern: Any) -> Iterable[Exception]:
# def __eq__(self, other: Any) -> bool:
# def __str__(self) -> str:
# def __init__(self):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ):
# async def accept_observer(self, obv: AsyncObserver[TSource]):
# def __match__(self, pattern: Any) -> Iterable[bool]:
# def __eq__(self, other: Any) -> bool:
# def __str__(self) -> str:
#
# Path: aioreactive/types.py
# class AsyncObservable(Generic[T_co]):
# __slots__ = ()
#
# @abstractmethod
# async def subscribe_async(self, observer: AsyncObserver[T_co]) -> AsyncDisposable:
# raise NotImplementedError
#
# class AsyncObserver(Generic[T_contra]):
# """An asynchronous observable."""
#
# __slots__ = ()
#
# @abstractmethod
# async def asend(self, value: T_contra) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def athrow(self, error: Exception) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def aclose(self) -> None:
# raise NotImplementedError
#
# Path: aioreactive/utils.py
# async def anoop(value: Optional[Any] = None):
# """Async no operation. Returns nothing"""
# pass
, which may contain function names, class names, or code. Output only the next line. | async def worker(inbox: MailboxProcessor[Msg[TSource]]): |
Given the following code snippet before the placeholder: <|code_start|>
async def athrow(self, error: Exception) -> None:
await self._fn(OnError(error))
async def aclose(self) -> None:
await self._fn(OnCompleted)
def noop() -> AsyncObserver[Any]:
return AsyncAnonymousObserver(anoop, anoop, anoop)
def safe_observer(obv: AsyncObserver[TSource], disposable: AsyncDisposable) -> AsyncObserver[TSource]:
"""Safe observer that wraps the given observer. Makes sure that
invocations are serialized and that the Rx grammar is not violated:
`(OnNext*(OnError|OnCompleted)?)`
I.e one or more OnNext, then terminates with a single OnError or
OnCompleted.
Args:
obv: Observer to serialize access to
disposable: Disposable to dispose when the observer closes.
"""
async def worker(inbox: MailboxProcessor[Notification[TSource]]):
async def message_loop(running: bool) -> None:
while running:
msg = await inbox.receive()
<|code_end|>
, predict the next line using imports from the current file:
import logging
from asyncio import Future, iscoroutinefunction
from typing import Any, AsyncIterable, AsyncIterator, Awaitable, Callable, List, Optional, Tuple, TypeVar, cast
from expression.core import MailboxProcessor, TailCall, tailrec_async
from expression.system import AsyncDisposable, CancellationTokenSource, Disposable
from .msg import DisposableMsg, DisposeMsg, Msg
from .notification import MsgKind, Notification, OnCompleted, OnError, OnNext
from .types import AsyncObservable, AsyncObserver
from .utils import anoop
and context including class names, function names, and sometimes code from other files:
# Path: aioreactive/msg.py
# class Msg(SupportsMatch[TSource], ABC):
# class SourceMsg(Msg[Notification[TSource]], SupportsMatch[TSource]):
# class OtherMsg(Msg[Notification[TOther]], SupportsMatch[TOther]):
# class DisposableMsg(Msg[AsyncDisposable], SupportsMatch[AsyncDisposable]):
# class InnerObservableMsg(Msg[AsyncObservable[TSource]], SupportsMatch[AsyncObservable[TSource]]):
# class InnerCompletedMsg(Msg[TSource]):
# class CompletedMsg_(Msg[Any]):
# class DisposeMsg_(Msg[None]):
# def __match__(self, pattern: Any) -> Iterable[Notification[TSource]]:
# def __match__(self, pattern: Any) -> Iterable[Notification[TOther]]:
# def __match__(self, pattern: Any) -> Iterable[AsyncDisposable]:
# def __match__(self, pattern: Any) -> Iterable[AsyncObservable[TSource]]:
# def __match__(self, pattern: Any) -> Iterable[Key]:
# def __match__(self, pattern: Any) -> Iterable[bool]:
# def __match__(self, pattern: Any) -> Iterable[bool]:
#
# Path: aioreactive/notification.py
# class MsgKind(Enum):
# class Notification(Generic[TSource], ABC):
# class OnNext(Notification[TSource], SupportsMatch[TSource]):
# class OnError(Notification[TSource], SupportsMatch[Exception]):
# class _OnCompleted(Notification[TSource], SupportsMatch[bool]):
# ON_NEXT = 1
# ON_ERROR = 2
# ON_COMPLETED = 3
# def __init__(self, kind: MsgKind):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ) -> None:
# async def accept_observer(self, obv: AsyncObserver[TSource]) -> None:
# def __repr__(self) -> str:
# def __init__(self, value: TSource):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ) -> None:
# async def accept_observer(self, obv: AsyncObserver[TSource]) -> None:
# def __match__(self, pattern: Any) -> Iterable[TSource]:
# def __eq__(self, other: Any) -> bool:
# def __str__(self) -> str:
# def __init__(self, exception: Exception):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ):
# async def accept_observer(self, obv: AsyncObserver[TSource]):
# def __match__(self, pattern: Any) -> Iterable[Exception]:
# def __eq__(self, other: Any) -> bool:
# def __str__(self) -> str:
# def __init__(self):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ):
# async def accept_observer(self, obv: AsyncObserver[TSource]):
# def __match__(self, pattern: Any) -> Iterable[bool]:
# def __eq__(self, other: Any) -> bool:
# def __str__(self) -> str:
#
# Path: aioreactive/types.py
# class AsyncObservable(Generic[T_co]):
# __slots__ = ()
#
# @abstractmethod
# async def subscribe_async(self, observer: AsyncObserver[T_co]) -> AsyncDisposable:
# raise NotImplementedError
#
# class AsyncObserver(Generic[T_contra]):
# """An asynchronous observable."""
#
# __slots__ = ()
#
# @abstractmethod
# async def asend(self, value: T_contra) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def athrow(self, error: Exception) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def aclose(self) -> None:
# raise NotImplementedError
#
# Path: aioreactive/utils.py
# async def anoop(value: Optional[Any] = None):
# """Async no operation. Returns nothing"""
# pass
. Output only the next line. | if msg.kind == MsgKind.ON_NEXT: |
Using the snippet: <|code_start|>
def __init__(
self,
asend: Callable[[TSource], Awaitable[None]] = anoop,
athrow: Callable[[Exception], Awaitable[None]] = anoop,
aclose: Callable[[], Awaitable[None]] = anoop,
) -> None:
super().__init__()
assert iscoroutinefunction(asend)
self._asend = asend
assert iscoroutinefunction(athrow)
self._athrow = athrow
assert iscoroutinefunction(aclose)
self._aclose = aclose
async def asend(self, value: TSource) -> None:
await self._asend(value)
async def athrow(self, error: Exception) -> None:
await self._athrow(error)
async def aclose(self) -> None:
await self._aclose()
class AsyncNotificationObserver(AsyncObserver[TSource]):
"""Observer created from an async notification processing function"""
<|code_end|>
, determine the next line of code. You have imports:
import logging
from asyncio import Future, iscoroutinefunction
from typing import Any, AsyncIterable, AsyncIterator, Awaitable, Callable, List, Optional, Tuple, TypeVar, cast
from expression.core import MailboxProcessor, TailCall, tailrec_async
from expression.system import AsyncDisposable, CancellationTokenSource, Disposable
from .msg import DisposableMsg, DisposeMsg, Msg
from .notification import MsgKind, Notification, OnCompleted, OnError, OnNext
from .types import AsyncObservable, AsyncObserver
from .utils import anoop
and context (class names, function names, or code) available:
# Path: aioreactive/msg.py
# class Msg(SupportsMatch[TSource], ABC):
# class SourceMsg(Msg[Notification[TSource]], SupportsMatch[TSource]):
# class OtherMsg(Msg[Notification[TOther]], SupportsMatch[TOther]):
# class DisposableMsg(Msg[AsyncDisposable], SupportsMatch[AsyncDisposable]):
# class InnerObservableMsg(Msg[AsyncObservable[TSource]], SupportsMatch[AsyncObservable[TSource]]):
# class InnerCompletedMsg(Msg[TSource]):
# class CompletedMsg_(Msg[Any]):
# class DisposeMsg_(Msg[None]):
# def __match__(self, pattern: Any) -> Iterable[Notification[TSource]]:
# def __match__(self, pattern: Any) -> Iterable[Notification[TOther]]:
# def __match__(self, pattern: Any) -> Iterable[AsyncDisposable]:
# def __match__(self, pattern: Any) -> Iterable[AsyncObservable[TSource]]:
# def __match__(self, pattern: Any) -> Iterable[Key]:
# def __match__(self, pattern: Any) -> Iterable[bool]:
# def __match__(self, pattern: Any) -> Iterable[bool]:
#
# Path: aioreactive/notification.py
# class MsgKind(Enum):
# class Notification(Generic[TSource], ABC):
# class OnNext(Notification[TSource], SupportsMatch[TSource]):
# class OnError(Notification[TSource], SupportsMatch[Exception]):
# class _OnCompleted(Notification[TSource], SupportsMatch[bool]):
# ON_NEXT = 1
# ON_ERROR = 2
# ON_COMPLETED = 3
# def __init__(self, kind: MsgKind):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ) -> None:
# async def accept_observer(self, obv: AsyncObserver[TSource]) -> None:
# def __repr__(self) -> str:
# def __init__(self, value: TSource):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ) -> None:
# async def accept_observer(self, obv: AsyncObserver[TSource]) -> None:
# def __match__(self, pattern: Any) -> Iterable[TSource]:
# def __eq__(self, other: Any) -> bool:
# def __str__(self) -> str:
# def __init__(self, exception: Exception):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ):
# async def accept_observer(self, obv: AsyncObserver[TSource]):
# def __match__(self, pattern: Any) -> Iterable[Exception]:
# def __eq__(self, other: Any) -> bool:
# def __str__(self) -> str:
# def __init__(self):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ):
# async def accept_observer(self, obv: AsyncObserver[TSource]):
# def __match__(self, pattern: Any) -> Iterable[bool]:
# def __eq__(self, other: Any) -> bool:
# def __str__(self) -> str:
#
# Path: aioreactive/types.py
# class AsyncObservable(Generic[T_co]):
# __slots__ = ()
#
# @abstractmethod
# async def subscribe_async(self, observer: AsyncObserver[T_co]) -> AsyncDisposable:
# raise NotImplementedError
#
# class AsyncObserver(Generic[T_contra]):
# """An asynchronous observable."""
#
# __slots__ = ()
#
# @abstractmethod
# async def asend(self, value: T_contra) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def athrow(self, error: Exception) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def aclose(self) -> None:
# raise NotImplementedError
#
# Path: aioreactive/utils.py
# async def anoop(value: Optional[Any] = None):
# """Async no operation. Returns nothing"""
# pass
. Output only the next line. | def __init__(self, fn: Callable[[Notification[TSource]], Awaitable[None]]) -> None: |
Based on the snippet: <|code_start|>
assert iscoroutinefunction(athrow)
self._athrow = athrow
assert iscoroutinefunction(aclose)
self._aclose = aclose
async def asend(self, value: TSource) -> None:
await self._asend(value)
async def athrow(self, error: Exception) -> None:
await self._athrow(error)
async def aclose(self) -> None:
await self._aclose()
class AsyncNotificationObserver(AsyncObserver[TSource]):
"""Observer created from an async notification processing function"""
def __init__(self, fn: Callable[[Notification[TSource]], Awaitable[None]]) -> None:
self._fn = fn
async def asend(self, value: TSource) -> None:
await self._fn(OnNext(value))
async def athrow(self, error: Exception) -> None:
await self._fn(OnError(error))
async def aclose(self) -> None:
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
from asyncio import Future, iscoroutinefunction
from typing import Any, AsyncIterable, AsyncIterator, Awaitable, Callable, List, Optional, Tuple, TypeVar, cast
from expression.core import MailboxProcessor, TailCall, tailrec_async
from expression.system import AsyncDisposable, CancellationTokenSource, Disposable
from .msg import DisposableMsg, DisposeMsg, Msg
from .notification import MsgKind, Notification, OnCompleted, OnError, OnNext
from .types import AsyncObservable, AsyncObserver
from .utils import anoop
and context (classes, functions, sometimes code) from other files:
# Path: aioreactive/msg.py
# class Msg(SupportsMatch[TSource], ABC):
# class SourceMsg(Msg[Notification[TSource]], SupportsMatch[TSource]):
# class OtherMsg(Msg[Notification[TOther]], SupportsMatch[TOther]):
# class DisposableMsg(Msg[AsyncDisposable], SupportsMatch[AsyncDisposable]):
# class InnerObservableMsg(Msg[AsyncObservable[TSource]], SupportsMatch[AsyncObservable[TSource]]):
# class InnerCompletedMsg(Msg[TSource]):
# class CompletedMsg_(Msg[Any]):
# class DisposeMsg_(Msg[None]):
# def __match__(self, pattern: Any) -> Iterable[Notification[TSource]]:
# def __match__(self, pattern: Any) -> Iterable[Notification[TOther]]:
# def __match__(self, pattern: Any) -> Iterable[AsyncDisposable]:
# def __match__(self, pattern: Any) -> Iterable[AsyncObservable[TSource]]:
# def __match__(self, pattern: Any) -> Iterable[Key]:
# def __match__(self, pattern: Any) -> Iterable[bool]:
# def __match__(self, pattern: Any) -> Iterable[bool]:
#
# Path: aioreactive/notification.py
# class MsgKind(Enum):
# class Notification(Generic[TSource], ABC):
# class OnNext(Notification[TSource], SupportsMatch[TSource]):
# class OnError(Notification[TSource], SupportsMatch[Exception]):
# class _OnCompleted(Notification[TSource], SupportsMatch[bool]):
# ON_NEXT = 1
# ON_ERROR = 2
# ON_COMPLETED = 3
# def __init__(self, kind: MsgKind):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ) -> None:
# async def accept_observer(self, obv: AsyncObserver[TSource]) -> None:
# def __repr__(self) -> str:
# def __init__(self, value: TSource):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ) -> None:
# async def accept_observer(self, obv: AsyncObserver[TSource]) -> None:
# def __match__(self, pattern: Any) -> Iterable[TSource]:
# def __eq__(self, other: Any) -> bool:
# def __str__(self) -> str:
# def __init__(self, exception: Exception):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ):
# async def accept_observer(self, obv: AsyncObserver[TSource]):
# def __match__(self, pattern: Any) -> Iterable[Exception]:
# def __eq__(self, other: Any) -> bool:
# def __str__(self) -> str:
# def __init__(self):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ):
# async def accept_observer(self, obv: AsyncObserver[TSource]):
# def __match__(self, pattern: Any) -> Iterable[bool]:
# def __eq__(self, other: Any) -> bool:
# def __str__(self) -> str:
#
# Path: aioreactive/types.py
# class AsyncObservable(Generic[T_co]):
# __slots__ = ()
#
# @abstractmethod
# async def subscribe_async(self, observer: AsyncObserver[T_co]) -> AsyncDisposable:
# raise NotImplementedError
#
# class AsyncObserver(Generic[T_contra]):
# """An asynchronous observable."""
#
# __slots__ = ()
#
# @abstractmethod
# async def asend(self, value: T_contra) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def athrow(self, error: Exception) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def aclose(self) -> None:
# raise NotImplementedError
#
# Path: aioreactive/utils.py
# async def anoop(value: Optional[Any] = None):
# """Async no operation. Returns nothing"""
# pass
. Output only the next line. | await self._fn(OnCompleted) |
Based on the snippet: <|code_start|> super().__init__()
assert iscoroutinefunction(asend)
self._asend = asend
assert iscoroutinefunction(athrow)
self._athrow = athrow
assert iscoroutinefunction(aclose)
self._aclose = aclose
async def asend(self, value: TSource) -> None:
await self._asend(value)
async def athrow(self, error: Exception) -> None:
await self._athrow(error)
async def aclose(self) -> None:
await self._aclose()
class AsyncNotificationObserver(AsyncObserver[TSource]):
"""Observer created from an async notification processing function"""
def __init__(self, fn: Callable[[Notification[TSource]], Awaitable[None]]) -> None:
self._fn = fn
async def asend(self, value: TSource) -> None:
await self._fn(OnNext(value))
async def athrow(self, error: Exception) -> None:
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
from asyncio import Future, iscoroutinefunction
from typing import Any, AsyncIterable, AsyncIterator, Awaitable, Callable, List, Optional, Tuple, TypeVar, cast
from expression.core import MailboxProcessor, TailCall, tailrec_async
from expression.system import AsyncDisposable, CancellationTokenSource, Disposable
from .msg import DisposableMsg, DisposeMsg, Msg
from .notification import MsgKind, Notification, OnCompleted, OnError, OnNext
from .types import AsyncObservable, AsyncObserver
from .utils import anoop
and context (classes, functions, sometimes code) from other files:
# Path: aioreactive/msg.py
# class Msg(SupportsMatch[TSource], ABC):
# class SourceMsg(Msg[Notification[TSource]], SupportsMatch[TSource]):
# class OtherMsg(Msg[Notification[TOther]], SupportsMatch[TOther]):
# class DisposableMsg(Msg[AsyncDisposable], SupportsMatch[AsyncDisposable]):
# class InnerObservableMsg(Msg[AsyncObservable[TSource]], SupportsMatch[AsyncObservable[TSource]]):
# class InnerCompletedMsg(Msg[TSource]):
# class CompletedMsg_(Msg[Any]):
# class DisposeMsg_(Msg[None]):
# def __match__(self, pattern: Any) -> Iterable[Notification[TSource]]:
# def __match__(self, pattern: Any) -> Iterable[Notification[TOther]]:
# def __match__(self, pattern: Any) -> Iterable[AsyncDisposable]:
# def __match__(self, pattern: Any) -> Iterable[AsyncObservable[TSource]]:
# def __match__(self, pattern: Any) -> Iterable[Key]:
# def __match__(self, pattern: Any) -> Iterable[bool]:
# def __match__(self, pattern: Any) -> Iterable[bool]:
#
# Path: aioreactive/notification.py
# class MsgKind(Enum):
# class Notification(Generic[TSource], ABC):
# class OnNext(Notification[TSource], SupportsMatch[TSource]):
# class OnError(Notification[TSource], SupportsMatch[Exception]):
# class _OnCompleted(Notification[TSource], SupportsMatch[bool]):
# ON_NEXT = 1
# ON_ERROR = 2
# ON_COMPLETED = 3
# def __init__(self, kind: MsgKind):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ) -> None:
# async def accept_observer(self, obv: AsyncObserver[TSource]) -> None:
# def __repr__(self) -> str:
# def __init__(self, value: TSource):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ) -> None:
# async def accept_observer(self, obv: AsyncObserver[TSource]) -> None:
# def __match__(self, pattern: Any) -> Iterable[TSource]:
# def __eq__(self, other: Any) -> bool:
# def __str__(self) -> str:
# def __init__(self, exception: Exception):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ):
# async def accept_observer(self, obv: AsyncObserver[TSource]):
# def __match__(self, pattern: Any) -> Iterable[Exception]:
# def __eq__(self, other: Any) -> bool:
# def __str__(self) -> str:
# def __init__(self):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ):
# async def accept_observer(self, obv: AsyncObserver[TSource]):
# def __match__(self, pattern: Any) -> Iterable[bool]:
# def __eq__(self, other: Any) -> bool:
# def __str__(self) -> str:
#
# Path: aioreactive/types.py
# class AsyncObservable(Generic[T_co]):
# __slots__ = ()
#
# @abstractmethod
# async def subscribe_async(self, observer: AsyncObserver[T_co]) -> AsyncDisposable:
# raise NotImplementedError
#
# class AsyncObserver(Generic[T_contra]):
# """An asynchronous observable."""
#
# __slots__ = ()
#
# @abstractmethod
# async def asend(self, value: T_contra) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def athrow(self, error: Exception) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def aclose(self) -> None:
# raise NotImplementedError
#
# Path: aioreactive/utils.py
# async def anoop(value: Optional[Any] = None):
# """Async no operation. Returns nothing"""
# pass
. Output only the next line. | await self._fn(OnError(error)) |
Here is a snippet: <|code_start|> athrow: Callable[[Exception], Awaitable[None]] = anoop,
aclose: Callable[[], Awaitable[None]] = anoop,
) -> None:
super().__init__()
assert iscoroutinefunction(asend)
self._asend = asend
assert iscoroutinefunction(athrow)
self._athrow = athrow
assert iscoroutinefunction(aclose)
self._aclose = aclose
async def asend(self, value: TSource) -> None:
await self._asend(value)
async def athrow(self, error: Exception) -> None:
await self._athrow(error)
async def aclose(self) -> None:
await self._aclose()
class AsyncNotificationObserver(AsyncObserver[TSource]):
"""Observer created from an async notification processing function"""
def __init__(self, fn: Callable[[Notification[TSource]], Awaitable[None]]) -> None:
self._fn = fn
async def asend(self, value: TSource) -> None:
<|code_end|>
. Write the next line using the current file imports:
import logging
from asyncio import Future, iscoroutinefunction
from typing import Any, AsyncIterable, AsyncIterator, Awaitable, Callable, List, Optional, Tuple, TypeVar, cast
from expression.core import MailboxProcessor, TailCall, tailrec_async
from expression.system import AsyncDisposable, CancellationTokenSource, Disposable
from .msg import DisposableMsg, DisposeMsg, Msg
from .notification import MsgKind, Notification, OnCompleted, OnError, OnNext
from .types import AsyncObservable, AsyncObserver
from .utils import anoop
and context from other files:
# Path: aioreactive/msg.py
# class Msg(SupportsMatch[TSource], ABC):
# class SourceMsg(Msg[Notification[TSource]], SupportsMatch[TSource]):
# class OtherMsg(Msg[Notification[TOther]], SupportsMatch[TOther]):
# class DisposableMsg(Msg[AsyncDisposable], SupportsMatch[AsyncDisposable]):
# class InnerObservableMsg(Msg[AsyncObservable[TSource]], SupportsMatch[AsyncObservable[TSource]]):
# class InnerCompletedMsg(Msg[TSource]):
# class CompletedMsg_(Msg[Any]):
# class DisposeMsg_(Msg[None]):
# def __match__(self, pattern: Any) -> Iterable[Notification[TSource]]:
# def __match__(self, pattern: Any) -> Iterable[Notification[TOther]]:
# def __match__(self, pattern: Any) -> Iterable[AsyncDisposable]:
# def __match__(self, pattern: Any) -> Iterable[AsyncObservable[TSource]]:
# def __match__(self, pattern: Any) -> Iterable[Key]:
# def __match__(self, pattern: Any) -> Iterable[bool]:
# def __match__(self, pattern: Any) -> Iterable[bool]:
#
# Path: aioreactive/notification.py
# class MsgKind(Enum):
# class Notification(Generic[TSource], ABC):
# class OnNext(Notification[TSource], SupportsMatch[TSource]):
# class OnError(Notification[TSource], SupportsMatch[Exception]):
# class _OnCompleted(Notification[TSource], SupportsMatch[bool]):
# ON_NEXT = 1
# ON_ERROR = 2
# ON_COMPLETED = 3
# def __init__(self, kind: MsgKind):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ) -> None:
# async def accept_observer(self, obv: AsyncObserver[TSource]) -> None:
# def __repr__(self) -> str:
# def __init__(self, value: TSource):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ) -> None:
# async def accept_observer(self, obv: AsyncObserver[TSource]) -> None:
# def __match__(self, pattern: Any) -> Iterable[TSource]:
# def __eq__(self, other: Any) -> bool:
# def __str__(self) -> str:
# def __init__(self, exception: Exception):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ):
# async def accept_observer(self, obv: AsyncObserver[TSource]):
# def __match__(self, pattern: Any) -> Iterable[Exception]:
# def __eq__(self, other: Any) -> bool:
# def __str__(self) -> str:
# def __init__(self):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ):
# async def accept_observer(self, obv: AsyncObserver[TSource]):
# def __match__(self, pattern: Any) -> Iterable[bool]:
# def __eq__(self, other: Any) -> bool:
# def __str__(self) -> str:
#
# Path: aioreactive/types.py
# class AsyncObservable(Generic[T_co]):
# __slots__ = ()
#
# @abstractmethod
# async def subscribe_async(self, observer: AsyncObserver[T_co]) -> AsyncDisposable:
# raise NotImplementedError
#
# class AsyncObserver(Generic[T_contra]):
# """An asynchronous observable."""
#
# __slots__ = ()
#
# @abstractmethod
# async def asend(self, value: T_contra) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def athrow(self, error: Exception) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def aclose(self) -> None:
# raise NotImplementedError
#
# Path: aioreactive/utils.py
# async def anoop(value: Optional[Any] = None):
# """Async no operation. Returns nothing"""
# pass
, which may include functions, classes, or code. Output only the next line. | await self._fn(OnNext(value)) |
Given the code snippet: <|code_start|>
log = logging.getLogger(__name__)
TSource = TypeVar("TSource")
class AsyncIteratorObserver(AsyncObserver[TSource], AsyncIterable[TSource], AsyncDisposable):
"""An async observer that might be iterated asynchronously."""
<|code_end|>
, generate the next line using the imports in this file:
import logging
from asyncio import Future, iscoroutinefunction
from typing import Any, AsyncIterable, AsyncIterator, Awaitable, Callable, List, Optional, Tuple, TypeVar, cast
from expression.core import MailboxProcessor, TailCall, tailrec_async
from expression.system import AsyncDisposable, CancellationTokenSource, Disposable
from .msg import DisposableMsg, DisposeMsg, Msg
from .notification import MsgKind, Notification, OnCompleted, OnError, OnNext
from .types import AsyncObservable, AsyncObserver
from .utils import anoop
and context (functions, classes, or occasionally code) from other files:
# Path: aioreactive/msg.py
# class Msg(SupportsMatch[TSource], ABC):
# class SourceMsg(Msg[Notification[TSource]], SupportsMatch[TSource]):
# class OtherMsg(Msg[Notification[TOther]], SupportsMatch[TOther]):
# class DisposableMsg(Msg[AsyncDisposable], SupportsMatch[AsyncDisposable]):
# class InnerObservableMsg(Msg[AsyncObservable[TSource]], SupportsMatch[AsyncObservable[TSource]]):
# class InnerCompletedMsg(Msg[TSource]):
# class CompletedMsg_(Msg[Any]):
# class DisposeMsg_(Msg[None]):
# def __match__(self, pattern: Any) -> Iterable[Notification[TSource]]:
# def __match__(self, pattern: Any) -> Iterable[Notification[TOther]]:
# def __match__(self, pattern: Any) -> Iterable[AsyncDisposable]:
# def __match__(self, pattern: Any) -> Iterable[AsyncObservable[TSource]]:
# def __match__(self, pattern: Any) -> Iterable[Key]:
# def __match__(self, pattern: Any) -> Iterable[bool]:
# def __match__(self, pattern: Any) -> Iterable[bool]:
#
# Path: aioreactive/notification.py
# class MsgKind(Enum):
# class Notification(Generic[TSource], ABC):
# class OnNext(Notification[TSource], SupportsMatch[TSource]):
# class OnError(Notification[TSource], SupportsMatch[Exception]):
# class _OnCompleted(Notification[TSource], SupportsMatch[bool]):
# ON_NEXT = 1
# ON_ERROR = 2
# ON_COMPLETED = 3
# def __init__(self, kind: MsgKind):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ) -> None:
# async def accept_observer(self, obv: AsyncObserver[TSource]) -> None:
# def __repr__(self) -> str:
# def __init__(self, value: TSource):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ) -> None:
# async def accept_observer(self, obv: AsyncObserver[TSource]) -> None:
# def __match__(self, pattern: Any) -> Iterable[TSource]:
# def __eq__(self, other: Any) -> bool:
# def __str__(self) -> str:
# def __init__(self, exception: Exception):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ):
# async def accept_observer(self, obv: AsyncObserver[TSource]):
# def __match__(self, pattern: Any) -> Iterable[Exception]:
# def __eq__(self, other: Any) -> bool:
# def __str__(self) -> str:
# def __init__(self):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ):
# async def accept_observer(self, obv: AsyncObserver[TSource]):
# def __match__(self, pattern: Any) -> Iterable[bool]:
# def __eq__(self, other: Any) -> bool:
# def __str__(self) -> str:
#
# Path: aioreactive/types.py
# class AsyncObservable(Generic[T_co]):
# __slots__ = ()
#
# @abstractmethod
# async def subscribe_async(self, observer: AsyncObserver[T_co]) -> AsyncDisposable:
# raise NotImplementedError
#
# class AsyncObserver(Generic[T_contra]):
# """An asynchronous observable."""
#
# __slots__ = ()
#
# @abstractmethod
# async def asend(self, value: T_contra) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def athrow(self, error: Exception) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def aclose(self) -> None:
# raise NotImplementedError
#
# Path: aioreactive/utils.py
# async def anoop(value: Optional[Any] = None):
# """Async no operation. Returns nothing"""
# pass
. Output only the next line. | def __init__(self, source: AsyncObservable[TSource]) -> None: |
Given snippet: <|code_start|> self._pull.set_result(True)
# Wake up any awaiters
for awaiter in self._awaiters[:1]:
awaiter.set_result(True)
return value
async def dispose_async(self) -> None:
if self._subscription is not None:
await self._subscription.dispose_async()
self._subscription = None
def __aiter__(self) -> AsyncIterator[TSource]:
log.debug("AsyncIteratorObserver:__aiter__")
return self
async def __anext__(self) -> TSource:
log.debug("AsyncIteratorObserver:__anext__()")
return await self.wait_for_push()
class AsyncAnonymousObserver(AsyncObserver[TSource]):
"""An anonymous AsyncObserver.
Creates as sink where the implementation is provided by three
optional and anonymous functions, asend, athrow and aclose. Used for
listening to a source."""
def __init__(
self,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
from asyncio import Future, iscoroutinefunction
from typing import Any, AsyncIterable, AsyncIterator, Awaitable, Callable, List, Optional, Tuple, TypeVar, cast
from expression.core import MailboxProcessor, TailCall, tailrec_async
from expression.system import AsyncDisposable, CancellationTokenSource, Disposable
from .msg import DisposableMsg, DisposeMsg, Msg
from .notification import MsgKind, Notification, OnCompleted, OnError, OnNext
from .types import AsyncObservable, AsyncObserver
from .utils import anoop
and context:
# Path: aioreactive/msg.py
# class Msg(SupportsMatch[TSource], ABC):
# class SourceMsg(Msg[Notification[TSource]], SupportsMatch[TSource]):
# class OtherMsg(Msg[Notification[TOther]], SupportsMatch[TOther]):
# class DisposableMsg(Msg[AsyncDisposable], SupportsMatch[AsyncDisposable]):
# class InnerObservableMsg(Msg[AsyncObservable[TSource]], SupportsMatch[AsyncObservable[TSource]]):
# class InnerCompletedMsg(Msg[TSource]):
# class CompletedMsg_(Msg[Any]):
# class DisposeMsg_(Msg[None]):
# def __match__(self, pattern: Any) -> Iterable[Notification[TSource]]:
# def __match__(self, pattern: Any) -> Iterable[Notification[TOther]]:
# def __match__(self, pattern: Any) -> Iterable[AsyncDisposable]:
# def __match__(self, pattern: Any) -> Iterable[AsyncObservable[TSource]]:
# def __match__(self, pattern: Any) -> Iterable[Key]:
# def __match__(self, pattern: Any) -> Iterable[bool]:
# def __match__(self, pattern: Any) -> Iterable[bool]:
#
# Path: aioreactive/notification.py
# class MsgKind(Enum):
# class Notification(Generic[TSource], ABC):
# class OnNext(Notification[TSource], SupportsMatch[TSource]):
# class OnError(Notification[TSource], SupportsMatch[Exception]):
# class _OnCompleted(Notification[TSource], SupportsMatch[bool]):
# ON_NEXT = 1
# ON_ERROR = 2
# ON_COMPLETED = 3
# def __init__(self, kind: MsgKind):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ) -> None:
# async def accept_observer(self, obv: AsyncObserver[TSource]) -> None:
# def __repr__(self) -> str:
# def __init__(self, value: TSource):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ) -> None:
# async def accept_observer(self, obv: AsyncObserver[TSource]) -> None:
# def __match__(self, pattern: Any) -> Iterable[TSource]:
# def __eq__(self, other: Any) -> bool:
# def __str__(self) -> str:
# def __init__(self, exception: Exception):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ):
# async def accept_observer(self, obv: AsyncObserver[TSource]):
# def __match__(self, pattern: Any) -> Iterable[Exception]:
# def __eq__(self, other: Any) -> bool:
# def __str__(self) -> str:
# def __init__(self):
# async def accept(
# self,
# asend: Callable[[TSource], Awaitable[None]],
# athrow: Callable[[Exception], Awaitable[None]],
# aclose: Callable[[], Awaitable[None]],
# ):
# async def accept_observer(self, obv: AsyncObserver[TSource]):
# def __match__(self, pattern: Any) -> Iterable[bool]:
# def __eq__(self, other: Any) -> bool:
# def __str__(self) -> str:
#
# Path: aioreactive/types.py
# class AsyncObservable(Generic[T_co]):
# __slots__ = ()
#
# @abstractmethod
# async def subscribe_async(self, observer: AsyncObserver[T_co]) -> AsyncDisposable:
# raise NotImplementedError
#
# class AsyncObserver(Generic[T_contra]):
# """An asynchronous observable."""
#
# __slots__ = ()
#
# @abstractmethod
# async def asend(self, value: T_contra) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def athrow(self, error: Exception) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def aclose(self) -> None:
# raise NotImplementedError
#
# Path: aioreactive/utils.py
# async def anoop(value: Optional[Any] = None):
# """Async no operation. Returns nothing"""
# pass
which might include code, classes, or functions. Output only the next line. | asend: Callable[[TSource], Awaitable[None]] = anoop, |
Predict the next line after this snippet: <|code_start|>
TSource = TypeVar("TSource")
log = logging.getLogger(__name__)
def canceller() -> Tuple[AsyncDisposable, CancellationToken]:
cts = CancellationTokenSource()
async def cancel() -> None:
log.debug("cancller, cancelling!")
cts.cancel()
return AsyncDisposable.create(cancel), cts.token
def create(subscribe: Callable[[AsyncObserver[TSource]], Awaitable[AsyncDisposable]]) -> AsyncObservable[TSource]:
"""Create an async observable.
Creates an `AsyncObservable[TSource]` from the given subscribe
function.
"""
<|code_end|>
using the current file's imports:
import asyncio
import logging
from asyncio import Future
from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Optional, Tuple, TypeVar
from expression.core import TailCallResult, aiotools, tailrec_async
from expression.core.fn import TailCall
from expression.system import AsyncDisposable, CancellationToken, CancellationTokenSource
from .observables import AsyncAnonymousObservable
from .observers import AsyncObserver, safe_observer
from .types import AsyncObservable
and any relevant context from other files:
# Path: aioreactive/observables.py
# class AsyncAnonymousObservable(AsyncObservable[TSource]):
#
# """An anonymous AsyncObservable.
#
# Uses a custom subscribe method.
# """
#
# def __init__(self, subscribe: Callable[[AsyncObserver[TSource]], Awaitable[AsyncDisposable]]) -> None:
# self._subscribe = subscribe
#
# async def subscribe_async(self, observer: AsyncObserver[TSource]) -> AsyncDisposable:
# log.debug("AsyncAnonymousObservable:subscribe_async(%s)", self._subscribe)
# return await self._subscribe(observer)
#
# Path: aioreactive/observers.py
# class AsyncIteratorObserver(AsyncObserver[TSource], AsyncIterable[TSource], AsyncDisposable):
# class AsyncAnonymousObserver(AsyncObserver[TSource]):
# class AsyncNotificationObserver(AsyncObserver[TSource]):
# class AsyncAwaitableObserver(Future[TSource], AsyncObserver[TSource], Disposable):
# def __init__(self, source: AsyncObservable[TSource]) -> None:
# async def asend(self, value: TSource) -> None:
# async def athrow(self, error: Exception) -> None:
# async def aclose(self) -> None:
# async def _wait_for_pull(self) -> None:
# async def _serialize_access(self) -> None:
# async def wait_for_push(self) -> TSource:
# async def dispose_async(self) -> None:
# def __aiter__(self) -> AsyncIterator[TSource]:
# async def __anext__(self) -> TSource:
# def __init__(
# self,
# asend: Callable[[TSource], Awaitable[None]] = anoop,
# athrow: Callable[[Exception], Awaitable[None]] = anoop,
# aclose: Callable[[], Awaitable[None]] = anoop,
# ) -> None:
# async def asend(self, value: TSource) -> None:
# async def athrow(self, error: Exception) -> None:
# async def aclose(self) -> None:
# def __init__(self, fn: Callable[[Notification[TSource]], Awaitable[None]]) -> None:
# async def asend(self, value: TSource) -> None:
# async def athrow(self, error: Exception) -> None:
# async def aclose(self) -> None:
# def noop() -> AsyncObserver[Any]:
# def safe_observer(obv: AsyncObserver[TSource], disposable: AsyncDisposable) -> AsyncObserver[TSource]:
# async def worker(inbox: MailboxProcessor[Notification[TSource]]):
# async def message_loop(running: bool) -> None:
# async def asend(value: TSource) -> None:
# async def athrow(ex: Exception) -> None:
# async def aclose() -> None:
# def auto_detach_observer(
# obv: AsyncObserver[TSource],
# ) -> Tuple[AsyncObserver[TSource], Callable[[Awaitable[AsyncDisposable]], Awaitable[AsyncDisposable]]]:
# async def worker(inbox: MailboxProcessor[Msg[TSource]]):
# async def message_loop(disposables: List[AsyncDisposable]):
# async def cancel():
# async def auto_detach(async_disposable: Awaitable[AsyncDisposable]):
# def __init__(
# self,
# asend: Callable[[TSource], Awaitable[None]] = anoop,
# athrow: Callable[[Exception], Awaitable[None]] = anoop,
# aclose: Callable[[], Awaitable[None]] = anoop,
# ) -> None:
# async def asend(self, value: TSource) -> None:
# async def athrow(self, error: Exception) -> None:
# async def aclose(self) -> None:
# def dispose(self) -> None:
#
# Path: aioreactive/types.py
# class AsyncObservable(Generic[T_co]):
# __slots__ = ()
#
# @abstractmethod
# async def subscribe_async(self, observer: AsyncObserver[T_co]) -> AsyncDisposable:
# raise NotImplementedError
. Output only the next line. | return AsyncAnonymousObservable(subscribe) |
Given the code snippet: <|code_start|>
TSource = TypeVar("TSource")
log = logging.getLogger(__name__)
def canceller() -> Tuple[AsyncDisposable, CancellationToken]:
cts = CancellationTokenSource()
async def cancel() -> None:
log.debug("cancller, cancelling!")
cts.cancel()
return AsyncDisposable.create(cancel), cts.token
<|code_end|>
, generate the next line using the imports in this file:
import asyncio
import logging
from asyncio import Future
from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Optional, Tuple, TypeVar
from expression.core import TailCallResult, aiotools, tailrec_async
from expression.core.fn import TailCall
from expression.system import AsyncDisposable, CancellationToken, CancellationTokenSource
from .observables import AsyncAnonymousObservable
from .observers import AsyncObserver, safe_observer
from .types import AsyncObservable
and context (functions, classes, or occasionally code) from other files:
# Path: aioreactive/observables.py
# class AsyncAnonymousObservable(AsyncObservable[TSource]):
#
# """An anonymous AsyncObservable.
#
# Uses a custom subscribe method.
# """
#
# def __init__(self, subscribe: Callable[[AsyncObserver[TSource]], Awaitable[AsyncDisposable]]) -> None:
# self._subscribe = subscribe
#
# async def subscribe_async(self, observer: AsyncObserver[TSource]) -> AsyncDisposable:
# log.debug("AsyncAnonymousObservable:subscribe_async(%s)", self._subscribe)
# return await self._subscribe(observer)
#
# Path: aioreactive/observers.py
# class AsyncIteratorObserver(AsyncObserver[TSource], AsyncIterable[TSource], AsyncDisposable):
# class AsyncAnonymousObserver(AsyncObserver[TSource]):
# class AsyncNotificationObserver(AsyncObserver[TSource]):
# class AsyncAwaitableObserver(Future[TSource], AsyncObserver[TSource], Disposable):
# def __init__(self, source: AsyncObservable[TSource]) -> None:
# async def asend(self, value: TSource) -> None:
# async def athrow(self, error: Exception) -> None:
# async def aclose(self) -> None:
# async def _wait_for_pull(self) -> None:
# async def _serialize_access(self) -> None:
# async def wait_for_push(self) -> TSource:
# async def dispose_async(self) -> None:
# def __aiter__(self) -> AsyncIterator[TSource]:
# async def __anext__(self) -> TSource:
# def __init__(
# self,
# asend: Callable[[TSource], Awaitable[None]] = anoop,
# athrow: Callable[[Exception], Awaitable[None]] = anoop,
# aclose: Callable[[], Awaitable[None]] = anoop,
# ) -> None:
# async def asend(self, value: TSource) -> None:
# async def athrow(self, error: Exception) -> None:
# async def aclose(self) -> None:
# def __init__(self, fn: Callable[[Notification[TSource]], Awaitable[None]]) -> None:
# async def asend(self, value: TSource) -> None:
# async def athrow(self, error: Exception) -> None:
# async def aclose(self) -> None:
# def noop() -> AsyncObserver[Any]:
# def safe_observer(obv: AsyncObserver[TSource], disposable: AsyncDisposable) -> AsyncObserver[TSource]:
# async def worker(inbox: MailboxProcessor[Notification[TSource]]):
# async def message_loop(running: bool) -> None:
# async def asend(value: TSource) -> None:
# async def athrow(ex: Exception) -> None:
# async def aclose() -> None:
# def auto_detach_observer(
# obv: AsyncObserver[TSource],
# ) -> Tuple[AsyncObserver[TSource], Callable[[Awaitable[AsyncDisposable]], Awaitable[AsyncDisposable]]]:
# async def worker(inbox: MailboxProcessor[Msg[TSource]]):
# async def message_loop(disposables: List[AsyncDisposable]):
# async def cancel():
# async def auto_detach(async_disposable: Awaitable[AsyncDisposable]):
# def __init__(
# self,
# asend: Callable[[TSource], Awaitable[None]] = anoop,
# athrow: Callable[[Exception], Awaitable[None]] = anoop,
# aclose: Callable[[], Awaitable[None]] = anoop,
# ) -> None:
# async def asend(self, value: TSource) -> None:
# async def athrow(self, error: Exception) -> None:
# async def aclose(self) -> None:
# def dispose(self) -> None:
#
# Path: aioreactive/types.py
# class AsyncObservable(Generic[T_co]):
# __slots__ = ()
#
# @abstractmethod
# async def subscribe_async(self, observer: AsyncObserver[T_co]) -> AsyncDisposable:
# raise NotImplementedError
. Output only the next line. | def create(subscribe: Callable[[AsyncObserver[TSource]], Awaitable[AsyncDisposable]]) -> AsyncObservable[TSource]: |
Based on the snippet: <|code_start|>log = logging.getLogger(__name__)
def canceller() -> Tuple[AsyncDisposable, CancellationToken]:
cts = CancellationTokenSource()
async def cancel() -> None:
log.debug("cancller, cancelling!")
cts.cancel()
return AsyncDisposable.create(cancel), cts.token
def create(subscribe: Callable[[AsyncObserver[TSource]], Awaitable[AsyncDisposable]]) -> AsyncObservable[TSource]:
"""Create an async observable.
Creates an `AsyncObservable[TSource]` from the given subscribe
function.
"""
return AsyncAnonymousObservable(subscribe)
def of_async_worker(worker: Callable[[AsyncObserver[Any], CancellationToken], Awaitable[None]]) -> AsyncObservable[Any]:
"""Create async observable from async worker function"""
log.debug("of_async_worker()")
async def subscribe_async(aobv: AsyncObserver[Any]) -> AsyncDisposable:
log.debug("of_async_worker:subscribe_async()")
disposable, token = canceller()
<|code_end|>
, predict the immediate next line with the help of imports:
import asyncio
import logging
from asyncio import Future
from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Optional, Tuple, TypeVar
from expression.core import TailCallResult, aiotools, tailrec_async
from expression.core.fn import TailCall
from expression.system import AsyncDisposable, CancellationToken, CancellationTokenSource
from .observables import AsyncAnonymousObservable
from .observers import AsyncObserver, safe_observer
from .types import AsyncObservable
and context (classes, functions, sometimes code) from other files:
# Path: aioreactive/observables.py
# class AsyncAnonymousObservable(AsyncObservable[TSource]):
#
# """An anonymous AsyncObservable.
#
# Uses a custom subscribe method.
# """
#
# def __init__(self, subscribe: Callable[[AsyncObserver[TSource]], Awaitable[AsyncDisposable]]) -> None:
# self._subscribe = subscribe
#
# async def subscribe_async(self, observer: AsyncObserver[TSource]) -> AsyncDisposable:
# log.debug("AsyncAnonymousObservable:subscribe_async(%s)", self._subscribe)
# return await self._subscribe(observer)
#
# Path: aioreactive/observers.py
# class AsyncIteratorObserver(AsyncObserver[TSource], AsyncIterable[TSource], AsyncDisposable):
# class AsyncAnonymousObserver(AsyncObserver[TSource]):
# class AsyncNotificationObserver(AsyncObserver[TSource]):
# class AsyncAwaitableObserver(Future[TSource], AsyncObserver[TSource], Disposable):
# def __init__(self, source: AsyncObservable[TSource]) -> None:
# async def asend(self, value: TSource) -> None:
# async def athrow(self, error: Exception) -> None:
# async def aclose(self) -> None:
# async def _wait_for_pull(self) -> None:
# async def _serialize_access(self) -> None:
# async def wait_for_push(self) -> TSource:
# async def dispose_async(self) -> None:
# def __aiter__(self) -> AsyncIterator[TSource]:
# async def __anext__(self) -> TSource:
# def __init__(
# self,
# asend: Callable[[TSource], Awaitable[None]] = anoop,
# athrow: Callable[[Exception], Awaitable[None]] = anoop,
# aclose: Callable[[], Awaitable[None]] = anoop,
# ) -> None:
# async def asend(self, value: TSource) -> None:
# async def athrow(self, error: Exception) -> None:
# async def aclose(self) -> None:
# def __init__(self, fn: Callable[[Notification[TSource]], Awaitable[None]]) -> None:
# async def asend(self, value: TSource) -> None:
# async def athrow(self, error: Exception) -> None:
# async def aclose(self) -> None:
# def noop() -> AsyncObserver[Any]:
# def safe_observer(obv: AsyncObserver[TSource], disposable: AsyncDisposable) -> AsyncObserver[TSource]:
# async def worker(inbox: MailboxProcessor[Notification[TSource]]):
# async def message_loop(running: bool) -> None:
# async def asend(value: TSource) -> None:
# async def athrow(ex: Exception) -> None:
# async def aclose() -> None:
# def auto_detach_observer(
# obv: AsyncObserver[TSource],
# ) -> Tuple[AsyncObserver[TSource], Callable[[Awaitable[AsyncDisposable]], Awaitable[AsyncDisposable]]]:
# async def worker(inbox: MailboxProcessor[Msg[TSource]]):
# async def message_loop(disposables: List[AsyncDisposable]):
# async def cancel():
# async def auto_detach(async_disposable: Awaitable[AsyncDisposable]):
# def __init__(
# self,
# asend: Callable[[TSource], Awaitable[None]] = anoop,
# athrow: Callable[[Exception], Awaitable[None]] = anoop,
# aclose: Callable[[], Awaitable[None]] = anoop,
# ) -> None:
# async def asend(self, value: TSource) -> None:
# async def athrow(self, error: Exception) -> None:
# async def aclose(self) -> None:
# def dispose(self) -> None:
#
# Path: aioreactive/types.py
# class AsyncObservable(Generic[T_co]):
# __slots__ = ()
#
# @abstractmethod
# async def subscribe_async(self, observer: AsyncObserver[T_co]) -> AsyncDisposable:
# raise NotImplementedError
. Output only the next line. | safe_obv = safe_observer(aobv, disposable) |
Continue the code snippet: <|code_start|>
TSource = TypeVar("TSource")
log = logging.getLogger(__name__)
def canceller() -> Tuple[AsyncDisposable, CancellationToken]:
cts = CancellationTokenSource()
async def cancel() -> None:
log.debug("cancller, cancelling!")
cts.cancel()
return AsyncDisposable.create(cancel), cts.token
<|code_end|>
. Use current file imports:
import asyncio
import logging
from asyncio import Future
from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Optional, Tuple, TypeVar
from expression.core import TailCallResult, aiotools, tailrec_async
from expression.core.fn import TailCall
from expression.system import AsyncDisposable, CancellationToken, CancellationTokenSource
from .observables import AsyncAnonymousObservable
from .observers import AsyncObserver, safe_observer
from .types import AsyncObservable
and context (classes, functions, or code) from other files:
# Path: aioreactive/observables.py
# class AsyncAnonymousObservable(AsyncObservable[TSource]):
#
# """An anonymous AsyncObservable.
#
# Uses a custom subscribe method.
# """
#
# def __init__(self, subscribe: Callable[[AsyncObserver[TSource]], Awaitable[AsyncDisposable]]) -> None:
# self._subscribe = subscribe
#
# async def subscribe_async(self, observer: AsyncObserver[TSource]) -> AsyncDisposable:
# log.debug("AsyncAnonymousObservable:subscribe_async(%s)", self._subscribe)
# return await self._subscribe(observer)
#
# Path: aioreactive/observers.py
# class AsyncIteratorObserver(AsyncObserver[TSource], AsyncIterable[TSource], AsyncDisposable):
# class AsyncAnonymousObserver(AsyncObserver[TSource]):
# class AsyncNotificationObserver(AsyncObserver[TSource]):
# class AsyncAwaitableObserver(Future[TSource], AsyncObserver[TSource], Disposable):
# def __init__(self, source: AsyncObservable[TSource]) -> None:
# async def asend(self, value: TSource) -> None:
# async def athrow(self, error: Exception) -> None:
# async def aclose(self) -> None:
# async def _wait_for_pull(self) -> None:
# async def _serialize_access(self) -> None:
# async def wait_for_push(self) -> TSource:
# async def dispose_async(self) -> None:
# def __aiter__(self) -> AsyncIterator[TSource]:
# async def __anext__(self) -> TSource:
# def __init__(
# self,
# asend: Callable[[TSource], Awaitable[None]] = anoop,
# athrow: Callable[[Exception], Awaitable[None]] = anoop,
# aclose: Callable[[], Awaitable[None]] = anoop,
# ) -> None:
# async def asend(self, value: TSource) -> None:
# async def athrow(self, error: Exception) -> None:
# async def aclose(self) -> None:
# def __init__(self, fn: Callable[[Notification[TSource]], Awaitable[None]]) -> None:
# async def asend(self, value: TSource) -> None:
# async def athrow(self, error: Exception) -> None:
# async def aclose(self) -> None:
# def noop() -> AsyncObserver[Any]:
# def safe_observer(obv: AsyncObserver[TSource], disposable: AsyncDisposable) -> AsyncObserver[TSource]:
# async def worker(inbox: MailboxProcessor[Notification[TSource]]):
# async def message_loop(running: bool) -> None:
# async def asend(value: TSource) -> None:
# async def athrow(ex: Exception) -> None:
# async def aclose() -> None:
# def auto_detach_observer(
# obv: AsyncObserver[TSource],
# ) -> Tuple[AsyncObserver[TSource], Callable[[Awaitable[AsyncDisposable]], Awaitable[AsyncDisposable]]]:
# async def worker(inbox: MailboxProcessor[Msg[TSource]]):
# async def message_loop(disposables: List[AsyncDisposable]):
# async def cancel():
# async def auto_detach(async_disposable: Awaitable[AsyncDisposable]):
# def __init__(
# self,
# asend: Callable[[TSource], Awaitable[None]] = anoop,
# athrow: Callable[[Exception], Awaitable[None]] = anoop,
# aclose: Callable[[], Awaitable[None]] = anoop,
# ) -> None:
# async def asend(self, value: TSource) -> None:
# async def athrow(self, error: Exception) -> None:
# async def aclose(self) -> None:
# def dispose(self) -> None:
#
# Path: aioreactive/types.py
# class AsyncObservable(Generic[T_co]):
# __slots__ = ()
#
# @abstractmethod
# async def subscribe_async(self, observer: AsyncObserver[T_co]) -> AsyncDisposable:
# raise NotImplementedError
. Output only the next line. | def create(subscribe: Callable[[AsyncObserver[TSource]], Awaitable[AsyncDisposable]]) -> AsyncObservable[TSource]: |
Given snippet: <|code_start|>
TSource = TypeVar("TSource")
log = logging.getLogger(__name__)
def noop(*args: Any, **kw: Any) -> None:
"""No operation. Returns nothing"""
pass
async def anoop(value: Optional[Any] = None):
"""Async no operation. Returns nothing"""
pass
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
from typing import Any, Optional, TypeVar
from .types import AsyncObserver
and context:
# Path: aioreactive/types.py
# class AsyncObserver(Generic[T_contra]):
# """An asynchronous observable."""
#
# __slots__ = ()
#
# @abstractmethod
# async def asend(self, value: T_contra) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def athrow(self, error: Exception) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def aclose(self) -> None:
# raise NotImplementedError
which might include code, classes, or functions. Output only the next line. | class NoopObserver(AsyncObserver[TSource]): |
Predict the next line for this snippet: <|code_start|>
log = logging.getLogger(__name__)
TSource = TypeVar("TSource")
async def run(
<|code_end|>
with the help of current file imports:
import asyncio
import logging
from typing import Awaitable, Callable, Optional, TypeVar
from expression.system.disposable import AsyncDisposable
from .observers import AsyncAwaitableObserver
from .types import AsyncObservable, AsyncObserver
and context from other files:
# Path: aioreactive/observers.py
# class AsyncAwaitableObserver(Future[TSource], AsyncObserver[TSource], Disposable):
# """An async awaitable observer.
#
# Both a future and async observer. The future resolves with the last
# value before the observer is closed. A close without any values sent
# is the same as cancelling the future."""
#
# def __init__(
# self,
# asend: Callable[[TSource], Awaitable[None]] = anoop,
# athrow: Callable[[Exception], Awaitable[None]] = anoop,
# aclose: Callable[[], Awaitable[None]] = anoop,
# ) -> None:
# super().__init__()
#
# assert iscoroutinefunction(asend)
# self._asend = asend
#
# assert iscoroutinefunction(athrow)
# self._athrow = athrow
#
# assert iscoroutinefunction(aclose)
# self._aclose = aclose
#
# self._last_value: Optional[TSource] = None
# self._is_stopped = False
# self._has_value = False
#
# async def asend(self, value: TSource) -> None:
# log.debug("AsyncAwaitableObserver:asend(%s)", str(value))
#
# if self._is_stopped:
# log.debug("AsyncAwaitableObserver:asend(), Closed!!")
# return
#
# self._last_value = value
# self._has_value = True
# await self._asend(value)
#
# async def athrow(self, error: Exception) -> None:
# log.debug("AsyncAwaitableObserver:athrow()")
# if self._is_stopped:
# log.debug("AsyncAwaitableObserver:athrow(), Closed!!")
# return
#
# self._is_stopped = True
#
# self.set_exception(error)
# await self._athrow(error)
#
# async def aclose(self) -> None:
# log.debug("AsyncAwaitableObserver:aclose")
#
# if self._is_stopped:
# log.debug("AsyncAwaitableObserver:aclose(), Closed!!")
# return
#
# self._is_stopped = True
#
# if self._has_value:
# self.set_result(cast("TSource", self._last_value))
# else:
# self.cancel()
# await self._aclose()
#
# def dispose(self) -> None:
# log.debug("AsyncAwaitableObserver:dispose()")
#
# self._is_stopped = True
#
# Path: aioreactive/types.py
# class AsyncObservable(Generic[T_co]):
# __slots__ = ()
#
# @abstractmethod
# async def subscribe_async(self, observer: AsyncObserver[T_co]) -> AsyncDisposable:
# raise NotImplementedError
#
# class AsyncObserver(Generic[T_contra]):
# """An asynchronous observable."""
#
# __slots__ = ()
#
# @abstractmethod
# async def asend(self, value: T_contra) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def athrow(self, error: Exception) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def aclose(self) -> None:
# raise NotImplementedError
, which may contain function names, class names, or code. Output only the next line. | source: AsyncObservable[TSource], observer: Optional[AsyncAwaitableObserver[TSource]] = None, timeout: int = 2 |
Predict the next line after this snippet: <|code_start|>
log = logging.getLogger(__name__)
TSource = TypeVar("TSource")
async def run(
<|code_end|>
using the current file's imports:
import asyncio
import logging
from typing import Awaitable, Callable, Optional, TypeVar
from expression.system.disposable import AsyncDisposable
from .observers import AsyncAwaitableObserver
from .types import AsyncObservable, AsyncObserver
and any relevant context from other files:
# Path: aioreactive/observers.py
# class AsyncAwaitableObserver(Future[TSource], AsyncObserver[TSource], Disposable):
# """An async awaitable observer.
#
# Both a future and async observer. The future resolves with the last
# value before the observer is closed. A close without any values sent
# is the same as cancelling the future."""
#
# def __init__(
# self,
# asend: Callable[[TSource], Awaitable[None]] = anoop,
# athrow: Callable[[Exception], Awaitable[None]] = anoop,
# aclose: Callable[[], Awaitable[None]] = anoop,
# ) -> None:
# super().__init__()
#
# assert iscoroutinefunction(asend)
# self._asend = asend
#
# assert iscoroutinefunction(athrow)
# self._athrow = athrow
#
# assert iscoroutinefunction(aclose)
# self._aclose = aclose
#
# self._last_value: Optional[TSource] = None
# self._is_stopped = False
# self._has_value = False
#
# async def asend(self, value: TSource) -> None:
# log.debug("AsyncAwaitableObserver:asend(%s)", str(value))
#
# if self._is_stopped:
# log.debug("AsyncAwaitableObserver:asend(), Closed!!")
# return
#
# self._last_value = value
# self._has_value = True
# await self._asend(value)
#
# async def athrow(self, error: Exception) -> None:
# log.debug("AsyncAwaitableObserver:athrow()")
# if self._is_stopped:
# log.debug("AsyncAwaitableObserver:athrow(), Closed!!")
# return
#
# self._is_stopped = True
#
# self.set_exception(error)
# await self._athrow(error)
#
# async def aclose(self) -> None:
# log.debug("AsyncAwaitableObserver:aclose")
#
# if self._is_stopped:
# log.debug("AsyncAwaitableObserver:aclose(), Closed!!")
# return
#
# self._is_stopped = True
#
# if self._has_value:
# self.set_result(cast("TSource", self._last_value))
# else:
# self.cancel()
# await self._aclose()
#
# def dispose(self) -> None:
# log.debug("AsyncAwaitableObserver:dispose()")
#
# self._is_stopped = True
#
# Path: aioreactive/types.py
# class AsyncObservable(Generic[T_co]):
# __slots__ = ()
#
# @abstractmethod
# async def subscribe_async(self, observer: AsyncObserver[T_co]) -> AsyncDisposable:
# raise NotImplementedError
#
# class AsyncObserver(Generic[T_contra]):
# """An asynchronous observable."""
#
# __slots__ = ()
#
# @abstractmethod
# async def asend(self, value: T_contra) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def athrow(self, error: Exception) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def aclose(self) -> None:
# raise NotImplementedError
. Output only the next line. | source: AsyncObservable[TSource], observer: Optional[AsyncAwaitableObserver[TSource]] = None, timeout: int = 2 |
Here is a snippet: <|code_start|>
log = logging.getLogger(__name__)
TSource = TypeVar("TSource")
async def run(
source: AsyncObservable[TSource], observer: Optional[AsyncAwaitableObserver[TSource]] = None, timeout: int = 2
) -> TSource:
"""Run the source with the given observer.
Similar to `subscribe_async()` but also awaits until the stream
closes and returns the final value received.
Args:
timeout -- Seconds before timing out in case source never closes.
Returns:
The last event sent through the stream. If any values have been
sent through the stream it will return the last value. If the
stream is closed without any previous values it will throw
`StopAsyncIteration`. For any other errors it will throw the
exception.
"""
# For run we need a noopobserver if no observer is specified to avoid
# blocking the last single stream in the chain.
<|code_end|>
. Write the next line using the current file imports:
import asyncio
import logging
from typing import Awaitable, Callable, Optional, TypeVar
from expression.system.disposable import AsyncDisposable
from .observers import AsyncAwaitableObserver
from .types import AsyncObservable, AsyncObserver
and context from other files:
# Path: aioreactive/observers.py
# class AsyncAwaitableObserver(Future[TSource], AsyncObserver[TSource], Disposable):
# """An async awaitable observer.
#
# Both a future and async observer. The future resolves with the last
# value before the observer is closed. A close without any values sent
# is the same as cancelling the future."""
#
# def __init__(
# self,
# asend: Callable[[TSource], Awaitable[None]] = anoop,
# athrow: Callable[[Exception], Awaitable[None]] = anoop,
# aclose: Callable[[], Awaitable[None]] = anoop,
# ) -> None:
# super().__init__()
#
# assert iscoroutinefunction(asend)
# self._asend = asend
#
# assert iscoroutinefunction(athrow)
# self._athrow = athrow
#
# assert iscoroutinefunction(aclose)
# self._aclose = aclose
#
# self._last_value: Optional[TSource] = None
# self._is_stopped = False
# self._has_value = False
#
# async def asend(self, value: TSource) -> None:
# log.debug("AsyncAwaitableObserver:asend(%s)", str(value))
#
# if self._is_stopped:
# log.debug("AsyncAwaitableObserver:asend(), Closed!!")
# return
#
# self._last_value = value
# self._has_value = True
# await self._asend(value)
#
# async def athrow(self, error: Exception) -> None:
# log.debug("AsyncAwaitableObserver:athrow()")
# if self._is_stopped:
# log.debug("AsyncAwaitableObserver:athrow(), Closed!!")
# return
#
# self._is_stopped = True
#
# self.set_exception(error)
# await self._athrow(error)
#
# async def aclose(self) -> None:
# log.debug("AsyncAwaitableObserver:aclose")
#
# if self._is_stopped:
# log.debug("AsyncAwaitableObserver:aclose(), Closed!!")
# return
#
# self._is_stopped = True
#
# if self._has_value:
# self.set_result(cast("TSource", self._last_value))
# else:
# self.cancel()
# await self._aclose()
#
# def dispose(self) -> None:
# log.debug("AsyncAwaitableObserver:dispose()")
#
# self._is_stopped = True
#
# Path: aioreactive/types.py
# class AsyncObservable(Generic[T_co]):
# __slots__ = ()
#
# @abstractmethod
# async def subscribe_async(self, observer: AsyncObserver[T_co]) -> AsyncDisposable:
# raise NotImplementedError
#
# class AsyncObserver(Generic[T_contra]):
# """An asynchronous observable."""
#
# __slots__ = ()
#
# @abstractmethod
# async def asend(self, value: T_contra) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def athrow(self, error: Exception) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def aclose(self) -> None:
# raise NotImplementedError
, which may include functions, classes, or code. Output only the next line. | obv: AsyncObserver[TSource] = observer or AsyncAwaitableObserver() |
Continue the code snippet: <|code_start|>
Uses a custom subscribe method.
"""
def __init__(self, subscribe: Callable[[AsyncObserver[TSource]], Awaitable[AsyncDisposable]]) -> None:
self._subscribe = subscribe
async def subscribe_async(self, observer: AsyncObserver[TSource]) -> AsyncDisposable:
log.debug("AsyncAnonymousObservable:subscribe_async(%s)", self._subscribe)
return await self._subscribe(observer)
class AsyncIterableObservable(AsyncIterable[TSource], AsyncObservable[TSource]):
def __init__(self, source: AsyncObservable[TSource]) -> None:
self._source = source
async def subscribe_async(self, observer: AsyncObserver[TSource]) -> AsyncDisposable:
return await self._source.subscribe_async(observer)
def __aiter__(self) -> AsyncIterator[TSource]:
"""Iterate asynchronously.
Transforms the async source to an async iterable. The source
will await for the iterator to pick up the value before
continuing to avoid queuing values.
Returns:
An async iterator.
"""
<|code_end|>
. Use current file imports:
import logging
from typing import AsyncIterable, AsyncIterator, Awaitable, Callable, TypeVar
from expression.system import AsyncDisposable
from .observers import AsyncIteratorObserver
from .types import AsyncObservable, AsyncObserver
and context (classes, functions, or code) from other files:
# Path: aioreactive/observers.py
# class AsyncIteratorObserver(AsyncObserver[TSource], AsyncIterable[TSource], AsyncDisposable):
# """An async observer that might be iterated asynchronously."""
#
# def __init__(self, source: AsyncObservable[TSource]) -> None:
# super().__init__()
#
# self._push: Future[TSource] = Future()
# self._pull: Future[bool] = Future()
#
# self._awaiters: List[Future[bool]] = []
# self._subscription: Optional[AsyncDisposable] = None
# self._source = source
# self._busy = False
#
# async def asend(self, value: TSource) -> None:
# log.debug("AsyncIteratorObserver:asend(%s)", value)
#
# await self._serialize_access()
#
# self._push.set_result(value)
# await self._wait_for_pull()
#
# async def athrow(self, error: Exception) -> None:
# log.debug("AsyncIteratorObserver:athrow()", error)
# await self._serialize_access()
#
# self._push.set_exception(error)
# await self._wait_for_pull()
#
# async def aclose(self) -> None:
# await self._serialize_access()
#
# self._push.set_exception(StopAsyncIteration)
# await self._wait_for_pull()
#
# async def _wait_for_pull(self) -> None:
# await self._pull
# self._pull = Future()
# self._busy = False
#
# async def _serialize_access(self) -> None:
# # Serialize producer event to the iterator
# while self._busy:
# fut: Future[bool] = Future()
# self._awaiters.append(fut)
# await fut
# self._awaiters.remove(fut)
#
# self._busy = True
#
# async def wait_for_push(self) -> TSource:
# if self._subscription is None:
# self._subscription = await self._source.subscribe_async(self)
#
# value = await self._push
# self._push = Future()
# self._pull.set_result(True)
#
# # Wake up any awaiters
# for awaiter in self._awaiters[:1]:
# awaiter.set_result(True)
# return value
#
# async def dispose_async(self) -> None:
# if self._subscription is not None:
# await self._subscription.dispose_async()
# self._subscription = None
#
# def __aiter__(self) -> AsyncIterator[TSource]:
# log.debug("AsyncIteratorObserver:__aiter__")
# return self
#
# async def __anext__(self) -> TSource:
# log.debug("AsyncIteratorObserver:__anext__()")
# return await self.wait_for_push()
#
# Path: aioreactive/types.py
# class AsyncObservable(Generic[T_co]):
# __slots__ = ()
#
# @abstractmethod
# async def subscribe_async(self, observer: AsyncObserver[T_co]) -> AsyncDisposable:
# raise NotImplementedError
#
# class AsyncObserver(Generic[T_contra]):
# """An asynchronous observable."""
#
# __slots__ = ()
#
# @abstractmethod
# async def asend(self, value: T_contra) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def athrow(self, error: Exception) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def aclose(self) -> None:
# raise NotImplementedError
. Output only the next line. | return AsyncIteratorObserver(self) |
Here is a snippet: <|code_start|>
TSource = TypeVar("TSource")
TResult = TypeVar("TResult")
TOther = TypeVar("TOther")
TError = TypeVar("TError")
T1 = TypeVar("T1")
T2 = TypeVar("T2")
log = logging.getLogger(__name__)
<|code_end|>
. Write the next line using the current file imports:
import logging
from typing import AsyncIterable, AsyncIterator, Awaitable, Callable, TypeVar
from expression.system import AsyncDisposable
from .observers import AsyncIteratorObserver
from .types import AsyncObservable, AsyncObserver
and context from other files:
# Path: aioreactive/observers.py
# class AsyncIteratorObserver(AsyncObserver[TSource], AsyncIterable[TSource], AsyncDisposable):
# """An async observer that might be iterated asynchronously."""
#
# def __init__(self, source: AsyncObservable[TSource]) -> None:
# super().__init__()
#
# self._push: Future[TSource] = Future()
# self._pull: Future[bool] = Future()
#
# self._awaiters: List[Future[bool]] = []
# self._subscription: Optional[AsyncDisposable] = None
# self._source = source
# self._busy = False
#
# async def asend(self, value: TSource) -> None:
# log.debug("AsyncIteratorObserver:asend(%s)", value)
#
# await self._serialize_access()
#
# self._push.set_result(value)
# await self._wait_for_pull()
#
# async def athrow(self, error: Exception) -> None:
# log.debug("AsyncIteratorObserver:athrow()", error)
# await self._serialize_access()
#
# self._push.set_exception(error)
# await self._wait_for_pull()
#
# async def aclose(self) -> None:
# await self._serialize_access()
#
# self._push.set_exception(StopAsyncIteration)
# await self._wait_for_pull()
#
# async def _wait_for_pull(self) -> None:
# await self._pull
# self._pull = Future()
# self._busy = False
#
# async def _serialize_access(self) -> None:
# # Serialize producer event to the iterator
# while self._busy:
# fut: Future[bool] = Future()
# self._awaiters.append(fut)
# await fut
# self._awaiters.remove(fut)
#
# self._busy = True
#
# async def wait_for_push(self) -> TSource:
# if self._subscription is None:
# self._subscription = await self._source.subscribe_async(self)
#
# value = await self._push
# self._push = Future()
# self._pull.set_result(True)
#
# # Wake up any awaiters
# for awaiter in self._awaiters[:1]:
# awaiter.set_result(True)
# return value
#
# async def dispose_async(self) -> None:
# if self._subscription is not None:
# await self._subscription.dispose_async()
# self._subscription = None
#
# def __aiter__(self) -> AsyncIterator[TSource]:
# log.debug("AsyncIteratorObserver:__aiter__")
# return self
#
# async def __anext__(self) -> TSource:
# log.debug("AsyncIteratorObserver:__anext__()")
# return await self.wait_for_push()
#
# Path: aioreactive/types.py
# class AsyncObservable(Generic[T_co]):
# __slots__ = ()
#
# @abstractmethod
# async def subscribe_async(self, observer: AsyncObserver[T_co]) -> AsyncDisposable:
# raise NotImplementedError
#
# class AsyncObserver(Generic[T_contra]):
# """An asynchronous observable."""
#
# __slots__ = ()
#
# @abstractmethod
# async def asend(self, value: T_contra) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def athrow(self, error: Exception) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def aclose(self) -> None:
# raise NotImplementedError
, which may include functions, classes, or code. Output only the next line. | class AsyncAnonymousObservable(AsyncObservable[TSource]): |
Predict the next line after this snippet: <|code_start|>
TSource = TypeVar("TSource")
TResult = TypeVar("TResult")
TOther = TypeVar("TOther")
TError = TypeVar("TError")
T1 = TypeVar("T1")
T2 = TypeVar("T2")
log = logging.getLogger(__name__)
class AsyncAnonymousObservable(AsyncObservable[TSource]):
"""An anonymous AsyncObservable.
Uses a custom subscribe method.
"""
<|code_end|>
using the current file's imports:
import logging
from typing import AsyncIterable, AsyncIterator, Awaitable, Callable, TypeVar
from expression.system import AsyncDisposable
from .observers import AsyncIteratorObserver
from .types import AsyncObservable, AsyncObserver
and any relevant context from other files:
# Path: aioreactive/observers.py
# class AsyncIteratorObserver(AsyncObserver[TSource], AsyncIterable[TSource], AsyncDisposable):
# """An async observer that might be iterated asynchronously."""
#
# def __init__(self, source: AsyncObservable[TSource]) -> None:
# super().__init__()
#
# self._push: Future[TSource] = Future()
# self._pull: Future[bool] = Future()
#
# self._awaiters: List[Future[bool]] = []
# self._subscription: Optional[AsyncDisposable] = None
# self._source = source
# self._busy = False
#
# async def asend(self, value: TSource) -> None:
# log.debug("AsyncIteratorObserver:asend(%s)", value)
#
# await self._serialize_access()
#
# self._push.set_result(value)
# await self._wait_for_pull()
#
# async def athrow(self, error: Exception) -> None:
# log.debug("AsyncIteratorObserver:athrow()", error)
# await self._serialize_access()
#
# self._push.set_exception(error)
# await self._wait_for_pull()
#
# async def aclose(self) -> None:
# await self._serialize_access()
#
# self._push.set_exception(StopAsyncIteration)
# await self._wait_for_pull()
#
# async def _wait_for_pull(self) -> None:
# await self._pull
# self._pull = Future()
# self._busy = False
#
# async def _serialize_access(self) -> None:
# # Serialize producer event to the iterator
# while self._busy:
# fut: Future[bool] = Future()
# self._awaiters.append(fut)
# await fut
# self._awaiters.remove(fut)
#
# self._busy = True
#
# async def wait_for_push(self) -> TSource:
# if self._subscription is None:
# self._subscription = await self._source.subscribe_async(self)
#
# value = await self._push
# self._push = Future()
# self._pull.set_result(True)
#
# # Wake up any awaiters
# for awaiter in self._awaiters[:1]:
# awaiter.set_result(True)
# return value
#
# async def dispose_async(self) -> None:
# if self._subscription is not None:
# await self._subscription.dispose_async()
# self._subscription = None
#
# def __aiter__(self) -> AsyncIterator[TSource]:
# log.debug("AsyncIteratorObserver:__aiter__")
# return self
#
# async def __anext__(self) -> TSource:
# log.debug("AsyncIteratorObserver:__anext__()")
# return await self.wait_for_push()
#
# Path: aioreactive/types.py
# class AsyncObservable(Generic[T_co]):
# __slots__ = ()
#
# @abstractmethod
# async def subscribe_async(self, observer: AsyncObserver[T_co]) -> AsyncDisposable:
# raise NotImplementedError
#
# class AsyncObserver(Generic[T_contra]):
# """An asynchronous observable."""
#
# __slots__ = ()
#
# @abstractmethod
# async def asend(self, value: T_contra) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def athrow(self, error: Exception) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def aclose(self) -> None:
# raise NotImplementedError
. Output only the next line. | def __init__(self, subscribe: Callable[[AsyncObserver[TSource]], Awaitable[AsyncDisposable]]) -> None: |
Predict the next line after this snippet: <|code_start|>
TSource = TypeVar("TSource")
TMessage = TypeVar("TMessage")
class MsgKind(Enum):
ON_NEXT = 1
ON_ERROR = 2
ON_COMPLETED = 3
class Notification(Generic[TSource], ABC):
"""Represents a message to a mailbox processor."""
def __init__(self, kind: MsgKind):
self.kind = kind # Message kind
@abstractmethod
async def accept(
self,
asend: Callable[[TSource], Awaitable[None]],
athrow: Callable[[Exception], Awaitable[None]],
aclose: Callable[[], Awaitable[None]],
) -> None:
raise NotImplementedError
@abstractmethod
<|code_end|>
using the current file's imports:
from abc import ABC, abstractmethod
from enum import Enum
from typing import Any, Awaitable, Callable, Generic, Iterable, TypeVar, get_origin
from expression.core import SupportsMatch
from .types import AsyncObserver
and any relevant context from other files:
# Path: aioreactive/types.py
# class AsyncObserver(Generic[T_contra]):
# """An asynchronous observable."""
#
# __slots__ = ()
#
# @abstractmethod
# async def asend(self, value: T_contra) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def athrow(self, error: Exception) -> None:
# raise NotImplementedError
#
# @abstractmethod
# async def aclose(self) -> None:
# raise NotImplementedError
. Output only the next line. | async def accept_observer(self, obv: AsyncObserver[TSource]) -> None: |
Based on the snippet: <|code_start|>
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)
@pytest.yield_fixture() # type: ignore
def event_loop():
<|code_end|>
, predict the immediate next line with the help of imports:
import asyncio
import logging
import aioreactive as rx
import pytest
from aioreactive.testing import VirtualTimeEventLoop
and context (classes, functions, sometimes code) from other files:
# Path: aioreactive/testing/virtual_events.py
# class VirtualTimeEventLoop(asyncio.BaseEventLoop):
# """Virtual time event loop.
#
# Works the same was as a normal event loop except that time is
# virtual. Time starts at 0 and only advances when something is
# scheduled into the future. Thus the event loops runs as quickly as
# possible while producing the same output as a normal event loop
# would do. This makes it ideal for unit-testing where you want to
# test delays but without spending time in real life.
# """
#
# def __init__(self) -> None:
# super().__init__()
#
# self._ready = collections.deque()
# self._current_handle = None
# self._debug = False
#
# self._time: float = 0.0
#
# def time(self):
# return self._time
#
# def _run_once(self):
# """Run one full iteration of the event loop. This calls all
# currently ready callbacks, polls for I/O, schedules the
# resulting callbacks, and finally schedules 'call_later'
# callbacks.
# """
# # log.debug("run_once()")
#
# sched_count = len(self._scheduled)
# if (
# sched_count > _MIN_SCHEDULED_TIMER_HANDLES
# and self._timer_cancelled_count / sched_count > _MIN_CANCELLED_TIMER_HANDLES_FRACTION
# ):
# # Remove delayed calls that were cancelled if their number
# # is too high
# new_scheduled = []
# for handle in self._scheduled:
# if handle._cancelled:
# handle._scheduled = False
# else:
# new_scheduled.append(handle)
#
# heapq.heapify(new_scheduled)
# self._scheduled = new_scheduled
# self._timer_cancelled_count = 0
# else:
# # Remove delayed calls that were cancelled from head of queue.
# while self._scheduled and self._scheduled[0]._cancelled:
# self._timer_cancelled_count -= 1
# handle = heapq.heappop(self._scheduled)
# handle._scheduled = False
#
# # print("***", self._ready)
# # print("***", self._scheduled)
#
# # Handle 'later' callbacks that are ready.
# while self._scheduled and not self._ready:
# handle = self._scheduled[0]
# handle = heapq.heappop(self._scheduled)
# handle._scheduled = False
# log.debug("Advancing time from %s to %s", self._time, handle._when)
# self._time = max(handle._when, self._time)
# self._ready.append(handle)
#
# # This is the only place where callbacks are actually *called*.
# # All other places just add them to ready. Note: We run all
# # currently scheduled callbacks, but not any callbacks scheduled
# # by callbacks run this time around -- they will be run the next
# # time (after another I/O poll). Use an idiom that is
# # thread-safe without using locks.
# ntodo = len(self._ready)
# for i in range(ntodo):
# handle = self._ready.popleft()
# if handle._cancelled:
# continue
# if self._debug:
# try:
# self._current_handle = handle
# t0 = self.time()
# handle._run()
# dt = self.time() - t0
# if dt >= self.slow_callback_duration:
# logger.warning("Executing %s took %.3f seconds", _format_handle(handle), dt)
# finally:
# self._current_handle = None
# else:
# handle._run()
# handle = None # Needed to break cycles when an exception occurs.
#
# def _write_to_self(self):
# pass
. Output only the next line. | loop = VirtualTimeEventLoop() |
Here is a snippet: <|code_start|>
TSource = TypeVar("TSource")
def to_async_iterable(source: AsyncObservable[TSource]) -> AsyncIterable[TSource]:
"""Convert async observable to async iterable.
Args:
count: The number of elements to skip before returning the
remaining values.
Returns:
A source stream that contains the values that occur
after the specified index in the input source stream.
"""
<|code_end|>
. Write the next line using the current file imports:
from typing import AsyncIterable, TypeVar
from .observables import AsyncIterableObservable, AsyncObservable
and context from other files:
# Path: aioreactive/observables.py
# T1 = TypeVar("T1")
# T2 = TypeVar("T2")
# class AsyncAnonymousObservable(AsyncObservable[TSource]):
# class AsyncIterableObservable(AsyncIterable[TSource], AsyncObservable[TSource]):
# def __init__(self, subscribe: Callable[[AsyncObserver[TSource]], Awaitable[AsyncDisposable]]) -> None:
# async def subscribe_async(self, observer: AsyncObserver[TSource]) -> AsyncDisposable:
# def __init__(self, source: AsyncObservable[TSource]) -> None:
# async def subscribe_async(self, observer: AsyncObserver[TSource]) -> AsyncDisposable:
# def __aiter__(self) -> AsyncIterator[TSource]:
, which may include functions, classes, or code. Output only the next line. | return AsyncIterableObservable(source) |
Here is a snippet: <|code_start|> pass
# for use in policy match element reducing
elif item == 'source_zones':
return self.src_zones
elif item == 'destination_zones':
return self.dst_zones
elif item == 'source_addresses':
return set(flatten([a.value for a in self.src_addresses]))
elif item == 'destination_addresses':
return set(flatten([a.value for a in self.dst_addresses]))
elif item == 'services':
return set(flatten([s.value for s in self._services]))
elif item == 'services_objects':
return self._services
else:
raise AttributeError()
@staticmethod
def _in_network(value, p_value, exact_match=False):
"""
"""
# 'any' address is an automatic match if we are exact
if exact_match and 'any' in p_value:
return True
addresses = [IPRange(a.split('-')[0], a.split('-')[1]) if '-' in a else IPNetwork(a)
<|code_end|>
. Write the next line using the current file imports:
from orangengine.utils import is_ipv4, enum, bidict, flatten
from orangengine.models.base import BaseObject
from collections import defaultdict
from netaddr import IPRange, IPNetwork
from terminaltables import AsciiTable
from functools import partial
and context from other files:
# Path: orangengine/utils.py
# def is_ipv4(value):
# """
# return true if value is any kind of ipv4 address.
# address, network, or range
# """
# try:
# if '-' in value:
# # try a range
# addr_range = value.split('-')
# IPRange(addr_range[0], addr_range[1])
# else:
# IPNetwork(value)
# except Exception:
# return False
# return True
#
# def enum(*sequential, **named):
# enums = dict(zip(sequential, range(len(sequential))), **named)
# reverse = dict((value, key) for key, value in enums.iteritems())
# enums['reverse_mapping'] = reverse
# return type('Enum', (), enums)
#
# class bidict(dict):
# """Bidirectional dictionary for two-way lookups
#
# Thanks to @Basj
# http://stackoverflow.com/questions/3318625/efficient-bidirectional-hash-table-in-python
#
# Extended to allow blind access to the inverse dict by way of __getitem__
# """
# def __init__(self, *args, **kwargs):
# super(bidict, self).__init__(*args, **kwargs)
# self.inverse = {}
# for key, value in self.iteritems():
# self.inverse.setdefault(value, []).append(key)
#
# def __setitem__(self, key, value):
# super(bidict, self).__setitem__(key, value)
# self.inverse.setdefault(value, []).append(key)
#
# def __delitem__(self, key):
# self.inverse.setdefault(self[key], []).remove(key)
# if self[key] in self.inverse and not self.inverse[self[key]]:
# del self.inverse[self[key]]
# super(bidict, self).__delitem__(key)
#
# def __getitem__(self, item):
# try:
# value = super(bidict, self).__getitem__(item)
# except KeyError:
# value = self.inverse[item]
# if value and len(value) == 1:
# value = value[0]
# return value
#
# def flatten(l):
# """Generate a flatten list of elements from an n-depth nested list
# """
# for el in l:
# if isinstance(el, Iterable) and not isinstance(el, basestring) and not isinstance(el, tuple):
# for sub in flatten(el):
# yield sub
# else:
# yield el
#
# Path: orangengine/models/base/baseobject.py
# class BaseObject(object):
# """Base class for all (most) objects. This class should almost never be
# instantiated directly. It contains a few methods that are the available to
# all sub classes.
# """
#
# def serialize(self):
# raise NotImplementedError()
#
# def to_json(self):
# """Return a json dump of self returned from self.serialize()
# """
# return json.dumps(self.serialize())
, which may include functions, classes, or code. Output only the next line. | for a in value if is_ipv4(a)] |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
class BasePolicy(BaseObject):
Action = enum('ALLOW', 'DENY', 'REJECT', 'DROP')
Logging = enum('START', 'END')
<|code_end|>
. Use current file imports:
(from orangengine.utils import is_ipv4, enum, bidict, flatten
from orangengine.models.base import BaseObject
from collections import defaultdict
from netaddr import IPRange, IPNetwork
from terminaltables import AsciiTable
from functools import partial)
and context including class names, function names, or small code snippets from other files:
# Path: orangengine/utils.py
# def is_ipv4(value):
# """
# return true if value is any kind of ipv4 address.
# address, network, or range
# """
# try:
# if '-' in value:
# # try a range
# addr_range = value.split('-')
# IPRange(addr_range[0], addr_range[1])
# else:
# IPNetwork(value)
# except Exception:
# return False
# return True
#
# def enum(*sequential, **named):
# enums = dict(zip(sequential, range(len(sequential))), **named)
# reverse = dict((value, key) for key, value in enums.iteritems())
# enums['reverse_mapping'] = reverse
# return type('Enum', (), enums)
#
# class bidict(dict):
# """Bidirectional dictionary for two-way lookups
#
# Thanks to @Basj
# http://stackoverflow.com/questions/3318625/efficient-bidirectional-hash-table-in-python
#
# Extended to allow blind access to the inverse dict by way of __getitem__
# """
# def __init__(self, *args, **kwargs):
# super(bidict, self).__init__(*args, **kwargs)
# self.inverse = {}
# for key, value in self.iteritems():
# self.inverse.setdefault(value, []).append(key)
#
# def __setitem__(self, key, value):
# super(bidict, self).__setitem__(key, value)
# self.inverse.setdefault(value, []).append(key)
#
# def __delitem__(self, key):
# self.inverse.setdefault(self[key], []).remove(key)
# if self[key] in self.inverse and not self.inverse[self[key]]:
# del self.inverse[self[key]]
# super(bidict, self).__delitem__(key)
#
# def __getitem__(self, item):
# try:
# value = super(bidict, self).__getitem__(item)
# except KeyError:
# value = self.inverse[item]
# if value and len(value) == 1:
# value = value[0]
# return value
#
# def flatten(l):
# """Generate a flatten list of elements from an n-depth nested list
# """
# for el in l:
# if isinstance(el, Iterable) and not isinstance(el, basestring) and not isinstance(el, tuple):
# for sub in flatten(el):
# yield sub
# else:
# yield el
#
# Path: orangengine/models/base/baseobject.py
# class BaseObject(object):
# """Base class for all (most) objects. This class should almost never be
# instantiated directly. It contains a few methods that are the available to
# all sub classes.
# """
#
# def serialize(self):
# raise NotImplementedError()
#
# def to_json(self):
# """Return a json dump of self returned from self.serialize()
# """
# return json.dumps(self.serialize())
. Output only the next line. | ActionMap = bidict({ |
Based on the snippet: <|code_start|> 'name': self.name,
'source_zones': self.src_zones,
'source_addresses': s_addrs,
'destination_zones': self.dst_zones,
'destination_addresses': d_addrs,
'services': services,
'action': self.ActionMap[self.action],
'description': self.description,
'logging': self.logging
}
def __getattr__(self, item):
"""
return a tuple representation of the policy with normalized values
"""
# s_addrs = set(flatten([a.value for a in self.src_addresses]))
# d_addrs = set(flatten([a.value for a in self.dst_addresses]))
# services = set(flatten([s.value for s in self._services]))
if item == 'value':
# return self.src_zones, self.dst_zones, list(s_addrs), list(d_addrs), list(services), self.action
pass
# for use in policy match element reducing
elif item == 'source_zones':
return self.src_zones
elif item == 'destination_zones':
return self.dst_zones
elif item == 'source_addresses':
<|code_end|>
, predict the immediate next line with the help of imports:
from orangengine.utils import is_ipv4, enum, bidict, flatten
from orangengine.models.base import BaseObject
from collections import defaultdict
from netaddr import IPRange, IPNetwork
from terminaltables import AsciiTable
from functools import partial
and context (classes, functions, sometimes code) from other files:
# Path: orangengine/utils.py
# def is_ipv4(value):
# """
# return true if value is any kind of ipv4 address.
# address, network, or range
# """
# try:
# if '-' in value:
# # try a range
# addr_range = value.split('-')
# IPRange(addr_range[0], addr_range[1])
# else:
# IPNetwork(value)
# except Exception:
# return False
# return True
#
# def enum(*sequential, **named):
# enums = dict(zip(sequential, range(len(sequential))), **named)
# reverse = dict((value, key) for key, value in enums.iteritems())
# enums['reverse_mapping'] = reverse
# return type('Enum', (), enums)
#
# class bidict(dict):
# """Bidirectional dictionary for two-way lookups
#
# Thanks to @Basj
# http://stackoverflow.com/questions/3318625/efficient-bidirectional-hash-table-in-python
#
# Extended to allow blind access to the inverse dict by way of __getitem__
# """
# def __init__(self, *args, **kwargs):
# super(bidict, self).__init__(*args, **kwargs)
# self.inverse = {}
# for key, value in self.iteritems():
# self.inverse.setdefault(value, []).append(key)
#
# def __setitem__(self, key, value):
# super(bidict, self).__setitem__(key, value)
# self.inverse.setdefault(value, []).append(key)
#
# def __delitem__(self, key):
# self.inverse.setdefault(self[key], []).remove(key)
# if self[key] in self.inverse and not self.inverse[self[key]]:
# del self.inverse[self[key]]
# super(bidict, self).__delitem__(key)
#
# def __getitem__(self, item):
# try:
# value = super(bidict, self).__getitem__(item)
# except KeyError:
# value = self.inverse[item]
# if value and len(value) == 1:
# value = value[0]
# return value
#
# def flatten(l):
# """Generate a flatten list of elements from an n-depth nested list
# """
# for el in l:
# if isinstance(el, Iterable) and not isinstance(el, basestring) and not isinstance(el, tuple):
# for sub in flatten(el):
# yield sub
# else:
# yield el
#
# Path: orangengine/models/base/baseobject.py
# class BaseObject(object):
# """Base class for all (most) objects. This class should almost never be
# instantiated directly. It contains a few methods that are the available to
# all sub classes.
# """
#
# def serialize(self):
# raise NotImplementedError()
#
# def to_json(self):
# """Return a json dump of self returned from self.serialize()
# """
# return json.dumps(self.serialize())
. Output only the next line. | return set(flatten([a.value for a in self.src_addresses])) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
class JuniperSRXService(BaseService):
def __init__(self, name, protocol=None, port=None):
super(JuniperSRXService, self).__init__(name, protocol, port)
def to_xml(self):
"""Map service objects to juniper SRX config tree elements
"""
def map_destination_port(port):
<|code_end|>
, generate the next line using the imports in this file:
from orangengine.models.base import BaseService, BasePortRange
from orangengine.utils import create_element
and context (functions, classes, or occasionally code) from other files:
# Path: orangengine/models/base/baseservice.py
# class BaseService(BaseObject):
#
# def __init__(self, name, protocol=None, port=None):
# """init a service"""
#
# self.name = name
# self.protocol = protocol if protocol else "unknown"
# if port is not None and '-' in port:
# start = port.split('-')[0]
# stop = port.split('-')[1]
# if start != stop:
# self.port = BasePortRange(start, stop)
# else:
# self.port = start
# else:
# self.port = port if port else "unknown"
# self.terms = list()
#
# def add_term(self, term):
# """append a service term"""
#
# self.terms.append(term)
#
# def __getattr__(self, item):
#
# if item == 'value':
# if len(self.terms) > 0:
# return [t.value for t in self.terms]
# elif isinstance(self.port, BasePortRange):
# return self.protocol, self.port.value
# else:
# return self.protocol, self.port
# else:
# raise AttributeError
#
# def table_value(self, with_names):
# if with_names:
# return self.name + " - " + self.value[0] + "/" + self.value[1]
# else:
# if isinstance(self.value, list):
# return "\n".join([s[0] + "/" + s[1] for s in self.value])
# return self.value[0] + "/" + self.value[1]
#
# @classmethod
# def from_criteria(cls, criteria):
# """Create an instance from the provided criteria
# """
#
# return cls(criteria['name'], criteria['protocol'], criteria['port'])
#
# def serialize(self):
# """Searialize self to a json acceptable data structure
# """
#
# terms = []
# if self.terms:
# for term in self.terms:
# terms.append(term.serialize())
#
# if isinstance(self.port, BasePortRange):
# port = self.port.serialize()
# else:
# port = self.port
#
# return {
# 'name': self.name,
# 'terms': terms,
# 'protocol': self.protocol,
# 'port': port,
# }
#
# class BasePortRange(BaseObject):
#
# def __init__(self, start, stop):
# """init a port range"""
#
# self.start = start
# self.stop = stop
#
# def __str__(self):
# return '{0} {1}'.format(self.start, self.stop)
#
# def __getattr__(self, item):
#
# if item == 'value':
# return self.start + "-" + self.stop
# else:
# raise AttributeError
#
# def serialize(self):
# """Searialize self to a json acceptable data structure
# """
#
# return {
# 'start': self.start,
# 'stop': self.stop,
# }
#
# Path: orangengine/utils.py
# def create_element(tag, text=None, parent=None):
# # create an ambiguous xml element
# if parent is not None:
# e = letree.SubElement(parent, tag)
# else:
# e = letree.Element(tag)
# if text:
# e.text = text
# return e
. Output only the next line. | if isinstance(port, BasePortRange): |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
class JuniperSRXService(BaseService):
def __init__(self, name, protocol=None, port=None):
super(JuniperSRXService, self).__init__(name, protocol, port)
def to_xml(self):
"""Map service objects to juniper SRX config tree elements
"""
def map_destination_port(port):
if isinstance(port, BasePortRange):
port = port.value
<|code_end|>
, determine the next line of code. You have imports:
from orangengine.models.base import BaseService, BasePortRange
from orangengine.utils import create_element
and context (class names, function names, or code) available:
# Path: orangengine/models/base/baseservice.py
# class BaseService(BaseObject):
#
# def __init__(self, name, protocol=None, port=None):
# """init a service"""
#
# self.name = name
# self.protocol = protocol if protocol else "unknown"
# if port is not None and '-' in port:
# start = port.split('-')[0]
# stop = port.split('-')[1]
# if start != stop:
# self.port = BasePortRange(start, stop)
# else:
# self.port = start
# else:
# self.port = port if port else "unknown"
# self.terms = list()
#
# def add_term(self, term):
# """append a service term"""
#
# self.terms.append(term)
#
# def __getattr__(self, item):
#
# if item == 'value':
# if len(self.terms) > 0:
# return [t.value for t in self.terms]
# elif isinstance(self.port, BasePortRange):
# return self.protocol, self.port.value
# else:
# return self.protocol, self.port
# else:
# raise AttributeError
#
# def table_value(self, with_names):
# if with_names:
# return self.name + " - " + self.value[0] + "/" + self.value[1]
# else:
# if isinstance(self.value, list):
# return "\n".join([s[0] + "/" + s[1] for s in self.value])
# return self.value[0] + "/" + self.value[1]
#
# @classmethod
# def from_criteria(cls, criteria):
# """Create an instance from the provided criteria
# """
#
# return cls(criteria['name'], criteria['protocol'], criteria['port'])
#
# def serialize(self):
# """Searialize self to a json acceptable data structure
# """
#
# terms = []
# if self.terms:
# for term in self.terms:
# terms.append(term.serialize())
#
# if isinstance(self.port, BasePortRange):
# port = self.port.serialize()
# else:
# port = self.port
#
# return {
# 'name': self.name,
# 'terms': terms,
# 'protocol': self.protocol,
# 'port': port,
# }
#
# class BasePortRange(BaseObject):
#
# def __init__(self, start, stop):
# """init a port range"""
#
# self.start = start
# self.stop = stop
#
# def __str__(self):
# return '{0} {1}'.format(self.start, self.stop)
#
# def __getattr__(self, item):
#
# if item == 'value':
# return self.start + "-" + self.stop
# else:
# raise AttributeError
#
# def serialize(self):
# """Searialize self to a json acceptable data structure
# """
#
# return {
# 'start': self.start,
# 'stop': self.stop,
# }
#
# Path: orangengine/utils.py
# def create_element(tag, text=None, parent=None):
# # create an ambiguous xml element
# if parent is not None:
# e = letree.SubElement(parent, tag)
# else:
# e = letree.Element(tag)
# if text:
# e.text = text
# return e
. Output only the next line. | return create_element('destination-port', text=port) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
"""
juniper driver specific utility functions
"""
# --- begin xml generation functions
def create_new_address(a_value):
if isinstance(a_value, list):
raise ValueError("Creating new address groups is not currently supported")
address_element = create_element('address')
<|code_end|>
, generate the next line using the imports in this file:
from lxml import etree as letree
from orangengine.utils import is_ipv4
and context (functions, classes, or occasionally code) from other files:
# Path: orangengine/utils.py
# def is_ipv4(value):
# """
# return true if value is any kind of ipv4 address.
# address, network, or range
# """
# try:
# if '-' in value:
# # try a range
# addr_range = value.split('-')
# IPRange(addr_range[0], addr_range[1])
# else:
# IPNetwork(value)
# except Exception:
# return False
# return True
. Output only the next line. | if is_ipv4(a_value): |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
class JuniperSRXServiceGroup(BaseServiceGroup):
def __init__(self, name):
super(JuniperSRXServiceGroup, self).__init__(name)
def to_xml(self):
"""Map service group objects to juniper SRX config tree elements
"""
<|code_end|>
, generate the next line using the imports in this file:
from orangengine.models.base import BaseServiceGroup
from orangengine.utils import create_element
and context (functions, classes, or occasionally code) from other files:
# Path: orangengine/models/base/baseservicegroup.py
# class BaseServiceGroup(BaseObject):
#
# def __init__(self, name):
# """init a service group"""
#
# self.name = name
# self.elements = list()
#
# def add(self, service):
# """add a service"""
#
# self.elements.append(service)
#
# def __getattr__(self, item):
# """
# yield the values of the underlying objects
# """
#
# if item == 'value':
# return [s.value for s in self.elements]
# else:
# raise AttributeError
#
# def table_value(self, with_names):
# value = "Group: " + self.name + "\n"
# for s in self.elements:
# value = value + " " + s.table_value(with_names) + "\n"
# return value.rstrip('\n') # remove the last new line
#
# def serialize(self):
# """Searialize self to a json acceptable data structure
# """
#
# elements = []
# for e in self.elements:
# elements.append(e.serialize())
#
# return {
# 'name': self.name,
# 'elements': elements
# }
#
# Path: orangengine/utils.py
# def create_element(tag, text=None, parent=None):
# # create an ambiguous xml element
# if parent is not None:
# e = letree.SubElement(parent, tag)
# else:
# e = letree.Element(tag)
# if text:
# e.text = text
# return e
. Output only the next line. | servicegroup_element = create_element('application-set') |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
class JuniperSRXAddressGroup(BaseAddressGroup):
def __init__(self, name):
super(JuniperSRXAddressGroup, self).__init__(name)
def to_xml(self):
"""Map address group objects to juniper SRX config tree elements
"""
addressgroup_element = create_element('address-set')
create_element('name', text=self.name, parent=addressgroup_element)
for a in self.elements:
<|code_end|>
using the current file's imports:
from orangengine.models.base import BaseAddressGroup, BaseAddress
from orangengine.utils import create_element
and any relevant context from other files:
# Path: orangengine/models/base/baseaddress.py
# class BaseAddress(BaseObject):
#
# AddressTypes = enum('IPv4', 'DNS', 'RANGE', 'ANY')
# TypeMap = bidict({
# AddressTypes.IPv4: 'ipv4',
# AddressTypes.DNS: 'dns',
# AddressTypes.RANGE: 'range',
# AddressTypes.ANY: 'any',
# })
#
# def __init__(self, name, value, a_type):
# """init address object"""
#
# self.name = name
# self.value = value
# self.a_type = a_type
#
# def __getattr__(self, item):
#
# if item == 'value':
# return self.value
# else:
# raise AttributeError
#
# def table_value(self, with_names):
# if with_names:
# return self.name + " - " + self.value
# else:
# return self.value
#
# @classmethod
# def from_criteria(cls, criteria):
# """Create an instance from the provided criteria
# """
#
# return cls(criteria['name'], criteria['value'], cls.TypeMap[criteria['type']])
#
# def serialize(self):
# """Searialize self to a json acceptable data structure
# """
# return {
# 'name': self.name,
# 'type': self.TypeMap[self.a_type],
# 'value': self.value,
# }
#
# Path: orangengine/models/base/baseaddressgroup.py
# class BaseAddressGroup(BaseObject):
#
# def __init__(self, name):
# """init a address group object"""
#
# self.name = name
# self.elements = list()
#
# def add(self, address):
# """add an address(group) object to the elements list"""
#
# self.elements.append(address)
#
# def __getattr__(self, item):
# """
# yeild the values of the underlying objects
# """
# if item == 'value':
# return [a.value for a in self.elements]
# else:
# raise AttributeError
#
# def table_value(self, with_names):
# value = "Group: " + self.name + "\n"
# for a in self.elements:
# value = value + " " + a.table_value(with_names) + "\n"
# return value.rstrip('\n') # remove the last new line
#
# def serialize(self):
# """Searialize self to a json acceptable data structure
# """
#
# elements = []
# for e in self.elements:
# elements.append(e.serialize())
#
# return {
# 'name': self.name,
# 'elements': elements
# }
#
# Path: orangengine/utils.py
# def create_element(tag, text=None, parent=None):
# # create an ambiguous xml element
# if parent is not None:
# e = letree.SubElement(parent, tag)
# else:
# e = letree.Element(tag)
# if text:
# e.text = text
# return e
. Output only the next line. | if isinstance(a, BaseAddress): |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
class JuniperSRXAddressGroup(BaseAddressGroup):
def __init__(self, name):
super(JuniperSRXAddressGroup, self).__init__(name)
def to_xml(self):
"""Map address group objects to juniper SRX config tree elements
"""
<|code_end|>
. Write the next line using the current file imports:
from orangengine.models.base import BaseAddressGroup, BaseAddress
from orangengine.utils import create_element
and context from other files:
# Path: orangengine/models/base/baseaddress.py
# class BaseAddress(BaseObject):
#
# AddressTypes = enum('IPv4', 'DNS', 'RANGE', 'ANY')
# TypeMap = bidict({
# AddressTypes.IPv4: 'ipv4',
# AddressTypes.DNS: 'dns',
# AddressTypes.RANGE: 'range',
# AddressTypes.ANY: 'any',
# })
#
# def __init__(self, name, value, a_type):
# """init address object"""
#
# self.name = name
# self.value = value
# self.a_type = a_type
#
# def __getattr__(self, item):
#
# if item == 'value':
# return self.value
# else:
# raise AttributeError
#
# def table_value(self, with_names):
# if with_names:
# return self.name + " - " + self.value
# else:
# return self.value
#
# @classmethod
# def from_criteria(cls, criteria):
# """Create an instance from the provided criteria
# """
#
# return cls(criteria['name'], criteria['value'], cls.TypeMap[criteria['type']])
#
# def serialize(self):
# """Searialize self to a json acceptable data structure
# """
# return {
# 'name': self.name,
# 'type': self.TypeMap[self.a_type],
# 'value': self.value,
# }
#
# Path: orangengine/models/base/baseaddressgroup.py
# class BaseAddressGroup(BaseObject):
#
# def __init__(self, name):
# """init a address group object"""
#
# self.name = name
# self.elements = list()
#
# def add(self, address):
# """add an address(group) object to the elements list"""
#
# self.elements.append(address)
#
# def __getattr__(self, item):
# """
# yeild the values of the underlying objects
# """
# if item == 'value':
# return [a.value for a in self.elements]
# else:
# raise AttributeError
#
# def table_value(self, with_names):
# value = "Group: " + self.name + "\n"
# for a in self.elements:
# value = value + " " + a.table_value(with_names) + "\n"
# return value.rstrip('\n') # remove the last new line
#
# def serialize(self):
# """Searialize self to a json acceptable data structure
# """
#
# elements = []
# for e in self.elements:
# elements.append(e.serialize())
#
# return {
# 'name': self.name,
# 'elements': elements
# }
#
# Path: orangengine/utils.py
# def create_element(tag, text=None, parent=None):
# # create an ambiguous xml element
# if parent is not None:
# e = letree.SubElement(parent, tag)
# else:
# e = letree.Element(tag)
# if text:
# e.text = text
# return e
, which may include functions, classes, or code. Output only the next line. | addressgroup_element = create_element('address-set') |
Given the following code snippet before the placeholder: <|code_start|> IdentTypes.ICMP6: 'ident-by-icmp6-type',
None: None,
})
WellKnownServiceMap = bidict({
('tcp', 80): 'web-browsing',
('tcp', 443): 'ssl',
('tcp', 22): 'ssh',
('udp', 123): 'ntp',
('tcp', 21): 'ftp',
('tcp', 23): 'telnet',
('tcp', 25): 'smtp',
('tcp', 1521): 'oracle',
('tcp', 1433): 'mssql-db',
('tcp', 445): 'ms-ds-smb',
})
def __init__(self, pandevice_object):
self.pandevice_object = pandevice_object
self.name = self.pandevice_object.name
self.default_type = PaloAltoApplication.IdentTypeMap[self.pandevice_object.default_type]
self.services = []
if self.default_type == PaloAltoApplication.IdentTypes.PORT:
for p in self.pandevice_object.default_port:
protocol = p.split('/')[0]
port = p.split('/')[1]
for port_element in port.split(','):
<|code_end|>
, predict the next line using imports from the current file:
from orangengine.utils import enum, bidict
from orangengine.models.base import BaseService
from orangengine.models.base import BaseObject
and context including class names, function names, and sometimes code from other files:
# Path: orangengine/utils.py
# def enum(*sequential, **named):
# enums = dict(zip(sequential, range(len(sequential))), **named)
# reverse = dict((value, key) for key, value in enums.iteritems())
# enums['reverse_mapping'] = reverse
# return type('Enum', (), enums)
#
# class bidict(dict):
# """Bidirectional dictionary for two-way lookups
#
# Thanks to @Basj
# http://stackoverflow.com/questions/3318625/efficient-bidirectional-hash-table-in-python
#
# Extended to allow blind access to the inverse dict by way of __getitem__
# """
# def __init__(self, *args, **kwargs):
# super(bidict, self).__init__(*args, **kwargs)
# self.inverse = {}
# for key, value in self.iteritems():
# self.inverse.setdefault(value, []).append(key)
#
# def __setitem__(self, key, value):
# super(bidict, self).__setitem__(key, value)
# self.inverse.setdefault(value, []).append(key)
#
# def __delitem__(self, key):
# self.inverse.setdefault(self[key], []).remove(key)
# if self[key] in self.inverse and not self.inverse[self[key]]:
# del self.inverse[self[key]]
# super(bidict, self).__delitem__(key)
#
# def __getitem__(self, item):
# try:
# value = super(bidict, self).__getitem__(item)
# except KeyError:
# value = self.inverse[item]
# if value and len(value) == 1:
# value = value[0]
# return value
#
# Path: orangengine/models/base/baseservice.py
# class BaseService(BaseObject):
#
# def __init__(self, name, protocol=None, port=None):
# """init a service"""
#
# self.name = name
# self.protocol = protocol if protocol else "unknown"
# if port is not None and '-' in port:
# start = port.split('-')[0]
# stop = port.split('-')[1]
# if start != stop:
# self.port = BasePortRange(start, stop)
# else:
# self.port = start
# else:
# self.port = port if port else "unknown"
# self.terms = list()
#
# def add_term(self, term):
# """append a service term"""
#
# self.terms.append(term)
#
# def __getattr__(self, item):
#
# if item == 'value':
# if len(self.terms) > 0:
# return [t.value for t in self.terms]
# elif isinstance(self.port, BasePortRange):
# return self.protocol, self.port.value
# else:
# return self.protocol, self.port
# else:
# raise AttributeError
#
# def table_value(self, with_names):
# if with_names:
# return self.name + " - " + self.value[0] + "/" + self.value[1]
# else:
# if isinstance(self.value, list):
# return "\n".join([s[0] + "/" + s[1] for s in self.value])
# return self.value[0] + "/" + self.value[1]
#
# @classmethod
# def from_criteria(cls, criteria):
# """Create an instance from the provided criteria
# """
#
# return cls(criteria['name'], criteria['protocol'], criteria['port'])
#
# def serialize(self):
# """Searialize self to a json acceptable data structure
# """
#
# terms = []
# if self.terms:
# for term in self.terms:
# terms.append(term.serialize())
#
# if isinstance(self.port, BasePortRange):
# port = self.port.serialize()
# else:
# port = self.port
#
# return {
# 'name': self.name,
# 'terms': terms,
# 'protocol': self.protocol,
# 'port': port,
# }
#
# Path: orangengine/models/base/baseobject.py
# class BaseObject(object):
# """Base class for all (most) objects. This class should almost never be
# instantiated directly. It contains a few methods that are the available to
# all sub classes.
# """
#
# def serialize(self):
# raise NotImplementedError()
#
# def to_json(self):
# """Return a json dump of self returned from self.serialize()
# """
# return json.dumps(self.serialize())
. Output only the next line. | self.services.append(BaseService(name="{0}-{1}".format(self.name, port_element), |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
class PaloAltoAddress(BaseAddress):
"""Palo Alto Address
Inherits from BaseAddress and provides access to the underlying pandevice object.
Also provides and mapper for the type field.
"""
<|code_end|>
. Use current file imports:
from orangengine.models.base import BaseAddress
from orangengine.utils import bidict
from pandevice import objects
and context (classes, functions, or code) from other files:
# Path: orangengine/models/base/baseaddress.py
# class BaseAddress(BaseObject):
#
# AddressTypes = enum('IPv4', 'DNS', 'RANGE', 'ANY')
# TypeMap = bidict({
# AddressTypes.IPv4: 'ipv4',
# AddressTypes.DNS: 'dns',
# AddressTypes.RANGE: 'range',
# AddressTypes.ANY: 'any',
# })
#
# def __init__(self, name, value, a_type):
# """init address object"""
#
# self.name = name
# self.value = value
# self.a_type = a_type
#
# def __getattr__(self, item):
#
# if item == 'value':
# return self.value
# else:
# raise AttributeError
#
# def table_value(self, with_names):
# if with_names:
# return self.name + " - " + self.value
# else:
# return self.value
#
# @classmethod
# def from_criteria(cls, criteria):
# """Create an instance from the provided criteria
# """
#
# return cls(criteria['name'], criteria['value'], cls.TypeMap[criteria['type']])
#
# def serialize(self):
# """Searialize self to a json acceptable data structure
# """
# return {
# 'name': self.name,
# 'type': self.TypeMap[self.a_type],
# 'value': self.value,
# }
#
# Path: orangengine/utils.py
# class bidict(dict):
# """Bidirectional dictionary for two-way lookups
#
# Thanks to @Basj
# http://stackoverflow.com/questions/3318625/efficient-bidirectional-hash-table-in-python
#
# Extended to allow blind access to the inverse dict by way of __getitem__
# """
# def __init__(self, *args, **kwargs):
# super(bidict, self).__init__(*args, **kwargs)
# self.inverse = {}
# for key, value in self.iteritems():
# self.inverse.setdefault(value, []).append(key)
#
# def __setitem__(self, key, value):
# super(bidict, self).__setitem__(key, value)
# self.inverse.setdefault(value, []).append(key)
#
# def __delitem__(self, key):
# self.inverse.setdefault(self[key], []).remove(key)
# if self[key] in self.inverse and not self.inverse[self[key]]:
# del self.inverse[self[key]]
# super(bidict, self).__delitem__(key)
#
# def __getitem__(self, item):
# try:
# value = super(bidict, self).__getitem__(item)
# except KeyError:
# value = self.inverse[item]
# if value and len(value) == 1:
# value = value[0]
# return value
. Output only the next line. | TypeMap = bidict({ |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
class JuniperSRXAddress(BaseAddress):
def __init__(self, name, value, a_type):
super(JuniperSRXAddress, self).__init__(name, value, a_type)
def to_xml(self):
"""Map address objects to juniper SRX config tree elements
"""
<|code_end|>
. Use current file imports:
from orangengine.models.base import BaseAddress
from orangengine.utils import create_element
and context (classes, functions, or code) from other files:
# Path: orangengine/models/base/baseaddress.py
# class BaseAddress(BaseObject):
#
# AddressTypes = enum('IPv4', 'DNS', 'RANGE', 'ANY')
# TypeMap = bidict({
# AddressTypes.IPv4: 'ipv4',
# AddressTypes.DNS: 'dns',
# AddressTypes.RANGE: 'range',
# AddressTypes.ANY: 'any',
# })
#
# def __init__(self, name, value, a_type):
# """init address object"""
#
# self.name = name
# self.value = value
# self.a_type = a_type
#
# def __getattr__(self, item):
#
# if item == 'value':
# return self.value
# else:
# raise AttributeError
#
# def table_value(self, with_names):
# if with_names:
# return self.name + " - " + self.value
# else:
# return self.value
#
# @classmethod
# def from_criteria(cls, criteria):
# """Create an instance from the provided criteria
# """
#
# return cls(criteria['name'], criteria['value'], cls.TypeMap[criteria['type']])
#
# def serialize(self):
# """Searialize self to a json acceptable data structure
# """
# return {
# 'name': self.name,
# 'type': self.TypeMap[self.a_type],
# 'value': self.value,
# }
#
# Path: orangengine/utils.py
# def create_element(tag, text=None, parent=None):
# # create an ambiguous xml element
# if parent is not None:
# e = letree.SubElement(parent, tag)
# else:
# e = letree.Element(tag)
# if text:
# e.text = text
# return e
. Output only the next line. | address_element = create_element('address') |
Based on the snippet: <|code_start|> ----------
X : None
currently unused, left for scikit compatibility
y : scipy.sparse
label space of shape :code:`(n_samples, n_labels)`
Returns
-------
arrray of arrays of label indexes (numpy.ndarray)
label space division, each sublist represents labels that are in that community
"""
edge_map = self.graph_builder.transform(y)
if self.graph_builder.is_weighted:
self.weights_ = dict(weight=list(edge_map.values()))
else:
self.weights_ = dict(weight=None)
self.graph_ = nx.Graph()
for n in range(y.shape[1]):
self.graph_.add_node(n)
for e, w in edge_map.items():
self.graph_.add_edge(e[0], e[1], weight=w)
if self.method == 'louvain':
partition_dict = community.best_partition(self.graph_)
memberships = [partition_dict[i] for i in range(y.shape[1])]
return np.array(
<|code_end|>
, predict the immediate next line with the help of imports:
import community
import networkx as nx
import numpy as np
from networkx.algorithms.community import asyn_lpa_communities
from .base import LabelGraphClustererBase
from .helpers import _membership_to_list_of_communities
and context (classes, functions, sometimes code) from other files:
# Path: skmultilearn/cluster/base.py
# class LabelGraphClustererBase(object):
# """An abstract base class for Label Graph clustering
#
# Inherit it in your classifier according to`developer guide <../developer.ipynb>`_.
#
# """
#
# def __init__(self, graph_builder):
# """
#
# Attributes
# ----------
# graph_builder : a GraphBuilderBase derivative class
# a graph building class for the clusterer
# """
# super(LabelGraphClustererBase, self).__init__()
# self.graph_builder = graph_builder
#
# def fit_predict(self, X, y):
# """ Abstract method for clustering label space
#
# Implement it in your classifier according to`developer guide <../developer.ipynb>`_.
#
# Raises
# ------
# NotImplementedError
# this is an abstract method
# """
# raise NotImplementedError("LabelGraphClustererBase::fit_predict()")
#
# Path: skmultilearn/cluster/helpers.py
# def _membership_to_list_of_communities(membership_vector, size):
# """Convert membership vector to list of lists of vertices in each community
#
# Parameters
# ----------
# membership_vector : list of int
# community membership i.e. vertex/label `i` is in community `membership_vector[i]`
# size : int
# the number of communities present in the membership vector
#
#
# Returns
# -------
# list_of_members : list of lists of int
# list of lists of vertex/label ids in each community per community
# """
# list_of_members = [[] for _ in range(size)]
# for vertex_id, community_id in enumerate(membership_vector):
# list_of_members[community_id].append(vertex_id)
# return list_of_members
. Output only the next line. | _membership_to_list_of_communities( |
Given snippet: <|code_start|> predictions = classifier.predict(X_test)
"""
def __init__(self, clusterer=None, pass_input_space=False):
super(MatrixLabelSpaceClusterer, self).__init__()
self.clusterer = clusterer
self.pass_input_space = pass_input_space
def fit_predict(self, X, y):
"""Clusters the output space
The clusterer's :code:`fit_predict` method is executed
on either X and y.T vectors (if :code:`self.pass_input_space` is true)
or just y.T to detect clusters of labels.
The transposition of label space is used to align with
the format expected by scikit-learn classifiers, i.e. we cluster
labels with label assignment vectors as samples.
Returns
-------
arrray of arrays of label indexes (numpy.ndarray)
label space division, each sublist represents labels that are in that community
"""
if self.pass_input_space:
result = self.clusterer.fit_predict(X, y.transpose())
else:
result = self.clusterer.fit_predict(y.transpose())
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
from .base import LabelSpaceClustererBase
from .helpers import _membership_to_list_of_communities
and context:
# Path: skmultilearn/cluster/base.py
# class LabelSpaceClustererBase(BaseEstimator):
# """An abstract base class for Label Space clustering
#
# Inherit it in your classifier according to`developer guide <../developer.ipynb>`_.
#
# """
#
# def __init__(self):
# super(LabelSpaceClustererBase, self).__init__()
#
# def fit_predict(self, X, y):
# """ Abstract method for clustering label space
#
# Implement it in your classifier according to`developer guide <../developer.ipynb>`_.
#
# Raises
# ------
# NotImplementedError
# this is an abstract method
# """
# raise NotImplementedError("LabelSpaceClustererBase::fit_predict()")
#
# Path: skmultilearn/cluster/helpers.py
# def _membership_to_list_of_communities(membership_vector, size):
# """Convert membership vector to list of lists of vertices in each community
#
# Parameters
# ----------
# membership_vector : list of int
# community membership i.e. vertex/label `i` is in community `membership_vector[i]`
# size : int
# the number of communities present in the membership vector
#
#
# Returns
# -------
# list_of_members : list of lists of int
# list of lists of vertex/label ids in each community per community
# """
# list_of_members = [[] for _ in range(size)]
# for vertex_id, community_id in enumerate(membership_vector):
# list_of_members[community_id].append(vertex_id)
# return list_of_members
which might include code, classes, or functions. Output only the next line. | return np.array(_membership_to_list_of_communities(result, 1 + max(result))) |
Given the code snippet: <|code_start|>
class BalancedKMeansClustererTest(ClassifierBaseTest):
def test_actually_works_on_proper_params(self):
for X, y in self.get_multilabel_data_for_tests('sparse'):
assert sp.issparse(y)
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
import scipy.sparse as sp
from skmultilearn.cluster import balancedkmeans
from skmultilearn.tests.classifier_basetest import ClassifierBaseTest
and context (functions, classes, or occasionally code) from other files:
# Path: skmultilearn/cluster/balancedkmeans.py
# class BalancedKMeansClusterer(LabelSpaceClustererBase):
# def __init__(self, k = None, it = None):
# def fit_predict(self, X, y):
#
# Path: skmultilearn/tests/classifier_basetest.py
# class ClassifierBaseTest(unittest.TestCase):
# def get_multilabel_data_for_tests(self, sparsity_indicator):
# feed_sparse = sparsity_indicator == 'sparse'
#
# if feed_sparse:
# return [(sparse.csr_matrix(EXAMPLE_X), sparse.csr_matrix(EXAMPLE_y))]
# else:
# return [(np.matrix(EXAMPLE_X), np.matrix(EXAMPLE_y))]
#
#
# def assertClassifierWorksWithSparsity(self, classifier, sparsity_indicator='sparse'):
# for X,y in self.get_multilabel_data_for_tests(sparsity_indicator):
# X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.33, random_state=42)
# classifier.fit(X_train, y_train)
# result = classifier.predict(X_test)
# self.assertEqual(result.shape, y_test.shape)
#
# def assertClassifierWorksWithCV(self, classifier):
# # all the nice stuff is tested here - whether the classifier is
# # clonable, etc.
# for X, y in self.get_multilabel_data_for_tests('dense'):
# n_iterations = 3
# cv = model_selection.ShuffleSplit(n_splits=n_iterations, test_size=0.5, random_state=0)
#
# scores = model_selection.cross_val_score(
# classifier, X, y=y, cv=cv, scoring='accuracy')
#
# self.assertEqual(len(scores), n_iterations)
#
# def assertClassifierPredictsProbabilities(self, classifier, sparsity_indicator='sparse'):
# for X, y in self.get_multilabel_data_for_tests(sparsity_indicator):
# X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.33, random_state=42)
# classifier.fit(X_train, y_train)
# result = classifier.predict_proba(X_test)
# result = result.todense()
#
# max_value = result.max()
# min_value = result.min()
#
# self.assertEqual(result.shape, (X_test.shape[0], y.shape[1]))
# self.assertGreaterEqual(np.round(max_value), 0.0)
# self.assertGreaterEqual(np.round(min_value), 0.0)
# self.assertLessEqual(np.round(min_value), 1.0)
# self.assertLessEqual(np.round(max_value), 1.0)
. Output only the next line. | balanced = balancedkmeans.BalancedKMeansClusterer(k=3, it=50) |
Given snippet: <|code_start|>
def get_matrix_clusterers(cluster_count=3):
base_clusterers = [KMeans(cluster_count)]
for base_clusterer in base_clusterers:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
import scipy.sparse as sp
from sklearn.cluster import KMeans
from skmultilearn.cluster import MatrixLabelSpaceClusterer
from skmultilearn.tests.classifier_basetest import ClassifierBaseTest
and context:
# Path: skmultilearn/cluster/matrix.py
# class MatrixLabelSpaceClusterer(LabelSpaceClustererBase):
# """Cluster the label space using a scikit-compatible matrix-based clusterer
#
# Parameters
# ----------
# clusterer : sklearn.base.ClusterMixin
# a clonable instance of a scikit-compatible clusterer, will be automatically
# put under :code:`self.clusterer`.
# pass_input_space : bool (default is False)
# whether to take :code:`X` into consideration upon clustering,
# use only if you know that the clusterer can handle two
# parameters for clustering, will be automatically
# put under :code:`self.pass_input_space`.
#
#
# Example code for using this clusterer looks like this:
#
# .. code-block:: python
#
# from sklearn.ensemble import RandomForestClassifier
# from sklearn.cluster import KMeans
# from skmultilearn.problem_transform import LabelPowerset
# from skmultilearn.cluster import MatrixLabelSpaceClusterer
# from skmultilearn.ensemble import LabelSpacePartitioningClassifier
#
# # construct base forest classifier
# base_classifier = RandomForestClassifier(n_estimators=1030)
#
# # setup problem transformation approach with sparse matrices for random forest
# problem_transform_classifier = LabelPowerset(classifier=base_classifier,
# require_dense=[False, False])
#
# # setup the clusterer
# clusterer = MatrixLabelSpaceClusterer(clusterer=KMeans(n_clusters=3))
#
# # setup the ensemble metaclassifier
# classifier = LabelSpacePartitioningClassifier(problem_transform_classifier, clusterer)
#
# # train
# classifier.fit(X_train, y_train)
#
# # predict
# predictions = classifier.predict(X_test)
# """
#
# def __init__(self, clusterer=None, pass_input_space=False):
# super(MatrixLabelSpaceClusterer, self).__init__()
#
# self.clusterer = clusterer
# self.pass_input_space = pass_input_space
#
# def fit_predict(self, X, y):
# """Clusters the output space
#
# The clusterer's :code:`fit_predict` method is executed
# on either X and y.T vectors (if :code:`self.pass_input_space` is true)
# or just y.T to detect clusters of labels.
#
# The transposition of label space is used to align with
# the format expected by scikit-learn classifiers, i.e. we cluster
# labels with label assignment vectors as samples.
#
# Returns
# -------
# arrray of arrays of label indexes (numpy.ndarray)
# label space division, each sublist represents labels that are in that community
# """
#
# if self.pass_input_space:
# result = self.clusterer.fit_predict(X, y.transpose())
# else:
# result = self.clusterer.fit_predict(y.transpose())
# return np.array(_membership_to_list_of_communities(result, 1 + max(result)))
#
# Path: skmultilearn/tests/classifier_basetest.py
# class ClassifierBaseTest(unittest.TestCase):
# def get_multilabel_data_for_tests(self, sparsity_indicator):
# feed_sparse = sparsity_indicator == 'sparse'
#
# if feed_sparse:
# return [(sparse.csr_matrix(EXAMPLE_X), sparse.csr_matrix(EXAMPLE_y))]
# else:
# return [(np.matrix(EXAMPLE_X), np.matrix(EXAMPLE_y))]
#
#
# def assertClassifierWorksWithSparsity(self, classifier, sparsity_indicator='sparse'):
# for X,y in self.get_multilabel_data_for_tests(sparsity_indicator):
# X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.33, random_state=42)
# classifier.fit(X_train, y_train)
# result = classifier.predict(X_test)
# self.assertEqual(result.shape, y_test.shape)
#
# def assertClassifierWorksWithCV(self, classifier):
# # all the nice stuff is tested here - whether the classifier is
# # clonable, etc.
# for X, y in self.get_multilabel_data_for_tests('dense'):
# n_iterations = 3
# cv = model_selection.ShuffleSplit(n_splits=n_iterations, test_size=0.5, random_state=0)
#
# scores = model_selection.cross_val_score(
# classifier, X, y=y, cv=cv, scoring='accuracy')
#
# self.assertEqual(len(scores), n_iterations)
#
# def assertClassifierPredictsProbabilities(self, classifier, sparsity_indicator='sparse'):
# for X, y in self.get_multilabel_data_for_tests(sparsity_indicator):
# X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.33, random_state=42)
# classifier.fit(X_train, y_train)
# result = classifier.predict_proba(X_test)
# result = result.todense()
#
# max_value = result.max()
# min_value = result.min()
#
# self.assertEqual(result.shape, (X_test.shape[0], y.shape[1]))
# self.assertGreaterEqual(np.round(max_value), 0.0)
# self.assertGreaterEqual(np.round(min_value), 0.0)
# self.assertLessEqual(np.round(min_value), 1.0)
# self.assertLessEqual(np.round(max_value), 1.0)
which might include code, classes, or functions. Output only the next line. | yield MatrixLabelSpaceClusterer(base_clusterer, False) |
Based on the snippet: <|code_start|>
def get_matrix_clusterers(cluster_count=3):
base_clusterers = [KMeans(cluster_count)]
for base_clusterer in base_clusterers:
yield MatrixLabelSpaceClusterer(base_clusterer, False)
<|code_end|>
, predict the immediate next line with the help of imports:
import numpy as np
import scipy.sparse as sp
from sklearn.cluster import KMeans
from skmultilearn.cluster import MatrixLabelSpaceClusterer
from skmultilearn.tests.classifier_basetest import ClassifierBaseTest
and context (classes, functions, sometimes code) from other files:
# Path: skmultilearn/cluster/matrix.py
# class MatrixLabelSpaceClusterer(LabelSpaceClustererBase):
# """Cluster the label space using a scikit-compatible matrix-based clusterer
#
# Parameters
# ----------
# clusterer : sklearn.base.ClusterMixin
# a clonable instance of a scikit-compatible clusterer, will be automatically
# put under :code:`self.clusterer`.
# pass_input_space : bool (default is False)
# whether to take :code:`X` into consideration upon clustering,
# use only if you know that the clusterer can handle two
# parameters for clustering, will be automatically
# put under :code:`self.pass_input_space`.
#
#
# Example code for using this clusterer looks like this:
#
# .. code-block:: python
#
# from sklearn.ensemble import RandomForestClassifier
# from sklearn.cluster import KMeans
# from skmultilearn.problem_transform import LabelPowerset
# from skmultilearn.cluster import MatrixLabelSpaceClusterer
# from skmultilearn.ensemble import LabelSpacePartitioningClassifier
#
# # construct base forest classifier
# base_classifier = RandomForestClassifier(n_estimators=1030)
#
# # setup problem transformation approach with sparse matrices for random forest
# problem_transform_classifier = LabelPowerset(classifier=base_classifier,
# require_dense=[False, False])
#
# # setup the clusterer
# clusterer = MatrixLabelSpaceClusterer(clusterer=KMeans(n_clusters=3))
#
# # setup the ensemble metaclassifier
# classifier = LabelSpacePartitioningClassifier(problem_transform_classifier, clusterer)
#
# # train
# classifier.fit(X_train, y_train)
#
# # predict
# predictions = classifier.predict(X_test)
# """
#
# def __init__(self, clusterer=None, pass_input_space=False):
# super(MatrixLabelSpaceClusterer, self).__init__()
#
# self.clusterer = clusterer
# self.pass_input_space = pass_input_space
#
# def fit_predict(self, X, y):
# """Clusters the output space
#
# The clusterer's :code:`fit_predict` method is executed
# on either X and y.T vectors (if :code:`self.pass_input_space` is true)
# or just y.T to detect clusters of labels.
#
# The transposition of label space is used to align with
# the format expected by scikit-learn classifiers, i.e. we cluster
# labels with label assignment vectors as samples.
#
# Returns
# -------
# arrray of arrays of label indexes (numpy.ndarray)
# label space division, each sublist represents labels that are in that community
# """
#
# if self.pass_input_space:
# result = self.clusterer.fit_predict(X, y.transpose())
# else:
# result = self.clusterer.fit_predict(y.transpose())
# return np.array(_membership_to_list_of_communities(result, 1 + max(result)))
#
# Path: skmultilearn/tests/classifier_basetest.py
# class ClassifierBaseTest(unittest.TestCase):
# def get_multilabel_data_for_tests(self, sparsity_indicator):
# feed_sparse = sparsity_indicator == 'sparse'
#
# if feed_sparse:
# return [(sparse.csr_matrix(EXAMPLE_X), sparse.csr_matrix(EXAMPLE_y))]
# else:
# return [(np.matrix(EXAMPLE_X), np.matrix(EXAMPLE_y))]
#
#
# def assertClassifierWorksWithSparsity(self, classifier, sparsity_indicator='sparse'):
# for X,y in self.get_multilabel_data_for_tests(sparsity_indicator):
# X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.33, random_state=42)
# classifier.fit(X_train, y_train)
# result = classifier.predict(X_test)
# self.assertEqual(result.shape, y_test.shape)
#
# def assertClassifierWorksWithCV(self, classifier):
# # all the nice stuff is tested here - whether the classifier is
# # clonable, etc.
# for X, y in self.get_multilabel_data_for_tests('dense'):
# n_iterations = 3
# cv = model_selection.ShuffleSplit(n_splits=n_iterations, test_size=0.5, random_state=0)
#
# scores = model_selection.cross_val_score(
# classifier, X, y=y, cv=cv, scoring='accuracy')
#
# self.assertEqual(len(scores), n_iterations)
#
# def assertClassifierPredictsProbabilities(self, classifier, sparsity_indicator='sparse'):
# for X, y in self.get_multilabel_data_for_tests(sparsity_indicator):
# X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.33, random_state=42)
# classifier.fit(X_train, y_train)
# result = classifier.predict_proba(X_test)
# result = result.todense()
#
# max_value = result.max()
# min_value = result.min()
#
# self.assertEqual(result.shape, (X_test.shape[0], y.shape[1]))
# self.assertGreaterEqual(np.round(max_value), 0.0)
# self.assertGreaterEqual(np.round(min_value), 0.0)
# self.assertLessEqual(np.round(min_value), 1.0)
# self.assertLessEqual(np.round(max_value), 1.0)
. Output only the next line. | class MatrixLabelSpaceClustererTests(ClassifierBaseTest): |
Continue the code snippet: <|code_start|>
def get_fixed_clusterers():
cluster_cases = [
# non-overlapping
[[1,2], [0, 3, 4]],
# overlapping
[[1,2,3], [0,3,4]]
]
for clusters in cluster_cases:
clusters = np.array(clusters)
<|code_end|>
. Use current file imports:
import scipy.sparse as sp
import numpy as np
from skmultilearn.cluster import FixedLabelSpaceClusterer
from skmultilearn.tests.classifier_basetest import ClassifierBaseTest
and context (classes, functions, or code) from other files:
# Path: skmultilearn/cluster/fixed.py
# class FixedLabelSpaceClusterer(LabelSpaceClustererBase):
# """Return a fixed label space partition
#
# This clusterer takes a predefined fixed ``clustering`` of the label space and returns it in fit_predict as the label
# space division. This is useful for employing expert knowledge about label space division or partitions in ensemble
# classifiers such as: :class:`~skmultilearn.ensemble.LabelSpacePartitioningClassifier` or
# :class:`~skmultilearn.ensemble.MajorityVotingClassifier`.
#
# Parameters
# ----------
# clusters : array of arrays of int
# provided partition of the label space in the for of numpy array of
# numpy arrays of indexes for each partition, ex. ``[[0,1],[2,3]]``
#
#
# An example use of the fixed clusterer with a label partitioning classifier to train randomforests for a set of
# subproblems defined upon expert knowledge:
#
# .. code :: python
#
# from skmultilearn.ensemble import LabelSpacePartitioningClassifier
# from skmultilearn.cluster import FixedLabelSpaceClusterer
# from skmultilearn.problem_transform import LabelPowerset
# from sklearn.ensemble import RandomForestClassifier
#
# classifier = LabelSpacePartitioningClassifier(
# classifier = LabelPowerset(
# classifier=RandomForestClassifier(n_estimators=100),
# require_dense = [False, True]
# ),
# require_dense = [True, True],
# clusterer = FixedLabelSpaceClusterer(clustering=[[1,2,3], [0,4]])
# )
#
# # train
# classifier.fit(X_train, y_train)
#
# # predict
# predictions = classifier.predict(X_test)
#
# """
#
# def __init__(self, clusters=None):
# super(FixedLabelSpaceClusterer, self).__init__()
#
# self.clusters = clusters
#
# def fit_predict(self, X, y):
# """Returns the provided label space division
#
# Parameters
# ----------
# X : None
# currently unused, left for scikit compatibility
# y : scipy.sparse
# label space of shape :code:`(n_samples, n_labels)`
#
# Returns
# -------
# arrray of arrays of label indexes (numpy.ndarray)
# label space division, each sublist represents labels that are in that community
# """
#
# return self.clusters
#
# Path: skmultilearn/tests/classifier_basetest.py
# class ClassifierBaseTest(unittest.TestCase):
# def get_multilabel_data_for_tests(self, sparsity_indicator):
# feed_sparse = sparsity_indicator == 'sparse'
#
# if feed_sparse:
# return [(sparse.csr_matrix(EXAMPLE_X), sparse.csr_matrix(EXAMPLE_y))]
# else:
# return [(np.matrix(EXAMPLE_X), np.matrix(EXAMPLE_y))]
#
#
# def assertClassifierWorksWithSparsity(self, classifier, sparsity_indicator='sparse'):
# for X,y in self.get_multilabel_data_for_tests(sparsity_indicator):
# X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.33, random_state=42)
# classifier.fit(X_train, y_train)
# result = classifier.predict(X_test)
# self.assertEqual(result.shape, y_test.shape)
#
# def assertClassifierWorksWithCV(self, classifier):
# # all the nice stuff is tested here - whether the classifier is
# # clonable, etc.
# for X, y in self.get_multilabel_data_for_tests('dense'):
# n_iterations = 3
# cv = model_selection.ShuffleSplit(n_splits=n_iterations, test_size=0.5, random_state=0)
#
# scores = model_selection.cross_val_score(
# classifier, X, y=y, cv=cv, scoring='accuracy')
#
# self.assertEqual(len(scores), n_iterations)
#
# def assertClassifierPredictsProbabilities(self, classifier, sparsity_indicator='sparse'):
# for X, y in self.get_multilabel_data_for_tests(sparsity_indicator):
# X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.33, random_state=42)
# classifier.fit(X_train, y_train)
# result = classifier.predict_proba(X_test)
# result = result.todense()
#
# max_value = result.max()
# min_value = result.min()
#
# self.assertEqual(result.shape, (X_test.shape[0], y.shape[1]))
# self.assertGreaterEqual(np.round(max_value), 0.0)
# self.assertGreaterEqual(np.round(min_value), 0.0)
# self.assertLessEqual(np.round(min_value), 1.0)
# self.assertLessEqual(np.round(max_value), 1.0)
. Output only the next line. | yield clusters, FixedLabelSpaceClusterer(clusters=clusters) |
Based on the snippet: <|code_start|>
def get_fixed_clusterers():
cluster_cases = [
# non-overlapping
[[1,2], [0, 3, 4]],
# overlapping
[[1,2,3], [0,3,4]]
]
for clusters in cluster_cases:
clusters = np.array(clusters)
yield clusters, FixedLabelSpaceClusterer(clusters=clusters)
<|code_end|>
, predict the immediate next line with the help of imports:
import scipy.sparse as sp
import numpy as np
from skmultilearn.cluster import FixedLabelSpaceClusterer
from skmultilearn.tests.classifier_basetest import ClassifierBaseTest
and context (classes, functions, sometimes code) from other files:
# Path: skmultilearn/cluster/fixed.py
# class FixedLabelSpaceClusterer(LabelSpaceClustererBase):
# """Return a fixed label space partition
#
# This clusterer takes a predefined fixed ``clustering`` of the label space and returns it in fit_predict as the label
# space division. This is useful for employing expert knowledge about label space division or partitions in ensemble
# classifiers such as: :class:`~skmultilearn.ensemble.LabelSpacePartitioningClassifier` or
# :class:`~skmultilearn.ensemble.MajorityVotingClassifier`.
#
# Parameters
# ----------
# clusters : array of arrays of int
# provided partition of the label space in the for of numpy array of
# numpy arrays of indexes for each partition, ex. ``[[0,1],[2,3]]``
#
#
# An example use of the fixed clusterer with a label partitioning classifier to train randomforests for a set of
# subproblems defined upon expert knowledge:
#
# .. code :: python
#
# from skmultilearn.ensemble import LabelSpacePartitioningClassifier
# from skmultilearn.cluster import FixedLabelSpaceClusterer
# from skmultilearn.problem_transform import LabelPowerset
# from sklearn.ensemble import RandomForestClassifier
#
# classifier = LabelSpacePartitioningClassifier(
# classifier = LabelPowerset(
# classifier=RandomForestClassifier(n_estimators=100),
# require_dense = [False, True]
# ),
# require_dense = [True, True],
# clusterer = FixedLabelSpaceClusterer(clustering=[[1,2,3], [0,4]])
# )
#
# # train
# classifier.fit(X_train, y_train)
#
# # predict
# predictions = classifier.predict(X_test)
#
# """
#
# def __init__(self, clusters=None):
# super(FixedLabelSpaceClusterer, self).__init__()
#
# self.clusters = clusters
#
# def fit_predict(self, X, y):
# """Returns the provided label space division
#
# Parameters
# ----------
# X : None
# currently unused, left for scikit compatibility
# y : scipy.sparse
# label space of shape :code:`(n_samples, n_labels)`
#
# Returns
# -------
# arrray of arrays of label indexes (numpy.ndarray)
# label space division, each sublist represents labels that are in that community
# """
#
# return self.clusters
#
# Path: skmultilearn/tests/classifier_basetest.py
# class ClassifierBaseTest(unittest.TestCase):
# def get_multilabel_data_for_tests(self, sparsity_indicator):
# feed_sparse = sparsity_indicator == 'sparse'
#
# if feed_sparse:
# return [(sparse.csr_matrix(EXAMPLE_X), sparse.csr_matrix(EXAMPLE_y))]
# else:
# return [(np.matrix(EXAMPLE_X), np.matrix(EXAMPLE_y))]
#
#
# def assertClassifierWorksWithSparsity(self, classifier, sparsity_indicator='sparse'):
# for X,y in self.get_multilabel_data_for_tests(sparsity_indicator):
# X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.33, random_state=42)
# classifier.fit(X_train, y_train)
# result = classifier.predict(X_test)
# self.assertEqual(result.shape, y_test.shape)
#
# def assertClassifierWorksWithCV(self, classifier):
# # all the nice stuff is tested here - whether the classifier is
# # clonable, etc.
# for X, y in self.get_multilabel_data_for_tests('dense'):
# n_iterations = 3
# cv = model_selection.ShuffleSplit(n_splits=n_iterations, test_size=0.5, random_state=0)
#
# scores = model_selection.cross_val_score(
# classifier, X, y=y, cv=cv, scoring='accuracy')
#
# self.assertEqual(len(scores), n_iterations)
#
# def assertClassifierPredictsProbabilities(self, classifier, sparsity_indicator='sparse'):
# for X, y in self.get_multilabel_data_for_tests(sparsity_indicator):
# X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.33, random_state=42)
# classifier.fit(X_train, y_train)
# result = classifier.predict_proba(X_test)
# result = result.todense()
#
# max_value = result.max()
# min_value = result.min()
#
# self.assertEqual(result.shape, (X_test.shape[0], y.shape[1]))
# self.assertGreaterEqual(np.round(max_value), 0.0)
# self.assertGreaterEqual(np.round(min_value), 0.0)
# self.assertLessEqual(np.round(min_value), 1.0)
# self.assertLessEqual(np.round(max_value), 1.0)
. Output only the next line. | class FixedLabelSpaceClustererTests(ClassifierBaseTest): |
Continue the code snippet: <|code_start|>
Parameters
----------
X : array-like or sparse matrix
An input feature matrix of shape :code:`(n_samples, n_features)`
sparse_format: str
Requested format of returned scipy.sparse matrix, if sparse is returned
enforce_sparse : bool
Ignore require_dense and enforce sparsity, useful internally
Returns
-------
array-like or sparse matrix
Transformed X values of shape :code:`(n_samples, n_features)`
.. note:: If :code:`require_dense` was set to :code:`True` for
input features in the constructor, the returned value is an
array-like of array-likes. If :code:`require_dense` is
set to :code:`false`, a sparse matrix of format
:code:`sparse_format` is returned, if possible - without cloning.
"""
is_sparse = issparse(X)
if is_sparse:
if self.require_dense[0] and not enforce_sparse:
return X.toarray()
else:
if sparse_format is None:
return X
else:
<|code_end|>
. Use current file imports:
import numpy as np
from ..utils import get_matrix_in_format, matrix_creation_function_for_format
from scipy.sparse import issparse
from sklearn.base import BaseEstimator, ClassifierMixin
and context (classes, functions, or code) from other files:
# Path: skmultilearn/utils.py
# def get_matrix_in_format(original_matrix, matrix_format):
# """Converts matrix to format
#
# Parameters
# ----------
#
# original_matrix : np.matrix or scipy matrix or np.array of np. arrays
# matrix to convert
#
# matrix_format : string
# format
#
# Returns
# -------
#
# matrix : scipy matrix
# matrix in given format
# """
# if isinstance(original_matrix, np.ndarray):
# return SPARSE_FORMAT_TO_CONSTRUCTOR[matrix_format](original_matrix)
#
# if original_matrix.getformat() == matrix_format:
# return original_matrix
#
# return original_matrix.asformat(matrix_format)
#
# def matrix_creation_function_for_format(sparse_format):
# if sparse_format not in SPARSE_FORMAT_TO_CONSTRUCTOR:
# return None
#
# return SPARSE_FORMAT_TO_CONSTRUCTOR[sparse_format]
. Output only the next line. | return get_matrix_in_format(X, sparse_format) |
Predict the next line after this snippet: <|code_start|> Requested format of returned scipy.sparse matrix, if sparse is returned
enforce_sparse : bool
Ignore require_dense and enforce sparsity, useful internally
Returns
-------
array-like or sparse matrix
Transformed X values of shape :code:`(n_samples, n_features)`
.. note:: If :code:`require_dense` was set to :code:`True` for
input features in the constructor, the returned value is an
array-like of array-likes. If :code:`require_dense` is
set to :code:`false`, a sparse matrix of format
:code:`sparse_format` is returned, if possible - without cloning.
"""
is_sparse = issparse(X)
if is_sparse:
if self.require_dense[0] and not enforce_sparse:
return X.toarray()
else:
if sparse_format is None:
return X
else:
return get_matrix_in_format(X, sparse_format)
else:
if self.require_dense[0] and not enforce_sparse:
# TODO: perhaps a check_array?
return X
else:
<|code_end|>
using the current file's imports:
import numpy as np
from ..utils import get_matrix_in_format, matrix_creation_function_for_format
from scipy.sparse import issparse
from sklearn.base import BaseEstimator, ClassifierMixin
and any relevant context from other files:
# Path: skmultilearn/utils.py
# def get_matrix_in_format(original_matrix, matrix_format):
# """Converts matrix to format
#
# Parameters
# ----------
#
# original_matrix : np.matrix or scipy matrix or np.array of np. arrays
# matrix to convert
#
# matrix_format : string
# format
#
# Returns
# -------
#
# matrix : scipy matrix
# matrix in given format
# """
# if isinstance(original_matrix, np.ndarray):
# return SPARSE_FORMAT_TO_CONSTRUCTOR[matrix_format](original_matrix)
#
# if original_matrix.getformat() == matrix_format:
# return original_matrix
#
# return original_matrix.asformat(matrix_format)
#
# def matrix_creation_function_for_format(sparse_format):
# if sparse_format not in SPARSE_FORMAT_TO_CONSTRUCTOR:
# return None
#
# return SPARSE_FORMAT_TO_CONSTRUCTOR[sparse_format]
. Output only the next line. | return matrix_creation_function_for_format(sparse_format)(X) |
Using the snippet: <|code_start|> ----------
X : currently unused, left for scikit compatibility
y : scipy.sparse
label space of shape :code:`(n_samples, n_labels)`
Returns
-------
array of arrays
numpy array of arrays of label indexes, where each sub-array
represents labels that are in a separate community
"""
number_of_labels = y.shape[1]
#Assign a label to a cluster no. label ordinal % number of labeSls
#We have to do the balance k-means and then use it for HOMER with the label powerset
Centers =[]
y = y.todense()
for i in range(0, self.k):
auxVector = y[:, random.randint(0, number_of_labels-1)]
Centers.append(np.asarray(auxVector))
#Now we have the clusters created and we need to make each label its corresponding cluster
while self.it > 0:
balancedCluster = []
for j in range(0, number_of_labels):
auxVector = y[:,j]
v = np.asarray(auxVector)
#Now we calculate the distance and store it in an array
distances = []
for i in range(0, self.k):
#Store the distances
<|code_end|>
, determine the next line of code. You have imports:
import numpy as np
import random
from .base import LabelSpaceClustererBase
from .helpers import _euclidean_distance, _recalculateCenters, _countNumberOfAparitions
and context (class names, function names, or code) available:
# Path: skmultilearn/cluster/base.py
# class LabelSpaceClustererBase(BaseEstimator):
# """An abstract base class for Label Space clustering
#
# Inherit it in your classifier according to`developer guide <../developer.ipynb>`_.
#
# """
#
# def __init__(self):
# super(LabelSpaceClustererBase, self).__init__()
#
# def fit_predict(self, X, y):
# """ Abstract method for clustering label space
#
# Implement it in your classifier according to`developer guide <../developer.ipynb>`_.
#
# Raises
# ------
# NotImplementedError
# this is an abstract method
# """
# raise NotImplementedError("LabelSpaceClustererBase::fit_predict()")
#
# Path: skmultilearn/cluster/helpers.py
# def _euclidean_distance(array1, array2):
# """Returns the euclidean distance of two arrays
#
# Parameters
# ----------
# array1 : array of numbers
#
# array2 : array of numbers
#
# Returns
# -------
# distance : float
# float with the euclidean distance, False if not possible
# """
# #Ensure that both arrays hava the same length
# if len(array1) != len(array2):
# return False
# else:
# distance = 0.0
# for i in range(0, len(array1)):
# distance = distance + pow(array1[i] - array2[i], 2)
# distance = math.sqrt(distance)
# return distance
#
# def _recalculateCenters(y, balancedCluster, k):
#
# Centers = []
# kAux = 0
# while kAux < k:
# vectorAux = np.zeros(len(y))
# for i in range(0, len(balancedCluster)):
#
# if int(kAux) == int(balancedCluster[i]):
# #We have to fill the vector
# for j in range(0, len(y)):
# vectorAux[j] += y[j,i]
#
# vectorAux /= k
# Centers.append(vectorAux)
# kAux += 1
# return Centers
#
# def _countNumberOfAparitions(array, number):
# """Number of aparitions of a number in an array
#
# Parameters
# ----------
# array : array of numbers
#
# number : number to search for
#
# Returns
# -------
# aparaitions : int
# Number of aparitions of the number in the given array
# """
# aparitions = 0
# for i in range(0, len(array)):
# if array[i] == number:
# aparitions += 1
# return aparitions
. Output only the next line. | distances.append(_euclidean_distance(v, Centers[i])) |
Given snippet: <|code_start|> Centers =[]
y = y.todense()
for i in range(0, self.k):
auxVector = y[:, random.randint(0, number_of_labels-1)]
Centers.append(np.asarray(auxVector))
#Now we have the clusters created and we need to make each label its corresponding cluster
while self.it > 0:
balancedCluster = []
for j in range(0, number_of_labels):
auxVector = y[:,j]
v = np.asarray(auxVector)
#Now we calculate the distance and store it in an array
distances = []
for i in range(0, self.k):
#Store the distances
distances.append(_euclidean_distance(v, Centers[i]))
finished = False
while not finished:
minIndex = np.argmin(distances)
balancedCluster.append(minIndex)
#Now we have the cluster we want to add this label to
numberOfAparitions = _countNumberOfAparitions(balancedCluster, minIndex)
if float(numberOfAparitions) > (float(float(number_of_labels)/float(self.k))+1):
distances[minIndex] = float("inf")
balancedCluster.pop()
else:
finished = True
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
import random
from .base import LabelSpaceClustererBase
from .helpers import _euclidean_distance, _recalculateCenters, _countNumberOfAparitions
and context:
# Path: skmultilearn/cluster/base.py
# class LabelSpaceClustererBase(BaseEstimator):
# """An abstract base class for Label Space clustering
#
# Inherit it in your classifier according to`developer guide <../developer.ipynb>`_.
#
# """
#
# def __init__(self):
# super(LabelSpaceClustererBase, self).__init__()
#
# def fit_predict(self, X, y):
# """ Abstract method for clustering label space
#
# Implement it in your classifier according to`developer guide <../developer.ipynb>`_.
#
# Raises
# ------
# NotImplementedError
# this is an abstract method
# """
# raise NotImplementedError("LabelSpaceClustererBase::fit_predict()")
#
# Path: skmultilearn/cluster/helpers.py
# def _euclidean_distance(array1, array2):
# """Returns the euclidean distance of two arrays
#
# Parameters
# ----------
# array1 : array of numbers
#
# array2 : array of numbers
#
# Returns
# -------
# distance : float
# float with the euclidean distance, False if not possible
# """
# #Ensure that both arrays hava the same length
# if len(array1) != len(array2):
# return False
# else:
# distance = 0.0
# for i in range(0, len(array1)):
# distance = distance + pow(array1[i] - array2[i], 2)
# distance = math.sqrt(distance)
# return distance
#
# def _recalculateCenters(y, balancedCluster, k):
#
# Centers = []
# kAux = 0
# while kAux < k:
# vectorAux = np.zeros(len(y))
# for i in range(0, len(balancedCluster)):
#
# if int(kAux) == int(balancedCluster[i]):
# #We have to fill the vector
# for j in range(0, len(y)):
# vectorAux[j] += y[j,i]
#
# vectorAux /= k
# Centers.append(vectorAux)
# kAux += 1
# return Centers
#
# def _countNumberOfAparitions(array, number):
# """Number of aparitions of a number in an array
#
# Parameters
# ----------
# array : array of numbers
#
# number : number to search for
#
# Returns
# -------
# aparaitions : int
# Number of aparitions of the number in the given array
# """
# aparitions = 0
# for i in range(0, len(array)):
# if array[i] == number:
# aparitions += 1
# return aparitions
which might include code, classes, or functions. Output only the next line. | Centers = _recalculateCenters(np.asarray(y), balancedCluster, self.k) |
Given the following code snippet before the placeholder: <|code_start|> -------
array of arrays
numpy array of arrays of label indexes, where each sub-array
represents labels that are in a separate community
"""
number_of_labels = y.shape[1]
#Assign a label to a cluster no. label ordinal % number of labeSls
#We have to do the balance k-means and then use it for HOMER with the label powerset
Centers =[]
y = y.todense()
for i in range(0, self.k):
auxVector = y[:, random.randint(0, number_of_labels-1)]
Centers.append(np.asarray(auxVector))
#Now we have the clusters created and we need to make each label its corresponding cluster
while self.it > 0:
balancedCluster = []
for j in range(0, number_of_labels):
auxVector = y[:,j]
v = np.asarray(auxVector)
#Now we calculate the distance and store it in an array
distances = []
for i in range(0, self.k):
#Store the distances
distances.append(_euclidean_distance(v, Centers[i]))
finished = False
while not finished:
minIndex = np.argmin(distances)
balancedCluster.append(minIndex)
#Now we have the cluster we want to add this label to
<|code_end|>
, predict the next line using imports from the current file:
import numpy as np
import random
from .base import LabelSpaceClustererBase
from .helpers import _euclidean_distance, _recalculateCenters, _countNumberOfAparitions
and context including class names, function names, and sometimes code from other files:
# Path: skmultilearn/cluster/base.py
# class LabelSpaceClustererBase(BaseEstimator):
# """An abstract base class for Label Space clustering
#
# Inherit it in your classifier according to`developer guide <../developer.ipynb>`_.
#
# """
#
# def __init__(self):
# super(LabelSpaceClustererBase, self).__init__()
#
# def fit_predict(self, X, y):
# """ Abstract method for clustering label space
#
# Implement it in your classifier according to`developer guide <../developer.ipynb>`_.
#
# Raises
# ------
# NotImplementedError
# this is an abstract method
# """
# raise NotImplementedError("LabelSpaceClustererBase::fit_predict()")
#
# Path: skmultilearn/cluster/helpers.py
# def _euclidean_distance(array1, array2):
# """Returns the euclidean distance of two arrays
#
# Parameters
# ----------
# array1 : array of numbers
#
# array2 : array of numbers
#
# Returns
# -------
# distance : float
# float with the euclidean distance, False if not possible
# """
# #Ensure that both arrays hava the same length
# if len(array1) != len(array2):
# return False
# else:
# distance = 0.0
# for i in range(0, len(array1)):
# distance = distance + pow(array1[i] - array2[i], 2)
# distance = math.sqrt(distance)
# return distance
#
# def _recalculateCenters(y, balancedCluster, k):
#
# Centers = []
# kAux = 0
# while kAux < k:
# vectorAux = np.zeros(len(y))
# for i in range(0, len(balancedCluster)):
#
# if int(kAux) == int(balancedCluster[i]):
# #We have to fill the vector
# for j in range(0, len(y)):
# vectorAux[j] += y[j,i]
#
# vectorAux /= k
# Centers.append(vectorAux)
# kAux += 1
# return Centers
#
# def _countNumberOfAparitions(array, number):
# """Number of aparitions of a number in an array
#
# Parameters
# ----------
# array : array of numbers
#
# number : number to search for
#
# Returns
# -------
# aparaitions : int
# Number of aparitions of the number in the given array
# """
# aparitions = 0
# for i in range(0, len(array)):
# if array[i] == number:
# aparitions += 1
# return aparitions
. Output only the next line. | numberOfAparitions = _countNumberOfAparitions(balancedCluster, minIndex) |
Predict the next line after this snippet: <|code_start|> if include_self_edges and (normalize_self_edges not in [True, False]):
raise ValueError("Decision whether to normalize self edges needs to be a boolean")
if normalize_self_edges and not include_self_edges:
raise ValueError("Include self edges must be set to true if normalization is true")
if normalize_self_edges and not weighted:
raise ValueError("Normalizing self-edge weights_ does not make sense in an unweighted graph")
self.is_weighted = weighted
self.include_self_edges = include_self_edges
self.normalize_self_edges = normalize_self_edges
def transform(self, y):
"""Generate adjacency matrix from label matrix
This function generates a weighted or unweighted co-occurence Label Graph adjacency matrix in dictionary of keys
format based on input binary label vectors
Parameters
----------
y : numpy.ndarray or scipy.sparse
dense or sparse binary matrix with shape
:code:`(n_samples, n_labels)`
Returns
-------
Dict[(int, int), float]
weight map with a tuple of label indexes as keys and a the number of samples in which the two co-occurred
"""
<|code_end|>
using the current file's imports:
from builtins import object
from ..utils import get_matrix_in_format
from sklearn.base import BaseEstimator
and any relevant context from other files:
# Path: skmultilearn/utils.py
# def get_matrix_in_format(original_matrix, matrix_format):
# """Converts matrix to format
#
# Parameters
# ----------
#
# original_matrix : np.matrix or scipy matrix or np.array of np. arrays
# matrix to convert
#
# matrix_format : string
# format
#
# Returns
# -------
#
# matrix : scipy matrix
# matrix in given format
# """
# if isinstance(original_matrix, np.ndarray):
# return SPARSE_FORMAT_TO_CONSTRUCTOR[matrix_format](original_matrix)
#
# if original_matrix.getformat() == matrix_format:
# return original_matrix
#
# return original_matrix.asformat(matrix_format)
. Output only the next line. | label_data = get_matrix_in_format(y, 'lil') |
Based on the snippet: <|code_start|> def test_ensure_input_format_returns_sparse_from_sparse_if_required(self):
classifier = ProblemTransformationBase(require_dense=False)
X = sp.csr_matrix(np.zeros((2, 3)))
ensured_X = classifier._ensure_input_format(X)
self.assertTrue(sp.issparse(ensured_X))
self.sparse_and_sparse_matrices_are_the_same(X, ensured_X)
def test_ensure_input_format_returns_sparse_from_dense_if_enforced(self):
for require_dense in itertools.product([True, False], repeat=2):
classifier = ProblemTransformationBase(require_dense=require_dense)
X = np.zeros((2, 3))
ensured_X = classifier._ensure_input_format(X, enforce_sparse=True)
self.assertTrue(sp.issparse(ensured_X))
self.dense_and_sparse_matrices_are_the_same(X, ensured_X)
def test_ensure_input_format_returns_sparse_from_sparse_if_enforced(self):
for require_dense in itertools.product([True, False], repeat=2):
classifier = ProblemTransformationBase(require_dense=require_dense)
X = sp.csr_matrix(np.zeros((2, 3)))
ensured_X = classifier._ensure_input_format(X, enforce_sparse=True)
self.assertTrue(sp.issparse(ensured_X))
self.sparse_and_sparse_matrices_are_the_same(X, ensured_X)
def test_ensure_input_format_returns_sparse_in_format_from_dense_if_enforced(self):
<|code_end|>
, predict the immediate next line with the help of imports:
import itertools
import unittest
import numpy as np
import scipy.sparse as sp
from builtins import range
from builtins import zip
from sklearn.base import BaseEstimator
from .test_utils import SPARSE_MATRIX_FORMATS
from ..base import ProblemTransformationBase
and context (classes, functions, sometimes code) from other files:
# Path: skmultilearn/tests/test_utils.py
# SPARSE_MATRIX_FORMATS = ["bsr", "coo", "csc", "csr", "dia", "dok", "lil"]
#
# Path: skmultilearn/base/problem_transformation.py
# class ProblemTransformationBase(MLClassifierBase):
# """Base class providing common functions for multi-label classifiers
# that follow the problem transformation approach.
#
# Problem transformation is the approach in which the
# original multi-label classification problem is transformed into one
# or more single-label problems, which are then solved by single-class
# or multi-class classifiers.
#
# Scikit-multilearn provides a number of such methods:
#
# - :class:`BinaryRelevance` - performs a single-label single-class classification for each label and sums the results :class:`BinaryRelevance`
# - :class:`ClassifierChains` - performs a single-label single-class classification for each label and sums the results :class:`ClassifierChain`
# - :class:`LabelPowerset` - performs a single-label single-class classification for each label and sums the results :class:`LabelPowerset`
#
# Parameters
# ----------
# classifier : scikit classifier type
# The base classifier that will be used in a class, will be automagically put under self.classifier for future access.
# require_dense : boolean (default is False)
# Whether the base classifier requires input as dense arrays.
# """
#
# def __init__(self, classifier=None, require_dense=None):
#
# super(ProblemTransformationBase, self).__init__()
#
# self.copyable_attrs = ["classifier", "require_dense"]
#
# self.classifier = classifier
# if require_dense is not None:
# if isinstance(require_dense, bool):
# self.require_dense = [require_dense, require_dense]
# else:
# assert len(require_dense) == 2 and isinstance(
# require_dense[0], bool) and isinstance(require_dense[1], bool)
# self.require_dense = require_dense
#
# else:
# if isinstance(self.classifier, MLClassifierBase):
# self.require_dense = [False, False]
# else:
# self.require_dense = [True, True]
#
# def _ensure_multi_label_from_single_class(self, matrix, matrix_format='csr'):
# """Transform single class outputs to a 2D sparse matrix
#
# Parameters
# ----------
# matrix : array-like
# input matrix to be checked
# matrix_format : str (default is csr)
# the matrix format to validate with
#
# Returns
# -------
# scipy.sparse
# a 2-dimensional sparse matrix
# """
# is_2d = None
# dim_1 = None
# dim_2 = None
#
# # check if array like of array likes
# if isinstance(matrix, (list, tuple, np.ndarray)):
# if isinstance(matrix[0], (list, tuple, np.ndarray)):
# is_2d = True
# dim_1 = len(matrix)
# dim_2 = len(matrix[0])
# # 1d list or array
# else:
# is_2d = False
# # shape is n_samples of 1 class assignment
# dim_1 = len(matrix)
# dim_2 = 1
#
# # not an array but 2D, probably a matrix
# elif matrix.ndim == 2:
# is_2d = True
# dim_1 = matrix.shape[0]
# dim_2 = matrix.shape[1]
#
# # what is it?
# else:
# raise ValueError("Matrix dimensions too large (>2) or other value error")
#
# new_matrix = None
# if is_2d:
# if issparse(matrix):
# new_matrix = matrix
# else:
# new_matrix = matrix_creation_function_for_format(matrix_format)(matrix, shape=(dim_1, dim_2))
# else:
# new_matrix = matrix_creation_function_for_format(matrix_format)(matrix).T
#
# assert new_matrix.shape == (dim_1, dim_2)
# return new_matrix
. Output only the next line. | for sparse_format in SPARSE_MATRIX_FORMATS: |
Here is a snippet: <|code_start|> else:
self.assertEqual(y[row][column], y_ensured[row * stride + column])
def dense_and_dense_matrices_are_the_same(self, X, ensured_X):
self.assertEqual(len(X), len(ensured_X))
for row in range(len(X)):
self.assertEqual(len(X[row]), len(ensured_X[row]))
for col in range(len(X[row])):
self.assertEqual(X[row][col], ensured_X[row][col])
def dense_and_sparse_matrices_are_the_same(self, X, ensured_X):
self.assertEqual(len(X), ensured_X.shape[0])
for row in range(len(X)):
self.assertEqual(len(X[row]), ensured_X.shape[1])
for col in range(len(X[row])):
self.assertEqual(X[row][col], ensured_X[row, col])
def sparse_and_sparse_matrices_are_the_same(self, X, ensured_X):
self.assertEqual(X.shape, ensured_X.shape)
# compare sparse matrices per
# http://stackoverflow.com/questions/30685024/check-if-two-scipy-sparse-csr-matrix-are-equal
self.assertTrue((X != ensured_X).nnz == 0)
def test_if_require_dense_is_correctly_set(self):
values = [True, False, [True, False], [
True, True], [False, False], [False, True]]
expected_values = [[True, True], [False, False], [
True, False], [True, True], [False, False], [False, True]]
for value, expected_value in zip(values, expected_values):
<|code_end|>
. Write the next line using the current file imports:
import itertools
import unittest
import numpy as np
import scipy.sparse as sp
from builtins import range
from builtins import zip
from sklearn.base import BaseEstimator
from .test_utils import SPARSE_MATRIX_FORMATS
from ..base import ProblemTransformationBase
and context from other files:
# Path: skmultilearn/tests/test_utils.py
# SPARSE_MATRIX_FORMATS = ["bsr", "coo", "csc", "csr", "dia", "dok", "lil"]
#
# Path: skmultilearn/base/problem_transformation.py
# class ProblemTransformationBase(MLClassifierBase):
# """Base class providing common functions for multi-label classifiers
# that follow the problem transformation approach.
#
# Problem transformation is the approach in which the
# original multi-label classification problem is transformed into one
# or more single-label problems, which are then solved by single-class
# or multi-class classifiers.
#
# Scikit-multilearn provides a number of such methods:
#
# - :class:`BinaryRelevance` - performs a single-label single-class classification for each label and sums the results :class:`BinaryRelevance`
# - :class:`ClassifierChains` - performs a single-label single-class classification for each label and sums the results :class:`ClassifierChain`
# - :class:`LabelPowerset` - performs a single-label single-class classification for each label and sums the results :class:`LabelPowerset`
#
# Parameters
# ----------
# classifier : scikit classifier type
# The base classifier that will be used in a class, will be automagically put under self.classifier for future access.
# require_dense : boolean (default is False)
# Whether the base classifier requires input as dense arrays.
# """
#
# def __init__(self, classifier=None, require_dense=None):
#
# super(ProblemTransformationBase, self).__init__()
#
# self.copyable_attrs = ["classifier", "require_dense"]
#
# self.classifier = classifier
# if require_dense is not None:
# if isinstance(require_dense, bool):
# self.require_dense = [require_dense, require_dense]
# else:
# assert len(require_dense) == 2 and isinstance(
# require_dense[0], bool) and isinstance(require_dense[1], bool)
# self.require_dense = require_dense
#
# else:
# if isinstance(self.classifier, MLClassifierBase):
# self.require_dense = [False, False]
# else:
# self.require_dense = [True, True]
#
# def _ensure_multi_label_from_single_class(self, matrix, matrix_format='csr'):
# """Transform single class outputs to a 2D sparse matrix
#
# Parameters
# ----------
# matrix : array-like
# input matrix to be checked
# matrix_format : str (default is csr)
# the matrix format to validate with
#
# Returns
# -------
# scipy.sparse
# a 2-dimensional sparse matrix
# """
# is_2d = None
# dim_1 = None
# dim_2 = None
#
# # check if array like of array likes
# if isinstance(matrix, (list, tuple, np.ndarray)):
# if isinstance(matrix[0], (list, tuple, np.ndarray)):
# is_2d = True
# dim_1 = len(matrix)
# dim_2 = len(matrix[0])
# # 1d list or array
# else:
# is_2d = False
# # shape is n_samples of 1 class assignment
# dim_1 = len(matrix)
# dim_2 = 1
#
# # not an array but 2D, probably a matrix
# elif matrix.ndim == 2:
# is_2d = True
# dim_1 = matrix.shape[0]
# dim_2 = matrix.shape[1]
#
# # what is it?
# else:
# raise ValueError("Matrix dimensions too large (>2) or other value error")
#
# new_matrix = None
# if is_2d:
# if issparse(matrix):
# new_matrix = matrix
# else:
# new_matrix = matrix_creation_function_for_format(matrix_format)(matrix, shape=(dim_1, dim_2))
# else:
# new_matrix = matrix_creation_function_for_format(matrix_format)(matrix).T
#
# assert new_matrix.shape == (dim_1, dim_2)
# return new_matrix
, which may include functions, classes, or code. Output only the next line. | classifier = ProblemTransformationBase( |
Given the following code snippet before the placeholder: <|code_start|>
SPARSE_MATRIX_FORMATS = ["bsr", "coo", "csc", "csr", "dia", "dok", "lil"]
class UtilsTest(unittest.TestCase):
def test_if_get_matrix_ensures_type(self):
matrix = sp.csr_matrix([])
for sparse_format in SPARSE_MATRIX_FORMATS:
<|code_end|>
, predict the next line using imports from the current file:
import unittest
import numpy as np
import scipy.sparse as sp
from ..utils import get_matrix_in_format, matrix_creation_function_for_format
and context including class names, function names, and sometimes code from other files:
# Path: skmultilearn/utils.py
# def get_matrix_in_format(original_matrix, matrix_format):
# """Converts matrix to format
#
# Parameters
# ----------
#
# original_matrix : np.matrix or scipy matrix or np.array of np. arrays
# matrix to convert
#
# matrix_format : string
# format
#
# Returns
# -------
#
# matrix : scipy matrix
# matrix in given format
# """
# if isinstance(original_matrix, np.ndarray):
# return SPARSE_FORMAT_TO_CONSTRUCTOR[matrix_format](original_matrix)
#
# if original_matrix.getformat() == matrix_format:
# return original_matrix
#
# return original_matrix.asformat(matrix_format)
#
# def matrix_creation_function_for_format(sparse_format):
# if sparse_format not in SPARSE_FORMAT_TO_CONSTRUCTOR:
# return None
#
# return SPARSE_FORMAT_TO_CONSTRUCTOR[sparse_format]
. Output only the next line. | new_matrix = get_matrix_in_format(matrix, sparse_format) |
Using the snippet: <|code_start|>
SPARSE_MATRIX_FORMATS = ["bsr", "coo", "csc", "csr", "dia", "dok", "lil"]
class UtilsTest(unittest.TestCase):
def test_if_get_matrix_ensures_type(self):
matrix = sp.csr_matrix([])
for sparse_format in SPARSE_MATRIX_FORMATS:
new_matrix = get_matrix_in_format(matrix, sparse_format)
self.assertTrue(sp.issparse(new_matrix))
self.assertTrue(new_matrix.format == sparse_format)
def test_if_matrix_creation_follows_format(self):
matrix = np.matrix([])
for sparse_format in SPARSE_MATRIX_FORMATS:
<|code_end|>
, determine the next line of code. You have imports:
import unittest
import numpy as np
import scipy.sparse as sp
from ..utils import get_matrix_in_format, matrix_creation_function_for_format
and context (class names, function names, or code) available:
# Path: skmultilearn/utils.py
# def get_matrix_in_format(original_matrix, matrix_format):
# """Converts matrix to format
#
# Parameters
# ----------
#
# original_matrix : np.matrix or scipy matrix or np.array of np. arrays
# matrix to convert
#
# matrix_format : string
# format
#
# Returns
# -------
#
# matrix : scipy matrix
# matrix in given format
# """
# if isinstance(original_matrix, np.ndarray):
# return SPARSE_FORMAT_TO_CONSTRUCTOR[matrix_format](original_matrix)
#
# if original_matrix.getformat() == matrix_format:
# return original_matrix
#
# return original_matrix.asformat(matrix_format)
#
# def matrix_creation_function_for_format(sparse_format):
# if sparse_format not in SPARSE_FORMAT_TO_CONSTRUCTOR:
# return None
#
# return SPARSE_FORMAT_TO_CONSTRUCTOR[sparse_format]
. Output only the next line. | new_matrix = matrix_creation_function_for_format( |
Based on the snippet: <|code_start|> overlap=self.allow_overlap
)
return self._detect_communities()
def _detect_communities(self):
if self.nested:
lowest_level = self.model_.get_levels()[0]
else:
lowest_level = self.model_
number_of_communities = lowest_level.get_B()
if self.allow_overlap:
# the overlaps block returns
# membership vector, and also edges vectors, we need just the membership here at the moment
membership_vector = list(lowest_level.get_overlap_blocks()[0])
else:
membership_vector = list(lowest_level.get_blocks())
if self.allow_overlap:
return _overlapping_membership_to_list_of_communities(membership_vector, number_of_communities)
return _membership_to_list_of_communities(membership_vector, number_of_communities)
def _model_fit_function(self):
if self.nested:
return gt.minimize_nested_blockmodel_dl
else:
return gt.minimize_blockmodel_dl
<|code_end|>
, predict the immediate next line with the help of imports:
import graph_tool.all as gt
import numpy as np
from .base import LabelGraphClustererBase
from .helpers import _membership_to_list_of_communities, _overlapping_membership_to_list_of_communities
and context (classes, functions, sometimes code) from other files:
# Path: skmultilearn/cluster/base.py
# class LabelGraphClustererBase(object):
# """An abstract base class for Label Graph clustering
#
# Inherit it in your classifier according to`developer guide <../developer.ipynb>`_.
#
# """
#
# def __init__(self, graph_builder):
# """
#
# Attributes
# ----------
# graph_builder : a GraphBuilderBase derivative class
# a graph building class for the clusterer
# """
# super(LabelGraphClustererBase, self).__init__()
# self.graph_builder = graph_builder
#
# def fit_predict(self, X, y):
# """ Abstract method for clustering label space
#
# Implement it in your classifier according to`developer guide <../developer.ipynb>`_.
#
# Raises
# ------
# NotImplementedError
# this is an abstract method
# """
# raise NotImplementedError("LabelGraphClustererBase::fit_predict()")
#
# Path: skmultilearn/cluster/helpers.py
# def _membership_to_list_of_communities(membership_vector, size):
# """Convert membership vector to list of lists of vertices in each community
#
# Parameters
# ----------
# membership_vector : list of int
# community membership i.e. vertex/label `i` is in community `membership_vector[i]`
# size : int
# the number of communities present in the membership vector
#
#
# Returns
# -------
# list_of_members : list of lists of int
# list of lists of vertex/label ids in each community per community
# """
# list_of_members = [[] for _ in range(size)]
# for vertex_id, community_id in enumerate(membership_vector):
# list_of_members[community_id].append(vertex_id)
# return list_of_members
#
# def _overlapping_membership_to_list_of_communities(membership_vector, size):
# """Convert membership vector to list of lists of vertices/labels in each community
#
# Parameters
# ----------
# membership_vector : list of lists of int
# community membership i.e. vertex/label `i` is in communities
# from list `membership_vector[i]`
# size : int
# the number of communities present in the membership vector
#
#
# Returns
# -------
# list_of_members : list of lists of int
# list of lists of vertex/label ids in each community per community
# """
# list_of_members = [[] for _ in range(size)]
# for vertex_id, community_ids in enumerate(membership_vector):
# for community_id in community_ids:
# list_of_members[community_id].append(vertex_id)
# return list_of_members
. Output only the next line. | class GraphToolLabelGraphClusterer(LabelGraphClustererBase): |
Using the snippet: <|code_start|> deg_corr=self.use_degree_correlation,
overlap=self.allow_overlap,
state_args=dict(recs=[weights],
rec_types=[self.weight_model])
)
else:
self.model_ = self._model_fit_function()(
graph,
deg_corr=self.use_degree_correlation,
overlap=self.allow_overlap
)
return self._detect_communities()
def _detect_communities(self):
if self.nested:
lowest_level = self.model_.get_levels()[0]
else:
lowest_level = self.model_
number_of_communities = lowest_level.get_B()
if self.allow_overlap:
# the overlaps block returns
# membership vector, and also edges vectors, we need just the membership here at the moment
membership_vector = list(lowest_level.get_overlap_blocks()[0])
else:
membership_vector = list(lowest_level.get_blocks())
if self.allow_overlap:
return _overlapping_membership_to_list_of_communities(membership_vector, number_of_communities)
<|code_end|>
, determine the next line of code. You have imports:
import graph_tool.all as gt
import numpy as np
from .base import LabelGraphClustererBase
from .helpers import _membership_to_list_of_communities, _overlapping_membership_to_list_of_communities
and context (class names, function names, or code) available:
# Path: skmultilearn/cluster/base.py
# class LabelGraphClustererBase(object):
# """An abstract base class for Label Graph clustering
#
# Inherit it in your classifier according to`developer guide <../developer.ipynb>`_.
#
# """
#
# def __init__(self, graph_builder):
# """
#
# Attributes
# ----------
# graph_builder : a GraphBuilderBase derivative class
# a graph building class for the clusterer
# """
# super(LabelGraphClustererBase, self).__init__()
# self.graph_builder = graph_builder
#
# def fit_predict(self, X, y):
# """ Abstract method for clustering label space
#
# Implement it in your classifier according to`developer guide <../developer.ipynb>`_.
#
# Raises
# ------
# NotImplementedError
# this is an abstract method
# """
# raise NotImplementedError("LabelGraphClustererBase::fit_predict()")
#
# Path: skmultilearn/cluster/helpers.py
# def _membership_to_list_of_communities(membership_vector, size):
# """Convert membership vector to list of lists of vertices in each community
#
# Parameters
# ----------
# membership_vector : list of int
# community membership i.e. vertex/label `i` is in community `membership_vector[i]`
# size : int
# the number of communities present in the membership vector
#
#
# Returns
# -------
# list_of_members : list of lists of int
# list of lists of vertex/label ids in each community per community
# """
# list_of_members = [[] for _ in range(size)]
# for vertex_id, community_id in enumerate(membership_vector):
# list_of_members[community_id].append(vertex_id)
# return list_of_members
#
# def _overlapping_membership_to_list_of_communities(membership_vector, size):
# """Convert membership vector to list of lists of vertices/labels in each community
#
# Parameters
# ----------
# membership_vector : list of lists of int
# community membership i.e. vertex/label `i` is in communities
# from list `membership_vector[i]`
# size : int
# the number of communities present in the membership vector
#
#
# Returns
# -------
# list_of_members : list of lists of int
# list of lists of vertex/label ids in each community per community
# """
# list_of_members = [[] for _ in range(size)]
# for vertex_id, community_ids in enumerate(membership_vector):
# for community_id in community_ids:
# list_of_members[community_id].append(vertex_id)
# return list_of_members
. Output only the next line. | return _membership_to_list_of_communities(membership_vector, number_of_communities) |
Given snippet: <|code_start|> self.model_ = self._model_fit_function()(
graph,
deg_corr=self.use_degree_correlation,
overlap=self.allow_overlap,
state_args=dict(recs=[weights],
rec_types=[self.weight_model])
)
else:
self.model_ = self._model_fit_function()(
graph,
deg_corr=self.use_degree_correlation,
overlap=self.allow_overlap
)
return self._detect_communities()
def _detect_communities(self):
if self.nested:
lowest_level = self.model_.get_levels()[0]
else:
lowest_level = self.model_
number_of_communities = lowest_level.get_B()
if self.allow_overlap:
# the overlaps block returns
# membership vector, and also edges vectors, we need just the membership here at the moment
membership_vector = list(lowest_level.get_overlap_blocks()[0])
else:
membership_vector = list(lowest_level.get_blocks())
if self.allow_overlap:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import graph_tool.all as gt
import numpy as np
from .base import LabelGraphClustererBase
from .helpers import _membership_to_list_of_communities, _overlapping_membership_to_list_of_communities
and context:
# Path: skmultilearn/cluster/base.py
# class LabelGraphClustererBase(object):
# """An abstract base class for Label Graph clustering
#
# Inherit it in your classifier according to`developer guide <../developer.ipynb>`_.
#
# """
#
# def __init__(self, graph_builder):
# """
#
# Attributes
# ----------
# graph_builder : a GraphBuilderBase derivative class
# a graph building class for the clusterer
# """
# super(LabelGraphClustererBase, self).__init__()
# self.graph_builder = graph_builder
#
# def fit_predict(self, X, y):
# """ Abstract method for clustering label space
#
# Implement it in your classifier according to`developer guide <../developer.ipynb>`_.
#
# Raises
# ------
# NotImplementedError
# this is an abstract method
# """
# raise NotImplementedError("LabelGraphClustererBase::fit_predict()")
#
# Path: skmultilearn/cluster/helpers.py
# def _membership_to_list_of_communities(membership_vector, size):
# """Convert membership vector to list of lists of vertices in each community
#
# Parameters
# ----------
# membership_vector : list of int
# community membership i.e. vertex/label `i` is in community `membership_vector[i]`
# size : int
# the number of communities present in the membership vector
#
#
# Returns
# -------
# list_of_members : list of lists of int
# list of lists of vertex/label ids in each community per community
# """
# list_of_members = [[] for _ in range(size)]
# for vertex_id, community_id in enumerate(membership_vector):
# list_of_members[community_id].append(vertex_id)
# return list_of_members
#
# def _overlapping_membership_to_list_of_communities(membership_vector, size):
# """Convert membership vector to list of lists of vertices/labels in each community
#
# Parameters
# ----------
# membership_vector : list of lists of int
# community membership i.e. vertex/label `i` is in communities
# from list `membership_vector[i]`
# size : int
# the number of communities present in the membership vector
#
#
# Returns
# -------
# list_of_members : list of lists of int
# list of lists of vertex/label ids in each community per community
# """
# list_of_members = [[] for _ in range(size)]
# for vertex_id, community_ids in enumerate(membership_vector):
# for community_id in community_ids:
# list_of_members[community_id].append(vertex_id)
# return list_of_members
which might include code, classes, or functions. Output only the next line. | return _overlapping_membership_to_list_of_communities(membership_vector, number_of_communities) |
Based on the snippet: <|code_start|> :type path: list or None
:param path:
optional list of path where the module or package should be
searched (use sys.path if nothing or None is given)
:type context_file: str or None
:param context_file:
context file to consider, necessary if the identifier has been
introduced using a relative import unresolvable in the actual
context (i.e. modutils)
:raise ImportError: if there is no such module in the directory
:rtype: (str or None, import type)
:return:
the path to the module's file or None if it's an integrated
builtin module such as 'sys'
"""
if context_file is not None:
context = os.path.dirname(context_file)
else:
context = context_file
if modpath[0] == 'xml':
# handle _xmlplus
try:
return _spec_from_modpath(['_xmlplus'] + modpath[1:], path, context)
except ImportError:
return _spec_from_modpath(modpath, path, context)
elif modpath == ['os', 'path']:
# FIXME: currently ignoring search_path...
<|code_end|>
, predict the immediate next line with the help of imports:
import imp
import os
import platform
import sys
import six
from distutils.sysconfig import get_python_lib # pylint: disable=import-error
from distutils.errors import DistutilsPlatformError
from .interpreter._import import spec
from .interpreter._import import util
and context (classes, functions, sometimes code) from other files:
# Path: bin/deps/astroid/interpreter/_import/spec.py
# _HAS_MACHINERY = True
# _HAS_MACHINERY = False
# _SPEC_FINDERS = (
# ImpFinder,
# ZipFinder,
# )
# def _imp_type_to_module_type(imp_type):
# def __new__(cls, name, module_type, location=None, origin=None,
# submodule_search_locations=None):
# def __init__(self, path=None):
# def find_module(self, modname, module_parts, processed, submodule_path):
# def contribute_to_path(self, spec, processed):
# def find_module(self, modname, module_parts, processed, submodule_path):
# def contribute_to_path(self, spec, processed):
# def find_module(self, modname, module_parts, processed, submodule_path):
# def contribute_to_path(self, spec, processed):
# def __init__(self, path):
# def find_module(self, modname, module_parts, processed, submodule_path):
# def find_module(self, modname, module_parts, processed, submodule_path):
# def contribute_to_path(self, spec, processed):
# def _is_setuptools_namespace(location):
# def _cached_set_diff(left, right):
# def _precache_zipimporters(path=None):
# def _search_zip(modpath, pic):
# def _find_spec_with_path(search_path, modname, module_parts, processed, submodule_path):
# def find_spec(modpath, path=None):
# class ModuleSpec(_ModuleSpec):
# class Finder(object):
# class ImpFinder(Finder):
# class ExplicitNamespacePackageFinder(ImpFinder):
# class ZipFinder(Finder):
# class PathSpecFinder(Finder):
. Output only the next line. | return spec.ModuleSpec(name='os.path', location=os.path.__file__, module_type=imp.PY_SOURCE) |
Using the snippet: <|code_start|>def check(filenames, select=None, ignore=None, ignore_decorators=None):
"""Generate docstring errors that exist in `filenames` iterable.
By default, the PEP-257 convention is checked. To specifically define the
set of error codes to check for, supply either `select` or `ignore` (but
not both). In either case, the parameter should be a collection of error
code strings, e.g., {'D100', 'D404'}.
When supplying `select`, only specified error codes will be reported.
When supplying `ignore`, all error codes which were not specified will be
reported.
Note that ignored error code refer to the entire set of possible
error codes, which is larger than just the PEP-257 convention. To your
convenience, you may use `pydocstyle.violations.conventions.pep257` as
a base set to add or remove errors from.
Examples
---------
>>> check(['pydocstyle.py'])
<generator object check at 0x...>
>>> check(['pydocstyle.py'], select=['D100'])
<generator object check at 0x...>
>>> check(['pydocstyle.py'], ignore=conventions.pep257 - {'D100'})
<generator object check at 0x...>
"""
if select is not None and ignore is not None:
<|code_end|>
, determine the next line of code. You have imports:
import ast
import string
import sys
import tokenize as tk
from itertools import takewhile
from re import compile as re
from collections import namedtuple
from . import violations
from .config import IllegalConfiguration
from .parser import (Package, Module, Class, NestedClass, Definition, AllError,
Method, Function, NestedFunction, Parser, StringIO,
ParseError)
from .utils import log, is_blank, pairwise
from .wordlists import IMPERATIVE_VERBS, IMPERATIVE_BLACKLIST, stem
and context (class names, function names, or code) available:
# Path: bin/deps/pydocstyle/config.py
# class IllegalConfiguration(Exception):
# """An exception for illegal configurations."""
#
# pass
#
# Path: bin/deps/pydocstyle/parser.py
# def next(obj, default=nothing):
# def __str__(self):
# def humanize(string):
# def __init__(self, *args):
# def __hash__(self):
# def __eq__(self, other):
# def __repr__(self):
# def __iter__(self):
# def _publicity(self):
# def source(self):
# def is_empty_or_comment(line):
# def __str__(self):
# def is_public(self):
# def __str__(self):
# def is_public(self):
# def is_test(self):
# def is_magic(self):
# def is_init(self):
# def is_public(self):
# def is_public(self):
# def __init__(self, message):
# def __init__(self, filelike):
# def move(self):
# def _next_from_generator(self):
# def __iter__(self):
# def __repr__(self):
# def __init__(self, *args):
# def parse(self, filelike, filename):
# def __call__(self, *args, **kwargs):
# def consume(self, kind):
# def leapfrog(self, kind, value=None):
# def parse_docstring(self):
# def parse_decorators(self):
# def parse_definitions(self, class_, all=False):
# def parse_all(self):
# def parse_module(self):
# def parse_definition(self, class_):
# def parse_skip_comment(self):
# def check_current(self, kind=None, value=None):
# def parse_from_import_statement(self):
# def _parse_from_import_source(self):
# def _parse_from_import_names(self, is_future_import):
# class ParseError(Exception):
# class Value(object):
# class Definition(Value):
# class Module(Definition):
# class Package(Module):
# class Function(Definition):
# class NestedFunction(Function):
# class Method(Function):
# class Class(Definition):
# class NestedClass(Class):
# class Decorator(Value):
# class AllError(Exception):
# class TokenStream(object):
# class TokenKind(int):
# class Token(Value):
# class Parser(object):
# VARIADIC_MAGIC_METHODS = ('__init__', '__call__', '__new__')
# LOGICAL_NEWLINES = {tk.NEWLINE, tk.INDENT, tk.DEDENT}
#
# Path: bin/deps/pydocstyle/utils.py
# def is_blank(string):
# def pairwise(iterable, default_value):
. Output only the next line. | raise IllegalConfiguration('Cannot pass both select and ignore. ' |
Based on the snippet: <|code_start|> @property
def checks(self):
all = [this_check for this_check in vars(type(self)).values()
if hasattr(this_check, '_check_for')]
return sorted(all, key=lambda this_check: not this_check._terminal)
@check_for(Definition, terminal=True)
def check_docstring_missing(self, definition, docstring):
"""D10{0,1,2,3}: Public definitions should have docstrings.
All modules should normally have docstrings. [...] all functions and
classes exported by a module should also have docstrings. Public
methods (including the __init__ constructor) should also have
docstrings.
Note: Public (exported) definitions are either those with names listed
in __all__ variable (if present), or those that do not start
with a single underscore.
"""
if (not docstring and definition.is_public or
docstring and is_blank(ast.literal_eval(docstring))):
codes = {Module: violations.D100,
Class: violations.D101,
NestedClass: violations.D106,
Method: (lambda: violations.D105() if definition.is_magic
else (violations.D107() if definition.is_init
else violations.D102())),
Function: violations.D103,
NestedFunction: violations.D103,
<|code_end|>
, predict the immediate next line with the help of imports:
import ast
import string
import sys
import tokenize as tk
from itertools import takewhile
from re import compile as re
from collections import namedtuple
from . import violations
from .config import IllegalConfiguration
from .parser import (Package, Module, Class, NestedClass, Definition, AllError,
Method, Function, NestedFunction, Parser, StringIO,
ParseError)
from .utils import log, is_blank, pairwise
from .wordlists import IMPERATIVE_VERBS, IMPERATIVE_BLACKLIST, stem
and context (classes, functions, sometimes code) from other files:
# Path: bin/deps/pydocstyle/config.py
# class IllegalConfiguration(Exception):
# """An exception for illegal configurations."""
#
# pass
#
# Path: bin/deps/pydocstyle/parser.py
# def next(obj, default=nothing):
# def __str__(self):
# def humanize(string):
# def __init__(self, *args):
# def __hash__(self):
# def __eq__(self, other):
# def __repr__(self):
# def __iter__(self):
# def _publicity(self):
# def source(self):
# def is_empty_or_comment(line):
# def __str__(self):
# def is_public(self):
# def __str__(self):
# def is_public(self):
# def is_test(self):
# def is_magic(self):
# def is_init(self):
# def is_public(self):
# def is_public(self):
# def __init__(self, message):
# def __init__(self, filelike):
# def move(self):
# def _next_from_generator(self):
# def __iter__(self):
# def __repr__(self):
# def __init__(self, *args):
# def parse(self, filelike, filename):
# def __call__(self, *args, **kwargs):
# def consume(self, kind):
# def leapfrog(self, kind, value=None):
# def parse_docstring(self):
# def parse_decorators(self):
# def parse_definitions(self, class_, all=False):
# def parse_all(self):
# def parse_module(self):
# def parse_definition(self, class_):
# def parse_skip_comment(self):
# def check_current(self, kind=None, value=None):
# def parse_from_import_statement(self):
# def _parse_from_import_source(self):
# def _parse_from_import_names(self, is_future_import):
# class ParseError(Exception):
# class Value(object):
# class Definition(Value):
# class Module(Definition):
# class Package(Module):
# class Function(Definition):
# class NestedFunction(Function):
# class Method(Function):
# class Class(Definition):
# class NestedClass(Class):
# class Decorator(Value):
# class AllError(Exception):
# class TokenStream(object):
# class TokenKind(int):
# class Token(Value):
# class Parser(object):
# VARIADIC_MAGIC_METHODS = ('__init__', '__call__', '__new__')
# LOGICAL_NEWLINES = {tk.NEWLINE, tk.INDENT, tk.DEDENT}
#
# Path: bin/deps/pydocstyle/utils.py
# def is_blank(string):
# def pairwise(iterable, default_value):
. Output only the next line. | Package: violations.D104} |
Predict the next line for this snippet: <|code_start|> definition=definition)
yield error
if this_check._terminal:
terminate = True
break
if terminate:
break
@property
def checks(self):
all = [this_check for this_check in vars(type(self)).values()
if hasattr(this_check, '_check_for')]
return sorted(all, key=lambda this_check: not this_check._terminal)
@check_for(Definition, terminal=True)
def check_docstring_missing(self, definition, docstring):
"""D10{0,1,2,3}: Public definitions should have docstrings.
All modules should normally have docstrings. [...] all functions and
classes exported by a module should also have docstrings. Public
methods (including the __init__ constructor) should also have
docstrings.
Note: Public (exported) definitions are either those with names listed
in __all__ variable (if present), or those that do not start
with a single underscore.
"""
if (not docstring and definition.is_public or
docstring and is_blank(ast.literal_eval(docstring))):
<|code_end|>
with the help of current file imports:
import ast
import string
import sys
import tokenize as tk
from itertools import takewhile
from re import compile as re
from collections import namedtuple
from . import violations
from .config import IllegalConfiguration
from .parser import (Package, Module, Class, NestedClass, Definition, AllError,
Method, Function, NestedFunction, Parser, StringIO,
ParseError)
from .utils import log, is_blank, pairwise
from .wordlists import IMPERATIVE_VERBS, IMPERATIVE_BLACKLIST, stem
and context from other files:
# Path: bin/deps/pydocstyle/config.py
# class IllegalConfiguration(Exception):
# """An exception for illegal configurations."""
#
# pass
#
# Path: bin/deps/pydocstyle/parser.py
# def next(obj, default=nothing):
# def __str__(self):
# def humanize(string):
# def __init__(self, *args):
# def __hash__(self):
# def __eq__(self, other):
# def __repr__(self):
# def __iter__(self):
# def _publicity(self):
# def source(self):
# def is_empty_or_comment(line):
# def __str__(self):
# def is_public(self):
# def __str__(self):
# def is_public(self):
# def is_test(self):
# def is_magic(self):
# def is_init(self):
# def is_public(self):
# def is_public(self):
# def __init__(self, message):
# def __init__(self, filelike):
# def move(self):
# def _next_from_generator(self):
# def __iter__(self):
# def __repr__(self):
# def __init__(self, *args):
# def parse(self, filelike, filename):
# def __call__(self, *args, **kwargs):
# def consume(self, kind):
# def leapfrog(self, kind, value=None):
# def parse_docstring(self):
# def parse_decorators(self):
# def parse_definitions(self, class_, all=False):
# def parse_all(self):
# def parse_module(self):
# def parse_definition(self, class_):
# def parse_skip_comment(self):
# def check_current(self, kind=None, value=None):
# def parse_from_import_statement(self):
# def _parse_from_import_source(self):
# def _parse_from_import_names(self, is_future_import):
# class ParseError(Exception):
# class Value(object):
# class Definition(Value):
# class Module(Definition):
# class Package(Module):
# class Function(Definition):
# class NestedFunction(Function):
# class Method(Function):
# class Class(Definition):
# class NestedClass(Class):
# class Decorator(Value):
# class AllError(Exception):
# class TokenStream(object):
# class TokenKind(int):
# class Token(Value):
# class Parser(object):
# VARIADIC_MAGIC_METHODS = ('__init__', '__call__', '__new__')
# LOGICAL_NEWLINES = {tk.NEWLINE, tk.INDENT, tk.DEDENT}
#
# Path: bin/deps/pydocstyle/utils.py
# def is_blank(string):
# def pairwise(iterable, default_value):
, which may contain function names, class names, or code. Output only the next line. | codes = {Module: violations.D100, |
Here is a snippet: <|code_start|> yield error
if this_check._terminal:
terminate = True
break
if terminate:
break
@property
def checks(self):
all = [this_check for this_check in vars(type(self)).values()
if hasattr(this_check, '_check_for')]
return sorted(all, key=lambda this_check: not this_check._terminal)
@check_for(Definition, terminal=True)
def check_docstring_missing(self, definition, docstring):
"""D10{0,1,2,3}: Public definitions should have docstrings.
All modules should normally have docstrings. [...] all functions and
classes exported by a module should also have docstrings. Public
methods (including the __init__ constructor) should also have
docstrings.
Note: Public (exported) definitions are either those with names listed
in __all__ variable (if present), or those that do not start
with a single underscore.
"""
if (not docstring and definition.is_public or
docstring and is_blank(ast.literal_eval(docstring))):
codes = {Module: violations.D100,
<|code_end|>
. Write the next line using the current file imports:
import ast
import string
import sys
import tokenize as tk
from itertools import takewhile
from re import compile as re
from collections import namedtuple
from . import violations
from .config import IllegalConfiguration
from .parser import (Package, Module, Class, NestedClass, Definition, AllError,
Method, Function, NestedFunction, Parser, StringIO,
ParseError)
from .utils import log, is_blank, pairwise
from .wordlists import IMPERATIVE_VERBS, IMPERATIVE_BLACKLIST, stem
and context from other files:
# Path: bin/deps/pydocstyle/config.py
# class IllegalConfiguration(Exception):
# """An exception for illegal configurations."""
#
# pass
#
# Path: bin/deps/pydocstyle/parser.py
# def next(obj, default=nothing):
# def __str__(self):
# def humanize(string):
# def __init__(self, *args):
# def __hash__(self):
# def __eq__(self, other):
# def __repr__(self):
# def __iter__(self):
# def _publicity(self):
# def source(self):
# def is_empty_or_comment(line):
# def __str__(self):
# def is_public(self):
# def __str__(self):
# def is_public(self):
# def is_test(self):
# def is_magic(self):
# def is_init(self):
# def is_public(self):
# def is_public(self):
# def __init__(self, message):
# def __init__(self, filelike):
# def move(self):
# def _next_from_generator(self):
# def __iter__(self):
# def __repr__(self):
# def __init__(self, *args):
# def parse(self, filelike, filename):
# def __call__(self, *args, **kwargs):
# def consume(self, kind):
# def leapfrog(self, kind, value=None):
# def parse_docstring(self):
# def parse_decorators(self):
# def parse_definitions(self, class_, all=False):
# def parse_all(self):
# def parse_module(self):
# def parse_definition(self, class_):
# def parse_skip_comment(self):
# def check_current(self, kind=None, value=None):
# def parse_from_import_statement(self):
# def _parse_from_import_source(self):
# def _parse_from_import_names(self, is_future_import):
# class ParseError(Exception):
# class Value(object):
# class Definition(Value):
# class Module(Definition):
# class Package(Module):
# class Function(Definition):
# class NestedFunction(Function):
# class Method(Function):
# class Class(Definition):
# class NestedClass(Class):
# class Decorator(Value):
# class AllError(Exception):
# class TokenStream(object):
# class TokenKind(int):
# class Token(Value):
# class Parser(object):
# VARIADIC_MAGIC_METHODS = ('__init__', '__call__', '__new__')
# LOGICAL_NEWLINES = {tk.NEWLINE, tk.INDENT, tk.DEDENT}
#
# Path: bin/deps/pydocstyle/utils.py
# def is_blank(string):
# def pairwise(iterable, default_value):
, which may include functions, classes, or code. Output only the next line. | Class: violations.D101, |
Given the following code snippet before the placeholder: <|code_start|> if this_check._terminal:
terminate = True
break
if terminate:
break
@property
def checks(self):
all = [this_check for this_check in vars(type(self)).values()
if hasattr(this_check, '_check_for')]
return sorted(all, key=lambda this_check: not this_check._terminal)
@check_for(Definition, terminal=True)
def check_docstring_missing(self, definition, docstring):
"""D10{0,1,2,3}: Public definitions should have docstrings.
All modules should normally have docstrings. [...] all functions and
classes exported by a module should also have docstrings. Public
methods (including the __init__ constructor) should also have
docstrings.
Note: Public (exported) definitions are either those with names listed
in __all__ variable (if present), or those that do not start
with a single underscore.
"""
if (not docstring and definition.is_public or
docstring and is_blank(ast.literal_eval(docstring))):
codes = {Module: violations.D100,
Class: violations.D101,
<|code_end|>
, predict the next line using imports from the current file:
import ast
import string
import sys
import tokenize as tk
from itertools import takewhile
from re import compile as re
from collections import namedtuple
from . import violations
from .config import IllegalConfiguration
from .parser import (Package, Module, Class, NestedClass, Definition, AllError,
Method, Function, NestedFunction, Parser, StringIO,
ParseError)
from .utils import log, is_blank, pairwise
from .wordlists import IMPERATIVE_VERBS, IMPERATIVE_BLACKLIST, stem
and context including class names, function names, and sometimes code from other files:
# Path: bin/deps/pydocstyle/config.py
# class IllegalConfiguration(Exception):
# """An exception for illegal configurations."""
#
# pass
#
# Path: bin/deps/pydocstyle/parser.py
# def next(obj, default=nothing):
# def __str__(self):
# def humanize(string):
# def __init__(self, *args):
# def __hash__(self):
# def __eq__(self, other):
# def __repr__(self):
# def __iter__(self):
# def _publicity(self):
# def source(self):
# def is_empty_or_comment(line):
# def __str__(self):
# def is_public(self):
# def __str__(self):
# def is_public(self):
# def is_test(self):
# def is_magic(self):
# def is_init(self):
# def is_public(self):
# def is_public(self):
# def __init__(self, message):
# def __init__(self, filelike):
# def move(self):
# def _next_from_generator(self):
# def __iter__(self):
# def __repr__(self):
# def __init__(self, *args):
# def parse(self, filelike, filename):
# def __call__(self, *args, **kwargs):
# def consume(self, kind):
# def leapfrog(self, kind, value=None):
# def parse_docstring(self):
# def parse_decorators(self):
# def parse_definitions(self, class_, all=False):
# def parse_all(self):
# def parse_module(self):
# def parse_definition(self, class_):
# def parse_skip_comment(self):
# def check_current(self, kind=None, value=None):
# def parse_from_import_statement(self):
# def _parse_from_import_source(self):
# def _parse_from_import_names(self, is_future_import):
# class ParseError(Exception):
# class Value(object):
# class Definition(Value):
# class Module(Definition):
# class Package(Module):
# class Function(Definition):
# class NestedFunction(Function):
# class Method(Function):
# class Class(Definition):
# class NestedClass(Class):
# class Decorator(Value):
# class AllError(Exception):
# class TokenStream(object):
# class TokenKind(int):
# class Token(Value):
# class Parser(object):
# VARIADIC_MAGIC_METHODS = ('__init__', '__call__', '__new__')
# LOGICAL_NEWLINES = {tk.NEWLINE, tk.INDENT, tk.DEDENT}
#
# Path: bin/deps/pydocstyle/utils.py
# def is_blank(string):
# def pairwise(iterable, default_value):
. Output only the next line. | NestedClass: violations.D106, |
Based on the snippet: <|code_start|> skipping_all = (definition.skipped_error_codes == 'all')
decorator_skip = ignore_decorators is not None and any(
len(ignore_decorators.findall(dec.name)) > 0
for dec in definition.decorators)
if not skipping_all and not decorator_skip:
error = this_check(self, definition,
definition.docstring)
else:
error = None
errors = error if hasattr(error, '__iter__') else [error]
for error in errors:
if error is not None and error.code not in \
definition.skipped_error_codes:
partition = this_check.__doc__.partition('.\n')
message, _, explanation = partition
error.set_context(explanation=explanation,
definition=definition)
yield error
if this_check._terminal:
terminate = True
break
if terminate:
break
@property
def checks(self):
all = [this_check for this_check in vars(type(self)).values()
if hasattr(this_check, '_check_for')]
return sorted(all, key=lambda this_check: not this_check._terminal)
<|code_end|>
, predict the immediate next line with the help of imports:
import ast
import string
import sys
import tokenize as tk
from itertools import takewhile
from re import compile as re
from collections import namedtuple
from . import violations
from .config import IllegalConfiguration
from .parser import (Package, Module, Class, NestedClass, Definition, AllError,
Method, Function, NestedFunction, Parser, StringIO,
ParseError)
from .utils import log, is_blank, pairwise
from .wordlists import IMPERATIVE_VERBS, IMPERATIVE_BLACKLIST, stem
and context (classes, functions, sometimes code) from other files:
# Path: bin/deps/pydocstyle/config.py
# class IllegalConfiguration(Exception):
# """An exception for illegal configurations."""
#
# pass
#
# Path: bin/deps/pydocstyle/parser.py
# def next(obj, default=nothing):
# def __str__(self):
# def humanize(string):
# def __init__(self, *args):
# def __hash__(self):
# def __eq__(self, other):
# def __repr__(self):
# def __iter__(self):
# def _publicity(self):
# def source(self):
# def is_empty_or_comment(line):
# def __str__(self):
# def is_public(self):
# def __str__(self):
# def is_public(self):
# def is_test(self):
# def is_magic(self):
# def is_init(self):
# def is_public(self):
# def is_public(self):
# def __init__(self, message):
# def __init__(self, filelike):
# def move(self):
# def _next_from_generator(self):
# def __iter__(self):
# def __repr__(self):
# def __init__(self, *args):
# def parse(self, filelike, filename):
# def __call__(self, *args, **kwargs):
# def consume(self, kind):
# def leapfrog(self, kind, value=None):
# def parse_docstring(self):
# def parse_decorators(self):
# def parse_definitions(self, class_, all=False):
# def parse_all(self):
# def parse_module(self):
# def parse_definition(self, class_):
# def parse_skip_comment(self):
# def check_current(self, kind=None, value=None):
# def parse_from_import_statement(self):
# def _parse_from_import_source(self):
# def _parse_from_import_names(self, is_future_import):
# class ParseError(Exception):
# class Value(object):
# class Definition(Value):
# class Module(Definition):
# class Package(Module):
# class Function(Definition):
# class NestedFunction(Function):
# class Method(Function):
# class Class(Definition):
# class NestedClass(Class):
# class Decorator(Value):
# class AllError(Exception):
# class TokenStream(object):
# class TokenKind(int):
# class Token(Value):
# class Parser(object):
# VARIADIC_MAGIC_METHODS = ('__init__', '__call__', '__new__')
# LOGICAL_NEWLINES = {tk.NEWLINE, tk.INDENT, tk.DEDENT}
#
# Path: bin/deps/pydocstyle/utils.py
# def is_blank(string):
# def pairwise(iterable, default_value):
. Output only the next line. | @check_for(Definition, terminal=True) |
Given snippet: <|code_start|> <generator object check at 0x...>
>>> check(['pydocstyle.py'], select=['D100'])
<generator object check at 0x...>
>>> check(['pydocstyle.py'], ignore=conventions.pep257 - {'D100'})
<generator object check at 0x...>
"""
if select is not None and ignore is not None:
raise IllegalConfiguration('Cannot pass both select and ignore. '
'They are mutually exclusive.')
elif select is not None:
checked_codes = select
elif ignore is not None:
checked_codes = list(set(violations.ErrorRegistry.get_error_codes()) -
set(ignore))
else:
checked_codes = violations.conventions.pep257
for filename in filenames:
log.info('Checking file %s.', filename)
try:
with tokenize_open(filename) as file:
source = file.read()
for error in ConventionChecker().check_source(source, filename,
ignore_decorators):
code = getattr(error, 'code', None)
if code in checked_codes:
yield error
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import ast
import string
import sys
import tokenize as tk
from itertools import takewhile
from re import compile as re
from collections import namedtuple
from . import violations
from .config import IllegalConfiguration
from .parser import (Package, Module, Class, NestedClass, Definition, AllError,
Method, Function, NestedFunction, Parser, StringIO,
ParseError)
from .utils import log, is_blank, pairwise
from .wordlists import IMPERATIVE_VERBS, IMPERATIVE_BLACKLIST, stem
and context:
# Path: bin/deps/pydocstyle/config.py
# class IllegalConfiguration(Exception):
# """An exception for illegal configurations."""
#
# pass
#
# Path: bin/deps/pydocstyle/parser.py
# def next(obj, default=nothing):
# def __str__(self):
# def humanize(string):
# def __init__(self, *args):
# def __hash__(self):
# def __eq__(self, other):
# def __repr__(self):
# def __iter__(self):
# def _publicity(self):
# def source(self):
# def is_empty_or_comment(line):
# def __str__(self):
# def is_public(self):
# def __str__(self):
# def is_public(self):
# def is_test(self):
# def is_magic(self):
# def is_init(self):
# def is_public(self):
# def is_public(self):
# def __init__(self, message):
# def __init__(self, filelike):
# def move(self):
# def _next_from_generator(self):
# def __iter__(self):
# def __repr__(self):
# def __init__(self, *args):
# def parse(self, filelike, filename):
# def __call__(self, *args, **kwargs):
# def consume(self, kind):
# def leapfrog(self, kind, value=None):
# def parse_docstring(self):
# def parse_decorators(self):
# def parse_definitions(self, class_, all=False):
# def parse_all(self):
# def parse_module(self):
# def parse_definition(self, class_):
# def parse_skip_comment(self):
# def check_current(self, kind=None, value=None):
# def parse_from_import_statement(self):
# def _parse_from_import_source(self):
# def _parse_from_import_names(self, is_future_import):
# class ParseError(Exception):
# class Value(object):
# class Definition(Value):
# class Module(Definition):
# class Package(Module):
# class Function(Definition):
# class NestedFunction(Function):
# class Method(Function):
# class Class(Definition):
# class NestedClass(Class):
# class Decorator(Value):
# class AllError(Exception):
# class TokenStream(object):
# class TokenKind(int):
# class Token(Value):
# class Parser(object):
# VARIADIC_MAGIC_METHODS = ('__init__', '__call__', '__new__')
# LOGICAL_NEWLINES = {tk.NEWLINE, tk.INDENT, tk.DEDENT}
#
# Path: bin/deps/pydocstyle/utils.py
# def is_blank(string):
# def pairwise(iterable, default_value):
which might include code, classes, or functions. Output only the next line. | except (EnvironmentError, AllError, ParseError) as error: |
Here is a snippet: <|code_start|> terminate = True
break
if terminate:
break
@property
def checks(self):
all = [this_check for this_check in vars(type(self)).values()
if hasattr(this_check, '_check_for')]
return sorted(all, key=lambda this_check: not this_check._terminal)
@check_for(Definition, terminal=True)
def check_docstring_missing(self, definition, docstring):
"""D10{0,1,2,3}: Public definitions should have docstrings.
All modules should normally have docstrings. [...] all functions and
classes exported by a module should also have docstrings. Public
methods (including the __init__ constructor) should also have
docstrings.
Note: Public (exported) definitions are either those with names listed
in __all__ variable (if present), or those that do not start
with a single underscore.
"""
if (not docstring and definition.is_public or
docstring and is_blank(ast.literal_eval(docstring))):
codes = {Module: violations.D100,
Class: violations.D101,
NestedClass: violations.D106,
<|code_end|>
. Write the next line using the current file imports:
import ast
import string
import sys
import tokenize as tk
from itertools import takewhile
from re import compile as re
from collections import namedtuple
from . import violations
from .config import IllegalConfiguration
from .parser import (Package, Module, Class, NestedClass, Definition, AllError,
Method, Function, NestedFunction, Parser, StringIO,
ParseError)
from .utils import log, is_blank, pairwise
from .wordlists import IMPERATIVE_VERBS, IMPERATIVE_BLACKLIST, stem
and context from other files:
# Path: bin/deps/pydocstyle/config.py
# class IllegalConfiguration(Exception):
# """An exception for illegal configurations."""
#
# pass
#
# Path: bin/deps/pydocstyle/parser.py
# def next(obj, default=nothing):
# def __str__(self):
# def humanize(string):
# def __init__(self, *args):
# def __hash__(self):
# def __eq__(self, other):
# def __repr__(self):
# def __iter__(self):
# def _publicity(self):
# def source(self):
# def is_empty_or_comment(line):
# def __str__(self):
# def is_public(self):
# def __str__(self):
# def is_public(self):
# def is_test(self):
# def is_magic(self):
# def is_init(self):
# def is_public(self):
# def is_public(self):
# def __init__(self, message):
# def __init__(self, filelike):
# def move(self):
# def _next_from_generator(self):
# def __iter__(self):
# def __repr__(self):
# def __init__(self, *args):
# def parse(self, filelike, filename):
# def __call__(self, *args, **kwargs):
# def consume(self, kind):
# def leapfrog(self, kind, value=None):
# def parse_docstring(self):
# def parse_decorators(self):
# def parse_definitions(self, class_, all=False):
# def parse_all(self):
# def parse_module(self):
# def parse_definition(self, class_):
# def parse_skip_comment(self):
# def check_current(self, kind=None, value=None):
# def parse_from_import_statement(self):
# def _parse_from_import_source(self):
# def _parse_from_import_names(self, is_future_import):
# class ParseError(Exception):
# class Value(object):
# class Definition(Value):
# class Module(Definition):
# class Package(Module):
# class Function(Definition):
# class NestedFunction(Function):
# class Method(Function):
# class Class(Definition):
# class NestedClass(Class):
# class Decorator(Value):
# class AllError(Exception):
# class TokenStream(object):
# class TokenKind(int):
# class Token(Value):
# class Parser(object):
# VARIADIC_MAGIC_METHODS = ('__init__', '__call__', '__new__')
# LOGICAL_NEWLINES = {tk.NEWLINE, tk.INDENT, tk.DEDENT}
#
# Path: bin/deps/pydocstyle/utils.py
# def is_blank(string):
# def pairwise(iterable, default_value):
, which may include functions, classes, or code. Output only the next line. | Method: (lambda: violations.D105() if definition.is_magic |
Continue the code snippet: <|code_start|> break
@property
def checks(self):
all = [this_check for this_check in vars(type(self)).values()
if hasattr(this_check, '_check_for')]
return sorted(all, key=lambda this_check: not this_check._terminal)
@check_for(Definition, terminal=True)
def check_docstring_missing(self, definition, docstring):
"""D10{0,1,2,3}: Public definitions should have docstrings.
All modules should normally have docstrings. [...] all functions and
classes exported by a module should also have docstrings. Public
methods (including the __init__ constructor) should also have
docstrings.
Note: Public (exported) definitions are either those with names listed
in __all__ variable (if present), or those that do not start
with a single underscore.
"""
if (not docstring and definition.is_public or
docstring and is_blank(ast.literal_eval(docstring))):
codes = {Module: violations.D100,
Class: violations.D101,
NestedClass: violations.D106,
Method: (lambda: violations.D105() if definition.is_magic
else (violations.D107() if definition.is_init
else violations.D102())),
<|code_end|>
. Use current file imports:
import ast
import string
import sys
import tokenize as tk
from itertools import takewhile
from re import compile as re
from collections import namedtuple
from . import violations
from .config import IllegalConfiguration
from .parser import (Package, Module, Class, NestedClass, Definition, AllError,
Method, Function, NestedFunction, Parser, StringIO,
ParseError)
from .utils import log, is_blank, pairwise
from .wordlists import IMPERATIVE_VERBS, IMPERATIVE_BLACKLIST, stem
and context (classes, functions, or code) from other files:
# Path: bin/deps/pydocstyle/config.py
# class IllegalConfiguration(Exception):
# """An exception for illegal configurations."""
#
# pass
#
# Path: bin/deps/pydocstyle/parser.py
# def next(obj, default=nothing):
# def __str__(self):
# def humanize(string):
# def __init__(self, *args):
# def __hash__(self):
# def __eq__(self, other):
# def __repr__(self):
# def __iter__(self):
# def _publicity(self):
# def source(self):
# def is_empty_or_comment(line):
# def __str__(self):
# def is_public(self):
# def __str__(self):
# def is_public(self):
# def is_test(self):
# def is_magic(self):
# def is_init(self):
# def is_public(self):
# def is_public(self):
# def __init__(self, message):
# def __init__(self, filelike):
# def move(self):
# def _next_from_generator(self):
# def __iter__(self):
# def __repr__(self):
# def __init__(self, *args):
# def parse(self, filelike, filename):
# def __call__(self, *args, **kwargs):
# def consume(self, kind):
# def leapfrog(self, kind, value=None):
# def parse_docstring(self):
# def parse_decorators(self):
# def parse_definitions(self, class_, all=False):
# def parse_all(self):
# def parse_module(self):
# def parse_definition(self, class_):
# def parse_skip_comment(self):
# def check_current(self, kind=None, value=None):
# def parse_from_import_statement(self):
# def _parse_from_import_source(self):
# def _parse_from_import_names(self, is_future_import):
# class ParseError(Exception):
# class Value(object):
# class Definition(Value):
# class Module(Definition):
# class Package(Module):
# class Function(Definition):
# class NestedFunction(Function):
# class Method(Function):
# class Class(Definition):
# class NestedClass(Class):
# class Decorator(Value):
# class AllError(Exception):
# class TokenStream(object):
# class TokenKind(int):
# class Token(Value):
# class Parser(object):
# VARIADIC_MAGIC_METHODS = ('__init__', '__call__', '__new__')
# LOGICAL_NEWLINES = {tk.NEWLINE, tk.INDENT, tk.DEDENT}
#
# Path: bin/deps/pydocstyle/utils.py
# def is_blank(string):
# def pairwise(iterable, default_value):
. Output only the next line. | Function: violations.D103, |
Here is a snippet: <|code_start|>
@property
def checks(self):
all = [this_check for this_check in vars(type(self)).values()
if hasattr(this_check, '_check_for')]
return sorted(all, key=lambda this_check: not this_check._terminal)
@check_for(Definition, terminal=True)
def check_docstring_missing(self, definition, docstring):
"""D10{0,1,2,3}: Public definitions should have docstrings.
All modules should normally have docstrings. [...] all functions and
classes exported by a module should also have docstrings. Public
methods (including the __init__ constructor) should also have
docstrings.
Note: Public (exported) definitions are either those with names listed
in __all__ variable (if present), or those that do not start
with a single underscore.
"""
if (not docstring and definition.is_public or
docstring and is_blank(ast.literal_eval(docstring))):
codes = {Module: violations.D100,
Class: violations.D101,
NestedClass: violations.D106,
Method: (lambda: violations.D105() if definition.is_magic
else (violations.D107() if definition.is_init
else violations.D102())),
Function: violations.D103,
<|code_end|>
. Write the next line using the current file imports:
import ast
import string
import sys
import tokenize as tk
from itertools import takewhile
from re import compile as re
from collections import namedtuple
from . import violations
from .config import IllegalConfiguration
from .parser import (Package, Module, Class, NestedClass, Definition, AllError,
Method, Function, NestedFunction, Parser, StringIO,
ParseError)
from .utils import log, is_blank, pairwise
from .wordlists import IMPERATIVE_VERBS, IMPERATIVE_BLACKLIST, stem
and context from other files:
# Path: bin/deps/pydocstyle/config.py
# class IllegalConfiguration(Exception):
# """An exception for illegal configurations."""
#
# pass
#
# Path: bin/deps/pydocstyle/parser.py
# def next(obj, default=nothing):
# def __str__(self):
# def humanize(string):
# def __init__(self, *args):
# def __hash__(self):
# def __eq__(self, other):
# def __repr__(self):
# def __iter__(self):
# def _publicity(self):
# def source(self):
# def is_empty_or_comment(line):
# def __str__(self):
# def is_public(self):
# def __str__(self):
# def is_public(self):
# def is_test(self):
# def is_magic(self):
# def is_init(self):
# def is_public(self):
# def is_public(self):
# def __init__(self, message):
# def __init__(self, filelike):
# def move(self):
# def _next_from_generator(self):
# def __iter__(self):
# def __repr__(self):
# def __init__(self, *args):
# def parse(self, filelike, filename):
# def __call__(self, *args, **kwargs):
# def consume(self, kind):
# def leapfrog(self, kind, value=None):
# def parse_docstring(self):
# def parse_decorators(self):
# def parse_definitions(self, class_, all=False):
# def parse_all(self):
# def parse_module(self):
# def parse_definition(self, class_):
# def parse_skip_comment(self):
# def check_current(self, kind=None, value=None):
# def parse_from_import_statement(self):
# def _parse_from_import_source(self):
# def _parse_from_import_names(self, is_future_import):
# class ParseError(Exception):
# class Value(object):
# class Definition(Value):
# class Module(Definition):
# class Package(Module):
# class Function(Definition):
# class NestedFunction(Function):
# class Method(Function):
# class Class(Definition):
# class NestedClass(Class):
# class Decorator(Value):
# class AllError(Exception):
# class TokenStream(object):
# class TokenKind(int):
# class Token(Value):
# class Parser(object):
# VARIADIC_MAGIC_METHODS = ('__init__', '__call__', '__new__')
# LOGICAL_NEWLINES = {tk.NEWLINE, tk.INDENT, tk.DEDENT}
#
# Path: bin/deps/pydocstyle/utils.py
# def is_blank(string):
# def pairwise(iterable, default_value):
, which may include functions, classes, or code. Output only the next line. | NestedFunction: violations.D103, |
Predict the next line for this snippet: <|code_start|> 'original_index',
'is_last_section'))
# First - create a list of possible contexts. Note that the
# `following_linex` member is until the end of the docstring.
contexts = (SectionContext(self._get_leading_words(lines[i].strip()),
lines[i - 1],
lines[i],
lines[i + 1:],
i,
False)
for i in suspected_section_indices)
# Now that we have manageable objects - rule out false positives.
contexts = (c for c in contexts if self._is_a_docstring_section(c))
# Now we shall trim the `following lines` field to only reach the
# next section name.
for a, b in pairwise(contexts, None):
end = -1 if b is None else b.original_index
new_ctx = SectionContext(a.section_name,
a.previous_line,
a.line,
lines[a.original_index + 1:end],
a.original_index,
b is None)
for err in self._check_section(docstring, definition, new_ctx):
yield err
<|code_end|>
with the help of current file imports:
import ast
import string
import sys
import tokenize as tk
from itertools import takewhile
from re import compile as re
from collections import namedtuple
from . import violations
from .config import IllegalConfiguration
from .parser import (Package, Module, Class, NestedClass, Definition, AllError,
Method, Function, NestedFunction, Parser, StringIO,
ParseError)
from .utils import log, is_blank, pairwise
from .wordlists import IMPERATIVE_VERBS, IMPERATIVE_BLACKLIST, stem
and context from other files:
# Path: bin/deps/pydocstyle/config.py
# class IllegalConfiguration(Exception):
# """An exception for illegal configurations."""
#
# pass
#
# Path: bin/deps/pydocstyle/parser.py
# def next(obj, default=nothing):
# def __str__(self):
# def humanize(string):
# def __init__(self, *args):
# def __hash__(self):
# def __eq__(self, other):
# def __repr__(self):
# def __iter__(self):
# def _publicity(self):
# def source(self):
# def is_empty_or_comment(line):
# def __str__(self):
# def is_public(self):
# def __str__(self):
# def is_public(self):
# def is_test(self):
# def is_magic(self):
# def is_init(self):
# def is_public(self):
# def is_public(self):
# def __init__(self, message):
# def __init__(self, filelike):
# def move(self):
# def _next_from_generator(self):
# def __iter__(self):
# def __repr__(self):
# def __init__(self, *args):
# def parse(self, filelike, filename):
# def __call__(self, *args, **kwargs):
# def consume(self, kind):
# def leapfrog(self, kind, value=None):
# def parse_docstring(self):
# def parse_decorators(self):
# def parse_definitions(self, class_, all=False):
# def parse_all(self):
# def parse_module(self):
# def parse_definition(self, class_):
# def parse_skip_comment(self):
# def check_current(self, kind=None, value=None):
# def parse_from_import_statement(self):
# def _parse_from_import_source(self):
# def _parse_from_import_names(self, is_future_import):
# class ParseError(Exception):
# class Value(object):
# class Definition(Value):
# class Module(Definition):
# class Package(Module):
# class Function(Definition):
# class NestedFunction(Function):
# class Method(Function):
# class Class(Definition):
# class NestedClass(Class):
# class Decorator(Value):
# class AllError(Exception):
# class TokenStream(object):
# class TokenKind(int):
# class Token(Value):
# class Parser(object):
# VARIADIC_MAGIC_METHODS = ('__init__', '__call__', '__new__')
# LOGICAL_NEWLINES = {tk.NEWLINE, tk.INDENT, tk.DEDENT}
#
# Path: bin/deps/pydocstyle/utils.py
# def is_blank(string):
# def pairwise(iterable, default_value):
, which may contain function names, class names, or code. Output only the next line. | parse = Parser() |
Continue the code snippet: <|code_start|> f._terminal = terminal
return f
return decorator
class ConventionChecker(object):
"""Checker for PEP 257 and numpy conventions.
D10x: Missing docstrings
D20x: Whitespace issues
D30x: Docstring formatting
D40x: Docstring content issues
"""
SECTION_NAMES = ['Short Summary',
'Extended Summary',
'Parameters',
'Returns',
'Yields',
'Other Parameters',
'Raises',
'See Also',
'Notes',
'References',
'Examples',
'Attributes',
'Methods']
def check_source(self, source, filename, ignore_decorators=None):
<|code_end|>
. Use current file imports:
import ast
import string
import sys
import tokenize as tk
from itertools import takewhile
from re import compile as re
from collections import namedtuple
from . import violations
from .config import IllegalConfiguration
from .parser import (Package, Module, Class, NestedClass, Definition, AllError,
Method, Function, NestedFunction, Parser, StringIO,
ParseError)
from .utils import log, is_blank, pairwise
from .wordlists import IMPERATIVE_VERBS, IMPERATIVE_BLACKLIST, stem
and context (classes, functions, or code) from other files:
# Path: bin/deps/pydocstyle/config.py
# class IllegalConfiguration(Exception):
# """An exception for illegal configurations."""
#
# pass
#
# Path: bin/deps/pydocstyle/parser.py
# def next(obj, default=nothing):
# def __str__(self):
# def humanize(string):
# def __init__(self, *args):
# def __hash__(self):
# def __eq__(self, other):
# def __repr__(self):
# def __iter__(self):
# def _publicity(self):
# def source(self):
# def is_empty_or_comment(line):
# def __str__(self):
# def is_public(self):
# def __str__(self):
# def is_public(self):
# def is_test(self):
# def is_magic(self):
# def is_init(self):
# def is_public(self):
# def is_public(self):
# def __init__(self, message):
# def __init__(self, filelike):
# def move(self):
# def _next_from_generator(self):
# def __iter__(self):
# def __repr__(self):
# def __init__(self, *args):
# def parse(self, filelike, filename):
# def __call__(self, *args, **kwargs):
# def consume(self, kind):
# def leapfrog(self, kind, value=None):
# def parse_docstring(self):
# def parse_decorators(self):
# def parse_definitions(self, class_, all=False):
# def parse_all(self):
# def parse_module(self):
# def parse_definition(self, class_):
# def parse_skip_comment(self):
# def check_current(self, kind=None, value=None):
# def parse_from_import_statement(self):
# def _parse_from_import_source(self):
# def _parse_from_import_names(self, is_future_import):
# class ParseError(Exception):
# class Value(object):
# class Definition(Value):
# class Module(Definition):
# class Package(Module):
# class Function(Definition):
# class NestedFunction(Function):
# class Method(Function):
# class Class(Definition):
# class NestedClass(Class):
# class Decorator(Value):
# class AllError(Exception):
# class TokenStream(object):
# class TokenKind(int):
# class Token(Value):
# class Parser(object):
# VARIADIC_MAGIC_METHODS = ('__init__', '__call__', '__new__')
# LOGICAL_NEWLINES = {tk.NEWLINE, tk.INDENT, tk.DEDENT}
#
# Path: bin/deps/pydocstyle/utils.py
# def is_blank(string):
# def pairwise(iterable, default_value):
. Output only the next line. | module = parse(StringIO(source), filename) |
Predict the next line for this snippet: <|code_start|> <generator object check at 0x...>
>>> check(['pydocstyle.py'], select=['D100'])
<generator object check at 0x...>
>>> check(['pydocstyle.py'], ignore=conventions.pep257 - {'D100'})
<generator object check at 0x...>
"""
if select is not None and ignore is not None:
raise IllegalConfiguration('Cannot pass both select and ignore. '
'They are mutually exclusive.')
elif select is not None:
checked_codes = select
elif ignore is not None:
checked_codes = list(set(violations.ErrorRegistry.get_error_codes()) -
set(ignore))
else:
checked_codes = violations.conventions.pep257
for filename in filenames:
log.info('Checking file %s.', filename)
try:
with tokenize_open(filename) as file:
source = file.read()
for error in ConventionChecker().check_source(source, filename,
ignore_decorators):
code = getattr(error, 'code', None)
if code in checked_codes:
yield error
<|code_end|>
with the help of current file imports:
import ast
import string
import sys
import tokenize as tk
from itertools import takewhile
from re import compile as re
from collections import namedtuple
from . import violations
from .config import IllegalConfiguration
from .parser import (Package, Module, Class, NestedClass, Definition, AllError,
Method, Function, NestedFunction, Parser, StringIO,
ParseError)
from .utils import log, is_blank, pairwise
from .wordlists import IMPERATIVE_VERBS, IMPERATIVE_BLACKLIST, stem
and context from other files:
# Path: bin/deps/pydocstyle/config.py
# class IllegalConfiguration(Exception):
# """An exception for illegal configurations."""
#
# pass
#
# Path: bin/deps/pydocstyle/parser.py
# def next(obj, default=nothing):
# def __str__(self):
# def humanize(string):
# def __init__(self, *args):
# def __hash__(self):
# def __eq__(self, other):
# def __repr__(self):
# def __iter__(self):
# def _publicity(self):
# def source(self):
# def is_empty_or_comment(line):
# def __str__(self):
# def is_public(self):
# def __str__(self):
# def is_public(self):
# def is_test(self):
# def is_magic(self):
# def is_init(self):
# def is_public(self):
# def is_public(self):
# def __init__(self, message):
# def __init__(self, filelike):
# def move(self):
# def _next_from_generator(self):
# def __iter__(self):
# def __repr__(self):
# def __init__(self, *args):
# def parse(self, filelike, filename):
# def __call__(self, *args, **kwargs):
# def consume(self, kind):
# def leapfrog(self, kind, value=None):
# def parse_docstring(self):
# def parse_decorators(self):
# def parse_definitions(self, class_, all=False):
# def parse_all(self):
# def parse_module(self):
# def parse_definition(self, class_):
# def parse_skip_comment(self):
# def check_current(self, kind=None, value=None):
# def parse_from_import_statement(self):
# def _parse_from_import_source(self):
# def _parse_from_import_names(self, is_future_import):
# class ParseError(Exception):
# class Value(object):
# class Definition(Value):
# class Module(Definition):
# class Package(Module):
# class Function(Definition):
# class NestedFunction(Function):
# class Method(Function):
# class Class(Definition):
# class NestedClass(Class):
# class Decorator(Value):
# class AllError(Exception):
# class TokenStream(object):
# class TokenKind(int):
# class Token(Value):
# class Parser(object):
# VARIADIC_MAGIC_METHODS = ('__init__', '__call__', '__new__')
# LOGICAL_NEWLINES = {tk.NEWLINE, tk.INDENT, tk.DEDENT}
#
# Path: bin/deps/pydocstyle/utils.py
# def is_blank(string):
# def pairwise(iterable, default_value):
, which may contain function names, class names, or code. Output only the next line. | except (EnvironmentError, AllError, ParseError) as error: |
Predict the next line after this snippet: <|code_start|>
Note that ignored error code refer to the entire set of possible
error codes, which is larger than just the PEP-257 convention. To your
convenience, you may use `pydocstyle.violations.conventions.pep257` as
a base set to add or remove errors from.
Examples
---------
>>> check(['pydocstyle.py'])
<generator object check at 0x...>
>>> check(['pydocstyle.py'], select=['D100'])
<generator object check at 0x...>
>>> check(['pydocstyle.py'], ignore=conventions.pep257 - {'D100'})
<generator object check at 0x...>
"""
if select is not None and ignore is not None:
raise IllegalConfiguration('Cannot pass both select and ignore. '
'They are mutually exclusive.')
elif select is not None:
checked_codes = select
elif ignore is not None:
checked_codes = list(set(violations.ErrorRegistry.get_error_codes()) -
set(ignore))
else:
checked_codes = violations.conventions.pep257
for filename in filenames:
<|code_end|>
using the current file's imports:
import ast
import string
import sys
import tokenize as tk
from itertools import takewhile
from re import compile as re
from collections import namedtuple
from . import violations
from .config import IllegalConfiguration
from .parser import (Package, Module, Class, NestedClass, Definition, AllError,
Method, Function, NestedFunction, Parser, StringIO,
ParseError)
from .utils import log, is_blank, pairwise
from .wordlists import IMPERATIVE_VERBS, IMPERATIVE_BLACKLIST, stem
and any relevant context from other files:
# Path: bin/deps/pydocstyle/config.py
# class IllegalConfiguration(Exception):
# """An exception for illegal configurations."""
#
# pass
#
# Path: bin/deps/pydocstyle/parser.py
# def next(obj, default=nothing):
# def __str__(self):
# def humanize(string):
# def __init__(self, *args):
# def __hash__(self):
# def __eq__(self, other):
# def __repr__(self):
# def __iter__(self):
# def _publicity(self):
# def source(self):
# def is_empty_or_comment(line):
# def __str__(self):
# def is_public(self):
# def __str__(self):
# def is_public(self):
# def is_test(self):
# def is_magic(self):
# def is_init(self):
# def is_public(self):
# def is_public(self):
# def __init__(self, message):
# def __init__(self, filelike):
# def move(self):
# def _next_from_generator(self):
# def __iter__(self):
# def __repr__(self):
# def __init__(self, *args):
# def parse(self, filelike, filename):
# def __call__(self, *args, **kwargs):
# def consume(self, kind):
# def leapfrog(self, kind, value=None):
# def parse_docstring(self):
# def parse_decorators(self):
# def parse_definitions(self, class_, all=False):
# def parse_all(self):
# def parse_module(self):
# def parse_definition(self, class_):
# def parse_skip_comment(self):
# def check_current(self, kind=None, value=None):
# def parse_from_import_statement(self):
# def _parse_from_import_source(self):
# def _parse_from_import_names(self, is_future_import):
# class ParseError(Exception):
# class Value(object):
# class Definition(Value):
# class Module(Definition):
# class Package(Module):
# class Function(Definition):
# class NestedFunction(Function):
# class Method(Function):
# class Class(Definition):
# class NestedClass(Class):
# class Decorator(Value):
# class AllError(Exception):
# class TokenStream(object):
# class TokenKind(int):
# class Token(Value):
# class Parser(object):
# VARIADIC_MAGIC_METHODS = ('__init__', '__call__', '__new__')
# LOGICAL_NEWLINES = {tk.NEWLINE, tk.INDENT, tk.DEDENT}
#
# Path: bin/deps/pydocstyle/utils.py
# def is_blank(string):
# def pairwise(iterable, default_value):
. Output only the next line. | log.info('Checking file %s.', filename) |
Given the code snippet: <|code_start|> error.set_context(explanation=explanation,
definition=definition)
yield error
if this_check._terminal:
terminate = True
break
if terminate:
break
@property
def checks(self):
all = [this_check for this_check in vars(type(self)).values()
if hasattr(this_check, '_check_for')]
return sorted(all, key=lambda this_check: not this_check._terminal)
@check_for(Definition, terminal=True)
def check_docstring_missing(self, definition, docstring):
"""D10{0,1,2,3}: Public definitions should have docstrings.
All modules should normally have docstrings. [...] all functions and
classes exported by a module should also have docstrings. Public
methods (including the __init__ constructor) should also have
docstrings.
Note: Public (exported) definitions are either those with names listed
in __all__ variable (if present), or those that do not start
with a single underscore.
"""
if (not docstring and definition.is_public or
<|code_end|>
, generate the next line using the imports in this file:
import ast
import string
import sys
import tokenize as tk
from itertools import takewhile
from re import compile as re
from collections import namedtuple
from . import violations
from .config import IllegalConfiguration
from .parser import (Package, Module, Class, NestedClass, Definition, AllError,
Method, Function, NestedFunction, Parser, StringIO,
ParseError)
from .utils import log, is_blank, pairwise
from .wordlists import IMPERATIVE_VERBS, IMPERATIVE_BLACKLIST, stem
and context (functions, classes, or occasionally code) from other files:
# Path: bin/deps/pydocstyle/config.py
# class IllegalConfiguration(Exception):
# """An exception for illegal configurations."""
#
# pass
#
# Path: bin/deps/pydocstyle/parser.py
# def next(obj, default=nothing):
# def __str__(self):
# def humanize(string):
# def __init__(self, *args):
# def __hash__(self):
# def __eq__(self, other):
# def __repr__(self):
# def __iter__(self):
# def _publicity(self):
# def source(self):
# def is_empty_or_comment(line):
# def __str__(self):
# def is_public(self):
# def __str__(self):
# def is_public(self):
# def is_test(self):
# def is_magic(self):
# def is_init(self):
# def is_public(self):
# def is_public(self):
# def __init__(self, message):
# def __init__(self, filelike):
# def move(self):
# def _next_from_generator(self):
# def __iter__(self):
# def __repr__(self):
# def __init__(self, *args):
# def parse(self, filelike, filename):
# def __call__(self, *args, **kwargs):
# def consume(self, kind):
# def leapfrog(self, kind, value=None):
# def parse_docstring(self):
# def parse_decorators(self):
# def parse_definitions(self, class_, all=False):
# def parse_all(self):
# def parse_module(self):
# def parse_definition(self, class_):
# def parse_skip_comment(self):
# def check_current(self, kind=None, value=None):
# def parse_from_import_statement(self):
# def _parse_from_import_source(self):
# def _parse_from_import_names(self, is_future_import):
# class ParseError(Exception):
# class Value(object):
# class Definition(Value):
# class Module(Definition):
# class Package(Module):
# class Function(Definition):
# class NestedFunction(Function):
# class Method(Function):
# class Class(Definition):
# class NestedClass(Class):
# class Decorator(Value):
# class AllError(Exception):
# class TokenStream(object):
# class TokenKind(int):
# class Token(Value):
# class Parser(object):
# VARIADIC_MAGIC_METHODS = ('__init__', '__call__', '__new__')
# LOGICAL_NEWLINES = {tk.NEWLINE, tk.INDENT, tk.DEDENT}
#
# Path: bin/deps/pydocstyle/utils.py
# def is_blank(string):
# def pairwise(iterable, default_value):
. Output only the next line. | docstring and is_blank(ast.literal_eval(docstring))): |
Given the following code snippet before the placeholder: <|code_start|> def _suspected_as_section(_line):
result = self._get_leading_words(_line.lower())
return result in lower_section_names
# Finding our suspects.
suspected_section_indices = [i for i, line in enumerate(lines) if
_suspected_as_section(line)]
SectionContext = namedtuple('SectionContext', ('section_name',
'previous_line',
'line',
'following_lines',
'original_index',
'is_last_section'))
# First - create a list of possible contexts. Note that the
# `following_linex` member is until the end of the docstring.
contexts = (SectionContext(self._get_leading_words(lines[i].strip()),
lines[i - 1],
lines[i],
lines[i + 1:],
i,
False)
for i in suspected_section_indices)
# Now that we have manageable objects - rule out false positives.
contexts = (c for c in contexts if self._is_a_docstring_section(c))
# Now we shall trim the `following lines` field to only reach the
# next section name.
<|code_end|>
, predict the next line using imports from the current file:
import ast
import string
import sys
import tokenize as tk
from itertools import takewhile
from re import compile as re
from collections import namedtuple
from . import violations
from .config import IllegalConfiguration
from .parser import (Package, Module, Class, NestedClass, Definition, AllError,
Method, Function, NestedFunction, Parser, StringIO,
ParseError)
from .utils import log, is_blank, pairwise
from .wordlists import IMPERATIVE_VERBS, IMPERATIVE_BLACKLIST, stem
and context including class names, function names, and sometimes code from other files:
# Path: bin/deps/pydocstyle/config.py
# class IllegalConfiguration(Exception):
# """An exception for illegal configurations."""
#
# pass
#
# Path: bin/deps/pydocstyle/parser.py
# def next(obj, default=nothing):
# def __str__(self):
# def humanize(string):
# def __init__(self, *args):
# def __hash__(self):
# def __eq__(self, other):
# def __repr__(self):
# def __iter__(self):
# def _publicity(self):
# def source(self):
# def is_empty_or_comment(line):
# def __str__(self):
# def is_public(self):
# def __str__(self):
# def is_public(self):
# def is_test(self):
# def is_magic(self):
# def is_init(self):
# def is_public(self):
# def is_public(self):
# def __init__(self, message):
# def __init__(self, filelike):
# def move(self):
# def _next_from_generator(self):
# def __iter__(self):
# def __repr__(self):
# def __init__(self, *args):
# def parse(self, filelike, filename):
# def __call__(self, *args, **kwargs):
# def consume(self, kind):
# def leapfrog(self, kind, value=None):
# def parse_docstring(self):
# def parse_decorators(self):
# def parse_definitions(self, class_, all=False):
# def parse_all(self):
# def parse_module(self):
# def parse_definition(self, class_):
# def parse_skip_comment(self):
# def check_current(self, kind=None, value=None):
# def parse_from_import_statement(self):
# def _parse_from_import_source(self):
# def _parse_from_import_names(self, is_future_import):
# class ParseError(Exception):
# class Value(object):
# class Definition(Value):
# class Module(Definition):
# class Package(Module):
# class Function(Definition):
# class NestedFunction(Function):
# class Method(Function):
# class Class(Definition):
# class NestedClass(Class):
# class Decorator(Value):
# class AllError(Exception):
# class TokenStream(object):
# class TokenKind(int):
# class Token(Value):
# class Parser(object):
# VARIADIC_MAGIC_METHODS = ('__init__', '__call__', '__new__')
# LOGICAL_NEWLINES = {tk.NEWLINE, tk.INDENT, tk.DEDENT}
#
# Path: bin/deps/pydocstyle/utils.py
# def is_blank(string):
# def pairwise(iterable, default_value):
. Output only the next line. | for a, b in pairwise(contexts, None): |
Here is a snippet: <|code_start|>VARIADIC_MAGIC_METHODS = ('__init__', '__call__', '__new__')
class AllError(Exception):
"""Raised when there is a problem with __all__ when parsing."""
def __init__(self, message):
"""Initialize the error with a more specific message."""
Exception.__init__(
self, message + textwrap.dedent("""
That means pydocstyle cannot decide which definitions are
public. Variable __all__ should be present at most once in
each file, in form
`__all__ = ('a_public_function', 'APublicClass', ...)`.
More info on __all__: http://stackoverflow.com/q/44834/. ')
"""))
class TokenStream(object):
# A logical newline is where a new expression or statement begins. When
# there is a physical new line, but not a logical one, for example:
# (x +
# y)
# The token will be tk.NL, not tk.NEWLINE.
LOGICAL_NEWLINES = {tk.NEWLINE, tk.INDENT, tk.DEDENT}
def __init__(self, filelike):
self._generator = tk.generate_tokens(filelike.readline)
self.current = Token(*next(self._generator, None))
self.line = self.current.start[0]
<|code_end|>
. Write the next line using the current file imports:
import logging
import six
import textwrap
import tokenize as tk
from itertools import chain, dropwhile
from re import compile as re
from .utils import log
from StringIO import StringIO
from io import StringIO
and context from other files:
# Path: bin/deps/pydocstyle/utils.py
# def is_blank(string):
# def pairwise(iterable, default_value):
, which may include functions, classes, or code. Output only the next line. | self.log = log |
Using the snippet: <|code_start|> self.code = code
self.short_desc = short_desc
self.context = context
self.parameters = parameters
self.definition = None
self.explanation = None
def set_context(self, definition, explanation):
"""Set the source code context for this error."""
self.definition = definition
self.explanation = explanation
filename = property(lambda self: self.definition.module.name)
line = property(lambda self: self.definition.start)
@property
def message(self):
"""Return the message to print to the user."""
ret = '{}: {}'.format(self.code, self.short_desc)
if self.context is not None:
specific_error_msg = self.context.format(*self.parameters)
ret += ' ({})'.format(specific_error_msg)
return ret
@property
def lines(self):
"""Return the source code lines for this error."""
source = ''
lines = self.definition.source
offset = self.definition.start
<|code_end|>
, determine the next line of code. You have imports:
from itertools import dropwhile
from functools import partial
from collections import namedtuple
from .utils import is_blank
and context (class names, function names, or code) available:
# Path: bin/deps/pydocstyle/utils.py
# def is_blank(string):
# """Return True iff the string contains only whitespaces."""
# return not string.strip()
. Output only the next line. | lines_stripped = list(reversed(list(dropwhile(is_blank, |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.