Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given snippet: <|code_start|> for i in range(self.record_count): flow_format = u.unpack_uint() flow_head = u.unpack_opaque() flow_u = xdrlib.Unpacker(flow_head) d = flows.getDecoder(flow_format) if d: self.flows[flow_format] = d(flow_u) class CounterSample(object): def __init__(self, u): self.size = u.unpack_uint() self.sequence = u.unpack_uint() self.source_id = u.unpack_uint() self.record_count = u.unpack_uint() self.counters = {} for i in range(self.record_count): counter_format = u.unpack_uint() counter = u.unpack_opaque() d = counters.getDecoder(counter_format) if d: self.counters[counter_format] = d(xdrlib.Unpacker(counter)) else: <|code_end|> , continue by predicting the next line. Consider current file imports: import xdrlib from tensor.protocol.sflow.protocol import flows, counters and context: # Path: tensor/protocol/sflow/protocol/flows.py # class IPv4Header(object): # class ISO8023Header(object): # class IPv6Header(object): # class IEEE80211MACHeader(object): # class PPPHeader(object): # class HeaderSample(object): # class EthernetSample(object): # class IPV4Sample(object): # class IPV6Sample(object): # class SwitchSample(object): # class RouterSample(object): # class GatewaySample(object): # class UserSample(object): # class URLSample(object): # class MPLSSample(object): # class NATSample(object): # class MPLSTunnelSample(object): # class MPLSVCSample(object): # class MPLSFTNSample(object): # class MPLSLDPFECSample(object): # class VLANTunnelSample(object): # def __init__(self, data): # def __init__(self, data): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def getDecoder(format): # # Path: tensor/protocol/sflow/protocol/counters.py # class InterfaceCounters(object): # class EthernetCounters(object): # class VLANCounters(object): # class TokenringCounters(object): # class VGCounters(object): # class HostCounters(object): # class HostAdapters(object): # class HostParent(object): # class HostCPUCounters(object): # class HostMemoryCounters(object): # class DiskIOCounters(object): # class NetIOCounters(object): # class SocketIPv4Counters(object): # class SocketIPv6Counters(object): # class VirtMemoryCounters(object): # class VirtDiskIOCounters(object): # class VirtNetIOCounters(object): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def getDecoder(format): which might include code, classes, or functions. Output only the next line.
print("Unknown format:", counter_format)
Continue the code snippet: <|code_start|> class Sflow(object): def __init__(self, payload, host): self.host = host assert isinstance(payload, bytes) u = xdrlib.Unpacker(payload) self.version = u.unpack_uint() self.samplers = { 1: FlowSample, 2: CounterSample } if self.version == 5: self.sflow_v5(u) def sflow_v5(self, u): self.addrtype = u.unpack_uint() if self.addrtype == 1: self.address = u.unpack_fstring(4) if self.addrtype == 2: <|code_end|> . Use current file imports: import xdrlib from tensor.protocol.sflow.protocol import flows, counters and context (classes, functions, or code) from other files: # Path: tensor/protocol/sflow/protocol/flows.py # class IPv4Header(object): # class ISO8023Header(object): # class IPv6Header(object): # class IEEE80211MACHeader(object): # class PPPHeader(object): # class HeaderSample(object): # class EthernetSample(object): # class IPV4Sample(object): # class IPV6Sample(object): # class SwitchSample(object): # class RouterSample(object): # class GatewaySample(object): # class UserSample(object): # class URLSample(object): # class MPLSSample(object): # class NATSample(object): # class MPLSTunnelSample(object): # class MPLSVCSample(object): # class MPLSFTNSample(object): # class MPLSLDPFECSample(object): # class VLANTunnelSample(object): # def __init__(self, data): # def __init__(self, data): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def getDecoder(format): # # Path: tensor/protocol/sflow/protocol/counters.py # class InterfaceCounters(object): # class EthernetCounters(object): # class VLANCounters(object): # class TokenringCounters(object): # class VGCounters(object): # class HostCounters(object): # class HostAdapters(object): # class HostParent(object): # class HostCPUCounters(object): # class HostMemoryCounters(object): # class DiskIOCounters(object): # class NetIOCounters(object): # class SocketIPv4Counters(object): # class SocketIPv6Counters(object): # class VirtMemoryCounters(object): # class VirtDiskIOCounters(object): # class VirtNetIOCounters(object): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def __init__(self, u): # def getDecoder(format): . Output only the next line.
self.address = u.unpack_fstring(16)
Given the following code snippet before the placeholder: <|code_start|> print(ethernet.type, repr(data)) class IPv6Header(object): def __init__(self, u): pass class IEEE80211MACHeader(object): def __init__(self, u): pass class PPPHeader(object): def __init__(self, u): pass class HeaderSample(object): def __init__(self, u): self.protocol = u.unpack_uint() self.frame_len = u.unpack_uint() self.payload_removed = u.unpack_uint() self.sample_header = u.unpack_string() self.samplers = { 1: ISO8023Header, 7: PPPHeader, 11: IPv4Header, 12: IPv6Header } <|code_end|> , predict the next line using imports from the current file: from construct import * from construct.adapters import MappingError from tensor.protocol.sflow.protocol import utils and context including class names, function names, and sometimes code from other files: # Path: tensor/protocol/sflow/protocol/utils.py # def unpack_address(u): # def __init__(self, addr_int): # def __str__(self): # def asString(self): # def __repr__(self): # class IPv4Address(object): . Output only the next line.
if self.samplers.get(self.protocol):
Predict the next line after this snippet: <|code_start|># # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301, USA. try: gettext.bindtextdomain('gedit-plugins') gettext.textdomain('gedit-plugins') _ = gettext.gettext except: _ = lambda s: s class Preferences(object): LANG_NAME = 0 LANG_CODE = 1 def __init__(self, datadir, get_languages_names_codes): <|code_end|> using the current file's imports: import os import gettext from gi.repository import Gio, Gtk from gpdefs import GETTEXT_PACKAGE from .services.services import Services from .settings import Settings and any relevant context from other files: # Path: plugins/translate/translate/settings.py # class Settings(): # # TRANSLATE_KEY_BASE = 'org.gnome.gedit.plugins.translate' # OUTPUT_TO_DOCUMENT = 'output-to-document' # LANGUAGE_PAIR = 'language-pair' # SERVICE = 'service' # API_KEY = 'api-key' # APERTIUM_SERVER_KEY = 'apertium-server' # # def __init__(self): # self._settings = Gio.Settings.new(self.TRANSLATE_KEY_BASE) # # def get_language_pair(self): # return self._settings.get_string(self.LANGUAGE_PAIR) # # def get_service(self): # return self._settings.get_uint(self.SERVICE) # # def get_apikey(self): # return self._settings.get_string(self.API_KEY) # # def get_output_document(self): # return self._settings.get_boolean(self.OUTPUT_TO_DOCUMENT) # # def set_language_pair(self, language_pair): # self._settings.set_string(self.LANGUAGE_PAIR, language_pair) # # def set_service(self, service_id): # self._settings.set_uint(self.SERVICE, service_id) # # def set_apikey(self, text): # self._settings.set_string(self.API_KEY, text) # # def set_output_document(self, document): # self._settings.set_boolean(self.OUTPUT_TO_DOCUMENT, document) # # def get_apertium_server(self): # return self._settings.get_string(self.APERTIUM_SERVER_KEY) . Output only the next line.
self._get_languages_names_codes = get_languages_names_codes
Given snippet: <|code_start|> gettext.bindtextdomain('gedit-plugins') gettext.textdomain('gedit-plugins') _ = gettext.gettext except: _ = lambda s: s class SessionSaverAppActivatable(GObject.Object, Gedit.AppActivatable): app = GObject.Property(type=Gedit.App) __instance = None def __init__(self): GObject.Object.__init__(self) SessionSaverAppActivatable.__instance = self @classmethod def get_instance(cls): return cls.__instance def do_activate(self): self._insert_session_menu() def do_deactivate(self): self.menu_ext = None def _insert_session_menu(self): self.menu_ext = self.extend_menu("tools-section") <|code_end|> , continue by predicting the next line. Consider current file imports: from gi.repository import GObject, Gio, Gedit from .store.xmlsessionstore import XMLSessionStore import gettext and context: # Path: plugins/sessionsaver/sessionsaver/store/xmlsessionstore.py # class XMLSessionStore(SessionStore): # def __init__(self, filename = None): # super(XMLSessionStore, self).__init__() # # if filename is None: # self.filename = os.path.join(GLib.get_user_config_dir(), 'gedit/saved-sessions.xml') # else: # self.filename = filename # # self.load() # # def _escape(self, string): # return string.replace('&', '&amp;') \ # .replace('<', '&lt;') \ # .replace('>', '&gt;') \ # .replace('"', '&quot;') # # def _dump_session(self, session): # files = ''.join([' <file path="%s"/>\n' % self._escape(location.get_uri()) # for location in session.files]) # session_name = self._escape(str(session.name)) # return '<session name="%s">\n%s</session>\n' % (session_name, files) # # def dump(self): # dump = [self._dump_session(session) for session in self] # return '<saved-sessions>\n%s</saved-sessions>\n' % ''.join(dump) # # def save(self): # dirname = os.path.dirname(self.filename) # if not os.path.isdir(dirname): # os.makedirs(dirname) # # fp = open(self.filename, "wb") # fp.write(bytes('<?xml version="1.0" encoding="UTF-8"?>\n','UTF-8')) # fp.write(bytes(self.dump(),'UTF-8')) # fp.close() # # def load(self): # if not os.path.isfile(self.filename): # return # # parser = expat.ParserCreate('UTF-8') # parser.buffer_text = True # parser.StartElementHandler = self._expat_start_handler # parser.EndElementHandler = self._expat_end_handler # # self._current_session = None # try: # parser.ParseFile(open(self.filename, 'rb')) # except: # return # del self._current_session # # def _expat_start_handler(self, tag, attr): # if tag == 'file': # assert self._current_session is not None # self._current_session.add_file(str(attr['path'])) # elif tag == 'session': # assert self._current_session is None # self._current_session = Session(attr['name']) # # def _expat_end_handler(self, tag): # if tag == 'session': # self.add(self._current_session) # self._current_session = None which might include code, classes, or functions. Output only the next line.
item = Gio.MenuItem.new(_("_Manage Saved Sessions…"), "win.managedsession")
Given the code snippet: <|code_start|> def get_default_language_codes(self): return 'en|es' def get_api_hint(self): return _("You need to obtain an API key at <a href='https://yandex.com/dev/translate/'>https://yandex.com/dev/translate/</a>") def has_api_key(self): return True def set_api_key(self, key): self._key = key def set_server(self, server): pass def init(self): self._fetch_remote_language_names() def get_language_names(self): if len(Yandex.g_language_codes) > 0 and len(Yandex.g_language_names) > 0: return Yandex.g_language_names return self.DEFAULT_LANGUAGE_NAMES def get_language_codes(self): if len(Yandex.g_language_codes) > 0 and len(Yandex.g_language_names) > 0: return Yandex.g_language_codes return self.DEFAULT_LANGUAGE_CODES <|code_end|> , generate the next line using the imports in this file: import urllib.request, urllib.parse, urllib.error import json import gettext from .service import Service and context (functions, classes, or occasionally code) from other files: # Path: plugins/translate/translate/services/service.py # class Service(metaclass=ABCMeta): # # @abstractmethod # def translate_text(self, text, language_pair): # pass # # @abstractmethod # def get_language_names(self): # pass # # @abstractmethod # def get_language_codes(self): # pass # # @abstractmethod # def get_language_pair_name(self, source, target, locales_names=None): # pass # # @abstractmethod # def get_default_language_codes(self): # pass # # @abstractmethod # def has_api_key(self): # pass # # @abstractmethod # def get_api_hint(self): # pass # # @abstractmethod # def set_api_key(self, key): # pass # # @abstractmethod # def set_server(self, server): # pass . Output only the next line.
def get_language_pair_name(self, source, target, locales_names=None):
Using the snippet: <|code_start|> dirname = os.path.dirname(self.filename) if not os.path.isdir(dirname): os.makedirs(dirname) fp = open(self.filename, "wb") fp.write(bytes('<?xml version="1.0" encoding="UTF-8"?>\n','UTF-8')) fp.write(bytes(self.dump(),'UTF-8')) fp.close() def load(self): if not os.path.isfile(self.filename): return parser = expat.ParserCreate('UTF-8') parser.buffer_text = True parser.StartElementHandler = self._expat_start_handler parser.EndElementHandler = self._expat_end_handler self._current_session = None try: parser.ParseFile(open(self.filename, 'rb')) except: return del self._current_session def _expat_start_handler(self, tag, attr): if tag == 'file': assert self._current_session is not None self._current_session.add_file(str(attr['path'])) elif tag == 'session': <|code_end|> , determine the next line of code. You have imports: import os.path from xml.parsers import expat from gi.repository import GLib from .sessionstore import SessionStore from .session import Session and context (class names, function names, or code) available: # Path: plugins/sessionsaver/sessionsaver/store/sessionstore.py # class SessionStore(GObject.Object): # __gsignals__ = { # "session-added": (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, # (GObject.TYPE_PYOBJECT,)), # "session-changed": (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, # (GObject.TYPE_PYOBJECT,)), # "session-removed": (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, # (GObject.TYPE_PYOBJECT,)) # } # # def __init__(self): # super(SessionStore, self).__init__() # self._sessions = [] # # def __iter__(self): # return iter(self._sessions) # # def __getitem__(self, index): # return self._sessions[index] # # def __getslice__(self, i, j): # return self._sessions[i:j] # # def __len__(self): # return len(self._sessions) # # def do_session_added(self, session): # self._sessions.append(session) # self._sessions.sort() # # def do_session_changed(self, session): # index = self._sessions.index(session) # self._sessions[index] = session # # def add(self, session): # assert isinstance(session, Session) # # if session in self: # self.emit('session-changed', session) # else: # self.emit('session-added', session) # # def do_session_removed(self, session): # self._sessions.remove(session) # # def remove(self, session): # assert isinstance(session, Session) # if session in self: # self.emit('session-removed', session) # # def index(self, session): # return self._sessions.index(session) # # Path: plugins/sessionsaver/sessionsaver/store/session.py # class Session(object): # def __init__(self, name, files = None): # super(Session, self).__init__() # self.name = name # if files is None: # files = [] # self.files = files # # def __lt__(self, session): # return (self.name.lower() < session.name.lower()) # # def __eq__(self, session): # return (self.name.lower() == session.name.lower()) # # def add_file(self, filename): # self.files.append(Gio.file_new_for_uri(filename)) . Output only the next line.
assert self._current_session is None
Predict the next line for this snippet: <|code_start|># along with gedit Session Saver Plugin; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, # Boston, MA 02110-1301 USA class XMLSessionStore(SessionStore): def __init__(self, filename = None): super(XMLSessionStore, self).__init__() if filename is None: self.filename = os.path.join(GLib.get_user_config_dir(), 'gedit/saved-sessions.xml') else: self.filename = filename self.load() def _escape(self, string): return string.replace('&', '&amp;') \ .replace('<', '&lt;') \ .replace('>', '&gt;') \ .replace('"', '&quot;') def _dump_session(self, session): files = ''.join([' <file path="%s"/>\n' % self._escape(location.get_uri()) for location in session.files]) session_name = self._escape(str(session.name)) return '<session name="%s">\n%s</session>\n' % (session_name, files) def dump(self): dump = [self._dump_session(session) for session in self] <|code_end|> with the help of current file imports: import os.path from xml.parsers import expat from gi.repository import GLib from .sessionstore import SessionStore from .session import Session and context from other files: # Path: plugins/sessionsaver/sessionsaver/store/sessionstore.py # class SessionStore(GObject.Object): # __gsignals__ = { # "session-added": (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, # (GObject.TYPE_PYOBJECT,)), # "session-changed": (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, # (GObject.TYPE_PYOBJECT,)), # "session-removed": (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, # (GObject.TYPE_PYOBJECT,)) # } # # def __init__(self): # super(SessionStore, self).__init__() # self._sessions = [] # # def __iter__(self): # return iter(self._sessions) # # def __getitem__(self, index): # return self._sessions[index] # # def __getslice__(self, i, j): # return self._sessions[i:j] # # def __len__(self): # return len(self._sessions) # # def do_session_added(self, session): # self._sessions.append(session) # self._sessions.sort() # # def do_session_changed(self, session): # index = self._sessions.index(session) # self._sessions[index] = session # # def add(self, session): # assert isinstance(session, Session) # # if session in self: # self.emit('session-changed', session) # else: # self.emit('session-added', session) # # def do_session_removed(self, session): # self._sessions.remove(session) # # def remove(self, session): # assert isinstance(session, Session) # if session in self: # self.emit('session-removed', session) # # def index(self, session): # return self._sessions.index(session) # # Path: plugins/sessionsaver/sessionsaver/store/session.py # class Session(object): # def __init__(self, name, files = None): # super(Session, self).__init__() # self.name = name # if files is None: # files = [] # self.files = files # # def __lt__(self, session): # return (self.name.lower() < session.name.lower()) # # def __eq__(self, session): # return (self.name.lower() == session.name.lower()) # # def add_file(self, filename): # self.files.append(Gio.file_new_for_uri(filename)) , which may contain function names, class names, or code. Output only the next line.
return '<saved-sessions>\n%s</saved-sessions>\n' % ''.join(dump)
Here is a snippet: <|code_start|> del self._highlight_tag def update_location(self): gfile = self._doc.get_file().get_location() if gfile is None: return if self.gfile is None or gfile.get_uri() != self.gfile.get_uri(): SynctexWindowActivatable.view_dict[gfile.get_uri()] = self self.gfile = gfile modeline_output_file = self.get_output_file() if modeline_output_file is not None: filename = modeline_output_file else: filename = self.gfile.get_basename() out_path = self.gfile.get_parent().get_child(filename).get_path() out_path = os.path.splitext(out_path) out_gfile = Gio.file_new_for_path(out_path[0] + ".pdf") if out_gfile.query_exists(None): self.out_gfile = out_gfile else: self.out_gfile = None self.update_active() <|code_end|> . Write the next line using the current file imports: from gi.repository import GObject, Pango, Gtk, Gedit, Peas, PeasGtk, Gio, Gdk from .evince_dbus import EvinceWindowProxy import dbus.mainloop.glib import logging import os import re import gettext and context from other files: # Path: plugins/synctex/synctex/evince_dbus.py # class EvinceWindowProxy: # """A DBUS proxy for an Evince Window.""" # daemon = None # bus = None # # def __init__(self, uri, spawn = False, logger = None): # self._log = logger # self.uri = uri # self.spawn = spawn # self.status = CLOSED # self.source_handler = None # self.dbus_name = '' # self._handler = None # try: # if EvinceWindowProxy.bus is None: # EvinceWindowProxy.bus = dbus.SessionBus() # # if EvinceWindowProxy.daemon is None: # EvinceWindowProxy.daemon = EvinceWindowProxy.bus.get_object(EV_DAEMON_NAME, # EV_DAEMON_PATH, # follow_name_owner_changes=True) # EvinceWindowProxy.bus.add_signal_receiver(self._on_doc_loaded, signal_name="DocumentLoaded", # dbus_interface = EV_WINDOW_IFACE, # sender_keyword='sender') # self._get_dbus_name(False) # # except dbus.DBusException: # if self._log: # self._log.debug("Could not connect to the Evince Daemon") # # def _on_doc_loaded(self, uri, **keyargs): # if uri == self.uri and self._handler is None: # self.handle_find_document_reply(keyargs['sender']) # # def _get_dbus_name(self, spawn): # EvinceWindowProxy.daemon.FindDocument(self.uri,spawn, # reply_handler=self.handle_find_document_reply, # error_handler=self.handle_find_document_error, # dbus_interface = EV_DAEMON_IFACE) # # def handle_find_document_error(self, error): # if self._log: # self._log.debug("FindDocument DBus call has failed") # # def handle_find_document_reply(self, evince_name): # if self._handler is not None: # handler = self._handler # else: # handler = self.handle_get_window_list_reply # if evince_name != '': # self.dbus_name = evince_name # self.status = RUNNING # self.evince = EvinceWindowProxy.bus.get_object(self.dbus_name, EVINCE_PATH) # self.evince.GetWindowList(dbus_interface = EVINCE_IFACE, # reply_handler = handler, # error_handler = self.handle_get_window_list_error) # # def handle_get_window_list_error (self, e): # if self._log: # self._log.debug("GetWindowList DBus call has failed") # # def handle_get_window_list_reply (self, window_list): # if len(window_list) > 0: # window_obj = EvinceWindowProxy.bus.get_object(self.dbus_name, window_list[0]) # self.window = dbus.Interface(window_obj,EV_WINDOW_IFACE) # self.window.connect_to_signal("Closed", self.on_window_close) # self.window.connect_to_signal("SyncSource", self.on_sync_source) # else: # #That should never happen. # if self._log: # self._log.debug("GetWindowList returned empty list") # # # def set_source_handler (self, source_handler): # self.source_handler = source_handler # # def on_window_close(self): # self.window = None # self.status = CLOSED # # def on_sync_source(self, input_file, source_link, timestamp): # if self.source_handler is not None: # self.source_handler(input_file, source_link, timestamp) # # def SyncView(self, input_file, data, time): # if self.status == CLOSED: # if self.spawn: # self._tmp_syncview = [input_file, data, time]; # self._handler = self._syncview_handler # self._get_dbus_name(True) # else: # self.window.SyncView(input_file, data, time, dbus_interface = "org.gnome.evince.Window") # # def _syncview_handler(self, window_list): # self.handle_get_window_list_reply(window_list) # # if self.status == CLOSED: # return False # self.window.SyncView(self._tmp_syncview[0],self._tmp_syncview[1], self._tmp_syncview[2], dbus_interface="org.gnome.evince.Window") # del self._tmp_syncview # self._handler = None # return True , which may include functions, classes, or code. Output only the next line.
def _highlight(self):
Using the snippet: <|code_start|> def get_default_language_codes(self): return 'eng|spa' def has_api_key(self): return False def set_api_key(self, key): pass def set_server(self, server): self.server = server def get_api_hint(self): pass def init(self): self._fetch_remote_language_names_and_pairs() def get_language_names(self): if len(Apertium.g_language_codes) > 0 and len(Apertium.g_language_names) > 0: return Apertium.g_language_names return self.DEFAULT_LANGUAGE_NAMES def get_language_codes(self): if len(Apertium.g_language_codes) > 0 and len(Apertium.g_language_names) > 0: return Apertium.g_language_codes return self.DEFAULT_LANGUAGE_CODES <|code_end|> , determine the next line of code. You have imports: import urllib.request, urllib.parse, urllib.error import json import locale from .service import Service and context (class names, function names, or code) available: # Path: plugins/translate/translate/services/service.py # class Service(metaclass=ABCMeta): # # @abstractmethod # def translate_text(self, text, language_pair): # pass # # @abstractmethod # def get_language_names(self): # pass # # @abstractmethod # def get_language_codes(self): # pass # # @abstractmethod # def get_language_pair_name(self, source, target, locales_names=None): # pass # # @abstractmethod # def get_default_language_codes(self): # pass # # @abstractmethod # def has_api_key(self): # pass # # @abstractmethod # def get_api_hint(self): # pass # # @abstractmethod # def set_api_key(self, key): # pass # # @abstractmethod # def set_server(self, server): # pass . Output only the next line.
def _get_lang_from_langcountry(self, language):
Given the following code snippet before the placeholder: <|code_start|> def __init__(self): super(SessionStore, self).__init__() self._sessions = [] def __iter__(self): return iter(self._sessions) def __getitem__(self, index): return self._sessions[index] def __getslice__(self, i, j): return self._sessions[i:j] def __len__(self): return len(self._sessions) def do_session_added(self, session): self._sessions.append(session) self._sessions.sort() def do_session_changed(self, session): index = self._sessions.index(session) self._sessions[index] = session def add(self, session): assert isinstance(session, Session) if session in self: self.emit('session-changed', session) else: <|code_end|> , predict the next line using imports from the current file: import os.path from gi.repository import GObject, GLib, Gio from .session import Session and context including class names, function names, and sometimes code from other files: # Path: plugins/sessionsaver/sessionsaver/store/session.py # class Session(object): # def __init__(self, name, files = None): # super(Session, self).__init__() # self.name = name # if files is None: # files = [] # self.files = files # # def __lt__(self, session): # return (self.name.lower() < session.name.lower()) # # def __eq__(self, session): # return (self.name.lower() == session.name.lower()) # # def add_file(self, filename): # self.files.append(Gio.file_new_for_uri(filename)) . Output only the next line.
self.emit('session-added', session)
Next line prediction: <|code_start|> self.__del__() class SaveSessionDialog(Dialog): def __init__(self, window, sessions, current_session, on_updated_sessions, data_dir): super(SaveSessionDialog, self).__init__('save-session-dialog', data_dir, window) self.NAME_COLUMN = 1 self.on_updated_sessions = on_updated_sessions self.sessions = sessions model = SessionModel(sessions) self.combobox = self['session-name'] self.combobox.set_model(model) self.combobox.set_entry_text_column(self.NAME_COLUMN) self.combobox.connect("changed", self.on_name_combo_changed) if current_session is None: self.on_name_combo_changed(self.combobox) else: self._set_combobox_active_by_name(current_session) self.dialog.connect('response', self.on_response) def _set_combobox_active_by_name(self, option_name): model = self.combobox.get_model() piter = model.get_iter_first() while piter is not None: <|code_end|> . Use current file imports: (from gi.repository import GObject, Gtk, Gedit from gpdefs import GETTEXT_PACKAGE from .store.session import Session import os.path import gettext) and context including class names, function names, or small code snippets from other files: # Path: plugins/sessionsaver/sessionsaver/store/session.py # class Session(object): # def __init__(self, name, files = None): # super(Session, self).__init__() # self.name = name # if files is None: # files = [] # self.files = files # # def __lt__(self, session): # return (self.name.lower() < session.name.lower()) # # def __eq__(self, session): # return (self.name.lower() == session.name.lower()) # # def add_file(self, filename): # self.files.append(Gio.file_new_for_uri(filename)) . Output only the next line.
if model.get_value(piter, self.NAME_COLUMN) == option_name:
Given the code snippet: <|code_start|># # The program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. try: gettext.bindtextdomain('gedit-plugins') gettext.textdomain('gedit-plugins') _ = gettext.gettext except: _ = lambda s: s # Holds style properties for a GtkSourceStyle element class Props: def __init__(self): self.background = None # str self.foreground = None # str self.italic = False self.bold = False self.strikethrough = False <|code_end|> , generate the next line using the imports in this file: import os import sys import collections import tempfile import gettext from xml.etree import ElementTree as ET from gi.repository import Gtk, GdkPixbuf, Gdk, GtkSource, Gio, GLib, Pango from .languages import samples and context (functions, classes, or occasionally code) from other files: # Path: plugins/colorschemer/schemer/languages.py . Output only the next line.
self.underline = False
Next line prediction: <|code_start|> def fetch_cached(self, context): cache_key = self.get_cache_key() user = context['request'].user if not user.is_staff and caching_enabled and cache.has_key(cache_key): cached_value = cache.get(cache_key) rendered_content = cached_value.get('content') sekizai = cached_value.get('sekizai') self._do_restore_sekizai_context(context, sekizai) return rendered_content def set_and_get_cache(self, user, sekizai_diff, content): if not user.is_staff and caching_enabled: value = {'content': content, 'sekizai': sekizai_diff} key = self.get_cache_key() cache.set(key, value, snippet_caching_time) return content def render_pointer(self, context, handle_errors=True): vars_qs = self.variables.select_related('snippet_variable').all() def var_for_context(var): default, overwrite = var.formatted_value, None if allow_inheritance: overwrite = context.get( inherit_variable_pattern.format(identifier=var.pk)) name = var.snippet_variable.name value = overwrite if overwrite is not None else default return (name, value) <|code_end|> . Use current file imports: (import re import logging from django.core.cache import cache from django.db import models from django.core.exceptions import ValidationError from django.template import Template, TemplateSyntaxError, \ TemplateDoesNotExist, loader, VariableDoesNotExist from django.template.loader import render_to_string from django.db.models import signals from django.contrib.sites.models import Site from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible from cms.models import CMSPlugin from sekizai.helpers import ( Watcher as sekizai_context_watcher, get_varname as sekizai_cache_key, ) from .resources_processor import get_resources from .settings import ( snippet_caching_time, caching_enabled, allow_inheritance, inherit_variable_pattern) from widgets_pool import widget_pool) and context including class names, function names, or small code snippets from other files: # Path: smartsnippets/resources_processor.py # def get_resources(resources_data): # """ # Parses resources_data to get all resources defined with # the following format: # snippet-field/custom.html, static: admin/style.css, # http://somesite/absolute-url.js # and returns a dictionary with resources extensions and the links defined. # """ # if not resources_data: # return {} # resources_data = resources_data or '' # resources = defaultdict(list) # for resource in resources_data.split(','): # processed_link = _process(resource) # if not processed_link: # continue # links = resources[processed_link[0]] # res_link = processed_link[1] # # check if already added. Note: using list and not set just to # # make sure the ordering is kept # if res_link not in links: # links.append(processed_link[1]) # return resources # # Path: smartsnippets/settings.py # def _has_data_defined(widget_data): # USE_BOOTSTRAP_ACE = getattr( # settings, 'SMARTSNIPPETS_USE_BOOTSTRAP_ACE', False) . Output only the next line.
variables = dict(var_for_context(var) for var in vars_qs)
Given the following code snippet before the placeholder: <|code_start|> 'Enter a comma separated list of choices that will be ' 'available in the dropdown variable when adding and ' 'configuring the custom component on a page.')) @property def choices_list(self): return ([choice.strip() for choice in self.choices.split(',') if choice.strip()] if self.choices else []) def save(self, *args, **kwargs): self.widget = 'DropDownField' super(DropDownVariable, self).save(*args, **kwargs) def remove_cached_pointers(instance, **kwargs): if not caching_enabled: return pointer_pks = SmartSnippetPointer.objects.filter( snippet=instance ).values_list('pk', flat=True) cache_keys = [ SmartSnippetPointer.cache_key_format.format(primary_key=pk) for pk in pointer_pks ] cache.delete_many(cache_keys) def remove_cached_variables(instance, **kwargs): if not caching_enabled: <|code_end|> , predict the next line using imports from the current file: import re import logging from django.core.cache import cache from django.db import models from django.core.exceptions import ValidationError from django.template import Template, TemplateSyntaxError, \ TemplateDoesNotExist, loader, VariableDoesNotExist from django.template.loader import render_to_string from django.db.models import signals from django.contrib.sites.models import Site from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible from cms.models import CMSPlugin from sekizai.helpers import ( Watcher as sekizai_context_watcher, get_varname as sekizai_cache_key, ) from .resources_processor import get_resources from .settings import ( snippet_caching_time, caching_enabled, allow_inheritance, inherit_variable_pattern) from widgets_pool import widget_pool and context including class names, function names, and sometimes code from other files: # Path: smartsnippets/resources_processor.py # def get_resources(resources_data): # """ # Parses resources_data to get all resources defined with # the following format: # snippet-field/custom.html, static: admin/style.css, # http://somesite/absolute-url.js # and returns a dictionary with resources extensions and the links defined. # """ # if not resources_data: # return {} # resources_data = resources_data or '' # resources = defaultdict(list) # for resource in resources_data.split(','): # processed_link = _process(resource) # if not processed_link: # continue # links = resources[processed_link[0]] # res_link = processed_link[1] # # check if already added. Note: using list and not set just to # # make sure the ordering is kept # if res_link not in links: # links.append(processed_link[1]) # return resources # # Path: smartsnippets/settings.py # def _has_data_defined(widget_data): # USE_BOOTSTRAP_ACE = getattr( # settings, 'SMARTSNIPPETS_USE_BOOTSTRAP_ACE', False) . Output only the next line.
return
Next line prediction: <|code_start|> @property def choices_list(self): return ([choice.strip() for choice in self.choices.split(',') if choice.strip()] if self.choices else []) def save(self, *args, **kwargs): self.widget = 'DropDownField' super(DropDownVariable, self).save(*args, **kwargs) def remove_cached_pointers(instance, **kwargs): if not caching_enabled: return pointer_pks = SmartSnippetPointer.objects.filter( snippet=instance ).values_list('pk', flat=True) cache_keys = [ SmartSnippetPointer.cache_key_format.format(primary_key=pk) for pk in pointer_pks ] cache.delete_many(cache_keys) def remove_cached_variables(instance, **kwargs): if not caching_enabled: return key = instance.snippet.get_cache_key() if key in cache: <|code_end|> . Use current file imports: (import re import logging from django.core.cache import cache from django.db import models from django.core.exceptions import ValidationError from django.template import Template, TemplateSyntaxError, \ TemplateDoesNotExist, loader, VariableDoesNotExist from django.template.loader import render_to_string from django.db.models import signals from django.contrib.sites.models import Site from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible from cms.models import CMSPlugin from sekizai.helpers import ( Watcher as sekizai_context_watcher, get_varname as sekizai_cache_key, ) from .resources_processor import get_resources from .settings import ( snippet_caching_time, caching_enabled, allow_inheritance, inherit_variable_pattern) from widgets_pool import widget_pool) and context including class names, function names, or small code snippets from other files: # Path: smartsnippets/resources_processor.py # def get_resources(resources_data): # """ # Parses resources_data to get all resources defined with # the following format: # snippet-field/custom.html, static: admin/style.css, # http://somesite/absolute-url.js # and returns a dictionary with resources extensions and the links defined. # """ # if not resources_data: # return {} # resources_data = resources_data or '' # resources = defaultdict(list) # for resource in resources_data.split(','): # processed_link = _process(resource) # if not processed_link: # continue # links = resources[processed_link[0]] # res_link = processed_link[1] # # check if already added. Note: using list and not set just to # # make sure the ordering is kept # if res_link not in links: # links.append(processed_link[1]) # return resources # # Path: smartsnippets/settings.py # def _has_data_defined(widget_data): # USE_BOOTSTRAP_ACE = getattr( # settings, 'SMARTSNIPPETS_USE_BOOTSTRAP_ACE', False) . Output only the next line.
cache.delete(key)
Predict the next line after this snippet: <|code_start|> ordering = ['name'] verbose_name = _('Custom Component') verbose_name_plural = _('Custom Components') def __init__(self, *args, **kwargs): #hack due to # https://code.djangoproject.com/ticket/16433#no1 for rel_obj in self._meta.get_all_related_objects(): rel_obj.help_text = "" super(SmartSnippet, self).__init__(*args, **kwargs) def get_template(self): if self.template_path: return loader.get_template(self.template_path) else: return Template(self.template_code) def clean_template_code(self): try: self.get_template() except (TemplateSyntaxError, TemplateDoesNotExist), e: raise ValidationError(str(e)) def get_cache_key(self): return 'smartsnippet-%s' % self.pk def render(self, context): return self.get_template().render(context) def __unicode__(self): <|code_end|> using the current file's imports: import re import logging from django.core.cache import cache from django.db import models from django.core.exceptions import ValidationError from django.template import Template, TemplateSyntaxError, \ TemplateDoesNotExist, loader, VariableDoesNotExist from django.template.loader import render_to_string from django.db.models import signals from django.contrib.sites.models import Site from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible from cms.models import CMSPlugin from sekizai.helpers import ( Watcher as sekizai_context_watcher, get_varname as sekizai_cache_key, ) from .resources_processor import get_resources from .settings import ( snippet_caching_time, caching_enabled, allow_inheritance, inherit_variable_pattern) from widgets_pool import widget_pool and any relevant context from other files: # Path: smartsnippets/resources_processor.py # def get_resources(resources_data): # """ # Parses resources_data to get all resources defined with # the following format: # snippet-field/custom.html, static: admin/style.css, # http://somesite/absolute-url.js # and returns a dictionary with resources extensions and the links defined. # """ # if not resources_data: # return {} # resources_data = resources_data or '' # resources = defaultdict(list) # for resource in resources_data.split(','): # processed_link = _process(resource) # if not processed_link: # continue # links = resources[processed_link[0]] # res_link = processed_link[1] # # check if already added. Note: using list and not set just to # # make sure the ordering is kept # if res_link not in links: # links.append(processed_link[1]) # return resources # # Path: smartsnippets/settings.py # def _has_data_defined(widget_data): # USE_BOOTSTRAP_ACE = getattr( # settings, 'SMARTSNIPPETS_USE_BOOTSTRAP_ACE', False) . Output only the next line.
return self.name
Based on the snippet: <|code_start|> related_name='variables') value = models.TextField() snippet = models.ForeignKey(SmartSnippetPointer, related_name='variables') class Meta: unique_together = (('snippet_variable', 'snippet')) @property def formatted_value(self): widget_instance = widget_pool.get_widget(self.widget)(self) return widget_instance.formatted_value @property def name(self): return self.snippet_variable.name @property def widget(self): return self.snippet_variable.widget @property def templates(self): return self.snippet_variable.resources_dict.get('html', set()) @property def js(self): return self.snippet_variable.resources_dict.get('js', set()) @property def css(self): <|code_end|> , predict the immediate next line with the help of imports: import re import logging from django.core.cache import cache from django.db import models from django.core.exceptions import ValidationError from django.template import Template, TemplateSyntaxError, \ TemplateDoesNotExist, loader, VariableDoesNotExist from django.template.loader import render_to_string from django.db.models import signals from django.contrib.sites.models import Site from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible from cms.models import CMSPlugin from sekizai.helpers import ( Watcher as sekizai_context_watcher, get_varname as sekizai_cache_key, ) from .resources_processor import get_resources from .settings import ( snippet_caching_time, caching_enabled, allow_inheritance, inherit_variable_pattern) from widgets_pool import widget_pool and context (classes, functions, sometimes code) from other files: # Path: smartsnippets/resources_processor.py # def get_resources(resources_data): # """ # Parses resources_data to get all resources defined with # the following format: # snippet-field/custom.html, static: admin/style.css, # http://somesite/absolute-url.js # and returns a dictionary with resources extensions and the links defined. # """ # if not resources_data: # return {} # resources_data = resources_data or '' # resources = defaultdict(list) # for resource in resources_data.split(','): # processed_link = _process(resource) # if not processed_link: # continue # links = resources[processed_link[0]] # res_link = processed_link[1] # # check if already added. Note: using list and not set just to # # make sure the ordering is kept # if res_link not in links: # links.append(processed_link[1]) # return resources # # Path: smartsnippets/settings.py # def _has_data_defined(widget_data): # USE_BOOTSTRAP_ACE = getattr( # settings, 'SMARTSNIPPETS_USE_BOOTSTRAP_ACE', False) . Output only the next line.
return self.snippet_variable.resources_dict.get('css', set())
Here is a snippet: <|code_start|> name = 'Text Field' template = 'smartsnippets/widgets/textfield/widget.html' class TextAreaField(SmartSnippetWidgetBase): name = 'TextArea Field' template = 'smartsnippets/widgets/textareafield/widget.html' class DropDownField(SmartSnippetWidgetBase): name = 'DropDown Field' model = DropDownVariable template = 'smartsnippets/widgets/dropdownfield/widget.html' class SwitcherField(SmartSnippetWidgetBase): name = 'Switcher Field' template = 'smartsnippets/widgets/switcherfield/widget.html' class URLField(SmartSnippetWidgetBase): name = 'URL Field' template = 'smartsnippets/widgets/urlfield/widget.html' class JSONField(TextField): name = 'JSON Field' @property def formatted_value(self): try: <|code_end|> . Write the next line using the current file imports: from smartsnippets.widgets_pool import widget_pool from smartsnippets.widgets_base import SmartSnippetWidgetBase from .models import DropDownVariable import collections import json and context from other files: # Path: smartsnippets/widgets_pool.py # class WidgetPool(object): # def __init__(self): # def discover_widgets(self): # def register_settings(self, namespace, settings_dict): # def unregister_settings(self, namespace, settings_keys=None): # def register_widget(self, widget): # def unregister_widget(self, widget): # def get_widget(self, name): # def get_all_widgets(self, has_model=False, snippet=None): # def get_settings(self, namespace, name=None): # # Path: smartsnippets/widgets_base.py # class SmartSnippetWidgetBase(object): # name = 'Base Widget' # model = SmartSnippetVariable # template = None # # def __init__(self, variable, **kwargs): # self.variable = variable # # @property # def formatted_value(self): # return self.variable.value # # def get_extra_data(self, request): # return {} # # def render(self, request, context=None): # if self.template is None: # raise NotImplementedError( # "render needs to be implemented or set a default template") # # default_data = {'field': self.variable} # select_template = list(self.variable.templates) + [self.template] # return render_to_string( # select_template, # dict(self.get_extra_data(request).items() + default_data.items()), # context_instance=(context or RequestContext(request)) # ) # # Path: smartsnippets/models.py # class DropDownVariable(SmartSnippetVariable): # choices = models.CharField( # max_length=512, # help_text=_( # 'Enter a comma separated list of choices that will be ' # 'available in the dropdown variable when adding and ' # 'configuring the custom component on a page.')) # # @property # def choices_list(self): # return ([choice.strip() for choice in self.choices.split(',') if choice.strip()] # if self.choices else []) # # def save(self, *args, **kwargs): # self.widget = 'DropDownField' # super(DropDownVariable, self).save(*args, **kwargs) , which may include functions, classes, or code. Output only the next line.
return json.loads(
Based on the snippet: <|code_start|> name = 'Text Field' template = 'smartsnippets/widgets/textfield/widget.html' class TextAreaField(SmartSnippetWidgetBase): name = 'TextArea Field' template = 'smartsnippets/widgets/textareafield/widget.html' class DropDownField(SmartSnippetWidgetBase): name = 'DropDown Field' model = DropDownVariable template = 'smartsnippets/widgets/dropdownfield/widget.html' class SwitcherField(SmartSnippetWidgetBase): name = 'Switcher Field' template = 'smartsnippets/widgets/switcherfield/widget.html' class URLField(SmartSnippetWidgetBase): name = 'URL Field' template = 'smartsnippets/widgets/urlfield/widget.html' class JSONField(TextField): name = 'JSON Field' @property def formatted_value(self): try: <|code_end|> , predict the immediate next line with the help of imports: from smartsnippets.widgets_pool import widget_pool from smartsnippets.widgets_base import SmartSnippetWidgetBase from .models import DropDownVariable import collections import json and context (classes, functions, sometimes code) from other files: # Path: smartsnippets/widgets_pool.py # class WidgetPool(object): # def __init__(self): # def discover_widgets(self): # def register_settings(self, namespace, settings_dict): # def unregister_settings(self, namespace, settings_keys=None): # def register_widget(self, widget): # def unregister_widget(self, widget): # def get_widget(self, name): # def get_all_widgets(self, has_model=False, snippet=None): # def get_settings(self, namespace, name=None): # # Path: smartsnippets/widgets_base.py # class SmartSnippetWidgetBase(object): # name = 'Base Widget' # model = SmartSnippetVariable # template = None # # def __init__(self, variable, **kwargs): # self.variable = variable # # @property # def formatted_value(self): # return self.variable.value # # def get_extra_data(self, request): # return {} # # def render(self, request, context=None): # if self.template is None: # raise NotImplementedError( # "render needs to be implemented or set a default template") # # default_data = {'field': self.variable} # select_template = list(self.variable.templates) + [self.template] # return render_to_string( # select_template, # dict(self.get_extra_data(request).items() + default_data.items()), # context_instance=(context or RequestContext(request)) # ) # # Path: smartsnippets/models.py # class DropDownVariable(SmartSnippetVariable): # choices = models.CharField( # max_length=512, # help_text=_( # 'Enter a comma separated list of choices that will be ' # 'available in the dropdown variable when adding and ' # 'configuring the custom component on a page.')) # # @property # def choices_list(self): # return ([choice.strip() for choice in self.choices.split(',') if choice.strip()] # if self.choices else []) # # def save(self, *args, **kwargs): # self.widget = 'DropDownField' # super(DropDownVariable, self).save(*args, **kwargs) . Output only the next line.
return json.loads(
Predict the next line after this snippet: <|code_start|> self._settings.pop(namespace, None) def register_widget(self, widget): if not issubclass(widget, SmartSnippetWidgetBase): raise ImproperlyConfigured( 'Smartsnippets widgets must be subclasses of WidgetBase, %s is not.' % widget ) widget_name = widget.__name__ if widget_name in self.widgets: raise WidgetAlreadyRegistered( "Cannot register %s, a widget with this name (%s) is already " "retgistered." % (widget, widget_name) ) widget.value = widget_name self.widgets[widget_name] = widget def unregister_widget(self, widget): widget_name = widget.__name__ if widget_name not in self.widgets: raise WidgetNotRegistered( 'The widget %s is not registered' % widget ) del self.widgets[widget_name] def get_widget(self, name): self.discover_widgets() return self.widgets[name] <|code_end|> using the current file's imports: from django.core.exceptions import ImproperlyConfigured from cms.utils.django_load import load from smartsnippets.exceptions import WidgetAlreadyRegistered, WidgetNotRegistered from smartsnippets.widgets_base import SmartSnippetWidgetBase from models import SmartSnippetVariable from collections import defaultdict and any relevant context from other files: # Path: smartsnippets/exceptions.py # class WidgetAlreadyRegistered(Exception): # pass # # class WidgetNotRegistered(Exception): # pass # # Path: smartsnippets/widgets_base.py # class SmartSnippetWidgetBase(object): # name = 'Base Widget' # model = SmartSnippetVariable # template = None # # def __init__(self, variable, **kwargs): # self.variable = variable # # @property # def formatted_value(self): # return self.variable.value # # def get_extra_data(self, request): # return {} # # def render(self, request, context=None): # if self.template is None: # raise NotImplementedError( # "render needs to be implemented or set a default template") # # default_data = {'field': self.variable} # select_template = list(self.variable.templates) + [self.template] # return render_to_string( # select_template, # dict(self.get_extra_data(request).items() + default_data.items()), # context_instance=(context or RequestContext(request)) # ) . Output only the next line.
def get_all_widgets(self, has_model=False, snippet=None):
Predict the next line after this snippet: <|code_start|> class WidgetPool(object): def __init__(self): self.widgets = {} self._settings = defaultdict(dict) <|code_end|> using the current file's imports: from django.core.exceptions import ImproperlyConfigured from cms.utils.django_load import load from smartsnippets.exceptions import WidgetAlreadyRegistered, WidgetNotRegistered from smartsnippets.widgets_base import SmartSnippetWidgetBase from models import SmartSnippetVariable from collections import defaultdict and any relevant context from other files: # Path: smartsnippets/exceptions.py # class WidgetAlreadyRegistered(Exception): # pass # # class WidgetNotRegistered(Exception): # pass # # Path: smartsnippets/widgets_base.py # class SmartSnippetWidgetBase(object): # name = 'Base Widget' # model = SmartSnippetVariable # template = None # # def __init__(self, variable, **kwargs): # self.variable = variable # # @property # def formatted_value(self): # return self.variable.value # # def get_extra_data(self, request): # return {} # # def render(self, request, context=None): # if self.template is None: # raise NotImplementedError( # "render needs to be implemented or set a default template") # # default_data = {'field': self.variable} # select_template = list(self.variable.templates) + [self.template] # return render_to_string( # select_template, # dict(self.get_extra_data(request).items() + default_data.items()), # context_instance=(context or RequestContext(request)) # ) . Output only the next line.
self.discovered = False
Using the snippet: <|code_start|> class WidgetPool(object): def __init__(self): self.widgets = {} self._settings = defaultdict(dict) self.discovered = False def discover_widgets(self): if self.discovered: return self.discovered = True load('widgets') <|code_end|> , determine the next line of code. You have imports: from django.core.exceptions import ImproperlyConfigured from cms.utils.django_load import load from smartsnippets.exceptions import WidgetAlreadyRegistered, WidgetNotRegistered from smartsnippets.widgets_base import SmartSnippetWidgetBase from models import SmartSnippetVariable from collections import defaultdict and context (class names, function names, or code) available: # Path: smartsnippets/exceptions.py # class WidgetAlreadyRegistered(Exception): # pass # # class WidgetNotRegistered(Exception): # pass # # Path: smartsnippets/widgets_base.py # class SmartSnippetWidgetBase(object): # name = 'Base Widget' # model = SmartSnippetVariable # template = None # # def __init__(self, variable, **kwargs): # self.variable = variable # # @property # def formatted_value(self): # return self.variable.value # # def get_extra_data(self, request): # return {} # # def render(self, request, context=None): # if self.template is None: # raise NotImplementedError( # "render needs to be implemented or set a default template") # # default_data = {'field': self.variable} # select_template = list(self.variable.templates) + [self.template] # return render_to_string( # select_template, # dict(self.get_extra_data(request).items() + default_data.items()), # context_instance=(context or RequestContext(request)) # ) . Output only the next line.
def register_settings(self, namespace, settings_dict):
Next line prediction: <|code_start|> class InheritPageContent(CMSPlugin): # from which page from_page = models.ForeignKey(Page) # from which section from_placeholder = models.CharField(max_length=255, db_index=True) class Meta: <|code_end|> . Use current file imports: (from django.db import models from cms.models import CMSPlugin, Page, Placeholder from smartsnippets.models import Variable) and context including class names, function names, or small code snippets from other files: # Path: smartsnippets/models.py # class Variable(models.Model): # snippet_variable = models.ForeignKey(SmartSnippetVariable, # related_name='variables') # value = models.TextField() # snippet = models.ForeignKey(SmartSnippetPointer, related_name='variables') # # class Meta: # unique_together = (('snippet_variable', 'snippet')) # # @property # def formatted_value(self): # from widgets_pool import widget_pool # widget_instance = widget_pool.get_widget(self.widget)(self) # return widget_instance.formatted_value # # @property # def name(self): # return self.snippet_variable.name # # @property # def widget(self): # return self.snippet_variable.widget # # @property # def templates(self): # return self.snippet_variable.resources_dict.get('html', set()) # # @property # def js(self): # return self.snippet_variable.resources_dict.get('js', set()) # # @property # def css(self): # return self.snippet_variable.resources_dict.get('css', set()) . Output only the next line.
db_table = 'cmsplugin_inheritpagecontent'
Predict the next line after this snippet: <|code_start|> label=_("page"), queryset=Page.objects.drafts()) site = None current_page = None class Meta: model = InheritPageContent fields = ('from_page', 'from_placeholder') @property def media(self): _media = super(InheritPageForm, self).media variables_media(_media, self._cache_variables) return _media def __init__(self, *args, **kwargs): self._cache_variables = [] super(InheritPageForm, self).__init__(*args, **kwargs) if self.current_page is not None: self.site = self.current_page.site if self.site is not None and 'from_page' in self.fields: site_pages = Page.objects.drafts().on_site(self.site) self.fields['from_page'].queryset = site_pages if self.instance.pk: phd = self.instance.get_placeholder() self._cache_variables = Variable.objects.filter( snippet__placeholder=phd ).select_related('snippet_variable') def clean_from_placeholder(self): slot = (self.cleaned_data.get('from_placeholder') or '').strip() <|code_end|> using the current file's imports: from django import forms from django.forms.models import ModelForm from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ from cms.models import Page from smartsnippets.cms_plugins import variables_media from smartsnippets.models import Variable from smartsnippets_inherit.models import InheritPageContent and any relevant context from other files: # Path: smartsnippets/cms_plugins.py # def variables_media(media, variables=None): # variables = variables or [] # media.add_js([static('admin/js/SmartSnippetLib.js')]) # media.add_js( # itertools.chain(*[var.js for var in variables]) # ) # media.add_css( # {'all': itertools.chain(*[var.css for var in variables])}) # # Path: smartsnippets/models.py # class Variable(models.Model): # snippet_variable = models.ForeignKey(SmartSnippetVariable, # related_name='variables') # value = models.TextField() # snippet = models.ForeignKey(SmartSnippetPointer, related_name='variables') # # class Meta: # unique_together = (('snippet_variable', 'snippet')) # # @property # def formatted_value(self): # from widgets_pool import widget_pool # widget_instance = widget_pool.get_widget(self.widget)(self) # return widget_instance.formatted_value # # @property # def name(self): # return self.snippet_variable.name # # @property # def widget(self): # return self.snippet_variable.widget # # @property # def templates(self): # return self.snippet_variable.resources_dict.get('html', set()) # # @property # def js(self): # return self.snippet_variable.resources_dict.get('js', set()) # # @property # def css(self): # return self.snippet_variable.resources_dict.get('css', set()) # # Path: smartsnippets_inherit/models.py # class InheritPageContent(CMSPlugin): # # from which page # from_page = models.ForeignKey(Page) # # from which section # from_placeholder = models.CharField(max_length=255, db_index=True) # # class Meta: # db_table = 'cmsplugin_inheritpagecontent' # # def get_placeholder(self): # try: # return self.from_page.placeholders.get(slot=self.from_placeholder) # except Placeholder.DoesNotExist: # return None . Output only the next line.
if not slot:
Using the snippet: <|code_start|> class InheritPageForm(ModelForm): from_page = forms.ModelChoiceField( label=_("page"), queryset=Page.objects.drafts()) site = None current_page = None class Meta: model = InheritPageContent fields = ('from_page', 'from_placeholder') @property def media(self): _media = super(InheritPageForm, self).media variables_media(_media, self._cache_variables) return _media def __init__(self, *args, **kwargs): self._cache_variables = [] super(InheritPageForm, self).__init__(*args, **kwargs) if self.current_page is not None: self.site = self.current_page.site if self.site is not None and 'from_page' in self.fields: <|code_end|> , determine the next line of code. You have imports: from django import forms from django.forms.models import ModelForm from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ from cms.models import Page from smartsnippets.cms_plugins import variables_media from smartsnippets.models import Variable from smartsnippets_inherit.models import InheritPageContent and context (class names, function names, or code) available: # Path: smartsnippets/cms_plugins.py # def variables_media(media, variables=None): # variables = variables or [] # media.add_js([static('admin/js/SmartSnippetLib.js')]) # media.add_js( # itertools.chain(*[var.js for var in variables]) # ) # media.add_css( # {'all': itertools.chain(*[var.css for var in variables])}) # # Path: smartsnippets/models.py # class Variable(models.Model): # snippet_variable = models.ForeignKey(SmartSnippetVariable, # related_name='variables') # value = models.TextField() # snippet = models.ForeignKey(SmartSnippetPointer, related_name='variables') # # class Meta: # unique_together = (('snippet_variable', 'snippet')) # # @property # def formatted_value(self): # from widgets_pool import widget_pool # widget_instance = widget_pool.get_widget(self.widget)(self) # return widget_instance.formatted_value # # @property # def name(self): # return self.snippet_variable.name # # @property # def widget(self): # return self.snippet_variable.widget # # @property # def templates(self): # return self.snippet_variable.resources_dict.get('html', set()) # # @property # def js(self): # return self.snippet_variable.resources_dict.get('js', set()) # # @property # def css(self): # return self.snippet_variable.resources_dict.get('css', set()) # # Path: smartsnippets_inherit/models.py # class InheritPageContent(CMSPlugin): # # from which page # from_page = models.ForeignKey(Page) # # from which section # from_placeholder = models.CharField(max_length=255, db_index=True) # # class Meta: # db_table = 'cmsplugin_inheritpagecontent' # # def get_placeholder(self): # try: # return self.from_page.placeholders.get(slot=self.from_placeholder) # except Placeholder.DoesNotExist: # return None . Output only the next line.
site_pages = Page.objects.drafts().on_site(self.site)
Given the following code snippet before the placeholder: <|code_start|> class InheritPageForm(ModelForm): from_page = forms.ModelChoiceField( label=_("page"), queryset=Page.objects.drafts()) site = None current_page = None class Meta: model = InheritPageContent fields = ('from_page', 'from_placeholder') @property def media(self): <|code_end|> , predict the next line using imports from the current file: from django import forms from django.forms.models import ModelForm from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ from cms.models import Page from smartsnippets.cms_plugins import variables_media from smartsnippets.models import Variable from smartsnippets_inherit.models import InheritPageContent and context including class names, function names, and sometimes code from other files: # Path: smartsnippets/cms_plugins.py # def variables_media(media, variables=None): # variables = variables or [] # media.add_js([static('admin/js/SmartSnippetLib.js')]) # media.add_js( # itertools.chain(*[var.js for var in variables]) # ) # media.add_css( # {'all': itertools.chain(*[var.css for var in variables])}) # # Path: smartsnippets/models.py # class Variable(models.Model): # snippet_variable = models.ForeignKey(SmartSnippetVariable, # related_name='variables') # value = models.TextField() # snippet = models.ForeignKey(SmartSnippetPointer, related_name='variables') # # class Meta: # unique_together = (('snippet_variable', 'snippet')) # # @property # def formatted_value(self): # from widgets_pool import widget_pool # widget_instance = widget_pool.get_widget(self.widget)(self) # return widget_instance.formatted_value # # @property # def name(self): # return self.snippet_variable.name # # @property # def widget(self): # return self.snippet_variable.widget # # @property # def templates(self): # return self.snippet_variable.resources_dict.get('html', set()) # # @property # def js(self): # return self.snippet_variable.resources_dict.get('js', set()) # # @property # def css(self): # return self.snippet_variable.resources_dict.get('css', set()) # # Path: smartsnippets_inherit/models.py # class InheritPageContent(CMSPlugin): # # from which page # from_page = models.ForeignKey(Page) # # from which section # from_placeholder = models.CharField(max_length=255, db_index=True) # # class Meta: # db_table = 'cmsplugin_inheritpagecontent' # # def get_placeholder(self): # try: # return self.from_page.placeholders.get(slot=self.from_placeholder) # except Placeholder.DoesNotExist: # return None . Output only the next line.
_media = super(InheritPageForm, self).media
Next line prediction: <|code_start|> @csrf_protect def variables_edit_view(request, plugin_id): plugin = get_object_or_404(InheritPageContent, id=plugin_id) if not has_plugin_permission(request.user, plugin.plugin_type, "change"): raise PermissionDenied snippet_plugin_id = None if request.method == 'DELETE': snippet_plugin_id = QueryDict(request.body).get('snippet_plugin') snippet_plugin_id = (snippet_plugin_id or request.REQUEST.get('snippet_plugin')) if snippet_plugin_id is None: return HttpResponseBadRequest('Snippet plugin missing') snippet_plugin = get_object_or_404( SmartSnippetPointer, id=snippet_plugin_id ) <|code_end|> . Use current file imports: (from django.shortcuts import get_object_or_404, render_to_response from django.http import HttpResponse, HttpResponseBadRequest, QueryDict from django.views.decorators.csrf import csrf_protect from django.core.exceptions import PermissionDenied from django.template import RequestContext from smartsnippets_inherit.models import InheritPageContent, OverwriteVariable from smartsnippets.models import SmartSnippetPointer from cms.utils.permissions import has_plugin_permission) and context including class names, function names, or small code snippets from other files: # Path: smartsnippets_inherit/models.py # class InheritPageContent(CMSPlugin): # # from which page # from_page = models.ForeignKey(Page) # # from which section # from_placeholder = models.CharField(max_length=255, db_index=True) # # class Meta: # db_table = 'cmsplugin_inheritpagecontent' # # def get_placeholder(self): # try: # return self.from_page.placeholders.get(slot=self.from_placeholder) # except Placeholder.DoesNotExist: # return None # # class OverwriteVariable(models.Model): # # which variable I overwrite # variable = models.ForeignKey(Variable) # # overwrite with this value # value = models.TextField() # # where I exist # plugin = models.ForeignKey( # InheritPageContent, related_name='overwrite_variables') # # def to_variable(self): # """ # Utility to transform this to a plugin variable object. This is used # for rendering as a plugin variable with the overwritten value. # """ # variable = self.variable # variable.value = self.value # return variable # # Path: smartsnippets/models.py # class SmartSnippetPointer(CMSPlugin): # snippet = models.ForeignKey(SmartSnippet, verbose_name='Custom Component') # cache_key_format = 'smartsnippet-pointer-{primary_key}' # # class Meta: # db_table = 'cmsplugin_smartsnippetpointer' # # def get_cache_key(self): # return self.cache_key_format.format(primary_key=self.pk) # # def _do_restore_sekizai_context(self, context, changes): # """Sekizai tags involve magic with the context object. # When need to restore the sekizai content to the context""" # cache_key = sekizai_cache_key() # sekizai_container = context.get(cache_key) # for key, values in changes.items(): # sekizai_namespace = sekizai_container[key] # for value in values: # sekizai_namespace.append(value) # # def fetch_cached(self, context): # cache_key = self.get_cache_key() # user = context['request'].user # if not user.is_staff and caching_enabled and cache.has_key(cache_key): # cached_value = cache.get(cache_key) # rendered_content = cached_value.get('content') # sekizai = cached_value.get('sekizai') # self._do_restore_sekizai_context(context, sekizai) # return rendered_content # # def set_and_get_cache(self, user, sekizai_diff, content): # if not user.is_staff and caching_enabled: # value = {'content': content, 'sekizai': sekizai_diff} # key = self.get_cache_key() # cache.set(key, value, snippet_caching_time) # return content # # def render_pointer(self, context, handle_errors=True): # vars_qs = self.variables.select_related('snippet_variable').all() # # def var_for_context(var): # default, overwrite = var.formatted_value, None # if allow_inheritance: # overwrite = context.get( # inherit_variable_pattern.format(identifier=var.pk)) # name = var.snippet_variable.name # value = overwrite if overwrite is not None else default # return (name, value) # # variables = dict(var_for_context(var) for var in vars_qs) # context.update(variables) # sekizai_differ = sekizai_context_watcher(context) # try: # content = self.snippet.render(context) # except VariableDoesNotExist as exc: # logger.exception("Cannot render plugin %s!", self) # if handle_errors: # content = render_to_string("smartsnippets/unrenderable_smartsnippet.html", # {'plugin_name': str(self)}) # else: # raise UnrenderableSmarSnippet(exc) # sekizai_diff = sekizai_differ.get_changes() # user = context.get('request').user # return self.set_and_get_cache(user, sekizai_diff, content) # # def render(self, context, handle_errors=True): # return self.fetch_cached(context) or self.render_pointer(context, handle_errors) # # def copy_relations(self, old_instance): # for variable in old_instance.variables.all(): # variable.pk = None # variable.snippet = self # variable.save() # # def __unicode__(self): # return unicode(self.snippet) . Output only the next line.
variables = snippet_plugin.variables.filter(
Given the code snippet: <|code_start|> @csrf_protect def variables_edit_view(request, plugin_id): plugin = get_object_or_404(InheritPageContent, id=plugin_id) if not has_plugin_permission(request.user, plugin.plugin_type, "change"): raise PermissionDenied snippet_plugin_id = None if request.method == 'DELETE': snippet_plugin_id = QueryDict(request.body).get('snippet_plugin') snippet_plugin_id = (snippet_plugin_id or request.REQUEST.get('snippet_plugin')) if snippet_plugin_id is None: return HttpResponseBadRequest('Snippet plugin missing') snippet_plugin = get_object_or_404( SmartSnippetPointer, id=snippet_plugin_id ) variables = snippet_plugin.variables.filter( snippet_variable__snippet=snippet_plugin.snippet ) overwrite_variables = None if request.method == 'POST': <|code_end|> , generate the next line using the imports in this file: from django.shortcuts import get_object_or_404, render_to_response from django.http import HttpResponse, HttpResponseBadRequest, QueryDict from django.views.decorators.csrf import csrf_protect from django.core.exceptions import PermissionDenied from django.template import RequestContext from smartsnippets_inherit.models import InheritPageContent, OverwriteVariable from smartsnippets.models import SmartSnippetPointer from cms.utils.permissions import has_plugin_permission and context (functions, classes, or occasionally code) from other files: # Path: smartsnippets_inherit/models.py # class InheritPageContent(CMSPlugin): # # from which page # from_page = models.ForeignKey(Page) # # from which section # from_placeholder = models.CharField(max_length=255, db_index=True) # # class Meta: # db_table = 'cmsplugin_inheritpagecontent' # # def get_placeholder(self): # try: # return self.from_page.placeholders.get(slot=self.from_placeholder) # except Placeholder.DoesNotExist: # return None # # class OverwriteVariable(models.Model): # # which variable I overwrite # variable = models.ForeignKey(Variable) # # overwrite with this value # value = models.TextField() # # where I exist # plugin = models.ForeignKey( # InheritPageContent, related_name='overwrite_variables') # # def to_variable(self): # """ # Utility to transform this to a plugin variable object. This is used # for rendering as a plugin variable with the overwritten value. # """ # variable = self.variable # variable.value = self.value # return variable # # Path: smartsnippets/models.py # class SmartSnippetPointer(CMSPlugin): # snippet = models.ForeignKey(SmartSnippet, verbose_name='Custom Component') # cache_key_format = 'smartsnippet-pointer-{primary_key}' # # class Meta: # db_table = 'cmsplugin_smartsnippetpointer' # # def get_cache_key(self): # return self.cache_key_format.format(primary_key=self.pk) # # def _do_restore_sekizai_context(self, context, changes): # """Sekizai tags involve magic with the context object. # When need to restore the sekizai content to the context""" # cache_key = sekizai_cache_key() # sekizai_container = context.get(cache_key) # for key, values in changes.items(): # sekizai_namespace = sekizai_container[key] # for value in values: # sekizai_namespace.append(value) # # def fetch_cached(self, context): # cache_key = self.get_cache_key() # user = context['request'].user # if not user.is_staff and caching_enabled and cache.has_key(cache_key): # cached_value = cache.get(cache_key) # rendered_content = cached_value.get('content') # sekizai = cached_value.get('sekizai') # self._do_restore_sekizai_context(context, sekizai) # return rendered_content # # def set_and_get_cache(self, user, sekizai_diff, content): # if not user.is_staff and caching_enabled: # value = {'content': content, 'sekizai': sekizai_diff} # key = self.get_cache_key() # cache.set(key, value, snippet_caching_time) # return content # # def render_pointer(self, context, handle_errors=True): # vars_qs = self.variables.select_related('snippet_variable').all() # # def var_for_context(var): # default, overwrite = var.formatted_value, None # if allow_inheritance: # overwrite = context.get( # inherit_variable_pattern.format(identifier=var.pk)) # name = var.snippet_variable.name # value = overwrite if overwrite is not None else default # return (name, value) # # variables = dict(var_for_context(var) for var in vars_qs) # context.update(variables) # sekizai_differ = sekizai_context_watcher(context) # try: # content = self.snippet.render(context) # except VariableDoesNotExist as exc: # logger.exception("Cannot render plugin %s!", self) # if handle_errors: # content = render_to_string("smartsnippets/unrenderable_smartsnippet.html", # {'plugin_name': str(self)}) # else: # raise UnrenderableSmarSnippet(exc) # sekizai_diff = sekizai_differ.get_changes() # user = context.get('request').user # return self.set_and_get_cache(user, sekizai_diff, content) # # def render(self, context, handle_errors=True): # return self.fetch_cached(context) or self.render_pointer(context, handle_errors) # # def copy_relations(self, old_instance): # for variable in old_instance.variables.all(): # variable.pk = None # variable.snippet = self # variable.save() # # def __unicode__(self): # return unicode(self.snippet) . Output only the next line.
variables = variables.select_related('snippet_variable')
Using the snippet: <|code_start|> variables = variables.select_related('snippet_variable') overwrite_variables = [] for var in variables: new_value = request.POST.get("_%s_" % var.snippet_variable.name) if new_value is None: continue try: existing_var = OverwriteVariable.objects.get( plugin=plugin, variable=var) existing_var.value = new_value existing_var.save() overwrite_variables.append(existing_var) except (OverwriteVariable.DoesNotExist, ): new_var = OverwriteVariable.objects.create( plugin=plugin, variable=var, value=new_value) overwrite_variables.append(new_var) if overwrite_variables is None: overwrite_variables = OverwriteVariable.objects.filter( plugin=plugin, variable__in=list(variables)) if request.method == 'DELETE': overwrite_variables.delete() overwrite_variables = [] # transform all into Variable instances overwrite_as_vars = [v.to_variable() for v in overwrite_variables] vars_to_render = { var.snippet_variable.name: var for var in list(variables) + overwrite_as_vars <|code_end|> , determine the next line of code. You have imports: from django.shortcuts import get_object_or_404, render_to_response from django.http import HttpResponse, HttpResponseBadRequest, QueryDict from django.views.decorators.csrf import csrf_protect from django.core.exceptions import PermissionDenied from django.template import RequestContext from smartsnippets_inherit.models import InheritPageContent, OverwriteVariable from smartsnippets.models import SmartSnippetPointer from cms.utils.permissions import has_plugin_permission and context (class names, function names, or code) available: # Path: smartsnippets_inherit/models.py # class InheritPageContent(CMSPlugin): # # from which page # from_page = models.ForeignKey(Page) # # from which section # from_placeholder = models.CharField(max_length=255, db_index=True) # # class Meta: # db_table = 'cmsplugin_inheritpagecontent' # # def get_placeholder(self): # try: # return self.from_page.placeholders.get(slot=self.from_placeholder) # except Placeholder.DoesNotExist: # return None # # class OverwriteVariable(models.Model): # # which variable I overwrite # variable = models.ForeignKey(Variable) # # overwrite with this value # value = models.TextField() # # where I exist # plugin = models.ForeignKey( # InheritPageContent, related_name='overwrite_variables') # # def to_variable(self): # """ # Utility to transform this to a plugin variable object. This is used # for rendering as a plugin variable with the overwritten value. # """ # variable = self.variable # variable.value = self.value # return variable # # Path: smartsnippets/models.py # class SmartSnippetPointer(CMSPlugin): # snippet = models.ForeignKey(SmartSnippet, verbose_name='Custom Component') # cache_key_format = 'smartsnippet-pointer-{primary_key}' # # class Meta: # db_table = 'cmsplugin_smartsnippetpointer' # # def get_cache_key(self): # return self.cache_key_format.format(primary_key=self.pk) # # def _do_restore_sekizai_context(self, context, changes): # """Sekizai tags involve magic with the context object. # When need to restore the sekizai content to the context""" # cache_key = sekizai_cache_key() # sekizai_container = context.get(cache_key) # for key, values in changes.items(): # sekizai_namespace = sekizai_container[key] # for value in values: # sekizai_namespace.append(value) # # def fetch_cached(self, context): # cache_key = self.get_cache_key() # user = context['request'].user # if not user.is_staff and caching_enabled and cache.has_key(cache_key): # cached_value = cache.get(cache_key) # rendered_content = cached_value.get('content') # sekizai = cached_value.get('sekizai') # self._do_restore_sekizai_context(context, sekizai) # return rendered_content # # def set_and_get_cache(self, user, sekizai_diff, content): # if not user.is_staff and caching_enabled: # value = {'content': content, 'sekizai': sekizai_diff} # key = self.get_cache_key() # cache.set(key, value, snippet_caching_time) # return content # # def render_pointer(self, context, handle_errors=True): # vars_qs = self.variables.select_related('snippet_variable').all() # # def var_for_context(var): # default, overwrite = var.formatted_value, None # if allow_inheritance: # overwrite = context.get( # inherit_variable_pattern.format(identifier=var.pk)) # name = var.snippet_variable.name # value = overwrite if overwrite is not None else default # return (name, value) # # variables = dict(var_for_context(var) for var in vars_qs) # context.update(variables) # sekizai_differ = sekizai_context_watcher(context) # try: # content = self.snippet.render(context) # except VariableDoesNotExist as exc: # logger.exception("Cannot render plugin %s!", self) # if handle_errors: # content = render_to_string("smartsnippets/unrenderable_smartsnippet.html", # {'plugin_name': str(self)}) # else: # raise UnrenderableSmarSnippet(exc) # sekizai_diff = sekizai_differ.get_changes() # user = context.get('request').user # return self.set_and_get_cache(user, sekizai_diff, content) # # def render(self, context, handle_errors=True): # return self.fetch_cached(context) or self.render_pointer(context, handle_errors) # # def copy_relations(self, old_instance): # for variable in old_instance.variables.all(): # variable.pk = None # variable.snippet = self # variable.save() # # def __unicode__(self): # return unicode(self.snippet) . Output only the next line.
}
Using the snippet: <|code_start|># # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # class TestReportCli(base.BaseAPIEndpointTestCase): def test_report_tenant_list(self): class DummyAPIClient(object): def get_tenants(*args, **kwargs): return ['ee530dfc-319a-438f-9d43-346cfef501d6', '91743a9a-688b-4526-b568-7b501531176c', '4468704c-972e-4cfd-a342-9b71c493b79b'] class ClientWrap(object): report = DummyAPIClient() class DummyParsedArgs(object): <|code_end|> , determine the next line of code. You have imports: from collections import abc from unittest import mock from cloudkittyclient.tests.unit.v1 import base from cloudkittyclient.v1 import report_cli and context (class names, function names, or code) available: # Path: cloudkittyclient/tests/unit/v1/base.py # class BaseAPIEndpointTestCase(utils.BaseTestCase): # def setUp(self): # # Path: cloudkittyclient/v1/report_cli.py # class CliSummaryGet(lister.Lister): # class CliTotalGet(show.ShowOne): # class CliTenantList(lister.Lister): # def take_action(self, parsed_args): # def get_parser(self, prog_name): # def take_action(self, parsed_args): # def get_parser(self, prog_name): # def take_action(self, parsed_args): # def get_parser(self, prog_name): . Output only the next line.
def __init__(self):
Given the following code snippet before the placeholder: <|code_start|># 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 TestReportCli(base.BaseAPIEndpointTestCase): def test_report_tenant_list(self): class DummyAPIClient(object): def get_tenants(*args, **kwargs): return ['ee530dfc-319a-438f-9d43-346cfef501d6', '91743a9a-688b-4526-b568-7b501531176c', '4468704c-972e-4cfd-a342-9b71c493b79b'] class ClientWrap(object): report = DummyAPIClient() class DummyParsedArgs(object): def __init__(self): self.begin = '2042-01-01T00:00:00' self.end = '2042-12-01T00:00:00' class DummyCliTenantList(report_cli.CliTenantList): def __init__(self): pass <|code_end|> , predict the next line using imports from the current file: from collections import abc from unittest import mock from cloudkittyclient.tests.unit.v1 import base from cloudkittyclient.v1 import report_cli and context including class names, function names, and sometimes code from other files: # Path: cloudkittyclient/tests/unit/v1/base.py # class BaseAPIEndpointTestCase(utils.BaseTestCase): # def setUp(self): # # Path: cloudkittyclient/v1/report_cli.py # class CliSummaryGet(lister.Lister): # class CliTotalGet(show.ShowOne): # class CliTenantList(lister.Lister): # def take_action(self, parsed_args): # def get_parser(self, prog_name): # def take_action(self, parsed_args): # def get_parser(self, prog_name): # def take_action(self, parsed_args): # def get_parser(self, prog_name): . Output only the next line.
def __get_client_from_osc(*args):
Predict the next line for this snippet: <|code_start|># # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # class TestSummary(base.BaseAPIEndpointTestCase): def test_get_summary(self): self.summary.get_summary() self.api_client.get.assert_called_once_with('/v2/summary') def test_get_summary_with_pagination_args(self): self.summary.get_summary(offset=10, limit=10) try: self.api_client.get.assert_called_once_with( '/v2/summary?limit=10&offset=10') except AssertionError: self.api_client.get.assert_called_once_with( '/v2/summary?offset=10&limit=10') def test_get_summary_filters(self): self.summary.get_summary( filters=OrderedDict([('one', 'two'), ('three', 'four')])) <|code_end|> with the help of current file imports: from collections import OrderedDict from cloudkittyclient.tests.unit.v2 import base and context from other files: # Path: cloudkittyclient/tests/unit/v2/base.py # class BaseAPIEndpointTestCase(utils.BaseTestCase): # def setUp(self): , which may contain function names, class names, or code. Output only the next line.
self.api_client.get.assert_called_once_with(
Predict the next line after this snippet: <|code_start|># Copyright 2019 Objectif Libre # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # class TestRating(base.BaseAPIEndpointTestCase): def test_get_modules(self): self.rating.get_module() <|code_end|> using the current file's imports: from cloudkittyclient.tests.unit.v2 import base and any relevant context from other files: # Path: cloudkittyclient/tests/unit/v2/base.py # class BaseAPIEndpointTestCase(utils.BaseTestCase): # def setUp(self): . Output only the next line.
self.api_client.get.assert_called_once_with('/v2/rating/modules')
Given the following code snippet before the placeholder: <|code_start|># License for the specific language governing permissions and limitations # under the License. # class TestReport(base.BaseAPIEndpointTestCase): def test_get_summary(self): self.report.get_summary() self.api_client.get.assert_called_once_with('/v1/report/summary') def test_get_summary_with_groupby(self): self.report.get_summary(groupby=['res_type', 'tenant_id']) self.api_client.get.assert_called_once_with( '/v1/report/summary?groupby=res_type%2Ctenant_id') def test_get_summary_with_begin_end(self): self.report.get_summary(begin='begin', end='end') try: self.api_client.get.assert_called_once_with( '/v1/report/summary?begin=begin&end=end') # Passing a dict to urlencode can change arg order except AssertionError: self.api_client.get.assert_called_once_with( '/v1/report/summary?end=end&begin=begin') def test_get_total(self): self.report.get_total() self.api_client.get.assert_called_once_with('/v1/report/total') <|code_end|> , predict the next line using imports from the current file: from cloudkittyclient.tests.unit.v1 import base and context including class names, function names, and sometimes code from other files: # Path: cloudkittyclient/tests/unit/v1/base.py # class BaseAPIEndpointTestCase(utils.BaseTestCase): # def setUp(self): . Output only the next line.
def test_get_total_with_begin_end(self):
Based on the snippet: <|code_start|># Copyright 2019 objectif Libre # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. class BaseAPIEndpointTestCase(utils.BaseTestCase): def setUp(self): super(BaseAPIEndpointTestCase, self).setUp() <|code_end|> , predict the immediate next line with the help of imports: from cloudkittyclient.tests import utils from cloudkittyclient.v2 import dataframes from cloudkittyclient.v2.rating import modules from cloudkittyclient.v2 import scope from cloudkittyclient.v2 import summary and context (classes, functions, sometimes code) from other files: # Path: cloudkittyclient/v2/dataframes.py # class DataframesManager(base.BaseManager): # def add_dataframes(self, **kwargs): # def get_dataframes(self, **kwargs): # # Path: cloudkittyclient/v2/rating/modules.py # class RatingManager(rating.RatingManager): # def get_module(self, **kwargs): # def update_module(self, **kwargs): # # Path: cloudkittyclient/v2/summary.py # class SummaryManager(base.BaseManager): # def get_summary(self, **kwargs): . Output only the next line.
self.api_client = utils.FakeHTTPClient()
Using the snippet: <|code_start|> os.replace(src=temp_path, dst=path) def has(self, *args, **kwargs): if not params_legal(args, kwargs): return None path = self.path_function(*args, **kwargs) return path.exists() class Storage: def __init__(self, storage_path): self.storage_path = pathlib.Path(storage_path) self.ids = StorageItem(self.path_ids) self.token = StorageItem(self.path_token) self.product = StorageItem(self.path_product, self.make_product) self.repository = StorageItem(self.path_repository) self.prices = StorageItem(self.path_prices, self.make_prices) self.prices_old = StorageItem(self.path_prices_old, self.make_prices) self.changelog = StorageItem(self.path_changelog, self.make_changelog) self.manifest_v1 = StorageItem(self.path_manifest_v1, compressed=True) self.manifest_v2 = StorageItem(self.path_manifest_v2, compressed=True) def __repr__(self): return f"Storage({repr(self.storage_path)})" def path_ids(self): return self.storage_path / "ids.json" def path_token(self): <|code_end|> , determine the next line of code. You have imports: import dataclasses import json import datetime import gzip import os import pathlib import itertools import string import gogdb.core.model as model from gogdb.core.dataclsloader import class_from_json and context (class names, function names, or code) available: # Path: gogdb/core/dataclsloader.py # def class_from_json(cls, data): # if data is None: # return None # if dataclasses.is_dataclass(cls): # if cls in annotations_cache: # annotations = annotations_cache.get(cls) # else: # annotations = typing.get_type_hints(cls) # annotations_cache[cls] = annotations # inst = cls() # for field_name, field_value in data.items(): # try: # field_type = annotations[field_name] # except KeyError: # raise KeyError("Invalid field {!r} in json. Valid fields for type {}: {!r}".format( # field_name, cls, list(annotations.keys()))) # try: # field_inst = class_from_json(field_type, field_value) # except TypeError: # raise TypeError(f"Failed to parse field {field_name}") # setattr(inst, field_name, field_inst) # return inst # elif get_origin(cls) is list: # list_element_type = get_args(cls)[0] # return [ # class_from_json(list_element_type, list_element) for # list_element in data] # elif cls is datetime.datetime: # return datetime.datetime.fromisoformat(data) # else: # if cls is not typing.Any: # if not (type(data) is cls or data is None): # raise TypeError(f"{repr(data)} is of type {type(data)}, {cls} required") # return data . Output only the next line.
return self.storage_path / "secret/token.json"
Using the snippet: <|code_start|> def build(prod_id, build_id): storagedb = get_storagedb() product = storagedb.product.load(prod_id) if product is None: flask.abort(404) repository_raw = storagedb.repository.load(prod_id, build_id) if repository_raw is None: flask.abort(404) <|code_end|> , determine the next line of code. You have imports: import flask import gogdb.core.buildloader as buildloader from gogdb.application.datasources import get_storagedb and context (class names, function names, or code) available: # Path: gogdb/application/datasources.py # def get_storagedb(): # if "storagedb" not in flask.g: # storage_path = flask.current_app.config["STORAGE_PATH"] # flask.g.storagedb = storage.Storage(storage_path) # # return flask.g.storagedb . Output only the next line.
build_data = [b for b in product.builds if b.id == build_id][0]
Based on the snippet: <|code_start|> #"installDirectory": "Fallout 2", #"projectName": "Fallout 2", "rootGameID": None, "support_commands": [], "timestamp": None } def load_repository_v1(data): source = FallbackDict(data["product"], REPOSITORY_V1_DEFAULTS) return model.RepositoryV1( timestamp = source["timestamp"], depots = [load_depot_v1(x) for x in source["depots"] if "manifest" in x], redists = [load_redist_v1(x) for x in source["depots"] if "manifest" not in x], support_commands = [load_support_command_v1(x) for x in source["support_commands"]], install_directory = source["installDirectory"], root_game_id = int_or_none(source["rootGameID"]), products = [load_repositoryproduct_v1(x) for x in source["gameIDs"]], name = source["projectName"] ) # Manifest V1 # =========== DEPOTITEM_V1_DEFAULTS = { "hash": None, "offset": 0, #"path": , "size": 0, "url": None, <|code_end|> , predict the immediate next line with the help of imports: import json import datetime import copy import gogdb.core.model as model from gogdb.core.normalization import normalize_system and context (classes, functions, sometimes code) from other files: # Path: gogdb/core/normalization.py # def normalize_system(system_name): # system_name = system_name.lower() # if system_name == "mac": # return "osx" # else: # return system_name . Output only the next line.
"symlinkType": None,
Using the snippet: <|code_start|> builds = orm.relationship( "Build", back_populates="product", cascade="all, delete-orphan", order_by="desc(Build.date_published)") pricehistory = orm.relationship( "PriceRecord", back_populates="product", cascade="all, delete-orphan", order_by="PriceRecord.date") changes = orm.relationship( "ChangeRecord", back_populates="product", cascade="all, delete-orphan", order_by="desc(ChangeRecord.id)") cs_systems = property( lambda self: get_systems_list(self, "cs_"), lambda self, v: set_systems_list(self, "cs_", v) ) comp_systems = property( lambda self: get_systems_list(self, "os_"), lambda self, v: set_systems_list(self, "os_", v) ) dl_systems = property( lambda self: get_systems_list(self, "dl_"), lambda self, v: set_systems_list(self, "dl_", v) ) @property def systems(self): if self.access >= 2: return self.comp_systems else: <|code_end|> , determine the next line of code. You have imports: import sqlalchemy as sql from sqlalchemy import orm from sqlalchemy import Column from gogdb.legacy.database import Base from gogdb.legacy.model.common import get_systems_list, set_systems_list and context (class names, function names, or code) available: # Path: gogdb/legacy/database.py # NAMING_CONVENTION = { # "ix": 'ix_%(column_0_label)s', # "uq": "uq_%(table_name)s_%(column_0_name)s", # "ck": "ck_%(table_name)s_%(constraint_name)s", # "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s", # "pk": "pk_%(table_name)s" # } # # Path: gogdb/legacy/model/common.py # def get_systems_list(self, prefix): # systems = [] # for system_name in ["windows", "mac", "linux"]: # if getattr(self, prefix + system_name) is None: # return None # elif getattr(self, prefix + system_name): # systems.append(system_name) # return systems # # def set_systems_list(self, prefix, systems): # for system_name in ["windows", "mac", "linux"]: # if system_name in systems: # setattr(self, prefix + system_name, True) # else: # setattr(self, prefix + system_name, False) . Output only the next line.
return self.dl_systems
Given snippet: <|code_start|> def __repr__(self): return "<Product(id={}, slug='{}')>".format(self.id, self.slug) class Language(Base): __tablename__ = "languages" prod_id = Column( sql.Integer, sql.ForeignKey("products.id"), primary_key=True) isocode = Column(sql.String(20), primary_key=True) product = orm.relationship("Product", back_populates="languages") def __repr__(self): return "<Language(prod_id={}, isocode='{}')>".format( self.prod_id, self.isocode) class Feature(Base): __tablename__ = "features" prod_id = Column( sql.Integer, sql.ForeignKey("products.id"), primary_key=True) slug = Column(sql.String(30), primary_key=True) product = orm.relationship("Product", back_populates="features") def __repr__(self): return "<Feature(prod_id={}, slug='{}')>".format( <|code_end|> , continue by predicting the next line. Consider current file imports: import sqlalchemy as sql from sqlalchemy import orm from sqlalchemy import Column from gogdb.legacy.database import Base from gogdb.legacy.model.common import get_systems_list, set_systems_list and context: # Path: gogdb/legacy/database.py # NAMING_CONVENTION = { # "ix": 'ix_%(column_0_label)s', # "uq": "uq_%(table_name)s_%(column_0_name)s", # "ck": "ck_%(table_name)s_%(constraint_name)s", # "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s", # "pk": "pk_%(table_name)s" # } # # Path: gogdb/legacy/model/common.py # def get_systems_list(self, prefix): # systems = [] # for system_name in ["windows", "mac", "linux"]: # if getattr(self, prefix + system_name) is None: # return None # elif getattr(self, prefix + system_name): # systems.append(system_name) # return systems # # def set_systems_list(self, prefix, systems): # for system_name in ["windows", "mac", "linux"]: # if system_name in systems: # setattr(self, prefix + system_name, True) # else: # setattr(self, prefix + system_name, False) which might include code, classes, or functions. Output only the next line.
self.prod_id, self.slug)
Given the code snippet: <|code_start|> class Product(Base): __tablename__ = "products" id = Column(sql.Integer, primary_key=True, autoincrement=False) title = Column(sql.String(120), nullable=True) slug = Column(sql.String(120), nullable=True) title_norm = Column(sql.String(120), default="", nullable=False) forum_id = Column(sql.String(120), nullable=True) product_type = Column(sql.String(20), nullable=True) is_secret = Column(sql.Boolean, nullable=True) is_price_visible = Column(sql.Boolean, nullable=True) can_be_reviewed = Column(sql.Boolean, nullable=True) base_prod_id = Column( sql.Integer, sql.ForeignKey("products.id"), nullable=True) cs_windows = Column(sql.Boolean, nullable=True) cs_mac = Column(sql.Boolean, nullable=True) cs_linux = Column(sql.Boolean, nullable=True) os_windows = Column(sql.Boolean, nullable=True) os_mac = Column(sql.Boolean, nullable=True) os_linux = Column(sql.Boolean, nullable=True) dl_windows = Column(sql.Boolean, nullable=True) <|code_end|> , generate the next line using the imports in this file: import sqlalchemy as sql from sqlalchemy import orm from sqlalchemy import Column from gogdb.legacy.database import Base from gogdb.legacy.model.common import get_systems_list, set_systems_list and context (functions, classes, or occasionally code) from other files: # Path: gogdb/legacy/database.py # NAMING_CONVENTION = { # "ix": 'ix_%(column_0_label)s', # "uq": "uq_%(table_name)s_%(column_0_name)s", # "ck": "ck_%(table_name)s_%(constraint_name)s", # "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s", # "pk": "pk_%(table_name)s" # } # # Path: gogdb/legacy/model/common.py # def get_systems_list(self, prefix): # systems = [] # for system_name in ["windows", "mac", "linux"]: # if getattr(self, prefix + system_name) is None: # return None # elif getattr(self, prefix + system_name): # systems.append(system_name) # return systems # # def set_systems_list(self, prefix, systems): # for system_name in ["windows", "mac", "linux"]: # if system_name in systems: # setattr(self, prefix + system_name, True) # else: # setattr(self, prefix + system_name, False) . Output only the next line.
dl_mac = Column(sql.Boolean, nullable=True)
Predict the next line after this snippet: <|code_start|> sql.Integer, sql.ForeignKey("products.id"), nullable=False) action = Column(sql.String(20), nullable=False) type_prim = Column(sql.String(40), nullable=False) type_sec = Column(sql.String(40), nullable=True) resource = Column(sql.String(120), nullable=False) old = Column(sql.String(120), nullable=True) new = Column(sql.String(120), nullable=True) @property def type(self): if self.type_sec: return self.type_prim + "." + self.type_sec else: return self.type_prim @property def old_int(self): if self.old is not None: return int(self.old) else: return None @property def new_int(self): if self.new is not None: return int(self.new) else: return None @property <|code_end|> using the current file's imports: import sqlalchemy as sql from sqlalchemy import orm from sqlalchemy import Column from gogdb.legacy.database import Base and any relevant context from other files: # Path: gogdb/legacy/database.py # NAMING_CONVENTION = { # "ix": 'ix_%(column_0_label)s', # "uq": "uq_%(table_name)s_%(column_0_name)s", # "ck": "ck_%(table_name)s_%(constraint_name)s", # "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s", # "pk": "pk_%(table_name)s" # } . Output only the next line.
def action_type(self):
Using the snippet: <|code_start|> ( idx_change.id, idx_change.title, idx_change.timestamp.timestamp(), idx_change.action, idx_change.category, idx_change.dl_type, idx_change.bonus_type, idx_change.property_name, json.dumps( idx_change.record, sort_keys=True, ensure_ascii=False, default=storage.json_encoder) ) ) summaries[changerec.timestamp].add(changerec.category) for timestamp, category_set in summaries.items(): category_str = ",".join(sorted(category_set)) cur.execute( "INSERT INTO changelog_summary VALUES (?, ?, ?, ?)", ( prod.id, prod.title, timestamp.timestamp(), category_str ) ) def index_main(db): <|code_end|> , determine the next line of code. You have imports: import json import sqlite3 import dataclasses import os import collections import logging import flask import gogdb.core.storage as storage import gogdb.core.model as model from gogdb.core.normalization import normalize_search, compress_systems and context (class names, function names, or code) available: # Path: gogdb/core/normalization.py # def normalize_search(search_str): # if search_str is None: # return "" # return "".join(c for c in search_str.lower() if c in NORMALIZED_CHARS) # # def compress_systems(systems): # """Compressed systems is just a string of the first letters""" # compressed = "" # for system in systems: # compressed += system[0] # return compressed . Output only the next line.
ids = db.ids.load()
Given the following code snippet before the placeholder: <|code_start|> if changerec.download_record.dl_old_bonus is not None: # Just set it potentially twice because it has to be the same value anyway idx_change.bonus_type = changerec.download_record.dl_old_bonus.bonus_type elif changerec.category == "property": idx_change.property_name = changerec.property_record.property_name cur.execute( "INSERT INTO changelog VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", ( idx_change.id, idx_change.title, idx_change.timestamp.timestamp(), idx_change.action, idx_change.category, idx_change.dl_type, idx_change.bonus_type, idx_change.property_name, json.dumps( idx_change.record, sort_keys=True, ensure_ascii=False, default=storage.json_encoder) ) ) summaries[changerec.timestamp].add(changerec.category) for timestamp, category_set in summaries.items(): category_str = ",".join(sorted(category_set)) cur.execute( "INSERT INTO changelog_summary VALUES (?, ?, ?, ?)", ( <|code_end|> , predict the next line using imports from the current file: import json import sqlite3 import dataclasses import os import collections import logging import flask import gogdb.core.storage as storage import gogdb.core.model as model from gogdb.core.normalization import normalize_search, compress_systems and context including class names, function names, and sometimes code from other files: # Path: gogdb/core/normalization.py # def normalize_search(search_str): # if search_str is None: # return "" # return "".join(c for c in search_str.lower() if c in NORMALIZED_CHARS) # # def compress_systems(systems): # """Compressed systems is just a string of the first letters""" # compressed = "" # for system in systems: # compressed += system[0] # return compressed . Output only the next line.
prod.id,
Next line prediction: <|code_start|> id = Column(sql.Integer, primary_key=True, autoincrement=True) repo_id = Column( sql.Integer, sql.ForeignKey("repository_v2.id"), nullable=False) manifest_id = Column( sql.Integer, sql.ForeignKey("depotmanifest_v2.id"), nullable=False) size = Column(sql.BigInteger, nullable=False) prod_id = Column(sql.Integer, nullable=False) is_gog_depot = Column(sql.Boolean, nullable=False) #bitness = Column(sql.String(50), nullable=True) bitness_32 = Column(sql.Boolean, nullable=True) bitness_64 = Column(sql.Boolean, nullable=True) is_offline = Column(sql.Boolean, nullable=False) languages_rel = orm.relationship( "DepotLangV2", cascade="all, delete-orphan") manifest = orm.relationship("DepotManifestV2", cascade="all") @property def languages(self): return [lang.lang for lang in self.languages_rel] @languages.setter def languages(self, value): self.languages_rel = [DepotLangV2(lang=lang) for lang in value] @property def bitness(self): values = [] <|code_end|> . Use current file imports: (import sqlalchemy as sql from sqlalchemy import orm from sqlalchemy import Column from gogdb.legacy.database import Base from gogdb.legacy.model.common import get_systems_list, set_systems_list) and context including class names, function names, or small code snippets from other files: # Path: gogdb/legacy/database.py # NAMING_CONVENTION = { # "ix": 'ix_%(column_0_label)s', # "uq": "uq_%(table_name)s_%(column_0_name)s", # "ck": "ck_%(table_name)s_%(constraint_name)s", # "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s", # "pk": "pk_%(table_name)s" # } # # Path: gogdb/legacy/model/common.py # def get_systems_list(self, prefix): # systems = [] # for system_name in ["windows", "mac", "linux"]: # if getattr(self, prefix + system_name) is None: # return None # elif getattr(self, prefix + system_name): # systems.append(system_name) # return systems # # def set_systems_list(self, prefix, systems): # for system_name in ["windows", "mac", "linux"]: # if system_name in systems: # setattr(self, prefix + system_name, True) # else: # setattr(self, prefix + system_name, False) . Output only the next line.
if self.bitness_32 is True: values.append("32")
Predict the next line for this snippet: <|code_start|> class DlFile(Base): __tablename__ = "files" __table_args__ = (sql.UniqueConstraint("download_id", "slug"),) download_id = Column(sql.Integer, sql.ForeignKey("downloads.id"), <|code_end|> with the help of current file imports: import sqlalchemy as sql from sqlalchemy import orm from sqlalchemy import Column from gogdb.legacy.database import Base and context from other files: # Path: gogdb/legacy/database.py # NAMING_CONVENTION = { # "ix": 'ix_%(column_0_label)s', # "uq": "uq_%(table_name)s_%(column_0_name)s", # "ck": "ck_%(table_name)s_%(constraint_name)s", # "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s", # "pk": "pk_%(table_name)s" # } , which may contain function names, class names, or code. Output only the next line.
primary_key=True, autoincrement=False)
Given snippet: <|code_start|> class PriceRecord(Base): __tablename__ = "pricerecords" id = Column(sql.Integer, primary_key=True, autoincrement=True) prod_id = Column(sql.Integer, sql.ForeignKey("products.id"), nullable=False) price_base = Column(sql.Numeric, nullable=True) price_final = Column(sql.Numeric, nullable=True) date = Column(sql.DateTime, nullable=False) product = orm.relationship("Product", back_populates="pricehistory") @property def discount(self): if self.price_base == 0: # If the product is free the final price is 100% of the base price price_fract = 1 elif self.price_final is None or self.price_base is None: # No discounts for products not for sale return None else: price_fract = self.price_final / self.price_base discount_rounded = int(round((1 - price_fract) * 100)) # Round discounts ending with 9 or 1 if (discount_rounded % 10) == 9: discount_rounded += 1 elif (discount_rounded % 10) == 1: discount_rounded -= 1 <|code_end|> , continue by predicting the next line. Consider current file imports: import sqlalchemy as sql from sqlalchemy import orm from sqlalchemy import Column from gogdb.legacy.database import Base and context: # Path: gogdb/legacy/database.py # NAMING_CONVENTION = { # "ix": 'ix_%(column_0_label)s', # "uq": "uq_%(table_name)s_%(column_0_name)s", # "ck": "ck_%(table_name)s_%(constraint_name)s", # "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s", # "pk": "pk_%(table_name)s" # } which might include code, classes, or functions. Output only the next line.
return discount_rounded
Using the snippet: <|code_start|> magnitude = int(math.floor(math.log(num, 1000))) val = num / math.pow(1000, magnitude) if magnitude >= len(BINARY_PREFIXES): magnitude = len(BINARY_PREFIXES) - 1 prefix = BINARY_PREFIXES[magnitude] if magnitude == 0: return '{:.0f}{}'.format(val, unit) if val >= 100: return '{:.0f}{}{}'.format(val, prefix, unit) elif val >= 10: return '{:.0f}{}{}'.format(val, prefix, unit) else: return '{:.1f}{}{}'.format(val, prefix, unit) def add_tree_item(tree, item): parts = pathlib.PureWindowsPath(item.path).parts head = parts[:-1] # Everything leading up to the last item in the path tail = parts[-1] # Last item of the path cur_level = tree # Walk down the tree one path component at a time for part in head: # Handle malformed manifests where links are inside links if getattr(cur_level, "type", None) == "link": return if part not in cur_level: # Directory does not yet exist, create it cur_level[part] = {} cur_level = cur_level[part] if item.type == "file": cur_level[tail] = item <|code_end|> , determine the next line of code. You have imports: import io import math import pathlib import flask import gogdb.core.buildloader as buildloader from gogdb.application.datasources import get_storagedb and context (class names, function names, or code) available: # Path: gogdb/application/datasources.py # def get_storagedb(): # if "storagedb" not in flask.g: # storage_path = flask.current_app.config["STORAGE_PATH"] # flask.g.storagedb = storage.Storage(storage_path) # # return flask.g.storagedb . Output only the next line.
elif item.type == "dir":
Predict the next line for this snippet: <|code_start|> PRODUCTS_PER_PAGE = 20 def product_list(): page = int(flask.request.args.get("page", "1")) search = flask.request.args.get("search", "").strip() # Filter illegal characters and resulting empty strings search_words = list(filter(None, (normalize_search(word) for word in search.split()))) cur = get_indexdb().cursor() if len(search) == 10 and search.isdecimal(): return flask.redirect(flask.url_for("product_info", prod_id=search), 303) elif search_words: query_filters = [] # Add a filter for each search word <|code_end|> with the help of current file imports: import string import datetime import flask import gogdb.core.model as model from gogdb.views.pagination import calc_pageinfo from gogdb.core.normalization import normalize_search, decompress_systems from gogdb.application.datasources import get_indexdb and context from other files: # Path: gogdb/views/pagination.py # def calc_pageinfo(page, num_products, items_per_page): # num_pages = int(math.ceil(num_products / items_per_page)) # page = min(max(page, 1), num_pages) # offset = (page - 1) * items_per_page # page_info = { # "is_first": page == 1, # "is_last": page == num_pages, # "page": page, # "num_pages": num_pages, # "from": offset, # "to": offset + items_per_page, # "prev_link": "", # Filled in later # "next_link": "" # } # return page_info # # Path: gogdb/core/normalization.py # def normalize_search(search_str): # if search_str is None: # return "" # return "".join(c for c in search_str.lower() if c in NORMALIZED_CHARS) # # def decompress_systems(compressed): # systems = [] # decompress_map = { # "w": "windows", # "l": "linux", # "o": "osx" # } # for letter in compressed: # systems.append(decompress_map[letter]) # return systems # # Path: gogdb/application/datasources.py # def get_indexdb(): # if "indexdb" not in flask.g: # storagedb = get_storagedb() # index_path = storagedb.path_indexdb() # flask.g.indexdb = sqlite3.connect(index_path) # flask.g.indexdb.row_factory = sqlite3.Row # # return flask.g.indexdb , which may contain function names, class names, or code. Output only the next line.
for word in search_words:
Based on the snippet: <|code_start|> order_string = "sale_rank DESC, LENGTH(title) ASC" else: filter_string = "" order_string = "sale_rank DESC" cur.execute("SELECT COUNT(*) FROM products {};".format(filter_string)) num_products = cur.fetchone()[0] page_info = calc_pageinfo(page, num_products, PRODUCTS_PER_PAGE) cur.execute( "SELECT * FROM products {} ORDER BY {} LIMIT ? OFFSET ?;".format(filter_string, order_string), (PRODUCTS_PER_PAGE, page_info["from"]) ) products = [] for prod_res in cur: idx_prod = model.IndexProduct( id = prod_res["product_id"], title = prod_res["title"], image_logo = prod_res["image_logo"], type = prod_res["product_type"], comp_systems = decompress_systems(prod_res["comp_systems"]), sale_rank = prod_res["sale_rank"], search_title = prod_res["search_title"] ) products.append(idx_prod) if search: page_info["prev_link"] = flask.url_for( "product_list", page=page_info["page"] - 1, search=search) page_info["next_link"] = flask.url_for( <|code_end|> , predict the immediate next line with the help of imports: import string import datetime import flask import gogdb.core.model as model from gogdb.views.pagination import calc_pageinfo from gogdb.core.normalization import normalize_search, decompress_systems from gogdb.application.datasources import get_indexdb and context (classes, functions, sometimes code) from other files: # Path: gogdb/views/pagination.py # def calc_pageinfo(page, num_products, items_per_page): # num_pages = int(math.ceil(num_products / items_per_page)) # page = min(max(page, 1), num_pages) # offset = (page - 1) * items_per_page # page_info = { # "is_first": page == 1, # "is_last": page == num_pages, # "page": page, # "num_pages": num_pages, # "from": offset, # "to": offset + items_per_page, # "prev_link": "", # Filled in later # "next_link": "" # } # return page_info # # Path: gogdb/core/normalization.py # def normalize_search(search_str): # if search_str is None: # return "" # return "".join(c for c in search_str.lower() if c in NORMALIZED_CHARS) # # def decompress_systems(compressed): # systems = [] # decompress_map = { # "w": "windows", # "l": "linux", # "o": "osx" # } # for letter in compressed: # systems.append(decompress_map[letter]) # return systems # # Path: gogdb/application/datasources.py # def get_indexdb(): # if "indexdb" not in flask.g: # storagedb = get_storagedb() # index_path = storagedb.path_indexdb() # flask.g.indexdb = sqlite3.connect(index_path) # flask.g.indexdb.row_factory = sqlite3.Row # # return flask.g.indexdb . Output only the next line.
"product_list", page=page_info["page"] + 1, search=search)
Given the following code snippet before the placeholder: <|code_start|> def product_list(): page = int(flask.request.args.get("page", "1")) search = flask.request.args.get("search", "").strip() # Filter illegal characters and resulting empty strings search_words = list(filter(None, (normalize_search(word) for word in search.split()))) cur = get_indexdb().cursor() if len(search) == 10 and search.isdecimal(): return flask.redirect(flask.url_for("product_info", prod_id=search), 303) elif search_words: query_filters = [] # Add a filter for each search word for word in search_words: # Should not be injectable because words are filtered word_cond = "search_title LIKE '%{}%'".format(word) query_filters.append(word_cond) filter_string = "WHERE " + " AND ".join(query_filters) order_string = "sale_rank DESC, LENGTH(title) ASC" else: filter_string = "" order_string = "sale_rank DESC" cur.execute("SELECT COUNT(*) FROM products {};".format(filter_string)) num_products = cur.fetchone()[0] page_info = calc_pageinfo(page, num_products, PRODUCTS_PER_PAGE) cur.execute( <|code_end|> , predict the next line using imports from the current file: import string import datetime import flask import gogdb.core.model as model from gogdb.views.pagination import calc_pageinfo from gogdb.core.normalization import normalize_search, decompress_systems from gogdb.application.datasources import get_indexdb and context including class names, function names, and sometimes code from other files: # Path: gogdb/views/pagination.py # def calc_pageinfo(page, num_products, items_per_page): # num_pages = int(math.ceil(num_products / items_per_page)) # page = min(max(page, 1), num_pages) # offset = (page - 1) * items_per_page # page_info = { # "is_first": page == 1, # "is_last": page == num_pages, # "page": page, # "num_pages": num_pages, # "from": offset, # "to": offset + items_per_page, # "prev_link": "", # Filled in later # "next_link": "" # } # return page_info # # Path: gogdb/core/normalization.py # def normalize_search(search_str): # if search_str is None: # return "" # return "".join(c for c in search_str.lower() if c in NORMALIZED_CHARS) # # def decompress_systems(compressed): # systems = [] # decompress_map = { # "w": "windows", # "l": "linux", # "o": "osx" # } # for letter in compressed: # systems.append(decompress_map[letter]) # return systems # # Path: gogdb/application/datasources.py # def get_indexdb(): # if "indexdb" not in flask.g: # storagedb = get_storagedb() # index_path = storagedb.path_indexdb() # flask.g.indexdb = sqlite3.connect(index_path) # flask.g.indexdb.row_factory = sqlite3.Row # # return flask.g.indexdb . Output only the next line.
"SELECT * FROM products {} ORDER BY {} LIMIT ? OFFSET ?;".format(filter_string, order_string),
Predict the next line for this snippet: <|code_start|> if len(search) == 10 and search.isdecimal(): return flask.redirect(flask.url_for("product_info", prod_id=search), 303) elif search_words: query_filters = [] # Add a filter for each search word for word in search_words: # Should not be injectable because words are filtered word_cond = "search_title LIKE '%{}%'".format(word) query_filters.append(word_cond) filter_string = "WHERE " + " AND ".join(query_filters) order_string = "sale_rank DESC, LENGTH(title) ASC" else: filter_string = "" order_string = "sale_rank DESC" cur.execute("SELECT COUNT(*) FROM products {};".format(filter_string)) num_products = cur.fetchone()[0] page_info = calc_pageinfo(page, num_products, PRODUCTS_PER_PAGE) cur.execute( "SELECT * FROM products {} ORDER BY {} LIMIT ? OFFSET ?;".format(filter_string, order_string), (PRODUCTS_PER_PAGE, page_info["from"]) ) products = [] for prod_res in cur: idx_prod = model.IndexProduct( id = prod_res["product_id"], title = prod_res["title"], image_logo = prod_res["image_logo"], <|code_end|> with the help of current file imports: import string import datetime import flask import gogdb.core.model as model from gogdb.views.pagination import calc_pageinfo from gogdb.core.normalization import normalize_search, decompress_systems from gogdb.application.datasources import get_indexdb and context from other files: # Path: gogdb/views/pagination.py # def calc_pageinfo(page, num_products, items_per_page): # num_pages = int(math.ceil(num_products / items_per_page)) # page = min(max(page, 1), num_pages) # offset = (page - 1) * items_per_page # page_info = { # "is_first": page == 1, # "is_last": page == num_pages, # "page": page, # "num_pages": num_pages, # "from": offset, # "to": offset + items_per_page, # "prev_link": "", # Filled in later # "next_link": "" # } # return page_info # # Path: gogdb/core/normalization.py # def normalize_search(search_str): # if search_str is None: # return "" # return "".join(c for c in search_str.lower() if c in NORMALIZED_CHARS) # # def decompress_systems(compressed): # systems = [] # decompress_map = { # "w": "windows", # "l": "linux", # "o": "osx" # } # for letter in compressed: # systems.append(decompress_map[letter]) # return systems # # Path: gogdb/application/datasources.py # def get_indexdb(): # if "indexdb" not in flask.g: # storagedb = get_storagedb() # index_path = storagedb.path_indexdb() # flask.g.indexdb = sqlite3.connect(index_path) # flask.g.indexdb.row_factory = sqlite3.Row # # return flask.g.indexdb , which may contain function names, class names, or code. Output only the next line.
type = prod_res["product_type"],
Predict the next line for this snippet: <|code_start|> async def fetch_repo_v1(self, repo_url, prod_id, build_id): return await self.get_json( f"repo v1 {repo_url}", url=repo_url, path=self.storage_path / f"raw/repo_v1/{prod_id}_{build_id}.json", caching=self.config.get("CACHE_REPO_V1", CACHE_NONE) ) async def fetch_manifest_v1(self, mf_name, manifest_url): return await self.get_json( f"manifest v1 {mf_name}", url=manifest_url, path=None, caching=CACHE_NONE ) async def fetch_repo_v2(self, repo_url, prod_id, build_id): return await self.get_json( f"repo v2 {repo_url}", url=repo_url, path=self.storage_path / f"raw/repo_v2/{prod_id}_{build_id}.json", caching=self.config.get("CACHE_REPO_V2", CACHE_NONE), decompress=True ) async def fetch_manifest_v2(self, manifest_id): manifest_url = "https://cdn.gog.com/content-system/v2/meta/{}/{}/{}".format( manifest_id[0:2], manifest_id[2:4], manifest_id) return await self.get_json( f"manifest v2 {manifest_id}", <|code_end|> with the help of current file imports: import pathlib import logging import json import zlib import os import aiohttp import gogdb.core.storage as storage from gogdb.updater.gogtoken import GogToken and context from other files: # Path: gogdb/updater/gogtoken.py # class GogToken: # def __init__(self, aio_session, client_id=GALAXY_ID, client_secret=GALAXY_SECRET): # self.aio_session = aio_session # self.client_id = client_id # self.client_secret = client_secret # # self.lock = asyncio.Lock() # # @classmethod # def from_file(cls, aio_session, filename): # token = cls(aio_session) # token.load(filename) # return token # # @classmethod # async def from_code(cls, aio_session, login_code, client_id=GALAXY_ID, client_secret=GALAXY_SECRET): # token_query = { # "client_id": client_id, # "client_secret": client_secret, # "grant_type": "authorization_code", # "code": login_code, # "redirect_uri": REDIRECT_URL # Needed for origin verification # } # token_resp = await aio_session.get(TOKEN_URL, params=token_query) # token = cls(aio_session, client_id, client_secret) # token.set_data(await token_resp.json()) # return token # # def set_data(self, token_data): # if "error" in token_data: # raise AuthError(token_data["error"], token_data["error_description"]) # # if "client_id" in token_data: # self.client_id = token_data["client_id"] # if "client_secret" in token_data: # self.client_secret = token_data["client_secret"] # self.access_token = token_data["access_token"] # self.refresh_token = token_data["refresh_token"] # self.expires_in = timedelta(seconds=token_data["expires_in"]) # self.scope = token_data["scope"] # self.session_id = token_data["session_id"] # self.token_type = token_data["token_type"] # self.user_id = token_data["user_id"] # if "created" in token_data: # self.created = datetime.fromtimestamp( # token_data["created"], tz=timezone.utc) # else: # self.created = datetime.now(tz=timezone.utc) # # def get_data(self): # token_data = { # "client_id": self.client_id, # "client_secret": self.client_secret, # "access_token": self.access_token, # "refresh_token": self.refresh_token, # "expires_in": int(self.expires_in.total_seconds()), # "scope": self.scope, # "session_id": self.session_id, # "token_type": self.token_type, # "user_id": self.user_id, # "created": int(self.created.timestamp()) # } # return token_data # # def load(self, filename): # with open(filename, "r") as f: # self.set_data(json.load(f)) # # def save(self, filename): # with open(filename, "w") as f: # json.dump(self.get_data(), f, indent=2, sort_keys=True) # # async def refresh(self, refresh_token=None): # if refresh_token is None: # refresh_token = self.refresh_token # token_query = { # "client_id": self.client_id, # "client_secret": self.client_secret, # "grant_type": "refresh_token", # "refresh_token": refresh_token # } # token_resp = await self.aio_session.get(TOKEN_URL, params=token_query) # self.set_data(await token_resp.json()) # # def expired(self, margin=timedelta(seconds=60)): # expires_at = self.created + self.expires_in # return (datetime.now(timezone.utc) - expires_at) > margin # # async def refresh_if_expired(self, refresh_token=None, margin=timedelta(seconds=60)): # await self.lock.acquire() # expired = self.expired(margin) # if expired: # await self.refresh(refresh_token) # self.lock.release() # return expired # # def __repr__(self): # return repr(self.__dict__) , which may contain function names, class names, or code. Output only the next line.
url=manifest_url,
Given snippet: <|code_start|> n_prod.dlcs = [l_dlc.id for l_dlc in l_prod.dlcs] n_prod.description = l_prod.description_full n_prod.changelog = l_prod.changelog or None for l_dl in l_prod.downloads: if l_dl.deleted: continue if l_dl.type == "bonus_content": n_prod.dl_bonus.append(convert_bonusdl(l_dl, l_prod.id)) elif l_dl.type == "installers": n_prod.dl_installer.append(convert_softwaredl(l_dl, l_prod.id)) elif l_dl.type == "language_packs": n_prod.dl_langpack.append(convert_softwaredl(l_dl, l_prod.id)) elif l_dl.type == "patches": n_prod.dl_patch.append(convert_softwaredl(l_dl, l_prod.id)) for l_build in l_prod.builds: if l_build.generation == 1: manifest_url = "https://cdn.gog.com/content-system/v1/manifests/{}/windows/{}/repository.json".format( l_prod.id, l_build.legacy_build_id) elif l_build.generation == 2: manifest_url = "https://cdn.gog.com/content-system/v2/meta/{}/{}/{}".format( l_build.meta_id[0:2], l_build.meta_id[2:4], l_build.meta_id) n_prod.builds.append(new_model.Build( id = l_build.build_id, product_id = l_build.prod_id, os = normalize_system(l_build.os), branch = None, <|code_end|> , continue by predicting the next line. Consider current file imports: import sys import datetime import copy import itertools import sqlalchemy import flask import gogdb.legacy.model as legacy_model import gogdb.core.storage import gogdb.core.model as new_model import gogdb.core.changelogger as changelogger from gogdb.core.normalization import normalize_system and context: # Path: gogdb/core/normalization.py # def normalize_system(system_name): # system_name = system_name.lower() # if system_name == "mac": # return "osx" # else: # return system_name which might include code, classes, or functions. Output only the next line.
version = l_build.version,
Here is a snippet: <|code_start|> cur_history = [] changelog = storagedb.changelog.load(prod_id) history_chart = {"labels": [], "values": [], "max": 0} if cur_history: current_price = copy.copy(cur_history[-1]) current_price.date = datetime.datetime.now(datetime.timezone.utc) cur_history.append(current_price) last_price = None for entry in cur_history: if entry.price_final is not None: history_chart["labels"].append(entry.date.isoformat()) history_chart["values"].append(str(entry.price_final_decimal)) history_chart["max"] = max( history_chart["max"], entry.price_final_decimal) elif last_price is not None: history_chart["labels"].append(entry.date.isoformat()) history_chart["values"].append(str(last_price)) history_chart["labels"].append(entry.date.isoformat()) history_chart["values"].append(None) last_price = entry.price_final_decimal history_chart["max"] = float(history_chart["max"]) priceframes = [] for start, end in zip(cur_history[:-1], cur_history[1:]): frame = { "start": start.date, "end": end.date, "discount": start.discount, "price_final": start.price_final_decimal, <|code_end|> . Write the next line using the current file imports: import copy import datetime import itertools import flask import gogdb.core.model as model from gogdb.application.datasources import get_storagedb, get_indexdb from gogdb.core.normalization import decompress_systems and context from other files: # Path: gogdb/application/datasources.py # def get_storagedb(): # if "storagedb" not in flask.g: # storage_path = flask.current_app.config["STORAGE_PATH"] # flask.g.storagedb = storage.Storage(storage_path) # # return flask.g.storagedb # # def get_indexdb(): # if "indexdb" not in flask.g: # storagedb = get_storagedb() # index_path = storagedb.path_indexdb() # flask.g.indexdb = sqlite3.connect(index_path) # flask.g.indexdb.row_factory = sqlite3.Row # # return flask.g.indexdb # # Path: gogdb/core/normalization.py # def decompress_systems(compressed): # systems = [] # decompress_map = { # "w": "windows", # "l": "linux", # "o": "osx" # } # for letter in compressed: # systems.append(decompress_map[letter]) # return systems , which may include functions, classes, or code. Output only the next line.
"price_base": start.price_base_decimal
Given snippet: <|code_start|> comp_systems = [] def __init__(self, product_id): self.id = product_id def product_info(prod_id): storagedb = get_storagedb() product = storagedb.product.load(prod_id) if product is None: flask.abort(404) # Allow loading pre 2019 prices if flask.request.args.get("old"): pricehistory = storagedb.prices_old.load(prod_id) has_old_prices = True else: pricehistory = storagedb.prices.load(prod_id) has_old_prices = False if pricehistory: cur_history = pricehistory["US"]["USD"] else: cur_history = [] changelog = storagedb.changelog.load(prod_id) history_chart = {"labels": [], "values": [], "max": 0} if cur_history: current_price = copy.copy(cur_history[-1]) current_price.date = datetime.datetime.now(datetime.timezone.utc) <|code_end|> , continue by predicting the next line. Consider current file imports: import copy import datetime import itertools import flask import gogdb.core.model as model from gogdb.application.datasources import get_storagedb, get_indexdb from gogdb.core.normalization import decompress_systems and context: # Path: gogdb/application/datasources.py # def get_storagedb(): # if "storagedb" not in flask.g: # storage_path = flask.current_app.config["STORAGE_PATH"] # flask.g.storagedb = storage.Storage(storage_path) # # return flask.g.storagedb # # def get_indexdb(): # if "indexdb" not in flask.g: # storagedb = get_storagedb() # index_path = storagedb.path_indexdb() # flask.g.indexdb = sqlite3.connect(index_path) # flask.g.indexdb.row_factory = sqlite3.Row # # return flask.g.indexdb # # Path: gogdb/core/normalization.py # def decompress_systems(compressed): # systems = [] # decompress_map = { # "w": "windows", # "l": "linux", # "o": "osx" # } # for letter in compressed: # systems.append(decompress_map[letter]) # return systems which might include code, classes, or functions. Output only the next line.
cur_history.append(current_price)
Continue the code snippet: <|code_start|> "dlcs": product.dlcs } all_references = set(itertools.chain.from_iterable(referenced_ids.values())) all_products = {} if all_references: cur = get_indexdb().cursor() placeholders = ", ".join(itertools.repeat("?", len(all_references))) cur.execute( "SELECT * FROM products WHERE product_id IN ({})".format(placeholders), tuple(all_references) ) for prod_res in cur: idx_prod = model.IndexProduct( id = prod_res["product_id"], title = prod_res["title"], image_logo = prod_res["image_logo"], type = prod_res["product_type"], comp_systems = decompress_systems(prod_res["comp_systems"]), sale_rank = prod_res["sale_rank"], search_title = prod_res["search_title"] ) all_products[idx_prod.id] = idx_prod referenced_products = { key: [all_products.get(ref_id, MockProduct(ref_id)) for ref_id in ref_ids] for key, ref_ids in referenced_ids.items() } return flask.render_template( "product_info.html", product=product, <|code_end|> . Use current file imports: import copy import datetime import itertools import flask import gogdb.core.model as model from gogdb.application.datasources import get_storagedb, get_indexdb from gogdb.core.normalization import decompress_systems and context (classes, functions, or code) from other files: # Path: gogdb/application/datasources.py # def get_storagedb(): # if "storagedb" not in flask.g: # storage_path = flask.current_app.config["STORAGE_PATH"] # flask.g.storagedb = storage.Storage(storage_path) # # return flask.g.storagedb # # def get_indexdb(): # if "indexdb" not in flask.g: # storagedb = get_storagedb() # index_path = storagedb.path_indexdb() # flask.g.indexdb = sqlite3.connect(index_path) # flask.g.indexdb.row_factory = sqlite3.Row # # return flask.g.indexdb # # Path: gogdb/core/normalization.py # def decompress_systems(compressed): # systems = [] # decompress_map = { # "w": "windows", # "l": "linux", # "o": "osx" # } # for letter in compressed: # systems.append(decompress_map[letter]) # return systems . Output only the next line.
referenced_products=referenced_products,
Based on the snippet: <|code_start|> recordgroups = [] for groupkey, items in itertools.groupby( changes, key=lambda record: (record.timestamp, record.id)): recordgroups.append(list(items)) page_info["prev_link"] = flask.url_for( view, page=page_info["page"] - 1) page_info["next_link"] = flask.url_for( view, page=page_info["page"] + 1) if view == "changelog_atom": response = flask.make_response(flask.render_template( "changelog_ext.xml", changes=recordgroups, page_info=page_info )) response.mimetype = "application/atom+xml" return response else: return flask.render_template( "changelog_ext.html", changes=recordgroups, page_info=page_info ) def changelog_atom(): return changelog_ext_page("changelog_atom") <|code_end|> , predict the immediate next line with the help of imports: import itertools import datetime import json import flask import gogdb.core.model as model from gogdb.views.pagination import calc_pageinfo from gogdb.application.datasources import get_indexdb from gogdb.core.dataclsloader import class_from_json and context (classes, functions, sometimes code) from other files: # Path: gogdb/views/pagination.py # def calc_pageinfo(page, num_products, items_per_page): # num_pages = int(math.ceil(num_products / items_per_page)) # page = min(max(page, 1), num_pages) # offset = (page - 1) * items_per_page # page_info = { # "is_first": page == 1, # "is_last": page == num_pages, # "page": page, # "num_pages": num_pages, # "from": offset, # "to": offset + items_per_page, # "prev_link": "", # Filled in later # "next_link": "" # } # return page_info # # Path: gogdb/application/datasources.py # def get_indexdb(): # if "indexdb" not in flask.g: # storagedb = get_storagedb() # index_path = storagedb.path_indexdb() # flask.g.indexdb = sqlite3.connect(index_path) # flask.g.indexdb.row_factory = sqlite3.Row # # return flask.g.indexdb # # Path: gogdb/core/dataclsloader.py # def class_from_json(cls, data): # if data is None: # return None # if dataclasses.is_dataclass(cls): # if cls in annotations_cache: # annotations = annotations_cache.get(cls) # else: # annotations = typing.get_type_hints(cls) # annotations_cache[cls] = annotations # inst = cls() # for field_name, field_value in data.items(): # try: # field_type = annotations[field_name] # except KeyError: # raise KeyError("Invalid field {!r} in json. Valid fields for type {}: {!r}".format( # field_name, cls, list(annotations.keys()))) # try: # field_inst = class_from_json(field_type, field_value) # except TypeError: # raise TypeError(f"Failed to parse field {field_name}") # setattr(inst, field_name, field_inst) # return inst # elif get_origin(cls) is list: # list_element_type = get_args(cls)[0] # return [ # class_from_json(list_element_type, list_element) for # list_element in data] # elif cls is datetime.datetime: # return datetime.datetime.fromisoformat(data) # else: # if cls is not typing.Any: # if not (type(data) is cls or data is None): # raise TypeError(f"{repr(data)} is of type {type(data)}, {cls} required") # return data . Output only the next line.
def changelog_ext():
Based on the snippet: <|code_start|> record = class_from_json(model.ChangeRecord, record_dict) ) changes.append(change) recordgroups = [] for groupkey, items in itertools.groupby( changes, key=lambda record: (record.timestamp, record.id)): recordgroups.append(list(items)) page_info["prev_link"] = flask.url_for( view, page=page_info["page"] - 1) page_info["next_link"] = flask.url_for( view, page=page_info["page"] + 1) if view == "changelog_atom": response = flask.make_response(flask.render_template( "changelog_ext.xml", changes=recordgroups, page_info=page_info )) response.mimetype = "application/atom+xml" return response else: return flask.render_template( "changelog_ext.html", changes=recordgroups, page_info=page_info ) <|code_end|> , predict the immediate next line with the help of imports: import itertools import datetime import json import flask import gogdb.core.model as model from gogdb.views.pagination import calc_pageinfo from gogdb.application.datasources import get_indexdb from gogdb.core.dataclsloader import class_from_json and context (classes, functions, sometimes code) from other files: # Path: gogdb/views/pagination.py # def calc_pageinfo(page, num_products, items_per_page): # num_pages = int(math.ceil(num_products / items_per_page)) # page = min(max(page, 1), num_pages) # offset = (page - 1) * items_per_page # page_info = { # "is_first": page == 1, # "is_last": page == num_pages, # "page": page, # "num_pages": num_pages, # "from": offset, # "to": offset + items_per_page, # "prev_link": "", # Filled in later # "next_link": "" # } # return page_info # # Path: gogdb/application/datasources.py # def get_indexdb(): # if "indexdb" not in flask.g: # storagedb = get_storagedb() # index_path = storagedb.path_indexdb() # flask.g.indexdb = sqlite3.connect(index_path) # flask.g.indexdb.row_factory = sqlite3.Row # # return flask.g.indexdb # # Path: gogdb/core/dataclsloader.py # def class_from_json(cls, data): # if data is None: # return None # if dataclasses.is_dataclass(cls): # if cls in annotations_cache: # annotations = annotations_cache.get(cls) # else: # annotations = typing.get_type_hints(cls) # annotations_cache[cls] = annotations # inst = cls() # for field_name, field_value in data.items(): # try: # field_type = annotations[field_name] # except KeyError: # raise KeyError("Invalid field {!r} in json. Valid fields for type {}: {!r}".format( # field_name, cls, list(annotations.keys()))) # try: # field_inst = class_from_json(field_type, field_value) # except TypeError: # raise TypeError(f"Failed to parse field {field_name}") # setattr(inst, field_name, field_inst) # return inst # elif get_origin(cls) is list: # list_element_type = get_args(cls)[0] # return [ # class_from_json(list_element_type, list_element) for # list_element in data] # elif cls is datetime.datetime: # return datetime.datetime.fromisoformat(data) # else: # if cls is not typing.Any: # if not (type(data) is cls or data is None): # raise TypeError(f"{repr(data)} is of type {type(data)}, {cls} required") # return data . Output only the next line.
def changelog_atom():
Here is a snippet: <|code_start|> title = change_res["product_title"], timestamp = datetime.datetime.fromtimestamp(change_res["timestamp"], datetime.timezone.utc), action = change_res["action"], category = change_res["category"], dl_type = change_res["dl_type"], bonus_type = change_res["bonus_type"], property_name = change_res["property_name"], record = class_from_json(model.ChangeRecord, record_dict) ) changes.append(change) recordgroups = [] for groupkey, items in itertools.groupby( changes, key=lambda record: (record.timestamp, record.id)): recordgroups.append(list(items)) page_info["prev_link"] = flask.url_for( view, page=page_info["page"] - 1) page_info["next_link"] = flask.url_for( view, page=page_info["page"] + 1) if view == "changelog_atom": response = flask.make_response(flask.render_template( "changelog_ext.xml", changes=recordgroups, page_info=page_info )) response.mimetype = "application/atom+xml" return response <|code_end|> . Write the next line using the current file imports: import itertools import datetime import json import flask import gogdb.core.model as model from gogdb.views.pagination import calc_pageinfo from gogdb.application.datasources import get_indexdb from gogdb.core.dataclsloader import class_from_json and context from other files: # Path: gogdb/views/pagination.py # def calc_pageinfo(page, num_products, items_per_page): # num_pages = int(math.ceil(num_products / items_per_page)) # page = min(max(page, 1), num_pages) # offset = (page - 1) * items_per_page # page_info = { # "is_first": page == 1, # "is_last": page == num_pages, # "page": page, # "num_pages": num_pages, # "from": offset, # "to": offset + items_per_page, # "prev_link": "", # Filled in later # "next_link": "" # } # return page_info # # Path: gogdb/application/datasources.py # def get_indexdb(): # if "indexdb" not in flask.g: # storagedb = get_storagedb() # index_path = storagedb.path_indexdb() # flask.g.indexdb = sqlite3.connect(index_path) # flask.g.indexdb.row_factory = sqlite3.Row # # return flask.g.indexdb # # Path: gogdb/core/dataclsloader.py # def class_from_json(cls, data): # if data is None: # return None # if dataclasses.is_dataclass(cls): # if cls in annotations_cache: # annotations = annotations_cache.get(cls) # else: # annotations = typing.get_type_hints(cls) # annotations_cache[cls] = annotations # inst = cls() # for field_name, field_value in data.items(): # try: # field_type = annotations[field_name] # except KeyError: # raise KeyError("Invalid field {!r} in json. Valid fields for type {}: {!r}".format( # field_name, cls, list(annotations.keys()))) # try: # field_inst = class_from_json(field_type, field_value) # except TypeError: # raise TypeError(f"Failed to parse field {field_name}") # setattr(inst, field_name, field_inst) # return inst # elif get_origin(cls) is list: # list_element_type = get_args(cls)[0] # return [ # class_from_json(list_element_type, list_element) for # list_element in data] # elif cls is datetime.datetime: # return datetime.datetime.fromisoformat(data) # else: # if cls is not typing.Any: # if not (type(data) is cls or data is None): # raise TypeError(f"{repr(data)} is of type {type(data)}, {cls} required") # return data , which may include functions, classes, or code. Output only the next line.
else:
Given snippet: <|code_start|>ITEMS_PER_PAGE = 100 def changelog(): page = int(flask.request.args.get("page", "1")) cur = get_indexdb().cursor() # Get total number of entries cur.execute("SELECT COUNT(*) FROM changelog_summary;") total_entries = cur.fetchone()[0] page_info = calc_pageinfo(page, total_entries, ITEMS_PER_PAGE) cur.execute( "SELECT * FROM changelog_summary ORDER BY timestamp DESC LIMIT ? OFFSET ?;", (ITEMS_PER_PAGE, page_info["from"]) ) changelog_summaries = [] for summary_res in cur: summary = model.IndexChangelogSummary( product_id = summary_res["product_id"], product_title = summary_res["product_title"], timestamp = datetime.datetime.fromtimestamp(summary_res["timestamp"], datetime.timezone.utc), categories = summary_res["categories"].split(",") ) changelog_summaries.append(summary) page_info["prev_link"] = flask.url_for( "changelog", page=page_info["page"] - 1) <|code_end|> , continue by predicting the next line. Consider current file imports: import datetime import flask import gogdb.core.model as model from gogdb.views.pagination import calc_pageinfo from gogdb.application.datasources import get_indexdb and context: # Path: gogdb/views/pagination.py # def calc_pageinfo(page, num_products, items_per_page): # num_pages = int(math.ceil(num_products / items_per_page)) # page = min(max(page, 1), num_pages) # offset = (page - 1) * items_per_page # page_info = { # "is_first": page == 1, # "is_last": page == num_pages, # "page": page, # "num_pages": num_pages, # "from": offset, # "to": offset + items_per_page, # "prev_link": "", # Filled in later # "next_link": "" # } # return page_info # # Path: gogdb/application/datasources.py # def get_indexdb(): # if "indexdb" not in flask.g: # storagedb = get_storagedb() # index_path = storagedb.path_indexdb() # flask.g.indexdb = sqlite3.connect(index_path) # flask.g.indexdb.row_factory = sqlite3.Row # # return flask.g.indexdb which might include code, classes, or functions. Output only the next line.
page_info["next_link"] = flask.url_for(
Based on the snippet: <|code_start|> ITEMS_PER_PAGE = 100 def changelog(): page = int(flask.request.args.get("page", "1")) cur = get_indexdb().cursor() # Get total number of entries cur.execute("SELECT COUNT(*) FROM changelog_summary;") total_entries = cur.fetchone()[0] page_info = calc_pageinfo(page, total_entries, ITEMS_PER_PAGE) <|code_end|> , predict the immediate next line with the help of imports: import datetime import flask import gogdb.core.model as model from gogdb.views.pagination import calc_pageinfo from gogdb.application.datasources import get_indexdb and context (classes, functions, sometimes code) from other files: # Path: gogdb/views/pagination.py # def calc_pageinfo(page, num_products, items_per_page): # num_pages = int(math.ceil(num_products / items_per_page)) # page = min(max(page, 1), num_pages) # offset = (page - 1) * items_per_page # page_info = { # "is_first": page == 1, # "is_last": page == num_pages, # "page": page, # "num_pages": num_pages, # "from": offset, # "to": offset + items_per_page, # "prev_link": "", # Filled in later # "next_link": "" # } # return page_info # # Path: gogdb/application/datasources.py # def get_indexdb(): # if "indexdb" not in flask.g: # storagedb = get_storagedb() # index_path = storagedb.path_indexdb() # flask.g.indexdb = sqlite3.connect(index_path) # flask.g.indexdb.row_factory = sqlite3.Row # # return flask.g.indexdb . Output only the next line.
cur.execute(
Continue the code snippet: <|code_start|> class BlogLoader: @classmethod def find_by_id(cls, db, blog_id): with db.cursor() as cursor: <|code_end|> . Use current file imports: from hakoblog.model.blog import Blog and context (classes, functions, or code) from other files: # Path: hakoblog/model/blog.py # class Blog: # def __init__(self, id, owner_id, title): # self.id = id # self.owner_id = owner_id # self.title = title . Output only the next line.
cursor.execute(
Next line prediction: <|code_start|> class UserLoader: @classmethod def find_by_name(cls, db, name): with db.cursor() as cursor: <|code_end|> . Use current file imports: (from hakoblog.model.user import User) and context including class names, function names, or small code snippets from other files: # Path: hakoblog/model/user.py # class User: # def __init__(self, id, name): # self.id = id # self.name = name . Output only the next line.
cursor.execute(
Predict the next line after this snippet: <|code_start|> def test_create(): db = DB() name = random_string(10) UserAction.create(db, name) user = UserLoader.find_by_name(db, name) assert user.name == name def test_ensure_global_user_created(): db = DB() with global_user(random_string(10)) as global_user_name: assert UserLoader.find_by_name(db, global_user_name) is None user = UserAction.ensure_global_user_created(db) assert user.name == global_user_name # Check no exceptions raises user_again = UserAction.ensure_global_user_created(db) <|code_end|> using the current file's imports: import tests.hakoblog # noqa: F401 from hakoblog.db import DB from hakoblog.loader.user import UserLoader from hakoblog.action.user import UserAction from tests.util import random_string, global_user and any relevant context from other files: # Path: hakoblog/db.py # class DB: # def __init__(self): # self.conn = MySQLdb.connect( # db=CONFIG.DATABASE, # host=CONFIG.DATABASE_HOST, # user=CONFIG.DATABASE_USER, # password=CONFIG.DATABASE_PASS, # cursorclass=MySQLdb.cursors.DictCursor, # charset="utf8", # ) # self.conn.autocommit(True) # # def cursor(self): # return self.conn.cursor() # # def close(self): # self.conn.close() # # def uuid_short(self): # with self.conn.cursor() as cursor: # cursor.execute("SELECT UUID_SHORT() as uuid") # return cursor.fetchone().get("uuid") # # Path: hakoblog/loader/user.py # class UserLoader: # @classmethod # def find_by_name(cls, db, name): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, name # FROM user # WHERE name = %s # LIMIT 1 # """, # (name,), # ) # row = cursor.fetchone() # # if row is None: # return None # # return User(**row) # # Path: hakoblog/action/user.py # class UserAction: # @classmethod # def create(self, db, name): # now = datetime.now() # new_id = db.uuid_short() # with db.cursor() as cursor: # cursor.execute( # """ # INSERT INTO user ( # id, name, created, modified # ) VALUES ( # %s, %s, %s, %s # ) # """, # (new_id, name, now, now), # ) # return new_id # # @classmethod # def ensure_global_user_created(cls, db): # global_user_name = CONFIG.GLOBAL_USER_NAME # user = UserLoader.find_by_name(db, global_user_name) # if user is None: # cls.create(db, global_user_name) # user = UserLoader.find_by_name(db, global_user_name) # return user # # Path: tests/util.py # def random_string(length, seq=string.digits + string.ascii_letters): # sr = random.SystemRandom() # return ''.join([sr.choice(seq) for i in range(length)]) # # @contextmanager # def global_user(name): # prev_name = CONFIG.GLOBAL_USER_NAME # CONFIG.GLOBAL_USER_NAME = name # yield name # CONFIG.GLOBAL_USER_NAME = prev_name . Output only the next line.
assert user_again.id == user.id
Based on the snippet: <|code_start|> def test_create(): db = DB() name = random_string(10) UserAction.create(db, name) user = UserLoader.find_by_name(db, name) assert user.name == name def test_ensure_global_user_created(): db = DB() with global_user(random_string(10)) as global_user_name: assert UserLoader.find_by_name(db, global_user_name) is None user = UserAction.ensure_global_user_created(db) assert user.name == global_user_name # Check no exceptions raises user_again = UserAction.ensure_global_user_created(db) <|code_end|> , predict the immediate next line with the help of imports: import tests.hakoblog # noqa: F401 from hakoblog.db import DB from hakoblog.loader.user import UserLoader from hakoblog.action.user import UserAction from tests.util import random_string, global_user and context (classes, functions, sometimes code) from other files: # Path: hakoblog/db.py # class DB: # def __init__(self): # self.conn = MySQLdb.connect( # db=CONFIG.DATABASE, # host=CONFIG.DATABASE_HOST, # user=CONFIG.DATABASE_USER, # password=CONFIG.DATABASE_PASS, # cursorclass=MySQLdb.cursors.DictCursor, # charset="utf8", # ) # self.conn.autocommit(True) # # def cursor(self): # return self.conn.cursor() # # def close(self): # self.conn.close() # # def uuid_short(self): # with self.conn.cursor() as cursor: # cursor.execute("SELECT UUID_SHORT() as uuid") # return cursor.fetchone().get("uuid") # # Path: hakoblog/loader/user.py # class UserLoader: # @classmethod # def find_by_name(cls, db, name): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, name # FROM user # WHERE name = %s # LIMIT 1 # """, # (name,), # ) # row = cursor.fetchone() # # if row is None: # return None # # return User(**row) # # Path: hakoblog/action/user.py # class UserAction: # @classmethod # def create(self, db, name): # now = datetime.now() # new_id = db.uuid_short() # with db.cursor() as cursor: # cursor.execute( # """ # INSERT INTO user ( # id, name, created, modified # ) VALUES ( # %s, %s, %s, %s # ) # """, # (new_id, name, now, now), # ) # return new_id # # @classmethod # def ensure_global_user_created(cls, db): # global_user_name = CONFIG.GLOBAL_USER_NAME # user = UserLoader.find_by_name(db, global_user_name) # if user is None: # cls.create(db, global_user_name) # user = UserLoader.find_by_name(db, global_user_name) # return user # # Path: tests/util.py # def random_string(length, seq=string.digits + string.ascii_letters): # sr = random.SystemRandom() # return ''.join([sr.choice(seq) for i in range(length)]) # # @contextmanager # def global_user(name): # prev_name = CONFIG.GLOBAL_USER_NAME # CONFIG.GLOBAL_USER_NAME = name # yield name # CONFIG.GLOBAL_USER_NAME = prev_name . Output only the next line.
assert user_again.id == user.id
Given the code snippet: <|code_start|> def test_create(): db = DB() name = random_string(10) UserAction.create(db, name) user = UserLoader.find_by_name(db, name) assert user.name == name def test_ensure_global_user_created(): db = DB() with global_user(random_string(10)) as global_user_name: assert UserLoader.find_by_name(db, global_user_name) is None user = UserAction.ensure_global_user_created(db) assert user.name == global_user_name # Check no exceptions raises user_again = UserAction.ensure_global_user_created(db) <|code_end|> , generate the next line using the imports in this file: import tests.hakoblog # noqa: F401 from hakoblog.db import DB from hakoblog.loader.user import UserLoader from hakoblog.action.user import UserAction from tests.util import random_string, global_user and context (functions, classes, or occasionally code) from other files: # Path: hakoblog/db.py # class DB: # def __init__(self): # self.conn = MySQLdb.connect( # db=CONFIG.DATABASE, # host=CONFIG.DATABASE_HOST, # user=CONFIG.DATABASE_USER, # password=CONFIG.DATABASE_PASS, # cursorclass=MySQLdb.cursors.DictCursor, # charset="utf8", # ) # self.conn.autocommit(True) # # def cursor(self): # return self.conn.cursor() # # def close(self): # self.conn.close() # # def uuid_short(self): # with self.conn.cursor() as cursor: # cursor.execute("SELECT UUID_SHORT() as uuid") # return cursor.fetchone().get("uuid") # # Path: hakoblog/loader/user.py # class UserLoader: # @classmethod # def find_by_name(cls, db, name): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, name # FROM user # WHERE name = %s # LIMIT 1 # """, # (name,), # ) # row = cursor.fetchone() # # if row is None: # return None # # return User(**row) # # Path: hakoblog/action/user.py # class UserAction: # @classmethod # def create(self, db, name): # now = datetime.now() # new_id = db.uuid_short() # with db.cursor() as cursor: # cursor.execute( # """ # INSERT INTO user ( # id, name, created, modified # ) VALUES ( # %s, %s, %s, %s # ) # """, # (new_id, name, now, now), # ) # return new_id # # @classmethod # def ensure_global_user_created(cls, db): # global_user_name = CONFIG.GLOBAL_USER_NAME # user = UserLoader.find_by_name(db, global_user_name) # if user is None: # cls.create(db, global_user_name) # user = UserLoader.find_by_name(db, global_user_name) # return user # # Path: tests/util.py # def random_string(length, seq=string.digits + string.ascii_letters): # sr = random.SystemRandom() # return ''.join([sr.choice(seq) for i in range(length)]) # # @contextmanager # def global_user(name): # prev_name = CONFIG.GLOBAL_USER_NAME # CONFIG.GLOBAL_USER_NAME = name # yield name # CONFIG.GLOBAL_USER_NAME = prev_name . Output only the next line.
assert user_again.id == user.id
Here is a snippet: <|code_start|> def test_create(): db = DB() name = random_string(10) UserAction.create(db, name) user = UserLoader.find_by_name(db, name) <|code_end|> . Write the next line using the current file imports: import tests.hakoblog # noqa: F401 from hakoblog.db import DB from hakoblog.loader.user import UserLoader from hakoblog.action.user import UserAction from tests.util import random_string, global_user and context from other files: # Path: hakoblog/db.py # class DB: # def __init__(self): # self.conn = MySQLdb.connect( # db=CONFIG.DATABASE, # host=CONFIG.DATABASE_HOST, # user=CONFIG.DATABASE_USER, # password=CONFIG.DATABASE_PASS, # cursorclass=MySQLdb.cursors.DictCursor, # charset="utf8", # ) # self.conn.autocommit(True) # # def cursor(self): # return self.conn.cursor() # # def close(self): # self.conn.close() # # def uuid_short(self): # with self.conn.cursor() as cursor: # cursor.execute("SELECT UUID_SHORT() as uuid") # return cursor.fetchone().get("uuid") # # Path: hakoblog/loader/user.py # class UserLoader: # @classmethod # def find_by_name(cls, db, name): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, name # FROM user # WHERE name = %s # LIMIT 1 # """, # (name,), # ) # row = cursor.fetchone() # # if row is None: # return None # # return User(**row) # # Path: hakoblog/action/user.py # class UserAction: # @classmethod # def create(self, db, name): # now = datetime.now() # new_id = db.uuid_short() # with db.cursor() as cursor: # cursor.execute( # """ # INSERT INTO user ( # id, name, created, modified # ) VALUES ( # %s, %s, %s, %s # ) # """, # (new_id, name, now, now), # ) # return new_id # # @classmethod # def ensure_global_user_created(cls, db): # global_user_name = CONFIG.GLOBAL_USER_NAME # user = UserLoader.find_by_name(db, global_user_name) # if user is None: # cls.create(db, global_user_name) # user = UserLoader.find_by_name(db, global_user_name) # return user # # Path: tests/util.py # def random_string(length, seq=string.digits + string.ascii_letters): # sr = random.SystemRandom() # return ''.join([sr.choice(seq) for i in range(length)]) # # @contextmanager # def global_user(name): # prev_name = CONFIG.GLOBAL_USER_NAME # CONFIG.GLOBAL_USER_NAME = name # yield name # CONFIG.GLOBAL_USER_NAME = prev_name , which may include functions, classes, or code. Output only the next line.
assert user.name == name
Given snippet: <|code_start|> found_entry = EntryLoader.find_by_id(db, entry.id) assert isinstance(found_entry, Entry) assert found_entry.id == entry.id not_found_entry = EntryLoader.find_by_id(db, 10) assert not_found_entry is None def test_find_entries(): "EntryLoader.find_entries can find entries for the specified blog" db = DB() blog = create_blog() entries = [] with freeze_time('2017-01-13 12:00:02'): entries.append(create_entry(blog=blog)) with freeze_time('2017-01-13 12:00:01'): entries.append(create_entry(blog=blog)) with freeze_time('2017-01-13 12:00:00'): entries.append(create_entry(blog=blog)) found_entries = EntryLoader.find_entries(db, blog.id) assert len(found_entries) == len(entries) assert [e.id for e in found_entries] == [e.id for e in entries] found_entries_with_limit = EntryLoader.find_entries(db, blog.id, limit=2) assert len(found_entries_with_limit) == len(entries[0:2]) assert [ e.id for e in found_entries_with_limit <|code_end|> , continue by predicting the next line. Consider current file imports: import tests.hakoblog # noqa: F401 from freezegun import freeze_time from hakoblog.db import DB from hakoblog.model.entry import Entry from hakoblog.loader.entry import EntryLoader from tests.util import create_entry, create_blog and context: # Path: hakoblog/db.py # class DB: # def __init__(self): # self.conn = MySQLdb.connect( # db=CONFIG.DATABASE, # host=CONFIG.DATABASE_HOST, # user=CONFIG.DATABASE_USER, # password=CONFIG.DATABASE_PASS, # cursorclass=MySQLdb.cursors.DictCursor, # charset="utf8", # ) # self.conn.autocommit(True) # # def cursor(self): # return self.conn.cursor() # # def close(self): # self.conn.close() # # def uuid_short(self): # with self.conn.cursor() as cursor: # cursor.execute("SELECT UUID_SHORT() as uuid") # return cursor.fetchone().get("uuid") # # Path: hakoblog/model/entry.py # class Entry: # def __init__(self, id, blog_id, title, body, created, modified): # self.id = id # self.blog_id = blog_id # self.title = title # self.body = body # self.created = created # self.modified = modified # # Path: hakoblog/loader/entry.py # class EntryLoader: # @classmethod # def find_by_id(cls, db, entry_id): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, blog_id, title, body, created, modified # FROM entry # WHERE id = %s # LIMIT 1 # """, # (entry_id,), # ) # row = cursor.fetchone() # # if row is None: # return None # # return Entry(**row) # # @classmethod # def find_entries(cls, db, blog_id, limit=30): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, blog_id, title, body, created, modified # FROM entry # WHERE blog_id = %s # ORDER BY created DESC # LIMIT %s # """, # (blog_id, limit), # ) # rows = cursor.fetchall() # # return [Entry(**r) for r in rows] # # Path: tests/util.py # def create_entry(blog=None): # db = DB() # # if blog is None: # blog = create_blog() # # new_entry_id = EntryAction.post( # db, # blog_id=blog.id, # title=random_string(30), # body=random_string(100), # ) # return EntryLoader.find_by_id(db, new_entry_id) # # def create_blog(user=None): # db = DB() # # if user is None: # user = create_user() # # new_blog_id = BlogAction.create( # db, # owner_id=user.id, # title=random_string(10), # ) # return BlogLoader.find_by_id(db, new_blog_id) which might include code, classes, or functions. Output only the next line.
] == [e.id for e in entries[0:2]]
Predict the next line after this snippet: <|code_start|> def test_find_by_id(): "EntryLoader.find_by_id() can find a entry by id" db = DB() entry = create_entry() found_entry = EntryLoader.find_by_id(db, entry.id) assert isinstance(found_entry, Entry) assert found_entry.id == entry.id not_found_entry = EntryLoader.find_by_id(db, 10) assert not_found_entry is None def test_find_entries(): "EntryLoader.find_entries can find entries for the specified blog" db = DB() blog = create_blog() entries = [] with freeze_time('2017-01-13 12:00:02'): entries.append(create_entry(blog=blog)) with freeze_time('2017-01-13 12:00:01'): entries.append(create_entry(blog=blog)) <|code_end|> using the current file's imports: import tests.hakoblog # noqa: F401 from freezegun import freeze_time from hakoblog.db import DB from hakoblog.model.entry import Entry from hakoblog.loader.entry import EntryLoader from tests.util import create_entry, create_blog and any relevant context from other files: # Path: hakoblog/db.py # class DB: # def __init__(self): # self.conn = MySQLdb.connect( # db=CONFIG.DATABASE, # host=CONFIG.DATABASE_HOST, # user=CONFIG.DATABASE_USER, # password=CONFIG.DATABASE_PASS, # cursorclass=MySQLdb.cursors.DictCursor, # charset="utf8", # ) # self.conn.autocommit(True) # # def cursor(self): # return self.conn.cursor() # # def close(self): # self.conn.close() # # def uuid_short(self): # with self.conn.cursor() as cursor: # cursor.execute("SELECT UUID_SHORT() as uuid") # return cursor.fetchone().get("uuid") # # Path: hakoblog/model/entry.py # class Entry: # def __init__(self, id, blog_id, title, body, created, modified): # self.id = id # self.blog_id = blog_id # self.title = title # self.body = body # self.created = created # self.modified = modified # # Path: hakoblog/loader/entry.py # class EntryLoader: # @classmethod # def find_by_id(cls, db, entry_id): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, blog_id, title, body, created, modified # FROM entry # WHERE id = %s # LIMIT 1 # """, # (entry_id,), # ) # row = cursor.fetchone() # # if row is None: # return None # # return Entry(**row) # # @classmethod # def find_entries(cls, db, blog_id, limit=30): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, blog_id, title, body, created, modified # FROM entry # WHERE blog_id = %s # ORDER BY created DESC # LIMIT %s # """, # (blog_id, limit), # ) # rows = cursor.fetchall() # # return [Entry(**r) for r in rows] # # Path: tests/util.py # def create_entry(blog=None): # db = DB() # # if blog is None: # blog = create_blog() # # new_entry_id = EntryAction.post( # db, # blog_id=blog.id, # title=random_string(30), # body=random_string(100), # ) # return EntryLoader.find_by_id(db, new_entry_id) # # def create_blog(user=None): # db = DB() # # if user is None: # user = create_user() # # new_blog_id = BlogAction.create( # db, # owner_id=user.id, # title=random_string(10), # ) # return BlogLoader.find_by_id(db, new_blog_id) . Output only the next line.
with freeze_time('2017-01-13 12:00:00'):
Using the snippet: <|code_start|> def test_find_by_id(): "EntryLoader.find_by_id() can find a entry by id" db = DB() entry = create_entry() found_entry = EntryLoader.find_by_id(db, entry.id) assert isinstance(found_entry, Entry) assert found_entry.id == entry.id not_found_entry = EntryLoader.find_by_id(db, 10) <|code_end|> , determine the next line of code. You have imports: import tests.hakoblog # noqa: F401 from freezegun import freeze_time from hakoblog.db import DB from hakoblog.model.entry import Entry from hakoblog.loader.entry import EntryLoader from tests.util import create_entry, create_blog and context (class names, function names, or code) available: # Path: hakoblog/db.py # class DB: # def __init__(self): # self.conn = MySQLdb.connect( # db=CONFIG.DATABASE, # host=CONFIG.DATABASE_HOST, # user=CONFIG.DATABASE_USER, # password=CONFIG.DATABASE_PASS, # cursorclass=MySQLdb.cursors.DictCursor, # charset="utf8", # ) # self.conn.autocommit(True) # # def cursor(self): # return self.conn.cursor() # # def close(self): # self.conn.close() # # def uuid_short(self): # with self.conn.cursor() as cursor: # cursor.execute("SELECT UUID_SHORT() as uuid") # return cursor.fetchone().get("uuid") # # Path: hakoblog/model/entry.py # class Entry: # def __init__(self, id, blog_id, title, body, created, modified): # self.id = id # self.blog_id = blog_id # self.title = title # self.body = body # self.created = created # self.modified = modified # # Path: hakoblog/loader/entry.py # class EntryLoader: # @classmethod # def find_by_id(cls, db, entry_id): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, blog_id, title, body, created, modified # FROM entry # WHERE id = %s # LIMIT 1 # """, # (entry_id,), # ) # row = cursor.fetchone() # # if row is None: # return None # # return Entry(**row) # # @classmethod # def find_entries(cls, db, blog_id, limit=30): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, blog_id, title, body, created, modified # FROM entry # WHERE blog_id = %s # ORDER BY created DESC # LIMIT %s # """, # (blog_id, limit), # ) # rows = cursor.fetchall() # # return [Entry(**r) for r in rows] # # Path: tests/util.py # def create_entry(blog=None): # db = DB() # # if blog is None: # blog = create_blog() # # new_entry_id = EntryAction.post( # db, # blog_id=blog.id, # title=random_string(30), # body=random_string(100), # ) # return EntryLoader.find_by_id(db, new_entry_id) # # def create_blog(user=None): # db = DB() # # if user is None: # user = create_user() # # new_blog_id = BlogAction.create( # db, # owner_id=user.id, # title=random_string(10), # ) # return BlogLoader.find_by_id(db, new_blog_id) . Output only the next line.
assert not_found_entry is None
Given the following code snippet before the placeholder: <|code_start|> def test_find_by_id(): "EntryLoader.find_by_id() can find a entry by id" db = DB() entry = create_entry() found_entry = EntryLoader.find_by_id(db, entry.id) assert isinstance(found_entry, Entry) <|code_end|> , predict the next line using imports from the current file: import tests.hakoblog # noqa: F401 from freezegun import freeze_time from hakoblog.db import DB from hakoblog.model.entry import Entry from hakoblog.loader.entry import EntryLoader from tests.util import create_entry, create_blog and context including class names, function names, and sometimes code from other files: # Path: hakoblog/db.py # class DB: # def __init__(self): # self.conn = MySQLdb.connect( # db=CONFIG.DATABASE, # host=CONFIG.DATABASE_HOST, # user=CONFIG.DATABASE_USER, # password=CONFIG.DATABASE_PASS, # cursorclass=MySQLdb.cursors.DictCursor, # charset="utf8", # ) # self.conn.autocommit(True) # # def cursor(self): # return self.conn.cursor() # # def close(self): # self.conn.close() # # def uuid_short(self): # with self.conn.cursor() as cursor: # cursor.execute("SELECT UUID_SHORT() as uuid") # return cursor.fetchone().get("uuid") # # Path: hakoblog/model/entry.py # class Entry: # def __init__(self, id, blog_id, title, body, created, modified): # self.id = id # self.blog_id = blog_id # self.title = title # self.body = body # self.created = created # self.modified = modified # # Path: hakoblog/loader/entry.py # class EntryLoader: # @classmethod # def find_by_id(cls, db, entry_id): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, blog_id, title, body, created, modified # FROM entry # WHERE id = %s # LIMIT 1 # """, # (entry_id,), # ) # row = cursor.fetchone() # # if row is None: # return None # # return Entry(**row) # # @classmethod # def find_entries(cls, db, blog_id, limit=30): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, blog_id, title, body, created, modified # FROM entry # WHERE blog_id = %s # ORDER BY created DESC # LIMIT %s # """, # (blog_id, limit), # ) # rows = cursor.fetchall() # # return [Entry(**r) for r in rows] # # Path: tests/util.py # def create_entry(blog=None): # db = DB() # # if blog is None: # blog = create_blog() # # new_entry_id = EntryAction.post( # db, # blog_id=blog.id, # title=random_string(30), # body=random_string(100), # ) # return EntryLoader.find_by_id(db, new_entry_id) # # def create_blog(user=None): # db = DB() # # if user is None: # user = create_user() # # new_blog_id = BlogAction.create( # db, # owner_id=user.id, # title=random_string(10), # ) # return BlogLoader.find_by_id(db, new_blog_id) . Output only the next line.
assert found_entry.id == entry.id
Given snippet: <|code_start|> def test_find_by_id(): "EntryLoader.find_by_id() can find a entry by id" db = DB() entry = create_entry() found_entry = EntryLoader.find_by_id(db, entry.id) assert isinstance(found_entry, Entry) assert found_entry.id == entry.id not_found_entry = EntryLoader.find_by_id(db, 10) assert not_found_entry is None def test_find_entries(): "EntryLoader.find_entries can find entries for the specified blog" db = DB() blog = create_blog() entries = [] with freeze_time('2017-01-13 12:00:02'): entries.append(create_entry(blog=blog)) with freeze_time('2017-01-13 12:00:01'): entries.append(create_entry(blog=blog)) with freeze_time('2017-01-13 12:00:00'): entries.append(create_entry(blog=blog)) found_entries = EntryLoader.find_entries(db, blog.id) assert len(found_entries) == len(entries) <|code_end|> , continue by predicting the next line. Consider current file imports: import tests.hakoblog # noqa: F401 from freezegun import freeze_time from hakoblog.db import DB from hakoblog.model.entry import Entry from hakoblog.loader.entry import EntryLoader from tests.util import create_entry, create_blog and context: # Path: hakoblog/db.py # class DB: # def __init__(self): # self.conn = MySQLdb.connect( # db=CONFIG.DATABASE, # host=CONFIG.DATABASE_HOST, # user=CONFIG.DATABASE_USER, # password=CONFIG.DATABASE_PASS, # cursorclass=MySQLdb.cursors.DictCursor, # charset="utf8", # ) # self.conn.autocommit(True) # # def cursor(self): # return self.conn.cursor() # # def close(self): # self.conn.close() # # def uuid_short(self): # with self.conn.cursor() as cursor: # cursor.execute("SELECT UUID_SHORT() as uuid") # return cursor.fetchone().get("uuid") # # Path: hakoblog/model/entry.py # class Entry: # def __init__(self, id, blog_id, title, body, created, modified): # self.id = id # self.blog_id = blog_id # self.title = title # self.body = body # self.created = created # self.modified = modified # # Path: hakoblog/loader/entry.py # class EntryLoader: # @classmethod # def find_by_id(cls, db, entry_id): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, blog_id, title, body, created, modified # FROM entry # WHERE id = %s # LIMIT 1 # """, # (entry_id,), # ) # row = cursor.fetchone() # # if row is None: # return None # # return Entry(**row) # # @classmethod # def find_entries(cls, db, blog_id, limit=30): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, blog_id, title, body, created, modified # FROM entry # WHERE blog_id = %s # ORDER BY created DESC # LIMIT %s # """, # (blog_id, limit), # ) # rows = cursor.fetchall() # # return [Entry(**r) for r in rows] # # Path: tests/util.py # def create_entry(blog=None): # db = DB() # # if blog is None: # blog = create_blog() # # new_entry_id = EntryAction.post( # db, # blog_id=blog.id, # title=random_string(30), # body=random_string(100), # ) # return EntryLoader.find_by_id(db, new_entry_id) # # def create_blog(user=None): # db = DB() # # if user is None: # user = create_user() # # new_blog_id = BlogAction.create( # db, # owner_id=user.id, # title=random_string(10), # ) # return BlogLoader.find_by_id(db, new_blog_id) which might include code, classes, or functions. Output only the next line.
assert [e.id for e in found_entries] == [e.id for e in entries]
Using the snippet: <|code_start|> blog = create_blog() entry_id = EntryAction.post( db, blog_id=blog.id, title='タイトル', body='こんにちは', ) found_entry = EntryLoader.find_by_id(db, entry_id) assert found_entry.blog_id == blog.id assert found_entry.title == 'タイトル' assert found_entry.body == 'こんにちは' def test_edit(): db = DB() blog = create_blog() entry_id = EntryAction.post( db, blog_id=blog.id, title='タイトルbefore', body='こんにちはbefore', ) EntryAction.edit( db, <|code_end|> , determine the next line of code. You have imports: import tests.hakoblog # noqa: F401 from hakoblog.db import DB from hakoblog.action.entry import EntryAction from hakoblog.loader.entry import EntryLoader from tests.util import create_blog, create_entry and context (class names, function names, or code) available: # Path: hakoblog/db.py # class DB: # def __init__(self): # self.conn = MySQLdb.connect( # db=CONFIG.DATABASE, # host=CONFIG.DATABASE_HOST, # user=CONFIG.DATABASE_USER, # password=CONFIG.DATABASE_PASS, # cursorclass=MySQLdb.cursors.DictCursor, # charset="utf8", # ) # self.conn.autocommit(True) # # def cursor(self): # return self.conn.cursor() # # def close(self): # self.conn.close() # # def uuid_short(self): # with self.conn.cursor() as cursor: # cursor.execute("SELECT UUID_SHORT() as uuid") # return cursor.fetchone().get("uuid") # # Path: hakoblog/action/entry.py # class EntryAction: # @classmethod # def post(cls, db, blog_id, title, body): # now = datetime.now() # new_id = db.uuid_short() # with db.cursor() as cursor: # cursor.execute( # """ # INSERT INTO entry ( # id, blog_id, title, body, created, modified # ) VALUES ( # %s, %s, %s, %s, %s, %s # ) # """, # (new_id, blog_id, title, body, now, now), # ) # return new_id # # @classmethod # def edit(cls, db, entry_id, title, body): # now = datetime.now() # with db.cursor() as cursor: # cursor.execute( # """ # UPDATE entry SET # title = %s, # body = %s, # modified = %s # WHERE id = %s # """, # (title, body, now, entry_id), # ) # # @classmethod # def delete(cls, db, entry_id): # with db.cursor() as cursor: # cursor.execute( # """ # DELETE FROM entry # WHERE id = %s # """, # (entry_id,), # ) # # Path: hakoblog/loader/entry.py # class EntryLoader: # @classmethod # def find_by_id(cls, db, entry_id): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, blog_id, title, body, created, modified # FROM entry # WHERE id = %s # LIMIT 1 # """, # (entry_id,), # ) # row = cursor.fetchone() # # if row is None: # return None # # return Entry(**row) # # @classmethod # def find_entries(cls, db, blog_id, limit=30): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, blog_id, title, body, created, modified # FROM entry # WHERE blog_id = %s # ORDER BY created DESC # LIMIT %s # """, # (blog_id, limit), # ) # rows = cursor.fetchall() # # return [Entry(**r) for r in rows] # # Path: tests/util.py # def create_blog(user=None): # db = DB() # # if user is None: # user = create_user() # # new_blog_id = BlogAction.create( # db, # owner_id=user.id, # title=random_string(10), # ) # return BlogLoader.find_by_id(db, new_blog_id) # # def create_entry(blog=None): # db = DB() # # if blog is None: # blog = create_blog() # # new_entry_id = EntryAction.post( # db, # blog_id=blog.id, # title=random_string(30), # body=random_string(100), # ) # return EntryLoader.find_by_id(db, new_entry_id) . Output only the next line.
entry_id=entry_id,
Using the snippet: <|code_start|> def test_post(): db = DB() blog = create_blog() entry_id = EntryAction.post( db, blog_id=blog.id, title='タイトル', <|code_end|> , determine the next line of code. You have imports: import tests.hakoblog # noqa: F401 from hakoblog.db import DB from hakoblog.action.entry import EntryAction from hakoblog.loader.entry import EntryLoader from tests.util import create_blog, create_entry and context (class names, function names, or code) available: # Path: hakoblog/db.py # class DB: # def __init__(self): # self.conn = MySQLdb.connect( # db=CONFIG.DATABASE, # host=CONFIG.DATABASE_HOST, # user=CONFIG.DATABASE_USER, # password=CONFIG.DATABASE_PASS, # cursorclass=MySQLdb.cursors.DictCursor, # charset="utf8", # ) # self.conn.autocommit(True) # # def cursor(self): # return self.conn.cursor() # # def close(self): # self.conn.close() # # def uuid_short(self): # with self.conn.cursor() as cursor: # cursor.execute("SELECT UUID_SHORT() as uuid") # return cursor.fetchone().get("uuid") # # Path: hakoblog/action/entry.py # class EntryAction: # @classmethod # def post(cls, db, blog_id, title, body): # now = datetime.now() # new_id = db.uuid_short() # with db.cursor() as cursor: # cursor.execute( # """ # INSERT INTO entry ( # id, blog_id, title, body, created, modified # ) VALUES ( # %s, %s, %s, %s, %s, %s # ) # """, # (new_id, blog_id, title, body, now, now), # ) # return new_id # # @classmethod # def edit(cls, db, entry_id, title, body): # now = datetime.now() # with db.cursor() as cursor: # cursor.execute( # """ # UPDATE entry SET # title = %s, # body = %s, # modified = %s # WHERE id = %s # """, # (title, body, now, entry_id), # ) # # @classmethod # def delete(cls, db, entry_id): # with db.cursor() as cursor: # cursor.execute( # """ # DELETE FROM entry # WHERE id = %s # """, # (entry_id,), # ) # # Path: hakoblog/loader/entry.py # class EntryLoader: # @classmethod # def find_by_id(cls, db, entry_id): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, blog_id, title, body, created, modified # FROM entry # WHERE id = %s # LIMIT 1 # """, # (entry_id,), # ) # row = cursor.fetchone() # # if row is None: # return None # # return Entry(**row) # # @classmethod # def find_entries(cls, db, blog_id, limit=30): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, blog_id, title, body, created, modified # FROM entry # WHERE blog_id = %s # ORDER BY created DESC # LIMIT %s # """, # (blog_id, limit), # ) # rows = cursor.fetchall() # # return [Entry(**r) for r in rows] # # Path: tests/util.py # def create_blog(user=None): # db = DB() # # if user is None: # user = create_user() # # new_blog_id = BlogAction.create( # db, # owner_id=user.id, # title=random_string(10), # ) # return BlogLoader.find_by_id(db, new_blog_id) # # def create_entry(blog=None): # db = DB() # # if blog is None: # blog = create_blog() # # new_entry_id = EntryAction.post( # db, # blog_id=blog.id, # title=random_string(30), # body=random_string(100), # ) # return EntryLoader.find_by_id(db, new_entry_id) . Output only the next line.
body='こんにちは',
Given the following code snippet before the placeholder: <|code_start|> def test_post(): db = DB() blog = create_blog() entry_id = EntryAction.post( db, blog_id=blog.id, title='タイトル', body='こんにちは', ) found_entry = EntryLoader.find_by_id(db, entry_id) assert found_entry.blog_id == blog.id <|code_end|> , predict the next line using imports from the current file: import tests.hakoblog # noqa: F401 from hakoblog.db import DB from hakoblog.action.entry import EntryAction from hakoblog.loader.entry import EntryLoader from tests.util import create_blog, create_entry and context including class names, function names, and sometimes code from other files: # Path: hakoblog/db.py # class DB: # def __init__(self): # self.conn = MySQLdb.connect( # db=CONFIG.DATABASE, # host=CONFIG.DATABASE_HOST, # user=CONFIG.DATABASE_USER, # password=CONFIG.DATABASE_PASS, # cursorclass=MySQLdb.cursors.DictCursor, # charset="utf8", # ) # self.conn.autocommit(True) # # def cursor(self): # return self.conn.cursor() # # def close(self): # self.conn.close() # # def uuid_short(self): # with self.conn.cursor() as cursor: # cursor.execute("SELECT UUID_SHORT() as uuid") # return cursor.fetchone().get("uuid") # # Path: hakoblog/action/entry.py # class EntryAction: # @classmethod # def post(cls, db, blog_id, title, body): # now = datetime.now() # new_id = db.uuid_short() # with db.cursor() as cursor: # cursor.execute( # """ # INSERT INTO entry ( # id, blog_id, title, body, created, modified # ) VALUES ( # %s, %s, %s, %s, %s, %s # ) # """, # (new_id, blog_id, title, body, now, now), # ) # return new_id # # @classmethod # def edit(cls, db, entry_id, title, body): # now = datetime.now() # with db.cursor() as cursor: # cursor.execute( # """ # UPDATE entry SET # title = %s, # body = %s, # modified = %s # WHERE id = %s # """, # (title, body, now, entry_id), # ) # # @classmethod # def delete(cls, db, entry_id): # with db.cursor() as cursor: # cursor.execute( # """ # DELETE FROM entry # WHERE id = %s # """, # (entry_id,), # ) # # Path: hakoblog/loader/entry.py # class EntryLoader: # @classmethod # def find_by_id(cls, db, entry_id): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, blog_id, title, body, created, modified # FROM entry # WHERE id = %s # LIMIT 1 # """, # (entry_id,), # ) # row = cursor.fetchone() # # if row is None: # return None # # return Entry(**row) # # @classmethod # def find_entries(cls, db, blog_id, limit=30): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, blog_id, title, body, created, modified # FROM entry # WHERE blog_id = %s # ORDER BY created DESC # LIMIT %s # """, # (blog_id, limit), # ) # rows = cursor.fetchall() # # return [Entry(**r) for r in rows] # # Path: tests/util.py # def create_blog(user=None): # db = DB() # # if user is None: # user = create_user() # # new_blog_id = BlogAction.create( # db, # owner_id=user.id, # title=random_string(10), # ) # return BlogLoader.find_by_id(db, new_blog_id) # # def create_entry(blog=None): # db = DB() # # if blog is None: # blog = create_blog() # # new_entry_id = EntryAction.post( # db, # blog_id=blog.id, # title=random_string(30), # body=random_string(100), # ) # return EntryLoader.find_by_id(db, new_entry_id) . Output only the next line.
assert found_entry.title == 'タイトル'
Using the snippet: <|code_start|> blog = create_blog() entry_id = EntryAction.post( db, blog_id=blog.id, title='タイトル', body='こんにちは', ) found_entry = EntryLoader.find_by_id(db, entry_id) assert found_entry.blog_id == blog.id assert found_entry.title == 'タイトル' assert found_entry.body == 'こんにちは' def test_edit(): db = DB() blog = create_blog() entry_id = EntryAction.post( db, blog_id=blog.id, title='タイトルbefore', body='こんにちはbefore', ) EntryAction.edit( db, entry_id=entry_id, <|code_end|> , determine the next line of code. You have imports: import tests.hakoblog # noqa: F401 from hakoblog.db import DB from hakoblog.action.entry import EntryAction from hakoblog.loader.entry import EntryLoader from tests.util import create_blog, create_entry and context (class names, function names, or code) available: # Path: hakoblog/db.py # class DB: # def __init__(self): # self.conn = MySQLdb.connect( # db=CONFIG.DATABASE, # host=CONFIG.DATABASE_HOST, # user=CONFIG.DATABASE_USER, # password=CONFIG.DATABASE_PASS, # cursorclass=MySQLdb.cursors.DictCursor, # charset="utf8", # ) # self.conn.autocommit(True) # # def cursor(self): # return self.conn.cursor() # # def close(self): # self.conn.close() # # def uuid_short(self): # with self.conn.cursor() as cursor: # cursor.execute("SELECT UUID_SHORT() as uuid") # return cursor.fetchone().get("uuid") # # Path: hakoblog/action/entry.py # class EntryAction: # @classmethod # def post(cls, db, blog_id, title, body): # now = datetime.now() # new_id = db.uuid_short() # with db.cursor() as cursor: # cursor.execute( # """ # INSERT INTO entry ( # id, blog_id, title, body, created, modified # ) VALUES ( # %s, %s, %s, %s, %s, %s # ) # """, # (new_id, blog_id, title, body, now, now), # ) # return new_id # # @classmethod # def edit(cls, db, entry_id, title, body): # now = datetime.now() # with db.cursor() as cursor: # cursor.execute( # """ # UPDATE entry SET # title = %s, # body = %s, # modified = %s # WHERE id = %s # """, # (title, body, now, entry_id), # ) # # @classmethod # def delete(cls, db, entry_id): # with db.cursor() as cursor: # cursor.execute( # """ # DELETE FROM entry # WHERE id = %s # """, # (entry_id,), # ) # # Path: hakoblog/loader/entry.py # class EntryLoader: # @classmethod # def find_by_id(cls, db, entry_id): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, blog_id, title, body, created, modified # FROM entry # WHERE id = %s # LIMIT 1 # """, # (entry_id,), # ) # row = cursor.fetchone() # # if row is None: # return None # # return Entry(**row) # # @classmethod # def find_entries(cls, db, blog_id, limit=30): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, blog_id, title, body, created, modified # FROM entry # WHERE blog_id = %s # ORDER BY created DESC # LIMIT %s # """, # (blog_id, limit), # ) # rows = cursor.fetchall() # # return [Entry(**r) for r in rows] # # Path: tests/util.py # def create_blog(user=None): # db = DB() # # if user is None: # user = create_user() # # new_blog_id = BlogAction.create( # db, # owner_id=user.id, # title=random_string(10), # ) # return BlogLoader.find_by_id(db, new_blog_id) # # def create_entry(blog=None): # db = DB() # # if blog is None: # blog = create_blog() # # new_entry_id = EntryAction.post( # db, # blog_id=blog.id, # title=random_string(30), # body=random_string(100), # ) # return EntryLoader.find_by_id(db, new_entry_id) . Output only the next line.
title='タイトルafter',
Using the snippet: <|code_start|> assert found_entry.blog_id == blog.id assert found_entry.title == 'タイトル' assert found_entry.body == 'こんにちは' def test_edit(): db = DB() blog = create_blog() entry_id = EntryAction.post( db, blog_id=blog.id, title='タイトルbefore', body='こんにちはbefore', ) EntryAction.edit( db, entry_id=entry_id, title='タイトルafter', body='こんにちはafter', ) found_entry = EntryLoader.find_by_id(db, entry_id) assert found_entry.blog_id == blog.id assert found_entry.title == 'タイトルafter' assert found_entry.body == 'こんにちはafter' <|code_end|> , determine the next line of code. You have imports: import tests.hakoblog # noqa: F401 from hakoblog.db import DB from hakoblog.action.entry import EntryAction from hakoblog.loader.entry import EntryLoader from tests.util import create_blog, create_entry and context (class names, function names, or code) available: # Path: hakoblog/db.py # class DB: # def __init__(self): # self.conn = MySQLdb.connect( # db=CONFIG.DATABASE, # host=CONFIG.DATABASE_HOST, # user=CONFIG.DATABASE_USER, # password=CONFIG.DATABASE_PASS, # cursorclass=MySQLdb.cursors.DictCursor, # charset="utf8", # ) # self.conn.autocommit(True) # # def cursor(self): # return self.conn.cursor() # # def close(self): # self.conn.close() # # def uuid_short(self): # with self.conn.cursor() as cursor: # cursor.execute("SELECT UUID_SHORT() as uuid") # return cursor.fetchone().get("uuid") # # Path: hakoblog/action/entry.py # class EntryAction: # @classmethod # def post(cls, db, blog_id, title, body): # now = datetime.now() # new_id = db.uuid_short() # with db.cursor() as cursor: # cursor.execute( # """ # INSERT INTO entry ( # id, blog_id, title, body, created, modified # ) VALUES ( # %s, %s, %s, %s, %s, %s # ) # """, # (new_id, blog_id, title, body, now, now), # ) # return new_id # # @classmethod # def edit(cls, db, entry_id, title, body): # now = datetime.now() # with db.cursor() as cursor: # cursor.execute( # """ # UPDATE entry SET # title = %s, # body = %s, # modified = %s # WHERE id = %s # """, # (title, body, now, entry_id), # ) # # @classmethod # def delete(cls, db, entry_id): # with db.cursor() as cursor: # cursor.execute( # """ # DELETE FROM entry # WHERE id = %s # """, # (entry_id,), # ) # # Path: hakoblog/loader/entry.py # class EntryLoader: # @classmethod # def find_by_id(cls, db, entry_id): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, blog_id, title, body, created, modified # FROM entry # WHERE id = %s # LIMIT 1 # """, # (entry_id,), # ) # row = cursor.fetchone() # # if row is None: # return None # # return Entry(**row) # # @classmethod # def find_entries(cls, db, blog_id, limit=30): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, blog_id, title, body, created, modified # FROM entry # WHERE blog_id = %s # ORDER BY created DESC # LIMIT %s # """, # (blog_id, limit), # ) # rows = cursor.fetchall() # # return [Entry(**r) for r in rows] # # Path: tests/util.py # def create_blog(user=None): # db = DB() # # if user is None: # user = create_user() # # new_blog_id = BlogAction.create( # db, # owner_id=user.id, # title=random_string(10), # ) # return BlogLoader.find_by_id(db, new_blog_id) # # def create_entry(blog=None): # db = DB() # # if blog is None: # blog = create_blog() # # new_entry_id = EntryAction.post( # db, # blog_id=blog.id, # title=random_string(30), # body=random_string(100), # ) # return EntryLoader.find_by_id(db, new_entry_id) . Output only the next line.
def test_delete():
Continue the code snippet: <|code_start|> def test_find_by_name(): db = DB() user = create_user() found_user = UserLoader.find_by_name(db, user.name) assert isinstance(found_user, User) assert found_user.name == user.name not_found_user = UserLoader.find_by_name(db, random_string(10)) <|code_end|> . Use current file imports: import tests.hakoblog # noqa: F401 from hakoblog.db import DB from hakoblog.model.user import User from hakoblog.loader.user import UserLoader from tests.util import random_string, create_user and context (classes, functions, or code) from other files: # Path: hakoblog/db.py # class DB: # def __init__(self): # self.conn = MySQLdb.connect( # db=CONFIG.DATABASE, # host=CONFIG.DATABASE_HOST, # user=CONFIG.DATABASE_USER, # password=CONFIG.DATABASE_PASS, # cursorclass=MySQLdb.cursors.DictCursor, # charset="utf8", # ) # self.conn.autocommit(True) # # def cursor(self): # return self.conn.cursor() # # def close(self): # self.conn.close() # # def uuid_short(self): # with self.conn.cursor() as cursor: # cursor.execute("SELECT UUID_SHORT() as uuid") # return cursor.fetchone().get("uuid") # # Path: hakoblog/model/user.py # class User: # def __init__(self, id, name): # self.id = id # self.name = name # # Path: hakoblog/loader/user.py # class UserLoader: # @classmethod # def find_by_name(cls, db, name): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, name # FROM user # WHERE name = %s # LIMIT 1 # """, # (name,), # ) # row = cursor.fetchone() # # if row is None: # return None # # return User(**row) # # Path: tests/util.py # def random_string(length, seq=string.digits + string.ascii_letters): # sr = random.SystemRandom() # return ''.join([sr.choice(seq) for i in range(length)]) # # def create_user(): # db = DB() # name = random_string(10) # UserAction.create(db, name) # return UserLoader.find_by_name(db, name) . Output only the next line.
assert not_found_user is None
Based on the snippet: <|code_start|> def test_find_by_name(): db = DB() user = create_user() found_user = UserLoader.find_by_name(db, user.name) assert isinstance(found_user, User) <|code_end|> , predict the immediate next line with the help of imports: import tests.hakoblog # noqa: F401 from hakoblog.db import DB from hakoblog.model.user import User from hakoblog.loader.user import UserLoader from tests.util import random_string, create_user and context (classes, functions, sometimes code) from other files: # Path: hakoblog/db.py # class DB: # def __init__(self): # self.conn = MySQLdb.connect( # db=CONFIG.DATABASE, # host=CONFIG.DATABASE_HOST, # user=CONFIG.DATABASE_USER, # password=CONFIG.DATABASE_PASS, # cursorclass=MySQLdb.cursors.DictCursor, # charset="utf8", # ) # self.conn.autocommit(True) # # def cursor(self): # return self.conn.cursor() # # def close(self): # self.conn.close() # # def uuid_short(self): # with self.conn.cursor() as cursor: # cursor.execute("SELECT UUID_SHORT() as uuid") # return cursor.fetchone().get("uuid") # # Path: hakoblog/model/user.py # class User: # def __init__(self, id, name): # self.id = id # self.name = name # # Path: hakoblog/loader/user.py # class UserLoader: # @classmethod # def find_by_name(cls, db, name): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, name # FROM user # WHERE name = %s # LIMIT 1 # """, # (name,), # ) # row = cursor.fetchone() # # if row is None: # return None # # return User(**row) # # Path: tests/util.py # def random_string(length, seq=string.digits + string.ascii_letters): # sr = random.SystemRandom() # return ''.join([sr.choice(seq) for i in range(length)]) # # def create_user(): # db = DB() # name = random_string(10) # UserAction.create(db, name) # return UserLoader.find_by_name(db, name) . Output only the next line.
assert found_user.name == user.name
Given snippet: <|code_start|> def test_find_by_name(): db = DB() user = create_user() found_user = UserLoader.find_by_name(db, user.name) assert isinstance(found_user, User) <|code_end|> , continue by predicting the next line. Consider current file imports: import tests.hakoblog # noqa: F401 from hakoblog.db import DB from hakoblog.model.user import User from hakoblog.loader.user import UserLoader from tests.util import random_string, create_user and context: # Path: hakoblog/db.py # class DB: # def __init__(self): # self.conn = MySQLdb.connect( # db=CONFIG.DATABASE, # host=CONFIG.DATABASE_HOST, # user=CONFIG.DATABASE_USER, # password=CONFIG.DATABASE_PASS, # cursorclass=MySQLdb.cursors.DictCursor, # charset="utf8", # ) # self.conn.autocommit(True) # # def cursor(self): # return self.conn.cursor() # # def close(self): # self.conn.close() # # def uuid_short(self): # with self.conn.cursor() as cursor: # cursor.execute("SELECT UUID_SHORT() as uuid") # return cursor.fetchone().get("uuid") # # Path: hakoblog/model/user.py # class User: # def __init__(self, id, name): # self.id = id # self.name = name # # Path: hakoblog/loader/user.py # class UserLoader: # @classmethod # def find_by_name(cls, db, name): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, name # FROM user # WHERE name = %s # LIMIT 1 # """, # (name,), # ) # row = cursor.fetchone() # # if row is None: # return None # # return User(**row) # # Path: tests/util.py # def random_string(length, seq=string.digits + string.ascii_letters): # sr = random.SystemRandom() # return ''.join([sr.choice(seq) for i in range(length)]) # # def create_user(): # db = DB() # name = random_string(10) # UserAction.create(db, name) # return UserLoader.find_by_name(db, name) which might include code, classes, or functions. Output only the next line.
assert found_user.name == user.name
Given the code snippet: <|code_start|> def test_init(): blog = Blog( id=0, owner_id=1, title='僕のブログ', ) <|code_end|> , generate the next line using the imports in this file: import tests.hakoblog # noqa: F401 from hakoblog.model.blog import Blog and context (functions, classes, or occasionally code) from other files: # Path: hakoblog/model/blog.py # class Blog: # def __init__(self, id, owner_id, title): # self.id = id # self.owner_id = owner_id # self.title = title . Output only the next line.
assert blog.id == 0
Here is a snippet: <|code_start|> def test_init(): user = User( id=0, name='hakobe932' ) <|code_end|> . Write the next line using the current file imports: import tests.hakoblog # noqa: F401 from hakoblog.model.user import User and context from other files: # Path: hakoblog/model/user.py # class User: # def __init__(self, id, name): # self.id = id # self.name = name , which may include functions, classes, or code. Output only the next line.
assert user.id == 0
Given the following code snippet before the placeholder: <|code_start|> def test_entry(): db = DB() with global_user(random_string(5)): blog = BlogAction.ensure_global_blog_created(db) entry = create_entry(blog=blog) res1 = web_client().get('/entry/' + str(entry.id)) assert res1.status == '200 OK' <|code_end|> , predict the next line using imports from the current file: import tests.hakoblog # noqa: F401 from pyquery import PyQuery as pq from hakoblog.db import DB from hakoblog.action.blog import BlogAction from tests.util import web_client, global_user, random_string, create_entry and context including class names, function names, and sometimes code from other files: # Path: hakoblog/db.py # class DB: # def __init__(self): # self.conn = MySQLdb.connect( # db=CONFIG.DATABASE, # host=CONFIG.DATABASE_HOST, # user=CONFIG.DATABASE_USER, # password=CONFIG.DATABASE_PASS, # cursorclass=MySQLdb.cursors.DictCursor, # charset="utf8", # ) # self.conn.autocommit(True) # # def cursor(self): # return self.conn.cursor() # # def close(self): # self.conn.close() # # def uuid_short(self): # with self.conn.cursor() as cursor: # cursor.execute("SELECT UUID_SHORT() as uuid") # return cursor.fetchone().get("uuid") # # Path: hakoblog/action/blog.py # class BlogAction: # @classmethod # def create(self, db, owner_id, title): # now = datetime.now() # new_id = db.uuid_short() # with db.cursor() as cursor: # cursor.execute( # """ # INSERT INTO blog ( # id, owner_id, title, created, modified # ) VALUES ( # %s, %s, %s, %s, %s # ) # """, # (new_id, owner_id, title, now, now), # ) # return new_id # # @classmethod # def ensure_global_blog_created(cls, db): # global_user = UserAction.ensure_global_user_created(db) # blog = BlogLoader.find_by_owner_id(db, global_user.id) # # if blog is None: # cls.create(db, global_user.id, "%s's blog" % (global_user.name,)) # blog = BlogLoader.find_by_owner_id(db, global_user.id) # # return blog # # Path: tests/util.py # def web_client(): # return web.test_client() # # @contextmanager # def global_user(name): # prev_name = CONFIG.GLOBAL_USER_NAME # CONFIG.GLOBAL_USER_NAME = name # yield name # CONFIG.GLOBAL_USER_NAME = prev_name # # def random_string(length, seq=string.digits + string.ascii_letters): # sr = random.SystemRandom() # return ''.join([sr.choice(seq) for i in range(length)]) # # def create_entry(blog=None): # db = DB() # # if blog is None: # blog = create_blog() # # new_entry_id = EntryAction.post( # db, # blog_id=blog.id, # title=random_string(30), # body=random_string(100), # ) # return EntryLoader.find_by_id(db, new_entry_id) . Output only the next line.
d = pq(res1.data)
Predict the next line after this snippet: <|code_start|> def test_entry(): db = DB() with global_user(random_string(5)): blog = BlogAction.ensure_global_blog_created(db) entry = create_entry(blog=blog) res1 = web_client().get('/entry/' + str(entry.id)) assert res1.status == '200 OK' <|code_end|> using the current file's imports: import tests.hakoblog # noqa: F401 from pyquery import PyQuery as pq from hakoblog.db import DB from hakoblog.action.blog import BlogAction from tests.util import web_client, global_user, random_string, create_entry and any relevant context from other files: # Path: hakoblog/db.py # class DB: # def __init__(self): # self.conn = MySQLdb.connect( # db=CONFIG.DATABASE, # host=CONFIG.DATABASE_HOST, # user=CONFIG.DATABASE_USER, # password=CONFIG.DATABASE_PASS, # cursorclass=MySQLdb.cursors.DictCursor, # charset="utf8", # ) # self.conn.autocommit(True) # # def cursor(self): # return self.conn.cursor() # # def close(self): # self.conn.close() # # def uuid_short(self): # with self.conn.cursor() as cursor: # cursor.execute("SELECT UUID_SHORT() as uuid") # return cursor.fetchone().get("uuid") # # Path: hakoblog/action/blog.py # class BlogAction: # @classmethod # def create(self, db, owner_id, title): # now = datetime.now() # new_id = db.uuid_short() # with db.cursor() as cursor: # cursor.execute( # """ # INSERT INTO blog ( # id, owner_id, title, created, modified # ) VALUES ( # %s, %s, %s, %s, %s # ) # """, # (new_id, owner_id, title, now, now), # ) # return new_id # # @classmethod # def ensure_global_blog_created(cls, db): # global_user = UserAction.ensure_global_user_created(db) # blog = BlogLoader.find_by_owner_id(db, global_user.id) # # if blog is None: # cls.create(db, global_user.id, "%s's blog" % (global_user.name,)) # blog = BlogLoader.find_by_owner_id(db, global_user.id) # # return blog # # Path: tests/util.py # def web_client(): # return web.test_client() # # @contextmanager # def global_user(name): # prev_name = CONFIG.GLOBAL_USER_NAME # CONFIG.GLOBAL_USER_NAME = name # yield name # CONFIG.GLOBAL_USER_NAME = prev_name # # def random_string(length, seq=string.digits + string.ascii_letters): # sr = random.SystemRandom() # return ''.join([sr.choice(seq) for i in range(length)]) # # def create_entry(blog=None): # db = DB() # # if blog is None: # blog = create_blog() # # new_entry_id = EntryAction.post( # db, # blog_id=blog.id, # title=random_string(30), # body=random_string(100), # ) # return EntryLoader.find_by_id(db, new_entry_id) . Output only the next line.
d = pq(res1.data)
Based on the snippet: <|code_start|> def test_entry(): db = DB() with global_user(random_string(5)): blog = BlogAction.ensure_global_blog_created(db) entry = create_entry(blog=blog) res1 = web_client().get('/entry/' + str(entry.id)) assert res1.status == '200 OK' <|code_end|> , predict the immediate next line with the help of imports: import tests.hakoblog # noqa: F401 from pyquery import PyQuery as pq from hakoblog.db import DB from hakoblog.action.blog import BlogAction from tests.util import web_client, global_user, random_string, create_entry and context (classes, functions, sometimes code) from other files: # Path: hakoblog/db.py # class DB: # def __init__(self): # self.conn = MySQLdb.connect( # db=CONFIG.DATABASE, # host=CONFIG.DATABASE_HOST, # user=CONFIG.DATABASE_USER, # password=CONFIG.DATABASE_PASS, # cursorclass=MySQLdb.cursors.DictCursor, # charset="utf8", # ) # self.conn.autocommit(True) # # def cursor(self): # return self.conn.cursor() # # def close(self): # self.conn.close() # # def uuid_short(self): # with self.conn.cursor() as cursor: # cursor.execute("SELECT UUID_SHORT() as uuid") # return cursor.fetchone().get("uuid") # # Path: hakoblog/action/blog.py # class BlogAction: # @classmethod # def create(self, db, owner_id, title): # now = datetime.now() # new_id = db.uuid_short() # with db.cursor() as cursor: # cursor.execute( # """ # INSERT INTO blog ( # id, owner_id, title, created, modified # ) VALUES ( # %s, %s, %s, %s, %s # ) # """, # (new_id, owner_id, title, now, now), # ) # return new_id # # @classmethod # def ensure_global_blog_created(cls, db): # global_user = UserAction.ensure_global_user_created(db) # blog = BlogLoader.find_by_owner_id(db, global_user.id) # # if blog is None: # cls.create(db, global_user.id, "%s's blog" % (global_user.name,)) # blog = BlogLoader.find_by_owner_id(db, global_user.id) # # return blog # # Path: tests/util.py # def web_client(): # return web.test_client() # # @contextmanager # def global_user(name): # prev_name = CONFIG.GLOBAL_USER_NAME # CONFIG.GLOBAL_USER_NAME = name # yield name # CONFIG.GLOBAL_USER_NAME = prev_name # # def random_string(length, seq=string.digits + string.ascii_letters): # sr = random.SystemRandom() # return ''.join([sr.choice(seq) for i in range(length)]) # # def create_entry(blog=None): # db = DB() # # if blog is None: # blog = create_blog() # # new_entry_id = EntryAction.post( # db, # blog_id=blog.id, # title=random_string(30), # body=random_string(100), # ) # return EntryLoader.find_by_id(db, new_entry_id) . Output only the next line.
d = pq(res1.data)
Here is a snippet: <|code_start|> def test_entry(): db = DB() with global_user(random_string(5)): blog = BlogAction.ensure_global_blog_created(db) entry = create_entry(blog=blog) res1 = web_client().get('/entry/' + str(entry.id)) <|code_end|> . Write the next line using the current file imports: import tests.hakoblog # noqa: F401 from pyquery import PyQuery as pq from hakoblog.db import DB from hakoblog.action.blog import BlogAction from tests.util import web_client, global_user, random_string, create_entry and context from other files: # Path: hakoblog/db.py # class DB: # def __init__(self): # self.conn = MySQLdb.connect( # db=CONFIG.DATABASE, # host=CONFIG.DATABASE_HOST, # user=CONFIG.DATABASE_USER, # password=CONFIG.DATABASE_PASS, # cursorclass=MySQLdb.cursors.DictCursor, # charset="utf8", # ) # self.conn.autocommit(True) # # def cursor(self): # return self.conn.cursor() # # def close(self): # self.conn.close() # # def uuid_short(self): # with self.conn.cursor() as cursor: # cursor.execute("SELECT UUID_SHORT() as uuid") # return cursor.fetchone().get("uuid") # # Path: hakoblog/action/blog.py # class BlogAction: # @classmethod # def create(self, db, owner_id, title): # now = datetime.now() # new_id = db.uuid_short() # with db.cursor() as cursor: # cursor.execute( # """ # INSERT INTO blog ( # id, owner_id, title, created, modified # ) VALUES ( # %s, %s, %s, %s, %s # ) # """, # (new_id, owner_id, title, now, now), # ) # return new_id # # @classmethod # def ensure_global_blog_created(cls, db): # global_user = UserAction.ensure_global_user_created(db) # blog = BlogLoader.find_by_owner_id(db, global_user.id) # # if blog is None: # cls.create(db, global_user.id, "%s's blog" % (global_user.name,)) # blog = BlogLoader.find_by_owner_id(db, global_user.id) # # return blog # # Path: tests/util.py # def web_client(): # return web.test_client() # # @contextmanager # def global_user(name): # prev_name = CONFIG.GLOBAL_USER_NAME # CONFIG.GLOBAL_USER_NAME = name # yield name # CONFIG.GLOBAL_USER_NAME = prev_name # # def random_string(length, seq=string.digits + string.ascii_letters): # sr = random.SystemRandom() # return ''.join([sr.choice(seq) for i in range(length)]) # # def create_entry(blog=None): # db = DB() # # if blog is None: # blog = create_blog() # # new_entry_id = EntryAction.post( # db, # blog_id=blog.id, # title=random_string(30), # body=random_string(100), # ) # return EntryLoader.find_by_id(db, new_entry_id) , which may include functions, classes, or code. Output only the next line.
assert res1.status == '200 OK'
Given the following code snippet before the placeholder: <|code_start|> def test_find_by_id(): db = DB() user = create_user() blog = create_blog(user=user) found_blog = BlogLoader.find_by_id(db, blog.id) assert found_blog.id == blog.id assert BlogLoader.find_by_id(db, -1) is None <|code_end|> , predict the next line using imports from the current file: import tests.hakoblog # noqa: F401 from hakoblog.db import DB from hakoblog.loader.blog import BlogLoader from tests.util import create_user, create_blog and context including class names, function names, and sometimes code from other files: # Path: hakoblog/db.py # class DB: # def __init__(self): # self.conn = MySQLdb.connect( # db=CONFIG.DATABASE, # host=CONFIG.DATABASE_HOST, # user=CONFIG.DATABASE_USER, # password=CONFIG.DATABASE_PASS, # cursorclass=MySQLdb.cursors.DictCursor, # charset="utf8", # ) # self.conn.autocommit(True) # # def cursor(self): # return self.conn.cursor() # # def close(self): # self.conn.close() # # def uuid_short(self): # with self.conn.cursor() as cursor: # cursor.execute("SELECT UUID_SHORT() as uuid") # return cursor.fetchone().get("uuid") # # Path: hakoblog/loader/blog.py # class BlogLoader: # @classmethod # def find_by_id(cls, db, blog_id): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, owner_id, title # FROM blog # WHERE id = %s # LIMIT 1 # """, # (blog_id,), # ) # row = cursor.fetchone() # # if row is None: # return None # # return Blog(**row) # # @classmethod # def find_by_owner_id(cls, db, owner_id): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, owner_id, title # FROM blog # WHERE owner_id = %s # LIMIT 1 # """, # (owner_id,), # ) # row = cursor.fetchone() # # if row is None: # return None # # return Blog(**row) # # Path: tests/util.py # def create_user(): # db = DB() # name = random_string(10) # UserAction.create(db, name) # return UserLoader.find_by_name(db, name) # # def create_blog(user=None): # db = DB() # # if user is None: # user = create_user() # # new_blog_id = BlogAction.create( # db, # owner_id=user.id, # title=random_string(10), # ) # return BlogLoader.find_by_id(db, new_blog_id) . Output only the next line.
def test_find_by_owner_id():
Continue the code snippet: <|code_start|> def test_find_by_id(): db = DB() user = create_user() blog = create_blog(user=user) found_blog = BlogLoader.find_by_id(db, blog.id) assert found_blog.id == blog.id assert BlogLoader.find_by_id(db, -1) is None <|code_end|> . Use current file imports: import tests.hakoblog # noqa: F401 from hakoblog.db import DB from hakoblog.loader.blog import BlogLoader from tests.util import create_user, create_blog and context (classes, functions, or code) from other files: # Path: hakoblog/db.py # class DB: # def __init__(self): # self.conn = MySQLdb.connect( # db=CONFIG.DATABASE, # host=CONFIG.DATABASE_HOST, # user=CONFIG.DATABASE_USER, # password=CONFIG.DATABASE_PASS, # cursorclass=MySQLdb.cursors.DictCursor, # charset="utf8", # ) # self.conn.autocommit(True) # # def cursor(self): # return self.conn.cursor() # # def close(self): # self.conn.close() # # def uuid_short(self): # with self.conn.cursor() as cursor: # cursor.execute("SELECT UUID_SHORT() as uuid") # return cursor.fetchone().get("uuid") # # Path: hakoblog/loader/blog.py # class BlogLoader: # @classmethod # def find_by_id(cls, db, blog_id): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, owner_id, title # FROM blog # WHERE id = %s # LIMIT 1 # """, # (blog_id,), # ) # row = cursor.fetchone() # # if row is None: # return None # # return Blog(**row) # # @classmethod # def find_by_owner_id(cls, db, owner_id): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, owner_id, title # FROM blog # WHERE owner_id = %s # LIMIT 1 # """, # (owner_id,), # ) # row = cursor.fetchone() # # if row is None: # return None # # return Blog(**row) # # Path: tests/util.py # def create_user(): # db = DB() # name = random_string(10) # UserAction.create(db, name) # return UserLoader.find_by_name(db, name) # # def create_blog(user=None): # db = DB() # # if user is None: # user = create_user() # # new_blog_id = BlogAction.create( # db, # owner_id=user.id, # title=random_string(10), # ) # return BlogLoader.find_by_id(db, new_blog_id) . Output only the next line.
def test_find_by_owner_id():
Based on the snippet: <|code_start|> def test_find_by_id(): db = DB() user = create_user() blog = create_blog(user=user) found_blog = BlogLoader.find_by_id(db, blog.id) assert found_blog.id == blog.id assert BlogLoader.find_by_id(db, -1) is None <|code_end|> , predict the immediate next line with the help of imports: import tests.hakoblog # noqa: F401 from hakoblog.db import DB from hakoblog.loader.blog import BlogLoader from tests.util import create_user, create_blog and context (classes, functions, sometimes code) from other files: # Path: hakoblog/db.py # class DB: # def __init__(self): # self.conn = MySQLdb.connect( # db=CONFIG.DATABASE, # host=CONFIG.DATABASE_HOST, # user=CONFIG.DATABASE_USER, # password=CONFIG.DATABASE_PASS, # cursorclass=MySQLdb.cursors.DictCursor, # charset="utf8", # ) # self.conn.autocommit(True) # # def cursor(self): # return self.conn.cursor() # # def close(self): # self.conn.close() # # def uuid_short(self): # with self.conn.cursor() as cursor: # cursor.execute("SELECT UUID_SHORT() as uuid") # return cursor.fetchone().get("uuid") # # Path: hakoblog/loader/blog.py # class BlogLoader: # @classmethod # def find_by_id(cls, db, blog_id): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, owner_id, title # FROM blog # WHERE id = %s # LIMIT 1 # """, # (blog_id,), # ) # row = cursor.fetchone() # # if row is None: # return None # # return Blog(**row) # # @classmethod # def find_by_owner_id(cls, db, owner_id): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, owner_id, title # FROM blog # WHERE owner_id = %s # LIMIT 1 # """, # (owner_id,), # ) # row = cursor.fetchone() # # if row is None: # return None # # return Blog(**row) # # Path: tests/util.py # def create_user(): # db = DB() # name = random_string(10) # UserAction.create(db, name) # return UserLoader.find_by_name(db, name) # # def create_blog(user=None): # db = DB() # # if user is None: # user = create_user() # # new_blog_id = BlogAction.create( # db, # owner_id=user.id, # title=random_string(10), # ) # return BlogLoader.find_by_id(db, new_blog_id) . Output only the next line.
def test_find_by_owner_id():
Next line prediction: <|code_start|> def test_find_by_id(): db = DB() user = create_user() blog = create_blog(user=user) found_blog = BlogLoader.find_by_id(db, blog.id) <|code_end|> . Use current file imports: (import tests.hakoblog # noqa: F401 from hakoblog.db import DB from hakoblog.loader.blog import BlogLoader from tests.util import create_user, create_blog) and context including class names, function names, or small code snippets from other files: # Path: hakoblog/db.py # class DB: # def __init__(self): # self.conn = MySQLdb.connect( # db=CONFIG.DATABASE, # host=CONFIG.DATABASE_HOST, # user=CONFIG.DATABASE_USER, # password=CONFIG.DATABASE_PASS, # cursorclass=MySQLdb.cursors.DictCursor, # charset="utf8", # ) # self.conn.autocommit(True) # # def cursor(self): # return self.conn.cursor() # # def close(self): # self.conn.close() # # def uuid_short(self): # with self.conn.cursor() as cursor: # cursor.execute("SELECT UUID_SHORT() as uuid") # return cursor.fetchone().get("uuid") # # Path: hakoblog/loader/blog.py # class BlogLoader: # @classmethod # def find_by_id(cls, db, blog_id): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, owner_id, title # FROM blog # WHERE id = %s # LIMIT 1 # """, # (blog_id,), # ) # row = cursor.fetchone() # # if row is None: # return None # # return Blog(**row) # # @classmethod # def find_by_owner_id(cls, db, owner_id): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, owner_id, title # FROM blog # WHERE owner_id = %s # LIMIT 1 # """, # (owner_id,), # ) # row = cursor.fetchone() # # if row is None: # return None # # return Blog(**row) # # Path: tests/util.py # def create_user(): # db = DB() # name = random_string(10) # UserAction.create(db, name) # return UserLoader.find_by_name(db, name) # # def create_blog(user=None): # db = DB() # # if user is None: # user = create_user() # # new_blog_id = BlogAction.create( # db, # owner_id=user.id, # title=random_string(10), # ) # return BlogLoader.find_by_id(db, new_blog_id) . Output only the next line.
assert found_blog.id == blog.id
Using the snippet: <|code_start|> class BlogAction: @classmethod def create(self, db, owner_id, title): now = datetime.now() new_id = db.uuid_short() <|code_end|> , determine the next line of code. You have imports: from datetime import datetime from hakoblog.action.user import UserAction from hakoblog.loader.blog import BlogLoader and context (class names, function names, or code) available: # Path: hakoblog/action/user.py # class UserAction: # @classmethod # def create(self, db, name): # now = datetime.now() # new_id = db.uuid_short() # with db.cursor() as cursor: # cursor.execute( # """ # INSERT INTO user ( # id, name, created, modified # ) VALUES ( # %s, %s, %s, %s # ) # """, # (new_id, name, now, now), # ) # return new_id # # @classmethod # def ensure_global_user_created(cls, db): # global_user_name = CONFIG.GLOBAL_USER_NAME # user = UserLoader.find_by_name(db, global_user_name) # if user is None: # cls.create(db, global_user_name) # user = UserLoader.find_by_name(db, global_user_name) # return user # # Path: hakoblog/loader/blog.py # class BlogLoader: # @classmethod # def find_by_id(cls, db, blog_id): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, owner_id, title # FROM blog # WHERE id = %s # LIMIT 1 # """, # (blog_id,), # ) # row = cursor.fetchone() # # if row is None: # return None # # return Blog(**row) # # @classmethod # def find_by_owner_id(cls, db, owner_id): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, owner_id, title # FROM blog # WHERE owner_id = %s # LIMIT 1 # """, # (owner_id,), # ) # row = cursor.fetchone() # # if row is None: # return None # # return Blog(**row) . Output only the next line.
with db.cursor() as cursor:
Predict the next line for this snippet: <|code_start|> class BlogAction: @classmethod def create(self, db, owner_id, title): <|code_end|> with the help of current file imports: from datetime import datetime from hakoblog.action.user import UserAction from hakoblog.loader.blog import BlogLoader and context from other files: # Path: hakoblog/action/user.py # class UserAction: # @classmethod # def create(self, db, name): # now = datetime.now() # new_id = db.uuid_short() # with db.cursor() as cursor: # cursor.execute( # """ # INSERT INTO user ( # id, name, created, modified # ) VALUES ( # %s, %s, %s, %s # ) # """, # (new_id, name, now, now), # ) # return new_id # # @classmethod # def ensure_global_user_created(cls, db): # global_user_name = CONFIG.GLOBAL_USER_NAME # user = UserLoader.find_by_name(db, global_user_name) # if user is None: # cls.create(db, global_user_name) # user = UserLoader.find_by_name(db, global_user_name) # return user # # Path: hakoblog/loader/blog.py # class BlogLoader: # @classmethod # def find_by_id(cls, db, blog_id): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, owner_id, title # FROM blog # WHERE id = %s # LIMIT 1 # """, # (blog_id,), # ) # row = cursor.fetchone() # # if row is None: # return None # # return Blog(**row) # # @classmethod # def find_by_owner_id(cls, db, owner_id): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, owner_id, title # FROM blog # WHERE owner_id = %s # LIMIT 1 # """, # (owner_id,), # ) # row = cursor.fetchone() # # if row is None: # return None # # return Blog(**row) , which may contain function names, class names, or code. Output only the next line.
now = datetime.now()
Using the snippet: <|code_start|> def test_index(): with global_user(random_string(5)) as global_user_name: res = web_client().get('/') assert res.status == '200 OK' d = pq(res.data) assert d('h1').text() == "%s's blog" % (global_user_name, ) <|code_end|> , determine the next line of code. You have imports: import tests.hakoblog # noqa: F401 from pyquery import PyQuery as pq from freezegun import freeze_time from hakoblog.db import DB from hakoblog.action.blog import BlogAction from tests.util import web_client, global_user, random_string, create_entry and context (class names, function names, or code) available: # Path: hakoblog/db.py # class DB: # def __init__(self): # self.conn = MySQLdb.connect( # db=CONFIG.DATABASE, # host=CONFIG.DATABASE_HOST, # user=CONFIG.DATABASE_USER, # password=CONFIG.DATABASE_PASS, # cursorclass=MySQLdb.cursors.DictCursor, # charset="utf8", # ) # self.conn.autocommit(True) # # def cursor(self): # return self.conn.cursor() # # def close(self): # self.conn.close() # # def uuid_short(self): # with self.conn.cursor() as cursor: # cursor.execute("SELECT UUID_SHORT() as uuid") # return cursor.fetchone().get("uuid") # # Path: hakoblog/action/blog.py # class BlogAction: # @classmethod # def create(self, db, owner_id, title): # now = datetime.now() # new_id = db.uuid_short() # with db.cursor() as cursor: # cursor.execute( # """ # INSERT INTO blog ( # id, owner_id, title, created, modified # ) VALUES ( # %s, %s, %s, %s, %s # ) # """, # (new_id, owner_id, title, now, now), # ) # return new_id # # @classmethod # def ensure_global_blog_created(cls, db): # global_user = UserAction.ensure_global_user_created(db) # blog = BlogLoader.find_by_owner_id(db, global_user.id) # # if blog is None: # cls.create(db, global_user.id, "%s's blog" % (global_user.name,)) # blog = BlogLoader.find_by_owner_id(db, global_user.id) # # return blog # # Path: tests/util.py # def web_client(): # return web.test_client() # # @contextmanager # def global_user(name): # prev_name = CONFIG.GLOBAL_USER_NAME # CONFIG.GLOBAL_USER_NAME = name # yield name # CONFIG.GLOBAL_USER_NAME = prev_name # # def random_string(length, seq=string.digits + string.ascii_letters): # sr = random.SystemRandom() # return ''.join([sr.choice(seq) for i in range(length)]) # # def create_entry(blog=None): # db = DB() # # if blog is None: # blog = create_blog() # # new_entry_id = EntryAction.post( # db, # blog_id=blog.id, # title=random_string(30), # body=random_string(100), # ) # return EntryLoader.find_by_id(db, new_entry_id) . Output only the next line.
def test_index_with_entries():
Predict the next line after this snippet: <|code_start|> def test_index(): with global_user(random_string(5)) as global_user_name: res = web_client().get('/') assert res.status == '200 OK' d = pq(res.data) assert d('h1').text() == "%s's blog" % (global_user_name, ) def test_index_with_entries(): db = DB() with global_user(random_string(5)): blog = BlogAction.ensure_global_blog_created(db) entries = [] <|code_end|> using the current file's imports: import tests.hakoblog # noqa: F401 from pyquery import PyQuery as pq from freezegun import freeze_time from hakoblog.db import DB from hakoblog.action.blog import BlogAction from tests.util import web_client, global_user, random_string, create_entry and any relevant context from other files: # Path: hakoblog/db.py # class DB: # def __init__(self): # self.conn = MySQLdb.connect( # db=CONFIG.DATABASE, # host=CONFIG.DATABASE_HOST, # user=CONFIG.DATABASE_USER, # password=CONFIG.DATABASE_PASS, # cursorclass=MySQLdb.cursors.DictCursor, # charset="utf8", # ) # self.conn.autocommit(True) # # def cursor(self): # return self.conn.cursor() # # def close(self): # self.conn.close() # # def uuid_short(self): # with self.conn.cursor() as cursor: # cursor.execute("SELECT UUID_SHORT() as uuid") # return cursor.fetchone().get("uuid") # # Path: hakoblog/action/blog.py # class BlogAction: # @classmethod # def create(self, db, owner_id, title): # now = datetime.now() # new_id = db.uuid_short() # with db.cursor() as cursor: # cursor.execute( # """ # INSERT INTO blog ( # id, owner_id, title, created, modified # ) VALUES ( # %s, %s, %s, %s, %s # ) # """, # (new_id, owner_id, title, now, now), # ) # return new_id # # @classmethod # def ensure_global_blog_created(cls, db): # global_user = UserAction.ensure_global_user_created(db) # blog = BlogLoader.find_by_owner_id(db, global_user.id) # # if blog is None: # cls.create(db, global_user.id, "%s's blog" % (global_user.name,)) # blog = BlogLoader.find_by_owner_id(db, global_user.id) # # return blog # # Path: tests/util.py # def web_client(): # return web.test_client() # # @contextmanager # def global_user(name): # prev_name = CONFIG.GLOBAL_USER_NAME # CONFIG.GLOBAL_USER_NAME = name # yield name # CONFIG.GLOBAL_USER_NAME = prev_name # # def random_string(length, seq=string.digits + string.ascii_letters): # sr = random.SystemRandom() # return ''.join([sr.choice(seq) for i in range(length)]) # # def create_entry(blog=None): # db = DB() # # if blog is None: # blog = create_blog() # # new_entry_id = EntryAction.post( # db, # blog_id=blog.id, # title=random_string(30), # body=random_string(100), # ) # return EntryLoader.find_by_id(db, new_entry_id) . Output only the next line.
with freeze_time('2017-01-13 12:00:02'):
Predict the next line for this snippet: <|code_start|> def test_index(): with global_user(random_string(5)) as global_user_name: res = web_client().get('/') assert res.status == '200 OK' d = pq(res.data) assert d('h1').text() == "%s's blog" % (global_user_name, ) def test_index_with_entries(): db = DB() with global_user(random_string(5)): blog = BlogAction.ensure_global_blog_created(db) entries = [] with freeze_time('2017-01-13 12:00:02'): entries.append(create_entry(blog=blog)) with freeze_time('2017-01-13 12:00:01'): entries.append(create_entry(blog=blog)) with freeze_time('2017-01-13 12:00:00'): entries.append(create_entry(blog=blog)) res = web_client().get('/') assert res.status == '200 OK' d = pq(res.data) <|code_end|> with the help of current file imports: import tests.hakoblog # noqa: F401 from pyquery import PyQuery as pq from freezegun import freeze_time from hakoblog.db import DB from hakoblog.action.blog import BlogAction from tests.util import web_client, global_user, random_string, create_entry and context from other files: # Path: hakoblog/db.py # class DB: # def __init__(self): # self.conn = MySQLdb.connect( # db=CONFIG.DATABASE, # host=CONFIG.DATABASE_HOST, # user=CONFIG.DATABASE_USER, # password=CONFIG.DATABASE_PASS, # cursorclass=MySQLdb.cursors.DictCursor, # charset="utf8", # ) # self.conn.autocommit(True) # # def cursor(self): # return self.conn.cursor() # # def close(self): # self.conn.close() # # def uuid_short(self): # with self.conn.cursor() as cursor: # cursor.execute("SELECT UUID_SHORT() as uuid") # return cursor.fetchone().get("uuid") # # Path: hakoblog/action/blog.py # class BlogAction: # @classmethod # def create(self, db, owner_id, title): # now = datetime.now() # new_id = db.uuid_short() # with db.cursor() as cursor: # cursor.execute( # """ # INSERT INTO blog ( # id, owner_id, title, created, modified # ) VALUES ( # %s, %s, %s, %s, %s # ) # """, # (new_id, owner_id, title, now, now), # ) # return new_id # # @classmethod # def ensure_global_blog_created(cls, db): # global_user = UserAction.ensure_global_user_created(db) # blog = BlogLoader.find_by_owner_id(db, global_user.id) # # if blog is None: # cls.create(db, global_user.id, "%s's blog" % (global_user.name,)) # blog = BlogLoader.find_by_owner_id(db, global_user.id) # # return blog # # Path: tests/util.py # def web_client(): # return web.test_client() # # @contextmanager # def global_user(name): # prev_name = CONFIG.GLOBAL_USER_NAME # CONFIG.GLOBAL_USER_NAME = name # yield name # CONFIG.GLOBAL_USER_NAME = prev_name # # def random_string(length, seq=string.digits + string.ascii_letters): # sr = random.SystemRandom() # return ''.join([sr.choice(seq) for i in range(length)]) # # def create_entry(blog=None): # db = DB() # # if blog is None: # blog = create_blog() # # new_entry_id = EntryAction.post( # db, # blog_id=blog.id, # title=random_string(30), # body=random_string(100), # ) # return EntryLoader.find_by_id(db, new_entry_id) , which may contain function names, class names, or code. Output only the next line.
assert [
Predict the next line after this snippet: <|code_start|> def test_index(): with global_user(random_string(5)) as global_user_name: res = web_client().get('/') assert res.status == '200 OK' d = pq(res.data) assert d('h1').text() == "%s's blog" % (global_user_name, ) def test_index_with_entries(): db = DB() with global_user(random_string(5)): blog = BlogAction.ensure_global_blog_created(db) <|code_end|> using the current file's imports: import tests.hakoblog # noqa: F401 from pyquery import PyQuery as pq from freezegun import freeze_time from hakoblog.db import DB from hakoblog.action.blog import BlogAction from tests.util import web_client, global_user, random_string, create_entry and any relevant context from other files: # Path: hakoblog/db.py # class DB: # def __init__(self): # self.conn = MySQLdb.connect( # db=CONFIG.DATABASE, # host=CONFIG.DATABASE_HOST, # user=CONFIG.DATABASE_USER, # password=CONFIG.DATABASE_PASS, # cursorclass=MySQLdb.cursors.DictCursor, # charset="utf8", # ) # self.conn.autocommit(True) # # def cursor(self): # return self.conn.cursor() # # def close(self): # self.conn.close() # # def uuid_short(self): # with self.conn.cursor() as cursor: # cursor.execute("SELECT UUID_SHORT() as uuid") # return cursor.fetchone().get("uuid") # # Path: hakoblog/action/blog.py # class BlogAction: # @classmethod # def create(self, db, owner_id, title): # now = datetime.now() # new_id = db.uuid_short() # with db.cursor() as cursor: # cursor.execute( # """ # INSERT INTO blog ( # id, owner_id, title, created, modified # ) VALUES ( # %s, %s, %s, %s, %s # ) # """, # (new_id, owner_id, title, now, now), # ) # return new_id # # @classmethod # def ensure_global_blog_created(cls, db): # global_user = UserAction.ensure_global_user_created(db) # blog = BlogLoader.find_by_owner_id(db, global_user.id) # # if blog is None: # cls.create(db, global_user.id, "%s's blog" % (global_user.name,)) # blog = BlogLoader.find_by_owner_id(db, global_user.id) # # return blog # # Path: tests/util.py # def web_client(): # return web.test_client() # # @contextmanager # def global_user(name): # prev_name = CONFIG.GLOBAL_USER_NAME # CONFIG.GLOBAL_USER_NAME = name # yield name # CONFIG.GLOBAL_USER_NAME = prev_name # # def random_string(length, seq=string.digits + string.ascii_letters): # sr = random.SystemRandom() # return ''.join([sr.choice(seq) for i in range(length)]) # # def create_entry(blog=None): # db = DB() # # if blog is None: # blog = create_blog() # # new_entry_id = EntryAction.post( # db, # blog_id=blog.id, # title=random_string(30), # body=random_string(100), # ) # return EntryLoader.find_by_id(db, new_entry_id) . Output only the next line.
entries = []
Predict the next line after this snippet: <|code_start|> def test_index(): with global_user(random_string(5)) as global_user_name: res = web_client().get('/') assert res.status == '200 OK' d = pq(res.data) assert d('h1').text() == "%s's blog" % (global_user_name, ) def test_index_with_entries(): db = DB() with global_user(random_string(5)): blog = BlogAction.ensure_global_blog_created(db) <|code_end|> using the current file's imports: import tests.hakoblog # noqa: F401 from pyquery import PyQuery as pq from freezegun import freeze_time from hakoblog.db import DB from hakoblog.action.blog import BlogAction from tests.util import web_client, global_user, random_string, create_entry and any relevant context from other files: # Path: hakoblog/db.py # class DB: # def __init__(self): # self.conn = MySQLdb.connect( # db=CONFIG.DATABASE, # host=CONFIG.DATABASE_HOST, # user=CONFIG.DATABASE_USER, # password=CONFIG.DATABASE_PASS, # cursorclass=MySQLdb.cursors.DictCursor, # charset="utf8", # ) # self.conn.autocommit(True) # # def cursor(self): # return self.conn.cursor() # # def close(self): # self.conn.close() # # def uuid_short(self): # with self.conn.cursor() as cursor: # cursor.execute("SELECT UUID_SHORT() as uuid") # return cursor.fetchone().get("uuid") # # Path: hakoblog/action/blog.py # class BlogAction: # @classmethod # def create(self, db, owner_id, title): # now = datetime.now() # new_id = db.uuid_short() # with db.cursor() as cursor: # cursor.execute( # """ # INSERT INTO blog ( # id, owner_id, title, created, modified # ) VALUES ( # %s, %s, %s, %s, %s # ) # """, # (new_id, owner_id, title, now, now), # ) # return new_id # # @classmethod # def ensure_global_blog_created(cls, db): # global_user = UserAction.ensure_global_user_created(db) # blog = BlogLoader.find_by_owner_id(db, global_user.id) # # if blog is None: # cls.create(db, global_user.id, "%s's blog" % (global_user.name,)) # blog = BlogLoader.find_by_owner_id(db, global_user.id) # # return blog # # Path: tests/util.py # def web_client(): # return web.test_client() # # @contextmanager # def global_user(name): # prev_name = CONFIG.GLOBAL_USER_NAME # CONFIG.GLOBAL_USER_NAME = name # yield name # CONFIG.GLOBAL_USER_NAME = prev_name # # def random_string(length, seq=string.digits + string.ascii_letters): # sr = random.SystemRandom() # return ''.join([sr.choice(seq) for i in range(length)]) # # def create_entry(blog=None): # db = DB() # # if blog is None: # blog = create_blog() # # new_entry_id = EntryAction.post( # db, # blog_id=blog.id, # title=random_string(30), # body=random_string(100), # ) # return EntryLoader.find_by_id(db, new_entry_id) . Output only the next line.
entries = []
Using the snippet: <|code_start|> def test_create(): db = DB() user = create_user() title = random_string(10) blog_id = BlogAction.create( <|code_end|> , determine the next line of code. You have imports: import tests.hakoblog # noqa: F401 from hakoblog.db import DB from hakoblog.loader.user import UserLoader from hakoblog.action.blog import BlogAction from hakoblog.loader.blog import BlogLoader from tests.util import random_string, create_user, global_user and context (class names, function names, or code) available: # Path: hakoblog/db.py # class DB: # def __init__(self): # self.conn = MySQLdb.connect( # db=CONFIG.DATABASE, # host=CONFIG.DATABASE_HOST, # user=CONFIG.DATABASE_USER, # password=CONFIG.DATABASE_PASS, # cursorclass=MySQLdb.cursors.DictCursor, # charset="utf8", # ) # self.conn.autocommit(True) # # def cursor(self): # return self.conn.cursor() # # def close(self): # self.conn.close() # # def uuid_short(self): # with self.conn.cursor() as cursor: # cursor.execute("SELECT UUID_SHORT() as uuid") # return cursor.fetchone().get("uuid") # # Path: hakoblog/loader/user.py # class UserLoader: # @classmethod # def find_by_name(cls, db, name): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, name # FROM user # WHERE name = %s # LIMIT 1 # """, # (name,), # ) # row = cursor.fetchone() # # if row is None: # return None # # return User(**row) # # Path: hakoblog/action/blog.py # class BlogAction: # @classmethod # def create(self, db, owner_id, title): # now = datetime.now() # new_id = db.uuid_short() # with db.cursor() as cursor: # cursor.execute( # """ # INSERT INTO blog ( # id, owner_id, title, created, modified # ) VALUES ( # %s, %s, %s, %s, %s # ) # """, # (new_id, owner_id, title, now, now), # ) # return new_id # # @classmethod # def ensure_global_blog_created(cls, db): # global_user = UserAction.ensure_global_user_created(db) # blog = BlogLoader.find_by_owner_id(db, global_user.id) # # if blog is None: # cls.create(db, global_user.id, "%s's blog" % (global_user.name,)) # blog = BlogLoader.find_by_owner_id(db, global_user.id) # # return blog # # Path: hakoblog/loader/blog.py # class BlogLoader: # @classmethod # def find_by_id(cls, db, blog_id): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, owner_id, title # FROM blog # WHERE id = %s # LIMIT 1 # """, # (blog_id,), # ) # row = cursor.fetchone() # # if row is None: # return None # # return Blog(**row) # # @classmethod # def find_by_owner_id(cls, db, owner_id): # with db.cursor() as cursor: # cursor.execute( # """ # SELECT id, owner_id, title # FROM blog # WHERE owner_id = %s # LIMIT 1 # """, # (owner_id,), # ) # row = cursor.fetchone() # # if row is None: # return None # # return Blog(**row) # # Path: tests/util.py # def random_string(length, seq=string.digits + string.ascii_letters): # sr = random.SystemRandom() # return ''.join([sr.choice(seq) for i in range(length)]) # # def create_user(): # db = DB() # name = random_string(10) # UserAction.create(db, name) # return UserLoader.find_by_name(db, name) # # @contextmanager # def global_user(name): # prev_name = CONFIG.GLOBAL_USER_NAME # CONFIG.GLOBAL_USER_NAME = name # yield name # CONFIG.GLOBAL_USER_NAME = prev_name . Output only the next line.
db,