Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given snippet: <|code_start|> else:
data_dir = os.path.join(get_home(), app_profiles[app]['dir'])
icon_path = os.path.join(image_dir, 'icons', app_profiles[app]['icon'])
if not os.path.exists(data_dir):
continue
files = os.listdir(data_dir)
files_filtered = [f for f in files if os.path.splitext(f)[1][1:] == app_profiles[app]['ext']]
for filename in files_filtered:
project = dict()
project['app'] = app
project['data_dir'] = data_dir
project['file'] = filename
project['display_name'] = os.path.splitext(filename)[0]
project['icon'] = icon_path
self.projects_list.append(project)
self.background = Gtk.EventBox()
self.background.get_style_context().add_class('project_list_background')
self.container = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=20)
self.align = Gtk.Alignment(xalign=0.5, yalign=0.5)
self.align.set_padding(10, 10, 20, 20)
self.align.add(self.container)
self.background.add(self.align)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import kano.gtk3.cursor as cursor
import kano_profile_gui.components.icons as icons
from gi.repository import Gtk
from kano.utils import get_home, read_json
from kano_profile.apps import get_app_list, get_app_data_dir, launch_project
from kano_profile.paths import app_profiles_file
from kano.logging import logger
from kano.gtk3.scrolled_window import ScrolledWindow
from .paths import image_dir
from kdesk.hourglass import hourglass_start, hourglass_end
and context:
# Path: kano_profile/apps.py
# def get_app_list():
# if not os.path.exists(apps_dir):
# return []
# else:
# return [p for p in os.listdir(apps_dir)
# if os.path.isdir(os.path.join(apps_dir, p))]
#
# def get_app_data_dir(app_name):
# data_str = 'data'
# app_data_dir = os.path.join(get_app_dir(app_name), data_str)
# return app_data_dir
#
# def launch_project(app, filename, data_dir, background=False):
# # This is necessary to support the new official names
# # TODO: once the apps have been renamed this will not be necessary
# name_translation = {
# 'make-art': 'kano-draw',
# 'terminal-quest': 'linux-story'
# }
#
# app_tr = name_translation.get(app, app)
#
# logger.info("launch_project: {} {} {}".format(app_tr, filename, data_dir))
#
# app_profiles = read_json(app_profiles_file)
#
# # XML file with complete pathname
# fullpath = os.path.join(data_dir, filename)
#
# # Prepare the command line to open the app with the new project
# try:
# cmd = (app_profiles[app_tr]['cmd']
# .format(fullpath=fullpath, filename=filename))
# except KeyError as exc:
# logger.warn(
# "Can't find app '{}' in the app profiles - [{}]"
# .format(app_tr, exc)
# )
# raise ValueError(_("App '{}' not available").format(app_tr))
#
# # Try to load the project if the app is already running, via a signal.
# _, _, rc = run_cmd('/usr/bin/kano-signal launch-share {}'.format(fullpath))
# if rc:
# # Likely the app is not running and the signal could not be sent, so start it now
# logger.warn("Error sending launch signal, starting the app now, rc={}".format(rc))
# if background:
# # TODO: After migrating to launching apps via systemd, shares for make-snake
# # stopped launching from KW. Created a special case here to avoid
# # fixing the make-snake cmd through systemd temporarily. FIX THIS.
# if app == 'make-snake':
# run_bg(cmd)
# else:
# run_cmd('systemd-run --user {cmd}'.format(cmd=cmd))
# else:
# _, _, rc = run_print_output_error(cmd)
# return rc
# else:
# logger.info("Sent signal to app: {} to open : {}".format(app_tr, fullpath))
#
# return 0
#
# Path: kano_profile/paths.py
# TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids')
# PAUSED_SESSIONS_FILE = os.path.join(kanoprofile_dir, '.paused_sessions')
#
# Path: kano_profile_gui/paths.py
which might include code, classes, or functions. Output only the next line. | if not self.projects_list: |
Given snippet: <|code_start|> project['app'] = app
project['data_dir'] = data_dir
project['file'] = filename
project['display_name'] = os.path.splitext(filename)[0]
project['icon'] = icon_path
self.projects_list.append(project)
self.background = Gtk.EventBox()
self.background.get_style_context().add_class('project_list_background')
self.container = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=20)
self.align = Gtk.Alignment(xalign=0.5, yalign=0.5)
self.align.set_padding(10, 10, 20, 20)
self.align.add(self.container)
self.background.add(self.align)
if not self.projects_list:
image_no_projects = icons.set_from_name('no_challenges')
image_no_projects.set_margin_top(70)
self.container.pack_start(image_no_projects, False, False, 0)
return
for i, project in enumerate(self.projects_list):
item = ProjectItem(project)
self.container.pack_start(item.background, False, False, 0)
# Each item shown in the list
class ProjectItem():
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import kano.gtk3.cursor as cursor
import kano_profile_gui.components.icons as icons
from gi.repository import Gtk
from kano.utils import get_home, read_json
from kano_profile.apps import get_app_list, get_app_data_dir, launch_project
from kano_profile.paths import app_profiles_file
from kano.logging import logger
from kano.gtk3.scrolled_window import ScrolledWindow
from .paths import image_dir
from kdesk.hourglass import hourglass_start, hourglass_end
and context:
# Path: kano_profile/apps.py
# def get_app_list():
# if not os.path.exists(apps_dir):
# return []
# else:
# return [p for p in os.listdir(apps_dir)
# if os.path.isdir(os.path.join(apps_dir, p))]
#
# def get_app_data_dir(app_name):
# data_str = 'data'
# app_data_dir = os.path.join(get_app_dir(app_name), data_str)
# return app_data_dir
#
# def launch_project(app, filename, data_dir, background=False):
# # This is necessary to support the new official names
# # TODO: once the apps have been renamed this will not be necessary
# name_translation = {
# 'make-art': 'kano-draw',
# 'terminal-quest': 'linux-story'
# }
#
# app_tr = name_translation.get(app, app)
#
# logger.info("launch_project: {} {} {}".format(app_tr, filename, data_dir))
#
# app_profiles = read_json(app_profiles_file)
#
# # XML file with complete pathname
# fullpath = os.path.join(data_dir, filename)
#
# # Prepare the command line to open the app with the new project
# try:
# cmd = (app_profiles[app_tr]['cmd']
# .format(fullpath=fullpath, filename=filename))
# except KeyError as exc:
# logger.warn(
# "Can't find app '{}' in the app profiles - [{}]"
# .format(app_tr, exc)
# )
# raise ValueError(_("App '{}' not available").format(app_tr))
#
# # Try to load the project if the app is already running, via a signal.
# _, _, rc = run_cmd('/usr/bin/kano-signal launch-share {}'.format(fullpath))
# if rc:
# # Likely the app is not running and the signal could not be sent, so start it now
# logger.warn("Error sending launch signal, starting the app now, rc={}".format(rc))
# if background:
# # TODO: After migrating to launching apps via systemd, shares for make-snake
# # stopped launching from KW. Created a special case here to avoid
# # fixing the make-snake cmd through systemd temporarily. FIX THIS.
# if app == 'make-snake':
# run_bg(cmd)
# else:
# run_cmd('systemd-run --user {cmd}'.format(cmd=cmd))
# else:
# _, _, rc = run_print_output_error(cmd)
# return rc
# else:
# logger.info("Sent signal to app: {} to open : {}".format(app_tr, fullpath))
#
# return 0
#
# Path: kano_profile/paths.py
# TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids')
# PAUSED_SESSIONS_FILE = os.path.join(kanoprofile_dir, '.paused_sessions')
#
# Path: kano_profile_gui/paths.py
which might include code, classes, or functions. Output only the next line. | def __init__(self, project): |
Based on the snippet: <|code_start|> self.title.get_style_context().add_class('project_item_title')
self.title.set_alignment(xalign=0, yalign=1)
self.label_container = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
self.label_container.pack_start(self.title, False, False, 0)
self.label_align = Gtk.Alignment(xalign=0, yalign=0.5, xscale=1, yscale=0)
self.label_align.add(self.label_container)
self.label_align.set_padding(0, 0, 10, 0)
self.image = Gtk.Image()
self.image.set_from_file(project['icon'])
self.container = Gtk.Box()
self.container.pack_start(self.image, False, False, 0)
self.container.pack_start(self.label_align, False, False, 0)
self.container.pack_end(self.button_padding, False, False, 0)
self.background.add(self.container)
def load(self, _button, app, filename, data_dir):
hourglass_start(app)
rc = launch_project(app, filename, data_dir)
if not rc == 0:
hourglass_end()
def share(self, _button, app, filename):
logger.info("share: {} {}".format(app, filename))
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import kano.gtk3.cursor as cursor
import kano_profile_gui.components.icons as icons
from gi.repository import Gtk
from kano.utils import get_home, read_json
from kano_profile.apps import get_app_list, get_app_data_dir, launch_project
from kano_profile.paths import app_profiles_file
from kano.logging import logger
from kano.gtk3.scrolled_window import ScrolledWindow
from .paths import image_dir
from kdesk.hourglass import hourglass_start, hourglass_end
and context (classes, functions, sometimes code) from other files:
# Path: kano_profile/apps.py
# def get_app_list():
# if not os.path.exists(apps_dir):
# return []
# else:
# return [p for p in os.listdir(apps_dir)
# if os.path.isdir(os.path.join(apps_dir, p))]
#
# def get_app_data_dir(app_name):
# data_str = 'data'
# app_data_dir = os.path.join(get_app_dir(app_name), data_str)
# return app_data_dir
#
# def launch_project(app, filename, data_dir, background=False):
# # This is necessary to support the new official names
# # TODO: once the apps have been renamed this will not be necessary
# name_translation = {
# 'make-art': 'kano-draw',
# 'terminal-quest': 'linux-story'
# }
#
# app_tr = name_translation.get(app, app)
#
# logger.info("launch_project: {} {} {}".format(app_tr, filename, data_dir))
#
# app_profiles = read_json(app_profiles_file)
#
# # XML file with complete pathname
# fullpath = os.path.join(data_dir, filename)
#
# # Prepare the command line to open the app with the new project
# try:
# cmd = (app_profiles[app_tr]['cmd']
# .format(fullpath=fullpath, filename=filename))
# except KeyError as exc:
# logger.warn(
# "Can't find app '{}' in the app profiles - [{}]"
# .format(app_tr, exc)
# )
# raise ValueError(_("App '{}' not available").format(app_tr))
#
# # Try to load the project if the app is already running, via a signal.
# _, _, rc = run_cmd('/usr/bin/kano-signal launch-share {}'.format(fullpath))
# if rc:
# # Likely the app is not running and the signal could not be sent, so start it now
# logger.warn("Error sending launch signal, starting the app now, rc={}".format(rc))
# if background:
# # TODO: After migrating to launching apps via systemd, shares for make-snake
# # stopped launching from KW. Created a special case here to avoid
# # fixing the make-snake cmd through systemd temporarily. FIX THIS.
# if app == 'make-snake':
# run_bg(cmd)
# else:
# run_cmd('systemd-run --user {cmd}'.format(cmd=cmd))
# else:
# _, _, rc = run_print_output_error(cmd)
# return rc
# else:
# logger.info("Sent signal to app: {} to open : {}".format(app_tr, fullpath))
#
# return 0
#
# Path: kano_profile/paths.py
# TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids')
# PAUSED_SESSIONS_FILE = os.path.join(kanoprofile_dir, '.paused_sessions')
#
# Path: kano_profile_gui/paths.py
. Output only the next line. | def activate(_win): |
Given the code snippet: <|code_start|> project['file'] = filename
project['display_name'] = os.path.splitext(filename)[0]
project['icon'] = icon_path
self.projects_list.append(project)
self.background = Gtk.EventBox()
self.background.get_style_context().add_class('project_list_background')
self.container = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=20)
self.align = Gtk.Alignment(xalign=0.5, yalign=0.5)
self.align.set_padding(10, 10, 20, 20)
self.align.add(self.container)
self.background.add(self.align)
if not self.projects_list:
image_no_projects = icons.set_from_name('no_challenges')
image_no_projects.set_margin_top(70)
self.container.pack_start(image_no_projects, False, False, 0)
return
for i, project in enumerate(self.projects_list):
item = ProjectItem(project)
self.container.pack_start(item.background, False, False, 0)
# Each item shown in the list
class ProjectItem():
def __init__(self, project):
self.background = Gtk.EventBox()
<|code_end|>
, generate the next line using the imports in this file:
import os
import kano.gtk3.cursor as cursor
import kano_profile_gui.components.icons as icons
from gi.repository import Gtk
from kano.utils import get_home, read_json
from kano_profile.apps import get_app_list, get_app_data_dir, launch_project
from kano_profile.paths import app_profiles_file
from kano.logging import logger
from kano.gtk3.scrolled_window import ScrolledWindow
from .paths import image_dir
from kdesk.hourglass import hourglass_start, hourglass_end
and context (functions, classes, or occasionally code) from other files:
# Path: kano_profile/apps.py
# def get_app_list():
# if not os.path.exists(apps_dir):
# return []
# else:
# return [p for p in os.listdir(apps_dir)
# if os.path.isdir(os.path.join(apps_dir, p))]
#
# def get_app_data_dir(app_name):
# data_str = 'data'
# app_data_dir = os.path.join(get_app_dir(app_name), data_str)
# return app_data_dir
#
# def launch_project(app, filename, data_dir, background=False):
# # This is necessary to support the new official names
# # TODO: once the apps have been renamed this will not be necessary
# name_translation = {
# 'make-art': 'kano-draw',
# 'terminal-quest': 'linux-story'
# }
#
# app_tr = name_translation.get(app, app)
#
# logger.info("launch_project: {} {} {}".format(app_tr, filename, data_dir))
#
# app_profiles = read_json(app_profiles_file)
#
# # XML file with complete pathname
# fullpath = os.path.join(data_dir, filename)
#
# # Prepare the command line to open the app with the new project
# try:
# cmd = (app_profiles[app_tr]['cmd']
# .format(fullpath=fullpath, filename=filename))
# except KeyError as exc:
# logger.warn(
# "Can't find app '{}' in the app profiles - [{}]"
# .format(app_tr, exc)
# )
# raise ValueError(_("App '{}' not available").format(app_tr))
#
# # Try to load the project if the app is already running, via a signal.
# _, _, rc = run_cmd('/usr/bin/kano-signal launch-share {}'.format(fullpath))
# if rc:
# # Likely the app is not running and the signal could not be sent, so start it now
# logger.warn("Error sending launch signal, starting the app now, rc={}".format(rc))
# if background:
# # TODO: After migrating to launching apps via systemd, shares for make-snake
# # stopped launching from KW. Created a special case here to avoid
# # fixing the make-snake cmd through systemd temporarily. FIX THIS.
# if app == 'make-snake':
# run_bg(cmd)
# else:
# run_cmd('systemd-run --user {cmd}'.format(cmd=cmd))
# else:
# _, _, rc = run_print_output_error(cmd)
# return rc
# else:
# logger.info("Sent signal to app: {} to open : {}".format(app_tr, fullpath))
#
# return 0
#
# Path: kano_profile/paths.py
# TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids')
# PAUSED_SESSIONS_FILE = os.path.join(kanoprofile_dir, '.paused_sessions')
#
# Path: kano_profile_gui/paths.py
. Output only the next line. | self.background.get_style_context().add_class('white') |
Next line prediction: <|code_start|>
icon_path = os.path.join(image_dir, 'icons', app_profiles[app]['icon'])
if not os.path.exists(data_dir):
continue
files = os.listdir(data_dir)
files_filtered = [f for f in files if os.path.splitext(f)[1][1:] == app_profiles[app]['ext']]
for filename in files_filtered:
project = dict()
project['app'] = app
project['data_dir'] = data_dir
project['file'] = filename
project['display_name'] = os.path.splitext(filename)[0]
project['icon'] = icon_path
self.projects_list.append(project)
self.background = Gtk.EventBox()
self.background.get_style_context().add_class('project_list_background')
self.container = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=20)
self.align = Gtk.Alignment(xalign=0.5, yalign=0.5)
self.align.set_padding(10, 10, 20, 20)
self.align.add(self.container)
self.background.add(self.align)
if not self.projects_list:
image_no_projects = icons.set_from_name('no_challenges')
<|code_end|>
. Use current file imports:
(import os
import kano.gtk3.cursor as cursor
import kano_profile_gui.components.icons as icons
from gi.repository import Gtk
from kano.utils import get_home, read_json
from kano_profile.apps import get_app_list, get_app_data_dir, launch_project
from kano_profile.paths import app_profiles_file
from kano.logging import logger
from kano.gtk3.scrolled_window import ScrolledWindow
from .paths import image_dir
from kdesk.hourglass import hourglass_start, hourglass_end)
and context including class names, function names, or small code snippets from other files:
# Path: kano_profile/apps.py
# def get_app_list():
# if not os.path.exists(apps_dir):
# return []
# else:
# return [p for p in os.listdir(apps_dir)
# if os.path.isdir(os.path.join(apps_dir, p))]
#
# def get_app_data_dir(app_name):
# data_str = 'data'
# app_data_dir = os.path.join(get_app_dir(app_name), data_str)
# return app_data_dir
#
# def launch_project(app, filename, data_dir, background=False):
# # This is necessary to support the new official names
# # TODO: once the apps have been renamed this will not be necessary
# name_translation = {
# 'make-art': 'kano-draw',
# 'terminal-quest': 'linux-story'
# }
#
# app_tr = name_translation.get(app, app)
#
# logger.info("launch_project: {} {} {}".format(app_tr, filename, data_dir))
#
# app_profiles = read_json(app_profiles_file)
#
# # XML file with complete pathname
# fullpath = os.path.join(data_dir, filename)
#
# # Prepare the command line to open the app with the new project
# try:
# cmd = (app_profiles[app_tr]['cmd']
# .format(fullpath=fullpath, filename=filename))
# except KeyError as exc:
# logger.warn(
# "Can't find app '{}' in the app profiles - [{}]"
# .format(app_tr, exc)
# )
# raise ValueError(_("App '{}' not available").format(app_tr))
#
# # Try to load the project if the app is already running, via a signal.
# _, _, rc = run_cmd('/usr/bin/kano-signal launch-share {}'.format(fullpath))
# if rc:
# # Likely the app is not running and the signal could not be sent, so start it now
# logger.warn("Error sending launch signal, starting the app now, rc={}".format(rc))
# if background:
# # TODO: After migrating to launching apps via systemd, shares for make-snake
# # stopped launching from KW. Created a special case here to avoid
# # fixing the make-snake cmd through systemd temporarily. FIX THIS.
# if app == 'make-snake':
# run_bg(cmd)
# else:
# run_cmd('systemd-run --user {cmd}'.format(cmd=cmd))
# else:
# _, _, rc = run_print_output_error(cmd)
# return rc
# else:
# logger.info("Sent signal to app: {} to open : {}".format(app_tr, fullpath))
#
# return 0
#
# Path: kano_profile/paths.py
# TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids')
# PAUSED_SESSIONS_FILE = os.path.join(kanoprofile_dir, '.paused_sessions')
#
# Path: kano_profile_gui/paths.py
. Output only the next line. | image_no_projects.set_margin_top(70) |
Given snippet: <|code_start|>#!/usr/bin/env python
# swag_screen.py
#
# Copyright (C) 2014, 2015 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
#
# Shows profile created
#
class SwagScreen(Template):
def __init__(self, win):
# Set window
self.win = win
self.win.set_decorated(False)
self.win.set_resizable(True)
# Set text depending on login
login = is_registered()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
from kano_login.templates.template import Template
from kano_profile_gui.images import get_image
from kano_world.functions import is_registered
and context:
# Path: kano_login/templates/template.py
# class Template(Gtk.Box):
#
# def __init__(self, img_filename, title, description, kano_button_text, orange_button_text):
# Gtk.Box.__init__(self, orientation=Gtk.Orientation.VERTICAL)
#
# if img_filename:
# self.image = Gtk.Image.new_from_file(img_filename)
# self.pack_start(self.image, False, False, 0)
#
# self.heading = Heading(title, description)
# self.kano_button = KanoButton(kano_button_text)
#
# self.pack_start(self.heading.container, False, False, 0)
#
# self.button_box = Gtk.ButtonBox(spacing=10)
# self.button_box.set_layout(Gtk.ButtonBoxStyle.SPREAD)
# self.button_box.set_margin_bottom(30)
# self.pack_start(self.button_box, False, False, 0)
#
# if not orange_button_text == "":
# self.orange_button = OrangeButton(orange_button_text)
# self.button_box.pack_start(self.orange_button, False, False, 0)
# self.button_box.pack_start(self.kano_button, False, False, 0)
# # The empty label is to centre the kano_button
# label = Gtk.Label(" ")
# self.button_box.pack_start(label, False, False, 0)
# else:
# self.button_box.pack_start(self.kano_button, False, False, 0)
#
# Path: kano_profile_gui/images.py
# def get_image(category, subcategory, name, subfolder_str):
# # The online badge image files are stored in the home directory.
# # The function bellow gets the corrects path.
# if category == 'badges' and subcategory == 'online':
# return get_online_badge_path(name)
#
# folder = os.path.join(image_dir, category, subfolder_str, subcategory)
# filename = '{name}.png'.format(name=name)
# fullpath = os.path.join(folder, filename)
# if not os.path.exists(fullpath):
# logger.error("missing image: {}".format(fullpath))
# return os.path.join(image_dir, 'icons/50/_missing.png')
# #ensure_dir(folder)
# #open(fullpath, 'w').close()
# #print '{} created'.format(fullpath)
# # try:
# # from randomavatar.randomavatar import Avatar
# # ensure_dir(folder)
# # avatar = Avatar(rows=10, columns=10)
# # image_byte_array = avatar.get_image(string=filename, width=width, height=width, pad=10)
# # avatar.save(image_byte_array=image_byte_array, save_location=fullpath)
# # print '{} created'.format(fullpath)
# # except Exception:
# # return os.path.join(image_dir, 'icons/50/_missing.png')
# return fullpath
#
# Path: kano_world/functions.py
# def is_registered():
# import mercury # Lazy import to avoid dynamically linking with global import
# kw = mercury.KanoWorld(kw_url)
# return kw.is_logged_in()
which might include code, classes, or functions. Output only the next line. | if login: |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
# swag_screen.py
#
# Copyright (C) 2014, 2015 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
#
# Shows profile created
#
class SwagScreen(Template):
def __init__(self, win):
# Set window
self.win = win
self.win.set_decorated(False)
self.win.set_resizable(True)
# Set text depending on login
login = is_registered()
<|code_end|>
with the help of current file imports:
import sys
from kano_login.templates.template import Template
from kano_profile_gui.images import get_image
from kano_world.functions import is_registered
and context from other files:
# Path: kano_login/templates/template.py
# class Template(Gtk.Box):
#
# def __init__(self, img_filename, title, description, kano_button_text, orange_button_text):
# Gtk.Box.__init__(self, orientation=Gtk.Orientation.VERTICAL)
#
# if img_filename:
# self.image = Gtk.Image.new_from_file(img_filename)
# self.pack_start(self.image, False, False, 0)
#
# self.heading = Heading(title, description)
# self.kano_button = KanoButton(kano_button_text)
#
# self.pack_start(self.heading.container, False, False, 0)
#
# self.button_box = Gtk.ButtonBox(spacing=10)
# self.button_box.set_layout(Gtk.ButtonBoxStyle.SPREAD)
# self.button_box.set_margin_bottom(30)
# self.pack_start(self.button_box, False, False, 0)
#
# if not orange_button_text == "":
# self.orange_button = OrangeButton(orange_button_text)
# self.button_box.pack_start(self.orange_button, False, False, 0)
# self.button_box.pack_start(self.kano_button, False, False, 0)
# # The empty label is to centre the kano_button
# label = Gtk.Label(" ")
# self.button_box.pack_start(label, False, False, 0)
# else:
# self.button_box.pack_start(self.kano_button, False, False, 0)
#
# Path: kano_profile_gui/images.py
# def get_image(category, subcategory, name, subfolder_str):
# # The online badge image files are stored in the home directory.
# # The function bellow gets the corrects path.
# if category == 'badges' and subcategory == 'online':
# return get_online_badge_path(name)
#
# folder = os.path.join(image_dir, category, subfolder_str, subcategory)
# filename = '{name}.png'.format(name=name)
# fullpath = os.path.join(folder, filename)
# if not os.path.exists(fullpath):
# logger.error("missing image: {}".format(fullpath))
# return os.path.join(image_dir, 'icons/50/_missing.png')
# #ensure_dir(folder)
# #open(fullpath, 'w').close()
# #print '{} created'.format(fullpath)
# # try:
# # from randomavatar.randomavatar import Avatar
# # ensure_dir(folder)
# # avatar = Avatar(rows=10, columns=10)
# # image_byte_array = avatar.get_image(string=filename, width=width, height=width, pad=10)
# # avatar.save(image_byte_array=image_byte_array, save_location=fullpath)
# # print '{} created'.format(fullpath)
# # except Exception:
# # return os.path.join(image_dir, 'icons/50/_missing.png')
# return fullpath
#
# Path: kano_world/functions.py
# def is_registered():
# import mercury # Lazy import to avoid dynamically linking with global import
# kw = mercury.KanoWorld(kw_url)
# return kw.is_logged_in()
, which may contain function names, class names, or code. Output only the next line. | if login: |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
# swag_screen.py
#
# Copyright (C) 2014, 2015 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
#
# Shows profile created
#
class SwagScreen(Template):
def __init__(self, win):
# Set window
self.win = win
self.win.set_decorated(False)
self.win.set_resizable(True)
# Set text depending on login
login = is_registered()
<|code_end|>
using the current file's imports:
import sys
from kano_login.templates.template import Template
from kano_profile_gui.images import get_image
from kano_world.functions import is_registered
and any relevant context from other files:
# Path: kano_login/templates/template.py
# class Template(Gtk.Box):
#
# def __init__(self, img_filename, title, description, kano_button_text, orange_button_text):
# Gtk.Box.__init__(self, orientation=Gtk.Orientation.VERTICAL)
#
# if img_filename:
# self.image = Gtk.Image.new_from_file(img_filename)
# self.pack_start(self.image, False, False, 0)
#
# self.heading = Heading(title, description)
# self.kano_button = KanoButton(kano_button_text)
#
# self.pack_start(self.heading.container, False, False, 0)
#
# self.button_box = Gtk.ButtonBox(spacing=10)
# self.button_box.set_layout(Gtk.ButtonBoxStyle.SPREAD)
# self.button_box.set_margin_bottom(30)
# self.pack_start(self.button_box, False, False, 0)
#
# if not orange_button_text == "":
# self.orange_button = OrangeButton(orange_button_text)
# self.button_box.pack_start(self.orange_button, False, False, 0)
# self.button_box.pack_start(self.kano_button, False, False, 0)
# # The empty label is to centre the kano_button
# label = Gtk.Label(" ")
# self.button_box.pack_start(label, False, False, 0)
# else:
# self.button_box.pack_start(self.kano_button, False, False, 0)
#
# Path: kano_profile_gui/images.py
# def get_image(category, subcategory, name, subfolder_str):
# # The online badge image files are stored in the home directory.
# # The function bellow gets the corrects path.
# if category == 'badges' and subcategory == 'online':
# return get_online_badge_path(name)
#
# folder = os.path.join(image_dir, category, subfolder_str, subcategory)
# filename = '{name}.png'.format(name=name)
# fullpath = os.path.join(folder, filename)
# if not os.path.exists(fullpath):
# logger.error("missing image: {}".format(fullpath))
# return os.path.join(image_dir, 'icons/50/_missing.png')
# #ensure_dir(folder)
# #open(fullpath, 'w').close()
# #print '{} created'.format(fullpath)
# # try:
# # from randomavatar.randomavatar import Avatar
# # ensure_dir(folder)
# # avatar = Avatar(rows=10, columns=10)
# # image_byte_array = avatar.get_image(string=filename, width=width, height=width, pad=10)
# # avatar.save(image_byte_array=image_byte_array, save_location=fullpath)
# # print '{} created'.format(fullpath)
# # except Exception:
# # return os.path.join(image_dir, 'icons/50/_missing.png')
# return fullpath
#
# Path: kano_world/functions.py
# def is_registered():
# import mercury # Lazy import to avoid dynamically linking with global import
# kw = mercury.KanoWorld(kw_url)
# return kw.is_logged_in()
. Output only the next line. | if login: |
Based on the snippet: <|code_start|>#!/usr/bin/env python
# progress_bar.py
#
# Copyright (C) 2014, 2015 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
#
# This displays orange progress bar along top of each screen
class ProgressBar(Gtk.Fixed):
def __init__(self, window_width):
Gtk.Fixed.__init__(self)
css_path = os.path.join(media_dir, "CSS/progress_bar.css")
apply_styling_to_screen(css_path)
# Height of the thin part of the progress bar
self.height = 10
# Height of the label
<|code_end|>
, predict the immediate next line with the help of imports:
import os
from gi.repository import Gtk
from kano_profile.badges import calculate_min_current_max_xp
from kano.gtk3.apply_styles import apply_styling_to_screen
from kano_profile_gui.paths import media_dir
and context (classes, functions, sometimes code) from other files:
# Path: kano_profile/badges.py
# def calculate_min_current_max_xp():
# level_rules = read_json(levels_file)
# if not level_rules:
# return -1, 0
#
# max_level = max([int(n) for n in level_rules.keys()])
# xp_now = calculate_xp()
#
# level_min = 0
# level_max = 0
#
# for level in xrange(1, max_level + 1):
# level_min = level_rules[str(level)]
#
# if level != max_level:
# level_max = level_rules[str(level + 1)]
# else:
# level_max = float('inf')
#
# if level_min <= xp_now <= level_max:
# return level_min, xp_now, level_max
#
# Path: kano_profile_gui/paths.py
. Output only the next line. | self.label_height = 30 |
Given the following code snippet before the placeholder: <|code_start|>
self.rest_of_bar = Gtk.EventBox()
self.rest_of_bar.get_style_context().add_class('rest_of_bar')
self.progress_label = Gtk.Label()
self.progress_label.set_alignment(xalign=0.5, yalign=0.5)
self.endpoint_label = Gtk.Label()
self.endpoint_label.set_alignment(xalign=0.5, yalign=0.5)
self.label_background = Gtk.EventBox()
self.label_background.get_style_context().add_class('progress_background')
self.label_background.set_size_request(self.label_width, self.label_height)
self.label_background.add(self.progress_label)
self.endpoint_background = Gtk.EventBox()
self.endpoint_background.get_style_context().add_class('endpoint_background')
self.endpoint_background.set_size_request(self.label_width, self.label_height)
self.endpoint_background.add(self.endpoint_label)
self.set_size_request(self.total_width, self.label_height)
self.set_progress()
def set_progress(self):
# Calculate xp_start, xp_progress, xp_end here
xp_start, xp_progress, xp_end = calculate_min_current_max_xp()
self.fraction = (xp_progress - xp_start + 0.0) / (xp_end - xp_start)
<|code_end|>
, predict the next line using imports from the current file:
import os
from gi.repository import Gtk
from kano_profile.badges import calculate_min_current_max_xp
from kano.gtk3.apply_styles import apply_styling_to_screen
from kano_profile_gui.paths import media_dir
and context including class names, function names, and sometimes code from other files:
# Path: kano_profile/badges.py
# def calculate_min_current_max_xp():
# level_rules = read_json(levels_file)
# if not level_rules:
# return -1, 0
#
# max_level = max([int(n) for n in level_rules.keys()])
# xp_now = calculate_xp()
#
# level_min = 0
# level_max = 0
#
# for level in xrange(1, max_level + 1):
# level_min = level_rules[str(level)]
#
# if level != max_level:
# level_max = level_rules[str(level + 1)]
# else:
# level_max = float('inf')
#
# if level_min <= xp_now <= level_max:
# return level_min, xp_now, level_max
#
# Path: kano_profile_gui/paths.py
. Output only the next line. | progress_width = (self.total_width - self.label_width) * self.fraction |
Next line prediction: <|code_start|>
class CategoryMenu(SelectMenu):
__gsignals__ = {
'category_item_selected': (GObject.SIGNAL_RUN_FIRST, None, (str,))
}
def __init__(self, parser):
# for some reason, this is not being obeyed
self.item_width = 55
self.item_height = 50
self._signal_name = 'category_item_selected'
self._parser = parser
# Initialise self._items
self._items = {}
# Save the order of the categories so we can use it outside
self.categories = self._parser.list_available_categories()
SelectMenu.__init__(self, self.categories, self._signal_name)
# Add the scrollbar for the category menu
sw = ScrolledWindow()
sw.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
# Set the scrollbar to the left
sw.set_placement(Gtk.CornerType.TOP_RIGHT)
sw.apply_styling_to_widget()
sw.set_size_request(-1, 364)
<|code_end|>
. Use current file imports:
(from gi import require_version
from gi.repository import Gtk, GObject
from kano_avatar_gui.SelectMenu import SelectMenu
from kano.gtk3.cursor import attach_cursor_events
from kano.gtk3.scrolled_window import ScrolledWindow)
and context including class names, function names, or small code snippets from other files:
# Path: kano_avatar_gui/SelectMenu.py
# class SelectMenu(Gtk.EventBox):
# def __init__(self, list_of_names, signal_name):
#
# Gtk.EventBox.__init__(self)
# apply_styling_to_screen(CSS_PATH)
#
# # Initialise self._items
# self._set_items(list_of_names)
#
# self._signal_name = signal_name
#
# # This is the selected_identifier
# self._selected = None
# self.get_style_context().add_class('select_menu')
#
# def _set_items(self, list_of_names):
# self._items = {}
#
# for name in list_of_names:
# self._items[name] = {}
# self._items[name]['selected'] = False
#
# def set_selected(self, identifier):
# '''Sets the selected element in the dictionary to True,
# and sets all the others to False
# '''
#
# self._selected = identifier
#
# def get_selected(self):
# '''Gets the name of the current selected image
# '''
#
# return self._selected
#
# def _unselect_all(self):
# '''Remove all styling on all images, and sets the 'selected'
# field to False
# '''
# self._selected = None
#
# def _add_option_to_items(self, identifier, name, item):
# '''Adds a new option in the self._items
# '''
# if identifier in self._items:
# self._items[identifier][name] = item
#
# def _remove_option_from_items(self, identifier, name):
# if identifier in self._items:
# self._items[identifier].pop(name, None)
#
# def get_option(self, identifier, option):
# if identifier in self._items:
# if option in self._items[identifier]:
# return self._items[identifier][option]
#
# return None
#
# def set_button(self, identifier, button):
# if identifier in self._items:
# self._items[identifier]['button'] = button
# else:
# logger.error(
# "Trying to set a button for an identifier that is not present")
#
# def unset_button(self, identifier):
# self._remove_option_from_items(identifier, 'button')
#
# def get_button(self, identifier):
# if identifier in self._items:
# if 'button' in self._items[identifier]:
# return self._items[identifier]['button']
#
# logger.error(
# "Trying to get a button for an identifier that is not present")
# return None
#
# def _add_selected_css(self, button):
# style = button.get_style_context()
# style.add_class('selected')
#
# def _remove_selected_css(self, button):
# style = button.get_style_context()
# style.remove_class('selected')
#
# def _add_selected_image(self, button, identifier):
# '''Pack the selected image into the button
# '''
# if 'active_path' in self._items[identifier]:
# path = self._items[identifier]['active_path']
# image = Gtk.Image.new_from_file(path)
# button.set_image(image)
#
# def _remove_selected_image(self, button, identifier):
# '''Pack the grey unselected image into the button
# '''
# if 'inactive_path' in self._items[identifier]:
# path = self._items[identifier]['inactive_path']
# image = Gtk.Image.new_from_file(path)
# button.set_image(image)
. Output only the next line. | self.add(sw) |
Given the code snippet: <|code_start|># quests.py
#
# Copyright (C) 2015 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2
#
QUESTS_LOAD_PATHS = [
os.path.join(os.path.dirname(os.path.abspath(__file__)), '../quests'),
'/usr/share/kano-profile/quests'
<|code_end|>
, generate the next line using the imports in this file:
import os
import json
import imp
from kano.logging import logger
from kano.utils import ensure_dir, run_cmd
from .paths import profile_dir
from kano_profile_gui.paths import media_dir
from kano.notifications import display_generic_notification
and context (functions, classes, or occasionally code) from other files:
# Path: kano_profile/paths.py
# TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids')
# PAUSED_SESSIONS_FILE = os.path.join(kanoprofile_dir, '.paused_sessions')
#
# Path: kano_profile_gui/paths.py
. Output only the next line. | ] |
Based on the snippet: <|code_start|># launch.py
#
# Copyright (C) 2015-2017 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2
#
# args is an array of arguments that were passed through the URL
# e.g., kano:launch:app-name, it will be ["app-name"]
def run(args):
try:
ret = args[0]
except (TypeError, IndexError) as exc:
<|code_end|>
, predict the immediate next line with the help of imports:
from kano.logging import logger
from kano_profile.apps import launch_project, check_installed
and context (classes, functions, sometimes code) from other files:
# Path: kano_profile/apps.py
# def launch_project(app, filename, data_dir, background=False):
# # This is necessary to support the new official names
# # TODO: once the apps have been renamed this will not be necessary
# name_translation = {
# 'make-art': 'kano-draw',
# 'terminal-quest': 'linux-story'
# }
#
# app_tr = name_translation.get(app, app)
#
# logger.info("launch_project: {} {} {}".format(app_tr, filename, data_dir))
#
# app_profiles = read_json(app_profiles_file)
#
# # XML file with complete pathname
# fullpath = os.path.join(data_dir, filename)
#
# # Prepare the command line to open the app with the new project
# try:
# cmd = (app_profiles[app_tr]['cmd']
# .format(fullpath=fullpath, filename=filename))
# except KeyError as exc:
# logger.warn(
# "Can't find app '{}' in the app profiles - [{}]"
# .format(app_tr, exc)
# )
# raise ValueError(_("App '{}' not available").format(app_tr))
#
# # Try to load the project if the app is already running, via a signal.
# _, _, rc = run_cmd('/usr/bin/kano-signal launch-share {}'.format(fullpath))
# if rc:
# # Likely the app is not running and the signal could not be sent, so start it now
# logger.warn("Error sending launch signal, starting the app now, rc={}".format(rc))
# if background:
# # TODO: After migrating to launching apps via systemd, shares for make-snake
# # stopped launching from KW. Created a special case here to avoid
# # fixing the make-snake cmd through systemd temporarily. FIX THIS.
# if app == 'make-snake':
# run_bg(cmd)
# else:
# run_cmd('systemd-run --user {cmd}'.format(cmd=cmd))
# else:
# _, _, rc = run_print_output_error(cmd)
# return rc
# else:
# logger.info("Sent signal to app: {} to open : {}".format(app_tr, fullpath))
#
# return 0
#
# def check_installed(app):
# """ Check if an app is installed and if not install it through kano apps.
# *Note* The translation between app and the corresponding kano-apps name is
# not straight forward. This function uses a mapping between those two.
# :param app: App name
# :type app: str
# :returns: True iff the app is installed and available
# :rtype: bool
# """
# from kano.utils.misc import is_installed
# from kano.utils.shell import run_cmd
# cmd_template = 'kano-apps install {app_name}'
# debpkg_to_kano_appstore = {
# 'make-light': 'powerup'
# }
# # Check if is already installed
# if is_installed(app):
# return True
#
# # Check if we know how to install it
# if app not in debpkg_to_kano_appstore:
# logger.error(
# "Do not know how to translate app '{}' to kano-apps"
# .format(app)
# )
# return False
#
# # Install it using kano apps
# logger.info(
# "'{}' not installed will attempt to install it as '{}' using kano apps"
# .format(app, debpkg_to_kano_appstore[app])
# )
# cmd = cmd_template.format(app_name=debpkg_to_kano_appstore[app])
# run_cmd(cmd)
#
# # Check whether it has been installed
# if not is_installed(app):
# # Something probably went wrong here
# logger.error(
# "Attempted to install app '{}' but something went wrong"
# .format(app)
# )
# return False
#
# return True
. Output only the next line. | logger.error( |
Given the following code snippet before the placeholder: <|code_start|># launch.py
#
# Copyright (C) 2015-2017 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2
#
# args is an array of arguments that were passed through the URL
# e.g., kano:launch:app-name, it will be ["app-name"]
def run(args):
try:
ret = args[0]
except (TypeError, IndexError) as exc:
<|code_end|>
, predict the next line using imports from the current file:
from kano.logging import logger
from kano_profile.apps import launch_project, check_installed
and context including class names, function names, and sometimes code from other files:
# Path: kano_profile/apps.py
# def launch_project(app, filename, data_dir, background=False):
# # This is necessary to support the new official names
# # TODO: once the apps have been renamed this will not be necessary
# name_translation = {
# 'make-art': 'kano-draw',
# 'terminal-quest': 'linux-story'
# }
#
# app_tr = name_translation.get(app, app)
#
# logger.info("launch_project: {} {} {}".format(app_tr, filename, data_dir))
#
# app_profiles = read_json(app_profiles_file)
#
# # XML file with complete pathname
# fullpath = os.path.join(data_dir, filename)
#
# # Prepare the command line to open the app with the new project
# try:
# cmd = (app_profiles[app_tr]['cmd']
# .format(fullpath=fullpath, filename=filename))
# except KeyError as exc:
# logger.warn(
# "Can't find app '{}' in the app profiles - [{}]"
# .format(app_tr, exc)
# )
# raise ValueError(_("App '{}' not available").format(app_tr))
#
# # Try to load the project if the app is already running, via a signal.
# _, _, rc = run_cmd('/usr/bin/kano-signal launch-share {}'.format(fullpath))
# if rc:
# # Likely the app is not running and the signal could not be sent, so start it now
# logger.warn("Error sending launch signal, starting the app now, rc={}".format(rc))
# if background:
# # TODO: After migrating to launching apps via systemd, shares for make-snake
# # stopped launching from KW. Created a special case here to avoid
# # fixing the make-snake cmd through systemd temporarily. FIX THIS.
# if app == 'make-snake':
# run_bg(cmd)
# else:
# run_cmd('systemd-run --user {cmd}'.format(cmd=cmd))
# else:
# _, _, rc = run_print_output_error(cmd)
# return rc
# else:
# logger.info("Sent signal to app: {} to open : {}".format(app_tr, fullpath))
#
# return 0
#
# def check_installed(app):
# """ Check if an app is installed and if not install it through kano apps.
# *Note* The translation between app and the corresponding kano-apps name is
# not straight forward. This function uses a mapping between those two.
# :param app: App name
# :type app: str
# :returns: True iff the app is installed and available
# :rtype: bool
# """
# from kano.utils.misc import is_installed
# from kano.utils.shell import run_cmd
# cmd_template = 'kano-apps install {app_name}'
# debpkg_to_kano_appstore = {
# 'make-light': 'powerup'
# }
# # Check if is already installed
# if is_installed(app):
# return True
#
# # Check if we know how to install it
# if app not in debpkg_to_kano_appstore:
# logger.error(
# "Do not know how to translate app '{}' to kano-apps"
# .format(app)
# )
# return False
#
# # Install it using kano apps
# logger.info(
# "'{}' not installed will attempt to install it as '{}' using kano apps"
# .format(app, debpkg_to_kano_appstore[app])
# )
# cmd = cmd_template.format(app_name=debpkg_to_kano_appstore[app])
# run_cmd(cmd)
#
# # Check whether it has been installed
# if not is_installed(app):
# # Something probably went wrong here
# logger.error(
# "Attempted to install app '{}' but something went wrong"
# .format(app)
# )
# return False
#
# return True
. Output only the next line. | logger.error( |
Based on the snippet: <|code_start|>def upload_share(file_path, title, app_name):
glob_session = get_glob_session()
if not glob_session:
return False, _("You are not logged in!")
return glob_session.upload_share(file_path, title, app_name)
def delete_share(share_id):
glob_session = get_glob_session()
if not glob_session:
return False, _("You are not logged in!")
return glob_session.delete_share(share_id)
def get_share_by_id(share_id):
endpoint = '/share/{}'.format(share_id)
success, text, data = request_wrapper(
'get', endpoint, headers=content_type_json
)
if not success:
return success, text, None
if 'item' in data:
return success, None, data['item']
def download_share(entry):
app = entry['app']
title = entry['title']
<|code_end|>
, predict the immediate next line with the help of imports:
import os
from slugify import slugify
from kano.utils import get_home, download_url, ensure_dir, read_json, write_json
from kano_profile.paths import app_profiles_file
from kano.logging import logger
from .connection import request_wrapper, content_type_json
from .functions import get_glob_session, get_kano_world_id
and context (classes, functions, sometimes code) from other files:
# Path: kano_profile/paths.py
# TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids')
# PAUSED_SESSIONS_FILE = os.path.join(kanoprofile_dir, '.paused_sessions')
#
# Path: kano_world/connection.py
# def _remove_sensitive_data(request_debug):
# def request_wrapper(method, endpoint, data=None, headers=None,
# session=None, files=None, params=None):
#
# Path: kano_world/functions.py
# def get_glob_session():
# return glob_session
#
# def get_kano_world_id():
# try:
# kw_id = load_profile()['kanoworld_id']
# except Exception:
# kw_id = ''
# return kw_id
. Output only the next line. | description = entry['description'] |
Predict the next line after this snippet: <|code_start|>
success, text = download_url(attachment_url, attachment_path)
if not success:
msg = "Error with downloading share file: {}".format(text)
logger.error(msg)
return False, msg
# Download screenshot
if cover_url:
cover_ext = cover_url.split('.')[-1]
cover_name = '{}.{}'.format(title_slugified, cover_ext)
cover_path = os.path.join(folder, cover_name)
success, text = download_url(cover_url, cover_path)
if not success:
msg = "Error with downloading cover file: {}".format(text)
logger.error(msg)
return False, msg
# Download resource file
if resource_url:
resource_ext = resource_url.split('.')[-1]
# Make sure we don't remove the tar from gz
if 'tar.gz' in resource_url:
resource_ext = 'tar.' + resource_ext
resource_name = '{}.{}'.format(title_slugified, resource_ext)
resource_path = os.path.join(folder, resource_name)
success, text = download_url(resource_url, resource_path)
if not success:
<|code_end|>
using the current file's imports:
import os
from slugify import slugify
from kano.utils import get_home, download_url, ensure_dir, read_json, write_json
from kano_profile.paths import app_profiles_file
from kano.logging import logger
from .connection import request_wrapper, content_type_json
from .functions import get_glob_session, get_kano_world_id
and any relevant context from other files:
# Path: kano_profile/paths.py
# TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids')
# PAUSED_SESSIONS_FILE = os.path.join(kanoprofile_dir, '.paused_sessions')
#
# Path: kano_world/connection.py
# def _remove_sensitive_data(request_debug):
# def request_wrapper(method, endpoint, data=None, headers=None,
# session=None, files=None, params=None):
#
# Path: kano_world/functions.py
# def get_glob_session():
# return glob_session
#
# def get_kano_world_id():
# try:
# kw_id = load_profile()['kanoworld_id']
# except Exception:
# kw_id = ''
# return kw_id
. Output only the next line. | msg = "Error with downloading resource file: {}".format(text) |
Based on the snippet: <|code_start|> glob_session = get_glob_session()
if not glob_session:
return False, _("You are not logged in!")
return glob_session.post_comment(share_id, comment)
def like_share(share_id):
glob_session = get_glob_session()
if not glob_session:
return False, _("You are not logged in!")
return glob_session.like_share(share_id)
def unlike_share(share_id):
glob_session = get_glob_session()
if not glob_session:
return False, _("You are not logged in!")
return glob_session.unlike_share(share_id)
def get_following():
glob_session = get_glob_session()
if not glob_session:
<|code_end|>
, predict the immediate next line with the help of imports:
import os
from slugify import slugify
from kano.utils import get_home, download_url, ensure_dir, read_json, write_json
from kano_profile.paths import app_profiles_file
from kano.logging import logger
from .connection import request_wrapper, content_type_json
from .functions import get_glob_session, get_kano_world_id
and context (classes, functions, sometimes code) from other files:
# Path: kano_profile/paths.py
# TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids')
# PAUSED_SESSIONS_FILE = os.path.join(kanoprofile_dir, '.paused_sessions')
#
# Path: kano_world/connection.py
# def _remove_sensitive_data(request_debug):
# def request_wrapper(method, endpoint, data=None, headers=None,
# session=None, files=None, params=None):
#
# Path: kano_world/functions.py
# def get_glob_session():
# return glob_session
#
# def get_kano_world_id():
# try:
# kw_id = load_profile()['kanoworld_id']
# except Exception:
# kw_id = ''
# return kw_id
. Output only the next line. | return False, _("You are not logged in!") |
Continue the code snippet: <|code_start|> app_profiles = read_json(app_profiles_file)
if app not in app_profiles:
logger.error("Cannot download share, app not found in app-profiles")
return
app_profile = app_profiles[app]
folder = os.path.join(get_home(), app_profile['dir'], 'webload')
ensure_dir(folder)
title_slugified = slugify(title)
# Download attachment
attachment_ext = attachment_url.split('.')[-1]
attachment_name = '{}.{}'.format(title_slugified, attachment_ext)
attachment_path = os.path.join(folder, attachment_name)
success, text = download_url(attachment_url, attachment_path)
if not success:
msg = "Error with downloading share file: {}".format(text)
logger.error(msg)
return False, msg
# Download screenshot
if cover_url:
cover_ext = cover_url.split('.')[-1]
cover_name = '{}.{}'.format(title_slugified, cover_ext)
cover_path = os.path.join(folder, cover_name)
<|code_end|>
. Use current file imports:
import os
from slugify import slugify
from kano.utils import get_home, download_url, ensure_dir, read_json, write_json
from kano_profile.paths import app_profiles_file
from kano.logging import logger
from .connection import request_wrapper, content_type_json
from .functions import get_glob_session, get_kano_world_id
and context (classes, functions, or code) from other files:
# Path: kano_profile/paths.py
# TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids')
# PAUSED_SESSIONS_FILE = os.path.join(kanoprofile_dir, '.paused_sessions')
#
# Path: kano_world/connection.py
# def _remove_sensitive_data(request_debug):
# def request_wrapper(method, endpoint, data=None, headers=None,
# session=None, files=None, params=None):
#
# Path: kano_world/functions.py
# def get_glob_session():
# return glob_session
#
# def get_kano_world_id():
# try:
# kw_id = load_profile()['kanoworld_id']
# except Exception:
# kw_id = ''
# return kw_id
. Output only the next line. | success, text = download_url(cover_url, cover_path) |
Based on the snippet: <|code_start|> glob_session = get_glob_session()
if not glob_session:
return False, _("You are not logged in!")
return glob_session.unlike_share(share_id)
def get_following():
glob_session = get_glob_session()
if not glob_session:
return False, _("You are not logged in!")
user_id = get_kano_world_id()
return glob_session.get_users_following(user_id)
def follow_user(user_id):
glob_session = get_glob_session()
if not glob_session:
return False, _("You are not logged in!")
return glob_session.follow_user(user_id)
def unfollow_user(user_id):
glob_session = get_glob_session()
<|code_end|>
, predict the immediate next line with the help of imports:
import os
from slugify import slugify
from kano.utils import get_home, download_url, ensure_dir, read_json, write_json
from kano_profile.paths import app_profiles_file
from kano.logging import logger
from .connection import request_wrapper, content_type_json
from .functions import get_glob_session, get_kano_world_id
and context (classes, functions, sometimes code) from other files:
# Path: kano_profile/paths.py
# TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids')
# PAUSED_SESSIONS_FILE = os.path.join(kanoprofile_dir, '.paused_sessions')
#
# Path: kano_world/connection.py
# def _remove_sensitive_data(request_debug):
# def request_wrapper(method, endpoint, data=None, headers=None,
# session=None, files=None, params=None):
#
# Path: kano_world/functions.py
# def get_glob_session():
# return glob_session
#
# def get_kano_world_id():
# try:
# kw_id = load_profile()['kanoworld_id']
# except Exception:
# kw_id = ''
# return kw_id
. Output only the next line. | if not glob_session: |
Given the code snippet: <|code_start|># cache_functions.py
#
# Copyright (C) 2015-2016 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
#
def cache_data(category, value):
if category in ['username', 'email']:
save_app_state_variable('kano-avatar-registration', category, value)
def get_cached_data(category):
return load_app_state_variable('kano-avatar-registration', category)
def cache_emails(email):
cache_data('email', email)
def cache_all(email, secondary_email, username,
birthday_day, birthday_month, birthday_year,
marketing_enabled):
<|code_end|>
, generate the next line using the imports in this file:
from kano_profile.apps import load_app_state_variable, save_app_state_variable
and context (functions, classes, or occasionally code) from other files:
# Path: kano_profile/apps.py
# def load_app_state_variable(app_name, variable):
# data = load_app_state(app_name)
# if variable in data:
# return data[variable]
#
# def save_app_state_variable(app_name, variable, value):
# """ Save a state variable to the user's Kano profile.
#
# :param app_name: The application that this variable is associated with.
# :type app_name: str
# :param variable: The name of the variable.
# :type data: str
# :param value: The variable data to be stored.
# :type value: any
# """
#
# msg = "save_app_state_variable {} {} {}".format(app_name, variable, value)
# logger.debug(msg)
#
# data = load_app_state(app_name)
# data[variable] = value
#
# save_app_state(app_name, data)
. Output only the next line. | cache_data('email', email) |
Next line prediction: <|code_start|># cache_functions.py
#
# Copyright (C) 2015-2016 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
#
def cache_data(category, value):
if category in ['username', 'email']:
save_app_state_variable('kano-avatar-registration', category, value)
def get_cached_data(category):
return load_app_state_variable('kano-avatar-registration', category)
def cache_emails(email):
cache_data('email', email)
def cache_all(email, secondary_email, username,
birthday_day, birthday_month, birthday_year,
marketing_enabled):
<|code_end|>
. Use current file imports:
(from kano_profile.apps import load_app_state_variable, save_app_state_variable)
and context including class names, function names, or small code snippets from other files:
# Path: kano_profile/apps.py
# def load_app_state_variable(app_name, variable):
# data = load_app_state(app_name)
# if variable in data:
# return data[variable]
#
# def save_app_state_variable(app_name, variable, value):
# """ Save a state variable to the user's Kano profile.
#
# :param app_name: The application that this variable is associated with.
# :type app_name: str
# :param variable: The name of the variable.
# :type data: str
# :param value: The variable data to be stored.
# :type value: any
# """
#
# msg = "save_app_state_variable {} {} {}".format(app_name, variable, value)
# logger.debug(msg)
#
# data = load_app_state(app_name)
# data[variable] = value
#
# save_app_state(app_name, data)
. Output only the next line. | cache_data('email', email) |
Given snippet: <|code_start|>def set_from_name(name):
image = Gtk.Image()
image.set_from_file(media_dir + "/images/icons/" + name + ".png")
return image
MEDIA_LOCS = ['../media', '/usr/share/kano-profile/media']
APP_ICON_SIZE = 68
def get_app_icon(loc, size=APP_ICON_SIZE):
try:
pb = GdkPixbuf.Pixbuf.new_from_file_at_size(loc, size, size)
icon = Gtk.Image.new_from_pixbuf(pb)
except:
icon = Gtk.Image.new_from_icon_name(loc, -1)
icon.set_pixel_size(size)
return icon
def get_ui_icon(name):
if name == 'green_arrow':
icon_number = 0
elif name == 'pale_right_arrow':
icon_number = 1
elif name == 'dark_left_arrow':
icon_number = 2
elif name == 'dark_right_arrow':
icon_number = 3
elif name == 'pale_left_arrow':
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
from gi.repository import Gtk, GdkPixbuf
from kano_profile_gui.paths import media_dir
and context:
# Path: kano_profile_gui/paths.py
which might include code, classes, or functions. Output only the next line. | icon_number = 4 |
Next line prediction: <|code_start|> else:
with f:
json.dump(data, f)
if 'SUDO_USER' in os.environ:
chown_path(path)
return path
def session_end(session_file):
if not os.path.exists(session_file):
msg = "Someone removed the tracker file, the runtime of this " \
"app will not be logged"
logger.warn(msg)
return
try:
rf = open_locked(session_file, 'r')
except IOError as e:
logger.error("Error opening the tracker session file {}".format(e))
else:
with rf:
data = json.load(rf)
data['elapsed'] = int(time.time()) - data['started']
data['finished'] = True
try:
wf = open(session_file, 'w')
except IOError as e:
<|code_end|>
. Use current file imports:
(import os
import json
import shutil
import time
from uuid import uuid1, uuid5
from kano.utils.hardware import get_cpu_id
from kano.utils.file_operations import read_file_contents, chown_path
from kano.logging import logger
from kano_profile.tracker.tracker_token import TOKEN
from kano_profile.paths import tracker_dir, tracker_events_file, \
PAUSED_SESSIONS_FILE
from kano_profile.tracker.tracking_session import TrackingSession
from kano_profile.tracker.tracking_utils import open_locked, get_utc_offset)
and context including class names, function names, or small code snippets from other files:
# Path: kano_profile/tracker/tracker_token.py
# TOKEN = load_token()
#
# Path: kano_profile/paths.py
# TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids')
# PAUSED_SESSIONS_FILE = os.path.join(kanoprofile_dir, '.paused_sessions')
#
# Path: kano_profile/tracker/tracking_session.py
# class TrackingSession(object):
# SESSION_FILE_RE = re.compile(r'^(\d+)-(.*).json$')
#
# def __init__(self, session_file=None, name=None, pid=None):
# if session_file:
# self._file = os.path.basename(session_file)
# self._pid, self._name = self.parse_session_file(self.file)
# elif name and pid:
# self._name = name
# self._pid = int(pid)
# self._file = self.parse_name_and_pid(self.name, self.pid)
#
# else:
# raise TypeError(
# 'TrackingSession requires a file or a name/pid combination'
# )
#
# def parse_session_file(self, session_file):
# matches = TrackingSession.SESSION_FILE_RE.findall(session_file)
#
# if not matches:
# return None, None
#
# match_data = matches[0]
#
# pid = int(match_data[0])
# name = match_data[1]
#
# return pid, name
#
# def parse_name_and_pid(self, name, pid):
# return "{}-{}.json".format(pid, name)
#
# def __repr__(self):
# return 'Tracking Session [Name: {name}, PID: {pid}]: {is_open}'.format(
# name=self.name,
# pid=self.pid,
# is_open='OPEN' if self.is_open() else 'CLOSED'
# )
#
# def __str__(self):
# return self.__repr__()
#
# def __eq__(self, other):
# return self.file == other.file
#
# @property
# def file(self):
# return self._file
#
# @property
# def path(self):
# return os.path.join(tracker_dir, self.file)
#
# @property
# def name(self):
# return self._name.encode('utf-8')
#
# @property
# def pid(self):
# return self._pid or 0
#
# def is_open(self):
# return is_pid_running(self.pid)
#
# def open(self, mode):
# try:
# session_f = open_locked(self.path, mode)
# except IOError as exc:
# logger.error(
# 'Error opening the tracking session file "{f}": {err}'
# .format(f=self.path, err=exc)
# )
# else:
# yield session_f
#
# def dumps(self):
# return json.dumps({
# 'name': self.name,
# 'pid': self.pid
# })
#
# @staticmethod
# def loads(session):
# session_data = json.loads(session.rstrip().lstrip())
# return TrackingSession(
# name=session_data.get('name'),
# pid=session_data.get('pid')
# )
#
# Path: kano_profile/tracker/tracking_utils.py
# class open_locked(file):
# """ A version of open with an exclusive lock to be used within
# controlled execution statements.
# """
# def __init__(self, *args, **kwargs):
# super(open_locked, self).__init__(*args, **kwargs)
# fcntl.flock(self, fcntl.LOCK_EX)
#
# def get_utc_offset():
# """ Returns the local UTC offset in seconds.
#
# :returns: UTC offsed in secconds.
# :rtype: int
# """
#
# is_dst = time.daylight and time.localtime().tm_isdst > 0
# return -int(time.altzone if is_dst else time.timezone)
. Output only the next line. | logger.error( |
Continue the code snippet: <|code_start|> f for f in os.listdir(tracker_dir) # noqa
if os.path.isfile(os.path.join(tracker_dir, f)) and # noqa
os.path.join(tracker_dir, f) != PAUSED_SESSIONS_FILE # noqa
] # noqa
def get_open_sessions():
open_sessions = []
for session_file in list_sessions():
session = TrackingSession(session_file=session_file)
if not os.path.isfile(session.path):
continue
if not session.is_open():
continue
open_sessions.append(session)
return open_sessions
def get_session_file_path(name, pid):
return "{}/{}-{}.json".format(tracker_dir, pid, name)
def get_session_unique_id(name, pid):
data = {}
tracker_session_file = get_session_file_path(name, pid)
<|code_end|>
. Use current file imports:
import os
import json
import shutil
import time
from uuid import uuid1, uuid5
from kano.utils.hardware import get_cpu_id
from kano.utils.file_operations import read_file_contents, chown_path
from kano.logging import logger
from kano_profile.tracker.tracker_token import TOKEN
from kano_profile.paths import tracker_dir, tracker_events_file, \
PAUSED_SESSIONS_FILE
from kano_profile.tracker.tracking_session import TrackingSession
from kano_profile.tracker.tracking_utils import open_locked, get_utc_offset
and context (classes, functions, or code) from other files:
# Path: kano_profile/tracker/tracker_token.py
# TOKEN = load_token()
#
# Path: kano_profile/paths.py
# TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids')
# PAUSED_SESSIONS_FILE = os.path.join(kanoprofile_dir, '.paused_sessions')
#
# Path: kano_profile/tracker/tracking_session.py
# class TrackingSession(object):
# SESSION_FILE_RE = re.compile(r'^(\d+)-(.*).json$')
#
# def __init__(self, session_file=None, name=None, pid=None):
# if session_file:
# self._file = os.path.basename(session_file)
# self._pid, self._name = self.parse_session_file(self.file)
# elif name and pid:
# self._name = name
# self._pid = int(pid)
# self._file = self.parse_name_and_pid(self.name, self.pid)
#
# else:
# raise TypeError(
# 'TrackingSession requires a file or a name/pid combination'
# )
#
# def parse_session_file(self, session_file):
# matches = TrackingSession.SESSION_FILE_RE.findall(session_file)
#
# if not matches:
# return None, None
#
# match_data = matches[0]
#
# pid = int(match_data[0])
# name = match_data[1]
#
# return pid, name
#
# def parse_name_and_pid(self, name, pid):
# return "{}-{}.json".format(pid, name)
#
# def __repr__(self):
# return 'Tracking Session [Name: {name}, PID: {pid}]: {is_open}'.format(
# name=self.name,
# pid=self.pid,
# is_open='OPEN' if self.is_open() else 'CLOSED'
# )
#
# def __str__(self):
# return self.__repr__()
#
# def __eq__(self, other):
# return self.file == other.file
#
# @property
# def file(self):
# return self._file
#
# @property
# def path(self):
# return os.path.join(tracker_dir, self.file)
#
# @property
# def name(self):
# return self._name.encode('utf-8')
#
# @property
# def pid(self):
# return self._pid or 0
#
# def is_open(self):
# return is_pid_running(self.pid)
#
# def open(self, mode):
# try:
# session_f = open_locked(self.path, mode)
# except IOError as exc:
# logger.error(
# 'Error opening the tracking session file "{f}": {err}'
# .format(f=self.path, err=exc)
# )
# else:
# yield session_f
#
# def dumps(self):
# return json.dumps({
# 'name': self.name,
# 'pid': self.pid
# })
#
# @staticmethod
# def loads(session):
# session_data = json.loads(session.rstrip().lstrip())
# return TrackingSession(
# name=session_data.get('name'),
# pid=session_data.get('pid')
# )
#
# Path: kano_profile/tracker/tracking_utils.py
# class open_locked(file):
# """ A version of open with an exclusive lock to be used within
# controlled execution statements.
# """
# def __init__(self, *args, **kwargs):
# super(open_locked, self).__init__(*args, **kwargs)
# fcntl.flock(self, fcntl.LOCK_EX)
#
# def get_utc_offset():
# """ Returns the local UTC offset in seconds.
#
# :returns: UTC offsed in secconds.
# :rtype: int
# """
#
# is_dst = time.daylight and time.localtime().tm_isdst > 0
# return -int(time.altzone if is_dst else time.timezone)
. Output only the next line. | try: |
Using the snippet: <|code_start|> '{}\n'.format(session.dumps())
)
return session.path
data = {
'pid': pid,
'name': name,
'started': int(time.time()),
'elapsed': 0,
'app_session_id': str(uuid5(uuid1(), name + str(pid))),
'finished': False,
'token-system': TOKEN
}
path = get_session_file_path(data['name'], data['pid'])
try:
f = open_locked(path, 'w')
except IOError as e:
logger.error("Error opening tracker session file {}".format(e))
else:
with f:
json.dump(data, f)
if 'SUDO_USER' in os.environ:
chown_path(path)
return path
<|code_end|>
, determine the next line of code. You have imports:
import os
import json
import shutil
import time
from uuid import uuid1, uuid5
from kano.utils.hardware import get_cpu_id
from kano.utils.file_operations import read_file_contents, chown_path
from kano.logging import logger
from kano_profile.tracker.tracker_token import TOKEN
from kano_profile.paths import tracker_dir, tracker_events_file, \
PAUSED_SESSIONS_FILE
from kano_profile.tracker.tracking_session import TrackingSession
from kano_profile.tracker.tracking_utils import open_locked, get_utc_offset
and context (class names, function names, or code) available:
# Path: kano_profile/tracker/tracker_token.py
# TOKEN = load_token()
#
# Path: kano_profile/paths.py
# TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids')
# PAUSED_SESSIONS_FILE = os.path.join(kanoprofile_dir, '.paused_sessions')
#
# Path: kano_profile/tracker/tracking_session.py
# class TrackingSession(object):
# SESSION_FILE_RE = re.compile(r'^(\d+)-(.*).json$')
#
# def __init__(self, session_file=None, name=None, pid=None):
# if session_file:
# self._file = os.path.basename(session_file)
# self._pid, self._name = self.parse_session_file(self.file)
# elif name and pid:
# self._name = name
# self._pid = int(pid)
# self._file = self.parse_name_and_pid(self.name, self.pid)
#
# else:
# raise TypeError(
# 'TrackingSession requires a file or a name/pid combination'
# )
#
# def parse_session_file(self, session_file):
# matches = TrackingSession.SESSION_FILE_RE.findall(session_file)
#
# if not matches:
# return None, None
#
# match_data = matches[0]
#
# pid = int(match_data[0])
# name = match_data[1]
#
# return pid, name
#
# def parse_name_and_pid(self, name, pid):
# return "{}-{}.json".format(pid, name)
#
# def __repr__(self):
# return 'Tracking Session [Name: {name}, PID: {pid}]: {is_open}'.format(
# name=self.name,
# pid=self.pid,
# is_open='OPEN' if self.is_open() else 'CLOSED'
# )
#
# def __str__(self):
# return self.__repr__()
#
# def __eq__(self, other):
# return self.file == other.file
#
# @property
# def file(self):
# return self._file
#
# @property
# def path(self):
# return os.path.join(tracker_dir, self.file)
#
# @property
# def name(self):
# return self._name.encode('utf-8')
#
# @property
# def pid(self):
# return self._pid or 0
#
# def is_open(self):
# return is_pid_running(self.pid)
#
# def open(self, mode):
# try:
# session_f = open_locked(self.path, mode)
# except IOError as exc:
# logger.error(
# 'Error opening the tracking session file "{f}": {err}'
# .format(f=self.path, err=exc)
# )
# else:
# yield session_f
#
# def dumps(self):
# return json.dumps({
# 'name': self.name,
# 'pid': self.pid
# })
#
# @staticmethod
# def loads(session):
# session_data = json.loads(session.rstrip().lstrip())
# return TrackingSession(
# name=session_data.get('name'),
# pid=session_data.get('pid')
# )
#
# Path: kano_profile/tracker/tracking_utils.py
# class open_locked(file):
# """ A version of open with an exclusive lock to be used within
# controlled execution statements.
# """
# def __init__(self, *args, **kwargs):
# super(open_locked, self).__init__(*args, **kwargs)
# fcntl.flock(self, fcntl.LOCK_EX)
#
# def get_utc_offset():
# """ Returns the local UTC offset in seconds.
#
# :returns: UTC offsed in secconds.
# :rtype: int
# """
#
# is_dst = time.daylight and time.localtime().tm_isdst > 0
# return -int(time.altzone if is_dst else time.timezone)
. Output only the next line. | def session_end(session_file): |
Predict the next line for this snippet: <|code_start|> try:
wf = open(session_file, 'w')
except IOError as e:
logger.error(
"Error opening the tracker session file {}".format(e))
else:
with wf:
json.dump(data, wf)
if 'SUDO_USER' in os.environ:
chown_path(session_file)
def get_paused_sessions():
if not os.path.exists(PAUSED_SESSIONS_FILE):
return []
try:
sessions_f = open_locked(PAUSED_SESSIONS_FILE, 'r')
except IOError as err:
logger.error('Error opening the paused sessions file: {}'.format(err))
return []
else:
with sessions_f:
paused_sessions = []
for session in sessions_f:
if not session:
continue
try:
new_session = TrackingSession.loads(session)
<|code_end|>
with the help of current file imports:
import os
import json
import shutil
import time
from uuid import uuid1, uuid5
from kano.utils.hardware import get_cpu_id
from kano.utils.file_operations import read_file_contents, chown_path
from kano.logging import logger
from kano_profile.tracker.tracker_token import TOKEN
from kano_profile.paths import tracker_dir, tracker_events_file, \
PAUSED_SESSIONS_FILE
from kano_profile.tracker.tracking_session import TrackingSession
from kano_profile.tracker.tracking_utils import open_locked, get_utc_offset
and context from other files:
# Path: kano_profile/tracker/tracker_token.py
# TOKEN = load_token()
#
# Path: kano_profile/paths.py
# TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids')
# PAUSED_SESSIONS_FILE = os.path.join(kanoprofile_dir, '.paused_sessions')
#
# Path: kano_profile/tracker/tracking_session.py
# class TrackingSession(object):
# SESSION_FILE_RE = re.compile(r'^(\d+)-(.*).json$')
#
# def __init__(self, session_file=None, name=None, pid=None):
# if session_file:
# self._file = os.path.basename(session_file)
# self._pid, self._name = self.parse_session_file(self.file)
# elif name and pid:
# self._name = name
# self._pid = int(pid)
# self._file = self.parse_name_and_pid(self.name, self.pid)
#
# else:
# raise TypeError(
# 'TrackingSession requires a file or a name/pid combination'
# )
#
# def parse_session_file(self, session_file):
# matches = TrackingSession.SESSION_FILE_RE.findall(session_file)
#
# if not matches:
# return None, None
#
# match_data = matches[0]
#
# pid = int(match_data[0])
# name = match_data[1]
#
# return pid, name
#
# def parse_name_and_pid(self, name, pid):
# return "{}-{}.json".format(pid, name)
#
# def __repr__(self):
# return 'Tracking Session [Name: {name}, PID: {pid}]: {is_open}'.format(
# name=self.name,
# pid=self.pid,
# is_open='OPEN' if self.is_open() else 'CLOSED'
# )
#
# def __str__(self):
# return self.__repr__()
#
# def __eq__(self, other):
# return self.file == other.file
#
# @property
# def file(self):
# return self._file
#
# @property
# def path(self):
# return os.path.join(tracker_dir, self.file)
#
# @property
# def name(self):
# return self._name.encode('utf-8')
#
# @property
# def pid(self):
# return self._pid or 0
#
# def is_open(self):
# return is_pid_running(self.pid)
#
# def open(self, mode):
# try:
# session_f = open_locked(self.path, mode)
# except IOError as exc:
# logger.error(
# 'Error opening the tracking session file "{f}": {err}'
# .format(f=self.path, err=exc)
# )
# else:
# yield session_f
#
# def dumps(self):
# return json.dumps({
# 'name': self.name,
# 'pid': self.pid
# })
#
# @staticmethod
# def loads(session):
# session_data = json.loads(session.rstrip().lstrip())
# return TrackingSession(
# name=session_data.get('name'),
# pid=session_data.get('pid')
# )
#
# Path: kano_profile/tracker/tracking_utils.py
# class open_locked(file):
# """ A version of open with an exclusive lock to be used within
# controlled execution statements.
# """
# def __init__(self, *args, **kwargs):
# super(open_locked, self).__init__(*args, **kwargs)
# fcntl.flock(self, fcntl.LOCK_EX)
#
# def get_utc_offset():
# """ Returns the local UTC offset in seconds.
#
# :returns: UTC offsed in secconds.
# :rtype: int
# """
#
# is_dst = time.daylight and time.localtime().tm_isdst > 0
# return -int(time.altzone if is_dst else time.timezone)
, which may contain function names, class names, or code. Output only the next line. | except TypeError: |
Based on the snippet: <|code_start|> else:
with rf:
data = json.load(rf)
data['elapsed'] = int(time.time()) - data['started']
data['finished'] = True
try:
wf = open(session_file, 'w')
except IOError as e:
logger.error(
"Error opening the tracker session file {}".format(e))
else:
with wf:
json.dump(data, wf)
if 'SUDO_USER' in os.environ:
chown_path(session_file)
def get_paused_sessions():
if not os.path.exists(PAUSED_SESSIONS_FILE):
return []
try:
sessions_f = open_locked(PAUSED_SESSIONS_FILE, 'r')
except IOError as err:
logger.error('Error opening the paused sessions file: {}'.format(err))
return []
else:
with sessions_f:
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import json
import shutil
import time
from uuid import uuid1, uuid5
from kano.utils.hardware import get_cpu_id
from kano.utils.file_operations import read_file_contents, chown_path
from kano.logging import logger
from kano_profile.tracker.tracker_token import TOKEN
from kano_profile.paths import tracker_dir, tracker_events_file, \
PAUSED_SESSIONS_FILE
from kano_profile.tracker.tracking_session import TrackingSession
from kano_profile.tracker.tracking_utils import open_locked, get_utc_offset
and context (classes, functions, sometimes code) from other files:
# Path: kano_profile/tracker/tracker_token.py
# TOKEN = load_token()
#
# Path: kano_profile/paths.py
# TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids')
# PAUSED_SESSIONS_FILE = os.path.join(kanoprofile_dir, '.paused_sessions')
#
# Path: kano_profile/tracker/tracking_session.py
# class TrackingSession(object):
# SESSION_FILE_RE = re.compile(r'^(\d+)-(.*).json$')
#
# def __init__(self, session_file=None, name=None, pid=None):
# if session_file:
# self._file = os.path.basename(session_file)
# self._pid, self._name = self.parse_session_file(self.file)
# elif name and pid:
# self._name = name
# self._pid = int(pid)
# self._file = self.parse_name_and_pid(self.name, self.pid)
#
# else:
# raise TypeError(
# 'TrackingSession requires a file or a name/pid combination'
# )
#
# def parse_session_file(self, session_file):
# matches = TrackingSession.SESSION_FILE_RE.findall(session_file)
#
# if not matches:
# return None, None
#
# match_data = matches[0]
#
# pid = int(match_data[0])
# name = match_data[1]
#
# return pid, name
#
# def parse_name_and_pid(self, name, pid):
# return "{}-{}.json".format(pid, name)
#
# def __repr__(self):
# return 'Tracking Session [Name: {name}, PID: {pid}]: {is_open}'.format(
# name=self.name,
# pid=self.pid,
# is_open='OPEN' if self.is_open() else 'CLOSED'
# )
#
# def __str__(self):
# return self.__repr__()
#
# def __eq__(self, other):
# return self.file == other.file
#
# @property
# def file(self):
# return self._file
#
# @property
# def path(self):
# return os.path.join(tracker_dir, self.file)
#
# @property
# def name(self):
# return self._name.encode('utf-8')
#
# @property
# def pid(self):
# return self._pid or 0
#
# def is_open(self):
# return is_pid_running(self.pid)
#
# def open(self, mode):
# try:
# session_f = open_locked(self.path, mode)
# except IOError as exc:
# logger.error(
# 'Error opening the tracking session file "{f}": {err}'
# .format(f=self.path, err=exc)
# )
# else:
# yield session_f
#
# def dumps(self):
# return json.dumps({
# 'name': self.name,
# 'pid': self.pid
# })
#
# @staticmethod
# def loads(session):
# session_data = json.loads(session.rstrip().lstrip())
# return TrackingSession(
# name=session_data.get('name'),
# pid=session_data.get('pid')
# )
#
# Path: kano_profile/tracker/tracking_utils.py
# class open_locked(file):
# """ A version of open with an exclusive lock to be used within
# controlled execution statements.
# """
# def __init__(self, *args, **kwargs):
# super(open_locked, self).__init__(*args, **kwargs)
# fcntl.flock(self, fcntl.LOCK_EX)
#
# def get_utc_offset():
# """ Returns the local UTC offset in seconds.
#
# :returns: UTC offsed in secconds.
# :rtype: int
# """
#
# is_dst = time.daylight and time.localtime().tm_isdst > 0
# return -int(time.altzone if is_dst else time.timezone)
. Output only the next line. | paused_sessions = [] |
Using the snippet: <|code_start|>def list_sessions():
return [ # noqa
f for f in os.listdir(tracker_dir) # noqa
if os.path.isfile(os.path.join(tracker_dir, f)) and # noqa
os.path.join(tracker_dir, f) != PAUSED_SESSIONS_FILE # noqa
] # noqa
def get_open_sessions():
open_sessions = []
for session_file in list_sessions():
session = TrackingSession(session_file=session_file)
if not os.path.isfile(session.path):
continue
if not session.is_open():
continue
open_sessions.append(session)
return open_sessions
def get_session_file_path(name, pid):
return "{}/{}-{}.json".format(tracker_dir, pid, name)
def get_session_unique_id(name, pid):
<|code_end|>
, determine the next line of code. You have imports:
import os
import json
import shutil
import time
from uuid import uuid1, uuid5
from kano.utils.hardware import get_cpu_id
from kano.utils.file_operations import read_file_contents, chown_path
from kano.logging import logger
from kano_profile.tracker.tracker_token import TOKEN
from kano_profile.paths import tracker_dir, tracker_events_file, \
PAUSED_SESSIONS_FILE
from kano_profile.tracker.tracking_session import TrackingSession
from kano_profile.tracker.tracking_utils import open_locked, get_utc_offset
and context (class names, function names, or code) available:
# Path: kano_profile/tracker/tracker_token.py
# TOKEN = load_token()
#
# Path: kano_profile/paths.py
# TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids')
# PAUSED_SESSIONS_FILE = os.path.join(kanoprofile_dir, '.paused_sessions')
#
# Path: kano_profile/tracker/tracking_session.py
# class TrackingSession(object):
# SESSION_FILE_RE = re.compile(r'^(\d+)-(.*).json$')
#
# def __init__(self, session_file=None, name=None, pid=None):
# if session_file:
# self._file = os.path.basename(session_file)
# self._pid, self._name = self.parse_session_file(self.file)
# elif name and pid:
# self._name = name
# self._pid = int(pid)
# self._file = self.parse_name_and_pid(self.name, self.pid)
#
# else:
# raise TypeError(
# 'TrackingSession requires a file or a name/pid combination'
# )
#
# def parse_session_file(self, session_file):
# matches = TrackingSession.SESSION_FILE_RE.findall(session_file)
#
# if not matches:
# return None, None
#
# match_data = matches[0]
#
# pid = int(match_data[0])
# name = match_data[1]
#
# return pid, name
#
# def parse_name_and_pid(self, name, pid):
# return "{}-{}.json".format(pid, name)
#
# def __repr__(self):
# return 'Tracking Session [Name: {name}, PID: {pid}]: {is_open}'.format(
# name=self.name,
# pid=self.pid,
# is_open='OPEN' if self.is_open() else 'CLOSED'
# )
#
# def __str__(self):
# return self.__repr__()
#
# def __eq__(self, other):
# return self.file == other.file
#
# @property
# def file(self):
# return self._file
#
# @property
# def path(self):
# return os.path.join(tracker_dir, self.file)
#
# @property
# def name(self):
# return self._name.encode('utf-8')
#
# @property
# def pid(self):
# return self._pid or 0
#
# def is_open(self):
# return is_pid_running(self.pid)
#
# def open(self, mode):
# try:
# session_f = open_locked(self.path, mode)
# except IOError as exc:
# logger.error(
# 'Error opening the tracking session file "{f}": {err}'
# .format(f=self.path, err=exc)
# )
# else:
# yield session_f
#
# def dumps(self):
# return json.dumps({
# 'name': self.name,
# 'pid': self.pid
# })
#
# @staticmethod
# def loads(session):
# session_data = json.loads(session.rstrip().lstrip())
# return TrackingSession(
# name=session_data.get('name'),
# pid=session_data.get('pid')
# )
#
# Path: kano_profile/tracker/tracking_utils.py
# class open_locked(file):
# """ A version of open with an exclusive lock to be used within
# controlled execution statements.
# """
# def __init__(self, *args, **kwargs):
# super(open_locked, self).__init__(*args, **kwargs)
# fcntl.flock(self, fcntl.LOCK_EX)
#
# def get_utc_offset():
# """ Returns the local UTC offset in seconds.
#
# :returns: UTC offsed in secconds.
# :rtype: int
# """
#
# is_dst = time.daylight and time.localtime().tm_isdst > 0
# return -int(time.altzone if is_dst else time.timezone)
. Output only the next line. | data = {} |
Using the snippet: <|code_start|> try:
paused_sessions_f = open_locked(PAUSED_SESSIONS_FILE, 'a')
except IOError as err:
logger.error(
'Error while opening the paused sessions file: {}'.format(err)
)
else:
paused_sessions_f.write(
'{}\n'.format(session.dumps())
)
return session.path
data = {
'pid': pid,
'name': name,
'started': int(time.time()),
'elapsed': 0,
'app_session_id': str(uuid5(uuid1(), name + str(pid))),
'finished': False,
'token-system': TOKEN
}
path = get_session_file_path(data['name'], data['pid'])
try:
f = open_locked(path, 'w')
except IOError as e:
logger.error("Error opening tracker session file {}".format(e))
else:
<|code_end|>
, determine the next line of code. You have imports:
import os
import json
import shutil
import time
from uuid import uuid1, uuid5
from kano.utils.hardware import get_cpu_id
from kano.utils.file_operations import read_file_contents, chown_path
from kano.logging import logger
from kano_profile.tracker.tracker_token import TOKEN
from kano_profile.paths import tracker_dir, tracker_events_file, \
PAUSED_SESSIONS_FILE
from kano_profile.tracker.tracking_session import TrackingSession
from kano_profile.tracker.tracking_utils import open_locked, get_utc_offset
and context (class names, function names, or code) available:
# Path: kano_profile/tracker/tracker_token.py
# TOKEN = load_token()
#
# Path: kano_profile/paths.py
# TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids')
# PAUSED_SESSIONS_FILE = os.path.join(kanoprofile_dir, '.paused_sessions')
#
# Path: kano_profile/tracker/tracking_session.py
# class TrackingSession(object):
# SESSION_FILE_RE = re.compile(r'^(\d+)-(.*).json$')
#
# def __init__(self, session_file=None, name=None, pid=None):
# if session_file:
# self._file = os.path.basename(session_file)
# self._pid, self._name = self.parse_session_file(self.file)
# elif name and pid:
# self._name = name
# self._pid = int(pid)
# self._file = self.parse_name_and_pid(self.name, self.pid)
#
# else:
# raise TypeError(
# 'TrackingSession requires a file or a name/pid combination'
# )
#
# def parse_session_file(self, session_file):
# matches = TrackingSession.SESSION_FILE_RE.findall(session_file)
#
# if not matches:
# return None, None
#
# match_data = matches[0]
#
# pid = int(match_data[0])
# name = match_data[1]
#
# return pid, name
#
# def parse_name_and_pid(self, name, pid):
# return "{}-{}.json".format(pid, name)
#
# def __repr__(self):
# return 'Tracking Session [Name: {name}, PID: {pid}]: {is_open}'.format(
# name=self.name,
# pid=self.pid,
# is_open='OPEN' if self.is_open() else 'CLOSED'
# )
#
# def __str__(self):
# return self.__repr__()
#
# def __eq__(self, other):
# return self.file == other.file
#
# @property
# def file(self):
# return self._file
#
# @property
# def path(self):
# return os.path.join(tracker_dir, self.file)
#
# @property
# def name(self):
# return self._name.encode('utf-8')
#
# @property
# def pid(self):
# return self._pid or 0
#
# def is_open(self):
# return is_pid_running(self.pid)
#
# def open(self, mode):
# try:
# session_f = open_locked(self.path, mode)
# except IOError as exc:
# logger.error(
# 'Error opening the tracking session file "{f}": {err}'
# .format(f=self.path, err=exc)
# )
# else:
# yield session_f
#
# def dumps(self):
# return json.dumps({
# 'name': self.name,
# 'pid': self.pid
# })
#
# @staticmethod
# def loads(session):
# session_data = json.loads(session.rstrip().lstrip())
# return TrackingSession(
# name=session_data.get('name'),
# pid=session_data.get('pid')
# )
#
# Path: kano_profile/tracker/tracking_utils.py
# class open_locked(file):
# """ A version of open with an exclusive lock to be used within
# controlled execution statements.
# """
# def __init__(self, *args, **kwargs):
# super(open_locked, self).__init__(*args, **kwargs)
# fcntl.flock(self, fcntl.LOCK_EX)
#
# def get_utc_offset():
# """ Returns the local UTC offset in seconds.
#
# :returns: UTC offsed in secconds.
# :rtype: int
# """
#
# is_dst = time.daylight and time.localtime().tm_isdst > 0
# return -int(time.altzone if is_dst else time.timezone)
. Output only the next line. | with f: |
Next line prediction: <|code_start|> app_data_dir = os.path.join(get_app_dir(app_name), data_str)
return app_data_dir
def get_app_state_file(app_name):
app_state_str = 'state.json'
app_state_file = os.path.join(get_app_dir(app_name), app_state_str)
return app_state_file
def load_app_state(app_name):
app_state_file = get_app_state_file(app_name)
app_state = read_json(app_state_file)
if not app_state:
app_state = dict()
return app_state
def load_app_state_encode(app_name):
try:
data = load_app_state(app_name)
if data:
encoded_data = json.dumps(data)
return encoded_data
except Exception as e:
logger.error("Could not encode and load app state:\n{}".format(e))
def load_app_state_variable(app_name, variable):
<|code_end|>
. Use current file imports:
(import json
import os
from kano.utils import read_json, write_json, get_date_now, ensure_dir, \
chown_path, run_print_output_error, run_bg, run_cmd
from kano.logging import logger
from kano_profile.paths import apps_dir, xp_file, kanoprofile_dir, \
app_profiles_file
from kano.utils.misc import is_installed
from kano.utils.shell import run_cmd)
and context including class names, function names, or small code snippets from other files:
# Path: kano_profile/paths.py
# TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids')
# PAUSED_SESSIONS_FILE = os.path.join(kanoprofile_dir, '.paused_sessions')
. Output only the next line. | data = load_app_state(app_name) |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# apps.py
#
# Copyright (C) 2014, 2015, 2017 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
#
def get_app_dir(app_name):
app_dir = os.path.join(apps_dir, app_name)
return app_dir
def get_app_data_dir(app_name):
data_str = 'data'
app_data_dir = os.path.join(get_app_dir(app_name), data_str)
return app_data_dir
def get_app_state_file(app_name):
app_state_str = 'state.json'
app_state_file = os.path.join(get_app_dir(app_name), app_state_str)
<|code_end|>
, generate the next line using the imports in this file:
import json
import os
from kano.utils import read_json, write_json, get_date_now, ensure_dir, \
chown_path, run_print_output_error, run_bg, run_cmd
from kano.logging import logger
from kano_profile.paths import apps_dir, xp_file, kanoprofile_dir, \
app_profiles_file
from kano.utils.misc import is_installed
from kano.utils.shell import run_cmd
and context (functions, classes, or occasionally code) from other files:
# Path: kano_profile/paths.py
# TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids')
# PAUSED_SESSIONS_FILE = os.path.join(kanoprofile_dir, '.paused_sessions')
. Output only the next line. | return app_state_file |
Next line prediction: <|code_start|>
def get_app_data_dir(app_name):
data_str = 'data'
app_data_dir = os.path.join(get_app_dir(app_name), data_str)
return app_data_dir
def get_app_state_file(app_name):
app_state_str = 'state.json'
app_state_file = os.path.join(get_app_dir(app_name), app_state_str)
return app_state_file
def load_app_state(app_name):
app_state_file = get_app_state_file(app_name)
app_state = read_json(app_state_file)
if not app_state:
app_state = dict()
return app_state
def load_app_state_encode(app_name):
try:
data = load_app_state(app_name)
if data:
encoded_data = json.dumps(data)
return encoded_data
except Exception as e:
<|code_end|>
. Use current file imports:
(import json
import os
from kano.utils import read_json, write_json, get_date_now, ensure_dir, \
chown_path, run_print_output_error, run_bg, run_cmd
from kano.logging import logger
from kano_profile.paths import apps_dir, xp_file, kanoprofile_dir, \
app_profiles_file
from kano.utils.misc import is_installed
from kano.utils.shell import run_cmd)
and context including class names, function names, or small code snippets from other files:
# Path: kano_profile/paths.py
# TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids')
# PAUSED_SESSIONS_FILE = os.path.join(kanoprofile_dir, '.paused_sessions')
. Output only the next line. | logger.error("Could not encode and load app state:\n{}".format(e)) |
Based on the snippet: <|code_start|>
def load_app_state(app_name):
app_state_file = get_app_state_file(app_name)
app_state = read_json(app_state_file)
if not app_state:
app_state = dict()
return app_state
def load_app_state_encode(app_name):
try:
data = load_app_state(app_name)
if data:
encoded_data = json.dumps(data)
return encoded_data
except Exception as e:
logger.error("Could not encode and load app state:\n{}".format(e))
def load_app_state_variable(app_name, variable):
data = load_app_state(app_name)
if variable in data:
return data[variable]
def load_app_state_variable_encode(app_name, variable):
try:
data = load_app_state_variable(app_name, variable)
if data:
<|code_end|>
, predict the immediate next line with the help of imports:
import json
import os
from kano.utils import read_json, write_json, get_date_now, ensure_dir, \
chown_path, run_print_output_error, run_bg, run_cmd
from kano.logging import logger
from kano_profile.paths import apps_dir, xp_file, kanoprofile_dir, \
app_profiles_file
from kano.utils.misc import is_installed
from kano.utils.shell import run_cmd
and context (classes, functions, sometimes code) from other files:
# Path: kano_profile/paths.py
# TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids')
# PAUSED_SESSIONS_FILE = os.path.join(kanoprofile_dir, '.paused_sessions')
. Output only the next line. | encoded_data = json.dumps(data) |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
__author__ = 'anewbigging'
fake = Factory.create()
def typeof_rave_data(value):
"""Function to duck-type values, not relying on standard Python functions because, for example,
a string of '1' should be typed as an integer and not as a string or float
since we're trying to replace like with like when scrambling."""
# Test if value is a date
for format in ['%d %b %Y', '%b %Y', '%Y', '%d %m %Y', '%m %Y', '%d/%b/%Y', '%b/%Y', '%d/%m/%Y', '%m/%Y']:
<|code_end|>
. Write the next line using the current file imports:
import datetime
import hashlib
from lxml import etree
from faker import Factory
from rwslib.extras.rwscmd.odmutils import E_ODM, A_ODM
and context from other files:
# Path: rwslib/extras/rwscmd/odmutils.py
# class E_ODM(Enum):
# """
# Defines ODM Elements
# """
# CLINICAL_DATA = odm('ClinicalData')
# SUBJECT_DATA = odm('SubjectData')
# STUDY_EVENT_DATA = odm('StudyEventData')
# FORM_DATA = odm('FormData')
# ITEM_GROUP_DATA = odm('ItemGroupData')
# ITEM_DATA = odm('ItemData')
# METADATA_VERSION = odm('MetaDataVersion')
#
# USER_REF = odm('UserRef')
# SOURCE_ID = odm('SourceID')
# DATE_TIME_STAMP_ = odm('DateTimeStamp')
# REASON_FOR_CHANGE = odm('ReasonForChange')
# LOCATION_REF = odm('LocationRef')
# QUERY = mdsol('Query')
# PROTOCOL_DEVIATION = mdsol('ProtocolDeviation')
# REVIEW = mdsol('Review')
# COMMENT = mdsol('Comment')
# SIGNATURE = odm('Signature')
# SIGNATURE_REF = odm('SignatureRef')
# SOURCEID = odm('SourceID')
#
# ITEM_DEF = odm('ItemDef')
# RANGE_CHECK = odm('RangeCheck')
# CODELIST_REF = odm('CodeListRef')
# CODELIST = odm('CodeList')
# CODELIST_ITEM = odm('CodeListItem')
# ENUMERATED_ITEM = odm('EnumeratedItem')
#
# class A_ODM(Enum):
# """
# Defines ODM Attributes
# """
# AUDIT_SUBCATEGORY_NAME = mdsol('AuditSubCategoryName')
# METADATA_VERSION_OID = 'MetaDataVersionOID'
# STUDY_OID = 'StudyOID'
# TRANSACTION_TYPE = 'TransactionType'
# SUBJECT_NAME = mdsol('SubjectName')
# SUBJECT_KEY = 'SubjectKey'
# USER_OID = 'UserOID'
# LOCATION_OID = 'LocationOID'
# ITEM_OID = 'ItemOID'
# VALUE = 'Value'
# STUDYEVENT_OID = 'StudyEventOID'
# STUDYEVENT_REPEAT_KEY = 'StudyEventRepeatKey'
# FORM_OID = 'FormOID'
# FORM_REPEAT_KEY = 'FormRepeatKey'
# ITEMGROUP_OID = 'ItemGroupOID'
# ITEMGROUP_REPEAT_KEY = 'ItemGroupRepeatKey'
# QUERY_REPEAT_KEY = 'QueryRepeatKey'
# STATUS = 'Status'
# RECIPIENT = 'Recipient'
# RESPONSE = 'Response'
# FREEZE = mdsol('Freeze')
# VERIFY = mdsol('Verify')
# LOCK = mdsol('Lock')
# SUBJECT_STATUS = mdsol('Status')
# PROTCOL_DEVIATION_REPEAT_KEY = 'ProtocolDeviationRepeatKey'
# CLASS = 'Class' # PV
# CODE = 'Code' # PV
# REVIEWED = 'Reviewed' #Reviews
# GROUP_NAME = 'GroupName'
# COMMENT_REPEAT_KEY = 'CommentRepeatKey'
# INSTANCE_NAME = mdsol('InstanceName')
# INSTANCE_OVERDUE = mdsol('InstanceOverdue')
# DATAPAGE_NAME = mdsol('DataPageName')
# SIGNATURE_OID = 'SignatureOID'
#
# OID = 'OID'
# DATATYPE = 'DataType'
# LENGTH = 'Length'
# SIGNIFICANT_DIGITS = 'SignficantDigits'
# CODELIST_OID = 'CodeListOID'
# CODED_VALUE = 'CodedValue'
# DATETIME_FORMAT = mdsol('DateTimeFormat')
, which may include functions, classes, or code. Output only the next line. | try: |
Predict the next line for this snippet: <|code_start|>class TestRWSStudies(unittest.TestCase):
def test_parse(self):
text = u"""<ODM FileType="Snapshot" FileOID="767a1f8b-7b72-4d12-adbe-37d4d62ba75e"
CreationDateTime="2013-04-08T10:02:17.781-00:00"
ODMVersion="1.3"
xmlns:mdsol="http://www.mdsol.com/ns/odm/metadata"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns="http://www.cdisc.org/ns/odm/v1.3">
<Study OID="Fixitol(Dev)">
<GlobalVariables>
<StudyName>Fixitol (Dev)</StudyName>
<StudyDescription/>
<ProtocolName>Fixitol</ProtocolName>
</GlobalVariables>
</Study>
<Study OID="IANTEST(Prod)">
<GlobalVariables>
<StudyName>IANTEST</StudyName>
<StudyDescription/>
<ProtocolName>IANTEST</ProtocolName>
</GlobalVariables>
</Study>
</ODM>"""
parsed = rwsobjects.RWSStudies(text)
self.assertEqual("1.3", parsed.ODMVersion)
self.assertEqual(2, len(parsed))
self.assertEqual(False, parsed[0].isProd())
self.assertEqual(True, parsed[1].isProd())
<|code_end|>
with the help of current file imports:
import unittest
from rwslib import rwsobjects
and context from other files:
# Path: rwslib/rwsobjects.py
# MEDI_NS = "{http://www.mdsol.com/ns/odm/metadata}"
# ODM_NS = "{http://www.cdisc.org/ns/odm/v1.3}"
# XLINK_NS = "{http://www.w3.org/1999/xlink}"
# STATUS_PROPERTIES = [
# "Overdue",
# "Touched",
# "Empty",
# "Incomplete",
# "NonConformant",
# "RequiresSecondPass",
# "RequiresReconciliation",
# "RequiresVerification",
# "Verified",
# "Frozen",
# "Locked",
# "RequiresReview",
# "PendingReview",
# "Reviewed",
# "RequiresAnswerQuery",
# "RequiresPendingCloseQuery",
# "RequiresCloseQuery",
# "StickyPlaced",
# "Signed",
# "SignatureCurrent",
# "RequiresTranslation",
# "RequiresCoding",
# "RequiresPendingAnswerQuery",
# "RequiresSignature",
# "ReadyForFreeze",
# "ReadyForLock",
# "SubjectKeyType",
# "SubjectName",
# ]
# def getEnvironmentFromNameAndProtocol(studyname, protocolname):
# def parseXMLString(xml):
# def __init__(self, msg, rws_error):
# def __init__(self, xml):
# def __unicode__(self):
# def __str__(self):
# def __init__(self, xml):
# def __init__(self, xml):
# def __init__(self, xml):
# def __init__(self, xml):
# def __init__(self, xml):
# def __init__(self, xml):
# def __init__(
# self,
# oid=None,
# studyname=None,
# protocolname=None,
# environment=None,
# projecttype=None,
# ):
# def isProd(self):
# def fromElement(cls, elem):
# def __init__(self, xml):
# def __init__(self):
# def fromElement(cls, elem):
# def __init__(self, xml):
# def __init__(self):
# def subject_name(self):
# def fromElement(cls, elem):
# def __init__(self, xml):
# class RWSException(Exception):
# class XMLRepr(object):
# class ODMDoc(XMLRepr):
# class RWSError(ODMDoc):
# class RWSErrorResponse(XMLRepr):
# class RWSResponse(XMLRepr):
# class RWSPostResponse(RWSResponse):
# class RWSPostErrorResponse(RWSErrorResponse):
# class RWSStudyListItem(object):
# class RWSStudies(list, ODMDoc):
# class MetaDataVersion(object):
# class RWSStudyMetadataVersions(list, ODMDoc, RWSStudyListItem):
# class RWSSubjectListItem(object):
# class RWSSubjects(list, ODMDoc):
, which may contain function names, class names, or code. Output only the next line. | class TestUtils(unittest.TestCase): |
Using the snippet: <|code_start|> self.assertNotEqual(s, i)
s = 'This is a large string to test scrambling of large strings'
i = self.scr.scramble_value(s)
self.assertNotEqual(s, i)
def test_scramble_date(self):
"""Test scrambling dates"""
dt = self.scr.scramble_value('10 MAR 2016')
self.assertTrue(datetime.datetime.strptime(dt, '%d %b %Y'))
dt = self.scr.scramble_value('MAR 2016')
self.assertTrue(datetime.datetime.strptime(dt, '%b %Y'))
def test_scramble_time(self):
"""Test scrambling times"""
dt = self.scr.scramble_value('18:12:14')
self.assertTrue(datetime.datetime.strptime(dt, '%H:%M:%S'))
dt = self.scr.scramble_value('18:12')
self.assertTrue(datetime.datetime.strptime(dt, '%H:%M'))
class TestScramblingWithMetadata(unittest.TestCase):
def setUp(self):
metadata = """
<ODM FileType="Snapshot" Granularity="Metadata" CreationDateTime="2016-02-29T13:47:23.654-00:00" FileOID="d460fc96-4f08-445f-89b1-0182e8e810c1" ODMVersion="1.3" xmlns:mdsol="http://www.mdsol.com/ns/odm/metadata" xmlns="http://www.cdisc.org/ns/odm/v1.3">
<Study OID="Test">
<GlobalVariables>
<StudyName>Test</StudyName>
<StudyDescription></StudyDescription>
<ProtocolName>Test</ProtocolName>
</GlobalVariables>
<BasicDefinitions/>
<|code_end|>
, determine the next line of code. You have imports:
from rwslib.extras.rwscmd import data_scrambler
from rwslib.extras.rwscmd.odmutils import E_ODM, A_ODM
from lxml import etree
from six import string_types
import unittest
import datetime
and context (class names, function names, or code) available:
# Path: rwslib/extras/rwscmd/data_scrambler.py
# def typeof_rave_data(value):
# def __init__(self, metadata=None):
# def scramble_int(self, length):
# def scramble_float(self, length, sd=0):
# def scramble_date(self, value, format='%d %b %Y'):
# def scramble_time(self, format='%H:%M:%S'):
# def scramble_string(self, length):
# def scramble_value(self, value):
# def scramble_subjectname(self, value):
# def scramble_codelist(self, codelist):
# def scramble_itemdata(self, oid, value):
# def scramble_query_value(self, value):
# def fill_empty(self, fixed_values, input):
# class Scramble():
#
# Path: rwslib/extras/rwscmd/odmutils.py
# class E_ODM(Enum):
# """
# Defines ODM Elements
# """
# CLINICAL_DATA = odm('ClinicalData')
# SUBJECT_DATA = odm('SubjectData')
# STUDY_EVENT_DATA = odm('StudyEventData')
# FORM_DATA = odm('FormData')
# ITEM_GROUP_DATA = odm('ItemGroupData')
# ITEM_DATA = odm('ItemData')
# METADATA_VERSION = odm('MetaDataVersion')
#
# USER_REF = odm('UserRef')
# SOURCE_ID = odm('SourceID')
# DATE_TIME_STAMP_ = odm('DateTimeStamp')
# REASON_FOR_CHANGE = odm('ReasonForChange')
# LOCATION_REF = odm('LocationRef')
# QUERY = mdsol('Query')
# PROTOCOL_DEVIATION = mdsol('ProtocolDeviation')
# REVIEW = mdsol('Review')
# COMMENT = mdsol('Comment')
# SIGNATURE = odm('Signature')
# SIGNATURE_REF = odm('SignatureRef')
# SOURCEID = odm('SourceID')
#
# ITEM_DEF = odm('ItemDef')
# RANGE_CHECK = odm('RangeCheck')
# CODELIST_REF = odm('CodeListRef')
# CODELIST = odm('CodeList')
# CODELIST_ITEM = odm('CodeListItem')
# ENUMERATED_ITEM = odm('EnumeratedItem')
#
# class A_ODM(Enum):
# """
# Defines ODM Attributes
# """
# AUDIT_SUBCATEGORY_NAME = mdsol('AuditSubCategoryName')
# METADATA_VERSION_OID = 'MetaDataVersionOID'
# STUDY_OID = 'StudyOID'
# TRANSACTION_TYPE = 'TransactionType'
# SUBJECT_NAME = mdsol('SubjectName')
# SUBJECT_KEY = 'SubjectKey'
# USER_OID = 'UserOID'
# LOCATION_OID = 'LocationOID'
# ITEM_OID = 'ItemOID'
# VALUE = 'Value'
# STUDYEVENT_OID = 'StudyEventOID'
# STUDYEVENT_REPEAT_KEY = 'StudyEventRepeatKey'
# FORM_OID = 'FormOID'
# FORM_REPEAT_KEY = 'FormRepeatKey'
# ITEMGROUP_OID = 'ItemGroupOID'
# ITEMGROUP_REPEAT_KEY = 'ItemGroupRepeatKey'
# QUERY_REPEAT_KEY = 'QueryRepeatKey'
# STATUS = 'Status'
# RECIPIENT = 'Recipient'
# RESPONSE = 'Response'
# FREEZE = mdsol('Freeze')
# VERIFY = mdsol('Verify')
# LOCK = mdsol('Lock')
# SUBJECT_STATUS = mdsol('Status')
# PROTCOL_DEVIATION_REPEAT_KEY = 'ProtocolDeviationRepeatKey'
# CLASS = 'Class' # PV
# CODE = 'Code' # PV
# REVIEWED = 'Reviewed' #Reviews
# GROUP_NAME = 'GroupName'
# COMMENT_REPEAT_KEY = 'CommentRepeatKey'
# INSTANCE_NAME = mdsol('InstanceName')
# INSTANCE_OVERDUE = mdsol('InstanceOverdue')
# DATAPAGE_NAME = mdsol('DataPageName')
# SIGNATURE_OID = 'SignatureOID'
#
# OID = 'OID'
# DATATYPE = 'DataType'
# LENGTH = 'Length'
# SIGNIFICANT_DIGITS = 'SignficantDigits'
# CODELIST_OID = 'CodeListOID'
# CODED_VALUE = 'CodedValue'
# DATETIME_FORMAT = mdsol('DateTimeFormat')
. Output only the next line. | <MetaDataVersion OID="1" Name="Metadata version 1"> |
Continue the code snippet: <|code_start|> """Test scrambling strings"""
s = 'asdf'
i = self.scr.scramble_value(s)
self.assertEqual(len(s), len(i))
self.assertNotEqual(s, i)
s = 'This is a large string to test scrambling of large strings'
i = self.scr.scramble_value(s)
self.assertNotEqual(s, i)
def test_scramble_date(self):
"""Test scrambling dates"""
dt = self.scr.scramble_value('10 MAR 2016')
self.assertTrue(datetime.datetime.strptime(dt, '%d %b %Y'))
dt = self.scr.scramble_value('MAR 2016')
self.assertTrue(datetime.datetime.strptime(dt, '%b %Y'))
def test_scramble_time(self):
"""Test scrambling times"""
dt = self.scr.scramble_value('18:12:14')
self.assertTrue(datetime.datetime.strptime(dt, '%H:%M:%S'))
dt = self.scr.scramble_value('18:12')
self.assertTrue(datetime.datetime.strptime(dt, '%H:%M'))
class TestScramblingWithMetadata(unittest.TestCase):
def setUp(self):
metadata = """
<ODM FileType="Snapshot" Granularity="Metadata" CreationDateTime="2016-02-29T13:47:23.654-00:00" FileOID="d460fc96-4f08-445f-89b1-0182e8e810c1" ODMVersion="1.3" xmlns:mdsol="http://www.mdsol.com/ns/odm/metadata" xmlns="http://www.cdisc.org/ns/odm/v1.3">
<Study OID="Test">
<GlobalVariables>
<StudyName>Test</StudyName>
<|code_end|>
. Use current file imports:
from rwslib.extras.rwscmd import data_scrambler
from rwslib.extras.rwscmd.odmutils import E_ODM, A_ODM
from lxml import etree
from six import string_types
import unittest
import datetime
and context (classes, functions, or code) from other files:
# Path: rwslib/extras/rwscmd/data_scrambler.py
# def typeof_rave_data(value):
# def __init__(self, metadata=None):
# def scramble_int(self, length):
# def scramble_float(self, length, sd=0):
# def scramble_date(self, value, format='%d %b %Y'):
# def scramble_time(self, format='%H:%M:%S'):
# def scramble_string(self, length):
# def scramble_value(self, value):
# def scramble_subjectname(self, value):
# def scramble_codelist(self, codelist):
# def scramble_itemdata(self, oid, value):
# def scramble_query_value(self, value):
# def fill_empty(self, fixed_values, input):
# class Scramble():
#
# Path: rwslib/extras/rwscmd/odmutils.py
# class E_ODM(Enum):
# """
# Defines ODM Elements
# """
# CLINICAL_DATA = odm('ClinicalData')
# SUBJECT_DATA = odm('SubjectData')
# STUDY_EVENT_DATA = odm('StudyEventData')
# FORM_DATA = odm('FormData')
# ITEM_GROUP_DATA = odm('ItemGroupData')
# ITEM_DATA = odm('ItemData')
# METADATA_VERSION = odm('MetaDataVersion')
#
# USER_REF = odm('UserRef')
# SOURCE_ID = odm('SourceID')
# DATE_TIME_STAMP_ = odm('DateTimeStamp')
# REASON_FOR_CHANGE = odm('ReasonForChange')
# LOCATION_REF = odm('LocationRef')
# QUERY = mdsol('Query')
# PROTOCOL_DEVIATION = mdsol('ProtocolDeviation')
# REVIEW = mdsol('Review')
# COMMENT = mdsol('Comment')
# SIGNATURE = odm('Signature')
# SIGNATURE_REF = odm('SignatureRef')
# SOURCEID = odm('SourceID')
#
# ITEM_DEF = odm('ItemDef')
# RANGE_CHECK = odm('RangeCheck')
# CODELIST_REF = odm('CodeListRef')
# CODELIST = odm('CodeList')
# CODELIST_ITEM = odm('CodeListItem')
# ENUMERATED_ITEM = odm('EnumeratedItem')
#
# class A_ODM(Enum):
# """
# Defines ODM Attributes
# """
# AUDIT_SUBCATEGORY_NAME = mdsol('AuditSubCategoryName')
# METADATA_VERSION_OID = 'MetaDataVersionOID'
# STUDY_OID = 'StudyOID'
# TRANSACTION_TYPE = 'TransactionType'
# SUBJECT_NAME = mdsol('SubjectName')
# SUBJECT_KEY = 'SubjectKey'
# USER_OID = 'UserOID'
# LOCATION_OID = 'LocationOID'
# ITEM_OID = 'ItemOID'
# VALUE = 'Value'
# STUDYEVENT_OID = 'StudyEventOID'
# STUDYEVENT_REPEAT_KEY = 'StudyEventRepeatKey'
# FORM_OID = 'FormOID'
# FORM_REPEAT_KEY = 'FormRepeatKey'
# ITEMGROUP_OID = 'ItemGroupOID'
# ITEMGROUP_REPEAT_KEY = 'ItemGroupRepeatKey'
# QUERY_REPEAT_KEY = 'QueryRepeatKey'
# STATUS = 'Status'
# RECIPIENT = 'Recipient'
# RESPONSE = 'Response'
# FREEZE = mdsol('Freeze')
# VERIFY = mdsol('Verify')
# LOCK = mdsol('Lock')
# SUBJECT_STATUS = mdsol('Status')
# PROTCOL_DEVIATION_REPEAT_KEY = 'ProtocolDeviationRepeatKey'
# CLASS = 'Class' # PV
# CODE = 'Code' # PV
# REVIEWED = 'Reviewed' #Reviews
# GROUP_NAME = 'GroupName'
# COMMENT_REPEAT_KEY = 'CommentRepeatKey'
# INSTANCE_NAME = mdsol('InstanceName')
# INSTANCE_OVERDUE = mdsol('InstanceOverdue')
# DATAPAGE_NAME = mdsol('DataPageName')
# SIGNATURE_OID = 'SignatureOID'
#
# OID = 'OID'
# DATATYPE = 'DataType'
# LENGTH = 'Length'
# SIGNIFICANT_DIGITS = 'SignficantDigits'
# CODELIST_OID = 'CodeListOID'
# CODED_VALUE = 'CodedValue'
# DATETIME_FORMAT = mdsol('DateTimeFormat')
. Output only the next line. | <StudyDescription></StudyDescription> |
Given the following code snippet before the placeholder: <|code_start|> result = self.runner.invoke(rwscmd.rws,
['--verbose', 'https://innovate.mdsol.com', 'autofill', '--steps', '1',
'--fixed', 'fixed.txt', 'Test', 'Prod', '001'],
input=u"defuser\npassword\n", catch_exceptions=False)
self.assertFalse(result.exception)
self.assertIn("Step 1\nGetting data list", result.output)
self.assertIn("Getting metadata version 1", result.output)
self.assertIn("Generating data", result.output)
self.assertIn('Fixing YN to value: 99', result.output)
self.assertNotIn("Step 2", result.output)
self.assertEqual(result.exit_code, 0)
def test_autofill_metadata(self):
with self.runner.isolated_filesystem():
with open('odm.xml', 'w') as f:
f.write(self.odm_metadata)
result = self.runner.invoke(rwscmd.rws,
['--verbose', 'https://innovate.mdsol.com', 'autofill', '--steps', '1',
'--metadata', 'odm.xml', 'Test', 'Prod', '001'],
input=u"defuser\npassword\n", catch_exceptions=False)
self.assertFalse(result.exception)
self.assertIn("Step 1\nGetting data list", result.output)
self.assertIn("Generating data", result.output)
self.assertNotIn("Step 2", result.output)
self.assertEqual(result.exit_code, 0)
if __name__ == '__main__':
<|code_end|>
, predict the next line using imports from the current file:
import unittest
import httpretty
from click.testing import CliRunner
from rwslib.extras.rwscmd import rwscmd
and context including class names, function names, and sometimes code from other files:
# Path: rwslib/extras/rwscmd/rwscmd.py
# GET_DATA_DATASET = 'rwscmd_getdata.odm'
# VALID_DATASET_FORMATS = ("odm")
# class GetDataConfigurableDataset(ConfigurableDatasetRequest):
# def __init__(self, dataset, study, environment, subject, params=None):
# def rws(ctx, url, username, password, raw, verbose, output, virtual_dir):
# def get_data(ctx, study, environment, subject):
# def rws_call(ctx, method, default_attr=None):
# def version(ctx):
# def data(ctx, path):
# def post(ctx, odm):
# def metadata(ctx, drafts, path):
# def direct(ctx, path):
# def autofill(ctx, steps, metadata, fixed, study, environment, subject):
. Output only the next line. | unittest.main() |
Given snippet: <|code_start|>
class JumpToKeyword(sublime_plugin.TextCommand):
def run(self, edit):
open_tab = self.view.file_name()
db_dir = get_setting(SettingObject.table_dir)
index_db = get_setting(SettingObject.index_dir)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import re
import sublime_plugin
import sublime
from ..command_helper.get_keyword import GetKeyword
from ..command_helper.get_metadata import get_rf_table_separator
from ..command_helper.jump_to_file import JumpToFile
from ..command_helper.noralize_cell import ReturnKeywordAndObject
from ..command_helper.utils.get_text import get_line
from ..setting.setting import get_setting
from ..setting.setting import SettingObject
from .query_completions import get_index_file
and context:
# Path: commands/query_completions.py
# def get_index_file(open_tab):
# db_table = rf_table_name(normalise_path(open_tab))
# index_name = get_index_name(db_table)
# index_file = path.join(
# get_setting(SettingObject.index_dir),
# index_name
# )
# if not path.exists(index_file):
# index_file = None
# return index_file
which might include code, classes, or functions. Output only the next line. | rf_cell = get_rf_table_separator(self.view)
|
Continue the code snippet: <|code_start|>
class ShowKeywordDocumentation(sublime_plugin.TextCommand):
def run(self, edit):
w = sublime.active_window()
panel = w.create_output_panel('kw_documentation')
<|code_end|>
. Use current file imports:
import sublime_plugin
import sublime
from ..setting.setting import get_setting
from ..setting.setting import SettingObject
from .query_completions import get_index_file
from ..command_helper.utils.get_text import get_line
from ..command_helper.noralize_cell import ReturnKeywordAndObject
from ..command_helper.get_metadata import get_rf_table_separator
from ..command_helper.get_documentation import GetKeywordDocumentation
and context (classes, functions, or code) from other files:
# Path: commands/query_completions.py
# def get_index_file(open_tab):
# db_table = rf_table_name(normalise_path(open_tab))
# index_name = get_index_name(db_table)
# index_file = path.join(
# get_setting(SettingObject.index_dir),
# index_name
# )
# if not path.exists(index_file):
# index_file = None
# return index_file
. Output only the next line. | open_tab = self.view.file_name()
|
Predict the next line after this snippet: <|code_start|> local('mv src/modules/{0}-beautified.js src/modules/{0}.js'.format(name))
# fab unify:list_modules='ajax'
def unify(list_modules=None):
# list of all dependencies of own Tiramisu
list_dependency = []
# read tiramisu.json
f = open('tiramisu.json', 'r')
tiramisu_json = json.load(f)
f.close()
# list_modules contains modules chosen to create their own tiramisu
if list_modules:
# Unify only selected modules
print '\n####### Unifying custom Tiramisu #######'
modules_chosen = ''.join(list_modules)
check_dependency(list_dependency, list_modules)
list_dependency = map(lambda x: x.strip(), list_dependency)
list_modules = sorted(set(list_modules + ''.join(list_dependency)))
modules = ['src/modules/tiramisu.'+official_dictionary_names[int(x)]+'.js' for x in list_modules]
modules.sort() # sorts normally by alphabetical order
modules.sort(key=len) # sorts by length
# modules in tiramisu
name_custom = ''.join(list_modules)
# unify modules with cat command
<|code_end|>
using the current file's imports:
import os, re, fileinput, shutil, urllib2
import simplejson as json
from fabric.api import local
from utils.version import get_version
from itertools import combinations
and any relevant context from other files:
# Path: utils/version.py
# def get_version(d=False):
# with open("src/tiramisu.core.js", "r") as f:
# for line in f:
# version = re.search(r"this.version = '([0-9]\.[0-9](?:\.[0-9](?:-b[0-9]{1,2})?)?)';", line)
# if (version is not None):
#
# with open("VERSION", "w") as version_file:
# version_file.write("""{version}\n{date}""".format(version=version.group(1), date=current_date))
#
# with open("utils/docs-intro.md", "w") as intro:
# for line in markdown_intro.format(version=version.group(1)):
# intro.write(line)
#
# with open("utils/readme.js", "w") as intro:
# intro.write("/*")
# for line in markdown_intro.format(version=version.group(1)).split('\n'):
# line = " * "+line+'\n'
# intro.write(line)
# intro.write(" */")
#
# if d:
# return current_date
# else:
# return version.group(1)
. Output only the next line. | cat = "cat src/tiramisu.core.js {0} > src/custom/tiramisu-{1}.js".format(' '.join(modules), name_custom) |
Based on the snippet: <|code_start|>
class TestApp(WebAppTestBase):
def test_welcome(self):
resp = self.get('/')
self.assertEquals(resp.status_code, 200)
<|code_end|>
, predict the immediate next line with the help of imports:
from gap.utils.tests import WebAppTestBase
and context (classes, functions, sometimes code) from other files:
# Path: gap/utils/tests.py
# class WebAppTestBase(TestBase):
# # Allow to share the setUpClass method among all parallel test classes
# _multiprocess_shared_ = False
#
# # Allow concurrent run of fixtures
# _multiprocess_can_split_ = False
#
# @classmethod
# def getApp(cls):
# '''
# Returns list of routes or instance of a WSGIApplication.
# Override this class in your class to test a handler directly.
# '''
# from app import handler
# return handler
#
# @property
# def app(self):
# import webtest
# app = self.getApp()
# if isinstance(app, (list, tuple)):
# import webapp2
# testapp = webapp2.WSGIApplication(app)
# else:
# testapp = app
# app = webtest.TestApp(testapp)
# return app
#
# def _app_method(self, method, *args, **kwargs):
# return getattr(self.app, method)(*args, **kwargs)
#
# def __getattr__(self, name, default=DEFAULT):
# if name in ('get', 'post', 'put', 'delete', 'post_json', 'put_json'):
# return getattr(self.app, name)
# elif name in self.__dict__:
# return self.__dict__[name]
# elif default is not DEFAULT:
# return default
# else:
# raise AttributeError("%s.%s has no attribute %r." % (self.__module__, self.__class__.__name__, name))
. Output only the next line. | self.assertEquals(resp.content_type, 'text/html') |
Next line prediction: <|code_start|>
@as_view
def welcome_screen(request, response):
return get_template("homepage.html").render({
'project_name': 'Example project',
})
@as_view
def not_found(request, response, *args, **kwargs):
response.set_status(404)
text = 'The page you are requesting was not found on this server.'
if settings['DEBUG']:
buffer = StringIO()
dump_routes(buffer)
buffer.seek(0)
return text + '<br>The known rotes are...<br><pre>' + buffer.read() + '</pre>'
else:
return text
def dump_routes(response, routes=None, indent=''):
if routes is None:
<|code_end|>
. Use current file imports:
(from utils.decorators import as_view
from gap.template import get_template
from StringIO import StringIO
from gap.conf import settings
from routes import routes)
and context including class names, function names, or small code snippets from other files:
# Path: gap/template.py
# def get_template(template_path):
# return JINJA_ENVIRONMENT.get_template(template_path)
. Output only the next line. | for route in routes: |
Next line prediction: <|code_start|>#!/usr/bin/env python
app_path = join(realpath(dirname(dirname(__file__))), 'src')
fix_sys_path(app_path)
TESTBED = setup_testbed()
# preimport common google apis
<|code_end|>
. Use current file imports:
(import sys
import IPython
from os.path import dirname, realpath, join
from gap.utils.setup import fix_sys_path, setup_testbed, setup_stubs
from google.appengine.api.urlfetch import fetch
from google.appengine.ext import db, ndb
from google.appengine.api import memcache)
and context including class names, function names, or small code snippets from other files:
# Path: gap/utils/setup.py
# def fix_sys_path(app_src=None):
# global _PATH_FIXED
# if not _PATH_FIXED:
# gae_path = find_gae_runtime_path()
# sys.path.insert(0, gae_path)
# # sys.path.insert(0, join(gae_path, 'lib'))
# import dev_appserver
# dev_appserver.fix_sys_path()
# _PATH_FIXED = 1
#
# if app_src and _PATH_FIXED < 2:
# sys.path.insert(0, app_src)
# _PATH_FIXED = 2
#
# def setup_testbed(stubs=DEFAULT_TESTBEDS, env={}):
# from google.appengine.ext import testbed
# t = testbed.Testbed()
# if env:
# t.setup_env(**env)
# t.activate()
# for stub in stubs:
# if stub == 'datastore':
# stub = 'datastore_v3'
# getattr(t, 'init_%s_stub' % stub)()
# if stub == 'urlfetch':
# t.urlfetch_stub = t.get_stub('urlfetch')
# elif stub == 'mail':
# t.mail_stub = t.get_stub(testbed.MAIL_SERVICE_NAME)
# import app
# return t
#
# def setup_stubs(app_src):
#
# from google.appengine.api import apiproxy_stub_map
#
# apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
#
# from google.appengine.api import urlfetch_stub
# apiproxy_stub_map.apiproxy.RegisterStub(
# 'urlfetch',
# urlfetch_stub.URLFetchServiceStub()
# )
# from google.appengine.api.memcache import memcache_stub
# apiproxy_stub_map.apiproxy.RegisterStub(
# 'memcache',
# memcache_stub.MemcacheServiceStub(),
# )
# from google.appengine.api import datastore_file_stub
# apiproxy_stub_map.apiproxy.RegisterStub(
# 'datastore',
# datastore_file_stub.DatastoreFileStub(app_id=read_yaml(app_src)['application'], datastore_file=join(dirname(app_src), '.tmp', 'test1.db'))
# )
# import app
. Output only the next line. | IPython.embed() |
Using the snippet: <|code_start|>#
# part of gap project (https://github.com/czervenka/gap)
__author__ = 'Lukas Lukovsky'
DEFAULT = object()
class TestBase(TestCase):
testbed = None
_gae_stubs = setup.DEFAULT_TESTBEDS
# Allow to share the setUpClass method among all parallel test classes
_multiprocess_shared_ = True
# Allow concurrent run of fixtures
_multiprocess_can_split_ = True
@classmethod
def setUpClass(cls):
# Begin with testbed instance
cls.testbed = setup.setup_testbed(stubs=cls._gae_stubs)
@classmethod
def tearDownClass(cls):
cls.testbed.deactivate()
@staticmethod
def login(email, admin=False, user_id=None):
<|code_end|>
, determine the next line of code. You have imports:
import json
import app
import webtest
import webapp2
import random
import string
from unittest import TestCase
from gap.utils import setup
from os import environ as env
from os import environ as env
from app import handler
from datetime import date, datetime, timedelta
from pprint import pprint
from google.appengine.ext import ndb
and context (class names, function names, or code) available:
# Path: gap/utils/setup.py
# GAE_APP_ROOT = 'src'
# GAE_RUNTIME_ROOT = None
# _PATH_FIXED = 0
# _PATH_FIXED = 1
# _PATH_FIXED = 2
# DEFAULT_TESTBEDS = (
# 'datastore',
# 'app_identity',
# 'memcache',
# 'files',
# 'urlfetch',
# 'mail',
# 'search',
# )
# def find_gae_runtime_path():
# def fix_sys_path(app_src=None):
# def read_yaml(app_src):
# def setup_stubs(app_src):
# def setup_testbed(stubs=DEFAULT_TESTBEDS, env={}):
. Output only the next line. | env['USER_EMAIL'] = email |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# Copyright 2007 Robin Gottfried <google@kebet.cz>
#
# 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.
#
# @author Robin Gottfried <google@kebet.cz>
# part of gap project (https://github.com/czervenka/gap)
__author = 'google@kebet.cz'
def defer(callback, *args, **kwargs):
if '_queue_name' in kwargs:
queue_name = kwargs['_queue_name']
del kwargs['_queue_name']
else:
queue_name = 'utils-defer'
callback = "%s.%s" % (callback.__module__, callback.__name__)
<|code_end|>
, generate the next line using the imports in this file:
import json
import webapp2
from google.appengine.api import taskqueue
from gap.utils.imports import import_class
and context (functions, classes, or occasionally code) from other files:
# Path: gap/utils/imports.py
# def import_class(class_name):
# """
# imports and returns class by its path
#
# USAGE:
# myclass = import_class('StringIO.StringIO')
# # or
# from StringIO import StringIO
# myclass = import_class(StringIO)
# """
# if isinstance(class_name, StringTypes):
# from importlib import import_module
# module_name, class_name = class_name.rsplit('.', 1)
# module = import_module(module_name)
# return getattr(module, class_name)
# else:
# return class_name
. Output only the next line. | taskqueue.add( |
Given the code snippet: <|code_start|>
def include(prefix, routes):
if isinstance(routes, StringTypes):
routes = import_class('%s.routes' % routes)
elif hasattr(routes, 'routes'):
routes = routes.routes
routes = [ Router.route_class(*route) if isinstance(route, tuple) else route for route in routes ]
return PathPrefixRoute(prefix, routes)
class BaseRouter(webapp2.Router):
def _get_filters(self):
return [import_class(f) for f in getattr(config, 'REQUEST_FILTERS', [])] # copy
def _run_filters(self, direction, method, *args):
to_return = False
filters = self._get_filters()[::direction]
for filter_ in filters:
if hasattr(filter_, method):
if not getattr(filter_, method)(*args):
to_return = False
break
else:
to_return = True
return to_return
def _dispatch(self, request, response):
<|code_end|>
, generate the next line using the imports in this file:
from types import StringTypes
from webapp2_extras.routes import PathPrefixRoute
from webapp2 import Router
from gap.utils.imports import import_class
import webapp2
import config
and context (functions, classes, or occasionally code) from other files:
# Path: gap/utils/imports.py
# def import_class(class_name):
# """
# imports and returns class by its path
#
# USAGE:
# myclass = import_class('StringIO.StringIO')
# # or
# from StringIO import StringIO
# myclass = import_class(StringIO)
# """
# if isinstance(class_name, StringTypes):
# from importlib import import_module
# module_name, class_name = class_name.rsplit('.', 1)
# module = import_module(module_name)
# return getattr(module, class_name)
# else:
# return class_name
. Output only the next line. | self._run_filters(1, 'process_request', request, response) |
Using the snippet: <|code_start|>
class JsonException(Exception):
def __init__(self, code, message=None, exception=None):
self.code = int(code)
if message is None:
message = self.get_status_message(code)
self.message = message
self.exception = exception
def get_status_message(self, code):
return responses.get(self.code, 'Unknown status')
class MessageEncoder(json.JSONEncoder):
def default(self, o):
if hasattr(o, 'as_dict'):
return o.as_dict()
elif hasattr(o, 'to_dict'):
return o.to_dict()
elif isinstance(o, (date, datetime)):
<|code_end|>
, determine the next line of code. You have imports:
import logging
import json
import time
from gap.conf import settings
from datetime import datetime, date
from httplib import responses
from traceback import format_exc
and context (class names, function names, or code) available:
# Path: gap/conf.py
# DEFAULT_SETTINGS = {}
# KEY = 'app_settings'
# class AppSettings(ndb.Expando):
# class LazyAppSettings(object):
# class SettingsDict(object):
# def get_key(cls):
# def put(self, *args, **kwargs):
# def get_uuid(cls):
# def set_uuid(cls):
# def __get__(self, instance, owner=None):
# def _set_settings(self, dict_data):
# def __getitem__(self, key):
# def new_setter(obj, key, value):
# def __setitem__(self, key, value):
# def add_setting(self, key, value):
# def save(self):
# def reload(self):
# def del_setting(self, key):
# def __hasitem__(self, key):
# def __contains__(self, key):
# def keys(self):
# def items(self):
# def values(self):
# def __iter__(self):
. Output only the next line. | return time.mktime(o.timetuple()) |
Given snippet: <|code_start|> # fix the parent at run time.
self.env = builder.env
self.bytecode = bytecode
self.argc = len(builder.args)
if builder.rest_arg:
self.fixed_argc = self.argc-1
else:
self.fixed_argc = self.argc
self.literals = list(builder.literals)
def lexical_parent_get(self):
return self.env.parent
def lexical_parent_set(self, parent):
self.env.parent = parent
lexical_parent = property(lexical_parent_get, lexical_parent_set)
def check_arity(self, argc):
if self.fixed_argc == self.argc:
if argc != self.argc:
raise WrongArgNumber("Expecting %d arguments, but got %d" %
(self.argc, argc))
else:
if argc < self.fixed_argc:
raise WrongArgNumber("Expecting at least %d arguments, but got %d" %
(self.fixed_argc, argc))
def disasm(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from cStringIO import StringIO
from .errors import WrongArgNumber
from .compiler.disasm import disasm
and context:
# Path: schemepy/skime/skime/errors.py
# class WrongArgNumber(CompileError):
# pass
#
# Path: schemepy/skime/skime/compiler/disasm.py
# def disasm(io, form):
# bytecode = form.bytecode
# env = form.env
# literals = form.literals
#
# ip = 0
# while ip < len(bytecode):
# io.write("%04X " % ip)
# instr = INSTRUCTIONS[bytecode[ip]]
# io.write("%20s " % instr.name)
# if instr.name in ['push_local', 'set_local']:
# io.write('idx: %d' % bytecode[ip+1])
# io.write(', name: ')
# io.write(env.get_name(bytecode[ip+1]))
# elif instr.name in ['push_local_depth', 'set_local_depth']:
# depth = bytecode[ip+1]
# idx = bytecode[ip+2]
# io.write("depth=%d, idx=%d" % (depth, idx))
# penv = env
# while depth > 0:
# penv = penv.parent
# depth -= 1
# io.write(" (name: %s)" % penv.get_name(idx))
# elif instr.name in ['goto', 'goto_if_not_false', 'goto_if_false']:
# io.write("ip=0x%04X" % bytecode[ip+1])
# elif instr.name == 'dynamic_set_local':
# lit = bytecode[ip-1]
# io.write('idx: %d' % bytecode[ip+1])
# io.write(', name: ')
# io.write(literals[lit].expression.name)
# else:
# io.write(', '.join(["%s=%s" % (name, val)
# for name, val in zip(instr.operands,
# bytecode[ip+1:
# ip+len(instr.operands)+1])]))
# io.write('\n')
# ip += instr.length
which might include code, classes, or functions. Output only the next line. | "Show the disassemble of the instructions of the proc. Useful for debug." |
Continue the code snippet: <|code_start|> self.fixed_argc = self.argc-1
else:
self.fixed_argc = self.argc
self.literals = list(builder.literals)
def lexical_parent_get(self):
return self.env.parent
def lexical_parent_set(self, parent):
self.env.parent = parent
lexical_parent = property(lexical_parent_get, lexical_parent_set)
def check_arity(self, argc):
if self.fixed_argc == self.argc:
if argc != self.argc:
raise WrongArgNumber("Expecting %d arguments, but got %d" %
(self.argc, argc))
else:
if argc < self.fixed_argc:
raise WrongArgNumber("Expecting at least %d arguments, but got %d" %
(self.fixed_argc, argc))
def disasm(self):
"Show the disassemble of the instructions of the proc. Useful for debug."
io = StringIO()
io.write('='*60)
io.write('\n')
io.write('Diasassemble of proc at %X\n' % id(self))
io.write('arguments: ')
<|code_end|>
. Use current file imports:
from cStringIO import StringIO
from .errors import WrongArgNumber
from .compiler.disasm import disasm
and context (classes, functions, or code) from other files:
# Path: schemepy/skime/skime/errors.py
# class WrongArgNumber(CompileError):
# pass
#
# Path: schemepy/skime/skime/compiler/disasm.py
# def disasm(io, form):
# bytecode = form.bytecode
# env = form.env
# literals = form.literals
#
# ip = 0
# while ip < len(bytecode):
# io.write("%04X " % ip)
# instr = INSTRUCTIONS[bytecode[ip]]
# io.write("%20s " % instr.name)
# if instr.name in ['push_local', 'set_local']:
# io.write('idx: %d' % bytecode[ip+1])
# io.write(', name: ')
# io.write(env.get_name(bytecode[ip+1]))
# elif instr.name in ['push_local_depth', 'set_local_depth']:
# depth = bytecode[ip+1]
# idx = bytecode[ip+2]
# io.write("depth=%d, idx=%d" % (depth, idx))
# penv = env
# while depth > 0:
# penv = penv.parent
# depth -= 1
# io.write(" (name: %s)" % penv.get_name(idx))
# elif instr.name in ['goto', 'goto_if_not_false', 'goto_if_false']:
# io.write("ip=0x%04X" % bytecode[ip+1])
# elif instr.name == 'dynamic_set_local':
# lit = bytecode[ip-1]
# io.write('idx: %d' % bytecode[ip+1])
# io.write(', name: ')
# io.write(literals[lit].expression.name)
# else:
# io.write(', '.join(["%s=%s" % (name, val)
# for name, val in zip(instr.operands,
# bytecode[ip+1:
# ip+len(instr.operands)+1])]))
# io.write('\n')
# ip += instr.length
. Output only the next line. | args = [self.env.get_name(i) for i in range(self.argc)] |
Next line prediction: <|code_start|> literals = literals.rest
if literals is not None:
raise SyntaxError("Invalid syntax rule format: literals should be a proper list.")
self.rules = []
# Process syntax rules
rules = body.rest
while rules is not None:
rule = rules.first
self.rules.append(SyntaxRule(rule, lit, env))
rules = rules.rest
except AttributeError:
raise SyntaxError("Invalid syntax for syntax-rules form")
def transform(self, env, form):
for rule in self.rules:
try:
md = rule.match(env, form)
return rule.expand(env, md)
except MatchError:
pass
raise SyntaxError("Can not find syntax rule to match the form %s" % form)
class SyntaxRule(object):
def __init__(self, rule, literals, env):
if not isinstance(rule, pair) or not isinstance(rule.rest, pair):
raise SyntaxError("Expecting (pattern template) for syntax rule, but got %s" % rule)
if rule.rest.rest is not None:
raise SyntaxError("Extra expressions in syntax rule: %s" % rule)
self.env = env
<|code_end|>
. Use current file imports:
(from .types.pair import Pair as pair
from .types.symbol import Symbol as sym
from .errors import SyntaxError)
and context including class names, function names, or small code snippets from other files:
# Path: schemepy/skime/skime/types/pair.py
# class Pair(object):
# """\
# The Pair pair of Scheme.
#
# Pair can be chained to form a list. The Python value None acts as
# end-of-list.
#
# Pair(1, Pair(2, None)) <==> '(1 2) <==> '(1 . (2 . ()))
# """
# __slots__ = ['first', 'rest']
#
# def __init__(self, first, rest):
# self.first = first
# self.rest = rest
#
# def get_car(self):
# return self.first
# def set_car(self, val):
# self.first = val
# def get_cdr(self):
# return self.rest
# def set_cdr(self, val):
# self.rest = val
# car = property(get_car, set_car)
# cdr = property(get_cdr, set_cdr)
#
# def __eq__(self, other):
# return isinstance(other, Pair) and \
# self.first == other.first and \
# self.rest == other.rest
# def __ne__(self, other):
# return not self.__eq__(other)
#
# def __str__(self):
# segments = [self.first.__str__()]
# elems = self.rest
#
# while isinstance(elems, Pair):
# segments.append(elems.first.__str__())
# elems = elems.rest
#
# if elems is not None:
# segments.append(".")
# segments.append(elems.__str__())
# return '(' + ' '.join(segments) + ')'
#
# Path: schemepy/skime/skime/types/symbol.py
# class Symbol(object):
# symbols = weakref.WeakValueDictionary({})
#
# def __new__(cls, name):
# """\
# Get the interned symbol of name. If no found, create
# a new interned symbol.
# """
# if cls.symbols.has_key(name):
# return cls.symbols[name]
#
# sym = object.__new__(cls)
# sym._name = name
# cls.symbols[name] = sym
# return sym
#
# def __eq__(self, other):
# return self is other
# def __ne__(self, other):
# return not self.__eq__(other)
#
# def get_name(self):
# return self._name
# def set_name(self):
# raise AttributeError("Can't modify name of a symbol.")
# name = property(get_name, set_name)
#
# def __str__(self):
# return self.name
# def __repr__(self):
# return "<symbol %s>" % self._name.__repr__()
#
# Path: schemepy/skime/skime/errors.py
# class SyntaxError(CompileError):
# pass
. Output only the next line. | self.variables = {} |
Given the following code snippet before the placeholder: <|code_start|>
class Macro(object):
def __init__(self, env, body):
self.lexical_parent = env
<|code_end|>
, predict the next line using imports from the current file:
from .types.pair import Pair as pair
from .types.symbol import Symbol as sym
from .errors import SyntaxError
and context including class names, function names, and sometimes code from other files:
# Path: schemepy/skime/skime/types/pair.py
# class Pair(object):
# """\
# The Pair pair of Scheme.
#
# Pair can be chained to form a list. The Python value None acts as
# end-of-list.
#
# Pair(1, Pair(2, None)) <==> '(1 2) <==> '(1 . (2 . ()))
# """
# __slots__ = ['first', 'rest']
#
# def __init__(self, first, rest):
# self.first = first
# self.rest = rest
#
# def get_car(self):
# return self.first
# def set_car(self, val):
# self.first = val
# def get_cdr(self):
# return self.rest
# def set_cdr(self, val):
# self.rest = val
# car = property(get_car, set_car)
# cdr = property(get_cdr, set_cdr)
#
# def __eq__(self, other):
# return isinstance(other, Pair) and \
# self.first == other.first and \
# self.rest == other.rest
# def __ne__(self, other):
# return not self.__eq__(other)
#
# def __str__(self):
# segments = [self.first.__str__()]
# elems = self.rest
#
# while isinstance(elems, Pair):
# segments.append(elems.first.__str__())
# elems = elems.rest
#
# if elems is not None:
# segments.append(".")
# segments.append(elems.__str__())
# return '(' + ' '.join(segments) + ')'
#
# Path: schemepy/skime/skime/types/symbol.py
# class Symbol(object):
# symbols = weakref.WeakValueDictionary({})
#
# def __new__(cls, name):
# """\
# Get the interned symbol of name. If no found, create
# a new interned symbol.
# """
# if cls.symbols.has_key(name):
# return cls.symbols[name]
#
# sym = object.__new__(cls)
# sym._name = name
# cls.symbols[name] = sym
# return sym
#
# def __eq__(self, other):
# return self is other
# def __ne__(self, other):
# return not self.__eq__(other)
#
# def get_name(self):
# return self._name
# def set_name(self):
# raise AttributeError("Can't modify name of a symbol.")
# name = property(get_name, set_name)
#
# def __str__(self):
# return self.name
# def __repr__(self):
# return "<symbol %s>" % self._name.__repr__()
#
# Path: schemepy/skime/skime/errors.py
# class SyntaxError(CompileError):
# pass
. Output only the next line. | try: |
Given the code snippet: <|code_start|> literals = literals.rest
if literals is not None:
raise SyntaxError("Invalid syntax rule format: literals should be a proper list.")
self.rules = []
# Process syntax rules
rules = body.rest
while rules is not None:
rule = rules.first
self.rules.append(SyntaxRule(rule, lit, env))
rules = rules.rest
except AttributeError:
raise SyntaxError("Invalid syntax for syntax-rules form")
def transform(self, env, form):
for rule in self.rules:
try:
md = rule.match(env, form)
return rule.expand(env, md)
except MatchError:
pass
raise SyntaxError("Can not find syntax rule to match the form %s" % form)
class SyntaxRule(object):
def __init__(self, rule, literals, env):
if not isinstance(rule, pair) or not isinstance(rule.rest, pair):
raise SyntaxError("Expecting (pattern template) for syntax rule, but got %s" % rule)
if rule.rest.rest is not None:
raise SyntaxError("Extra expressions in syntax rule: %s" % rule)
self.env = env
<|code_end|>
, generate the next line using the imports in this file:
from .types.pair import Pair as pair
from .types.symbol import Symbol as sym
from .errors import SyntaxError
and context (functions, classes, or occasionally code) from other files:
# Path: schemepy/skime/skime/types/pair.py
# class Pair(object):
# """\
# The Pair pair of Scheme.
#
# Pair can be chained to form a list. The Python value None acts as
# end-of-list.
#
# Pair(1, Pair(2, None)) <==> '(1 2) <==> '(1 . (2 . ()))
# """
# __slots__ = ['first', 'rest']
#
# def __init__(self, first, rest):
# self.first = first
# self.rest = rest
#
# def get_car(self):
# return self.first
# def set_car(self, val):
# self.first = val
# def get_cdr(self):
# return self.rest
# def set_cdr(self, val):
# self.rest = val
# car = property(get_car, set_car)
# cdr = property(get_cdr, set_cdr)
#
# def __eq__(self, other):
# return isinstance(other, Pair) and \
# self.first == other.first and \
# self.rest == other.rest
# def __ne__(self, other):
# return not self.__eq__(other)
#
# def __str__(self):
# segments = [self.first.__str__()]
# elems = self.rest
#
# while isinstance(elems, Pair):
# segments.append(elems.first.__str__())
# elems = elems.rest
#
# if elems is not None:
# segments.append(".")
# segments.append(elems.__str__())
# return '(' + ' '.join(segments) + ')'
#
# Path: schemepy/skime/skime/types/symbol.py
# class Symbol(object):
# symbols = weakref.WeakValueDictionary({})
#
# def __new__(cls, name):
# """\
# Get the interned symbol of name. If no found, create
# a new interned symbol.
# """
# if cls.symbols.has_key(name):
# return cls.symbols[name]
#
# sym = object.__new__(cls)
# sym._name = name
# cls.symbols[name] = sym
# return sym
#
# def __eq__(self, other):
# return self is other
# def __ne__(self, other):
# return not self.__eq__(other)
#
# def get_name(self):
# return self._name
# def set_name(self):
# raise AttributeError("Can't modify name of a symbol.")
# name = property(get_name, set_name)
#
# def __str__(self):
# return self.name
# def __repr__(self):
# return "<symbol %s>" % self._name.__repr__()
#
# Path: schemepy/skime/skime/errors.py
# class SyntaxError(CompileError):
# pass
. Output only the next line. | self.variables = {} |
Here is a snippet: <|code_start|>
lib = find_library("mzscheme3m")
if lib is None:
raise RuntimeError("Can't find a mzscheme library to use.")
mz = cdll.LoadLibrary(lib)
# Load the helper library which exports the macro's as C functions
path = os.path.abspath(os.path.join(os.path.split(__file__)[0], '_mzhelper.so'))
_mzhelper = cdll.LoadLibrary(path)
<|code_end|>
. Write the next line using the current file imports:
from ctypes.util import find_library
from ctypes import *
from schemepy.types import *
from schemepy import exceptions
from schemepy import tpcl
from _ctypes import Py_INCREF, Py_DECREF, PyObj_FromPtr
import types
import os.path
import init_mz
and context from other files:
# Path: schemepy/exceptions.py
# class Error(Exception):
# class ConversionError(Error):
# class VMNotFoundError(Error):
# class ProfileNotFoundError(Error):
# class BackendNotFoundError(Error):
# class SchemeError(Error):
# class ScmSystemError(SchemeError):
# class ScmNumericalError(SchemeError):
# class ScmWrongArgType(SchemeError):
# class ScmWrongArgNumber(SchemeError):
# class ScmSyntaxError(SchemeError):
# class ScmUnboundVariable(SchemeError):
# class ScmMiscError(SchemeError):
# def __str__(self):
# def __init__(self, value, message):
# def __init__(self, message):
# def __init__(self, message):
# def __init__(self, message):
# def __init__(self, message):
# def __init__(self, message):
# def __init__(self, message):
# def __init__(self, message):
# def __init__(self, message):
# def __init__(self, message):
# def __init__(self, message):
# def __init__(self, message):
#
# Path: schemepy/tpcl.py
# def setup(vm):
, which may include functions, classes, or code. Output only the next line. | class SCM(c_void_p): |
Here is a snippet: <|code_start|> self.report_error("Expecting end of code, but more code is got")
return expr
def parse_expr(self):
def parse_pound():
if self.peak(idx=1) == 't':
self.pop(n=2)
return True
if self.peak(idx=1) == 'f':
self.pop(n=2)
return False
if self.peak(idx=1) == '(':
return self.parse_vector()
def parse_number_or_symbol():
if self.isdigit(self.peak(idx=1)):
return self.parse_number()
return self.parse_symbol()
mapping = {
'#' : parse_pound,
'(' : self.parse_list,
"'" : self.parse_quote,
'`' : self.parse_quote,
',' : self.parse_unquote,
'+' : parse_number_or_symbol,
'-' : parse_number_or_symbol,
'"' : self.parse_string
}
<|code_end|>
. Write the next line using the current file imports:
from ..types.symbol import Symbol as sym
from ..types.pair import Pair as pair
from ..errors import ParseError
and context from other files:
# Path: schemepy/skime/skime/types/symbol.py
# class Symbol(object):
# symbols = weakref.WeakValueDictionary({})
#
# def __new__(cls, name):
# """\
# Get the interned symbol of name. If no found, create
# a new interned symbol.
# """
# if cls.symbols.has_key(name):
# return cls.symbols[name]
#
# sym = object.__new__(cls)
# sym._name = name
# cls.symbols[name] = sym
# return sym
#
# def __eq__(self, other):
# return self is other
# def __ne__(self, other):
# return not self.__eq__(other)
#
# def get_name(self):
# return self._name
# def set_name(self):
# raise AttributeError("Can't modify name of a symbol.")
# name = property(get_name, set_name)
#
# def __str__(self):
# return self.name
# def __repr__(self):
# return "<symbol %s>" % self._name.__repr__()
#
# Path: schemepy/skime/skime/types/pair.py
# class Pair(object):
# """\
# The Pair pair of Scheme.
#
# Pair can be chained to form a list. The Python value None acts as
# end-of-list.
#
# Pair(1, Pair(2, None)) <==> '(1 2) <==> '(1 . (2 . ()))
# """
# __slots__ = ['first', 'rest']
#
# def __init__(self, first, rest):
# self.first = first
# self.rest = rest
#
# def get_car(self):
# return self.first
# def set_car(self, val):
# self.first = val
# def get_cdr(self):
# return self.rest
# def set_cdr(self, val):
# self.rest = val
# car = property(get_car, set_car)
# cdr = property(get_cdr, set_cdr)
#
# def __eq__(self, other):
# return isinstance(other, Pair) and \
# self.first == other.first and \
# self.rest == other.rest
# def __ne__(self, other):
# return not self.__eq__(other)
#
# def __str__(self):
# segments = [self.first.__str__()]
# elems = self.rest
#
# while isinstance(elems, Pair):
# segments.append(elems.first.__str__())
# elems = elems.rest
#
# if elems is not None:
# segments.append(".")
# segments.append(elems.__str__())
# return '(' + ' '.join(segments) + ')'
#
# Path: schemepy/skime/skime/errors.py
# class ParseError(CompileError):
# pass
, which may include functions, classes, or code. Output only the next line. | self.skip_all() |
Given snippet: <|code_start|> def parse_symbol(self):
pos1 = self.pos
self.pop()
while self.more() and \
not self.isspace(self.peak()) and \
not self.peak() in ['\'', ')', '(', ',', '@']:
self.pop()
pos2 = self.pos
return sym(self.text[pos1:pos2])
def parse_string(self):
mappings = {
'"':'"',
'\\':'\\',
'n':'\n',
't':'\t'
}
self.eat('"')
strings = []
pos1 = self.pos
while self.more():
if self.peak() == '"':
break
if self.peak() == '\\':
self.pop()
ch = self.peak()
if ch in mappings:
strings.append(self.text[pos1:self.pos-1])
strings.append(mappings[ch])
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from ..types.symbol import Symbol as sym
from ..types.pair import Pair as pair
from ..errors import ParseError
and context:
# Path: schemepy/skime/skime/types/symbol.py
# class Symbol(object):
# symbols = weakref.WeakValueDictionary({})
#
# def __new__(cls, name):
# """\
# Get the interned symbol of name. If no found, create
# a new interned symbol.
# """
# if cls.symbols.has_key(name):
# return cls.symbols[name]
#
# sym = object.__new__(cls)
# sym._name = name
# cls.symbols[name] = sym
# return sym
#
# def __eq__(self, other):
# return self is other
# def __ne__(self, other):
# return not self.__eq__(other)
#
# def get_name(self):
# return self._name
# def set_name(self):
# raise AttributeError("Can't modify name of a symbol.")
# name = property(get_name, set_name)
#
# def __str__(self):
# return self.name
# def __repr__(self):
# return "<symbol %s>" % self._name.__repr__()
#
# Path: schemepy/skime/skime/types/pair.py
# class Pair(object):
# """\
# The Pair pair of Scheme.
#
# Pair can be chained to form a list. The Python value None acts as
# end-of-list.
#
# Pair(1, Pair(2, None)) <==> '(1 2) <==> '(1 . (2 . ()))
# """
# __slots__ = ['first', 'rest']
#
# def __init__(self, first, rest):
# self.first = first
# self.rest = rest
#
# def get_car(self):
# return self.first
# def set_car(self, val):
# self.first = val
# def get_cdr(self):
# return self.rest
# def set_cdr(self, val):
# self.rest = val
# car = property(get_car, set_car)
# cdr = property(get_cdr, set_cdr)
#
# def __eq__(self, other):
# return isinstance(other, Pair) and \
# self.first == other.first and \
# self.rest == other.rest
# def __ne__(self, other):
# return not self.__eq__(other)
#
# def __str__(self):
# segments = [self.first.__str__()]
# elems = self.rest
#
# while isinstance(elems, Pair):
# segments.append(elems.first.__str__())
# elems = elems.rest
#
# if elems is not None:
# segments.append(".")
# segments.append(elems.__str__())
# return '(' + ' '.join(segments) + ')'
#
# Path: schemepy/skime/skime/errors.py
# class ParseError(CompileError):
# pass
which might include code, classes, or functions. Output only the next line. | self.pop() |
Based on the snippet: <|code_start|> isfloat = False
pos1 = self.pos
while self.isdigit(self.peak()):
self.pop()
if self.eat('.'):
isfloat = True
while self.isdigit(self.peak()):
self.pop()
pos2 = self.pos
if pos2 == pos1:
return None
if isfloat:
return float(self.text[pos1:pos2])
else:
return int(self.text[pos1:pos2])
def parse_list(self):
self.eat('(')
elems = []
while self.more():
self.skip_all()
if self.peak() == ')':
elems.append(None)
break
if self.peak() == '.' and self.peak(idx=1) != '.':
self.eat('.')
elems.append(self.parse_expr())
self.skip_all()
break
<|code_end|>
, predict the immediate next line with the help of imports:
from ..types.symbol import Symbol as sym
from ..types.pair import Pair as pair
from ..errors import ParseError
and context (classes, functions, sometimes code) from other files:
# Path: schemepy/skime/skime/types/symbol.py
# class Symbol(object):
# symbols = weakref.WeakValueDictionary({})
#
# def __new__(cls, name):
# """\
# Get the interned symbol of name. If no found, create
# a new interned symbol.
# """
# if cls.symbols.has_key(name):
# return cls.symbols[name]
#
# sym = object.__new__(cls)
# sym._name = name
# cls.symbols[name] = sym
# return sym
#
# def __eq__(self, other):
# return self is other
# def __ne__(self, other):
# return not self.__eq__(other)
#
# def get_name(self):
# return self._name
# def set_name(self):
# raise AttributeError("Can't modify name of a symbol.")
# name = property(get_name, set_name)
#
# def __str__(self):
# return self.name
# def __repr__(self):
# return "<symbol %s>" % self._name.__repr__()
#
# Path: schemepy/skime/skime/types/pair.py
# class Pair(object):
# """\
# The Pair pair of Scheme.
#
# Pair can be chained to form a list. The Python value None acts as
# end-of-list.
#
# Pair(1, Pair(2, None)) <==> '(1 2) <==> '(1 . (2 . ()))
# """
# __slots__ = ['first', 'rest']
#
# def __init__(self, first, rest):
# self.first = first
# self.rest = rest
#
# def get_car(self):
# return self.first
# def set_car(self, val):
# self.first = val
# def get_cdr(self):
# return self.rest
# def set_cdr(self, val):
# self.rest = val
# car = property(get_car, set_car)
# cdr = property(get_cdr, set_cdr)
#
# def __eq__(self, other):
# return isinstance(other, Pair) and \
# self.first == other.first and \
# self.rest == other.rest
# def __ne__(self, other):
# return not self.__eq__(other)
#
# def __str__(self):
# segments = [self.first.__str__()]
# elems = self.rest
#
# while isinstance(elems, Pair):
# segments.append(elems.first.__str__())
# elems = elems.rest
#
# if elems is not None:
# segments.append(".")
# segments.append(elems.__str__())
# return '(' + ' '.join(segments) + ')'
#
# Path: schemepy/skime/skime/errors.py
# class ParseError(CompileError):
# pass
. Output only the next line. | elems.append(self.parse_expr()) |
Using the snippet: <|code_start|> field, request, params, model, model_admin, field_path
)
if hasattr(field, 'verbose_name'):
self.lookup_title = field.verbose_name
else:
self.lookup_title = other_model._meta.verbose_name
self.title = self.lookup_title
def has_output(self):
if hasattr(self.field, 'rel') and self.field.null:
extra = 1
else:
extra = 0
return len(self.lookup_choices) + extra > 1
def expected_parameters(self):
return [self.lookup_kwarg_lft, self.lookup_kwarg_rght, self.lookup_kwarg_isnull]
def choices(self, cl):
yield {
'selected': self.lookup_val_tid is None
and self.lookup_val_lft is None
and self.lookup_val_rght is None
and not self.lookup_val_isnull,
'query_string': cl.get_query_string({}, [
self.lookup_kwarg_tid,
self.lookup_kwarg_lft,
self.lookup_kwarg_rght,
self.lookup_kwarg_isnull,
]),
<|code_end|>
, determine the next line of code. You have imports:
from django.conf import settings
from django.contrib import admin
from django.contrib.admin.util import get_model_from_relation
from django.core.urlresolvers import reverse
from django.utils.encoding import smart_text, force_text
from django.utils.translation import ugettext_lazy as _
from django_mptt_admin.admin import DjangoMpttAdmin
from mptt.models import TreeForeignKey
from cms.utils import get_language_from_request
from . import models
from .utils import get_form, get_admin
from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE
and context (class names, function names, or code) available:
# Path: cmsplugin_shop/utils.py
# def get_form(name):
# return import_string(getattr(settings.settings,
# 'CMSPLUGIN_SHOP_{}_FORM'.format(name.upper()),
# 'cmsplugin_shop.forms.{}Form'.format(name),
# ))
#
# def get_admin(name):
# return import_string(getattr(settings.settings,
# 'CMSPLUGIN_SHOP_{}_ADMIN'.format(name.upper()),
# 'cmsplugin_shop.admins.{}Admin'.format(name),
# ))
. Output only the next line. | 'display': _('All'), |
Based on the snippet: <|code_start|>from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement
def cart(self):
try:
c = Cart.objects.get(id=self.session[settings.SESSION_KEY_CART], order=None)
except (KeyError, Cart.DoesNotExist):
# delete expired carts
Cart.objects.filter(
last_updated__lt = timezone.now() - datetime.timedelta(settings.CART_EXPIRY_DAYS),
order=None
).delete()
# create new one
c = Cart()
self.session[settings.SESSION_KEY_CART] = c.id
return c
def save_cart(self):
self.cart.save()
self.session[settings.SESSION_KEY_CART] = self.cart.id
<|code_end|>
, predict the immediate next line with the help of imports:
import datetime
from django.utils import timezone
from django.utils.functional import cached_property
from . import settings
from .models import Cart
and context (classes, functions, sometimes code) from other files:
# Path: cmsplugin_shop/models.py
# class Cart(models.Model):
# last_updated = models.DateTimeField(_('last updated'), auto_now=True)
#
# class Meta:
# verbose_name = _('cart')
# verbose_name_plural = _('carts')
#
# def __str__(self):
# return ', '.join(map(smart_text, self.all_items))
#
# def get_absolute_url(self):
# return reverse('Cart:cart')
#
# @cached_property
# def all_items(self):
# return list(self.items.order_by('product__name', 'package__multiple'))
#
# def get_price(self):
# if len(self.all_items):
# return sum(item.get_price() for item in self.all_items)
# else:
# return Price(0)
# get_price.short_description = _('price')
. Output only the next line. | class CartMiddleware(object): |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement
@apphook_pool.register
class CatalogApp(CMSApp):
name = _('Catalog')
urls = [catalog]
app_name = 'Catalog'
@apphook_pool.register
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.utils.translation import ugettext_lazy as _
from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool
from .urls import catalog, cart, order, my_orders
and context:
# Path: cmsplugin_shop/urls.py
which might include code, classes, or functions. Output only the next line. | class CartApp(CMSApp): |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement
@apphook_pool.register
class CatalogApp(CMSApp):
name = _('Catalog')
urls = [catalog]
app_name = 'Catalog'
@apphook_pool.register
class CartApp(CMSApp):
name = _('Cart')
urls = [cart]
app_name = 'Cart'
@apphook_pool.register
class OrderApp(CMSApp):
name = _('Order')
urls = [order]
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.utils.translation import ugettext_lazy as _
from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool
from .urls import catalog, cart, order, my_orders
and context:
# Path: cmsplugin_shop/urls.py
which might include code, classes, or functions. Output only the next line. | app_name = 'Order' |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement
@apphook_pool.register
class CatalogApp(CMSApp):
name = _('Catalog')
urls = [catalog]
app_name = 'Catalog'
<|code_end|>
, determine the next line of code. You have imports:
from django.utils.translation import ugettext_lazy as _
from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool
from .urls import catalog, cart, order, my_orders
and context (class names, function names, or code) available:
# Path: cmsplugin_shop/urls.py
. Output only the next line. | @apphook_pool.register |
Predict the next line after this snippet: <|code_start|>from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement
class ProductPlugin(CMSPluginBase):
model = ProductPlugin
name = _('Product')
text_enabled = True
def render(self, context, instance, placeholder):
context.update({
'plugin': instance,
'product': instance.product,
'placeholder': placeholder,
<|code_end|>
using the current file's imports:
from cms.plugin_base import CMSPluginBase
from django.utils.translation import ugettext as _
from .models import ProductPlugin, CategoryPlugin
and any relevant context from other files:
# Path: cmsplugin_shop/models.py
# class ProductPlugin(CMSPlugin):
# product = models.ForeignKey(Product, verbose_name=_('product'))
# template = models.CharField(_('template'), max_length=100, choices=settings.PRODUCT_TEMPLATES,
# default=settings.PRODUCT_TEMPLATES[0][0],
# help_text=_('the template used to render plugin'))
#
# def __str__(self):
# return self.product.name
#
# @cached_property
# def render_template(self):
# return 'cmsplugin_shop/product/%s.html' % self.template
#
# class CategoryPlugin(CMSPlugin):
# category = models.ForeignKey(Category, verbose_name=_('category'))
# template = models.CharField(_('template'), max_length=100, choices=settings.CATEGORY_TEMPLATES,
# default=settings.CATEGORY_TEMPLATES[0][0],
# help_text=_('the template used to render plugin'))
#
# def __str__(self):
# return self.category.name
#
# @cached_property
# def render_template(self):
# return 'cmsplugin_shop/category/%s.html' % self.template
. Output only the next line. | }) |
Predict the next line after this snippet: <|code_start|>from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement
class ProductPlugin(CMSPluginBase):
model = ProductPlugin
name = _('Product')
text_enabled = True
def render(self, context, instance, placeholder):
context.update({
'plugin': instance,
'product': instance.product,
'placeholder': placeholder,
})
return context
class CategoryPlugin(CMSPluginBase):
model = CategoryPlugin
name = _('Category')
<|code_end|>
using the current file's imports:
from cms.plugin_base import CMSPluginBase
from django.utils.translation import ugettext as _
from .models import ProductPlugin, CategoryPlugin
and any relevant context from other files:
# Path: cmsplugin_shop/models.py
# class ProductPlugin(CMSPlugin):
# product = models.ForeignKey(Product, verbose_name=_('product'))
# template = models.CharField(_('template'), max_length=100, choices=settings.PRODUCT_TEMPLATES,
# default=settings.PRODUCT_TEMPLATES[0][0],
# help_text=_('the template used to render plugin'))
#
# def __str__(self):
# return self.product.name
#
# @cached_property
# def render_template(self):
# return 'cmsplugin_shop/product/%s.html' % self.template
#
# class CategoryPlugin(CMSPlugin):
# category = models.ForeignKey(Category, verbose_name=_('category'))
# template = models.CharField(_('template'), max_length=100, choices=settings.CATEGORY_TEMPLATES,
# default=settings.CATEGORY_TEMPLATES[0][0],
# help_text=_('the template used to render plugin'))
#
# def __str__(self):
# return self.category.name
#
# @cached_property
# def render_template(self):
# return 'cmsplugin_shop/category/%s.html' % self.template
. Output only the next line. | text_enabled = True |
Given the code snippet: <|code_start|>from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement
@python_2_unicode_compatible
class BasePrice(object):
def __lt__(self, other):
try:
if PRICE_TYPE == 'gross':
return self.gross < other.gross
else:
return self.net < other.net
except:
return NotImplemented
<|code_end|>
, generate the next line using the imports in this file:
from collections import namedtuple
from decimal import Decimal
from django.utils.encoding import python_2_unicode_compatible
from itertools import groupby
from .settings import PRICE_TYPE
from .utils import quantize, currency
and context (functions, classes, or occasionally code) from other files:
# Path: cmsplugin_shop/settings.py
# PRICE_TYPE = S('PRICE_TYPE', 'gross')
#
# Path: cmsplugin_shop/utils.py
# def quantize(price):
# return price.quantize(QUANTIZE)
#
# def currency(val, localeconv=None, international=False):
# """Formats val according to the currency settings for current language."""
# val = Decimal(val)
# conv = localeconv_cache.getconv()
# conv.update(localeconv or settings.LOCALECONV)
#
# # split integer part and fraction
# parts = str(abs(val)).split('.')
#
# # grouping
# groups = []
# s = parts[0]
# for interval in locale._grouping_intervals(conv['mon_grouping']):
# if not s:
# break
# groups.append(s[-interval:])
# s = s[:-interval]
# if s:
# groups.append(s)
# groups.reverse()
# s = smart_text(conv['mon_thousands_sep']).join(groups)
#
# # display fraction for non integer values
# if len(parts) > 1:
# s += smart_text(conv['mon_decimal_point']) + parts[1]
#
# # '<' and '>' are markers if the sign must be inserted between symbol and value
# s = '<' + s + '>'
#
# smb = smart_text(conv[international and 'int_curr_symbol' or 'currency_symbol'])
# precedes = conv[val<0 and 'n_cs_precedes' or 'p_cs_precedes']
# separated = conv[val<0 and 'n_sep_by_space' or 'p_sep_by_space']
#
# if precedes:
# s = smb + (separated and ' ' or '') + s
# else:
# s = s + (separated and ' ' or '') + smb
#
# sign_pos = conv[val<0 and 'n_sign_posn' or 'p_sign_posn']
# sign = conv[val<0 and 'negative_sign' or 'positive_sign']
#
# if sign_pos == 0:
# s = '(' + s + ')'
# elif sign_pos == 1:
# s = sign + s
# elif sign_pos == 2:
# s = s + sign
# elif sign_pos == 3:
# s = s.replace('<', sign)
# elif sign_pos == 4:
# s = s.replace('>', sign)
# else:
# # the default if nothing specified;
# # this should be the most fitting sign position
# s = sign + s
#
# return s.replace('<', '').replace('>', '')
. Output only the next line. | def __le__(self, other): |
Continue the code snippet: <|code_start|> try:
if PRICE_TYPE == 'gross':
return self.gross < other.gross
else:
return self.net < other.net
except:
return NotImplemented
def __le__(self, other):
return self < other or self == other
def __eq__(self, other):
try:
if PRICE_TYPE == 'gross':
return self.gross == other.gross
else:
return self.net == other.net
except:
return False
def __ne__(self, other):
return not self == other
def __radd__(self, other):
return self + other
def __rmul__(self, other):
return self * other
@property
<|code_end|>
. Use current file imports:
from collections import namedtuple
from decimal import Decimal
from django.utils.encoding import python_2_unicode_compatible
from itertools import groupby
from .settings import PRICE_TYPE
from .utils import quantize, currency
and context (classes, functions, or code) from other files:
# Path: cmsplugin_shop/settings.py
# PRICE_TYPE = S('PRICE_TYPE', 'gross')
#
# Path: cmsplugin_shop/utils.py
# def quantize(price):
# return price.quantize(QUANTIZE)
#
# def currency(val, localeconv=None, international=False):
# """Formats val according to the currency settings for current language."""
# val = Decimal(val)
# conv = localeconv_cache.getconv()
# conv.update(localeconv or settings.LOCALECONV)
#
# # split integer part and fraction
# parts = str(abs(val)).split('.')
#
# # grouping
# groups = []
# s = parts[0]
# for interval in locale._grouping_intervals(conv['mon_grouping']):
# if not s:
# break
# groups.append(s[-interval:])
# s = s[:-interval]
# if s:
# groups.append(s)
# groups.reverse()
# s = smart_text(conv['mon_thousands_sep']).join(groups)
#
# # display fraction for non integer values
# if len(parts) > 1:
# s += smart_text(conv['mon_decimal_point']) + parts[1]
#
# # '<' and '>' are markers if the sign must be inserted between symbol and value
# s = '<' + s + '>'
#
# smb = smart_text(conv[international and 'int_curr_symbol' or 'currency_symbol'])
# precedes = conv[val<0 and 'n_cs_precedes' or 'p_cs_precedes']
# separated = conv[val<0 and 'n_sep_by_space' or 'p_sep_by_space']
#
# if precedes:
# s = smb + (separated and ' ' or '') + s
# else:
# s = s + (separated and ' ' or '') + smb
#
# sign_pos = conv[val<0 and 'n_sign_posn' or 'p_sign_posn']
# sign = conv[val<0 and 'negative_sign' or 'positive_sign']
#
# if sign_pos == 0:
# s = '(' + s + ')'
# elif sign_pos == 1:
# s = sign + s
# elif sign_pos == 2:
# s = s + sign
# elif sign_pos == 3:
# s = s.replace('<', sign)
# elif sign_pos == 4:
# s = s.replace('>', sign)
# else:
# # the default if nothing specified;
# # this should be the most fitting sign position
# s = sign + s
#
# return s.replace('<', '').replace('>', '')
. Output only the next line. | def tax(self): |
Using the snippet: <|code_start|>from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement
@python_2_unicode_compatible
class BasePrice(object):
def __lt__(self, other):
try:
if PRICE_TYPE == 'gross':
return self.gross < other.gross
else:
return self.net < other.net
except:
return NotImplemented
<|code_end|>
, determine the next line of code. You have imports:
from collections import namedtuple
from decimal import Decimal
from django.utils.encoding import python_2_unicode_compatible
from itertools import groupby
from .settings import PRICE_TYPE
from .utils import quantize, currency
and context (class names, function names, or code) available:
# Path: cmsplugin_shop/settings.py
# PRICE_TYPE = S('PRICE_TYPE', 'gross')
#
# Path: cmsplugin_shop/utils.py
# def quantize(price):
# return price.quantize(QUANTIZE)
#
# def currency(val, localeconv=None, international=False):
# """Formats val according to the currency settings for current language."""
# val = Decimal(val)
# conv = localeconv_cache.getconv()
# conv.update(localeconv or settings.LOCALECONV)
#
# # split integer part and fraction
# parts = str(abs(val)).split('.')
#
# # grouping
# groups = []
# s = parts[0]
# for interval in locale._grouping_intervals(conv['mon_grouping']):
# if not s:
# break
# groups.append(s[-interval:])
# s = s[:-interval]
# if s:
# groups.append(s)
# groups.reverse()
# s = smart_text(conv['mon_thousands_sep']).join(groups)
#
# # display fraction for non integer values
# if len(parts) > 1:
# s += smart_text(conv['mon_decimal_point']) + parts[1]
#
# # '<' and '>' are markers if the sign must be inserted between symbol and value
# s = '<' + s + '>'
#
# smb = smart_text(conv[international and 'int_curr_symbol' or 'currency_symbol'])
# precedes = conv[val<0 and 'n_cs_precedes' or 'p_cs_precedes']
# separated = conv[val<0 and 'n_sep_by_space' or 'p_sep_by_space']
#
# if precedes:
# s = smb + (separated and ' ' or '') + s
# else:
# s = s + (separated and ' ' or '') + smb
#
# sign_pos = conv[val<0 and 'n_sign_posn' or 'p_sign_posn']
# sign = conv[val<0 and 'negative_sign' or 'positive_sign']
#
# if sign_pos == 0:
# s = '(' + s + ')'
# elif sign_pos == 1:
# s = sign + s
# elif sign_pos == 2:
# s = s + sign
# elif sign_pos == 3:
# s = s.replace('<', sign)
# elif sign_pos == 4:
# s = s.replace('>', sign)
# else:
# # the default if nothing specified;
# # this should be the most fitting sign position
# s = sign + s
#
# return s.replace('<', '').replace('>', '')
. Output only the next line. | def __le__(self, other): |
Predict the next line after this snippet: <|code_start|>
class PriceField(models.DecimalField):
def __init__(self, *args, **kwargs):
kwargs.setdefault('decimal_places', settings.DECIMAL_PLACES)
kwargs.setdefault('max_digits', settings.MAX_DIGITS)
super(PriceField, self).__init__(*args, **kwargs)
class TaxRateField(models.DecimalField):
def __init__(self, *args, **kwargs):
kwargs.setdefault('decimal_places', 4)
kwargs.setdefault('max_digits', 9)
kwargs.setdefault('choices', settings.TAX_RATES.items())
kwargs.setdefault('default', settings.DEFAULT_TAX_RATE)
super(TaxRateField, self).__init__(*args, **kwargs)
@MPTTModelBase.register
@python_2_unicode_compatible
class Node(models.Model):
parent = TreeForeignKey('self', verbose_name=_('category'), blank=True, null=True,
related_name='children', limit_choices_to={'product':None})
name = models.CharField(_('name'), max_length=250)
slug = models.SlugField(_('slug'), max_length=250, db_index=True, unique=False)
summary = HTMLField(_('summary'), blank=True, default='')
description = HTMLField(_('description'), blank=True, default='')
photo = FilerImageField(verbose_name='Fotka', null=True, blank=True, on_delete=models.SET_NULL)
page_title = models.CharField(_('page title'), max_length=250, blank=True, null=True,
<|code_end|>
using the current file's imports:
import tagging
from cms.models import CMSPlugin
from django.contrib.sites.models import Site
from django.core.exceptions import ValidationError
from django.core.mail import send_mail
from django.core.urlresolvers import reverse
from django.core.validators import RegexValidator
from django.db import models
from django.template import Context
from django.template.loader import get_template
from django.utils.encoding import python_2_unicode_compatible, smart_text
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _
from filer.fields.image import FilerImageField
from mptt.fields import TreeForeignKey
from mptt.models import MPTTModelBase
from . import settings
from .price import Price
from .utils import get_rand_hash, get_html_field
and any relevant context from other files:
# Path: cmsplugin_shop/price.py
# class Price(BasePrice, namedtuple('Price', 'net gross rate')):
#
# def __new__(cls, price, rate=0):
# price = Decimal(price)
# rate = Decimal(rate)
# if rate:
# if PRICE_TYPE == 'gross':
# gross = quantize(price)
# net = quantize(gross / rate)
# else:
# net = quantize(price)
# gross = quantize(net * rate)
# else:
# gross = net = quantize(price)
# return super(Price, cls).__new__(cls, net, gross, rate)
#
# def __mul__(self, other):
# try:
# other = Decimal(other)
# if PRICE_TYPE == 'gross':
# return Price(self.gross * other, self.rate)
# else:
# return Price(self.net * other, self.rate)
# except TypeError:
# return NotImplemented
#
# def __add__(self, other):
# if isinstance(other, Price):
# return ComplexPrice((self, other))
# elif isinstance(other, ComplexPrice):
# return ComplexPrice((self,) + other.prices)
# else:
# try:
# return self + Price(other, self.rate)
# except TypeError:
# return NotImplemented
#
# Path: cmsplugin_shop/utils.py
# def get_rand_hash(length=32, stringset=string.ascii_letters+string.digits):
# return ''.join([stringset[i%len(stringset)] for i in [ord(x) for x in os.urandom(length)]])
#
# def get_html_field():
# return import_string(getattr(settings.settings,
# 'CMSPLUGIN_SHOP_HTML_FIELD',
# 'djangocms_text_ckeditor.fields.HTMLField',
# ))
. Output only the next line. | help_text=_('overwrite the title (html title tag)')) |
Next line prediction: <|code_start|> cart = models.OneToOneField(Cart, verbose_name=_('cart'), editable=False)
state = models.ForeignKey(OrderState, verbose_name=_('state'))
first_name = models.CharField(_('first name'), max_length=30)
last_name = models.CharField(_('last name'), max_length=30)
email = models.EmailField(_('email'))
phone = models.CharField(_('phone'), max_length=150, validators=[
RegexValidator(r'^\+?[0-9 ]+$')])
address = models.TextField(_('address'))
note = models.TextField(_('note'), blank=True)
comment = models.TextField(_('internal comment'), blank=True)
delivery_method = models.ForeignKey(DeliveryMethod, verbose_name=_('delivery method'))
payment_method = models.ForeignKey(PaymentMethod, verbose_name=_('payment method'))
voucher = models.ForeignKey(Voucher, verbose_name=_('voucher'), related_name='orders',
blank=True, null=True)
class Meta:
ordering = ('-date',)
verbose_name = _('order')
verbose_name_plural = _('orders')
def __str__(self):
return '{} {} {}'.format(self.date, self.first_name, self.last_name)
def get_confirm_url(self):
return reverse('Order:confirm', kwargs={'slug':self.slug})
def get_edit_url(self):
return reverse('admin:{}_{}_change'.format(self._meta.app_label, self._meta.model_name), args=(self.id,))
def get_absolute_url(self):
<|code_end|>
. Use current file imports:
(import tagging
from cms.models import CMSPlugin
from django.contrib.sites.models import Site
from django.core.exceptions import ValidationError
from django.core.mail import send_mail
from django.core.urlresolvers import reverse
from django.core.validators import RegexValidator
from django.db import models
from django.template import Context
from django.template.loader import get_template
from django.utils.encoding import python_2_unicode_compatible, smart_text
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _
from filer.fields.image import FilerImageField
from mptt.fields import TreeForeignKey
from mptt.models import MPTTModelBase
from . import settings
from .price import Price
from .utils import get_rand_hash, get_html_field)
and context including class names, function names, or small code snippets from other files:
# Path: cmsplugin_shop/price.py
# class Price(BasePrice, namedtuple('Price', 'net gross rate')):
#
# def __new__(cls, price, rate=0):
# price = Decimal(price)
# rate = Decimal(rate)
# if rate:
# if PRICE_TYPE == 'gross':
# gross = quantize(price)
# net = quantize(gross / rate)
# else:
# net = quantize(price)
# gross = quantize(net * rate)
# else:
# gross = net = quantize(price)
# return super(Price, cls).__new__(cls, net, gross, rate)
#
# def __mul__(self, other):
# try:
# other = Decimal(other)
# if PRICE_TYPE == 'gross':
# return Price(self.gross * other, self.rate)
# else:
# return Price(self.net * other, self.rate)
# except TypeError:
# return NotImplemented
#
# def __add__(self, other):
# if isinstance(other, Price):
# return ComplexPrice((self, other))
# elif isinstance(other, ComplexPrice):
# return ComplexPrice((self,) + other.prices)
# else:
# try:
# return self + Price(other, self.rate)
# except TypeError:
# return NotImplemented
#
# Path: cmsplugin_shop/utils.py
# def get_rand_hash(length=32, stringset=string.ascii_letters+string.digits):
# return ''.join([stringset[i%len(stringset)] for i in [ord(x) for x in os.urandom(length)]])
#
# def get_html_field():
# return import_string(getattr(settings.settings,
# 'CMSPLUGIN_SHOP_HTML_FIELD',
# 'djangocms_text_ckeditor.fields.HTMLField',
# ))
. Output only the next line. | return self.user \ |
Given the code snippet: <|code_start|>class OrderState(models.Model):
code = models.SlugField(_('code'))
name = models.CharField(_('name'), max_length=150)
description = HTMLField(_('description'), blank=True, default='')
class Meta:
verbose_name = _('order state')
verbose_name_plural = _('order states')
def __str__(self):
return self.name
@python_2_unicode_compatible
class Order(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True,
on_delete=models.SET_NULL)
slug = models.SlugField(editable=False)
date = models.DateTimeField(auto_now_add=True, editable=False)
cart = models.OneToOneField(Cart, verbose_name=_('cart'), editable=False)
state = models.ForeignKey(OrderState, verbose_name=_('state'))
first_name = models.CharField(_('first name'), max_length=30)
last_name = models.CharField(_('last name'), max_length=30)
email = models.EmailField(_('email'))
phone = models.CharField(_('phone'), max_length=150, validators=[
RegexValidator(r'^\+?[0-9 ]+$')])
address = models.TextField(_('address'))
note = models.TextField(_('note'), blank=True)
<|code_end|>
, generate the next line using the imports in this file:
import tagging
from cms.models import CMSPlugin
from django.contrib.sites.models import Site
from django.core.exceptions import ValidationError
from django.core.mail import send_mail
from django.core.urlresolvers import reverse
from django.core.validators import RegexValidator
from django.db import models
from django.template import Context
from django.template.loader import get_template
from django.utils.encoding import python_2_unicode_compatible, smart_text
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _
from filer.fields.image import FilerImageField
from mptt.fields import TreeForeignKey
from mptt.models import MPTTModelBase
from . import settings
from .price import Price
from .utils import get_rand_hash, get_html_field
and context (functions, classes, or occasionally code) from other files:
# Path: cmsplugin_shop/price.py
# class Price(BasePrice, namedtuple('Price', 'net gross rate')):
#
# def __new__(cls, price, rate=0):
# price = Decimal(price)
# rate = Decimal(rate)
# if rate:
# if PRICE_TYPE == 'gross':
# gross = quantize(price)
# net = quantize(gross / rate)
# else:
# net = quantize(price)
# gross = quantize(net * rate)
# else:
# gross = net = quantize(price)
# return super(Price, cls).__new__(cls, net, gross, rate)
#
# def __mul__(self, other):
# try:
# other = Decimal(other)
# if PRICE_TYPE == 'gross':
# return Price(self.gross * other, self.rate)
# else:
# return Price(self.net * other, self.rate)
# except TypeError:
# return NotImplemented
#
# def __add__(self, other):
# if isinstance(other, Price):
# return ComplexPrice((self, other))
# elif isinstance(other, ComplexPrice):
# return ComplexPrice((self,) + other.prices)
# else:
# try:
# return self + Price(other, self.rate)
# except TypeError:
# return NotImplemented
#
# Path: cmsplugin_shop/utils.py
# def get_rand_hash(length=32, stringset=string.ascii_letters+string.digits):
# return ''.join([stringset[i%len(stringset)] for i in [ord(x) for x in os.urandom(length)]])
#
# def get_html_field():
# return import_string(getattr(settings.settings,
# 'CMSPLUGIN_SHOP_HTML_FIELD',
# 'djangocms_text_ckeditor.fields.HTMLField',
# ))
. Output only the next line. | comment = models.TextField(_('internal comment'), blank=True) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
conn = get_vendor("DB").get_redis()
@controller_get
def get_worker_names(
<|code_end|>
, predict the next line using imports from the current file:
import redis
import copy
import dHydra.core.util as util
import tornado.escape as escape
from dHydra.core.Functions import *
from dHydra.core.Controller import controller
from dHydra.core.Controller import controller_get
from dHydra.core.Controller import controller_post
and context including class names, function names, and sometimes code from other files:
# Path: dHydra/core/Controller.py
# def controller(func):
# def _controller(
# query_arguments,
# body_arguments,
# get_query_argument,
# get_body_argument
# ):
# result = func(
# query_arguments,
# body_arguments,
# get_query_argument,
# get_body_argument
# )
# return result
# return _controller
#
# Path: dHydra/core/Controller.py
# def controller_get(func):
# def _controller(
# query_arguments,
# get_query_argument,
# ):
# result = func(
# query_arguments,
# get_query_argument,
# )
# return result
# return _controller
#
# Path: dHydra/core/Controller.py
# def controller_post(func):
# def _controller(
# query_arguments,
# body_arguments,
# get_query_argument,
# get_body_argument
# ):
# result = func(
# query_arguments,
# body_arguments,
# get_query_argument,
# get_body_argument
# )
# return result
# return _controller
. Output only the next line. | query_arguments, |
Based on the snippet: <|code_start|># coding: utf-8
start_worker(
worker_name="CtpMd",
nickname="CtpMd",
config="CtpMd.json"
<|code_end|>
, predict the immediate next line with the help of imports:
from dHydra.main import start_worker
and context (classes, functions, sometimes code) from other files:
# Path: dHydra/main.py
# def start_worker(worker_name, **kwargs):
# worker = get_worker_class(worker_name=worker_name, **kwargs)
# worker_dict[worker.nickname] = worker
# worker.start()
. Output only the next line. | ) |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
class EasyUncle(Vendor):
def __init__(
self,
accounts="easyuncle.json",
**kwargs
):
<|code_end|>
using the current file's imports:
from dHydra.core.Functions import get_vendor
from dHydra.core.Vendor import Vendor
from ctp.futures import ApiStruct
from datetime import datetime
import dHydra.core.util as util
import threading
import os
import pandas
import copy
and any relevant context from other files:
# Path: dHydra/core/Functions.py
# def get_vendor(name, vendor_name=None, **kwargs):
# """
# get_vendor方法,动态加载vendor类
# """
# logger = logging.getLogger('Functions')
# if vendor_name is None:
# vendor_name = "V-" + name
# class_name = name
# module_name = 'Vendor.' + name + '.' + class_name
# if os.path.exists(
# os.getcwd() + "/Vendor/" +
# name + "/" + class_name + ".py"
# ):
# try:
# instance = getattr(
# __import__(module_name, globals(), locals(), [class_name], 0),
# class_name
# )(**kwargs)
# except ImportError:
# traceback.print_exc()
# else:
# try:
# instance = getattr(
# __import__(
# "dHydra." + module_name,
# globals(),
# locals(),
# [class_name],
# 0
# ),
# class_name
# )(**kwargs)
# except ImportError:
# traceback.print_exc()
# return instance
#
# Path: dHydra/core/Vendor.py
# class Vendor:
#
# def __init__(
# self,
# log_path="log", #
# console_log=True, # 屏幕打印日志开关,默认True
# console_log_level=logging.INFO, # 屏幕打印日志的级别,默认为INFO
# critical_log=False, # critica单独l写文件日志,默认关闭
# error_log=True, # error级别单独写文件日志,默认开启
# warning_log=False, # warning级别单独写日志,默认关闭
# info_log=True, # info级别单独写日志,默认开启
# debug_log=False, # debug级别日志,默认关闭
# **kwargs
# ):
# self.logger = util.get_logger(
# log_path=log_path, #
# console_log=console_log, # 屏幕打印日志开关,默认True
# console_log_level=console_log_level, # 屏幕打印日志的级别,默认为INFO
# critical_log=critical_log, # critica单独l写文件日志,默认关闭
# error_log=error_log, # error级别单独写文件日志,默认开启
# warning_log=warning_log, # warning级别单独写日志,默认关闭
# info_log=info_log, # info级别单独写日志,默认开启
# debug_log=debug_log, # debug级别日志,默认关闭
# logger_name=self.__class__.__name__,
# )
. Output only the next line. | super().__init__(**kwargs) |
Using the snippet: <|code_start|> ):
super().__init__(**kwargs)
self.request_id = 0
# Note (IMPORTANT):
# broker_id, user_id, password, instrument_ids, market_front should
# be bytes
cfg = util.read_config(os.getcwd() + "/" + account)
if "broker_id" in cfg:
broker_id = cfg["broker_id"]
if "password" in cfg:
password = cfg["password"]
if "user_id" in cfg:
user_id = cfg["user_id"]
if "market_front" in cfg:
market_front = cfg["market_front"]
if instrument_ids is None:
self.logger.warning("没有初始化订阅的合约品种,将采用默认品种作为演示:")
instrument_ids = list(pandas.DataFrame.from_csv(
os.getcwd() + "/data/instruments.csv"
).index)
self.logger.info("订阅品种:{}".format(instrument_ids))
if (broker_id is None) or (user_id is None) or (password is None) \
or (market_front is None):
self.logger.error("CTP连接信息不完整")
sys.exit(0)
self.broker_id = broker_id.encode()
self.user_id = user_id.encode()
self.password = password.encode()
self.instrument_ids = list()
<|code_end|>
, determine the next line of code. You have imports:
import hashlib
import os
import sys
import tempfile
import time
import dHydra.core.util as util
import threading
import pandas
import sys
from dHydra.core.Vendor import Vendor
from ctp.futures import ApiStruct, MdApi
and context (class names, function names, or code) available:
# Path: dHydra/core/Vendor.py
# class Vendor:
#
# def __init__(
# self,
# log_path="log", #
# console_log=True, # 屏幕打印日志开关,默认True
# console_log_level=logging.INFO, # 屏幕打印日志的级别,默认为INFO
# critical_log=False, # critica单独l写文件日志,默认关闭
# error_log=True, # error级别单独写文件日志,默认开启
# warning_log=False, # warning级别单独写日志,默认关闭
# info_log=True, # info级别单独写日志,默认开启
# debug_log=False, # debug级别日志,默认关闭
# **kwargs
# ):
# self.logger = util.get_logger(
# log_path=log_path, #
# console_log=console_log, # 屏幕打印日志开关,默认True
# console_log_level=console_log_level, # 屏幕打印日志的级别,默认为INFO
# critical_log=critical_log, # critica单独l写文件日志,默认关闭
# error_log=error_log, # error级别单独写文件日志,默认开启
# warning_log=warning_log, # warning级别单独写日志,默认关闭
# info_log=info_log, # info级别单独写日志,默认开启
# debug_log=debug_log, # debug级别日志,默认关闭
# logger_name=self.__class__.__name__,
# )
. Output only the next line. | self.market_front = market_front.encode() |
Given the code snippet: <|code_start|> ]
for s in shutdown_signals:
if hasattr(signal, s):
signal.signal(
getattr(signal, s, None),
__on_termination__
)
def start_worker(worker_name, **kwargs):
worker = get_worker_class(worker_name=worker_name, **kwargs)
worker_dict[worker.nickname] = worker
worker.start()
def terminate_worker(nickname=None, pid=None):
logger.info("{}".format(worker_dict))
if pid is None:
pid = get_pid_by_nickname(redis_cli=__redis__, nickname=nickname)
os.kill(pid, signal.SIGTERM)
i = 0
while worker_dict[nickname]._popen is None and i < 30:
time.sleep(0.1)
i += 1
worker_dict[nickname]._popen.wait(1)
worker_dict.pop(nickname)
def get_workers_info(
redis_cli=None,
<|code_end|>
, generate the next line using the imports in this file:
from dHydra.console import logger, get_worker_class
from dHydra.core.Functions import get_vendor
import click
import multiprocessing
import time
import os
import json
import traceback
import sys
import pickle
import signal
import signal
import sys
import threading
import time
import dHydra.web
and context (functions, classes, or occasionally code) from other files:
# Path: dHydra/console.py
# def init_logger():
# def start(worker_name=None, nickname=None):
# def terminate(nickname=None):
# def start_worker(worker_name=None, nickname=None, **kwargs):
# def stop_worker(nickname=None):
# def send_command(
# channel_name="dHydra.Command",
# command_type="sys",
# operation_name=None,
# token=None,
# kwargs={}
# ):
#
# Path: dHydra/core/Functions.py
# def get_vendor(name, vendor_name=None, **kwargs):
# """
# get_vendor方法,动态加载vendor类
# """
# logger = logging.getLogger('Functions')
# if vendor_name is None:
# vendor_name = "V-" + name
# class_name = name
# module_name = 'Vendor.' + name + '.' + class_name
# if os.path.exists(
# os.getcwd() + "/Vendor/" +
# name + "/" + class_name + ".py"
# ):
# try:
# instance = getattr(
# __import__(module_name, globals(), locals(), [class_name], 0),
# class_name
# )(**kwargs)
# except ImportError:
# traceback.print_exc()
# else:
# try:
# instance = getattr(
# __import__(
# "dHydra." + module_name,
# globals(),
# locals(),
# [class_name],
# 0
# ),
# class_name
# )(**kwargs)
# except ImportError:
# traceback.print_exc()
# return instance
. Output only the next line. | by="nickname", |
Given the code snippet: <|code_start|> "SIGTERM", # kill 命令
]
for s in shutdown_signals:
if hasattr(signal, s):
signal.signal(
getattr(signal, s, None),
__on_termination__
)
def start_worker(worker_name, **kwargs):
worker = get_worker_class(worker_name=worker_name, **kwargs)
worker_dict[worker.nickname] = worker
worker.start()
def terminate_worker(nickname=None, pid=None):
logger.info("{}".format(worker_dict))
if pid is None:
pid = get_pid_by_nickname(redis_cli=__redis__, nickname=nickname)
os.kill(pid, signal.SIGTERM)
i = 0
while worker_dict[nickname]._popen is None and i < 30:
time.sleep(0.1)
i += 1
worker_dict[nickname]._popen.wait(1)
worker_dict.pop(nickname)
def get_workers_info(
<|code_end|>
, generate the next line using the imports in this file:
from dHydra.console import logger, get_worker_class
from dHydra.core.Functions import get_vendor
import click
import multiprocessing
import time
import os
import json
import traceback
import sys
import pickle
import signal
import signal
import sys
import threading
import time
import dHydra.web
and context (functions, classes, or occasionally code) from other files:
# Path: dHydra/console.py
# def init_logger():
# def start(worker_name=None, nickname=None):
# def terminate(nickname=None):
# def start_worker(worker_name=None, nickname=None, **kwargs):
# def stop_worker(nickname=None):
# def send_command(
# channel_name="dHydra.Command",
# command_type="sys",
# operation_name=None,
# token=None,
# kwargs={}
# ):
#
# Path: dHydra/core/Functions.py
# def get_vendor(name, vendor_name=None, **kwargs):
# """
# get_vendor方法,动态加载vendor类
# """
# logger = logging.getLogger('Functions')
# if vendor_name is None:
# vendor_name = "V-" + name
# class_name = name
# module_name = 'Vendor.' + name + '.' + class_name
# if os.path.exists(
# os.getcwd() + "/Vendor/" +
# name + "/" + class_name + ".py"
# ):
# try:
# instance = getattr(
# __import__(module_name, globals(), locals(), [class_name], 0),
# class_name
# )(**kwargs)
# except ImportError:
# traceback.print_exc()
# else:
# try:
# instance = getattr(
# __import__(
# "dHydra." + module_name,
# globals(),
# locals(),
# [class_name],
# 0
# ),
# class_name
# )(**kwargs)
# except ImportError:
# traceback.print_exc()
# return instance
. Output only the next line. | redis_cli=None, |
Next line prediction: <|code_start|> if hasattr(signal, s):
signal.signal(
getattr(signal, s, None),
__on_termination__
)
def start_worker(worker_name, **kwargs):
worker = get_worker_class(worker_name=worker_name, **kwargs)
worker_dict[worker.nickname] = worker
worker.start()
def terminate_worker(nickname=None, pid=None):
logger.info("{}".format(worker_dict))
if pid is None:
pid = get_pid_by_nickname(redis_cli=__redis__, nickname=nickname)
os.kill(pid, signal.SIGTERM)
i = 0
while worker_dict[nickname]._popen is None and i < 30:
time.sleep(0.1)
i += 1
worker_dict[nickname]._popen.wait(1)
worker_dict.pop(nickname)
def get_workers_info(
redis_cli=None,
by="nickname",
nickname=None,
<|code_end|>
. Use current file imports:
(from dHydra.console import logger, get_worker_class
from dHydra.core.Functions import get_vendor
import click
import multiprocessing
import time
import os
import json
import traceback
import sys
import pickle
import signal
import signal
import sys
import threading
import time
import dHydra.web)
and context including class names, function names, or small code snippets from other files:
# Path: dHydra/console.py
# def init_logger():
# def start(worker_name=None, nickname=None):
# def terminate(nickname=None):
# def start_worker(worker_name=None, nickname=None, **kwargs):
# def stop_worker(nickname=None):
# def send_command(
# channel_name="dHydra.Command",
# command_type="sys",
# operation_name=None,
# token=None,
# kwargs={}
# ):
#
# Path: dHydra/core/Functions.py
# def get_vendor(name, vendor_name=None, **kwargs):
# """
# get_vendor方法,动态加载vendor类
# """
# logger = logging.getLogger('Functions')
# if vendor_name is None:
# vendor_name = "V-" + name
# class_name = name
# module_name = 'Vendor.' + name + '.' + class_name
# if os.path.exists(
# os.getcwd() + "/Vendor/" +
# name + "/" + class_name + ".py"
# ):
# try:
# instance = getattr(
# __import__(module_name, globals(), locals(), [class_name], 0),
# class_name
# )(**kwargs)
# except ImportError:
# traceback.print_exc()
# else:
# try:
# instance = getattr(
# __import__(
# "dHydra." + module_name,
# globals(),
# locals(),
# [class_name],
# 0
# ),
# class_name
# )(**kwargs)
# except ImportError:
# traceback.print_exc()
# return instance
. Output only the next line. | worker_name=None, |
Given snippet: <|code_start|>#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class WrongException(exception.BrickException):
pass
class TestRetryDecorator(base.TestCase):
def test_no_retry_required(self):
self.counter = 0
with mock.patch.object(utils, '_time_sleep') as mock_sleep:
@utils.retry(exception.VolumeDeviceNotFound,
interval=2,
retries=3,
backoff_rate=2)
def succeeds():
self.counter += 1
return 'success'
ret = succeeds()
self.assertFalse(mock_sleep.called)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import functools
import time
from unittest import mock
from os_brick import exception
from os_brick.tests import base
from os_brick import utils
and context:
# Path: os_brick/exception.py
# LOG = logging.getLogger(__name__)
# class BrickException(Exception):
# class NotFound(BrickException):
# class Invalid(BrickException):
# class InvalidParameterValue(Invalid):
# class NoFibreChannelHostsFound(BrickException):
# class NoFibreChannelVolumeDeviceFound(BrickException):
# class VolumeNotDeactivated(BrickException):
# class VolumeDeviceNotFound(BrickException):
# class VolumePathsNotFound(BrickException):
# class VolumePathNotRemoved(BrickException):
# class ProtocolNotSupported(BrickException):
# class TargetPortalNotFound(BrickException):
# class TargetPortalsNotFound(TargetPortalNotFound):
# class FailedISCSITargetPortalLogin(BrickException):
# class BlockDeviceReadOnly(BrickException):
# class VolumeGroupNotFound(BrickException):
# class VolumeGroupCreationFailed(BrickException):
# class CommandExecutionFailed(BrickException):
# class VolumeDriverException(BrickException):
# class InvalidIOHandleObject(BrickException):
# class VolumeEncryptionNotSupported(Invalid):
# class VolumeLocalCacheNotSupported(Invalid):
# class InvalidConnectorProtocol(ValueError):
# class ExceptionChainer(BrickException):
# class ExecutionTimeout(putils.ProcessExecutionError):
# def __init__(self, message=None, **kwargs):
# def __init__(self, *args, **kwargs):
# def __repr__(self):
# def __nonzero__(self) -> bool:
# def add_exception(self, exc_type, exc_val, exc_tb) -> None:
# def context(self,
# catch_exception: bool,
# msg: str = '',
# *msg_args: Iterable):
# def __enter__(self):
# def __exit__(self, exc_type, exc_val, exc_tb):
#
# Path: os_brick/tests/base.py
# class TestCase(testtools.TestCase):
# SENTINEL = object()
# def setUp(self):
# def _common_cleanup(self):
# def log_level(self, level):
# def mock_object(self, obj, attr_name, new_attr=SENTINEL, **kwargs):
# def patch(self, path, *args, **kwargs):
#
# Path: os_brick/utils.py
# def _sleep(secs: float) -> None:
# def __init__(self, codes: Union[int, Tuple[int, ...]]):
# def _check_exit_code(self, exc: Type[Exception]) -> bool:
# def retry(retry_param: Union[None,
# Type[Exception],
# Tuple[Type[Exception], ...],
# int,
# Tuple[int, ...]],
# interval: float = 1,
# retries: int = 3,
# backoff_rate: float = 2,
# retry: Callable = tenacity.retry_if_exception_type) -> Callable:
# def _decorator(f):
# def _wrapper(*args, **kwargs):
# def platform_matches(current_platform: str, connector_platform: str) -> bool:
# def os_matches(current_os: str, connector_os: str) -> bool:
# def merge_dict(dict1: dict, dict2: dict) -> dict:
# def trace(f: Callable) -> Callable:
# def trace_logging_wrapper(*args, **kwargs):
# def convert_str(text: Union[bytes, str]) -> str:
# def get_host_nqn():
# LOG = logging.getLogger(__name__)
# class retry_if_exit_code(tenacity.retry_if_exception):
which might include code, classes, or functions. Output only the next line. | self.assertEqual('success', ret) |
Given snippet: <|code_start|># (c) Copyright 2015 Hewlett-Packard Development Company, L.P.
#
# 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 WrongException(exception.BrickException):
pass
class TestRetryDecorator(base.TestCase):
def test_no_retry_required(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import functools
import time
from unittest import mock
from os_brick import exception
from os_brick.tests import base
from os_brick import utils
and context:
# Path: os_brick/exception.py
# LOG = logging.getLogger(__name__)
# class BrickException(Exception):
# class NotFound(BrickException):
# class Invalid(BrickException):
# class InvalidParameterValue(Invalid):
# class NoFibreChannelHostsFound(BrickException):
# class NoFibreChannelVolumeDeviceFound(BrickException):
# class VolumeNotDeactivated(BrickException):
# class VolumeDeviceNotFound(BrickException):
# class VolumePathsNotFound(BrickException):
# class VolumePathNotRemoved(BrickException):
# class ProtocolNotSupported(BrickException):
# class TargetPortalNotFound(BrickException):
# class TargetPortalsNotFound(TargetPortalNotFound):
# class FailedISCSITargetPortalLogin(BrickException):
# class BlockDeviceReadOnly(BrickException):
# class VolumeGroupNotFound(BrickException):
# class VolumeGroupCreationFailed(BrickException):
# class CommandExecutionFailed(BrickException):
# class VolumeDriverException(BrickException):
# class InvalidIOHandleObject(BrickException):
# class VolumeEncryptionNotSupported(Invalid):
# class VolumeLocalCacheNotSupported(Invalid):
# class InvalidConnectorProtocol(ValueError):
# class ExceptionChainer(BrickException):
# class ExecutionTimeout(putils.ProcessExecutionError):
# def __init__(self, message=None, **kwargs):
# def __init__(self, *args, **kwargs):
# def __repr__(self):
# def __nonzero__(self) -> bool:
# def add_exception(self, exc_type, exc_val, exc_tb) -> None:
# def context(self,
# catch_exception: bool,
# msg: str = '',
# *msg_args: Iterable):
# def __enter__(self):
# def __exit__(self, exc_type, exc_val, exc_tb):
#
# Path: os_brick/tests/base.py
# class TestCase(testtools.TestCase):
# SENTINEL = object()
# def setUp(self):
# def _common_cleanup(self):
# def log_level(self, level):
# def mock_object(self, obj, attr_name, new_attr=SENTINEL, **kwargs):
# def patch(self, path, *args, **kwargs):
#
# Path: os_brick/utils.py
# def _sleep(secs: float) -> None:
# def __init__(self, codes: Union[int, Tuple[int, ...]]):
# def _check_exit_code(self, exc: Type[Exception]) -> bool:
# def retry(retry_param: Union[None,
# Type[Exception],
# Tuple[Type[Exception], ...],
# int,
# Tuple[int, ...]],
# interval: float = 1,
# retries: int = 3,
# backoff_rate: float = 2,
# retry: Callable = tenacity.retry_if_exception_type) -> Callable:
# def _decorator(f):
# def _wrapper(*args, **kwargs):
# def platform_matches(current_platform: str, connector_platform: str) -> bool:
# def os_matches(current_os: str, connector_os: str) -> bool:
# def merge_dict(dict1: dict, dict2: dict) -> dict:
# def trace(f: Callable) -> Callable:
# def trace_logging_wrapper(*args, **kwargs):
# def convert_str(text: Union[bytes, str]) -> str:
# def get_host_nqn():
# LOG = logging.getLogger(__name__)
# class retry_if_exit_code(tenacity.retry_if_exception):
which might include code, classes, or functions. Output only the next line. | self.counter = 0 |
Given the following code snippet before the placeholder: <|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 WrongException(exception.BrickException):
pass
class TestRetryDecorator(base.TestCase):
def test_no_retry_required(self):
self.counter = 0
with mock.patch.object(utils, '_time_sleep') as mock_sleep:
@utils.retry(exception.VolumeDeviceNotFound,
interval=2,
retries=3,
backoff_rate=2)
def succeeds():
self.counter += 1
return 'success'
<|code_end|>
, predict the next line using imports from the current file:
import functools
import time
from unittest import mock
from os_brick import exception
from os_brick.tests import base
from os_brick import utils
and context including class names, function names, and sometimes code from other files:
# Path: os_brick/exception.py
# LOG = logging.getLogger(__name__)
# class BrickException(Exception):
# class NotFound(BrickException):
# class Invalid(BrickException):
# class InvalidParameterValue(Invalid):
# class NoFibreChannelHostsFound(BrickException):
# class NoFibreChannelVolumeDeviceFound(BrickException):
# class VolumeNotDeactivated(BrickException):
# class VolumeDeviceNotFound(BrickException):
# class VolumePathsNotFound(BrickException):
# class VolumePathNotRemoved(BrickException):
# class ProtocolNotSupported(BrickException):
# class TargetPortalNotFound(BrickException):
# class TargetPortalsNotFound(TargetPortalNotFound):
# class FailedISCSITargetPortalLogin(BrickException):
# class BlockDeviceReadOnly(BrickException):
# class VolumeGroupNotFound(BrickException):
# class VolumeGroupCreationFailed(BrickException):
# class CommandExecutionFailed(BrickException):
# class VolumeDriverException(BrickException):
# class InvalidIOHandleObject(BrickException):
# class VolumeEncryptionNotSupported(Invalid):
# class VolumeLocalCacheNotSupported(Invalid):
# class InvalidConnectorProtocol(ValueError):
# class ExceptionChainer(BrickException):
# class ExecutionTimeout(putils.ProcessExecutionError):
# def __init__(self, message=None, **kwargs):
# def __init__(self, *args, **kwargs):
# def __repr__(self):
# def __nonzero__(self) -> bool:
# def add_exception(self, exc_type, exc_val, exc_tb) -> None:
# def context(self,
# catch_exception: bool,
# msg: str = '',
# *msg_args: Iterable):
# def __enter__(self):
# def __exit__(self, exc_type, exc_val, exc_tb):
#
# Path: os_brick/tests/base.py
# class TestCase(testtools.TestCase):
# SENTINEL = object()
# def setUp(self):
# def _common_cleanup(self):
# def log_level(self, level):
# def mock_object(self, obj, attr_name, new_attr=SENTINEL, **kwargs):
# def patch(self, path, *args, **kwargs):
#
# Path: os_brick/utils.py
# def _sleep(secs: float) -> None:
# def __init__(self, codes: Union[int, Tuple[int, ...]]):
# def _check_exit_code(self, exc: Type[Exception]) -> bool:
# def retry(retry_param: Union[None,
# Type[Exception],
# Tuple[Type[Exception], ...],
# int,
# Tuple[int, ...]],
# interval: float = 1,
# retries: int = 3,
# backoff_rate: float = 2,
# retry: Callable = tenacity.retry_if_exception_type) -> Callable:
# def _decorator(f):
# def _wrapper(*args, **kwargs):
# def platform_matches(current_platform: str, connector_platform: str) -> bool:
# def os_matches(current_os: str, connector_os: str) -> bool:
# def merge_dict(dict1: dict, dict2: dict) -> dict:
# def trace(f: Callable) -> Callable:
# def trace_logging_wrapper(*args, **kwargs):
# def convert_str(text: Union[bytes, str]) -> str:
# def get_host_nqn():
# LOG = logging.getLogger(__name__)
# class retry_if_exit_code(tenacity.retry_if_exception):
. Output only the next line. | ret = succeeds() |
Next line prediction: <|code_start|>
def test_fake_execute(self):
mock_execute = mock.Mock()
executor = brick_executor.Executor(root_helper=None,
execute=mock_execute)
self.assertEqual(mock_execute, executor._Executor__execute)
@mock.patch('sys.stdin', encoding='UTF-8')
@mock.patch('os_brick.executor.priv_rootwrap.execute')
def test_execute_non_safe_str_exception(self, execute_mock, stdin_mock):
execute_mock.side_effect = putils.ProcessExecutionError(
stdout='España', stderr='Zürich')
executor = brick_executor.Executor(root_helper=None)
exc = self.assertRaises(putils.ProcessExecutionError,
executor._execute)
self.assertEqual('Espa\xf1a', exc.stdout)
self.assertEqual('Z\xfcrich', exc.stderr)
@mock.patch('sys.stdin', encoding='UTF-8')
@mock.patch('os_brick.executor.priv_rootwrap.execute')
def test_execute_non_safe_str(self, execute_mock, stdin_mock):
execute_mock.return_value = ('España', 'Zürich')
executor = brick_executor.Executor(root_helper=None)
stdout, stderr = executor._execute()
self.assertEqual('Espa\xf1a', stdout)
self.assertEqual('Z\xfcrich', stderr)
@mock.patch('sys.stdin', encoding='UTF-8')
<|code_end|>
. Use current file imports:
(import threading
from unittest import mock
from oslo_concurrency import processutils as putils
from oslo_context import context as context_utils
from os_brick import executor as brick_executor
from os_brick.privileged import rootwrap
from os_brick.tests import base)
and context including class names, function names, or small code snippets from other files:
# Path: os_brick/executor.py
# class Executor(object):
# class Thread(threading.Thread):
# def __init__(self, root_helper, execute=None,
# *args, **kwargs):
# def safe_decode(string):
# def make_putils_error_safe(cls, exc):
# def _execute(self, *args, **kwargs) -> Tuple[str, str]:
# def set_execute(self, execute):
# def set_root_helper(self, helper):
# def __init__(self, *args, **kwargs):
# def run(self):
#
# Path: os_brick/privileged/rootwrap.py
# LOG = logging.getLogger(__name__)
# def custom_execute(*cmd, **kwargs):
# def on_timeout(proc):
# def on_execute(proc):
# def on_completion(proc):
# def execute(*cmd, **kwargs):
# def execute_root(*cmd, **kwargs):
# def unlink_root(*links, **kwargs):
#
# Path: os_brick/tests/base.py
# class TestCase(testtools.TestCase):
# SENTINEL = object()
# def setUp(self):
# def _common_cleanup(self):
# def log_level(self, level):
# def mock_object(self, obj, attr_name, new_attr=SENTINEL, **kwargs):
# def patch(self, path, *args, **kwargs):
. Output only the next line. | @mock.patch('os_brick.executor.priv_rootwrap.execute') |
Predict the next line after this snippet: <|code_start|> @mock.patch('os_brick.executor.priv_rootwrap.execute')
def test_execute_non_safe_str_exception(self, execute_mock, stdin_mock):
execute_mock.side_effect = putils.ProcessExecutionError(
stdout='España', stderr='Zürich')
executor = brick_executor.Executor(root_helper=None)
exc = self.assertRaises(putils.ProcessExecutionError,
executor._execute)
self.assertEqual('Espa\xf1a', exc.stdout)
self.assertEqual('Z\xfcrich', exc.stderr)
@mock.patch('sys.stdin', encoding='UTF-8')
@mock.patch('os_brick.executor.priv_rootwrap.execute')
def test_execute_non_safe_str(self, execute_mock, stdin_mock):
execute_mock.return_value = ('España', 'Zürich')
executor = brick_executor.Executor(root_helper=None)
stdout, stderr = executor._execute()
self.assertEqual('Espa\xf1a', stdout)
self.assertEqual('Z\xfcrich', stderr)
@mock.patch('sys.stdin', encoding='UTF-8')
@mock.patch('os_brick.executor.priv_rootwrap.execute')
def test_execute_non_safe_bytes_exception(self, execute_mock, stdin_mock):
execute_mock.side_effect = putils.ProcessExecutionError(
stdout=bytes('España', 'utf-8'),
stderr=bytes('Zürich', 'utf-8'))
executor = brick_executor.Executor(root_helper=None)
exc = self.assertRaises(putils.ProcessExecutionError,
<|code_end|>
using the current file's imports:
import threading
from unittest import mock
from oslo_concurrency import processutils as putils
from oslo_context import context as context_utils
from os_brick import executor as brick_executor
from os_brick.privileged import rootwrap
from os_brick.tests import base
and any relevant context from other files:
# Path: os_brick/executor.py
# class Executor(object):
# class Thread(threading.Thread):
# def __init__(self, root_helper, execute=None,
# *args, **kwargs):
# def safe_decode(string):
# def make_putils_error_safe(cls, exc):
# def _execute(self, *args, **kwargs) -> Tuple[str, str]:
# def set_execute(self, execute):
# def set_root_helper(self, helper):
# def __init__(self, *args, **kwargs):
# def run(self):
#
# Path: os_brick/privileged/rootwrap.py
# LOG = logging.getLogger(__name__)
# def custom_execute(*cmd, **kwargs):
# def on_timeout(proc):
# def on_execute(proc):
# def on_completion(proc):
# def execute(*cmd, **kwargs):
# def execute_root(*cmd, **kwargs):
# def unlink_root(*links, **kwargs):
#
# Path: os_brick/tests/base.py
# class TestCase(testtools.TestCase):
# SENTINEL = object()
# def setUp(self):
# def _common_cleanup(self):
# def log_level(self, level):
# def mock_object(self, obj, attr_name, new_attr=SENTINEL, **kwargs):
# def patch(self, path, *args, **kwargs):
. Output only the next line. | executor._execute) |
Next line prediction: <|code_start|>
executor = brick_executor.Executor(root_helper=None)
exc = self.assertRaises(putils.ProcessExecutionError,
executor._execute)
self.assertEqual('Espa\xf1a', exc.stdout)
self.assertEqual('Z\xfcrich', exc.stderr)
@mock.patch('sys.stdin', encoding='UTF-8')
@mock.patch('os_brick.executor.priv_rootwrap.execute')
def test_execute_non_safe_str(self, execute_mock, stdin_mock):
execute_mock.return_value = ('España', 'Zürich')
executor = brick_executor.Executor(root_helper=None)
stdout, stderr = executor._execute()
self.assertEqual('Espa\xf1a', stdout)
self.assertEqual('Z\xfcrich', stderr)
@mock.patch('sys.stdin', encoding='UTF-8')
@mock.patch('os_brick.executor.priv_rootwrap.execute')
def test_execute_non_safe_bytes_exception(self, execute_mock, stdin_mock):
execute_mock.side_effect = putils.ProcessExecutionError(
stdout=bytes('España', 'utf-8'),
stderr=bytes('Zürich', 'utf-8'))
executor = brick_executor.Executor(root_helper=None)
exc = self.assertRaises(putils.ProcessExecutionError,
executor._execute)
self.assertEqual('Espa\xf1a', exc.stdout)
self.assertEqual('Z\xfcrich', exc.stderr)
<|code_end|>
. Use current file imports:
(import threading
from unittest import mock
from oslo_concurrency import processutils as putils
from oslo_context import context as context_utils
from os_brick import executor as brick_executor
from os_brick.privileged import rootwrap
from os_brick.tests import base)
and context including class names, function names, or small code snippets from other files:
# Path: os_brick/executor.py
# class Executor(object):
# class Thread(threading.Thread):
# def __init__(self, root_helper, execute=None,
# *args, **kwargs):
# def safe_decode(string):
# def make_putils_error_safe(cls, exc):
# def _execute(self, *args, **kwargs) -> Tuple[str, str]:
# def set_execute(self, execute):
# def set_root_helper(self, helper):
# def __init__(self, *args, **kwargs):
# def run(self):
#
# Path: os_brick/privileged/rootwrap.py
# LOG = logging.getLogger(__name__)
# def custom_execute(*cmd, **kwargs):
# def on_timeout(proc):
# def on_execute(proc):
# def on_completion(proc):
# def execute(*cmd, **kwargs):
# def execute_root(*cmd, **kwargs):
# def unlink_root(*links, **kwargs):
#
# Path: os_brick/tests/base.py
# class TestCase(testtools.TestCase):
# SENTINEL = object()
# def setUp(self):
# def _common_cleanup(self):
# def log_level(self, level):
# def mock_object(self, obj, attr_name, new_attr=SENTINEL, **kwargs):
# def patch(self, path, *args, **kwargs):
. Output only the next line. | @mock.patch('sys.stdin', encoding='UTF-8') |
Given the following code snippet before the placeholder: <|code_start|> mock.call('cryptsetup', 'isLuks', '--verbose', self.dev_path,
root_helper=self.root_helper,
run_as_root=True, check_exit_code=True),
], any_order=False)
@mock.patch('os_brick.executor.Executor._execute')
def test__close_volume(self, mock_execute):
self.encryptor.detach_volume()
mock_execute.assert_has_calls([
mock.call('cryptsetup', 'luksClose', self.dev_name,
root_helper=self.root_helper,
attempts=3, run_as_root=True, check_exit_code=[0, 4]),
])
@mock.patch('os_brick.executor.Executor._execute')
def test_detach_volume(self, mock_execute):
self.encryptor.detach_volume()
mock_execute.assert_has_calls([
mock.call('cryptsetup', 'luksClose', self.dev_name,
root_helper=self.root_helper,
attempts=3, run_as_root=True, check_exit_code=[0, 4]),
])
class Luks2EncryptorTestCase(LuksEncryptorTestCase):
def _create(self):
return luks.Luks2Encryptor(root_helper=self.root_helper,
connection_info=self.connection_info,
<|code_end|>
, predict the next line using imports from the current file:
from unittest import mock
from oslo_concurrency import processutils as putils
from os_brick.encryptors import luks
from os_brick.tests.encryptors import test_cryptsetup
and context including class names, function names, and sometimes code from other files:
# Path: os_brick/encryptors/luks.py
# LOG = logging.getLogger(__name__)
# def is_luks(root_helper, device, execute=None):
# def __init__(self, root_helper,
# connection_info,
# keymgr,
# execute=None,
# *args, **kwargs):
# def _format_volume(self, passphrase, **kwargs):
# def _format_luks_volume(self, passphrase, version, **kwargs):
# def _open_volume(self, passphrase, **kwargs):
# def attach_volume(self, context, **kwargs):
# def _close_volume(self, **kwargs):
# def __init__(self, root_helper,
# connection_info,
# keymgr,
# execute=None,
# *args, **kwargs):
# def _format_volume(self, passphrase, **kwargs):
# class LuksEncryptor(cryptsetup.CryptsetupEncryptor):
# class Luks2Encryptor(LuksEncryptor):
#
# Path: os_brick/tests/encryptors/test_cryptsetup.py
# def fake__get_key(context, passphrase):
# def _create(self, mock_exists):
# def setUp(self):
# def test__open_volume(self, mock_execute):
# def test_attach_volume(self, mock_execute):
# def test__close_volume(self, mock_execute):
# def test_detach_volume(self, mock_execute):
# def test_init_volume_encryption_not_supported(self):
# def test_init_volume_encryption_with_old_name(self, mock_exists,
# mock_execute):
# def test_init_volume_encryption_with_wwn(self, mock_exists, mock_execute):
# class CryptsetupEncryptorTestCase(test_base.VolumeEncryptorTestCase):
. Output only the next line. | keymgr=self.keymgr) |
Given the following code snippet before the placeholder: <|code_start|> run_as_root=True, check_exit_code=True, attempts=3),
])
@mock.patch('os_brick.executor.Executor._execute')
def test__open_volume(self, mock_execute):
self.encryptor._open_volume("passphrase")
mock_execute.assert_has_calls([
mock.call('cryptsetup', 'luksOpen', '--key-file=-', self.dev_path,
self.dev_name, process_input='passphrase',
root_helper=self.root_helper,
run_as_root=True, check_exit_code=True),
])
@mock.patch('os_brick.executor.Executor._execute')
def test_attach_volume(self, mock_execute):
fake_key = '0c84146034e747639b698368807286df'
self.encryptor._get_key = mock.MagicMock()
self.encryptor._get_key.return_value = (
test_cryptsetup.fake__get_key(None, fake_key))
self.encryptor.attach_volume(None)
mock_execute.assert_has_calls([
mock.call('cryptsetup', 'luksOpen', '--key-file=-', self.dev_path,
self.dev_name, process_input=fake_key,
root_helper=self.root_helper,
run_as_root=True, check_exit_code=True),
mock.call('ln', '--symbolic', '--force',
'/dev/mapper/%s' % self.dev_name, self.symlink_path,
<|code_end|>
, predict the next line using imports from the current file:
from unittest import mock
from oslo_concurrency import processutils as putils
from os_brick.encryptors import luks
from os_brick.tests.encryptors import test_cryptsetup
and context including class names, function names, and sometimes code from other files:
# Path: os_brick/encryptors/luks.py
# LOG = logging.getLogger(__name__)
# def is_luks(root_helper, device, execute=None):
# def __init__(self, root_helper,
# connection_info,
# keymgr,
# execute=None,
# *args, **kwargs):
# def _format_volume(self, passphrase, **kwargs):
# def _format_luks_volume(self, passphrase, version, **kwargs):
# def _open_volume(self, passphrase, **kwargs):
# def attach_volume(self, context, **kwargs):
# def _close_volume(self, **kwargs):
# def __init__(self, root_helper,
# connection_info,
# keymgr,
# execute=None,
# *args, **kwargs):
# def _format_volume(self, passphrase, **kwargs):
# class LuksEncryptor(cryptsetup.CryptsetupEncryptor):
# class Luks2Encryptor(LuksEncryptor):
#
# Path: os_brick/tests/encryptors/test_cryptsetup.py
# def fake__get_key(context, passphrase):
# def _create(self, mock_exists):
# def setUp(self):
# def test__open_volume(self, mock_execute):
# def test_attach_volume(self, mock_execute):
# def test__close_volume(self, mock_execute):
# def test_detach_volume(self, mock_execute):
# def test_init_volume_encryption_not_supported(self):
# def test_init_volume_encryption_with_old_name(self, mock_exists,
# mock_execute):
# def test_init_volume_encryption_with_wwn(self, mock_exists, mock_execute):
# class CryptsetupEncryptorTestCase(test_base.VolumeEncryptorTestCase):
. Output only the next line. | root_helper=self.root_helper, |
Using the snippet: <|code_start|> def test_get_volume_paths(self, mock_get_disk_paths_by_scsi_id,
mock_get_fc_mappings,
mock_sleep,
volume_mappings, expected_paths,
scsi_id_side_eff=None,
use_multipath=False,
is_mpio_disk=False):
mock_get_dev_num = self._diskutils.get_device_number_from_device_name
mock_get_fc_mappings.return_value = volume_mappings
mock_get_disk_paths_by_scsi_id.side_effect = scsi_id_side_eff
self._diskutils.is_mpio_disk.return_value = is_mpio_disk
self._connector.use_multipath = use_multipath
vol_paths = self._connector.get_volume_paths(mock.sentinel.conn_props)
self.assertEqual(expected_paths, vol_paths)
# In this test case, either the volume is found after the first
# attempt, either it's not found at all, in which case we'd expect
# the number of retries to be the requested maximum number of rescans.
expected_try_count = (1 if expected_paths
else self._connector.device_scan_attempts)
self._diskutils.rescan_disks.assert_has_calls(
[mock.call()] * expected_try_count)
mock_get_fc_mappings.assert_has_calls(
[mock.call(mock.sentinel.conn_props)] * expected_try_count)
mock_sleep.assert_has_calls(
[mock.call(mock.sentinel.rescan_interval)] *
(expected_try_count - 1))
<|code_end|>
, determine the next line of code. You have imports:
from unittest import mock
from os_win import exceptions as os_win_exc
from os_brick import exception
from os_brick.initiator.windows import fibre_channel as fc
from os_brick.tests.windows import test_base
import ddt
and context (class names, function names, or code) available:
# Path: os_brick/exception.py
# LOG = logging.getLogger(__name__)
# class BrickException(Exception):
# class NotFound(BrickException):
# class Invalid(BrickException):
# class InvalidParameterValue(Invalid):
# class NoFibreChannelHostsFound(BrickException):
# class NoFibreChannelVolumeDeviceFound(BrickException):
# class VolumeNotDeactivated(BrickException):
# class VolumeDeviceNotFound(BrickException):
# class VolumePathsNotFound(BrickException):
# class VolumePathNotRemoved(BrickException):
# class ProtocolNotSupported(BrickException):
# class TargetPortalNotFound(BrickException):
# class TargetPortalsNotFound(TargetPortalNotFound):
# class FailedISCSITargetPortalLogin(BrickException):
# class BlockDeviceReadOnly(BrickException):
# class VolumeGroupNotFound(BrickException):
# class VolumeGroupCreationFailed(BrickException):
# class CommandExecutionFailed(BrickException):
# class VolumeDriverException(BrickException):
# class InvalidIOHandleObject(BrickException):
# class VolumeEncryptionNotSupported(Invalid):
# class VolumeLocalCacheNotSupported(Invalid):
# class InvalidConnectorProtocol(ValueError):
# class ExceptionChainer(BrickException):
# class ExecutionTimeout(putils.ProcessExecutionError):
# def __init__(self, message=None, **kwargs):
# def __init__(self, *args, **kwargs):
# def __repr__(self):
# def __nonzero__(self) -> bool:
# def add_exception(self, exc_type, exc_val, exc_tb) -> None:
# def context(self,
# catch_exception: bool,
# msg: str = '',
# *msg_args: Iterable):
# def __enter__(self):
# def __exit__(self, exc_type, exc_val, exc_tb):
#
# Path: os_brick/initiator/windows/fibre_channel.py
# LOG = logging.getLogger(__name__)
# class WindowsFCConnector(win_conn_base.BaseWindowsConnector):
# def __init__(self, *args, **kwargs):
# def get_connector_properties(*args, **kwargs):
# def connect_volume(self, connection_properties):
# def get_volume_paths(self, connection_properties):
# def _get_fc_volume_mappings(self, connection_properties):
# def _get_fc_hba_mappings(self):
# def _get_disk_paths_by_scsi_id(self, connection_properties, fcp_lun):
# def _get_dev_nums_by_scsi_id(self, local_port_wwn, remote_port_wwn,
# fcp_lun):
# def _get_fc_hba_wwn_for_port(self, port_wwn):
# def disconnect_volume(self, connection_properties, device_info=None,
# force=False, ignore_errors=False):
#
# Path: os_brick/tests/windows/test_base.py
# class WindowsConnectorTestBase(base.TestCase):
# def setUp(self):
. Output only the next line. | dev_names = [mapping['device_name'] |
Next line prediction: <|code_start|> fake_init_target_map = {mock.sentinel.local_wwpn: remote_wwpns}
conn_props = dict(initiator_target_map=fake_init_target_map)
mock_get_dev_nums.side_effect = [os_win_exc.FCException,
[mock.sentinel.dev_num]]
mock_get_dev_name = self._diskutils.get_device_name_by_device_number
mock_get_dev_name.return_value = mock.sentinel.dev_name
disk_paths = self._connector._get_disk_paths_by_scsi_id(
conn_props, mock.sentinel.fcp_lun)
self.assertEqual([mock.sentinel.dev_name], disk_paths)
mock_get_dev_nums.assert_has_calls([
mock.call(mock.sentinel.local_wwpn,
remote_wwpn,
mock.sentinel.fcp_lun)
for remote_wwpn in remote_wwpns])
mock_get_dev_name.assert_called_once_with(mock.sentinel.dev_num)
@mock.patch.object(fc.WindowsFCConnector, '_get_fc_hba_wwn_for_port')
def test_get_dev_nums_by_scsi_id(self, mock_get_fc_hba_wwn):
fake_identifier = dict(id=mock.sentinel.id,
type=mock.sentinel.type)
mock_get_fc_hba_wwn.return_value = mock.sentinel.local_wwnn
self._fc_utils.get_scsi_device_identifiers.return_value = [
fake_identifier]
self._diskutils.get_disk_numbers_by_unique_id.return_value = (
mock.sentinel.dev_nums)
<|code_end|>
. Use current file imports:
(from unittest import mock
from os_win import exceptions as os_win_exc
from os_brick import exception
from os_brick.initiator.windows import fibre_channel as fc
from os_brick.tests.windows import test_base
import ddt)
and context including class names, function names, or small code snippets from other files:
# Path: os_brick/exception.py
# LOG = logging.getLogger(__name__)
# class BrickException(Exception):
# class NotFound(BrickException):
# class Invalid(BrickException):
# class InvalidParameterValue(Invalid):
# class NoFibreChannelHostsFound(BrickException):
# class NoFibreChannelVolumeDeviceFound(BrickException):
# class VolumeNotDeactivated(BrickException):
# class VolumeDeviceNotFound(BrickException):
# class VolumePathsNotFound(BrickException):
# class VolumePathNotRemoved(BrickException):
# class ProtocolNotSupported(BrickException):
# class TargetPortalNotFound(BrickException):
# class TargetPortalsNotFound(TargetPortalNotFound):
# class FailedISCSITargetPortalLogin(BrickException):
# class BlockDeviceReadOnly(BrickException):
# class VolumeGroupNotFound(BrickException):
# class VolumeGroupCreationFailed(BrickException):
# class CommandExecutionFailed(BrickException):
# class VolumeDriverException(BrickException):
# class InvalidIOHandleObject(BrickException):
# class VolumeEncryptionNotSupported(Invalid):
# class VolumeLocalCacheNotSupported(Invalid):
# class InvalidConnectorProtocol(ValueError):
# class ExceptionChainer(BrickException):
# class ExecutionTimeout(putils.ProcessExecutionError):
# def __init__(self, message=None, **kwargs):
# def __init__(self, *args, **kwargs):
# def __repr__(self):
# def __nonzero__(self) -> bool:
# def add_exception(self, exc_type, exc_val, exc_tb) -> None:
# def context(self,
# catch_exception: bool,
# msg: str = '',
# *msg_args: Iterable):
# def __enter__(self):
# def __exit__(self, exc_type, exc_val, exc_tb):
#
# Path: os_brick/initiator/windows/fibre_channel.py
# LOG = logging.getLogger(__name__)
# class WindowsFCConnector(win_conn_base.BaseWindowsConnector):
# def __init__(self, *args, **kwargs):
# def get_connector_properties(*args, **kwargs):
# def connect_volume(self, connection_properties):
# def get_volume_paths(self, connection_properties):
# def _get_fc_volume_mappings(self, connection_properties):
# def _get_fc_hba_mappings(self):
# def _get_disk_paths_by_scsi_id(self, connection_properties, fcp_lun):
# def _get_dev_nums_by_scsi_id(self, local_port_wwn, remote_port_wwn,
# fcp_lun):
# def _get_fc_hba_wwn_for_port(self, port_wwn):
# def disconnect_volume(self, connection_properties, device_info=None,
# force=False, ignore_errors=False):
#
# Path: os_brick/tests/windows/test_base.py
# class WindowsConnectorTestBase(base.TestCase):
# def setUp(self):
. Output only the next line. | dev_nums = self._connector._get_dev_nums_by_scsi_id( |
Given the following code snippet before the placeholder: <|code_start|> self.assertEqual([mock.sentinel.dev_name], disk_paths)
mock_get_dev_nums.assert_has_calls([
mock.call(mock.sentinel.local_wwpn,
remote_wwpn,
mock.sentinel.fcp_lun)
for remote_wwpn in remote_wwpns])
mock_get_dev_name.assert_called_once_with(mock.sentinel.dev_num)
@mock.patch.object(fc.WindowsFCConnector, '_get_fc_hba_wwn_for_port')
def test_get_dev_nums_by_scsi_id(self, mock_get_fc_hba_wwn):
fake_identifier = dict(id=mock.sentinel.id,
type=mock.sentinel.type)
mock_get_fc_hba_wwn.return_value = mock.sentinel.local_wwnn
self._fc_utils.get_scsi_device_identifiers.return_value = [
fake_identifier]
self._diskutils.get_disk_numbers_by_unique_id.return_value = (
mock.sentinel.dev_nums)
dev_nums = self._connector._get_dev_nums_by_scsi_id(
mock.sentinel.local_wwpn,
mock.sentinel.remote_wwpn,
mock.sentinel.fcp_lun)
self.assertEqual(mock.sentinel.dev_nums, dev_nums)
mock_get_fc_hba_wwn.assert_called_once_with(mock.sentinel.local_wwpn)
self._fc_utils.get_scsi_device_identifiers.assert_called_once_with(
mock.sentinel.local_wwnn, mock.sentinel.local_wwpn,
mock.sentinel.remote_wwpn, mock.sentinel.fcp_lun)
<|code_end|>
, predict the next line using imports from the current file:
from unittest import mock
from os_win import exceptions as os_win_exc
from os_brick import exception
from os_brick.initiator.windows import fibre_channel as fc
from os_brick.tests.windows import test_base
import ddt
and context including class names, function names, and sometimes code from other files:
# Path: os_brick/exception.py
# LOG = logging.getLogger(__name__)
# class BrickException(Exception):
# class NotFound(BrickException):
# class Invalid(BrickException):
# class InvalidParameterValue(Invalid):
# class NoFibreChannelHostsFound(BrickException):
# class NoFibreChannelVolumeDeviceFound(BrickException):
# class VolumeNotDeactivated(BrickException):
# class VolumeDeviceNotFound(BrickException):
# class VolumePathsNotFound(BrickException):
# class VolumePathNotRemoved(BrickException):
# class ProtocolNotSupported(BrickException):
# class TargetPortalNotFound(BrickException):
# class TargetPortalsNotFound(TargetPortalNotFound):
# class FailedISCSITargetPortalLogin(BrickException):
# class BlockDeviceReadOnly(BrickException):
# class VolumeGroupNotFound(BrickException):
# class VolumeGroupCreationFailed(BrickException):
# class CommandExecutionFailed(BrickException):
# class VolumeDriverException(BrickException):
# class InvalidIOHandleObject(BrickException):
# class VolumeEncryptionNotSupported(Invalid):
# class VolumeLocalCacheNotSupported(Invalid):
# class InvalidConnectorProtocol(ValueError):
# class ExceptionChainer(BrickException):
# class ExecutionTimeout(putils.ProcessExecutionError):
# def __init__(self, message=None, **kwargs):
# def __init__(self, *args, **kwargs):
# def __repr__(self):
# def __nonzero__(self) -> bool:
# def add_exception(self, exc_type, exc_val, exc_tb) -> None:
# def context(self,
# catch_exception: bool,
# msg: str = '',
# *msg_args: Iterable):
# def __enter__(self):
# def __exit__(self, exc_type, exc_val, exc_tb):
#
# Path: os_brick/initiator/windows/fibre_channel.py
# LOG = logging.getLogger(__name__)
# class WindowsFCConnector(win_conn_base.BaseWindowsConnector):
# def __init__(self, *args, **kwargs):
# def get_connector_properties(*args, **kwargs):
# def connect_volume(self, connection_properties):
# def get_volume_paths(self, connection_properties):
# def _get_fc_volume_mappings(self, connection_properties):
# def _get_fc_hba_mappings(self):
# def _get_disk_paths_by_scsi_id(self, connection_properties, fcp_lun):
# def _get_dev_nums_by_scsi_id(self, local_port_wwn, remote_port_wwn,
# fcp_lun):
# def _get_fc_hba_wwn_for_port(self, port_wwn):
# def disconnect_volume(self, connection_properties, device_info=None,
# force=False, ignore_errors=False):
#
# Path: os_brick/tests/windows/test_base.py
# class WindowsConnectorTestBase(base.TestCase):
# def setUp(self):
. Output only the next line. | self._diskutils.get_disk_numbers_by_unique_id.assert_called_once_with( |
Using the snippet: <|code_start|># All Rights Reserved.
#
# 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 BaseISCSIConnector(initiator_connector.InitiatorConnector):
def _iterate_all_targets(self, connection_properties):
for portal, iqn, lun in self._get_all_targets(connection_properties):
props = copy.deepcopy(connection_properties)
props['target_portal'] = portal
props['target_iqn'] = iqn
<|code_end|>
, determine the next line of code. You have imports:
import copy
from os_brick.initiator import initiator_connector
and context (class names, function names, or code) available:
# Path: os_brick/initiator/initiator_connector.py
# class InitiatorConnector(executor.Executor, metaclass=abc.ABCMeta):
# def __init__(self, root_helper, driver=None, execute=None,
# device_scan_attempts=initiator.DEVICE_SCAN_ATTEMPTS_DEFAULT,
# *args, **kwargs):
# def set_driver(self, driver):
# def get_connector_properties(root_helper, *args, **kwargs):
# def check_valid_device(self, path, run_as_root=True):
# def connect_volume(self, connection_properties):
# def disconnect_volume(self, connection_properties, device_info,
# force=False, ignore_errors=False):
# def get_volume_paths(self, connection_properties):
# def get_search_path(self):
# def extend_volume(self, connection_properties):
# def get_all_available_volumes(self, connection_properties=None):
# def check_IO_handle_valid(self, handle, data_type, protocol):
. Output only the next line. | props['target_lun'] = lun |
Here is a snippet: <|code_start|># All Rights Reserved.
#
# 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.
LOG = logging.getLogger(__name__)
class WindowsFCConnector(win_conn_base.BaseWindowsConnector):
def __init__(self, *args, **kwargs):
super(WindowsFCConnector, self).__init__(*args, **kwargs)
self.use_multipath = kwargs.get('use_multipath', False)
self._fc_utils = utilsfactory.get_fc_utils()
@staticmethod
def get_connector_properties(*args, **kwargs):
<|code_end|>
. Write the next line using the current file imports:
import collections
import time
from os_win import exceptions as os_win_exc
from os_win import utilsfactory
from oslo_log import log as logging
from os_brick import exception
from os_brick.i18n import _
from os_brick.initiator.windows import base as win_conn_base
from os_brick import utils
and context from other files:
# Path: os_brick/exception.py
# LOG = logging.getLogger(__name__)
# class BrickException(Exception):
# class NotFound(BrickException):
# class Invalid(BrickException):
# class InvalidParameterValue(Invalid):
# class NoFibreChannelHostsFound(BrickException):
# class NoFibreChannelVolumeDeviceFound(BrickException):
# class VolumeNotDeactivated(BrickException):
# class VolumeDeviceNotFound(BrickException):
# class VolumePathsNotFound(BrickException):
# class VolumePathNotRemoved(BrickException):
# class ProtocolNotSupported(BrickException):
# class TargetPortalNotFound(BrickException):
# class TargetPortalsNotFound(TargetPortalNotFound):
# class FailedISCSITargetPortalLogin(BrickException):
# class BlockDeviceReadOnly(BrickException):
# class VolumeGroupNotFound(BrickException):
# class VolumeGroupCreationFailed(BrickException):
# class CommandExecutionFailed(BrickException):
# class VolumeDriverException(BrickException):
# class InvalidIOHandleObject(BrickException):
# class VolumeEncryptionNotSupported(Invalid):
# class VolumeLocalCacheNotSupported(Invalid):
# class InvalidConnectorProtocol(ValueError):
# class ExceptionChainer(BrickException):
# class ExecutionTimeout(putils.ProcessExecutionError):
# def __init__(self, message=None, **kwargs):
# def __init__(self, *args, **kwargs):
# def __repr__(self):
# def __nonzero__(self) -> bool:
# def add_exception(self, exc_type, exc_val, exc_tb) -> None:
# def context(self,
# catch_exception: bool,
# msg: str = '',
# *msg_args: Iterable):
# def __enter__(self):
# def __exit__(self, exc_type, exc_val, exc_tb):
#
# Path: os_brick/i18n.py
# DOMAIN = 'os-brick'
#
# Path: os_brick/initiator/windows/base.py
# LOG = logging.getLogger(__name__)
# DEFAULT_DEVICE_SCAN_INTERVAL = 2
# class BaseWindowsConnector(initiator_connector.InitiatorConnector):
# def __init__(self, root_helper=None, *args, **kwargs):
# def check_multipath_support(enforce_multipath):
# def get_connector_properties(*args, **kwargs):
# def _get_scsi_wwn(self, device_number):
# def check_valid_device(self, path, *args, **kwargs):
# def get_all_available_volumes(self):
# def _check_device_paths(self, device_paths):
# def extend_volume(self, connection_properties):
# def get_search_path(self):
#
# Path: os_brick/utils.py
# def _sleep(secs: float) -> None:
# def __init__(self, codes: Union[int, Tuple[int, ...]]):
# def _check_exit_code(self, exc: Type[Exception]) -> bool:
# def retry(retry_param: Union[None,
# Type[Exception],
# Tuple[Type[Exception], ...],
# int,
# Tuple[int, ...]],
# interval: float = 1,
# retries: int = 3,
# backoff_rate: float = 2,
# retry: Callable = tenacity.retry_if_exception_type) -> Callable:
# def _decorator(f):
# def _wrapper(*args, **kwargs):
# def platform_matches(current_platform: str, connector_platform: str) -> bool:
# def os_matches(current_os: str, connector_os: str) -> bool:
# def merge_dict(dict1: dict, dict2: dict) -> dict:
# def trace(f: Callable) -> Callable:
# def trace_logging_wrapper(*args, **kwargs):
# def convert_str(text: Union[bytes, str]) -> str:
# def get_host_nqn():
# LOG = logging.getLogger(__name__)
# class retry_if_exit_code(tenacity.retry_if_exception):
, which may include functions, classes, or code. Output only the next line. | props = {} |
Given the code snippet: <|code_start|># Copyright 2016 Cloudbase Solutions Srl
# All Rights Reserved.
#
# 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.
LOG = logging.getLogger(__name__)
class WindowsFCConnector(win_conn_base.BaseWindowsConnector):
def __init__(self, *args, **kwargs):
super(WindowsFCConnector, self).__init__(*args, **kwargs)
self.use_multipath = kwargs.get('use_multipath', False)
<|code_end|>
, generate the next line using the imports in this file:
import collections
import time
from os_win import exceptions as os_win_exc
from os_win import utilsfactory
from oslo_log import log as logging
from os_brick import exception
from os_brick.i18n import _
from os_brick.initiator.windows import base as win_conn_base
from os_brick import utils
and context (functions, classes, or occasionally code) from other files:
# Path: os_brick/exception.py
# LOG = logging.getLogger(__name__)
# class BrickException(Exception):
# class NotFound(BrickException):
# class Invalid(BrickException):
# class InvalidParameterValue(Invalid):
# class NoFibreChannelHostsFound(BrickException):
# class NoFibreChannelVolumeDeviceFound(BrickException):
# class VolumeNotDeactivated(BrickException):
# class VolumeDeviceNotFound(BrickException):
# class VolumePathsNotFound(BrickException):
# class VolumePathNotRemoved(BrickException):
# class ProtocolNotSupported(BrickException):
# class TargetPortalNotFound(BrickException):
# class TargetPortalsNotFound(TargetPortalNotFound):
# class FailedISCSITargetPortalLogin(BrickException):
# class BlockDeviceReadOnly(BrickException):
# class VolumeGroupNotFound(BrickException):
# class VolumeGroupCreationFailed(BrickException):
# class CommandExecutionFailed(BrickException):
# class VolumeDriverException(BrickException):
# class InvalidIOHandleObject(BrickException):
# class VolumeEncryptionNotSupported(Invalid):
# class VolumeLocalCacheNotSupported(Invalid):
# class InvalidConnectorProtocol(ValueError):
# class ExceptionChainer(BrickException):
# class ExecutionTimeout(putils.ProcessExecutionError):
# def __init__(self, message=None, **kwargs):
# def __init__(self, *args, **kwargs):
# def __repr__(self):
# def __nonzero__(self) -> bool:
# def add_exception(self, exc_type, exc_val, exc_tb) -> None:
# def context(self,
# catch_exception: bool,
# msg: str = '',
# *msg_args: Iterable):
# def __enter__(self):
# def __exit__(self, exc_type, exc_val, exc_tb):
#
# Path: os_brick/i18n.py
# DOMAIN = 'os-brick'
#
# Path: os_brick/initiator/windows/base.py
# LOG = logging.getLogger(__name__)
# DEFAULT_DEVICE_SCAN_INTERVAL = 2
# class BaseWindowsConnector(initiator_connector.InitiatorConnector):
# def __init__(self, root_helper=None, *args, **kwargs):
# def check_multipath_support(enforce_multipath):
# def get_connector_properties(*args, **kwargs):
# def _get_scsi_wwn(self, device_number):
# def check_valid_device(self, path, *args, **kwargs):
# def get_all_available_volumes(self):
# def _check_device_paths(self, device_paths):
# def extend_volume(self, connection_properties):
# def get_search_path(self):
#
# Path: os_brick/utils.py
# def _sleep(secs: float) -> None:
# def __init__(self, codes: Union[int, Tuple[int, ...]]):
# def _check_exit_code(self, exc: Type[Exception]) -> bool:
# def retry(retry_param: Union[None,
# Type[Exception],
# Tuple[Type[Exception], ...],
# int,
# Tuple[int, ...]],
# interval: float = 1,
# retries: int = 3,
# backoff_rate: float = 2,
# retry: Callable = tenacity.retry_if_exception_type) -> Callable:
# def _decorator(f):
# def _wrapper(*args, **kwargs):
# def platform_matches(current_platform: str, connector_platform: str) -> bool:
# def os_matches(current_os: str, connector_os: str) -> bool:
# def merge_dict(dict1: dict, dict2: dict) -> dict:
# def trace(f: Callable) -> Callable:
# def trace_logging_wrapper(*args, **kwargs):
# def convert_str(text: Union[bytes, str]) -> str:
# def get_host_nqn():
# LOG = logging.getLogger(__name__)
# class retry_if_exit_code(tenacity.retry_if_exception):
. Output only the next line. | self._fc_utils = utilsfactory.get_fc_utils() |
Next line prediction: <|code_start|> mappings[port['node_name']].append(port['port_name'])
return mappings
def _get_disk_paths_by_scsi_id(self, connection_properties, fcp_lun):
for local_port_wwn, remote_port_wwns in connection_properties[
'initiator_target_map'].items():
for remote_port_wwn in remote_port_wwns:
try:
dev_nums = self._get_dev_nums_by_scsi_id(
local_port_wwn, remote_port_wwn, fcp_lun)
# This may raise a DiskNotFound exception if the disks
# are meanwhile claimed by the MPIO service.
disk_paths = [
self._diskutils.get_device_name_by_device_number(
dev_num)
for dev_num in dev_nums]
return disk_paths
except os_win_exc.FCException as ex:
LOG.debug("Failed to retrieve volume paths by SCSI id. "
"Exception: %s", ex)
continue
return []
def _get_dev_nums_by_scsi_id(self, local_port_wwn, remote_port_wwn,
fcp_lun):
LOG.debug("Fetching SCSI Unique ID for FCP lun %(fcp_lun)s. "
"Port WWN: %(local_port_wwn)s. "
"Remote port WWN: %(remote_port_wwn)s.",
dict(fcp_lun=fcp_lun,
<|code_end|>
. Use current file imports:
(import collections
import time
from os_win import exceptions as os_win_exc
from os_win import utilsfactory
from oslo_log import log as logging
from os_brick import exception
from os_brick.i18n import _
from os_brick.initiator.windows import base as win_conn_base
from os_brick import utils)
and context including class names, function names, or small code snippets from other files:
# Path: os_brick/exception.py
# LOG = logging.getLogger(__name__)
# class BrickException(Exception):
# class NotFound(BrickException):
# class Invalid(BrickException):
# class InvalidParameterValue(Invalid):
# class NoFibreChannelHostsFound(BrickException):
# class NoFibreChannelVolumeDeviceFound(BrickException):
# class VolumeNotDeactivated(BrickException):
# class VolumeDeviceNotFound(BrickException):
# class VolumePathsNotFound(BrickException):
# class VolumePathNotRemoved(BrickException):
# class ProtocolNotSupported(BrickException):
# class TargetPortalNotFound(BrickException):
# class TargetPortalsNotFound(TargetPortalNotFound):
# class FailedISCSITargetPortalLogin(BrickException):
# class BlockDeviceReadOnly(BrickException):
# class VolumeGroupNotFound(BrickException):
# class VolumeGroupCreationFailed(BrickException):
# class CommandExecutionFailed(BrickException):
# class VolumeDriverException(BrickException):
# class InvalidIOHandleObject(BrickException):
# class VolumeEncryptionNotSupported(Invalid):
# class VolumeLocalCacheNotSupported(Invalid):
# class InvalidConnectorProtocol(ValueError):
# class ExceptionChainer(BrickException):
# class ExecutionTimeout(putils.ProcessExecutionError):
# def __init__(self, message=None, **kwargs):
# def __init__(self, *args, **kwargs):
# def __repr__(self):
# def __nonzero__(self) -> bool:
# def add_exception(self, exc_type, exc_val, exc_tb) -> None:
# def context(self,
# catch_exception: bool,
# msg: str = '',
# *msg_args: Iterable):
# def __enter__(self):
# def __exit__(self, exc_type, exc_val, exc_tb):
#
# Path: os_brick/i18n.py
# DOMAIN = 'os-brick'
#
# Path: os_brick/initiator/windows/base.py
# LOG = logging.getLogger(__name__)
# DEFAULT_DEVICE_SCAN_INTERVAL = 2
# class BaseWindowsConnector(initiator_connector.InitiatorConnector):
# def __init__(self, root_helper=None, *args, **kwargs):
# def check_multipath_support(enforce_multipath):
# def get_connector_properties(*args, **kwargs):
# def _get_scsi_wwn(self, device_number):
# def check_valid_device(self, path, *args, **kwargs):
# def get_all_available_volumes(self):
# def _check_device_paths(self, device_paths):
# def extend_volume(self, connection_properties):
# def get_search_path(self):
#
# Path: os_brick/utils.py
# def _sleep(secs: float) -> None:
# def __init__(self, codes: Union[int, Tuple[int, ...]]):
# def _check_exit_code(self, exc: Type[Exception]) -> bool:
# def retry(retry_param: Union[None,
# Type[Exception],
# Tuple[Type[Exception], ...],
# int,
# Tuple[int, ...]],
# interval: float = 1,
# retries: int = 3,
# backoff_rate: float = 2,
# retry: Callable = tenacity.retry_if_exception_type) -> Callable:
# def _decorator(f):
# def _wrapper(*args, **kwargs):
# def platform_matches(current_platform: str, connector_platform: str) -> bool:
# def os_matches(current_os: str, connector_os: str) -> bool:
# def merge_dict(dict1: dict, dict2: dict) -> dict:
# def trace(f: Callable) -> Callable:
# def trace_logging_wrapper(*args, **kwargs):
# def convert_str(text: Union[bytes, str]) -> str:
# def get_host_nqn():
# LOG = logging.getLogger(__name__)
# class retry_if_exit_code(tenacity.retry_if_exception):
. Output only the next line. | local_port_wwn=local_port_wwn, |
Given snippet: <|code_start|>
mock_mkdirs.assert_called_once_with('/etc/nvme',
mode=0o755,
exist_ok=True)
mock_exec.assert_called_once_with('nvme', 'show-hostnqn')
mock_open.assert_called_once_with('/etc/nvme/hostnqn', 'w')
stripped_hostnqn = hostnqn.strip.return_value
mock_open().write.assert_called_once_with(stripped_hostnqn)
mock_chmod.assert_called_once_with('/etc/nvme/hostnqn', 0o644)
self.assertEqual(stripped_hostnqn, res)
@mock.patch('os.chmod')
@mock.patch.object(builtins, 'open', new_callable=mock.mock_open)
@mock.patch('os.makedirs')
@mock.patch.object(rootwrap, 'custom_execute')
def test_create_hostnqn_generate(self, mock_exec, mock_mkdirs, mock_open,
mock_chmod):
hostnqn = mock.Mock()
mock_exec.side_effect = [
putils.ProcessExecutionError(exit_code=errno.ENOENT,
stdout="totally exist sub-command"),
(hostnqn, mock.sentinel.err)
]
res = privsep_nvme.create_hostnqn()
mock_mkdirs.assert_called_once_with('/etc/nvme',
mode=0o755,
exist_ok=True)
self.assertEqual(2, mock_exec.call_count)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import builtins
import errno
import ddt
import os_brick.privileged as privsep_brick
import os_brick.privileged.nvmeof as privsep_nvme
from unittest import mock
from oslo_concurrency import processutils as putils
from os_brick.privileged import rootwrap
from os_brick.tests import base
and context:
# Path: os_brick/privileged/rootwrap.py
# LOG = logging.getLogger(__name__)
# def custom_execute(*cmd, **kwargs):
# def on_timeout(proc):
# def on_execute(proc):
# def on_completion(proc):
# def execute(*cmd, **kwargs):
# def execute_root(*cmd, **kwargs):
# def unlink_root(*links, **kwargs):
#
# Path: os_brick/tests/base.py
# class TestCase(testtools.TestCase):
# SENTINEL = object()
# def setUp(self):
# def _common_cleanup(self):
# def log_level(self, level):
# def mock_object(self, obj, attr_name, new_attr=SENTINEL, **kwargs):
# def patch(self, path, *args, **kwargs):
which might include code, classes, or functions. Output only the next line. | mock_exec.assert_has_calls([mock.call('nvme', 'show-hostnqn'), |
Using the snippet: <|code_start|>
@mock.patch('os.chmod')
@mock.patch.object(builtins, 'open', new_callable=mock.mock_open)
@mock.patch('os.makedirs')
@mock.patch.object(rootwrap, 'custom_execute')
def test_create_hostnqn_generate_old_nvme_cli(self, mock_exec, mock_mkdirs,
mock_open, mock_chmod):
hostnqn = mock.Mock()
mock_exec.side_effect = [
putils.ProcessExecutionError(
exit_code=231,
stdout="error: Invalid sub-command\n"),
(hostnqn, mock.sentinel.err)
]
res = privsep_nvme.create_hostnqn()
mock_mkdirs.assert_called_once_with('/etc/nvme',
mode=0o755,
exist_ok=True)
self.assertEqual(2, mock_exec.call_count)
mock_exec.assert_has_calls([mock.call('nvme', 'show-hostnqn'),
mock.call('nvme', 'gen-hostnqn')])
mock_open.assert_called_once_with('/etc/nvme/hostnqn', 'w')
stripped_hostnqn = hostnqn.strip.return_value
mock_open().write.assert_called_once_with(stripped_hostnqn)
mock_chmod.assert_called_once_with('/etc/nvme/hostnqn', 0o644)
self.assertEqual(stripped_hostnqn, res)
<|code_end|>
, determine the next line of code. You have imports:
import builtins
import errno
import ddt
import os_brick.privileged as privsep_brick
import os_brick.privileged.nvmeof as privsep_nvme
from unittest import mock
from oslo_concurrency import processutils as putils
from os_brick.privileged import rootwrap
from os_brick.tests import base
and context (class names, function names, or code) available:
# Path: os_brick/privileged/rootwrap.py
# LOG = logging.getLogger(__name__)
# def custom_execute(*cmd, **kwargs):
# def on_timeout(proc):
# def on_execute(proc):
# def on_completion(proc):
# def execute(*cmd, **kwargs):
# def execute_root(*cmd, **kwargs):
# def unlink_root(*links, **kwargs):
#
# Path: os_brick/tests/base.py
# class TestCase(testtools.TestCase):
# SENTINEL = object()
# def setUp(self):
# def _common_cleanup(self):
# def log_level(self, level):
# def mock_object(self, obj, attr_name, new_attr=SENTINEL, **kwargs):
# def patch(self, path, *args, **kwargs):
. Output only the next line. | @ddt.data(OSError(errno.ENOENT), # nvme not present in system |
Given the following code snippet before the placeholder: <|code_start|># Copyright 2016 Cloudbase Solutions Srl
# All Rights Reserved.
#
# 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 FakeWindowsConnector(win_conn_base.BaseWindowsConnector):
def connect_volume(self, connection_properties):
return {}
def disconnect_volume(self, connection_properties, device_info,
force=False, ignore_errors=False):
pass
def get_volume_paths(self, connection_properties):
<|code_end|>
, predict the next line using imports from the current file:
from os_brick.initiator.windows import base as win_conn_base
and context including class names, function names, and sometimes code from other files:
# Path: os_brick/initiator/windows/base.py
# LOG = logging.getLogger(__name__)
# DEFAULT_DEVICE_SCAN_INTERVAL = 2
# class BaseWindowsConnector(initiator_connector.InitiatorConnector):
# def __init__(self, root_helper=None, *args, **kwargs):
# def check_multipath_support(enforce_multipath):
# def get_connector_properties(*args, **kwargs):
# def _get_scsi_wwn(self, device_number):
# def check_valid_device(self, path, *args, **kwargs):
# def get_all_available_volumes(self):
# def _check_device_paths(self, device_paths):
# def extend_volume(self, connection_properties):
# def get_search_path(self):
. Output only the next line. | return [] |
Predict the next line after this snippet: <|code_start|> def test_get_mapped_casdev(self, moc_exec):
out_ready = """type id disk status write policy device
cache 1 /dev/nvme0n1 Running wt -
└core 1 /dev/sdd Active - /dev/cas1-1"""
err = ''
engine = opencas.OpenCASEngine(root_helper=None, opencas_cache_id=1)
moc_exec.return_value = (out_ready, err)
ret1 = engine._get_mapped_casdev('/dev/sdd')
self.assertEqual('/dev/cas1-1', ret1)
@mock.patch('os_brick.executor.Executor._execute')
def test_get_mapped_coredev(self, moc_exec):
out_ready = """type id disk status write policy device
cache 1 /dev/nvme0n1 Running wt -
└core 1 /dev/sdd Active - /dev/cas1-1"""
err = ''
engine = opencas.OpenCASEngine(root_helper=None, opencas_cache_id=1)
moc_exec.return_value = (out_ready, err)
ret1, ret2 = engine._get_mapped_coredev('/dev/cas1-1')
self.assertEqual('1', ret1)
self.assertEqual('/dev/sdd', ret2)
@mock.patch('os_brick.executor.Executor._execute')
@mock.patch('os_brick.caches.opencas.OpenCASEngine._get_mapped_casdev')
def test_map_casdisk(self, moc_get_mapped_casdev, moc_exec):
engine = opencas.OpenCASEngine(root_helper=None, opencas_cache_id=1)
moc_get_mapped_casdev.return_value = ''
<|code_end|>
using the current file's imports:
from unittest import mock
from oslo_concurrency import processutils as putils
from os_brick.caches import opencas
from os_brick import exception
from os_brick.tests import base
and any relevant context from other files:
# Path: os_brick/caches/opencas.py
# LOG = logging.getLogger(__name__)
# class OpenCASEngine(executor.Executor, caches.CacheEngineBase):
# def __init__(self, **kwargs):
# def os_execute(self, *cmd, **kwargs):
# def is_engine_ready(self, **kwargs):
# def attach_volume(self, **kwargs):
# def detach_volume(self, **kwargs):
# def _get_mapped_casdev(self, core):
# def _get_mapped_coredev(self, casdev):
# def _map_casdisk(self, core):
# def _unmap_casdisk(self, coreid):
#
# Path: os_brick/exception.py
# LOG = logging.getLogger(__name__)
# class BrickException(Exception):
# class NotFound(BrickException):
# class Invalid(BrickException):
# class InvalidParameterValue(Invalid):
# class NoFibreChannelHostsFound(BrickException):
# class NoFibreChannelVolumeDeviceFound(BrickException):
# class VolumeNotDeactivated(BrickException):
# class VolumeDeviceNotFound(BrickException):
# class VolumePathsNotFound(BrickException):
# class VolumePathNotRemoved(BrickException):
# class ProtocolNotSupported(BrickException):
# class TargetPortalNotFound(BrickException):
# class TargetPortalsNotFound(TargetPortalNotFound):
# class FailedISCSITargetPortalLogin(BrickException):
# class BlockDeviceReadOnly(BrickException):
# class VolumeGroupNotFound(BrickException):
# class VolumeGroupCreationFailed(BrickException):
# class CommandExecutionFailed(BrickException):
# class VolumeDriverException(BrickException):
# class InvalidIOHandleObject(BrickException):
# class VolumeEncryptionNotSupported(Invalid):
# class VolumeLocalCacheNotSupported(Invalid):
# class InvalidConnectorProtocol(ValueError):
# class ExceptionChainer(BrickException):
# class ExecutionTimeout(putils.ProcessExecutionError):
# def __init__(self, message=None, **kwargs):
# def __init__(self, *args, **kwargs):
# def __repr__(self):
# def __nonzero__(self) -> bool:
# def add_exception(self, exc_type, exc_val, exc_tb) -> None:
# def context(self,
# catch_exception: bool,
# msg: str = '',
# *msg_args: Iterable):
# def __enter__(self):
# def __exit__(self, exc_type, exc_val, exc_tb):
#
# Path: os_brick/tests/base.py
# class TestCase(testtools.TestCase):
# SENTINEL = object()
# def setUp(self):
# def _common_cleanup(self):
# def log_level(self, level):
# def mock_object(self, obj, attr_name, new_attr=SENTINEL, **kwargs):
# def patch(self, path, *args, **kwargs):
. Output only the next line. | moc_exec.return_value = ('', '') |
Given snippet: <|code_start|> cache 1 /dev/nvme0n1 Running wt -
└core 1 /dev/sdd Active - /dev/cas1-1"""
err = ''
engine = opencas.OpenCASEngine(root_helper=None, opencas_cache_id=1)
moc_exec.return_value = (out_ready, err)
ret1, ret2 = engine._get_mapped_coredev('/dev/cas1-1')
self.assertEqual('1', ret1)
self.assertEqual('/dev/sdd', ret2)
@mock.patch('os_brick.executor.Executor._execute')
@mock.patch('os_brick.caches.opencas.OpenCASEngine._get_mapped_casdev')
def test_map_casdisk(self, moc_get_mapped_casdev, moc_exec):
engine = opencas.OpenCASEngine(root_helper=None, opencas_cache_id=1)
moc_get_mapped_casdev.return_value = ''
moc_exec.return_value = ('', '')
engine._map_casdisk('/dev/sdd')
moc_exec.assert_has_calls([
mock.call('casadm', '-A', '-i', 1, '-d', '/dev/sdd',
run_as_root=True, root_helper=None)
])
@mock.patch('os_brick.executor.Executor._execute')
def test_unmap_casdisk(self, moc_exec):
engine = opencas.OpenCASEngine(root_helper=None, opencas_cache_id=1)
moc_exec.return_value = ('', '')
engine._unmap_casdisk('1')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from unittest import mock
from oslo_concurrency import processutils as putils
from os_brick.caches import opencas
from os_brick import exception
from os_brick.tests import base
and context:
# Path: os_brick/caches/opencas.py
# LOG = logging.getLogger(__name__)
# class OpenCASEngine(executor.Executor, caches.CacheEngineBase):
# def __init__(self, **kwargs):
# def os_execute(self, *cmd, **kwargs):
# def is_engine_ready(self, **kwargs):
# def attach_volume(self, **kwargs):
# def detach_volume(self, **kwargs):
# def _get_mapped_casdev(self, core):
# def _get_mapped_coredev(self, casdev):
# def _map_casdisk(self, core):
# def _unmap_casdisk(self, coreid):
#
# Path: os_brick/exception.py
# LOG = logging.getLogger(__name__)
# class BrickException(Exception):
# class NotFound(BrickException):
# class Invalid(BrickException):
# class InvalidParameterValue(Invalid):
# class NoFibreChannelHostsFound(BrickException):
# class NoFibreChannelVolumeDeviceFound(BrickException):
# class VolumeNotDeactivated(BrickException):
# class VolumeDeviceNotFound(BrickException):
# class VolumePathsNotFound(BrickException):
# class VolumePathNotRemoved(BrickException):
# class ProtocolNotSupported(BrickException):
# class TargetPortalNotFound(BrickException):
# class TargetPortalsNotFound(TargetPortalNotFound):
# class FailedISCSITargetPortalLogin(BrickException):
# class BlockDeviceReadOnly(BrickException):
# class VolumeGroupNotFound(BrickException):
# class VolumeGroupCreationFailed(BrickException):
# class CommandExecutionFailed(BrickException):
# class VolumeDriverException(BrickException):
# class InvalidIOHandleObject(BrickException):
# class VolumeEncryptionNotSupported(Invalid):
# class VolumeLocalCacheNotSupported(Invalid):
# class InvalidConnectorProtocol(ValueError):
# class ExceptionChainer(BrickException):
# class ExecutionTimeout(putils.ProcessExecutionError):
# def __init__(self, message=None, **kwargs):
# def __init__(self, *args, **kwargs):
# def __repr__(self):
# def __nonzero__(self) -> bool:
# def add_exception(self, exc_type, exc_val, exc_tb) -> None:
# def context(self,
# catch_exception: bool,
# msg: str = '',
# *msg_args: Iterable):
# def __enter__(self):
# def __exit__(self, exc_type, exc_val, exc_tb):
#
# Path: os_brick/tests/base.py
# class TestCase(testtools.TestCase):
# SENTINEL = object()
# def setUp(self):
# def _common_cleanup(self):
# def log_level(self, level):
# def mock_object(self, obj, attr_name, new_attr=SENTINEL, **kwargs):
# def patch(self, path, *args, **kwargs):
which might include code, classes, or functions. Output only the next line. | moc_exec.assert_has_calls([ |
Next line prediction: <|code_start|># Copyright (c) 2013 The Johns Hopkins University/Applied Physics Laboratory
# All Rights Reserved.
#
# 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 OpenCASEngineTestCase(base.TestCase):
def setUp(self):
super(OpenCASEngineTestCase, self).setUp()
self.connection_info = {
"data": {
"device_path": "/dev/disk/by-path/"
"ip-192.0.2.0:3260-iscsi-iqn.2010-10.org.openstack"
":volume-fake_uuid-lun-1",
<|code_end|>
. Use current file imports:
(from unittest import mock
from oslo_concurrency import processutils as putils
from os_brick.caches import opencas
from os_brick import exception
from os_brick.tests import base)
and context including class names, function names, or small code snippets from other files:
# Path: os_brick/caches/opencas.py
# LOG = logging.getLogger(__name__)
# class OpenCASEngine(executor.Executor, caches.CacheEngineBase):
# def __init__(self, **kwargs):
# def os_execute(self, *cmd, **kwargs):
# def is_engine_ready(self, **kwargs):
# def attach_volume(self, **kwargs):
# def detach_volume(self, **kwargs):
# def _get_mapped_casdev(self, core):
# def _get_mapped_coredev(self, casdev):
# def _map_casdisk(self, core):
# def _unmap_casdisk(self, coreid):
#
# Path: os_brick/exception.py
# LOG = logging.getLogger(__name__)
# class BrickException(Exception):
# class NotFound(BrickException):
# class Invalid(BrickException):
# class InvalidParameterValue(Invalid):
# class NoFibreChannelHostsFound(BrickException):
# class NoFibreChannelVolumeDeviceFound(BrickException):
# class VolumeNotDeactivated(BrickException):
# class VolumeDeviceNotFound(BrickException):
# class VolumePathsNotFound(BrickException):
# class VolumePathNotRemoved(BrickException):
# class ProtocolNotSupported(BrickException):
# class TargetPortalNotFound(BrickException):
# class TargetPortalsNotFound(TargetPortalNotFound):
# class FailedISCSITargetPortalLogin(BrickException):
# class BlockDeviceReadOnly(BrickException):
# class VolumeGroupNotFound(BrickException):
# class VolumeGroupCreationFailed(BrickException):
# class CommandExecutionFailed(BrickException):
# class VolumeDriverException(BrickException):
# class InvalidIOHandleObject(BrickException):
# class VolumeEncryptionNotSupported(Invalid):
# class VolumeLocalCacheNotSupported(Invalid):
# class InvalidConnectorProtocol(ValueError):
# class ExceptionChainer(BrickException):
# class ExecutionTimeout(putils.ProcessExecutionError):
# def __init__(self, message=None, **kwargs):
# def __init__(self, *args, **kwargs):
# def __repr__(self):
# def __nonzero__(self) -> bool:
# def add_exception(self, exc_type, exc_val, exc_tb) -> None:
# def context(self,
# catch_exception: bool,
# msg: str = '',
# *msg_args: Iterable):
# def __enter__(self):
# def __exit__(self, exc_type, exc_val, exc_tb):
#
# Path: os_brick/tests/base.py
# class TestCase(testtools.TestCase):
# SENTINEL = object()
# def setUp(self):
# def _common_cleanup(self):
# def log_level(self, level):
# def mock_object(self, obj, attr_name, new_attr=SENTINEL, **kwargs):
# def patch(self, path, *args, **kwargs):
. Output only the next line. | }, |
Here is a snippet: <|code_start|> self.mock_execute.assert_has_calls(calls)
@mock.patch.object(remotefs.RemoteFsClient, '_read_mounts',
return_value=[])
def test_vzstorage_invalid_share(self, mock_read_mounts):
client = remotefs.VZStorageRemoteFSClient(
"vzstorage", root_helper='true', vzstorage_mount_point_base='/mnt')
self.assertRaises(exception.BrickException, client.mount, ':')
class ScalityRemoteFsClientTestCase(base.TestCase):
def test_no_mount_point_scality(self):
self.assertRaises(exception.InvalidParameterValue,
remotefs.ScalityRemoteFsClient,
'scality', root_helper='true')
def test_get_mount_point(self):
fsclient = remotefs.ScalityRemoteFsClient(
'scality', root_helper='true', scality_mount_point_base='/fake')
self.assertEqual('/fake/path/00', fsclient.get_mount_point('path'))
@mock.patch('oslo_concurrency.processutils.execute', return_value=None)
@mock.patch('os_brick.remotefs.remotefs.RemoteFsClient._do_mount')
def test_mount(self, mock_do_mount, mock_execute):
fsclient = remotefs.ScalityRemoteFsClient(
'scality', root_helper='true', scality_mount_point_base='/fake',
execute=putils.execute)
with mock.patch.object(fsclient, '_read_mounts', return_value={}):
fsclient.mount('fake')
<|code_end|>
. Write the next line using the current file imports:
import os
import tempfile
from unittest import mock
from oslo_concurrency import processutils as putils
from os_brick import exception
from os_brick.privileged import rootwrap as priv_rootwrap
from os_brick.remotefs import remotefs
from os_brick.tests import base
and context from other files:
# Path: os_brick/exception.py
# LOG = logging.getLogger(__name__)
# class BrickException(Exception):
# class NotFound(BrickException):
# class Invalid(BrickException):
# class InvalidParameterValue(Invalid):
# class NoFibreChannelHostsFound(BrickException):
# class NoFibreChannelVolumeDeviceFound(BrickException):
# class VolumeNotDeactivated(BrickException):
# class VolumeDeviceNotFound(BrickException):
# class VolumePathsNotFound(BrickException):
# class VolumePathNotRemoved(BrickException):
# class ProtocolNotSupported(BrickException):
# class TargetPortalNotFound(BrickException):
# class TargetPortalsNotFound(TargetPortalNotFound):
# class FailedISCSITargetPortalLogin(BrickException):
# class BlockDeviceReadOnly(BrickException):
# class VolumeGroupNotFound(BrickException):
# class VolumeGroupCreationFailed(BrickException):
# class CommandExecutionFailed(BrickException):
# class VolumeDriverException(BrickException):
# class InvalidIOHandleObject(BrickException):
# class VolumeEncryptionNotSupported(Invalid):
# class VolumeLocalCacheNotSupported(Invalid):
# class InvalidConnectorProtocol(ValueError):
# class ExceptionChainer(BrickException):
# class ExecutionTimeout(putils.ProcessExecutionError):
# def __init__(self, message=None, **kwargs):
# def __init__(self, *args, **kwargs):
# def __repr__(self):
# def __nonzero__(self) -> bool:
# def add_exception(self, exc_type, exc_val, exc_tb) -> None:
# def context(self,
# catch_exception: bool,
# msg: str = '',
# *msg_args: Iterable):
# def __enter__(self):
# def __exit__(self, exc_type, exc_val, exc_tb):
#
# Path: os_brick/privileged/rootwrap.py
# LOG = logging.getLogger(__name__)
# def custom_execute(*cmd, **kwargs):
# def on_timeout(proc):
# def on_execute(proc):
# def on_completion(proc):
# def execute(*cmd, **kwargs):
# def execute_root(*cmd, **kwargs):
# def unlink_root(*links, **kwargs):
#
# Path: os_brick/remotefs/remotefs.py
# LOG = logging.getLogger(__name__)
# class RemoteFsClient(executor.Executor):
# class ScalityRemoteFsClient(RemoteFsClient):
# class VZStorageRemoteFSClient(RemoteFsClient):
# def __init__(self, mount_type, root_helper,
# execute=None, *args, **kwargs):
# def get_mount_base(self):
# def _get_hash_str(self, base_str):
# def get_mount_point(self, device_name: str):
# def _read_mounts(self):
# def mount(self, share, flags=None):
# def _do_mount(self, mount_type, share, mount_path, mount_options=None,
# flags=None):
# def _mount_nfs(self, nfs_share, mount_path, flags=None):
# def _check_nfs_options(self):
# def _option_exists(self, options, opt_pattern):
# def _update_option(self, options, option, value=None):
# def __init__(self, mount_type, root_helper,
# execute=None, *args, **kwargs):
# def get_mount_point(self, device_name):
# def mount(self, share, flags=None):
# def _vzstorage_write_mds_list(self, cluster_name, mdss):
# def _do_mount(self, mount_type, vz_share, mount_path,
# mount_options=None, flags=None):
#
# Path: os_brick/tests/base.py
# class TestCase(testtools.TestCase):
# SENTINEL = object()
# def setUp(self):
# def _common_cleanup(self):
# def log_level(self, level):
# def mock_object(self, obj, attr_name, new_attr=SENTINEL, **kwargs):
# def patch(self, path, *args, **kwargs):
, which may include functions, classes, or code. Output only the next line. | mock_execute.assert_called_once_with( |
Next line prediction: <|code_start|> smbfs_mount_point_base='/mnt')
share = '10.0.0.1:/qwe'
mount_point = client.get_mount_point(share)
client.mount(share)
calls = [mock.call('mkdir', '-p', mount_point, check_exit_code=0),
mock.call('mount', '-t', 'cifs', share, mount_point,
run_as_root=True, root_helper='true',
check_exit_code=0)]
self.mock_execute.assert_has_calls(calls)
@mock.patch.object(remotefs.RemoteFsClient, '_read_mounts',
return_value=[])
def test_nfs(self, mock_read_mounts):
client = remotefs.RemoteFsClient("nfs", root_helper='true',
nfs_mount_point_base='/mnt')
share = '10.0.0.1:/qwe'
mount_point = client.get_mount_point(share)
client.mount(share)
calls = [mock.call('mkdir', '-p', mount_point, check_exit_code=0),
mock.call('mount', '-t', 'nfs', '-o', 'vers=4,minorversion=1',
share, mount_point, check_exit_code=0,
run_as_root=True, root_helper='true')]
self.mock_execute.assert_has_calls(calls)
def test_read_mounts(self):
mounts = """device1 mnt_point1 ext4 rw,seclabel,relatime 0 0
device2 mnt_point2 ext4 rw,seclabel,relatime 0 0"""
with mock.patch('os_brick.remotefs.remotefs.open',
mock.mock_open(read_data=mounts)) as mock_open:
client = remotefs.RemoteFsClient("cifs", root_helper='true',
<|code_end|>
. Use current file imports:
(import os
import tempfile
from unittest import mock
from oslo_concurrency import processutils as putils
from os_brick import exception
from os_brick.privileged import rootwrap as priv_rootwrap
from os_brick.remotefs import remotefs
from os_brick.tests import base)
and context including class names, function names, or small code snippets from other files:
# Path: os_brick/exception.py
# LOG = logging.getLogger(__name__)
# class BrickException(Exception):
# class NotFound(BrickException):
# class Invalid(BrickException):
# class InvalidParameterValue(Invalid):
# class NoFibreChannelHostsFound(BrickException):
# class NoFibreChannelVolumeDeviceFound(BrickException):
# class VolumeNotDeactivated(BrickException):
# class VolumeDeviceNotFound(BrickException):
# class VolumePathsNotFound(BrickException):
# class VolumePathNotRemoved(BrickException):
# class ProtocolNotSupported(BrickException):
# class TargetPortalNotFound(BrickException):
# class TargetPortalsNotFound(TargetPortalNotFound):
# class FailedISCSITargetPortalLogin(BrickException):
# class BlockDeviceReadOnly(BrickException):
# class VolumeGroupNotFound(BrickException):
# class VolumeGroupCreationFailed(BrickException):
# class CommandExecutionFailed(BrickException):
# class VolumeDriverException(BrickException):
# class InvalidIOHandleObject(BrickException):
# class VolumeEncryptionNotSupported(Invalid):
# class VolumeLocalCacheNotSupported(Invalid):
# class InvalidConnectorProtocol(ValueError):
# class ExceptionChainer(BrickException):
# class ExecutionTimeout(putils.ProcessExecutionError):
# def __init__(self, message=None, **kwargs):
# def __init__(self, *args, **kwargs):
# def __repr__(self):
# def __nonzero__(self) -> bool:
# def add_exception(self, exc_type, exc_val, exc_tb) -> None:
# def context(self,
# catch_exception: bool,
# msg: str = '',
# *msg_args: Iterable):
# def __enter__(self):
# def __exit__(self, exc_type, exc_val, exc_tb):
#
# Path: os_brick/privileged/rootwrap.py
# LOG = logging.getLogger(__name__)
# def custom_execute(*cmd, **kwargs):
# def on_timeout(proc):
# def on_execute(proc):
# def on_completion(proc):
# def execute(*cmd, **kwargs):
# def execute_root(*cmd, **kwargs):
# def unlink_root(*links, **kwargs):
#
# Path: os_brick/remotefs/remotefs.py
# LOG = logging.getLogger(__name__)
# class RemoteFsClient(executor.Executor):
# class ScalityRemoteFsClient(RemoteFsClient):
# class VZStorageRemoteFSClient(RemoteFsClient):
# def __init__(self, mount_type, root_helper,
# execute=None, *args, **kwargs):
# def get_mount_base(self):
# def _get_hash_str(self, base_str):
# def get_mount_point(self, device_name: str):
# def _read_mounts(self):
# def mount(self, share, flags=None):
# def _do_mount(self, mount_type, share, mount_path, mount_options=None,
# flags=None):
# def _mount_nfs(self, nfs_share, mount_path, flags=None):
# def _check_nfs_options(self):
# def _option_exists(self, options, opt_pattern):
# def _update_option(self, options, option, value=None):
# def __init__(self, mount_type, root_helper,
# execute=None, *args, **kwargs):
# def get_mount_point(self, device_name):
# def mount(self, share, flags=None):
# def _vzstorage_write_mds_list(self, cluster_name, mdss):
# def _do_mount(self, mount_type, vz_share, mount_path,
# mount_options=None, flags=None):
#
# Path: os_brick/tests/base.py
# class TestCase(testtools.TestCase):
# SENTINEL = object()
# def setUp(self):
# def _common_cleanup(self):
# def log_level(self, level):
# def mock_object(self, obj, attr_name, new_attr=SENTINEL, **kwargs):
# def patch(self, path, *args, **kwargs):
. Output only the next line. | smbfs_mount_point_base='/mnt') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.