Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Based on the snippet: <|code_start|> def DBRepair(self, db, db_uid, *args, **kwargs):
db_path = self.databases['paths_index'][db_uid]
plyvel.RepairDB(db_path)
return success()
def _gen_response(self, request, cmd_status, cmd_value):
if cmd_status == FAILURE_STATUS:
header = ResponseHeader(status=cmd_status, err_code=cmd_value[0], err_msg=cmd_value[1])
content = ResponseContent(datas=None)
else:
if 'compression' in request.meta:
compression = request.meta['compression']
else:
compression = False
header = ResponseHeader(status=cmd_status, compression=compression)
content = ResponseContent(datas=cmd_value, compression=compression)
return header, content
def command(self, message, *args, **kwargs):
status = SUCCESS_STATUS
err_code, err_msg = None, None
# DB does not exist
if message.db_uid and (not message.db_uid in self.databases):
error_msg = "Database %s doesn't exist" % message.db_uid
errors_logger.error(error_msg)
<|code_end|>
, predict the immediate next line with the help of imports:
import plyvel
import logging
import time
from .db import DatabaseOptions
from .message import ResponseContent, ResponseHeader
from .constants import KEY_ERROR, TYPE_ERROR, DATABASE_ERROR,\
VALUE_ERROR, RUNTIME_ERROR, SIGNAL_ERROR,\
SUCCESS_STATUS, FAILURE_STATUS, WARNING_STATUS,\
SIGNAL_BATCH_PUT, SIGNAL_BATCH_DELETE
from .utils.patterns import destructurate
from .helpers.internals import failure, success
and context (classes, functions, sometimes code) from other files:
# Path: elevator/db.py
# class DatabaseOptions(dict):
# def __init__(self, *args, **kwargs):
# self['create_if_missing'] = True
# self['error_if_exists'] = False
# self['bloom_filter_bits'] = 10 # Value recommended by leveldb doc
# self['paranoid_checks'] = False
# self['lru_cache_size'] = 512 * (1 << 20) # 512 Mo
# self['write_buffer_size'] = 4 * (1 << 20) # 4 Mo
# self['block_size'] = 4096
# self['max_open_files'] = 1000
#
# for key, value in kwargs.iteritems():
# if key in self:
# self[key] = value
#
# Path: elevator/message.py
# class ResponseContent(tuple):
# """Handler objects for responses messages
#
# Format:
# {
# 'meta': {
# 'status': 1|0|-1,
# 'err_code': null|0|1|[...],
# 'err_msg': '',
# },
# 'datas': [...],
# }
# """
# def __new__(cls, *args, **kwargs):
# response = {
# 'datas': cls._format_datas(kwargs['datas']),
# }
# activity_logger.debug('<Response ' + str(response['datas']) + '>')
# msg = msgpack.packb(response)
#
# if kwargs.pop('compression', False) is True:
# msg = lz4.dumps(msg)
#
# return msg
#
# @classmethod
# def _format_datas(cls, datas):
# if datas and not isinstance(datas, (tuple, list)):
# datas = [datas]
# return datas
#
# class ResponseHeader(dict):
# def __new__(cls, *args, **kwargs):
# header = {
# 'status': kwargs.pop('status'),
# 'err_code': kwargs.pop('err_code', None),
# 'err_msg': kwargs.pop('err_msg', None),
# 'compression': kwargs.pop('compression', False)
# }
# activity_logger.debug('<ResponseHeader ' + str(header) + '>')
#
# for key, value in kwargs.iteritems():
# header.update({key: value})
#
# return msgpack.packb(header)
#
# Path: elevator/constants.py
# KEY_ERROR = 1
#
# TYPE_ERROR = 0
#
# DATABASE_ERROR = 6
#
# VALUE_ERROR = 2
#
# RUNTIME_ERROR = 4
#
# SIGNAL_ERROR = 7
#
# SUCCESS_STATUS = 1
#
# FAILURE_STATUS = -1
#
# WARNING_STATUS = -2
#
# SIGNAL_BATCH_PUT = 1
#
# SIGNAL_BATCH_DELETE = 0
#
# Path: elevator/utils/patterns.py
# def destructurate(container):
# try:
# return container[0], container[1:]
# except (KeyError, AttributeError):
# raise DestructurationError("Can't destructurate a non-sequence container")
#
# Path: elevator/helpers/internals.py
# def failure(err_code, err_msg):
# """Returns a formatted error status and content"""
# return (FAILURE_STATUS, [err_code, err_msg])
#
# def success(content=None):
# """Returns a formatted success status and content"""
# return (SUCCESS_STATUS, content)
. Output only the next line. | status, value = failure(RUNTIME_ERROR, error_msg) |
Based on the snippet: <|code_start|> # a consistent state of the db
db_snapshot = db.snapshot()
it = db_snapshot.iterator(start=key_from,
include_key=include_key,
include_value=include_value,
include_stop=True)
value = []
pos = 0
while pos < offset:
try:
value.append(it.next())
except StopIteration:
break
pos += 1
return success(value)
def Batch(self, db, collection, *args, **kwargs):
batch = db.write_batch()
batch_actions = {
SIGNAL_BATCH_PUT: batch.put,
SIGNAL_BATCH_DELETE: batch.delete,
}
try:
for command in collection:
signal, args = destructurate(command)
batch_actions[signal](*args)
except KeyError: # Unrecognized signal
<|code_end|>
, predict the immediate next line with the help of imports:
import plyvel
import logging
import time
from .db import DatabaseOptions
from .message import ResponseContent, ResponseHeader
from .constants import KEY_ERROR, TYPE_ERROR, DATABASE_ERROR,\
VALUE_ERROR, RUNTIME_ERROR, SIGNAL_ERROR,\
SUCCESS_STATUS, FAILURE_STATUS, WARNING_STATUS,\
SIGNAL_BATCH_PUT, SIGNAL_BATCH_DELETE
from .utils.patterns import destructurate
from .helpers.internals import failure, success
and context (classes, functions, sometimes code) from other files:
# Path: elevator/db.py
# class DatabaseOptions(dict):
# def __init__(self, *args, **kwargs):
# self['create_if_missing'] = True
# self['error_if_exists'] = False
# self['bloom_filter_bits'] = 10 # Value recommended by leveldb doc
# self['paranoid_checks'] = False
# self['lru_cache_size'] = 512 * (1 << 20) # 512 Mo
# self['write_buffer_size'] = 4 * (1 << 20) # 4 Mo
# self['block_size'] = 4096
# self['max_open_files'] = 1000
#
# for key, value in kwargs.iteritems():
# if key in self:
# self[key] = value
#
# Path: elevator/message.py
# class ResponseContent(tuple):
# """Handler objects for responses messages
#
# Format:
# {
# 'meta': {
# 'status': 1|0|-1,
# 'err_code': null|0|1|[...],
# 'err_msg': '',
# },
# 'datas': [...],
# }
# """
# def __new__(cls, *args, **kwargs):
# response = {
# 'datas': cls._format_datas(kwargs['datas']),
# }
# activity_logger.debug('<Response ' + str(response['datas']) + '>')
# msg = msgpack.packb(response)
#
# if kwargs.pop('compression', False) is True:
# msg = lz4.dumps(msg)
#
# return msg
#
# @classmethod
# def _format_datas(cls, datas):
# if datas and not isinstance(datas, (tuple, list)):
# datas = [datas]
# return datas
#
# class ResponseHeader(dict):
# def __new__(cls, *args, **kwargs):
# header = {
# 'status': kwargs.pop('status'),
# 'err_code': kwargs.pop('err_code', None),
# 'err_msg': kwargs.pop('err_msg', None),
# 'compression': kwargs.pop('compression', False)
# }
# activity_logger.debug('<ResponseHeader ' + str(header) + '>')
#
# for key, value in kwargs.iteritems():
# header.update({key: value})
#
# return msgpack.packb(header)
#
# Path: elevator/constants.py
# KEY_ERROR = 1
#
# TYPE_ERROR = 0
#
# DATABASE_ERROR = 6
#
# VALUE_ERROR = 2
#
# RUNTIME_ERROR = 4
#
# SIGNAL_ERROR = 7
#
# SUCCESS_STATUS = 1
#
# FAILURE_STATUS = -1
#
# WARNING_STATUS = -2
#
# SIGNAL_BATCH_PUT = 1
#
# SIGNAL_BATCH_DELETE = 0
#
# Path: elevator/utils/patterns.py
# def destructurate(container):
# try:
# return container[0], container[1:]
# except (KeyError, AttributeError):
# raise DestructurationError("Can't destructurate a non-sequence container")
#
# Path: elevator/helpers/internals.py
# def failure(err_code, err_msg):
# """Returns a formatted error status and content"""
# return (FAILURE_STATUS, [err_code, err_msg])
#
# def success(content=None):
# """Returns a formatted success status and content"""
# return (SUCCESS_STATUS, content)
. Output only the next line. | return failure(SIGNAL_ERROR, "Unrecognized signal received : %r" % signal) |
Predict the next line after this snippet: <|code_start|> 'MGET': self.MGet,
'PING': self.Ping,
'DBCONNECT': self.DBConnect,
'DBMOUNT': self.DBMount,
'DBUMOUNT': self.DBUmount,
'DBCREATE': self.DBCreate,
'DBDROP': self.DBDrop,
'DBLIST': self.DBList,
'DBREPAIR': self.DBRepair,
}
self.context = {}
def Get(self, db, key, *args, **kwargs):
"""
Handles GET message command.
Executes a Get operation over the plyvel backend.
db => LevelDB object
*args => (key) to fetch
"""
value = db.get(key)
if not value:
error_msg = "Key %r does not exist" % key
errors_logger.exception(error_msg)
return failure(KEY_ERROR, error_msg)
else:
return success(value)
def MGet(self, db, keys, *args, **kwargs):
<|code_end|>
using the current file's imports:
import plyvel
import logging
import time
from .db import DatabaseOptions
from .message import ResponseContent, ResponseHeader
from .constants import KEY_ERROR, TYPE_ERROR, DATABASE_ERROR,\
VALUE_ERROR, RUNTIME_ERROR, SIGNAL_ERROR,\
SUCCESS_STATUS, FAILURE_STATUS, WARNING_STATUS,\
SIGNAL_BATCH_PUT, SIGNAL_BATCH_DELETE
from .utils.patterns import destructurate
from .helpers.internals import failure, success
and any relevant context from other files:
# Path: elevator/db.py
# class DatabaseOptions(dict):
# def __init__(self, *args, **kwargs):
# self['create_if_missing'] = True
# self['error_if_exists'] = False
# self['bloom_filter_bits'] = 10 # Value recommended by leveldb doc
# self['paranoid_checks'] = False
# self['lru_cache_size'] = 512 * (1 << 20) # 512 Mo
# self['write_buffer_size'] = 4 * (1 << 20) # 4 Mo
# self['block_size'] = 4096
# self['max_open_files'] = 1000
#
# for key, value in kwargs.iteritems():
# if key in self:
# self[key] = value
#
# Path: elevator/message.py
# class ResponseContent(tuple):
# """Handler objects for responses messages
#
# Format:
# {
# 'meta': {
# 'status': 1|0|-1,
# 'err_code': null|0|1|[...],
# 'err_msg': '',
# },
# 'datas': [...],
# }
# """
# def __new__(cls, *args, **kwargs):
# response = {
# 'datas': cls._format_datas(kwargs['datas']),
# }
# activity_logger.debug('<Response ' + str(response['datas']) + '>')
# msg = msgpack.packb(response)
#
# if kwargs.pop('compression', False) is True:
# msg = lz4.dumps(msg)
#
# return msg
#
# @classmethod
# def _format_datas(cls, datas):
# if datas and not isinstance(datas, (tuple, list)):
# datas = [datas]
# return datas
#
# class ResponseHeader(dict):
# def __new__(cls, *args, **kwargs):
# header = {
# 'status': kwargs.pop('status'),
# 'err_code': kwargs.pop('err_code', None),
# 'err_msg': kwargs.pop('err_msg', None),
# 'compression': kwargs.pop('compression', False)
# }
# activity_logger.debug('<ResponseHeader ' + str(header) + '>')
#
# for key, value in kwargs.iteritems():
# header.update({key: value})
#
# return msgpack.packb(header)
#
# Path: elevator/constants.py
# KEY_ERROR = 1
#
# TYPE_ERROR = 0
#
# DATABASE_ERROR = 6
#
# VALUE_ERROR = 2
#
# RUNTIME_ERROR = 4
#
# SIGNAL_ERROR = 7
#
# SUCCESS_STATUS = 1
#
# FAILURE_STATUS = -1
#
# WARNING_STATUS = -2
#
# SIGNAL_BATCH_PUT = 1
#
# SIGNAL_BATCH_DELETE = 0
#
# Path: elevator/utils/patterns.py
# def destructurate(container):
# try:
# return container[0], container[1:]
# except (KeyError, AttributeError):
# raise DestructurationError("Can't destructurate a non-sequence container")
#
# Path: elevator/helpers/internals.py
# def failure(err_code, err_msg):
# """Returns a formatted error status and content"""
# return (FAILURE_STATUS, [err_code, err_msg])
#
# def success(content=None):
# """Returns a formatted success status and content"""
# return (SUCCESS_STATUS, content)
. Output only the next line. | status = SUCCESS_STATUS |
Given snippet: <|code_start|> def DBCreate(self, db, db_name, db_options=None, *args, **kwargs):
db_options = DatabaseOptions(**db_options) if db_options else DatabaseOptions()
if db_name in self.databases.index['name_to_uid']:
error_msg = "Database %s already exists" % db_name
errors_logger.error(error_msg)
return failure(DATABASE_ERROR, error_msg)
return self.databases.add(db_name, db_options)
def DBDrop(self, db, db_name, *args, **kwargs):
if not self.databases.exists(db_name):
error_msg = "Database %s does not exist" % db_name
errors_logger.error(error_msg)
return failure(DATABASE_ERROR, error_msg)
status, content = self.databases.drop(db_name)
return status, content
def DBList(self, db, *args, **kwargs):
return success(self.databases.list())
def DBRepair(self, db, db_uid, *args, **kwargs):
db_path = self.databases['paths_index'][db_uid]
plyvel.RepairDB(db_path)
return success()
def _gen_response(self, request, cmd_status, cmd_value):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import plyvel
import logging
import time
from .db import DatabaseOptions
from .message import ResponseContent, ResponseHeader
from .constants import KEY_ERROR, TYPE_ERROR, DATABASE_ERROR,\
VALUE_ERROR, RUNTIME_ERROR, SIGNAL_ERROR,\
SUCCESS_STATUS, FAILURE_STATUS, WARNING_STATUS,\
SIGNAL_BATCH_PUT, SIGNAL_BATCH_DELETE
from .utils.patterns import destructurate
from .helpers.internals import failure, success
and context:
# Path: elevator/db.py
# class DatabaseOptions(dict):
# def __init__(self, *args, **kwargs):
# self['create_if_missing'] = True
# self['error_if_exists'] = False
# self['bloom_filter_bits'] = 10 # Value recommended by leveldb doc
# self['paranoid_checks'] = False
# self['lru_cache_size'] = 512 * (1 << 20) # 512 Mo
# self['write_buffer_size'] = 4 * (1 << 20) # 4 Mo
# self['block_size'] = 4096
# self['max_open_files'] = 1000
#
# for key, value in kwargs.iteritems():
# if key in self:
# self[key] = value
#
# Path: elevator/message.py
# class ResponseContent(tuple):
# """Handler objects for responses messages
#
# Format:
# {
# 'meta': {
# 'status': 1|0|-1,
# 'err_code': null|0|1|[...],
# 'err_msg': '',
# },
# 'datas': [...],
# }
# """
# def __new__(cls, *args, **kwargs):
# response = {
# 'datas': cls._format_datas(kwargs['datas']),
# }
# activity_logger.debug('<Response ' + str(response['datas']) + '>')
# msg = msgpack.packb(response)
#
# if kwargs.pop('compression', False) is True:
# msg = lz4.dumps(msg)
#
# return msg
#
# @classmethod
# def _format_datas(cls, datas):
# if datas and not isinstance(datas, (tuple, list)):
# datas = [datas]
# return datas
#
# class ResponseHeader(dict):
# def __new__(cls, *args, **kwargs):
# header = {
# 'status': kwargs.pop('status'),
# 'err_code': kwargs.pop('err_code', None),
# 'err_msg': kwargs.pop('err_msg', None),
# 'compression': kwargs.pop('compression', False)
# }
# activity_logger.debug('<ResponseHeader ' + str(header) + '>')
#
# for key, value in kwargs.iteritems():
# header.update({key: value})
#
# return msgpack.packb(header)
#
# Path: elevator/constants.py
# KEY_ERROR = 1
#
# TYPE_ERROR = 0
#
# DATABASE_ERROR = 6
#
# VALUE_ERROR = 2
#
# RUNTIME_ERROR = 4
#
# SIGNAL_ERROR = 7
#
# SUCCESS_STATUS = 1
#
# FAILURE_STATUS = -1
#
# WARNING_STATUS = -2
#
# SIGNAL_BATCH_PUT = 1
#
# SIGNAL_BATCH_DELETE = 0
#
# Path: elevator/utils/patterns.py
# def destructurate(container):
# try:
# return container[0], container[1:]
# except (KeyError, AttributeError):
# raise DestructurationError("Can't destructurate a non-sequence container")
#
# Path: elevator/helpers/internals.py
# def failure(err_code, err_msg):
# """Returns a formatted error status and content"""
# return (FAILURE_STATUS, [err_code, err_msg])
#
# def success(content=None):
# """Returns a formatted success status and content"""
# return (SUCCESS_STATUS, content)
which might include code, classes, or functions. Output only the next line. | if cmd_status == FAILURE_STATUS: |
Predict the next line for this snippet: <|code_start|> def Get(self, db, key, *args, **kwargs):
"""
Handles GET message command.
Executes a Get operation over the plyvel backend.
db => LevelDB object
*args => (key) to fetch
"""
value = db.get(key)
if not value:
error_msg = "Key %r does not exist" % key
errors_logger.exception(error_msg)
return failure(KEY_ERROR, error_msg)
else:
return success(value)
def MGet(self, db, keys, *args, **kwargs):
status = SUCCESS_STATUS
db_snapshot = db.snapshot()
values = [None] * len(keys)
min_key, max_key = min(keys), max(keys)
keys_index = {k: index for index, k in enumerate(keys)}
bound_range = db_snapshot.iterator(start=min_key, stop=max_key, include_stop=True)
for key, value in bound_range:
if key in keys_index:
values[keys_index[key]] = value
<|code_end|>
with the help of current file imports:
import plyvel
import logging
import time
from .db import DatabaseOptions
from .message import ResponseContent, ResponseHeader
from .constants import KEY_ERROR, TYPE_ERROR, DATABASE_ERROR,\
VALUE_ERROR, RUNTIME_ERROR, SIGNAL_ERROR,\
SUCCESS_STATUS, FAILURE_STATUS, WARNING_STATUS,\
SIGNAL_BATCH_PUT, SIGNAL_BATCH_DELETE
from .utils.patterns import destructurate
from .helpers.internals import failure, success
and context from other files:
# Path: elevator/db.py
# class DatabaseOptions(dict):
# def __init__(self, *args, **kwargs):
# self['create_if_missing'] = True
# self['error_if_exists'] = False
# self['bloom_filter_bits'] = 10 # Value recommended by leveldb doc
# self['paranoid_checks'] = False
# self['lru_cache_size'] = 512 * (1 << 20) # 512 Mo
# self['write_buffer_size'] = 4 * (1 << 20) # 4 Mo
# self['block_size'] = 4096
# self['max_open_files'] = 1000
#
# for key, value in kwargs.iteritems():
# if key in self:
# self[key] = value
#
# Path: elevator/message.py
# class ResponseContent(tuple):
# """Handler objects for responses messages
#
# Format:
# {
# 'meta': {
# 'status': 1|0|-1,
# 'err_code': null|0|1|[...],
# 'err_msg': '',
# },
# 'datas': [...],
# }
# """
# def __new__(cls, *args, **kwargs):
# response = {
# 'datas': cls._format_datas(kwargs['datas']),
# }
# activity_logger.debug('<Response ' + str(response['datas']) + '>')
# msg = msgpack.packb(response)
#
# if kwargs.pop('compression', False) is True:
# msg = lz4.dumps(msg)
#
# return msg
#
# @classmethod
# def _format_datas(cls, datas):
# if datas and not isinstance(datas, (tuple, list)):
# datas = [datas]
# return datas
#
# class ResponseHeader(dict):
# def __new__(cls, *args, **kwargs):
# header = {
# 'status': kwargs.pop('status'),
# 'err_code': kwargs.pop('err_code', None),
# 'err_msg': kwargs.pop('err_msg', None),
# 'compression': kwargs.pop('compression', False)
# }
# activity_logger.debug('<ResponseHeader ' + str(header) + '>')
#
# for key, value in kwargs.iteritems():
# header.update({key: value})
#
# return msgpack.packb(header)
#
# Path: elevator/constants.py
# KEY_ERROR = 1
#
# TYPE_ERROR = 0
#
# DATABASE_ERROR = 6
#
# VALUE_ERROR = 2
#
# RUNTIME_ERROR = 4
#
# SIGNAL_ERROR = 7
#
# SUCCESS_STATUS = 1
#
# FAILURE_STATUS = -1
#
# WARNING_STATUS = -2
#
# SIGNAL_BATCH_PUT = 1
#
# SIGNAL_BATCH_DELETE = 0
#
# Path: elevator/utils/patterns.py
# def destructurate(container):
# try:
# return container[0], container[1:]
# except (KeyError, AttributeError):
# raise DestructurationError("Can't destructurate a non-sequence container")
#
# Path: elevator/helpers/internals.py
# def failure(err_code, err_msg):
# """Returns a formatted error status and content"""
# return (FAILURE_STATUS, [err_code, err_msg])
#
# def success(content=None):
# """Returns a formatted success status and content"""
# return (SUCCESS_STATUS, content)
, which may contain function names, class names, or code. Output only the next line. | status = WARNING_STATUS if any(v is None for v in values) else status |
Continue the code snippet: <|code_start|> del db_snapshot
return success(value)
def Slice(self, db, key_from, offset,
include_key=True, include_value=True):
"""Returns a slice of the db. `offset` keys,
starting a `key_from`"""
# Operates over a snapshot in order to return
# a consistent state of the db
db_snapshot = db.snapshot()
it = db_snapshot.iterator(start=key_from,
include_key=include_key,
include_value=include_value,
include_stop=True)
value = []
pos = 0
while pos < offset:
try:
value.append(it.next())
except StopIteration:
break
pos += 1
return success(value)
def Batch(self, db, collection, *args, **kwargs):
batch = db.write_batch()
batch_actions = {
<|code_end|>
. Use current file imports:
import plyvel
import logging
import time
from .db import DatabaseOptions
from .message import ResponseContent, ResponseHeader
from .constants import KEY_ERROR, TYPE_ERROR, DATABASE_ERROR,\
VALUE_ERROR, RUNTIME_ERROR, SIGNAL_ERROR,\
SUCCESS_STATUS, FAILURE_STATUS, WARNING_STATUS,\
SIGNAL_BATCH_PUT, SIGNAL_BATCH_DELETE
from .utils.patterns import destructurate
from .helpers.internals import failure, success
and context (classes, functions, or code) from other files:
# Path: elevator/db.py
# class DatabaseOptions(dict):
# def __init__(self, *args, **kwargs):
# self['create_if_missing'] = True
# self['error_if_exists'] = False
# self['bloom_filter_bits'] = 10 # Value recommended by leveldb doc
# self['paranoid_checks'] = False
# self['lru_cache_size'] = 512 * (1 << 20) # 512 Mo
# self['write_buffer_size'] = 4 * (1 << 20) # 4 Mo
# self['block_size'] = 4096
# self['max_open_files'] = 1000
#
# for key, value in kwargs.iteritems():
# if key in self:
# self[key] = value
#
# Path: elevator/message.py
# class ResponseContent(tuple):
# """Handler objects for responses messages
#
# Format:
# {
# 'meta': {
# 'status': 1|0|-1,
# 'err_code': null|0|1|[...],
# 'err_msg': '',
# },
# 'datas': [...],
# }
# """
# def __new__(cls, *args, **kwargs):
# response = {
# 'datas': cls._format_datas(kwargs['datas']),
# }
# activity_logger.debug('<Response ' + str(response['datas']) + '>')
# msg = msgpack.packb(response)
#
# if kwargs.pop('compression', False) is True:
# msg = lz4.dumps(msg)
#
# return msg
#
# @classmethod
# def _format_datas(cls, datas):
# if datas and not isinstance(datas, (tuple, list)):
# datas = [datas]
# return datas
#
# class ResponseHeader(dict):
# def __new__(cls, *args, **kwargs):
# header = {
# 'status': kwargs.pop('status'),
# 'err_code': kwargs.pop('err_code', None),
# 'err_msg': kwargs.pop('err_msg', None),
# 'compression': kwargs.pop('compression', False)
# }
# activity_logger.debug('<ResponseHeader ' + str(header) + '>')
#
# for key, value in kwargs.iteritems():
# header.update({key: value})
#
# return msgpack.packb(header)
#
# Path: elevator/constants.py
# KEY_ERROR = 1
#
# TYPE_ERROR = 0
#
# DATABASE_ERROR = 6
#
# VALUE_ERROR = 2
#
# RUNTIME_ERROR = 4
#
# SIGNAL_ERROR = 7
#
# SUCCESS_STATUS = 1
#
# FAILURE_STATUS = -1
#
# WARNING_STATUS = -2
#
# SIGNAL_BATCH_PUT = 1
#
# SIGNAL_BATCH_DELETE = 0
#
# Path: elevator/utils/patterns.py
# def destructurate(container):
# try:
# return container[0], container[1:]
# except (KeyError, AttributeError):
# raise DestructurationError("Can't destructurate a non-sequence container")
#
# Path: elevator/helpers/internals.py
# def failure(err_code, err_msg):
# """Returns a formatted error status and content"""
# return (FAILURE_STATUS, [err_code, err_msg])
#
# def success(content=None):
# """Returns a formatted success status and content"""
# return (SUCCESS_STATUS, content)
. Output only the next line. | SIGNAL_BATCH_PUT: batch.put, |
Predict the next line for this snippet: <|code_start|>
return success(value)
def Slice(self, db, key_from, offset,
include_key=True, include_value=True):
"""Returns a slice of the db. `offset` keys,
starting a `key_from`"""
# Operates over a snapshot in order to return
# a consistent state of the db
db_snapshot = db.snapshot()
it = db_snapshot.iterator(start=key_from,
include_key=include_key,
include_value=include_value,
include_stop=True)
value = []
pos = 0
while pos < offset:
try:
value.append(it.next())
except StopIteration:
break
pos += 1
return success(value)
def Batch(self, db, collection, *args, **kwargs):
batch = db.write_batch()
batch_actions = {
SIGNAL_BATCH_PUT: batch.put,
<|code_end|>
with the help of current file imports:
import plyvel
import logging
import time
from .db import DatabaseOptions
from .message import ResponseContent, ResponseHeader
from .constants import KEY_ERROR, TYPE_ERROR, DATABASE_ERROR,\
VALUE_ERROR, RUNTIME_ERROR, SIGNAL_ERROR,\
SUCCESS_STATUS, FAILURE_STATUS, WARNING_STATUS,\
SIGNAL_BATCH_PUT, SIGNAL_BATCH_DELETE
from .utils.patterns import destructurate
from .helpers.internals import failure, success
and context from other files:
# Path: elevator/db.py
# class DatabaseOptions(dict):
# def __init__(self, *args, **kwargs):
# self['create_if_missing'] = True
# self['error_if_exists'] = False
# self['bloom_filter_bits'] = 10 # Value recommended by leveldb doc
# self['paranoid_checks'] = False
# self['lru_cache_size'] = 512 * (1 << 20) # 512 Mo
# self['write_buffer_size'] = 4 * (1 << 20) # 4 Mo
# self['block_size'] = 4096
# self['max_open_files'] = 1000
#
# for key, value in kwargs.iteritems():
# if key in self:
# self[key] = value
#
# Path: elevator/message.py
# class ResponseContent(tuple):
# """Handler objects for responses messages
#
# Format:
# {
# 'meta': {
# 'status': 1|0|-1,
# 'err_code': null|0|1|[...],
# 'err_msg': '',
# },
# 'datas': [...],
# }
# """
# def __new__(cls, *args, **kwargs):
# response = {
# 'datas': cls._format_datas(kwargs['datas']),
# }
# activity_logger.debug('<Response ' + str(response['datas']) + '>')
# msg = msgpack.packb(response)
#
# if kwargs.pop('compression', False) is True:
# msg = lz4.dumps(msg)
#
# return msg
#
# @classmethod
# def _format_datas(cls, datas):
# if datas and not isinstance(datas, (tuple, list)):
# datas = [datas]
# return datas
#
# class ResponseHeader(dict):
# def __new__(cls, *args, **kwargs):
# header = {
# 'status': kwargs.pop('status'),
# 'err_code': kwargs.pop('err_code', None),
# 'err_msg': kwargs.pop('err_msg', None),
# 'compression': kwargs.pop('compression', False)
# }
# activity_logger.debug('<ResponseHeader ' + str(header) + '>')
#
# for key, value in kwargs.iteritems():
# header.update({key: value})
#
# return msgpack.packb(header)
#
# Path: elevator/constants.py
# KEY_ERROR = 1
#
# TYPE_ERROR = 0
#
# DATABASE_ERROR = 6
#
# VALUE_ERROR = 2
#
# RUNTIME_ERROR = 4
#
# SIGNAL_ERROR = 7
#
# SUCCESS_STATUS = 1
#
# FAILURE_STATUS = -1
#
# WARNING_STATUS = -2
#
# SIGNAL_BATCH_PUT = 1
#
# SIGNAL_BATCH_DELETE = 0
#
# Path: elevator/utils/patterns.py
# def destructurate(container):
# try:
# return container[0], container[1:]
# except (KeyError, AttributeError):
# raise DestructurationError("Can't destructurate a non-sequence container")
#
# Path: elevator/helpers/internals.py
# def failure(err_code, err_msg):
# """Returns a formatted error status and content"""
# return (FAILURE_STATUS, [err_code, err_msg])
#
# def success(content=None):
# """Returns a formatted success status and content"""
# return (SUCCESS_STATUS, content)
, which may contain function names, class names, or code. Output only the next line. | SIGNAL_BATCH_DELETE: batch.delete, |
Here is a snippet: <|code_start|> """Returns a slice of the db. `offset` keys,
starting a `key_from`"""
# Operates over a snapshot in order to return
# a consistent state of the db
db_snapshot = db.snapshot()
it = db_snapshot.iterator(start=key_from,
include_key=include_key,
include_value=include_value,
include_stop=True)
value = []
pos = 0
while pos < offset:
try:
value.append(it.next())
except StopIteration:
break
pos += 1
return success(value)
def Batch(self, db, collection, *args, **kwargs):
batch = db.write_batch()
batch_actions = {
SIGNAL_BATCH_PUT: batch.put,
SIGNAL_BATCH_DELETE: batch.delete,
}
try:
for command in collection:
<|code_end|>
. Write the next line using the current file imports:
import plyvel
import logging
import time
from .db import DatabaseOptions
from .message import ResponseContent, ResponseHeader
from .constants import KEY_ERROR, TYPE_ERROR, DATABASE_ERROR,\
VALUE_ERROR, RUNTIME_ERROR, SIGNAL_ERROR,\
SUCCESS_STATUS, FAILURE_STATUS, WARNING_STATUS,\
SIGNAL_BATCH_PUT, SIGNAL_BATCH_DELETE
from .utils.patterns import destructurate
from .helpers.internals import failure, success
and context from other files:
# Path: elevator/db.py
# class DatabaseOptions(dict):
# def __init__(self, *args, **kwargs):
# self['create_if_missing'] = True
# self['error_if_exists'] = False
# self['bloom_filter_bits'] = 10 # Value recommended by leveldb doc
# self['paranoid_checks'] = False
# self['lru_cache_size'] = 512 * (1 << 20) # 512 Mo
# self['write_buffer_size'] = 4 * (1 << 20) # 4 Mo
# self['block_size'] = 4096
# self['max_open_files'] = 1000
#
# for key, value in kwargs.iteritems():
# if key in self:
# self[key] = value
#
# Path: elevator/message.py
# class ResponseContent(tuple):
# """Handler objects for responses messages
#
# Format:
# {
# 'meta': {
# 'status': 1|0|-1,
# 'err_code': null|0|1|[...],
# 'err_msg': '',
# },
# 'datas': [...],
# }
# """
# def __new__(cls, *args, **kwargs):
# response = {
# 'datas': cls._format_datas(kwargs['datas']),
# }
# activity_logger.debug('<Response ' + str(response['datas']) + '>')
# msg = msgpack.packb(response)
#
# if kwargs.pop('compression', False) is True:
# msg = lz4.dumps(msg)
#
# return msg
#
# @classmethod
# def _format_datas(cls, datas):
# if datas and not isinstance(datas, (tuple, list)):
# datas = [datas]
# return datas
#
# class ResponseHeader(dict):
# def __new__(cls, *args, **kwargs):
# header = {
# 'status': kwargs.pop('status'),
# 'err_code': kwargs.pop('err_code', None),
# 'err_msg': kwargs.pop('err_msg', None),
# 'compression': kwargs.pop('compression', False)
# }
# activity_logger.debug('<ResponseHeader ' + str(header) + '>')
#
# for key, value in kwargs.iteritems():
# header.update({key: value})
#
# return msgpack.packb(header)
#
# Path: elevator/constants.py
# KEY_ERROR = 1
#
# TYPE_ERROR = 0
#
# DATABASE_ERROR = 6
#
# VALUE_ERROR = 2
#
# RUNTIME_ERROR = 4
#
# SIGNAL_ERROR = 7
#
# SUCCESS_STATUS = 1
#
# FAILURE_STATUS = -1
#
# WARNING_STATUS = -2
#
# SIGNAL_BATCH_PUT = 1
#
# SIGNAL_BATCH_DELETE = 0
#
# Path: elevator/utils/patterns.py
# def destructurate(container):
# try:
# return container[0], container[1:]
# except (KeyError, AttributeError):
# raise DestructurationError("Can't destructurate a non-sequence container")
#
# Path: elevator/helpers/internals.py
# def failure(err_code, err_msg):
# """Returns a formatted error status and content"""
# return (FAILURE_STATUS, [err_code, err_msg])
#
# def success(content=None):
# """Returns a formatted success status and content"""
# return (SUCCESS_STATUS, content)
, which may include functions, classes, or code. Output only the next line. | signal, args = destructurate(command) |
Continue the code snippet: <|code_start|> 'DELETE': self.Delete,
'EXISTS': self.Exists,
'RANGE': self.Range,
'SLICE': self.Slice,
'BATCH': self.Batch,
'MGET': self.MGet,
'PING': self.Ping,
'DBCONNECT': self.DBConnect,
'DBMOUNT': self.DBMount,
'DBUMOUNT': self.DBUmount,
'DBCREATE': self.DBCreate,
'DBDROP': self.DBDrop,
'DBLIST': self.DBList,
'DBREPAIR': self.DBRepair,
}
self.context = {}
def Get(self, db, key, *args, **kwargs):
"""
Handles GET message command.
Executes a Get operation over the plyvel backend.
db => LevelDB object
*args => (key) to fetch
"""
value = db.get(key)
if not value:
error_msg = "Key %r does not exist" % key
errors_logger.exception(error_msg)
<|code_end|>
. Use current file imports:
import plyvel
import logging
import time
from .db import DatabaseOptions
from .message import ResponseContent, ResponseHeader
from .constants import KEY_ERROR, TYPE_ERROR, DATABASE_ERROR,\
VALUE_ERROR, RUNTIME_ERROR, SIGNAL_ERROR,\
SUCCESS_STATUS, FAILURE_STATUS, WARNING_STATUS,\
SIGNAL_BATCH_PUT, SIGNAL_BATCH_DELETE
from .utils.patterns import destructurate
from .helpers.internals import failure, success
and context (classes, functions, or code) from other files:
# Path: elevator/db.py
# class DatabaseOptions(dict):
# def __init__(self, *args, **kwargs):
# self['create_if_missing'] = True
# self['error_if_exists'] = False
# self['bloom_filter_bits'] = 10 # Value recommended by leveldb doc
# self['paranoid_checks'] = False
# self['lru_cache_size'] = 512 * (1 << 20) # 512 Mo
# self['write_buffer_size'] = 4 * (1 << 20) # 4 Mo
# self['block_size'] = 4096
# self['max_open_files'] = 1000
#
# for key, value in kwargs.iteritems():
# if key in self:
# self[key] = value
#
# Path: elevator/message.py
# class ResponseContent(tuple):
# """Handler objects for responses messages
#
# Format:
# {
# 'meta': {
# 'status': 1|0|-1,
# 'err_code': null|0|1|[...],
# 'err_msg': '',
# },
# 'datas': [...],
# }
# """
# def __new__(cls, *args, **kwargs):
# response = {
# 'datas': cls._format_datas(kwargs['datas']),
# }
# activity_logger.debug('<Response ' + str(response['datas']) + '>')
# msg = msgpack.packb(response)
#
# if kwargs.pop('compression', False) is True:
# msg = lz4.dumps(msg)
#
# return msg
#
# @classmethod
# def _format_datas(cls, datas):
# if datas and not isinstance(datas, (tuple, list)):
# datas = [datas]
# return datas
#
# class ResponseHeader(dict):
# def __new__(cls, *args, **kwargs):
# header = {
# 'status': kwargs.pop('status'),
# 'err_code': kwargs.pop('err_code', None),
# 'err_msg': kwargs.pop('err_msg', None),
# 'compression': kwargs.pop('compression', False)
# }
# activity_logger.debug('<ResponseHeader ' + str(header) + '>')
#
# for key, value in kwargs.iteritems():
# header.update({key: value})
#
# return msgpack.packb(header)
#
# Path: elevator/constants.py
# KEY_ERROR = 1
#
# TYPE_ERROR = 0
#
# DATABASE_ERROR = 6
#
# VALUE_ERROR = 2
#
# RUNTIME_ERROR = 4
#
# SIGNAL_ERROR = 7
#
# SUCCESS_STATUS = 1
#
# FAILURE_STATUS = -1
#
# WARNING_STATUS = -2
#
# SIGNAL_BATCH_PUT = 1
#
# SIGNAL_BATCH_DELETE = 0
#
# Path: elevator/utils/patterns.py
# def destructurate(container):
# try:
# return container[0], container[1:]
# except (KeyError, AttributeError):
# raise DestructurationError("Can't destructurate a non-sequence container")
#
# Path: elevator/helpers/internals.py
# def failure(err_code, err_msg):
# """Returns a formatted error status and content"""
# return (FAILURE_STATUS, [err_code, err_msg])
#
# def success(content=None):
# """Returns a formatted success status and content"""
# return (SUCCESS_STATUS, content)
. Output only the next line. | return failure(KEY_ERROR, error_msg) |
Based on the snippet: <|code_start|> 'RANGE': self.Range,
'SLICE': self.Slice,
'BATCH': self.Batch,
'MGET': self.MGet,
'PING': self.Ping,
'DBCONNECT': self.DBConnect,
'DBMOUNT': self.DBMount,
'DBUMOUNT': self.DBUmount,
'DBCREATE': self.DBCreate,
'DBDROP': self.DBDrop,
'DBLIST': self.DBList,
'DBREPAIR': self.DBRepair,
}
self.context = {}
def Get(self, db, key, *args, **kwargs):
"""
Handles GET message command.
Executes a Get operation over the plyvel backend.
db => LevelDB object
*args => (key) to fetch
"""
value = db.get(key)
if not value:
error_msg = "Key %r does not exist" % key
errors_logger.exception(error_msg)
return failure(KEY_ERROR, error_msg)
else:
<|code_end|>
, predict the immediate next line with the help of imports:
import plyvel
import logging
import time
from .db import DatabaseOptions
from .message import ResponseContent, ResponseHeader
from .constants import KEY_ERROR, TYPE_ERROR, DATABASE_ERROR,\
VALUE_ERROR, RUNTIME_ERROR, SIGNAL_ERROR,\
SUCCESS_STATUS, FAILURE_STATUS, WARNING_STATUS,\
SIGNAL_BATCH_PUT, SIGNAL_BATCH_DELETE
from .utils.patterns import destructurate
from .helpers.internals import failure, success
and context (classes, functions, sometimes code) from other files:
# Path: elevator/db.py
# class DatabaseOptions(dict):
# def __init__(self, *args, **kwargs):
# self['create_if_missing'] = True
# self['error_if_exists'] = False
# self['bloom_filter_bits'] = 10 # Value recommended by leveldb doc
# self['paranoid_checks'] = False
# self['lru_cache_size'] = 512 * (1 << 20) # 512 Mo
# self['write_buffer_size'] = 4 * (1 << 20) # 4 Mo
# self['block_size'] = 4096
# self['max_open_files'] = 1000
#
# for key, value in kwargs.iteritems():
# if key in self:
# self[key] = value
#
# Path: elevator/message.py
# class ResponseContent(tuple):
# """Handler objects for responses messages
#
# Format:
# {
# 'meta': {
# 'status': 1|0|-1,
# 'err_code': null|0|1|[...],
# 'err_msg': '',
# },
# 'datas': [...],
# }
# """
# def __new__(cls, *args, **kwargs):
# response = {
# 'datas': cls._format_datas(kwargs['datas']),
# }
# activity_logger.debug('<Response ' + str(response['datas']) + '>')
# msg = msgpack.packb(response)
#
# if kwargs.pop('compression', False) is True:
# msg = lz4.dumps(msg)
#
# return msg
#
# @classmethod
# def _format_datas(cls, datas):
# if datas and not isinstance(datas, (tuple, list)):
# datas = [datas]
# return datas
#
# class ResponseHeader(dict):
# def __new__(cls, *args, **kwargs):
# header = {
# 'status': kwargs.pop('status'),
# 'err_code': kwargs.pop('err_code', None),
# 'err_msg': kwargs.pop('err_msg', None),
# 'compression': kwargs.pop('compression', False)
# }
# activity_logger.debug('<ResponseHeader ' + str(header) + '>')
#
# for key, value in kwargs.iteritems():
# header.update({key: value})
#
# return msgpack.packb(header)
#
# Path: elevator/constants.py
# KEY_ERROR = 1
#
# TYPE_ERROR = 0
#
# DATABASE_ERROR = 6
#
# VALUE_ERROR = 2
#
# RUNTIME_ERROR = 4
#
# SIGNAL_ERROR = 7
#
# SUCCESS_STATUS = 1
#
# FAILURE_STATUS = -1
#
# WARNING_STATUS = -2
#
# SIGNAL_BATCH_PUT = 1
#
# SIGNAL_BATCH_DELETE = 0
#
# Path: elevator/utils/patterns.py
# def destructurate(container):
# try:
# return container[0], container[1:]
# except (KeyError, AttributeError):
# raise DestructurationError("Can't destructurate a non-sequence container")
#
# Path: elevator/helpers/internals.py
# def failure(err_code, err_msg):
# """Returns a formatted error status and content"""
# return (FAILURE_STATUS, [err_code, err_msg])
#
# def success(content=None):
# """Returns a formatted success status and content"""
# return (SUCCESS_STATUS, content)
. Output only the next line. | return success(value) |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
# Copyright (c) 2012 theo crevon
#
# See the file LICENSE for copying permission.
errors_logger = logging.getLogger("errors_logger")
class Proxy():
def __init__(self, transport, endpoint):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import zmq
import logging
from .env import Environment
and context:
# Path: debian/elevator/usr/share/pyshared/elevator/env.py
# class Environment(dict):
# """
# Unix shells like environment class. Implements add,
# get, load, flush methods. Handles lists of values too.
# Basically Acts like a basic key/value store.
# """
# __metaclass__ = Singleton
#
# def __init__(self, env_file='', *args, **kwargs):
# if env_file:
# self.load_from_file(env_file=env_file) # Has to be called last!
#
# self.update(kwargs)
# dict.__init__(self, *args, **kwargs)
#
# def load_from_file(self, env_file):
# """
# Updates the environment using an ini file containing
# key/value descriptions.
# """
# config = ConfigParser()
#
# with open(env_file, 'r') as f:
# config.readfp(f)
#
# for section in config.sections():
# self.update({section: items_to_dict(config.items(section))})
#
# def reload_from_file(self, env_file=''):
# self.flush(env_file)
# self.load(env_file)
#
# def load_from_args(self, section, args):
# """Loads argparse kwargs into environment, as `section`"""
# if not section in self:
# self[section] = {}
#
# for (arg, value) in args:
# self[section][arg] = value
#
# def flush(self):
# """
# Flushes the environment from it's manually
# set attributes.
# """
# for attr in self.attributes:
# delattr(self, attr)
which might include code, classes, or functions. Output only the next line. | self.env = Environment() |
Given the code snippet: <|code_start|> def status(self, db_name):
"""Returns the mounted/unmounted database status"""
db_uid = self.index['name_to_uid'][db_name] if db_name in self.index['name_to_uid'] else None
return self[db_uid].status
def mount(self, db_name):
db_uid = self.index['name_to_uid'][db_name] if db_name in self.index['name_to_uid'] else None
return self[db_uid].mount()
def umount(self, db_name):
db_uid = self.index['name_to_uid'][db_name] if db_name in self.index['name_to_uid'] else None
return self[db_uid].umount()
def add(self, db_name, db_options=None):
"""Adds a db to the DatabasesStore object, and sync it
to the store file"""
db_options = db_options or DatabaseOptions()
db_name_is_path = db_name.startswith('.') or ('/' in db_name)
is_abspath = lambda: not db_name.startswith('.') and ('/' in db_name)
# Handle case when a db is a path
if db_name_is_path:
if not is_abspath():
return failure(DATABASE_ERROR, "Canno't create database from relative path")
try:
new_db_path = db_name
if not os.path.exists(new_db_path):
os.mkdir(new_db_path)
except OSError as e:
<|code_end|>
, generate the next line using the imports in this file:
import os
import uuid
import logging
import plyvel
import ujson as json
from shutil import rmtree
from plyvel import CorruptionError
from .constants import OS_ERROR, DATABASE_ERROR
from .utils.patterns import enum
from .helpers.internals import failure, success
and context (functions, classes, or occasionally code) from other files:
# Path: elevator/constants.py
# OS_ERROR = 5
#
# DATABASE_ERROR = 6
#
# Path: elevator/utils/patterns.py
# def enum(*sequential, **named):
# enums = dict(zip(sequential, range(len(sequential))), **named)
# return type('Enum', (), enums)
#
# Path: elevator/helpers/internals.py
# def failure(err_code, err_msg):
# """Returns a formatted error status and content"""
# return (FAILURE_STATUS, [err_code, err_msg])
#
# def success(content=None):
# """Returns a formatted success status and content"""
# return (SUCCESS_STATUS, content)
. Output only the next line. | return failure(OS_ERROR, e.strerror) |
Given the following code snippet before the placeholder: <|code_start|>
@property
def connector(self):
return self._connector
@connector.setter
def connector(self, value):
if isinstance(value, plyvel.DB) or value is None:
self._connector = value
else:
raise TypeError("Connector whether should be"
"a plyvel object or None")
@connector.deleter
def connector(self):
del self._connector
def set_connector(self, path, *args, **kwargs):
kwargs.update({'create_if_missing': True})
try:
self._connector = plyvel.DB(path, *args, **kwargs)
except CorruptionError as e:
errors_logger.exception(e.message)
def mount(self):
if self.status is self.STATUS.UNMOUNTED:
self.set_connector(self.path)
if self.connector is None:
<|code_end|>
, predict the next line using imports from the current file:
import os
import uuid
import logging
import plyvel
import ujson as json
from shutil import rmtree
from plyvel import CorruptionError
from .constants import OS_ERROR, DATABASE_ERROR
from .utils.patterns import enum
from .helpers.internals import failure, success
and context including class names, function names, and sometimes code from other files:
# Path: elevator/constants.py
# OS_ERROR = 5
#
# DATABASE_ERROR = 6
#
# Path: elevator/utils/patterns.py
# def enum(*sequential, **named):
# enums = dict(zip(sequential, range(len(sequential))), **named)
# return type('Enum', (), enums)
#
# Path: elevator/helpers/internals.py
# def failure(err_code, err_msg):
# """Returns a formatted error status and content"""
# return (FAILURE_STATUS, [err_code, err_msg])
#
# def success(content=None):
# """Returns a formatted success status and content"""
# return (SUCCESS_STATUS, content)
. Output only the next line. | return failure(DATABASE_ERROR, "Database %s could not be mounted" % self.path) |
Continue the code snippet: <|code_start|>
# Copyright (c) 2012 theo crevon
#
# See the file LICENSE for copying permission.
activity_logger = logging.getLogger("activity_logger")
errors_logger = logging.getLogger("errors_logger")
class DatabaseOptions(dict):
def __init__(self, *args, **kwargs):
self['create_if_missing'] = True
self['error_if_exists'] = False
self['bloom_filter_bits'] = 10 # Value recommended by leveldb doc
self['paranoid_checks'] = False
self['lru_cache_size'] = 512 * (1 << 20) # 512 Mo
self['write_buffer_size'] = 4 * (1 << 20) # 4 Mo
self['block_size'] = 4096
self['max_open_files'] = 1000
for key, value in kwargs.iteritems():
if key in self:
self[key] = value
class Database(object):
<|code_end|>
. Use current file imports:
import os
import uuid
import logging
import plyvel
import ujson as json
from shutil import rmtree
from plyvel import CorruptionError
from .constants import OS_ERROR, DATABASE_ERROR
from .utils.patterns import enum
from .helpers.internals import failure, success
and context (classes, functions, or code) from other files:
# Path: elevator/constants.py
# OS_ERROR = 5
#
# DATABASE_ERROR = 6
#
# Path: elevator/utils/patterns.py
# def enum(*sequential, **named):
# enums = dict(zip(sequential, range(len(sequential))), **named)
# return type('Enum', (), enums)
#
# Path: elevator/helpers/internals.py
# def failure(err_code, err_msg):
# """Returns a formatted error status and content"""
# return (FAILURE_STATUS, [err_code, err_msg])
#
# def success(content=None):
# """Returns a formatted success status and content"""
# return (SUCCESS_STATUS, content)
. Output only the next line. | STATUS = enum('MOUNTED', 'UNMOUNTED') |
Predict the next line after this snippet: <|code_start|>
@property
def connector(self):
return self._connector
@connector.setter
def connector(self, value):
if isinstance(value, plyvel.DB) or value is None:
self._connector = value
else:
raise TypeError("Connector whether should be"
"a plyvel object or None")
@connector.deleter
def connector(self):
del self._connector
def set_connector(self, path, *args, **kwargs):
kwargs.update({'create_if_missing': True})
try:
self._connector = plyvel.DB(path, *args, **kwargs)
except CorruptionError as e:
errors_logger.exception(e.message)
def mount(self):
if self.status is self.STATUS.UNMOUNTED:
self.set_connector(self.path)
if self.connector is None:
<|code_end|>
using the current file's imports:
import os
import uuid
import logging
import plyvel
import ujson as json
from shutil import rmtree
from plyvel import CorruptionError
from .constants import OS_ERROR, DATABASE_ERROR
from .utils.patterns import enum
from .helpers.internals import failure, success
and any relevant context from other files:
# Path: elevator/constants.py
# OS_ERROR = 5
#
# DATABASE_ERROR = 6
#
# Path: elevator/utils/patterns.py
# def enum(*sequential, **named):
# enums = dict(zip(sequential, range(len(sequential))), **named)
# return type('Enum', (), enums)
#
# Path: elevator/helpers/internals.py
# def failure(err_code, err_msg):
# """Returns a formatted error status and content"""
# return (FAILURE_STATUS, [err_code, err_msg])
#
# def success(content=None):
# """Returns a formatted success status and content"""
# return (SUCCESS_STATUS, content)
. Output only the next line. | return failure(DATABASE_ERROR, "Database %s could not be mounted" % self.path) |
Using the snippet: <|code_start|> def connector(self, value):
if isinstance(value, plyvel.DB) or value is None:
self._connector = value
else:
raise TypeError("Connector whether should be"
"a plyvel object or None")
@connector.deleter
def connector(self):
del self._connector
def set_connector(self, path, *args, **kwargs):
kwargs.update({'create_if_missing': True})
try:
self._connector = plyvel.DB(path, *args, **kwargs)
except CorruptionError as e:
errors_logger.exception(e.message)
def mount(self):
if self.status is self.STATUS.UNMOUNTED:
self.set_connector(self.path)
if self.connector is None:
return failure(DATABASE_ERROR, "Database %s could not be mounted" % self.path)
self.status = self.STATUS.MOUNTED
else:
return failure(DATABASE_ERROR, "Database %r already mounted" % self.path)
<|code_end|>
, determine the next line of code. You have imports:
import os
import uuid
import logging
import plyvel
import ujson as json
from shutil import rmtree
from plyvel import CorruptionError
from .constants import OS_ERROR, DATABASE_ERROR
from .utils.patterns import enum
from .helpers.internals import failure, success
and context (class names, function names, or code) available:
# Path: elevator/constants.py
# OS_ERROR = 5
#
# DATABASE_ERROR = 6
#
# Path: elevator/utils/patterns.py
# def enum(*sequential, **named):
# enums = dict(zip(sequential, range(len(sequential))), **named)
# return type('Enum', (), enums)
#
# Path: elevator/helpers/internals.py
# def failure(err_code, err_msg):
# """Returns a formatted error status and content"""
# return (FAILURE_STATUS, [err_code, err_msg])
#
# def success(content=None):
# """Returns a formatted success status and content"""
# return (SUCCESS_STATUS, content)
. Output only the next line. | return success() |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
# Copyright (c) 2012 theo crevon
#
# See the file LICENSE for copying permission.
from __future__ import absolute_import
def failure(err_code, err_msg):
"""Returns a formatted error status and content"""
return (FAILURE_STATUS, [err_code, err_msg])
def success(content=None):
"""Returns a formatted success status and content"""
<|code_end|>
, predict the immediate next line with the help of imports:
from ..constants import FAILURE_STATUS, SUCCESS_STATUS, WARNING_STATUS
and context (classes, functions, sometimes code) from other files:
# Path: elevator/constants.py
# FAILURE_STATUS = -1
#
# SUCCESS_STATUS = 1
#
# WARNING_STATUS = -2
. Output only the next line. | return (SUCCESS_STATUS, content) |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
# Copyright (c) 2012 theo crevon
#
# See the file LICENSE for copying permission.
from __future__ import absolute_import
def failure(err_code, err_msg):
"""Returns a formatted error status and content"""
return (FAILURE_STATUS, [err_code, err_msg])
def success(content=None):
"""Returns a formatted success status and content"""
return (SUCCESS_STATUS, content)
def warning(error_code, error_msg, content):
"""Returns a formatted warning status and content"""
<|code_end|>
. Write the next line using the current file imports:
from ..constants import FAILURE_STATUS, SUCCESS_STATUS, WARNING_STATUS
and context from other files:
# Path: elevator/constants.py
# FAILURE_STATUS = -1
#
# SUCCESS_STATUS = 1
#
# WARNING_STATUS = -2
, which may include functions, classes, or code. Output only the next line. | return (WARNING_STATUS, [error_code, error_msg, content]) |
Given snippet: <|code_start|>"""LineSolution is a task describing the functional form for transforming
pixel position to wavelength. The inputs for this task are the given pixel position
and the corresponding wavelength. The user selects an input functional form and
order for that form. The task then calculates the coefficients for that form.
Possible options for the wavelength solution include polynomial, legendre, spline.
HISTORY
20090915 SMC Initially Written by SM Crawford
20101018 SMC Updated to use interfit
LIMITATIONS
"""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from PySpectrograph.Utilities.fit import interfit
and context:
# Path: PySpectrograph/Utilities/fit.py
# class interfit(curfit):
#
# """Given an x and y data arrays, find the best fitting curve.
# After the initial fit, iterate on the solution to reject any
# points which are away from the solution
#
# * x - list or array of x data
# * y - list or array of y data
# * yerr - error on y data
# * coef - Initial coefficients for fit
# * function - function to be fit to the data:
# options include polynomial, legendre, chebyshev, or spline
# * order - order of the function that is fit
# * thresh - threshold for rejection
# * niter - number of times to iterate
#
#
# """
#
# def __init__(self, x, y, yerr=None, coef=None, function='poly', order=3,
# thresh=3, niter=5):
# # set up the variables
# self.x_orig = x
# self.y_orig = y
# self.npts = len(self.x_orig)
# if yerr is None:
# self.yerr_orig = np.ones(self.npts)
# else:
# self.yerr_orig = yerr
#
# self.order = order
# self.thresh = thresh
# self.niter = niter
#
# self.set_func(function)
# self.set_coef(coef)
# self.set_mask(init=True)
# self.set_arrays(self.x_orig, self.y_orig, self.mask, err=self.yerr_orig)
#
# def set_mask(self, init=False):
# """Set the mask according to the values for rejecting points"""
# self.mask = np.ones(self.npts, dtype=bool)
# if init:
# return
#
# # difference the arrays
# diff = self.y_orig - self(self.x_orig)
# sigma = self.sigma(self.x, self.y)
# self.mask = (abs(diff) < self.thresh * sigma)
#
# def set_arrays(self, x, y, mask, err=None):
# """set the arrays using a mask"""
# self.x = x[mask]
# self.y = y[mask]
# if err is not None:
# self.yerr = err[mask]
#
# def interfit(self):
# """Fit a function and then iterate it to reject possible outlyiers"""
# self.fit()
# for i in range(self.niter):
# self.set_mask()
# self.set_arrays(self.x_orig, self.y_orig, self.mask, err=self.yerr_orig)
# self.fit()
which might include code, classes, or functions. Output only the next line. | class LineSolution(interfit): |
Next line prediction: <|code_start|>"""LineFit is a task describing the functional form for transforming
pixel position to wavelength by fitting a model spectrum. The inputs for this task
are an observed spectrum and a calibrated spectrum
and the corresponding wavelength. The user selects an input functional form and
order for that form. The task then calculates the coefficients for that form.
Possible options for the wavelength solution include polynomial, legendre, spline.
HISTORY
20090915 SMC Initially Written by SM Crawford
20101018 SMC Updated to use interfit
LIMITATIONS
"""
<|code_end|>
. Use current file imports:
(from scipy import optimize
from PySpectrograph.Utilities.fit import interfit)
and context including class names, function names, or small code snippets from other files:
# Path: PySpectrograph/Utilities/fit.py
# class interfit(curfit):
#
# """Given an x and y data arrays, find the best fitting curve.
# After the initial fit, iterate on the solution to reject any
# points which are away from the solution
#
# * x - list or array of x data
# * y - list or array of y data
# * yerr - error on y data
# * coef - Initial coefficients for fit
# * function - function to be fit to the data:
# options include polynomial, legendre, chebyshev, or spline
# * order - order of the function that is fit
# * thresh - threshold for rejection
# * niter - number of times to iterate
#
#
# """
#
# def __init__(self, x, y, yerr=None, coef=None, function='poly', order=3,
# thresh=3, niter=5):
# # set up the variables
# self.x_orig = x
# self.y_orig = y
# self.npts = len(self.x_orig)
# if yerr is None:
# self.yerr_orig = np.ones(self.npts)
# else:
# self.yerr_orig = yerr
#
# self.order = order
# self.thresh = thresh
# self.niter = niter
#
# self.set_func(function)
# self.set_coef(coef)
# self.set_mask(init=True)
# self.set_arrays(self.x_orig, self.y_orig, self.mask, err=self.yerr_orig)
#
# def set_mask(self, init=False):
# """Set the mask according to the values for rejecting points"""
# self.mask = np.ones(self.npts, dtype=bool)
# if init:
# return
#
# # difference the arrays
# diff = self.y_orig - self(self.x_orig)
# sigma = self.sigma(self.x, self.y)
# self.mask = (abs(diff) < self.thresh * sigma)
#
# def set_arrays(self, x, y, mask, err=None):
# """set the arrays using a mask"""
# self.x = x[mask]
# self.y = y[mask]
# if err is not None:
# self.yerr = err[mask]
#
# def interfit(self):
# """Fit a function and then iterate it to reject possible outlyiers"""
# self.fit()
# for i in range(self.niter):
# self.set_mask()
# self.set_arrays(self.x_orig, self.y_orig, self.mask, err=self.yerr_orig)
# self.fit()
. Output only the next line. | class LineFit(interfit): |
Next line prediction: <|code_start|> def set_wavelength(self, wavelength, new=False):
"""Set the wavelength scale
If new is True, then it will create a new wavelength
using wrange and dw
"""
if self.wrange is None and wavelength is not None:
self.wrange = [wavelength.min(), wavelength.max()]
if self.stype == 'line' or new:
self.wavelength = np.arange(self.wrange[0], self.wrange[1], self.dw)
elif self.stype == 'continuum':
self.wavelength = wavelength
else:
self.wavelength = wavelength
self.nwave = len(self.wavelength)
def set_flux(self, wavelength, flux):
"""Set the flux levels"""
if flux is not None and len(flux) == self.nwave:
self.flux = flux
elif flux is not None and wavelength is not None:
if self.stype == 'line':
self.flux = np.zeros(self.nwave, dtype=float)
for w, f in zip(wavelength, flux):
<|code_end|>
. Use current file imports:
(import numpy as np
from PySpectrograph.Utilities.Functions import Normal)
and context including class names, function names, or small code snippets from other files:
# Path: PySpectrograph/Utilities/Functions.py
# def Normal(arr, mean, sigma, scale=1):
# """Return the normal distribution of N dimensions
#
# arr--The input array of N dimensions
# mean--the mean of the distribution--either a scalor or N-dimensional array
# sigma--the std deviation of the distribution--either a scalor or N-dimensial array
# scale--the scale of the distrubion
#
# """
# arr = arr
# mean = mean
# sigma = sigma
# scale = scale
# dim = np.ndim(arr) - 1
#
# # check to make sure that mean and sigma have dimensions that match dim
# # and create the arrays to calculate the distribution
# if isinstance(mean, np.ndarray):
# if len(mean) != dim:
# raise FunctionsError('Mean and input array are different number of dimensions')
# mean = np.reshape(mean, (dim, 1, 1))
# if isinstance(sigma, np.ndarray):
# if len(sigma) != dim:
# raise FunctionsError('Sigma and input array are different number of dimensions')
# sigma = np.reshape(sigma, (dim, 1, 1))
#
# # calculate the gaussian
# z = scale * np.exp(-0.5 * (arr - mean) ** 2 / sigma)
# return z
. Output only the next line. | self.flux += Normal(self.wavelength, w, self.sigma * self.dw, f) |
Given the following code snippet before the placeholder: <|code_start|>
def n_index():
return 1.0000
def gratingequation(sigma, order, sign, alpha, beta, gamma=0, nd=n_index):
"""Apply the grating equation to determine the wavelength
w = sigma/m cos (gamma) * n_ind *(sin alpha +- sin beta)
returns wavelength in mm
"""
<|code_end|>
, predict the next line using imports from the current file:
from PySpectrograph.Utilities.degreemath import cosd, sind
and context including class names, function names, and sometimes code from other files:
# Path: PySpectrograph/Utilities/degreemath.py
# def cosd(x):
# """Return the cos of x where x is in degrees"""
# if isinstance(x, numpy.ndarray):
# return numpy.cos(math.pi * x / 180.0)
# return math.cos(math.radians(x))
#
# def sind(x):
# """Return the sin of x where x is in degrees"""
# if isinstance(x, numpy.ndarray):
# return numpy.sin(math.pi * x / 180.0)
# return math.sin(math.radians(x))
. Output only the next line. | angle = cosd(gamma) * nd() * (sind(alpha) + sign * sind(beta)) |
Given snippet: <|code_start|>
def n_index():
return 1.0000
def gratingequation(sigma, order, sign, alpha, beta, gamma=0, nd=n_index):
"""Apply the grating equation to determine the wavelength
w = sigma/m cos (gamma) * n_ind *(sin alpha +- sin beta)
returns wavelength in mm
"""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from PySpectrograph.Utilities.degreemath import cosd, sind
and context:
# Path: PySpectrograph/Utilities/degreemath.py
# def cosd(x):
# """Return the cos of x where x is in degrees"""
# if isinstance(x, numpy.ndarray):
# return numpy.cos(math.pi * x / 180.0)
# return math.cos(math.radians(x))
#
# def sind(x):
# """Return the sin of x where x is in degrees"""
# if isinstance(x, numpy.ndarray):
# return numpy.sin(math.pi * x / 180.0)
# return math.sin(math.radians(x))
which might include code, classes, or functions. Output only the next line. | angle = cosd(gamma) * nd() * (sind(alpha) + sign * sind(beta)) |
Given the code snippet: <|code_start|> yval--offset on the ccd in the y-direction
var--array with the variance values
"""
def __init__(self, x, y, sgraph, xlen=3162, yval=0, order=3):
# set up the variables
self.x = x
self.y = y
self.sgraph = sgraph
self.yval = yval
self.xlen = xlen
self.order = order
self.function = 'model'
# set the parameters
self.reset_coef()
def reset_coef(self):
xpos = self.sgraph.detector.xpos
ypos = self.yval + self.sgraph.detector.ypos
fcam = self.sgraph.camera.focallength
self.set_spcoef(fcam, xpos, ypos)
self.spcoef = [self.fcam, self.xpos, self.ypos]
self.set_ndcoef()
# the total coefficient
self.set_coef()
def set_spcoef(self, fcam, xpos, ypos):
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
from PySpectrograph.Utilities import fit as ft
and context (functions, classes, or occasionally code) from other files:
# Path: PySpectrograph/Utilities/fit.py
# def fit(function, parameters, y, x=None, var=1, warn=False):
# def f(params):
# i = 0
# for p in parameters:
# p.set(params[i])
# i += 1
# return (y - function(x)) / var
#
# if x is None:
# x = np.arange(y.shape[0])
# p = [param() for param in parameters]
# return optimize.leastsq(f, p, full_output=1, warning=warn)
. Output only the next line. | self.fcam = ft.Parameter(fcam) |
Next line prediction: <|code_start|>
xp = np.array([1134.87, 1239.11, 1498.22, 1687.21, 1904.49, 1997.15, 2025.77, 2202.59, 2559.72, 2673.74, 3124.34])
wp = np.array([4500.9772,
4524.6805,
4582.7474,
4624.2757,
4671.226,
4690.9711,
4697.02,
4734.1524,
4807.019,
4829.709,
4916.51])
def test_LineSolution():
<|code_end|>
. Use current file imports:
(import numpy as np
import pylab as pl
from PySpectrograph.WavelengthSolution import LineSolution as LS)
and context including class names, function names, or small code snippets from other files:
# Path: PySpectrograph/WavelengthSolution/LineSolution.py
# class LineSolution(interfit):
#
# """LineSolution is a task describing the functional form for transforming
# pixel position to wavelength.
#
# * x - list or array of x data
# * y - list or array of y data
# * yerr - error on y data
# * coef - Initial coefficients for fit
# * function - function to be fit to the data:
# options include polynomial, legendre, chebyshev, or spline
# * order - order of the function that is fit
# * thresh - threshold for rejection
# * niter - number of times to iterate
#
# """
#
# def value(self, x):
# """Calculate the value of the array
# """
# return self(x)
. Output only the next line. | ls = LS.LineSolution(xp, wp, function='legendre') |
Based on the snippet: <|code_start|> bulk = []
for r in rooms:
r = int(r)
room_history = 'room:{0}:history'.format(r)
rchannel = 'room:{0}'.format(r)
bulk.append((b'SREM', 'room:{0}:users'.format(r), str(uid)))
bulk.append((b"RPUSH", room_history, json.dumps(
{"kind": "left", "author": username, "uid": uid})))
bulk.append((b"LTRIM", room_history, b'-100', b'-1'))
self._output.publish(rchannel, ['chat.left', r, {
'ident': uid,
}])
if rooms:
bulk.append((b'RENAME',
'user:{0}:rooms'.format(uid),
'user:{0}:bookmarks'.format(uid)))
self._redis.bulk(bulk)
def _sync_(self, pairs):
iterpairs = iter(pairs)
zadd = [b'ZADD', b'connections']
tm = int(time.time())
for cid, cookie in zip(iterpairs, iterpairs):
zadd.append(str(tm))
zadd.append(cid)
_, exp, _ = self._redis.bulk((zadd,
(b'ZRANGEBYSCORE', 'connections', b'-inf', str(tm - 20)),
(b'ZREMRANGEBYSCORE', 'connections', b'-inf', str(tm - 20)),
))
for conn in exp:
<|code_end|>
, predict the immediate next line with the help of imports:
import json
import time
import logging
from .service import BaseService, User
and context (classes, functions, sometimes code) from other files:
# Path: examples/tabbedchat/tabbedchat/service.py
# class BaseService(object):
# _method_prefix = None
#
# def configure(self, loop):
# """Usually used for getting dependencies"""
#
# def _checkname(self, val):
# if not isinstance(val, str):
# return False
# if not val.startswith(self._method_prefix):
# return False
# val = val[len(self._method_prefix):]
# if val.startswith('_'):
# return False
# return True
#
# def __call__(self, msg):
# if len(msg) < 2:
# log.warning("Wrong message %r", msg)
# return
# if msg[1] == b'heartbeat':
# return
# elif msg[1] == b'connect':
# return
# elif msg[1] == b'message':
# try:
# data = json.loads(msg[2].decode('utf-8'))
# except ValueError:
# log.warning("Can't unpack json")
# return
# if not data or not self._checkname(data[0]):
# log.warning("Wrong json")
# return
# try:
# usr = User(cid=msg[0])
# meth = getattr(self, data[0][len(self._method_prefix):])
# meth(usr, *data[1:])
# except Exception:
# log.exception("Error handling %r", data[0])
# elif msg[1] == b'msgfrom':
# try:
# data = json.loads(msg[3].decode('utf-8'))
# except ValueError:
# log.warning("Can't unpack json")
# return
# if not data or not self._checkname(data[0]):
# log.warning("Wrong json")
# return
# try:
# usr = User(cid=msg[0], uid=int(msg[2].split(b':')[1]))
# getattr(self, data[0][len('auth.'):])(usr, *data[1:])
# except Exception:
# log.exception("Error handling %r", data[0])
# elif msg[1] == b'disconnect':
# self._disconnect_(User(cid=msg[0]))
# elif msg[1] == b'sync':
# self._sync_(msg[2:])
# else:
# log.warning("Wrong message %r", msg)
# return
#
# class User(object):
#
# def __init__(self, cid=None, uid=None):
# self.cid = cid
# self.uid = uid
. Output only the next line. | self._disconnect_(User(cid=conn)) |
Next line prediction: <|code_start|>
CONFIG='test/wlimit.yaml'
CHAT_FW = "ipc:///tmp/zerogw-test-chatfw"
class Wlimit(Base):
timeout = 2 # in zmq.select units (seconds)
config = CONFIG
def setUp(self):
self.zmq = zmq.Context(1)
self.addCleanup(self.zmq.term)
super().setUp()
self.chatfw = self.zmq.socket(zmq.PULL)
self.addCleanup(self.chatfw.close)
self.chatfw.connect(CHAT_FW)
def backend_recv(self, backend=None):
if backend is None:
sock = self.chatfw
else:
sock = self.minigame
if (([sock], [], []) !=
zmq.select([sock], [], [], timeout=self.timeout)):
<|code_end|>
. Use current file imports:
(import zmq
import unittest
from http import client as http
from .simple import Base, TimeoutError)
and context including class names, function names, or small code snippets from other files:
# Path: test/simple.py
# class Base(unittest.TestCase):
# config = CONFIG
#
# def setUp(self):
# self.do_init()
# time.sleep(START_TIMEOUT)
#
# def do_init(self):
# self.proc = subprocess.Popen([ZEROGW_BINARY, '-c', self.config])
# self.addCleanup(stop_process, self.proc)
#
# def http(self, host='localhost'):
# conn = http.HTTPConnection(host, timeout=1.0)
# conn.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
# for i in range(100):
# try:
# conn.sock.connect(HTTP_ADDR)
# except socket.error:
# time.sleep(0.1)
# continue
# else:
# break
# else:
# raise RuntimeError("Can't connect to zerogw")
# return conn
#
# def websock(self, **kw):
# return CheckingWebsock(self, **kw)
#
# class TimeoutError(Exception):
# pass
. Output only the next line. | raise TimeoutError() |
Based on the snippet: <|code_start|>
class Stripe(Service):
name = 'Stripe'
status_url = 'https://status.stripe.com/'
icon_url = '/images/icons/stripe.png'
def get_status(self):
r = requests.get(self.status_url)
b = BeautifulSoup(r.content, 'html.parser')
div = b.select_one('.status-bubble')
status_classes = div.attrs['class']
if 'status-up' in status_classes:
<|code_end|>
, predict the immediate next line with the help of imports:
import requests
from bs4 import BeautifulSoup
from isserviceup.services.models.service import Service, Status
and context (classes, functions, sometimes code) from other files:
# Path: isserviceup/services/models/service.py
# class Service(object):
#
# @property
# def id(self):
# return self.__class__.__name__
#
# @property
# def status_url(self):
# raise NotImplemented()
#
# @property
# def icon_url(self):
# raise NotImplemented()
#
# @property
# def name(self):
# raise NotImplemented()
#
# def get_status(self):
# raise NotImplemented()
#
# class Status(Enum):
# ok = 1 # green
# maintenance = 2 # blue
# minor = 3 # yellow
# major = 4 # orange
# critical = 5 # red
# unavailable = 6 # gray
. Output only the next line. | return Status.ok |
Predict the next line after this snippet: <|code_start|>DEBUG = config('DEBUG', cast=bool, default=False)
FRONTEND_URL = config('FRONTEND_URL', default='http://localhost:8000/')
REDIS_URL = config('REDIS_URL', default='redis://redis:devpassword@redis')
MONGO_URL = config('MONGO_URL', default='mongodb://mongo/isserviceup')
STATUS_UPDATE_INTERVAL = config('STATUS_UPDATE_INTERVAL', cast=int, default=30)
SERVE_STATIC_FILES = config('SERVE_STATIC_FILES', cast=bool, default=True)
SENTRY_DSN = config('SENTRY_DSN', default=None)
CELERY_EAGER = config('CELERY_EAGER', cast=bool, default=False)
CELERY_BROKER = config('CELERY_BROKER', default=REDIS_URL)
CELERY_BACKEND = config('CELERY_BACKEND', default=REDIS_URL)
GITHUB_CLIENT_ID = config('GITHUB_CLIENT_ID', default=None)
GITHUB_CLIENT_SECRET = config('GITHUB_CLIENT_SECRET', default=None)
SLACK_WEB_HOOK_URL = config('SLACK_WEB_HOOK_URL', default=None)
NOTIFIERS = [
# Slack(SLACK_WEB_HOOK_URL)
]
# If True, on the first status update of the run, it will notify the status
# even if they didn't change.
NOTIFY_ON_STARTUP = config('NOTIFY_ON_STARTUP', default=False, cast=bool)
# To use, set CACHET_NOTIFIER=True, and set the values for
# CACHET_URL, CACHET_TOKEN, CACHET_COMPONENTS.
CACHET_NOTIFIER = config('CACHET_NOTIFIER', default=False, cast=bool)
if CACHET_NOTIFIER:
<|code_end|>
using the current file's imports:
import os
import stat
import shutil
from decouple import config
from isserviceup.notifiers.cachet import Cachet
from isserviceup.services.models.service import Status
and any relevant context from other files:
# Path: isserviceup/notifiers/cachet.py
# class Cachet(Notifier):
# """Notifies to the Cachet status page components, about the state of their
# corresponding services.
#
# :param cachet_url: The URL for the Cachet status page.
# If empty, will get it from config('CACHET_URL').
# :type cachet: str
# :param cachet_token: The Cachet API Token.
# If empty, will get it from config('CACHET_TOKEN').
# :type cachet_token: str
# :param cachet_components: Which components in Cachet are going to be
# notified. Is a dictionary with each key being the service class, and
# its value, the Cachet component id. If empty, will get it from
# config('CACHET_COMPONENTS'), and it has to be a comma separated string
# with each service class, a colon, and the component id. (For example,
# CACHET_COMPONENTS=Docker:1,Github:4)
# :type cachet_components: dict
# """
#
# def __init__(self, cachet_url="", cachet_token="",
# cachet_components=None):
# self.cachet_url = cachet_url or config('CACHET_URL', default=None)
# self.cachet_token = (cachet_token or
# config('CACHET_TOKEN', default=None))
# self.cachet_components = (cachet_components or
# config('CACHET_COMPONENTS', default=None,
# cast=self._components_to_dict))
#
# def _components_to_dict(self, components=None):
# try:
# return dict([[side.strip() for side in component.split(":")]
# for component in components.split(",")])
# except ValueError as error:
# print("Value error: {msg}".format(msg=error.message))
# return {}
#
# def _get_component_name(self, service):
# return type(service).__name__
#
# def _get_component_url(self, service):
# component = self._get_component_name(service)
# if component in self.cachet_components:
# url = "{base_url}/api/v1/components/{component}".format(
# base_url=self.cachet_url.strip("/"),
# component=self.cachet_components[component]
# )
# return url
# return False
#
# def _get_headers(self):
# return {
# 'Content-Type': 'application/json',
# 'X-Cachet-Token': self.cachet_token,
# }
#
# def _build_payload(self, service, old_status, new_status):
# payload = {
# 'name': service.name,
# 'status': CachetStatus.get_cachet_status(new_status),
# 'old_status': CachetStatus.get_cachet_status(old_status),
# }
# return payload
#
# def _is_valid(self, service):
# return (
# self.cachet_url and self.cachet_token and self.cachet_components
# and self._get_component_name(service) in self.cachet_components
# )
#
# def notify(self, service, old_status, new_status):
# if self._is_valid(service):
# url = self._get_component_url(service)
# headers = self._get_headers()
# payload = self._build_payload(service, old_status, new_status)
# print("Notifying {} with {}".format(url, payload))
# requests.put(url, json=payload, headers=headers)
. Output only the next line. | NOTIFIERS.append(Cachet()) |
Given snippet: <|code_start|>
class GCloud(Service):
name = 'Google Cloud'
status_url = 'https://status.cloud.google.com/'
icon_url = '/images/icons/gcloud.png'
def get_status(self):
r = requests.get(self.status_url)
b = BeautifulSoup(r.content, 'html.parser')
status = next(x for x in b.find(class_='subheader').attrs['class']
if x.startswith('open-incident-bar-'))
if status == 'open-incident-bar-clear':
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import requests
from bs4 import BeautifulSoup
from isserviceup.services.models.service import Service, Status
and context:
# Path: isserviceup/services/models/service.py
# class Service(object):
#
# @property
# def id(self):
# return self.__class__.__name__
#
# @property
# def status_url(self):
# raise NotImplemented()
#
# @property
# def icon_url(self):
# raise NotImplemented()
#
# @property
# def name(self):
# raise NotImplemented()
#
# def get_status(self):
# raise NotImplemented()
#
# class Status(Enum):
# ok = 1 # green
# maintenance = 2 # blue
# minor = 3 # yellow
# major = 4 # orange
# critical = 5 # red
# unavailable = 6 # gray
which might include code, classes, or functions. Output only the next line. | return Status.ok |
Predict the next line after this snippet: <|code_start|>
mod = Blueprint('auth', __name__)
@mod.route('/oauth_callback', methods=['GET'])
def oauth_callback():
code = request.args['code']
res = github.get_access_token(code)
access_token = res.json()['access_token']
res = github.get_user_info(access_token)
data = res.json()
user = upsert_user(github_access_token=access_token,
avatar_url=data['avatar_url'],
username=data['login'])
print('user={}'.format(user))
sid = sessions.create({
'user_id': str(user.id),
})
<|code_end|>
using the current file's imports:
from flask import Blueprint
from flask import redirect
from flask import request
from isserviceup.config import config
from isserviceup.helpers import github
from isserviceup.storage import sessions
from isserviceup.storage.users import upsert_user
and any relevant context from other files:
# Path: isserviceup/config/config.py
# def s2l(x):
# def ensure_private_ssh_key():
# def get_status_description():
# DEBUG = config('DEBUG', cast=bool, default=False)
# FRONTEND_URL = config('FRONTEND_URL', default='http://localhost:8000/')
# REDIS_URL = config('REDIS_URL', default='redis://redis:devpassword@redis')
# MONGO_URL = config('MONGO_URL', default='mongodb://mongo/isserviceup')
# STATUS_UPDATE_INTERVAL = config('STATUS_UPDATE_INTERVAL', cast=int, default=30)
# SERVE_STATIC_FILES = config('SERVE_STATIC_FILES', cast=bool, default=True)
# SENTRY_DSN = config('SENTRY_DSN', default=None)
# CELERY_EAGER = config('CELERY_EAGER', cast=bool, default=False)
# CELERY_BROKER = config('CELERY_BROKER', default=REDIS_URL)
# CELERY_BACKEND = config('CELERY_BACKEND', default=REDIS_URL)
# GITHUB_CLIENT_ID = config('GITHUB_CLIENT_ID', default=None)
# GITHUB_CLIENT_SECRET = config('GITHUB_CLIENT_SECRET', default=None)
# SLACK_WEB_HOOK_URL = config('SLACK_WEB_HOOK_URL', default=None)
# NOTIFIERS = [
# # Slack(SLACK_WEB_HOOK_URL)
# ]
# NOTIFY_ON_STARTUP = config('NOTIFY_ON_STARTUP', default=False, cast=bool)
# CACHET_NOTIFIER = config('CACHET_NOTIFIER', default=False, cast=bool)
# SERVICES = config('SERVICES', cast=s2l, default=None)
# PRIVATE_SSH_KEY = config('PRIVATE_SSH_KEY', default='')
# PRIVATE_SSH_KEY = ''
#
# Path: isserviceup/helpers/github.py
# def get_access_token(code):
# def get_user_info(access_token):
#
# Path: isserviceup/storage/sessions.py
# SESSION_TTL = 60*60*24*30
# def get(sid):
# def create(data):
# def destroy(sid):
#
# Path: isserviceup/storage/users.py
# def upsert_user(avatar_url, username, github_access_token):
# return User.objects(username=username).upsert_one(set__avatar_url=avatar_url,
# set__github_access_token=github_access_token)
. Output only the next line. | return redirect(config.FRONTEND_URL + '#/?code=' + sid) |
Given snippet: <|code_start|>
mod = Blueprint('auth', __name__)
@mod.route('/oauth_callback', methods=['GET'])
def oauth_callback():
code = request.args['code']
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from flask import Blueprint
from flask import redirect
from flask import request
from isserviceup.config import config
from isserviceup.helpers import github
from isserviceup.storage import sessions
from isserviceup.storage.users import upsert_user
and context:
# Path: isserviceup/config/config.py
# def s2l(x):
# def ensure_private_ssh_key():
# def get_status_description():
# DEBUG = config('DEBUG', cast=bool, default=False)
# FRONTEND_URL = config('FRONTEND_URL', default='http://localhost:8000/')
# REDIS_URL = config('REDIS_URL', default='redis://redis:devpassword@redis')
# MONGO_URL = config('MONGO_URL', default='mongodb://mongo/isserviceup')
# STATUS_UPDATE_INTERVAL = config('STATUS_UPDATE_INTERVAL', cast=int, default=30)
# SERVE_STATIC_FILES = config('SERVE_STATIC_FILES', cast=bool, default=True)
# SENTRY_DSN = config('SENTRY_DSN', default=None)
# CELERY_EAGER = config('CELERY_EAGER', cast=bool, default=False)
# CELERY_BROKER = config('CELERY_BROKER', default=REDIS_URL)
# CELERY_BACKEND = config('CELERY_BACKEND', default=REDIS_URL)
# GITHUB_CLIENT_ID = config('GITHUB_CLIENT_ID', default=None)
# GITHUB_CLIENT_SECRET = config('GITHUB_CLIENT_SECRET', default=None)
# SLACK_WEB_HOOK_URL = config('SLACK_WEB_HOOK_URL', default=None)
# NOTIFIERS = [
# # Slack(SLACK_WEB_HOOK_URL)
# ]
# NOTIFY_ON_STARTUP = config('NOTIFY_ON_STARTUP', default=False, cast=bool)
# CACHET_NOTIFIER = config('CACHET_NOTIFIER', default=False, cast=bool)
# SERVICES = config('SERVICES', cast=s2l, default=None)
# PRIVATE_SSH_KEY = config('PRIVATE_SSH_KEY', default='')
# PRIVATE_SSH_KEY = ''
#
# Path: isserviceup/helpers/github.py
# def get_access_token(code):
# def get_user_info(access_token):
#
# Path: isserviceup/storage/sessions.py
# SESSION_TTL = 60*60*24*30
# def get(sid):
# def create(data):
# def destroy(sid):
#
# Path: isserviceup/storage/users.py
# def upsert_user(avatar_url, username, github_access_token):
# return User.objects(username=username).upsert_one(set__avatar_url=avatar_url,
# set__github_access_token=github_access_token)
which might include code, classes, or functions. Output only the next line. | res = github.get_access_token(code) |
Continue the code snippet: <|code_start|>
mod = Blueprint('auth', __name__)
@mod.route('/oauth_callback', methods=['GET'])
def oauth_callback():
code = request.args['code']
res = github.get_access_token(code)
access_token = res.json()['access_token']
res = github.get_user_info(access_token)
data = res.json()
user = upsert_user(github_access_token=access_token,
avatar_url=data['avatar_url'],
username=data['login'])
print('user={}'.format(user))
<|code_end|>
. Use current file imports:
from flask import Blueprint
from flask import redirect
from flask import request
from isserviceup.config import config
from isserviceup.helpers import github
from isserviceup.storage import sessions
from isserviceup.storage.users import upsert_user
and context (classes, functions, or code) from other files:
# Path: isserviceup/config/config.py
# def s2l(x):
# def ensure_private_ssh_key():
# def get_status_description():
# DEBUG = config('DEBUG', cast=bool, default=False)
# FRONTEND_URL = config('FRONTEND_URL', default='http://localhost:8000/')
# REDIS_URL = config('REDIS_URL', default='redis://redis:devpassword@redis')
# MONGO_URL = config('MONGO_URL', default='mongodb://mongo/isserviceup')
# STATUS_UPDATE_INTERVAL = config('STATUS_UPDATE_INTERVAL', cast=int, default=30)
# SERVE_STATIC_FILES = config('SERVE_STATIC_FILES', cast=bool, default=True)
# SENTRY_DSN = config('SENTRY_DSN', default=None)
# CELERY_EAGER = config('CELERY_EAGER', cast=bool, default=False)
# CELERY_BROKER = config('CELERY_BROKER', default=REDIS_URL)
# CELERY_BACKEND = config('CELERY_BACKEND', default=REDIS_URL)
# GITHUB_CLIENT_ID = config('GITHUB_CLIENT_ID', default=None)
# GITHUB_CLIENT_SECRET = config('GITHUB_CLIENT_SECRET', default=None)
# SLACK_WEB_HOOK_URL = config('SLACK_WEB_HOOK_URL', default=None)
# NOTIFIERS = [
# # Slack(SLACK_WEB_HOOK_URL)
# ]
# NOTIFY_ON_STARTUP = config('NOTIFY_ON_STARTUP', default=False, cast=bool)
# CACHET_NOTIFIER = config('CACHET_NOTIFIER', default=False, cast=bool)
# SERVICES = config('SERVICES', cast=s2l, default=None)
# PRIVATE_SSH_KEY = config('PRIVATE_SSH_KEY', default='')
# PRIVATE_SSH_KEY = ''
#
# Path: isserviceup/helpers/github.py
# def get_access_token(code):
# def get_user_info(access_token):
#
# Path: isserviceup/storage/sessions.py
# SESSION_TTL = 60*60*24*30
# def get(sid):
# def create(data):
# def destroy(sid):
#
# Path: isserviceup/storage/users.py
# def upsert_user(avatar_url, username, github_access_token):
# return User.objects(username=username).upsert_one(set__avatar_url=avatar_url,
# set__github_access_token=github_access_token)
. Output only the next line. | sid = sessions.create({ |
Continue the code snippet: <|code_start|>
mod = Blueprint('auth', __name__)
@mod.route('/oauth_callback', methods=['GET'])
def oauth_callback():
code = request.args['code']
res = github.get_access_token(code)
access_token = res.json()['access_token']
res = github.get_user_info(access_token)
data = res.json()
<|code_end|>
. Use current file imports:
from flask import Blueprint
from flask import redirect
from flask import request
from isserviceup.config import config
from isserviceup.helpers import github
from isserviceup.storage import sessions
from isserviceup.storage.users import upsert_user
and context (classes, functions, or code) from other files:
# Path: isserviceup/config/config.py
# def s2l(x):
# def ensure_private_ssh_key():
# def get_status_description():
# DEBUG = config('DEBUG', cast=bool, default=False)
# FRONTEND_URL = config('FRONTEND_URL', default='http://localhost:8000/')
# REDIS_URL = config('REDIS_URL', default='redis://redis:devpassword@redis')
# MONGO_URL = config('MONGO_URL', default='mongodb://mongo/isserviceup')
# STATUS_UPDATE_INTERVAL = config('STATUS_UPDATE_INTERVAL', cast=int, default=30)
# SERVE_STATIC_FILES = config('SERVE_STATIC_FILES', cast=bool, default=True)
# SENTRY_DSN = config('SENTRY_DSN', default=None)
# CELERY_EAGER = config('CELERY_EAGER', cast=bool, default=False)
# CELERY_BROKER = config('CELERY_BROKER', default=REDIS_URL)
# CELERY_BACKEND = config('CELERY_BACKEND', default=REDIS_URL)
# GITHUB_CLIENT_ID = config('GITHUB_CLIENT_ID', default=None)
# GITHUB_CLIENT_SECRET = config('GITHUB_CLIENT_SECRET', default=None)
# SLACK_WEB_HOOK_URL = config('SLACK_WEB_HOOK_URL', default=None)
# NOTIFIERS = [
# # Slack(SLACK_WEB_HOOK_URL)
# ]
# NOTIFY_ON_STARTUP = config('NOTIFY_ON_STARTUP', default=False, cast=bool)
# CACHET_NOTIFIER = config('CACHET_NOTIFIER', default=False, cast=bool)
# SERVICES = config('SERVICES', cast=s2l, default=None)
# PRIVATE_SSH_KEY = config('PRIVATE_SSH_KEY', default='')
# PRIVATE_SSH_KEY = ''
#
# Path: isserviceup/helpers/github.py
# def get_access_token(code):
# def get_user_info(access_token):
#
# Path: isserviceup/storage/sessions.py
# SESSION_TTL = 60*60*24*30
# def get(sid):
# def create(data):
# def destroy(sid):
#
# Path: isserviceup/storage/users.py
# def upsert_user(avatar_url, username, github_access_token):
# return User.objects(username=username).upsert_one(set__avatar_url=avatar_url,
# set__github_access_token=github_access_token)
. Output only the next line. | user = upsert_user(github_access_token=access_token, |
Predict the next line for this snippet: <|code_start|>
def authenticated(blocking=True):
def decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
user = None
auth = request.headers.get('Authorization')
if auth and len(auth) >= 7:
sid = auth[7:] # 'Bearer ' prefix
session = sessions.get(sid)
if session and session.get('user_id'):
user = get_user(session['user_id'])
if user:
user.sid = sid
if blocking and not user:
<|code_end|>
with the help of current file imports:
from flask import request
from six import wraps
from isserviceup.helpers.exceptions import ApiException
from isserviceup.storage import sessions
from isserviceup.storage.users import get_user
and context from other files:
# Path: isserviceup/helpers/exceptions.py
# class ApiException(Exception):
# def __init__(self, message, status_code=400, **kwargs):
# super(ApiException, self).__init__()
# self.message = message
# self.status_code = status_code
# self.extra = kwargs
#
# Path: isserviceup/storage/sessions.py
# SESSION_TTL = 60*60*24*30
# def get(sid):
# def create(data):
# def destroy(sid):
#
# Path: isserviceup/storage/users.py
# def get_user(user_id):
# return User.objects.with_id(user_id)
, which may contain function names, class names, or code. Output only the next line. | raise ApiException('unauthorized', status_code=401) |
Based on the snippet: <|code_start|>
def authenticated(blocking=True):
def decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
user = None
auth = request.headers.get('Authorization')
if auth and len(auth) >= 7:
sid = auth[7:] # 'Bearer ' prefix
<|code_end|>
, predict the immediate next line with the help of imports:
from flask import request
from six import wraps
from isserviceup.helpers.exceptions import ApiException
from isserviceup.storage import sessions
from isserviceup.storage.users import get_user
and context (classes, functions, sometimes code) from other files:
# Path: isserviceup/helpers/exceptions.py
# class ApiException(Exception):
# def __init__(self, message, status_code=400, **kwargs):
# super(ApiException, self).__init__()
# self.message = message
# self.status_code = status_code
# self.extra = kwargs
#
# Path: isserviceup/storage/sessions.py
# SESSION_TTL = 60*60*24*30
# def get(sid):
# def create(data):
# def destroy(sid):
#
# Path: isserviceup/storage/users.py
# def get_user(user_id):
# return User.objects.with_id(user_id)
. Output only the next line. | session = sessions.get(sid) |
Here is a snippet: <|code_start|>
def authenticated(blocking=True):
def decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
user = None
auth = request.headers.get('Authorization')
if auth and len(auth) >= 7:
sid = auth[7:] # 'Bearer ' prefix
session = sessions.get(sid)
if session and session.get('user_id'):
<|code_end|>
. Write the next line using the current file imports:
from flask import request
from six import wraps
from isserviceup.helpers.exceptions import ApiException
from isserviceup.storage import sessions
from isserviceup.storage.users import get_user
and context from other files:
# Path: isserviceup/helpers/exceptions.py
# class ApiException(Exception):
# def __init__(self, message, status_code=400, **kwargs):
# super(ApiException, self).__init__()
# self.message = message
# self.status_code = status_code
# self.extra = kwargs
#
# Path: isserviceup/storage/sessions.py
# SESSION_TTL = 60*60*24*30
# def get(sid):
# def create(data):
# def destroy(sid):
#
# Path: isserviceup/storage/users.py
# def get_user(user_id):
# return User.objects.with_id(user_id)
, which may include functions, classes, or code. Output only the next line. | user = get_user(session['user_id']) |
Next line prediction: <|code_start|>
class Azure(Service):
name = 'Microsoft Azure'
status_url = 'https://azure.microsoft.com/en-us/status/'
icon_url = '/images/icons/azure.png'
def get_status(self):
r = requests.get(self.status_url)
b = BeautifulSoup(r.content, 'html.parser')
div = str(b.select_one('.section.section-size3.section-slate09'))
if 'health-circle' in div or 'health-check' in div or 'health-information' in div:
<|code_end|>
. Use current file imports:
(import requests
from bs4 import BeautifulSoup
from isserviceup.services.models.service import Service, Status)
and context including class names, function names, or small code snippets from other files:
# Path: isserviceup/services/models/service.py
# class Service(object):
#
# @property
# def id(self):
# return self.__class__.__name__
#
# @property
# def status_url(self):
# raise NotImplemented()
#
# @property
# def icon_url(self):
# raise NotImplemented()
#
# @property
# def name(self):
# raise NotImplemented()
#
# def get_status(self):
# raise NotImplemented()
#
# class Status(Enum):
# ok = 1 # green
# maintenance = 2 # blue
# minor = 3 # yellow
# major = 4 # orange
# critical = 5 # red
# unavailable = 6 # gray
. Output only the next line. | return Status.ok |
Predict the next line for this snippet: <|code_start|>
class Heroku(Service):
name = 'Heroku'
status_url = 'https://status.heroku.com/'
icon_url = '/images/icons/heroku.png'
def get_status(self):
r = requests.get('https://status.heroku.com/api/v3/current-status')
res = r.json()
status = res['status']['Production']
if status == 'green':
<|code_end|>
with the help of current file imports:
import requests
from isserviceup.services.models.service import Service, Status
and context from other files:
# Path: isserviceup/services/models/service.py
# class Service(object):
#
# @property
# def id(self):
# return self.__class__.__name__
#
# @property
# def status_url(self):
# raise NotImplemented()
#
# @property
# def icon_url(self):
# raise NotImplemented()
#
# @property
# def name(self):
# raise NotImplemented()
#
# def get_status(self):
# raise NotImplemented()
#
# class Status(Enum):
# ok = 1 # green
# maintenance = 2 # blue
# minor = 3 # yellow
# major = 4 # orange
# critical = 5 # red
# unavailable = 6 # gray
, which may contain function names, class names, or code. Output only the next line. | return Status.ok |
Predict the next line after this snippet: <|code_start|> icon_url = '/images/icons/gitlab.png'
def __init__(self):
# Will check if the GitLab website is OK.
self.check_http = config('GITLAB_CHECK_HTTP', default=True, cast=bool)
# Will check if the GitLab JSON API is OK.
self.check_json = config('GITLAB_CHECK_JSON', default=True, cast=bool)
# Will check if the SSH connections to git@{gitlab_url} are OK.
# To use this you need to set the PRIVATE_SSH_KEY option in the config.
self.check_ssh = config('GITLAB_CHECK_SSH', default=False, cast=bool)
# If you need to monitor multiple GitLab instances and need each one to
# have a different behaviour: extend this class, override the __init__
# function, call super, and then override these properties.
def _check_http(self):
request = requests.get(self.status_url)
return request.ok
def _check_json(self):
request = requests.get('{base}/api/v4/projects'.format(
base=self.status_url.strip('/')
))
try:
if request.json():
return True
except ValueError as error:
print('Value error: {msg}'.format(msg=error.message))
return False
def _check_private_ssh_key(self):
<|code_end|>
using the current file's imports:
import requests
import subprocess
from decouple import config
from isserviceup.config import config as isu_config
from isserviceup.services.models.service import Service, Status
from urlparse import urlparse
from urllib.parse import urlparse
and any relevant context from other files:
# Path: isserviceup/config/config.py
# def s2l(x):
# def ensure_private_ssh_key():
# def get_status_description():
# DEBUG = config('DEBUG', cast=bool, default=False)
# FRONTEND_URL = config('FRONTEND_URL', default='http://localhost:8000/')
# REDIS_URL = config('REDIS_URL', default='redis://redis:devpassword@redis')
# MONGO_URL = config('MONGO_URL', default='mongodb://mongo/isserviceup')
# STATUS_UPDATE_INTERVAL = config('STATUS_UPDATE_INTERVAL', cast=int, default=30)
# SERVE_STATIC_FILES = config('SERVE_STATIC_FILES', cast=bool, default=True)
# SENTRY_DSN = config('SENTRY_DSN', default=None)
# CELERY_EAGER = config('CELERY_EAGER', cast=bool, default=False)
# CELERY_BROKER = config('CELERY_BROKER', default=REDIS_URL)
# CELERY_BACKEND = config('CELERY_BACKEND', default=REDIS_URL)
# GITHUB_CLIENT_ID = config('GITHUB_CLIENT_ID', default=None)
# GITHUB_CLIENT_SECRET = config('GITHUB_CLIENT_SECRET', default=None)
# SLACK_WEB_HOOK_URL = config('SLACK_WEB_HOOK_URL', default=None)
# NOTIFIERS = [
# # Slack(SLACK_WEB_HOOK_URL)
# ]
# NOTIFY_ON_STARTUP = config('NOTIFY_ON_STARTUP', default=False, cast=bool)
# CACHET_NOTIFIER = config('CACHET_NOTIFIER', default=False, cast=bool)
# SERVICES = config('SERVICES', cast=s2l, default=None)
# PRIVATE_SSH_KEY = config('PRIVATE_SSH_KEY', default='')
# PRIVATE_SSH_KEY = ''
#
# Path: isserviceup/services/models/service.py
# class Service(object):
#
# @property
# def id(self):
# return self.__class__.__name__
#
# @property
# def status_url(self):
# raise NotImplemented()
#
# @property
# def icon_url(self):
# raise NotImplemented()
#
# @property
# def name(self):
# raise NotImplemented()
#
# def get_status(self):
# raise NotImplemented()
#
# class Status(Enum):
# ok = 1 # green
# maintenance = 2 # blue
# minor = 3 # yellow
# major = 4 # orange
# critical = 5 # red
# unavailable = 6 # gray
. Output only the next line. | if not isu_config.ensure_private_ssh_key(): |
Predict the next line for this snippet: <|code_start|> url=self.status_url,
error='No private SSH key found. Make sure the file path you '
'set in option PRIVATE_SSH_KEY is correct. If it is a '
'shared file, make sure it has permissions to be read '
'by other users.'))
return False
return True
def _check_ssh(self):
if not self._check_private_ssh_key():
return False
url = urlparse(self.status_url)
try:
ssh = subprocess.check_output([
'ssh', '-T', '-o StrictHostKeyChecking=no',
'git@{host}'.format(host=url.netloc)
])
except subprocess.CalledProcessError as error:
print('GitLab SSH error for {url}: {error}'.format(
url=self.status_url, error=error))
return False
return 'Welcome to GitLab' in str(ssh)
def get_status(self):
status = [
not self.check_http or self._check_http(),
not self.check_json or self._check_json(),
not self.check_ssh or self._check_ssh(),
]
if all(status):
<|code_end|>
with the help of current file imports:
import requests
import subprocess
from decouple import config
from isserviceup.config import config as isu_config
from isserviceup.services.models.service import Service, Status
from urlparse import urlparse
from urllib.parse import urlparse
and context from other files:
# Path: isserviceup/config/config.py
# def s2l(x):
# def ensure_private_ssh_key():
# def get_status_description():
# DEBUG = config('DEBUG', cast=bool, default=False)
# FRONTEND_URL = config('FRONTEND_URL', default='http://localhost:8000/')
# REDIS_URL = config('REDIS_URL', default='redis://redis:devpassword@redis')
# MONGO_URL = config('MONGO_URL', default='mongodb://mongo/isserviceup')
# STATUS_UPDATE_INTERVAL = config('STATUS_UPDATE_INTERVAL', cast=int, default=30)
# SERVE_STATIC_FILES = config('SERVE_STATIC_FILES', cast=bool, default=True)
# SENTRY_DSN = config('SENTRY_DSN', default=None)
# CELERY_EAGER = config('CELERY_EAGER', cast=bool, default=False)
# CELERY_BROKER = config('CELERY_BROKER', default=REDIS_URL)
# CELERY_BACKEND = config('CELERY_BACKEND', default=REDIS_URL)
# GITHUB_CLIENT_ID = config('GITHUB_CLIENT_ID', default=None)
# GITHUB_CLIENT_SECRET = config('GITHUB_CLIENT_SECRET', default=None)
# SLACK_WEB_HOOK_URL = config('SLACK_WEB_HOOK_URL', default=None)
# NOTIFIERS = [
# # Slack(SLACK_WEB_HOOK_URL)
# ]
# NOTIFY_ON_STARTUP = config('NOTIFY_ON_STARTUP', default=False, cast=bool)
# CACHET_NOTIFIER = config('CACHET_NOTIFIER', default=False, cast=bool)
# SERVICES = config('SERVICES', cast=s2l, default=None)
# PRIVATE_SSH_KEY = config('PRIVATE_SSH_KEY', default='')
# PRIVATE_SSH_KEY = ''
#
# Path: isserviceup/services/models/service.py
# class Service(object):
#
# @property
# def id(self):
# return self.__class__.__name__
#
# @property
# def status_url(self):
# raise NotImplemented()
#
# @property
# def icon_url(self):
# raise NotImplemented()
#
# @property
# def name(self):
# raise NotImplemented()
#
# def get_status(self):
# raise NotImplemented()
#
# class Status(Enum):
# ok = 1 # green
# maintenance = 2 # blue
# minor = 3 # yellow
# major = 4 # orange
# critical = 5 # red
# unavailable = 6 # gray
, which may contain function names, class names, or code. Output only the next line. | return Status.ok |
Next line prediction: <|code_start|>
class Slack(Service):
name = 'Slack'
status_url = 'https://status.slack.com/'
icon_url = '/images/icons/slack.png'
def get_status(self):
r = requests.get(self.status_url)
b = BeautifulSoup(r.content, 'html.parser')
div = b.select_one('.current_status')
status_classes = div.attrs['class']
if 'all_clear' in status_classes:
<|code_end|>
. Use current file imports:
(import requests
from bs4 import BeautifulSoup
from isserviceup.services.models.service import Service, Status)
and context including class names, function names, or small code snippets from other files:
# Path: isserviceup/services/models/service.py
# class Service(object):
#
# @property
# def id(self):
# return self.__class__.__name__
#
# @property
# def status_url(self):
# raise NotImplemented()
#
# @property
# def icon_url(self):
# raise NotImplemented()
#
# @property
# def name(self):
# raise NotImplemented()
#
# def get_status(self):
# raise NotImplemented()
#
# class Status(Enum):
# ok = 1 # green
# maintenance = 2 # blue
# minor = 3 # yellow
# major = 4 # orange
# critical = 5 # red
# unavailable = 6 # gray
. Output only the next line. | return Status.ok |
Given the following code snippet before the placeholder: <|code_start|>
_status_key = lambda service: 'service:{}'.format(service.name)
_last_update_key = 'services:last_update'
def set_last_update(client, t):
client.set(_last_update_key, t)
def set_service_status(client, service, status):
key = _status_key(service)
pipe = client.pipeline()
pipe.hget(key, 'status')
pipe.hmset(key, {
'status': status.name,
'last_update': time.time(),
})
prev_status = pipe.execute()[0]
if prev_status is not None:
<|code_end|>
, predict the next line using imports from the current file:
import time
from isserviceup.services.models.service import Status
and context including class names, function names, and sometimes code from other files:
# Path: isserviceup/services/models/service.py
# class Status(Enum):
# ok = 1 # green
# maintenance = 2 # blue
# minor = 3 # yellow
# major = 4 # orange
# critical = 5 # red
# unavailable = 6 # gray
. Output only the next line. | prev_status = Status[prev_status] |
Given the following code snippet before the placeholder: <|code_start|>
class AWS(Service):
name = 'Amazon Web Services'
status_url = 'http://status.aws.amazon.com/'
icon_url = '/images/icons/aws.png'
def get_status(self):
r = requests.get(self.status_url)
b = BeautifulSoup(r.content, 'html.parser')
tc = str(b.find('table'))
if ('status0.gif' in tc) or ('status1.gif' in tc):
<|code_end|>
, predict the next line using imports from the current file:
import requests
from bs4 import BeautifulSoup
from isserviceup.services.models.service import Service, Status
and context including class names, function names, and sometimes code from other files:
# Path: isserviceup/services/models/service.py
# class Service(object):
#
# @property
# def id(self):
# return self.__class__.__name__
#
# @property
# def status_url(self):
# raise NotImplemented()
#
# @property
# def icon_url(self):
# raise NotImplemented()
#
# @property
# def name(self):
# raise NotImplemented()
#
# def get_status(self):
# raise NotImplemented()
#
# class Status(Enum):
# ok = 1 # green
# maintenance = 2 # blue
# minor = 3 # yellow
# major = 4 # orange
# critical = 5 # red
# unavailable = 6 # gray
. Output only the next line. | return Status.ok |
Given the code snippet: <|code_start|>
DEFAULT_MONITORED_STATUS = [
Status.ok.name,
Status.major.name,
Status.critical.name
]
class User(Document):
username = StringField(required=True, unique=True)
avatar_url = StringField()
github_access_token = StringField()
timestamp = DateTimeField(default=datetime.datetime.now)
monitored_status = ListField(StringField(), default=DEFAULT_MONITORED_STATUS)
slack_webhook = URLField(default=None)
def update_favs(self, field, value):
<|code_end|>
, generate the next line using the imports in this file:
import datetime
from mongoengine import StringField, Document, DateTimeField, BooleanField, ListField, URLField
from isserviceup.models.favorite import Favorite
from isserviceup.services.models.service import Status
and context (functions, classes, or occasionally code) from other files:
# Path: isserviceup/models/favorite.py
# class Favorite(Document):
# meta = {
# 'indexes': [
# {'fields': ('user_id',) },
# {'fields': ('service_id',) },
# {'fields': ('user_id', 'service_id'), 'unique': True}
# ]
# }
#
# user_id = StringField(required=True)
# service_id = StringField(required=True)
# timestamp = DateTimeField(default=datetime.datetime.now)
#
# monitored_status = ListField(default=None)
# slack_webhook = URLField(default=None)
#
# Path: isserviceup/services/models/service.py
# class Status(Enum):
# ok = 1 # green
# maintenance = 2 # blue
# minor = 3 # yellow
# major = 4 # orange
# critical = 5 # red
# unavailable = 6 # gray
. Output only the next line. | Favorite.objects(user_id=str(self.id))\ |
Given snippet: <|code_start|>
static_url_path = '' if config.SERVE_STATIC_FILES else None
static_folder = '../frontend/dist' if config.SERVE_STATIC_FILES else None
app = Flask(__name__, static_url_path=static_url_path, static_folder=static_folder)
app.config.from_object(config)
app.debug = config.DEBUG
CORS(app)
sentry = None
if config.SENTRY_DSN:
sentry = Sentry(app, logging=True, level=logging.ERROR)
@app.errorhandler(Exception)
def handle_generic_exception(error):
print('Exception={}'.format(error))
traceback.print_exc()
if sentry:
sentry.captureException()
return exceptions.handle_exception(error)
app.register_blueprint(status_bp.mod, url_prefix='/status')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
import traceback
from flask import Flask, jsonify
from flask_cors import CORS
from raven.contrib.flask import Sentry
from isserviceup.api import auth as auth_bp
from isserviceup.api import status as status_bp
from isserviceup.api import user as user_bp
from isserviceup.config import config
from isserviceup.helpers import exceptions
from isserviceup.helpers.exceptions import ApiException
and context:
# Path: isserviceup/api/auth.py
# def oauth_callback():
#
# Path: isserviceup/api/status.py
# @mod.route('', methods=['GET'])
# @authenticated(blocking=False)
# def status(user):
# type = request.args.get('type')
# favorite_services = []
#
# services = SERVICES.values()
#
# if user:
# favorite_services = get_favorite_services(str(user.id))
#
# if type == 'favorite':
# services = favorite_services
# for service in services:
# service.star = True
# else:
# favorite_services = {x.name: True for x in favorite_services}
#
# values = get_services_status(managers.rclient, services)
#
# data = []
# for i, service in enumerate(services):
# status = values[i] if values[i] else Status.unavailable
# star = True if type == 'favorite' else (service.name in favorite_services)
# s = {
# 'name': service.name,
# 'icon_url': service.icon_url,
# 'status_url': service.status_url,
# 'status': status.name,
# 'star': star,
# 'id': service.id,
# }
# data.append(s)
#
# return jsonify({
# 'data': {
# 'services': data,
# }
# })
#
# Path: isserviceup/api/user.py
# def get_user(user):
# def edit_user(user):
# def logout(user):
# def star(user):
#
# Path: isserviceup/config/config.py
# def s2l(x):
# def ensure_private_ssh_key():
# def get_status_description():
# DEBUG = config('DEBUG', cast=bool, default=False)
# FRONTEND_URL = config('FRONTEND_URL', default='http://localhost:8000/')
# REDIS_URL = config('REDIS_URL', default='redis://redis:devpassword@redis')
# MONGO_URL = config('MONGO_URL', default='mongodb://mongo/isserviceup')
# STATUS_UPDATE_INTERVAL = config('STATUS_UPDATE_INTERVAL', cast=int, default=30)
# SERVE_STATIC_FILES = config('SERVE_STATIC_FILES', cast=bool, default=True)
# SENTRY_DSN = config('SENTRY_DSN', default=None)
# CELERY_EAGER = config('CELERY_EAGER', cast=bool, default=False)
# CELERY_BROKER = config('CELERY_BROKER', default=REDIS_URL)
# CELERY_BACKEND = config('CELERY_BACKEND', default=REDIS_URL)
# GITHUB_CLIENT_ID = config('GITHUB_CLIENT_ID', default=None)
# GITHUB_CLIENT_SECRET = config('GITHUB_CLIENT_SECRET', default=None)
# SLACK_WEB_HOOK_URL = config('SLACK_WEB_HOOK_URL', default=None)
# NOTIFIERS = [
# # Slack(SLACK_WEB_HOOK_URL)
# ]
# NOTIFY_ON_STARTUP = config('NOTIFY_ON_STARTUP', default=False, cast=bool)
# CACHET_NOTIFIER = config('CACHET_NOTIFIER', default=False, cast=bool)
# SERVICES = config('SERVICES', cast=s2l, default=None)
# PRIVATE_SSH_KEY = config('PRIVATE_SSH_KEY', default='')
# PRIVATE_SSH_KEY = ''
#
# Path: isserviceup/helpers/exceptions.py
# class ApiException(Exception):
# def __init__(self, message, status_code=400, **kwargs):
# def format_exception(message, code=None, extra=None):
# def handle_exception(error):
#
# Path: isserviceup/helpers/exceptions.py
# class ApiException(Exception):
# def __init__(self, message, status_code=400, **kwargs):
# super(ApiException, self).__init__()
# self.message = message
# self.status_code = status_code
# self.extra = kwargs
which might include code, classes, or functions. Output only the next line. | app.register_blueprint(auth_bp.mod, url_prefix='/auth') |
Given snippet: <|code_start|>
static_url_path = '' if config.SERVE_STATIC_FILES else None
static_folder = '../frontend/dist' if config.SERVE_STATIC_FILES else None
app = Flask(__name__, static_url_path=static_url_path, static_folder=static_folder)
app.config.from_object(config)
app.debug = config.DEBUG
CORS(app)
sentry = None
if config.SENTRY_DSN:
sentry = Sentry(app, logging=True, level=logging.ERROR)
@app.errorhandler(Exception)
def handle_generic_exception(error):
print('Exception={}'.format(error))
traceback.print_exc()
if sentry:
sentry.captureException()
return exceptions.handle_exception(error)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
import traceback
from flask import Flask, jsonify
from flask_cors import CORS
from raven.contrib.flask import Sentry
from isserviceup.api import auth as auth_bp
from isserviceup.api import status as status_bp
from isserviceup.api import user as user_bp
from isserviceup.config import config
from isserviceup.helpers import exceptions
from isserviceup.helpers.exceptions import ApiException
and context:
# Path: isserviceup/api/auth.py
# def oauth_callback():
#
# Path: isserviceup/api/status.py
# @mod.route('', methods=['GET'])
# @authenticated(blocking=False)
# def status(user):
# type = request.args.get('type')
# favorite_services = []
#
# services = SERVICES.values()
#
# if user:
# favorite_services = get_favorite_services(str(user.id))
#
# if type == 'favorite':
# services = favorite_services
# for service in services:
# service.star = True
# else:
# favorite_services = {x.name: True for x in favorite_services}
#
# values = get_services_status(managers.rclient, services)
#
# data = []
# for i, service in enumerate(services):
# status = values[i] if values[i] else Status.unavailable
# star = True if type == 'favorite' else (service.name in favorite_services)
# s = {
# 'name': service.name,
# 'icon_url': service.icon_url,
# 'status_url': service.status_url,
# 'status': status.name,
# 'star': star,
# 'id': service.id,
# }
# data.append(s)
#
# return jsonify({
# 'data': {
# 'services': data,
# }
# })
#
# Path: isserviceup/api/user.py
# def get_user(user):
# def edit_user(user):
# def logout(user):
# def star(user):
#
# Path: isserviceup/config/config.py
# def s2l(x):
# def ensure_private_ssh_key():
# def get_status_description():
# DEBUG = config('DEBUG', cast=bool, default=False)
# FRONTEND_URL = config('FRONTEND_URL', default='http://localhost:8000/')
# REDIS_URL = config('REDIS_URL', default='redis://redis:devpassword@redis')
# MONGO_URL = config('MONGO_URL', default='mongodb://mongo/isserviceup')
# STATUS_UPDATE_INTERVAL = config('STATUS_UPDATE_INTERVAL', cast=int, default=30)
# SERVE_STATIC_FILES = config('SERVE_STATIC_FILES', cast=bool, default=True)
# SENTRY_DSN = config('SENTRY_DSN', default=None)
# CELERY_EAGER = config('CELERY_EAGER', cast=bool, default=False)
# CELERY_BROKER = config('CELERY_BROKER', default=REDIS_URL)
# CELERY_BACKEND = config('CELERY_BACKEND', default=REDIS_URL)
# GITHUB_CLIENT_ID = config('GITHUB_CLIENT_ID', default=None)
# GITHUB_CLIENT_SECRET = config('GITHUB_CLIENT_SECRET', default=None)
# SLACK_WEB_HOOK_URL = config('SLACK_WEB_HOOK_URL', default=None)
# NOTIFIERS = [
# # Slack(SLACK_WEB_HOOK_URL)
# ]
# NOTIFY_ON_STARTUP = config('NOTIFY_ON_STARTUP', default=False, cast=bool)
# CACHET_NOTIFIER = config('CACHET_NOTIFIER', default=False, cast=bool)
# SERVICES = config('SERVICES', cast=s2l, default=None)
# PRIVATE_SSH_KEY = config('PRIVATE_SSH_KEY', default='')
# PRIVATE_SSH_KEY = ''
#
# Path: isserviceup/helpers/exceptions.py
# class ApiException(Exception):
# def __init__(self, message, status_code=400, **kwargs):
# def format_exception(message, code=None, extra=None):
# def handle_exception(error):
#
# Path: isserviceup/helpers/exceptions.py
# class ApiException(Exception):
# def __init__(self, message, status_code=400, **kwargs):
# super(ApiException, self).__init__()
# self.message = message
# self.status_code = status_code
# self.extra = kwargs
which might include code, classes, or functions. Output only the next line. | app.register_blueprint(status_bp.mod, url_prefix='/status') |
Using the snippet: <|code_start|>
static_url_path = '' if config.SERVE_STATIC_FILES else None
static_folder = '../frontend/dist' if config.SERVE_STATIC_FILES else None
app = Flask(__name__, static_url_path=static_url_path, static_folder=static_folder)
app.config.from_object(config)
app.debug = config.DEBUG
CORS(app)
sentry = None
if config.SENTRY_DSN:
sentry = Sentry(app, logging=True, level=logging.ERROR)
@app.errorhandler(Exception)
def handle_generic_exception(error):
print('Exception={}'.format(error))
traceback.print_exc()
if sentry:
sentry.captureException()
return exceptions.handle_exception(error)
app.register_blueprint(status_bp.mod, url_prefix='/status')
app.register_blueprint(auth_bp.mod, url_prefix='/auth')
<|code_end|>
, determine the next line of code. You have imports:
import logging
import traceback
from flask import Flask, jsonify
from flask_cors import CORS
from raven.contrib.flask import Sentry
from isserviceup.api import auth as auth_bp
from isserviceup.api import status as status_bp
from isserviceup.api import user as user_bp
from isserviceup.config import config
from isserviceup.helpers import exceptions
from isserviceup.helpers.exceptions import ApiException
and context (class names, function names, or code) available:
# Path: isserviceup/api/auth.py
# def oauth_callback():
#
# Path: isserviceup/api/status.py
# @mod.route('', methods=['GET'])
# @authenticated(blocking=False)
# def status(user):
# type = request.args.get('type')
# favorite_services = []
#
# services = SERVICES.values()
#
# if user:
# favorite_services = get_favorite_services(str(user.id))
#
# if type == 'favorite':
# services = favorite_services
# for service in services:
# service.star = True
# else:
# favorite_services = {x.name: True for x in favorite_services}
#
# values = get_services_status(managers.rclient, services)
#
# data = []
# for i, service in enumerate(services):
# status = values[i] if values[i] else Status.unavailable
# star = True if type == 'favorite' else (service.name in favorite_services)
# s = {
# 'name': service.name,
# 'icon_url': service.icon_url,
# 'status_url': service.status_url,
# 'status': status.name,
# 'star': star,
# 'id': service.id,
# }
# data.append(s)
#
# return jsonify({
# 'data': {
# 'services': data,
# }
# })
#
# Path: isserviceup/api/user.py
# def get_user(user):
# def edit_user(user):
# def logout(user):
# def star(user):
#
# Path: isserviceup/config/config.py
# def s2l(x):
# def ensure_private_ssh_key():
# def get_status_description():
# DEBUG = config('DEBUG', cast=bool, default=False)
# FRONTEND_URL = config('FRONTEND_URL', default='http://localhost:8000/')
# REDIS_URL = config('REDIS_URL', default='redis://redis:devpassword@redis')
# MONGO_URL = config('MONGO_URL', default='mongodb://mongo/isserviceup')
# STATUS_UPDATE_INTERVAL = config('STATUS_UPDATE_INTERVAL', cast=int, default=30)
# SERVE_STATIC_FILES = config('SERVE_STATIC_FILES', cast=bool, default=True)
# SENTRY_DSN = config('SENTRY_DSN', default=None)
# CELERY_EAGER = config('CELERY_EAGER', cast=bool, default=False)
# CELERY_BROKER = config('CELERY_BROKER', default=REDIS_URL)
# CELERY_BACKEND = config('CELERY_BACKEND', default=REDIS_URL)
# GITHUB_CLIENT_ID = config('GITHUB_CLIENT_ID', default=None)
# GITHUB_CLIENT_SECRET = config('GITHUB_CLIENT_SECRET', default=None)
# SLACK_WEB_HOOK_URL = config('SLACK_WEB_HOOK_URL', default=None)
# NOTIFIERS = [
# # Slack(SLACK_WEB_HOOK_URL)
# ]
# NOTIFY_ON_STARTUP = config('NOTIFY_ON_STARTUP', default=False, cast=bool)
# CACHET_NOTIFIER = config('CACHET_NOTIFIER', default=False, cast=bool)
# SERVICES = config('SERVICES', cast=s2l, default=None)
# PRIVATE_SSH_KEY = config('PRIVATE_SSH_KEY', default='')
# PRIVATE_SSH_KEY = ''
#
# Path: isserviceup/helpers/exceptions.py
# class ApiException(Exception):
# def __init__(self, message, status_code=400, **kwargs):
# def format_exception(message, code=None, extra=None):
# def handle_exception(error):
#
# Path: isserviceup/helpers/exceptions.py
# class ApiException(Exception):
# def __init__(self, message, status_code=400, **kwargs):
# super(ApiException, self).__init__()
# self.message = message
# self.status_code = status_code
# self.extra = kwargs
. Output only the next line. | app.register_blueprint(user_bp.mod, url_prefix='/user') |
Continue the code snippet: <|code_start|>
static_url_path = '' if config.SERVE_STATIC_FILES else None
static_folder = '../frontend/dist' if config.SERVE_STATIC_FILES else None
app = Flask(__name__, static_url_path=static_url_path, static_folder=static_folder)
app.config.from_object(config)
app.debug = config.DEBUG
CORS(app)
sentry = None
if config.SENTRY_DSN:
sentry = Sentry(app, logging=True, level=logging.ERROR)
@app.errorhandler(Exception)
def handle_generic_exception(error):
print('Exception={}'.format(error))
traceback.print_exc()
if sentry:
sentry.captureException()
<|code_end|>
. Use current file imports:
import logging
import traceback
from flask import Flask, jsonify
from flask_cors import CORS
from raven.contrib.flask import Sentry
from isserviceup.api import auth as auth_bp
from isserviceup.api import status as status_bp
from isserviceup.api import user as user_bp
from isserviceup.config import config
from isserviceup.helpers import exceptions
from isserviceup.helpers.exceptions import ApiException
and context (classes, functions, or code) from other files:
# Path: isserviceup/api/auth.py
# def oauth_callback():
#
# Path: isserviceup/api/status.py
# @mod.route('', methods=['GET'])
# @authenticated(blocking=False)
# def status(user):
# type = request.args.get('type')
# favorite_services = []
#
# services = SERVICES.values()
#
# if user:
# favorite_services = get_favorite_services(str(user.id))
#
# if type == 'favorite':
# services = favorite_services
# for service in services:
# service.star = True
# else:
# favorite_services = {x.name: True for x in favorite_services}
#
# values = get_services_status(managers.rclient, services)
#
# data = []
# for i, service in enumerate(services):
# status = values[i] if values[i] else Status.unavailable
# star = True if type == 'favorite' else (service.name in favorite_services)
# s = {
# 'name': service.name,
# 'icon_url': service.icon_url,
# 'status_url': service.status_url,
# 'status': status.name,
# 'star': star,
# 'id': service.id,
# }
# data.append(s)
#
# return jsonify({
# 'data': {
# 'services': data,
# }
# })
#
# Path: isserviceup/api/user.py
# def get_user(user):
# def edit_user(user):
# def logout(user):
# def star(user):
#
# Path: isserviceup/config/config.py
# def s2l(x):
# def ensure_private_ssh_key():
# def get_status_description():
# DEBUG = config('DEBUG', cast=bool, default=False)
# FRONTEND_URL = config('FRONTEND_URL', default='http://localhost:8000/')
# REDIS_URL = config('REDIS_URL', default='redis://redis:devpassword@redis')
# MONGO_URL = config('MONGO_URL', default='mongodb://mongo/isserviceup')
# STATUS_UPDATE_INTERVAL = config('STATUS_UPDATE_INTERVAL', cast=int, default=30)
# SERVE_STATIC_FILES = config('SERVE_STATIC_FILES', cast=bool, default=True)
# SENTRY_DSN = config('SENTRY_DSN', default=None)
# CELERY_EAGER = config('CELERY_EAGER', cast=bool, default=False)
# CELERY_BROKER = config('CELERY_BROKER', default=REDIS_URL)
# CELERY_BACKEND = config('CELERY_BACKEND', default=REDIS_URL)
# GITHUB_CLIENT_ID = config('GITHUB_CLIENT_ID', default=None)
# GITHUB_CLIENT_SECRET = config('GITHUB_CLIENT_SECRET', default=None)
# SLACK_WEB_HOOK_URL = config('SLACK_WEB_HOOK_URL', default=None)
# NOTIFIERS = [
# # Slack(SLACK_WEB_HOOK_URL)
# ]
# NOTIFY_ON_STARTUP = config('NOTIFY_ON_STARTUP', default=False, cast=bool)
# CACHET_NOTIFIER = config('CACHET_NOTIFIER', default=False, cast=bool)
# SERVICES = config('SERVICES', cast=s2l, default=None)
# PRIVATE_SSH_KEY = config('PRIVATE_SSH_KEY', default='')
# PRIVATE_SSH_KEY = ''
#
# Path: isserviceup/helpers/exceptions.py
# class ApiException(Exception):
# def __init__(self, message, status_code=400, **kwargs):
# def format_exception(message, code=None, extra=None):
# def handle_exception(error):
#
# Path: isserviceup/helpers/exceptions.py
# class ApiException(Exception):
# def __init__(self, message, status_code=400, **kwargs):
# super(ApiException, self).__init__()
# self.message = message
# self.status_code = status_code
# self.extra = kwargs
. Output only the next line. | return exceptions.handle_exception(error) |
Here is a snippet: <|code_start|>app.config.from_object(config)
app.debug = config.DEBUG
CORS(app)
sentry = None
if config.SENTRY_DSN:
sentry = Sentry(app, logging=True, level=logging.ERROR)
@app.errorhandler(Exception)
def handle_generic_exception(error):
print('Exception={}'.format(error))
traceback.print_exc()
if sentry:
sentry.captureException()
return exceptions.handle_exception(error)
app.register_blueprint(status_bp.mod, url_prefix='/status')
app.register_blueprint(auth_bp.mod, url_prefix='/auth')
app.register_blueprint(user_bp.mod, url_prefix='/user')
@app.route('/', methods=['GET'])
def index():
if config.SERVE_STATIC_FILES:
return app.send_static_file('index.html')
else:
<|code_end|>
. Write the next line using the current file imports:
import logging
import traceback
from flask import Flask, jsonify
from flask_cors import CORS
from raven.contrib.flask import Sentry
from isserviceup.api import auth as auth_bp
from isserviceup.api import status as status_bp
from isserviceup.api import user as user_bp
from isserviceup.config import config
from isserviceup.helpers import exceptions
from isserviceup.helpers.exceptions import ApiException
and context from other files:
# Path: isserviceup/api/auth.py
# def oauth_callback():
#
# Path: isserviceup/api/status.py
# @mod.route('', methods=['GET'])
# @authenticated(blocking=False)
# def status(user):
# type = request.args.get('type')
# favorite_services = []
#
# services = SERVICES.values()
#
# if user:
# favorite_services = get_favorite_services(str(user.id))
#
# if type == 'favorite':
# services = favorite_services
# for service in services:
# service.star = True
# else:
# favorite_services = {x.name: True for x in favorite_services}
#
# values = get_services_status(managers.rclient, services)
#
# data = []
# for i, service in enumerate(services):
# status = values[i] if values[i] else Status.unavailable
# star = True if type == 'favorite' else (service.name in favorite_services)
# s = {
# 'name': service.name,
# 'icon_url': service.icon_url,
# 'status_url': service.status_url,
# 'status': status.name,
# 'star': star,
# 'id': service.id,
# }
# data.append(s)
#
# return jsonify({
# 'data': {
# 'services': data,
# }
# })
#
# Path: isserviceup/api/user.py
# def get_user(user):
# def edit_user(user):
# def logout(user):
# def star(user):
#
# Path: isserviceup/config/config.py
# def s2l(x):
# def ensure_private_ssh_key():
# def get_status_description():
# DEBUG = config('DEBUG', cast=bool, default=False)
# FRONTEND_URL = config('FRONTEND_URL', default='http://localhost:8000/')
# REDIS_URL = config('REDIS_URL', default='redis://redis:devpassword@redis')
# MONGO_URL = config('MONGO_URL', default='mongodb://mongo/isserviceup')
# STATUS_UPDATE_INTERVAL = config('STATUS_UPDATE_INTERVAL', cast=int, default=30)
# SERVE_STATIC_FILES = config('SERVE_STATIC_FILES', cast=bool, default=True)
# SENTRY_DSN = config('SENTRY_DSN', default=None)
# CELERY_EAGER = config('CELERY_EAGER', cast=bool, default=False)
# CELERY_BROKER = config('CELERY_BROKER', default=REDIS_URL)
# CELERY_BACKEND = config('CELERY_BACKEND', default=REDIS_URL)
# GITHUB_CLIENT_ID = config('GITHUB_CLIENT_ID', default=None)
# GITHUB_CLIENT_SECRET = config('GITHUB_CLIENT_SECRET', default=None)
# SLACK_WEB_HOOK_URL = config('SLACK_WEB_HOOK_URL', default=None)
# NOTIFIERS = [
# # Slack(SLACK_WEB_HOOK_URL)
# ]
# NOTIFY_ON_STARTUP = config('NOTIFY_ON_STARTUP', default=False, cast=bool)
# CACHET_NOTIFIER = config('CACHET_NOTIFIER', default=False, cast=bool)
# SERVICES = config('SERVICES', cast=s2l, default=None)
# PRIVATE_SSH_KEY = config('PRIVATE_SSH_KEY', default='')
# PRIVATE_SSH_KEY = ''
#
# Path: isserviceup/helpers/exceptions.py
# class ApiException(Exception):
# def __init__(self, message, status_code=400, **kwargs):
# def format_exception(message, code=None, extra=None):
# def handle_exception(error):
#
# Path: isserviceup/helpers/exceptions.py
# class ApiException(Exception):
# def __init__(self, message, status_code=400, **kwargs):
# super(ApiException, self).__init__()
# self.message = message
# self.status_code = status_code
# self.extra = kwargs
, which may include functions, classes, or code. Output only the next line. | raise ApiException('page not found', 404) |
Next line prediction: <|code_start|> def __init__(self):
# Will check if the Weblate website is OK.
self.check_http = config('WEBLATE_CHECK_HTTP', default=True, cast=bool)
# Will check if the Weblate JSON API is OK.
self.check_json = config('WEBLATE_CHECK_JSON', default=True, cast=bool)
# If you need to monitor multiple Weblate instances and need each one
# to have a different behaviour: extend this class, override the
# __init__ function, call super, and then override these properties.
def _check_http(self):
request = requests.get(self.status_url)
return request.ok
def _check_json(self):
request = requests.get('{base}/api/projects'.format(
base=self.status_url.strip('/')
))
try:
if request.json():
return True
except ValueError as error:
print('Value error: {msg}'.format(msg=error.message))
return False
def get_status(self):
status = [
not self.check_http or self._check_http(),
not self.check_json or self._check_json(),
]
if all(status):
<|code_end|>
. Use current file imports:
(import requests
from decouple import config
from isserviceup.services.models.service import Service, Status)
and context including class names, function names, or small code snippets from other files:
# Path: isserviceup/services/models/service.py
# class Service(object):
#
# @property
# def id(self):
# return self.__class__.__name__
#
# @property
# def status_url(self):
# raise NotImplemented()
#
# @property
# def icon_url(self):
# raise NotImplemented()
#
# @property
# def name(self):
# raise NotImplemented()
#
# def get_status(self):
# raise NotImplemented()
#
# class Status(Enum):
# ok = 1 # green
# maintenance = 2 # blue
# minor = 3 # yellow
# major = 4 # orange
# critical = 5 # red
# unavailable = 6 # gray
. Output only the next line. | return Status.ok |
Based on the snippet: <|code_start|>
SESSION_TTL = 60*60*24*30
_session_key = lambda x: 'session:{}'.format(x)
def get(sid):
<|code_end|>
, predict the immediate next line with the help of imports:
import json
from isserviceup import managers
from isserviceup.helpers import utils
and context (classes, functions, sometimes code) from other files:
# Path: isserviceup/managers.py
#
# Path: isserviceup/helpers/utils.py
# def random_string(n=10):
. Output only the next line. | res = managers.rclient.get(_session_key(sid)) |
Predict the next line for this snippet: <|code_start|>
SESSION_TTL = 60*60*24*30
_session_key = lambda x: 'session:{}'.format(x)
def get(sid):
res = managers.rclient.get(_session_key(sid))
if not res:
return None
res = json.loads(res)
return res
def create(data):
<|code_end|>
with the help of current file imports:
import json
from isserviceup import managers
from isserviceup.helpers import utils
and context from other files:
# Path: isserviceup/managers.py
#
# Path: isserviceup/helpers/utils.py
# def random_string(n=10):
, which may contain function names, class names, or code. Output only the next line. | sid = utils.random_string(16) |
Next line prediction: <|code_start|>
GitHubStatusMap = {
'good': Status.ok,
'major': Status.major,
'minor': Status.minor
}
<|code_end|>
. Use current file imports:
(import requests
from isserviceup.services.models.service import Service, Status)
and context including class names, function names, or small code snippets from other files:
# Path: isserviceup/services/models/service.py
# class Service(object):
#
# @property
# def id(self):
# return self.__class__.__name__
#
# @property
# def status_url(self):
# raise NotImplemented()
#
# @property
# def icon_url(self):
# raise NotImplemented()
#
# @property
# def name(self):
# raise NotImplemented()
#
# def get_status(self):
# raise NotImplemented()
#
# class Status(Enum):
# ok = 1 # green
# maintenance = 2 # blue
# minor = 3 # yellow
# major = 4 # orange
# critical = 5 # red
# unavailable = 6 # gray
. Output only the next line. | class GitHub(Service): |
Continue the code snippet: <|code_start|>
class StatusIOPlugin(Service):
status_url = 'https://api.status.io/'
@property
def statuspage_id(self):
raise NotImplemented()
def get_status(self):
r = requests.get('{}/1.0/status/{}'.format(
self.status_url.strip("/"), self.statuspage_id
))
try:
j = r.json()
except ValueError:
print(r.content)
raise
expected_status = {
<|code_end|>
. Use current file imports:
import requests
from isserviceup.services.models.service import Service, Status
and context (classes, functions, or code) from other files:
# Path: isserviceup/services/models/service.py
# class Service(object):
#
# @property
# def id(self):
# return self.__class__.__name__
#
# @property
# def status_url(self):
# raise NotImplemented()
#
# @property
# def icon_url(self):
# raise NotImplemented()
#
# @property
# def name(self):
# raise NotImplemented()
#
# def get_status(self):
# raise NotImplemented()
#
# class Status(Enum):
# ok = 1 # green
# maintenance = 2 # blue
# minor = 3 # yellow
# major = 4 # orange
# critical = 5 # red
# unavailable = 6 # gray
. Output only the next line. | 100: Status.ok, |
Given the code snippet: <|code_start|>
class Vultr(Service):
name = 'Vultr'
status_url = 'https://www.vultr.com/status'
icon_url = '/images/icons/vultr.png'
def get_status(self):
r = requests.get(self.status_url)
b = BeautifulSoup(r.content, 'html.parser')
div = b.find('div', {'class': 'row'})
status = div.findAll('i', {'class': 'zmdi'})
if all('text-sucess' in str(s) for s in status):
<|code_end|>
, generate the next line using the imports in this file:
import requests
from bs4 import BeautifulSoup
from isserviceup.services.models.service import Service, Status
and context (functions, classes, or occasionally code) from other files:
# Path: isserviceup/services/models/service.py
# class Service(object):
#
# @property
# def id(self):
# return self.__class__.__name__
#
# @property
# def status_url(self):
# raise NotImplemented()
#
# @property
# def icon_url(self):
# raise NotImplemented()
#
# @property
# def name(self):
# raise NotImplemented()
#
# def get_status(self):
# raise NotImplemented()
#
# class Status(Enum):
# ok = 1 # green
# maintenance = 2 # blue
# minor = 3 # yellow
# major = 4 # orange
# critical = 5 # red
# unavailable = 6 # gray
. Output only the next line. | return Status.ok |
Predict the next line after this snippet: <|code_start|>
class CachetStatus(Enum):
ok = 1
minor = 2
major = 3
critical = 4
@staticmethod
def get_cachet_status(status):
status_map = {
Status.ok: CachetStatus.ok,
Status.maintenance: CachetStatus.minor,
Status.minor: CachetStatus.minor,
Status.major: CachetStatus.major,
Status.critical: CachetStatus.critical,
Status.unavailable: CachetStatus.critical,
}
status = status and Status[status]
return (status_map[status].value if status in status_map
else CachetStatus.critical.value)
<|code_end|>
using the current file's imports:
import requests
from enum import Enum
from decouple import config
from isserviceup.notifiers.notifier import Notifier
from isserviceup.services.models.service import Status
and any relevant context from other files:
# Path: isserviceup/notifiers/notifier.py
# class Notifier(object):
#
# def notify(self, service, old_status, new_status):
# raise NotImplemented()
. Output only the next line. | class Cachet(Notifier): |
Based on the snippet: <|code_start|>
class StatusPagePlugin(Service):
def get_status(self):
r = requests.get(self.status_url)
b = BeautifulSoup(r.content, 'html.parser')
page_status = b.find(class_=['status', 'index'])
try:
status = next(x for x in page_status.attrs['class'] if x.startswith('status-'))
if status == 'status-none':
<|code_end|>
, predict the immediate next line with the help of imports:
import requests
from bs4 import BeautifulSoup
from isserviceup.services.models.service import Service, Status
and context (classes, functions, sometimes code) from other files:
# Path: isserviceup/services/models/service.py
# class Service(object):
#
# @property
# def id(self):
# return self.__class__.__name__
#
# @property
# def status_url(self):
# raise NotImplemented()
#
# @property
# def icon_url(self):
# raise NotImplemented()
#
# @property
# def name(self):
# raise NotImplemented()
#
# def get_status(self):
# raise NotImplemented()
#
# class Status(Enum):
# ok = 1 # green
# maintenance = 2 # blue
# minor = 3 # yellow
# major = 4 # orange
# critical = 5 # red
# unavailable = 6 # gray
. Output only the next line. | return Status.ok |
Using the snippet: <|code_start|> def _init_boselector_df(self, data, labels):
self.attributes = data.columns
self.coeff_df = pd.DataFrame()
self.initialized = True
return data.as_matrix(), labels.values
def fit(self, data, labels, epochs=10, verbose=1):
"""
Fits the boosted selector
:param data: Pandas DataFrame containing all the data
:param labels: Pandas Series with the labels
:param epochs: Number of fitting iterations. Defaults to 10.
:param verbose: print progress bar
:return: None
"""
if not self.initialized:
data, labels = self._init_boselector_df(data, labels)
else:
if isinstance(data, pd.core.frame.DataFrame):
data = data.as_matrix()
if isinstance(labels, pd.core.series.Series):
labels = labels.values
start = time.time()
for m in range(epochs):
<|code_end|>
, determine the next line of code. You have imports:
import pandas as pd
import numpy as np
import sys
import time
import abc
from DSTK.utils import sampling_helpers as sh
from sklearn.metrics import precision_score, accuracy_score, recall_score, roc_auc_score
and context (class names, function names, or code) available:
# Path: DSTK/utils/sampling_helpers.py
# def get_minority_majority_keys(sample_size_dict):
# def upsample_minority_class(data, labels, random_seed=None):
# def downsample_majority_class(data, labels, random_seed=None):
# def random_sample(data, label, sample_fraction, random_seed=None):
# def create_bags(data, label, sample_fraction, num_bags, bagging_fraction, random_seed=None):
# def permute_column_of_numpy_array(array, col_idx, random_seed=None):
. Output only the next line. | boot_data, oob_data, boot_labels, oob_labels = sh.random_sample(data, |
Predict the next line after this snippet: <|code_start|>
cancer_ds = ds.load_breast_cancer()
data = cancer_ds['data'][:, :20]
labels = 2 * cancer_ds['target'] - 1
random_seed = 42
def test_downsample():
initial_cntr = Counter(labels)
min_size = np.min(initial_cntr.values())
<|code_end|>
using the current file's imports:
from sklearn import datasets as ds
from collections import Counter
from DSTK.utils import sampling_helpers as sh
import numpy as np
and any relevant context from other files:
# Path: DSTK/utils/sampling_helpers.py
# def get_minority_majority_keys(sample_size_dict):
# def upsample_minority_class(data, labels, random_seed=None):
# def downsample_majority_class(data, labels, random_seed=None):
# def random_sample(data, label, sample_fraction, random_seed=None):
# def create_bags(data, label, sample_fraction, num_bags, bagging_fraction, random_seed=None):
# def permute_column_of_numpy_array(array, col_idx, random_seed=None):
. Output only the next line. | down_data, down_labels = sh.downsample_majority_class(data, labels, random_seed=random_seed) |
Using the snippet: <|code_start|>from __future__ import division
class _Node(object):
def __init__(self, id, threshold, left_child, right_child, is_leaf, counts, statistic):
self.id = id
self.threshold = threshold
self.left_child = left_child
self.right_child = right_child
self.is_leaf = is_leaf
self.counts = counts
self.statistic = statistic
self.cond_proba = counts / counts.sum()
self.log_odds = np.log(counts[1] / counts[0])
def __str__(self):
return "id: {}, threshold: {}, left_id: {}, right_id: {}, leaf: {}, counts: {}, statistic: {}, probas: {}, log_odds: {}".format(self.id, self.threshold, self.left_child, self.right_child, self.is_leaf, self.counts, self.statistic, self.cond_proba, self.log_odds)
<|code_end|>
, determine the next line of code. You have imports:
import numpy as np
import scipy.stats as st
from DSTK.FeatureBinning.base_binner import BaseBinner
from DSTK.FeatureBinning._utils import _naive_bayes_bins, _filter_special_values
and context (class names, function names, or code) available:
# Path: DSTK/FeatureBinning/base_binner.py
# class BaseBinner(object):
# __metaclass__ = abc.ABCMeta
#
# @abc.abstractproperty
# def splits(self):
# raise NotImplementedError
#
# @splits.setter
# def splits(self, values):
# raise NotImplementedError
#
# @abc.abstractproperty
# def values(self):
# raise NotImplementedError
#
# @values.setter
# def values(self, values):
# raise NotImplementedError
#
# @abc.abstractmethod
# def fit(self, values, targets):
# raise NotImplementedError
#
# @abc.abstractproperty
# def is_fit(self):
# raise NotImplementedError
#
# @is_fit.setter
# def is_fit(self, is_fit):
# raise NotImplementedError
#
# def transform(self, values, **kwargs):
# """
# # See output of 'fit_transform()'
# # :param feature_values:
# # :param class_index:
# # :return:
# # """
# if not self.is_fit:
# raise AssertionError("FeatureBinner has to be fit to the data first.")
#
# class_index = kwargs.get('class_index', 1)
# idx = np.searchsorted(self.splits, values, side='right')
#
# # searchsorted on nan values gives wrong idx when input is nan
# # as it assumes the nan value is "right" of a nan split
# idx[np.where(np.isnan(values))[0]] -= 1
#
# if class_index:
# return np.asarray(self.values)[idx][:, class_index]
# else:
# return np.asarray(self.values)[idx]
#
# def fit_transform(self, feature_values, target_values, **kwargs):
# """
# :param feature_values: list or array of the feature values
# :param target_values: list or array of the corresponding labels
# :param class_index: Index of the corresponding class in the conditional probability vector for each bucket.
# Defaults to 1 (as mostly used for binary classification)
# :return: list of cond_proba_buckets with corresponding conditional probabilities P( T | x in X )
# for a given example with value x in bin with range X to have label T and list of conditional probabilities for each value to be of class T
# """
# self.fit(feature_values, target_values)
# return self.transform(feature_values, **kwargs)
#
# def add_bin(self, right_bin_edge, bin_value):
#
# if right_bin_edge in self.splits:
# warnings.warn("Bin edge already exists.", UserWarning)
# return self
#
# # use np.searchsorted instead of digitize as the latter
# # gives the wrong result for purely non-numeric splits
# # see corresponding test for the issue
# idx = np.searchsorted(self.splits, right_bin_edge, side='right')
# self.splits = np.insert(self.splits, idx, right_bin_edge).tolist()
# self.values = np.insert(self.values, [idx], bin_value, axis=0).tolist()
#
# return self
#
# def __str__(self):
# return self.__repr__()
#
# def __repr__(self):
# sp = np.asarray(self.splits)
# vals = np.asarray(self.values)
# non_na_sp = sp[~np.isnan(sp)]
# non_na_val = vals[~np.isnan(sp)]
# na_val = vals[np.isnan(sp)].flatten()
#
# non_na_str = ["<= {}: {}".format(split, val) for split, val in zip(non_na_sp, non_na_val)]
# non_na_str += ["NaN: {}".format(na_val)]
#
# return "\n".join(non_na_str)
#
# Path: DSTK/FeatureBinning/_utils.py
# def _naive_bayes_bins(target, prior, num_classes=2):
# if len(target) > 1:
# cnts = np.bincount(target, minlength=num_classes)
# return list(cnts / cnts.sum())
# else:
# return [1 - prior, prior]
#
# def _filter_special_values(values, filter_values):
# feats = np.array(values)
# filters = np.array(filter_values)
#
# special_vals_idx_dct = dict()
# for val in filters:
# if np.isnan(val):
# idx = np.where(np.isnan(feats))[0]
# else:
# idx = np.where(feats == val)[0]
#
# special_vals_idx_dct.update({str(val): idx})
#
# all_special_idx = list()
# for vals in special_vals_idx_dct.values():
# all_special_idx += vals.tolist()
#
# all_special_idx = np.asarray(all_special_idx)
# all_idx = np.arange(0, len(feats), 1, dtype=int)
# all_non_special_idx = [idx for idx in all_idx if idx not in all_special_idx]
# special_vals_idx_dct.update({'regular': all_non_special_idx})
#
# return special_vals_idx_dct
. Output only the next line. | class ConditionalInferenceBinner(BaseBinner): |
Predict the next line for this snippet: <|code_start|>
def _create_partition(lst_of_splits):
return np.append(lst_of_splits, np.PINF)
def test_returning_value():
<|code_end|>
with the help of current file imports:
import pytest
import numpy as np
from DSTK.GAM.gam import ShapeFunction
and context from other files:
# Path: DSTK/GAM/gam.py
# def _recurse(tree, feature_vec):
# def _get_sum_of_gamma_correction(tree, data, labels, class_weights, feature_name):
# def _get_shape_for_attribute(attribute_data, labels, class_weights, feature_name, criterion, splitter,
# max_depth, min_samples_split, min_samples_leaf, min_weight_fraction_leaf,
# max_features, random_state, max_leaf_nodes, presort):
# def __init__(self, **kwargs):
# def _get_metadata_dict(self):
# def _train_cost(self, data, labels):
# def _get_pseudo_responses(self, data, labels):
# def _init_shapes_and_data(self, data, labels):
# def _update_learning_rate(self, dct, epoch):
# def _initialize_class_weights(self, labels):
# def _get_class_weights(self, labels):
# def train(self, data, targets, **kwargs):
# def _get_trimmed_record_indices(self, responses):
# def _calculate_gradient_shape(self, data, labels, bag_indices=None, max_workers=1):
# def __init__(self, gam):
# def __getattr__(self, item):
# def smoothen(self, data, penalty=None):
# def _create_smooth_shape(shape, values, name, penalties):
# def _fit_spline(values, target_vals, penalties):
# class GAM(BaseGAM):
# class SmoothGAM(BaseGAM):
, which may contain function names, class names, or code. Output only the next line. | func = ShapeFunction(_create_partition(np.linspace(1, 10, 10)), -1 * np.linspace(1, 10, 11), 'test_1') |
Next line prediction: <|code_start|> Note that it can handle NaN by assigning it its own range.
E.g.
>>> feats = [0, 1, 2, np.nan, 5, np.nan]
>>> labels = [0, 1, 0, 1, 1, 0]
then
>>> tfb = DecisionTreeBinner()
>>> tfb.fit(feats, labels, max_leaf_nodes = 3)
>>> tfb.cond_proba_buckets
... [((-inf, 0.5), [1.0, 0.0]),
... ((0.5, 1.5), [0.0, 1.0]),
... ((1.5, inf), [0.5, 0.5]),
... (nan, [0.5, 0.5])]
which we can interpret as: given an example with label 0 there is a 25% probability of having a feature value in the range
(-inf, 0.5).
:param feature_values: list or array of the feature values
:param target_values: list or array of the corresponding labels
:param kwargs: supports all keywords of an sklearn.DecisionTreeClassifier
:return: Nothing, but sets the self.cond_proba_buckets field
"""
assert (values is not None) & (values != []), "feature_values cannot be None or empty"
assert (target is not None) & (target != []), "target_values cannot be None or empty"
assert len(values) == len(target), "feature_values and target_values must have same length"
<|code_end|>
. Use current file imports:
(import sklearn
import numpy as np
from sklearn.tree import DecisionTreeClassifier
from DSTK.FeatureBinning._utils import _process_nan_values, _get_non_nan_values_and_targets
from DSTK.FeatureBinning.base_binner import BaseBinner)
and context including class names, function names, or small code snippets from other files:
# Path: DSTK/FeatureBinning/_utils.py
# def _process_nan_values(values, target, prior):
#
# feats = np.array(values)
# labels = np.array(target)
# num_classes = np.bincount(target).size
#
# num_nan = len(feats[np.isnan(feats)])
# val_count = np.bincount(labels[np.isnan(feats)], minlength=num_classes)
# if (num_nan == 0) and prior:
# return [1 - prior, prior]
# elif (num_nan == 0) and (prior is None):
# return (np.ones((num_classes,), dtype='float64') / num_classes).tolist()
# return list(val_count / num_nan)
#
# def _get_non_nan_values_and_targets(values, target):
# feats = np.array(values)
# labels = np.array(target)
#
# return feats[~np.isnan(feats)].reshape(-1, 1), labels[~np.isnan(feats)].reshape(-1, 1)
#
# Path: DSTK/FeatureBinning/base_binner.py
# class BaseBinner(object):
# __metaclass__ = abc.ABCMeta
#
# @abc.abstractproperty
# def splits(self):
# raise NotImplementedError
#
# @splits.setter
# def splits(self, values):
# raise NotImplementedError
#
# @abc.abstractproperty
# def values(self):
# raise NotImplementedError
#
# @values.setter
# def values(self, values):
# raise NotImplementedError
#
# @abc.abstractmethod
# def fit(self, values, targets):
# raise NotImplementedError
#
# @abc.abstractproperty
# def is_fit(self):
# raise NotImplementedError
#
# @is_fit.setter
# def is_fit(self, is_fit):
# raise NotImplementedError
#
# def transform(self, values, **kwargs):
# """
# # See output of 'fit_transform()'
# # :param feature_values:
# # :param class_index:
# # :return:
# # """
# if not self.is_fit:
# raise AssertionError("FeatureBinner has to be fit to the data first.")
#
# class_index = kwargs.get('class_index', 1)
# idx = np.searchsorted(self.splits, values, side='right')
#
# # searchsorted on nan values gives wrong idx when input is nan
# # as it assumes the nan value is "right" of a nan split
# idx[np.where(np.isnan(values))[0]] -= 1
#
# if class_index:
# return np.asarray(self.values)[idx][:, class_index]
# else:
# return np.asarray(self.values)[idx]
#
# def fit_transform(self, feature_values, target_values, **kwargs):
# """
# :param feature_values: list or array of the feature values
# :param target_values: list or array of the corresponding labels
# :param class_index: Index of the corresponding class in the conditional probability vector for each bucket.
# Defaults to 1 (as mostly used for binary classification)
# :return: list of cond_proba_buckets with corresponding conditional probabilities P( T | x in X )
# for a given example with value x in bin with range X to have label T and list of conditional probabilities for each value to be of class T
# """
# self.fit(feature_values, target_values)
# return self.transform(feature_values, **kwargs)
#
# def add_bin(self, right_bin_edge, bin_value):
#
# if right_bin_edge in self.splits:
# warnings.warn("Bin edge already exists.", UserWarning)
# return self
#
# # use np.searchsorted instead of digitize as the latter
# # gives the wrong result for purely non-numeric splits
# # see corresponding test for the issue
# idx = np.searchsorted(self.splits, right_bin_edge, side='right')
# self.splits = np.insert(self.splits, idx, right_bin_edge).tolist()
# self.values = np.insert(self.values, [idx], bin_value, axis=0).tolist()
#
# return self
#
# def __str__(self):
# return self.__repr__()
#
# def __repr__(self):
# sp = np.asarray(self.splits)
# vals = np.asarray(self.values)
# non_na_sp = sp[~np.isnan(sp)]
# non_na_val = vals[~np.isnan(sp)]
# na_val = vals[np.isnan(sp)].flatten()
#
# non_na_str = ["<= {}: {}".format(split, val) for split, val in zip(non_na_sp, non_na_val)]
# non_na_str += ["NaN: {}".format(na_val)]
#
# return "\n".join(non_na_str)
. Output only the next line. | non_nan_feats, non_nan_labels = _get_non_nan_values_and_targets(values, target) |
Given snippet: <|code_start|> 'shape_data': './shapes'
}
with open('{}/{}/{}.json'.format(file_path, model_name, model_name), 'w') as fp:
js.dump(dct, fp, sort_keys=True, indent=2, separators=(',', ': '))
self._make_tarfile('{}/{}.tar.gz'.format(file_path, model_name), '{}/{}'.format(file_path, model_name))
@staticmethod
def _make_tarfile(output_filename, source_dir):
with tf.open(output_filename, "w:gz") as tar:
tar.add(source_dir, arcname=os.path.basename(source_dir))
def load_from_tar(file_name):
model_name = file_name.split('/')[-1].replace('.tar.gz', '')
gam = DeserializedGAM()
with tf.open(file_name, "r:gz") as tar:
f = tar.extractfile('{}/{}.json'.format(model_name, model_name))
content = js.loads(f.read())
gam._n_features = content['num_features']
gam.feature_names = content['feature_names']
for member in tar.getmembers():
if member.isfile() and (member.name != '{}/{}.json'.format(model_name, model_name)):
f = tar.extractfile(member.path)
content = js.loads(f.read())
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
import pandas
import json as js
import tarfile as tf
import os
import abc
from DSTK.GAM.utils.shape_function import ShapeFunction
from DSTK.utils.function_helpers import sigmoid
and context:
# Path: DSTK/GAM/utils/shape_function.py
# class ShapeFunction(object):
#
# def __init__(self, list_of_splits, list_of_values, name):
# assert len(list_of_splits) == len(list_of_values), 'splits and values need to be of the same length'
# assert all(list_of_splits[i] <= list_of_splits[i+1] for i in xrange(len(list_of_splits)-1)), 'range of splits has to be sorted!'
#
# self.splits = np.asarray(list_of_splits, dtype=np.float64)
# self.values = np.asarray(list_of_values, dtype=np.float64)
# self.name = name
#
# def get_value(self, feature_value):
# idx = np.searchsorted(self.splits, feature_value, side='right')
# if idx == len(self.splits):
# idx = -1
# return self.values[idx]
#
# def multiply(self, const):
# return ShapeFunction(self.splits, const * self.values, self.name)
#
# def add(self, other):
# return self.__add__(other)
#
# def __add__(self, other):
#
# assert isinstance(other, ShapeFunction), "Can only add other shape function"
#
# assert self.name == other.name, "Cannot add shapes of different features"
#
# new_splits = self.splits.copy()
# new_vals = self.values.copy()
#
# for split, val in zip(other.splits, other.values):
# idx = np.searchsorted(new_splits, split, side='right')
# new_val = val
# if split in new_splits:
# idx_2 = np.argwhere(new_splits == split)
# new_vals[idx_2] = new_vals[idx_2] + new_val
# elif idx == len(new_splits) and (~np.isposinf(split)):
# new_splits = np.append(new_splits, split)
# new_vals = np.append(new_vals, new_val)
# elif np.isposinf(split):
# new_vals[-1] = new_vals[-1] + new_val
# else:
# new_splits = np.insert(new_splits, idx, split)
# new_vals = np.insert(new_vals, idx, new_val)
#
# return ShapeFunction(new_splits, new_vals, self.name)
#
# def __str__(self):
# return ''.join(['< {} : {}\n'.format(tup[0], tup[1]) for tup in zip(self.splits, self.values)])
#
# def equals(self, other):
# return (self.splits == other.splits).all() and (self.values == other.values).all()
#
# def serialize(self, file_path, meta_data=dict()):
# meta_data_dct = {
# 'serialization_date': datetime.now().strftime('%Y-%m-%d %H:%M:%S%z')
# }
# meta_data_dct.update(meta_data)
#
# dct = {
# 'feature_name': self.name,
# 'splits': self.splits.tolist(),
# 'values': self.values.tolist(),
# 'split_rule': 'LT',
# 'meta_data': meta_data_dct
# }
#
# if not os.path.exists(file_path):
# os.makedirs(file_path)
#
# with open('{}/{}.json'.format(file_path, ShapeFunction.create_clean_file_name(self.name)), 'w') as fp:
# js.dump(dct, fp, sort_keys=True, indent=2, separators=(',', ': '))
#
#
# @staticmethod
# def create_clean_file_name(file_name):
# cleaning_pattern = re.compile(r'[\\#\.\$@!><\|/]+')
# return re.sub(cleaning_pattern, "__", file_name)
#
# @staticmethod
# def load_from_json(file_path):
# with open(file_path, 'r') as fp:
# dct = js.load(fp=fp)
#
# return ShapeFunction(np.asarray(dct['splits']),
# np.asarray(dct['values']),
# dct['feature_name'])
#
# Path: DSTK/utils/function_helpers.py
# def _sigmoid(x):
which might include code, classes, or functions. Output only the next line. | gam.shapes.update({content['feature_name']: ShapeFunction(content['splits'], |
Given snippet: <|code_start|>from __future__ import division
class BaseGAM(object):
__metaclass__ = abc.ABCMeta
def __init__(self):
self.shapes = dict()
self.is_fit = False
self.initialized = False
self.n_features = None
self.feature_names = None
def _get_index_for_feature(self, feature_name):
return self.feature_names.index(feature_name)
def logit_score(self, vec):
return np.sum([func.get_value(vec[self._get_index_for_feature(feat)]) for feat, func in self.shapes.iteritems()])
def _score_single_record(self, vec):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
import pandas
import json as js
import tarfile as tf
import os
import abc
from DSTK.GAM.utils.shape_function import ShapeFunction
from DSTK.utils.function_helpers import sigmoid
and context:
# Path: DSTK/GAM/utils/shape_function.py
# class ShapeFunction(object):
#
# def __init__(self, list_of_splits, list_of_values, name):
# assert len(list_of_splits) == len(list_of_values), 'splits and values need to be of the same length'
# assert all(list_of_splits[i] <= list_of_splits[i+1] for i in xrange(len(list_of_splits)-1)), 'range of splits has to be sorted!'
#
# self.splits = np.asarray(list_of_splits, dtype=np.float64)
# self.values = np.asarray(list_of_values, dtype=np.float64)
# self.name = name
#
# def get_value(self, feature_value):
# idx = np.searchsorted(self.splits, feature_value, side='right')
# if idx == len(self.splits):
# idx = -1
# return self.values[idx]
#
# def multiply(self, const):
# return ShapeFunction(self.splits, const * self.values, self.name)
#
# def add(self, other):
# return self.__add__(other)
#
# def __add__(self, other):
#
# assert isinstance(other, ShapeFunction), "Can only add other shape function"
#
# assert self.name == other.name, "Cannot add shapes of different features"
#
# new_splits = self.splits.copy()
# new_vals = self.values.copy()
#
# for split, val in zip(other.splits, other.values):
# idx = np.searchsorted(new_splits, split, side='right')
# new_val = val
# if split in new_splits:
# idx_2 = np.argwhere(new_splits == split)
# new_vals[idx_2] = new_vals[idx_2] + new_val
# elif idx == len(new_splits) and (~np.isposinf(split)):
# new_splits = np.append(new_splits, split)
# new_vals = np.append(new_vals, new_val)
# elif np.isposinf(split):
# new_vals[-1] = new_vals[-1] + new_val
# else:
# new_splits = np.insert(new_splits, idx, split)
# new_vals = np.insert(new_vals, idx, new_val)
#
# return ShapeFunction(new_splits, new_vals, self.name)
#
# def __str__(self):
# return ''.join(['< {} : {}\n'.format(tup[0], tup[1]) for tup in zip(self.splits, self.values)])
#
# def equals(self, other):
# return (self.splits == other.splits).all() and (self.values == other.values).all()
#
# def serialize(self, file_path, meta_data=dict()):
# meta_data_dct = {
# 'serialization_date': datetime.now().strftime('%Y-%m-%d %H:%M:%S%z')
# }
# meta_data_dct.update(meta_data)
#
# dct = {
# 'feature_name': self.name,
# 'splits': self.splits.tolist(),
# 'values': self.values.tolist(),
# 'split_rule': 'LT',
# 'meta_data': meta_data_dct
# }
#
# if not os.path.exists(file_path):
# os.makedirs(file_path)
#
# with open('{}/{}.json'.format(file_path, ShapeFunction.create_clean_file_name(self.name)), 'w') as fp:
# js.dump(dct, fp, sort_keys=True, indent=2, separators=(',', ': '))
#
#
# @staticmethod
# def create_clean_file_name(file_name):
# cleaning_pattern = re.compile(r'[\\#\.\$@!><\|/]+')
# return re.sub(cleaning_pattern, "__", file_name)
#
# @staticmethod
# def load_from_json(file_path):
# with open(file_path, 'r') as fp:
# dct = js.load(fp=fp)
#
# return ShapeFunction(np.asarray(dct['splits']),
# np.asarray(dct['values']),
# dct['feature_name'])
#
# Path: DSTK/utils/function_helpers.py
# def _sigmoid(x):
which might include code, classes, or functions. Output only the next line. | return [sigmoid(-2 * np.sum([func.get_value(vec[self._get_index_for_feature(feat)]) for feat, func in self.shapes.iteritems()])), \ |
Given the following code snippet before the placeholder: <|code_start|>
cancer_ds = ds.load_breast_cancer()
data = cancer_ds['data'][:, :20]
labels = 2 * cancer_ds['target'] - 1
assert_scores = [
[0.5538394842641805, 0.44616051573581944],
[0.49861290044203543, 0.5013870995579646],
[0.5470227126670573, 0.4529772873329428],
[0.513940794277825, 0.48605920572217504],
[0.529758125364891, 0.470241874635109]
]
test_root_folder = '/tmp/test_gam_serialization'
def teardown():
if os.path.exists(test_root_folder):
shutil.rmtree(test_root_folder)
def test_gam_training():
<|code_end|>
, predict the next line using imports from the current file:
from sklearn import datasets as ds
from DSTK.GAM.gam import GAM, ShapeFunction
from DSTK.tests.tests_gam.test_shape_function import _create_partition
from DSTK.GAM.base_gam import load_from_tar
import numpy as np
import os
import shutil
and context including class names, function names, and sometimes code from other files:
# Path: DSTK/GAM/gam.py
# def _recurse(tree, feature_vec):
# def _get_sum_of_gamma_correction(tree, data, labels, class_weights, feature_name):
# def _get_shape_for_attribute(attribute_data, labels, class_weights, feature_name, criterion, splitter,
# max_depth, min_samples_split, min_samples_leaf, min_weight_fraction_leaf,
# max_features, random_state, max_leaf_nodes, presort):
# def __init__(self, **kwargs):
# def _get_metadata_dict(self):
# def _train_cost(self, data, labels):
# def _get_pseudo_responses(self, data, labels):
# def _init_shapes_and_data(self, data, labels):
# def _update_learning_rate(self, dct, epoch):
# def _initialize_class_weights(self, labels):
# def _get_class_weights(self, labels):
# def train(self, data, targets, **kwargs):
# def _get_trimmed_record_indices(self, responses):
# def _calculate_gradient_shape(self, data, labels, bag_indices=None, max_workers=1):
# def __init__(self, gam):
# def __getattr__(self, item):
# def smoothen(self, data, penalty=None):
# def _create_smooth_shape(shape, values, name, penalties):
# def _fit_spline(values, target_vals, penalties):
# class GAM(BaseGAM):
# class SmoothGAM(BaseGAM):
#
# Path: DSTK/tests/tests_gam/test_shape_function.py
# def _create_partition(lst_of_splits):
# return np.append(lst_of_splits, np.PINF)
#
# Path: DSTK/GAM/base_gam.py
# def load_from_tar(file_name):
#
# model_name = file_name.split('/')[-1].replace('.tar.gz', '')
#
# gam = DeserializedGAM()
#
# with tf.open(file_name, "r:gz") as tar:
# f = tar.extractfile('{}/{}.json'.format(model_name, model_name))
# content = js.loads(f.read())
# gam._n_features = content['num_features']
# gam.feature_names = content['feature_names']
#
# for member in tar.getmembers():
# if member.isfile() and (member.name != '{}/{}.json'.format(model_name, model_name)):
# f = tar.extractfile(member.path)
# content = js.loads(f.read())
# gam.shapes.update({content['feature_name']: ShapeFunction(content['splits'],
# content['values'],
# content['feature_name'])})
#
# assert set(gam.shapes.keys()) == set(gam.feature_names), 'feature names and shape names do not match up'
# return gam
. Output only the next line. | gam = GAM(max_depth=3, max_leaf_nodes=5, random_state=42, balancer_seed=42) |
Predict the next line after this snippet: <|code_start|>cancer_ds = ds.load_breast_cancer()
data = cancer_ds['data'][:, :20]
labels = 2 * cancer_ds['target'] - 1
assert_scores = [
[0.5538394842641805, 0.44616051573581944],
[0.49861290044203543, 0.5013870995579646],
[0.5470227126670573, 0.4529772873329428],
[0.513940794277825, 0.48605920572217504],
[0.529758125364891, 0.470241874635109]
]
test_root_folder = '/tmp/test_gam_serialization'
def teardown():
if os.path.exists(test_root_folder):
shutil.rmtree(test_root_folder)
def test_gam_training():
gam = GAM(max_depth=3, max_leaf_nodes=5, random_state=42, balancer_seed=42)
gam.train(data, labels, n_iter=5, learning_rate=0.0025, num_bags=1, num_workers=3)
for idx, vec in enumerate(data[:5, :]):
gam_scores = gam.score(vec)
np.testing.assert_almost_equal(np.sum(gam_scores), 1.0, 10)
np.testing.assert_almost_equal(gam_scores, assert_scores[idx], 10)
def test_correct_scoring():
<|code_end|>
using the current file's imports:
from sklearn import datasets as ds
from DSTK.GAM.gam import GAM, ShapeFunction
from DSTK.tests.tests_gam.test_shape_function import _create_partition
from DSTK.GAM.base_gam import load_from_tar
import numpy as np
import os
import shutil
and any relevant context from other files:
# Path: DSTK/GAM/gam.py
# def _recurse(tree, feature_vec):
# def _get_sum_of_gamma_correction(tree, data, labels, class_weights, feature_name):
# def _get_shape_for_attribute(attribute_data, labels, class_weights, feature_name, criterion, splitter,
# max_depth, min_samples_split, min_samples_leaf, min_weight_fraction_leaf,
# max_features, random_state, max_leaf_nodes, presort):
# def __init__(self, **kwargs):
# def _get_metadata_dict(self):
# def _train_cost(self, data, labels):
# def _get_pseudo_responses(self, data, labels):
# def _init_shapes_and_data(self, data, labels):
# def _update_learning_rate(self, dct, epoch):
# def _initialize_class_weights(self, labels):
# def _get_class_weights(self, labels):
# def train(self, data, targets, **kwargs):
# def _get_trimmed_record_indices(self, responses):
# def _calculate_gradient_shape(self, data, labels, bag_indices=None, max_workers=1):
# def __init__(self, gam):
# def __getattr__(self, item):
# def smoothen(self, data, penalty=None):
# def _create_smooth_shape(shape, values, name, penalties):
# def _fit_spline(values, target_vals, penalties):
# class GAM(BaseGAM):
# class SmoothGAM(BaseGAM):
#
# Path: DSTK/tests/tests_gam/test_shape_function.py
# def _create_partition(lst_of_splits):
# return np.append(lst_of_splits, np.PINF)
#
# Path: DSTK/GAM/base_gam.py
# def load_from_tar(file_name):
#
# model_name = file_name.split('/')[-1].replace('.tar.gz', '')
#
# gam = DeserializedGAM()
#
# with tf.open(file_name, "r:gz") as tar:
# f = tar.extractfile('{}/{}.json'.format(model_name, model_name))
# content = js.loads(f.read())
# gam._n_features = content['num_features']
# gam.feature_names = content['feature_names']
#
# for member in tar.getmembers():
# if member.isfile() and (member.name != '{}/{}.json'.format(model_name, model_name)):
# f = tar.extractfile(member.path)
# content = js.loads(f.read())
# gam.shapes.update({content['feature_name']: ShapeFunction(content['splits'],
# content['values'],
# content['feature_name'])})
#
# assert set(gam.shapes.keys()) == set(gam.feature_names), 'feature names and shape names do not match up'
# return gam
. Output only the next line. | func1 = ShapeFunction(_create_partition(np.linspace(1, 10, 10)), np.linspace(1, 10, 11), 'attr_1') |
Using the snippet: <|code_start|>cancer_ds = ds.load_breast_cancer()
data = cancer_ds['data'][:, :20]
labels = 2 * cancer_ds['target'] - 1
assert_scores = [
[0.5538394842641805, 0.44616051573581944],
[0.49861290044203543, 0.5013870995579646],
[0.5470227126670573, 0.4529772873329428],
[0.513940794277825, 0.48605920572217504],
[0.529758125364891, 0.470241874635109]
]
test_root_folder = '/tmp/test_gam_serialization'
def teardown():
if os.path.exists(test_root_folder):
shutil.rmtree(test_root_folder)
def test_gam_training():
gam = GAM(max_depth=3, max_leaf_nodes=5, random_state=42, balancer_seed=42)
gam.train(data, labels, n_iter=5, learning_rate=0.0025, num_bags=1, num_workers=3)
for idx, vec in enumerate(data[:5, :]):
gam_scores = gam.score(vec)
np.testing.assert_almost_equal(np.sum(gam_scores), 1.0, 10)
np.testing.assert_almost_equal(gam_scores, assert_scores[idx], 10)
def test_correct_scoring():
<|code_end|>
, determine the next line of code. You have imports:
from sklearn import datasets as ds
from DSTK.GAM.gam import GAM, ShapeFunction
from DSTK.tests.tests_gam.test_shape_function import _create_partition
from DSTK.GAM.base_gam import load_from_tar
import numpy as np
import os
import shutil
and context (class names, function names, or code) available:
# Path: DSTK/GAM/gam.py
# def _recurse(tree, feature_vec):
# def _get_sum_of_gamma_correction(tree, data, labels, class_weights, feature_name):
# def _get_shape_for_attribute(attribute_data, labels, class_weights, feature_name, criterion, splitter,
# max_depth, min_samples_split, min_samples_leaf, min_weight_fraction_leaf,
# max_features, random_state, max_leaf_nodes, presort):
# def __init__(self, **kwargs):
# def _get_metadata_dict(self):
# def _train_cost(self, data, labels):
# def _get_pseudo_responses(self, data, labels):
# def _init_shapes_and_data(self, data, labels):
# def _update_learning_rate(self, dct, epoch):
# def _initialize_class_weights(self, labels):
# def _get_class_weights(self, labels):
# def train(self, data, targets, **kwargs):
# def _get_trimmed_record_indices(self, responses):
# def _calculate_gradient_shape(self, data, labels, bag_indices=None, max_workers=1):
# def __init__(self, gam):
# def __getattr__(self, item):
# def smoothen(self, data, penalty=None):
# def _create_smooth_shape(shape, values, name, penalties):
# def _fit_spline(values, target_vals, penalties):
# class GAM(BaseGAM):
# class SmoothGAM(BaseGAM):
#
# Path: DSTK/tests/tests_gam/test_shape_function.py
# def _create_partition(lst_of_splits):
# return np.append(lst_of_splits, np.PINF)
#
# Path: DSTK/GAM/base_gam.py
# def load_from_tar(file_name):
#
# model_name = file_name.split('/')[-1].replace('.tar.gz', '')
#
# gam = DeserializedGAM()
#
# with tf.open(file_name, "r:gz") as tar:
# f = tar.extractfile('{}/{}.json'.format(model_name, model_name))
# content = js.loads(f.read())
# gam._n_features = content['num_features']
# gam.feature_names = content['feature_names']
#
# for member in tar.getmembers():
# if member.isfile() and (member.name != '{}/{}.json'.format(model_name, model_name)):
# f = tar.extractfile(member.path)
# content = js.loads(f.read())
# gam.shapes.update({content['feature_name']: ShapeFunction(content['splits'],
# content['values'],
# content['feature_name'])})
#
# assert set(gam.shapes.keys()) == set(gam.feature_names), 'feature names and shape names do not match up'
# return gam
. Output only the next line. | func1 = ShapeFunction(_create_partition(np.linspace(1, 10, 10)), np.linspace(1, 10, 11), 'attr_1') |
Given the following code snippet before the placeholder: <|code_start|>
for vec in data:
# the shape function cancel each other in their effect
# hence the exponent is zero and the probability 0.5
assert gam.logit_score(vec) == 0.5
assert gam.score(vec) == [0.2689414213699951, 0.7310585786300049]
def test_pseudo_response():
func1 = ShapeFunction(_create_partition([0]), [np.log(3), np.log(100)], 'attr_1')
gam = GAM(max_depth=3, max_leaf_nodes=5, random_state=42)
gam.shapes = {'attr_1': func1}
gam.feature_names = ['attr_1']
data = np.asarray([[-1], [1]])
pseudo_resp = gam._get_pseudo_responses(data, [1, -1])
np.testing.assert_almost_equal(pseudo_resp, [0.2, -1.9998],
decimal=6,
verbose=True,
err_msg="Pseudo Response doesn't match")
def test_serialization_deserialization():
gam = GAM(max_depth=3, max_leaf_nodes=5, random_state=42, balancer_seed=42)
gam.train(data, labels, n_iter=5, learning_rate=0.0025, num_bags=1, num_workers=3)
gam.serialize('gbt_gam', file_path='/tmp/test_gam_serialization')
<|code_end|>
, predict the next line using imports from the current file:
from sklearn import datasets as ds
from DSTK.GAM.gam import GAM, ShapeFunction
from DSTK.tests.tests_gam.test_shape_function import _create_partition
from DSTK.GAM.base_gam import load_from_tar
import numpy as np
import os
import shutil
and context including class names, function names, and sometimes code from other files:
# Path: DSTK/GAM/gam.py
# def _recurse(tree, feature_vec):
# def _get_sum_of_gamma_correction(tree, data, labels, class_weights, feature_name):
# def _get_shape_for_attribute(attribute_data, labels, class_weights, feature_name, criterion, splitter,
# max_depth, min_samples_split, min_samples_leaf, min_weight_fraction_leaf,
# max_features, random_state, max_leaf_nodes, presort):
# def __init__(self, **kwargs):
# def _get_metadata_dict(self):
# def _train_cost(self, data, labels):
# def _get_pseudo_responses(self, data, labels):
# def _init_shapes_and_data(self, data, labels):
# def _update_learning_rate(self, dct, epoch):
# def _initialize_class_weights(self, labels):
# def _get_class_weights(self, labels):
# def train(self, data, targets, **kwargs):
# def _get_trimmed_record_indices(self, responses):
# def _calculate_gradient_shape(self, data, labels, bag_indices=None, max_workers=1):
# def __init__(self, gam):
# def __getattr__(self, item):
# def smoothen(self, data, penalty=None):
# def _create_smooth_shape(shape, values, name, penalties):
# def _fit_spline(values, target_vals, penalties):
# class GAM(BaseGAM):
# class SmoothGAM(BaseGAM):
#
# Path: DSTK/tests/tests_gam/test_shape_function.py
# def _create_partition(lst_of_splits):
# return np.append(lst_of_splits, np.PINF)
#
# Path: DSTK/GAM/base_gam.py
# def load_from_tar(file_name):
#
# model_name = file_name.split('/')[-1].replace('.tar.gz', '')
#
# gam = DeserializedGAM()
#
# with tf.open(file_name, "r:gz") as tar:
# f = tar.extractfile('{}/{}.json'.format(model_name, model_name))
# content = js.loads(f.read())
# gam._n_features = content['num_features']
# gam.feature_names = content['feature_names']
#
# for member in tar.getmembers():
# if member.isfile() and (member.name != '{}/{}.json'.format(model_name, model_name)):
# f = tar.extractfile(member.path)
# content = js.loads(f.read())
# gam.shapes.update({content['feature_name']: ShapeFunction(content['splits'],
# content['values'],
# content['feature_name'])})
#
# assert set(gam.shapes.keys()) == set(gam.feature_names), 'feature names and shape names do not match up'
# return gam
. Output only the next line. | scoring_gam = load_from_tar('/tmp/test_gam_serialization/gbt_gam.tar.gz') |
Using the snippet: <|code_start|>
cancer_ds = ds.load_breast_cancer()
data = cancer_ds['data']
target = cancer_ds['target']
def test_recursion():
<|code_end|>
, determine the next line of code. You have imports:
import sklearn.datasets as ds
import numpy as np
from DSTK.FeatureBinning import decision_tree_binner as tfb
and context (class names, function names, or code) available:
# Path: DSTK/FeatureBinning/decision_tree_binner.py
# def _recurse_tree(tree, lst, mdlp, node_id=0, depth=0, min_val=np.NINF, max_val=np.PINF):
# def _convert_count_buckets_to_split_and_vals(sorted_nodes):
# def _check_mdlp_stop(tree, node_id):
# def _calculate_entropy(array):
# def _calculate_gain(tree, node_id):
# def _calculate_noise_delta(tree, node_id):
# def _get_variables_for_entropy_calculation(tree, node_id):
# def is_fit(self):
# def values(self):
# def splits(self):
# def is_fit(self, is_fit):
# def values(self, values):
# def splits(self, splits):
# def __init__(self, name, **kwargs):
# def fit(self, values, target):
# class DecisionTreeBinner(BaseBinner):
. Output only the next line. | binner = tfb.DecisionTreeBinner('test', max_leaf_nodes=4) |
Given the following code snippet before the placeholder: <|code_start|>
def test_special_values_filter():
vals = np.asarray([-1.0, 3.1, 11.3, 0.5, np.NaN, -1.0, 3.1])
special_vals = np.asarray([-1.0, np.NaN])
<|code_end|>
, predict the next line using imports from the current file:
import numpy as np
from DSTK.FeatureBinning._utils import _filter_special_values, _naive_bayes_bins
and context including class names, function names, and sometimes code from other files:
# Path: DSTK/FeatureBinning/_utils.py
# def _filter_special_values(values, filter_values):
# feats = np.array(values)
# filters = np.array(filter_values)
#
# special_vals_idx_dct = dict()
# for val in filters:
# if np.isnan(val):
# idx = np.where(np.isnan(feats))[0]
# else:
# idx = np.where(feats == val)[0]
#
# special_vals_idx_dct.update({str(val): idx})
#
# all_special_idx = list()
# for vals in special_vals_idx_dct.values():
# all_special_idx += vals.tolist()
#
# all_special_idx = np.asarray(all_special_idx)
# all_idx = np.arange(0, len(feats), 1, dtype=int)
# all_non_special_idx = [idx for idx in all_idx if idx not in all_special_idx]
# special_vals_idx_dct.update({'regular': all_non_special_idx})
#
# return special_vals_idx_dct
#
# def _naive_bayes_bins(target, prior, num_classes=2):
# if len(target) > 1:
# cnts = np.bincount(target, minlength=num_classes)
# return list(cnts / cnts.sum())
# else:
# return [1 - prior, prior]
. Output only the next line. | idx_dct = _filter_special_values(vals, special_vals) |
Here is a snippet: <|code_start|>
def test_special_values_filter():
vals = np.asarray([-1.0, 3.1, 11.3, 0.5, np.NaN, -1.0, 3.1])
special_vals = np.asarray([-1.0, np.NaN])
idx_dct = _filter_special_values(vals, special_vals)
np.testing.assert_equal(idx_dct[str(np.NaN)], [4])
np.testing.assert_equal(idx_dct[str(-1.0)], [0, 5])
np.testing.assert_equal(idx_dct['regular'], [1, 2, 3, 6])
def test_special_values_filter_2():
vals = np.asarray([-1.0, 3.1, 11.3, 0.5, np.NaN, -1.0, 3.1])
special_vals = np.asarray([np.NaN])
idx_dct = _filter_special_values(vals, special_vals)
np.testing.assert_equal(idx_dct[str(np.NaN)], [4])
np.testing.assert_equal(idx_dct['regular'], [0, 1, 2, 3, 5, 6])
def test_naive_bayes_bin():
target = np.asarray([0, 1, 1, 1, 0, 1, 0, 1, 1, 1])
mean = target.mean()
<|code_end|>
. Write the next line using the current file imports:
import numpy as np
from DSTK.FeatureBinning._utils import _filter_special_values, _naive_bayes_bins
and context from other files:
# Path: DSTK/FeatureBinning/_utils.py
# def _filter_special_values(values, filter_values):
# feats = np.array(values)
# filters = np.array(filter_values)
#
# special_vals_idx_dct = dict()
# for val in filters:
# if np.isnan(val):
# idx = np.where(np.isnan(feats))[0]
# else:
# idx = np.where(feats == val)[0]
#
# special_vals_idx_dct.update({str(val): idx})
#
# all_special_idx = list()
# for vals in special_vals_idx_dct.values():
# all_special_idx += vals.tolist()
#
# all_special_idx = np.asarray(all_special_idx)
# all_idx = np.arange(0, len(feats), 1, dtype=int)
# all_non_special_idx = [idx for idx in all_idx if idx not in all_special_idx]
# special_vals_idx_dct.update({'regular': all_non_special_idx})
#
# return special_vals_idx_dct
#
# def _naive_bayes_bins(target, prior, num_classes=2):
# if len(target) > 1:
# cnts = np.bincount(target, minlength=num_classes)
# return list(cnts / cnts.sum())
# else:
# return [1 - prior, prior]
, which may include functions, classes, or code. Output only the next line. | np.testing.assert_almost_equal(_naive_bayes_bins(target, 0.5, num_classes=2), [1-mean, mean], decimal=10) |
Given the code snippet: <|code_start|> for v in val:
_hex.append( v.encode('hex') )
if v in printable:
_val += v
else:
_val += '.'
return (' '.join(_hex), _val)
# callback for tracing instructions
def hook_code(uc, address, size, user_data):
# end of shellcode
if address > g_code_base + g_sc_len:
uc.emu_stop()
# callback for interrupt
def hook_intr(uc, intno, user_data):
global g_before_pc
reg_dump(uc, True)
_print_reg = ''
if g_uc_arch == UC_ARCH_ARM64:
_print_reg = 'X'
syscall_no = get_reg( uc, UC_ARM64_REG_X8 )
syscall_name = arm64_syscall.get( syscall_no )
PC = get_reg( uc, UC_ARM64_REG_PC )
else:
_print_reg = 'R'
syscall_no = get_reg( uc, UC_ARM_REG_R7 )
PC = get_reg( uc, UC_ARM_REG_PC )
if g_uc_mode == UC_MODE_THUMB:
<|code_end|>
, generate the next line using the imports in this file:
from optparse import OptionParser
from unicorn import *
from unicorn.arm_const import *
from unicorn.arm64_const import *
from capstone import *
from capstone.arm import *
from struct import unpack
from ARMSCGen import *
from shellcodes.thumb import syscall as th_syscall
from shellcodes.arm import syscall as arm_syscall
from shellcodes.arm64 import syscall as arm64_syscall
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import TerminalFormatter
import os, sys
and context (functions, classes, or occasionally code) from other files:
# Path: shellcodes/thumb/syscall.py
# def get(no):
#
# Path: shellcodes/arm/syscall.py
# def get(no):
#
# Path: shellcodes/arm64/syscall.py
# def get(no):
. Output only the next line. | syscall_name = th_syscall.get( syscall_no ) |
Next line prediction: <|code_start|> if v in printable:
_val += v
else:
_val += '.'
return (' '.join(_hex), _val)
# callback for tracing instructions
def hook_code(uc, address, size, user_data):
# end of shellcode
if address > g_code_base + g_sc_len:
uc.emu_stop()
# callback for interrupt
def hook_intr(uc, intno, user_data):
global g_before_pc
reg_dump(uc, True)
_print_reg = ''
if g_uc_arch == UC_ARCH_ARM64:
_print_reg = 'X'
syscall_no = get_reg( uc, UC_ARM64_REG_X8 )
syscall_name = arm64_syscall.get( syscall_no )
PC = get_reg( uc, UC_ARM64_REG_PC )
else:
_print_reg = 'R'
syscall_no = get_reg( uc, UC_ARM_REG_R7 )
PC = get_reg( uc, UC_ARM_REG_PC )
if g_uc_mode == UC_MODE_THUMB:
syscall_name = th_syscall.get( syscall_no )
else:
<|code_end|>
. Use current file imports:
(from optparse import OptionParser
from unicorn import *
from unicorn.arm_const import *
from unicorn.arm64_const import *
from capstone import *
from capstone.arm import *
from struct import unpack
from ARMSCGen import *
from shellcodes.thumb import syscall as th_syscall
from shellcodes.arm import syscall as arm_syscall
from shellcodes.arm64 import syscall as arm64_syscall
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import TerminalFormatter
import os, sys)
and context including class names, function names, or small code snippets from other files:
# Path: shellcodes/thumb/syscall.py
# def get(no):
#
# Path: shellcodes/arm/syscall.py
# def get(no):
#
# Path: shellcodes/arm64/syscall.py
# def get(no):
. Output only the next line. | syscall_name = arm_syscall.get( syscall_no ) |
Given snippet: <|code_start|> if val == 0:
return ""
if isinstance(val, bytearray):
val = str(val)
_hex = []
_val = ''
for v in val:
_hex.append( v.encode('hex') )
if v in printable:
_val += v
else:
_val += '.'
return (' '.join(_hex), _val)
# callback for tracing instructions
def hook_code(uc, address, size, user_data):
# end of shellcode
if address > g_code_base + g_sc_len:
uc.emu_stop()
# callback for interrupt
def hook_intr(uc, intno, user_data):
global g_before_pc
reg_dump(uc, True)
_print_reg = ''
if g_uc_arch == UC_ARCH_ARM64:
_print_reg = 'X'
syscall_no = get_reg( uc, UC_ARM64_REG_X8 )
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from optparse import OptionParser
from unicorn import *
from unicorn.arm_const import *
from unicorn.arm64_const import *
from capstone import *
from capstone.arm import *
from struct import unpack
from ARMSCGen import *
from shellcodes.thumb import syscall as th_syscall
from shellcodes.arm import syscall as arm_syscall
from shellcodes.arm64 import syscall as arm64_syscall
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import TerminalFormatter
import os, sys
and context:
# Path: shellcodes/thumb/syscall.py
# def get(no):
#
# Path: shellcodes/arm/syscall.py
# def get(no):
#
# Path: shellcodes/arm64/syscall.py
# def get(no):
which might include code, classes, or functions. Output only the next line. | syscall_name = arm64_syscall.get( syscall_no ) |
Given snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
compliance_checker/tests/test_util.py
"""
class TestUtils(unittest.TestCase):
"""
Test suite for utilities
"""
def test_datetime_is_iso(self):
"""
Test that ISO 8601 dates are properly parsed, and non ISO 8601 dates
are excluded
"""
good_datetime = "2011-01-21T02:30:11Z"
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
from compliance_checker import util
and context:
# Path: compliance_checker/util.py
# def datetime_is_iso(date_str):
# def dateparse(date_str):
# def kvp_convert(input_coll):
which might include code, classes, or functions. Output only the next line. | self.assertTrue(util.datetime_is_iso(good_datetime)[0]) |
Given the following code snippet before the placeholder: <|code_start|>
assert os.stat(tmp_txt_file).st_size > 0
def test_single_json_output(self, tmp_txt_file):
"""
Tests that a suite can produce JSON output to a file
"""
return_value, errors = ComplianceChecker.run_checker(
ds_loc=static_files("conv_bad"),
verbose=0,
criteria="strict",
checker_names=["cf"],
output_filename=tmp_txt_file,
output_format="json",
)
assert os.stat(tmp_txt_file).st_size > 0
with open(tmp_txt_file) as f:
r = json.load(f)
assert "cf" in r
def test_list_checks(self):
"""
Tests listing of both old-style, deprecated checkers using .name
attributes, and newer ones which use ._cc_spec and _cc_spec_version
attributes
"""
# hack: use argparse.Namespace to mock checker object with attributes
# since SimpleNamespace is Python 3.3+ only
<|code_end|>
, predict the next line using imports from the current file:
import io
import json
import os
import sys
import pytest
from argparse import Namespace
from compliance_checker.runner import CheckSuite, ComplianceChecker
from .conftest import static_files
and context including class names, function names, and sometimes code from other files:
# Path: compliance_checker/runner.py
# def stdout_redirector(stream):
# def run_checker(
# cls,
# ds_loc,
# checker_names,
# verbose,
# criteria,
# skip_checks=None,
# include_checks=None,
# output_filename="-",
# output_format=["text"],
# options=None,
# ):
# def stdout_output(cls, cs, score_dict, verbose, limit):
# def html_output(cls, cs, score_dict, output_filename, ds_loc, limit):
# def json_output(
# cls, cs, score_dict, output_filename, ds_loc, limit, output_type="json"
# ):
# def check_errors(cls, score_groups, verbose):
# class ComplianceChecker(object):
#
# Path: compliance_checker/tests/conftest.py
# def static_files(cdl_stem):
# """
# Returns the Path to a valid nc dataset\n
# replaces the old STATIC_FILES dict
# """
# datadir = Path(resource_filename("compliance_checker", "tests/data")).resolve()
# assert datadir.exists(), f"{datadir} not found"
#
# cdl_paths = glob_down(datadir, f"{cdl_stem}.cdl", 3)
# assert (
# len(cdl_paths) > 0
# ), f"No file named {cdl_stem}.cdl found in {datadir} or its subfolders"
# assert (
# len(cdl_paths) == 1
# ), f"Multiple candidates found with the name {cdl_stem}.cdl:\n{cdl_paths}\nPlease reconcile naming conflict"
# cdl_path = cdl_paths[0] # PurePath object
#
# nc_path = cdl_path.parent / f"{cdl_path.stem}.nc"
# if not nc_path.exists():
# generate_dataset(cdl_path, nc_path)
# assert (
# nc_path.exists()
# ), f"ncgen CLI utility failed to produce {nc_path} from {cdl_path}"
# return str(nc_path)
. Output only the next line. | CheckSuite.checkers.clear() |
Here is a snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Tests for command line output and parsing
"""
@pytest.mark.usefixtures("checksuite_setup")
class TestCLI:
"""
Tests various functions and aspects of the command line tool and runner
"""
def shortDescription(self):
return None
def test_unicode_acdd_html(self, tmp_txt_file):
"""
Tests that the checker is capable of producing HTML with unicode characters
"""
<|code_end|>
. Write the next line using the current file imports:
import io
import json
import os
import sys
import pytest
from argparse import Namespace
from compliance_checker.runner import CheckSuite, ComplianceChecker
from .conftest import static_files
and context from other files:
# Path: compliance_checker/runner.py
# def stdout_redirector(stream):
# def run_checker(
# cls,
# ds_loc,
# checker_names,
# verbose,
# criteria,
# skip_checks=None,
# include_checks=None,
# output_filename="-",
# output_format=["text"],
# options=None,
# ):
# def stdout_output(cls, cs, score_dict, verbose, limit):
# def html_output(cls, cs, score_dict, output_filename, ds_loc, limit):
# def json_output(
# cls, cs, score_dict, output_filename, ds_loc, limit, output_type="json"
# ):
# def check_errors(cls, score_groups, verbose):
# class ComplianceChecker(object):
#
# Path: compliance_checker/tests/conftest.py
# def static_files(cdl_stem):
# """
# Returns the Path to a valid nc dataset\n
# replaces the old STATIC_FILES dict
# """
# datadir = Path(resource_filename("compliance_checker", "tests/data")).resolve()
# assert datadir.exists(), f"{datadir} not found"
#
# cdl_paths = glob_down(datadir, f"{cdl_stem}.cdl", 3)
# assert (
# len(cdl_paths) > 0
# ), f"No file named {cdl_stem}.cdl found in {datadir} or its subfolders"
# assert (
# len(cdl_paths) == 1
# ), f"Multiple candidates found with the name {cdl_stem}.cdl:\n{cdl_paths}\nPlease reconcile naming conflict"
# cdl_path = cdl_paths[0] # PurePath object
#
# nc_path = cdl_path.parent / f"{cdl_path.stem}.nc"
# if not nc_path.exists():
# generate_dataset(cdl_path, nc_path)
# assert (
# nc_path.exists()
# ), f"ncgen CLI utility failed to produce {nc_path} from {cdl_path}"
# return str(nc_path)
, which may include functions, classes, or code. Output only the next line. | return_value, errors = ComplianceChecker.run_checker( |
Given snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Tests for command line output and parsing
"""
@pytest.mark.usefixtures("checksuite_setup")
class TestCLI:
"""
Tests various functions and aspects of the command line tool and runner
"""
def shortDescription(self):
return None
def test_unicode_acdd_html(self, tmp_txt_file):
"""
Tests that the checker is capable of producing HTML with unicode characters
"""
return_value, errors = ComplianceChecker.run_checker(
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import io
import json
import os
import sys
import pytest
from argparse import Namespace
from compliance_checker.runner import CheckSuite, ComplianceChecker
from .conftest import static_files
and context:
# Path: compliance_checker/runner.py
# def stdout_redirector(stream):
# def run_checker(
# cls,
# ds_loc,
# checker_names,
# verbose,
# criteria,
# skip_checks=None,
# include_checks=None,
# output_filename="-",
# output_format=["text"],
# options=None,
# ):
# def stdout_output(cls, cs, score_dict, verbose, limit):
# def html_output(cls, cs, score_dict, output_filename, ds_loc, limit):
# def json_output(
# cls, cs, score_dict, output_filename, ds_loc, limit, output_type="json"
# ):
# def check_errors(cls, score_groups, verbose):
# class ComplianceChecker(object):
#
# Path: compliance_checker/tests/conftest.py
# def static_files(cdl_stem):
# """
# Returns the Path to a valid nc dataset\n
# replaces the old STATIC_FILES dict
# """
# datadir = Path(resource_filename("compliance_checker", "tests/data")).resolve()
# assert datadir.exists(), f"{datadir} not found"
#
# cdl_paths = glob_down(datadir, f"{cdl_stem}.cdl", 3)
# assert (
# len(cdl_paths) > 0
# ), f"No file named {cdl_stem}.cdl found in {datadir} or its subfolders"
# assert (
# len(cdl_paths) == 1
# ), f"Multiple candidates found with the name {cdl_stem}.cdl:\n{cdl_paths}\nPlease reconcile naming conflict"
# cdl_path = cdl_paths[0] # PurePath object
#
# nc_path = cdl_path.parent / f"{cdl_path.stem}.nc"
# if not nc_path.exists():
# generate_dataset(cdl_path, nc_path)
# assert (
# nc_path.exists()
# ), f"ncgen CLI utility failed to produce {nc_path} from {cdl_path}"
# return str(nc_path)
which might include code, classes, or functions. Output only the next line. | ds_loc=static_files("2dim"), |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for base compliance checker class"""
class TestBase(TestCase):
"""
Tests functionality of the base compliance checker class
"""
def setUp(self):
<|code_end|>
with the help of current file imports:
import os
from unittest import TestCase
from netCDF4 import Dataset
from compliance_checker import base
and context from other files:
# Path: compliance_checker/base.py
# def get_namespaces():
# def csv_splitter(input_string):
# def __init__(self, split_func=None):
# def validator_func(self, input_value):
# def validate(self, input_name, input_value):
# def validate_type(self, input_name, input_value):
# def validator_func(self, input_value):
# def validator_func(self, input_value):
# def validator_func(self, input_value):
# def __init__(self, fpath):
# def filepath(self):
# def setup(self, ds):
# def __init__(self, options=None):
# def get_test_ctx(self, severity, name, variable=None):
# def __del__(self):
# def std_check_in(cls, dataset, name, allowed_vals):
# def std_check(cls, dataset, name):
# def __init__(
# self,
# weight=BaseCheck.MEDIUM,
# value=None,
# name=None,
# msgs=None,
# children=None,
# checker=None,
# check_method=None,
# variable_name=None,
# ):
# def __repr__(self):
# def serialize(self):
# def __eq__(self, other):
# def __init__(
# self,
# category=None,
# description="",
# out_of=0,
# score=0,
# messages=None,
# variable=None,
# ):
# def to_result(self):
# def assert_true(self, test, message):
# def add_failure(self, message):
# def add_pass(self):
# def std_check_in(base_context, name, allowed_vals):
# def std_check(dataset, name):
# def xpath_check(tree, xpath):
# def maybe_get_global_attr(attr_name, ds):
# def attr_check(kvp, ds, priority, ret_val, gname=None, var_name=None):
# def check_has(priority=BaseCheck.HIGH, gname=None):
# def _inner(func):
# def _dec(s, ds):
# def fix_return_value(v, method_name, method=None, checker=None):
# def ratable_result(value, name, msgs, variable_name=None):
# def score_group(group_name=None):
# def _inner(func):
# def _dec(s, ds):
# def dogroup(r):
# class ValidationObject(object):
# class EmailValidator(ValidationObject):
# class RegexValidator(ValidationObject):
# class UrlValidator(ValidationObject):
# class GenericFile(object):
# class BaseCheck(object):
# class BaseNCCheck(object):
# class BaseSOSGCCheck(object):
# class BaseSOSDSCheck(object):
# class Result(object):
# class TestCtx(object):
# HIGH = 3
# MEDIUM = 2
# LOW = 1
, which may contain function names, class names, or code. Output only the next line. | self.acdd = base.BaseCheck() |
Predict the next line for this snippet: <|code_start|># Copyright 2022 The Deluca Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class PIDState(Obj):
P: float = field(0.0, jaxed=True)
I: float = field(0.0, jaxed=True)
D: float = field(0.0, jaxed=True)
<|code_end|>
with the help of current file imports:
from deluca.core import Agent
from deluca.core import field
from deluca.core import Obj
and context from other files:
# Path: deluca/core.py
# class Agent(Obj):
#
# @abstractmethod
# def __call__(self, state, obs, *args, **kwargs):
# """Return an updated state"""
#
# def init(self):
# return AgentState()
#
# Path: deluca/core.py
# def field(default=None, jaxed=True, **kwargs):
# if "default_factory" not in kwargs:
# kwargs["default"] = default
# kwargs["pytree_node"] = jaxed
# return flax.struct.field(**kwargs)
#
# Path: deluca/core.py
# class Obj:
#
# def freeze(self):
# object.__setattr__(self, "__frozen__", True)
#
# def unfreeze(self):
# object.__setattr__(self, "__frozen__", False)
#
# def is_frozen(self):
# return not hasattr(self, "__frozen__") or getattr(self, "__frozen__")
#
# def __new__(cls, *args, **kwargs):
# """A true bastardization of __new__..."""
#
# def __setattr__(self, name, value):
# if self.is_frozen():
# raise dataclasses.FrozenInstanceError
# object.__setattr__(self, name, value)
#
# def replace(self, **updates):
# obj = dataclasses.replace(self, **updates)
# obj.freeze()
# return obj
#
# cls.__setattr__ = __setattr__
# cls.replace = replace
#
# obj = object.__new__(cls)
# obj.unfreeze()
#
# return obj
#
# @classmethod
# def __init_subclass__(cls, *args, **kwargs):
# flax.struct.dataclass(cls)
#
# @classmethod
# def create(cls, *args, **kwargs):
# # NOTE: Oh boy, this is so janky
# obj = cls(*args, **kwargs)
# obj.setup()
# obj.freeze()
#
# return obj
#
# @classmethod
# def unflatten(cls, treedef, leaves):
# """Expost a default unflatten method"""
# return jax.tree_util.tree_unflatten(treedef, leaves)
#
# def setup(self):
# """Used in place of __init__"""
#
# def flatten(self):
# """Expose a default flatten method"""
# return jax.tree_util.tree_flatten(self)[0]
, which may contain function names, class names, or code. Output only the next line. | class PID(Agent): |
Given the code snippet: <|code_start|># Copyright 2022 The Deluca Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""predestined controller."""
class Predestined(Controller):
"""predestined controller."""
time: float = deluca.field(jaxed=False)
steps: int = deluca.field(jaxed=False)
dt: float = deluca.field(jaxed=False)
u_ins: jnp.array = deluca.field(jaxed=False)
def __call__(self, state, obs, *args, **kwargs):
action = jax.lax.dynamic_slice(self.u_ins, (state.steps.astype(int),), (1,))
time = obs.time
<|code_end|>
, generate the next line using the imports in this file:
import deluca
import jax
import jax.numpy as jnp
from deluca.lung.core import Controller
from deluca.lung.core import DEFAULT_DT
from deluca.lung.core import proper_time
and context (functions, classes, or occasionally code) from other files:
# Path: deluca/lung/core.py
# class Controller(deluca.Agent):
# """Controller."""
#
# def init(self, waveform=None):
# if waveform is None:
# waveform = BreathWaveform.create()
# return ControllerState()
#
# @property
# def max(self):
# return 100
#
# @property
# def min(self):
# return 0
#
# def decay(self, waveform, t):
# elapsed = waveform.elapsed(t)
#
# def false_func():
# result = jax.lax.cond(
# elapsed < waveform.xp[waveform.ex_bounds[0]], lambda x: 0.0,
# lambda x: 5 * (1 - jnp.exp(5 * (waveform.xp[waveform.ex_bounds[
# 0]] - elapsed))).astype(waveform.dtype), None)
# return result
#
# # float(inf) as substitute to None since cond requries same type output
# result = jax.lax.cond(elapsed < waveform.xp[waveform.in_bounds[1]],
# lambda x: float("inf"), lambda x: false_func(), None)
# return result
#
# Path: deluca/lung/core.py
# DEFAULT_DT = 0.03
#
# Path: deluca/lung/core.py
# def proper_time(t):
# return jax.lax.cond(t == float("inf"), lambda x: 0., lambda x: x, t)
. Output only the next line. | new_dt = jnp.max(jnp.array([DEFAULT_DT, time - proper_time(state.time)])) |
Here is a snippet: <|code_start|># Copyright 2022 The Deluca Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""predestined controller."""
class Predestined(Controller):
"""predestined controller."""
time: float = deluca.field(jaxed=False)
steps: int = deluca.field(jaxed=False)
dt: float = deluca.field(jaxed=False)
u_ins: jnp.array = deluca.field(jaxed=False)
def __call__(self, state, obs, *args, **kwargs):
action = jax.lax.dynamic_slice(self.u_ins, (state.steps.astype(int),), (1,))
time = obs.time
<|code_end|>
. Write the next line using the current file imports:
import deluca
import jax
import jax.numpy as jnp
from deluca.lung.core import Controller
from deluca.lung.core import DEFAULT_DT
from deluca.lung.core import proper_time
and context from other files:
# Path: deluca/lung/core.py
# class Controller(deluca.Agent):
# """Controller."""
#
# def init(self, waveform=None):
# if waveform is None:
# waveform = BreathWaveform.create()
# return ControllerState()
#
# @property
# def max(self):
# return 100
#
# @property
# def min(self):
# return 0
#
# def decay(self, waveform, t):
# elapsed = waveform.elapsed(t)
#
# def false_func():
# result = jax.lax.cond(
# elapsed < waveform.xp[waveform.ex_bounds[0]], lambda x: 0.0,
# lambda x: 5 * (1 - jnp.exp(5 * (waveform.xp[waveform.ex_bounds[
# 0]] - elapsed))).astype(waveform.dtype), None)
# return result
#
# # float(inf) as substitute to None since cond requries same type output
# result = jax.lax.cond(elapsed < waveform.xp[waveform.in_bounds[1]],
# lambda x: float("inf"), lambda x: false_func(), None)
# return result
#
# Path: deluca/lung/core.py
# DEFAULT_DT = 0.03
#
# Path: deluca/lung/core.py
# def proper_time(t):
# return jax.lax.cond(t == float("inf"), lambda x: 0., lambda x: x, t)
, which may include functions, classes, or code. Output only the next line. | new_dt = jnp.max(jnp.array([DEFAULT_DT, time - proper_time(state.time)])) |
Continue the code snippet: <|code_start|> """
Description: Initialize the dynamics of the model.
Args:
A (jnp.ndarray): system dynamics
B (jnp.ndarray): system dynamics
Q (jnp.ndarray): cost matrices (i.e. cost = x^TQx + u^TRu)
R (jnp.ndarray): cost matrices (i.e. cost = x^TQx + u^TRu)
K (jnp.ndarray): Starting policy (optional). Defaults to LQR gain.
start_time (int):
H (postive int): history of the controller
lr_scale (Real):
decay (boolean):
"""
self.d_state, self.d_action = B.shape # State & Action Dimensions
self.A, self.B = A, B # System Dynamics
self.t = 0 # Time Counter (for decaying learning rate)
self.H = H
self.lr_scale, self.decay = lr_scale, decay
self.delta = delta
# Model Parameters
# initial linear policy / perturbation contributions / bias
# TODO: need to address problem of LQR with jax.lax.scan
<|code_end|>
. Use current file imports:
from numbers import Real
from deluca.agents._lqr import LQR
from deluca.agents.core import Agent
import jax.numpy as jnp
import numpy as np
import numpy.random as random
and context (classes, functions, or code) from other files:
# Path: deluca/agents/_lqr.py
# class LQR(Agent):
# """
# LQR
# """
#
# # TODO: need to address problem of LQR with jax.lax.scan
#
# def __init__(
# self, A: jnp.ndarray, B: jnp.ndarray, Q: jnp.ndarray = None, R: jnp.ndarray = None
# ) -> None:
# """
# Description: Initialize the infinite-time horizon LQR.
# Args:
# A (jnp.ndarray): system dynamics
# B (jnp.ndarray): system dynamics
# Q (jnp.ndarray): cost matrices (i.e. cost = x^TQx + u^TRu)
# R (jnp.ndarray): cost matrices (i.e. cost = x^TQx + u^TRu)
#
# Returns:
# None
# """
#
# state_size, action_size = B.shape
#
# if Q is None:
# Q = jnp.identity(state_size, dtype=jnp.float32)
#
# if R is None:
# R = jnp.identity(action_size, dtype=jnp.float32)
#
# # solve the ricatti equation
# X = dare(A, B, Q, R)
#
# # compute LQR gain
# self.K = jnp.linalg.inv(B.T @ X @ B + R) @ (B.T @ X @ A)
#
# def __call__(self, state) -> jnp.ndarray:
# """
# Description: Return the action based on current state and internal parameters.
#
# Args:
# state (float/numpy.ndarray): current state
#
# Returns:
# jnp.ndarray: action to take
# """
# return -self.K @ state
. Output only the next line. | self.K = K if K is not None else LQR(self.A, self.B, Q, R).K |
Using the snippet: <|code_start|>"""Tests for breath_dataset."""
class BreathDatasetTest(chex.TestCase):
def setUp(self):
super().setUp()
result = {}
u_in = jnp.array([1 for i in range(29)] +
[0 for i in range(29)] +
[1 for i in range(29)] + [0])
u_out = jnp.array([0 for i in range(29)] +
[1 for i in range(29)] +
[0 for i in range(29)] + [1])
pressure = jnp.array([1 for i in range(29)] +
[0 for i in range(29)] +
[1 for i in range(29)] + [0])
target = jnp.array([1 for i in range(29)] +
[0 for i in range(29)] +
[1 for i in range(29)] + [0])
timeseries = {
'timestamp': jnp.array([0.03 * i for i in range(88)]),
'pressure': pressure,
'flow': jnp.array([0 for i in range(88)]),
'target': target,
'u_in': u_in,
'u_out': u_out
}
result['timeseries'] = timeseries
paths = [result for i in range(10)]
<|code_end|>
, determine the next line of code. You have imports:
from absl.testing import absltest
from deluca.lung.utils.data.breath_dataset import BreathDataset
from deluca.lung.utils.data.breath_dataset import get_initial_pressure
from deluca.lung.utils.data.breath_dataset import get_shuffled_and_batched_data
import chex
import jax
import jax.numpy as jnp
and context (class names, function names, or code) available:
# Path: deluca/lung/utils/data/breath_dataset.py
# class BreathDataset:
# """dataset for breaths."""
#
# @classmethod
# def from_paths(
# cls,
# paths,
# seed=0,
# clip=(0, None), # used to be (2, -1)
# breath_length=29,
# keys=["train", "test"],
# splits=[0.9, 0.1],
# fit_scaler_key="train",
# ):
# """process data from paths."""
# obj = object.__new__(cls)
# raw_data = []
#
# for path in paths:
# analyzer = Analyzer(path)
# raw_data += analyzer.get_breaths(clip=clip, breath_length=breath_length)
#
# # Shuffle and split raw_data
# rng = np.random.default_rng(seed)
# splits = (np.array(splits) / np.sum(splits) *
# len(raw_data)).astype("int")[:-1]
# rng.shuffle(raw_data)
# obj.splits = {
# key: val for key, val in zip(keys, np.split(raw_data, splits))
# }
#
# # Compute mean, std for u_in and pressure
# obj.u_normalizer = ShiftScaleTransform(
# jnp.array([u for u, p in obj.splits[fit_scaler_key]]))
# print(f"u_in: mean={obj.u_normalizer.mean}, std={obj.u_normalizer.std}")
# obj.p_normalizer = ShiftScaleTransform(
# jnp.array([p for u, p in obj.splits[fit_scaler_key]]))
# print(f"pressure: mean={obj.p_normalizer.mean}, std={obj.p_normalizer.std}")
#
# obj.data = {}
# for key in keys:
# obj.data[key] = (jnp.array([u for u, p in obj.splits[key]]),
# jnp.array([p for u, p in obj.splits[key]]))
# return obj
#
# Path: deluca/lung/utils/data/breath_dataset.py
# def get_initial_pressure(dataset, key):
# return jnp.array([dataset.p_normalizer(p[0]) for u, p in dataset.splits[key]
# ]).mean().item()
#
# Path: deluca/lung/utils/data/breath_dataset.py
# def get_shuffled_and_batched_data(dataset, batch_size, key, prng_key):
# """function to shuffle and batch data."""
# x, y = dataset.data[key]
# x = jax.random.permutation(prng_key, x)
# y = jax.random.permutation(prng_key, y)
# prng_key, _ = jax.random.split(prng_key)
# num_batches = x.shape[0] // batch_size
# trunc_len = num_batches * batch_size
# trunc_x = x[:trunc_len]
# trunc_y = y[:trunc_len]
# batched_x = jnp.reshape(trunc_x, (num_batches, batch_size, trunc_x.shape[1]))
# batched_y = jnp.reshape(trunc_y, (num_batches, batch_size, trunc_y.shape[1]))
# return batched_x, batched_y, prng_key
. Output only the next line. | self.dataset = BreathDataset.from_paths(paths, clip=(0, None)) |
Here is a snippet: <|code_start|> [0 for i in range(29)] +
[1 for i in range(29)] + [0])
target = jnp.array([1 for i in range(29)] +
[0 for i in range(29)] +
[1 for i in range(29)] + [0])
timeseries = {
'timestamp': jnp.array([0.03 * i for i in range(88)]),
'pressure': pressure,
'flow': jnp.array([0 for i in range(88)]),
'target': target,
'u_in': u_in,
'u_out': u_out
}
result['timeseries'] = timeseries
paths = [result for i in range(10)]
self.dataset = BreathDataset.from_paths(paths, clip=(0, None))
def test_get_shuffled_and_batched_data(self):
prng_key = jax.random.PRNGKey(0)
batch_size = 2
x, y, prng_key = get_shuffled_and_batched_data(
self.dataset, batch_size, 'train', prng_key)
u_in = jnp.array([1 for i in range(29)])
p = jnp.array([1 for i in range(29)])
self.assertEqual(x.shape, (9, 2, 29))
self.assertEqual(y.shape, (9, 2, 29))
assert jnp.allclose(u_in, x[0, 0])
assert jnp.allclose(p, y[0, 0])
def test_get_initial_pressure(self):
<|code_end|>
. Write the next line using the current file imports:
from absl.testing import absltest
from deluca.lung.utils.data.breath_dataset import BreathDataset
from deluca.lung.utils.data.breath_dataset import get_initial_pressure
from deluca.lung.utils.data.breath_dataset import get_shuffled_and_batched_data
import chex
import jax
import jax.numpy as jnp
and context from other files:
# Path: deluca/lung/utils/data/breath_dataset.py
# class BreathDataset:
# """dataset for breaths."""
#
# @classmethod
# def from_paths(
# cls,
# paths,
# seed=0,
# clip=(0, None), # used to be (2, -1)
# breath_length=29,
# keys=["train", "test"],
# splits=[0.9, 0.1],
# fit_scaler_key="train",
# ):
# """process data from paths."""
# obj = object.__new__(cls)
# raw_data = []
#
# for path in paths:
# analyzer = Analyzer(path)
# raw_data += analyzer.get_breaths(clip=clip, breath_length=breath_length)
#
# # Shuffle and split raw_data
# rng = np.random.default_rng(seed)
# splits = (np.array(splits) / np.sum(splits) *
# len(raw_data)).astype("int")[:-1]
# rng.shuffle(raw_data)
# obj.splits = {
# key: val for key, val in zip(keys, np.split(raw_data, splits))
# }
#
# # Compute mean, std for u_in and pressure
# obj.u_normalizer = ShiftScaleTransform(
# jnp.array([u for u, p in obj.splits[fit_scaler_key]]))
# print(f"u_in: mean={obj.u_normalizer.mean}, std={obj.u_normalizer.std}")
# obj.p_normalizer = ShiftScaleTransform(
# jnp.array([p for u, p in obj.splits[fit_scaler_key]]))
# print(f"pressure: mean={obj.p_normalizer.mean}, std={obj.p_normalizer.std}")
#
# obj.data = {}
# for key in keys:
# obj.data[key] = (jnp.array([u for u, p in obj.splits[key]]),
# jnp.array([p for u, p in obj.splits[key]]))
# return obj
#
# Path: deluca/lung/utils/data/breath_dataset.py
# def get_initial_pressure(dataset, key):
# return jnp.array([dataset.p_normalizer(p[0]) for u, p in dataset.splits[key]
# ]).mean().item()
#
# Path: deluca/lung/utils/data/breath_dataset.py
# def get_shuffled_and_batched_data(dataset, batch_size, key, prng_key):
# """function to shuffle and batch data."""
# x, y = dataset.data[key]
# x = jax.random.permutation(prng_key, x)
# y = jax.random.permutation(prng_key, y)
# prng_key, _ = jax.random.split(prng_key)
# num_batches = x.shape[0] // batch_size
# trunc_len = num_batches * batch_size
# trunc_x = x[:trunc_len]
# trunc_y = y[:trunc_len]
# batched_x = jnp.reshape(trunc_x, (num_batches, batch_size, trunc_x.shape[1]))
# batched_y = jnp.reshape(trunc_y, (num_batches, batch_size, trunc_y.shape[1]))
# return batched_x, batched_y, prng_key
, which may include functions, classes, or code. Output only the next line. | p_0 = get_initial_pressure(self.dataset, 'train') |
Based on the snippet: <|code_start|> def setUp(self):
super().setUp()
result = {}
u_in = jnp.array([1 for i in range(29)] +
[0 for i in range(29)] +
[1 for i in range(29)] + [0])
u_out = jnp.array([0 for i in range(29)] +
[1 for i in range(29)] +
[0 for i in range(29)] + [1])
pressure = jnp.array([1 for i in range(29)] +
[0 for i in range(29)] +
[1 for i in range(29)] + [0])
target = jnp.array([1 for i in range(29)] +
[0 for i in range(29)] +
[1 for i in range(29)] + [0])
timeseries = {
'timestamp': jnp.array([0.03 * i for i in range(88)]),
'pressure': pressure,
'flow': jnp.array([0 for i in range(88)]),
'target': target,
'u_in': u_in,
'u_out': u_out
}
result['timeseries'] = timeseries
paths = [result for i in range(10)]
self.dataset = BreathDataset.from_paths(paths, clip=(0, None))
def test_get_shuffled_and_batched_data(self):
prng_key = jax.random.PRNGKey(0)
batch_size = 2
<|code_end|>
, predict the immediate next line with the help of imports:
from absl.testing import absltest
from deluca.lung.utils.data.breath_dataset import BreathDataset
from deluca.lung.utils.data.breath_dataset import get_initial_pressure
from deluca.lung.utils.data.breath_dataset import get_shuffled_and_batched_data
import chex
import jax
import jax.numpy as jnp
and context (classes, functions, sometimes code) from other files:
# Path: deluca/lung/utils/data/breath_dataset.py
# class BreathDataset:
# """dataset for breaths."""
#
# @classmethod
# def from_paths(
# cls,
# paths,
# seed=0,
# clip=(0, None), # used to be (2, -1)
# breath_length=29,
# keys=["train", "test"],
# splits=[0.9, 0.1],
# fit_scaler_key="train",
# ):
# """process data from paths."""
# obj = object.__new__(cls)
# raw_data = []
#
# for path in paths:
# analyzer = Analyzer(path)
# raw_data += analyzer.get_breaths(clip=clip, breath_length=breath_length)
#
# # Shuffle and split raw_data
# rng = np.random.default_rng(seed)
# splits = (np.array(splits) / np.sum(splits) *
# len(raw_data)).astype("int")[:-1]
# rng.shuffle(raw_data)
# obj.splits = {
# key: val for key, val in zip(keys, np.split(raw_data, splits))
# }
#
# # Compute mean, std for u_in and pressure
# obj.u_normalizer = ShiftScaleTransform(
# jnp.array([u for u, p in obj.splits[fit_scaler_key]]))
# print(f"u_in: mean={obj.u_normalizer.mean}, std={obj.u_normalizer.std}")
# obj.p_normalizer = ShiftScaleTransform(
# jnp.array([p for u, p in obj.splits[fit_scaler_key]]))
# print(f"pressure: mean={obj.p_normalizer.mean}, std={obj.p_normalizer.std}")
#
# obj.data = {}
# for key in keys:
# obj.data[key] = (jnp.array([u for u, p in obj.splits[key]]),
# jnp.array([p for u, p in obj.splits[key]]))
# return obj
#
# Path: deluca/lung/utils/data/breath_dataset.py
# def get_initial_pressure(dataset, key):
# return jnp.array([dataset.p_normalizer(p[0]) for u, p in dataset.splits[key]
# ]).mean().item()
#
# Path: deluca/lung/utils/data/breath_dataset.py
# def get_shuffled_and_batched_data(dataset, batch_size, key, prng_key):
# """function to shuffle and batch data."""
# x, y = dataset.data[key]
# x = jax.random.permutation(prng_key, x)
# y = jax.random.permutation(prng_key, y)
# prng_key, _ = jax.random.split(prng_key)
# num_batches = x.shape[0] // batch_size
# trunc_len = num_batches * batch_size
# trunc_x = x[:trunc_len]
# trunc_y = y[:trunc_len]
# batched_x = jnp.reshape(trunc_x, (num_batches, batch_size, trunc_x.shape[1]))
# batched_y = jnp.reshape(trunc_y, (num_batches, batch_size, trunc_y.shape[1]))
# return batched_x, batched_y, prng_key
. Output only the next line. | x, y, prng_key = get_shuffled_and_batched_data( |
Predict the next line after this snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Expiratory."""
class Expiratory(Controller):
"""Expiratory."""
waveform: BreathWaveform = deluca.field(jaxed=False)
# TODO(dsuo): Handle dataclass initialization of jax objects
def setup(self):
if self.waveform is None:
self.waveform = BreathWaveform.create()
@jax.jit
def __call__(self, state, obs, *args, **kwargs):
time = obs.time
u_out = jax.lax.cond(
self.waveform.is_in(time), lambda x: 0, lambda x: 1,
jnp.zeros_like(time))
<|code_end|>
using the current file's imports:
import deluca
import jax
import jax.numpy as jnp
from deluca.lung.core import BreathWaveform
from deluca.lung.core import Controller
from deluca.lung.core import DEFAULT_DT
from deluca.lung.core import proper_time
and any relevant context from other files:
# Path: deluca/lung/core.py
# class BreathWaveform(deluca.Obj):
# r"""Waveform generator with shape |‾\_."""
# peep: float = deluca.field(5., jaxed=False)
# pip: float = deluca.field(35., jaxed=False)
# bpm: int = deluca.field(20, jaxed=False)
# fp: jnp.array = deluca.field(jaxed=False)
# xp: jnp.array = deluca.field(jaxed=False)
# in_bounds: Tuple[int, int] = deluca.field((0, 1), jaxed=False)
# ex_bounds: Tuple[int, int] = deluca.field((2, 4), jaxed=False)
# period: float = deluca.field(jaxed=False)
# dt: float = deluca.field(DEFAULT_DT, jaxed=False)
# dtype: jax._src.numpy.lax_numpy._ScalarMeta = deluca.field(
# jnp.float32, jaxed=False)
#
# def setup(self):
# if self.fp is None:
# self.fp = jnp.array([self.pip, self.pip, self.peep, self.peep, self.pip])
# if self.xp is None:
# self.xp = jnp.array(DEFAULT_XP)
# self.period = 60 / self.bpm
#
# def at(self, t):
#
# @functools.partial(jax.jit, static_argnums=(3,))
# def static_interp(t, xp, fp, period):
# return jnp.interp(t, xp, fp, period=period)
#
# return static_interp(t, self.xp, self.fp, self.period).astype(self.dtype)
#
# def elapsed(self, t):
# return t % self.period
#
# def is_in(self, t):
# return self.elapsed(t) <= self.xp[self.in_bounds[1]]
#
# def is_ex(self, t):
# return not self.is_in(t)
#
# Path: deluca/lung/core.py
# class Controller(deluca.Agent):
# """Controller."""
#
# def init(self, waveform=None):
# if waveform is None:
# waveform = BreathWaveform.create()
# return ControllerState()
#
# @property
# def max(self):
# return 100
#
# @property
# def min(self):
# return 0
#
# def decay(self, waveform, t):
# elapsed = waveform.elapsed(t)
#
# def false_func():
# result = jax.lax.cond(
# elapsed < waveform.xp[waveform.ex_bounds[0]], lambda x: 0.0,
# lambda x: 5 * (1 - jnp.exp(5 * (waveform.xp[waveform.ex_bounds[
# 0]] - elapsed))).astype(waveform.dtype), None)
# return result
#
# # float(inf) as substitute to None since cond requries same type output
# result = jax.lax.cond(elapsed < waveform.xp[waveform.in_bounds[1]],
# lambda x: float("inf"), lambda x: false_func(), None)
# return result
#
# Path: deluca/lung/core.py
# DEFAULT_DT = 0.03
#
# Path: deluca/lung/core.py
# def proper_time(t):
# return jax.lax.cond(t == float("inf"), lambda x: 0., lambda x: x, t)
. Output only the next line. | new_dt = jnp.max(jnp.array([DEFAULT_DT, time - proper_time(state.time)])) |
Next line prediction: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Expiratory."""
class Expiratory(Controller):
"""Expiratory."""
waveform: BreathWaveform = deluca.field(jaxed=False)
# TODO(dsuo): Handle dataclass initialization of jax objects
def setup(self):
if self.waveform is None:
self.waveform = BreathWaveform.create()
@jax.jit
def __call__(self, state, obs, *args, **kwargs):
time = obs.time
u_out = jax.lax.cond(
self.waveform.is_in(time), lambda x: 0, lambda x: 1,
jnp.zeros_like(time))
<|code_end|>
. Use current file imports:
(import deluca
import jax
import jax.numpy as jnp
from deluca.lung.core import BreathWaveform
from deluca.lung.core import Controller
from deluca.lung.core import DEFAULT_DT
from deluca.lung.core import proper_time)
and context including class names, function names, or small code snippets from other files:
# Path: deluca/lung/core.py
# class BreathWaveform(deluca.Obj):
# r"""Waveform generator with shape |‾\_."""
# peep: float = deluca.field(5., jaxed=False)
# pip: float = deluca.field(35., jaxed=False)
# bpm: int = deluca.field(20, jaxed=False)
# fp: jnp.array = deluca.field(jaxed=False)
# xp: jnp.array = deluca.field(jaxed=False)
# in_bounds: Tuple[int, int] = deluca.field((0, 1), jaxed=False)
# ex_bounds: Tuple[int, int] = deluca.field((2, 4), jaxed=False)
# period: float = deluca.field(jaxed=False)
# dt: float = deluca.field(DEFAULT_DT, jaxed=False)
# dtype: jax._src.numpy.lax_numpy._ScalarMeta = deluca.field(
# jnp.float32, jaxed=False)
#
# def setup(self):
# if self.fp is None:
# self.fp = jnp.array([self.pip, self.pip, self.peep, self.peep, self.pip])
# if self.xp is None:
# self.xp = jnp.array(DEFAULT_XP)
# self.period = 60 / self.bpm
#
# def at(self, t):
#
# @functools.partial(jax.jit, static_argnums=(3,))
# def static_interp(t, xp, fp, period):
# return jnp.interp(t, xp, fp, period=period)
#
# return static_interp(t, self.xp, self.fp, self.period).astype(self.dtype)
#
# def elapsed(self, t):
# return t % self.period
#
# def is_in(self, t):
# return self.elapsed(t) <= self.xp[self.in_bounds[1]]
#
# def is_ex(self, t):
# return not self.is_in(t)
#
# Path: deluca/lung/core.py
# class Controller(deluca.Agent):
# """Controller."""
#
# def init(self, waveform=None):
# if waveform is None:
# waveform = BreathWaveform.create()
# return ControllerState()
#
# @property
# def max(self):
# return 100
#
# @property
# def min(self):
# return 0
#
# def decay(self, waveform, t):
# elapsed = waveform.elapsed(t)
#
# def false_func():
# result = jax.lax.cond(
# elapsed < waveform.xp[waveform.ex_bounds[0]], lambda x: 0.0,
# lambda x: 5 * (1 - jnp.exp(5 * (waveform.xp[waveform.ex_bounds[
# 0]] - elapsed))).astype(waveform.dtype), None)
# return result
#
# # float(inf) as substitute to None since cond requries same type output
# result = jax.lax.cond(elapsed < waveform.xp[waveform.in_bounds[1]],
# lambda x: float("inf"), lambda x: false_func(), None)
# return result
#
# Path: deluca/lung/core.py
# DEFAULT_DT = 0.03
#
# Path: deluca/lung/core.py
# def proper_time(t):
# return jax.lax.cond(t == float("inf"), lambda x: 0., lambda x: x, t)
. Output only the next line. | new_dt = jnp.max(jnp.array([DEFAULT_DT, time - proper_time(state.time)])) |
Given the following code snippet before the placeholder: <|code_start|> F[h][0] @ (X[h].flatten() - X_old[h].flatten()) +
F[h][1] @ (U[h] - U_old[h]))
W = W.at[0].set(w)
W = jnp.roll(W, -1, axis=0)
if h >= H:
delta_E, delta_off = grad_loss(E, off, W, H, M, X[h - H], env_sim,
cost_func, U_old[h - H:], k[h - H:],
K[h - H:], X_old[h - H:], D, F, alpha, C)
E -= lr / h * delta_E
off -= lr / h * delta_off
return X, U, cost
def iGPC_closed(
env_true,
env_sim,
cost_func,
U,
T,
k=None,
K=None,
X=None,
w_is="de",
lr=None,
ref_alpha=1.0,
backtracking=True,
verbose=True,
):
alpha, r = ref_alpha, 1
<|code_end|>
, predict the next line using imports from the current file:
import time
import jax.numpy as jnp
import jax
from deluca.igpc.rollout import rollout, compute_ders
from deluca.igpc.lqr_solver import LQR
and context including class names, function names, and sometimes code from other files:
# Path: deluca/igpc/rollout.py
# @partial(jax.jit, static_argnums=(1,))
# def rollout(env,
# cost_func,
# U_old,
# k=None,
# K=None,
# X_old=None,
# alpha=1.0,
# H=None,
# start_state=None):
# """
# Arg List
# env: The environment to do the rollout on. This is treated as a
# derstructible copy.
# U_old: A base open loop control sequence
# k: open loop gain (iLQR)
# K: closed loop gain (iLQR)
# X_old: Previous trajectory to compute gain (iLQR)
# alpha: Optional multplier to the open loop gain (iLQR)
# D: Optional noise vectors for the rollout (GPC)
# F: Linearization shift ??? (GPC)
# H: The horizon length to perform a rollout.
# """
# ## problematic
# # if H == None:
# # H = env.H
# H = env.H
# X, U = [None] * (H + 1), [None] * (H)
# if start_state is None:
# start_state = env.init()
# X[0], cost = start_state, 0.0
# for h in range(H):
# if k is None:
# U[h] = U_old[h]
# else:
# X_flat = X[h].flatten()
# X_old_flat = X_old[h].flatten()
# U[h] = U_old[h] + alpha * k[h] + K[h] @ (X_flat - X_old_flat)
#
# X[h + 1], _ = env(X[h], U[h])
# cost += cost_func(X[h], U[h], env)
# return X, U, cost
#
# def compute_ders(env, cost, X, U, H=None):
# D, F, C = compute_ders_inner(env, cost, X, U, H=None)
# F = list(zip(*F))
# C = list(zip(*C))
# return D, F, C
#
# Path: deluca/igpc/lqr_solver.py
# def LQR(F, C):
# H, d = len(C), C[0][0].shape[0]
# K, k = (
# [None for _ in range(H)],
# [None for _ in range(H)],
# )
#
# V_x, V_xx = np.zeros(d), np.zeros((d, d))
# # V_x, V_xx = jnp.zeros(d), jnp.zeros((d, d))
#
# # F_x, F_u = F
# # C_x, C_u, C_xx, C_uu = C
#
# # def loop(carry, args):
# # v_x, v_xx = carry
# # f_x, f_u, c_x, c_u, c_xx, c_uu = args
#
# # q_x, q_u = c_x + f_x.T @ v_x, c_u + f_u.T @ v_x
# # q_xx, q_ux, q_uu = (
# # c_xx + f_x.T @ v_xx @ f_x,
# # f_u.T @ v_xx @ f_x,
# # c_uu + f_u.T @ v_xx @ f_u,
# # )
#
# # K, k = -jnp.linalg.inv(q_uu) @ q_ux, -jnp.linalg.inv(q_uu) @ q_u
# # v_x = q_x - K.T @ q_uu @ k
# # v_xx = q_xx - K.T @ q_uu @ K
# # v_xx = (v_xx + v_xx.T) / 2
#
# # return (v_x, v_xx), (K, k)
#
# # _, (K, k) = jax.lax.scan(loop, (V_x, V_xx), (F_x, F_u, C_x, C_u, C_xx, C_uu))
# for h in range(H - 1, -1, -1):
# f_x, f_u = F[h]
# c_x, c_u, c_xx, c_uu = C[h]
# Q_x, Q_u = c_x + f_x.T @ V_x, c_u + f_u.T @ V_x
#
# Q_xx, Q_ux, Q_uu = (
# c_xx + f_x.T @ V_xx @ f_x,
# f_u.T @ V_xx @ f_x,
# c_uu + f_u.T @ V_xx @ f_u,
# )
# K[h], k[h] = -np.linalg.inv(Q_uu) @ Q_ux, -np.linalg.inv(Q_uu) @ Q_u
# V_x = Q_x - K[h].T @ Q_uu @ k[h]
# V_xx = Q_xx - K[h].T @ Q_uu @ K[h]
# V_xx = (V_xx + V_xx.T) / 2
# return k, K
. Output only the next line. | X, U, c = rollout(env_true, cost_func, U, k, K, X) |
Given the following code snippet before the placeholder: <|code_start|> if h >= H:
delta_E, delta_off = grad_loss(E, off, W, H, M, X[h - H], env_sim,
cost_func, U_old[h - H:], k[h - H:],
K[h - H:], X_old[h - H:], D, F, alpha, C)
E -= lr / h * delta_E
off -= lr / h * delta_off
return X, U, cost
def iGPC_closed(
env_true,
env_sim,
cost_func,
U,
T,
k=None,
K=None,
X=None,
w_is="de",
lr=None,
ref_alpha=1.0,
backtracking=True,
verbose=True,
):
alpha, r = ref_alpha, 1
X, U, c = rollout(env_true, cost_func, U, k, K, X)
print(f"iGPC: t = {-1}, r = {r}, c = {c}")
assert w_is in ["de", "dede", "delin"]
prev_loop_fail = False
for t in range(T):
<|code_end|>
, predict the next line using imports from the current file:
import time
import jax.numpy as jnp
import jax
from deluca.igpc.rollout import rollout, compute_ders
from deluca.igpc.lqr_solver import LQR
and context including class names, function names, and sometimes code from other files:
# Path: deluca/igpc/rollout.py
# @partial(jax.jit, static_argnums=(1,))
# def rollout(env,
# cost_func,
# U_old,
# k=None,
# K=None,
# X_old=None,
# alpha=1.0,
# H=None,
# start_state=None):
# """
# Arg List
# env: The environment to do the rollout on. This is treated as a
# derstructible copy.
# U_old: A base open loop control sequence
# k: open loop gain (iLQR)
# K: closed loop gain (iLQR)
# X_old: Previous trajectory to compute gain (iLQR)
# alpha: Optional multplier to the open loop gain (iLQR)
# D: Optional noise vectors for the rollout (GPC)
# F: Linearization shift ??? (GPC)
# H: The horizon length to perform a rollout.
# """
# ## problematic
# # if H == None:
# # H = env.H
# H = env.H
# X, U = [None] * (H + 1), [None] * (H)
# if start_state is None:
# start_state = env.init()
# X[0], cost = start_state, 0.0
# for h in range(H):
# if k is None:
# U[h] = U_old[h]
# else:
# X_flat = X[h].flatten()
# X_old_flat = X_old[h].flatten()
# U[h] = U_old[h] + alpha * k[h] + K[h] @ (X_flat - X_old_flat)
#
# X[h + 1], _ = env(X[h], U[h])
# cost += cost_func(X[h], U[h], env)
# return X, U, cost
#
# def compute_ders(env, cost, X, U, H=None):
# D, F, C = compute_ders_inner(env, cost, X, U, H=None)
# F = list(zip(*F))
# C = list(zip(*C))
# return D, F, C
#
# Path: deluca/igpc/lqr_solver.py
# def LQR(F, C):
# H, d = len(C), C[0][0].shape[0]
# K, k = (
# [None for _ in range(H)],
# [None for _ in range(H)],
# )
#
# V_x, V_xx = np.zeros(d), np.zeros((d, d))
# # V_x, V_xx = jnp.zeros(d), jnp.zeros((d, d))
#
# # F_x, F_u = F
# # C_x, C_u, C_xx, C_uu = C
#
# # def loop(carry, args):
# # v_x, v_xx = carry
# # f_x, f_u, c_x, c_u, c_xx, c_uu = args
#
# # q_x, q_u = c_x + f_x.T @ v_x, c_u + f_u.T @ v_x
# # q_xx, q_ux, q_uu = (
# # c_xx + f_x.T @ v_xx @ f_x,
# # f_u.T @ v_xx @ f_x,
# # c_uu + f_u.T @ v_xx @ f_u,
# # )
#
# # K, k = -jnp.linalg.inv(q_uu) @ q_ux, -jnp.linalg.inv(q_uu) @ q_u
# # v_x = q_x - K.T @ q_uu @ k
# # v_xx = q_xx - K.T @ q_uu @ K
# # v_xx = (v_xx + v_xx.T) / 2
#
# # return (v_x, v_xx), (K, k)
#
# # _, (K, k) = jax.lax.scan(loop, (V_x, V_xx), (F_x, F_u, C_x, C_u, C_xx, C_uu))
# for h in range(H - 1, -1, -1):
# f_x, f_u = F[h]
# c_x, c_u, c_xx, c_uu = C[h]
# Q_x, Q_u = c_x + f_x.T @ V_x, c_u + f_u.T @ V_x
#
# Q_xx, Q_ux, Q_uu = (
# c_xx + f_x.T @ V_xx @ f_x,
# f_u.T @ V_xx @ f_x,
# c_uu + f_u.T @ V_xx @ f_u,
# )
# K[h], k[h] = -np.linalg.inv(Q_uu) @ Q_ux, -np.linalg.inv(Q_uu) @ Q_u
# V_x = Q_x - K[h].T @ Q_uu @ k[h]
# V_xx = Q_xx - K[h].T @ Q_uu @ K[h]
# V_xx = (V_xx + V_xx.T) / 2
# return k, K
. Output only the next line. | D, F, C = compute_ders(env_sim, cost_func, X, U) |
Based on the snippet: <|code_start|> delta_E, delta_off = grad_loss(E, off, W, H, M, X[h - H], env_sim,
cost_func, U_old[h - H:], k[h - H:],
K[h - H:], X_old[h - H:], D, F, alpha, C)
E -= lr / h * delta_E
off -= lr / h * delta_off
return X, U, cost
def iGPC_closed(
env_true,
env_sim,
cost_func,
U,
T,
k=None,
K=None,
X=None,
w_is="de",
lr=None,
ref_alpha=1.0,
backtracking=True,
verbose=True,
):
alpha, r = ref_alpha, 1
X, U, c = rollout(env_true, cost_func, U, k, K, X)
print(f"iGPC: t = {-1}, r = {r}, c = {c}")
assert w_is in ["de", "dede", "delin"]
prev_loop_fail = False
for t in range(T):
D, F, C = compute_ders(env_sim, cost_func, X, U)
<|code_end|>
, predict the immediate next line with the help of imports:
import time
import jax.numpy as jnp
import jax
from deluca.igpc.rollout import rollout, compute_ders
from deluca.igpc.lqr_solver import LQR
and context (classes, functions, sometimes code) from other files:
# Path: deluca/igpc/rollout.py
# @partial(jax.jit, static_argnums=(1,))
# def rollout(env,
# cost_func,
# U_old,
# k=None,
# K=None,
# X_old=None,
# alpha=1.0,
# H=None,
# start_state=None):
# """
# Arg List
# env: The environment to do the rollout on. This is treated as a
# derstructible copy.
# U_old: A base open loop control sequence
# k: open loop gain (iLQR)
# K: closed loop gain (iLQR)
# X_old: Previous trajectory to compute gain (iLQR)
# alpha: Optional multplier to the open loop gain (iLQR)
# D: Optional noise vectors for the rollout (GPC)
# F: Linearization shift ??? (GPC)
# H: The horizon length to perform a rollout.
# """
# ## problematic
# # if H == None:
# # H = env.H
# H = env.H
# X, U = [None] * (H + 1), [None] * (H)
# if start_state is None:
# start_state = env.init()
# X[0], cost = start_state, 0.0
# for h in range(H):
# if k is None:
# U[h] = U_old[h]
# else:
# X_flat = X[h].flatten()
# X_old_flat = X_old[h].flatten()
# U[h] = U_old[h] + alpha * k[h] + K[h] @ (X_flat - X_old_flat)
#
# X[h + 1], _ = env(X[h], U[h])
# cost += cost_func(X[h], U[h], env)
# return X, U, cost
#
# def compute_ders(env, cost, X, U, H=None):
# D, F, C = compute_ders_inner(env, cost, X, U, H=None)
# F = list(zip(*F))
# C = list(zip(*C))
# return D, F, C
#
# Path: deluca/igpc/lqr_solver.py
# def LQR(F, C):
# H, d = len(C), C[0][0].shape[0]
# K, k = (
# [None for _ in range(H)],
# [None for _ in range(H)],
# )
#
# V_x, V_xx = np.zeros(d), np.zeros((d, d))
# # V_x, V_xx = jnp.zeros(d), jnp.zeros((d, d))
#
# # F_x, F_u = F
# # C_x, C_u, C_xx, C_uu = C
#
# # def loop(carry, args):
# # v_x, v_xx = carry
# # f_x, f_u, c_x, c_u, c_xx, c_uu = args
#
# # q_x, q_u = c_x + f_x.T @ v_x, c_u + f_u.T @ v_x
# # q_xx, q_ux, q_uu = (
# # c_xx + f_x.T @ v_xx @ f_x,
# # f_u.T @ v_xx @ f_x,
# # c_uu + f_u.T @ v_xx @ f_u,
# # )
#
# # K, k = -jnp.linalg.inv(q_uu) @ q_ux, -jnp.linalg.inv(q_uu) @ q_u
# # v_x = q_x - K.T @ q_uu @ k
# # v_xx = q_xx - K.T @ q_uu @ K
# # v_xx = (v_xx + v_xx.T) / 2
#
# # return (v_x, v_xx), (K, k)
#
# # _, (K, k) = jax.lax.scan(loop, (V_x, V_xx), (F_x, F_u, C_x, C_u, C_xx, C_uu))
# for h in range(H - 1, -1, -1):
# f_x, f_u = F[h]
# c_x, c_u, c_xx, c_uu = C[h]
# Q_x, Q_u = c_x + f_x.T @ V_x, c_u + f_u.T @ V_x
#
# Q_xx, Q_ux, Q_uu = (
# c_xx + f_x.T @ V_xx @ f_x,
# f_u.T @ V_xx @ f_x,
# c_uu + f_u.T @ V_xx @ f_u,
# )
# K[h], k[h] = -np.linalg.inv(Q_uu) @ Q_ux, -np.linalg.inv(Q_uu) @ Q_u
# V_x = Q_x - K[h].T @ Q_uu @ k[h]
# V_xx = Q_xx - K[h].T @ Q_uu @ K[h]
# V_xx = (V_xx + V_xx.T) / 2
# return k, K
. Output only the next line. | k, K = LQR(F, C) |
Here is a snippet: <|code_start|> y = 3.0 * x
flow_new = 1.0 * (jnp.tanh(0.03 * (y - 130)) + 1.0)
flow_new = jnp.clip(flow_new, 0.0, 1.72)
return flow_new
def Solenoid(x):
return x > 0
class BalloonLung(LungEnv):
"""Lung simulator based on the two-balloon experiment.
Source: https://en.wikipedia.org/wiki/Two-balloon_experiment
TODO:
- time / dt
- dynamics
- waveform
- phase
"""
leak: bool = deluca.field(False, jaxed=False)
peep_valve: float = deluca.field(5.0, jaxed=False)
PC: float = deluca.field(40.0, jaxed=False)
P0: float = deluca.field(0.0, jaxed=False)
R: float = deluca.field(15.0, jaxed=False)
C: float = deluca.field(10.0, jaxed=False)
dt: float = deluca.field(0.03, jaxed=False)
min_volume: float = deluca.field(1.5, jaxed=False)
r0: float = deluca.field(jaxed=False)
<|code_end|>
. Write the next line using the current file imports:
import deluca.core
import jax
import jax.numpy as jnp
from deluca.lung.core import BreathWaveform
from deluca.lung.core import LungEnv
and context from other files:
# Path: deluca/lung/core.py
# class BreathWaveform(deluca.Obj):
# r"""Waveform generator with shape |‾\_."""
# peep: float = deluca.field(5., jaxed=False)
# pip: float = deluca.field(35., jaxed=False)
# bpm: int = deluca.field(20, jaxed=False)
# fp: jnp.array = deluca.field(jaxed=False)
# xp: jnp.array = deluca.field(jaxed=False)
# in_bounds: Tuple[int, int] = deluca.field((0, 1), jaxed=False)
# ex_bounds: Tuple[int, int] = deluca.field((2, 4), jaxed=False)
# period: float = deluca.field(jaxed=False)
# dt: float = deluca.field(DEFAULT_DT, jaxed=False)
# dtype: jax._src.numpy.lax_numpy._ScalarMeta = deluca.field(
# jnp.float32, jaxed=False)
#
# def setup(self):
# if self.fp is None:
# self.fp = jnp.array([self.pip, self.pip, self.peep, self.peep, self.pip])
# if self.xp is None:
# self.xp = jnp.array(DEFAULT_XP)
# self.period = 60 / self.bpm
#
# def at(self, t):
#
# @functools.partial(jax.jit, static_argnums=(3,))
# def static_interp(t, xp, fp, period):
# return jnp.interp(t, xp, fp, period=period)
#
# return static_interp(t, self.xp, self.fp, self.period).astype(self.dtype)
#
# def elapsed(self, t):
# return t % self.period
#
# def is_in(self, t):
# return self.elapsed(t) <= self.xp[self.in_bounds[1]]
#
# def is_ex(self, t):
# return not self.is_in(t)
#
# Path: deluca/lung/core.py
# class LungEnv(deluca.Env):
# """Lung environment."""
#
# def time(self, state):
# return self.dt * state.steps
#
# @property
# def dt(self):
# return DEFAULT_DT
#
# @property
# def physical(self):
# return False
#
# def should_abort(self):
# return False
#
# def wait(self, duration):
# pass
#
# def cleanup(self):
# pass
, which may include functions, classes, or code. Output only the next line. | waveform: BreathWaveform = deluca.field(jaxed=False) |
Next line prediction: <|code_start|>"""Balloon Lung."""
# pylint: disable=g-long-lambda
class Observation(deluca.Obj):
predicted_pressure: float = 0.0
time: float = 0.0
class SimulatorState(deluca.Obj):
steps: int = 0
time: float = 0.0
volume: float = 0.0
predicted_pressure: float = 0.0
target: float = 0.0
def PropValve(x):
y = 3.0 * x
flow_new = 1.0 * (jnp.tanh(0.03 * (y - 130)) + 1.0)
flow_new = jnp.clip(flow_new, 0.0, 1.72)
return flow_new
def Solenoid(x):
return x > 0
<|code_end|>
. Use current file imports:
(import deluca.core
import jax
import jax.numpy as jnp
from deluca.lung.core import BreathWaveform
from deluca.lung.core import LungEnv)
and context including class names, function names, or small code snippets from other files:
# Path: deluca/lung/core.py
# class BreathWaveform(deluca.Obj):
# r"""Waveform generator with shape |‾\_."""
# peep: float = deluca.field(5., jaxed=False)
# pip: float = deluca.field(35., jaxed=False)
# bpm: int = deluca.field(20, jaxed=False)
# fp: jnp.array = deluca.field(jaxed=False)
# xp: jnp.array = deluca.field(jaxed=False)
# in_bounds: Tuple[int, int] = deluca.field((0, 1), jaxed=False)
# ex_bounds: Tuple[int, int] = deluca.field((2, 4), jaxed=False)
# period: float = deluca.field(jaxed=False)
# dt: float = deluca.field(DEFAULT_DT, jaxed=False)
# dtype: jax._src.numpy.lax_numpy._ScalarMeta = deluca.field(
# jnp.float32, jaxed=False)
#
# def setup(self):
# if self.fp is None:
# self.fp = jnp.array([self.pip, self.pip, self.peep, self.peep, self.pip])
# if self.xp is None:
# self.xp = jnp.array(DEFAULT_XP)
# self.period = 60 / self.bpm
#
# def at(self, t):
#
# @functools.partial(jax.jit, static_argnums=(3,))
# def static_interp(t, xp, fp, period):
# return jnp.interp(t, xp, fp, period=period)
#
# return static_interp(t, self.xp, self.fp, self.period).astype(self.dtype)
#
# def elapsed(self, t):
# return t % self.period
#
# def is_in(self, t):
# return self.elapsed(t) <= self.xp[self.in_bounds[1]]
#
# def is_ex(self, t):
# return not self.is_in(t)
#
# Path: deluca/lung/core.py
# class LungEnv(deluca.Env):
# """Lung environment."""
#
# def time(self, state):
# return self.dt * state.steps
#
# @property
# def dt(self):
# return DEFAULT_DT
#
# @property
# def physical(self):
# return False
#
# def should_abort(self):
# return False
#
# def wait(self, duration):
# pass
#
# def cleanup(self):
# pass
. Output only the next line. | class BalloonLung(LungEnv): |
Given the code snippet: <|code_start|>
class PIDNetwork(nn.Module):
@nn.compact
def __call__(self, x):
x = nn.Dense(features=1, use_bias=False, name="K")(x)
return x
# generic PID controller
class PID(Controller):
"""PID controller."""
model: nn.module = deluca.field(PIDNetwork, jaxed=False)
params: jnp.array = deluca.field(jaxed=True) # jnp.array([3.0, 4.0, 0.0]
RC: float = deluca.field(0.5, jaxed=False)
dt: float = deluca.field(0.03, jaxed=False)
model_apply: collections.abc.Callable = deluca.field(jaxed=False)
def setup(self):
self.model = PIDNetwork()
if self.params is None:
self.params = self.model.init(jax.random.PRNGKey(0), jnp.ones([
3,
]))["params"]
# TODO(dsuo): Handle dataclass initialization of jax objects
self.model_apply = jax.jit(self.model.apply)
def init(self, waveform=None):
if waveform is None:
<|code_end|>
, generate the next line using the imports in this file:
import collections.abc
import deluca.core
import flax.linen as nn
import jax
import jax.numpy as jnp
from deluca.lung.core import BreathWaveform
from deluca.lung.core import Controller
from deluca.lung.core import DEFAULT_DT
from deluca.lung.core import proper_time
and context (functions, classes, or occasionally code) from other files:
# Path: deluca/lung/core.py
# class BreathWaveform(deluca.Obj):
# r"""Waveform generator with shape |‾\_."""
# peep: float = deluca.field(5., jaxed=False)
# pip: float = deluca.field(35., jaxed=False)
# bpm: int = deluca.field(20, jaxed=False)
# fp: jnp.array = deluca.field(jaxed=False)
# xp: jnp.array = deluca.field(jaxed=False)
# in_bounds: Tuple[int, int] = deluca.field((0, 1), jaxed=False)
# ex_bounds: Tuple[int, int] = deluca.field((2, 4), jaxed=False)
# period: float = deluca.field(jaxed=False)
# dt: float = deluca.field(DEFAULT_DT, jaxed=False)
# dtype: jax._src.numpy.lax_numpy._ScalarMeta = deluca.field(
# jnp.float32, jaxed=False)
#
# def setup(self):
# if self.fp is None:
# self.fp = jnp.array([self.pip, self.pip, self.peep, self.peep, self.pip])
# if self.xp is None:
# self.xp = jnp.array(DEFAULT_XP)
# self.period = 60 / self.bpm
#
# def at(self, t):
#
# @functools.partial(jax.jit, static_argnums=(3,))
# def static_interp(t, xp, fp, period):
# return jnp.interp(t, xp, fp, period=period)
#
# return static_interp(t, self.xp, self.fp, self.period).astype(self.dtype)
#
# def elapsed(self, t):
# return t % self.period
#
# def is_in(self, t):
# return self.elapsed(t) <= self.xp[self.in_bounds[1]]
#
# def is_ex(self, t):
# return not self.is_in(t)
#
# Path: deluca/lung/core.py
# class Controller(deluca.Agent):
# """Controller."""
#
# def init(self, waveform=None):
# if waveform is None:
# waveform = BreathWaveform.create()
# return ControllerState()
#
# @property
# def max(self):
# return 100
#
# @property
# def min(self):
# return 0
#
# def decay(self, waveform, t):
# elapsed = waveform.elapsed(t)
#
# def false_func():
# result = jax.lax.cond(
# elapsed < waveform.xp[waveform.ex_bounds[0]], lambda x: 0.0,
# lambda x: 5 * (1 - jnp.exp(5 * (waveform.xp[waveform.ex_bounds[
# 0]] - elapsed))).astype(waveform.dtype), None)
# return result
#
# # float(inf) as substitute to None since cond requries same type output
# result = jax.lax.cond(elapsed < waveform.xp[waveform.in_bounds[1]],
# lambda x: float("inf"), lambda x: false_func(), None)
# return result
#
# Path: deluca/lung/core.py
# DEFAULT_DT = 0.03
#
# Path: deluca/lung/core.py
# def proper_time(t):
# return jax.lax.cond(t == float("inf"), lambda x: 0., lambda x: x, t)
. Output only the next line. | waveform = BreathWaveform.create() |
Here is a snippet: <|code_start|># Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""PID controller."""
# TODO(dsuo,alexjyu): refactor with deluca PID
class PIDControllerState(deluca.Obj):
waveform: deluca.Obj
p: float = 0.
i: float = 0.
d: float = 0.
time: float = float("inf")
steps: int = 0
dt: float = DEFAULT_DT
class PIDNetwork(nn.Module):
@nn.compact
def __call__(self, x):
x = nn.Dense(features=1, use_bias=False, name="K")(x)
return x
# generic PID controller
<|code_end|>
. Write the next line using the current file imports:
import collections.abc
import deluca.core
import flax.linen as nn
import jax
import jax.numpy as jnp
from deluca.lung.core import BreathWaveform
from deluca.lung.core import Controller
from deluca.lung.core import DEFAULT_DT
from deluca.lung.core import proper_time
and context from other files:
# Path: deluca/lung/core.py
# class BreathWaveform(deluca.Obj):
# r"""Waveform generator with shape |‾\_."""
# peep: float = deluca.field(5., jaxed=False)
# pip: float = deluca.field(35., jaxed=False)
# bpm: int = deluca.field(20, jaxed=False)
# fp: jnp.array = deluca.field(jaxed=False)
# xp: jnp.array = deluca.field(jaxed=False)
# in_bounds: Tuple[int, int] = deluca.field((0, 1), jaxed=False)
# ex_bounds: Tuple[int, int] = deluca.field((2, 4), jaxed=False)
# period: float = deluca.field(jaxed=False)
# dt: float = deluca.field(DEFAULT_DT, jaxed=False)
# dtype: jax._src.numpy.lax_numpy._ScalarMeta = deluca.field(
# jnp.float32, jaxed=False)
#
# def setup(self):
# if self.fp is None:
# self.fp = jnp.array([self.pip, self.pip, self.peep, self.peep, self.pip])
# if self.xp is None:
# self.xp = jnp.array(DEFAULT_XP)
# self.period = 60 / self.bpm
#
# def at(self, t):
#
# @functools.partial(jax.jit, static_argnums=(3,))
# def static_interp(t, xp, fp, period):
# return jnp.interp(t, xp, fp, period=period)
#
# return static_interp(t, self.xp, self.fp, self.period).astype(self.dtype)
#
# def elapsed(self, t):
# return t % self.period
#
# def is_in(self, t):
# return self.elapsed(t) <= self.xp[self.in_bounds[1]]
#
# def is_ex(self, t):
# return not self.is_in(t)
#
# Path: deluca/lung/core.py
# class Controller(deluca.Agent):
# """Controller."""
#
# def init(self, waveform=None):
# if waveform is None:
# waveform = BreathWaveform.create()
# return ControllerState()
#
# @property
# def max(self):
# return 100
#
# @property
# def min(self):
# return 0
#
# def decay(self, waveform, t):
# elapsed = waveform.elapsed(t)
#
# def false_func():
# result = jax.lax.cond(
# elapsed < waveform.xp[waveform.ex_bounds[0]], lambda x: 0.0,
# lambda x: 5 * (1 - jnp.exp(5 * (waveform.xp[waveform.ex_bounds[
# 0]] - elapsed))).astype(waveform.dtype), None)
# return result
#
# # float(inf) as substitute to None since cond requries same type output
# result = jax.lax.cond(elapsed < waveform.xp[waveform.in_bounds[1]],
# lambda x: float("inf"), lambda x: false_func(), None)
# return result
#
# Path: deluca/lung/core.py
# DEFAULT_DT = 0.03
#
# Path: deluca/lung/core.py
# def proper_time(t):
# return jax.lax.cond(t == float("inf"), lambda x: 0., lambda x: x, t)
, which may include functions, classes, or code. Output only the next line. | class PID(Controller): |
Here is a snippet: <|code_start|># Copyright 2022 The Deluca Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""PID controller."""
# TODO(dsuo,alexjyu): refactor with deluca PID
class PIDControllerState(deluca.Obj):
waveform: deluca.Obj
p: float = 0.
i: float = 0.
d: float = 0.
time: float = float("inf")
steps: int = 0
<|code_end|>
. Write the next line using the current file imports:
import collections.abc
import deluca.core
import flax.linen as nn
import jax
import jax.numpy as jnp
from deluca.lung.core import BreathWaveform
from deluca.lung.core import Controller
from deluca.lung.core import DEFAULT_DT
from deluca.lung.core import proper_time
and context from other files:
# Path: deluca/lung/core.py
# class BreathWaveform(deluca.Obj):
# r"""Waveform generator with shape |‾\_."""
# peep: float = deluca.field(5., jaxed=False)
# pip: float = deluca.field(35., jaxed=False)
# bpm: int = deluca.field(20, jaxed=False)
# fp: jnp.array = deluca.field(jaxed=False)
# xp: jnp.array = deluca.field(jaxed=False)
# in_bounds: Tuple[int, int] = deluca.field((0, 1), jaxed=False)
# ex_bounds: Tuple[int, int] = deluca.field((2, 4), jaxed=False)
# period: float = deluca.field(jaxed=False)
# dt: float = deluca.field(DEFAULT_DT, jaxed=False)
# dtype: jax._src.numpy.lax_numpy._ScalarMeta = deluca.field(
# jnp.float32, jaxed=False)
#
# def setup(self):
# if self.fp is None:
# self.fp = jnp.array([self.pip, self.pip, self.peep, self.peep, self.pip])
# if self.xp is None:
# self.xp = jnp.array(DEFAULT_XP)
# self.period = 60 / self.bpm
#
# def at(self, t):
#
# @functools.partial(jax.jit, static_argnums=(3,))
# def static_interp(t, xp, fp, period):
# return jnp.interp(t, xp, fp, period=period)
#
# return static_interp(t, self.xp, self.fp, self.period).astype(self.dtype)
#
# def elapsed(self, t):
# return t % self.period
#
# def is_in(self, t):
# return self.elapsed(t) <= self.xp[self.in_bounds[1]]
#
# def is_ex(self, t):
# return not self.is_in(t)
#
# Path: deluca/lung/core.py
# class Controller(deluca.Agent):
# """Controller."""
#
# def init(self, waveform=None):
# if waveform is None:
# waveform = BreathWaveform.create()
# return ControllerState()
#
# @property
# def max(self):
# return 100
#
# @property
# def min(self):
# return 0
#
# def decay(self, waveform, t):
# elapsed = waveform.elapsed(t)
#
# def false_func():
# result = jax.lax.cond(
# elapsed < waveform.xp[waveform.ex_bounds[0]], lambda x: 0.0,
# lambda x: 5 * (1 - jnp.exp(5 * (waveform.xp[waveform.ex_bounds[
# 0]] - elapsed))).astype(waveform.dtype), None)
# return result
#
# # float(inf) as substitute to None since cond requries same type output
# result = jax.lax.cond(elapsed < waveform.xp[waveform.in_bounds[1]],
# lambda x: float("inf"), lambda x: false_func(), None)
# return result
#
# Path: deluca/lung/core.py
# DEFAULT_DT = 0.03
#
# Path: deluca/lung/core.py
# def proper_time(t):
# return jax.lax.cond(t == float("inf"), lambda x: 0., lambda x: x, t)
, which may include functions, classes, or code. Output only the next line. | dt: float = DEFAULT_DT |
Given the code snippet: <|code_start|> self.params = self.model.init(jax.random.PRNGKey(0), jnp.ones([
3,
]))["params"]
# TODO(dsuo): Handle dataclass initialization of jax objects
self.model_apply = jax.jit(self.model.apply)
def init(self, waveform=None):
if waveform is None:
waveform = BreathWaveform.create()
state = PIDControllerState(waveform=waveform)
return state
@jax.jit
def __call__(self, controller_state, obs):
pressure, t = obs.predicted_pressure, obs.time
waveform = controller_state.waveform
target = waveform.at(t)
err = jnp.array(target - pressure)
decay = jnp.array(self.dt / (self.dt + self.RC))
p, i, d = controller_state.p, controller_state.i, controller_state.d
next_p = err
next_i = i + decay * (err - i)
next_d = d + decay * (err - p - d)
controller_state = controller_state.replace(p=next_p, i=next_i, d=next_d)
next_coef = jnp.array([next_p, next_i, next_d])
u_in = self.model_apply({"params": self.params}, next_coef)
u_in = jax.lax.clamp(0.0, u_in.astype(jnp.float64), 100.0)
# update controller_state
new_dt = jnp.max(
<|code_end|>
, generate the next line using the imports in this file:
import collections.abc
import deluca.core
import flax.linen as nn
import jax
import jax.numpy as jnp
from deluca.lung.core import BreathWaveform
from deluca.lung.core import Controller
from deluca.lung.core import DEFAULT_DT
from deluca.lung.core import proper_time
and context (functions, classes, or occasionally code) from other files:
# Path: deluca/lung/core.py
# class BreathWaveform(deluca.Obj):
# r"""Waveform generator with shape |‾\_."""
# peep: float = deluca.field(5., jaxed=False)
# pip: float = deluca.field(35., jaxed=False)
# bpm: int = deluca.field(20, jaxed=False)
# fp: jnp.array = deluca.field(jaxed=False)
# xp: jnp.array = deluca.field(jaxed=False)
# in_bounds: Tuple[int, int] = deluca.field((0, 1), jaxed=False)
# ex_bounds: Tuple[int, int] = deluca.field((2, 4), jaxed=False)
# period: float = deluca.field(jaxed=False)
# dt: float = deluca.field(DEFAULT_DT, jaxed=False)
# dtype: jax._src.numpy.lax_numpy._ScalarMeta = deluca.field(
# jnp.float32, jaxed=False)
#
# def setup(self):
# if self.fp is None:
# self.fp = jnp.array([self.pip, self.pip, self.peep, self.peep, self.pip])
# if self.xp is None:
# self.xp = jnp.array(DEFAULT_XP)
# self.period = 60 / self.bpm
#
# def at(self, t):
#
# @functools.partial(jax.jit, static_argnums=(3,))
# def static_interp(t, xp, fp, period):
# return jnp.interp(t, xp, fp, period=period)
#
# return static_interp(t, self.xp, self.fp, self.period).astype(self.dtype)
#
# def elapsed(self, t):
# return t % self.period
#
# def is_in(self, t):
# return self.elapsed(t) <= self.xp[self.in_bounds[1]]
#
# def is_ex(self, t):
# return not self.is_in(t)
#
# Path: deluca/lung/core.py
# class Controller(deluca.Agent):
# """Controller."""
#
# def init(self, waveform=None):
# if waveform is None:
# waveform = BreathWaveform.create()
# return ControllerState()
#
# @property
# def max(self):
# return 100
#
# @property
# def min(self):
# return 0
#
# def decay(self, waveform, t):
# elapsed = waveform.elapsed(t)
#
# def false_func():
# result = jax.lax.cond(
# elapsed < waveform.xp[waveform.ex_bounds[0]], lambda x: 0.0,
# lambda x: 5 * (1 - jnp.exp(5 * (waveform.xp[waveform.ex_bounds[
# 0]] - elapsed))).astype(waveform.dtype), None)
# return result
#
# # float(inf) as substitute to None since cond requries same type output
# result = jax.lax.cond(elapsed < waveform.xp[waveform.in_bounds[1]],
# lambda x: float("inf"), lambda x: false_func(), None)
# return result
#
# Path: deluca/lung/core.py
# DEFAULT_DT = 0.03
#
# Path: deluca/lung/core.py
# def proper_time(t):
# return jax.lax.cond(t == float("inf"), lambda x: 0., lambda x: x, t)
. Output only the next line. | jnp.array([DEFAULT_DT, t - proper_time(controller_state.time)])) |
Here is a snippet: <|code_start|> u_history_len, p_history_len, u_window, p_window,
sync_unnormalized_pressure, num_boundary_models, funcs):
"""False branch of jax.lax.cond in call function."""
u_in_normalized = u_normalizer(u_in).squeeze()
state = state.replace(
u_history=update_history(state.u_history, u_in_normalized),
t_in=state.t_in + 1)
boundary_features = jnp.hstack(
[state.u_history[-u_history_len:], state.p_history[-p_history_len:]])
default_features = jnp.hstack(
[state.u_history[-u_window:], state.p_history[-p_window:]])
default_pad_len = (u_history_len + p_history_len) - (u_window + p_window)
default_features = jnp.hstack(
[jnp.zeros((default_pad_len,)), default_features])
features = jax.lax.cond(
model_idx == num_boundary_models,
lambda x: default_features,
lambda x: boundary_features,
None,
)
normalized_pressure = jax.lax.switch(model_idx, funcs, features)
normalized_pressure = normalized_pressure.astype(jnp.float64)
state = state.replace(predicted_pressure=normalized_pressure)
new_p_history = update_history(state.p_history, normalized_pressure)
state = state.replace(p_history=new_p_history
) # just for inference. This is undone during training
state = sync_unnormalized_pressure(state) # unscale predicted pressure
return state
<|code_end|>
. Write the next line using the current file imports:
import functools
import deluca.core
import flax.linen as nn
import jax
import jax.numpy as jnp
from typing import Any, Dict
from deluca.lung.core import LungEnv
from deluca.lung.utils.data.transform import ShiftScaleTransform
from deluca.lung.utils.nn import MLP
from deluca.lung.utils.nn import ShallowBoundaryModel
and context from other files:
# Path: deluca/lung/core.py
# class LungEnv(deluca.Env):
# """Lung environment."""
#
# def time(self, state):
# return self.dt * state.steps
#
# @property
# def dt(self):
# return DEFAULT_DT
#
# @property
# def physical(self):
# return False
#
# def should_abort(self):
# return False
#
# def wait(self, duration):
# pass
#
# def cleanup(self):
# pass
#
# Path: deluca/lung/utils/data/transform.py
# class ShiftScaleTransform:
# """Data normalizer."""
#
# # vectors is an array of vectors
# def __init__(self, vectors):
# vectors_concat = jnp.concatenate(vectors)
# self.mean = jnp.mean(vectors_concat)
# self.std = jnp.std(vectors_concat)
# print(self.mean, self.std)
#
# def _transform(self, x, mean, std):
# return (x - mean) / std
#
# def _inverse_transform(self, x, mean, std):
# return (x * std) + mean
#
# def __call__(self, vector):
# return self._transform(vector, self.mean, self.std)
#
# def inverse(self, vector):
# return self._inverse_transform(vector, self.mean, self.std)
#
# Path: deluca/lung/utils/nn/mlp.py
# class MLP(nn.Module):
# """multilayered perceptron."""
# hidden_dim: int = 10
# out_dim: int = 1
# n_layers: int = 2
# droprate: float = 0.0
# activation_fn: Callable = nn.relu
#
# @nn.compact
# def __call__(self, x):
# for i in range(self.n_layers - 1):
# x = nn.Dense(
# features=self.hidden_dim, use_bias=True, name=f"MLP_fc{i}")(
# x)
# x = nn.Dropout(
# rate=self.droprate, deterministic=False)(
# x, rng=jax.random.PRNGKey(0))
# x = self.activation_fn(x)
# x = nn.Dense(features=self.out_dim, use_bias=True, name=f"MLP_fc{i + 1}")(x)
# return x.squeeze() # squeeze for consistent shape w/ boundary model output
#
# Path: deluca/lung/utils/nn/shallow_boundary_model.py
# class ShallowBoundaryModel(nn.Module):
# """Shallow boundary module."""
# out_dim: int = 1
# hidden_dim: int = 100
# model_num: int = 0
#
# @nn.compact
# def __call__(self, x):
# # need to flatten extra dimensions required by CNN and LSTM
# x = x.squeeze()
# x = nn.Dense(
# features=self.hidden_dim,
# use_bias=False,
# name=f"shallow_fc{1}_model" + str(self.model_num),
# )(
# x)
# x = nn.tanh(x)
# x = nn.Dense(
# features=self.out_dim,
# use_bias=True,
# name=f"shallow_fc{2}_model" + str(self.model_num))(
# x)
# return x.squeeze() # squeeze for consistent shape w/ boundary model output
, which may include functions, classes, or code. Output only the next line. | class LearnedLung(LungEnv): |
Predict the next line for this snippet: <|code_start|> [state.u_history[-u_history_len:], state.p_history[-p_history_len:]])
default_features = jnp.hstack(
[state.u_history[-u_window:], state.p_history[-p_window:]])
default_pad_len = (u_history_len + p_history_len) - (u_window + p_window)
default_features = jnp.hstack(
[jnp.zeros((default_pad_len,)), default_features])
features = jax.lax.cond(
model_idx == num_boundary_models,
lambda x: default_features,
lambda x: boundary_features,
None,
)
normalized_pressure = jax.lax.switch(model_idx, funcs, features)
normalized_pressure = normalized_pressure.astype(jnp.float64)
state = state.replace(predicted_pressure=normalized_pressure)
new_p_history = update_history(state.p_history, normalized_pressure)
state = state.replace(p_history=new_p_history
) # just for inference. This is undone during training
state = sync_unnormalized_pressure(state) # unscale predicted pressure
return state
class LearnedLung(LungEnv):
"""Learned lung."""
params: list = deluca.field(jaxed=True)
init_rng: jnp.array = deluca.field(jaxed=False)
u_window: int = deluca.field(5, jaxed=False)
p_window: int = deluca.field(3, jaxed=False)
u_history_len: int = deluca.field(5, jaxed=False)
p_history_len: int = deluca.field(5, jaxed=False)
<|code_end|>
with the help of current file imports:
import functools
import deluca.core
import flax.linen as nn
import jax
import jax.numpy as jnp
from typing import Any, Dict
from deluca.lung.core import LungEnv
from deluca.lung.utils.data.transform import ShiftScaleTransform
from deluca.lung.utils.nn import MLP
from deluca.lung.utils.nn import ShallowBoundaryModel
and context from other files:
# Path: deluca/lung/core.py
# class LungEnv(deluca.Env):
# """Lung environment."""
#
# def time(self, state):
# return self.dt * state.steps
#
# @property
# def dt(self):
# return DEFAULT_DT
#
# @property
# def physical(self):
# return False
#
# def should_abort(self):
# return False
#
# def wait(self, duration):
# pass
#
# def cleanup(self):
# pass
#
# Path: deluca/lung/utils/data/transform.py
# class ShiftScaleTransform:
# """Data normalizer."""
#
# # vectors is an array of vectors
# def __init__(self, vectors):
# vectors_concat = jnp.concatenate(vectors)
# self.mean = jnp.mean(vectors_concat)
# self.std = jnp.std(vectors_concat)
# print(self.mean, self.std)
#
# def _transform(self, x, mean, std):
# return (x - mean) / std
#
# def _inverse_transform(self, x, mean, std):
# return (x * std) + mean
#
# def __call__(self, vector):
# return self._transform(vector, self.mean, self.std)
#
# def inverse(self, vector):
# return self._inverse_transform(vector, self.mean, self.std)
#
# Path: deluca/lung/utils/nn/mlp.py
# class MLP(nn.Module):
# """multilayered perceptron."""
# hidden_dim: int = 10
# out_dim: int = 1
# n_layers: int = 2
# droprate: float = 0.0
# activation_fn: Callable = nn.relu
#
# @nn.compact
# def __call__(self, x):
# for i in range(self.n_layers - 1):
# x = nn.Dense(
# features=self.hidden_dim, use_bias=True, name=f"MLP_fc{i}")(
# x)
# x = nn.Dropout(
# rate=self.droprate, deterministic=False)(
# x, rng=jax.random.PRNGKey(0))
# x = self.activation_fn(x)
# x = nn.Dense(features=self.out_dim, use_bias=True, name=f"MLP_fc{i + 1}")(x)
# return x.squeeze() # squeeze for consistent shape w/ boundary model output
#
# Path: deluca/lung/utils/nn/shallow_boundary_model.py
# class ShallowBoundaryModel(nn.Module):
# """Shallow boundary module."""
# out_dim: int = 1
# hidden_dim: int = 100
# model_num: int = 0
#
# @nn.compact
# def __call__(self, x):
# # need to flatten extra dimensions required by CNN and LSTM
# x = x.squeeze()
# x = nn.Dense(
# features=self.hidden_dim,
# use_bias=False,
# name=f"shallow_fc{1}_model" + str(self.model_num),
# )(
# x)
# x = nn.tanh(x)
# x = nn.Dense(
# features=self.out_dim,
# use_bias=True,
# name=f"shallow_fc{2}_model" + str(self.model_num))(
# x)
# return x.squeeze() # squeeze for consistent shape w/ boundary model output
, which may contain function names, class names, or code. Output only the next line. | u_normalizer: ShiftScaleTransform = deluca.field(jaxed=False) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.