Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Based on the snippet: <|code_start|>
def __next__(self):
cmd = self.stream.read_vint()
if cmd == bp.AUTHENTICATION_RESP:
return cmd, self.stream.read_tuple("b")
elif cmd == bp.OUTPUT:
return cmd, self.stream.read_tuple("bb")
elif cmd == bp.PARTITIONED_OUTPUT:
return cmd, self.stream.write_tuple("ibb")
elif cmd == bp.STATUS:
return cmd, self.stream.read_tuple("s")
elif cmd == bp.PROGRESS:
return cmd, self.stream.read_tuple("f")
elif cmd == bp.REGISTER_COUNTER:
return cmd, self.stream.read_tuple("iss")
elif cmd == bp.INCREMENT_COUNTER:
return cmd, self.stream.read_tuple("il")
elif cmd == bp.DONE:
raise StopIteration
else:
raise RuntimeError("unknown command: %d" % cmd)
def __iter__(self):
return self
# py2 compat
def next(self):
return self.__next__()
<|code_end|>
, predict the immediate next line with the help of imports:
import io
import os
import unittest
import pydoop.mapreduce.api as api
import pydoop.mapreduce.binary_protocol as bp
import pydoop.mapreduce.pipes as pipes
import pydoop.sercore as sercore
from pydoop.test_utils import WDTestCase
and context (classes, functions, sometimes code) from other files:
# Path: pydoop/test_utils.py
# class WDTestCase(unittest.TestCase):
#
# def setUp(self):
# self.wd = tempfile.mkdtemp(prefix='pydoop_test_')
#
# def tearDown(self):
# shutil.rmtree(self.wd)
#
# def _mkfn(self, basename):
# return os.path.join(self.wd, basename)
#
# def _mkf(self, basename, mode='w'):
# return open(self._mkfn(basename), mode)
. Output only the next line. | class TestFileConnection(WDTestCase): |
Here is a snippet: <|code_start|> return not roles.isdisjoint(user_roles)
async def on_message(self, message):
if message.channel != self.channel:
return
user = message.author
name = user.name
data = message.content
config = self.script.config
command_prefix = config.command_prefix
chat_prefix = config.chat_prefix
if data.startswith(command_prefix):
if not self.has_role(user, config.command_roles):
return
cmd = data[len(command_prefix):]
result = self.handle_command(name, cmd)
if not result:
return
self.send(f'{user.mention}: {result}')
elif data.startswith(chat_prefix):
top_role = user.top_role
if not self.has_role(user, config.chat_roles):
return
data = data[len(chat_prefix):].strip()
message = '<%s> %s' % (name, data)
message = message[:MAX_DISCORD_CHAT_SIZE]
print(message)
self.server.send_chat(message)
def handle_command(self, name, command):
<|code_end|>
. Write the next line using the current file imports:
import discord
from cuwo.common import parse_command
from cuwo.script import ServerScript, ConnectionScript, ScriptInterface
and context from other files:
# Path: cuwo/common.py
# def parse_command(message):
# try:
# args = shlex.split(message)
# except ValueError:
# # shlex failed. let's just split per space
# args = message.split(' ')
# if args:
# command = args.pop(0)
# else:
# command = ''
# return command, args
#
# Path: cuwo/script.py
# class ServerScript(BaseScript):
# connection_class = ConnectionScript
# commands = None
# aliases = None
#
# def __init__(self, server):
# self.script_name = self.__module__.split('.')[1]
#
# self.server = server
# self.world = server.world
# self.loop = server.loop
# server.scripts.add(self)
# self.children = []
# self.on_load()
# for connection in server.connections:
# self.call('on_existing_connection', connection=connection)
#
# def on_new_connection(self, event):
# if self.connection_class is None:
# return
# script = self.connection_class(self, event.connection)
# script.call('on_connect')
#
# def on_existing_connection(self, event):
# if self.connection_class is None:
# return
# self.connection_class(self, event.connection)
#
# def on_command(self, event):
# return self.call_command(event.user, event.command, event.args)
#
# def unload(self):
# if self.server is None:
# return
# self.on_unload()
# self.server.scripts.remove(self)
# for script in self.children[:]:
# script.unload()
# self.children = None
# self.server = None
# self.world = None
#
# def call_command(self, user, command, args):
# if self.commands is None:
# return
# command = command.lower()
# command = self.aliases.get(command, command)
# command = self.commands.get(command, None)
# if not command:
# return
# user.parent = self # for ScriptInterface
#
# if len(args) < command.min_args:
# return command.get_syntax()
# if command.max_args is not None and len(args) > command.max_args:
# return command.get_syntax()
#
# try:
# ret = command(user, *args) or ''
# except InvalidPlayer:
# ret = 'Invalid player specified'
# except InsufficientRights:
# ret = 'Insufficient rights'
# except Exception:
# import traceback
# traceback.print_exc()
# ret = ''
# return ret
#
# class ConnectionScript(BaseScript):
# def __init__(self, parent, connection):
# self.script_name = parent.script_name
#
# self.parent = parent
# self.server = parent.server
# self.world = parent.world
# self.loop = connection.loop
# self.connection = connection
# connection.scripts.add(self)
# parent.children.append(self)
# self.on_load()
#
# def on_disconnect(self, event):
# self.unload()
#
# def on_command(self, event):
# ret = self.parent.call_command(self, event.command, event.args)
# if ret is None:
# return
# if ret:
# self.connection.send_chat(ret)
# return False
#
# def get_player(self, name=None):
# if name is None:
# return self.connection
# return get_player(self.server, name)
#
# def get_commands(self):
# rights = self.connection.rights
# for command in self.server.get_commands():
# if command.is_compatible(rights):
# yield command
#
# def get_command(self, name):
# command = self.server.get_command(name)
# if not command:
# return
# if not command.is_compatible(self.connection.rights):
# return
# return command
#
# def unload(self):
# if self.parent is None:
# return
# self.connection.scripts.remove(self)
# self.parent.children.remove(self)
# self.on_unload()
# self.parent = None
# self.connection = None
# self.server = None
# self.world = None
#
# @property
# def entity(self):
# return self.connection.entity
#
# class ScriptInterface:
# """
# Used for external script interfaces to emulate a connection for e.g.
# console and IRC commands
# """
#
# def __init__(self, name, server, *rights):
# self.name = name
# self.rights = AttributeSet(rights)
# self.server = server
# self.connection = self
# self.parent = None # set by call_command
#
# def get_player(self, name):
# if name is None:
# raise InvalidPlayer()
# return get_player(self.server, name)
#
# def get_commands(self):
# return self.server.get_commands()
#
# def get_command(self, name):
# return self.server.get_command(name)
, which may include functions, classes, or code. Output only the next line. | command, args = parse_command(command) |
Using the snippet: <|code_start|> def handle_command(self, name, command):
command, args = parse_command(command)
try:
return self.commands[command](self, *args)
except KeyError:
pass
ret = self.server.call_command(self.interface, command, args)
if ret is not None:
return ret
return 'Invalid command'
def send(self, msg):
if self.channel is None:
return
self.loop.create_task(self.send_message(self.channel, msg))
class DiscordScriptConnection(ConnectionScript):
def on_join(self, event):
self.parent.send(f'{self.connection.name} entered the game')
def on_unload(self):
if not self.connection.has_joined:
return
self.parent.send(f'{self.connection.name} disconnected')
def on_chat(self, event):
self.parent.send(f'<{self.connection.name}> {event.message}')
<|code_end|>
, determine the next line of code. You have imports:
import discord
from cuwo.common import parse_command
from cuwo.script import ServerScript, ConnectionScript, ScriptInterface
and context (class names, function names, or code) available:
# Path: cuwo/common.py
# def parse_command(message):
# try:
# args = shlex.split(message)
# except ValueError:
# # shlex failed. let's just split per space
# args = message.split(' ')
# if args:
# command = args.pop(0)
# else:
# command = ''
# return command, args
#
# Path: cuwo/script.py
# class ServerScript(BaseScript):
# connection_class = ConnectionScript
# commands = None
# aliases = None
#
# def __init__(self, server):
# self.script_name = self.__module__.split('.')[1]
#
# self.server = server
# self.world = server.world
# self.loop = server.loop
# server.scripts.add(self)
# self.children = []
# self.on_load()
# for connection in server.connections:
# self.call('on_existing_connection', connection=connection)
#
# def on_new_connection(self, event):
# if self.connection_class is None:
# return
# script = self.connection_class(self, event.connection)
# script.call('on_connect')
#
# def on_existing_connection(self, event):
# if self.connection_class is None:
# return
# self.connection_class(self, event.connection)
#
# def on_command(self, event):
# return self.call_command(event.user, event.command, event.args)
#
# def unload(self):
# if self.server is None:
# return
# self.on_unload()
# self.server.scripts.remove(self)
# for script in self.children[:]:
# script.unload()
# self.children = None
# self.server = None
# self.world = None
#
# def call_command(self, user, command, args):
# if self.commands is None:
# return
# command = command.lower()
# command = self.aliases.get(command, command)
# command = self.commands.get(command, None)
# if not command:
# return
# user.parent = self # for ScriptInterface
#
# if len(args) < command.min_args:
# return command.get_syntax()
# if command.max_args is not None and len(args) > command.max_args:
# return command.get_syntax()
#
# try:
# ret = command(user, *args) or ''
# except InvalidPlayer:
# ret = 'Invalid player specified'
# except InsufficientRights:
# ret = 'Insufficient rights'
# except Exception:
# import traceback
# traceback.print_exc()
# ret = ''
# return ret
#
# class ConnectionScript(BaseScript):
# def __init__(self, parent, connection):
# self.script_name = parent.script_name
#
# self.parent = parent
# self.server = parent.server
# self.world = parent.world
# self.loop = connection.loop
# self.connection = connection
# connection.scripts.add(self)
# parent.children.append(self)
# self.on_load()
#
# def on_disconnect(self, event):
# self.unload()
#
# def on_command(self, event):
# ret = self.parent.call_command(self, event.command, event.args)
# if ret is None:
# return
# if ret:
# self.connection.send_chat(ret)
# return False
#
# def get_player(self, name=None):
# if name is None:
# return self.connection
# return get_player(self.server, name)
#
# def get_commands(self):
# rights = self.connection.rights
# for command in self.server.get_commands():
# if command.is_compatible(rights):
# yield command
#
# def get_command(self, name):
# command = self.server.get_command(name)
# if not command:
# return
# if not command.is_compatible(self.connection.rights):
# return
# return command
#
# def unload(self):
# if self.parent is None:
# return
# self.connection.scripts.remove(self)
# self.parent.children.remove(self)
# self.on_unload()
# self.parent = None
# self.connection = None
# self.server = None
# self.world = None
#
# @property
# def entity(self):
# return self.connection.entity
#
# class ScriptInterface:
# """
# Used for external script interfaces to emulate a connection for e.g.
# console and IRC commands
# """
#
# def __init__(self, name, server, *rights):
# self.name = name
# self.rights = AttributeSet(rights)
# self.server = server
# self.connection = self
# self.parent = None # set by call_command
#
# def get_player(self, name):
# if name is None:
# raise InvalidPlayer()
# return get_player(self.server, name)
#
# def get_commands(self):
# return self.server.get_commands()
#
# def get_command(self, name):
# return self.server.get_command(name)
. Output only the next line. | class DiscordScriptServer(ServerScript): |
Given the following code snippet before the placeholder: <|code_start|> if not result:
return
self.send(f'{user.mention}: {result}')
elif data.startswith(chat_prefix):
top_role = user.top_role
if not self.has_role(user, config.chat_roles):
return
data = data[len(chat_prefix):].strip()
message = '<%s> %s' % (name, data)
message = message[:MAX_DISCORD_CHAT_SIZE]
print(message)
self.server.send_chat(message)
def handle_command(self, name, command):
command, args = parse_command(command)
try:
return self.commands[command](self, *args)
except KeyError:
pass
ret = self.server.call_command(self.interface, command, args)
if ret is not None:
return ret
return 'Invalid command'
def send(self, msg):
if self.channel is None:
return
self.loop.create_task(self.send_message(self.channel, msg))
<|code_end|>
, predict the next line using imports from the current file:
import discord
from cuwo.common import parse_command
from cuwo.script import ServerScript, ConnectionScript, ScriptInterface
and context including class names, function names, and sometimes code from other files:
# Path: cuwo/common.py
# def parse_command(message):
# try:
# args = shlex.split(message)
# except ValueError:
# # shlex failed. let's just split per space
# args = message.split(' ')
# if args:
# command = args.pop(0)
# else:
# command = ''
# return command, args
#
# Path: cuwo/script.py
# class ServerScript(BaseScript):
# connection_class = ConnectionScript
# commands = None
# aliases = None
#
# def __init__(self, server):
# self.script_name = self.__module__.split('.')[1]
#
# self.server = server
# self.world = server.world
# self.loop = server.loop
# server.scripts.add(self)
# self.children = []
# self.on_load()
# for connection in server.connections:
# self.call('on_existing_connection', connection=connection)
#
# def on_new_connection(self, event):
# if self.connection_class is None:
# return
# script = self.connection_class(self, event.connection)
# script.call('on_connect')
#
# def on_existing_connection(self, event):
# if self.connection_class is None:
# return
# self.connection_class(self, event.connection)
#
# def on_command(self, event):
# return self.call_command(event.user, event.command, event.args)
#
# def unload(self):
# if self.server is None:
# return
# self.on_unload()
# self.server.scripts.remove(self)
# for script in self.children[:]:
# script.unload()
# self.children = None
# self.server = None
# self.world = None
#
# def call_command(self, user, command, args):
# if self.commands is None:
# return
# command = command.lower()
# command = self.aliases.get(command, command)
# command = self.commands.get(command, None)
# if not command:
# return
# user.parent = self # for ScriptInterface
#
# if len(args) < command.min_args:
# return command.get_syntax()
# if command.max_args is not None and len(args) > command.max_args:
# return command.get_syntax()
#
# try:
# ret = command(user, *args) or ''
# except InvalidPlayer:
# ret = 'Invalid player specified'
# except InsufficientRights:
# ret = 'Insufficient rights'
# except Exception:
# import traceback
# traceback.print_exc()
# ret = ''
# return ret
#
# class ConnectionScript(BaseScript):
# def __init__(self, parent, connection):
# self.script_name = parent.script_name
#
# self.parent = parent
# self.server = parent.server
# self.world = parent.world
# self.loop = connection.loop
# self.connection = connection
# connection.scripts.add(self)
# parent.children.append(self)
# self.on_load()
#
# def on_disconnect(self, event):
# self.unload()
#
# def on_command(self, event):
# ret = self.parent.call_command(self, event.command, event.args)
# if ret is None:
# return
# if ret:
# self.connection.send_chat(ret)
# return False
#
# def get_player(self, name=None):
# if name is None:
# return self.connection
# return get_player(self.server, name)
#
# def get_commands(self):
# rights = self.connection.rights
# for command in self.server.get_commands():
# if command.is_compatible(rights):
# yield command
#
# def get_command(self, name):
# command = self.server.get_command(name)
# if not command:
# return
# if not command.is_compatible(self.connection.rights):
# return
# return command
#
# def unload(self):
# if self.parent is None:
# return
# self.connection.scripts.remove(self)
# self.parent.children.remove(self)
# self.on_unload()
# self.parent = None
# self.connection = None
# self.server = None
# self.world = None
#
# @property
# def entity(self):
# return self.connection.entity
#
# class ScriptInterface:
# """
# Used for external script interfaces to emulate a connection for e.g.
# console and IRC commands
# """
#
# def __init__(self, name, server, *rights):
# self.name = name
# self.rights = AttributeSet(rights)
# self.server = server
# self.connection = self
# self.parent = None # set by call_command
#
# def get_player(self, name):
# if name is None:
# raise InvalidPlayer()
# return get_player(self.server, name)
#
# def get_commands(self):
# return self.server.get_commands()
#
# def get_command(self, name):
# return self.server.get_command(name)
. Output only the next line. | class DiscordScriptConnection(ConnectionScript): |
Given the following code snippet before the placeholder: <|code_start|># cuwo is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cuwo. If not, see <http://www.gnu.org/licenses/>.
"""
Discord client that can be used as a way to control the game server
Depends on the discord package. Install with:
pip install -U discord.py
"""
MAX_DISCORD_CHAT_SIZE = 100
class DiscordClient(discord.Client):
commands = {}
channel = None
def __init__(self, script):
super().__init__()
self.script = script
self.loop = script.loop
self.server = self.script.server
config = self.script.config
<|code_end|>
, predict the next line using imports from the current file:
import discord
from cuwo.common import parse_command
from cuwo.script import ServerScript, ConnectionScript, ScriptInterface
and context including class names, function names, and sometimes code from other files:
# Path: cuwo/common.py
# def parse_command(message):
# try:
# args = shlex.split(message)
# except ValueError:
# # shlex failed. let's just split per space
# args = message.split(' ')
# if args:
# command = args.pop(0)
# else:
# command = ''
# return command, args
#
# Path: cuwo/script.py
# class ServerScript(BaseScript):
# connection_class = ConnectionScript
# commands = None
# aliases = None
#
# def __init__(self, server):
# self.script_name = self.__module__.split('.')[1]
#
# self.server = server
# self.world = server.world
# self.loop = server.loop
# server.scripts.add(self)
# self.children = []
# self.on_load()
# for connection in server.connections:
# self.call('on_existing_connection', connection=connection)
#
# def on_new_connection(self, event):
# if self.connection_class is None:
# return
# script = self.connection_class(self, event.connection)
# script.call('on_connect')
#
# def on_existing_connection(self, event):
# if self.connection_class is None:
# return
# self.connection_class(self, event.connection)
#
# def on_command(self, event):
# return self.call_command(event.user, event.command, event.args)
#
# def unload(self):
# if self.server is None:
# return
# self.on_unload()
# self.server.scripts.remove(self)
# for script in self.children[:]:
# script.unload()
# self.children = None
# self.server = None
# self.world = None
#
# def call_command(self, user, command, args):
# if self.commands is None:
# return
# command = command.lower()
# command = self.aliases.get(command, command)
# command = self.commands.get(command, None)
# if not command:
# return
# user.parent = self # for ScriptInterface
#
# if len(args) < command.min_args:
# return command.get_syntax()
# if command.max_args is not None and len(args) > command.max_args:
# return command.get_syntax()
#
# try:
# ret = command(user, *args) or ''
# except InvalidPlayer:
# ret = 'Invalid player specified'
# except InsufficientRights:
# ret = 'Insufficient rights'
# except Exception:
# import traceback
# traceback.print_exc()
# ret = ''
# return ret
#
# class ConnectionScript(BaseScript):
# def __init__(self, parent, connection):
# self.script_name = parent.script_name
#
# self.parent = parent
# self.server = parent.server
# self.world = parent.world
# self.loop = connection.loop
# self.connection = connection
# connection.scripts.add(self)
# parent.children.append(self)
# self.on_load()
#
# def on_disconnect(self, event):
# self.unload()
#
# def on_command(self, event):
# ret = self.parent.call_command(self, event.command, event.args)
# if ret is None:
# return
# if ret:
# self.connection.send_chat(ret)
# return False
#
# def get_player(self, name=None):
# if name is None:
# return self.connection
# return get_player(self.server, name)
#
# def get_commands(self):
# rights = self.connection.rights
# for command in self.server.get_commands():
# if command.is_compatible(rights):
# yield command
#
# def get_command(self, name):
# command = self.server.get_command(name)
# if not command:
# return
# if not command.is_compatible(self.connection.rights):
# return
# return command
#
# def unload(self):
# if self.parent is None:
# return
# self.connection.scripts.remove(self)
# self.parent.children.remove(self)
# self.on_unload()
# self.parent = None
# self.connection = None
# self.server = None
# self.world = None
#
# @property
# def entity(self):
# return self.connection.entity
#
# class ScriptInterface:
# """
# Used for external script interfaces to emulate a connection for e.g.
# console and IRC commands
# """
#
# def __init__(self, name, server, *rights):
# self.name = name
# self.rights = AttributeSet(rights)
# self.server = server
# self.connection = self
# self.parent = None # set by call_command
#
# def get_player(self, name):
# if name is None:
# raise InvalidPlayer()
# return get_player(self.server, name)
#
# def get_commands(self):
# return self.server.get_commands()
#
# def get_command(self, name):
# return self.server.get_command(name)
. Output only the next line. | self.interface = ScriptInterface('Discord', self.server, |
Given the following code snippet before the placeholder: <|code_start|>
@irc3.event(irc3.rfc.PRIVMSG)
def on_privmsg(self, mask, event, target, data=None):
if event != 'PRIVMSG':
return
user = mask.nick
if user in self.command_users:
prefix = '@'
elif user in self.chat_users:
prefix = '+'
else:
return
prefix = '@' if user in self.command_users else '+'
name = prefix + user
if data.startswith(self.command_prefix):
if user not in self.command_users:
return
cmd = data[len(self.command_prefix):]
result = self.handle_command(name, cmd)
if result is None:
return
self.send('%s: %s' % (user, result))
elif data.startswith(self.chat_prefix):
data = data[len(self.chat_prefix):].strip()
message = '<%s> %s' % (name, data)
message = message[:MAX_IRC_CHAT_SIZE]
print(message)
self.server.send_chat(message)
def handle_command(self, name, command):
<|code_end|>
, predict the next line using imports from the current file:
import irc3
from cuwo.common import parse_command
from cuwo.script import ServerScript, ConnectionScript, ScriptInterface
and context including class names, function names, and sometimes code from other files:
# Path: cuwo/common.py
# def parse_command(message):
# try:
# args = shlex.split(message)
# except ValueError:
# # shlex failed. let's just split per space
# args = message.split(' ')
# if args:
# command = args.pop(0)
# else:
# command = ''
# return command, args
#
# Path: cuwo/script.py
# class ServerScript(BaseScript):
# connection_class = ConnectionScript
# commands = None
# aliases = None
#
# def __init__(self, server):
# self.script_name = self.__module__.split('.')[1]
#
# self.server = server
# self.world = server.world
# self.loop = server.loop
# server.scripts.add(self)
# self.children = []
# self.on_load()
# for connection in server.connections:
# self.call('on_existing_connection', connection=connection)
#
# def on_new_connection(self, event):
# if self.connection_class is None:
# return
# script = self.connection_class(self, event.connection)
# script.call('on_connect')
#
# def on_existing_connection(self, event):
# if self.connection_class is None:
# return
# self.connection_class(self, event.connection)
#
# def on_command(self, event):
# return self.call_command(event.user, event.command, event.args)
#
# def unload(self):
# if self.server is None:
# return
# self.on_unload()
# self.server.scripts.remove(self)
# for script in self.children[:]:
# script.unload()
# self.children = None
# self.server = None
# self.world = None
#
# def call_command(self, user, command, args):
# if self.commands is None:
# return
# command = command.lower()
# command = self.aliases.get(command, command)
# command = self.commands.get(command, None)
# if not command:
# return
# user.parent = self # for ScriptInterface
#
# if len(args) < command.min_args:
# return command.get_syntax()
# if command.max_args is not None and len(args) > command.max_args:
# return command.get_syntax()
#
# try:
# ret = command(user, *args) or ''
# except InvalidPlayer:
# ret = 'Invalid player specified'
# except InsufficientRights:
# ret = 'Insufficient rights'
# except Exception:
# import traceback
# traceback.print_exc()
# ret = ''
# return ret
#
# class ConnectionScript(BaseScript):
# def __init__(self, parent, connection):
# self.script_name = parent.script_name
#
# self.parent = parent
# self.server = parent.server
# self.world = parent.world
# self.loop = connection.loop
# self.connection = connection
# connection.scripts.add(self)
# parent.children.append(self)
# self.on_load()
#
# def on_disconnect(self, event):
# self.unload()
#
# def on_command(self, event):
# ret = self.parent.call_command(self, event.command, event.args)
# if ret is None:
# return
# if ret:
# self.connection.send_chat(ret)
# return False
#
# def get_player(self, name=None):
# if name is None:
# return self.connection
# return get_player(self.server, name)
#
# def get_commands(self):
# rights = self.connection.rights
# for command in self.server.get_commands():
# if command.is_compatible(rights):
# yield command
#
# def get_command(self, name):
# command = self.server.get_command(name)
# if not command:
# return
# if not command.is_compatible(self.connection.rights):
# return
# return command
#
# def unload(self):
# if self.parent is None:
# return
# self.connection.scripts.remove(self)
# self.parent.children.remove(self)
# self.on_unload()
# self.parent = None
# self.connection = None
# self.server = None
# self.world = None
#
# @property
# def entity(self):
# return self.connection.entity
#
# class ScriptInterface:
# """
# Used for external script interfaces to emulate a connection for e.g.
# console and IRC commands
# """
#
# def __init__(self, name, server, *rights):
# self.name = name
# self.rights = AttributeSet(rights)
# self.server = server
# self.connection = self
# self.parent = None # set by call_command
#
# def get_player(self, name):
# if name is None:
# raise InvalidPlayer()
# return get_player(self.server, name)
#
# def get_commands(self):
# return self.server.get_commands()
#
# def get_command(self, name):
# return self.server.get_command(name)
. Output only the next line. | command, args = parse_command(command) |
Here is a snippet: <|code_start|> users.add(name)
else:
users.discard(name)
def send(self, msg):
self.bot.privmsg(self.script.channel, msg)
def me(self, msg):
msg = 'ACTION ' + msg
self.bot.ctcp(self.script.channel, msg)
class IRCScriptConnection(ConnectionScript):
def on_join(self, event):
self.parent.send('* %s entered the game' % self.connection.name)
def on_unload(self):
if not self.connection.has_joined:
return
self.parent.send('* %s disconnected' % self.connection.name)
def on_chat(self, event):
message = '<\x0306%s\x0F> %s' % (self.connection.name, event.message)
self.parent.send(message)
def unpack_modes(value):
return {item for sublist in value for item in sublist}
<|code_end|>
. Write the next line using the current file imports:
import irc3
from cuwo.common import parse_command
from cuwo.script import ServerScript, ConnectionScript, ScriptInterface
and context from other files:
# Path: cuwo/common.py
# def parse_command(message):
# try:
# args = shlex.split(message)
# except ValueError:
# # shlex failed. let's just split per space
# args = message.split(' ')
# if args:
# command = args.pop(0)
# else:
# command = ''
# return command, args
#
# Path: cuwo/script.py
# class ServerScript(BaseScript):
# connection_class = ConnectionScript
# commands = None
# aliases = None
#
# def __init__(self, server):
# self.script_name = self.__module__.split('.')[1]
#
# self.server = server
# self.world = server.world
# self.loop = server.loop
# server.scripts.add(self)
# self.children = []
# self.on_load()
# for connection in server.connections:
# self.call('on_existing_connection', connection=connection)
#
# def on_new_connection(self, event):
# if self.connection_class is None:
# return
# script = self.connection_class(self, event.connection)
# script.call('on_connect')
#
# def on_existing_connection(self, event):
# if self.connection_class is None:
# return
# self.connection_class(self, event.connection)
#
# def on_command(self, event):
# return self.call_command(event.user, event.command, event.args)
#
# def unload(self):
# if self.server is None:
# return
# self.on_unload()
# self.server.scripts.remove(self)
# for script in self.children[:]:
# script.unload()
# self.children = None
# self.server = None
# self.world = None
#
# def call_command(self, user, command, args):
# if self.commands is None:
# return
# command = command.lower()
# command = self.aliases.get(command, command)
# command = self.commands.get(command, None)
# if not command:
# return
# user.parent = self # for ScriptInterface
#
# if len(args) < command.min_args:
# return command.get_syntax()
# if command.max_args is not None and len(args) > command.max_args:
# return command.get_syntax()
#
# try:
# ret = command(user, *args) or ''
# except InvalidPlayer:
# ret = 'Invalid player specified'
# except InsufficientRights:
# ret = 'Insufficient rights'
# except Exception:
# import traceback
# traceback.print_exc()
# ret = ''
# return ret
#
# class ConnectionScript(BaseScript):
# def __init__(self, parent, connection):
# self.script_name = parent.script_name
#
# self.parent = parent
# self.server = parent.server
# self.world = parent.world
# self.loop = connection.loop
# self.connection = connection
# connection.scripts.add(self)
# parent.children.append(self)
# self.on_load()
#
# def on_disconnect(self, event):
# self.unload()
#
# def on_command(self, event):
# ret = self.parent.call_command(self, event.command, event.args)
# if ret is None:
# return
# if ret:
# self.connection.send_chat(ret)
# return False
#
# def get_player(self, name=None):
# if name is None:
# return self.connection
# return get_player(self.server, name)
#
# def get_commands(self):
# rights = self.connection.rights
# for command in self.server.get_commands():
# if command.is_compatible(rights):
# yield command
#
# def get_command(self, name):
# command = self.server.get_command(name)
# if not command:
# return
# if not command.is_compatible(self.connection.rights):
# return
# return command
#
# def unload(self):
# if self.parent is None:
# return
# self.connection.scripts.remove(self)
# self.parent.children.remove(self)
# self.on_unload()
# self.parent = None
# self.connection = None
# self.server = None
# self.world = None
#
# @property
# def entity(self):
# return self.connection.entity
#
# class ScriptInterface:
# """
# Used for external script interfaces to emulate a connection for e.g.
# console and IRC commands
# """
#
# def __init__(self, name, server, *rights):
# self.name = name
# self.rights = AttributeSet(rights)
# self.server = server
# self.connection = self
# self.parent = None # set by call_command
#
# def get_player(self, name):
# if name is None:
# raise InvalidPlayer()
# return get_player(self.server, name)
#
# def get_commands(self):
# return self.server.get_commands()
#
# def get_command(self, name):
# return self.server.get_command(name)
, which may include functions, classes, or code. Output only the next line. | class IRCScriptServer(ServerScript): |
Given the following code snippet before the placeholder: <|code_start|> modes, names = params[0], params[1:]
if modes[0] not in '-+':
modes = '+' + modes
if channel == self.bot.nick:
return
for c in modes:
if c in '-+':
sign = c
continue
name = names.pop(0)
try:
users = self.mode_dict[c]
except KeyError:
continue
if sign == '+':
users.add(name)
else:
users.discard(name)
def send(self, msg):
self.bot.privmsg(self.script.channel, msg)
def me(self, msg):
msg = 'ACTION ' + msg
self.bot.ctcp(self.script.channel, msg)
<|code_end|>
, predict the next line using imports from the current file:
import irc3
from cuwo.common import parse_command
from cuwo.script import ServerScript, ConnectionScript, ScriptInterface
and context including class names, function names, and sometimes code from other files:
# Path: cuwo/common.py
# def parse_command(message):
# try:
# args = shlex.split(message)
# except ValueError:
# # shlex failed. let's just split per space
# args = message.split(' ')
# if args:
# command = args.pop(0)
# else:
# command = ''
# return command, args
#
# Path: cuwo/script.py
# class ServerScript(BaseScript):
# connection_class = ConnectionScript
# commands = None
# aliases = None
#
# def __init__(self, server):
# self.script_name = self.__module__.split('.')[1]
#
# self.server = server
# self.world = server.world
# self.loop = server.loop
# server.scripts.add(self)
# self.children = []
# self.on_load()
# for connection in server.connections:
# self.call('on_existing_connection', connection=connection)
#
# def on_new_connection(self, event):
# if self.connection_class is None:
# return
# script = self.connection_class(self, event.connection)
# script.call('on_connect')
#
# def on_existing_connection(self, event):
# if self.connection_class is None:
# return
# self.connection_class(self, event.connection)
#
# def on_command(self, event):
# return self.call_command(event.user, event.command, event.args)
#
# def unload(self):
# if self.server is None:
# return
# self.on_unload()
# self.server.scripts.remove(self)
# for script in self.children[:]:
# script.unload()
# self.children = None
# self.server = None
# self.world = None
#
# def call_command(self, user, command, args):
# if self.commands is None:
# return
# command = command.lower()
# command = self.aliases.get(command, command)
# command = self.commands.get(command, None)
# if not command:
# return
# user.parent = self # for ScriptInterface
#
# if len(args) < command.min_args:
# return command.get_syntax()
# if command.max_args is not None and len(args) > command.max_args:
# return command.get_syntax()
#
# try:
# ret = command(user, *args) or ''
# except InvalidPlayer:
# ret = 'Invalid player specified'
# except InsufficientRights:
# ret = 'Insufficient rights'
# except Exception:
# import traceback
# traceback.print_exc()
# ret = ''
# return ret
#
# class ConnectionScript(BaseScript):
# def __init__(self, parent, connection):
# self.script_name = parent.script_name
#
# self.parent = parent
# self.server = parent.server
# self.world = parent.world
# self.loop = connection.loop
# self.connection = connection
# connection.scripts.add(self)
# parent.children.append(self)
# self.on_load()
#
# def on_disconnect(self, event):
# self.unload()
#
# def on_command(self, event):
# ret = self.parent.call_command(self, event.command, event.args)
# if ret is None:
# return
# if ret:
# self.connection.send_chat(ret)
# return False
#
# def get_player(self, name=None):
# if name is None:
# return self.connection
# return get_player(self.server, name)
#
# def get_commands(self):
# rights = self.connection.rights
# for command in self.server.get_commands():
# if command.is_compatible(rights):
# yield command
#
# def get_command(self, name):
# command = self.server.get_command(name)
# if not command:
# return
# if not command.is_compatible(self.connection.rights):
# return
# return command
#
# def unload(self):
# if self.parent is None:
# return
# self.connection.scripts.remove(self)
# self.parent.children.remove(self)
# self.on_unload()
# self.parent = None
# self.connection = None
# self.server = None
# self.world = None
#
# @property
# def entity(self):
# return self.connection.entity
#
# class ScriptInterface:
# """
# Used for external script interfaces to emulate a connection for e.g.
# console and IRC commands
# """
#
# def __init__(self, name, server, *rights):
# self.name = name
# self.rights = AttributeSet(rights)
# self.server = server
# self.connection = self
# self.parent = None # set by call_command
#
# def get_player(self, name):
# if name is None:
# raise InvalidPlayer()
# return get_player(self.server, name)
#
# def get_commands(self):
# return self.server.get_commands()
#
# def get_command(self, name):
# return self.server.get_command(name)
. Output only the next line. | class IRCScriptConnection(ConnectionScript): |
Based on the snippet: <|code_start|># but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cuwo. If not, see <http://www.gnu.org/licenses/>.
"""
IRC client that can be used as a way to control the game server
Depends on the irc3 package. Install with:
pip install irc3
"""
MAX_IRC_CHAT_SIZE = 100
@irc3.plugin
class ServerPlugin:
commands = {}
def __init__(self, bot):
self.bot = bot
self.script = bot.config['script']
self.server = self.script.server
config = self.script.config
self.chat_prefix = config.chatprefix
self.command_prefix = config.commandprefix
<|code_end|>
, predict the immediate next line with the help of imports:
import irc3
from cuwo.common import parse_command
from cuwo.script import ServerScript, ConnectionScript, ScriptInterface
and context (classes, functions, sometimes code) from other files:
# Path: cuwo/common.py
# def parse_command(message):
# try:
# args = shlex.split(message)
# except ValueError:
# # shlex failed. let's just split per space
# args = message.split(' ')
# if args:
# command = args.pop(0)
# else:
# command = ''
# return command, args
#
# Path: cuwo/script.py
# class ServerScript(BaseScript):
# connection_class = ConnectionScript
# commands = None
# aliases = None
#
# def __init__(self, server):
# self.script_name = self.__module__.split('.')[1]
#
# self.server = server
# self.world = server.world
# self.loop = server.loop
# server.scripts.add(self)
# self.children = []
# self.on_load()
# for connection in server.connections:
# self.call('on_existing_connection', connection=connection)
#
# def on_new_connection(self, event):
# if self.connection_class is None:
# return
# script = self.connection_class(self, event.connection)
# script.call('on_connect')
#
# def on_existing_connection(self, event):
# if self.connection_class is None:
# return
# self.connection_class(self, event.connection)
#
# def on_command(self, event):
# return self.call_command(event.user, event.command, event.args)
#
# def unload(self):
# if self.server is None:
# return
# self.on_unload()
# self.server.scripts.remove(self)
# for script in self.children[:]:
# script.unload()
# self.children = None
# self.server = None
# self.world = None
#
# def call_command(self, user, command, args):
# if self.commands is None:
# return
# command = command.lower()
# command = self.aliases.get(command, command)
# command = self.commands.get(command, None)
# if not command:
# return
# user.parent = self # for ScriptInterface
#
# if len(args) < command.min_args:
# return command.get_syntax()
# if command.max_args is not None and len(args) > command.max_args:
# return command.get_syntax()
#
# try:
# ret = command(user, *args) or ''
# except InvalidPlayer:
# ret = 'Invalid player specified'
# except InsufficientRights:
# ret = 'Insufficient rights'
# except Exception:
# import traceback
# traceback.print_exc()
# ret = ''
# return ret
#
# class ConnectionScript(BaseScript):
# def __init__(self, parent, connection):
# self.script_name = parent.script_name
#
# self.parent = parent
# self.server = parent.server
# self.world = parent.world
# self.loop = connection.loop
# self.connection = connection
# connection.scripts.add(self)
# parent.children.append(self)
# self.on_load()
#
# def on_disconnect(self, event):
# self.unload()
#
# def on_command(self, event):
# ret = self.parent.call_command(self, event.command, event.args)
# if ret is None:
# return
# if ret:
# self.connection.send_chat(ret)
# return False
#
# def get_player(self, name=None):
# if name is None:
# return self.connection
# return get_player(self.server, name)
#
# def get_commands(self):
# rights = self.connection.rights
# for command in self.server.get_commands():
# if command.is_compatible(rights):
# yield command
#
# def get_command(self, name):
# command = self.server.get_command(name)
# if not command:
# return
# if not command.is_compatible(self.connection.rights):
# return
# return command
#
# def unload(self):
# if self.parent is None:
# return
# self.connection.scripts.remove(self)
# self.parent.children.remove(self)
# self.on_unload()
# self.parent = None
# self.connection = None
# self.server = None
# self.world = None
#
# @property
# def entity(self):
# return self.connection.entity
#
# class ScriptInterface:
# """
# Used for external script interfaces to emulate a connection for e.g.
# console and IRC commands
# """
#
# def __init__(self, name, server, *rights):
# self.name = name
# self.rights = AttributeSet(rights)
# self.server = server
# self.connection = self
# self.parent = None # set by call_command
#
# def get_player(self, name):
# if name is None:
# raise InvalidPlayer()
# return get_player(self.server, name)
#
# def get_commands(self):
# return self.server.get_commands()
#
# def get_command(self, name):
# return self.server.get_command(name)
. Output only the next line. | self.interface = ScriptInterface('IRC', self.server, *config.rights) |
Given the following code snippet before the placeholder: <|code_start|>
WRITE_INTERVAL = 10
DEFAULT_PORT = 12364
EXPIRE_TIME = master.UPDATE_RATE * 1.5
BLACKLIST_FILE = 'blacklist.json'
def is_sane_count(count):
return count < 500
class MasterServer(master.MasterProtocol):
def __init__(self, loop, filename, blacklist_file):
self.loop = loop
self.filename = filename
self.output = {}
self.blacklist_file = blacklist_file
self.blacklist = set()
self.ip_database = pygeoip.GeoIP('GeoIP.dat')
def connection_made(self, transport):
self.transport = transport
asyncio.Task(self.update())
def datagram_received(self, data, addr):
host, port = addr
if host in self.blacklist:
return
<|code_end|>
, predict the next line using imports from the current file:
import sys
import master
import asyncio
import pygeoip
import argparse
import json
import os
import socket
import signal
from cuwo import constants
from cuwo.exceptions import InvalidData
from cuwo.win32 import WindowsEventLoop
and context including class names, function names, and sometimes code from other files:
# Path: cuwo/constants.py
# CLIENT_VERSION = 3
# SERVER_PORT = 12345
# FULL_MASK = 0x0000FFFFFFFFFFFF
# MAX_TIME = 24 * 60 * 60 * 1000
# NORMAL_TIME_SPEED = 10.0
# SLEEP_TIME_SPEED = 100.0
# BLOCK_SCALE = 0x10000
# ZONE_SCALE = BLOCK_SCALE * 256
# REGION_SCALE = ZONE_SCALE * 64
# MISSION_SCALE = REGION_SCALE // 8
# MISSIONS_IN_REGION = 8
# MAX_POS = REGION_SCALE * 1024
# MAX_ZONE = MAX_POS // ZONE_SCALE
# CHUNK_SCALE = ZONE_SCALE
# MAX_CHUNK = MAX_ZONE
# SECTOR_SCALE = REGION_SCALE
# AIR_BLOCK = 0
# SOLID_BLOCK = 1
# WATER_BLOCK = 2
# FLAT_WATER_BLOCK = 3
# HOSTILE_FLAG = 1 << 5
# FRIENDLY_PLAYER_TYPE = 0
# HOSTILE_TYPE = 1
# FRIENDLY_TYPE = 2 # also 4, 5
# NAMED_FRIENDLY_TYPE = 3
# TARGET_TYPE = 6
# CLIMBING_FLAG = 1 << 0
# ATTACKING_FLAG = 1 << 2
# GLIDER_FLAG = 1 << 4
# LANTERN_FLAG = 1 << 9
# STEALTH_FLAG = 1 << 10
# IMMOVABLE_FLAG = 1 << 8
# SOLID_PARTICLE = 0
# BOMB_PARTICLE = 1
# NO_SPREAD_PARTICLE = 2
# NO_ACCELERATION_PARTICLE = 3
# NO_GRAVITY_PARTICLE = 4
# WARRIOR_CLASS = 1
# BERSERKER = 0
# GUARDIAN = 1
# RANGER_CLASS = 2
# SNIPER = 0
# SCOUT = 1
# MAGE_CLASS = 3
# FIRE_MAGE = 0
# WATER_MAGE = 1
# ROGUE_CLASS = 4
# ASSASSIN = 0
# NINJA = 1
# CLASS_NAMES = {
# WARRIOR_CLASS: 'Warrior',
# RANGER_CLASS: 'Ranger',
# MAGE_CLASS: 'Mage',
# ROGUE_CLASS: 'Rogue'
# }
# CLASS_SPECIALIZATIONS = {
# WARRIOR_CLASS: {
# BERSERKER: 'Berserker',
# GUARDIAN: 'Guardian'
# },
# RANGER_CLASS: {
# SNIPER: 'Sniper',
# SCOUT: 'Scout'
# },
# MAGE_CLASS: {
# FIRE_MAGE: 'Fire',
# WATER_MAGE: 'Water'
# },
# ROGUE_CLASS: {
# ASSASSIN: 'Assassin',
# NINJA: 'Ninja'
# }
# }
# MATERIAL_NAMES = {
# 1: 'Iron',
# 2: 'Wood',
# 5: 'Obsidian',
# 7: 'Bone',
# 11: 'Gold',
# 12: 'Silver',
# 13: 'Emerald',
# 14: 'Sapphire',
# 15: 'Ruby',
# 16: 'Diamond',
# 17: 'Sandstone',
# 18: 'Saurian',
# 19: 'Parrot',
# 20: 'Mammoth',
# 21: 'Plant',
# 22: 'Ice',
# 23: 'Licht',
# 24: 'Glass',
# 25: 'Silk',
# 26: 'Linen',
# 27: 'Cotton',
# 128: 'Fire',
# 129: 'Unholy',
# 130: 'Ice',
# 131: 'Wind'
# }
#
# Path: cuwo/exceptions.py
# class InvalidData(Exception):
# """
# Raised when invalid data is received
# """
. Output only the next line. | if port != constants.SERVER_PORT: |
Here is a snippet: <|code_start|> return info[0][4][0]
@asyncio.coroutine
def on_server(self, data, addr):
host, port = addr
if data.ip is None:
data.ip = host
else:
use_ip = False
try:
ip = yield from self.resolve(data.ip)
use_ip = ip == host
except (socket.gaierror, IndexError):
pass
if not use_ip:
data.ip = host
self.add_server(data, host)
def add_server(self, data, ip):
try:
location = self.ip_database.country_code_by_addr(ip)
except TypeError:
location = '?'
data.location = location
data.mode = data.mode or 'default'
self.output[ip] = data.get()
def on_packet(self, value, addr):
try:
value = master.ServerData(value)
<|code_end|>
. Write the next line using the current file imports:
import sys
import master
import asyncio
import pygeoip
import argparse
import json
import os
import socket
import signal
from cuwo import constants
from cuwo.exceptions import InvalidData
from cuwo.win32 import WindowsEventLoop
and context from other files:
# Path: cuwo/constants.py
# CLIENT_VERSION = 3
# SERVER_PORT = 12345
# FULL_MASK = 0x0000FFFFFFFFFFFF
# MAX_TIME = 24 * 60 * 60 * 1000
# NORMAL_TIME_SPEED = 10.0
# SLEEP_TIME_SPEED = 100.0
# BLOCK_SCALE = 0x10000
# ZONE_SCALE = BLOCK_SCALE * 256
# REGION_SCALE = ZONE_SCALE * 64
# MISSION_SCALE = REGION_SCALE // 8
# MISSIONS_IN_REGION = 8
# MAX_POS = REGION_SCALE * 1024
# MAX_ZONE = MAX_POS // ZONE_SCALE
# CHUNK_SCALE = ZONE_SCALE
# MAX_CHUNK = MAX_ZONE
# SECTOR_SCALE = REGION_SCALE
# AIR_BLOCK = 0
# SOLID_BLOCK = 1
# WATER_BLOCK = 2
# FLAT_WATER_BLOCK = 3
# HOSTILE_FLAG = 1 << 5
# FRIENDLY_PLAYER_TYPE = 0
# HOSTILE_TYPE = 1
# FRIENDLY_TYPE = 2 # also 4, 5
# NAMED_FRIENDLY_TYPE = 3
# TARGET_TYPE = 6
# CLIMBING_FLAG = 1 << 0
# ATTACKING_FLAG = 1 << 2
# GLIDER_FLAG = 1 << 4
# LANTERN_FLAG = 1 << 9
# STEALTH_FLAG = 1 << 10
# IMMOVABLE_FLAG = 1 << 8
# SOLID_PARTICLE = 0
# BOMB_PARTICLE = 1
# NO_SPREAD_PARTICLE = 2
# NO_ACCELERATION_PARTICLE = 3
# NO_GRAVITY_PARTICLE = 4
# WARRIOR_CLASS = 1
# BERSERKER = 0
# GUARDIAN = 1
# RANGER_CLASS = 2
# SNIPER = 0
# SCOUT = 1
# MAGE_CLASS = 3
# FIRE_MAGE = 0
# WATER_MAGE = 1
# ROGUE_CLASS = 4
# ASSASSIN = 0
# NINJA = 1
# CLASS_NAMES = {
# WARRIOR_CLASS: 'Warrior',
# RANGER_CLASS: 'Ranger',
# MAGE_CLASS: 'Mage',
# ROGUE_CLASS: 'Rogue'
# }
# CLASS_SPECIALIZATIONS = {
# WARRIOR_CLASS: {
# BERSERKER: 'Berserker',
# GUARDIAN: 'Guardian'
# },
# RANGER_CLASS: {
# SNIPER: 'Sniper',
# SCOUT: 'Scout'
# },
# MAGE_CLASS: {
# FIRE_MAGE: 'Fire',
# WATER_MAGE: 'Water'
# },
# ROGUE_CLASS: {
# ASSASSIN: 'Assassin',
# NINJA: 'Ninja'
# }
# }
# MATERIAL_NAMES = {
# 1: 'Iron',
# 2: 'Wood',
# 5: 'Obsidian',
# 7: 'Bone',
# 11: 'Gold',
# 12: 'Silver',
# 13: 'Emerald',
# 14: 'Sapphire',
# 15: 'Ruby',
# 16: 'Diamond',
# 17: 'Sandstone',
# 18: 'Saurian',
# 19: 'Parrot',
# 20: 'Mammoth',
# 21: 'Plant',
# 22: 'Ice',
# 23: 'Licht',
# 24: 'Glass',
# 25: 'Silk',
# 26: 'Linen',
# 27: 'Cotton',
# 128: 'Fire',
# 129: 'Unholy',
# 130: 'Ice',
# 131: 'Wind'
# }
#
# Path: cuwo/exceptions.py
# class InvalidData(Exception):
# """
# Raised when invalid data is received
# """
, which may include functions, classes, or code. Output only the next line. | except InvalidData: |
Using the snippet: <|code_start|>
def connection_made(self, transport):
self.transport = transport
self.task = asyncio.get_event_loop().create_task(self.send_loop())
@asyncio.coroutine
def send_loop(self):
config = self.server.config.base
data = ServerData()
while True:
data.name = config.server_name
data.max = config.max_players
data.ip = self.server.config.master.hostname
data.players = len(self.server.players)
data.mode = self.server.get_mode()
self.send_packet(data.get(), self.address)
yield from asyncio.sleep(UPDATE_RATE)
def on_packet(self, data, addr):
if data.get('ack', False):
self.on_ack()
def on_ack(self):
if self.has_response:
return
self.has_response = True
print('Received response from master server')
<|code_end|>
, determine the next line of code. You have imports:
from cuwo.script import ServerScript
from cuwo.exceptions import InvalidData
import zlib
import json
import asyncio
and context (class names, function names, or code) available:
# Path: cuwo/script.py
# class ServerScript(BaseScript):
# connection_class = ConnectionScript
# commands = None
# aliases = None
#
# def __init__(self, server):
# self.script_name = self.__module__.split('.')[1]
#
# self.server = server
# self.world = server.world
# self.loop = server.loop
# server.scripts.add(self)
# self.children = []
# self.on_load()
# for connection in server.connections:
# self.call('on_existing_connection', connection=connection)
#
# def on_new_connection(self, event):
# if self.connection_class is None:
# return
# script = self.connection_class(self, event.connection)
# script.call('on_connect')
#
# def on_existing_connection(self, event):
# if self.connection_class is None:
# return
# self.connection_class(self, event.connection)
#
# def on_command(self, event):
# return self.call_command(event.user, event.command, event.args)
#
# def unload(self):
# if self.server is None:
# return
# self.on_unload()
# self.server.scripts.remove(self)
# for script in self.children[:]:
# script.unload()
# self.children = None
# self.server = None
# self.world = None
#
# def call_command(self, user, command, args):
# if self.commands is None:
# return
# command = command.lower()
# command = self.aliases.get(command, command)
# command = self.commands.get(command, None)
# if not command:
# return
# user.parent = self # for ScriptInterface
#
# if len(args) < command.min_args:
# return command.get_syntax()
# if command.max_args is not None and len(args) > command.max_args:
# return command.get_syntax()
#
# try:
# ret = command(user, *args) or ''
# except InvalidPlayer:
# ret = 'Invalid player specified'
# except InsufficientRights:
# ret = 'Insufficient rights'
# except Exception:
# import traceback
# traceback.print_exc()
# ret = ''
# return ret
#
# Path: cuwo/exceptions.py
# class InvalidData(Exception):
# """
# Raised when invalid data is received
# """
. Output only the next line. | class MasterRelay(ServerScript): |
Based on the snippet: <|code_start|> def error_received(self, exc):
print('Master error:', exc)
def on_packet(self, data, addr):
pass
def send_packet(self, value, addr):
if self.transport is None:
return
data = zlib.compress(json.dumps(value).encode('utf-8'))
self.transport.sendto(data, addr)
def on_bad_packet(self, addr):
pass
class ServerData(object):
location = None
ip = None
def __init__(self, data=None):
if data is None:
return
try:
self.name = data.pop('name')
self.max = data.pop('max')
self.players = data.pop('players')
self.mode = data.pop('mode')
self.ip = data.pop('ip', None)
except KeyError:
<|code_end|>
, predict the immediate next line with the help of imports:
from cuwo.script import ServerScript
from cuwo.exceptions import InvalidData
import zlib
import json
import asyncio
and context (classes, functions, sometimes code) from other files:
# Path: cuwo/script.py
# class ServerScript(BaseScript):
# connection_class = ConnectionScript
# commands = None
# aliases = None
#
# def __init__(self, server):
# self.script_name = self.__module__.split('.')[1]
#
# self.server = server
# self.world = server.world
# self.loop = server.loop
# server.scripts.add(self)
# self.children = []
# self.on_load()
# for connection in server.connections:
# self.call('on_existing_connection', connection=connection)
#
# def on_new_connection(self, event):
# if self.connection_class is None:
# return
# script = self.connection_class(self, event.connection)
# script.call('on_connect')
#
# def on_existing_connection(self, event):
# if self.connection_class is None:
# return
# self.connection_class(self, event.connection)
#
# def on_command(self, event):
# return self.call_command(event.user, event.command, event.args)
#
# def unload(self):
# if self.server is None:
# return
# self.on_unload()
# self.server.scripts.remove(self)
# for script in self.children[:]:
# script.unload()
# self.children = None
# self.server = None
# self.world = None
#
# def call_command(self, user, command, args):
# if self.commands is None:
# return
# command = command.lower()
# command = self.aliases.get(command, command)
# command = self.commands.get(command, None)
# if not command:
# return
# user.parent = self # for ScriptInterface
#
# if len(args) < command.min_args:
# return command.get_syntax()
# if command.max_args is not None and len(args) > command.max_args:
# return command.get_syntax()
#
# try:
# ret = command(user, *args) or ''
# except InvalidPlayer:
# ret = 'Invalid player specified'
# except InsufficientRights:
# ret = 'Insufficient rights'
# except Exception:
# import traceback
# traceback.print_exc()
# ret = ''
# return ret
#
# Path: cuwo/exceptions.py
# class InvalidData(Exception):
# """
# Raised when invalid data is received
# """
. Output only the next line. | raise InvalidData() |
Continue the code snippet: <|code_start|> for value in self.cache.values():
if value is None:
continue
yield value
def stop(self):
self.running = False
def run(self):
print('Initializing tgen...')
tgen.initialize(self.parent.seed, './data/')
print('Done')
while self.running:
key = self.gen_queue.get()
x, y = key
print('Generating chunk', x, y)
off_x = (x - self.parent.chunk_x) * 256.0
off_y = (y - self.parent.chunk_y) * 256.0
data = tgen.generate(x, y).get_render(off_x, off_y)
res = ChunkData(data)
self.cache[key] = res
class Camera(object):
up = down = left = right = False
shift = False
x_rot = -27.0
z_rot = 244
def __init__(self):
<|code_end|>
. Use current file imports:
import sys
import sdl2
import sdl2.ext
import threading
import math
import os
import traceback
from cuwo import tgen
from cuwo.vector import Vector3, Quaternion
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.constants import GLfloat_4
from OpenGL.GL import shaders
from OpenGL.GL.ARB.vertex_buffer_object import *
from queue import PriorityQueue, Full
from ctypes import *
and context (classes, functions, or code) from other files:
# Path: cuwo/vector.py
# def ivec3(x=0, y=0, z=0):
# def vec3(x=0, y=0, z=0):
# def qvec3(x=0, y=0, z=0):
. Output only the next line. | self.pos = Vector3((40.31, 158.36, 173.21)) |
Given the following code snippet before the placeholder: <|code_start|>
def run(self):
print('Initializing tgen...')
tgen.initialize(self.parent.seed, './data/')
print('Done')
while self.running:
key = self.gen_queue.get()
x, y = key
print('Generating chunk', x, y)
off_x = (x - self.parent.chunk_x) * 256.0
off_y = (y - self.parent.chunk_y) * 256.0
data = tgen.generate(x, y).get_render(off_x, off_y)
res = ChunkData(data)
self.cache[key] = res
class Camera(object):
up = down = left = right = False
shift = False
x_rot = -27.0
z_rot = 244
def __init__(self):
self.pos = Vector3((40.31, 158.36, 173.21))
def on_mouse(self, dx, dy):
self.z_rot -= dx
self.x_rot -= dy
def get_rot(self):
<|code_end|>
, predict the next line using imports from the current file:
import sys
import sdl2
import sdl2.ext
import threading
import math
import os
import traceback
from cuwo import tgen
from cuwo.vector import Vector3, Quaternion
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.constants import GLfloat_4
from OpenGL.GL import shaders
from OpenGL.GL.ARB.vertex_buffer_object import *
from queue import PriorityQueue, Full
from ctypes import *
and context including class names, function names, and sometimes code from other files:
# Path: cuwo/vector.py
# def ivec3(x=0, y=0, z=0):
# def vec3(x=0, y=0, z=0):
# def qvec3(x=0, y=0, z=0):
. Output only the next line. | rot = Quaternion() |
Continue the code snippet: <|code_start|>"""
Performs logging
"""
class LoggerWriter:
data = ''
errors = 'strict'
def __init__(self, fp, logger, level):
self.fp = fp
self.errors = fp.errors
self.encoding = fp.encoding
self.logger = logger
self.level = level
def write(self, message):
self.data += message
splitted = self.data.split('\n')
for message in splitted[:-1]:
self.logger.log(self.level, message)
self.data = splitted[-1]
def flush(self):
self.fp.flush()
<|code_end|>
. Use current file imports:
from cuwo.script import ServerScript
from cuwo.common import create_file_path
from logging.handlers import TimedRotatingFileHandler
import logging
import time
import sys
and context (classes, functions, or code) from other files:
# Path: cuwo/script.py
# class ServerScript(BaseScript):
# connection_class = ConnectionScript
# commands = None
# aliases = None
#
# def __init__(self, server):
# self.script_name = self.__module__.split('.')[1]
#
# self.server = server
# self.world = server.world
# self.loop = server.loop
# server.scripts.add(self)
# self.children = []
# self.on_load()
# for connection in server.connections:
# self.call('on_existing_connection', connection=connection)
#
# def on_new_connection(self, event):
# if self.connection_class is None:
# return
# script = self.connection_class(self, event.connection)
# script.call('on_connect')
#
# def on_existing_connection(self, event):
# if self.connection_class is None:
# return
# self.connection_class(self, event.connection)
#
# def on_command(self, event):
# return self.call_command(event.user, event.command, event.args)
#
# def unload(self):
# if self.server is None:
# return
# self.on_unload()
# self.server.scripts.remove(self)
# for script in self.children[:]:
# script.unload()
# self.children = None
# self.server = None
# self.world = None
#
# def call_command(self, user, command, args):
# if self.commands is None:
# return
# command = command.lower()
# command = self.aliases.get(command, command)
# command = self.commands.get(command, None)
# if not command:
# return
# user.parent = self # for ScriptInterface
#
# if len(args) < command.min_args:
# return command.get_syntax()
# if command.max_args is not None and len(args) > command.max_args:
# return command.get_syntax()
#
# try:
# ret = command(user, *args) or ''
# except InvalidPlayer:
# ret = 'Invalid player specified'
# except InsufficientRights:
# ret = 'Insufficient rights'
# except Exception:
# import traceback
# traceback.print_exc()
# ret = ''
# return ret
#
# Path: cuwo/common.py
# def create_file_path(path):
# create_path(os.path.dirname(path))
. Output only the next line. | class LogServer(ServerScript): |
Predict the next line for this snippet: <|code_start|> self.errors = fp.errors
self.encoding = fp.encoding
self.logger = logger
self.level = level
def write(self, message):
self.data += message
splitted = self.data.split('\n')
for message in splitted[:-1]:
self.logger.log(self.level, message)
self.data = splitted[-1]
def flush(self):
self.fp.flush()
class LogServer(ServerScript):
connection_class = None
def on_load(self):
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# also write stdout/stderr to log file
sys.stdout = LoggerWriter(sys.__stdout__, logger, logging.INFO)
sys.sterr = LoggerWriter(sys.__stderr__, logger, logging.ERROR)
config = self.server.config.base
logfile = config.log_name
if config.rotate_daily:
<|code_end|>
with the help of current file imports:
from cuwo.script import ServerScript
from cuwo.common import create_file_path
from logging.handlers import TimedRotatingFileHandler
import logging
import time
import sys
and context from other files:
# Path: cuwo/script.py
# class ServerScript(BaseScript):
# connection_class = ConnectionScript
# commands = None
# aliases = None
#
# def __init__(self, server):
# self.script_name = self.__module__.split('.')[1]
#
# self.server = server
# self.world = server.world
# self.loop = server.loop
# server.scripts.add(self)
# self.children = []
# self.on_load()
# for connection in server.connections:
# self.call('on_existing_connection', connection=connection)
#
# def on_new_connection(self, event):
# if self.connection_class is None:
# return
# script = self.connection_class(self, event.connection)
# script.call('on_connect')
#
# def on_existing_connection(self, event):
# if self.connection_class is None:
# return
# self.connection_class(self, event.connection)
#
# def on_command(self, event):
# return self.call_command(event.user, event.command, event.args)
#
# def unload(self):
# if self.server is None:
# return
# self.on_unload()
# self.server.scripts.remove(self)
# for script in self.children[:]:
# script.unload()
# self.children = None
# self.server = None
# self.world = None
#
# def call_command(self, user, command, args):
# if self.commands is None:
# return
# command = command.lower()
# command = self.aliases.get(command, command)
# command = self.commands.get(command, None)
# if not command:
# return
# user.parent = self # for ScriptInterface
#
# if len(args) < command.min_args:
# return command.get_syntax()
# if command.max_args is not None and len(args) > command.max_args:
# return command.get_syntax()
#
# try:
# ret = command(user, *args) or ''
# except InvalidPlayer:
# ret = 'Invalid player specified'
# except InsufficientRights:
# ret = 'Insufficient rights'
# except Exception:
# import traceback
# traceback.print_exc()
# ret = ''
# return ret
#
# Path: cuwo/common.py
# def create_file_path(path):
# create_path(os.path.dirname(path))
, which may contain function names, class names, or code. Output only the next line. | create_file_path(logfile) |
Based on the snippet: <|code_start|># Copyright (c) Mathias Kaerlev 2013-2017.
#
# This file is part of cuwo.
#
# cuwo is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cuwo is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cuwo. If not, see <http://www.gnu.org/licenses/>.
cmd_folder = os.path.realpath(os.path.abspath('.'))
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
def switch_axes(x, y, z):
return x, z, y
def to_qmo(in_file, out_file):
cub = CubModel(ByteReader(open(in_file, 'rb').read()))
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import sys
import argparse
import os
from cuwo.bytes import ByteReader, ByteWriter
from cuwo.qmo import QubicleFile, QubicleModel
from cuwo.cub import CubModel
and context (classes, functions, sometimes code) from other files:
# Path: cuwo/qmo.py
# class QubicleFile:
# def __init__(self, reader=None):
# self.models = []
# if reader is None:
# return
# if read_string(reader) != MAGIC:
# raise NotImplementedError('invalid magic')
# elif read_string(reader) != VERSION:
# raise NotImplementedError('unsupported version')
# for _ in range(reader.read_uint32()):
# self.models.append(QubicleModel(reader))
# self.junk = reader.read()
# if len(self.junk) != 108:
# raise NotImplementedError
#
# def write(self, writer):
# write_string(writer, MAGIC)
# write_string(writer, VERSION)
# writer.write_uint32(len(self.models))
# for model in self.models:
# model.write(writer)
# writer.write(b'\x00' * 108)
#
# class QubicleModel:
# def __init__(self, reader=None):
# self.blocks = {}
# if reader is None:
# self.x_size = self.y_size = self.z_size = 0
# self.name = 'Empty'
# self.x_offset = self.y_offset = self.z_offset = 0
# self.hidden = 0
# return
# self.x_size = reader.read_uint32()
# self.y_size = reader.read_uint32()
# self.z_size = reader.read_uint32()
# self.name = read_string(reader)
# self.x_offset = reader.read_int32()
# self.y_offset = reader.read_int32()
# self.z_offset = reader.read_int32()
# self.hidden = reader.read_uint8()
# rle_count = reader.read_uint32()
# i = 0
# while rle_count:
# value = reader.read_uint32()
# rle_count -= 1
# if value == 2: # repetition
# times = reader.read_uint32()
# color = reader.read_uint32()
# rle_count -= 2
# else:
# times = 1
# color = value
# if color & 0xFF000000 == 0:
# i += times
# continue
# r = int(color & 0x0000FF)
# g = int((color & 0x00FF00) >> 8)
# b = int((color & 0xFF0000) >> 16)
# for _ in range(times):
# x = i / (self.y_size * self.z_size)
# y = (i % (self.y_size * self.z_size)) / self.z_size
# z = i % self.z_size
# self.blocks[(int(x), int(y), int(z))] = (r, g, b)
# i += 1
#
# def write(self, writer):
# writer.write_uint32(self.x_size)
# writer.write_uint32(self.y_size)
# writer.write_uint32(self.z_size)
# write_string(writer, self.name)
# writer.write_int32(self.x_offset)
# writer.write_int32(self.y_offset)
# writer.write_int32(self.z_offset)
# writer.write_uint8(self.hidden)
# writer.write_uint32(self.x_size * self.y_size * self.z_size)
# for x in range(self.x_size):
# for y in range(self.y_size):
# for z in range(self.z_size):
# c = self.blocks.get((x, y, z), None)
# if c is None:
# writer.write_uint32(0)
# continue
# r, g, b = c
# c2 = r | (g << 8) | (b << 16) | (0x7F << 24)
# writer.write_uint32(c2)
#
# Path: cuwo/cub.py
# class CubModel:
# def __init__(self, reader=None):
# self.blocks = {}
# if reader is None:
# return
# self.x_size = reader.read_uint32()
# self.y_size = reader.read_uint32()
# self.z_size = reader.read_uint32()
# for z in range(self.z_size):
# for y in range(self.y_size):
# for x in range(self.x_size):
# r = reader.read_uint8()
# g = reader.read_uint8()
# b = reader.read_uint8()
# if r == 0 and g == 0 and b == 0:
# continue
# self.blocks[(x, y, z)] = (r, g, b)
#
# def write(self, writer):
# writer.write_uint32(self.x_size)
# writer.write_uint32(self.y_size)
# writer.write_uint32(self.z_size)
# for z in range(self.z_size):
# for y in range(self.y_size):
# for x in range(self.x_size):
# r, g, b = self.blocks.get((x, y, z), (0, 0, 0))
# writer.write_uint8(r)
# writer.write_uint8(g)
# writer.write_uint8(b)
. Output only the next line. | qmo_file = QubicleFile() |
Given the following code snippet before the placeholder: <|code_start|># Copyright (c) Mathias Kaerlev 2013-2017.
#
# This file is part of cuwo.
#
# cuwo is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cuwo is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cuwo. If not, see <http://www.gnu.org/licenses/>.
cmd_folder = os.path.realpath(os.path.abspath('.'))
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
def switch_axes(x, y, z):
return x, z, y
def to_qmo(in_file, out_file):
cub = CubModel(ByteReader(open(in_file, 'rb').read()))
qmo_file = QubicleFile()
<|code_end|>
, predict the next line using imports from the current file:
import os
import sys
import argparse
import os
from cuwo.bytes import ByteReader, ByteWriter
from cuwo.qmo import QubicleFile, QubicleModel
from cuwo.cub import CubModel
and context including class names, function names, and sometimes code from other files:
# Path: cuwo/qmo.py
# class QubicleFile:
# def __init__(self, reader=None):
# self.models = []
# if reader is None:
# return
# if read_string(reader) != MAGIC:
# raise NotImplementedError('invalid magic')
# elif read_string(reader) != VERSION:
# raise NotImplementedError('unsupported version')
# for _ in range(reader.read_uint32()):
# self.models.append(QubicleModel(reader))
# self.junk = reader.read()
# if len(self.junk) != 108:
# raise NotImplementedError
#
# def write(self, writer):
# write_string(writer, MAGIC)
# write_string(writer, VERSION)
# writer.write_uint32(len(self.models))
# for model in self.models:
# model.write(writer)
# writer.write(b'\x00' * 108)
#
# class QubicleModel:
# def __init__(self, reader=None):
# self.blocks = {}
# if reader is None:
# self.x_size = self.y_size = self.z_size = 0
# self.name = 'Empty'
# self.x_offset = self.y_offset = self.z_offset = 0
# self.hidden = 0
# return
# self.x_size = reader.read_uint32()
# self.y_size = reader.read_uint32()
# self.z_size = reader.read_uint32()
# self.name = read_string(reader)
# self.x_offset = reader.read_int32()
# self.y_offset = reader.read_int32()
# self.z_offset = reader.read_int32()
# self.hidden = reader.read_uint8()
# rle_count = reader.read_uint32()
# i = 0
# while rle_count:
# value = reader.read_uint32()
# rle_count -= 1
# if value == 2: # repetition
# times = reader.read_uint32()
# color = reader.read_uint32()
# rle_count -= 2
# else:
# times = 1
# color = value
# if color & 0xFF000000 == 0:
# i += times
# continue
# r = int(color & 0x0000FF)
# g = int((color & 0x00FF00) >> 8)
# b = int((color & 0xFF0000) >> 16)
# for _ in range(times):
# x = i / (self.y_size * self.z_size)
# y = (i % (self.y_size * self.z_size)) / self.z_size
# z = i % self.z_size
# self.blocks[(int(x), int(y), int(z))] = (r, g, b)
# i += 1
#
# def write(self, writer):
# writer.write_uint32(self.x_size)
# writer.write_uint32(self.y_size)
# writer.write_uint32(self.z_size)
# write_string(writer, self.name)
# writer.write_int32(self.x_offset)
# writer.write_int32(self.y_offset)
# writer.write_int32(self.z_offset)
# writer.write_uint8(self.hidden)
# writer.write_uint32(self.x_size * self.y_size * self.z_size)
# for x in range(self.x_size):
# for y in range(self.y_size):
# for z in range(self.z_size):
# c = self.blocks.get((x, y, z), None)
# if c is None:
# writer.write_uint32(0)
# continue
# r, g, b = c
# c2 = r | (g << 8) | (b << 16) | (0x7F << 24)
# writer.write_uint32(c2)
#
# Path: cuwo/cub.py
# class CubModel:
# def __init__(self, reader=None):
# self.blocks = {}
# if reader is None:
# return
# self.x_size = reader.read_uint32()
# self.y_size = reader.read_uint32()
# self.z_size = reader.read_uint32()
# for z in range(self.z_size):
# for y in range(self.y_size):
# for x in range(self.x_size):
# r = reader.read_uint8()
# g = reader.read_uint8()
# b = reader.read_uint8()
# if r == 0 and g == 0 and b == 0:
# continue
# self.blocks[(x, y, z)] = (r, g, b)
#
# def write(self, writer):
# writer.write_uint32(self.x_size)
# writer.write_uint32(self.y_size)
# writer.write_uint32(self.z_size)
# for z in range(self.z_size):
# for y in range(self.y_size):
# for x in range(self.x_size):
# r, g, b = self.blocks.get((x, y, z), (0, 0, 0))
# writer.write_uint8(r)
# writer.write_uint8(g)
# writer.write_uint8(b)
. Output only the next line. | qmo_model = QubicleModel() |
Next line prediction: <|code_start|># Copyright (c) Mathias Kaerlev 2013-2017.
#
# This file is part of cuwo.
#
# cuwo is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cuwo is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cuwo. If not, see <http://www.gnu.org/licenses/>.
cmd_folder = os.path.realpath(os.path.abspath('.'))
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
def switch_axes(x, y, z):
return x, z, y
def to_qmo(in_file, out_file):
<|code_end|>
. Use current file imports:
(import os
import sys
import argparse
import os
from cuwo.bytes import ByteReader, ByteWriter
from cuwo.qmo import QubicleFile, QubicleModel
from cuwo.cub import CubModel)
and context including class names, function names, or small code snippets from other files:
# Path: cuwo/qmo.py
# class QubicleFile:
# def __init__(self, reader=None):
# self.models = []
# if reader is None:
# return
# if read_string(reader) != MAGIC:
# raise NotImplementedError('invalid magic')
# elif read_string(reader) != VERSION:
# raise NotImplementedError('unsupported version')
# for _ in range(reader.read_uint32()):
# self.models.append(QubicleModel(reader))
# self.junk = reader.read()
# if len(self.junk) != 108:
# raise NotImplementedError
#
# def write(self, writer):
# write_string(writer, MAGIC)
# write_string(writer, VERSION)
# writer.write_uint32(len(self.models))
# for model in self.models:
# model.write(writer)
# writer.write(b'\x00' * 108)
#
# class QubicleModel:
# def __init__(self, reader=None):
# self.blocks = {}
# if reader is None:
# self.x_size = self.y_size = self.z_size = 0
# self.name = 'Empty'
# self.x_offset = self.y_offset = self.z_offset = 0
# self.hidden = 0
# return
# self.x_size = reader.read_uint32()
# self.y_size = reader.read_uint32()
# self.z_size = reader.read_uint32()
# self.name = read_string(reader)
# self.x_offset = reader.read_int32()
# self.y_offset = reader.read_int32()
# self.z_offset = reader.read_int32()
# self.hidden = reader.read_uint8()
# rle_count = reader.read_uint32()
# i = 0
# while rle_count:
# value = reader.read_uint32()
# rle_count -= 1
# if value == 2: # repetition
# times = reader.read_uint32()
# color = reader.read_uint32()
# rle_count -= 2
# else:
# times = 1
# color = value
# if color & 0xFF000000 == 0:
# i += times
# continue
# r = int(color & 0x0000FF)
# g = int((color & 0x00FF00) >> 8)
# b = int((color & 0xFF0000) >> 16)
# for _ in range(times):
# x = i / (self.y_size * self.z_size)
# y = (i % (self.y_size * self.z_size)) / self.z_size
# z = i % self.z_size
# self.blocks[(int(x), int(y), int(z))] = (r, g, b)
# i += 1
#
# def write(self, writer):
# writer.write_uint32(self.x_size)
# writer.write_uint32(self.y_size)
# writer.write_uint32(self.z_size)
# write_string(writer, self.name)
# writer.write_int32(self.x_offset)
# writer.write_int32(self.y_offset)
# writer.write_int32(self.z_offset)
# writer.write_uint8(self.hidden)
# writer.write_uint32(self.x_size * self.y_size * self.z_size)
# for x in range(self.x_size):
# for y in range(self.y_size):
# for z in range(self.z_size):
# c = self.blocks.get((x, y, z), None)
# if c is None:
# writer.write_uint32(0)
# continue
# r, g, b = c
# c2 = r | (g << 8) | (b << 16) | (0x7F << 24)
# writer.write_uint32(c2)
#
# Path: cuwo/cub.py
# class CubModel:
# def __init__(self, reader=None):
# self.blocks = {}
# if reader is None:
# return
# self.x_size = reader.read_uint32()
# self.y_size = reader.read_uint32()
# self.z_size = reader.read_uint32()
# for z in range(self.z_size):
# for y in range(self.y_size):
# for x in range(self.x_size):
# r = reader.read_uint8()
# g = reader.read_uint8()
# b = reader.read_uint8()
# if r == 0 and g == 0 and b == 0:
# continue
# self.blocks[(x, y, z)] = (r, g, b)
#
# def write(self, writer):
# writer.write_uint32(self.x_size)
# writer.write_uint32(self.y_size)
# writer.write_uint32(self.z_size)
# for z in range(self.z_size):
# for y in range(self.y_size):
# for x in range(self.x_size):
# r, g, b = self.blocks.get((x, y, z), (0, 0, 0))
# writer.write_uint8(r)
# writer.write_uint8(g)
# writer.write_uint8(b)
. Output only the next line. | cub = CubModel(ByteReader(open(in_file, 'rb').read())) |
Given the code snippet: <|code_start|># GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cuwo. If not, see <http://www.gnu.org/licenses/>.
"""
Prevents Denial of Service attacks to some degree.
XXX should probably be merged with anticheat
"""
class SaneConnection(ConnectionScript):
def on_connect(self, event):
self.timeout = self.server.config.base.connection_timeout
self.timeout_call = self.loop.call_later(self.timeout, self.on_timeout)
def on_entity_update(self, event):
self.timeout_call.cancel()
self.timeout_call = self.loop.call_later(self.timeout, self.on_timeout)
def on_timeout(self):
if self.connection is None:
return
host = self.connection.address[0]
print('Connection %s timed out, disconnecting...' % host)
self.connection.disconnect()
<|code_end|>
, generate the next line using the imports in this file:
from cuwo.script import ServerScript, ConnectionScript
and context (functions, classes, or occasionally code) from other files:
# Path: cuwo/script.py
# class ServerScript(BaseScript):
# connection_class = ConnectionScript
# commands = None
# aliases = None
#
# def __init__(self, server):
# self.script_name = self.__module__.split('.')[1]
#
# self.server = server
# self.world = server.world
# self.loop = server.loop
# server.scripts.add(self)
# self.children = []
# self.on_load()
# for connection in server.connections:
# self.call('on_existing_connection', connection=connection)
#
# def on_new_connection(self, event):
# if self.connection_class is None:
# return
# script = self.connection_class(self, event.connection)
# script.call('on_connect')
#
# def on_existing_connection(self, event):
# if self.connection_class is None:
# return
# self.connection_class(self, event.connection)
#
# def on_command(self, event):
# return self.call_command(event.user, event.command, event.args)
#
# def unload(self):
# if self.server is None:
# return
# self.on_unload()
# self.server.scripts.remove(self)
# for script in self.children[:]:
# script.unload()
# self.children = None
# self.server = None
# self.world = None
#
# def call_command(self, user, command, args):
# if self.commands is None:
# return
# command = command.lower()
# command = self.aliases.get(command, command)
# command = self.commands.get(command, None)
# if not command:
# return
# user.parent = self # for ScriptInterface
#
# if len(args) < command.min_args:
# return command.get_syntax()
# if command.max_args is not None and len(args) > command.max_args:
# return command.get_syntax()
#
# try:
# ret = command(user, *args) or ''
# except InvalidPlayer:
# ret = 'Invalid player specified'
# except InsufficientRights:
# ret = 'Insufficient rights'
# except Exception:
# import traceback
# traceback.print_exc()
# ret = ''
# return ret
#
# class ConnectionScript(BaseScript):
# def __init__(self, parent, connection):
# self.script_name = parent.script_name
#
# self.parent = parent
# self.server = parent.server
# self.world = parent.world
# self.loop = connection.loop
# self.connection = connection
# connection.scripts.add(self)
# parent.children.append(self)
# self.on_load()
#
# def on_disconnect(self, event):
# self.unload()
#
# def on_command(self, event):
# ret = self.parent.call_command(self, event.command, event.args)
# if ret is None:
# return
# if ret:
# self.connection.send_chat(ret)
# return False
#
# def get_player(self, name=None):
# if name is None:
# return self.connection
# return get_player(self.server, name)
#
# def get_commands(self):
# rights = self.connection.rights
# for command in self.server.get_commands():
# if command.is_compatible(rights):
# yield command
#
# def get_command(self, name):
# command = self.server.get_command(name)
# if not command:
# return
# if not command.is_compatible(self.connection.rights):
# return
# return command
#
# def unload(self):
# if self.parent is None:
# return
# self.connection.scripts.remove(self)
# self.parent.children.remove(self)
# self.on_unload()
# self.parent = None
# self.connection = None
# self.server = None
# self.world = None
#
# @property
# def entity(self):
# return self.connection.entity
. Output only the next line. | class SaneServer(ServerScript): |
Using the snippet: <|code_start|># Copyright (c) Mathias Kaerlev 2013-2017.
#
# This file is part of cuwo.
#
# cuwo is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cuwo is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cuwo. If not, see <http://www.gnu.org/licenses/>.
"""
Anticheat script for cuwo
by Sarcen
"""
CUWO_ANTICHEAT = "cuwo anti-cheat"
LOG_LEVEL_VERBOSE = 2
LOG_LEVEL_DEFAULT = 1
LOG_LEVEL_NONE = 0
<|code_end|>
, determine the next line of code. You have imports:
from cuwo.constants import (WARRIOR_CLASS, RANGER_CLASS,
MAGE_CLASS, ROGUE_CLASS)
from cuwo.vector import qvec3, ivec3, vec3
and context (class names, function names, or code) available:
# Path: cuwo/constants.py
# WARRIOR_CLASS = 1
#
# RANGER_CLASS = 2
#
# MAGE_CLASS = 3
#
# ROGUE_CLASS = 4
#
# Path: cuwo/vector.py
# def qvec3(x=0, y=0, z=0):
# return Vector3((x, y, z), dtype=np.int64)
#
# def ivec3(x=0, y=0, z=0):
# return Vector3((x, y, z), dtype=np.int32)
#
# def vec3(x=0, y=0, z=0):
# return Vector3((x, y, z), dtype=np.float32)
. Output only the next line. | LEGAL_CLASSES = (WARRIOR_CLASS, RANGER_CLASS, MAGE_CLASS, ROGUE_CLASS) |
Given the code snippet: <|code_start|># Copyright (c) Mathias Kaerlev 2013-2017.
#
# This file is part of cuwo.
#
# cuwo is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cuwo is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cuwo. If not, see <http://www.gnu.org/licenses/>.
"""
Anticheat script for cuwo
by Sarcen
"""
CUWO_ANTICHEAT = "cuwo anti-cheat"
LOG_LEVEL_VERBOSE = 2
LOG_LEVEL_DEFAULT = 1
LOG_LEVEL_NONE = 0
<|code_end|>
, generate the next line using the imports in this file:
from cuwo.constants import (WARRIOR_CLASS, RANGER_CLASS,
MAGE_CLASS, ROGUE_CLASS)
from cuwo.vector import qvec3, ivec3, vec3
and context (functions, classes, or occasionally code) from other files:
# Path: cuwo/constants.py
# WARRIOR_CLASS = 1
#
# RANGER_CLASS = 2
#
# MAGE_CLASS = 3
#
# ROGUE_CLASS = 4
#
# Path: cuwo/vector.py
# def qvec3(x=0, y=0, z=0):
# return Vector3((x, y, z), dtype=np.int64)
#
# def ivec3(x=0, y=0, z=0):
# return Vector3((x, y, z), dtype=np.int32)
#
# def vec3(x=0, y=0, z=0):
# return Vector3((x, y, z), dtype=np.float32)
. Output only the next line. | LEGAL_CLASSES = (WARRIOR_CLASS, RANGER_CLASS, MAGE_CLASS, ROGUE_CLASS) |
Using the snippet: <|code_start|># Copyright (c) Mathias Kaerlev 2013-2017.
#
# This file is part of cuwo.
#
# cuwo is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cuwo is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cuwo. If not, see <http://www.gnu.org/licenses/>.
"""
Anticheat script for cuwo
by Sarcen
"""
CUWO_ANTICHEAT = "cuwo anti-cheat"
LOG_LEVEL_VERBOSE = 2
LOG_LEVEL_DEFAULT = 1
LOG_LEVEL_NONE = 0
<|code_end|>
, determine the next line of code. You have imports:
from cuwo.constants import (WARRIOR_CLASS, RANGER_CLASS,
MAGE_CLASS, ROGUE_CLASS)
from cuwo.vector import qvec3, ivec3, vec3
and context (class names, function names, or code) available:
# Path: cuwo/constants.py
# WARRIOR_CLASS = 1
#
# RANGER_CLASS = 2
#
# MAGE_CLASS = 3
#
# ROGUE_CLASS = 4
#
# Path: cuwo/vector.py
# def qvec3(x=0, y=0, z=0):
# return Vector3((x, y, z), dtype=np.int64)
#
# def ivec3(x=0, y=0, z=0):
# return Vector3((x, y, z), dtype=np.int32)
#
# def vec3(x=0, y=0, z=0):
# return Vector3((x, y, z), dtype=np.float32)
. Output only the next line. | LEGAL_CLASSES = (WARRIOR_CLASS, RANGER_CLASS, MAGE_CLASS, ROGUE_CLASS) |
Based on the snippet: <|code_start|># Copyright (c) Mathias Kaerlev 2013-2017.
#
# This file is part of cuwo.
#
# cuwo is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cuwo is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cuwo. If not, see <http://www.gnu.org/licenses/>.
"""
Anticheat script for cuwo
by Sarcen
"""
CUWO_ANTICHEAT = "cuwo anti-cheat"
LOG_LEVEL_VERBOSE = 2
LOG_LEVEL_DEFAULT = 1
LOG_LEVEL_NONE = 0
<|code_end|>
, predict the immediate next line with the help of imports:
from cuwo.constants import (WARRIOR_CLASS, RANGER_CLASS,
MAGE_CLASS, ROGUE_CLASS)
from cuwo.vector import qvec3, ivec3, vec3
and context (classes, functions, sometimes code) from other files:
# Path: cuwo/constants.py
# WARRIOR_CLASS = 1
#
# RANGER_CLASS = 2
#
# MAGE_CLASS = 3
#
# ROGUE_CLASS = 4
#
# Path: cuwo/vector.py
# def qvec3(x=0, y=0, z=0):
# return Vector3((x, y, z), dtype=np.int64)
#
# def ivec3(x=0, y=0, z=0):
# return Vector3((x, y, z), dtype=np.int32)
#
# def vec3(x=0, y=0, z=0):
# return Vector3((x, y, z), dtype=np.float32)
. Output only the next line. | LEGAL_CLASSES = (WARRIOR_CLASS, RANGER_CLASS, MAGE_CLASS, ROGUE_CLASS) |
Continue the code snippet: <|code_start|> 103: {'class': (MAGE_CLASS, ), },
# Shield
104: {'class': (WARRIOR_CLASS, ),
'weapon': (13, )},
# Generic
80: {}, # Drink potion
81: {}, # Eat
82: {}, # Present pet food
83: {}, # Sit
84: {}, # Sleep
106: {}, # Ride pet
107: {} # Sailing
})
APPEARANCES = dict({
2: {'scale': 0.96,
'radius': 0.96,
'height': 2.16,
'scale_head': 1.01,
'scale_feet': 0.98,
'scale_hand': 1.00,
'scale_body': 1.00,
'scale_back': 0.80,
'scale_shoulder': 1.00,
'scale_weapon': 0.98,
'scale_wing': 1.00,
'scale_unknown': 1.00,
<|code_end|>
. Use current file imports:
from cuwo.constants import (WARRIOR_CLASS, RANGER_CLASS,
MAGE_CLASS, ROGUE_CLASS)
from cuwo.vector import qvec3, ivec3, vec3
and context (classes, functions, or code) from other files:
# Path: cuwo/constants.py
# WARRIOR_CLASS = 1
#
# RANGER_CLASS = 2
#
# MAGE_CLASS = 3
#
# ROGUE_CLASS = 4
#
# Path: cuwo/vector.py
# def qvec3(x=0, y=0, z=0):
# return Vector3((x, y, z), dtype=np.int64)
#
# def ivec3(x=0, y=0, z=0):
# return Vector3((x, y, z), dtype=np.int32)
#
# def vec3(x=0, y=0, z=0):
# return Vector3((x, y, z), dtype=np.float32)
. Output only the next line. | 'offset_body': vec3(0, 0, -5), |
Using the snippet: <|code_start|># it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cuwo is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cuwo. If not, see <http://www.gnu.org/licenses/>.
"""
Player versus player mode!
"""
class VersusConnection(ConnectionScript):
def on_join(self, event):
self.entity.flags |= HOSTILE_FLAG
def on_flags_update(self, event):
self.entity.flags |= HOSTILE_FLAG
def on_kill(self, event):
self.server.send_chat('%s killed %s!' % (self.entity.name,
event.target.name))
<|code_end|>
, determine the next line of code. You have imports:
from cuwo.script import ServerScript, ConnectionScript
from cuwo.constants import HOSTILE_FLAG
and context (class names, function names, or code) available:
# Path: cuwo/script.py
# class ServerScript(BaseScript):
# connection_class = ConnectionScript
# commands = None
# aliases = None
#
# def __init__(self, server):
# self.script_name = self.__module__.split('.')[1]
#
# self.server = server
# self.world = server.world
# self.loop = server.loop
# server.scripts.add(self)
# self.children = []
# self.on_load()
# for connection in server.connections:
# self.call('on_existing_connection', connection=connection)
#
# def on_new_connection(self, event):
# if self.connection_class is None:
# return
# script = self.connection_class(self, event.connection)
# script.call('on_connect')
#
# def on_existing_connection(self, event):
# if self.connection_class is None:
# return
# self.connection_class(self, event.connection)
#
# def on_command(self, event):
# return self.call_command(event.user, event.command, event.args)
#
# def unload(self):
# if self.server is None:
# return
# self.on_unload()
# self.server.scripts.remove(self)
# for script in self.children[:]:
# script.unload()
# self.children = None
# self.server = None
# self.world = None
#
# def call_command(self, user, command, args):
# if self.commands is None:
# return
# command = command.lower()
# command = self.aliases.get(command, command)
# command = self.commands.get(command, None)
# if not command:
# return
# user.parent = self # for ScriptInterface
#
# if len(args) < command.min_args:
# return command.get_syntax()
# if command.max_args is not None and len(args) > command.max_args:
# return command.get_syntax()
#
# try:
# ret = command(user, *args) or ''
# except InvalidPlayer:
# ret = 'Invalid player specified'
# except InsufficientRights:
# ret = 'Insufficient rights'
# except Exception:
# import traceback
# traceback.print_exc()
# ret = ''
# return ret
#
# class ConnectionScript(BaseScript):
# def __init__(self, parent, connection):
# self.script_name = parent.script_name
#
# self.parent = parent
# self.server = parent.server
# self.world = parent.world
# self.loop = connection.loop
# self.connection = connection
# connection.scripts.add(self)
# parent.children.append(self)
# self.on_load()
#
# def on_disconnect(self, event):
# self.unload()
#
# def on_command(self, event):
# ret = self.parent.call_command(self, event.command, event.args)
# if ret is None:
# return
# if ret:
# self.connection.send_chat(ret)
# return False
#
# def get_player(self, name=None):
# if name is None:
# return self.connection
# return get_player(self.server, name)
#
# def get_commands(self):
# rights = self.connection.rights
# for command in self.server.get_commands():
# if command.is_compatible(rights):
# yield command
#
# def get_command(self, name):
# command = self.server.get_command(name)
# if not command:
# return
# if not command.is_compatible(self.connection.rights):
# return
# return command
#
# def unload(self):
# if self.parent is None:
# return
# self.connection.scripts.remove(self)
# self.parent.children.remove(self)
# self.on_unload()
# self.parent = None
# self.connection = None
# self.server = None
# self.world = None
#
# @property
# def entity(self):
# return self.connection.entity
#
# Path: cuwo/constants.py
# HOSTILE_FLAG = 1 << 5
. Output only the next line. | class VersusServer(ServerScript): |
Continue the code snippet: <|code_start|># Copyright (c) Mathias Kaerlev 2013-2017.
#
# This file is part of cuwo.
#
# cuwo is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cuwo is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cuwo. If not, see <http://www.gnu.org/licenses/>.
"""
Player versus player mode!
"""
class VersusConnection(ConnectionScript):
def on_join(self, event):
<|code_end|>
. Use current file imports:
from cuwo.script import ServerScript, ConnectionScript
from cuwo.constants import HOSTILE_FLAG
and context (classes, functions, or code) from other files:
# Path: cuwo/script.py
# class ServerScript(BaseScript):
# connection_class = ConnectionScript
# commands = None
# aliases = None
#
# def __init__(self, server):
# self.script_name = self.__module__.split('.')[1]
#
# self.server = server
# self.world = server.world
# self.loop = server.loop
# server.scripts.add(self)
# self.children = []
# self.on_load()
# for connection in server.connections:
# self.call('on_existing_connection', connection=connection)
#
# def on_new_connection(self, event):
# if self.connection_class is None:
# return
# script = self.connection_class(self, event.connection)
# script.call('on_connect')
#
# def on_existing_connection(self, event):
# if self.connection_class is None:
# return
# self.connection_class(self, event.connection)
#
# def on_command(self, event):
# return self.call_command(event.user, event.command, event.args)
#
# def unload(self):
# if self.server is None:
# return
# self.on_unload()
# self.server.scripts.remove(self)
# for script in self.children[:]:
# script.unload()
# self.children = None
# self.server = None
# self.world = None
#
# def call_command(self, user, command, args):
# if self.commands is None:
# return
# command = command.lower()
# command = self.aliases.get(command, command)
# command = self.commands.get(command, None)
# if not command:
# return
# user.parent = self # for ScriptInterface
#
# if len(args) < command.min_args:
# return command.get_syntax()
# if command.max_args is not None and len(args) > command.max_args:
# return command.get_syntax()
#
# try:
# ret = command(user, *args) or ''
# except InvalidPlayer:
# ret = 'Invalid player specified'
# except InsufficientRights:
# ret = 'Insufficient rights'
# except Exception:
# import traceback
# traceback.print_exc()
# ret = ''
# return ret
#
# class ConnectionScript(BaseScript):
# def __init__(self, parent, connection):
# self.script_name = parent.script_name
#
# self.parent = parent
# self.server = parent.server
# self.world = parent.world
# self.loop = connection.loop
# self.connection = connection
# connection.scripts.add(self)
# parent.children.append(self)
# self.on_load()
#
# def on_disconnect(self, event):
# self.unload()
#
# def on_command(self, event):
# ret = self.parent.call_command(self, event.command, event.args)
# if ret is None:
# return
# if ret:
# self.connection.send_chat(ret)
# return False
#
# def get_player(self, name=None):
# if name is None:
# return self.connection
# return get_player(self.server, name)
#
# def get_commands(self):
# rights = self.connection.rights
# for command in self.server.get_commands():
# if command.is_compatible(rights):
# yield command
#
# def get_command(self, name):
# command = self.server.get_command(name)
# if not command:
# return
# if not command.is_compatible(self.connection.rights):
# return
# return command
#
# def unload(self):
# if self.parent is None:
# return
# self.connection.scripts.remove(self)
# self.parent.children.remove(self)
# self.on_unload()
# self.parent = None
# self.connection = None
# self.server = None
# self.world = None
#
# @property
# def entity(self):
# return self.connection.entity
#
# Path: cuwo/constants.py
# HOSTILE_FLAG = 1 << 5
. Output only the next line. | self.entity.flags |= HOSTILE_FLAG |
Given snippet: <|code_start|> command = self.commands.get(command, None)
if not command:
return
user.parent = self # for ScriptInterface
if len(args) < command.min_args:
return command.get_syntax()
if command.max_args is not None and len(args) > command.max_args:
return command.get_syntax()
try:
ret = command(user, *args) or ''
except InvalidPlayer:
ret = 'Invalid player specified'
except InsufficientRights:
ret = 'Insufficient rights'
except Exception:
traceback.print_exc()
ret = ''
return ret
class ScriptInterface:
"""
Used for external script interfaces to emulate a connection for e.g.
console and IRC commands
"""
def __init__(self, name, server, *rights):
self.name = name
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from cuwo.types import AttributeSet, AttributeDict
import collections
import sys
import inspect
import traceback
and context:
# Path: cuwo/types.py
# class AttributeSet(set):
# """
# set with attribute access, i.e.
#
# foo = AttributeSet()
# foo.bar = True
# foo.bar == 'bar' in foo == True
# foo.bar = False
# foo.bar == 'bar' in foo == False
#
# This works as a quick shorthand for membership testing.
# """
#
# def __getattr__(self, name):
# return name in self
#
# def __setattr__(self, name, value):
# if value:
# self.add(name)
# else:
# self.discard(name)
#
# class AttributeDict(dict):
# """
# dict with attribute access
# """
# def __init__(self, *args, **kw):
# super(AttributeDict, self).__init__(*args, **kw)
# self.__dict__ = self
which might include code, classes, or functions. Output only the next line. | self.rights = AttributeSet(rights) |
Based on the snippet: <|code_start|> def __contains__(self, name):
return name in self.items
def add(self, script):
self.items[script.script_name] = script
self.cached_calls.clear()
def remove(self, script):
del self.items[script.script_name]
self.cached_calls.clear()
def unload(self):
for script in self.items.copy().values():
script.unload()
def get(self):
return self.items.values()
def call(self, event_name, **kw):
try:
handlers = self.cached_calls[event_name]
except KeyError:
handlers = []
for script in self.items.values():
f = getattr(script, event_name, None)
if not f:
continue
handlers.append(f)
self.cached_calls[event_name] = handlers
<|code_end|>
, predict the immediate next line with the help of imports:
from cuwo.types import AttributeSet, AttributeDict
import collections
import sys
import inspect
import traceback
and context (classes, functions, sometimes code) from other files:
# Path: cuwo/types.py
# class AttributeSet(set):
# """
# set with attribute access, i.e.
#
# foo = AttributeSet()
# foo.bar = True
# foo.bar == 'bar' in foo == True
# foo.bar = False
# foo.bar == 'bar' in foo == False
#
# This works as a quick shorthand for membership testing.
# """
#
# def __getattr__(self, name):
# return name in self
#
# def __setattr__(self, name, value):
# if value:
# self.add(name)
# else:
# self.discard(name)
#
# class AttributeDict(dict):
# """
# dict with attribute access
# """
# def __init__(self, *args, **kw):
# super(AttributeDict, self).__init__(*args, **kw)
# self.__dict__ = self
. Output only the next line. | event = AttributeDict(kw) |
Predict the next line for this snippet: <|code_start|># cuwo is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cuwo is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cuwo. If not, see <http://www.gnu.org/licenses/>.
sys.path.append('.')
class TerrainGeneratorTests(unittest.TestCase):
def setUp(self):
print('Initializing tgen')
tgen.initialize(26879, './data/')
print('Done')
def test_static_entities(self):
with open('./tests/tgen_static.dat', 'rb') as fp:
data = zlib.decompress(fp.read())
reader = ByteReader(data)
source = []
while reader.get_left() > 0:
<|code_end|>
with the help of current file imports:
import unittest
import sys
import os
import zlib
import subprocess
from cuwo import tgen
from cuwo.bytes import ByteReader
from cuwo.static import StaticEntityHeader
and context from other files:
# Path: cuwo/static.py
# class StaticEntityHeader(WrapStaticEntityHeader):
# def is_dynamic(self):
# return self.get_type() in DYNAMIC_ENTITIES
#
# def get_type(self):
# return strings.STATIC_NAMES[self.entity_type]
#
# def set_type(self, name):
# self.entity_type = strings.STATIC_IDS[name]
, which may contain function names, class names, or code. Output only the next line. | entity = StaticEntityHeader() |
Using the snippet: <|code_start|>
@asyncio.coroutine
def async_stdin():
global reader
if reader is None:
reader = yield from get_stdin()
line = yield from reader.readline()
return line.decode('utf8')
class ConsoleServer(ServerScript):
connection_class = None
def on_load(self):
if not stdout.isatty():
return
self.interface = ScriptInterface('Console', self.server, 'admin',
'console')
self.task = self.loop.create_task(self.run())
@asyncio.coroutine
def run(self):
while True:
line = yield from async_stdin()
self.handle_line(line)
def handle_line(self, line):
if not line.startswith('/'):
self.server.send_chat(line)
return
<|code_end|>
, determine the next line of code. You have imports:
import sys
import asyncio
import msvcrt
from cuwo.common import parse_command
from cuwo.script import ServerScript, ScriptInterface
and context (class names, function names, or code) available:
# Path: cuwo/common.py
# def parse_command(message):
# try:
# args = shlex.split(message)
# except ValueError:
# # shlex failed. let's just split per space
# args = message.split(' ')
# if args:
# command = args.pop(0)
# else:
# command = ''
# return command, args
#
# Path: cuwo/script.py
# class ServerScript(BaseScript):
# connection_class = ConnectionScript
# commands = None
# aliases = None
#
# def __init__(self, server):
# self.script_name = self.__module__.split('.')[1]
#
# self.server = server
# self.world = server.world
# self.loop = server.loop
# server.scripts.add(self)
# self.children = []
# self.on_load()
# for connection in server.connections:
# self.call('on_existing_connection', connection=connection)
#
# def on_new_connection(self, event):
# if self.connection_class is None:
# return
# script = self.connection_class(self, event.connection)
# script.call('on_connect')
#
# def on_existing_connection(self, event):
# if self.connection_class is None:
# return
# self.connection_class(self, event.connection)
#
# def on_command(self, event):
# return self.call_command(event.user, event.command, event.args)
#
# def unload(self):
# if self.server is None:
# return
# self.on_unload()
# self.server.scripts.remove(self)
# for script in self.children[:]:
# script.unload()
# self.children = None
# self.server = None
# self.world = None
#
# def call_command(self, user, command, args):
# if self.commands is None:
# return
# command = command.lower()
# command = self.aliases.get(command, command)
# command = self.commands.get(command, None)
# if not command:
# return
# user.parent = self # for ScriptInterface
#
# if len(args) < command.min_args:
# return command.get_syntax()
# if command.max_args is not None and len(args) > command.max_args:
# return command.get_syntax()
#
# try:
# ret = command(user, *args) or ''
# except InvalidPlayer:
# ret = 'Invalid player specified'
# except InsufficientRights:
# ret = 'Insufficient rights'
# except Exception:
# import traceback
# traceback.print_exc()
# ret = ''
# return ret
#
# class ScriptInterface:
# """
# Used for external script interfaces to emulate a connection for e.g.
# console and IRC commands
# """
#
# def __init__(self, name, server, *rights):
# self.name = name
# self.rights = AttributeSet(rights)
# self.server = server
# self.connection = self
# self.parent = None # set by call_command
#
# def get_player(self, name):
# if name is None:
# raise InvalidPlayer()
# return get_player(self.server, name)
#
# def get_commands(self):
# return self.server.get_commands()
#
# def get_command(self, name):
# return self.server.get_command(name)
. Output only the next line. | command, args = parse_command(line[1:]) |
Based on the snippet: <|code_start|> elif c == '\x08': # delete
current = current[:-1]
write_stdout('\x08 \x08')
else:
current += c
write_stdout(c)
stdout.flush()
yield from asyncio.sleep(0.04)
return current
else:
reader = None
@asyncio.coroutine
def get_stdin():
loop = asyncio.get_event_loop()
reader = asyncio.StreamReader()
reader_protocol = asyncio.StreamReaderProtocol(reader)
yield from loop.connect_read_pipe(lambda: reader_protocol, sys.stdin)
return reader
@asyncio.coroutine
def async_stdin():
global reader
if reader is None:
reader = yield from get_stdin()
line = yield from reader.readline()
return line.decode('utf8')
<|code_end|>
, predict the immediate next line with the help of imports:
import sys
import asyncio
import msvcrt
from cuwo.common import parse_command
from cuwo.script import ServerScript, ScriptInterface
and context (classes, functions, sometimes code) from other files:
# Path: cuwo/common.py
# def parse_command(message):
# try:
# args = shlex.split(message)
# except ValueError:
# # shlex failed. let's just split per space
# args = message.split(' ')
# if args:
# command = args.pop(0)
# else:
# command = ''
# return command, args
#
# Path: cuwo/script.py
# class ServerScript(BaseScript):
# connection_class = ConnectionScript
# commands = None
# aliases = None
#
# def __init__(self, server):
# self.script_name = self.__module__.split('.')[1]
#
# self.server = server
# self.world = server.world
# self.loop = server.loop
# server.scripts.add(self)
# self.children = []
# self.on_load()
# for connection in server.connections:
# self.call('on_existing_connection', connection=connection)
#
# def on_new_connection(self, event):
# if self.connection_class is None:
# return
# script = self.connection_class(self, event.connection)
# script.call('on_connect')
#
# def on_existing_connection(self, event):
# if self.connection_class is None:
# return
# self.connection_class(self, event.connection)
#
# def on_command(self, event):
# return self.call_command(event.user, event.command, event.args)
#
# def unload(self):
# if self.server is None:
# return
# self.on_unload()
# self.server.scripts.remove(self)
# for script in self.children[:]:
# script.unload()
# self.children = None
# self.server = None
# self.world = None
#
# def call_command(self, user, command, args):
# if self.commands is None:
# return
# command = command.lower()
# command = self.aliases.get(command, command)
# command = self.commands.get(command, None)
# if not command:
# return
# user.parent = self # for ScriptInterface
#
# if len(args) < command.min_args:
# return command.get_syntax()
# if command.max_args is not None and len(args) > command.max_args:
# return command.get_syntax()
#
# try:
# ret = command(user, *args) or ''
# except InvalidPlayer:
# ret = 'Invalid player specified'
# except InsufficientRights:
# ret = 'Insufficient rights'
# except Exception:
# import traceback
# traceback.print_exc()
# ret = ''
# return ret
#
# class ScriptInterface:
# """
# Used for external script interfaces to emulate a connection for e.g.
# console and IRC commands
# """
#
# def __init__(self, name, server, *rights):
# self.name = name
# self.rights = AttributeSet(rights)
# self.server = server
# self.connection = self
# self.parent = None # set by call_command
#
# def get_player(self, name):
# if name is None:
# raise InvalidPlayer()
# return get_player(self.server, name)
#
# def get_commands(self):
# return self.server.get_commands()
#
# def get_command(self, name):
# return self.server.get_command(name)
. Output only the next line. | class ConsoleServer(ServerScript): |
Next line prediction: <|code_start|> stdout.flush()
yield from asyncio.sleep(0.04)
return current
else:
reader = None
@asyncio.coroutine
def get_stdin():
loop = asyncio.get_event_loop()
reader = asyncio.StreamReader()
reader_protocol = asyncio.StreamReaderProtocol(reader)
yield from loop.connect_read_pipe(lambda: reader_protocol, sys.stdin)
return reader
@asyncio.coroutine
def async_stdin():
global reader
if reader is None:
reader = yield from get_stdin()
line = yield from reader.readline()
return line.decode('utf8')
class ConsoleServer(ServerScript):
connection_class = None
def on_load(self):
if not stdout.isatty():
return
<|code_end|>
. Use current file imports:
(import sys
import asyncio
import msvcrt
from cuwo.common import parse_command
from cuwo.script import ServerScript, ScriptInterface)
and context including class names, function names, or small code snippets from other files:
# Path: cuwo/common.py
# def parse_command(message):
# try:
# args = shlex.split(message)
# except ValueError:
# # shlex failed. let's just split per space
# args = message.split(' ')
# if args:
# command = args.pop(0)
# else:
# command = ''
# return command, args
#
# Path: cuwo/script.py
# class ServerScript(BaseScript):
# connection_class = ConnectionScript
# commands = None
# aliases = None
#
# def __init__(self, server):
# self.script_name = self.__module__.split('.')[1]
#
# self.server = server
# self.world = server.world
# self.loop = server.loop
# server.scripts.add(self)
# self.children = []
# self.on_load()
# for connection in server.connections:
# self.call('on_existing_connection', connection=connection)
#
# def on_new_connection(self, event):
# if self.connection_class is None:
# return
# script = self.connection_class(self, event.connection)
# script.call('on_connect')
#
# def on_existing_connection(self, event):
# if self.connection_class is None:
# return
# self.connection_class(self, event.connection)
#
# def on_command(self, event):
# return self.call_command(event.user, event.command, event.args)
#
# def unload(self):
# if self.server is None:
# return
# self.on_unload()
# self.server.scripts.remove(self)
# for script in self.children[:]:
# script.unload()
# self.children = None
# self.server = None
# self.world = None
#
# def call_command(self, user, command, args):
# if self.commands is None:
# return
# command = command.lower()
# command = self.aliases.get(command, command)
# command = self.commands.get(command, None)
# if not command:
# return
# user.parent = self # for ScriptInterface
#
# if len(args) < command.min_args:
# return command.get_syntax()
# if command.max_args is not None and len(args) > command.max_args:
# return command.get_syntax()
#
# try:
# ret = command(user, *args) or ''
# except InvalidPlayer:
# ret = 'Invalid player specified'
# except InsufficientRights:
# ret = 'Insufficient rights'
# except Exception:
# import traceback
# traceback.print_exc()
# ret = ''
# return ret
#
# class ScriptInterface:
# """
# Used for external script interfaces to emulate a connection for e.g.
# console and IRC commands
# """
#
# def __init__(self, name, server, *rights):
# self.name = name
# self.rights = AttributeSet(rights)
# self.server = server
# self.connection = self
# self.parent = None # set by call_command
#
# def get_player(self, name):
# if name is None:
# raise InvalidPlayer()
# return get_player(self.server, name)
#
# def get_commands(self):
# return self.server.get_commands()
#
# def get_command(self, name):
# return self.server.get_command(name)
. Output only the next line. | self.interface = ScriptInterface('Console', self.server, 'admin', |
Based on the snippet: <|code_start|># Copyright (c) Mathias Kaerlev 2013-2017.
#
# This file is part of cuwo.
#
# cuwo is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cuwo is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cuwo. If not, see <http://www.gnu.org/licenses/>.
"""
Ban management
"""
SELF_BANNED = 'You are banned: {reason}'
PLAYER_BANNED = '{name} has been banned: {reason}'
DEFAULT_REASON = 'No reason specified'
DATA_NAME = 'banlist'
<|code_end|>
, predict the immediate next line with the help of imports:
from cuwo.script import ServerScript, command, admin
and context (classes, functions, sometimes code) from other files:
# Path: cuwo/script.py
# class InvalidPlayer(Exception):
# class InsufficientRights(Exception):
# class Command:
# class ScriptManager:
# class BaseScript:
# class ConnectionScript(BaseScript):
# class ServerScript(BaseScript):
# class ScriptInterface:
# def get_player(server, value):
# def __init__(self, func):
# def __call__(self, *arg, **kw):
# def is_compatible(self, rights):
# def get_help(self):
# def get_syntax(self):
# def get_command_base(func):
# def set_command_base(new_func, func):
# def command(func, klass=None):
# def alias(*aliases):
# def dec(func):
# def restrict(*user_types):
# def dec(func):
# def new_func(script, *arg, **kw):
# def __init__(self):
# def __getattr__(self, name):
# def __getitem__(self, name):
# def __contains__(self, name):
# def add(self, script):
# def remove(self, script):
# def unload(self):
# def get(self):
# def call(self, event_name, **kw):
# def call(self, event_name, **kw):
# def on_load(self):
# def on_unload(self):
# def unload(self):
# def __init__(self, parent, connection):
# def on_disconnect(self, event):
# def on_command(self, event):
# def get_player(self, name=None):
# def get_commands(self):
# def get_command(self, name):
# def unload(self):
# def entity(self):
# def __init__(self, server):
# def on_new_connection(self, event):
# def on_existing_connection(self, event):
# def on_command(self, event):
# def unload(self):
# def call_command(self, user, command, args):
# def __init__(self, name, server, *rights):
# def get_player(self, name):
# def get_commands(self):
# def get_command(self, name):
. Output only the next line. | class BanServer(ServerScript): |
Using the snippet: <|code_start|> connection.send_chat(SELF_BANNED.format(reason=reason))
connection.disconnect()
banned_players.append(connection)
if name is None:
continue
message = PLAYER_BANNED.format(name=name, reason=reason)
print(message)
self.server.send_chat(message)
return banned_players
def unban(self, ip):
try:
self.ban_entries.pop(ip)
self.save_bans()
return True
except KeyError:
return False
def on_connection_attempt(self, event):
try:
reason = self.ban_entries[event.address[0]]
except KeyError:
return
return SELF_BANNED.format(reason=reason)
def get_class():
return BanServer
<|code_end|>
, determine the next line of code. You have imports:
from cuwo.script import ServerScript, command, admin
and context (class names, function names, or code) available:
# Path: cuwo/script.py
# class InvalidPlayer(Exception):
# class InsufficientRights(Exception):
# class Command:
# class ScriptManager:
# class BaseScript:
# class ConnectionScript(BaseScript):
# class ServerScript(BaseScript):
# class ScriptInterface:
# def get_player(server, value):
# def __init__(self, func):
# def __call__(self, *arg, **kw):
# def is_compatible(self, rights):
# def get_help(self):
# def get_syntax(self):
# def get_command_base(func):
# def set_command_base(new_func, func):
# def command(func, klass=None):
# def alias(*aliases):
# def dec(func):
# def restrict(*user_types):
# def dec(func):
# def new_func(script, *arg, **kw):
# def __init__(self):
# def __getattr__(self, name):
# def __getitem__(self, name):
# def __contains__(self, name):
# def add(self, script):
# def remove(self, script):
# def unload(self):
# def get(self):
# def call(self, event_name, **kw):
# def call(self, event_name, **kw):
# def on_load(self):
# def on_unload(self):
# def unload(self):
# def __init__(self, parent, connection):
# def on_disconnect(self, event):
# def on_command(self, event):
# def get_player(self, name=None):
# def get_commands(self):
# def get_command(self, name):
# def unload(self):
# def entity(self):
# def __init__(self, server):
# def on_new_connection(self, event):
# def on_existing_connection(self, event):
# def on_command(self, event):
# def unload(self):
# def call_command(self, user, command, args):
# def __init__(self, name, server, *rights):
# def get_player(self, name):
# def get_commands(self):
# def get_command(self, name):
. Output only the next line. | @command |
Given the following code snippet before the placeholder: <|code_start|> connection.disconnect()
banned_players.append(connection)
if name is None:
continue
message = PLAYER_BANNED.format(name=name, reason=reason)
print(message)
self.server.send_chat(message)
return banned_players
def unban(self, ip):
try:
self.ban_entries.pop(ip)
self.save_bans()
return True
except KeyError:
return False
def on_connection_attempt(self, event):
try:
reason = self.ban_entries[event.address[0]]
except KeyError:
return
return SELF_BANNED.format(reason=reason)
def get_class():
return BanServer
@command
<|code_end|>
, predict the next line using imports from the current file:
from cuwo.script import ServerScript, command, admin
and context including class names, function names, and sometimes code from other files:
# Path: cuwo/script.py
# class InvalidPlayer(Exception):
# class InsufficientRights(Exception):
# class Command:
# class ScriptManager:
# class BaseScript:
# class ConnectionScript(BaseScript):
# class ServerScript(BaseScript):
# class ScriptInterface:
# def get_player(server, value):
# def __init__(self, func):
# def __call__(self, *arg, **kw):
# def is_compatible(self, rights):
# def get_help(self):
# def get_syntax(self):
# def get_command_base(func):
# def set_command_base(new_func, func):
# def command(func, klass=None):
# def alias(*aliases):
# def dec(func):
# def restrict(*user_types):
# def dec(func):
# def new_func(script, *arg, **kw):
# def __init__(self):
# def __getattr__(self, name):
# def __getitem__(self, name):
# def __contains__(self, name):
# def add(self, script):
# def remove(self, script):
# def unload(self):
# def get(self):
# def call(self, event_name, **kw):
# def call(self, event_name, **kw):
# def on_load(self):
# def on_unload(self):
# def unload(self):
# def __init__(self, parent, connection):
# def on_disconnect(self, event):
# def on_command(self, event):
# def get_player(self, name=None):
# def get_commands(self):
# def get_command(self, name):
# def unload(self):
# def entity(self):
# def __init__(self, server):
# def on_new_connection(self, event):
# def on_existing_connection(self, event):
# def on_command(self, event):
# def unload(self):
# def call_command(self, user, command, args):
# def __init__(self, name, server, *rights):
# def get_player(self, name):
# def get_commands(self):
# def get_command(self, name):
. Output only the next line. | @admin |
Given the code snippet: <|code_start|># Copyright (c) Mathias Kaerlev 2013-2017.
#
# This file is part of cuwo.
#
# cuwo is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cuwo is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cuwo. If not, see <http://www.gnu.org/licenses/>.
sys.path.append('.')
def switch_axes(x, y, z):
return x, z, y
def convert_qmo(data, path):
<|code_end|>
, generate the next line using the imports in this file:
import sys
import argparse
from cuwo import tgen
from cuwo.bytes import ByteWriter
from cuwo.qmo import QubicleFile, QubicleModel
and context (functions, classes, or occasionally code) from other files:
# Path: cuwo/qmo.py
# class QubicleFile:
# def __init__(self, reader=None):
# self.models = []
# if reader is None:
# return
# if read_string(reader) != MAGIC:
# raise NotImplementedError('invalid magic')
# elif read_string(reader) != VERSION:
# raise NotImplementedError('unsupported version')
# for _ in range(reader.read_uint32()):
# self.models.append(QubicleModel(reader))
# self.junk = reader.read()
# if len(self.junk) != 108:
# raise NotImplementedError
#
# def write(self, writer):
# write_string(writer, MAGIC)
# write_string(writer, VERSION)
# writer.write_uint32(len(self.models))
# for model in self.models:
# model.write(writer)
# writer.write(b'\x00' * 108)
#
# class QubicleModel:
# def __init__(self, reader=None):
# self.blocks = {}
# if reader is None:
# self.x_size = self.y_size = self.z_size = 0
# self.name = 'Empty'
# self.x_offset = self.y_offset = self.z_offset = 0
# self.hidden = 0
# return
# self.x_size = reader.read_uint32()
# self.y_size = reader.read_uint32()
# self.z_size = reader.read_uint32()
# self.name = read_string(reader)
# self.x_offset = reader.read_int32()
# self.y_offset = reader.read_int32()
# self.z_offset = reader.read_int32()
# self.hidden = reader.read_uint8()
# rle_count = reader.read_uint32()
# i = 0
# while rle_count:
# value = reader.read_uint32()
# rle_count -= 1
# if value == 2: # repetition
# times = reader.read_uint32()
# color = reader.read_uint32()
# rle_count -= 2
# else:
# times = 1
# color = value
# if color & 0xFF000000 == 0:
# i += times
# continue
# r = int(color & 0x0000FF)
# g = int((color & 0x00FF00) >> 8)
# b = int((color & 0xFF0000) >> 16)
# for _ in range(times):
# x = i / (self.y_size * self.z_size)
# y = (i % (self.y_size * self.z_size)) / self.z_size
# z = i % self.z_size
# self.blocks[(int(x), int(y), int(z))] = (r, g, b)
# i += 1
#
# def write(self, writer):
# writer.write_uint32(self.x_size)
# writer.write_uint32(self.y_size)
# writer.write_uint32(self.z_size)
# write_string(writer, self.name)
# writer.write_int32(self.x_offset)
# writer.write_int32(self.y_offset)
# writer.write_int32(self.z_offset)
# writer.write_uint8(self.hidden)
# writer.write_uint32(self.x_size * self.y_size * self.z_size)
# for x in range(self.x_size):
# for y in range(self.y_size):
# for z in range(self.z_size):
# c = self.blocks.get((x, y, z), None)
# if c is None:
# writer.write_uint32(0)
# continue
# r, g, b = c
# c2 = r | (g << 8) | (b << 16) | (0x7F << 24)
# writer.write_uint32(c2)
. Output only the next line. | qmo_file = QubicleFile() |
Given snippet: <|code_start|># Copyright (c) Mathias Kaerlev 2013-2017.
#
# This file is part of cuwo.
#
# cuwo is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cuwo is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cuwo. If not, see <http://www.gnu.org/licenses/>.
sys.path.append('.')
def switch_axes(x, y, z):
return x, z, y
def convert_qmo(data, path):
qmo_file = QubicleFile()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
import argparse
from cuwo import tgen
from cuwo.bytes import ByteWriter
from cuwo.qmo import QubicleFile, QubicleModel
and context:
# Path: cuwo/qmo.py
# class QubicleFile:
# def __init__(self, reader=None):
# self.models = []
# if reader is None:
# return
# if read_string(reader) != MAGIC:
# raise NotImplementedError('invalid magic')
# elif read_string(reader) != VERSION:
# raise NotImplementedError('unsupported version')
# for _ in range(reader.read_uint32()):
# self.models.append(QubicleModel(reader))
# self.junk = reader.read()
# if len(self.junk) != 108:
# raise NotImplementedError
#
# def write(self, writer):
# write_string(writer, MAGIC)
# write_string(writer, VERSION)
# writer.write_uint32(len(self.models))
# for model in self.models:
# model.write(writer)
# writer.write(b'\x00' * 108)
#
# class QubicleModel:
# def __init__(self, reader=None):
# self.blocks = {}
# if reader is None:
# self.x_size = self.y_size = self.z_size = 0
# self.name = 'Empty'
# self.x_offset = self.y_offset = self.z_offset = 0
# self.hidden = 0
# return
# self.x_size = reader.read_uint32()
# self.y_size = reader.read_uint32()
# self.z_size = reader.read_uint32()
# self.name = read_string(reader)
# self.x_offset = reader.read_int32()
# self.y_offset = reader.read_int32()
# self.z_offset = reader.read_int32()
# self.hidden = reader.read_uint8()
# rle_count = reader.read_uint32()
# i = 0
# while rle_count:
# value = reader.read_uint32()
# rle_count -= 1
# if value == 2: # repetition
# times = reader.read_uint32()
# color = reader.read_uint32()
# rle_count -= 2
# else:
# times = 1
# color = value
# if color & 0xFF000000 == 0:
# i += times
# continue
# r = int(color & 0x0000FF)
# g = int((color & 0x00FF00) >> 8)
# b = int((color & 0xFF0000) >> 16)
# for _ in range(times):
# x = i / (self.y_size * self.z_size)
# y = (i % (self.y_size * self.z_size)) / self.z_size
# z = i % self.z_size
# self.blocks[(int(x), int(y), int(z))] = (r, g, b)
# i += 1
#
# def write(self, writer):
# writer.write_uint32(self.x_size)
# writer.write_uint32(self.y_size)
# writer.write_uint32(self.z_size)
# write_string(writer, self.name)
# writer.write_int32(self.x_offset)
# writer.write_int32(self.y_offset)
# writer.write_int32(self.z_offset)
# writer.write_uint8(self.hidden)
# writer.write_uint32(self.x_size * self.y_size * self.z_size)
# for x in range(self.x_size):
# for y in range(self.y_size):
# for z in range(self.z_size):
# c = self.blocks.get((x, y, z), None)
# if c is None:
# writer.write_uint32(0)
# continue
# r, g, b = c
# c2 = r | (g << 8) | (b << 16) | (0x7F << 24)
# writer.write_uint32(c2)
which might include code, classes, or functions. Output only the next line. | qmo_model = QubicleModel() |
Predict the next line after this snippet: <|code_start|>
def __init__(self, pickled_model_path, delay=0.2):
""" Create a MarioKart Agent instance.
Args:
pickled_model_path: Path to the stored state-decision model file.
screenshot_folder: Name of the folder where the current Dolphin game's screenshots are stored.
"""
saved_model_file = open(pickled_model_path, 'rb')
saved_model_obj = pickle.load(saved_model_file)
self.decision_map = saved_model_obj.get("model")
self.default_map = saved_model_obj.get("defaults")
saved_model_file.close()
self.frame_delay = delay
self.screenshot_dir = os.path.join(helper.get_home_folder(), '.dolphin-emu', 'ScreenShots', self.game_name)
self.key_map = key2pad.KeyPadMap()
self.key_states = dict()
def process_frame(self):
""" Process a single frame of the current Dolphin game.
Note:
Process means read the state of the game and decide what action to take in this context.
Dolphin will not take screenshots if the game is paused!
"""
# Advance the Dolphin frame
dp_frames.advance('P')
# Take screenshot of current Dolphin frame
<|code_end|>
using the current file's imports:
import logging
import pickle
import os
import time
import random
from src import dp_screenshot, helper, mk_downsampler, key2pad, dp_frames
and any relevant context from other files:
# Path: src/dp_screenshot.py
# def take_screenshot():
#
# Path: src/helper.py
# def validate_function_key(slot_key):
# def get_output_folder():
# def get_models_folder():
# def get_dataset_folder():
# def get_home_folder():
# def pickle_object(data, name, directory=get_output_folder()):
# def generate_img_key(image):
# def get_tensor(image):
# def get_output_vector(presses):
# def get_key_state_from_vector(vector):
#
# Path: src/mk_downsampler.py
# class Downsampler:
# def __init__(self, game_name, blur_size=25, intermediate_dim=300, final_dim=10):
# def downsample_dir(self, save_imgs=False, clean_data=False):
# def downsample(self, file_path, output_name=None, save_img=False, clean_data=False):
# def save_image(self, img, output_name):
#
# Path: src/key2pad.py
# class KeyPadMap:
# def __init__(self):
# def update(self, keys):
# def convert_key(self, key, is_press):
#
# Path: src/dp_frames.py
# def advance(slot_key):
# def inc_speed(slot_key):
# def dec_speed(slot_key):
# def res_speed(slot_key):
. Output only the next line. | dp_screenshot.take_screenshot() |
Next line prediction: <|code_start|> distributed random number between 0 and 1 and comparing it to the probability of pressing a button in a given
state. If the random number is above the probability threshold, the action is taken. If a state has never been
encountered before, an action is chosen based on how often that action is taken in total out of all encountered
states.
3) The basic Mario Kart AI agent takes the desired action by sending controller inputs to the Dolphin emulator using
fifo pipes and advancing the game by 1 frame, at which point the process starts again based on the next frame
(state)
"""
logger = logging.getLogger(__name__)
class MarioKartAgent:
""" Class implementing a basic Mario Kart AI agent using conditional probability. """
game_name = "NABE01"
def __init__(self, pickled_model_path, delay=0.2):
""" Create a MarioKart Agent instance.
Args:
pickled_model_path: Path to the stored state-decision model file.
screenshot_folder: Name of the folder where the current Dolphin game's screenshots are stored.
"""
saved_model_file = open(pickled_model_path, 'rb')
saved_model_obj = pickle.load(saved_model_file)
self.decision_map = saved_model_obj.get("model")
self.default_map = saved_model_obj.get("defaults")
saved_model_file.close()
self.frame_delay = delay
<|code_end|>
. Use current file imports:
(import logging
import pickle
import os
import time
import random
from src import dp_screenshot, helper, mk_downsampler, key2pad, dp_frames)
and context including class names, function names, or small code snippets from other files:
# Path: src/dp_screenshot.py
# def take_screenshot():
#
# Path: src/helper.py
# def validate_function_key(slot_key):
# def get_output_folder():
# def get_models_folder():
# def get_dataset_folder():
# def get_home_folder():
# def pickle_object(data, name, directory=get_output_folder()):
# def generate_img_key(image):
# def get_tensor(image):
# def get_output_vector(presses):
# def get_key_state_from_vector(vector):
#
# Path: src/mk_downsampler.py
# class Downsampler:
# def __init__(self, game_name, blur_size=25, intermediate_dim=300, final_dim=10):
# def downsample_dir(self, save_imgs=False, clean_data=False):
# def downsample(self, file_path, output_name=None, save_img=False, clean_data=False):
# def save_image(self, img, output_name):
#
# Path: src/key2pad.py
# class KeyPadMap:
# def __init__(self):
# def update(self, keys):
# def convert_key(self, key, is_press):
#
# Path: src/dp_frames.py
# def advance(slot_key):
# def inc_speed(slot_key):
# def dec_speed(slot_key):
# def res_speed(slot_key):
. Output only the next line. | self.screenshot_dir = os.path.join(helper.get_home_folder(), '.dolphin-emu', 'ScreenShots', self.game_name) |
Using the snippet: <|code_start|> screenshot_folder: Name of the folder where the current Dolphin game's screenshots are stored.
"""
saved_model_file = open(pickled_model_path, 'rb')
saved_model_obj = pickle.load(saved_model_file)
self.decision_map = saved_model_obj.get("model")
self.default_map = saved_model_obj.get("defaults")
saved_model_file.close()
self.frame_delay = delay
self.screenshot_dir = os.path.join(helper.get_home_folder(), '.dolphin-emu', 'ScreenShots', self.game_name)
self.key_map = key2pad.KeyPadMap()
self.key_states = dict()
def process_frame(self):
""" Process a single frame of the current Dolphin game.
Note:
Process means read the state of the game and decide what action to take in this context.
Dolphin will not take screenshots if the game is paused!
"""
# Advance the Dolphin frame
dp_frames.advance('P')
# Take screenshot of current Dolphin frame
dp_screenshot.take_screenshot()
screenshot_file = os.path.join(self.screenshot_dir, 'NABE01-1.png')
time.sleep(self.frame_delay)
try:
# Downsample the screenshot and calculate dictionary key
<|code_end|>
, determine the next line of code. You have imports:
import logging
import pickle
import os
import time
import random
from src import dp_screenshot, helper, mk_downsampler, key2pad, dp_frames
and context (class names, function names, or code) available:
# Path: src/dp_screenshot.py
# def take_screenshot():
#
# Path: src/helper.py
# def validate_function_key(slot_key):
# def get_output_folder():
# def get_models_folder():
# def get_dataset_folder():
# def get_home_folder():
# def pickle_object(data, name, directory=get_output_folder()):
# def generate_img_key(image):
# def get_tensor(image):
# def get_output_vector(presses):
# def get_key_state_from_vector(vector):
#
# Path: src/mk_downsampler.py
# class Downsampler:
# def __init__(self, game_name, blur_size=25, intermediate_dim=300, final_dim=10):
# def downsample_dir(self, save_imgs=False, clean_data=False):
# def downsample(self, file_path, output_name=None, save_img=False, clean_data=False):
# def save_image(self, img, output_name):
#
# Path: src/key2pad.py
# class KeyPadMap:
# def __init__(self):
# def update(self, keys):
# def convert_key(self, key, is_press):
#
# Path: src/dp_frames.py
# def advance(slot_key):
# def inc_speed(slot_key):
# def dec_speed(slot_key):
# def res_speed(slot_key):
. Output only the next line. | ds_image = mk_downsampler.Downsampler(self.game_name, final_dim=15).downsample(screenshot_file) |
Using the snippet: <|code_start|> state. If the random number is above the probability threshold, the action is taken. If a state has never been
encountered before, an action is chosen based on how often that action is taken in total out of all encountered
states.
3) The basic Mario Kart AI agent takes the desired action by sending controller inputs to the Dolphin emulator using
fifo pipes and advancing the game by 1 frame, at which point the process starts again based on the next frame
(state)
"""
logger = logging.getLogger(__name__)
class MarioKartAgent:
""" Class implementing a basic Mario Kart AI agent using conditional probability. """
game_name = "NABE01"
def __init__(self, pickled_model_path, delay=0.2):
""" Create a MarioKart Agent instance.
Args:
pickled_model_path: Path to the stored state-decision model file.
screenshot_folder: Name of the folder where the current Dolphin game's screenshots are stored.
"""
saved_model_file = open(pickled_model_path, 'rb')
saved_model_obj = pickle.load(saved_model_file)
self.decision_map = saved_model_obj.get("model")
self.default_map = saved_model_obj.get("defaults")
saved_model_file.close()
self.frame_delay = delay
self.screenshot_dir = os.path.join(helper.get_home_folder(), '.dolphin-emu', 'ScreenShots', self.game_name)
<|code_end|>
, determine the next line of code. You have imports:
import logging
import pickle
import os
import time
import random
from src import dp_screenshot, helper, mk_downsampler, key2pad, dp_frames
and context (class names, function names, or code) available:
# Path: src/dp_screenshot.py
# def take_screenshot():
#
# Path: src/helper.py
# def validate_function_key(slot_key):
# def get_output_folder():
# def get_models_folder():
# def get_dataset_folder():
# def get_home_folder():
# def pickle_object(data, name, directory=get_output_folder()):
# def generate_img_key(image):
# def get_tensor(image):
# def get_output_vector(presses):
# def get_key_state_from_vector(vector):
#
# Path: src/mk_downsampler.py
# class Downsampler:
# def __init__(self, game_name, blur_size=25, intermediate_dim=300, final_dim=10):
# def downsample_dir(self, save_imgs=False, clean_data=False):
# def downsample(self, file_path, output_name=None, save_img=False, clean_data=False):
# def save_image(self, img, output_name):
#
# Path: src/key2pad.py
# class KeyPadMap:
# def __init__(self):
# def update(self, keys):
# def convert_key(self, key, is_press):
#
# Path: src/dp_frames.py
# def advance(slot_key):
# def inc_speed(slot_key):
# def dec_speed(slot_key):
# def res_speed(slot_key):
. Output only the next line. | self.key_map = key2pad.KeyPadMap() |
Given snippet: <|code_start|>class MarioKartAgent:
""" Class implementing a basic Mario Kart AI agent using conditional probability. """
game_name = "NABE01"
def __init__(self, pickled_model_path, delay=0.2):
""" Create a MarioKart Agent instance.
Args:
pickled_model_path: Path to the stored state-decision model file.
screenshot_folder: Name of the folder where the current Dolphin game's screenshots are stored.
"""
saved_model_file = open(pickled_model_path, 'rb')
saved_model_obj = pickle.load(saved_model_file)
self.decision_map = saved_model_obj.get("model")
self.default_map = saved_model_obj.get("defaults")
saved_model_file.close()
self.frame_delay = delay
self.screenshot_dir = os.path.join(helper.get_home_folder(), '.dolphin-emu', 'ScreenShots', self.game_name)
self.key_map = key2pad.KeyPadMap()
self.key_states = dict()
def process_frame(self):
""" Process a single frame of the current Dolphin game.
Note:
Process means read the state of the game and decide what action to take in this context.
Dolphin will not take screenshots if the game is paused!
"""
# Advance the Dolphin frame
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
import pickle
import os
import time
import random
from src import dp_screenshot, helper, mk_downsampler, key2pad, dp_frames
and context:
# Path: src/dp_screenshot.py
# def take_screenshot():
#
# Path: src/helper.py
# def validate_function_key(slot_key):
# def get_output_folder():
# def get_models_folder():
# def get_dataset_folder():
# def get_home_folder():
# def pickle_object(data, name, directory=get_output_folder()):
# def generate_img_key(image):
# def get_tensor(image):
# def get_output_vector(presses):
# def get_key_state_from_vector(vector):
#
# Path: src/mk_downsampler.py
# class Downsampler:
# def __init__(self, game_name, blur_size=25, intermediate_dim=300, final_dim=10):
# def downsample_dir(self, save_imgs=False, clean_data=False):
# def downsample(self, file_path, output_name=None, save_img=False, clean_data=False):
# def save_image(self, img, output_name):
#
# Path: src/key2pad.py
# class KeyPadMap:
# def __init__(self):
# def update(self, keys):
# def convert_key(self, key, is_press):
#
# Path: src/dp_frames.py
# def advance(slot_key):
# def inc_speed(slot_key):
# def dec_speed(slot_key):
# def res_speed(slot_key):
which might include code, classes, or functions. Output only the next line. | dp_frames.advance('P') |
Here is a snippet: <|code_start|> """ Save data as a pickled file in dir """
output = os.path.join(directory, "{}.pkl".format(name))
with open(output, 'wb') as m:
pickle.dump(data, m, pickle.HIGHEST_PROTOCOL)
def generate_img_key(image):
try:
image_single_channel = image[:, :, 1]
except IndexError:
image_single_channel = image
except TypeError:
logger.warning("Image key not generated.")
return None
return tuple(image_single_channel.flatten())
def get_tensor(image):
try:
image_single_channel = image[:, :, 1]
except IndexError:
image_single_channel = image
except TypeError:
logger.warning("Image tensor not generated.")
return None
return torch.from_numpy(image_single_channel).contiguous()
def get_output_vector(presses):
out = []
<|code_end|>
. Write the next line using the current file imports:
import logging
import pickle
import re
import os
import random
import torch
from src import keylog
and context from other files:
# Path: src/keylog.py
# class Keyboard(enum.Enum):
# class KeyLog:
# def __init__(self, logging_delay=0.3):
# def start(self):
# def on_press(self, key):
# def on_release(self, key):
# def record(self):
# def save_to_file(self, file_name="log.json"):
# def _get_key_value(key):
, which may include functions, classes, or code. Output only the next line. | for key in keylog.Keyboard: |
Given snippet: <|code_start|>
class KeyPadMap:
def __init__(self):
self.previous_keys = dict((el.name, False) for el in keylog.Keyboard)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import src.keylog as keylog
from src import dp_controller
and context:
# Path: src/dp_controller.py
# class Button(enum.Enum):
# class Trigger(enum.Enum):
# class Stick(enum.Enum):
# class DolphinController:
# A = 0
# B = 1
# X = 2
# Y = 3
# Z = 4
# START = 5
# L = 6
# R = 7
# D_UP = 8
# D_DOWN = 9
# D_LEFT = 10
# D_RIGHT = 11
# L = 0
# R = 1
# MAIN = 0
# C = 1
# def __init__(self, path):
# def __enter__(self):
# def __exit__(self, *args):
# def press_button(self, button):
# def release_button(self, button):
# def press_release_button(self, button, delay):
# def set_trigger(self, trigger, amount):
# def set_stick(self, stick, x, y):
# def reset(self):
which might include code, classes, or functions. Output only the next line. | self.p = dp_controller.DolphinController("~/.dolphin-emu/Pipes/pipe").__enter__() |
Here is a snippet: <|code_start|> # on key press callback. sets pressed key state to 1. shows warning if key is not defined.
def on_press(self, key):
if key == keyboard.Key.f9 or key == keyboard.Key.esc: return
try:
value = self._get_key_value(key)
self.state[Keyboard[value].name] = 1
if self.state[Keyboard[value].name] == 0:
logger.debug('key {} pressed {}'.format(value, self.state[Keyboard[value].name]))
except KeyError:
logger.warning("Pressed key not defined within allowable controller inputs.")
# on key release callback. sets released key state to False
def on_release(self, key):
try:
value = self._get_key_value(key)
self.state[Keyboard[value].name] = 0
if self.state[Keyboard[value].name] == 1:
logger.debug('{} released {}'.format(value, self.state[Keyboard[value].name]))
except KeyError:
if key == keyboard.Key.esc:
self.finish = True
# save_dolphin_state key press log
self.save_to_file()
# Stop listener
return False
# log key press states while taking screenshots based on defined frequency
def record(self):
if self.finish: return
threading.Timer(self.logging_delay, self.record).start()
<|code_end|>
. Write the next line using the current file imports:
import enum
import logging
import json
import threading
import os
from pynput import keyboard
from src import dp_screenshot, helper
and context from other files:
# Path: src/dp_screenshot.py
# def take_screenshot():
#
# Path: src/helper.py
# def validate_function_key(slot_key):
# def get_output_folder():
# def get_models_folder():
# def get_dataset_folder():
# def get_home_folder():
# def pickle_object(data, name, directory=get_output_folder()):
# def generate_img_key(image):
# def get_tensor(image):
# def get_output_vector(presses):
# def get_key_state_from_vector(vector):
, which may include functions, classes, or code. Output only the next line. | dp_screenshot.take_screenshot() |
Using the snippet: <|code_start|> except KeyError:
logger.warning("Pressed key not defined within allowable controller inputs.")
# on key release callback. sets released key state to False
def on_release(self, key):
try:
value = self._get_key_value(key)
self.state[Keyboard[value].name] = 0
if self.state[Keyboard[value].name] == 1:
logger.debug('{} released {}'.format(value, self.state[Keyboard[value].name]))
except KeyError:
if key == keyboard.Key.esc:
self.finish = True
# save_dolphin_state key press log
self.save_to_file()
# Stop listener
return False
# log key press states while taking screenshots based on defined frequency
def record(self):
if self.finish: return
threading.Timer(self.logging_delay, self.record).start()
dp_screenshot.take_screenshot()
self.log['data'].append({
"count": self.count,
"presses": dict(self.state)
})
self.count += 1
def save_to_file(self, file_name="log.json"):
<|code_end|>
, determine the next line of code. You have imports:
import enum
import logging
import json
import threading
import os
from pynput import keyboard
from src import dp_screenshot, helper
and context (class names, function names, or code) available:
# Path: src/dp_screenshot.py
# def take_screenshot():
#
# Path: src/helper.py
# def validate_function_key(slot_key):
# def get_output_folder():
# def get_models_folder():
# def get_dataset_folder():
# def get_home_folder():
# def pickle_object(data, name, directory=get_output_folder()):
# def generate_img_key(image):
# def get_tensor(image):
# def get_output_vector(presses):
# def get_key_state_from_vector(vector):
. Output only the next line. | output_dir = helper.get_output_folder() |
Given the code snippet: <|code_start|> for step, (x, y) in enumerate(train_loader):
# Wrap label 'y' in variable
y_label = y.view(-1, output_vec)
if torch.cuda.is_available():
y_label = y_label.cuda()
nn_label = Variable(y_label)
# Forward pass
forward_pass = mkcnn(x)
loss = loss_func(forward_pass, nn_label) # compute loss
optimizer.zero_grad() # zero gradients from previous step
loss.backward() # compute gradients
optimizer.step() # apply backpropagation
# Log training data
if step % 50 == 0:
print('Epoch: ', epoch, 'Step: ', step, '| training loss: %.4f' % loss.data[0])
valid_loss = 0
for (valid_x, valid_y) in valid_loader:
valid_y_label = valid_y.view(-1, output_vec)
if torch.cuda.is_available():
valid_y_label = valid_y_label.cuda()
valid_nn_label = Variable(valid_y_label)
valid_forward_pass = mkcnn(valid_x)
valid_loss_eval = loss_func(valid_forward_pass, valid_nn_label) # compute validation loss
valid_loss += valid_loss_eval.data[0]
print('Epoch: ', epoch, 'Step: ', step, '| validation loss: %.4f' % valid_loss)
validation_losses.append(valid_loss)
# Save model
<|code_end|>
, generate the next line using the imports in this file:
import logging
import os
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from src import helper, keylog
from src.agents.train_valid_data import get_mario_train_valid_loader
from torch.autograd import Variable
and context (functions, classes, or occasionally code) from other files:
# Path: src/helper.py
# def validate_function_key(slot_key):
# def get_output_folder():
# def get_models_folder():
# def get_dataset_folder():
# def get_home_folder():
# def pickle_object(data, name, directory=get_output_folder()):
# def generate_img_key(image):
# def get_tensor(image):
# def get_output_vector(presses):
# def get_key_state_from_vector(vector):
#
# Path: src/keylog.py
# class Keyboard(enum.Enum):
# class KeyLog:
# def __init__(self, logging_delay=0.3):
# def start(self):
# def on_press(self, key):
# def on_release(self, key):
# def record(self):
# def save_to_file(self, file_name="log.json"):
# def _get_key_value(key):
#
# Path: src/agents/train_valid_data.py
# def get_mario_train_valid_loader(batch_size,
# augment,
# random_seed,
# valid_size=0.2,
# shuffle=True,
# history=1,
# num_workers=1,
# pin_memory=False):
# """
# Utility function for loading and returning train and valid
# multi-process iterators over the MarioKart dataset. A sample
# 9x9 grid of the images can be optionally displayed.
# If using CUDA, num_workers should be set to 1 and pin_memory to True.
# Params
# ------
# - data_dir: path directory to the dataset.
# - batch_size: how many samples per batch to load.
# - augment: whether to apply the data augmentation scheme
# mentioned in the paper. Only applied on the train split.
# - random_seed: fix seed for reproducibility.
# - valid_size: percentage split of the training set used for
# the validation set. Should be a float in the range [0, 1].
# - shuffle: whether to shuffle the train/validation indices.
# - show_sample: plot 9x9 sample grid of the dataset.
# - num_workers: number of subprocesses to use when loading the dataset.
# - pin_memory: whether to copy tensors into CUDA pinned memory. Set it to
# True if using GPU.
# Returns
# -------
# - train_loader: training set iterator.
# - valid_loader: validation set iterator.
# """
# error_msg = "[!] valid_size should be in the range [0, 1]."
# assert ((valid_size >= 0) and (valid_size <= 1)), error_msg
#
# normalize = transforms.Normalize(mean=[0.5, 0.5, 0.5],
# std=[0.5, 0.5, 0.5])
#
# # define transforms
# valid_transform = transforms.Compose([
# transforms.ToTensor(),
# normalize
# ])
# if augment:
# train_transform = transforms.Compose([
# transforms.RandomCrop(32, padding=4),
# transforms.ToTensor(),
# normalize
# ])
# else:
# train_transform = transforms.Compose([
# transforms.ToTensor(),
# normalize
# ])
#
# # load the dataset
# train_dataset = MarioKartDataset(transform=train_transform, history=history)
# valid_dataset = MarioKartDataset(transform=valid_transform, history=history)
#
# num_train = len(train_dataset)
# indices = list(range(num_train))
# split = int(np.floor(valid_size * num_train))
#
# if shuffle:
# np.random.seed(random_seed)
# np.random.shuffle(indices)
#
# train_idx, valid_idx = indices[split:], indices[:split]
#
# train_sampler = SubsetRandomSampler(train_idx)
# valid_sampler = SubsetRandomSampler(valid_idx)
#
# train_loader = torch.utils.data.DataLoader(train_dataset,
# batch_size=batch_size, sampler=train_sampler,
# num_workers=num_workers, pin_memory=pin_memory)
#
# valid_loader = torch.utils.data.DataLoader(valid_dataset,
# batch_size=batch_size, sampler=valid_sampler,
# num_workers=num_workers, pin_memory=pin_memory)
# return train_loader, valid_loader
. Output only the next line. | torch.save(mkcnn, os.path.join(helper.get_models_folder(), "mkcnn_{}_frames.pkl".format(num_input_frames))) |
Next line prediction: <|code_start|>"""
This module implements a Convolutional Neural Network (CNN) Mario Kart AI Agent using PyTorch.
"""
logger = logging.getLogger(__name__)
# Hyper Parameters
input_size = 15
<|code_end|>
. Use current file imports:
(import logging
import os
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from src import helper, keylog
from src.agents.train_valid_data import get_mario_train_valid_loader
from torch.autograd import Variable)
and context including class names, function names, or small code snippets from other files:
# Path: src/helper.py
# def validate_function_key(slot_key):
# def get_output_folder():
# def get_models_folder():
# def get_dataset_folder():
# def get_home_folder():
# def pickle_object(data, name, directory=get_output_folder()):
# def generate_img_key(image):
# def get_tensor(image):
# def get_output_vector(presses):
# def get_key_state_from_vector(vector):
#
# Path: src/keylog.py
# class Keyboard(enum.Enum):
# class KeyLog:
# def __init__(self, logging_delay=0.3):
# def start(self):
# def on_press(self, key):
# def on_release(self, key):
# def record(self):
# def save_to_file(self, file_name="log.json"):
# def _get_key_value(key):
#
# Path: src/agents/train_valid_data.py
# def get_mario_train_valid_loader(batch_size,
# augment,
# random_seed,
# valid_size=0.2,
# shuffle=True,
# history=1,
# num_workers=1,
# pin_memory=False):
# """
# Utility function for loading and returning train and valid
# multi-process iterators over the MarioKart dataset. A sample
# 9x9 grid of the images can be optionally displayed.
# If using CUDA, num_workers should be set to 1 and pin_memory to True.
# Params
# ------
# - data_dir: path directory to the dataset.
# - batch_size: how many samples per batch to load.
# - augment: whether to apply the data augmentation scheme
# mentioned in the paper. Only applied on the train split.
# - random_seed: fix seed for reproducibility.
# - valid_size: percentage split of the training set used for
# the validation set. Should be a float in the range [0, 1].
# - shuffle: whether to shuffle the train/validation indices.
# - show_sample: plot 9x9 sample grid of the dataset.
# - num_workers: number of subprocesses to use when loading the dataset.
# - pin_memory: whether to copy tensors into CUDA pinned memory. Set it to
# True if using GPU.
# Returns
# -------
# - train_loader: training set iterator.
# - valid_loader: validation set iterator.
# """
# error_msg = "[!] valid_size should be in the range [0, 1]."
# assert ((valid_size >= 0) and (valid_size <= 1)), error_msg
#
# normalize = transforms.Normalize(mean=[0.5, 0.5, 0.5],
# std=[0.5, 0.5, 0.5])
#
# # define transforms
# valid_transform = transforms.Compose([
# transforms.ToTensor(),
# normalize
# ])
# if augment:
# train_transform = transforms.Compose([
# transforms.RandomCrop(32, padding=4),
# transforms.ToTensor(),
# normalize
# ])
# else:
# train_transform = transforms.Compose([
# transforms.ToTensor(),
# normalize
# ])
#
# # load the dataset
# train_dataset = MarioKartDataset(transform=train_transform, history=history)
# valid_dataset = MarioKartDataset(transform=valid_transform, history=history)
#
# num_train = len(train_dataset)
# indices = list(range(num_train))
# split = int(np.floor(valid_size * num_train))
#
# if shuffle:
# np.random.seed(random_seed)
# np.random.shuffle(indices)
#
# train_idx, valid_idx = indices[split:], indices[:split]
#
# train_sampler = SubsetRandomSampler(train_idx)
# valid_sampler = SubsetRandomSampler(valid_idx)
#
# train_loader = torch.utils.data.DataLoader(train_dataset,
# batch_size=batch_size, sampler=train_sampler,
# num_workers=num_workers, pin_memory=pin_memory)
#
# valid_loader = torch.utils.data.DataLoader(valid_dataset,
# batch_size=batch_size, sampler=valid_sampler,
# num_workers=num_workers, pin_memory=pin_memory)
# return train_loader, valid_loader
. Output only the next line. | output_vec = len(keylog.Keyboard) |
Based on the snippet: <|code_start|> nn.LeakyReLU(),
nn.Linear(self.fc_hidden3, output_vec),
)
if torch.cuda.is_available():
print("cuda is available.")
self.cuda()
def forward(self, x):
""" Forward pass of the neural network. Accepts a tensor of size input_size*input_size. """
x = x.view(-1, self.conv1_in, self.input_size, self.input_size)
x = Variable(x).float()
if torch.cuda.is_available():
x = x.cuda()
out = self.conv1(x)
out = self.conv2(out)
out = out.view(out.size(0), -1) # flatten the output of conv2 to (batch_size, 6 * 5 *5)
out = self.fc(out)
return out
if __name__ == '__main__':
""" Train neural network Mario Kart AI agent. """
mkcnn = MKCNN()
# Define gradient descent optimizer and loss function
optimizer = torch.optim.Adam(mkcnn.parameters(), weight_decay=l2_reg, lr=learning_rate)
loss_func = nn.MSELoss()
# Load data
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
import os
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from src import helper, keylog
from src.agents.train_valid_data import get_mario_train_valid_loader
from torch.autograd import Variable
and context (classes, functions, sometimes code) from other files:
# Path: src/helper.py
# def validate_function_key(slot_key):
# def get_output_folder():
# def get_models_folder():
# def get_dataset_folder():
# def get_home_folder():
# def pickle_object(data, name, directory=get_output_folder()):
# def generate_img_key(image):
# def get_tensor(image):
# def get_output_vector(presses):
# def get_key_state_from_vector(vector):
#
# Path: src/keylog.py
# class Keyboard(enum.Enum):
# class KeyLog:
# def __init__(self, logging_delay=0.3):
# def start(self):
# def on_press(self, key):
# def on_release(self, key):
# def record(self):
# def save_to_file(self, file_name="log.json"):
# def _get_key_value(key):
#
# Path: src/agents/train_valid_data.py
# def get_mario_train_valid_loader(batch_size,
# augment,
# random_seed,
# valid_size=0.2,
# shuffle=True,
# history=1,
# num_workers=1,
# pin_memory=False):
# """
# Utility function for loading and returning train and valid
# multi-process iterators over the MarioKart dataset. A sample
# 9x9 grid of the images can be optionally displayed.
# If using CUDA, num_workers should be set to 1 and pin_memory to True.
# Params
# ------
# - data_dir: path directory to the dataset.
# - batch_size: how many samples per batch to load.
# - augment: whether to apply the data augmentation scheme
# mentioned in the paper. Only applied on the train split.
# - random_seed: fix seed for reproducibility.
# - valid_size: percentage split of the training set used for
# the validation set. Should be a float in the range [0, 1].
# - shuffle: whether to shuffle the train/validation indices.
# - show_sample: plot 9x9 sample grid of the dataset.
# - num_workers: number of subprocesses to use when loading the dataset.
# - pin_memory: whether to copy tensors into CUDA pinned memory. Set it to
# True if using GPU.
# Returns
# -------
# - train_loader: training set iterator.
# - valid_loader: validation set iterator.
# """
# error_msg = "[!] valid_size should be in the range [0, 1]."
# assert ((valid_size >= 0) and (valid_size <= 1)), error_msg
#
# normalize = transforms.Normalize(mean=[0.5, 0.5, 0.5],
# std=[0.5, 0.5, 0.5])
#
# # define transforms
# valid_transform = transforms.Compose([
# transforms.ToTensor(),
# normalize
# ])
# if augment:
# train_transform = transforms.Compose([
# transforms.RandomCrop(32, padding=4),
# transforms.ToTensor(),
# normalize
# ])
# else:
# train_transform = transforms.Compose([
# transforms.ToTensor(),
# normalize
# ])
#
# # load the dataset
# train_dataset = MarioKartDataset(transform=train_transform, history=history)
# valid_dataset = MarioKartDataset(transform=valid_transform, history=history)
#
# num_train = len(train_dataset)
# indices = list(range(num_train))
# split = int(np.floor(valid_size * num_train))
#
# if shuffle:
# np.random.seed(random_seed)
# np.random.shuffle(indices)
#
# train_idx, valid_idx = indices[split:], indices[:split]
#
# train_sampler = SubsetRandomSampler(train_idx)
# valid_sampler = SubsetRandomSampler(valid_idx)
#
# train_loader = torch.utils.data.DataLoader(train_dataset,
# batch_size=batch_size, sampler=train_sampler,
# num_workers=num_workers, pin_memory=pin_memory)
#
# valid_loader = torch.utils.data.DataLoader(valid_dataset,
# batch_size=batch_size, sampler=valid_sampler,
# num_workers=num_workers, pin_memory=pin_memory)
# return train_loader, valid_loader
. Output only the next line. | train_loader, valid_loader = get_mario_train_valid_loader(batch_size, False, 123, history=num_input_frames) |
Using the snippet: <|code_start|> for step, (x, y) in enumerate(train_loader):
# Wrap label 'y' in variable
y_label = y.view(-1, output_vec)
if torch.cuda.is_available():
y_label = y_label.cuda()
nn_label = Variable(y_label)
# Forward pass
forward_pass = mkcrnn(x)
loss = loss_func(forward_pass, nn_label) # compute loss
optimizer.zero_grad() # zero gradients from previous step
loss.backward() # compute gradients
optimizer.step() # apply backpropagation
# Log training data
if step % 50 == 0:
print('Epoch: ', epoch, 'Step: ', step, '| training loss: %.4f' % loss.data[0])
valid_loss = 0
for (valid_x, valid_y) in valid_loader:
valid_y_label = valid_y.view(-1, output_vec)
if torch.cuda.is_available():
valid_y_label = valid_y_label.cuda()
valid_nn_label = Variable(valid_y_label)
valid_forward_pass = mkcrnn(valid_x)
valid_loss_eval = loss_func(valid_forward_pass, valid_nn_label) # compute validation loss
valid_loss += valid_loss_eval.data[0]
print('Epoch: ', epoch, 'Step: ', step, '| validation loss: %.4f' % valid_loss)
validation_losses.append(valid_loss)
# Save model
<|code_end|>
, determine the next line of code. You have imports:
import logging
import os
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from src import helper, keylog
from src.agents.train_valid_data import get_mario_train_valid_loader
from torch.autograd import Variable
and context (class names, function names, or code) available:
# Path: src/helper.py
# def validate_function_key(slot_key):
# def get_output_folder():
# def get_models_folder():
# def get_dataset_folder():
# def get_home_folder():
# def pickle_object(data, name, directory=get_output_folder()):
# def generate_img_key(image):
# def get_tensor(image):
# def get_output_vector(presses):
# def get_key_state_from_vector(vector):
#
# Path: src/keylog.py
# class Keyboard(enum.Enum):
# class KeyLog:
# def __init__(self, logging_delay=0.3):
# def start(self):
# def on_press(self, key):
# def on_release(self, key):
# def record(self):
# def save_to_file(self, file_name="log.json"):
# def _get_key_value(key):
#
# Path: src/agents/train_valid_data.py
# def get_mario_train_valid_loader(batch_size,
# augment,
# random_seed,
# valid_size=0.2,
# shuffle=True,
# history=1,
# num_workers=1,
# pin_memory=False):
# """
# Utility function for loading and returning train and valid
# multi-process iterators over the MarioKart dataset. A sample
# 9x9 grid of the images can be optionally displayed.
# If using CUDA, num_workers should be set to 1 and pin_memory to True.
# Params
# ------
# - data_dir: path directory to the dataset.
# - batch_size: how many samples per batch to load.
# - augment: whether to apply the data augmentation scheme
# mentioned in the paper. Only applied on the train split.
# - random_seed: fix seed for reproducibility.
# - valid_size: percentage split of the training set used for
# the validation set. Should be a float in the range [0, 1].
# - shuffle: whether to shuffle the train/validation indices.
# - show_sample: plot 9x9 sample grid of the dataset.
# - num_workers: number of subprocesses to use when loading the dataset.
# - pin_memory: whether to copy tensors into CUDA pinned memory. Set it to
# True if using GPU.
# Returns
# -------
# - train_loader: training set iterator.
# - valid_loader: validation set iterator.
# """
# error_msg = "[!] valid_size should be in the range [0, 1]."
# assert ((valid_size >= 0) and (valid_size <= 1)), error_msg
#
# normalize = transforms.Normalize(mean=[0.5, 0.5, 0.5],
# std=[0.5, 0.5, 0.5])
#
# # define transforms
# valid_transform = transforms.Compose([
# transforms.ToTensor(),
# normalize
# ])
# if augment:
# train_transform = transforms.Compose([
# transforms.RandomCrop(32, padding=4),
# transforms.ToTensor(),
# normalize
# ])
# else:
# train_transform = transforms.Compose([
# transforms.ToTensor(),
# normalize
# ])
#
# # load the dataset
# train_dataset = MarioKartDataset(transform=train_transform, history=history)
# valid_dataset = MarioKartDataset(transform=valid_transform, history=history)
#
# num_train = len(train_dataset)
# indices = list(range(num_train))
# split = int(np.floor(valid_size * num_train))
#
# if shuffle:
# np.random.seed(random_seed)
# np.random.shuffle(indices)
#
# train_idx, valid_idx = indices[split:], indices[:split]
#
# train_sampler = SubsetRandomSampler(train_idx)
# valid_sampler = SubsetRandomSampler(valid_idx)
#
# train_loader = torch.utils.data.DataLoader(train_dataset,
# batch_size=batch_size, sampler=train_sampler,
# num_workers=num_workers, pin_memory=pin_memory)
#
# valid_loader = torch.utils.data.DataLoader(valid_dataset,
# batch_size=batch_size, sampler=valid_sampler,
# num_workers=num_workers, pin_memory=pin_memory)
# return train_loader, valid_loader
. Output only the next line. | torch.save(mkcrnn, os.path.join(helper.get_models_folder(), "mkcrnn_{}_gru.pkl".format(history))) |
Here is a snippet: <|code_start|>"""
This module implements a Convolutional Recurrent Neural Network (CRNN) Mario Kart AI Agent using
Gated Recurrent Units (GRUs) and PyTorch.
"""
logger = logging.getLogger(__name__)
# Hyper Parameters
input_size = 15
hidden_size_1 = 64
hidden_size_2 = 64
hidden_size_3 = 64
<|code_end|>
. Write the next line using the current file imports:
import logging
import os
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from src import helper, keylog
from src.agents.train_valid_data import get_mario_train_valid_loader
from torch.autograd import Variable
and context from other files:
# Path: src/helper.py
# def validate_function_key(slot_key):
# def get_output_folder():
# def get_models_folder():
# def get_dataset_folder():
# def get_home_folder():
# def pickle_object(data, name, directory=get_output_folder()):
# def generate_img_key(image):
# def get_tensor(image):
# def get_output_vector(presses):
# def get_key_state_from_vector(vector):
#
# Path: src/keylog.py
# class Keyboard(enum.Enum):
# class KeyLog:
# def __init__(self, logging_delay=0.3):
# def start(self):
# def on_press(self, key):
# def on_release(self, key):
# def record(self):
# def save_to_file(self, file_name="log.json"):
# def _get_key_value(key):
#
# Path: src/agents/train_valid_data.py
# def get_mario_train_valid_loader(batch_size,
# augment,
# random_seed,
# valid_size=0.2,
# shuffle=True,
# history=1,
# num_workers=1,
# pin_memory=False):
# """
# Utility function for loading and returning train and valid
# multi-process iterators over the MarioKart dataset. A sample
# 9x9 grid of the images can be optionally displayed.
# If using CUDA, num_workers should be set to 1 and pin_memory to True.
# Params
# ------
# - data_dir: path directory to the dataset.
# - batch_size: how many samples per batch to load.
# - augment: whether to apply the data augmentation scheme
# mentioned in the paper. Only applied on the train split.
# - random_seed: fix seed for reproducibility.
# - valid_size: percentage split of the training set used for
# the validation set. Should be a float in the range [0, 1].
# - shuffle: whether to shuffle the train/validation indices.
# - show_sample: plot 9x9 sample grid of the dataset.
# - num_workers: number of subprocesses to use when loading the dataset.
# - pin_memory: whether to copy tensors into CUDA pinned memory. Set it to
# True if using GPU.
# Returns
# -------
# - train_loader: training set iterator.
# - valid_loader: validation set iterator.
# """
# error_msg = "[!] valid_size should be in the range [0, 1]."
# assert ((valid_size >= 0) and (valid_size <= 1)), error_msg
#
# normalize = transforms.Normalize(mean=[0.5, 0.5, 0.5],
# std=[0.5, 0.5, 0.5])
#
# # define transforms
# valid_transform = transforms.Compose([
# transforms.ToTensor(),
# normalize
# ])
# if augment:
# train_transform = transforms.Compose([
# transforms.RandomCrop(32, padding=4),
# transforms.ToTensor(),
# normalize
# ])
# else:
# train_transform = transforms.Compose([
# transforms.ToTensor(),
# normalize
# ])
#
# # load the dataset
# train_dataset = MarioKartDataset(transform=train_transform, history=history)
# valid_dataset = MarioKartDataset(transform=valid_transform, history=history)
#
# num_train = len(train_dataset)
# indices = list(range(num_train))
# split = int(np.floor(valid_size * num_train))
#
# if shuffle:
# np.random.seed(random_seed)
# np.random.shuffle(indices)
#
# train_idx, valid_idx = indices[split:], indices[:split]
#
# train_sampler = SubsetRandomSampler(train_idx)
# valid_sampler = SubsetRandomSampler(valid_idx)
#
# train_loader = torch.utils.data.DataLoader(train_dataset,
# batch_size=batch_size, sampler=train_sampler,
# num_workers=num_workers, pin_memory=pin_memory)
#
# valid_loader = torch.utils.data.DataLoader(valid_dataset,
# batch_size=batch_size, sampler=valid_sampler,
# num_workers=num_workers, pin_memory=pin_memory)
# return train_loader, valid_loader
, which may include functions, classes, or code. Output only the next line. | output_vec = len(keylog.Keyboard) |
Continue the code snippet: <|code_start|> num_layers=history, dropout=0.5)
if torch.cuda.is_available():
print("cuda is available.")
self.cuda()
def forward(self, x):
""" Forward pass of the neural network. Accepts a tensor of size input_size*input_size. """
x = x.view(-1, self.conv1_in, self.input_size, self.input_size)
x = Variable(x).float()
if torch.cuda.is_available():
x = x.cuda()
out = self.conv1(x)
out = self.conv2(out)
out = out.view(-1,history,5*5)
out, _ = self.gru(out)
out = out.view(-1, history * self.hidden_size_1)
out = self.encoder(out)
return out
if __name__ == '__main__':
""" Train neural network Mario Kart AI agent. """
mkcrnn = MKCRNN_gru()
# Define gradient descent optimizer and loss function
optimizer = torch.optim.Adam(mkcrnn.parameters(), weight_decay=l2_reg, lr=learning_rate)
loss_func = nn.MSELoss()
# Load data
<|code_end|>
. Use current file imports:
import logging
import os
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from src import helper, keylog
from src.agents.train_valid_data import get_mario_train_valid_loader
from torch.autograd import Variable
and context (classes, functions, or code) from other files:
# Path: src/helper.py
# def validate_function_key(slot_key):
# def get_output_folder():
# def get_models_folder():
# def get_dataset_folder():
# def get_home_folder():
# def pickle_object(data, name, directory=get_output_folder()):
# def generate_img_key(image):
# def get_tensor(image):
# def get_output_vector(presses):
# def get_key_state_from_vector(vector):
#
# Path: src/keylog.py
# class Keyboard(enum.Enum):
# class KeyLog:
# def __init__(self, logging_delay=0.3):
# def start(self):
# def on_press(self, key):
# def on_release(self, key):
# def record(self):
# def save_to_file(self, file_name="log.json"):
# def _get_key_value(key):
#
# Path: src/agents/train_valid_data.py
# def get_mario_train_valid_loader(batch_size,
# augment,
# random_seed,
# valid_size=0.2,
# shuffle=True,
# history=1,
# num_workers=1,
# pin_memory=False):
# """
# Utility function for loading and returning train and valid
# multi-process iterators over the MarioKart dataset. A sample
# 9x9 grid of the images can be optionally displayed.
# If using CUDA, num_workers should be set to 1 and pin_memory to True.
# Params
# ------
# - data_dir: path directory to the dataset.
# - batch_size: how many samples per batch to load.
# - augment: whether to apply the data augmentation scheme
# mentioned in the paper. Only applied on the train split.
# - random_seed: fix seed for reproducibility.
# - valid_size: percentage split of the training set used for
# the validation set. Should be a float in the range [0, 1].
# - shuffle: whether to shuffle the train/validation indices.
# - show_sample: plot 9x9 sample grid of the dataset.
# - num_workers: number of subprocesses to use when loading the dataset.
# - pin_memory: whether to copy tensors into CUDA pinned memory. Set it to
# True if using GPU.
# Returns
# -------
# - train_loader: training set iterator.
# - valid_loader: validation set iterator.
# """
# error_msg = "[!] valid_size should be in the range [0, 1]."
# assert ((valid_size >= 0) and (valid_size <= 1)), error_msg
#
# normalize = transforms.Normalize(mean=[0.5, 0.5, 0.5],
# std=[0.5, 0.5, 0.5])
#
# # define transforms
# valid_transform = transforms.Compose([
# transforms.ToTensor(),
# normalize
# ])
# if augment:
# train_transform = transforms.Compose([
# transforms.RandomCrop(32, padding=4),
# transforms.ToTensor(),
# normalize
# ])
# else:
# train_transform = transforms.Compose([
# transforms.ToTensor(),
# normalize
# ])
#
# # load the dataset
# train_dataset = MarioKartDataset(transform=train_transform, history=history)
# valid_dataset = MarioKartDataset(transform=valid_transform, history=history)
#
# num_train = len(train_dataset)
# indices = list(range(num_train))
# split = int(np.floor(valid_size * num_train))
#
# if shuffle:
# np.random.seed(random_seed)
# np.random.shuffle(indices)
#
# train_idx, valid_idx = indices[split:], indices[:split]
#
# train_sampler = SubsetRandomSampler(train_idx)
# valid_sampler = SubsetRandomSampler(valid_idx)
#
# train_loader = torch.utils.data.DataLoader(train_dataset,
# batch_size=batch_size, sampler=train_sampler,
# num_workers=num_workers, pin_memory=pin_memory)
#
# valid_loader = torch.utils.data.DataLoader(valid_dataset,
# batch_size=batch_size, sampler=valid_sampler,
# num_workers=num_workers, pin_memory=pin_memory)
# return train_loader, valid_loader
. Output only the next line. | train_loader, valid_loader = get_mario_train_valid_loader(batch_size, False, 123, history=history) |
Based on the snippet: <|code_start|> for step, (x, y) in enumerate(train_loader):
# Wrap label 'y' in variable
y_label = y.view(-1, output_vec)
if torch.cuda.is_available():
y_label = y_label.cuda()
nn_label = Variable(y_label)
# Forward pass
forward_pass = mkrnn(x)
loss = loss_func(forward_pass, nn_label) # compute loss
optimizer.zero_grad() # zero gradients from previous step
loss.backward() # compute gradients
optimizer.step() # apply backpropagation
# Log training data
if step % 50 == 0:
print('Epoch: ', epoch, 'Step: ', step, '| training loss: %.4f' % loss.data[0])
valid_loss = 0
for (valid_x, valid_y) in valid_loader:
valid_y_label = valid_y.view(-1, output_vec)
if torch.cuda.is_available():
valid_y_label = valid_y_label.cuda()
valid_nn_label = Variable(valid_y_label)
valid_forward_pass = mkrnn(valid_x)
valid_loss_eval = loss_func(valid_forward_pass, valid_nn_label) # compute validation loss
valid_loss += valid_loss_eval.data[0]
print('Epoch: ', epoch, 'Step: ', step, '| validation loss: %.4f' % valid_loss)
validation_losses.append(valid_loss)
# Save model
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
import os
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from src import helper, keylog
from src.agents.train_valid_data import get_mario_train_valid_loader
from torch.autograd import Variable
and context (classes, functions, sometimes code) from other files:
# Path: src/helper.py
# def validate_function_key(slot_key):
# def get_output_folder():
# def get_models_folder():
# def get_dataset_folder():
# def get_home_folder():
# def pickle_object(data, name, directory=get_output_folder()):
# def generate_img_key(image):
# def get_tensor(image):
# def get_output_vector(presses):
# def get_key_state_from_vector(vector):
#
# Path: src/keylog.py
# class Keyboard(enum.Enum):
# class KeyLog:
# def __init__(self, logging_delay=0.3):
# def start(self):
# def on_press(self, key):
# def on_release(self, key):
# def record(self):
# def save_to_file(self, file_name="log.json"):
# def _get_key_value(key):
#
# Path: src/agents/train_valid_data.py
# def get_mario_train_valid_loader(batch_size,
# augment,
# random_seed,
# valid_size=0.2,
# shuffle=True,
# history=1,
# num_workers=1,
# pin_memory=False):
# """
# Utility function for loading and returning train and valid
# multi-process iterators over the MarioKart dataset. A sample
# 9x9 grid of the images can be optionally displayed.
# If using CUDA, num_workers should be set to 1 and pin_memory to True.
# Params
# ------
# - data_dir: path directory to the dataset.
# - batch_size: how many samples per batch to load.
# - augment: whether to apply the data augmentation scheme
# mentioned in the paper. Only applied on the train split.
# - random_seed: fix seed for reproducibility.
# - valid_size: percentage split of the training set used for
# the validation set. Should be a float in the range [0, 1].
# - shuffle: whether to shuffle the train/validation indices.
# - show_sample: plot 9x9 sample grid of the dataset.
# - num_workers: number of subprocesses to use when loading the dataset.
# - pin_memory: whether to copy tensors into CUDA pinned memory. Set it to
# True if using GPU.
# Returns
# -------
# - train_loader: training set iterator.
# - valid_loader: validation set iterator.
# """
# error_msg = "[!] valid_size should be in the range [0, 1]."
# assert ((valid_size >= 0) and (valid_size <= 1)), error_msg
#
# normalize = transforms.Normalize(mean=[0.5, 0.5, 0.5],
# std=[0.5, 0.5, 0.5])
#
# # define transforms
# valid_transform = transforms.Compose([
# transforms.ToTensor(),
# normalize
# ])
# if augment:
# train_transform = transforms.Compose([
# transforms.RandomCrop(32, padding=4),
# transforms.ToTensor(),
# normalize
# ])
# else:
# train_transform = transforms.Compose([
# transforms.ToTensor(),
# normalize
# ])
#
# # load the dataset
# train_dataset = MarioKartDataset(transform=train_transform, history=history)
# valid_dataset = MarioKartDataset(transform=valid_transform, history=history)
#
# num_train = len(train_dataset)
# indices = list(range(num_train))
# split = int(np.floor(valid_size * num_train))
#
# if shuffle:
# np.random.seed(random_seed)
# np.random.shuffle(indices)
#
# train_idx, valid_idx = indices[split:], indices[:split]
#
# train_sampler = SubsetRandomSampler(train_idx)
# valid_sampler = SubsetRandomSampler(valid_idx)
#
# train_loader = torch.utils.data.DataLoader(train_dataset,
# batch_size=batch_size, sampler=train_sampler,
# num_workers=num_workers, pin_memory=pin_memory)
#
# valid_loader = torch.utils.data.DataLoader(valid_dataset,
# batch_size=batch_size, sampler=valid_sampler,
# num_workers=num_workers, pin_memory=pin_memory)
# return train_loader, valid_loader
. Output only the next line. | torch.save(mkrnn, os.path.join(helper.get_models_folder(), "mkrnn_{}_lstm.pkl".format(history))) |
Given the following code snippet before the placeholder: <|code_start|>"""
This module implements a Recurrent Neural Network (RNN) Mario Kart AI Agent using
Long Short-Term Memory (LSTM) and PyTorch.
"""
logger = logging.getLogger(__name__)
# Hyper Parameters
input_size = 15
hidden_size_1 = 64
hidden_size_2 = 64
hidden_size_3 = 64
<|code_end|>
, predict the next line using imports from the current file:
import logging
import os
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from src import helper, keylog
from src.agents.train_valid_data import get_mario_train_valid_loader
from torch.autograd import Variable
and context including class names, function names, and sometimes code from other files:
# Path: src/helper.py
# def validate_function_key(slot_key):
# def get_output_folder():
# def get_models_folder():
# def get_dataset_folder():
# def get_home_folder():
# def pickle_object(data, name, directory=get_output_folder()):
# def generate_img_key(image):
# def get_tensor(image):
# def get_output_vector(presses):
# def get_key_state_from_vector(vector):
#
# Path: src/keylog.py
# class Keyboard(enum.Enum):
# class KeyLog:
# def __init__(self, logging_delay=0.3):
# def start(self):
# def on_press(self, key):
# def on_release(self, key):
# def record(self):
# def save_to_file(self, file_name="log.json"):
# def _get_key_value(key):
#
# Path: src/agents/train_valid_data.py
# def get_mario_train_valid_loader(batch_size,
# augment,
# random_seed,
# valid_size=0.2,
# shuffle=True,
# history=1,
# num_workers=1,
# pin_memory=False):
# """
# Utility function for loading and returning train and valid
# multi-process iterators over the MarioKart dataset. A sample
# 9x9 grid of the images can be optionally displayed.
# If using CUDA, num_workers should be set to 1 and pin_memory to True.
# Params
# ------
# - data_dir: path directory to the dataset.
# - batch_size: how many samples per batch to load.
# - augment: whether to apply the data augmentation scheme
# mentioned in the paper. Only applied on the train split.
# - random_seed: fix seed for reproducibility.
# - valid_size: percentage split of the training set used for
# the validation set. Should be a float in the range [0, 1].
# - shuffle: whether to shuffle the train/validation indices.
# - show_sample: plot 9x9 sample grid of the dataset.
# - num_workers: number of subprocesses to use when loading the dataset.
# - pin_memory: whether to copy tensors into CUDA pinned memory. Set it to
# True if using GPU.
# Returns
# -------
# - train_loader: training set iterator.
# - valid_loader: validation set iterator.
# """
# error_msg = "[!] valid_size should be in the range [0, 1]."
# assert ((valid_size >= 0) and (valid_size <= 1)), error_msg
#
# normalize = transforms.Normalize(mean=[0.5, 0.5, 0.5],
# std=[0.5, 0.5, 0.5])
#
# # define transforms
# valid_transform = transforms.Compose([
# transforms.ToTensor(),
# normalize
# ])
# if augment:
# train_transform = transforms.Compose([
# transforms.RandomCrop(32, padding=4),
# transforms.ToTensor(),
# normalize
# ])
# else:
# train_transform = transforms.Compose([
# transforms.ToTensor(),
# normalize
# ])
#
# # load the dataset
# train_dataset = MarioKartDataset(transform=train_transform, history=history)
# valid_dataset = MarioKartDataset(transform=valid_transform, history=history)
#
# num_train = len(train_dataset)
# indices = list(range(num_train))
# split = int(np.floor(valid_size * num_train))
#
# if shuffle:
# np.random.seed(random_seed)
# np.random.shuffle(indices)
#
# train_idx, valid_idx = indices[split:], indices[:split]
#
# train_sampler = SubsetRandomSampler(train_idx)
# valid_sampler = SubsetRandomSampler(valid_idx)
#
# train_loader = torch.utils.data.DataLoader(train_dataset,
# batch_size=batch_size, sampler=train_sampler,
# num_workers=num_workers, pin_memory=pin_memory)
#
# valid_loader = torch.utils.data.DataLoader(valid_dataset,
# batch_size=batch_size, sampler=valid_sampler,
# num_workers=num_workers, pin_memory=pin_memory)
# return train_loader, valid_loader
. Output only the next line. | output_vec = len(keylog.Keyboard) |
Given the code snippet: <|code_start|> nn.Dropout(0.5),
nn.LeakyReLU(),
nn.Linear(self.hidden_size_3, self.output_vec)
)
if torch.cuda.is_available():
print("cuda is available.")
self.cuda()
def forward(self, x):
""" Forward pass of the neural network. Accepts a tensor of size input_size*input_size. """
x_input = x.view(-1, self.history, self.input_size * self.input_size)
if torch.cuda.is_available():
x_input = x_input.cuda()
x = Variable(x_input).float()
out, _ = self.lstm(x)
out = out.view(-1, self.history * self.hidden_size_1)
encoded = self.encoder(out)
return encoded
if __name__ == '__main__':
""" Train neural network Mario Kart AI agent. """
mkrnn = MKRNN_lstm()
# Define gradient descent optimizer and loss function
optimizer = torch.optim.Adam(mkrnn.parameters(), weight_decay=l2_reg, lr=learning_rate)
loss_func = nn.MSELoss()
# Load data
<|code_end|>
, generate the next line using the imports in this file:
import logging
import os
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from src import helper, keylog
from src.agents.train_valid_data import get_mario_train_valid_loader
from torch.autograd import Variable
and context (functions, classes, or occasionally code) from other files:
# Path: src/helper.py
# def validate_function_key(slot_key):
# def get_output_folder():
# def get_models_folder():
# def get_dataset_folder():
# def get_home_folder():
# def pickle_object(data, name, directory=get_output_folder()):
# def generate_img_key(image):
# def get_tensor(image):
# def get_output_vector(presses):
# def get_key_state_from_vector(vector):
#
# Path: src/keylog.py
# class Keyboard(enum.Enum):
# class KeyLog:
# def __init__(self, logging_delay=0.3):
# def start(self):
# def on_press(self, key):
# def on_release(self, key):
# def record(self):
# def save_to_file(self, file_name="log.json"):
# def _get_key_value(key):
#
# Path: src/agents/train_valid_data.py
# def get_mario_train_valid_loader(batch_size,
# augment,
# random_seed,
# valid_size=0.2,
# shuffle=True,
# history=1,
# num_workers=1,
# pin_memory=False):
# """
# Utility function for loading and returning train and valid
# multi-process iterators over the MarioKart dataset. A sample
# 9x9 grid of the images can be optionally displayed.
# If using CUDA, num_workers should be set to 1 and pin_memory to True.
# Params
# ------
# - data_dir: path directory to the dataset.
# - batch_size: how many samples per batch to load.
# - augment: whether to apply the data augmentation scheme
# mentioned in the paper. Only applied on the train split.
# - random_seed: fix seed for reproducibility.
# - valid_size: percentage split of the training set used for
# the validation set. Should be a float in the range [0, 1].
# - shuffle: whether to shuffle the train/validation indices.
# - show_sample: plot 9x9 sample grid of the dataset.
# - num_workers: number of subprocesses to use when loading the dataset.
# - pin_memory: whether to copy tensors into CUDA pinned memory. Set it to
# True if using GPU.
# Returns
# -------
# - train_loader: training set iterator.
# - valid_loader: validation set iterator.
# """
# error_msg = "[!] valid_size should be in the range [0, 1]."
# assert ((valid_size >= 0) and (valid_size <= 1)), error_msg
#
# normalize = transforms.Normalize(mean=[0.5, 0.5, 0.5],
# std=[0.5, 0.5, 0.5])
#
# # define transforms
# valid_transform = transforms.Compose([
# transforms.ToTensor(),
# normalize
# ])
# if augment:
# train_transform = transforms.Compose([
# transforms.RandomCrop(32, padding=4),
# transforms.ToTensor(),
# normalize
# ])
# else:
# train_transform = transforms.Compose([
# transforms.ToTensor(),
# normalize
# ])
#
# # load the dataset
# train_dataset = MarioKartDataset(transform=train_transform, history=history)
# valid_dataset = MarioKartDataset(transform=valid_transform, history=history)
#
# num_train = len(train_dataset)
# indices = list(range(num_train))
# split = int(np.floor(valid_size * num_train))
#
# if shuffle:
# np.random.seed(random_seed)
# np.random.shuffle(indices)
#
# train_idx, valid_idx = indices[split:], indices[:split]
#
# train_sampler = SubsetRandomSampler(train_idx)
# valid_sampler = SubsetRandomSampler(valid_idx)
#
# train_loader = torch.utils.data.DataLoader(train_dataset,
# batch_size=batch_size, sampler=train_sampler,
# num_workers=num_workers, pin_memory=pin_memory)
#
# valid_loader = torch.utils.data.DataLoader(valid_dataset,
# batch_size=batch_size, sampler=valid_sampler,
# num_workers=num_workers, pin_memory=pin_memory)
# return train_loader, valid_loader
. Output only the next line. | train_loader, valid_loader = get_mario_train_valid_loader(batch_size, False, 123, history=history) |
Next line prediction: <|code_start|>logger = logging.getLogger(__name__)
class MarioKartNN:
""" Class implementing a neural network Mario Kart AI agent """
game_name = "NABE01"
def __init__(self, pickled_model_path, history_length=1, delay=0.2):
""" Create a MarioKart Agent instance.
Args:
pickled_model_path: Path to the neural network model file.
"""
self.model = torch.load(pickled_model_path)
self.frame_delay = delay
self.screenshot_dir = os.path.join(helper.get_home_folder(), '.dolphin-emu', 'ScreenShots', self.game_name)
self.key_map = key2pad.KeyPadMap()
self.history_length = history_length
self.previous_tensors = collections.deque([], history_length)
def process_frame(self):
""" Process a single frame of the current Dolphin game.
Note:
Process means read the state of the game and decide what action to take in this context.
Dolphin will not take screenshots if the game is paused!
"""
# Advance the Dolphin frame
# dp_frames.advance('P')
# Take screenshot of current Dolphin frame
<|code_end|>
. Use current file imports:
(import collections
import logging
import os
import time
import torch
from src import dp_screenshot, helper, mk_downsampler, key2pad)
and context including class names, function names, or small code snippets from other files:
# Path: src/dp_screenshot.py
# def take_screenshot():
#
# Path: src/helper.py
# def validate_function_key(slot_key):
# def get_output_folder():
# def get_models_folder():
# def get_dataset_folder():
# def get_home_folder():
# def pickle_object(data, name, directory=get_output_folder()):
# def generate_img_key(image):
# def get_tensor(image):
# def get_output_vector(presses):
# def get_key_state_from_vector(vector):
#
# Path: src/mk_downsampler.py
# class Downsampler:
# def __init__(self, game_name, blur_size=25, intermediate_dim=300, final_dim=10):
# def downsample_dir(self, save_imgs=False, clean_data=False):
# def downsample(self, file_path, output_name=None, save_img=False, clean_data=False):
# def save_image(self, img, output_name):
#
# Path: src/key2pad.py
# class KeyPadMap:
# def __init__(self):
# def update(self, keys):
# def convert_key(self, key, is_press):
. Output only the next line. | dp_screenshot.take_screenshot() |
Here is a snippet: <|code_start|>"""
This module implements a Mario Kart AI agent using a Neural Network.
"""
logger = logging.getLogger(__name__)
class MarioKartNN:
""" Class implementing a neural network Mario Kart AI agent """
game_name = "NABE01"
def __init__(self, pickled_model_path, history_length=1, delay=0.2):
""" Create a MarioKart Agent instance.
Args:
pickled_model_path: Path to the neural network model file.
"""
self.model = torch.load(pickled_model_path)
self.frame_delay = delay
<|code_end|>
. Write the next line using the current file imports:
import collections
import logging
import os
import time
import torch
from src import dp_screenshot, helper, mk_downsampler, key2pad
and context from other files:
# Path: src/dp_screenshot.py
# def take_screenshot():
#
# Path: src/helper.py
# def validate_function_key(slot_key):
# def get_output_folder():
# def get_models_folder():
# def get_dataset_folder():
# def get_home_folder():
# def pickle_object(data, name, directory=get_output_folder()):
# def generate_img_key(image):
# def get_tensor(image):
# def get_output_vector(presses):
# def get_key_state_from_vector(vector):
#
# Path: src/mk_downsampler.py
# class Downsampler:
# def __init__(self, game_name, blur_size=25, intermediate_dim=300, final_dim=10):
# def downsample_dir(self, save_imgs=False, clean_data=False):
# def downsample(self, file_path, output_name=None, save_img=False, clean_data=False):
# def save_image(self, img, output_name):
#
# Path: src/key2pad.py
# class KeyPadMap:
# def __init__(self):
# def update(self, keys):
# def convert_key(self, key, is_press):
, which may include functions, classes, or code. Output only the next line. | self.screenshot_dir = os.path.join(helper.get_home_folder(), '.dolphin-emu', 'ScreenShots', self.game_name) |
Here is a snippet: <|code_start|>
def __init__(self, pickled_model_path, history_length=1, delay=0.2):
""" Create a MarioKart Agent instance.
Args:
pickled_model_path: Path to the neural network model file.
"""
self.model = torch.load(pickled_model_path)
self.frame_delay = delay
self.screenshot_dir = os.path.join(helper.get_home_folder(), '.dolphin-emu', 'ScreenShots', self.game_name)
self.key_map = key2pad.KeyPadMap()
self.history_length = history_length
self.previous_tensors = collections.deque([], history_length)
def process_frame(self):
""" Process a single frame of the current Dolphin game.
Note:
Process means read the state of the game and decide what action to take in this context.
Dolphin will not take screenshots if the game is paused!
"""
# Advance the Dolphin frame
# dp_frames.advance('P')
# Take screenshot of current Dolphin frame
dp_screenshot.take_screenshot()
screenshot_file = os.path.join(self.screenshot_dir, 'NABE01-1.png')
# time.sleep(self.frame_delay)
try:
# Downsample the screenshot and calculate dictionary key
<|code_end|>
. Write the next line using the current file imports:
import collections
import logging
import os
import time
import torch
from src import dp_screenshot, helper, mk_downsampler, key2pad
and context from other files:
# Path: src/dp_screenshot.py
# def take_screenshot():
#
# Path: src/helper.py
# def validate_function_key(slot_key):
# def get_output_folder():
# def get_models_folder():
# def get_dataset_folder():
# def get_home_folder():
# def pickle_object(data, name, directory=get_output_folder()):
# def generate_img_key(image):
# def get_tensor(image):
# def get_output_vector(presses):
# def get_key_state_from_vector(vector):
#
# Path: src/mk_downsampler.py
# class Downsampler:
# def __init__(self, game_name, blur_size=25, intermediate_dim=300, final_dim=10):
# def downsample_dir(self, save_imgs=False, clean_data=False):
# def downsample(self, file_path, output_name=None, save_img=False, clean_data=False):
# def save_image(self, img, output_name):
#
# Path: src/key2pad.py
# class KeyPadMap:
# def __init__(self):
# def update(self, keys):
# def convert_key(self, key, is_press):
, which may include functions, classes, or code. Output only the next line. | ds_image = mk_downsampler.Downsampler(self.game_name, final_dim=15).downsample(screenshot_file) |
Continue the code snippet: <|code_start|>"""
This module implements a Mario Kart AI agent using a Neural Network.
"""
logger = logging.getLogger(__name__)
class MarioKartNN:
""" Class implementing a neural network Mario Kart AI agent """
game_name = "NABE01"
def __init__(self, pickled_model_path, history_length=1, delay=0.2):
""" Create a MarioKart Agent instance.
Args:
pickled_model_path: Path to the neural network model file.
"""
self.model = torch.load(pickled_model_path)
self.frame_delay = delay
self.screenshot_dir = os.path.join(helper.get_home_folder(), '.dolphin-emu', 'ScreenShots', self.game_name)
<|code_end|>
. Use current file imports:
import collections
import logging
import os
import time
import torch
from src import dp_screenshot, helper, mk_downsampler, key2pad
and context (classes, functions, or code) from other files:
# Path: src/dp_screenshot.py
# def take_screenshot():
#
# Path: src/helper.py
# def validate_function_key(slot_key):
# def get_output_folder():
# def get_models_folder():
# def get_dataset_folder():
# def get_home_folder():
# def pickle_object(data, name, directory=get_output_folder()):
# def generate_img_key(image):
# def get_tensor(image):
# def get_output_vector(presses):
# def get_key_state_from_vector(vector):
#
# Path: src/mk_downsampler.py
# class Downsampler:
# def __init__(self, game_name, blur_size=25, intermediate_dim=300, final_dim=10):
# def downsample_dir(self, save_imgs=False, clean_data=False):
# def downsample(self, file_path, output_name=None, save_img=False, clean_data=False):
# def save_image(self, img, output_name):
#
# Path: src/key2pad.py
# class KeyPadMap:
# def __init__(self):
# def update(self, keys):
# def convert_key(self, key, is_press):
. Output only the next line. | self.key_map = key2pad.KeyPadMap() |
Next line prediction: <|code_start|>""" This module provides tools for programmatic control of the Dolphin emulator's save state functionality. """
logger = logging.getLogger(__name__)
def save_dolphin_state(slot_key):
""" Save the current state of a running Dolphin emulator.
Args:
slot_key: Keyboard key corresponding to the Dolphin save state slot
to save the current state of the emulator to.
"""
try:
<|code_end|>
. Use current file imports:
(import logging
import pyautogui
from src import helper)
and context including class names, function names, or small code snippets from other files:
# Path: src/helper.py
# def validate_function_key(slot_key):
# def get_output_folder():
# def get_models_folder():
# def get_dataset_folder():
# def get_home_folder():
# def pickle_object(data, name, directory=get_output_folder()):
# def generate_img_key(image):
# def get_tensor(image):
# def get_output_vector(presses):
# def get_key_state_from_vector(vector):
. Output only the next line. | helper.validate_function_key(slot_key) |
Given the code snippet: <|code_start|> for step, (x, y) in enumerate(train_loader):
# Wrap label 'y' in variable
y_label = y.view(-1, output_vec)
if torch.cuda.is_available():
y_label = y_label.cuda()
nn_label = Variable(y_label)
# Forward pass
forward_pass = mknn(x)
loss = loss_func(forward_pass, nn_label) # compute loss
optimizer.zero_grad() # zero gradients from previous step
loss.backward() # compute gradients
optimizer.step() # apply backpropagation
# Log training data
if step % 50 == 0:
print('Epoch: ', epoch, 'Step: ', step, '| training loss: %.4f' % loss.data[0])
valid_loss = 0
for (valid_x, valid_y) in valid_loader:
valid_y_label = valid_y.view(-1, output_vec)
if torch.cuda.is_available():
valid_y_label = valid_y_label.cuda()
valid_nn_label = Variable(valid_y_label)
valid_forward_pass = mknn(valid_x)
valid_loss_eval = loss_func(valid_forward_pass, valid_nn_label) # compute validation loss
valid_loss += valid_loss_eval.data[0]
print('Epoch: ', epoch, 'Step: ', step, '| validation loss: %.4f' % valid_loss)
validation_losses.append(valid_loss)
# Save model
<|code_end|>
, generate the next line using the imports in this file:
import logging
import os
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from src import helper, keylog
from src.agents.train_valid_data import get_mario_train_valid_loader
from torch.autograd import Variable
and context (functions, classes, or occasionally code) from other files:
# Path: src/helper.py
# def validate_function_key(slot_key):
# def get_output_folder():
# def get_models_folder():
# def get_dataset_folder():
# def get_home_folder():
# def pickle_object(data, name, directory=get_output_folder()):
# def generate_img_key(image):
# def get_tensor(image):
# def get_output_vector(presses):
# def get_key_state_from_vector(vector):
#
# Path: src/keylog.py
# class Keyboard(enum.Enum):
# class KeyLog:
# def __init__(self, logging_delay=0.3):
# def start(self):
# def on_press(self, key):
# def on_release(self, key):
# def record(self):
# def save_to_file(self, file_name="log.json"):
# def _get_key_value(key):
#
# Path: src/agents/train_valid_data.py
# def get_mario_train_valid_loader(batch_size,
# augment,
# random_seed,
# valid_size=0.2,
# shuffle=True,
# history=1,
# num_workers=1,
# pin_memory=False):
# """
# Utility function for loading and returning train and valid
# multi-process iterators over the MarioKart dataset. A sample
# 9x9 grid of the images can be optionally displayed.
# If using CUDA, num_workers should be set to 1 and pin_memory to True.
# Params
# ------
# - data_dir: path directory to the dataset.
# - batch_size: how many samples per batch to load.
# - augment: whether to apply the data augmentation scheme
# mentioned in the paper. Only applied on the train split.
# - random_seed: fix seed for reproducibility.
# - valid_size: percentage split of the training set used for
# the validation set. Should be a float in the range [0, 1].
# - shuffle: whether to shuffle the train/validation indices.
# - show_sample: plot 9x9 sample grid of the dataset.
# - num_workers: number of subprocesses to use when loading the dataset.
# - pin_memory: whether to copy tensors into CUDA pinned memory. Set it to
# True if using GPU.
# Returns
# -------
# - train_loader: training set iterator.
# - valid_loader: validation set iterator.
# """
# error_msg = "[!] valid_size should be in the range [0, 1]."
# assert ((valid_size >= 0) and (valid_size <= 1)), error_msg
#
# normalize = transforms.Normalize(mean=[0.5, 0.5, 0.5],
# std=[0.5, 0.5, 0.5])
#
# # define transforms
# valid_transform = transforms.Compose([
# transforms.ToTensor(),
# normalize
# ])
# if augment:
# train_transform = transforms.Compose([
# transforms.RandomCrop(32, padding=4),
# transforms.ToTensor(),
# normalize
# ])
# else:
# train_transform = transforms.Compose([
# transforms.ToTensor(),
# normalize
# ])
#
# # load the dataset
# train_dataset = MarioKartDataset(transform=train_transform, history=history)
# valid_dataset = MarioKartDataset(transform=valid_transform, history=history)
#
# num_train = len(train_dataset)
# indices = list(range(num_train))
# split = int(np.floor(valid_size * num_train))
#
# if shuffle:
# np.random.seed(random_seed)
# np.random.shuffle(indices)
#
# train_idx, valid_idx = indices[split:], indices[:split]
#
# train_sampler = SubsetRandomSampler(train_idx)
# valid_sampler = SubsetRandomSampler(valid_idx)
#
# train_loader = torch.utils.data.DataLoader(train_dataset,
# batch_size=batch_size, sampler=train_sampler,
# num_workers=num_workers, pin_memory=pin_memory)
#
# valid_loader = torch.utils.data.DataLoader(valid_dataset,
# batch_size=batch_size, sampler=valid_sampler,
# num_workers=num_workers, pin_memory=pin_memory)
# return train_loader, valid_loader
. Output only the next line. | torch.save(mknn, os.path.join(helper.get_models_folder(), "mknn.pkl")) |
Continue the code snippet: <|code_start|>"""
This module implements a Neural Network (NN) Mario Kart AI Agent using PyTorch.
"""
logger = logging.getLogger(__name__)
# Hyper Parameters
input_size = 15
hidden_size_1 = 64
hidden_size_2 = 64
hidden_size_3 = 32
<|code_end|>
. Use current file imports:
import logging
import os
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from src import helper, keylog
from src.agents.train_valid_data import get_mario_train_valid_loader
from torch.autograd import Variable
and context (classes, functions, or code) from other files:
# Path: src/helper.py
# def validate_function_key(slot_key):
# def get_output_folder():
# def get_models_folder():
# def get_dataset_folder():
# def get_home_folder():
# def pickle_object(data, name, directory=get_output_folder()):
# def generate_img_key(image):
# def get_tensor(image):
# def get_output_vector(presses):
# def get_key_state_from_vector(vector):
#
# Path: src/keylog.py
# class Keyboard(enum.Enum):
# class KeyLog:
# def __init__(self, logging_delay=0.3):
# def start(self):
# def on_press(self, key):
# def on_release(self, key):
# def record(self):
# def save_to_file(self, file_name="log.json"):
# def _get_key_value(key):
#
# Path: src/agents/train_valid_data.py
# def get_mario_train_valid_loader(batch_size,
# augment,
# random_seed,
# valid_size=0.2,
# shuffle=True,
# history=1,
# num_workers=1,
# pin_memory=False):
# """
# Utility function for loading and returning train and valid
# multi-process iterators over the MarioKart dataset. A sample
# 9x9 grid of the images can be optionally displayed.
# If using CUDA, num_workers should be set to 1 and pin_memory to True.
# Params
# ------
# - data_dir: path directory to the dataset.
# - batch_size: how many samples per batch to load.
# - augment: whether to apply the data augmentation scheme
# mentioned in the paper. Only applied on the train split.
# - random_seed: fix seed for reproducibility.
# - valid_size: percentage split of the training set used for
# the validation set. Should be a float in the range [0, 1].
# - shuffle: whether to shuffle the train/validation indices.
# - show_sample: plot 9x9 sample grid of the dataset.
# - num_workers: number of subprocesses to use when loading the dataset.
# - pin_memory: whether to copy tensors into CUDA pinned memory. Set it to
# True if using GPU.
# Returns
# -------
# - train_loader: training set iterator.
# - valid_loader: validation set iterator.
# """
# error_msg = "[!] valid_size should be in the range [0, 1]."
# assert ((valid_size >= 0) and (valid_size <= 1)), error_msg
#
# normalize = transforms.Normalize(mean=[0.5, 0.5, 0.5],
# std=[0.5, 0.5, 0.5])
#
# # define transforms
# valid_transform = transforms.Compose([
# transforms.ToTensor(),
# normalize
# ])
# if augment:
# train_transform = transforms.Compose([
# transforms.RandomCrop(32, padding=4),
# transforms.ToTensor(),
# normalize
# ])
# else:
# train_transform = transforms.Compose([
# transforms.ToTensor(),
# normalize
# ])
#
# # load the dataset
# train_dataset = MarioKartDataset(transform=train_transform, history=history)
# valid_dataset = MarioKartDataset(transform=valid_transform, history=history)
#
# num_train = len(train_dataset)
# indices = list(range(num_train))
# split = int(np.floor(valid_size * num_train))
#
# if shuffle:
# np.random.seed(random_seed)
# np.random.shuffle(indices)
#
# train_idx, valid_idx = indices[split:], indices[:split]
#
# train_sampler = SubsetRandomSampler(train_idx)
# valid_sampler = SubsetRandomSampler(valid_idx)
#
# train_loader = torch.utils.data.DataLoader(train_dataset,
# batch_size=batch_size, sampler=train_sampler,
# num_workers=num_workers, pin_memory=pin_memory)
#
# valid_loader = torch.utils.data.DataLoader(valid_dataset,
# batch_size=batch_size, sampler=valid_sampler,
# num_workers=num_workers, pin_memory=pin_memory)
# return train_loader, valid_loader
. Output only the next line. | output_vec = len(keylog.Keyboard) |
Continue the code snippet: <|code_start|> nn.LeakyReLU(),
nn.Linear(self.hidden_size_2, self.hidden_size_3),
nn.Dropout(0.5),
nn.LeakyReLU(),
nn.Linear(self.hidden_size_3, self.output_vec)
)
if torch.cuda.is_available():
print("cuda is available.")
self.cuda()
def forward(self, x):
""" Forward pass of the neural network. Accepts a tensor of size input_size*input_size. """
x_input = x.view(-1, self.input_size * self.input_size)
if torch.cuda.is_available():
x_input = x_input.cuda()
x = Variable(x_input).float()
encoded = self.encoder(x)
return encoded
if __name__ == '__main__':
""" Train neural network Mario Kart AI agent. """
mknn = MKNN()
# Define gradient descent optimizer and loss function
optimizer = torch.optim.Adam(mknn.parameters(), weight_decay=l2_reg, lr=learning_rate)
loss_func = nn.MSELoss()
# Load data
<|code_end|>
. Use current file imports:
import logging
import os
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from src import helper, keylog
from src.agents.train_valid_data import get_mario_train_valid_loader
from torch.autograd import Variable
and context (classes, functions, or code) from other files:
# Path: src/helper.py
# def validate_function_key(slot_key):
# def get_output_folder():
# def get_models_folder():
# def get_dataset_folder():
# def get_home_folder():
# def pickle_object(data, name, directory=get_output_folder()):
# def generate_img_key(image):
# def get_tensor(image):
# def get_output_vector(presses):
# def get_key_state_from_vector(vector):
#
# Path: src/keylog.py
# class Keyboard(enum.Enum):
# class KeyLog:
# def __init__(self, logging_delay=0.3):
# def start(self):
# def on_press(self, key):
# def on_release(self, key):
# def record(self):
# def save_to_file(self, file_name="log.json"):
# def _get_key_value(key):
#
# Path: src/agents/train_valid_data.py
# def get_mario_train_valid_loader(batch_size,
# augment,
# random_seed,
# valid_size=0.2,
# shuffle=True,
# history=1,
# num_workers=1,
# pin_memory=False):
# """
# Utility function for loading and returning train and valid
# multi-process iterators over the MarioKart dataset. A sample
# 9x9 grid of the images can be optionally displayed.
# If using CUDA, num_workers should be set to 1 and pin_memory to True.
# Params
# ------
# - data_dir: path directory to the dataset.
# - batch_size: how many samples per batch to load.
# - augment: whether to apply the data augmentation scheme
# mentioned in the paper. Only applied on the train split.
# - random_seed: fix seed for reproducibility.
# - valid_size: percentage split of the training set used for
# the validation set. Should be a float in the range [0, 1].
# - shuffle: whether to shuffle the train/validation indices.
# - show_sample: plot 9x9 sample grid of the dataset.
# - num_workers: number of subprocesses to use when loading the dataset.
# - pin_memory: whether to copy tensors into CUDA pinned memory. Set it to
# True if using GPU.
# Returns
# -------
# - train_loader: training set iterator.
# - valid_loader: validation set iterator.
# """
# error_msg = "[!] valid_size should be in the range [0, 1]."
# assert ((valid_size >= 0) and (valid_size <= 1)), error_msg
#
# normalize = transforms.Normalize(mean=[0.5, 0.5, 0.5],
# std=[0.5, 0.5, 0.5])
#
# # define transforms
# valid_transform = transforms.Compose([
# transforms.ToTensor(),
# normalize
# ])
# if augment:
# train_transform = transforms.Compose([
# transforms.RandomCrop(32, padding=4),
# transforms.ToTensor(),
# normalize
# ])
# else:
# train_transform = transforms.Compose([
# transforms.ToTensor(),
# normalize
# ])
#
# # load the dataset
# train_dataset = MarioKartDataset(transform=train_transform, history=history)
# valid_dataset = MarioKartDataset(transform=valid_transform, history=history)
#
# num_train = len(train_dataset)
# indices = list(range(num_train))
# split = int(np.floor(valid_size * num_train))
#
# if shuffle:
# np.random.seed(random_seed)
# np.random.shuffle(indices)
#
# train_idx, valid_idx = indices[split:], indices[:split]
#
# train_sampler = SubsetRandomSampler(train_idx)
# valid_sampler = SubsetRandomSampler(valid_idx)
#
# train_loader = torch.utils.data.DataLoader(train_dataset,
# batch_size=batch_size, sampler=train_sampler,
# num_workers=num_workers, pin_memory=pin_memory)
#
# valid_loader = torch.utils.data.DataLoader(valid_dataset,
# batch_size=batch_size, sampler=valid_sampler,
# num_workers=num_workers, pin_memory=pin_memory)
# return train_loader, valid_loader
. Output only the next line. | train_loader, valid_loader = get_mario_train_valid_loader(batch_size, False, 123) |
Continue the code snippet: <|code_start|>""" This module implements the image downsampling component of the basic Mario Kart AI agent. """
logger = logging.getLogger(__name__)
class Downsampler:
def __init__(self, game_name, blur_size=25, intermediate_dim=300, final_dim=10):
self.game_name = game_name
self.blur_size = blur_size
if intermediate_dim % final_dim != 0:
raise ValueError("final dimensions must divide into intermediate dimensions completely.")
self.pooling_dim = int(intermediate_dim / final_dim)
self.inter_dim = (intermediate_dim, intermediate_dim)
<|code_end|>
. Use current file imports:
import logging
import traceback
import cv2
import numpy as np
import os
from skimage.measure import block_reduce
from src import helper
and context (classes, functions, or code) from other files:
# Path: src/helper.py
# def validate_function_key(slot_key):
# def get_output_folder():
# def get_models_folder():
# def get_dataset_folder():
# def get_home_folder():
# def pickle_object(data, name, directory=get_output_folder()):
# def generate_img_key(image):
# def get_tensor(image):
# def get_output_vector(presses):
# def get_key_state_from_vector(vector):
. Output only the next line. | self.screenshot_dir = os.path.join(helper.get_home_folder(), '.dolphin-emu', 'ScreenShots') |
Continue the code snippet: <|code_start|> True if using GPU.
Returns
-------
- train_loader: training set iterator.
- valid_loader: validation set iterator.
"""
error_msg = "[!] valid_size should be in the range [0, 1]."
assert ((valid_size >= 0) and (valid_size <= 1)), error_msg
normalize = transforms.Normalize(mean=[0.5, 0.5, 0.5],
std=[0.5, 0.5, 0.5])
# define transforms
valid_transform = transforms.Compose([
transforms.ToTensor(),
normalize
])
if augment:
train_transform = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.ToTensor(),
normalize
])
else:
train_transform = transforms.Compose([
transforms.ToTensor(),
normalize
])
# load the dataset
<|code_end|>
. Use current file imports:
import numpy as np
import torch
from torch.utils.data.sampler import SubsetRandomSampler
from torchvision import transforms
from src.agents.mk_dataset import MarioKartDataset
and context (classes, functions, or code) from other files:
# Path: src/agents/mk_dataset.py
# class MarioKartDataset(Dataset):
# """Mario Kart dataset."""
#
# def __init__(self, log_file=os.path.join(helper.get_dataset_folder(), 'mario_kart', "mario_kart.json"),
# transform=None, history=1):
# """
# Args:
# log_file: file path location to the log file containing key press states.
# """
# self.images = os.path.join(helper.get_dataset_folder(), 'mario_kart', "images")
# with open(log_file, 'r') as f:
# self.data = json.load(f).get('data')
# self.transform = transform
# self.history = history
#
# def __len__(self):
# return len(self.data)
#
# def __getitem__(self, idx):
# key_state = self.data[idx]
# img_count = key_state.get('count')
# tensors = []
# for i in range(self.history):
# img_name = os.path.join(self.images, "{}.png".format(img_count - i))
# image = cv2.imread(img_name)
# img_tensor = helper.get_tensor(image)
# if img_tensor is not None:
# tensors.append(img_tensor)
# else:
# logger.warning("Image not found, using last tensor found")
# tensors.append(tensors[-1])
# tensor = torch.stack(tensors)
# return tensor, helper.get_output_vector(key_state['presses'])
. Output only the next line. | train_dataset = MarioKartDataset(transform=train_transform, history=history) |
Continue the code snippet: <|code_start|>""" This module contains code for maintaining the basic Mario Kart AI agent's state-decision map. """
logger = logging.getLogger(__name__)
class StateModel:
""" Class for storing the basic Mario Kart AI agent's state-decision probabilities in a lookup table.
Attributes:
screenshot_dir: Directory where the Dolphin emulator saves screenshots.
keylog_filename: Name of the file where Dolphin keyboard output was logged to.
output_dir: Directory where the Dolphin keyboard log is stored.
image_dir: Directory containing the downsampled Dolphin images.
state_decision_map: Dictionary containing the state to decision probability mapping.
"""
def __init__(self, training_keylog="log.json", model_name="naive_model", clean_imgs=False):
<|code_end|>
. Use current file imports:
import logging
import json
import cv2
import pickle
import os
from src import helper, keylog
and context (classes, functions, or code) from other files:
# Path: src/helper.py
# def validate_function_key(slot_key):
# def get_output_folder():
# def get_models_folder():
# def get_dataset_folder():
# def get_home_folder():
# def pickle_object(data, name, directory=get_output_folder()):
# def generate_img_key(image):
# def get_tensor(image):
# def get_output_vector(presses):
# def get_key_state_from_vector(vector):
#
# Path: src/keylog.py
# class Keyboard(enum.Enum):
# class KeyLog:
# def __init__(self, logging_delay=0.3):
# def start(self):
# def on_press(self, key):
# def on_release(self, key):
# def record(self):
# def save_to_file(self, file_name="log.json"):
# def _get_key_value(key):
. Output only the next line. | self.screenshot_dir = os.path.join(helper.get_home_folder(), '.dolphin-emu', 'ScreenShots') |
Using the snippet: <|code_start|>""" This module contains code for maintaining the basic Mario Kart AI agent's state-decision map. """
logger = logging.getLogger(__name__)
class StateModel:
""" Class for storing the basic Mario Kart AI agent's state-decision probabilities in a lookup table.
Attributes:
screenshot_dir: Directory where the Dolphin emulator saves screenshots.
keylog_filename: Name of the file where Dolphin keyboard output was logged to.
output_dir: Directory where the Dolphin keyboard log is stored.
image_dir: Directory containing the downsampled Dolphin images.
state_decision_map: Dictionary containing the state to decision probability mapping.
"""
def __init__(self, training_keylog="log.json", model_name="naive_model", clean_imgs=False):
self.screenshot_dir = os.path.join(helper.get_home_folder(), '.dolphin-emu', 'ScreenShots')
self.keylog_filename = training_keylog
self.output_dir = helper.get_output_folder()
self.image_dir = os.path.join(helper.get_output_folder(), "images")
self.models_dir = os.path.join(helper.get_models_folder())
self.model_name = model_name
self.clean_imgs = clean_imgs
self.state_counts = dict()
self.state_decision_map = dict()
<|code_end|>
, determine the next line of code. You have imports:
import logging
import json
import cv2
import pickle
import os
from src import helper, keylog
and context (class names, function names, or code) available:
# Path: src/helper.py
# def validate_function_key(slot_key):
# def get_output_folder():
# def get_models_folder():
# def get_dataset_folder():
# def get_home_folder():
# def pickle_object(data, name, directory=get_output_folder()):
# def generate_img_key(image):
# def get_tensor(image):
# def get_output_vector(presses):
# def get_key_state_from_vector(vector):
#
# Path: src/keylog.py
# class Keyboard(enum.Enum):
# class KeyLog:
# def __init__(self, logging_delay=0.3):
# def start(self):
# def on_press(self, key):
# def on_release(self, key):
# def record(self):
# def save_to_file(self, file_name="log.json"):
# def _get_key_value(key):
. Output only the next line. | self.defaults = {k.name: 0 for k in keylog.Keyboard} |
Predict the next line after this snippet: <|code_start|> for step, (x, y) in enumerate(train_loader):
# Wrap label 'y' in variable
y_label = y.view(-1, output_vec)
if torch.cuda.is_available():
y_label = y_label.cuda()
nn_label = Variable(y_label)
# Forward pass
forward_pass = mkcrnn(x)
loss = loss_func(forward_pass, nn_label) # compute loss
optimizer.zero_grad() # zero gradients from previous step
loss.backward() # compute gradients
optimizer.step() # apply backpropagation
# Log training data
if step % 50 == 0:
print('Epoch: ', epoch, 'Step: ', step, '| training loss: %.4f' % loss.data[0])
valid_loss = 0
for (valid_x, valid_y) in valid_loader:
valid_y_label = valid_y.view(-1, output_vec)
if torch.cuda.is_available():
valid_y_label = valid_y_label.cuda()
valid_nn_label = Variable(valid_y_label)
valid_forward_pass = mkcrnn(valid_x)
valid_loss_eval = loss_func(valid_forward_pass, valid_nn_label) # compute validation loss
valid_loss += valid_loss_eval.data[0]
print('Epoch: ', epoch, 'Step: ', step, '| validation loss: %.4f' % valid_loss)
validation_losses.append(valid_loss)
# Save model
<|code_end|>
using the current file's imports:
import logging
import os
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from src import helper, keylog
from src.agents.train_valid_data import get_mario_train_valid_loader
from torch.autograd import Variable
and any relevant context from other files:
# Path: src/helper.py
# def validate_function_key(slot_key):
# def get_output_folder():
# def get_models_folder():
# def get_dataset_folder():
# def get_home_folder():
# def pickle_object(data, name, directory=get_output_folder()):
# def generate_img_key(image):
# def get_tensor(image):
# def get_output_vector(presses):
# def get_key_state_from_vector(vector):
#
# Path: src/keylog.py
# class Keyboard(enum.Enum):
# class KeyLog:
# def __init__(self, logging_delay=0.3):
# def start(self):
# def on_press(self, key):
# def on_release(self, key):
# def record(self):
# def save_to_file(self, file_name="log.json"):
# def _get_key_value(key):
#
# Path: src/agents/train_valid_data.py
# def get_mario_train_valid_loader(batch_size,
# augment,
# random_seed,
# valid_size=0.2,
# shuffle=True,
# history=1,
# num_workers=1,
# pin_memory=False):
# """
# Utility function for loading and returning train and valid
# multi-process iterators over the MarioKart dataset. A sample
# 9x9 grid of the images can be optionally displayed.
# If using CUDA, num_workers should be set to 1 and pin_memory to True.
# Params
# ------
# - data_dir: path directory to the dataset.
# - batch_size: how many samples per batch to load.
# - augment: whether to apply the data augmentation scheme
# mentioned in the paper. Only applied on the train split.
# - random_seed: fix seed for reproducibility.
# - valid_size: percentage split of the training set used for
# the validation set. Should be a float in the range [0, 1].
# - shuffle: whether to shuffle the train/validation indices.
# - show_sample: plot 9x9 sample grid of the dataset.
# - num_workers: number of subprocesses to use when loading the dataset.
# - pin_memory: whether to copy tensors into CUDA pinned memory. Set it to
# True if using GPU.
# Returns
# -------
# - train_loader: training set iterator.
# - valid_loader: validation set iterator.
# """
# error_msg = "[!] valid_size should be in the range [0, 1]."
# assert ((valid_size >= 0) and (valid_size <= 1)), error_msg
#
# normalize = transforms.Normalize(mean=[0.5, 0.5, 0.5],
# std=[0.5, 0.5, 0.5])
#
# # define transforms
# valid_transform = transforms.Compose([
# transforms.ToTensor(),
# normalize
# ])
# if augment:
# train_transform = transforms.Compose([
# transforms.RandomCrop(32, padding=4),
# transforms.ToTensor(),
# normalize
# ])
# else:
# train_transform = transforms.Compose([
# transforms.ToTensor(),
# normalize
# ])
#
# # load the dataset
# train_dataset = MarioKartDataset(transform=train_transform, history=history)
# valid_dataset = MarioKartDataset(transform=valid_transform, history=history)
#
# num_train = len(train_dataset)
# indices = list(range(num_train))
# split = int(np.floor(valid_size * num_train))
#
# if shuffle:
# np.random.seed(random_seed)
# np.random.shuffle(indices)
#
# train_idx, valid_idx = indices[split:], indices[:split]
#
# train_sampler = SubsetRandomSampler(train_idx)
# valid_sampler = SubsetRandomSampler(valid_idx)
#
# train_loader = torch.utils.data.DataLoader(train_dataset,
# batch_size=batch_size, sampler=train_sampler,
# num_workers=num_workers, pin_memory=pin_memory)
#
# valid_loader = torch.utils.data.DataLoader(valid_dataset,
# batch_size=batch_size, sampler=valid_sampler,
# num_workers=num_workers, pin_memory=pin_memory)
# return train_loader, valid_loader
. Output only the next line. | torch.save(mkcrnn, os.path.join(helper.get_models_folder(), "mkcrnn_{}_frames_{}_lstm.pkl".format(num_input_frames, history))) |
Next line prediction: <|code_start|>"""
This module implements a Convolutional Recurrent Neural Network (CRNN) Mario Kart AI Agent using
Long Short-Term Memory (LSTM) and PyTorch.
"""
logger = logging.getLogger(__name__)
# Hyper Parameters
input_size = 15
hidden_size_2 = 64
hidden_size_3 = 64
hidden_size_4 = 64
<|code_end|>
. Use current file imports:
(import logging
import os
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from src import helper, keylog
from src.agents.train_valid_data import get_mario_train_valid_loader
from torch.autograd import Variable)
and context including class names, function names, or small code snippets from other files:
# Path: src/helper.py
# def validate_function_key(slot_key):
# def get_output_folder():
# def get_models_folder():
# def get_dataset_folder():
# def get_home_folder():
# def pickle_object(data, name, directory=get_output_folder()):
# def generate_img_key(image):
# def get_tensor(image):
# def get_output_vector(presses):
# def get_key_state_from_vector(vector):
#
# Path: src/keylog.py
# class Keyboard(enum.Enum):
# class KeyLog:
# def __init__(self, logging_delay=0.3):
# def start(self):
# def on_press(self, key):
# def on_release(self, key):
# def record(self):
# def save_to_file(self, file_name="log.json"):
# def _get_key_value(key):
#
# Path: src/agents/train_valid_data.py
# def get_mario_train_valid_loader(batch_size,
# augment,
# random_seed,
# valid_size=0.2,
# shuffle=True,
# history=1,
# num_workers=1,
# pin_memory=False):
# """
# Utility function for loading and returning train and valid
# multi-process iterators over the MarioKart dataset. A sample
# 9x9 grid of the images can be optionally displayed.
# If using CUDA, num_workers should be set to 1 and pin_memory to True.
# Params
# ------
# - data_dir: path directory to the dataset.
# - batch_size: how many samples per batch to load.
# - augment: whether to apply the data augmentation scheme
# mentioned in the paper. Only applied on the train split.
# - random_seed: fix seed for reproducibility.
# - valid_size: percentage split of the training set used for
# the validation set. Should be a float in the range [0, 1].
# - shuffle: whether to shuffle the train/validation indices.
# - show_sample: plot 9x9 sample grid of the dataset.
# - num_workers: number of subprocesses to use when loading the dataset.
# - pin_memory: whether to copy tensors into CUDA pinned memory. Set it to
# True if using GPU.
# Returns
# -------
# - train_loader: training set iterator.
# - valid_loader: validation set iterator.
# """
# error_msg = "[!] valid_size should be in the range [0, 1]."
# assert ((valid_size >= 0) and (valid_size <= 1)), error_msg
#
# normalize = transforms.Normalize(mean=[0.5, 0.5, 0.5],
# std=[0.5, 0.5, 0.5])
#
# # define transforms
# valid_transform = transforms.Compose([
# transforms.ToTensor(),
# normalize
# ])
# if augment:
# train_transform = transforms.Compose([
# transforms.RandomCrop(32, padding=4),
# transforms.ToTensor(),
# normalize
# ])
# else:
# train_transform = transforms.Compose([
# transforms.ToTensor(),
# normalize
# ])
#
# # load the dataset
# train_dataset = MarioKartDataset(transform=train_transform, history=history)
# valid_dataset = MarioKartDataset(transform=valid_transform, history=history)
#
# num_train = len(train_dataset)
# indices = list(range(num_train))
# split = int(np.floor(valid_size * num_train))
#
# if shuffle:
# np.random.seed(random_seed)
# np.random.shuffle(indices)
#
# train_idx, valid_idx = indices[split:], indices[:split]
#
# train_sampler = SubsetRandomSampler(train_idx)
# valid_sampler = SubsetRandomSampler(valid_idx)
#
# train_loader = torch.utils.data.DataLoader(train_dataset,
# batch_size=batch_size, sampler=train_sampler,
# num_workers=num_workers, pin_memory=pin_memory)
#
# valid_loader = torch.utils.data.DataLoader(valid_dataset,
# batch_size=batch_size, sampler=valid_sampler,
# num_workers=num_workers, pin_memory=pin_memory)
# return train_loader, valid_loader
. Output only the next line. | output_vec = len(keylog.Keyboard) |
Next line prediction: <|code_start|> )
if torch.cuda.is_available():
print("cuda is available.")
self.cuda()
def forward(self, x):
""" Forward pass of the neural network. Accepts a tensor of size input_size*input_size. """
x = x.view(-1, self.conv1_in, self.input_size, self.input_size)
x = Variable(x).float()
if torch.cuda.is_available():
x = x.cuda()
out = self.conv1(x)
out = self.conv2(out)
out = out.view(-1, self.history, self.hidden_size_1)
out, _ = self.lstm(out)
out = out.view(-1, self.history * self.hidden_size_2)
encoded = self.encoder(out)
return encoded
if __name__ == '__main__':
""" Train neural network Mario Kart AI agent. """
mkcrnn = MKCRNN_lstm()
# Define gradient descent optimizer and loss function
optimizer = torch.optim.Adam(mkcrnn.parameters(), weight_decay=l2_reg, lr=learning_rate)
loss_func = nn.MSELoss()
# Load data
<|code_end|>
. Use current file imports:
(import logging
import os
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from src import helper, keylog
from src.agents.train_valid_data import get_mario_train_valid_loader
from torch.autograd import Variable)
and context including class names, function names, or small code snippets from other files:
# Path: src/helper.py
# def validate_function_key(slot_key):
# def get_output_folder():
# def get_models_folder():
# def get_dataset_folder():
# def get_home_folder():
# def pickle_object(data, name, directory=get_output_folder()):
# def generate_img_key(image):
# def get_tensor(image):
# def get_output_vector(presses):
# def get_key_state_from_vector(vector):
#
# Path: src/keylog.py
# class Keyboard(enum.Enum):
# class KeyLog:
# def __init__(self, logging_delay=0.3):
# def start(self):
# def on_press(self, key):
# def on_release(self, key):
# def record(self):
# def save_to_file(self, file_name="log.json"):
# def _get_key_value(key):
#
# Path: src/agents/train_valid_data.py
# def get_mario_train_valid_loader(batch_size,
# augment,
# random_seed,
# valid_size=0.2,
# shuffle=True,
# history=1,
# num_workers=1,
# pin_memory=False):
# """
# Utility function for loading and returning train and valid
# multi-process iterators over the MarioKart dataset. A sample
# 9x9 grid of the images can be optionally displayed.
# If using CUDA, num_workers should be set to 1 and pin_memory to True.
# Params
# ------
# - data_dir: path directory to the dataset.
# - batch_size: how many samples per batch to load.
# - augment: whether to apply the data augmentation scheme
# mentioned in the paper. Only applied on the train split.
# - random_seed: fix seed for reproducibility.
# - valid_size: percentage split of the training set used for
# the validation set. Should be a float in the range [0, 1].
# - shuffle: whether to shuffle the train/validation indices.
# - show_sample: plot 9x9 sample grid of the dataset.
# - num_workers: number of subprocesses to use when loading the dataset.
# - pin_memory: whether to copy tensors into CUDA pinned memory. Set it to
# True if using GPU.
# Returns
# -------
# - train_loader: training set iterator.
# - valid_loader: validation set iterator.
# """
# error_msg = "[!] valid_size should be in the range [0, 1]."
# assert ((valid_size >= 0) and (valid_size <= 1)), error_msg
#
# normalize = transforms.Normalize(mean=[0.5, 0.5, 0.5],
# std=[0.5, 0.5, 0.5])
#
# # define transforms
# valid_transform = transforms.Compose([
# transforms.ToTensor(),
# normalize
# ])
# if augment:
# train_transform = transforms.Compose([
# transforms.RandomCrop(32, padding=4),
# transforms.ToTensor(),
# normalize
# ])
# else:
# train_transform = transforms.Compose([
# transforms.ToTensor(),
# normalize
# ])
#
# # load the dataset
# train_dataset = MarioKartDataset(transform=train_transform, history=history)
# valid_dataset = MarioKartDataset(transform=valid_transform, history=history)
#
# num_train = len(train_dataset)
# indices = list(range(num_train))
# split = int(np.floor(valid_size * num_train))
#
# if shuffle:
# np.random.seed(random_seed)
# np.random.shuffle(indices)
#
# train_idx, valid_idx = indices[split:], indices[:split]
#
# train_sampler = SubsetRandomSampler(train_idx)
# valid_sampler = SubsetRandomSampler(valid_idx)
#
# train_loader = torch.utils.data.DataLoader(train_dataset,
# batch_size=batch_size, sampler=train_sampler,
# num_workers=num_workers, pin_memory=pin_memory)
#
# valid_loader = torch.utils.data.DataLoader(valid_dataset,
# batch_size=batch_size, sampler=valid_sampler,
# num_workers=num_workers, pin_memory=pin_memory)
# return train_loader, valid_loader
. Output only the next line. | train_loader, valid_loader = get_mario_train_valid_loader(batch_size, False, 123, history=num_input_frames) |
Next line prediction: <|code_start|> initial=0.1,
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
core_exceptions.DeadlineExceeded,
core_exceptions.ServiceUnavailable,
),
deadline=20.0,
),
default_timeout=20.0,
client_info=client_info,
),
self.enroll_data_sources: gapic_v1.method.wrap_method(
self.enroll_data_sources, default_timeout=None, client_info=client_info,
),
}
def close(self):
"""Closes resources associated with the transport.
.. warning::
Only call this method if the transport is NOT shared
with other clients - this may cause errors in other clients!
"""
raise NotImplementedError()
@property
def get_data_source(
self,
) -> Callable[
<|code_end|>
. Use current file imports:
(import abc
import pkg_resources
import google.auth # type: ignore
import google.api_core
from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
from google.oauth2 import service_account # type: ignore
from google.cloud.bigquery_datatransfer_v1.types import datatransfer
from google.cloud.bigquery_datatransfer_v1.types import transfer
from google.protobuf import empty_pb2 # type: ignore)
and context including class names, function names, or small code snippets from other files:
# Path: google/cloud/bigquery_datatransfer_v1/types/datatransfer.py
# class DataSourceParameter(proto.Message):
# class Type(proto.Enum):
# class DataSource(proto.Message):
# class AuthorizationType(proto.Enum):
# class DataRefreshType(proto.Enum):
# class GetDataSourceRequest(proto.Message):
# class ListDataSourcesRequest(proto.Message):
# class ListDataSourcesResponse(proto.Message):
# class CreateTransferConfigRequest(proto.Message):
# class UpdateTransferConfigRequest(proto.Message):
# class GetTransferConfigRequest(proto.Message):
# class DeleteTransferConfigRequest(proto.Message):
# class GetTransferRunRequest(proto.Message):
# class DeleteTransferRunRequest(proto.Message):
# class ListTransferConfigsRequest(proto.Message):
# class ListTransferConfigsResponse(proto.Message):
# class ListTransferRunsRequest(proto.Message):
# class RunAttempt(proto.Enum):
# class ListTransferRunsResponse(proto.Message):
# class ListTransferLogsRequest(proto.Message):
# class ListTransferLogsResponse(proto.Message):
# class CheckValidCredsRequest(proto.Message):
# class CheckValidCredsResponse(proto.Message):
# class ScheduleTransferRunsRequest(proto.Message):
# class ScheduleTransferRunsResponse(proto.Message):
# class StartManualTransferRunsRequest(proto.Message):
# class TimeRange(proto.Message):
# class StartManualTransferRunsResponse(proto.Message):
# class EnrollDataSourcesRequest(proto.Message):
# TYPE_UNSPECIFIED = 0
# STRING = 1
# INTEGER = 2
# DOUBLE = 3
# BOOLEAN = 4
# RECORD = 5
# PLUS_PAGE = 6
# AUTHORIZATION_TYPE_UNSPECIFIED = 0
# AUTHORIZATION_CODE = 1
# GOOGLE_PLUS_AUTHORIZATION_CODE = 2
# FIRST_PARTY_OAUTH = 3
# DATA_REFRESH_TYPE_UNSPECIFIED = 0
# SLIDING_WINDOW = 1
# CUSTOM_SLIDING_WINDOW = 2
# RUN_ATTEMPT_UNSPECIFIED = 0
# LATEST = 1
# def raw_page(self):
# def raw_page(self):
# def raw_page(self):
# def raw_page(self):
#
# Path: google/cloud/bigquery_datatransfer_v1/types/transfer.py
# class TransferType(proto.Enum):
# class TransferState(proto.Enum):
# class EmailPreferences(proto.Message):
# class ScheduleOptions(proto.Message):
# class UserInfo(proto.Message):
# class TransferConfig(proto.Message):
# class TransferRun(proto.Message):
# class TransferMessage(proto.Message):
# class MessageSeverity(proto.Enum):
# TRANSFER_TYPE_UNSPECIFIED = 0
# BATCH = 1
# STREAMING = 2
# TRANSFER_STATE_UNSPECIFIED = 0
# PENDING = 2
# RUNNING = 3
# SUCCEEDED = 4
# FAILED = 5
# CANCELLED = 6
# MESSAGE_SEVERITY_UNSPECIFIED = 0
# INFO = 1
# WARNING = 2
# ERROR = 3
. Output only the next line. | [datatransfer.GetDataSourceRequest], |
Based on the snippet: <|code_start|> with other clients - this may cause errors in other clients!
"""
raise NotImplementedError()
@property
def get_data_source(
self,
) -> Callable[
[datatransfer.GetDataSourceRequest],
Union[datatransfer.DataSource, Awaitable[datatransfer.DataSource]],
]:
raise NotImplementedError()
@property
def list_data_sources(
self,
) -> Callable[
[datatransfer.ListDataSourcesRequest],
Union[
datatransfer.ListDataSourcesResponse,
Awaitable[datatransfer.ListDataSourcesResponse],
],
]:
raise NotImplementedError()
@property
def create_transfer_config(
self,
) -> Callable[
[datatransfer.CreateTransferConfigRequest],
<|code_end|>
, predict the immediate next line with the help of imports:
import abc
import pkg_resources
import google.auth # type: ignore
import google.api_core
from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
from google.oauth2 import service_account # type: ignore
from google.cloud.bigquery_datatransfer_v1.types import datatransfer
from google.cloud.bigquery_datatransfer_v1.types import transfer
from google.protobuf import empty_pb2 # type: ignore
and context (classes, functions, sometimes code) from other files:
# Path: google/cloud/bigquery_datatransfer_v1/types/datatransfer.py
# class DataSourceParameter(proto.Message):
# class Type(proto.Enum):
# class DataSource(proto.Message):
# class AuthorizationType(proto.Enum):
# class DataRefreshType(proto.Enum):
# class GetDataSourceRequest(proto.Message):
# class ListDataSourcesRequest(proto.Message):
# class ListDataSourcesResponse(proto.Message):
# class CreateTransferConfigRequest(proto.Message):
# class UpdateTransferConfigRequest(proto.Message):
# class GetTransferConfigRequest(proto.Message):
# class DeleteTransferConfigRequest(proto.Message):
# class GetTransferRunRequest(proto.Message):
# class DeleteTransferRunRequest(proto.Message):
# class ListTransferConfigsRequest(proto.Message):
# class ListTransferConfigsResponse(proto.Message):
# class ListTransferRunsRequest(proto.Message):
# class RunAttempt(proto.Enum):
# class ListTransferRunsResponse(proto.Message):
# class ListTransferLogsRequest(proto.Message):
# class ListTransferLogsResponse(proto.Message):
# class CheckValidCredsRequest(proto.Message):
# class CheckValidCredsResponse(proto.Message):
# class ScheduleTransferRunsRequest(proto.Message):
# class ScheduleTransferRunsResponse(proto.Message):
# class StartManualTransferRunsRequest(proto.Message):
# class TimeRange(proto.Message):
# class StartManualTransferRunsResponse(proto.Message):
# class EnrollDataSourcesRequest(proto.Message):
# TYPE_UNSPECIFIED = 0
# STRING = 1
# INTEGER = 2
# DOUBLE = 3
# BOOLEAN = 4
# RECORD = 5
# PLUS_PAGE = 6
# AUTHORIZATION_TYPE_UNSPECIFIED = 0
# AUTHORIZATION_CODE = 1
# GOOGLE_PLUS_AUTHORIZATION_CODE = 2
# FIRST_PARTY_OAUTH = 3
# DATA_REFRESH_TYPE_UNSPECIFIED = 0
# SLIDING_WINDOW = 1
# CUSTOM_SLIDING_WINDOW = 2
# RUN_ATTEMPT_UNSPECIFIED = 0
# LATEST = 1
# def raw_page(self):
# def raw_page(self):
# def raw_page(self):
# def raw_page(self):
#
# Path: google/cloud/bigquery_datatransfer_v1/types/transfer.py
# class TransferType(proto.Enum):
# class TransferState(proto.Enum):
# class EmailPreferences(proto.Message):
# class ScheduleOptions(proto.Message):
# class UserInfo(proto.Message):
# class TransferConfig(proto.Message):
# class TransferRun(proto.Message):
# class TransferMessage(proto.Message):
# class MessageSeverity(proto.Enum):
# TRANSFER_TYPE_UNSPECIFIED = 0
# BATCH = 1
# STREAMING = 2
# TRANSFER_STATE_UNSPECIFIED = 0
# PENDING = 2
# RUNNING = 3
# SUCCEEDED = 4
# FAILED = 5
# CANCELLED = 6
# MESSAGE_SEVERITY_UNSPECIFIED = 0
# INFO = 1
# WARNING = 2
# ERROR = 3
. Output only the next line. | Union[transfer.TransferConfig, Awaitable[transfer.TransferConfig]], |
Here is a snippet: <|code_start|> default_data_refresh_window_days (int):
Default data refresh window on days. Only meaningful when
``data_refresh_type`` = ``SLIDING_WINDOW``.
manual_runs_disabled (bool):
Disables backfilling and manual run
scheduling for the data source.
minimum_schedule_interval (google.protobuf.duration_pb2.Duration):
The minimum interval for scheduler to
schedule runs.
"""
class AuthorizationType(proto.Enum):
r"""The type of authorization needed for this data source."""
AUTHORIZATION_TYPE_UNSPECIFIED = 0
AUTHORIZATION_CODE = 1
GOOGLE_PLUS_AUTHORIZATION_CODE = 2
FIRST_PARTY_OAUTH = 3
class DataRefreshType(proto.Enum):
r"""Represents how the data source supports data auto refresh."""
DATA_REFRESH_TYPE_UNSPECIFIED = 0
SLIDING_WINDOW = 1
CUSTOM_SLIDING_WINDOW = 2
name = proto.Field(proto.STRING, number=1,)
data_source_id = proto.Field(proto.STRING, number=2,)
display_name = proto.Field(proto.STRING, number=3,)
description = proto.Field(proto.STRING, number=4,)
client_id = proto.Field(proto.STRING, number=5,)
scopes = proto.RepeatedField(proto.STRING, number=6,)
<|code_end|>
. Write the next line using the current file imports:
import proto # type: ignore
from google.cloud.bigquery_datatransfer_v1.types import transfer
from google.protobuf import duration_pb2 # type: ignore
from google.protobuf import field_mask_pb2 # type: ignore
from google.protobuf import timestamp_pb2 # type: ignore
from google.protobuf import wrappers_pb2 # type: ignore
and context from other files:
# Path: google/cloud/bigquery_datatransfer_v1/types/transfer.py
# class TransferType(proto.Enum):
# class TransferState(proto.Enum):
# class EmailPreferences(proto.Message):
# class ScheduleOptions(proto.Message):
# class UserInfo(proto.Message):
# class TransferConfig(proto.Message):
# class TransferRun(proto.Message):
# class TransferMessage(proto.Message):
# class MessageSeverity(proto.Enum):
# TRANSFER_TYPE_UNSPECIFIED = 0
# BATCH = 1
# STREAMING = 2
# TRANSFER_STATE_UNSPECIFIED = 0
# PENDING = 2
# RUNNING = 3
# SUCCEEDED = 4
# FAILED = 5
# CANCELLED = 6
# MESSAGE_SEVERITY_UNSPECIFIED = 0
# INFO = 1
# WARNING = 2
# ERROR = 3
, which may include functions, classes, or code. Output only the next line. | transfer_type = proto.Field(proto.ENUM, number=7, enum=transfer.TransferType,) |
Continue the code 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.
#
class ListDataSourcesPager:
"""A pager for iterating through ``list_data_sources`` requests.
This class thinly wraps an initial
:class:`google.cloud.bigquery_datatransfer_v1.types.ListDataSourcesResponse` object, and
provides an ``__iter__`` method to iterate through its
``data_sources`` field.
If there are more pages, the ``__iter__`` method will make additional
``ListDataSources`` requests and continue to iterate
through the ``data_sources`` field on the
corresponding responses.
All the usual :class:`google.cloud.bigquery_datatransfer_v1.types.ListDataSourcesResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
def __init__(
self,
<|code_end|>
. Use current file imports:
from typing import (
Any,
AsyncIterator,
Awaitable,
Callable,
Sequence,
Tuple,
Optional,
Iterator,
)
from google.cloud.bigquery_datatransfer_v1.types import datatransfer
from google.cloud.bigquery_datatransfer_v1.types import transfer
and context (classes, functions, or code) from other files:
# Path: google/cloud/bigquery_datatransfer_v1/types/datatransfer.py
# class DataSourceParameter(proto.Message):
# class Type(proto.Enum):
# class DataSource(proto.Message):
# class AuthorizationType(proto.Enum):
# class DataRefreshType(proto.Enum):
# class GetDataSourceRequest(proto.Message):
# class ListDataSourcesRequest(proto.Message):
# class ListDataSourcesResponse(proto.Message):
# class CreateTransferConfigRequest(proto.Message):
# class UpdateTransferConfigRequest(proto.Message):
# class GetTransferConfigRequest(proto.Message):
# class DeleteTransferConfigRequest(proto.Message):
# class GetTransferRunRequest(proto.Message):
# class DeleteTransferRunRequest(proto.Message):
# class ListTransferConfigsRequest(proto.Message):
# class ListTransferConfigsResponse(proto.Message):
# class ListTransferRunsRequest(proto.Message):
# class RunAttempt(proto.Enum):
# class ListTransferRunsResponse(proto.Message):
# class ListTransferLogsRequest(proto.Message):
# class ListTransferLogsResponse(proto.Message):
# class CheckValidCredsRequest(proto.Message):
# class CheckValidCredsResponse(proto.Message):
# class ScheduleTransferRunsRequest(proto.Message):
# class ScheduleTransferRunsResponse(proto.Message):
# class StartManualTransferRunsRequest(proto.Message):
# class TimeRange(proto.Message):
# class StartManualTransferRunsResponse(proto.Message):
# class EnrollDataSourcesRequest(proto.Message):
# TYPE_UNSPECIFIED = 0
# STRING = 1
# INTEGER = 2
# DOUBLE = 3
# BOOLEAN = 4
# RECORD = 5
# PLUS_PAGE = 6
# AUTHORIZATION_TYPE_UNSPECIFIED = 0
# AUTHORIZATION_CODE = 1
# GOOGLE_PLUS_AUTHORIZATION_CODE = 2
# FIRST_PARTY_OAUTH = 3
# DATA_REFRESH_TYPE_UNSPECIFIED = 0
# SLIDING_WINDOW = 1
# CUSTOM_SLIDING_WINDOW = 2
# RUN_ATTEMPT_UNSPECIFIED = 0
# LATEST = 1
# def raw_page(self):
# def raw_page(self):
# def raw_page(self):
# def raw_page(self):
#
# Path: google/cloud/bigquery_datatransfer_v1/types/transfer.py
# class TransferType(proto.Enum):
# class TransferState(proto.Enum):
# class EmailPreferences(proto.Message):
# class ScheduleOptions(proto.Message):
# class UserInfo(proto.Message):
# class TransferConfig(proto.Message):
# class TransferRun(proto.Message):
# class TransferMessage(proto.Message):
# class MessageSeverity(proto.Enum):
# TRANSFER_TYPE_UNSPECIFIED = 0
# BATCH = 1
# STREAMING = 2
# TRANSFER_STATE_UNSPECIFIED = 0
# PENDING = 2
# RUNNING = 3
# SUCCEEDED = 4
# FAILED = 5
# CANCELLED = 6
# MESSAGE_SEVERITY_UNSPECIFIED = 0
# INFO = 1
# WARNING = 2
# ERROR = 3
. Output only the next line. | method: Callable[..., datatransfer.ListDataSourcesResponse], |
Next line prediction: <|code_start|> metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
request (google.cloud.bigquery_datatransfer_v1.types.ListTransferConfigsRequest):
The initial request object.
response (google.cloud.bigquery_datatransfer_v1.types.ListTransferConfigsResponse):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = datatransfer.ListTransferConfigsRequest(request)
self._response = response
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
return getattr(self._response, name)
@property
def pages(self) -> Iterator[datatransfer.ListTransferConfigsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
self._response = self._method(self._request, metadata=self._metadata)
yield self._response
<|code_end|>
. Use current file imports:
(from typing import (
Any,
AsyncIterator,
Awaitable,
Callable,
Sequence,
Tuple,
Optional,
Iterator,
)
from google.cloud.bigquery_datatransfer_v1.types import datatransfer
from google.cloud.bigquery_datatransfer_v1.types import transfer)
and context including class names, function names, or small code snippets from other files:
# Path: google/cloud/bigquery_datatransfer_v1/types/datatransfer.py
# class DataSourceParameter(proto.Message):
# class Type(proto.Enum):
# class DataSource(proto.Message):
# class AuthorizationType(proto.Enum):
# class DataRefreshType(proto.Enum):
# class GetDataSourceRequest(proto.Message):
# class ListDataSourcesRequest(proto.Message):
# class ListDataSourcesResponse(proto.Message):
# class CreateTransferConfigRequest(proto.Message):
# class UpdateTransferConfigRequest(proto.Message):
# class GetTransferConfigRequest(proto.Message):
# class DeleteTransferConfigRequest(proto.Message):
# class GetTransferRunRequest(proto.Message):
# class DeleteTransferRunRequest(proto.Message):
# class ListTransferConfigsRequest(proto.Message):
# class ListTransferConfigsResponse(proto.Message):
# class ListTransferRunsRequest(proto.Message):
# class RunAttempt(proto.Enum):
# class ListTransferRunsResponse(proto.Message):
# class ListTransferLogsRequest(proto.Message):
# class ListTransferLogsResponse(proto.Message):
# class CheckValidCredsRequest(proto.Message):
# class CheckValidCredsResponse(proto.Message):
# class ScheduleTransferRunsRequest(proto.Message):
# class ScheduleTransferRunsResponse(proto.Message):
# class StartManualTransferRunsRequest(proto.Message):
# class TimeRange(proto.Message):
# class StartManualTransferRunsResponse(proto.Message):
# class EnrollDataSourcesRequest(proto.Message):
# TYPE_UNSPECIFIED = 0
# STRING = 1
# INTEGER = 2
# DOUBLE = 3
# BOOLEAN = 4
# RECORD = 5
# PLUS_PAGE = 6
# AUTHORIZATION_TYPE_UNSPECIFIED = 0
# AUTHORIZATION_CODE = 1
# GOOGLE_PLUS_AUTHORIZATION_CODE = 2
# FIRST_PARTY_OAUTH = 3
# DATA_REFRESH_TYPE_UNSPECIFIED = 0
# SLIDING_WINDOW = 1
# CUSTOM_SLIDING_WINDOW = 2
# RUN_ATTEMPT_UNSPECIFIED = 0
# LATEST = 1
# def raw_page(self):
# def raw_page(self):
# def raw_page(self):
# def raw_page(self):
#
# Path: google/cloud/bigquery_datatransfer_v1/types/transfer.py
# class TransferType(proto.Enum):
# class TransferState(proto.Enum):
# class EmailPreferences(proto.Message):
# class ScheduleOptions(proto.Message):
# class UserInfo(proto.Message):
# class TransferConfig(proto.Message):
# class TransferRun(proto.Message):
# class TransferMessage(proto.Message):
# class MessageSeverity(proto.Enum):
# TRANSFER_TYPE_UNSPECIFIED = 0
# BATCH = 1
# STREAMING = 2
# TRANSFER_STATE_UNSPECIFIED = 0
# PENDING = 2
# RUNNING = 3
# SUCCEEDED = 4
# FAILED = 5
# CANCELLED = 6
# MESSAGE_SEVERITY_UNSPECIFIED = 0
# INFO = 1
# WARNING = 2
# ERROR = 3
. Output only the next line. | def __iter__(self) -> Iterator[transfer.TransferConfig]: |
Given snippet: <|code_start|> "203.104.209.23",
"203.104.209.39",
"203.104.209.55",
"203.104.209.102",
)
# 伪装成Win7 x64上的IE11
user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko'
# 匹配网页中所需信息的正则表达式
patterns = {'dmm_token': re.compile(r'http-dmm-token" content="([\d|\w]+)"'),
'token': re.compile(r'token" content="([\d|\w]+)"'),
'reset': re.compile(r'認証エラー'),
'osapi': re.compile(r'URL\W+:\W+"(.*)",')}
def __init__(self, login_id, password):
""" 使用`login_id`和`password`来初始化认证对象。
`login_id`为登录DMM网站所需的用户名,一般为电子邮件地址,`password`为登录所需的密码。
仅支持用DMM账号登录,不支持Facebook和Google+账号登录。
:param login_id: str
:param password: str
:return: none
"""
# 初始化登录变量
self.login_id = login_id
self.password = password
# 初始化aiohttp会话,如果设定了代理服务器,则通过代理服务器发起会话
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import aiohttp
import asyncio
import json
import re
import time
from urllib.parse import urlparse, parse_qs
from base import config
from auth.exceptions import OOIAuthException
and context:
# Path: base/config.py
#
# Path: auth/exceptions.py
# class OOIAuthException(OOIBaseException):
# pass
which might include code, classes, or functions. Output only the next line. | if config.proxy: |
Predict the next line after this snippet: <|code_start|> self.world_ip = None
self.api_token = None
self.api_starttime = None
self.entry = None
def __del__(self):
"""析构函数,用于关闭aiohttp的会话。
:return: none
"""
self.session.close()
@asyncio.coroutine
def _request(self, url, method='GET', data=None, timeout_message='连接失败', timeout=10):
"""使用asyncio.wait_for包装过的会话向远端服务器发起请求。
`url`为请求的URL地址,`method`为请求的方法, `data`为发起POST请求时的数据,`timeout_message`为请求超时后抛出异常所带的信息,
`timeout`为超时时间,单位为秒。
:param url: str
:param method: str
:param data: dict
:param timeout_message: str
:param timeout: int
:return: generator
"""
try:
response = yield from asyncio.wait_for(self.session.request(method, url, data=data, headers=self.headers),
timeout)
return response
except asyncio.TimeoutError:
<|code_end|>
using the current file's imports:
import aiohttp
import asyncio
import json
import re
import time
from urllib.parse import urlparse, parse_qs
from base import config
from auth.exceptions import OOIAuthException
and any relevant context from other files:
# Path: base/config.py
#
# Path: auth/exceptions.py
# class OOIAuthException(OOIBaseException):
# pass
. Output only the next line. | raise OOIAuthException(timeout_message) |
Given snippet: <|code_start|>
:param request: aiohttp.web.Request
:return: dict
"""
session = yield from get_session(request)
if 'mode' in session:
mode = session['mode']
else:
session['mode'] = 1
mode = 1
return {'mode': mode}
@asyncio.coroutine
def login(self, request):
"""接受登录表单提交的数据,登录后跳转或登录失败后展示错误信息。
:param request: aiohttp.web.Request
:return: aiohttp.web.HTTPFound or aiohttp.web.Response
"""
post = yield from request.post()
session = yield from get_session(request)
login_id = post.get('login_id', None)
password = post.get('password', None)
mode = int(post.get('mode', 1))
session['mode'] = mode
if login_id and password:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import asyncio
import aiohttp.web
import aiohttp_jinja2
from aiohttp_session import get_session
from auth.kancolle import KancolleAuth, OOIAuthException
and context:
# Path: auth/kancolle.py
# class KancolleAuth:
# def __init__(self, login_id, password):
# def __del__(self):
# def _request(self, url, method='GET', data=None, timeout_message='连接失败', timeout=10):
# def _get_dmm_tokens(self):
# def _get_ajax_token(self):
# def _get_osapi_url(self):
# def _get_world(self):
# def _get_api_token(self):
# def get_osapi(self):
# def get_entry(self):
which might include code, classes, or functions. Output only the next line. | kancolle = KancolleAuth(login_id, password) |
Given the following code snippet before the placeholder: <|code_start|> def login(self, request):
"""接受登录表单提交的数据,登录后跳转或登录失败后展示错误信息。
:param request: aiohttp.web.Request
:return: aiohttp.web.HTTPFound or aiohttp.web.Response
"""
post = yield from request.post()
session = yield from get_session(request)
login_id = post.get('login_id', None)
password = post.get('password', None)
mode = int(post.get('mode', 1))
session['mode'] = mode
if login_id and password:
kancolle = KancolleAuth(login_id, password)
if mode in (1, 2, 3):
try:
yield from kancolle.get_entry()
session['api_token'] = kancolle.api_token
session['api_starttime'] = kancolle.api_starttime
session['world_ip'] = kancolle.world_ip
if mode == 2:
return aiohttp.web.HTTPFound('/kcv')
elif mode == 3:
return aiohttp.web.HTTPFound('/poi')
else:
return aiohttp.web.HTTPFound('/kancolle')
<|code_end|>
, predict the next line using imports from the current file:
import asyncio
import aiohttp.web
import aiohttp_jinja2
from aiohttp_session import get_session
from auth.kancolle import KancolleAuth, OOIAuthException
and context including class names, function names, and sometimes code from other files:
# Path: auth/kancolle.py
# class KancolleAuth:
# def __init__(self, login_id, password):
# def __del__(self):
# def _request(self, url, method='GET', data=None, timeout_message='连接失败', timeout=10):
# def _get_dmm_tokens(self):
# def _get_ajax_token(self):
# def _get_osapi_url(self):
# def _get_world(self):
# def _get_api_token(self):
# def get_osapi(self):
# def get_entry(self):
. Output only the next line. | except OOIAuthException as e: |
Continue the code snippet: <|code_start|>"""转发客户端FLASH和游戏服务器之间的通信。
接受客户端FLASH发送到OOI3服务器的请求,将其转发给用户所在的游戏服务器,获得响应后再返回给客户端FLASH。
"""
class APIHandler:
""" OOI3中用于转发客户端FLASH和游戏服务器间通信的类。"""
def __init__(self):
""" 构造函数,根据环境变量初始化代理服务器。
:return: none
"""
<|code_end|>
. Use current file imports:
import aiohttp
import aiohttp.web
import asyncio
from aiohttp_session import get_session
from base import config
and context (classes, functions, or code) from other files:
# Path: base/config.py
. Output only the next line. | if config.proxy: |
Next line prediction: <|code_start|> news = []
h3s = soup.find_all('h3', class_='tec--card__title')
# Limit to 10 news
i = 0
for h3 in h3s:
title = h3.a.string
link = h3.a['href']
news.append(dict(title=title, link=link))
i += 1
if i == 10:
break
return news
# Strategy Pattern - a dictionary of functions. Key: the name of the News Source. Value: the Function to execute
strategies = dict(tec_g1=__tec_g1, tec_cw=__tec_cw, tec_olhar=__tec_olhar, tec_canal=__tec_canal, tec_uol=__tec_uol,
tec_giz=__tec_giz, tec_conv=__tec_conv, tec_tecmundo=__tec_tecmundo)
def get_most_read(key):
"""
Gets the most read news from a given page
:param key: the key of the source page (e.g: g1)
:return: a list with the most read news from the page and the name of news source
"""
ns = get_ns(key)
<|code_end|>
. Use current file imports:
(from app.aml_utils import getpage, parsepage, get_ns
from app.news_source_national import g1)
and context including class names, function names, or small code snippets from other files:
# Path: app/aml_utils.py
# def getpage(url):
# """
# Downloads the html page
#
# :rtype: tuple
# :param url: the page address
# :return: the header response and contents (bytes) of the page
# """
# http = httplib2.Http('.cache', disable_ssl_certificate_validation=True)
# headers = {
# 'User-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36'}
#
# response, content = http.request(url, headers=headers)
# return response, content
#
# def parsepage(content):
# """
# Parses a single page and its contents into a BeautifulSoup object
#
# :param content: bytearray
# :return soup: object
# """
# soup = BeautifulSoup(content, 'lxml')
# return soup
#
# def get_ns(key):
# """
# Gets a news_source filtered by key
# :param key: the key of the news source (e.g: g1, uol, etc.)
# :return: the news source object
# """
# ns = NewsSource.query.filter_by(
# key=key).first() # Fetch news source by key
# return ns
#
# Path: app/news_source_national.py
# def g1(soup):
# """
# Gets the most read news from the g1 page
#
# :param soup: the BeautifulSoup object
# :return: a list with the most read news from the G1 Page
# """
# news = []
# scripts = soup.find_all('script')
#
# for script in scripts:
# script_content = script.text
#
# # O conteúdo do G1 agora é gerado por script. Primeiro achamos o script correto, pois são vários
# if script_content.find('#G1-POST-TOP') != -1:
# i = 0
#
# # Recuperamos as URLs mais acessadas
# while True:
# # Primeiro achamos um top-post (url) com essa chave de busca
# key_index = script_content.find('#G1-POST-TOP', i)
#
# if key_index == -1:
# break
#
# # Agora achamos o começo da url
# start_index = script_content.rfind('"', 0, key_index) + 1
#
# # Agora achamos o final da url
# end_index = script_content.find('"', key_index)
#
# # E agora pegamos a URL (substring)
# url = script_content[start_index: end_index]
#
# # Com a URL, entramos na página e descobrimos o título dela
# response, content = getpage(url)
# soup2 = parsepage(content)
# title = soup2.find('h1', class_='content-head__title').string
#
# news.append(dict(title=title, link=url))
#
# # Preparamos o próximo índice de busca
# i = key_index + 10
#
# return news
. Output only the next line. | response, content = getpage(ns.url) # Download the page |
Continue the code snippet: <|code_start|> h3s = soup.find_all('h3', class_='tec--card__title')
# Limit to 10 news
i = 0
for h3 in h3s:
title = h3.a.string
link = h3.a['href']
news.append(dict(title=title, link=link))
i += 1
if i == 10:
break
return news
# Strategy Pattern - a dictionary of functions. Key: the name of the News Source. Value: the Function to execute
strategies = dict(tec_g1=__tec_g1, tec_cw=__tec_cw, tec_olhar=__tec_olhar, tec_canal=__tec_canal, tec_uol=__tec_uol,
tec_giz=__tec_giz, tec_conv=__tec_conv, tec_tecmundo=__tec_tecmundo)
def get_most_read(key):
"""
Gets the most read news from a given page
:param key: the key of the source page (e.g: g1)
:return: a list with the most read news from the page and the name of news source
"""
ns = get_ns(key)
response, content = getpage(ns.url) # Download the page
<|code_end|>
. Use current file imports:
from app.aml_utils import getpage, parsepage, get_ns
from app.news_source_national import g1
and context (classes, functions, or code) from other files:
# Path: app/aml_utils.py
# def getpage(url):
# """
# Downloads the html page
#
# :rtype: tuple
# :param url: the page address
# :return: the header response and contents (bytes) of the page
# """
# http = httplib2.Http('.cache', disable_ssl_certificate_validation=True)
# headers = {
# 'User-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36'}
#
# response, content = http.request(url, headers=headers)
# return response, content
#
# def parsepage(content):
# """
# Parses a single page and its contents into a BeautifulSoup object
#
# :param content: bytearray
# :return soup: object
# """
# soup = BeautifulSoup(content, 'lxml')
# return soup
#
# def get_ns(key):
# """
# Gets a news_source filtered by key
# :param key: the key of the news source (e.g: g1, uol, etc.)
# :return: the news source object
# """
# ns = NewsSource.query.filter_by(
# key=key).first() # Fetch news source by key
# return ns
#
# Path: app/news_source_national.py
# def g1(soup):
# """
# Gets the most read news from the g1 page
#
# :param soup: the BeautifulSoup object
# :return: a list with the most read news from the G1 Page
# """
# news = []
# scripts = soup.find_all('script')
#
# for script in scripts:
# script_content = script.text
#
# # O conteúdo do G1 agora é gerado por script. Primeiro achamos o script correto, pois são vários
# if script_content.find('#G1-POST-TOP') != -1:
# i = 0
#
# # Recuperamos as URLs mais acessadas
# while True:
# # Primeiro achamos um top-post (url) com essa chave de busca
# key_index = script_content.find('#G1-POST-TOP', i)
#
# if key_index == -1:
# break
#
# # Agora achamos o começo da url
# start_index = script_content.rfind('"', 0, key_index) + 1
#
# # Agora achamos o final da url
# end_index = script_content.find('"', key_index)
#
# # E agora pegamos a URL (substring)
# url = script_content[start_index: end_index]
#
# # Com a URL, entramos na página e descobrimos o título dela
# response, content = getpage(url)
# soup2 = parsepage(content)
# title = soup2.find('h1', class_='content-head__title').string
#
# news.append(dict(title=title, link=url))
#
# # Preparamos o próximo índice de busca
# i = key_index + 10
#
# return news
. Output only the next line. | soup = parsepage(content) # Then we parse it |
Given the following code snippet before the placeholder: <|code_start|> title = a.string
link = a['href']
news.append(dict(title=title, link=link))
return news
def __tec_olhar(soup):
"""
Gets the most read news from the Olhar Digital page
:param soup: the BeautifulSoup object
:return: a list with the most read news from the Olhar Digital page
"""
# DEPRECATED
news = []
images = soup.find('div', id='div-gpt-corpo2').next_sibling.next_sibling.find_all('img')
for img in images:
title = img['alt']
link = img.parent['href']
news.append(dict(title=title, link=link))
return news
def __tec_conv(soup):
"""
Gets the most read news from the Convergencia Digital page
:param soup: the BeautifulSoup object
:return: a list with the most read news from the Convergencia Digital page
"""
news = []
<|code_end|>
, predict the next line using imports from the current file:
from app.aml_utils import getpage, parsepage, get_ns
from app.news_source_national import g1
and context including class names, function names, and sometimes code from other files:
# Path: app/aml_utils.py
# def getpage(url):
# """
# Downloads the html page
#
# :rtype: tuple
# :param url: the page address
# :return: the header response and contents (bytes) of the page
# """
# http = httplib2.Http('.cache', disable_ssl_certificate_validation=True)
# headers = {
# 'User-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36'}
#
# response, content = http.request(url, headers=headers)
# return response, content
#
# def parsepage(content):
# """
# Parses a single page and its contents into a BeautifulSoup object
#
# :param content: bytearray
# :return soup: object
# """
# soup = BeautifulSoup(content, 'lxml')
# return soup
#
# def get_ns(key):
# """
# Gets a news_source filtered by key
# :param key: the key of the news source (e.g: g1, uol, etc.)
# :return: the news source object
# """
# ns = NewsSource.query.filter_by(
# key=key).first() # Fetch news source by key
# return ns
#
# Path: app/news_source_national.py
# def g1(soup):
# """
# Gets the most read news from the g1 page
#
# :param soup: the BeautifulSoup object
# :return: a list with the most read news from the G1 Page
# """
# news = []
# scripts = soup.find_all('script')
#
# for script in scripts:
# script_content = script.text
#
# # O conteúdo do G1 agora é gerado por script. Primeiro achamos o script correto, pois são vários
# if script_content.find('#G1-POST-TOP') != -1:
# i = 0
#
# # Recuperamos as URLs mais acessadas
# while True:
# # Primeiro achamos um top-post (url) com essa chave de busca
# key_index = script_content.find('#G1-POST-TOP', i)
#
# if key_index == -1:
# break
#
# # Agora achamos o começo da url
# start_index = script_content.rfind('"', 0, key_index) + 1
#
# # Agora achamos o final da url
# end_index = script_content.find('"', key_index)
#
# # E agora pegamos a URL (substring)
# url = script_content[start_index: end_index]
#
# # Com a URL, entramos na página e descobrimos o título dela
# response, content = getpage(url)
# soup2 = parsepage(content)
# title = soup2.find('h1', class_='content-head__title').string
#
# news.append(dict(title=title, link=url))
#
# # Preparamos o próximo índice de busca
# i = key_index + 10
#
# return news
. Output only the next line. | ns = get_ns('tec_conv') |
Using the snippet: <|code_start|>"""
news_source_technology.py: Scraping functions for the most read Technology News Sources
__author__ = "Fernando P. Lopes"
__email__ = "fpedrosa@gmail.com"
"""
def __tec_g1(soup):
"""
Gets the most read news from the G1 Technology page
:param soup: the BeautifulSoup object
:return: a list with the most read news from the G1 Technology page
"""
<|code_end|>
, determine the next line of code. You have imports:
from app.aml_utils import getpage, parsepage, get_ns
from app.news_source_national import g1
and context (class names, function names, or code) available:
# Path: app/aml_utils.py
# def getpage(url):
# """
# Downloads the html page
#
# :rtype: tuple
# :param url: the page address
# :return: the header response and contents (bytes) of the page
# """
# http = httplib2.Http('.cache', disable_ssl_certificate_validation=True)
# headers = {
# 'User-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36'}
#
# response, content = http.request(url, headers=headers)
# return response, content
#
# def parsepage(content):
# """
# Parses a single page and its contents into a BeautifulSoup object
#
# :param content: bytearray
# :return soup: object
# """
# soup = BeautifulSoup(content, 'lxml')
# return soup
#
# def get_ns(key):
# """
# Gets a news_source filtered by key
# :param key: the key of the news source (e.g: g1, uol, etc.)
# :return: the news source object
# """
# ns = NewsSource.query.filter_by(
# key=key).first() # Fetch news source by key
# return ns
#
# Path: app/news_source_national.py
# def g1(soup):
# """
# Gets the most read news from the g1 page
#
# :param soup: the BeautifulSoup object
# :return: a list with the most read news from the G1 Page
# """
# news = []
# scripts = soup.find_all('script')
#
# for script in scripts:
# script_content = script.text
#
# # O conteúdo do G1 agora é gerado por script. Primeiro achamos o script correto, pois são vários
# if script_content.find('#G1-POST-TOP') != -1:
# i = 0
#
# # Recuperamos as URLs mais acessadas
# while True:
# # Primeiro achamos um top-post (url) com essa chave de busca
# key_index = script_content.find('#G1-POST-TOP', i)
#
# if key_index == -1:
# break
#
# # Agora achamos o começo da url
# start_index = script_content.rfind('"', 0, key_index) + 1
#
# # Agora achamos o final da url
# end_index = script_content.find('"', key_index)
#
# # E agora pegamos a URL (substring)
# url = script_content[start_index: end_index]
#
# # Com a URL, entramos na página e descobrimos o título dela
# response, content = getpage(url)
# soup2 = parsepage(content)
# title = soup2.find('h1', class_='content-head__title').string
#
# news.append(dict(title=title, link=url))
#
# # Preparamos o próximo índice de busca
# i = key_index + 10
#
# return news
. Output only the next line. | news = g1(soup) |
Here is a snippet: <|code_start|> Gets the most read news from the Rock Bizz page
:param soup: the BeautifulSoup object
:return: a list with the most read news from the Rock Bizz page
"""
news = []
ns = get_ns('m_bizz')
main = soup.find('main', id='main')
articles = main.find_all('article')
for article in articles:
title = article.a.string
link = article.a['href']
news.append(dict(title=title, link=link))
return news
# Strategy Pattern - a dictionary of functions. Key: the name of the News Source. Value: the Function to execute
strategies = dict(m_rs=__m_rs, m_bizz=__m_rockbizz)
def get_most_read(key):
"""
Gets the most read news from a given page
:param key: the key of the source page (e.g: g1)
:return: a list with the most read news from the page and the name of news source
"""
ns = get_ns(key)
<|code_end|>
. Write the next line using the current file imports:
from app.aml_utils import getpage, parsepage, get_ns
and context from other files:
# Path: app/aml_utils.py
# def getpage(url):
# """
# Downloads the html page
#
# :rtype: tuple
# :param url: the page address
# :return: the header response and contents (bytes) of the page
# """
# http = httplib2.Http('.cache', disable_ssl_certificate_validation=True)
# headers = {
# 'User-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36'}
#
# response, content = http.request(url, headers=headers)
# return response, content
#
# def parsepage(content):
# """
# Parses a single page and its contents into a BeautifulSoup object
#
# :param content: bytearray
# :return soup: object
# """
# soup = BeautifulSoup(content, 'lxml')
# return soup
#
# def get_ns(key):
# """
# Gets a news_source filtered by key
# :param key: the key of the news source (e.g: g1, uol, etc.)
# :return: the news source object
# """
# ns = NewsSource.query.filter_by(
# key=key).first() # Fetch news source by key
# return ns
, which may include functions, classes, or code. Output only the next line. | response, content = getpage(ns.url) # Download the page |
Given the code snippet: <|code_start|> :param soup: the BeautifulSoup object
:return: a list with the most read news from the Rock Bizz page
"""
news = []
ns = get_ns('m_bizz')
main = soup.find('main', id='main')
articles = main.find_all('article')
for article in articles:
title = article.a.string
link = article.a['href']
news.append(dict(title=title, link=link))
return news
# Strategy Pattern - a dictionary of functions. Key: the name of the News Source. Value: the Function to execute
strategies = dict(m_rs=__m_rs, m_bizz=__m_rockbizz)
def get_most_read(key):
"""
Gets the most read news from a given page
:param key: the key of the source page (e.g: g1)
:return: a list with the most read news from the page and the name of news source
"""
ns = get_ns(key)
response, content = getpage(ns.url) # Download the page
<|code_end|>
, generate the next line using the imports in this file:
from app.aml_utils import getpage, parsepage, get_ns
and context (functions, classes, or occasionally code) from other files:
# Path: app/aml_utils.py
# def getpage(url):
# """
# Downloads the html page
#
# :rtype: tuple
# :param url: the page address
# :return: the header response and contents (bytes) of the page
# """
# http = httplib2.Http('.cache', disable_ssl_certificate_validation=True)
# headers = {
# 'User-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36'}
#
# response, content = http.request(url, headers=headers)
# return response, content
#
# def parsepage(content):
# """
# Parses a single page and its contents into a BeautifulSoup object
#
# :param content: bytearray
# :return soup: object
# """
# soup = BeautifulSoup(content, 'lxml')
# return soup
#
# def get_ns(key):
# """
# Gets a news_source filtered by key
# :param key: the key of the news source (e.g: g1, uol, etc.)
# :return: the news source object
# """
# ns = NewsSource.query.filter_by(
# key=key).first() # Fetch news source by key
# return ns
. Output only the next line. | soup = parsepage(content) # Then we parse it |
Continue the code snippet: <|code_start|>__email__ = "fpedrosa@gmail.com"
"""
def __m_rs(soup):
"""
Gets the most read news from the Rolling Stone page
:param soup: the BeautifulSoup object
:return: a list with the most read news from the Rolling Stone page
"""
news = []
anchors = soup.find('ol', class_='c-trending__list').find_all('a')
for a in anchors:
title = a.text
link = a['href']
news.append(dict(title=title, link=link))
return news
def __m_whiplash(soup):
"""
Gets the most read news from the Whiplash page
:param soup: the BeautifulSoup object
:return: a list with the most read news from the Whiplash page
"""
news = []
<|code_end|>
. Use current file imports:
from app.aml_utils import getpage, parsepage, get_ns
and context (classes, functions, or code) from other files:
# Path: app/aml_utils.py
# def getpage(url):
# """
# Downloads the html page
#
# :rtype: tuple
# :param url: the page address
# :return: the header response and contents (bytes) of the page
# """
# http = httplib2.Http('.cache', disable_ssl_certificate_validation=True)
# headers = {
# 'User-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36'}
#
# response, content = http.request(url, headers=headers)
# return response, content
#
# def parsepage(content):
# """
# Parses a single page and its contents into a BeautifulSoup object
#
# :param content: bytearray
# :return soup: object
# """
# soup = BeautifulSoup(content, 'lxml')
# return soup
#
# def get_ns(key):
# """
# Gets a news_source filtered by key
# :param key: the key of the news source (e.g: g1, uol, etc.)
# :return: the news source object
# """
# ns = NewsSource.query.filter_by(
# key=key).first() # Fetch news source by key
# return ns
. Output only the next line. | ns = get_ns('m_whiplash') |
Next line prediction: <|code_start|> """
Gets the most read news from the Grande Premio page
:param soup: the BeautifulSoup object
:return: a list with the most read news from the Grande Premio page
"""
news = []
ns = get_ns('e_gp')
divs = soup.find_all('div', class_='bloco-trending')
for div in divs:
link = ns.url + div.parent['href']
title = div.find('div', class_='titulo').string
news.append(dict(title=title, link=link))
return news
# Strategy Pattern - a dictionary of functions. Key: the name of the News Source. Value: the Function to execute
strategies = dict(e_fox_br=__e_fox_br, e_lance=__e_lance, e_gp=__e_gp)
def get_most_read(key):
"""
Gets the most read news from a given page
:param key: the key of the source page (e.g: g1)
:return: a list with the most read news from the page and the name of news source
"""
ns = get_ns(key)
<|code_end|>
. Use current file imports:
(from app.aml_utils import getpage, parsepage, get_ns)
and context including class names, function names, or small code snippets from other files:
# Path: app/aml_utils.py
# def getpage(url):
# """
# Downloads the html page
#
# :rtype: tuple
# :param url: the page address
# :return: the header response and contents (bytes) of the page
# """
# http = httplib2.Http('.cache', disable_ssl_certificate_validation=True)
# headers = {
# 'User-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36'}
#
# response, content = http.request(url, headers=headers)
# return response, content
#
# def parsepage(content):
# """
# Parses a single page and its contents into a BeautifulSoup object
#
# :param content: bytearray
# :return soup: object
# """
# soup = BeautifulSoup(content, 'lxml')
# return soup
#
# def get_ns(key):
# """
# Gets a news_source filtered by key
# :param key: the key of the news source (e.g: g1, uol, etc.)
# :return: the news source object
# """
# ns = NewsSource.query.filter_by(
# key=key).first() # Fetch news source by key
# return ns
. Output only the next line. | response, content = getpage(ns.url) # Download the page |
Continue the code snippet: <|code_start|> Gets the most read news from the Grande Premio page
:param soup: the BeautifulSoup object
:return: a list with the most read news from the Grande Premio page
"""
news = []
ns = get_ns('e_gp')
divs = soup.find_all('div', class_='bloco-trending')
for div in divs:
link = ns.url + div.parent['href']
title = div.find('div', class_='titulo').string
news.append(dict(title=title, link=link))
return news
# Strategy Pattern - a dictionary of functions. Key: the name of the News Source. Value: the Function to execute
strategies = dict(e_fox_br=__e_fox_br, e_lance=__e_lance, e_gp=__e_gp)
def get_most_read(key):
"""
Gets the most read news from a given page
:param key: the key of the source page (e.g: g1)
:return: a list with the most read news from the page and the name of news source
"""
ns = get_ns(key)
response, content = getpage(ns.url) # Download the page
<|code_end|>
. Use current file imports:
from app.aml_utils import getpage, parsepage, get_ns
and context (classes, functions, or code) from other files:
# Path: app/aml_utils.py
# def getpage(url):
# """
# Downloads the html page
#
# :rtype: tuple
# :param url: the page address
# :return: the header response and contents (bytes) of the page
# """
# http = httplib2.Http('.cache', disable_ssl_certificate_validation=True)
# headers = {
# 'User-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36'}
#
# response, content = http.request(url, headers=headers)
# return response, content
#
# def parsepage(content):
# """
# Parses a single page and its contents into a BeautifulSoup object
#
# :param content: bytearray
# :return soup: object
# """
# soup = BeautifulSoup(content, 'lxml')
# return soup
#
# def get_ns(key):
# """
# Gets a news_source filtered by key
# :param key: the key of the news source (e.g: g1, uol, etc.)
# :return: the news source object
# """
# ns = NewsSource.query.filter_by(
# key=key).first() # Fetch news source by key
# return ns
. Output only the next line. | soup = parsepage(content) # Then we parse it |
Given the following code snippet before the placeholder: <|code_start|>"""
news_source_sports.py: Scraping functions for the most read News Sources of the Sports Category
__author__ = "Fernando P. Lopes"
__email__ = "fpedrosa@gmail.com"
"""
def __e_fox_br(soup):
"""
Gets the most read news from the Fox Sports page
:param soup: the BeautifulSoup object
:return: a list with the most read news from the Fox Sports page
"""
news = []
<|code_end|>
, predict the next line using imports from the current file:
from app.aml_utils import getpage, parsepage, get_ns
and context including class names, function names, and sometimes code from other files:
# Path: app/aml_utils.py
# def getpage(url):
# """
# Downloads the html page
#
# :rtype: tuple
# :param url: the page address
# :return: the header response and contents (bytes) of the page
# """
# http = httplib2.Http('.cache', disable_ssl_certificate_validation=True)
# headers = {
# 'User-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36'}
#
# response, content = http.request(url, headers=headers)
# return response, content
#
# def parsepage(content):
# """
# Parses a single page and its contents into a BeautifulSoup object
#
# :param content: bytearray
# :return soup: object
# """
# soup = BeautifulSoup(content, 'lxml')
# return soup
#
# def get_ns(key):
# """
# Gets a news_source filtered by key
# :param key: the key of the news source (e.g: g1, uol, etc.)
# :return: the news source object
# """
# ns = NewsSource.query.filter_by(
# key=key).first() # Fetch news source by key
# return ns
. Output only the next line. | ns = get_ns('e_fox_br') |
Continue the code snippet: <|code_start|> Gets the most read news from the Área Vip page
:param soup: the BeautifulSoup object
:return: a list with the most read news from the Área Vip page
"""
news = []
divs = soup.find_all('div', class_='td-block-span12')
for d in divs[:3]:
a = d.find(anchor_has_no_class)
title = a['title']
link = a['href']
news.append(dict(title=title, link=link))
return news
# Strategy Pattern - a dictionary of functions. Key: the name of the News Source. Value: the Function to execute
strategies = dict(en_ego=__en_ego, en_fuxico=__en_fuxico, en_contigo=__en_contigo, en_tititi=__en_tititi,
en_vip=__en_vip, en_omelete=__en_omelete, en_nerd=__en_nerd)
def get_most_read(key):
"""
Gets the most read news from a given page
:param key: the key of the source page (e.g: g1)
:return: a list with the most read news from the page and the name of news source
"""
ns = get_ns(key)
<|code_end|>
. Use current file imports:
from app.aml_utils import getpage, parsepage, get_ns, anchor_has_no_class
and context (classes, functions, or code) from other files:
# Path: app/aml_utils.py
# def getpage(url):
# """
# Downloads the html page
#
# :rtype: tuple
# :param url: the page address
# :return: the header response and contents (bytes) of the page
# """
# http = httplib2.Http('.cache', disable_ssl_certificate_validation=True)
# headers = {
# 'User-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36'}
#
# response, content = http.request(url, headers=headers)
# return response, content
#
# def parsepage(content):
# """
# Parses a single page and its contents into a BeautifulSoup object
#
# :param content: bytearray
# :return soup: object
# """
# soup = BeautifulSoup(content, 'lxml')
# return soup
#
# def get_ns(key):
# """
# Gets a news_source filtered by key
# :param key: the key of the news source (e.g: g1, uol, etc.)
# :return: the news source object
# """
# ns = NewsSource.query.filter_by(
# key=key).first() # Fetch news source by key
# return ns
#
# def anchor_has_no_class(tag):
# """
# Helper function. Checks if an anchor tag has class attribute
#
# :param tag: an HTML tag
# :return: boolean value
# """
# return not tag.has_attr('class') and tag.name == 'a'
. Output only the next line. | response, content = getpage(ns.url) # Download the page |
Based on the snippet: <|code_start|> :param soup: the BeautifulSoup object
:return: a list with the most read news from the Área Vip page
"""
news = []
divs = soup.find_all('div', class_='td-block-span12')
for d in divs[:3]:
a = d.find(anchor_has_no_class)
title = a['title']
link = a['href']
news.append(dict(title=title, link=link))
return news
# Strategy Pattern - a dictionary of functions. Key: the name of the News Source. Value: the Function to execute
strategies = dict(en_ego=__en_ego, en_fuxico=__en_fuxico, en_contigo=__en_contigo, en_tititi=__en_tititi,
en_vip=__en_vip, en_omelete=__en_omelete, en_nerd=__en_nerd)
def get_most_read(key):
"""
Gets the most read news from a given page
:param key: the key of the source page (e.g: g1)
:return: a list with the most read news from the page and the name of news source
"""
ns = get_ns(key)
response, content = getpage(ns.url) # Download the page
<|code_end|>
, predict the immediate next line with the help of imports:
from app.aml_utils import getpage, parsepage, get_ns, anchor_has_no_class
and context (classes, functions, sometimes code) from other files:
# Path: app/aml_utils.py
# def getpage(url):
# """
# Downloads the html page
#
# :rtype: tuple
# :param url: the page address
# :return: the header response and contents (bytes) of the page
# """
# http = httplib2.Http('.cache', disable_ssl_certificate_validation=True)
# headers = {
# 'User-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36'}
#
# response, content = http.request(url, headers=headers)
# return response, content
#
# def parsepage(content):
# """
# Parses a single page and its contents into a BeautifulSoup object
#
# :param content: bytearray
# :return soup: object
# """
# soup = BeautifulSoup(content, 'lxml')
# return soup
#
# def get_ns(key):
# """
# Gets a news_source filtered by key
# :param key: the key of the news source (e.g: g1, uol, etc.)
# :return: the news source object
# """
# ns = NewsSource.query.filter_by(
# key=key).first() # Fetch news source by key
# return ns
#
# def anchor_has_no_class(tag):
# """
# Helper function. Checks if an anchor tag has class attribute
#
# :param tag: an HTML tag
# :return: boolean value
# """
# return not tag.has_attr('class') and tag.name == 'a'
. Output only the next line. | soup = parsepage(content) # Then we parse it |
Predict the next line for this snippet: <|code_start|>
def __en_fuxico(soup):
"""
Gets the most read news from the Fuxico page
:param soup: the BeautifulSoup object
:return: a list with the most read news from the Fuxico page
"""
news = []
links = soup.find_all('a', class_='news-box-link')
# Limit to 10 news
i = 0
for link in links:
title = link.h2.string
news.append(dict(title=title, link=link['href']))
i += 1
if i == 10:
break
return news
def __en_contigo(soup):
"""
Gets the most read news from the Contigo page
:param soup: the BeautifulSoup object
:return: a list with the most read news from the Contigo page
"""
# DEPRECATED
news = []
<|code_end|>
with the help of current file imports:
from app.aml_utils import getpage, parsepage, get_ns, anchor_has_no_class
and context from other files:
# Path: app/aml_utils.py
# def getpage(url):
# """
# Downloads the html page
#
# :rtype: tuple
# :param url: the page address
# :return: the header response and contents (bytes) of the page
# """
# http = httplib2.Http('.cache', disable_ssl_certificate_validation=True)
# headers = {
# 'User-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36'}
#
# response, content = http.request(url, headers=headers)
# return response, content
#
# def parsepage(content):
# """
# Parses a single page and its contents into a BeautifulSoup object
#
# :param content: bytearray
# :return soup: object
# """
# soup = BeautifulSoup(content, 'lxml')
# return soup
#
# def get_ns(key):
# """
# Gets a news_source filtered by key
# :param key: the key of the news source (e.g: g1, uol, etc.)
# :return: the news source object
# """
# ns = NewsSource.query.filter_by(
# key=key).first() # Fetch news source by key
# return ns
#
# def anchor_has_no_class(tag):
# """
# Helper function. Checks if an anchor tag has class attribute
#
# :param tag: an HTML tag
# :return: boolean value
# """
# return not tag.has_attr('class') and tag.name == 'a'
, which may contain function names, class names, or code. Output only the next line. | ns = get_ns('en_contigo') |
Given snippet: <|code_start|> """
Gets the most read news from the Tititi page
:param soup: the BeautifulSoup object
:return: a list with the most read news from the Tititi page
"""
# DEPRECATED
news = []
ns = get_ns('en_tititi')
anchors = soup.find('div', class_='box mais-lidas clearfix').find_all('a')
for a in anchors:
title = a.p.string
link = ns.url + a['href']
news.append(dict(title=title, link=link))
return news
def __en_vip(soup):
"""
Gets the most read news from the Área Vip page
:param soup: the BeautifulSoup object
:return: a list with the most read news from the Área Vip page
"""
news = []
divs = soup.find_all('div', class_='td-block-span12')
for d in divs[:3]:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from app.aml_utils import getpage, parsepage, get_ns, anchor_has_no_class
and context:
# Path: app/aml_utils.py
# def getpage(url):
# """
# Downloads the html page
#
# :rtype: tuple
# :param url: the page address
# :return: the header response and contents (bytes) of the page
# """
# http = httplib2.Http('.cache', disable_ssl_certificate_validation=True)
# headers = {
# 'User-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36'}
#
# response, content = http.request(url, headers=headers)
# return response, content
#
# def parsepage(content):
# """
# Parses a single page and its contents into a BeautifulSoup object
#
# :param content: bytearray
# :return soup: object
# """
# soup = BeautifulSoup(content, 'lxml')
# return soup
#
# def get_ns(key):
# """
# Gets a news_source filtered by key
# :param key: the key of the news source (e.g: g1, uol, etc.)
# :return: the news source object
# """
# ns = NewsSource.query.filter_by(
# key=key).first() # Fetch news source by key
# return ns
#
# def anchor_has_no_class(tag):
# """
# Helper function. Checks if an anchor tag has class attribute
#
# :param tag: an HTML tag
# :return: boolean value
# """
# return not tag.has_attr('class') and tag.name == 'a'
which might include code, classes, or functions. Output only the next line. | a = d.find(anchor_has_no_class) |
Given snippet: <|code_start|>def __re_any(subreddit):
"""
Gets the most read entries of the Ask Reddit/TIL/IAmA subreddits from the last 24 hours
:param soup: the BeautifulSoup object
:return: a list with the most read news from the Ask Reddit page
"""
posts = []
base_url = f'https://www.reddit.com/r/{subreddit}/{listing}.json?limit={limit}&t={timeframe}'
request = requests.get(base_url, headers={'User-agent': 'asmaislidas'})
json_data = request.json()
for post in json_data['data']['children']:
title = post['data']['title']
link = 'https://www.reddit.com' + post['data']['permalink']
posts.append(dict(title=title, link=link))
return posts
# Strategy Pattern - a dictionary of functions. Key: the name of the News Source. Value: the Function to execute
strategies=dict(re_ask=__re_any, re_science=__re_any, re_life=__re_any, re_world=__re_any, re_til=__re_any, re_iama=__re_any, re_aww=__re_any,
re_bros=__re_any, re_derps=__re_any, re_interestingasfuck=__re_any, re_damnthatsinteresting=__re_any, re_nextfuckinglevel=__re_any)
def get_most_read(key):
"""
Gets the most read news from a given page
:param key: the key of the source page (e.g: g1)
:return: a list with the most read news from the page and the name of news source
"""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from app.aml_utils import getpage, parsepage, get_ns
import requests
and context:
# Path: app/aml_utils.py
# def getpage(url):
# """
# Downloads the html page
#
# :rtype: tuple
# :param url: the page address
# :return: the header response and contents (bytes) of the page
# """
# http = httplib2.Http('.cache', disable_ssl_certificate_validation=True)
# headers = {
# 'User-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36'}
#
# response, content = http.request(url, headers=headers)
# return response, content
#
# def parsepage(content):
# """
# Parses a single page and its contents into a BeautifulSoup object
#
# :param content: bytearray
# :return soup: object
# """
# soup = BeautifulSoup(content, 'lxml')
# return soup
#
# def get_ns(key):
# """
# Gets a news_source filtered by key
# :param key: the key of the news source (e.g: g1, uol, etc.)
# :return: the news source object
# """
# ns = NewsSource.query.filter_by(
# key=key).first() # Fetch news source by key
# return ns
which might include code, classes, or functions. Output only the next line. | ns=get_ns(key) |
Predict the next line for this snippet: <|code_start|>def __ny(soup):
"""
DEPRECATED
Gets the most read news from NY Times page
:param soup: the BeautifulSoup object
:return: a list with the most read news from the NY Times page
"""
news = []
divs = soup.find_all('div', class_='story')
for d in divs[:10]:
link = d.h3.a['href']
title = d.h3.a.string
news.append(dict(title=title, link=link))
return news
# Strategy Pattern - a dictionary of functions. Key: the name of the News Source. Value: the Function to execute
strategies = dict(fox=__fox, wp=__wp, tg=__tg, lf=__lf, tt=__tt, ep=__ep, ny=__ny, reu=__reu)
def get_most_read(key):
"""
Gets the most read news from a given page
:param key: the key of the source page (e.g: g1)
:return: a list with the most read news from the page and the name of news source
"""
ns = get_ns(key)
<|code_end|>
with the help of current file imports:
from app.aml_utils import getpage, parsepage, get_ns
and context from other files:
# Path: app/aml_utils.py
# def getpage(url):
# """
# Downloads the html page
#
# :rtype: tuple
# :param url: the page address
# :return: the header response and contents (bytes) of the page
# """
# http = httplib2.Http('.cache', disable_ssl_certificate_validation=True)
# headers = {
# 'User-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36'}
#
# response, content = http.request(url, headers=headers)
# return response, content
#
# def parsepage(content):
# """
# Parses a single page and its contents into a BeautifulSoup object
#
# :param content: bytearray
# :return soup: object
# """
# soup = BeautifulSoup(content, 'lxml')
# return soup
#
# def get_ns(key):
# """
# Gets a news_source filtered by key
# :param key: the key of the news source (e.g: g1, uol, etc.)
# :return: the news source object
# """
# ns = NewsSource.query.filter_by(
# key=key).first() # Fetch news source by key
# return ns
, which may contain function names, class names, or code. Output only the next line. | response, content = getpage(ns.url) # Download the page |
Based on the snippet: <|code_start|> """
DEPRECATED
Gets the most read news from NY Times page
:param soup: the BeautifulSoup object
:return: a list with the most read news from the NY Times page
"""
news = []
divs = soup.find_all('div', class_='story')
for d in divs[:10]:
link = d.h3.a['href']
title = d.h3.a.string
news.append(dict(title=title, link=link))
return news
# Strategy Pattern - a dictionary of functions. Key: the name of the News Source. Value: the Function to execute
strategies = dict(fox=__fox, wp=__wp, tg=__tg, lf=__lf, tt=__tt, ep=__ep, ny=__ny, reu=__reu)
def get_most_read(key):
"""
Gets the most read news from a given page
:param key: the key of the source page (e.g: g1)
:return: a list with the most read news from the page and the name of news source
"""
ns = get_ns(key)
response, content = getpage(ns.url) # Download the page
<|code_end|>
, predict the immediate next line with the help of imports:
from app.aml_utils import getpage, parsepage, get_ns
and context (classes, functions, sometimes code) from other files:
# Path: app/aml_utils.py
# def getpage(url):
# """
# Downloads the html page
#
# :rtype: tuple
# :param url: the page address
# :return: the header response and contents (bytes) of the page
# """
# http = httplib2.Http('.cache', disable_ssl_certificate_validation=True)
# headers = {
# 'User-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36'}
#
# response, content = http.request(url, headers=headers)
# return response, content
#
# def parsepage(content):
# """
# Parses a single page and its contents into a BeautifulSoup object
#
# :param content: bytearray
# :return soup: object
# """
# soup = BeautifulSoup(content, 'lxml')
# return soup
#
# def get_ns(key):
# """
# Gets a news_source filtered by key
# :param key: the key of the news source (e.g: g1, uol, etc.)
# :return: the news source object
# """
# ns = NewsSource.query.filter_by(
# key=key).first() # Fetch news source by key
# return ns
. Output only the next line. | soup = parsepage(content) # Then we parse it |
Next line prediction: <|code_start|> link = a['href']
title = a.text
news.append(dict(title=title, link=link))
return news
def __lf(soup):
"""
Gets the most read news from the Le Figaro page
:param soup: the BeautifulSoup object
:return: a list with the most read news from the Le Figaro page
"""
news = []
anchors = soup.find('div', class_='fig-toparticles__main').find_all('a')
for a in anchors:
link = a['href']
title = a.text
news.append(dict(title=title, link=link))
return news
def __tt(soup):
"""
Gets the most read news from The Telegraph page
:param soup: the BeautifulSoup object
:return: a list with the most read news from the The Telegraph page
"""
# DEPRECATED - Can't access source code due to script
news = []
<|code_end|>
. Use current file imports:
(from app.aml_utils import getpage, parsepage, get_ns)
and context including class names, function names, or small code snippets from other files:
# Path: app/aml_utils.py
# def getpage(url):
# """
# Downloads the html page
#
# :rtype: tuple
# :param url: the page address
# :return: the header response and contents (bytes) of the page
# """
# http = httplib2.Http('.cache', disable_ssl_certificate_validation=True)
# headers = {
# 'User-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36'}
#
# response, content = http.request(url, headers=headers)
# return response, content
#
# def parsepage(content):
# """
# Parses a single page and its contents into a BeautifulSoup object
#
# :param content: bytearray
# :return soup: object
# """
# soup = BeautifulSoup(content, 'lxml')
# return soup
#
# def get_ns(key):
# """
# Gets a news_source filtered by key
# :param key: the key of the news source (e.g: g1, uol, etc.)
# :return: the news source object
# """
# ns = NewsSource.query.filter_by(
# key=key).first() # Fetch news source by key
# return ns
. Output only the next line. | ns = get_ns('tt') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.