Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Using the snippet: <|code_start|>
def in_jasper_session(self):
return False
def use_server(self):
try:
doc_jasper_server = self.doc.use_jasper_server.lower()
return doc_jasper_server == "jasperserver only" or doc_jasper_server == "both"
except:
return False
def use_local(self):
doc_jasper_server = self.doc.use_jasper_server.lower()
return doc_jasper_server == "local jrxml only" or doc_jasper_server == "both"
def get_report_origin(self):
try:
origin = self.doc.use_jasper_server.lower()
except:
origin = "localserver"
return origin
def get_jasperconfig_from_db(self):
self.doc = frappe.db.get_value('JasperServerConfig', None, "*", ignore=True, as_dict=True) or frappe._dict({})
self.createJasperSession()
def resume(self):
if self.data['data']:
return
data = self.get_jasper_session_data()
<|code_end|>
, determine the next line of code. You have imports:
from frappe.model.document import Document
from frappe import _
from io import BytesIO
from jasper_erpnext_report.utils.file import get_file, get_html_reports_images_path
from jasper_erpnext_report.utils.file import JasperXmlReport, get_html_reports_path
from distutils.dir_util import copy_tree
from jasper_erpnext_report.utils.utils import getFrappeVersion
import frappe
import uuid, os
import jasper_erpnext_report.utils.utils as utils
import re
import hashlib
import frappe.utils.email_lib
import frappe.email
and context (class names, function names, or code) available:
# Path: jasper_erpnext_report/utils/file.py
# def get_file(path, modes="r", raise_not_found=False):
# if modes != "r":
# content = read_file(path, modes=modes, raise_not_found=raise_not_found)
# else:
# content = frappe.read_file(path, raise_not_found=raise_not_found)
#
# return content
#
# def get_html_reports_images_path(report_path, where="images"):
# path = os.path.join(report_path, where)
# frappe.create_folder(path)
# return path
#
# Path: jasper_erpnext_report/utils/file.py
# def get_image_name(iname):
# def get_images_path(compiled_path):
# def get_jasper_path(for_all_sites = False):
# def write_StringIO_to_file(file_path, output):
# def write_file(content, file_path, modes="w+"):
# def check_extension(fname):
# def get_extension(fname):
# def remove_from_doc(dt, dn, field, where_field = "name"):
# def delete_from_doc(dt, dn, field, value, where_field):
# def delete_from_FileData(dt, dn, file_url):
# def remove_directory(path, ignore_errors=True):
# def remove_compiled_report(root_path):
# def get_file(path, modes="r", raise_not_found=False):
# def read_file(path, modes="r", raise_not_found=False):
# def get_html_reports_path(report_name, where="reports", hash=None, localsite=None):
# def get_html_reports_images_path(report_path, where="images"):
. Output only the next line. | if data: |
Next line prediction: <|code_start|> def reset_data_session(self):
self.data = frappe._dict({'data': frappe._dict({})})
def in_jasper_session(self):
return False
def use_server(self):
try:
doc_jasper_server = self.doc.use_jasper_server.lower()
return doc_jasper_server == "jasperserver only" or doc_jasper_server == "both"
except:
return False
def use_local(self):
doc_jasper_server = self.doc.use_jasper_server.lower()
return doc_jasper_server == "local jrxml only" or doc_jasper_server == "both"
def get_report_origin(self):
try:
origin = self.doc.use_jasper_server.lower()
except:
origin = "localserver"
return origin
def get_jasperconfig_from_db(self):
self.doc = frappe.db.get_value('JasperServerConfig', None, "*", ignore=True, as_dict=True) or frappe._dict({})
self.createJasperSession()
def resume(self):
if self.data['data']:
<|code_end|>
. Use current file imports:
(from frappe.model.document import Document
from frappe import _
from io import BytesIO
from jasper_erpnext_report.utils.file import get_file, get_html_reports_images_path
from jasper_erpnext_report.utils.file import JasperXmlReport, get_html_reports_path
from distutils.dir_util import copy_tree
from jasper_erpnext_report.utils.utils import getFrappeVersion
import frappe
import uuid, os
import jasper_erpnext_report.utils.utils as utils
import re
import hashlib
import frappe.utils.email_lib
import frappe.email)
and context including class names, function names, or small code snippets from other files:
# Path: jasper_erpnext_report/utils/file.py
# def get_file(path, modes="r", raise_not_found=False):
# if modes != "r":
# content = read_file(path, modes=modes, raise_not_found=raise_not_found)
# else:
# content = frappe.read_file(path, raise_not_found=raise_not_found)
#
# return content
#
# def get_html_reports_images_path(report_path, where="images"):
# path = os.path.join(report_path, where)
# frappe.create_folder(path)
# return path
#
# Path: jasper_erpnext_report/utils/file.py
# def get_image_name(iname):
# def get_images_path(compiled_path):
# def get_jasper_path(for_all_sites = False):
# def write_StringIO_to_file(file_path, output):
# def write_file(content, file_path, modes="w+"):
# def check_extension(fname):
# def get_extension(fname):
# def remove_from_doc(dt, dn, field, where_field = "name"):
# def delete_from_doc(dt, dn, field, value, where_field):
# def delete_from_FileData(dt, dn, file_url):
# def remove_directory(path, ignore_errors=True):
# def remove_compiled_report(root_path):
# def get_file(path, modes="r", raise_not_found=False):
# def read_file(path, modes="r", raise_not_found=False):
# def get_html_reports_path(report_name, where="reports", hash=None, localsite=None):
# def get_html_reports_images_path(report_path, where="images"):
. Output only the next line. | return |
Next line prediction: <|code_start|>from __future__ import unicode_literals
__author__ = 'luissaguas'
_logger = frappe.logger("jasper_erpnext_report")
<|code_end|>
. Use current file imports:
(from frappe.model.document import Document
from frappe import _
from io import BytesIO
from jasper_erpnext_report.utils.file import get_file, get_html_reports_images_path
from jasper_erpnext_report.utils.file import JasperXmlReport, get_html_reports_path
from distutils.dir_util import copy_tree
from jasper_erpnext_report.utils.utils import getFrappeVersion
import frappe
import uuid, os
import jasper_erpnext_report.utils.utils as utils
import re
import hashlib
import frappe.utils.email_lib
import frappe.email)
and context including class names, function names, or small code snippets from other files:
# Path: jasper_erpnext_report/utils/file.py
# def get_file(path, modes="r", raise_not_found=False):
# if modes != "r":
# content = read_file(path, modes=modes, raise_not_found=raise_not_found)
# else:
# content = frappe.read_file(path, raise_not_found=raise_not_found)
#
# return content
#
# def get_html_reports_images_path(report_path, where="images"):
# path = os.path.join(report_path, where)
# frappe.create_folder(path)
# return path
#
# Path: jasper_erpnext_report/utils/file.py
# def get_image_name(iname):
# def get_images_path(compiled_path):
# def get_jasper_path(for_all_sites = False):
# def write_StringIO_to_file(file_path, output):
# def write_file(content, file_path, modes="w+"):
# def check_extension(fname):
# def get_extension(fname):
# def remove_from_doc(dt, dn, field, where_field = "name"):
# def delete_from_doc(dt, dn, field, value, where_field):
# def delete_from_FileData(dt, dn, file_url):
# def remove_directory(path, ignore_errors=True):
# def remove_compiled_report(root_path):
# def get_file(path, modes="r", raise_not_found=False):
# def read_file(path, modes="r", raise_not_found=False):
# def get_html_reports_path(report_name, where="reports", hash=None, localsite=None):
# def get_html_reports_images_path(report_path, where="images"):
. Output only the next line. | jasper_fields_not_supported = ["parent", "owner", "modified_by", "parenttype", "parentfield", "docstatus", "doctype", "name", "idx"] |
Given the following code snippet before the placeholder: <|code_start|>
### Constants ##################################################################
ROW_SIZE = 8
COL_SIZE = 4
SPEED_INCREASE = .15 #In pixels per frame
################################################################################
### Globals ####################################################################
_enemies = None
<|code_end|>
, predict the next line using imports from the current file:
from math import log1p
from random import randint
from game.enemy import Enemy
from game import gamedata
import pygame.time
and context including class names, function names, and sometimes code from other files:
# Path: game/enemy.py
# class Enemy(GameObject):
# STATES = config.Enum(*ENEMY_STATES)
# anim = 0.0
# base_speed = 0.5
# GROUP = None
# shoot_odds = 0.002
# should_flip = False
# start_time = None
# velocity = [0.5, 0.0]
#
# def __init__(self, form_position):
# super().__init__()
# ### Local variables ####################################################
# the_color = choice(color.LIST)
# the_id = id(the_color)
# ########################################################################
#
# ### Object Attributes ##################################################
# self.amount_lowered = 0
# self._anim = 0.0
# self.color = the_color
# self.column = None
# self._form_position = form_position
# self.current_frame_list = ENEMY_FRAMES_COLOR_BLIND if settings.SETTINGS['color_blind'] else ENEMY_FRAMES
# self.image = self.current_frame_list[the_id][0]
# self.position = list(START_POS)
# self.rect = Rect(START_POS, self.image.get_size())
# self.state = Enemy.STATES.IDLE
# self.emitter = ParticleEmitter(color.color_particles[the_id], self.rect, 1)
# ########################################################################
#
# ### Preparation ########################################################
# del self.acceleration, self.velocity
# ########################################################################
#
# def appear(self):
# self.add(Enemy.GROUP)
# self.position = [
# START_POS[0] * (self._form_position[0] + 1) * 1.5,
# START_POS[1] * (self._form_position[1] + 1) * 1.5,
# ]
# self.rect.topleft = (self.position[0] + .5, self.position[1] + .5)
# self.color = choice(color.LIST)
# self.__animate()
# self.emitter.pool = color.color_particles[id(self.color)]
# self.change_state(Enemy.STATES.ACTIVE)
#
# def move(self):
# self.__animate()
# self.position[0] += Enemy.velocity[0]
# self.rect.topleft = (self.position[0] + .5, self.position[1] + .5)
#
# if uniform(0, 1) < Enemy.shoot_odds and not enemybullet.EnemyBullet.halt:
# #With Enemy.shoot_odds% of firing...
# #TODO: Use another probability distribution
# b = enemybullet.get_enemy_bullet()
# b.rect.midtop = self.rect.midbottom
# b.position = list(b.rect.topleft)
# b.add(enemybullet.EnemyBullet.GROUP)
#
# if not Enemy.should_flip:
# #If the squadron of enemies is not marked to reverse direction...
# if self.rect.left < 0 or self.rect.right > config.SCREEN_WIDTH:
# #If this enemy touches either end of the screen...
# Enemy.should_flip = True
#
# def die(self):
# balloflight.get_ball(self.rect.topleft, self.column, self.color).add(Enemy.GROUP)
# _hurt.play()
# self.emitter.burst(20)
# self.kill()
#
# self.position = [-300.0, -300.0]
# self.rect.topleft = self.position
# self.change_state(Enemy.STATES.IDLE)
# Enemy.velocity[0] += copysign(0.1, Enemy.velocity[0])
# #^ Increase the enemy squadron's speed (copysign() considers direction)
#
# def lower(self):
# self.__animate()
# self.amount_lowered += 1
# self.position[1] += 1
# self.rect.top = self.position[1]
# if self.amount_lowered == LOWER_INCREMENT:
# self.amount_lowered = 0
# self.change_state(Enemy.STATES.ACTIVE)
#
# def cheer(self):
# self.__animate()
# self.position[1] -= 2 * sin((Enemy.anim/2) - (pi/4) * self._form_position[0])
# self.rect.top = self.position[1] + .5
#
# def __animate(self):
# self._anim = int(3 - abs(Enemy.anim - 3)) % 4
# self.image = self.current_frame_list[id(self.color)][self._anim]
#
# actions = {
# STATES.APPEARING: 'appear',
# STATES.LOWERING : 'lower' ,
# STATES.ACTIVE : 'move' ,
# STATES.DYING : 'die' ,
# STATES.IDLE : None ,
# STATES.CHEERING : 'cheer' ,
# }
#
# Path: game/gamedata.py
# DEFAULT_LIVES = 3
# MAX_COMBO_TIME = 60 #In frames
# def clean_up():
. Output only the next line. | ENEMY_GROUP = None |
Predict the next line after this snippet: <|code_start|>
### Constants ##################################################################
ROW_SIZE = 8
COL_SIZE = 4
SPEED_INCREASE = .15 #In pixels per frame
################################################################################
### Globals ####################################################################
_enemies = None
<|code_end|>
using the current file's imports:
from math import log1p
from random import randint
from game.enemy import Enemy
from game import gamedata
import pygame.time
and any relevant context from other files:
# Path: game/enemy.py
# class Enemy(GameObject):
# STATES = config.Enum(*ENEMY_STATES)
# anim = 0.0
# base_speed = 0.5
# GROUP = None
# shoot_odds = 0.002
# should_flip = False
# start_time = None
# velocity = [0.5, 0.0]
#
# def __init__(self, form_position):
# super().__init__()
# ### Local variables ####################################################
# the_color = choice(color.LIST)
# the_id = id(the_color)
# ########################################################################
#
# ### Object Attributes ##################################################
# self.amount_lowered = 0
# self._anim = 0.0
# self.color = the_color
# self.column = None
# self._form_position = form_position
# self.current_frame_list = ENEMY_FRAMES_COLOR_BLIND if settings.SETTINGS['color_blind'] else ENEMY_FRAMES
# self.image = self.current_frame_list[the_id][0]
# self.position = list(START_POS)
# self.rect = Rect(START_POS, self.image.get_size())
# self.state = Enemy.STATES.IDLE
# self.emitter = ParticleEmitter(color.color_particles[the_id], self.rect, 1)
# ########################################################################
#
# ### Preparation ########################################################
# del self.acceleration, self.velocity
# ########################################################################
#
# def appear(self):
# self.add(Enemy.GROUP)
# self.position = [
# START_POS[0] * (self._form_position[0] + 1) * 1.5,
# START_POS[1] * (self._form_position[1] + 1) * 1.5,
# ]
# self.rect.topleft = (self.position[0] + .5, self.position[1] + .5)
# self.color = choice(color.LIST)
# self.__animate()
# self.emitter.pool = color.color_particles[id(self.color)]
# self.change_state(Enemy.STATES.ACTIVE)
#
# def move(self):
# self.__animate()
# self.position[0] += Enemy.velocity[0]
# self.rect.topleft = (self.position[0] + .5, self.position[1] + .5)
#
# if uniform(0, 1) < Enemy.shoot_odds and not enemybullet.EnemyBullet.halt:
# #With Enemy.shoot_odds% of firing...
# #TODO: Use another probability distribution
# b = enemybullet.get_enemy_bullet()
# b.rect.midtop = self.rect.midbottom
# b.position = list(b.rect.topleft)
# b.add(enemybullet.EnemyBullet.GROUP)
#
# if not Enemy.should_flip:
# #If the squadron of enemies is not marked to reverse direction...
# if self.rect.left < 0 or self.rect.right > config.SCREEN_WIDTH:
# #If this enemy touches either end of the screen...
# Enemy.should_flip = True
#
# def die(self):
# balloflight.get_ball(self.rect.topleft, self.column, self.color).add(Enemy.GROUP)
# _hurt.play()
# self.emitter.burst(20)
# self.kill()
#
# self.position = [-300.0, -300.0]
# self.rect.topleft = self.position
# self.change_state(Enemy.STATES.IDLE)
# Enemy.velocity[0] += copysign(0.1, Enemy.velocity[0])
# #^ Increase the enemy squadron's speed (copysign() considers direction)
#
# def lower(self):
# self.__animate()
# self.amount_lowered += 1
# self.position[1] += 1
# self.rect.top = self.position[1]
# if self.amount_lowered == LOWER_INCREMENT:
# self.amount_lowered = 0
# self.change_state(Enemy.STATES.ACTIVE)
#
# def cheer(self):
# self.__animate()
# self.position[1] -= 2 * sin((Enemy.anim/2) - (pi/4) * self._form_position[0])
# self.rect.top = self.position[1] + .5
#
# def __animate(self):
# self._anim = int(3 - abs(Enemy.anim - 3)) % 4
# self.image = self.current_frame_list[id(self.color)][self._anim]
#
# actions = {
# STATES.APPEARING: 'appear',
# STATES.LOWERING : 'lower' ,
# STATES.ACTIVE : 'move' ,
# STATES.DYING : 'die' ,
# STATES.IDLE : None ,
# STATES.CHEERING : 'cheer' ,
# }
#
# Path: game/gamedata.py
# DEFAULT_LIVES = 3
# MAX_COMBO_TIME = 60 #In frames
# def clean_up():
. Output only the next line. | ENEMY_GROUP = None |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
BASE_PATH = os.path.dirname(os.path.abspath(__file__))
OUTPUT_PATH = os.path.join(BASE_PATH, 'index.html')
BUNDLE_PATH = os.path.join(BASE_PATH, 'src', 'bundle.js')
template = """<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
<link rel="stylesheet" href="src/style.css">
<|code_end|>
, generate the next line using the imports in this file:
import os
import io
import react
from react import React
from react import utils
and context (functions, classes, or occasionally code) from other files:
# Path: react/react.py
# class React:
# """
# Wrap basic functionality to\
# render react views. The only\
# thing it cares is that there\
# is a global.RenderToString(opts)\
# function defined in the pre-loaded\
# js libs. This render function\
# renders a component, matches a route, etc\
# and returns the rendered view\
# or a json with extra data.
#
# :param dict opts: Dict of parameters the\
# js render function will receive, it must\
# be serializable with json
# """
# def __init__(self, opts):
# self.opts = opts
#
# def build_js_script(self):
# """
# :return: The call to the JS render function
# :rtype: str
# """
# return ('global.RenderToString({})'
# .format(self.as_json()))
#
# def render(self):
# """
# :return: Result of the JS render call
# :rtype: str
# :raises react.excepts.V8Error: if there was\
# an error running the JS script
# """
# return utils.run_script(self.build_js_script())
#
# def as_json(self):
# """
# Serialize :py:attr:`.opts` into a json.\
# This is used internally and can\
# be overridden to provide a faster\
# json serializer.
#
# :return: Opts in json format
# :rtype: str
# """
# return self.to_json(self.opts)
#
# @staticmethod
# def to_json(data):
# """
# Serialize a dict into a json.
#
# :param data: Dict to convert into JSON
# :type data: dict or str
# :return: Received data in json format
# :rtype: str
# """
# if isinstance(data, six.text_type):
# return data
#
# data_ = json.dumps(data)
#
# if isinstance(data_, six.binary_type):
# return data_.decode('utf-8')
# else:
# return data_
#
# @staticmethod
# def to_dict(json_str):
# """
# De-serialize a json string into a python dict.
#
# :param str json_str: String to convert into dict
# :return: Received string in dict format
# :rtype: dict
# """
# return json.loads(json_str)
#
# Path: react/utils.py
# def set_up():
# def load_libs(scripts_paths):
# def run_script(script):
. Output only the next line. | </head> |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
BASE_PATH = os.path.dirname(os.path.abspath(__file__))
OUTPUT_PATH = os.path.join(BASE_PATH, 'index.html')
BUNDLE_PATH = os.path.join(BASE_PATH, 'src', 'bundle.js')
template = """<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
<link rel="stylesheet" href="src/style.css">
</head>
<body>
<div id="content">{pre_rendered_content}</div>
<script>
window.preLoadedState = {pre_loaded_state};
<|code_end|>
. Use current file imports:
import os
import io
import react
from react import React
from react import utils
and context (classes, functions, or code) from other files:
# Path: react/react.py
# class React:
# """
# Wrap basic functionality to\
# render react views. The only\
# thing it cares is that there\
# is a global.RenderToString(opts)\
# function defined in the pre-loaded\
# js libs. This render function\
# renders a component, matches a route, etc\
# and returns the rendered view\
# or a json with extra data.
#
# :param dict opts: Dict of parameters the\
# js render function will receive, it must\
# be serializable with json
# """
# def __init__(self, opts):
# self.opts = opts
#
# def build_js_script(self):
# """
# :return: The call to the JS render function
# :rtype: str
# """
# return ('global.RenderToString({})'
# .format(self.as_json()))
#
# def render(self):
# """
# :return: Result of the JS render call
# :rtype: str
# :raises react.excepts.V8Error: if there was\
# an error running the JS script
# """
# return utils.run_script(self.build_js_script())
#
# def as_json(self):
# """
# Serialize :py:attr:`.opts` into a json.\
# This is used internally and can\
# be overridden to provide a faster\
# json serializer.
#
# :return: Opts in json format
# :rtype: str
# """
# return self.to_json(self.opts)
#
# @staticmethod
# def to_json(data):
# """
# Serialize a dict into a json.
#
# :param data: Dict to convert into JSON
# :type data: dict or str
# :return: Received data in json format
# :rtype: str
# """
# if isinstance(data, six.text_type):
# return data
#
# data_ = json.dumps(data)
#
# if isinstance(data_, six.binary_type):
# return data_.decode('utf-8')
# else:
# return data_
#
# @staticmethod
# def to_dict(json_str):
# """
# De-serialize a json string into a python dict.
#
# :param str json_str: String to convert into dict
# :return: Received string in dict format
# :rtype: dict
# """
# return json.loads(json_str)
#
# Path: react/utils.py
# def set_up():
# def load_libs(scripts_paths):
# def run_script(script):
. Output only the next line. | </script> |
Given the following code snippet before the placeholder: <|code_start|>
logging.disable(logging.CRITICAL)
_global = '__global'
@contextmanager
def js_file(data):
if isinstance(data, six.text_type):
data = data.encode('utf-8')
temp = tempfile.NamedTemporaryFile(delete=False)
temp.write(data)
temp.close()
try:
yield temp.name
finally:
os.remove(temp.name)
class UtilsTest(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
<|code_end|>
, predict the next line using imports from the current file:
from unittest.mock import patch
from mock import patch
from contextlib import contextmanager
from react import utils
import unittest
import logging
import os
import tempfile
import six
import react
and context including class names, function names, and sometimes code from other files:
# Path: react/utils.py
# def set_up():
# def load_libs(scripts_paths):
# def run_script(script):
. Output only the next line. | def test_set_up(self): |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
try:
except ImportError:
logging.disable(logging.CRITICAL)
<|code_end|>
with the help of current file imports:
from unittest.mock import patch
from mock import patch
from react.react import _DEFINE_GLOBALS_SCRIPT
import unittest
import logging
import collections
import six
import react
and context from other files:
# Path: react/react.py
# _DEFINE_GLOBALS_SCRIPT = (
# 'var global = global || this,'
# 'console = console || {'
# ' warn: function(){},'
# ' error: function(){},'
# ' log: function(){},'
# ' info: function(){}};')
, which may contain function names, class names, or code. Output only the next line. | class ReactTest(unittest.TestCase): |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
BASE_PATH = os.path.dirname(os.path.abspath(__file__))
OUTPUT_PATH = os.path.join(BASE_PATH, 'index.html')
BUNDLE_PATH = os.path.join(BASE_PATH, 'src', 'bundle.js')
template = """<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
<link rel="stylesheet" href="src/style.css">
</head>
<body>
<|code_end|>
, generate the next line using the imports in this file:
import os
import time
import io
import react
from react import React
from react import utils
and context (functions, classes, or occasionally code) from other files:
# Path: react/react.py
# class React:
# """
# Wrap basic functionality to\
# render react views. The only\
# thing it cares is that there\
# is a global.RenderToString(opts)\
# function defined in the pre-loaded\
# js libs. This render function\
# renders a component, matches a route, etc\
# and returns the rendered view\
# or a json with extra data.
#
# :param dict opts: Dict of parameters the\
# js render function will receive, it must\
# be serializable with json
# """
# def __init__(self, opts):
# self.opts = opts
#
# def build_js_script(self):
# """
# :return: The call to the JS render function
# :rtype: str
# """
# return ('global.RenderToString({})'
# .format(self.as_json()))
#
# def render(self):
# """
# :return: Result of the JS render call
# :rtype: str
# :raises react.excepts.V8Error: if there was\
# an error running the JS script
# """
# return utils.run_script(self.build_js_script())
#
# def as_json(self):
# """
# Serialize :py:attr:`.opts` into a json.\
# This is used internally and can\
# be overridden to provide a faster\
# json serializer.
#
# :return: Opts in json format
# :rtype: str
# """
# return self.to_json(self.opts)
#
# @staticmethod
# def to_json(data):
# """
# Serialize a dict into a json.
#
# :param data: Dict to convert into JSON
# :type data: dict or str
# :return: Received data in json format
# :rtype: str
# """
# if isinstance(data, six.text_type):
# return data
#
# data_ = json.dumps(data)
#
# if isinstance(data_, six.binary_type):
# return data_.decode('utf-8')
# else:
# return data_
#
# @staticmethod
# def to_dict(json_str):
# """
# De-serialize a json string into a python dict.
#
# :param str json_str: String to convert into dict
# :return: Received string in dict format
# :rtype: dict
# """
# return json.loads(json_str)
#
# Path: react/utils.py
# def set_up():
# def load_libs(scripts_paths):
# def run_script(script):
. Output only the next line. | <div id="content">{pre_rendered_content}</div> |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
BASE_PATH = os.path.dirname(os.path.abspath(__file__))
OUTPUT_PATH = os.path.join(BASE_PATH, 'index.html')
BUNDLE_PATH = os.path.join(BASE_PATH, 'src', 'bundle.js')
template = """<!DOCTYPE html>
<|code_end|>
, predict the next line using imports from the current file:
import os
import time
import io
import react
from react import React
from react import utils
and context including class names, function names, and sometimes code from other files:
# Path: react/react.py
# class React:
# """
# Wrap basic functionality to\
# render react views. The only\
# thing it cares is that there\
# is a global.RenderToString(opts)\
# function defined in the pre-loaded\
# js libs. This render function\
# renders a component, matches a route, etc\
# and returns the rendered view\
# or a json with extra data.
#
# :param dict opts: Dict of parameters the\
# js render function will receive, it must\
# be serializable with json
# """
# def __init__(self, opts):
# self.opts = opts
#
# def build_js_script(self):
# """
# :return: The call to the JS render function
# :rtype: str
# """
# return ('global.RenderToString({})'
# .format(self.as_json()))
#
# def render(self):
# """
# :return: Result of the JS render call
# :rtype: str
# :raises react.excepts.V8Error: if there was\
# an error running the JS script
# """
# return utils.run_script(self.build_js_script())
#
# def as_json(self):
# """
# Serialize :py:attr:`.opts` into a json.\
# This is used internally and can\
# be overridden to provide a faster\
# json serializer.
#
# :return: Opts in json format
# :rtype: str
# """
# return self.to_json(self.opts)
#
# @staticmethod
# def to_json(data):
# """
# Serialize a dict into a json.
#
# :param data: Dict to convert into JSON
# :type data: dict or str
# :return: Received data in json format
# :rtype: str
# """
# if isinstance(data, six.text_type):
# return data
#
# data_ = json.dumps(data)
#
# if isinstance(data_, six.binary_type):
# return data_.decode('utf-8')
# else:
# return data_
#
# @staticmethod
# def to_dict(json_str):
# """
# De-serialize a json string into a python dict.
#
# :param str json_str: String to convert into dict
# :return: Received string in dict format
# :rtype: dict
# """
# return json.loads(json_str)
#
# Path: react/utils.py
# def set_up():
# def load_libs(scripts_paths):
# def run_script(script):
. Output only the next line. | <html> |
Here is a snippet: <|code_start|> cred_issued = cred_secret_issue(params, pub, EGenc, ipub, isec, public_attr)
u, EncE, sig_s = decode(encode(cred_issued))
## The user decrypts the amac
mac = cred_secret_issue_user_decrypt(params, keypair, u, EncE, ipub, public_attr, EGenc, sig_s)
mac = decode(encode(mac))
## User Shows back full credential to issuer
(creds, sig_o, zis) = cred_show(params, ipub, mac, sig_s, public_attr + private_attr, export_zi=True)
## The credential contains a number of commitments to the attributes
(u, Cmis, Cup) = creds
assert len(Cmis) == 2
assert Cmis[0] == timeout * u + zis[0] * h
assert Cmis[1] == LT_user_ID * u + zis[1] * h
# Derive a service specific User ID
Gid = G.hash_to_point(b"ServiceNameRP")
Uid = LT_user_ID * Gid
# Define the statements to be proved
zk = define_proof(G)
# Define the proof environemnt
env = ZKEnv(zk)
env.u, env.h = u, h
env.Cm0p, env.Cm1 = Cmis[0] - (timeout * u), Cmis[1]
env.Uid, env.Gid = Uid, Gid
env.LT_ID = LT_user_ID
<|code_end|>
. Write the next line using the current file imports:
from amacscreds import cred_setup, cred_CredKeyge, cred_UserKeyge, cred_secret_issue_user, cred_secret_issue, cred_secret_issue_user_decrypt, cred_show, cred_show_check, cred_secret_issue_user_check
from genzkp import *
from petlib.pack import encode, decode
and context from other files:
# Path: petlib/pack.py
# def encode(structure, custom_encoder=None):
# """ Encode a structure containing petlib objects to a binary format. May define a custom encoder for user classes. """
# encoder = make_encoder(custom_encoder)
# packed_data = msgpack.packb(structure, default=encoder, use_bin_type=True)
# return packed_data
#
# def decode(packed_data, custom_decoder=None):
# """ Decode a binary byte sequence into a structure containing pelib objects. May define a custom decoder for custom classes. """
# decoder = make_decoder(custom_decoder)
# structure = msgpack.unpackb(
# packed_data,
# ext_hook=decoder,
# encoding='utf-8')
# return structure
, which may include functions, classes, or code. Output only the next line. | env.z0, env.z1 = zis[0], zis[1] |
Given the code snippet: <|code_start|>
try:
_OPENSSL_VERSION = get_openssl_version(_C)
except:
_OPENSSL_VERSION = OpenSSLVersion.V1_1
# Store constants
class Const:
POINT_CONVERSION_COMPRESSED = 2,
POINT_CONVERSION_UNCOMPRESSED = 4,
POINT_CONVERSION_HYBRID = 6
_inited = False
def version():
if _OPENSSL_VERSION == OpenSSLVersion.V1_0:
cstr = _C.SSLeay_version(_C.SSLEAY_VERSION)
else:
cstr = _C.OpenSSL_version(_C.OPENSSL_VERSION)
return str(_FFI.string(cstr))
def get_errors():
errors = []
err = _C.ERR_get_error()
<|code_end|>
, generate the next line using the imports in this file:
import os
import platform
import cffi
import sys
import threading
from ._petlib import ffi, lib
from ._compat import get_openssl_version, OpenSSLVersion # pylint: disable=unused-import
from .ec import EcPt, EcGroup
and context (functions, classes, or occasionally code) from other files:
# Path: petlib/_compat.py
# def get_openssl_version(lib=None, warn=False):
# """Returns the OpenSSL version that is used for bindings."""
#
# if lib is None:
# lib = get_abi_lib()
#
# try:
# full_version = lib.OpenSSL_version_num()
# except AttributeError:
# full_version = lib.SSLeay()
#
# version = full_version >> 20
# if version == 0x101:
# return OpenSSLVersion.V1_1
# elif version == 0x100:
# if warn:
# warnings.warn(
# "Support for the system OpenSSL version (0x%x) is pending deprecation. "
# "Please upgrade to OpenSSL v1.1" % version)
# return OpenSSLVersion.V1_0
# else:
# # If the version is not 1.0 or 1.1, assume its a later one, and optimistically
# # assume it doesn't horribly break the interface this time.
# if warn:
# warnings.warn(
# "System OpenSSL version is not supported: %d. "
# "Attempting to use in OpenSSL v1.1 mode." % version)
# return OpenSSLVersion.V1_1
#
# class OpenSSLVersion:
# V1_0 = "1_0"
# V1_1 = "1_1"
. Output only the next line. | while err != 0: |
Continue the code snippet: <|code_start|> errors += [err]
err = _C.ERR_get_error()
assert isinstance(errors, list)
return errors
class InitCiphers(object):
# pylint: disable=global-statement
def __init__(self):
global _inited
self.on = False
self._C = _C
if not _inited:
_C.OPENSSL_init()
_C.init_ciphers()
_inited = True
self.on = True
def __del__(self):
global _inited
if _inited and self.on and self._C:
_inited = False
self._C.cleanup_ciphers()
if _C and _FFI:
_ciphers = InitCiphers()
if _OPENSSL_VERSION == OpenSSLVersion.V1_0:
if _C.CRYPTO_get_locking_callback() == _FFI.NULL:
<|code_end|>
. Use current file imports:
import os
import platform
import cffi
import sys
import threading
from ._petlib import ffi, lib
from ._compat import get_openssl_version, OpenSSLVersion # pylint: disable=unused-import
from .ec import EcPt, EcGroup
and context (classes, functions, or code) from other files:
# Path: petlib/_compat.py
# def get_openssl_version(lib=None, warn=False):
# """Returns the OpenSSL version that is used for bindings."""
#
# if lib is None:
# lib = get_abi_lib()
#
# try:
# full_version = lib.OpenSSL_version_num()
# except AttributeError:
# full_version = lib.SSLeay()
#
# version = full_version >> 20
# if version == 0x101:
# return OpenSSLVersion.V1_1
# elif version == 0x100:
# if warn:
# warnings.warn(
# "Support for the system OpenSSL version (0x%x) is pending deprecation. "
# "Please upgrade to OpenSSL v1.1" % version)
# return OpenSSLVersion.V1_0
# else:
# # If the version is not 1.0 or 1.1, assume its a later one, and optimistically
# # assume it doesn't horribly break the interface this time.
# if warn:
# warnings.warn(
# "System OpenSSL version is not supported: %d. "
# "Attempting to use in OpenSSL v1.1 mode." % version)
# return OpenSSLVersion.V1_1
#
# class OpenSSLVersion:
# V1_0 = "1_0"
# V1_1 = "1_1"
. Output only the next line. | _C.setup_ssl_threads() |
Predict the next line for this snippet: <|code_start|> except AttributeError:
return self.mod_inverse(Bn.from_num(m))
def mod_pow(self, other, m, ctx=None):
""" Performs the modular exponentiation of self ** other % m.
Example:
>>> one100 = Bn(100)
>>> one100.mod_pow(2, 3) # Modular exponentiation
1
"""
return self.__pow__(other, m, ctx=ctx)
def divmod(self, other):
"""Returns the integer division and remainder of this number by another.
Synonym for (div, mod) = divmod(self, other)"""
return self.__divmod__(other)
def __rdivmod__(self, other):
return Bn(other).__divmod__(self)
def __divmod__(self, other):
try:
dv = Bn()
rem = Bn()
local_ctx = get_ctx()
ret = _C.BN_div(dv.bn, rem.bn, self.bn, other.bn, local_ctx.bnctx)
if __debug__:
_check(ret)
<|code_end|>
with the help of current file imports:
from .bindings import _FFI, _C, get_errors
from functools import wraps
from copy import copy, deepcopy
from binascii import hexlify, unhexlify # pylint: disable=unused-import
from builtins import int # pylint: disable=redefined-builtin
from builtins import object # pylint: disable=redefined-builtin
from future.utils import python_2_unicode_compatible
import pytest
import threading
import time
and context from other files:
# Path: petlib/bindings.py
# _FFI = ffi
#
# _C = lib
#
# def get_errors():
# errors = []
# err = _C.ERR_get_error()
# while err != 0:
# errors += [err]
# err = _C.ERR_get_error()
# assert isinstance(errors, list)
# return errors
, which may contain function names, class names, or code. Output only the next line. | return (dv, rem) |
Predict the next line for this snippet: <|code_start|>_thread_local = threading.local()
def get_ctx():
global _thread_local
try:
return _thread_local.ctx
except BaseException:
_thread_local.ctx = BnCtx()
return _thread_local.ctx
@python_2_unicode_compatible
class Bn(object):
"""The core Big Number class.
It supports all comparisons (<, <=, ==, !=, >=, >),
arithmetic operations (+, -, %, /, divmod, pow)
and copy operations (copy and deep copy). The right-hand
side operand may be a small native python integer (<2^64). """
__C = _C
# We know this class will keep minimal state
__slots__ = ['bn']
# -- static methods
@staticmethod
def from_num(num):
<|code_end|>
with the help of current file imports:
from .bindings import _FFI, _C, get_errors
from functools import wraps
from copy import copy, deepcopy
from binascii import hexlify, unhexlify # pylint: disable=unused-import
from builtins import int # pylint: disable=redefined-builtin
from builtins import object # pylint: disable=redefined-builtin
from future.utils import python_2_unicode_compatible
import pytest
import threading
import time
and context from other files:
# Path: petlib/bindings.py
# _FFI = ffi
#
# _C = lib
#
# def get_errors():
# errors = []
# err = _C.ERR_get_error()
# while err != 0:
# errors += [err]
# err = _C.ERR_get_error()
# assert isinstance(errors, list)
# return errors
, which may contain function names, class names, or code. Output only the next line. | if isinstance(num, int): |
Given the code snippet: <|code_start|> except BaseException:
_thread_local.ctx = BnCtx()
return _thread_local.ctx
@python_2_unicode_compatible
class Bn(object):
"""The core Big Number class.
It supports all comparisons (<, <=, ==, !=, >=, >),
arithmetic operations (+, -, %, /, divmod, pow)
and copy operations (copy and deep copy). The right-hand
side operand may be a small native python integer (<2^64). """
__C = _C
# We know this class will keep minimal state
__slots__ = ['bn']
# -- static methods
@staticmethod
def from_num(num):
if isinstance(num, int):
return Bn(num)
elif isinstance(num, Bn):
return num
else:
# raise TypeError("Cannot coerce %s into a BN." % num)
return NotImplemented
<|code_end|>
, generate the next line using the imports in this file:
from .bindings import _FFI, _C, get_errors
from functools import wraps
from copy import copy, deepcopy
from binascii import hexlify, unhexlify # pylint: disable=unused-import
from builtins import int # pylint: disable=redefined-builtin
from builtins import object # pylint: disable=redefined-builtin
from future.utils import python_2_unicode_compatible
import pytest
import threading
import time
and context (functions, classes, or occasionally code) from other files:
# Path: petlib/bindings.py
# _FFI = ffi
#
# _C = lib
#
# def get_errors():
# errors = []
# err = _C.ERR_get_error()
# while err != 0:
# errors += [err]
# err = _C.ERR_get_error()
# assert isinstance(errors, list)
# return errors
. Output only the next line. | @staticmethod |
Using the snippet: <|code_start|> ")" : None,
"*" : "asterisk",
"+" : "plus",
"," : "comma",
"-" : "minus",
"." : None,
"/" : "slash",
":" : "colon",
";" : "semicolon",
"=" : "equal",
">" : "greater",
"?" : "question",
"@" : "at",
"[" : "bracketleft",
"\\" : "backslash",
"]" : "bracketright",
"^" : None,
"_" : "underscore"
}
# set keyboard characteristics
self.set_keylist(keylist)
self.set_timeout(timeout)
def set_keylist(self, keylist=None):
# See _keyboard.basekeyboard.BaseKeyboard
if keylist == None or keylist == []:
<|code_end|>
, determine the next line of code. You have imports:
from pygaze.libtime import clock
from pygaze import settings
from pygaze._keyboard.basekeyboard import BaseKeyboard
from pygaze._misc.misc import copy_docstr
import pygaze
import psychopy.event
and context (class names, function names, or code) available:
# Path: pygaze/libtime.py
# def expstart():
# def get_time():
# def pause(pausetime):
# def expend():
#
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
#
# Path: pygaze/_keyboard/basekeyboard.py
# class BaseKeyboard:
#
# """A keyboard for collecting responses"""
#
# def __init__(self):
#
# """
# Initializes the Keyboard object
#
# arguments
#
# None
#
# keyword arguments
#
# keylist -- list of keys that are allowed, e.g. ["1","a","enter"]
# for the 1, A and Enter keys (default =
# KEYLIST)
# timeout -- time in milliseconds after which None is returned
# on a call to the get_key method when no keypress is
# registered (default = KEYTIMEOUT)
# """
#
# pass
#
#
# def set_keylist(self):
#
# """
# Set a list of accepted keys
#
# arguments
#
# None
#
# keyword arguments
#
# keylist -- list of keys that are allowed (e.g.
# ["1","a","enter"]) or None to allow all keys
# (default = None)
#
# returns
#
# None -- sets klist property
# """
#
# pass
#
#
# def set_timeout(self):
#
# """
# Set a timeout (in milliseconds)
#
# arguments
#
# None
#
# keyword arguments
#
# timeout -- time in milliseconds after which None is returned
# on a call to get_key method when no keypress is
# registered (default = None)
#
# returns
#
# None -- sets timeout property
# """
#
# pass
#
#
# def get_key(self):
#
# """
# Wait for keyboard input
#
# arguments
#
# None
#
# keyword arguments
#
# keylist -- list of keys that are allowed (e.g.
# ["1","a","enter"]), None to allow all keys or
# "default" to use klist property (default = "default")
# timeout -- time in milliseconds after which None is returned
# when no keypress is registered (default = None);
# None for no timeout or "default" to use the timeout
# property (default = "default")
# flush -- Boolean indicating if all input from before
# calling get_key should be ignored, if set to
# False keypresses from before calling this
# function will be registered, otherwise every
# keyboard input from before calling this function
# will be flushed (default = False)
#
# returns
#
# key, presstime -- key is a string, indicating which button has
# been pressed or None when no key has been
# pressed
# presstime is the time (measured from
# expbegintime) a keypress or a timeout occured
# """
#
# pass
. Output only the next line. | self.klist = None
|
Using the snippet: <|code_start|>class PsychoPyKeyboard(BaseKeyboard):
# See _keyboard.basekeyboard.BaseKeyboard
def __init__(self, keylist=settings.KEYLIST, timeout=settings.KEYTIMEOUT):
# See _keyboard.basekeyboard.BaseKeyboard
# try to copy docstring (but ignore it if it fails, as we do
# not need it for actual functioning of the code)
try:
copy_docstr(BaseKeyboard, PsychoPyKeyboard)
except:
# we're not even going to show a warning, since the copied
# docstring is useful for code editors; these load the docs
# in a non-verbose manner, so warning messages would be lost
pass
# keymap
self.keymap = {
"!" : "exclamation",
'"' : "doublequote",
"#" : "hash",
"$" : "dollar",
"&" : "ampersand",
# '\"' : "quoteleft",
"(" : None,
")" : None,
"*" : "asterisk",
"+" : "plus",
<|code_end|>
, determine the next line of code. You have imports:
from pygaze.libtime import clock
from pygaze import settings
from pygaze._keyboard.basekeyboard import BaseKeyboard
from pygaze._misc.misc import copy_docstr
import pygaze
import psychopy.event
and context (class names, function names, or code) available:
# Path: pygaze/libtime.py
# def expstart():
# def get_time():
# def pause(pausetime):
# def expend():
#
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
#
# Path: pygaze/_keyboard/basekeyboard.py
# class BaseKeyboard:
#
# """A keyboard for collecting responses"""
#
# def __init__(self):
#
# """
# Initializes the Keyboard object
#
# arguments
#
# None
#
# keyword arguments
#
# keylist -- list of keys that are allowed, e.g. ["1","a","enter"]
# for the 1, A and Enter keys (default =
# KEYLIST)
# timeout -- time in milliseconds after which None is returned
# on a call to the get_key method when no keypress is
# registered (default = KEYTIMEOUT)
# """
#
# pass
#
#
# def set_keylist(self):
#
# """
# Set a list of accepted keys
#
# arguments
#
# None
#
# keyword arguments
#
# keylist -- list of keys that are allowed (e.g.
# ["1","a","enter"]) or None to allow all keys
# (default = None)
#
# returns
#
# None -- sets klist property
# """
#
# pass
#
#
# def set_timeout(self):
#
# """
# Set a timeout (in milliseconds)
#
# arguments
#
# None
#
# keyword arguments
#
# timeout -- time in milliseconds after which None is returned
# on a call to get_key method when no keypress is
# registered (default = None)
#
# returns
#
# None -- sets timeout property
# """
#
# pass
#
#
# def get_key(self):
#
# """
# Wait for keyboard input
#
# arguments
#
# None
#
# keyword arguments
#
# keylist -- list of keys that are allowed (e.g.
# ["1","a","enter"]), None to allow all keys or
# "default" to use klist property (default = "default")
# timeout -- time in milliseconds after which None is returned
# when no keypress is registered (default = None);
# None for no timeout or "default" to use the timeout
# property (default = "default")
# flush -- Boolean indicating if all input from before
# calling get_key should be ignored, if set to
# False keypresses from before calling this
# function will be registered, otherwise every
# keyboard input from before calling this function
# will be flushed (default = False)
#
# returns
#
# key, presstime -- key is a string, indicating which button has
# been pressed or None when no key has been
# pressed
# presstime is the time (measured from
# expbegintime) a keypress or a timeout occured
# """
#
# pass
. Output only the next line. | "," : "comma",
|
Continue the code snippet: <|code_start|>
def set_timeout(self, timeout=None):
# See _keyboard.basekeyboard.BaseKeyboard
self.timeout = timeout
def get_key(self, keylist="default", timeout="default", flush=False):
# See _keyboard.basekeyboard.BaseKeyboard
# set keylist and timeout
if keylist == "default":
keylist = self.klist
if timeout == "default":
timeout = self.timeout
# flush if necessary
if flush:
psychopy.event.clearEvents(eventType="keyboard")
# starttime
starttime = clock.get_time()
time = clock.get_time()
# wait for input
while timeout == None or time - starttime <= timeout:
keys = psychopy.event.getKeys(keyList=keylist,timeStamped=False)
for key in keys:
<|code_end|>
. Use current file imports:
from pygaze.libtime import clock
from pygaze import settings
from pygaze._keyboard.basekeyboard import BaseKeyboard
from pygaze._misc.misc import copy_docstr
import pygaze
import psychopy.event
and context (classes, functions, or code) from other files:
# Path: pygaze/libtime.py
# def expstart():
# def get_time():
# def pause(pausetime):
# def expend():
#
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
#
# Path: pygaze/_keyboard/basekeyboard.py
# class BaseKeyboard:
#
# """A keyboard for collecting responses"""
#
# def __init__(self):
#
# """
# Initializes the Keyboard object
#
# arguments
#
# None
#
# keyword arguments
#
# keylist -- list of keys that are allowed, e.g. ["1","a","enter"]
# for the 1, A and Enter keys (default =
# KEYLIST)
# timeout -- time in milliseconds after which None is returned
# on a call to the get_key method when no keypress is
# registered (default = KEYTIMEOUT)
# """
#
# pass
#
#
# def set_keylist(self):
#
# """
# Set a list of accepted keys
#
# arguments
#
# None
#
# keyword arguments
#
# keylist -- list of keys that are allowed (e.g.
# ["1","a","enter"]) or None to allow all keys
# (default = None)
#
# returns
#
# None -- sets klist property
# """
#
# pass
#
#
# def set_timeout(self):
#
# """
# Set a timeout (in milliseconds)
#
# arguments
#
# None
#
# keyword arguments
#
# timeout -- time in milliseconds after which None is returned
# on a call to get_key method when no keypress is
# registered (default = None)
#
# returns
#
# None -- sets timeout property
# """
#
# pass
#
#
# def get_key(self):
#
# """
# Wait for keyboard input
#
# arguments
#
# None
#
# keyword arguments
#
# keylist -- list of keys that are allowed (e.g.
# ["1","a","enter"]), None to allow all keys or
# "default" to use klist property (default = "default")
# timeout -- time in milliseconds after which None is returned
# when no keypress is registered (default = None);
# None for no timeout or "default" to use the timeout
# property (default = "default")
# flush -- Boolean indicating if all input from before
# calling get_key should be ignored, if set to
# False keypresses from before calling this
# function will be registered, otherwise every
# keyboard input from before calling this function
# will be flushed (default = False)
#
# returns
#
# key, presstime -- key is a string, indicating which button has
# been pressed or None when no key has been
# pressed
# presstime is the time (measured from
# expbegintime) a keypress or a timeout occured
# """
#
# pass
. Output only the next line. | if keylist == None or key in keylist:
|
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
#
# This file is part of PyGaze - the open-source toolbox for eye tracking
#
# PyGaze is a Python module for easily creating gaze contingent experiments
# or other software (as well as non-gaze contingent experiments/software)
# Copyright (C) 2012-2013 Edwin S. Dalmaijer
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
# try importing PIL
try:
except:
try:
<|code_end|>
, generate the next line using the imports in this file:
from pygaze import settings
from pygaze.screen import Screen
from pygaze.mouse import Mouse
from pygaze.keyboard import Keyboard
from pygaze.sound import Sound
from PIL import Image
import pygaze
import os
import sys
import platform
import array
import Image
import pylink
import pygame
import psychopy
import pygame
import tempfile
import os
and context (functions, classes, or occasionally code) from other files:
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
#
# Path: pygaze/screen.py
# class Screen(BaseScreen):
#
# """
# A class for Screen objects, for visual stimuli (to be displayed via a
# Display object)
# """
#
# def __init__(self, disptype=settings.DISPTYPE, **args):
#
# """
# Initializes the Screen object.
#
# Keyword arguments:
# disptype -- Type of display: either "pygame" or "psychopy"
# (default = DISPTYPE)
# dispsize -- size of the display in pixels: a (width, height)
# tuple (default = DISPSIZE)
# fgc -- the foreground colour: a colour name (e.g. "red") or
# a RGB(A) tuple (e.g. (255,0,0) or (255,0,0,255))
# (default = FGC)
# bgc -- the background colour: a colour name (e.g. "red") or
# a RGB(A) tuple (e.g. (255,0,0) or (255,0,0,255))
# (default = BGC)
# screennr -- the screen number: 0, 1 etc. (default =
# SCREENNR)
# mousevisible -- Boolean indicating mouse visibility (default =
# MOUSEVISIBLE)
# screen -- a Screen object to be presented on the new Display
# (default=None)
# """
#
# if disptype == "pygame":
# from pygaze._screen.pygamescreen import PyGameScreen as Screen
# elif disptype == "psychopy":
# from pygaze._screen.psychopyscreen import PsychoPyScreen as Screen
# elif disptype == "opensesame":
# from pygaze._screen.osscreen import OSScreen as Screen
# else:
# raise Exception("Unexpected disptype: {}".format(disptype))
# self.__class__ = Screen
# self.__class__.__init__(self, **args)
# copy_docstr(BaseScreen, Screen)
#
# Path: pygaze/mouse.py
# class Mouse(BaseMouse):
#
# """A mouse for collecting responses"""
#
# def __init__(self, disptype=settings.DISPTYPE, **args):
#
# """
# See BaseMouse docstring
# """
#
# if disptype == "pygame":
# from pygaze._mouse.pygamemouse import PyGameMouse as Mouse
# elif disptype == "psychopy":
# from pygaze._mouse.psychopymouse import PsychoPyMouse as Mouse
# elif disptype == "opensesame":
# from pygaze._mouse.osmouse import OSMouse as Mouse
# else:
# raise Exception("Unexpected disptype: {}".format(disptype))
# self.__class__ = Mouse
# self.__class__.__init__(self, **args)
# copy_docstr(BaseMouse, Mouse)
#
# Path: pygaze/keyboard.py
# class Keyboard(BaseKeyboard):
#
# # see BaseKeyboard
#
# def __init__(self, disptype=settings.DISPTYPE, **args):
#
# # see BaseKeyboard
#
# if disptype == "pygame":
# from pygaze._keyboard.pygamekeyboard import PyGameKeyboard as \
# Keyboard
# elif disptype == "psychopy":
# from pygaze._keyboard.psychopykeyboard import PsychoPyKeyboard as \
# Keyboard
# elif disptype == "opensesame":
# from pygaze._keyboard.oskeyboard import OSKeyboard as \
# Keyboard
# else:
# raise Exception("Unexpected disptype: %s".format(disptype))
# self.__class__ = Keyboard
# self.__class__.__init__(self, **args)
# copy_docstr(BaseKeyboard, Keyboard)
#
# Path: pygaze/sound.py
# class Sound(BaseSound):
#
# """Sound playback"""
#
# def __init__(self, disptype=settings.DISPTYPE, **args):
#
# """
# See BaseSound docstring
# """
#
# if disptype in ("pygame", "psychopy", "opensesame"):
# from pygaze._sound.pygamesound import PyGameSound as Sound
# else:
# raise Exception("Unexpected disptype: {}".format(disptype))
# self.__class__ = Sound
# self.__class__.__init__(self, **args)
# copy_docstr(BaseSound, Sound)
. Output only the next line. | except: |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
#
# This file is part of PyGaze - the open-source toolbox for eye tracking
#
# PyGaze is a Python module for easily creating gaze contingent experiments
# or other software (as well as non-gaze contingent experiments/software)
# Copyright (C) 2012-2013 Edwin S. Dalmaijer
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
# try importing PIL
try:
except:
try:
except:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pygaze import settings
from pygaze.screen import Screen
from pygaze.mouse import Mouse
from pygaze.keyboard import Keyboard
from pygaze.sound import Sound
from PIL import Image
import pygaze
import os
import sys
import platform
import array
import Image
import pylink
import pygame
import psychopy
import pygame
import tempfile
import os
and context:
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
#
# Path: pygaze/screen.py
# class Screen(BaseScreen):
#
# """
# A class for Screen objects, for visual stimuli (to be displayed via a
# Display object)
# """
#
# def __init__(self, disptype=settings.DISPTYPE, **args):
#
# """
# Initializes the Screen object.
#
# Keyword arguments:
# disptype -- Type of display: either "pygame" or "psychopy"
# (default = DISPTYPE)
# dispsize -- size of the display in pixels: a (width, height)
# tuple (default = DISPSIZE)
# fgc -- the foreground colour: a colour name (e.g. "red") or
# a RGB(A) tuple (e.g. (255,0,0) or (255,0,0,255))
# (default = FGC)
# bgc -- the background colour: a colour name (e.g. "red") or
# a RGB(A) tuple (e.g. (255,0,0) or (255,0,0,255))
# (default = BGC)
# screennr -- the screen number: 0, 1 etc. (default =
# SCREENNR)
# mousevisible -- Boolean indicating mouse visibility (default =
# MOUSEVISIBLE)
# screen -- a Screen object to be presented on the new Display
# (default=None)
# """
#
# if disptype == "pygame":
# from pygaze._screen.pygamescreen import PyGameScreen as Screen
# elif disptype == "psychopy":
# from pygaze._screen.psychopyscreen import PsychoPyScreen as Screen
# elif disptype == "opensesame":
# from pygaze._screen.osscreen import OSScreen as Screen
# else:
# raise Exception("Unexpected disptype: {}".format(disptype))
# self.__class__ = Screen
# self.__class__.__init__(self, **args)
# copy_docstr(BaseScreen, Screen)
#
# Path: pygaze/mouse.py
# class Mouse(BaseMouse):
#
# """A mouse for collecting responses"""
#
# def __init__(self, disptype=settings.DISPTYPE, **args):
#
# """
# See BaseMouse docstring
# """
#
# if disptype == "pygame":
# from pygaze._mouse.pygamemouse import PyGameMouse as Mouse
# elif disptype == "psychopy":
# from pygaze._mouse.psychopymouse import PsychoPyMouse as Mouse
# elif disptype == "opensesame":
# from pygaze._mouse.osmouse import OSMouse as Mouse
# else:
# raise Exception("Unexpected disptype: {}".format(disptype))
# self.__class__ = Mouse
# self.__class__.__init__(self, **args)
# copy_docstr(BaseMouse, Mouse)
#
# Path: pygaze/keyboard.py
# class Keyboard(BaseKeyboard):
#
# # see BaseKeyboard
#
# def __init__(self, disptype=settings.DISPTYPE, **args):
#
# # see BaseKeyboard
#
# if disptype == "pygame":
# from pygaze._keyboard.pygamekeyboard import PyGameKeyboard as \
# Keyboard
# elif disptype == "psychopy":
# from pygaze._keyboard.psychopykeyboard import PsychoPyKeyboard as \
# Keyboard
# elif disptype == "opensesame":
# from pygaze._keyboard.oskeyboard import OSKeyboard as \
# Keyboard
# else:
# raise Exception("Unexpected disptype: %s".format(disptype))
# self.__class__ = Keyboard
# self.__class__.__init__(self, **args)
# copy_docstr(BaseKeyboard, Keyboard)
#
# Path: pygaze/sound.py
# class Sound(BaseSound):
#
# """Sound playback"""
#
# def __init__(self, disptype=settings.DISPTYPE, **args):
#
# """
# See BaseSound docstring
# """
#
# if disptype in ("pygame", "psychopy", "opensesame"):
# from pygaze._sound.pygamesound import PyGameSound as Sound
# else:
# raise Exception("Unexpected disptype: {}".format(disptype))
# self.__class__ = Sound
# self.__class__.__init__(self, **args)
# copy_docstr(BaseSound, Sound)
which might include code, classes, or functions. Output only the next line. | print("Failed to import PIL.") |
Given snippet: <|code_start|># it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
# we try importing the copy_docstr function, but as we do not really need it
# for a proper functioning of the code, we simply ignore it when it fails to
# be imported correctly
try:
except:
pass
class OSDisplay(BaseDisplay):
# See _display.basedisplay.BaseDisplay for documentation
def __init__(self, **args):
# See _display.basedisplay.BaseDisplay for documentation
# try to import copy docstring (but ignore it if it fails, as we do
# not need it for actual functioning of the code)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pygaze.py3compat import *
from pygaze import settings
from libopensesame.exceptions import osexception
from openexp.canvas import canvas
from openexp.keyboard import keyboard
from pygaze._display.basedisplay import BaseDisplay
from pygaze._misc.misc import copy_docstr
and context:
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
#
# Path: pygaze/_display/basedisplay.py
# class BaseDisplay:
#
# """A class for Display objects, to present Screen objects on a monitor"""
#
# def __init__(self):
#
# """
# Initializes a Display object.
#
# arguments
#
# None
#
# keyword arguments
#
# dispsize -- size of the display in pixels: a (width, height)
# tuple (default = DISPSIZE)
# fgc -- the foreground colour: a RGB tuple, e.g. (255,0,0)
# for red or (0,0,0) for black (default = FGC)
# bgc -- the background colour: a RGB tuple, e.g. (0,0,255)
# for blue or (255,255,255) for white (default = BGC)
# screen -- a screen.Screen instance to be presented on the new
# Display (default=None)
# """
#
# pass
#
# def show(self):
#
# """
# Updates ('flips') the display.
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
# time -- the exact refresh time when disptype is PsychoPy,
# or an estimate when disptype is PyGame
# """
#
# pass
#
# def show_part(self, rect, screen=None):
#
# """
# Fills AND shows part(s) of the screen to given specified screen
# (only works when disptype is PyGame; when this is set to PsychoPy
# the entire display is filled and updated)
#
# arguments
#
# rect -- a single or a list of rects; a rect is a (x,y,w,h)
# tuple or list
#
# keyword arguments
#
# screen -- the screen of which the specified rects should be
# updated to the display (default = None)
#
# returns
#
# time -- the exact refresh time when disptype is PsychoPy,
# or an estimate when disptype is PyGame
# """
#
# pass
#
# def fill(self, screen=None):
#
# """
# Fills the screen with the background colour of the Screen, NOT
# updating it (call Display.show() to actually show the new contents)
#
# arguments
#
# None
#
# keyword arguments
#
# screen -- the screen that should be drawn to the display or
# None to fill the display with its background colour
#
# returns
#
# None
# """
#
# pass
#
# def close(self):
#
# """
# Closes the display
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
#
# None
# """
#
# pass
#
# def make_screenshot(self, filename="screenshot.png"):
#
# """
# Make a screenshot from the current display.
#
# arguments
#
# None
#
# keyword arguments
#
# filename -- path and filename, under wich the screenshot will be
# saved. Defaults to screenshot.png
#
# returns
#
# None
# """
#
# pass
which might include code, classes, or functions. Output only the next line. | try:
|
Here is a snippet: <|code_start|> def __init__(self, **args):
# See _display.basedisplay.BaseDisplay for documentation
# try to import copy docstring (but ignore it if it fails, as we do
# not need it for actual functioning of the code)
try:
copy_docstr(BaseDisplay, OSDisplay)
except:
# we're not even going to show a warning, since the copied
# docstring is useful for code editors; these load the docs
# in a non-verbose manner, so warning messages would be lost
pass
self.experiment = settings.osexperiment
self.canvas = canvas(self.experiment)
self.dispsize = self.experiment.resolution()
def show(self):
# See _display.basedisplay.BaseDisplay for documentation
return self.canvas.show()
def show_part(self, rect, screen=None):
# See _display.basedisplay.BaseDisplay for documentation
return self.canvas.show()
<|code_end|>
. Write the next line using the current file imports:
from pygaze.py3compat import *
from pygaze import settings
from libopensesame.exceptions import osexception
from openexp.canvas import canvas
from openexp.keyboard import keyboard
from pygaze._display.basedisplay import BaseDisplay
from pygaze._misc.misc import copy_docstr
and context from other files:
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
#
# Path: pygaze/_display/basedisplay.py
# class BaseDisplay:
#
# """A class for Display objects, to present Screen objects on a monitor"""
#
# def __init__(self):
#
# """
# Initializes a Display object.
#
# arguments
#
# None
#
# keyword arguments
#
# dispsize -- size of the display in pixels: a (width, height)
# tuple (default = DISPSIZE)
# fgc -- the foreground colour: a RGB tuple, e.g. (255,0,0)
# for red or (0,0,0) for black (default = FGC)
# bgc -- the background colour: a RGB tuple, e.g. (0,0,255)
# for blue or (255,255,255) for white (default = BGC)
# screen -- a screen.Screen instance to be presented on the new
# Display (default=None)
# """
#
# pass
#
# def show(self):
#
# """
# Updates ('flips') the display.
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
# time -- the exact refresh time when disptype is PsychoPy,
# or an estimate when disptype is PyGame
# """
#
# pass
#
# def show_part(self, rect, screen=None):
#
# """
# Fills AND shows part(s) of the screen to given specified screen
# (only works when disptype is PyGame; when this is set to PsychoPy
# the entire display is filled and updated)
#
# arguments
#
# rect -- a single or a list of rects; a rect is a (x,y,w,h)
# tuple or list
#
# keyword arguments
#
# screen -- the screen of which the specified rects should be
# updated to the display (default = None)
#
# returns
#
# time -- the exact refresh time when disptype is PsychoPy,
# or an estimate when disptype is PyGame
# """
#
# pass
#
# def fill(self, screen=None):
#
# """
# Fills the screen with the background colour of the Screen, NOT
# updating it (call Display.show() to actually show the new contents)
#
# arguments
#
# None
#
# keyword arguments
#
# screen -- the screen that should be drawn to the display or
# None to fill the display with its background colour
#
# returns
#
# None
# """
#
# pass
#
# def close(self):
#
# """
# Closes the display
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
#
# None
# """
#
# pass
#
# def make_screenshot(self, filename="screenshot.png"):
#
# """
# Make a screenshot from the current display.
#
# arguments
#
# None
#
# keyword arguments
#
# filename -- path and filename, under wich the screenshot will be
# saved. Defaults to screenshot.png
#
# returns
#
# None
# """
#
# pass
, which may include functions, classes, or code. Output only the next line. | def fill(self, screen=None):
|
Based on the snippet: <|code_start|># Copyright (C) 2012-2013 Edwin S. Dalmaijer
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
class Keyboard(BaseKeyboard):
# see BaseKeyboard
def __init__(self, disptype=settings.DISPTYPE, **args):
# see BaseKeyboard
if disptype == "pygame":
elif disptype == "psychopy":
elif disptype == "opensesame":
else:
raise Exception("Unexpected disptype: %s".format(disptype))
<|code_end|>
, predict the immediate next line with the help of imports:
from pygaze.py3compat import *
from pygaze import settings
from pygaze._misc.misc import copy_docstr
from pygaze._keyboard.basekeyboard import BaseKeyboard
from pygaze._keyboard.pygamekeyboard import PyGameKeyboard as \
Keyboard
from pygaze._keyboard.psychopykeyboard import PsychoPyKeyboard as \
Keyboard
from pygaze._keyboard.oskeyboard import OSKeyboard as \
Keyboard
and context (classes, functions, sometimes code) from other files:
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
#
# Path: pygaze/_misc/misc.py
# def copy_docstr(src, target):
#
# """
# Copies docstrings from the methods of a source class to the methods of a
# target class.
#
# arguments:
# src -- source class (e.g. BaseDisplay)
# target -- target class (e.g. PyGameDisplay)
# """
#
# for attr_name in dir(target):
# if not hasattr(src, attr_name) or not ismethod(getattr(src, attr_name)):
# continue
# getattr(target, attr_name).__func__.__doc__ = getattr(src, attr_name).__func__.__doc__
#
# Path: pygaze/_keyboard/basekeyboard.py
# class BaseKeyboard:
#
# """A keyboard for collecting responses"""
#
# def __init__(self):
#
# """
# Initializes the Keyboard object
#
# arguments
#
# None
#
# keyword arguments
#
# keylist -- list of keys that are allowed, e.g. ["1","a","enter"]
# for the 1, A and Enter keys (default =
# KEYLIST)
# timeout -- time in milliseconds after which None is returned
# on a call to the get_key method when no keypress is
# registered (default = KEYTIMEOUT)
# """
#
# pass
#
#
# def set_keylist(self):
#
# """
# Set a list of accepted keys
#
# arguments
#
# None
#
# keyword arguments
#
# keylist -- list of keys that are allowed (e.g.
# ["1","a","enter"]) or None to allow all keys
# (default = None)
#
# returns
#
# None -- sets klist property
# """
#
# pass
#
#
# def set_timeout(self):
#
# """
# Set a timeout (in milliseconds)
#
# arguments
#
# None
#
# keyword arguments
#
# timeout -- time in milliseconds after which None is returned
# on a call to get_key method when no keypress is
# registered (default = None)
#
# returns
#
# None -- sets timeout property
# """
#
# pass
#
#
# def get_key(self):
#
# """
# Wait for keyboard input
#
# arguments
#
# None
#
# keyword arguments
#
# keylist -- list of keys that are allowed (e.g.
# ["1","a","enter"]), None to allow all keys or
# "default" to use klist property (default = "default")
# timeout -- time in milliseconds after which None is returned
# when no keypress is registered (default = None);
# None for no timeout or "default" to use the timeout
# property (default = "default")
# flush -- Boolean indicating if all input from before
# calling get_key should be ignored, if set to
# False keypresses from before calling this
# function will be registered, otherwise every
# keyboard input from before calling this function
# will be flushed (default = False)
#
# returns
#
# key, presstime -- key is a string, indicating which button has
# been pressed or None when no key has been
# pressed
# presstime is the time (measured from
# expbegintime) a keypress or a timeout occured
# """
#
# pass
. Output only the next line. | self.__class__ = Keyboard
|
Next line prediction: <|code_start|># This file is part of PyGaze - the open-source toolbox for eye tracking
#
# PyGaze is a Python module for easily creating gaze contingent experiments
# or other software (as well as non-gaze contingent experiments/software)
# Copyright (C) 2012-2013 Edwin S. Dalmaijer
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
class Keyboard(BaseKeyboard):
# see BaseKeyboard
def __init__(self, disptype=settings.DISPTYPE, **args):
# see BaseKeyboard
if disptype == "pygame":
<|code_end|>
. Use current file imports:
(from pygaze.py3compat import *
from pygaze import settings
from pygaze._misc.misc import copy_docstr
from pygaze._keyboard.basekeyboard import BaseKeyboard
from pygaze._keyboard.pygamekeyboard import PyGameKeyboard as \
Keyboard
from pygaze._keyboard.psychopykeyboard import PsychoPyKeyboard as \
Keyboard
from pygaze._keyboard.oskeyboard import OSKeyboard as \
Keyboard
)
and context including class names, function names, or small code snippets from other files:
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
#
# Path: pygaze/_misc/misc.py
# def copy_docstr(src, target):
#
# """
# Copies docstrings from the methods of a source class to the methods of a
# target class.
#
# arguments:
# src -- source class (e.g. BaseDisplay)
# target -- target class (e.g. PyGameDisplay)
# """
#
# for attr_name in dir(target):
# if not hasattr(src, attr_name) or not ismethod(getattr(src, attr_name)):
# continue
# getattr(target, attr_name).__func__.__doc__ = getattr(src, attr_name).__func__.__doc__
#
# Path: pygaze/_keyboard/basekeyboard.py
# class BaseKeyboard:
#
# """A keyboard for collecting responses"""
#
# def __init__(self):
#
# """
# Initializes the Keyboard object
#
# arguments
#
# None
#
# keyword arguments
#
# keylist -- list of keys that are allowed, e.g. ["1","a","enter"]
# for the 1, A and Enter keys (default =
# KEYLIST)
# timeout -- time in milliseconds after which None is returned
# on a call to the get_key method when no keypress is
# registered (default = KEYTIMEOUT)
# """
#
# pass
#
#
# def set_keylist(self):
#
# """
# Set a list of accepted keys
#
# arguments
#
# None
#
# keyword arguments
#
# keylist -- list of keys that are allowed (e.g.
# ["1","a","enter"]) or None to allow all keys
# (default = None)
#
# returns
#
# None -- sets klist property
# """
#
# pass
#
#
# def set_timeout(self):
#
# """
# Set a timeout (in milliseconds)
#
# arguments
#
# None
#
# keyword arguments
#
# timeout -- time in milliseconds after which None is returned
# on a call to get_key method when no keypress is
# registered (default = None)
#
# returns
#
# None -- sets timeout property
# """
#
# pass
#
#
# def get_key(self):
#
# """
# Wait for keyboard input
#
# arguments
#
# None
#
# keyword arguments
#
# keylist -- list of keys that are allowed (e.g.
# ["1","a","enter"]), None to allow all keys or
# "default" to use klist property (default = "default")
# timeout -- time in milliseconds after which None is returned
# when no keypress is registered (default = None);
# None for no timeout or "default" to use the timeout
# property (default = "default")
# flush -- Boolean indicating if all input from before
# calling get_key should be ignored, if set to
# False keypresses from before calling this
# function will be registered, otherwise every
# keyboard input from before calling this function
# will be flushed (default = False)
#
# returns
#
# key, presstime -- key is a string, indicating which button has
# been pressed or None when no key has been
# pressed
# presstime is the time (measured from
# expbegintime) a keypress or a timeout occured
# """
#
# pass
. Output only the next line. | elif disptype == "psychopy":
|
Using the snippet: <|code_start|># PyGaze is a Python module for easily creating gaze contingent experiments
# or other software (as well as non-gaze contingent experiments/software)
# Copyright (C) 2012-2013 Edwin S. Dalmaijer
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
class Keyboard(BaseKeyboard):
# see BaseKeyboard
def __init__(self, disptype=settings.DISPTYPE, **args):
# see BaseKeyboard
if disptype == "pygame":
elif disptype == "psychopy":
elif disptype == "opensesame":
<|code_end|>
, determine the next line of code. You have imports:
from pygaze.py3compat import *
from pygaze import settings
from pygaze._misc.misc import copy_docstr
from pygaze._keyboard.basekeyboard import BaseKeyboard
from pygaze._keyboard.pygamekeyboard import PyGameKeyboard as \
Keyboard
from pygaze._keyboard.psychopykeyboard import PsychoPyKeyboard as \
Keyboard
from pygaze._keyboard.oskeyboard import OSKeyboard as \
Keyboard
and context (class names, function names, or code) available:
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
#
# Path: pygaze/_misc/misc.py
# def copy_docstr(src, target):
#
# """
# Copies docstrings from the methods of a source class to the methods of a
# target class.
#
# arguments:
# src -- source class (e.g. BaseDisplay)
# target -- target class (e.g. PyGameDisplay)
# """
#
# for attr_name in dir(target):
# if not hasattr(src, attr_name) or not ismethod(getattr(src, attr_name)):
# continue
# getattr(target, attr_name).__func__.__doc__ = getattr(src, attr_name).__func__.__doc__
#
# Path: pygaze/_keyboard/basekeyboard.py
# class BaseKeyboard:
#
# """A keyboard for collecting responses"""
#
# def __init__(self):
#
# """
# Initializes the Keyboard object
#
# arguments
#
# None
#
# keyword arguments
#
# keylist -- list of keys that are allowed, e.g. ["1","a","enter"]
# for the 1, A and Enter keys (default =
# KEYLIST)
# timeout -- time in milliseconds after which None is returned
# on a call to the get_key method when no keypress is
# registered (default = KEYTIMEOUT)
# """
#
# pass
#
#
# def set_keylist(self):
#
# """
# Set a list of accepted keys
#
# arguments
#
# None
#
# keyword arguments
#
# keylist -- list of keys that are allowed (e.g.
# ["1","a","enter"]) or None to allow all keys
# (default = None)
#
# returns
#
# None -- sets klist property
# """
#
# pass
#
#
# def set_timeout(self):
#
# """
# Set a timeout (in milliseconds)
#
# arguments
#
# None
#
# keyword arguments
#
# timeout -- time in milliseconds after which None is returned
# on a call to get_key method when no keypress is
# registered (default = None)
#
# returns
#
# None -- sets timeout property
# """
#
# pass
#
#
# def get_key(self):
#
# """
# Wait for keyboard input
#
# arguments
#
# None
#
# keyword arguments
#
# keylist -- list of keys that are allowed (e.g.
# ["1","a","enter"]), None to allow all keys or
# "default" to use klist property (default = "default")
# timeout -- time in milliseconds after which None is returned
# when no keypress is registered (default = None);
# None for no timeout or "default" to use the timeout
# property (default = "default")
# flush -- Boolean indicating if all input from before
# calling get_key should be ignored, if set to
# False keypresses from before calling this
# function will be registered, otherwise every
# keyboard input from before calling this function
# will be flushed (default = False)
#
# returns
#
# key, presstime -- key is a string, indicating which button has
# been pressed or None when no key has been
# pressed
# presstime is the time (measured from
# expbegintime) a keypress or a timeout occured
# """
#
# pass
. Output only the next line. | else:
|
Predict the next line after this snippet: <|code_start|> # try to copy docstring (but ignore it if it fails, as we do
# not need it for actual functioning of the code)
try:
copy_docstr(BaseSound, PyGameSound)
except:
# we're not even going to show a warning, since the copied
# docstring is useful for code editors; these load the docs
# in a non-verbose manner, so warning messages would be lost
pass
pygame.mixer.init(frequency=settings.SOUNDSAMPLINGFREQUENCY,
size=settings.SOUNDSAMPLESIZE, channels=settings.SOUNDCHANNELS,
buffer=settings.SOUNDBUFFERSIZE)
# if a sound file was specified, use soundfile and ignore other keyword arguments
if soundfile is not None:
if not os.path.exists(soundfile):
raise Exception("Error in libsound.Player.__init__(): Sound file '{}' not found!".format(soundfile))
if os.path.splitext(soundfile)[1].lower() not in (".ogg", ".wav"):
raise Exception("Error in libsound.Player.__init__(): Sound file '{}' is not in .ogg or .wav format!".format(soundfile))
self.sound = pygame.mixer.Sound(soundfile)
# if no soundfile was specified, use keyword arguments to create sound
else:
if osc == "sine":
_func = math.sin
elif osc == "saw":
_func = self.saw
elif osc == "square":
<|code_end|>
using the current file's imports:
from pygaze import settings
from pygaze._sound.basesound import BaseSound
from pygaze._misc.misc import copy_docstr
import math
import numpy
import os.path
import pygame
import random
and any relevant context from other files:
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
#
# Path: pygaze/_sound/basesound.py
# class BaseSound:
#
# """A Sound class for creating and playing sounds"""
#
# def __init__(self):
#
# """
# Initializes a Sound Instance
#
# arguments
#
# None
#
# keyword arguments
#
# osc -- type of oscillator; allowed: "sine", "saw", "square",
# "whitenoise" (default = SOUNDOSCILLATOR)
# freq -- sound frequency in Herz, either float or integer
# (default = SOUNDFREQUENCY)
# length -- sound length in milliseconds (default =
# SOUNDLENGTH)
# attack -- sound attack ('fade in') in milliseconds (default =
# SOUNDATTACK)
# decay -- sound decay ('fade out') in milliseconds (default =
# SOUNDDECAY)
# soundfile -- full path to soundfile with .ogg or .wav extension
# or None for no file; if a file is specified, all
# other keyword arguments will be ignored (default =
# None)
# """
#
# pass
#
#
# def pan(self):
#
# """
# Sets the panning of a sound (the volume of the 'unpanned'
# channel decreases, while the other channel remaines the same)
#
# arguments
#
# panning -- either a float between -1 and 1, "left" or "right":
# "left": full panning to left (same as -1)
# < 0: panning to left
# 0: no panning
# > 0: panning to right
# "right": full panning to left (same as 1)
#
# keyword arguments
#
# None
#
# returns
#
# None -- self.sound is panned
# """
#
# pass
#
#
# def play(self):
#
# """
# Plays specified sound (keyword argument loops specifies how many
# repeats after being played once, -1 is infinite); function does not
# wait for playback end, but returns immediately
#
# arguments
#
# None
#
# keyword arguments
#
# repeats -- specifies the amount of repeats after being played
# once (-1 is infinite) (default = 0)
#
# returns
#
# None -- self.sound is played
# """
#
# pass
#
#
# def stop(self):
#
# """
# Stops sound playback
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
#
# None -- self.sound stops playing
# """
#
# pass
#
#
# def set_volume(self):
#
# """
# Set the playback volume (loudness) to specified value
#
# arguments
#
# volume -- float between 0 and 1
#
# keyword arguments
#
# None
#
# returns
#
# None -- sets self.sound volume to specified value
# """
#
# pass
. Output only the next line. | _func = self.square
|
Predict the next line after this snippet: <|code_start|> copy_docstr(BaseSound, PyGameSound)
except:
# we're not even going to show a warning, since the copied
# docstring is useful for code editors; these load the docs
# in a non-verbose manner, so warning messages would be lost
pass
pygame.mixer.init(frequency=settings.SOUNDSAMPLINGFREQUENCY,
size=settings.SOUNDSAMPLESIZE, channels=settings.SOUNDCHANNELS,
buffer=settings.SOUNDBUFFERSIZE)
# if a sound file was specified, use soundfile and ignore other keyword arguments
if soundfile is not None:
if not os.path.exists(soundfile):
raise Exception("Error in libsound.Player.__init__(): Sound file '{}' not found!".format(soundfile))
if os.path.splitext(soundfile)[1].lower() not in (".ogg", ".wav"):
raise Exception("Error in libsound.Player.__init__(): Sound file '{}' is not in .ogg or .wav format!".format(soundfile))
self.sound = pygame.mixer.Sound(soundfile)
# if no soundfile was specified, use keyword arguments to create sound
else:
if osc == "sine":
_func = math.sin
elif osc == "saw":
_func = self.saw
elif osc == "square":
_func = self.square
elif osc == "whitenoise":
_func = self.white_noise
<|code_end|>
using the current file's imports:
from pygaze import settings
from pygaze._sound.basesound import BaseSound
from pygaze._misc.misc import copy_docstr
import math
import numpy
import os.path
import pygame
import random
and any relevant context from other files:
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
#
# Path: pygaze/_sound/basesound.py
# class BaseSound:
#
# """A Sound class for creating and playing sounds"""
#
# def __init__(self):
#
# """
# Initializes a Sound Instance
#
# arguments
#
# None
#
# keyword arguments
#
# osc -- type of oscillator; allowed: "sine", "saw", "square",
# "whitenoise" (default = SOUNDOSCILLATOR)
# freq -- sound frequency in Herz, either float or integer
# (default = SOUNDFREQUENCY)
# length -- sound length in milliseconds (default =
# SOUNDLENGTH)
# attack -- sound attack ('fade in') in milliseconds (default =
# SOUNDATTACK)
# decay -- sound decay ('fade out') in milliseconds (default =
# SOUNDDECAY)
# soundfile -- full path to soundfile with .ogg or .wav extension
# or None for no file; if a file is specified, all
# other keyword arguments will be ignored (default =
# None)
# """
#
# pass
#
#
# def pan(self):
#
# """
# Sets the panning of a sound (the volume of the 'unpanned'
# channel decreases, while the other channel remaines the same)
#
# arguments
#
# panning -- either a float between -1 and 1, "left" or "right":
# "left": full panning to left (same as -1)
# < 0: panning to left
# 0: no panning
# > 0: panning to right
# "right": full panning to left (same as 1)
#
# keyword arguments
#
# None
#
# returns
#
# None -- self.sound is panned
# """
#
# pass
#
#
# def play(self):
#
# """
# Plays specified sound (keyword argument loops specifies how many
# repeats after being played once, -1 is infinite); function does not
# wait for playback end, but returns immediately
#
# arguments
#
# None
#
# keyword arguments
#
# repeats -- specifies the amount of repeats after being played
# once (-1 is infinite) (default = 0)
#
# returns
#
# None -- self.sound is played
# """
#
# pass
#
#
# def stop(self):
#
# """
# Stops sound playback
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
#
# None -- self.sound stops playing
# """
#
# pass
#
#
# def set_volume(self):
#
# """
# Set the playback volume (loudness) to specified value
#
# arguments
#
# volume -- float between 0 and 1
#
# keyword arguments
#
# None
#
# returns
#
# None -- sets self.sound volume to specified value
# """
#
# pass
. Output only the next line. | else:
|
Here is a snippet: <|code_start|> def __init__(self, keylist=settings.KEYLIST, timeout=settings.KEYTIMEOUT):
# See _keyboard.basekeyboard.BaseKeyboard
# try to copy docstring (but ignore it if it fails, as we do
# not need it for actual functioning of the code)
try:
copy_docstr(BaseKeyboard, OSKeyboard)
except:
# we're not even going to show a warning, since the copied
# docstring is useful for code editors; these load the docs
# in a non-verbose manner, so warning messages would be lost
pass
self.experiment = settings.osexperiment
self.keyboard = keyboard(self.experiment, keylist=keylist,
timeout=timeout)
def set_keylist(self, keylist=None):
# See _keyboard.basekeyboard.BaseKeyboard
self.keyboard.keylist = keylist
def set_timeout(self, timeout=None):
# See _keyboard.basekeyboard.BaseKeyboard
self.keyboard.timeout = timeout
<|code_end|>
. Write the next line using the current file imports:
from libopensesame.exceptions import osexception
from openexp.keyboard import keyboard
from pygaze.py3compat import *
from pygaze import settings
from pygaze._keyboard.basekeyboard import BaseKeyboard
from pygaze._misc.misc import copy_docstr
and context from other files:
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
#
# Path: pygaze/_keyboard/basekeyboard.py
# class BaseKeyboard:
#
# """A keyboard for collecting responses"""
#
# def __init__(self):
#
# """
# Initializes the Keyboard object
#
# arguments
#
# None
#
# keyword arguments
#
# keylist -- list of keys that are allowed, e.g. ["1","a","enter"]
# for the 1, A and Enter keys (default =
# KEYLIST)
# timeout -- time in milliseconds after which None is returned
# on a call to the get_key method when no keypress is
# registered (default = KEYTIMEOUT)
# """
#
# pass
#
#
# def set_keylist(self):
#
# """
# Set a list of accepted keys
#
# arguments
#
# None
#
# keyword arguments
#
# keylist -- list of keys that are allowed (e.g.
# ["1","a","enter"]) or None to allow all keys
# (default = None)
#
# returns
#
# None -- sets klist property
# """
#
# pass
#
#
# def set_timeout(self):
#
# """
# Set a timeout (in milliseconds)
#
# arguments
#
# None
#
# keyword arguments
#
# timeout -- time in milliseconds after which None is returned
# on a call to get_key method when no keypress is
# registered (default = None)
#
# returns
#
# None -- sets timeout property
# """
#
# pass
#
#
# def get_key(self):
#
# """
# Wait for keyboard input
#
# arguments
#
# None
#
# keyword arguments
#
# keylist -- list of keys that are allowed (e.g.
# ["1","a","enter"]), None to allow all keys or
# "default" to use klist property (default = "default")
# timeout -- time in milliseconds after which None is returned
# when no keypress is registered (default = None);
# None for no timeout or "default" to use the timeout
# property (default = "default")
# flush -- Boolean indicating if all input from before
# calling get_key should be ignored, if set to
# False keypresses from before calling this
# function will be registered, otherwise every
# keyboard input from before calling this function
# will be flushed (default = False)
#
# returns
#
# key, presstime -- key is a string, indicating which button has
# been pressed or None when no key has been
# pressed
# presstime is the time (measured from
# expbegintime) a keypress or a timeout occured
# """
#
# pass
, which may include functions, classes, or code. Output only the next line. | def get_key(self, keylist="default", timeout="default", flush=False):
|
Continue the code snippet: <|code_start|>
# set keyboard characteristics
self.set_keylist(keylist)
self.set_timeout(timeout)
def set_keylist(self, keylist=None):
# See _keyboard.basekeyboard.BaseKeyboard
if keylist == None or keylist == []:
self.klist = None
else:
self.klist = []
for key in keylist:
self.klist.append(key)
def set_timeout(self, timeout=None):
# See _keyboard.basekeyboard.BaseKeyboard
self.timeout = timeout
def get_key(self, keylist="default", timeout="default", flush=False):
# See _keyboard.basekeyboard.BaseKeyboard
# set keylist and timeout
if keylist == "default":
<|code_end|>
. Use current file imports:
from pygaze.libtime import clock
from pygaze import settings
from pygaze._keyboard.basekeyboard import BaseKeyboard
from pygaze._misc.misc import copy_docstr
import pygaze
import pygame
import pygame.key
and context (classes, functions, or code) from other files:
# Path: pygaze/libtime.py
# def expstart():
# def get_time():
# def pause(pausetime):
# def expend():
#
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
#
# Path: pygaze/_keyboard/basekeyboard.py
# class BaseKeyboard:
#
# """A keyboard for collecting responses"""
#
# def __init__(self):
#
# """
# Initializes the Keyboard object
#
# arguments
#
# None
#
# keyword arguments
#
# keylist -- list of keys that are allowed, e.g. ["1","a","enter"]
# for the 1, A and Enter keys (default =
# KEYLIST)
# timeout -- time in milliseconds after which None is returned
# on a call to the get_key method when no keypress is
# registered (default = KEYTIMEOUT)
# """
#
# pass
#
#
# def set_keylist(self):
#
# """
# Set a list of accepted keys
#
# arguments
#
# None
#
# keyword arguments
#
# keylist -- list of keys that are allowed (e.g.
# ["1","a","enter"]) or None to allow all keys
# (default = None)
#
# returns
#
# None -- sets klist property
# """
#
# pass
#
#
# def set_timeout(self):
#
# """
# Set a timeout (in milliseconds)
#
# arguments
#
# None
#
# keyword arguments
#
# timeout -- time in milliseconds after which None is returned
# on a call to get_key method when no keypress is
# registered (default = None)
#
# returns
#
# None -- sets timeout property
# """
#
# pass
#
#
# def get_key(self):
#
# """
# Wait for keyboard input
#
# arguments
#
# None
#
# keyword arguments
#
# keylist -- list of keys that are allowed (e.g.
# ["1","a","enter"]), None to allow all keys or
# "default" to use klist property (default = "default")
# timeout -- time in milliseconds after which None is returned
# when no keypress is registered (default = None);
# None for no timeout or "default" to use the timeout
# property (default = "default")
# flush -- Boolean indicating if all input from before
# calling get_key should be ignored, if set to
# False keypresses from before calling this
# function will be registered, otherwise every
# keyboard input from before calling this function
# will be flushed (default = False)
#
# returns
#
# key, presstime -- key is a string, indicating which button has
# been pressed or None when no key has been
# pressed
# presstime is the time (measured from
# expbegintime) a keypress or a timeout occured
# """
#
# pass
. Output only the next line. | keylist = self.klist
|
Continue the code snippet: <|code_start|># we try importing the copy_docstr function, but as we do not really need it
# for a proper functioning of the code, we simply ignore it when it fails to
# be imported correctly
try:
except:
pass
class PyGameKeyboard(BaseKeyboard):
# See _keyboard.basekeyboard.BaseKeyboard
def __init__(self, keylist=settings.KEYLIST, timeout=settings.KEYTIMEOUT):
# See _keyboard.basekeyboard.BaseKeyboard
# try to copy docstring (but ignore it if it fails, as we do
# not need it for actual functioning of the code)
try:
copy_docstr(BaseKeyboard, PyGameKeyboard)
except:
# we're not even going to show a warning, since the copied
# docstring is useful for code editors; these load the docs
# in a non-verbose manner, so warning messages would be lost
pass
# dictionary for keynames and codes
self.key_codes = {}
for i in dir(pygame):
<|code_end|>
. Use current file imports:
from pygaze.libtime import clock
from pygaze import settings
from pygaze._keyboard.basekeyboard import BaseKeyboard
from pygaze._misc.misc import copy_docstr
import pygaze
import pygame
import pygame.key
and context (classes, functions, or code) from other files:
# Path: pygaze/libtime.py
# def expstart():
# def get_time():
# def pause(pausetime):
# def expend():
#
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
#
# Path: pygaze/_keyboard/basekeyboard.py
# class BaseKeyboard:
#
# """A keyboard for collecting responses"""
#
# def __init__(self):
#
# """
# Initializes the Keyboard object
#
# arguments
#
# None
#
# keyword arguments
#
# keylist -- list of keys that are allowed, e.g. ["1","a","enter"]
# for the 1, A and Enter keys (default =
# KEYLIST)
# timeout -- time in milliseconds after which None is returned
# on a call to the get_key method when no keypress is
# registered (default = KEYTIMEOUT)
# """
#
# pass
#
#
# def set_keylist(self):
#
# """
# Set a list of accepted keys
#
# arguments
#
# None
#
# keyword arguments
#
# keylist -- list of keys that are allowed (e.g.
# ["1","a","enter"]) or None to allow all keys
# (default = None)
#
# returns
#
# None -- sets klist property
# """
#
# pass
#
#
# def set_timeout(self):
#
# """
# Set a timeout (in milliseconds)
#
# arguments
#
# None
#
# keyword arguments
#
# timeout -- time in milliseconds after which None is returned
# on a call to get_key method when no keypress is
# registered (default = None)
#
# returns
#
# None -- sets timeout property
# """
#
# pass
#
#
# def get_key(self):
#
# """
# Wait for keyboard input
#
# arguments
#
# None
#
# keyword arguments
#
# keylist -- list of keys that are allowed (e.g.
# ["1","a","enter"]), None to allow all keys or
# "default" to use klist property (default = "default")
# timeout -- time in milliseconds after which None is returned
# when no keypress is registered (default = None);
# None for no timeout or "default" to use the timeout
# property (default = "default")
# flush -- Boolean indicating if all input from before
# calling get_key should be ignored, if set to
# False keypresses from before calling this
# function will be registered, otherwise every
# keyboard input from before calling this function
# will be flushed (default = False)
#
# returns
#
# key, presstime -- key is a string, indicating which button has
# been pressed or None when no key has been
# pressed
# presstime is the time (measured from
# expbegintime) a keypress or a timeout occured
# """
#
# pass
. Output only the next line. | if i[:2] == "K_":
|
Based on the snippet: <|code_start|> code = eval("pygame.%s" % i)
name1 = pygame.key.name(code).lower()
name2 = name1.upper()
name3 = i[2:].lower()
name4 = name3.upper()
self.key_codes[name1] = code
self.key_codes[name2] = code
self.key_codes[name3] = code
self.key_codes[name4] = code
# set keyboard characteristics
self.set_keylist(keylist)
self.set_timeout(timeout)
def set_keylist(self, keylist=None):
# See _keyboard.basekeyboard.BaseKeyboard
if keylist == None or keylist == []:
self.klist = None
else:
self.klist = []
for key in keylist:
self.klist.append(key)
def set_timeout(self, timeout=None):
# See _keyboard.basekeyboard.BaseKeyboard
<|code_end|>
, predict the immediate next line with the help of imports:
from pygaze.libtime import clock
from pygaze import settings
from pygaze._keyboard.basekeyboard import BaseKeyboard
from pygaze._misc.misc import copy_docstr
import pygaze
import pygame
import pygame.key
and context (classes, functions, sometimes code) from other files:
# Path: pygaze/libtime.py
# def expstart():
# def get_time():
# def pause(pausetime):
# def expend():
#
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
#
# Path: pygaze/_keyboard/basekeyboard.py
# class BaseKeyboard:
#
# """A keyboard for collecting responses"""
#
# def __init__(self):
#
# """
# Initializes the Keyboard object
#
# arguments
#
# None
#
# keyword arguments
#
# keylist -- list of keys that are allowed, e.g. ["1","a","enter"]
# for the 1, A and Enter keys (default =
# KEYLIST)
# timeout -- time in milliseconds after which None is returned
# on a call to the get_key method when no keypress is
# registered (default = KEYTIMEOUT)
# """
#
# pass
#
#
# def set_keylist(self):
#
# """
# Set a list of accepted keys
#
# arguments
#
# None
#
# keyword arguments
#
# keylist -- list of keys that are allowed (e.g.
# ["1","a","enter"]) or None to allow all keys
# (default = None)
#
# returns
#
# None -- sets klist property
# """
#
# pass
#
#
# def set_timeout(self):
#
# """
# Set a timeout (in milliseconds)
#
# arguments
#
# None
#
# keyword arguments
#
# timeout -- time in milliseconds after which None is returned
# on a call to get_key method when no keypress is
# registered (default = None)
#
# returns
#
# None -- sets timeout property
# """
#
# pass
#
#
# def get_key(self):
#
# """
# Wait for keyboard input
#
# arguments
#
# None
#
# keyword arguments
#
# keylist -- list of keys that are allowed (e.g.
# ["1","a","enter"]), None to allow all keys or
# "default" to use klist property (default = "default")
# timeout -- time in milliseconds after which None is returned
# when no keypress is registered (default = None);
# None for no timeout or "default" to use the timeout
# property (default = "default")
# flush -- Boolean indicating if all input from before
# calling get_key should be ignored, if set to
# False keypresses from before calling this
# function will be registered, otherwise every
# keyboard input from before calling this function
# will be flushed (default = False)
#
# returns
#
# key, presstime -- key is a string, indicating which button has
# been pressed or None when no key has been
# pressed
# presstime is the time (measured from
# expbegintime) a keypress or a timeout occured
# """
#
# pass
. Output only the next line. | self.timeout = timeout
|
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
#
# This file is part of PyGaze - the open-source toolbox for eye tracking
#
# PyGaze is a Python module for easily creating gaze contingent experiments
# or other software (as well as non-gaze contingent experiments/software)
# Copyright (C) 2012-2013 Edwin S. Dalmaijer
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
if settings.DISPTYPE == "psychopy":
elif settings.DISPTYPE == "pygame":
elif settings.DISPTYPE == "opensesame":
<|code_end|>
, predict the immediate next line with the help of imports:
from pygaze.py3compat import *
from pygaze import settings
from pygaze._time.psychopytime import PsychoPyTime as Time
from pygaze._time.pygametime import PyGameTime as Time
from pygaze._time.ostime import OSTime as Time
import pygaze
and context (classes, functions, sometimes code) from other files:
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
. Output only the next line. | else:
|
Given the code snippet: <|code_start|>#
# PyGaze is a Python module for easily creating gaze contingent experiments
# or other software (as well as non-gaze contingent experiments/software)
# Copyright (C) 2012-2013 Edwin S. Dalmaijer
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
# we try importing the copy_docstr function, but as we do not really need it
# for a proper functioning of the code, we simply ignore it when it fails to
# be imported correctly
try:
except:
pass
class OSTime(BaseTime):
# see pygaze._time.basetime.BaseTime
<|code_end|>
, generate the next line using the imports in this file:
from pygaze.py3compat import *
from pygaze import settings
from pygaze._time.basetime import BaseTime
from pygaze._misc.misc import copy_docstr
and context (functions, classes, or occasionally code) from other files:
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
#
# Path: pygaze/_time/basetime.py
# class BaseTime:
#
# """Class for keeping track of time"""
#
# def __init__(self):
#
# """
# Initializes a Time instance
#
# arguments
#
# None
#
# keyword arguments
#
# None
# """
#
# pass
#
#
# def expstart(self):
#
# """
# Time is set to 0 when calling this
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
#
# Nothing
# """
#
# pass
#
#
# def get_time(self):
#
# """
# Returns current time in milliseconds
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
#
# time -- current time in milliseconds, as measured since
# expbegintime
# """
#
# pass
#
#
# def pause(self):
#
# """
# Pauses the experiment for given number of milliseconds
#
# arguments
#
# pausetime -- time to pause in milliseconds
#
# keyword arguments
#
# None
#
# returns
#
# pausetime -- actual time the system paused (in milliseconds)
# """
#
# pass
#
#
# def expend(self):
#
# """
# Completely ends the experiment (only call this at the end!)
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
#
# endtime -- ending time of the experiment (in milliseconds since
# expbegintime
# """
#
# pass
. Output only the next line. | def __init__(self): |
Here is a snippet: <|code_start|>fixscreen.draw_fixation(fixtype='cross',pw=2)
targetscreens = {}
targetscreens['left'] = libscreen.Screen()
targetscreens['left'].draw_circle(pos=(settings.DISPSIZE[0]*0.25,settings.DISPSIZE[1]/2), fill=True)
targetscreens['right'] = libscreen.Screen()
targetscreens['right'].draw_circle(pos=(settings.DISPSIZE[0]*0.75,settings.DISPSIZE[1]/2), fill=True)
feedbackscreens = {}
feedbackscreens[1] = libscreen.Screen()
feedbackscreens[1].draw_text(text='correct', colour=(0,255,0))
feedbackscreens[0] = libscreen.Screen()
feedbackscreens[0].draw_text(text='incorrect', colour=(255,0,0))
# # # # #
# run the experiment
# run 20 trials
for trialnr in range(1,21):
# prepare trial
trialtype = random.choice(['left','right'])
# present fixation
disp.fill(screen=fixscreen)
disp.show()
libtime.pause(random.randint(750, 1250))
# present target
disp.fill(targetscreens[trialtype])
t0 = disp.show()
# wait for input
<|code_end|>
. Write the next line using the current file imports:
import random
from pygaze import libscreen
from pygaze import libtime
from pygaze import libinput
from pygaze import liblog
from pygaze import settings
and context from other files:
# Path: pygaze/libscreen.py
#
# Path: pygaze/libtime.py
# def expstart():
# def get_time():
# def pause(pausetime):
# def expend():
#
# Path: pygaze/libinput.py
#
# Path: pygaze/liblog.py
#
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
, which may include functions, classes, or code. Output only the next line. | response, t1 = kb.get_key() |
Predict the next line for this snippet: <|code_start|>
# run 20 trials
for trialnr in range(1,21):
# prepare trial
trialtype = random.choice(['left','right'])
# present fixation
disp.fill(screen=fixscreen)
disp.show()
libtime.pause(random.randint(750, 1250))
# present target
disp.fill(targetscreens[trialtype])
t0 = disp.show()
# wait for input
response, t1 = kb.get_key()
# end the experiment when 'escape' is pressed
if response == 'escape':
break
# process input
if response == trialtype:
correct = 1
else:
correct = 0
# present feedback
disp.fill(feedbackscreens[correct])
<|code_end|>
with the help of current file imports:
import random
from pygaze import libscreen
from pygaze import libtime
from pygaze import libinput
from pygaze import liblog
from pygaze import settings
and context from other files:
# Path: pygaze/libscreen.py
#
# Path: pygaze/libtime.py
# def expstart():
# def get_time():
# def pause(pausetime):
# def expend():
#
# Path: pygaze/libinput.py
#
# Path: pygaze/liblog.py
#
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
, which may contain function names, class names, or code. Output only the next line. | disp.show() |
Here is a snippet: <|code_start|># example script for using PyGaze
# # # # #
# importing the relevant libraries
# # # # #
# setup the experiment
# create display object
disp = libscreen.Display()
# create keyboard object
kb = libinput.Keyboard(keylist=['left','right','escape'], timeout=2000)
# create logfile object
log = liblog.Logfile()
log.write(["trialnr", "trialtype", "response", "RT", "correct"])
# create screens
fixscreen = libscreen.Screen()
fixscreen.draw_fixation(fixtype='cross',pw=2)
targetscreens = {}
targetscreens['left'] = libscreen.Screen()
targetscreens['left'].draw_circle(pos=(settings.DISPSIZE[0]*0.25,settings.DISPSIZE[1]/2), fill=True)
targetscreens['right'] = libscreen.Screen()
targetscreens['right'].draw_circle(pos=(settings.DISPSIZE[0]*0.75,settings.DISPSIZE[1]/2), fill=True)
<|code_end|>
. Write the next line using the current file imports:
import random
from pygaze import libscreen
from pygaze import libtime
from pygaze import libinput
from pygaze import liblog
from pygaze import settings
and context from other files:
# Path: pygaze/libscreen.py
#
# Path: pygaze/libtime.py
# def expstart():
# def get_time():
# def pause(pausetime):
# def expend():
#
# Path: pygaze/libinput.py
#
# Path: pygaze/liblog.py
#
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
, which may include functions, classes, or code. Output only the next line. | feedbackscreens = {} |
Continue the code snippet: <|code_start|>targetscreens['right'] = libscreen.Screen()
targetscreens['right'].draw_circle(pos=(settings.DISPSIZE[0]*0.75,settings.DISPSIZE[1]/2), fill=True)
feedbackscreens = {}
feedbackscreens[1] = libscreen.Screen()
feedbackscreens[1].draw_text(text='correct', colour=(0,255,0))
feedbackscreens[0] = libscreen.Screen()
feedbackscreens[0].draw_text(text='incorrect', colour=(255,0,0))
# # # # #
# run the experiment
# run 20 trials
for trialnr in range(1,21):
# prepare trial
trialtype = random.choice(['left','right'])
# present fixation
disp.fill(screen=fixscreen)
disp.show()
libtime.pause(random.randint(750, 1250))
# present target
disp.fill(targetscreens[trialtype])
t0 = disp.show()
# wait for input
response, t1 = kb.get_key()
# end the experiment when 'escape' is pressed
if response == 'escape':
<|code_end|>
. Use current file imports:
import random
from pygaze import libscreen
from pygaze import libtime
from pygaze import libinput
from pygaze import liblog
from pygaze import settings
and context (classes, functions, or code) from other files:
# Path: pygaze/libscreen.py
#
# Path: pygaze/libtime.py
# def expstart():
# def get_time():
# def pause(pausetime):
# def expend():
#
# Path: pygaze/libinput.py
#
# Path: pygaze/liblog.py
#
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
. Output only the next line. | break |
Based on the snippet: <|code_start|> disp.show()
libtime.pause(random.randint(750, 1250))
# present target
disp.fill(targetscreens[trialtype])
t0 = disp.show()
# wait for input
response, t1 = kb.get_key()
# end the experiment when 'escape' is pressed
if response == 'escape':
break
# process input
if response == trialtype:
correct = 1
else:
correct = 0
# present feedback
disp.fill(feedbackscreens[correct])
disp.show()
libtime.pause(500)
# log stuff
log.write([trialnr, trialtype, response, t1-t0, correct])
# end the experiment
log.close()
<|code_end|>
, predict the immediate next line with the help of imports:
import random
from pygaze import libscreen
from pygaze import libtime
from pygaze import libinput
from pygaze import liblog
from pygaze import settings
and context (classes, functions, sometimes code) from other files:
# Path: pygaze/libscreen.py
#
# Path: pygaze/libtime.py
# def expstart():
# def get_time():
# def pause(pausetime):
# def expend():
#
# Path: pygaze/libinput.py
#
# Path: pygaze/liblog.py
#
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
. Output only the next line. | disp.close() |
Here is a snippet: <|code_start|> # docstring is useful for code editors; these load the docs
# in a non-verbose manner, so warning messages would be lost
pass
self.dispsize = dispsize
self.fgc = fgc
self.bgc = bgc
self.screennr = screennr
self.mousevis = False
self.monitor = monitor
# create window
pygaze.expdisplay = Window(size=self.dispsize, pos=None,
color=rgb2psychorgb(self.bgc), colorSpace="rgb",
fullscr=settings.FULLSCREEN, monitor=self.monitor,
screen=self.screennr, units="pix")
# set mouse visibility
pygaze.expdisplay.setMouseVisible(self.mousevis)
# get screen in window
if screen:
for s in screen.screen:
s.draw()
def show(self):
# See _display.basedisplay.BaseDisplay for documentation
pygaze.expdisplay.flip()
return clock.get_time()
<|code_end|>
. Write the next line using the current file imports:
from pygaze import settings
from pygaze._misc.misc import rgb2psychorgb
from pygaze.libtime import clock
from pygaze._display.basedisplay import BaseDisplay
from psychopy.visual import Window
from pygaze._misc.misc import copy_docstr
import pygaze
and context from other files:
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
#
# Path: pygaze/_misc/misc.py
# def rgb2psychorgb(rgbgun):
#
# """Returns a converted RGB gun
#
# arguments
# rgbgun -- a (R,G,B) or (R,G,B,A) tuple containing values between 0
# and 255; other values (e.g. 'red' or hex values) may be
# passed as well, but will be returned as they were
# returns
# psyrgb -- a (R,G,B) tuple containing values between -1 and 1; or
# rgbgun when passed rgbgun was not a tuple or a list
# """
#
# if type(rgbgun) not in [tuple,list]:
# return rgbgun
#
# psyrgb = []
#
# for val in rgbgun:
# psyrgb.append((val/127.5)-1)
#
# # return (R,G,B), since PsychoPy does not like alpha channels anymore
#
# return tuple(psyrgb[0:3])
#
# Path: pygaze/libtime.py
# def expstart():
# def get_time():
# def pause(pausetime):
# def expend():
#
# Path: pygaze/_display/basedisplay.py
# class BaseDisplay:
#
# """A class for Display objects, to present Screen objects on a monitor"""
#
# def __init__(self):
#
# """
# Initializes a Display object.
#
# arguments
#
# None
#
# keyword arguments
#
# dispsize -- size of the display in pixels: a (width, height)
# tuple (default = DISPSIZE)
# fgc -- the foreground colour: a RGB tuple, e.g. (255,0,0)
# for red or (0,0,0) for black (default = FGC)
# bgc -- the background colour: a RGB tuple, e.g. (0,0,255)
# for blue or (255,255,255) for white (default = BGC)
# screen -- a screen.Screen instance to be presented on the new
# Display (default=None)
# """
#
# pass
#
# def show(self):
#
# """
# Updates ('flips') the display.
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
# time -- the exact refresh time when disptype is PsychoPy,
# or an estimate when disptype is PyGame
# """
#
# pass
#
# def show_part(self, rect, screen=None):
#
# """
# Fills AND shows part(s) of the screen to given specified screen
# (only works when disptype is PyGame; when this is set to PsychoPy
# the entire display is filled and updated)
#
# arguments
#
# rect -- a single or a list of rects; a rect is a (x,y,w,h)
# tuple or list
#
# keyword arguments
#
# screen -- the screen of which the specified rects should be
# updated to the display (default = None)
#
# returns
#
# time -- the exact refresh time when disptype is PsychoPy,
# or an estimate when disptype is PyGame
# """
#
# pass
#
# def fill(self, screen=None):
#
# """
# Fills the screen with the background colour of the Screen, NOT
# updating it (call Display.show() to actually show the new contents)
#
# arguments
#
# None
#
# keyword arguments
#
# screen -- the screen that should be drawn to the display or
# None to fill the display with its background colour
#
# returns
#
# None
# """
#
# pass
#
# def close(self):
#
# """
# Closes the display
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
#
# None
# """
#
# pass
#
# def make_screenshot(self, filename="screenshot.png"):
#
# """
# Make a screenshot from the current display.
#
# arguments
#
# None
#
# keyword arguments
#
# filename -- path and filename, under wich the screenshot will be
# saved. Defaults to screenshot.png
#
# returns
#
# None
# """
#
# pass
, which may include functions, classes, or code. Output only the next line. | def show_part(self, rect, screen=None):
|
Continue the code snippet: <|code_start|># but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
# we try importing the copy_docstr function, but as we do not really need it
# for a proper functioning of the code, we simply ignore it when it fails to
# be imported correctly
try:
except:
pass
class PsychoPyDisplay(BaseDisplay):
# See _display.basedisplay.BaseDisplay for documentation
def __init__(self, dispsize=settings.DISPSIZE, fgc=settings.FGC,
bgc=settings.BGC, screennr=settings.SCREENNR, monitor = None, screen=None, **args):
# See _display.basedisplay.BaseDisplay for documentation
# try to import copy docstring (but ignore it if it fails, as we do
# not need it for actual functioning of the code)
try:
copy_docstr(BaseDisplay, PsychoPyDisplay)
<|code_end|>
. Use current file imports:
from pygaze import settings
from pygaze._misc.misc import rgb2psychorgb
from pygaze.libtime import clock
from pygaze._display.basedisplay import BaseDisplay
from psychopy.visual import Window
from pygaze._misc.misc import copy_docstr
import pygaze
and context (classes, functions, or code) from other files:
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
#
# Path: pygaze/_misc/misc.py
# def rgb2psychorgb(rgbgun):
#
# """Returns a converted RGB gun
#
# arguments
# rgbgun -- a (R,G,B) or (R,G,B,A) tuple containing values between 0
# and 255; other values (e.g. 'red' or hex values) may be
# passed as well, but will be returned as they were
# returns
# psyrgb -- a (R,G,B) tuple containing values between -1 and 1; or
# rgbgun when passed rgbgun was not a tuple or a list
# """
#
# if type(rgbgun) not in [tuple,list]:
# return rgbgun
#
# psyrgb = []
#
# for val in rgbgun:
# psyrgb.append((val/127.5)-1)
#
# # return (R,G,B), since PsychoPy does not like alpha channels anymore
#
# return tuple(psyrgb[0:3])
#
# Path: pygaze/libtime.py
# def expstart():
# def get_time():
# def pause(pausetime):
# def expend():
#
# Path: pygaze/_display/basedisplay.py
# class BaseDisplay:
#
# """A class for Display objects, to present Screen objects on a monitor"""
#
# def __init__(self):
#
# """
# Initializes a Display object.
#
# arguments
#
# None
#
# keyword arguments
#
# dispsize -- size of the display in pixels: a (width, height)
# tuple (default = DISPSIZE)
# fgc -- the foreground colour: a RGB tuple, e.g. (255,0,0)
# for red or (0,0,0) for black (default = FGC)
# bgc -- the background colour: a RGB tuple, e.g. (0,0,255)
# for blue or (255,255,255) for white (default = BGC)
# screen -- a screen.Screen instance to be presented on the new
# Display (default=None)
# """
#
# pass
#
# def show(self):
#
# """
# Updates ('flips') the display.
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
# time -- the exact refresh time when disptype is PsychoPy,
# or an estimate when disptype is PyGame
# """
#
# pass
#
# def show_part(self, rect, screen=None):
#
# """
# Fills AND shows part(s) of the screen to given specified screen
# (only works when disptype is PyGame; when this is set to PsychoPy
# the entire display is filled and updated)
#
# arguments
#
# rect -- a single or a list of rects; a rect is a (x,y,w,h)
# tuple or list
#
# keyword arguments
#
# screen -- the screen of which the specified rects should be
# updated to the display (default = None)
#
# returns
#
# time -- the exact refresh time when disptype is PsychoPy,
# or an estimate when disptype is PyGame
# """
#
# pass
#
# def fill(self, screen=None):
#
# """
# Fills the screen with the background colour of the Screen, NOT
# updating it (call Display.show() to actually show the new contents)
#
# arguments
#
# None
#
# keyword arguments
#
# screen -- the screen that should be drawn to the display or
# None to fill the display with its background colour
#
# returns
#
# None
# """
#
# pass
#
# def close(self):
#
# """
# Closes the display
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
#
# None
# """
#
# pass
#
# def make_screenshot(self, filename="screenshot.png"):
#
# """
# Make a screenshot from the current display.
#
# arguments
#
# None
#
# keyword arguments
#
# filename -- path and filename, under wich the screenshot will be
# saved. Defaults to screenshot.png
#
# returns
#
# None
# """
#
# pass
. Output only the next line. | except:
|
Using the snippet: <|code_start|> # get screen in window
if screen:
for s in screen.screen:
s.draw()
def show(self):
# See _display.basedisplay.BaseDisplay for documentation
pygaze.expdisplay.flip()
return clock.get_time()
def show_part(self, rect, screen=None):
# See _display.basedisplay.BaseDisplay for documentation
self.fill(screen)
self.show()
print("WARNING! screen.Display.show_part not available for PsychoPy display type; fill() and show() are used instead")
return clock.get_time()
def fill(self, screen=None):
# See _display.basedisplay.BaseDisplay for documentation
pygaze.expdisplay.clearBuffer()
if screen != None:
for s in screen.screen:
<|code_end|>
, determine the next line of code. You have imports:
from pygaze import settings
from pygaze._misc.misc import rgb2psychorgb
from pygaze.libtime import clock
from pygaze._display.basedisplay import BaseDisplay
from psychopy.visual import Window
from pygaze._misc.misc import copy_docstr
import pygaze
and context (class names, function names, or code) available:
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
#
# Path: pygaze/_misc/misc.py
# def rgb2psychorgb(rgbgun):
#
# """Returns a converted RGB gun
#
# arguments
# rgbgun -- a (R,G,B) or (R,G,B,A) tuple containing values between 0
# and 255; other values (e.g. 'red' or hex values) may be
# passed as well, but will be returned as they were
# returns
# psyrgb -- a (R,G,B) tuple containing values between -1 and 1; or
# rgbgun when passed rgbgun was not a tuple or a list
# """
#
# if type(rgbgun) not in [tuple,list]:
# return rgbgun
#
# psyrgb = []
#
# for val in rgbgun:
# psyrgb.append((val/127.5)-1)
#
# # return (R,G,B), since PsychoPy does not like alpha channels anymore
#
# return tuple(psyrgb[0:3])
#
# Path: pygaze/libtime.py
# def expstart():
# def get_time():
# def pause(pausetime):
# def expend():
#
# Path: pygaze/_display/basedisplay.py
# class BaseDisplay:
#
# """A class for Display objects, to present Screen objects on a monitor"""
#
# def __init__(self):
#
# """
# Initializes a Display object.
#
# arguments
#
# None
#
# keyword arguments
#
# dispsize -- size of the display in pixels: a (width, height)
# tuple (default = DISPSIZE)
# fgc -- the foreground colour: a RGB tuple, e.g. (255,0,0)
# for red or (0,0,0) for black (default = FGC)
# bgc -- the background colour: a RGB tuple, e.g. (0,0,255)
# for blue or (255,255,255) for white (default = BGC)
# screen -- a screen.Screen instance to be presented on the new
# Display (default=None)
# """
#
# pass
#
# def show(self):
#
# """
# Updates ('flips') the display.
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
# time -- the exact refresh time when disptype is PsychoPy,
# or an estimate when disptype is PyGame
# """
#
# pass
#
# def show_part(self, rect, screen=None):
#
# """
# Fills AND shows part(s) of the screen to given specified screen
# (only works when disptype is PyGame; when this is set to PsychoPy
# the entire display is filled and updated)
#
# arguments
#
# rect -- a single or a list of rects; a rect is a (x,y,w,h)
# tuple or list
#
# keyword arguments
#
# screen -- the screen of which the specified rects should be
# updated to the display (default = None)
#
# returns
#
# time -- the exact refresh time when disptype is PsychoPy,
# or an estimate when disptype is PyGame
# """
#
# pass
#
# def fill(self, screen=None):
#
# """
# Fills the screen with the background colour of the Screen, NOT
# updating it (call Display.show() to actually show the new contents)
#
# arguments
#
# None
#
# keyword arguments
#
# screen -- the screen that should be drawn to the display or
# None to fill the display with its background colour
#
# returns
#
# None
# """
#
# pass
#
# def close(self):
#
# """
# Closes the display
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
#
# None
# """
#
# pass
#
# def make_screenshot(self, filename="screenshot.png"):
#
# """
# Make a screenshot from the current display.
#
# arguments
#
# None
#
# keyword arguments
#
# filename -- path and filename, under wich the screenshot will be
# saved. Defaults to screenshot.png
#
# returns
#
# None
# """
#
# pass
. Output only the next line. | s.draw()
|
Next line prediction: <|code_start|> pygaze.expdisplay.setMouseVisible(self.mousevis)
# get screen in window
if screen:
for s in screen.screen:
s.draw()
def show(self):
# See _display.basedisplay.BaseDisplay for documentation
pygaze.expdisplay.flip()
return clock.get_time()
def show_part(self, rect, screen=None):
# See _display.basedisplay.BaseDisplay for documentation
self.fill(screen)
self.show()
print("WARNING! screen.Display.show_part not available for PsychoPy display type; fill() and show() are used instead")
return clock.get_time()
def fill(self, screen=None):
# See _display.basedisplay.BaseDisplay for documentation
pygaze.expdisplay.clearBuffer()
if screen != None:
<|code_end|>
. Use current file imports:
(from pygaze import settings
from pygaze._misc.misc import rgb2psychorgb
from pygaze.libtime import clock
from pygaze._display.basedisplay import BaseDisplay
from psychopy.visual import Window
from pygaze._misc.misc import copy_docstr
import pygaze
)
and context including class names, function names, or small code snippets from other files:
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
#
# Path: pygaze/_misc/misc.py
# def rgb2psychorgb(rgbgun):
#
# """Returns a converted RGB gun
#
# arguments
# rgbgun -- a (R,G,B) or (R,G,B,A) tuple containing values between 0
# and 255; other values (e.g. 'red' or hex values) may be
# passed as well, but will be returned as they were
# returns
# psyrgb -- a (R,G,B) tuple containing values between -1 and 1; or
# rgbgun when passed rgbgun was not a tuple or a list
# """
#
# if type(rgbgun) not in [tuple,list]:
# return rgbgun
#
# psyrgb = []
#
# for val in rgbgun:
# psyrgb.append((val/127.5)-1)
#
# # return (R,G,B), since PsychoPy does not like alpha channels anymore
#
# return tuple(psyrgb[0:3])
#
# Path: pygaze/libtime.py
# def expstart():
# def get_time():
# def pause(pausetime):
# def expend():
#
# Path: pygaze/_display/basedisplay.py
# class BaseDisplay:
#
# """A class for Display objects, to present Screen objects on a monitor"""
#
# def __init__(self):
#
# """
# Initializes a Display object.
#
# arguments
#
# None
#
# keyword arguments
#
# dispsize -- size of the display in pixels: a (width, height)
# tuple (default = DISPSIZE)
# fgc -- the foreground colour: a RGB tuple, e.g. (255,0,0)
# for red or (0,0,0) for black (default = FGC)
# bgc -- the background colour: a RGB tuple, e.g. (0,0,255)
# for blue or (255,255,255) for white (default = BGC)
# screen -- a screen.Screen instance to be presented on the new
# Display (default=None)
# """
#
# pass
#
# def show(self):
#
# """
# Updates ('flips') the display.
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
# time -- the exact refresh time when disptype is PsychoPy,
# or an estimate when disptype is PyGame
# """
#
# pass
#
# def show_part(self, rect, screen=None):
#
# """
# Fills AND shows part(s) of the screen to given specified screen
# (only works when disptype is PyGame; when this is set to PsychoPy
# the entire display is filled and updated)
#
# arguments
#
# rect -- a single or a list of rects; a rect is a (x,y,w,h)
# tuple or list
#
# keyword arguments
#
# screen -- the screen of which the specified rects should be
# updated to the display (default = None)
#
# returns
#
# time -- the exact refresh time when disptype is PsychoPy,
# or an estimate when disptype is PyGame
# """
#
# pass
#
# def fill(self, screen=None):
#
# """
# Fills the screen with the background colour of the Screen, NOT
# updating it (call Display.show() to actually show the new contents)
#
# arguments
#
# None
#
# keyword arguments
#
# screen -- the screen that should be drawn to the display or
# None to fill the display with its background colour
#
# returns
#
# None
# """
#
# pass
#
# def close(self):
#
# """
# Closes the display
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
#
# None
# """
#
# pass
#
# def make_screenshot(self, filename="screenshot.png"):
#
# """
# Make a screenshot from the current display.
#
# arguments
#
# None
#
# keyword arguments
#
# filename -- path and filename, under wich the screenshot will be
# saved. Defaults to screenshot.png
#
# returns
#
# None
# """
#
# pass
. Output only the next line. | for s in screen.screen:
|
Next line prediction: <|code_start|># This file is part of PyGaze - the open-source toolbox for eye tracking
#
# PyGaze is a Python module for easily creating gaze contingent experiments
# or other software (as well as non-gaze contingent experiments/software)
# Copyright (C) 2012-2013 Edwin S. Dalmaijer
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
class Display(BaseDisplay):
# see BaseDisplay
def __init__(self, disptype=settings.DISPTYPE, **args):
# see BaseDisplay
if disptype == "pygame":
<|code_end|>
. Use current file imports:
(from pygaze.py3compat import *
from pygaze import settings
from pygaze._misc.misc import copy_docstr
from pygaze._display.basedisplay import BaseDisplay
from pygaze._display.pygamedisplay import PyGameDisplay as Display
from pygaze._display.psychopydisplay import PsychoPyDisplay as Display
from pygaze._display.osdisplay import OSDisplay as Display
)
and context including class names, function names, or small code snippets from other files:
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
#
# Path: pygaze/_misc/misc.py
# def copy_docstr(src, target):
#
# """
# Copies docstrings from the methods of a source class to the methods of a
# target class.
#
# arguments:
# src -- source class (e.g. BaseDisplay)
# target -- target class (e.g. PyGameDisplay)
# """
#
# for attr_name in dir(target):
# if not hasattr(src, attr_name) or not ismethod(getattr(src, attr_name)):
# continue
# getattr(target, attr_name).__func__.__doc__ = getattr(src, attr_name).__func__.__doc__
#
# Path: pygaze/_display/basedisplay.py
# class BaseDisplay:
#
# """A class for Display objects, to present Screen objects on a monitor"""
#
# def __init__(self):
#
# """
# Initializes a Display object.
#
# arguments
#
# None
#
# keyword arguments
#
# dispsize -- size of the display in pixels: a (width, height)
# tuple (default = DISPSIZE)
# fgc -- the foreground colour: a RGB tuple, e.g. (255,0,0)
# for red or (0,0,0) for black (default = FGC)
# bgc -- the background colour: a RGB tuple, e.g. (0,0,255)
# for blue or (255,255,255) for white (default = BGC)
# screen -- a screen.Screen instance to be presented on the new
# Display (default=None)
# """
#
# pass
#
# def show(self):
#
# """
# Updates ('flips') the display.
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
# time -- the exact refresh time when disptype is PsychoPy,
# or an estimate when disptype is PyGame
# """
#
# pass
#
# def show_part(self, rect, screen=None):
#
# """
# Fills AND shows part(s) of the screen to given specified screen
# (only works when disptype is PyGame; when this is set to PsychoPy
# the entire display is filled and updated)
#
# arguments
#
# rect -- a single or a list of rects; a rect is a (x,y,w,h)
# tuple or list
#
# keyword arguments
#
# screen -- the screen of which the specified rects should be
# updated to the display (default = None)
#
# returns
#
# time -- the exact refresh time when disptype is PsychoPy,
# or an estimate when disptype is PyGame
# """
#
# pass
#
# def fill(self, screen=None):
#
# """
# Fills the screen with the background colour of the Screen, NOT
# updating it (call Display.show() to actually show the new contents)
#
# arguments
#
# None
#
# keyword arguments
#
# screen -- the screen that should be drawn to the display or
# None to fill the display with its background colour
#
# returns
#
# None
# """
#
# pass
#
# def close(self):
#
# """
# Closes the display
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
#
# None
# """
#
# pass
#
# def make_screenshot(self, filename="screenshot.png"):
#
# """
# Make a screenshot from the current display.
#
# arguments
#
# None
#
# keyword arguments
#
# filename -- path and filename, under wich the screenshot will be
# saved. Defaults to screenshot.png
#
# returns
#
# None
# """
#
# pass
. Output only the next line. | elif disptype == "psychopy":
|
Continue the code snippet: <|code_start|>#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
class Display(BaseDisplay):
# see BaseDisplay
def __init__(self, disptype=settings.DISPTYPE, **args):
# see BaseDisplay
if disptype == "pygame":
elif disptype == "psychopy":
elif disptype == "opensesame":
else:
raise Exception("Unexpected disptype : %s" % disptype)
self.__class__ = Display
<|code_end|>
. Use current file imports:
from pygaze.py3compat import *
from pygaze import settings
from pygaze._misc.misc import copy_docstr
from pygaze._display.basedisplay import BaseDisplay
from pygaze._display.pygamedisplay import PyGameDisplay as Display
from pygaze._display.psychopydisplay import PsychoPyDisplay as Display
from pygaze._display.osdisplay import OSDisplay as Display
and context (classes, functions, or code) from other files:
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
#
# Path: pygaze/_misc/misc.py
# def copy_docstr(src, target):
#
# """
# Copies docstrings from the methods of a source class to the methods of a
# target class.
#
# arguments:
# src -- source class (e.g. BaseDisplay)
# target -- target class (e.g. PyGameDisplay)
# """
#
# for attr_name in dir(target):
# if not hasattr(src, attr_name) or not ismethod(getattr(src, attr_name)):
# continue
# getattr(target, attr_name).__func__.__doc__ = getattr(src, attr_name).__func__.__doc__
#
# Path: pygaze/_display/basedisplay.py
# class BaseDisplay:
#
# """A class for Display objects, to present Screen objects on a monitor"""
#
# def __init__(self):
#
# """
# Initializes a Display object.
#
# arguments
#
# None
#
# keyword arguments
#
# dispsize -- size of the display in pixels: a (width, height)
# tuple (default = DISPSIZE)
# fgc -- the foreground colour: a RGB tuple, e.g. (255,0,0)
# for red or (0,0,0) for black (default = FGC)
# bgc -- the background colour: a RGB tuple, e.g. (0,0,255)
# for blue or (255,255,255) for white (default = BGC)
# screen -- a screen.Screen instance to be presented on the new
# Display (default=None)
# """
#
# pass
#
# def show(self):
#
# """
# Updates ('flips') the display.
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
# time -- the exact refresh time when disptype is PsychoPy,
# or an estimate when disptype is PyGame
# """
#
# pass
#
# def show_part(self, rect, screen=None):
#
# """
# Fills AND shows part(s) of the screen to given specified screen
# (only works when disptype is PyGame; when this is set to PsychoPy
# the entire display is filled and updated)
#
# arguments
#
# rect -- a single or a list of rects; a rect is a (x,y,w,h)
# tuple or list
#
# keyword arguments
#
# screen -- the screen of which the specified rects should be
# updated to the display (default = None)
#
# returns
#
# time -- the exact refresh time when disptype is PsychoPy,
# or an estimate when disptype is PyGame
# """
#
# pass
#
# def fill(self, screen=None):
#
# """
# Fills the screen with the background colour of the Screen, NOT
# updating it (call Display.show() to actually show the new contents)
#
# arguments
#
# None
#
# keyword arguments
#
# screen -- the screen that should be drawn to the display or
# None to fill the display with its background colour
#
# returns
#
# None
# """
#
# pass
#
# def close(self):
#
# """
# Closes the display
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
#
# None
# """
#
# pass
#
# def make_screenshot(self, filename="screenshot.png"):
#
# """
# Make a screenshot from the current display.
#
# arguments
#
# None
#
# keyword arguments
#
# filename -- path and filename, under wich the screenshot will be
# saved. Defaults to screenshot.png
#
# returns
#
# None
# """
#
# pass
. Output only the next line. | self.__class__.__init__(self, **args)
|
Predict the next line for this snippet: <|code_start|>#
# PyGaze is a Python module for easily creating gaze contingent experiments
# or other software (as well as non-gaze contingent experiments/software)
# Copyright (C) 2012-2013 Edwin S. Dalmaijer
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
class Display(BaseDisplay):
# see BaseDisplay
def __init__(self, disptype=settings.DISPTYPE, **args):
# see BaseDisplay
if disptype == "pygame":
elif disptype == "psychopy":
<|code_end|>
with the help of current file imports:
from pygaze.py3compat import *
from pygaze import settings
from pygaze._misc.misc import copy_docstr
from pygaze._display.basedisplay import BaseDisplay
from pygaze._display.pygamedisplay import PyGameDisplay as Display
from pygaze._display.psychopydisplay import PsychoPyDisplay as Display
from pygaze._display.osdisplay import OSDisplay as Display
and context from other files:
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
#
# Path: pygaze/_misc/misc.py
# def copy_docstr(src, target):
#
# """
# Copies docstrings from the methods of a source class to the methods of a
# target class.
#
# arguments:
# src -- source class (e.g. BaseDisplay)
# target -- target class (e.g. PyGameDisplay)
# """
#
# for attr_name in dir(target):
# if not hasattr(src, attr_name) or not ismethod(getattr(src, attr_name)):
# continue
# getattr(target, attr_name).__func__.__doc__ = getattr(src, attr_name).__func__.__doc__
#
# Path: pygaze/_display/basedisplay.py
# class BaseDisplay:
#
# """A class for Display objects, to present Screen objects on a monitor"""
#
# def __init__(self):
#
# """
# Initializes a Display object.
#
# arguments
#
# None
#
# keyword arguments
#
# dispsize -- size of the display in pixels: a (width, height)
# tuple (default = DISPSIZE)
# fgc -- the foreground colour: a RGB tuple, e.g. (255,0,0)
# for red or (0,0,0) for black (default = FGC)
# bgc -- the background colour: a RGB tuple, e.g. (0,0,255)
# for blue or (255,255,255) for white (default = BGC)
# screen -- a screen.Screen instance to be presented on the new
# Display (default=None)
# """
#
# pass
#
# def show(self):
#
# """
# Updates ('flips') the display.
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
# time -- the exact refresh time when disptype is PsychoPy,
# or an estimate when disptype is PyGame
# """
#
# pass
#
# def show_part(self, rect, screen=None):
#
# """
# Fills AND shows part(s) of the screen to given specified screen
# (only works when disptype is PyGame; when this is set to PsychoPy
# the entire display is filled and updated)
#
# arguments
#
# rect -- a single or a list of rects; a rect is a (x,y,w,h)
# tuple or list
#
# keyword arguments
#
# screen -- the screen of which the specified rects should be
# updated to the display (default = None)
#
# returns
#
# time -- the exact refresh time when disptype is PsychoPy,
# or an estimate when disptype is PyGame
# """
#
# pass
#
# def fill(self, screen=None):
#
# """
# Fills the screen with the background colour of the Screen, NOT
# updating it (call Display.show() to actually show the new contents)
#
# arguments
#
# None
#
# keyword arguments
#
# screen -- the screen that should be drawn to the display or
# None to fill the display with its background colour
#
# returns
#
# None
# """
#
# pass
#
# def close(self):
#
# """
# Closes the display
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
#
# None
# """
#
# pass
#
# def make_screenshot(self, filename="screenshot.png"):
#
# """
# Make a screenshot from the current display.
#
# arguments
#
# None
#
# keyword arguments
#
# filename -- path and filename, under wich the screenshot will be
# saved. Defaults to screenshot.png
#
# returns
#
# None
# """
#
# pass
, which may contain function names, class names, or code. Output only the next line. | elif disptype == "opensesame":
|
Predict the next line after this snippet: <|code_start|>#
# PyGaze is a Python module for easily creating gaze contingent experiments
# or other software (as well as non-gaze contingent experiments/software)
# Copyright (C) 2012-2013 Edwin S. Dalmaijer
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
if settings.DISPTYPE == "psychopy":
try:
except:
raise Exception("Error in plugins.frl: PsychoPy could not be loaded!")
else:
try:
except:
raise Exception("Error in plugins.frl: PyGame could not be loaded!")
<|code_end|>
using the current file's imports:
from pygaze import settings
from psychopy.visual import Aperture
from pygaze._misc.misc import pos2psychopos, psychopos2pos
import pygame
import pygaze
and any relevant context from other files:
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
#
# Path: pygaze/_misc/misc.py
# def pos2psychopos(pos, dispsize=None):
#
# """Returns a converted position tuple (x,y) (internal use)
#
# arguments
# pos -- a (x,y) position tuple, assuming (0,0) is top left
#
# keyword arguments
# dispsize -- a (width, height) tuple for the display resolution or None
# for autodetecting the size of current active window
# (default = None)
#
# returns
# pos -- a (x,y) tuple that makes sense to PsychoPy (i.e. (0,0) is
# display center; bottom left is (-,-) and top right is
# (+,+))
# """
#
# if dispsize is None:
# dispsize = settings.DISPSIZE[:]
#
# x = pos[0] - dispsize[0]/2
# y = (pos[1] - dispsize[1]/2) * -1
#
# return (x,y)
#
# def psychopos2pos(pos, dispsize=None):
#
# """Returns a converted position tuple (x,y) (internal use)
#
# arguments
# pos -- a (x,y) tuple that makes sense to PsychoPy (i.e. (0,0) is
# display center; bottom left is (-,-) and top right is
# (+,+))
#
# keyword arguments
# dispsize -- a (width, height) tuple for the display resolution or None
# for autodetecting the size of current active window
# (default = None)
#
# returns
# pos -- a (x,y) position tuple, assuming (0,0) is top left
# """
#
# if dispsize is None:
# dispsize = settings.DISPSIZE[:]
#
# x = pos[0] + dispsize[0]/2
# y = (pos[1] * -1) + dispsize[1]/2
#
# return (x,y)
. Output only the next line. | class FRL:
|
Predict the next line for this snippet: <|code_start|># the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
# we try importing the copy_docstr function, but as we do not really need it
# for a proper functioning of the code, we simply ignore it when it fails to
# be imported correctly
try:
except:
pass
class PyGameTime(BaseTime):
# see pygaze._time.basetime.BaseTime
def __init__(self):
# see pygaze._time.basetime.BaseTime
# try to copy docstring (but ignore it if it fails, as we do
# not need it for actual functioning of the code)
<|code_end|>
with the help of current file imports:
import pygame
import time
import sys
from pygaze._time.basetime import BaseTime
from pygaze._misc.misc import copy_docstr
and context from other files:
# Path: pygaze/_time/basetime.py
# class BaseTime:
#
# """Class for keeping track of time"""
#
# def __init__(self):
#
# """
# Initializes a Time instance
#
# arguments
#
# None
#
# keyword arguments
#
# None
# """
#
# pass
#
#
# def expstart(self):
#
# """
# Time is set to 0 when calling this
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
#
# Nothing
# """
#
# pass
#
#
# def get_time(self):
#
# """
# Returns current time in milliseconds
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
#
# time -- current time in milliseconds, as measured since
# expbegintime
# """
#
# pass
#
#
# def pause(self):
#
# """
# Pauses the experiment for given number of milliseconds
#
# arguments
#
# pausetime -- time to pause in milliseconds
#
# keyword arguments
#
# None
#
# returns
#
# pausetime -- actual time the system paused (in milliseconds)
# """
#
# pass
#
#
# def expend(self):
#
# """
# Completely ends the experiment (only call this at the end!)
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
#
# endtime -- ending time of the experiment (in milliseconds since
# expbegintime
# """
#
# pass
, which may contain function names, class names, or code. Output only the next line. | try: |
Predict the next line after this snippet: <|code_start|>
def show_part(self, rect, screen=None):
# See _display.basedisplay.BaseDisplay for documentation
if len(rect) > 1:
for r in rect:
pygaze.expdisplay.set_clip(r)
if screen:
pygaze.expdisplay.blit(screen.screen, (0,0))
pygame.display.update(r)
pygaze.expdisplay.set_clip(None)
elif len(rect) == 1:
pygaze.expdisplay.clip(rect)
if screen:
pygaze.expdisplay.blit(screen.screen, (0,0))
pygame.display.update(rect)
pygaze.expdisplay.set_clip(None)
else:
raise Exception("Error in libscreen.Display.show_part: rect should be a single rect (i.e. a (x,y,w,h) tuple) or a list of rects!")
return clock.get_time()
def fill(self, screen=None):
# See _display.basedisplay.BaseDisplay for documentation
<|code_end|>
using the current file's imports:
from pygaze import settings
from pygaze.libtime import clock
from pygaze._display.basedisplay import BaseDisplay
from pygaze._misc.misc import copy_docstr
import pygaze
import copy
import math
import os.path
import pygame
import pygame.display
import pygame.draw
import pygame.image
and any relevant context from other files:
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
#
# Path: pygaze/libtime.py
# def expstart():
# def get_time():
# def pause(pausetime):
# def expend():
#
# Path: pygaze/_display/basedisplay.py
# class BaseDisplay:
#
# """A class for Display objects, to present Screen objects on a monitor"""
#
# def __init__(self):
#
# """
# Initializes a Display object.
#
# arguments
#
# None
#
# keyword arguments
#
# dispsize -- size of the display in pixels: a (width, height)
# tuple (default = DISPSIZE)
# fgc -- the foreground colour: a RGB tuple, e.g. (255,0,0)
# for red or (0,0,0) for black (default = FGC)
# bgc -- the background colour: a RGB tuple, e.g. (0,0,255)
# for blue or (255,255,255) for white (default = BGC)
# screen -- a screen.Screen instance to be presented on the new
# Display (default=None)
# """
#
# pass
#
# def show(self):
#
# """
# Updates ('flips') the display.
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
# time -- the exact refresh time when disptype is PsychoPy,
# or an estimate when disptype is PyGame
# """
#
# pass
#
# def show_part(self, rect, screen=None):
#
# """
# Fills AND shows part(s) of the screen to given specified screen
# (only works when disptype is PyGame; when this is set to PsychoPy
# the entire display is filled and updated)
#
# arguments
#
# rect -- a single or a list of rects; a rect is a (x,y,w,h)
# tuple or list
#
# keyword arguments
#
# screen -- the screen of which the specified rects should be
# updated to the display (default = None)
#
# returns
#
# time -- the exact refresh time when disptype is PsychoPy,
# or an estimate when disptype is PyGame
# """
#
# pass
#
# def fill(self, screen=None):
#
# """
# Fills the screen with the background colour of the Screen, NOT
# updating it (call Display.show() to actually show the new contents)
#
# arguments
#
# None
#
# keyword arguments
#
# screen -- the screen that should be drawn to the display or
# None to fill the display with its background colour
#
# returns
#
# None
# """
#
# pass
#
# def close(self):
#
# """
# Closes the display
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
#
# None
# """
#
# pass
#
# def make_screenshot(self, filename="screenshot.png"):
#
# """
# Make a screenshot from the current display.
#
# arguments
#
# None
#
# keyword arguments
#
# filename -- path and filename, under wich the screenshot will be
# saved. Defaults to screenshot.png
#
# returns
#
# None
# """
#
# pass
. Output only the next line. | pygaze.expdisplay.fill(self.bgc)
|
Predict the next line for this snippet: <|code_start|>
def __init__(self, dispsize=settings.DISPSIZE, fgc=settings.FGC,
bgc=settings.BGC, screen=None, **args):
# See _display.basedisplay.BaseDisplay for documentation
# try to import copy docstring (but ignore it if it fails, as we do
# not need it for actual functioning of the code)
try:
copy_docstr(BaseDisplay, PyGameDisplay)
except:
# we're not even going to show a warning, since the copied
# docstring is useful for code editors; these load the docs
# in a non-verbose manner, so warning messages would be lost
pass
self.dispsize = dispsize
self.fgc = fgc
self.bgc = bgc
self.mousevis = False
# initialize PyGame display-module
pygame.display.init()
# make mouse invisible (should be so per default, but you never know)
pygame.mouse.set_visible(self.mousevis)
if settings.FULLSCREEN:
mode = pygame.FULLSCREEN|pygame.HWSURFACE|pygame.DOUBLEBUF
else:
mode = pygame.HWSURFACE|pygame.DOUBLEBUF
# create surface for full screen displaying
<|code_end|>
with the help of current file imports:
from pygaze import settings
from pygaze.libtime import clock
from pygaze._display.basedisplay import BaseDisplay
from pygaze._misc.misc import copy_docstr
import pygaze
import copy
import math
import os.path
import pygame
import pygame.display
import pygame.draw
import pygame.image
and context from other files:
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
#
# Path: pygaze/libtime.py
# def expstart():
# def get_time():
# def pause(pausetime):
# def expend():
#
# Path: pygaze/_display/basedisplay.py
# class BaseDisplay:
#
# """A class for Display objects, to present Screen objects on a monitor"""
#
# def __init__(self):
#
# """
# Initializes a Display object.
#
# arguments
#
# None
#
# keyword arguments
#
# dispsize -- size of the display in pixels: a (width, height)
# tuple (default = DISPSIZE)
# fgc -- the foreground colour: a RGB tuple, e.g. (255,0,0)
# for red or (0,0,0) for black (default = FGC)
# bgc -- the background colour: a RGB tuple, e.g. (0,0,255)
# for blue or (255,255,255) for white (default = BGC)
# screen -- a screen.Screen instance to be presented on the new
# Display (default=None)
# """
#
# pass
#
# def show(self):
#
# """
# Updates ('flips') the display.
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
# time -- the exact refresh time when disptype is PsychoPy,
# or an estimate when disptype is PyGame
# """
#
# pass
#
# def show_part(self, rect, screen=None):
#
# """
# Fills AND shows part(s) of the screen to given specified screen
# (only works when disptype is PyGame; when this is set to PsychoPy
# the entire display is filled and updated)
#
# arguments
#
# rect -- a single or a list of rects; a rect is a (x,y,w,h)
# tuple or list
#
# keyword arguments
#
# screen -- the screen of which the specified rects should be
# updated to the display (default = None)
#
# returns
#
# time -- the exact refresh time when disptype is PsychoPy,
# or an estimate when disptype is PyGame
# """
#
# pass
#
# def fill(self, screen=None):
#
# """
# Fills the screen with the background colour of the Screen, NOT
# updating it (call Display.show() to actually show the new contents)
#
# arguments
#
# None
#
# keyword arguments
#
# screen -- the screen that should be drawn to the display or
# None to fill the display with its background colour
#
# returns
#
# None
# """
#
# pass
#
# def close(self):
#
# """
# Closes the display
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
#
# None
# """
#
# pass
#
# def make_screenshot(self, filename="screenshot.png"):
#
# """
# Make a screenshot from the current display.
#
# arguments
#
# None
#
# keyword arguments
#
# filename -- path and filename, under wich the screenshot will be
# saved. Defaults to screenshot.png
#
# returns
#
# None
# """
#
# pass
, which may contain function names, class names, or code. Output only the next line. | pygaze.expdisplay = pygame.display.set_mode(self.dispsize, mode)
|
Using the snippet: <|code_start|> # initialize PyGame display-module
pygame.display.init()
# make mouse invisible (should be so per default, but you never know)
pygame.mouse.set_visible(self.mousevis)
if settings.FULLSCREEN:
mode = pygame.FULLSCREEN|pygame.HWSURFACE|pygame.DOUBLEBUF
else:
mode = pygame.HWSURFACE|pygame.DOUBLEBUF
# create surface for full screen displaying
pygaze.expdisplay = pygame.display.set_mode(self.dispsize, mode)
# blit screen to display surface (if user entered one)
if screen:
pygaze.expdisplay.blit(screen.screen,(0,0))
else:
pygaze.expdisplay.fill(self.bgc)
def show(self):
# See _display.basedisplay.BaseDisplay for documentation
pygame.display.flip()
return clock.get_time()
def show_part(self, rect, screen=None):
# See _display.basedisplay.BaseDisplay for documentation
<|code_end|>
, determine the next line of code. You have imports:
from pygaze import settings
from pygaze.libtime import clock
from pygaze._display.basedisplay import BaseDisplay
from pygaze._misc.misc import copy_docstr
import pygaze
import copy
import math
import os.path
import pygame
import pygame.display
import pygame.draw
import pygame.image
and context (class names, function names, or code) available:
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
#
# Path: pygaze/libtime.py
# def expstart():
# def get_time():
# def pause(pausetime):
# def expend():
#
# Path: pygaze/_display/basedisplay.py
# class BaseDisplay:
#
# """A class for Display objects, to present Screen objects on a monitor"""
#
# def __init__(self):
#
# """
# Initializes a Display object.
#
# arguments
#
# None
#
# keyword arguments
#
# dispsize -- size of the display in pixels: a (width, height)
# tuple (default = DISPSIZE)
# fgc -- the foreground colour: a RGB tuple, e.g. (255,0,0)
# for red or (0,0,0) for black (default = FGC)
# bgc -- the background colour: a RGB tuple, e.g. (0,0,255)
# for blue or (255,255,255) for white (default = BGC)
# screen -- a screen.Screen instance to be presented on the new
# Display (default=None)
# """
#
# pass
#
# def show(self):
#
# """
# Updates ('flips') the display.
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
# time -- the exact refresh time when disptype is PsychoPy,
# or an estimate when disptype is PyGame
# """
#
# pass
#
# def show_part(self, rect, screen=None):
#
# """
# Fills AND shows part(s) of the screen to given specified screen
# (only works when disptype is PyGame; when this is set to PsychoPy
# the entire display is filled and updated)
#
# arguments
#
# rect -- a single or a list of rects; a rect is a (x,y,w,h)
# tuple or list
#
# keyword arguments
#
# screen -- the screen of which the specified rects should be
# updated to the display (default = None)
#
# returns
#
# time -- the exact refresh time when disptype is PsychoPy,
# or an estimate when disptype is PyGame
# """
#
# pass
#
# def fill(self, screen=None):
#
# """
# Fills the screen with the background colour of the Screen, NOT
# updating it (call Display.show() to actually show the new contents)
#
# arguments
#
# None
#
# keyword arguments
#
# screen -- the screen that should be drawn to the display or
# None to fill the display with its background colour
#
# returns
#
# None
# """
#
# pass
#
# def close(self):
#
# """
# Closes the display
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
#
# None
# """
#
# pass
#
# def make_screenshot(self, filename="screenshot.png"):
#
# """
# Make a screenshot from the current display.
#
# arguments
#
# None
#
# keyword arguments
#
# filename -- path and filename, under wich the screenshot will be
# saved. Defaults to screenshot.png
#
# returns
#
# None
# """
#
# pass
. Output only the next line. | if len(rect) > 1:
|
Continue the code snippet: <|code_start|>
# # # # #
# VIBRATION
if RUMBLE:
# define necessary structure
class XINPUT_VIBRATION(ctypes.Structure):
_fields_ = [("wLeftMotorSpeed", ctypes.c_ushort),
("wRightMotorSpeed", ctypes.c_ushort)]
# load Xinput.dll
try:
print("trying to import xinput1_1.dll")
<|code_end|>
. Use current file imports:
import ctypes
import pygaze.libtime as timer
from constants import *
from pygaze.display import Display
from pygaze.screen import Screen
from pygaze.joystick import Joystick
and context (classes, functions, or code) from other files:
# Path: pygaze/display.py
# class Display(BaseDisplay):
#
# # see BaseDisplay
#
# def __init__(self, disptype=settings.DISPTYPE, **args):
#
# # see BaseDisplay
#
# if disptype == "pygame":
# from pygaze._display.pygamedisplay import PyGameDisplay as Display
# elif disptype == "psychopy":
# from pygaze._display.psychopydisplay import PsychoPyDisplay as Display
# elif disptype == "opensesame":
# from pygaze._display.osdisplay import OSDisplay as Display
# else:
# raise Exception("Unexpected disptype : %s" % disptype)
# self.__class__ = Display
# self.__class__.__init__(self, **args)
# copy_docstr(BaseDisplay, Display)
#
# Path: pygaze/screen.py
# class Screen(BaseScreen):
#
# """
# A class for Screen objects, for visual stimuli (to be displayed via a
# Display object)
# """
#
# def __init__(self, disptype=settings.DISPTYPE, **args):
#
# """
# Initializes the Screen object.
#
# Keyword arguments:
# disptype -- Type of display: either "pygame" or "psychopy"
# (default = DISPTYPE)
# dispsize -- size of the display in pixels: a (width, height)
# tuple (default = DISPSIZE)
# fgc -- the foreground colour: a colour name (e.g. "red") or
# a RGB(A) tuple (e.g. (255,0,0) or (255,0,0,255))
# (default = FGC)
# bgc -- the background colour: a colour name (e.g. "red") or
# a RGB(A) tuple (e.g. (255,0,0) or (255,0,0,255))
# (default = BGC)
# screennr -- the screen number: 0, 1 etc. (default =
# SCREENNR)
# mousevisible -- Boolean indicating mouse visibility (default =
# MOUSEVISIBLE)
# screen -- a Screen object to be presented on the new Display
# (default=None)
# """
#
# if disptype == "pygame":
# from pygaze._screen.pygamescreen import PyGameScreen as Screen
# elif disptype == "psychopy":
# from pygaze._screen.psychopyscreen import PsychoPyScreen as Screen
# elif disptype == "opensesame":
# from pygaze._screen.osscreen import OSScreen as Screen
# else:
# raise Exception("Unexpected disptype: {}".format(disptype))
# self.__class__ = Screen
# self.__class__.__init__(self, **args)
# copy_docstr(BaseScreen, Screen)
#
# Path: pygaze/joystick.py
# class Joystick(BaseJoystick):
#
# # see BaseJoystick
#
# def __init__(self, disptype=settings.DISPTYPE, **args):
#
# # see BaseJoystick
#
# if disptype in ("pygame", "psychopy"):
# from pygaze._joystick.pygamejoystick import PyGameJoystick
# self.__class__ = PyGameJoystick
# else:
# raise Exception("Unexpected disptype: {}".format(disptype))
# self.__class__.__init__(self, **args)
# copy_docstr(BaseJoystick, Joystick)
. Output only the next line. | xinput = ctypes.windll.xinput1_1
|
Next line prediction: <|code_start|>
# # # # #
# VIBRATION
if RUMBLE:
# define necessary structure
class XINPUT_VIBRATION(ctypes.Structure):
_fields_ = [("wLeftMotorSpeed", ctypes.c_ushort),
("wRightMotorSpeed", ctypes.c_ushort)]
# load Xinput.dll
try:
print("trying to import xinput1_1.dll")
xinput = ctypes.windll.xinput1_1
<|code_end|>
. Use current file imports:
(import ctypes
import pygaze.libtime as timer
from constants import *
from pygaze.display import Display
from pygaze.screen import Screen
from pygaze.joystick import Joystick
)
and context including class names, function names, or small code snippets from other files:
# Path: pygaze/display.py
# class Display(BaseDisplay):
#
# # see BaseDisplay
#
# def __init__(self, disptype=settings.DISPTYPE, **args):
#
# # see BaseDisplay
#
# if disptype == "pygame":
# from pygaze._display.pygamedisplay import PyGameDisplay as Display
# elif disptype == "psychopy":
# from pygaze._display.psychopydisplay import PsychoPyDisplay as Display
# elif disptype == "opensesame":
# from pygaze._display.osdisplay import OSDisplay as Display
# else:
# raise Exception("Unexpected disptype : %s" % disptype)
# self.__class__ = Display
# self.__class__.__init__(self, **args)
# copy_docstr(BaseDisplay, Display)
#
# Path: pygaze/screen.py
# class Screen(BaseScreen):
#
# """
# A class for Screen objects, for visual stimuli (to be displayed via a
# Display object)
# """
#
# def __init__(self, disptype=settings.DISPTYPE, **args):
#
# """
# Initializes the Screen object.
#
# Keyword arguments:
# disptype -- Type of display: either "pygame" or "psychopy"
# (default = DISPTYPE)
# dispsize -- size of the display in pixels: a (width, height)
# tuple (default = DISPSIZE)
# fgc -- the foreground colour: a colour name (e.g. "red") or
# a RGB(A) tuple (e.g. (255,0,0) or (255,0,0,255))
# (default = FGC)
# bgc -- the background colour: a colour name (e.g. "red") or
# a RGB(A) tuple (e.g. (255,0,0) or (255,0,0,255))
# (default = BGC)
# screennr -- the screen number: 0, 1 etc. (default =
# SCREENNR)
# mousevisible -- Boolean indicating mouse visibility (default =
# MOUSEVISIBLE)
# screen -- a Screen object to be presented on the new Display
# (default=None)
# """
#
# if disptype == "pygame":
# from pygaze._screen.pygamescreen import PyGameScreen as Screen
# elif disptype == "psychopy":
# from pygaze._screen.psychopyscreen import PsychoPyScreen as Screen
# elif disptype == "opensesame":
# from pygaze._screen.osscreen import OSScreen as Screen
# else:
# raise Exception("Unexpected disptype: {}".format(disptype))
# self.__class__ = Screen
# self.__class__.__init__(self, **args)
# copy_docstr(BaseScreen, Screen)
#
# Path: pygaze/joystick.py
# class Joystick(BaseJoystick):
#
# # see BaseJoystick
#
# def __init__(self, disptype=settings.DISPTYPE, **args):
#
# # see BaseJoystick
#
# if disptype in ("pygame", "psychopy"):
# from pygaze._joystick.pygamejoystick import PyGameJoystick
# self.__class__ = PyGameJoystick
# else:
# raise Exception("Unexpected disptype: {}".format(disptype))
# self.__class__.__init__(self, **args)
# copy_docstr(BaseJoystick, Joystick)
. Output only the next line. | except:
|
Given the code snippet: <|code_start|> XInputSetState.argtypes = [ctypes.c_uint, ctypes.POINTER(XINPUT_VIBRATION)]
XInputSetState.restype = ctypes.c_uint
# define helper function
def set_vibration(controller, left_motor, right_motor):
vibration = XINPUT_VIBRATION(int(left_motor * 65535), int(right_motor * 65535))
XInputSetState(controller, ctypes.byref(vibration))
# # # # #
# PYGAZE INSTANCES
# visual
disp = Display()
scr = Screen()
# input
js = Joystick()
# # # # #
# RUN
# run until a minute has passed
t0 = timer.get_time()
t1 = timer.get_time()
text = "Test the joystick!"
while t1 - t0 < 60000:
# get joystick input
event, value, t1 = js.get_joyinput(timeout=10)
# update text
if event != None:
<|code_end|>
, generate the next line using the imports in this file:
import ctypes
import pygaze.libtime as timer
from constants import *
from pygaze.display import Display
from pygaze.screen import Screen
from pygaze.joystick import Joystick
and context (functions, classes, or occasionally code) from other files:
# Path: pygaze/display.py
# class Display(BaseDisplay):
#
# # see BaseDisplay
#
# def __init__(self, disptype=settings.DISPTYPE, **args):
#
# # see BaseDisplay
#
# if disptype == "pygame":
# from pygaze._display.pygamedisplay import PyGameDisplay as Display
# elif disptype == "psychopy":
# from pygaze._display.psychopydisplay import PsychoPyDisplay as Display
# elif disptype == "opensesame":
# from pygaze._display.osdisplay import OSDisplay as Display
# else:
# raise Exception("Unexpected disptype : %s" % disptype)
# self.__class__ = Display
# self.__class__.__init__(self, **args)
# copy_docstr(BaseDisplay, Display)
#
# Path: pygaze/screen.py
# class Screen(BaseScreen):
#
# """
# A class for Screen objects, for visual stimuli (to be displayed via a
# Display object)
# """
#
# def __init__(self, disptype=settings.DISPTYPE, **args):
#
# """
# Initializes the Screen object.
#
# Keyword arguments:
# disptype -- Type of display: either "pygame" or "psychopy"
# (default = DISPTYPE)
# dispsize -- size of the display in pixels: a (width, height)
# tuple (default = DISPSIZE)
# fgc -- the foreground colour: a colour name (e.g. "red") or
# a RGB(A) tuple (e.g. (255,0,0) or (255,0,0,255))
# (default = FGC)
# bgc -- the background colour: a colour name (e.g. "red") or
# a RGB(A) tuple (e.g. (255,0,0) or (255,0,0,255))
# (default = BGC)
# screennr -- the screen number: 0, 1 etc. (default =
# SCREENNR)
# mousevisible -- Boolean indicating mouse visibility (default =
# MOUSEVISIBLE)
# screen -- a Screen object to be presented on the new Display
# (default=None)
# """
#
# if disptype == "pygame":
# from pygaze._screen.pygamescreen import PyGameScreen as Screen
# elif disptype == "psychopy":
# from pygaze._screen.psychopyscreen import PsychoPyScreen as Screen
# elif disptype == "opensesame":
# from pygaze._screen.osscreen import OSScreen as Screen
# else:
# raise Exception("Unexpected disptype: {}".format(disptype))
# self.__class__ = Screen
# self.__class__.__init__(self, **args)
# copy_docstr(BaseScreen, Screen)
#
# Path: pygaze/joystick.py
# class Joystick(BaseJoystick):
#
# # see BaseJoystick
#
# def __init__(self, disptype=settings.DISPTYPE, **args):
#
# # see BaseJoystick
#
# if disptype in ("pygame", "psychopy"):
# from pygaze._joystick.pygamejoystick import PyGameJoystick
# self.__class__ = PyGameJoystick
# else:
# raise Exception("Unexpected disptype: {}".format(disptype))
# self.__class__.__init__(self, **args)
# copy_docstr(BaseJoystick, Joystick)
. Output only the next line. | text = text="%s: %s" % (event, value)
|
Predict the next line after this snippet: <|code_start|>
self.expbegintime = psychopy.core.getTime() * 1000
def get_time(self):
# see pygaze._time.basetime.BaseTime
return psychopy.core.getTime() * 1000 - self.expbegintime
def pause(self, pausetime):
# see pygaze._time.basetime.BaseTime
t0 = psychopy.core.getTime()
psychopy.core.wait(pausetime/1000.0)
t1 = psychopy.core.getTime()
return t1-t0
def expend(self):
# see pygaze._time.basetime.BaseTime
endtime = self.get_time() * 1000
psychopy.core.quit()
<|code_end|>
using the current file's imports:
import psychopy.core
from pygaze._time.basetime import BaseTime
from pygaze._misc.misc import copy_docstr
and any relevant context from other files:
# Path: pygaze/_time/basetime.py
# class BaseTime:
#
# """Class for keeping track of time"""
#
# def __init__(self):
#
# """
# Initializes a Time instance
#
# arguments
#
# None
#
# keyword arguments
#
# None
# """
#
# pass
#
#
# def expstart(self):
#
# """
# Time is set to 0 when calling this
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
#
# Nothing
# """
#
# pass
#
#
# def get_time(self):
#
# """
# Returns current time in milliseconds
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
#
# time -- current time in milliseconds, as measured since
# expbegintime
# """
#
# pass
#
#
# def pause(self):
#
# """
# Pauses the experiment for given number of milliseconds
#
# arguments
#
# pausetime -- time to pause in milliseconds
#
# keyword arguments
#
# None
#
# returns
#
# pausetime -- actual time the system paused (in milliseconds)
# """
#
# pass
#
#
# def expend(self):
#
# """
# Completely ends the experiment (only call this at the end!)
#
# arguments
#
# None
#
# keyword arguments
#
# None
#
# returns
#
# endtime -- ending time of the experiment (in milliseconds since
# expbegintime
# """
#
# pass
. Output only the next line. | return endtime |
Based on the snippet: <|code_start|>## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>
#
# version: 0.4 (25-03-2013)
# on Windows, PyGame's webcam support is a bit shaky, so we provide a vidcap
# back-end; project homepage: http://videocapture.sourceforge.net/
vidimp = False
if sys.platform == 'win32':
# we needn't use vidcap specifically, so we try to import it
try:
vidimp = True
# if this fails, we present a warning, but do not need to crash
except:
print("WARNING! libwebcam: vidcap could not be imported; pygame back-end is still available")
# for other platforms, we use PyGame
pgcamimp = False
try:
pygame.camera.init()
pgcamimp = True
<|code_end|>
, predict the immediate next line with the help of imports:
from pygaze import settings
from PIL import Image
import sys
import vidcap
import pygame.camera
import pygame.image
and context (classes, functions, sometimes code) from other files:
# Path: pygaze/settings.py
# class Settings(object):
# def __init__(self):
# def read_module(self, mod):
# def __getattr__(self, setting):
# def __setattr__(self, setting, value):
. Output only the next line. | except: |
Here is a snippet: <|code_start|>
# supported operators
operators = {
ast.Add: op.add,
ast.Sub: op.sub,
ast.Mult: op.mul,
ast.Div: op.truediv,
ast.Pow: op.pow,
ast.BitXor: op.xor,
ast.USub: op.neg,
ast.Invert: op.invert,
}
# eval_expr / _eval from: http://stackoverflow.com/a/9558001/2374860
def eval_expr(expr):
return _eval(ast.parse(expr, mode="eval").body)
def _eval(node):
if isinstance(node, ast.Num): # <number> e.g. 1 or -1
return node.n
elif isinstance(node, ast.BinOp): # <left> <operator> <right>
return operators[type(node.op)](_eval(node.left), _eval(node.right))
elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., ~1
return operators[type(node.op)](_eval(node.operand))
else:
raise TypeError(node)
<|code_end|>
. Write the next line using the current file imports:
import ast
import operator as op
import re
import shlex
import sys
from datetime import datetime
from functools import reduce
from .colorable import Colorable
from .ledgerbilexceptions import ERROR_RETURN_VALUE, LdgReconcilerError
from .settings_getter import get_setting
and context from other files:
# Path: ledgerbil/colorable.py
# class Colorable:
#
# START_CODE = "\033"
# END_CODE = f"{START_CODE}[0m"
#
# BRIGHT_OFFSET = 60
#
# COLORS = {
# "black": 30,
# "gray": 30,
# "grey": 30,
# "red": 31,
# "green": 32,
# "yellow": 33,
# "blue": 34,
# "magenta": 35,
# "purple": 35,
# "cyan": 36,
# "white": 37,
# }
#
# ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
#
# def __init__(self, color, value, fmt="", bright=False):
#
# if color not in self.COLORS:
# raise UnsupportedColorError(
# f"I don't know what to do with this color: {color}"
# )
#
# self.my_color = color
# self.value = value
# self.bright = bright
# self.format_string = fmt
#
# def __repr__(self):
# return (
# f"Colorable('{self.my_color}', '{self.value}', "
# f"fmt='{self.format_string}', bright={self.bright})"
# )
#
# def __str__(self):
# start = self.ansi_sequence(self.COLORS[self.my_color], bright=self.bright)
# ansi_str = f"{start}{self.value:{self.format_string}}{self.END_CODE}"
# return ansi_str
#
# def __len__(self):
# return len(self.value)
#
# def __eq__(self, other):
# return str(self) == str(other)
#
# def ansi_sequence(self, code, bright=False):
# offset = 60 if bright else 0
# color = code + offset
# return f"{self.START_CODE}[0;{color}m"
#
# def plain(self):
# return self.value
#
# @staticmethod
# def get_plain_string(ansi_string):
# return Colorable.ansi_escape.sub("", ansi_string)
#
# Path: ledgerbil/ledgerbilexceptions.py
# ERROR_RETURN_VALUE = 1
#
# class LdgReconcilerError(LdgException):
# pass
#
# Path: ledgerbil/settings_getter.py
# def get_setting(setting, default=None):
# if settings and hasattr(settings, setting):
# return getattr(settings, setting)
#
# return defaults.get(setting, default)
, which may include functions, classes, or code. Output only the next line. | def get_date_string(the_date, the_format=None): |
Next line prediction: <|code_start|> get_date(date_string)
return True
except ValueError:
return False
def is_integer(value):
try:
return re.sub(r"^[-+]", "", value).isdigit()
except TypeError:
return False
def is_float(value):
try:
float(value)
return True
except ValueError:
return False
def get_float(value):
return float(re.sub(r"[ $,]", "", value))
def get_start_and_end_range(numbers):
int_nums = [int(num) for num in numbers]
return min(int_nums), max(int_nums) + 1
<|code_end|>
. Use current file imports:
(import ast
import operator as op
import re
import shlex
import sys
from datetime import datetime
from functools import reduce
from .colorable import Colorable
from .ledgerbilexceptions import ERROR_RETURN_VALUE, LdgReconcilerError
from .settings_getter import get_setting)
and context including class names, function names, or small code snippets from other files:
# Path: ledgerbil/colorable.py
# class Colorable:
#
# START_CODE = "\033"
# END_CODE = f"{START_CODE}[0m"
#
# BRIGHT_OFFSET = 60
#
# COLORS = {
# "black": 30,
# "gray": 30,
# "grey": 30,
# "red": 31,
# "green": 32,
# "yellow": 33,
# "blue": 34,
# "magenta": 35,
# "purple": 35,
# "cyan": 36,
# "white": 37,
# }
#
# ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
#
# def __init__(self, color, value, fmt="", bright=False):
#
# if color not in self.COLORS:
# raise UnsupportedColorError(
# f"I don't know what to do with this color: {color}"
# )
#
# self.my_color = color
# self.value = value
# self.bright = bright
# self.format_string = fmt
#
# def __repr__(self):
# return (
# f"Colorable('{self.my_color}', '{self.value}', "
# f"fmt='{self.format_string}', bright={self.bright})"
# )
#
# def __str__(self):
# start = self.ansi_sequence(self.COLORS[self.my_color], bright=self.bright)
# ansi_str = f"{start}{self.value:{self.format_string}}{self.END_CODE}"
# return ansi_str
#
# def __len__(self):
# return len(self.value)
#
# def __eq__(self, other):
# return str(self) == str(other)
#
# def ansi_sequence(self, code, bright=False):
# offset = 60 if bright else 0
# color = code + offset
# return f"{self.START_CODE}[0;{color}m"
#
# def plain(self):
# return self.value
#
# @staticmethod
# def get_plain_string(ansi_string):
# return Colorable.ansi_escape.sub("", ansi_string)
#
# Path: ledgerbil/ledgerbilexceptions.py
# ERROR_RETURN_VALUE = 1
#
# class LdgReconcilerError(LdgException):
# pass
#
# Path: ledgerbil/settings_getter.py
# def get_setting(setting, default=None):
# if settings and hasattr(settings, setting):
# return getattr(settings, setting)
#
# return defaults.get(setting, default)
. Output only the next line. | def product(numbers): |
Given the code snippet: <|code_start|>
def get_plain_amount(amount, colwidth=1, decimals=2, prefix="$ "):
amount_formatted = f"{prefix}{get_amount_str(amount, decimals)}"
return f"{amount_formatted:>{colwidth}}"
def get_colored_amount(
amount, colwidth=1, decimals=2, prefix="$ ", positive="green", zero="green"
):
amount_formatted = f"{prefix}{get_amount_str(amount, decimals)}"
# avoid inconsistent 0 coloring from round/float intrigue
if amount_formatted == f"{prefix}{0:.{decimals}f}":
amount = 0
if amount == 0:
color = zero
elif amount < 0:
color = "red"
else:
color = positive
return str(Colorable(color, amount_formatted, f">{colwidth}"))
def assert_only_one_matching_account(accounts):
if len(set(accounts)) > 1:
message = "More than one matching account:\n"
for account in sorted(accounts):
<|code_end|>
, generate the next line using the imports in this file:
import ast
import operator as op
import re
import shlex
import sys
from datetime import datetime
from functools import reduce
from .colorable import Colorable
from .ledgerbilexceptions import ERROR_RETURN_VALUE, LdgReconcilerError
from .settings_getter import get_setting
and context (functions, classes, or occasionally code) from other files:
# Path: ledgerbil/colorable.py
# class Colorable:
#
# START_CODE = "\033"
# END_CODE = f"{START_CODE}[0m"
#
# BRIGHT_OFFSET = 60
#
# COLORS = {
# "black": 30,
# "gray": 30,
# "grey": 30,
# "red": 31,
# "green": 32,
# "yellow": 33,
# "blue": 34,
# "magenta": 35,
# "purple": 35,
# "cyan": 36,
# "white": 37,
# }
#
# ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
#
# def __init__(self, color, value, fmt="", bright=False):
#
# if color not in self.COLORS:
# raise UnsupportedColorError(
# f"I don't know what to do with this color: {color}"
# )
#
# self.my_color = color
# self.value = value
# self.bright = bright
# self.format_string = fmt
#
# def __repr__(self):
# return (
# f"Colorable('{self.my_color}', '{self.value}', "
# f"fmt='{self.format_string}', bright={self.bright})"
# )
#
# def __str__(self):
# start = self.ansi_sequence(self.COLORS[self.my_color], bright=self.bright)
# ansi_str = f"{start}{self.value:{self.format_string}}{self.END_CODE}"
# return ansi_str
#
# def __len__(self):
# return len(self.value)
#
# def __eq__(self, other):
# return str(self) == str(other)
#
# def ansi_sequence(self, code, bright=False):
# offset = 60 if bright else 0
# color = code + offset
# return f"{self.START_CODE}[0;{color}m"
#
# def plain(self):
# return self.value
#
# @staticmethod
# def get_plain_string(ansi_string):
# return Colorable.ansi_escape.sub("", ansi_string)
#
# Path: ledgerbil/ledgerbilexceptions.py
# ERROR_RETURN_VALUE = 1
#
# class LdgReconcilerError(LdgException):
# pass
#
# Path: ledgerbil/settings_getter.py
# def get_setting(setting, default=None):
# if settings and hasattr(settings, setting):
# return getattr(settings, setting)
#
# return defaults.get(setting, default)
. Output only the next line. | message += f" {account}\n" |
Predict the next line for this snippet: <|code_start|>
# supported operators
operators = {
ast.Add: op.add,
ast.Sub: op.sub,
ast.Mult: op.mul,
ast.Div: op.truediv,
ast.Pow: op.pow,
<|code_end|>
with the help of current file imports:
import ast
import operator as op
import re
import shlex
import sys
from datetime import datetime
from functools import reduce
from .colorable import Colorable
from .ledgerbilexceptions import ERROR_RETURN_VALUE, LdgReconcilerError
from .settings_getter import get_setting
and context from other files:
# Path: ledgerbil/colorable.py
# class Colorable:
#
# START_CODE = "\033"
# END_CODE = f"{START_CODE}[0m"
#
# BRIGHT_OFFSET = 60
#
# COLORS = {
# "black": 30,
# "gray": 30,
# "grey": 30,
# "red": 31,
# "green": 32,
# "yellow": 33,
# "blue": 34,
# "magenta": 35,
# "purple": 35,
# "cyan": 36,
# "white": 37,
# }
#
# ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
#
# def __init__(self, color, value, fmt="", bright=False):
#
# if color not in self.COLORS:
# raise UnsupportedColorError(
# f"I don't know what to do with this color: {color}"
# )
#
# self.my_color = color
# self.value = value
# self.bright = bright
# self.format_string = fmt
#
# def __repr__(self):
# return (
# f"Colorable('{self.my_color}', '{self.value}', "
# f"fmt='{self.format_string}', bright={self.bright})"
# )
#
# def __str__(self):
# start = self.ansi_sequence(self.COLORS[self.my_color], bright=self.bright)
# ansi_str = f"{start}{self.value:{self.format_string}}{self.END_CODE}"
# return ansi_str
#
# def __len__(self):
# return len(self.value)
#
# def __eq__(self, other):
# return str(self) == str(other)
#
# def ansi_sequence(self, code, bright=False):
# offset = 60 if bright else 0
# color = code + offset
# return f"{self.START_CODE}[0;{color}m"
#
# def plain(self):
# return self.value
#
# @staticmethod
# def get_plain_string(ansi_string):
# return Colorable.ansi_escape.sub("", ansi_string)
#
# Path: ledgerbil/ledgerbilexceptions.py
# ERROR_RETURN_VALUE = 1
#
# class LdgReconcilerError(LdgException):
# pass
#
# Path: ledgerbil/settings_getter.py
# def get_setting(setting, default=None):
# if settings and hasattr(settings, setting):
# return getattr(settings, setting)
#
# return defaults.get(setting, default)
, which may contain function names, class names, or code. Output only the next line. | ast.BitXor: op.xor, |
Given snippet: <|code_start|> args, ledger_args = grid.get_args(["food", "--transpose"])
report = grid.get_grid_report(args, ledger_args)
helper = OutputFileTester("test_grid_end_to_end_flat_transposed")
helper.save_out_file(report)
helper.assert_out_equals_expected()
def test_get_grid_report_flat_report_expenses_monthly():
args, ledger_args = grid.get_args(["expenses", "--sort", "row", "--month"])
report = grid.get_grid_report(args, ledger_args)
helper = OutputFileTester("test_grid_end_to_end_flat_monthly_expenses")
helper.save_out_file(report)
helper.assert_out_equals_expected()
def test_get_grid_report_flat_report_single_column():
args, ledger_args = grid.get_args(["food", "--period", "2018"])
report = grid.get_grid_report(args, ledger_args)
expected = (
" 2018\n"
" $ 57.40 expenses: food: groceries\n"
" $ 42.17 expenses: food: dining out\n"
" ------------\n"
" $ 99.57\n"
)
assert Colorable.get_plain_string(report) == expected
def test_get_grid_report_flat_report_single_column_transposed():
args, ledger_args = grid.get_args(["food", "--period", "2018", "--transpose"])
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import subprocess
import pytest
from textwrap import dedent
from unittest import mock
from ... import settings, settings_getter
from ...colorable import Colorable
from ...tests import filetester as FT
from ...tests.helpers import OutputFileTester
from .. import grid
and context:
# Path: ledgerbil/colorable.py
# class Colorable:
#
# START_CODE = "\033"
# END_CODE = f"{START_CODE}[0m"
#
# BRIGHT_OFFSET = 60
#
# COLORS = {
# "black": 30,
# "gray": 30,
# "grey": 30,
# "red": 31,
# "green": 32,
# "yellow": 33,
# "blue": 34,
# "magenta": 35,
# "purple": 35,
# "cyan": 36,
# "white": 37,
# }
#
# ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
#
# def __init__(self, color, value, fmt="", bright=False):
#
# if color not in self.COLORS:
# raise UnsupportedColorError(
# f"I don't know what to do with this color: {color}"
# )
#
# self.my_color = color
# self.value = value
# self.bright = bright
# self.format_string = fmt
#
# def __repr__(self):
# return (
# f"Colorable('{self.my_color}', '{self.value}', "
# f"fmt='{self.format_string}', bright={self.bright})"
# )
#
# def __str__(self):
# start = self.ansi_sequence(self.COLORS[self.my_color], bright=self.bright)
# ansi_str = f"{start}{self.value:{self.format_string}}{self.END_CODE}"
# return ansi_str
#
# def __len__(self):
# return len(self.value)
#
# def __eq__(self, other):
# return str(self) == str(other)
#
# def ansi_sequence(self, code, bright=False):
# offset = 60 if bright else 0
# color = code + offset
# return f"{self.START_CODE}[0;{color}m"
#
# def plain(self):
# return self.value
#
# @staticmethod
# def get_plain_string(ansi_string):
# return Colorable.ansi_escape.sub("", ansi_string)
#
# Path: ledgerbil/tests/filetester.py
# CACHE_FILE_TEST = os.path.join(testdir, ".ledgerbil_cache_test")
# def read_file(filename):
# def temp_file(data):
# def delete_test_cache_file():
#
# Path: ledgerbil/tests/helpers.py
# class OutputFileTester(OutputFileTesterBase):
# def __init__(self, testfile):
# super().__init__()
# self.testfile = testfile
#
# def save_out_file(self, data):
# with open(self.get_out_filename(self.testfile), "w", encoding="utf-8") as afile:
# afile.write(self.remove_color(data))
#
# def assert_out_equals_expected(self):
# assert filecmp.cmp(
# self.get_out_filename(self.testfile),
# self.get_expected_filename(self.testfile),
# ), f"test filename out: {self.get_out_filename(self.testfile)}"
which might include code, classes, or functions. Output only the next line. | report = grid.get_grid_report(args, ledger_args) |
Predict the next line after this snippet: <|code_start|>@mock.patch(__name__ + ".LEDGER", "fubar")
def test_ledger_not_found():
assert ledger_not_found()
def test_get_grid_report_flat_report_expenses():
args, ledger_args = grid.get_args(["expenses", "--sort", "row"])
report = grid.get_grid_report(args, ledger_args)
helper = OutputFileTester("test_grid_end_to_end_flat_expenses")
helper.save_out_file(report)
helper.assert_out_equals_expected()
def test_get_grid_report_flat_report_transposed():
args, ledger_args = grid.get_args(["food", "--transpose"])
report = grid.get_grid_report(args, ledger_args)
helper = OutputFileTester("test_grid_end_to_end_flat_transposed")
helper.save_out_file(report)
helper.assert_out_equals_expected()
def test_get_grid_report_flat_report_expenses_monthly():
args, ledger_args = grid.get_args(["expenses", "--sort", "row", "--month"])
report = grid.get_grid_report(args, ledger_args)
helper = OutputFileTester("test_grid_end_to_end_flat_monthly_expenses")
helper.save_out_file(report)
helper.assert_out_equals_expected()
def test_get_grid_report_flat_report_single_column():
<|code_end|>
using the current file's imports:
import subprocess
import pytest
from textwrap import dedent
from unittest import mock
from ... import settings, settings_getter
from ...colorable import Colorable
from ...tests import filetester as FT
from ...tests.helpers import OutputFileTester
from .. import grid
and any relevant context from other files:
# Path: ledgerbil/colorable.py
# class Colorable:
#
# START_CODE = "\033"
# END_CODE = f"{START_CODE}[0m"
#
# BRIGHT_OFFSET = 60
#
# COLORS = {
# "black": 30,
# "gray": 30,
# "grey": 30,
# "red": 31,
# "green": 32,
# "yellow": 33,
# "blue": 34,
# "magenta": 35,
# "purple": 35,
# "cyan": 36,
# "white": 37,
# }
#
# ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
#
# def __init__(self, color, value, fmt="", bright=False):
#
# if color not in self.COLORS:
# raise UnsupportedColorError(
# f"I don't know what to do with this color: {color}"
# )
#
# self.my_color = color
# self.value = value
# self.bright = bright
# self.format_string = fmt
#
# def __repr__(self):
# return (
# f"Colorable('{self.my_color}', '{self.value}', "
# f"fmt='{self.format_string}', bright={self.bright})"
# )
#
# def __str__(self):
# start = self.ansi_sequence(self.COLORS[self.my_color], bright=self.bright)
# ansi_str = f"{start}{self.value:{self.format_string}}{self.END_CODE}"
# return ansi_str
#
# def __len__(self):
# return len(self.value)
#
# def __eq__(self, other):
# return str(self) == str(other)
#
# def ansi_sequence(self, code, bright=False):
# offset = 60 if bright else 0
# color = code + offset
# return f"{self.START_CODE}[0;{color}m"
#
# def plain(self):
# return self.value
#
# @staticmethod
# def get_plain_string(ansi_string):
# return Colorable.ansi_escape.sub("", ansi_string)
#
# Path: ledgerbil/tests/filetester.py
# CACHE_FILE_TEST = os.path.join(testdir, ".ledgerbil_cache_test")
# def read_file(filename):
# def temp_file(data):
# def delete_test_cache_file():
#
# Path: ledgerbil/tests/helpers.py
# class OutputFileTester(OutputFileTesterBase):
# def __init__(self, testfile):
# super().__init__()
# self.testfile = testfile
#
# def save_out_file(self, data):
# with open(self.get_out_filename(self.testfile), "w", encoding="utf-8") as afile:
# afile.write(self.remove_color(data))
#
# def assert_out_equals_expected(self):
# assert filecmp.cmp(
# self.get_out_filename(self.testfile),
# self.get_expected_filename(self.testfile),
# ), f"test filename out: {self.get_out_filename(self.testfile)}"
. Output only the next line. | args, ledger_args = grid.get_args(["food", "--period", "2018"]) |
Given the code snippet: <|code_start|> )
assert Colorable.get_plain_string(report) == expected
def test_get_grid_report_flat_report_single_row():
args, ledger_args = grid.get_args(["groceries"])
report = grid.get_grid_report(args, ledger_args)
expected = (
" 2017 2018 Total\n"
" $ 34.63 $ 57.40 $ 92.03 expenses: food: groceries\n"
)
assert Colorable.get_plain_string(report) == expected
def test_get_grid_report_flat_report_single_row_transposed():
args, ledger_args = grid.get_args(["groceries", "--transpose"])
report = grid.get_grid_report(args, ledger_args)
expected = (
" expenses:\n"
" food:\n"
" groceries\n"
" $ 34.63 2017\n"
" $ 57.40 2018\n"
" ------------\n"
" $ 92.03\n"
)
assert Colorable.get_plain_string(report) == expected
def test_get_grid_report_flat_report_single_row_and_column():
<|code_end|>
, generate the next line using the imports in this file:
import subprocess
import pytest
from textwrap import dedent
from unittest import mock
from ... import settings, settings_getter
from ...colorable import Colorable
from ...tests import filetester as FT
from ...tests.helpers import OutputFileTester
from .. import grid
and context (functions, classes, or occasionally code) from other files:
# Path: ledgerbil/colorable.py
# class Colorable:
#
# START_CODE = "\033"
# END_CODE = f"{START_CODE}[0m"
#
# BRIGHT_OFFSET = 60
#
# COLORS = {
# "black": 30,
# "gray": 30,
# "grey": 30,
# "red": 31,
# "green": 32,
# "yellow": 33,
# "blue": 34,
# "magenta": 35,
# "purple": 35,
# "cyan": 36,
# "white": 37,
# }
#
# ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
#
# def __init__(self, color, value, fmt="", bright=False):
#
# if color not in self.COLORS:
# raise UnsupportedColorError(
# f"I don't know what to do with this color: {color}"
# )
#
# self.my_color = color
# self.value = value
# self.bright = bright
# self.format_string = fmt
#
# def __repr__(self):
# return (
# f"Colorable('{self.my_color}', '{self.value}', "
# f"fmt='{self.format_string}', bright={self.bright})"
# )
#
# def __str__(self):
# start = self.ansi_sequence(self.COLORS[self.my_color], bright=self.bright)
# ansi_str = f"{start}{self.value:{self.format_string}}{self.END_CODE}"
# return ansi_str
#
# def __len__(self):
# return len(self.value)
#
# def __eq__(self, other):
# return str(self) == str(other)
#
# def ansi_sequence(self, code, bright=False):
# offset = 60 if bright else 0
# color = code + offset
# return f"{self.START_CODE}[0;{color}m"
#
# def plain(self):
# return self.value
#
# @staticmethod
# def get_plain_string(ansi_string):
# return Colorable.ansi_escape.sub("", ansi_string)
#
# Path: ledgerbil/tests/filetester.py
# CACHE_FILE_TEST = os.path.join(testdir, ".ledgerbil_cache_test")
# def read_file(filename):
# def temp_file(data):
# def delete_test_cache_file():
#
# Path: ledgerbil/tests/helpers.py
# class OutputFileTester(OutputFileTesterBase):
# def __init__(self, testfile):
# super().__init__()
# self.testfile = testfile
#
# def save_out_file(self, data):
# with open(self.get_out_filename(self.testfile), "w", encoding="utf-8") as afile:
# afile.write(self.remove_color(data))
#
# def assert_out_equals_expected(self):
# assert filecmp.cmp(
# self.get_out_filename(self.testfile),
# self.get_expected_filename(self.testfile),
# ), f"test filename out: {self.get_out_filename(self.testfile)}"
. Output only the next line. | args, ledger_args = grid.get_args(["groceries", "--period", "2018"]) |
Predict the next line after this snippet: <|code_start|> history += f" {contrib_total_f} {transfers_total_f}\n"
return history
def get_comparison_report_column_headers(num_years, labels=True):
header3 = "" if num_years < 3 else f"{'3yr %':>{COL_GAIN}}"
header5 = "" if num_years < 5 else f"{'5yr %':>{COL_GAIN}}"
header10 = "" if num_years < 10 else f"{'10yr %':>{COL_GAIN}}"
if labels:
col1 = f"{'labels':{COL_LABEL}}"
else:
col1 = f"{'accounts':{COL_ACCOUNT}}"
return str(
Colorable(
"cyan",
(
f"{col1} {'value':>{COL_VALUE}} % {'gain val':>{COL_GAIN_VALUE}}"
f" yr {'all %':>{COL_GAIN}} {'1yr %':>{COL_GAIN}} {header3} "
f"{header5} {header10}"
),
)
)
def get_sorted_comparison_items(comparison_items, sort):
sort_options = {
"v": "value",
<|code_end|>
using the current file's imports:
import argparse
import itertools
import json
import re
from collections import defaultdict, namedtuple
from operator import attrgetter
from textwrap import dedent
from . import util
from .colorable import Colorable
from .ledgerbilexceptions import LdgPortfolioError
from .settings_getter import get_setting
and any relevant context from other files:
# Path: ledgerbil/colorable.py
# class Colorable:
#
# START_CODE = "\033"
# END_CODE = f"{START_CODE}[0m"
#
# BRIGHT_OFFSET = 60
#
# COLORS = {
# "black": 30,
# "gray": 30,
# "grey": 30,
# "red": 31,
# "green": 32,
# "yellow": 33,
# "blue": 34,
# "magenta": 35,
# "purple": 35,
# "cyan": 36,
# "white": 37,
# }
#
# ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
#
# def __init__(self, color, value, fmt="", bright=False):
#
# if color not in self.COLORS:
# raise UnsupportedColorError(
# f"I don't know what to do with this color: {color}"
# )
#
# self.my_color = color
# self.value = value
# self.bright = bright
# self.format_string = fmt
#
# def __repr__(self):
# return (
# f"Colorable('{self.my_color}', '{self.value}', "
# f"fmt='{self.format_string}', bright={self.bright})"
# )
#
# def __str__(self):
# start = self.ansi_sequence(self.COLORS[self.my_color], bright=self.bright)
# ansi_str = f"{start}{self.value:{self.format_string}}{self.END_CODE}"
# return ansi_str
#
# def __len__(self):
# return len(self.value)
#
# def __eq__(self, other):
# return str(self) == str(other)
#
# def ansi_sequence(self, code, bright=False):
# offset = 60 if bright else 0
# color = code + offset
# return f"{self.START_CODE}[0;{color}m"
#
# def plain(self):
# return self.value
#
# @staticmethod
# def get_plain_string(ansi_string):
# return Colorable.ansi_escape.sub("", ansi_string)
#
# Path: ledgerbil/ledgerbilexceptions.py
# class LdgPortfolioError(LdgException):
# pass
#
# Path: ledgerbil/settings_getter.py
# def get_setting(setting, default=None):
# if settings and hasattr(settings, setting):
# return getattr(settings, setting)
#
# return defaults.get(setting, default)
. Output only the next line. | "g": "gain_value", |
Here is a snippet: <|code_start|> transfers_total += year.transfers
gain_val_total += year.gain_value
if len(years) > 1:
contrib_total_f = util.get_colored_amount(
contrib_total, colwidth=COL_CONTRIB, decimals=0
)
transfers_total_f = util.get_colored_amount(
transfers_total, colwidth=COL_TRANSFERS, decimals=0
)
gain_val_total_f = util.get_colored_amount(
gain_val_total, colwidth=COL_GAIN_VALUE, decimals=0
)
report += (
f" {contrib_total_f} {transfers_total_f} "
f'{"":{COL_VALUE + COL_GAIN + 2}} {gain_val_total_f}'
)
return report
def get_yearly_combined_accounts(accounts, included_years):
# Combine all the accounts into total contributions and value per year
year_start, year_end = util.get_start_and_end_range(included_years)
totals = defaultdict(lambda: defaultdict(float))
for account in accounts:
previous_value = 0
for year in range(year_start, year_end):
if str(year) not in account["years"].keys():
# todo: integration with ledger to get current info
<|code_end|>
. Write the next line using the current file imports:
import argparse
import itertools
import json
import re
from collections import defaultdict, namedtuple
from operator import attrgetter
from textwrap import dedent
from . import util
from .colorable import Colorable
from .ledgerbilexceptions import LdgPortfolioError
from .settings_getter import get_setting
and context from other files:
# Path: ledgerbil/colorable.py
# class Colorable:
#
# START_CODE = "\033"
# END_CODE = f"{START_CODE}[0m"
#
# BRIGHT_OFFSET = 60
#
# COLORS = {
# "black": 30,
# "gray": 30,
# "grey": 30,
# "red": 31,
# "green": 32,
# "yellow": 33,
# "blue": 34,
# "magenta": 35,
# "purple": 35,
# "cyan": 36,
# "white": 37,
# }
#
# ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
#
# def __init__(self, color, value, fmt="", bright=False):
#
# if color not in self.COLORS:
# raise UnsupportedColorError(
# f"I don't know what to do with this color: {color}"
# )
#
# self.my_color = color
# self.value = value
# self.bright = bright
# self.format_string = fmt
#
# def __repr__(self):
# return (
# f"Colorable('{self.my_color}', '{self.value}', "
# f"fmt='{self.format_string}', bright={self.bright})"
# )
#
# def __str__(self):
# start = self.ansi_sequence(self.COLORS[self.my_color], bright=self.bright)
# ansi_str = f"{start}{self.value:{self.format_string}}{self.END_CODE}"
# return ansi_str
#
# def __len__(self):
# return len(self.value)
#
# def __eq__(self, other):
# return str(self) == str(other)
#
# def ansi_sequence(self, code, bright=False):
# offset = 60 if bright else 0
# color = code + offset
# return f"{self.START_CODE}[0;{color}m"
#
# def plain(self):
# return self.value
#
# @staticmethod
# def get_plain_string(ansi_string):
# return Colorable.ansi_escape.sub("", ansi_string)
#
# Path: ledgerbil/ledgerbilexceptions.py
# class LdgPortfolioError(LdgException):
# pass
#
# Path: ledgerbil/settings_getter.py
# def get_setting(setting, default=None):
# if settings and hasattr(settings, setting):
# return getattr(settings, setting)
#
# return defaults.get(setting, default)
, which may include functions, classes, or code. Output only the next line. | totals[year]["contributions"] += 0 |
Continue the code snippet: <|code_start|>
history += (
f" {year} {contrib_f} {transfers_f} {shares_f} "
f"{price_f} {value_f} {gain_f}\n"
)
previous_shares = shares
previous_price = price
previous_value = value
contrib_total += contrib
transfers_total += transfers
if len(years) > 1:
contrib_total_f = util.get_colored_amount(contrib_total, 10, 0)
transfers_total_f = util.get_colored_amount(transfers_total, 10, 0)
history += f" {contrib_total_f} {transfers_total_f}\n"
return history
def get_comparison_report_column_headers(num_years, labels=True):
header3 = "" if num_years < 3 else f"{'3yr %':>{COL_GAIN}}"
header5 = "" if num_years < 5 else f"{'5yr %':>{COL_GAIN}}"
header10 = "" if num_years < 10 else f"{'10yr %':>{COL_GAIN}}"
if labels:
col1 = f"{'labels':{COL_LABEL}}"
else:
col1 = f"{'accounts':{COL_ACCOUNT}}"
<|code_end|>
. Use current file imports:
import argparse
import itertools
import json
import re
from collections import defaultdict, namedtuple
from operator import attrgetter
from textwrap import dedent
from . import util
from .colorable import Colorable
from .ledgerbilexceptions import LdgPortfolioError
from .settings_getter import get_setting
and context (classes, functions, or code) from other files:
# Path: ledgerbil/colorable.py
# class Colorable:
#
# START_CODE = "\033"
# END_CODE = f"{START_CODE}[0m"
#
# BRIGHT_OFFSET = 60
#
# COLORS = {
# "black": 30,
# "gray": 30,
# "grey": 30,
# "red": 31,
# "green": 32,
# "yellow": 33,
# "blue": 34,
# "magenta": 35,
# "purple": 35,
# "cyan": 36,
# "white": 37,
# }
#
# ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
#
# def __init__(self, color, value, fmt="", bright=False):
#
# if color not in self.COLORS:
# raise UnsupportedColorError(
# f"I don't know what to do with this color: {color}"
# )
#
# self.my_color = color
# self.value = value
# self.bright = bright
# self.format_string = fmt
#
# def __repr__(self):
# return (
# f"Colorable('{self.my_color}', '{self.value}', "
# f"fmt='{self.format_string}', bright={self.bright})"
# )
#
# def __str__(self):
# start = self.ansi_sequence(self.COLORS[self.my_color], bright=self.bright)
# ansi_str = f"{start}{self.value:{self.format_string}}{self.END_CODE}"
# return ansi_str
#
# def __len__(self):
# return len(self.value)
#
# def __eq__(self, other):
# return str(self) == str(other)
#
# def ansi_sequence(self, code, bright=False):
# offset = 60 if bright else 0
# color = code + offset
# return f"{self.START_CODE}[0;{color}m"
#
# def plain(self):
# return self.value
#
# @staticmethod
# def get_plain_string(ansi_string):
# return Colorable.ansi_escape.sub("", ansi_string)
#
# Path: ledgerbil/ledgerbilexceptions.py
# class LdgPortfolioError(LdgException):
# pass
#
# Path: ledgerbil/settings_getter.py
# def get_setting(setting, default=None):
# if settings and hasattr(settings, setting):
# return getattr(settings, setting)
#
# return defaults.get(setting, default)
. Output only the next line. | return str( |
Given snippet: <|code_start|>
def get_ledger_command(args=None):
files = []
for f in get_setting("LEDGER_FILES"):
files += ["-f", os.path.join(get_setting("LEDGER_DIR"), f)]
return get_setting("LEDGER_COMMAND") + tuple(files) + (args or ())
def get_ledger_output(args=None):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import subprocess
from ..settings_getter import get_setting
and context:
# Path: ledgerbil/settings_getter.py
# def get_setting(setting, default=None):
# if settings and hasattr(settings, setting):
# return getattr(settings, setting)
#
# return defaults.get(setting, default)
which might include code, classes, or functions. Output only the next line. | cmd = get_ledger_command(args) |
Predict the next line for this snippet: <|code_start|> else:
match = DOLLARS_REGEX.match(line)
if match:
amount, account = match.groups()
symbol = "$"
if not match:
return None
return AccountBalance(
account.strip() if strip_account else account, get_float(amount), symbol
)
def get_account_balance_generic(line):
balance = get_account_balance(line, shares=False)
if not balance:
return get_account_balance(line, shares=True)
return balance
def get_payee_subtotal(line):
DOLLARS = 0
match = PAYEE_SUBTOTAL_REGEX.match(line)
if match:
return get_float(match.groups()[DOLLARS])
return None
def get_first_dollar_amount_float(line):
<|code_end|>
with the help of current file imports:
import re
from collections import namedtuple
from ..util import get_float
and context from other files:
# Path: ledgerbil/util.py
# def get_float(value):
# return float(re.sub(r"[ $,]", "", value))
, which may contain function names, class names, or code. Output only the next line. | DOLLARS = 0 |
Given the code snippet: <|code_start|>
# (ledgerthing noqa'ed: is used in patch but reported as unused)
def test_repr():
lines = ["2018/01/08 blah", " e: xyz", " l: abc $-10"]
thing = LedgerThing(lines)
assert repr(thing) == f"LedgerThing({lines}, reconcile_account=None)"
assert isinstance(eval(repr(thing)), LedgerThing)
<|code_end|>
, generate the next line using the imports in this file:
from datetime import date
from unittest import TestCase
from .. import ledgerthing, settings, settings_getter # noqa: F401
from ..ledgerbilexceptions import LdgReconcilerError
from ..ledgerthing import (
REC_CLEARED,
REC_PENDING,
REC_UNCLEARED,
UNSPECIFIED_PAYEE,
LedgerPosting,
LedgerThing,
get_ledger_posting,
)
from .helpers import Redirector
import pytest
and context (functions, classes, or occasionally code) from other files:
# Path: ledgerbil/ledgerbilexceptions.py
# class LdgReconcilerError(LdgException):
# pass
#
# Path: ledgerbil/ledgerthing.py
# UNSPECIFIED_PAYEE = "<Unspecified payee>"
# DATE_REGEX = r"^\d{4}(?:[-/]\d\d){2}(?=\s|$)"
# TOP_LINE_REGEX = re.compile(
# r"(" + DATE_REGEX + r")(?:\s+|$)" # date with required whitespace (or $)
# r"\s*([!*])?\s*" # optional transaction state (c/p)
# r"(?:\(([^)]*)\)\s*)?" # optional transaction # and whitespace
# r"(.*?)(?= |$)" # opt. payee ends with two spaces (or $)
# )
# POSTING_REGEX = re.compile(
# r"""(?x) # verbose mode
# ^\s+ # opening indent
# ([!*])? # optional pending/cleared
# (?:\s*)? # optional whitespace after p/c
# ([^;]+?)(?<=\S)(?=\ \ |$) # account - 2 spaces ends acct
# (?:\s* # optional share info, leading whitespace
# (-?\s*[.,0-9]+) # num shares
# (?:\s*([^@; ]+)) # symbol
# (?:\s*@\s*)? # optional @
# )? # close of optional share stuff
# \(?([-+*/()$\d.,\s]+)?\)? # optional amount expression
# (?:\s*=\s*[^;]+\s*)? # optional balance assertion
# (?:;.*$|$) # optional end comment
# """
# )
# REC_PENDING = "!"
# REC_CLEARED = "*"
# REC_UNCLEARED = ""
# def get_ledger_posting(line):
# def __init__(self, lines, reconcile_account=None):
# def __repr__(self):
# def __str__(self):
# def parse_top_line(self, line):
# def parse_transaction_lines(self, lines):
# def get_lines(self):
# def is_new_thing(line):
# def is_transaction_start(line):
# def assert_only_one_status(self, statuses):
# def assert_only_one_symbol(self, symbols):
# def assert_only_shares_if_shares(self, shareses):
# def assert_not_top_line_status(self):
# def get_date_and_payee(self):
# def get_date_string(self):
# def is_pending(self):
# def set_pending(self):
# def is_cleared(self):
# def set_cleared(self):
# def set_uncleared(self):
# class LedgerThing:
#
# Path: ledgerbil/tests/helpers.py
# class Redirector(TestCase):
# def setUp(self):
# self.savestdout = sys.stdout
# self.reset_redirect()
#
# self.savestderr = sys.stderr
# self.reset_err_redirect()
#
# def tearDown(self):
# self.redirect.close()
# sys.stdout = self.savestdout
#
# self.redirecterr.close()
# sys.stderr = self.savestderr
#
# def reset_redirect(self):
# self.redirect = StringIO()
# sys.stdout = self.redirect
#
# def reset_err_redirect(self):
# self.redirecterr = StringIO()
# sys.stderr = self.redirecterr
. Output only the next line. | def test_str(): |
Next line prediction: <|code_start|>
# (ledgerthing noqa'ed: is used in patch but reported as unused)
def test_repr():
lines = ["2018/01/08 blah", " e: xyz", " l: abc $-10"]
thing = LedgerThing(lines)
assert repr(thing) == f"LedgerThing({lines}, reconcile_account=None)"
assert isinstance(eval(repr(thing)), LedgerThing)
<|code_end|>
. Use current file imports:
(from datetime import date
from unittest import TestCase
from .. import ledgerthing, settings, settings_getter # noqa: F401
from ..ledgerbilexceptions import LdgReconcilerError
from ..ledgerthing import (
REC_CLEARED,
REC_PENDING,
REC_UNCLEARED,
UNSPECIFIED_PAYEE,
LedgerPosting,
LedgerThing,
get_ledger_posting,
)
from .helpers import Redirector
import pytest)
and context including class names, function names, or small code snippets from other files:
# Path: ledgerbil/ledgerbilexceptions.py
# class LdgReconcilerError(LdgException):
# pass
#
# Path: ledgerbil/ledgerthing.py
# UNSPECIFIED_PAYEE = "<Unspecified payee>"
# DATE_REGEX = r"^\d{4}(?:[-/]\d\d){2}(?=\s|$)"
# TOP_LINE_REGEX = re.compile(
# r"(" + DATE_REGEX + r")(?:\s+|$)" # date with required whitespace (or $)
# r"\s*([!*])?\s*" # optional transaction state (c/p)
# r"(?:\(([^)]*)\)\s*)?" # optional transaction # and whitespace
# r"(.*?)(?= |$)" # opt. payee ends with two spaces (or $)
# )
# POSTING_REGEX = re.compile(
# r"""(?x) # verbose mode
# ^\s+ # opening indent
# ([!*])? # optional pending/cleared
# (?:\s*)? # optional whitespace after p/c
# ([^;]+?)(?<=\S)(?=\ \ |$) # account - 2 spaces ends acct
# (?:\s* # optional share info, leading whitespace
# (-?\s*[.,0-9]+) # num shares
# (?:\s*([^@; ]+)) # symbol
# (?:\s*@\s*)? # optional @
# )? # close of optional share stuff
# \(?([-+*/()$\d.,\s]+)?\)? # optional amount expression
# (?:\s*=\s*[^;]+\s*)? # optional balance assertion
# (?:;.*$|$) # optional end comment
# """
# )
# REC_PENDING = "!"
# REC_CLEARED = "*"
# REC_UNCLEARED = ""
# def get_ledger_posting(line):
# def __init__(self, lines, reconcile_account=None):
# def __repr__(self):
# def __str__(self):
# def parse_top_line(self, line):
# def parse_transaction_lines(self, lines):
# def get_lines(self):
# def is_new_thing(line):
# def is_transaction_start(line):
# def assert_only_one_status(self, statuses):
# def assert_only_one_symbol(self, symbols):
# def assert_only_shares_if_shares(self, shareses):
# def assert_not_top_line_status(self):
# def get_date_and_payee(self):
# def get_date_string(self):
# def is_pending(self):
# def set_pending(self):
# def is_cleared(self):
# def set_cleared(self):
# def set_uncleared(self):
# class LedgerThing:
#
# Path: ledgerbil/tests/helpers.py
# class Redirector(TestCase):
# def setUp(self):
# self.savestdout = sys.stdout
# self.reset_redirect()
#
# self.savestderr = sys.stderr
# self.reset_err_redirect()
#
# def tearDown(self):
# self.redirect.close()
# sys.stdout = self.savestdout
#
# self.redirecterr.close()
# sys.stderr = self.savestderr
#
# def reset_redirect(self):
# self.redirect = StringIO()
# sys.stdout = self.redirect
#
# def reset_err_redirect(self):
# self.redirecterr = StringIO()
# sys.stderr = self.redirecterr
. Output only the next line. | def test_str(): |
Based on the snippet: <|code_start|>
# (ledgerthing noqa'ed: is used in patch but reported as unused)
def test_repr():
lines = ["2018/01/08 blah", " e: xyz", " l: abc $-10"]
thing = LedgerThing(lines)
assert repr(thing) == f"LedgerThing({lines}, reconcile_account=None)"
assert isinstance(eval(repr(thing)), LedgerThing)
def test_str():
lines = ["2018/01/08 blah", " e: xyz", " l: abc $-10"]
thing = LedgerThing(lines)
assert str(thing) == "\n".join(lines)
<|code_end|>
, predict the immediate next line with the help of imports:
from datetime import date
from unittest import TestCase
from .. import ledgerthing, settings, settings_getter # noqa: F401
from ..ledgerbilexceptions import LdgReconcilerError
from ..ledgerthing import (
REC_CLEARED,
REC_PENDING,
REC_UNCLEARED,
UNSPECIFIED_PAYEE,
LedgerPosting,
LedgerThing,
get_ledger_posting,
)
from .helpers import Redirector
import pytest
and context (classes, functions, sometimes code) from other files:
# Path: ledgerbil/ledgerbilexceptions.py
# class LdgReconcilerError(LdgException):
# pass
#
# Path: ledgerbil/ledgerthing.py
# UNSPECIFIED_PAYEE = "<Unspecified payee>"
# DATE_REGEX = r"^\d{4}(?:[-/]\d\d){2}(?=\s|$)"
# TOP_LINE_REGEX = re.compile(
# r"(" + DATE_REGEX + r")(?:\s+|$)" # date with required whitespace (or $)
# r"\s*([!*])?\s*" # optional transaction state (c/p)
# r"(?:\(([^)]*)\)\s*)?" # optional transaction # and whitespace
# r"(.*?)(?= |$)" # opt. payee ends with two spaces (or $)
# )
# POSTING_REGEX = re.compile(
# r"""(?x) # verbose mode
# ^\s+ # opening indent
# ([!*])? # optional pending/cleared
# (?:\s*)? # optional whitespace after p/c
# ([^;]+?)(?<=\S)(?=\ \ |$) # account - 2 spaces ends acct
# (?:\s* # optional share info, leading whitespace
# (-?\s*[.,0-9]+) # num shares
# (?:\s*([^@; ]+)) # symbol
# (?:\s*@\s*)? # optional @
# )? # close of optional share stuff
# \(?([-+*/()$\d.,\s]+)?\)? # optional amount expression
# (?:\s*=\s*[^;]+\s*)? # optional balance assertion
# (?:;.*$|$) # optional end comment
# """
# )
# REC_PENDING = "!"
# REC_CLEARED = "*"
# REC_UNCLEARED = ""
# def get_ledger_posting(line):
# def __init__(self, lines, reconcile_account=None):
# def __repr__(self):
# def __str__(self):
# def parse_top_line(self, line):
# def parse_transaction_lines(self, lines):
# def get_lines(self):
# def is_new_thing(line):
# def is_transaction_start(line):
# def assert_only_one_status(self, statuses):
# def assert_only_one_symbol(self, symbols):
# def assert_only_shares_if_shares(self, shareses):
# def assert_not_top_line_status(self):
# def get_date_and_payee(self):
# def get_date_string(self):
# def is_pending(self):
# def set_pending(self):
# def is_cleared(self):
# def set_cleared(self):
# def set_uncleared(self):
# class LedgerThing:
#
# Path: ledgerbil/tests/helpers.py
# class Redirector(TestCase):
# def setUp(self):
# self.savestdout = sys.stdout
# self.reset_redirect()
#
# self.savestderr = sys.stderr
# self.reset_err_redirect()
#
# def tearDown(self):
# self.redirect.close()
# sys.stdout = self.savestdout
#
# self.redirecterr.close()
# sys.stderr = self.savestderr
#
# def reset_redirect(self):
# self.redirect = StringIO()
# sys.stdout = self.redirect
#
# def reset_err_redirect(self):
# self.redirecterr = StringIO()
# sys.stderr = self.redirecterr
. Output only the next line. | def test_non_transaction_date(): |
Given the following code snippet before the placeholder: <|code_start|>
# (ledgerthing noqa'ed: is used in patch but reported as unused)
def test_repr():
lines = ["2018/01/08 blah", " e: xyz", " l: abc $-10"]
thing = LedgerThing(lines)
assert repr(thing) == f"LedgerThing({lines}, reconcile_account=None)"
assert isinstance(eval(repr(thing)), LedgerThing)
<|code_end|>
, predict the next line using imports from the current file:
from datetime import date
from unittest import TestCase
from .. import ledgerthing, settings, settings_getter # noqa: F401
from ..ledgerbilexceptions import LdgReconcilerError
from ..ledgerthing import (
REC_CLEARED,
REC_PENDING,
REC_UNCLEARED,
UNSPECIFIED_PAYEE,
LedgerPosting,
LedgerThing,
get_ledger_posting,
)
from .helpers import Redirector
import pytest
and context including class names, function names, and sometimes code from other files:
# Path: ledgerbil/ledgerbilexceptions.py
# class LdgReconcilerError(LdgException):
# pass
#
# Path: ledgerbil/ledgerthing.py
# UNSPECIFIED_PAYEE = "<Unspecified payee>"
# DATE_REGEX = r"^\d{4}(?:[-/]\d\d){2}(?=\s|$)"
# TOP_LINE_REGEX = re.compile(
# r"(" + DATE_REGEX + r")(?:\s+|$)" # date with required whitespace (or $)
# r"\s*([!*])?\s*" # optional transaction state (c/p)
# r"(?:\(([^)]*)\)\s*)?" # optional transaction # and whitespace
# r"(.*?)(?= |$)" # opt. payee ends with two spaces (or $)
# )
# POSTING_REGEX = re.compile(
# r"""(?x) # verbose mode
# ^\s+ # opening indent
# ([!*])? # optional pending/cleared
# (?:\s*)? # optional whitespace after p/c
# ([^;]+?)(?<=\S)(?=\ \ |$) # account - 2 spaces ends acct
# (?:\s* # optional share info, leading whitespace
# (-?\s*[.,0-9]+) # num shares
# (?:\s*([^@; ]+)) # symbol
# (?:\s*@\s*)? # optional @
# )? # close of optional share stuff
# \(?([-+*/()$\d.,\s]+)?\)? # optional amount expression
# (?:\s*=\s*[^;]+\s*)? # optional balance assertion
# (?:;.*$|$) # optional end comment
# """
# )
# REC_PENDING = "!"
# REC_CLEARED = "*"
# REC_UNCLEARED = ""
# def get_ledger_posting(line):
# def __init__(self, lines, reconcile_account=None):
# def __repr__(self):
# def __str__(self):
# def parse_top_line(self, line):
# def parse_transaction_lines(self, lines):
# def get_lines(self):
# def is_new_thing(line):
# def is_transaction_start(line):
# def assert_only_one_status(self, statuses):
# def assert_only_one_symbol(self, symbols):
# def assert_only_shares_if_shares(self, shareses):
# def assert_not_top_line_status(self):
# def get_date_and_payee(self):
# def get_date_string(self):
# def is_pending(self):
# def set_pending(self):
# def is_cleared(self):
# def set_cleared(self):
# def set_uncleared(self):
# class LedgerThing:
#
# Path: ledgerbil/tests/helpers.py
# class Redirector(TestCase):
# def setUp(self):
# self.savestdout = sys.stdout
# self.reset_redirect()
#
# self.savestderr = sys.stderr
# self.reset_err_redirect()
#
# def tearDown(self):
# self.redirect.close()
# sys.stdout = self.savestdout
#
# self.redirecterr.close()
# sys.stderr = self.savestderr
#
# def reset_redirect(self):
# self.redirect = StringIO()
# sys.stdout = self.redirect
#
# def reset_err_redirect(self):
# self.redirecterr = StringIO()
# sys.stderr = self.redirecterr
. Output only the next line. | def test_str(): |
Here is a snippet: <|code_start|>
# (ledgerthing noqa'ed: is used in patch but reported as unused)
def test_repr():
lines = ["2018/01/08 blah", " e: xyz", " l: abc $-10"]
thing = LedgerThing(lines)
assert repr(thing) == f"LedgerThing({lines}, reconcile_account=None)"
assert isinstance(eval(repr(thing)), LedgerThing)
def test_str():
lines = ["2018/01/08 blah", " e: xyz", " l: abc $-10"]
thing = LedgerThing(lines)
assert str(thing) == "\n".join(lines)
<|code_end|>
. Write the next line using the current file imports:
from datetime import date
from unittest import TestCase
from .. import ledgerthing, settings, settings_getter # noqa: F401
from ..ledgerbilexceptions import LdgReconcilerError
from ..ledgerthing import (
REC_CLEARED,
REC_PENDING,
REC_UNCLEARED,
UNSPECIFIED_PAYEE,
LedgerPosting,
LedgerThing,
get_ledger_posting,
)
from .helpers import Redirector
import pytest
and context from other files:
# Path: ledgerbil/ledgerbilexceptions.py
# class LdgReconcilerError(LdgException):
# pass
#
# Path: ledgerbil/ledgerthing.py
# UNSPECIFIED_PAYEE = "<Unspecified payee>"
# DATE_REGEX = r"^\d{4}(?:[-/]\d\d){2}(?=\s|$)"
# TOP_LINE_REGEX = re.compile(
# r"(" + DATE_REGEX + r")(?:\s+|$)" # date with required whitespace (or $)
# r"\s*([!*])?\s*" # optional transaction state (c/p)
# r"(?:\(([^)]*)\)\s*)?" # optional transaction # and whitespace
# r"(.*?)(?= |$)" # opt. payee ends with two spaces (or $)
# )
# POSTING_REGEX = re.compile(
# r"""(?x) # verbose mode
# ^\s+ # opening indent
# ([!*])? # optional pending/cleared
# (?:\s*)? # optional whitespace after p/c
# ([^;]+?)(?<=\S)(?=\ \ |$) # account - 2 spaces ends acct
# (?:\s* # optional share info, leading whitespace
# (-?\s*[.,0-9]+) # num shares
# (?:\s*([^@; ]+)) # symbol
# (?:\s*@\s*)? # optional @
# )? # close of optional share stuff
# \(?([-+*/()$\d.,\s]+)?\)? # optional amount expression
# (?:\s*=\s*[^;]+\s*)? # optional balance assertion
# (?:;.*$|$) # optional end comment
# """
# )
# REC_PENDING = "!"
# REC_CLEARED = "*"
# REC_UNCLEARED = ""
# def get_ledger_posting(line):
# def __init__(self, lines, reconcile_account=None):
# def __repr__(self):
# def __str__(self):
# def parse_top_line(self, line):
# def parse_transaction_lines(self, lines):
# def get_lines(self):
# def is_new_thing(line):
# def is_transaction_start(line):
# def assert_only_one_status(self, statuses):
# def assert_only_one_symbol(self, symbols):
# def assert_only_shares_if_shares(self, shareses):
# def assert_not_top_line_status(self):
# def get_date_and_payee(self):
# def get_date_string(self):
# def is_pending(self):
# def set_pending(self):
# def is_cleared(self):
# def set_cleared(self):
# def set_uncleared(self):
# class LedgerThing:
#
# Path: ledgerbil/tests/helpers.py
# class Redirector(TestCase):
# def setUp(self):
# self.savestdout = sys.stdout
# self.reset_redirect()
#
# self.savestderr = sys.stderr
# self.reset_err_redirect()
#
# def tearDown(self):
# self.redirect.close()
# sys.stdout = self.savestdout
#
# self.redirecterr.close()
# sys.stderr = self.savestderr
#
# def reset_redirect(self):
# self.redirect = StringIO()
# sys.stdout = self.redirect
#
# def reset_err_redirect(self):
# self.redirecterr = StringIO()
# sys.stderr = self.redirecterr
, which may include functions, classes, or code. Output only the next line. | def test_non_transaction_date(): |
Given snippet: <|code_start|>#!/usr/bin/env python3
def main(argv=None):
if argv is None:
argv = sys.argv[1:]
command = argv[0] if argv else ""
other = {
"grid": grid,
"inv": investments,
"investments": investments,
"pass": passthrough,
"port": portfolio,
"portfolio": portfolio,
}
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
from ledgerbil import ledgerbil, portfolio
from ledgerbil.ledgershell import grid, investments, passthrough
and context:
# Path: ledgerbil/ledgerbil.py
# def run_ledgerbil(args):
# def matching_account_found(ledgerfiles, reconcile_account):
# def get_args(args):
# def main(argv=None):
#
# Path: ledgerbil/portfolio.py
# VALID_YEAR_KEYS = {"symbol", "price", "shares", "contributions", "transfers", "note"}
# NULL_GAIN = -1
# COL_GAIN = 7
# COL_CONTRIB = 9
# COL_TRANSFERS = 10
# COL_VALUE = 11
# COL_GAIN_VALUE = 11
# COL_NUM_YEARS = 2
# COL_ACCOUNT = 40
# COL_LABEL = 12
# COL_PERCENT = 3
# def get_portfolio_report(args):
# def strip_assets_prefix(s):
# def no_match(accounts_regex, labels, yearly=False):
# def get_matching_accounts(accounts_regex, labels_string=""):
# def get_list(accounts):
# def validate_json_year_keys(year):
# def get_performance_report_header(accounts, num_years):
# def get_performance_report(accounts, included_years):
# def get_annualized_total_return(gains, num_years):
# def get_formatted_gain(gains=None, num_years=1, annualized_total=None):
# def get_gain(gains, num_years):
# def get_performance_report_column_headers(num_years):
# def get_performance_report_years(years):
# def get_yearly_combined_accounts(accounts, included_years):
# def get_yearly_with_gains(totals):
# def get_history_report(matching_accounts):
# def get_account_history(account):
# def get_comparison_report_column_headers(num_years, labels=True):
# def get_sorted_comparison_items(comparison_items, sort):
# def get_comparison_report(
# accounts, labels, accounts_regex, included_years, sort, accounts_only
# ):
# def get_comparison_summary(years, col1):
# def get_comparison_report_line(comparison_item, percent, labels):
# def get_portfolio_data():
# def get_args(args):
# def main(argv=None):
#
# Path: ledgerbil/ledgershell/grid.py
# TOTAL_HEADER = "Total"
# SORT_DEFAULT = TOTAL_HEADER.lower()
# EMPTY_VALUE = ""
# AMOUNT_WIDTH = 14 # width of columns with amounts
# ACCOUNT_PAYEE_COLUMN = -1 # last column, aka row header
# TOTAL_COLUMN = -2 # second to last column (*if* we have a total)
# AMOUNT_COLUMN_START = 0 # inclusive
# AMOUNT_COLUMN_END = TOTAL_COLUMN # exclusive
# AMOUNT_COLUMN_END = ACCOUNT_PAYEE_COLUMN # exclusive
# DATA_ROW_START = 1
# DATA_ROW_END = -1 if has_total_row else len(rows) # exclusive
# HEADER_ROW = 0
# FOOTER_ROW = -1 if has_total_row else None
# TRUNC_CHAR = "~"
# ACCOUNT_TYPES = ["assets:", "liabilities:", "income:", "expenses:", "equity:"]
# HEADER_SPLIT = r"(?<=: )|(?<=:)(?=\S)|(?<=[- ])"
# ACCOUNT_PAYEE_HEADER = EMPTY_VALUE
# ACCOUNT_PAYEE_COLUMN = -1
# TOTAL_COLUMN = -2
# def get_grid_report(args, ledger_args):
# def get_csv_report(rows, tabs=False):
# def get_flat_report(rows, networth=False):
# def get_flat_report_header(headers, width=14):
# def get_flat_report_header_lists(headers, width=14):
# def get_period_names(args, ledger_args, unit="year"):
# def get_columns(args, ledger_args, period_names, current_period=None):
# def get_column(args, ledger_args, period_name, ending):
# def get_column_accounts(period_name, ledger_args, depth=0):
# def validate_column_total(period_name, column_total=0, ledgers_total=0):
# def warn_column_total(period_name, column_total=0, ledgers_total=0):
# def get_column_payees(period_name, ledger_args):
# def get_column_networth(period_name, ledger_args):
# def get_rows(
# row_headers,
# columns,
# period_names,
# sort=SORT_DEFAULT,
# limit_rows=0,
# total_only=False,
# no_total=False,
# ):
# def get_grid(row_headers, columns):
# def get_args(args):
# def main(argv=None):
#
# Path: ledgerbil/ledgershell/investments.py
# def get_investment_command_options(accounts, end_date, shares=False):
# def warn_negative_dollars(amount, account):
# def get_lines(args, shares=False):
# def get_dollars(args):
# def get_shares(args):
# def get_investment_report(args):
# def get_args(args):
# def main(argv=None):
#
# Path: ledgerbil/ledgershell/passthrough.py
# def get_args(args):
# def main(argv=None):
which might include code, classes, or functions. Output only the next line. | if command not in other: |
Using the snippet: <|code_start|>#!/usr/bin/env python3
def main(argv=None):
if argv is None:
argv = sys.argv[1:]
command = argv[0] if argv else ""
other = {
"grid": grid,
"inv": investments,
"investments": investments,
"pass": passthrough,
"port": portfolio,
"portfolio": portfolio,
}
<|code_end|>
, determine the next line of code. You have imports:
import sys
from ledgerbil import ledgerbil, portfolio
from ledgerbil.ledgershell import grid, investments, passthrough
and context (class names, function names, or code) available:
# Path: ledgerbil/ledgerbil.py
# def run_ledgerbil(args):
# def matching_account_found(ledgerfiles, reconcile_account):
# def get_args(args):
# def main(argv=None):
#
# Path: ledgerbil/portfolio.py
# VALID_YEAR_KEYS = {"symbol", "price", "shares", "contributions", "transfers", "note"}
# NULL_GAIN = -1
# COL_GAIN = 7
# COL_CONTRIB = 9
# COL_TRANSFERS = 10
# COL_VALUE = 11
# COL_GAIN_VALUE = 11
# COL_NUM_YEARS = 2
# COL_ACCOUNT = 40
# COL_LABEL = 12
# COL_PERCENT = 3
# def get_portfolio_report(args):
# def strip_assets_prefix(s):
# def no_match(accounts_regex, labels, yearly=False):
# def get_matching_accounts(accounts_regex, labels_string=""):
# def get_list(accounts):
# def validate_json_year_keys(year):
# def get_performance_report_header(accounts, num_years):
# def get_performance_report(accounts, included_years):
# def get_annualized_total_return(gains, num_years):
# def get_formatted_gain(gains=None, num_years=1, annualized_total=None):
# def get_gain(gains, num_years):
# def get_performance_report_column_headers(num_years):
# def get_performance_report_years(years):
# def get_yearly_combined_accounts(accounts, included_years):
# def get_yearly_with_gains(totals):
# def get_history_report(matching_accounts):
# def get_account_history(account):
# def get_comparison_report_column_headers(num_years, labels=True):
# def get_sorted_comparison_items(comparison_items, sort):
# def get_comparison_report(
# accounts, labels, accounts_regex, included_years, sort, accounts_only
# ):
# def get_comparison_summary(years, col1):
# def get_comparison_report_line(comparison_item, percent, labels):
# def get_portfolio_data():
# def get_args(args):
# def main(argv=None):
#
# Path: ledgerbil/ledgershell/grid.py
# TOTAL_HEADER = "Total"
# SORT_DEFAULT = TOTAL_HEADER.lower()
# EMPTY_VALUE = ""
# AMOUNT_WIDTH = 14 # width of columns with amounts
# ACCOUNT_PAYEE_COLUMN = -1 # last column, aka row header
# TOTAL_COLUMN = -2 # second to last column (*if* we have a total)
# AMOUNT_COLUMN_START = 0 # inclusive
# AMOUNT_COLUMN_END = TOTAL_COLUMN # exclusive
# AMOUNT_COLUMN_END = ACCOUNT_PAYEE_COLUMN # exclusive
# DATA_ROW_START = 1
# DATA_ROW_END = -1 if has_total_row else len(rows) # exclusive
# HEADER_ROW = 0
# FOOTER_ROW = -1 if has_total_row else None
# TRUNC_CHAR = "~"
# ACCOUNT_TYPES = ["assets:", "liabilities:", "income:", "expenses:", "equity:"]
# HEADER_SPLIT = r"(?<=: )|(?<=:)(?=\S)|(?<=[- ])"
# ACCOUNT_PAYEE_HEADER = EMPTY_VALUE
# ACCOUNT_PAYEE_COLUMN = -1
# TOTAL_COLUMN = -2
# def get_grid_report(args, ledger_args):
# def get_csv_report(rows, tabs=False):
# def get_flat_report(rows, networth=False):
# def get_flat_report_header(headers, width=14):
# def get_flat_report_header_lists(headers, width=14):
# def get_period_names(args, ledger_args, unit="year"):
# def get_columns(args, ledger_args, period_names, current_period=None):
# def get_column(args, ledger_args, period_name, ending):
# def get_column_accounts(period_name, ledger_args, depth=0):
# def validate_column_total(period_name, column_total=0, ledgers_total=0):
# def warn_column_total(period_name, column_total=0, ledgers_total=0):
# def get_column_payees(period_name, ledger_args):
# def get_column_networth(period_name, ledger_args):
# def get_rows(
# row_headers,
# columns,
# period_names,
# sort=SORT_DEFAULT,
# limit_rows=0,
# total_only=False,
# no_total=False,
# ):
# def get_grid(row_headers, columns):
# def get_args(args):
# def main(argv=None):
#
# Path: ledgerbil/ledgershell/investments.py
# def get_investment_command_options(accounts, end_date, shares=False):
# def warn_negative_dollars(amount, account):
# def get_lines(args, shares=False):
# def get_dollars(args):
# def get_shares(args):
# def get_investment_report(args):
# def get_args(args):
# def main(argv=None):
#
# Path: ledgerbil/ledgershell/passthrough.py
# def get_args(args):
# def main(argv=None):
. Output only the next line. | if command not in other: |
Using the snippet: <|code_start|>#!/usr/bin/env python3
def main(argv=None):
if argv is None:
argv = sys.argv[1:]
command = argv[0] if argv else ""
other = {
"grid": grid,
"inv": investments,
"investments": investments,
"pass": passthrough,
"port": portfolio,
"portfolio": portfolio,
<|code_end|>
, determine the next line of code. You have imports:
import sys
from ledgerbil import ledgerbil, portfolio
from ledgerbil.ledgershell import grid, investments, passthrough
and context (class names, function names, or code) available:
# Path: ledgerbil/ledgerbil.py
# def run_ledgerbil(args):
# def matching_account_found(ledgerfiles, reconcile_account):
# def get_args(args):
# def main(argv=None):
#
# Path: ledgerbil/portfolio.py
# VALID_YEAR_KEYS = {"symbol", "price", "shares", "contributions", "transfers", "note"}
# NULL_GAIN = -1
# COL_GAIN = 7
# COL_CONTRIB = 9
# COL_TRANSFERS = 10
# COL_VALUE = 11
# COL_GAIN_VALUE = 11
# COL_NUM_YEARS = 2
# COL_ACCOUNT = 40
# COL_LABEL = 12
# COL_PERCENT = 3
# def get_portfolio_report(args):
# def strip_assets_prefix(s):
# def no_match(accounts_regex, labels, yearly=False):
# def get_matching_accounts(accounts_regex, labels_string=""):
# def get_list(accounts):
# def validate_json_year_keys(year):
# def get_performance_report_header(accounts, num_years):
# def get_performance_report(accounts, included_years):
# def get_annualized_total_return(gains, num_years):
# def get_formatted_gain(gains=None, num_years=1, annualized_total=None):
# def get_gain(gains, num_years):
# def get_performance_report_column_headers(num_years):
# def get_performance_report_years(years):
# def get_yearly_combined_accounts(accounts, included_years):
# def get_yearly_with_gains(totals):
# def get_history_report(matching_accounts):
# def get_account_history(account):
# def get_comparison_report_column_headers(num_years, labels=True):
# def get_sorted_comparison_items(comparison_items, sort):
# def get_comparison_report(
# accounts, labels, accounts_regex, included_years, sort, accounts_only
# ):
# def get_comparison_summary(years, col1):
# def get_comparison_report_line(comparison_item, percent, labels):
# def get_portfolio_data():
# def get_args(args):
# def main(argv=None):
#
# Path: ledgerbil/ledgershell/grid.py
# TOTAL_HEADER = "Total"
# SORT_DEFAULT = TOTAL_HEADER.lower()
# EMPTY_VALUE = ""
# AMOUNT_WIDTH = 14 # width of columns with amounts
# ACCOUNT_PAYEE_COLUMN = -1 # last column, aka row header
# TOTAL_COLUMN = -2 # second to last column (*if* we have a total)
# AMOUNT_COLUMN_START = 0 # inclusive
# AMOUNT_COLUMN_END = TOTAL_COLUMN # exclusive
# AMOUNT_COLUMN_END = ACCOUNT_PAYEE_COLUMN # exclusive
# DATA_ROW_START = 1
# DATA_ROW_END = -1 if has_total_row else len(rows) # exclusive
# HEADER_ROW = 0
# FOOTER_ROW = -1 if has_total_row else None
# TRUNC_CHAR = "~"
# ACCOUNT_TYPES = ["assets:", "liabilities:", "income:", "expenses:", "equity:"]
# HEADER_SPLIT = r"(?<=: )|(?<=:)(?=\S)|(?<=[- ])"
# ACCOUNT_PAYEE_HEADER = EMPTY_VALUE
# ACCOUNT_PAYEE_COLUMN = -1
# TOTAL_COLUMN = -2
# def get_grid_report(args, ledger_args):
# def get_csv_report(rows, tabs=False):
# def get_flat_report(rows, networth=False):
# def get_flat_report_header(headers, width=14):
# def get_flat_report_header_lists(headers, width=14):
# def get_period_names(args, ledger_args, unit="year"):
# def get_columns(args, ledger_args, period_names, current_period=None):
# def get_column(args, ledger_args, period_name, ending):
# def get_column_accounts(period_name, ledger_args, depth=0):
# def validate_column_total(period_name, column_total=0, ledgers_total=0):
# def warn_column_total(period_name, column_total=0, ledgers_total=0):
# def get_column_payees(period_name, ledger_args):
# def get_column_networth(period_name, ledger_args):
# def get_rows(
# row_headers,
# columns,
# period_names,
# sort=SORT_DEFAULT,
# limit_rows=0,
# total_only=False,
# no_total=False,
# ):
# def get_grid(row_headers, columns):
# def get_args(args):
# def main(argv=None):
#
# Path: ledgerbil/ledgershell/investments.py
# def get_investment_command_options(accounts, end_date, shares=False):
# def warn_negative_dollars(amount, account):
# def get_lines(args, shares=False):
# def get_dollars(args):
# def get_shares(args):
# def get_investment_report(args):
# def get_args(args):
# def main(argv=None):
#
# Path: ledgerbil/ledgershell/passthrough.py
# def get_args(args):
# def main(argv=None):
. Output only the next line. | } |
Given the code snippet: <|code_start|>#!/usr/bin/env python3
def main(argv=None):
if argv is None:
argv = sys.argv[1:]
command = argv[0] if argv else ""
other = {
"grid": grid,
"inv": investments,
"investments": investments,
"pass": passthrough,
"port": portfolio,
"portfolio": portfolio,
}
if command not in other:
return ledgerbil.main(argv)
<|code_end|>
, generate the next line using the imports in this file:
import sys
from ledgerbil import ledgerbil, portfolio
from ledgerbil.ledgershell import grid, investments, passthrough
and context (functions, classes, or occasionally code) from other files:
# Path: ledgerbil/ledgerbil.py
# def run_ledgerbil(args):
# def matching_account_found(ledgerfiles, reconcile_account):
# def get_args(args):
# def main(argv=None):
#
# Path: ledgerbil/portfolio.py
# VALID_YEAR_KEYS = {"symbol", "price", "shares", "contributions", "transfers", "note"}
# NULL_GAIN = -1
# COL_GAIN = 7
# COL_CONTRIB = 9
# COL_TRANSFERS = 10
# COL_VALUE = 11
# COL_GAIN_VALUE = 11
# COL_NUM_YEARS = 2
# COL_ACCOUNT = 40
# COL_LABEL = 12
# COL_PERCENT = 3
# def get_portfolio_report(args):
# def strip_assets_prefix(s):
# def no_match(accounts_regex, labels, yearly=False):
# def get_matching_accounts(accounts_regex, labels_string=""):
# def get_list(accounts):
# def validate_json_year_keys(year):
# def get_performance_report_header(accounts, num_years):
# def get_performance_report(accounts, included_years):
# def get_annualized_total_return(gains, num_years):
# def get_formatted_gain(gains=None, num_years=1, annualized_total=None):
# def get_gain(gains, num_years):
# def get_performance_report_column_headers(num_years):
# def get_performance_report_years(years):
# def get_yearly_combined_accounts(accounts, included_years):
# def get_yearly_with_gains(totals):
# def get_history_report(matching_accounts):
# def get_account_history(account):
# def get_comparison_report_column_headers(num_years, labels=True):
# def get_sorted_comparison_items(comparison_items, sort):
# def get_comparison_report(
# accounts, labels, accounts_regex, included_years, sort, accounts_only
# ):
# def get_comparison_summary(years, col1):
# def get_comparison_report_line(comparison_item, percent, labels):
# def get_portfolio_data():
# def get_args(args):
# def main(argv=None):
#
# Path: ledgerbil/ledgershell/grid.py
# TOTAL_HEADER = "Total"
# SORT_DEFAULT = TOTAL_HEADER.lower()
# EMPTY_VALUE = ""
# AMOUNT_WIDTH = 14 # width of columns with amounts
# ACCOUNT_PAYEE_COLUMN = -1 # last column, aka row header
# TOTAL_COLUMN = -2 # second to last column (*if* we have a total)
# AMOUNT_COLUMN_START = 0 # inclusive
# AMOUNT_COLUMN_END = TOTAL_COLUMN # exclusive
# AMOUNT_COLUMN_END = ACCOUNT_PAYEE_COLUMN # exclusive
# DATA_ROW_START = 1
# DATA_ROW_END = -1 if has_total_row else len(rows) # exclusive
# HEADER_ROW = 0
# FOOTER_ROW = -1 if has_total_row else None
# TRUNC_CHAR = "~"
# ACCOUNT_TYPES = ["assets:", "liabilities:", "income:", "expenses:", "equity:"]
# HEADER_SPLIT = r"(?<=: )|(?<=:)(?=\S)|(?<=[- ])"
# ACCOUNT_PAYEE_HEADER = EMPTY_VALUE
# ACCOUNT_PAYEE_COLUMN = -1
# TOTAL_COLUMN = -2
# def get_grid_report(args, ledger_args):
# def get_csv_report(rows, tabs=False):
# def get_flat_report(rows, networth=False):
# def get_flat_report_header(headers, width=14):
# def get_flat_report_header_lists(headers, width=14):
# def get_period_names(args, ledger_args, unit="year"):
# def get_columns(args, ledger_args, period_names, current_period=None):
# def get_column(args, ledger_args, period_name, ending):
# def get_column_accounts(period_name, ledger_args, depth=0):
# def validate_column_total(period_name, column_total=0, ledgers_total=0):
# def warn_column_total(period_name, column_total=0, ledgers_total=0):
# def get_column_payees(period_name, ledger_args):
# def get_column_networth(period_name, ledger_args):
# def get_rows(
# row_headers,
# columns,
# period_names,
# sort=SORT_DEFAULT,
# limit_rows=0,
# total_only=False,
# no_total=False,
# ):
# def get_grid(row_headers, columns):
# def get_args(args):
# def main(argv=None):
#
# Path: ledgerbil/ledgershell/investments.py
# def get_investment_command_options(accounts, end_date, shares=False):
# def warn_negative_dollars(amount, account):
# def get_lines(args, shares=False):
# def get_dollars(args):
# def get_shares(args):
# def get_investment_report(args):
# def get_args(args):
# def main(argv=None):
#
# Path: ledgerbil/ledgershell/passthrough.py
# def get_args(args):
# def main(argv=None):
. Output only the next line. | else: |
Given snippet: <|code_start|>
@mock.patch(__name__ + ".scheduler.handle_error")
def test_scheduler_error(mock_error):
schedulefiledata = ";; scheduler enter 321 days"
with FT.temp_file(schedulefiledata) as temp_schedule_filename:
ledgerfile = None # is going to error before we use ledgerfile
scheduler.run_scheduler(ledgerfile, temp_schedule_filename)
expected = dedent(
"""\
Invalid schedule file config:
;; scheduler enter 321 days
Expected:
;; scheduler ; enter N days"""
)
mock_error.assert_called_once_with(expected)
@mock.patch(__name__ + ".scheduler.print")
def test_next_scheduled_date(mock_print):
with FT.temp_file(schedule_testdata) as tempfile:
return_value = scheduler.print_next_scheduled_date(tempfile)
assert return_value is None
mock_print.assert_called_once_with("2007/07/07")
@mock.patch(__name__ + ".scheduler.print")
def test_next_scheduled_date_no_next(mock_print):
with FT.temp_file(";; scheduler ; enter 45 days") as tempfile:
return_value = scheduler.print_next_scheduled_date(tempfile)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from datetime import date
from textwrap import dedent
from unittest import mock
from dateutil.relativedelta import relativedelta
from .. import scheduler, util
from ..ledgerfile import LedgerFile
from . import filetester as FT
from .test_schedulefile import schedule_testdata
and context:
# Path: ledgerbil/ledgerfile.py
# class LedgerFile:
# STARTING_DATE = date(1899, 1, 1)
# thing_counter = -1
#
# def __init__(self, filename, reconcile_account=None):
# self.filename = filename
# self.rec_account = reconcile_account # Could be partial or regex
# self.reset()
#
# def reset(self):
# self.things = []
# self.rec_account_matched = None # Full account name
# self.read_file()
#
# def read_file(self):
# if not self.is_writable():
# sys.exit(-1)
#
# current_lines = []
# with open(self.filename, "r", encoding="utf-8") as the_file:
# for line in the_file:
# line = line.rstrip()
#
# if LedgerThing.is_new_thing(line):
# self.add_thing_from_lines(current_lines)
# current_lines = []
#
# current_lines.append(line)
#
# self.add_thing_from_lines(current_lines)
#
# def is_writable(self):
# # Catch read-only files as well as bad filenames
# try:
# with open(self.filename, "r+"):
# return True
# except IOError as e:
# print(f"error: {e}", file=sys.stderr)
# return False
#
# def add_thing_from_lines(self, lines):
# lines = remove_trailing_blank_lines(lines)
# if lines:
# thing = LedgerThing(lines, self.rec_account)
# self.add_things([thing])
#
# def add_things(self, things):
# for thing in things:
# self.thing_counter += 1
# thing.thing_number = self.thing_counter
# self.things.append(thing)
#
# if self.rec_account and thing.rec_account_matched:
# if not self.rec_account_matched:
# self.rec_account_matched = thing.rec_account_matched
# else:
# assert_only_one_matching_account(
# {self.rec_account_matched, thing.rec_account_matched}
# )
#
# def sort(self):
# current_date = self.STARTING_DATE
#
# for thing in self.things:
# if thing.thing_date is None:
# thing.thing_date = current_date
# else:
# current_date = thing.thing_date
#
# self.things.sort(key=attrgetter("thing_date", "thing_number"))
#
# def print_file(self):
# for thing in self.things:
# for line in thing.get_lines():
# print(line)
# print()
#
# def write_file(self):
# with open(self.filename, "w", encoding="utf-8") as the_file:
# for thing in self.things:
# the_file.write("\n".join(thing.get_lines()) + "\n\n")
#
# Path: ledgerbil/tests/test_schedulefile.py
# def test_next_scheduled_transaction():
# def test_next_scheduled_transaction_no_next():
# def test_add_thing_with_no_lines():
which might include code, classes, or functions. Output only the next line. | assert return_value is None |
Predict the next line for this snippet: <|code_start|>
def get_schedule_file(the_date, schedule, enter_days=7):
return (
f";; scheduler ; enter {enter_days} days\n"
"\n"
f"{the_date} bananas unlimited\n"
f" ;; schedule ; {schedule}\n"
" e: misc\n"
" l: credit card $-50\n\n"
)
def run_it(before_date, after_date, schedule, enter_days=7):
schedulefiledata = get_schedule_file(
util.get_date_string(before_date), schedule, enter_days
)
with FT.temp_file(schedulefiledata) as temp_schedule_filename:
with FT.temp_file("") as temp_ledger_filename:
ledgerfile = LedgerFile(temp_ledger_filename)
return_value = scheduler.run_scheduler(ledgerfile, temp_schedule_filename)
assert not return_value
actual_data = FT.read_file(temp_schedule_filename)
expected_data = get_schedule_file(
<|code_end|>
with the help of current file imports:
from datetime import date
from textwrap import dedent
from unittest import mock
from dateutil.relativedelta import relativedelta
from .. import scheduler, util
from ..ledgerfile import LedgerFile
from . import filetester as FT
from .test_schedulefile import schedule_testdata
and context from other files:
# Path: ledgerbil/ledgerfile.py
# class LedgerFile:
# STARTING_DATE = date(1899, 1, 1)
# thing_counter = -1
#
# def __init__(self, filename, reconcile_account=None):
# self.filename = filename
# self.rec_account = reconcile_account # Could be partial or regex
# self.reset()
#
# def reset(self):
# self.things = []
# self.rec_account_matched = None # Full account name
# self.read_file()
#
# def read_file(self):
# if not self.is_writable():
# sys.exit(-1)
#
# current_lines = []
# with open(self.filename, "r", encoding="utf-8") as the_file:
# for line in the_file:
# line = line.rstrip()
#
# if LedgerThing.is_new_thing(line):
# self.add_thing_from_lines(current_lines)
# current_lines = []
#
# current_lines.append(line)
#
# self.add_thing_from_lines(current_lines)
#
# def is_writable(self):
# # Catch read-only files as well as bad filenames
# try:
# with open(self.filename, "r+"):
# return True
# except IOError as e:
# print(f"error: {e}", file=sys.stderr)
# return False
#
# def add_thing_from_lines(self, lines):
# lines = remove_trailing_blank_lines(lines)
# if lines:
# thing = LedgerThing(lines, self.rec_account)
# self.add_things([thing])
#
# def add_things(self, things):
# for thing in things:
# self.thing_counter += 1
# thing.thing_number = self.thing_counter
# self.things.append(thing)
#
# if self.rec_account and thing.rec_account_matched:
# if not self.rec_account_matched:
# self.rec_account_matched = thing.rec_account_matched
# else:
# assert_only_one_matching_account(
# {self.rec_account_matched, thing.rec_account_matched}
# )
#
# def sort(self):
# current_date = self.STARTING_DATE
#
# for thing in self.things:
# if thing.thing_date is None:
# thing.thing_date = current_date
# else:
# current_date = thing.thing_date
#
# self.things.sort(key=attrgetter("thing_date", "thing_number"))
#
# def print_file(self):
# for thing in self.things:
# for line in thing.get_lines():
# print(line)
# print()
#
# def write_file(self):
# with open(self.filename, "w", encoding="utf-8") as the_file:
# for thing in self.things:
# the_file.write("\n".join(thing.get_lines()) + "\n\n")
#
# Path: ledgerbil/tests/test_schedulefile.py
# def test_next_scheduled_transaction():
# def test_next_scheduled_transaction_no_next():
# def test_add_thing_with_no_lines():
, which may contain function names, class names, or code. Output only the next line. | util.get_date_string(after_date), schedule, enter_days |
Using the snippet: <|code_start|>
def get_investment_command_options(accounts, end_date, shares=False):
options = ["--no-total"]
if shares:
options += ["--exchange", "."] # override --market
options += ["--end", end_date]
return tuple(["bal"] + parse_args(accounts) + options)
def warn_negative_dollars(amount, account):
warning = Colorable("red", "WARNING:")
amount = Colorable("red", amount)
print(
f'{warning} Negative dollar amount {amount} for "{account.strip()}". '
"This may be a data entry mistake, or because we are "
"looking at a date range.\n"
)
<|code_end|>
, determine the next line of code. You have imports:
import argparse
import re
from textwrap import dedent
from ..colorable import Colorable
from ..settings_getter import get_setting
from ..util import parse_args
from .runner import get_ledger_command, get_ledger_output
from .util import AccountBalance, get_account_balance
and context (class names, function names, or code) available:
# Path: ledgerbil/colorable.py
# class Colorable:
#
# START_CODE = "\033"
# END_CODE = f"{START_CODE}[0m"
#
# BRIGHT_OFFSET = 60
#
# COLORS = {
# "black": 30,
# "gray": 30,
# "grey": 30,
# "red": 31,
# "green": 32,
# "yellow": 33,
# "blue": 34,
# "magenta": 35,
# "purple": 35,
# "cyan": 36,
# "white": 37,
# }
#
# ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
#
# def __init__(self, color, value, fmt="", bright=False):
#
# if color not in self.COLORS:
# raise UnsupportedColorError(
# f"I don't know what to do with this color: {color}"
# )
#
# self.my_color = color
# self.value = value
# self.bright = bright
# self.format_string = fmt
#
# def __repr__(self):
# return (
# f"Colorable('{self.my_color}', '{self.value}', "
# f"fmt='{self.format_string}', bright={self.bright})"
# )
#
# def __str__(self):
# start = self.ansi_sequence(self.COLORS[self.my_color], bright=self.bright)
# ansi_str = f"{start}{self.value:{self.format_string}}{self.END_CODE}"
# return ansi_str
#
# def __len__(self):
# return len(self.value)
#
# def __eq__(self, other):
# return str(self) == str(other)
#
# def ansi_sequence(self, code, bright=False):
# offset = 60 if bright else 0
# color = code + offset
# return f"{self.START_CODE}[0;{color}m"
#
# def plain(self):
# return self.value
#
# @staticmethod
# def get_plain_string(ansi_string):
# return Colorable.ansi_escape.sub("", ansi_string)
#
# Path: ledgerbil/settings_getter.py
# def get_setting(setting, default=None):
# if settings and hasattr(settings, setting):
# return getattr(settings, setting)
#
# return defaults.get(setting, default)
#
# Path: ledgerbil/util.py
# def parse_args(args):
# # args should be a string, but we'll make sure it isn't None
# # (which would cause the string to be read from stdin)
# try:
# return shlex.split(args or "")
# except ValueError as e:
# print(f"*** {e}")
# return None
#
# Path: ledgerbil/ledgershell/runner.py
# def get_ledger_command(args=None):
# files = []
# for f in get_setting("LEDGER_FILES"):
# files += ["-f", os.path.join(get_setting("LEDGER_DIR"), f)]
# return get_setting("LEDGER_COMMAND") + tuple(files) + (args or ())
#
# def get_ledger_output(args=None):
# cmd = get_ledger_command(args)
# process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
# output, _ = process.communicate()
# return output.decode("unicode_escape").rstrip()
#
# Path: ledgerbil/ledgershell/util.py
# AMOUNT = r"-?[\d,.]+"
# DOLLARS_REGEX = re.compile(rf"^\s*(?:(\$\s*{AMOUNT}|0(?= )))(.*)$")
# SHARES_REGEX = re.compile(rf"\s*({AMOUNT}) ([a-zA-Z]+)(.*)$")
# FIRST_DOLLAR_AMOUNT_REGEX = re.compile(rf"^.*?\$\s*({AMOUNT}).*$")
# PAYEE_SUBTOTAL_REGEX = re.compile(r"^.*?\$\s*(\S+)\s*\$.*$")
# DOLLARS = 0
# DOLLARS = 0
# def get_account_balance(line, shares=False, strip_account=True):
# def get_account_balance_generic(line):
# def get_payee_subtotal(line):
# def get_first_dollar_amount_float(line):
. Output only the next line. | def get_lines(args, shares=False): |
Using the snippet: <|code_start|>
def get_investment_command_options(accounts, end_date, shares=False):
options = ["--no-total"]
if shares:
options += ["--exchange", "."] # override --market
options += ["--end", end_date]
return tuple(["bal"] + parse_args(accounts) + options)
def warn_negative_dollars(amount, account):
warning = Colorable("red", "WARNING:")
amount = Colorable("red", amount)
print(
f'{warning} Negative dollar amount {amount} for "{account.strip()}". '
"This may be a data entry mistake, or because we are "
"looking at a date range.\n"
)
def get_lines(args, shares=False):
<|code_end|>
, determine the next line of code. You have imports:
import argparse
import re
from textwrap import dedent
from ..colorable import Colorable
from ..settings_getter import get_setting
from ..util import parse_args
from .runner import get_ledger_command, get_ledger_output
from .util import AccountBalance, get_account_balance
and context (class names, function names, or code) available:
# Path: ledgerbil/colorable.py
# class Colorable:
#
# START_CODE = "\033"
# END_CODE = f"{START_CODE}[0m"
#
# BRIGHT_OFFSET = 60
#
# COLORS = {
# "black": 30,
# "gray": 30,
# "grey": 30,
# "red": 31,
# "green": 32,
# "yellow": 33,
# "blue": 34,
# "magenta": 35,
# "purple": 35,
# "cyan": 36,
# "white": 37,
# }
#
# ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
#
# def __init__(self, color, value, fmt="", bright=False):
#
# if color not in self.COLORS:
# raise UnsupportedColorError(
# f"I don't know what to do with this color: {color}"
# )
#
# self.my_color = color
# self.value = value
# self.bright = bright
# self.format_string = fmt
#
# def __repr__(self):
# return (
# f"Colorable('{self.my_color}', '{self.value}', "
# f"fmt='{self.format_string}', bright={self.bright})"
# )
#
# def __str__(self):
# start = self.ansi_sequence(self.COLORS[self.my_color], bright=self.bright)
# ansi_str = f"{start}{self.value:{self.format_string}}{self.END_CODE}"
# return ansi_str
#
# def __len__(self):
# return len(self.value)
#
# def __eq__(self, other):
# return str(self) == str(other)
#
# def ansi_sequence(self, code, bright=False):
# offset = 60 if bright else 0
# color = code + offset
# return f"{self.START_CODE}[0;{color}m"
#
# def plain(self):
# return self.value
#
# @staticmethod
# def get_plain_string(ansi_string):
# return Colorable.ansi_escape.sub("", ansi_string)
#
# Path: ledgerbil/settings_getter.py
# def get_setting(setting, default=None):
# if settings and hasattr(settings, setting):
# return getattr(settings, setting)
#
# return defaults.get(setting, default)
#
# Path: ledgerbil/util.py
# def parse_args(args):
# # args should be a string, but we'll make sure it isn't None
# # (which would cause the string to be read from stdin)
# try:
# return shlex.split(args or "")
# except ValueError as e:
# print(f"*** {e}")
# return None
#
# Path: ledgerbil/ledgershell/runner.py
# def get_ledger_command(args=None):
# files = []
# for f in get_setting("LEDGER_FILES"):
# files += ["-f", os.path.join(get_setting("LEDGER_DIR"), f)]
# return get_setting("LEDGER_COMMAND") + tuple(files) + (args or ())
#
# def get_ledger_output(args=None):
# cmd = get_ledger_command(args)
# process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
# output, _ = process.communicate()
# return output.decode("unicode_escape").rstrip()
#
# Path: ledgerbil/ledgershell/util.py
# AMOUNT = r"-?[\d,.]+"
# DOLLARS_REGEX = re.compile(rf"^\s*(?:(\$\s*{AMOUNT}|0(?= )))(.*)$")
# SHARES_REGEX = re.compile(rf"\s*({AMOUNT}) ([a-zA-Z]+)(.*)$")
# FIRST_DOLLAR_AMOUNT_REGEX = re.compile(rf"^.*?\$\s*({AMOUNT}).*$")
# PAYEE_SUBTOTAL_REGEX = re.compile(r"^.*?\$\s*(\S+)\s*\$.*$")
# DOLLARS = 0
# DOLLARS = 0
# def get_account_balance(line, shares=False, strip_account=True):
# def get_account_balance_generic(line):
# def get_payee_subtotal(line):
# def get_first_dollar_amount_float(line):
. Output only the next line. | options = get_investment_command_options(args.accounts, args.end, shares) |
Predict the next line after this snippet: <|code_start|>
def get_investment_command_options(accounts, end_date, shares=False):
options = ["--no-total"]
if shares:
options += ["--exchange", "."] # override --market
options += ["--end", end_date]
return tuple(["bal"] + parse_args(accounts) + options)
def warn_negative_dollars(amount, account):
warning = Colorable("red", "WARNING:")
amount = Colorable("red", amount)
print(
<|code_end|>
using the current file's imports:
import argparse
import re
from textwrap import dedent
from ..colorable import Colorable
from ..settings_getter import get_setting
from ..util import parse_args
from .runner import get_ledger_command, get_ledger_output
from .util import AccountBalance, get_account_balance
and any relevant context from other files:
# Path: ledgerbil/colorable.py
# class Colorable:
#
# START_CODE = "\033"
# END_CODE = f"{START_CODE}[0m"
#
# BRIGHT_OFFSET = 60
#
# COLORS = {
# "black": 30,
# "gray": 30,
# "grey": 30,
# "red": 31,
# "green": 32,
# "yellow": 33,
# "blue": 34,
# "magenta": 35,
# "purple": 35,
# "cyan": 36,
# "white": 37,
# }
#
# ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
#
# def __init__(self, color, value, fmt="", bright=False):
#
# if color not in self.COLORS:
# raise UnsupportedColorError(
# f"I don't know what to do with this color: {color}"
# )
#
# self.my_color = color
# self.value = value
# self.bright = bright
# self.format_string = fmt
#
# def __repr__(self):
# return (
# f"Colorable('{self.my_color}', '{self.value}', "
# f"fmt='{self.format_string}', bright={self.bright})"
# )
#
# def __str__(self):
# start = self.ansi_sequence(self.COLORS[self.my_color], bright=self.bright)
# ansi_str = f"{start}{self.value:{self.format_string}}{self.END_CODE}"
# return ansi_str
#
# def __len__(self):
# return len(self.value)
#
# def __eq__(self, other):
# return str(self) == str(other)
#
# def ansi_sequence(self, code, bright=False):
# offset = 60 if bright else 0
# color = code + offset
# return f"{self.START_CODE}[0;{color}m"
#
# def plain(self):
# return self.value
#
# @staticmethod
# def get_plain_string(ansi_string):
# return Colorable.ansi_escape.sub("", ansi_string)
#
# Path: ledgerbil/settings_getter.py
# def get_setting(setting, default=None):
# if settings and hasattr(settings, setting):
# return getattr(settings, setting)
#
# return defaults.get(setting, default)
#
# Path: ledgerbil/util.py
# def parse_args(args):
# # args should be a string, but we'll make sure it isn't None
# # (which would cause the string to be read from stdin)
# try:
# return shlex.split(args or "")
# except ValueError as e:
# print(f"*** {e}")
# return None
#
# Path: ledgerbil/ledgershell/runner.py
# def get_ledger_command(args=None):
# files = []
# for f in get_setting("LEDGER_FILES"):
# files += ["-f", os.path.join(get_setting("LEDGER_DIR"), f)]
# return get_setting("LEDGER_COMMAND") + tuple(files) + (args or ())
#
# def get_ledger_output(args=None):
# cmd = get_ledger_command(args)
# process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
# output, _ = process.communicate()
# return output.decode("unicode_escape").rstrip()
#
# Path: ledgerbil/ledgershell/util.py
# AMOUNT = r"-?[\d,.]+"
# DOLLARS_REGEX = re.compile(rf"^\s*(?:(\$\s*{AMOUNT}|0(?= )))(.*)$")
# SHARES_REGEX = re.compile(rf"\s*({AMOUNT}) ([a-zA-Z]+)(.*)$")
# FIRST_DOLLAR_AMOUNT_REGEX = re.compile(rf"^.*?\$\s*({AMOUNT}).*$")
# PAYEE_SUBTOTAL_REGEX = re.compile(r"^.*?\$\s*(\S+)\s*\$.*$")
# DOLLARS = 0
# DOLLARS = 0
# def get_account_balance(line, shares=False, strip_account=True):
# def get_account_balance_generic(line):
# def get_payee_subtotal(line):
# def get_first_dollar_amount_float(line):
. Output only the next line. | f'{warning} Negative dollar amount {amount} for "{account.strip()}". ' |
Given snippet: <|code_start|>
def get_investment_command_options(accounts, end_date, shares=False):
options = ["--no-total"]
if shares:
options += ["--exchange", "."] # override --market
options += ["--end", end_date]
return tuple(["bal"] + parse_args(accounts) + options)
def warn_negative_dollars(amount, account):
warning = Colorable("red", "WARNING:")
amount = Colorable("red", amount)
print(
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import argparse
import re
from textwrap import dedent
from ..colorable import Colorable
from ..settings_getter import get_setting
from ..util import parse_args
from .runner import get_ledger_command, get_ledger_output
from .util import AccountBalance, get_account_balance
and context:
# Path: ledgerbil/colorable.py
# class Colorable:
#
# START_CODE = "\033"
# END_CODE = f"{START_CODE}[0m"
#
# BRIGHT_OFFSET = 60
#
# COLORS = {
# "black": 30,
# "gray": 30,
# "grey": 30,
# "red": 31,
# "green": 32,
# "yellow": 33,
# "blue": 34,
# "magenta": 35,
# "purple": 35,
# "cyan": 36,
# "white": 37,
# }
#
# ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
#
# def __init__(self, color, value, fmt="", bright=False):
#
# if color not in self.COLORS:
# raise UnsupportedColorError(
# f"I don't know what to do with this color: {color}"
# )
#
# self.my_color = color
# self.value = value
# self.bright = bright
# self.format_string = fmt
#
# def __repr__(self):
# return (
# f"Colorable('{self.my_color}', '{self.value}', "
# f"fmt='{self.format_string}', bright={self.bright})"
# )
#
# def __str__(self):
# start = self.ansi_sequence(self.COLORS[self.my_color], bright=self.bright)
# ansi_str = f"{start}{self.value:{self.format_string}}{self.END_CODE}"
# return ansi_str
#
# def __len__(self):
# return len(self.value)
#
# def __eq__(self, other):
# return str(self) == str(other)
#
# def ansi_sequence(self, code, bright=False):
# offset = 60 if bright else 0
# color = code + offset
# return f"{self.START_CODE}[0;{color}m"
#
# def plain(self):
# return self.value
#
# @staticmethod
# def get_plain_string(ansi_string):
# return Colorable.ansi_escape.sub("", ansi_string)
#
# Path: ledgerbil/settings_getter.py
# def get_setting(setting, default=None):
# if settings and hasattr(settings, setting):
# return getattr(settings, setting)
#
# return defaults.get(setting, default)
#
# Path: ledgerbil/util.py
# def parse_args(args):
# # args should be a string, but we'll make sure it isn't None
# # (which would cause the string to be read from stdin)
# try:
# return shlex.split(args or "")
# except ValueError as e:
# print(f"*** {e}")
# return None
#
# Path: ledgerbil/ledgershell/runner.py
# def get_ledger_command(args=None):
# files = []
# for f in get_setting("LEDGER_FILES"):
# files += ["-f", os.path.join(get_setting("LEDGER_DIR"), f)]
# return get_setting("LEDGER_COMMAND") + tuple(files) + (args or ())
#
# def get_ledger_output(args=None):
# cmd = get_ledger_command(args)
# process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
# output, _ = process.communicate()
# return output.decode("unicode_escape").rstrip()
#
# Path: ledgerbil/ledgershell/util.py
# AMOUNT = r"-?[\d,.]+"
# DOLLARS_REGEX = re.compile(rf"^\s*(?:(\$\s*{AMOUNT}|0(?= )))(.*)$")
# SHARES_REGEX = re.compile(rf"\s*({AMOUNT}) ([a-zA-Z]+)(.*)$")
# FIRST_DOLLAR_AMOUNT_REGEX = re.compile(rf"^.*?\$\s*({AMOUNT}).*$")
# PAYEE_SUBTOTAL_REGEX = re.compile(r"^.*?\$\s*(\S+)\s*\$.*$")
# DOLLARS = 0
# DOLLARS = 0
# def get_account_balance(line, shares=False, strip_account=True):
# def get_account_balance_generic(line):
# def get_payee_subtotal(line):
# def get_first_dollar_amount_float(line):
which might include code, classes, or functions. Output only the next line. | f'{warning} Negative dollar amount {amount} for "{account.strip()}". ' |
Given the following code snippet before the placeholder: <|code_start|>
def get_investment_command_options(accounts, end_date, shares=False):
options = ["--no-total"]
if shares:
options += ["--exchange", "."] # override --market
options += ["--end", end_date]
return tuple(["bal"] + parse_args(accounts) + options)
def warn_negative_dollars(amount, account):
warning = Colorable("red", "WARNING:")
amount = Colorable("red", amount)
print(
f'{warning} Negative dollar amount {amount} for "{account.strip()}". '
"This may be a data entry mistake, or because we are "
"looking at a date range.\n"
)
def get_lines(args, shares=False):
options = get_investment_command_options(args.accounts, args.end, shares)
output = get_ledger_output(options)
if args.command:
print(" ".join(get_ledger_command(options)))
<|code_end|>
, predict the next line using imports from the current file:
import argparse
import re
from textwrap import dedent
from ..colorable import Colorable
from ..settings_getter import get_setting
from ..util import parse_args
from .runner import get_ledger_command, get_ledger_output
from .util import AccountBalance, get_account_balance
and context including class names, function names, and sometimes code from other files:
# Path: ledgerbil/colorable.py
# class Colorable:
#
# START_CODE = "\033"
# END_CODE = f"{START_CODE}[0m"
#
# BRIGHT_OFFSET = 60
#
# COLORS = {
# "black": 30,
# "gray": 30,
# "grey": 30,
# "red": 31,
# "green": 32,
# "yellow": 33,
# "blue": 34,
# "magenta": 35,
# "purple": 35,
# "cyan": 36,
# "white": 37,
# }
#
# ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
#
# def __init__(self, color, value, fmt="", bright=False):
#
# if color not in self.COLORS:
# raise UnsupportedColorError(
# f"I don't know what to do with this color: {color}"
# )
#
# self.my_color = color
# self.value = value
# self.bright = bright
# self.format_string = fmt
#
# def __repr__(self):
# return (
# f"Colorable('{self.my_color}', '{self.value}', "
# f"fmt='{self.format_string}', bright={self.bright})"
# )
#
# def __str__(self):
# start = self.ansi_sequence(self.COLORS[self.my_color], bright=self.bright)
# ansi_str = f"{start}{self.value:{self.format_string}}{self.END_CODE}"
# return ansi_str
#
# def __len__(self):
# return len(self.value)
#
# def __eq__(self, other):
# return str(self) == str(other)
#
# def ansi_sequence(self, code, bright=False):
# offset = 60 if bright else 0
# color = code + offset
# return f"{self.START_CODE}[0;{color}m"
#
# def plain(self):
# return self.value
#
# @staticmethod
# def get_plain_string(ansi_string):
# return Colorable.ansi_escape.sub("", ansi_string)
#
# Path: ledgerbil/settings_getter.py
# def get_setting(setting, default=None):
# if settings and hasattr(settings, setting):
# return getattr(settings, setting)
#
# return defaults.get(setting, default)
#
# Path: ledgerbil/util.py
# def parse_args(args):
# # args should be a string, but we'll make sure it isn't None
# # (which would cause the string to be read from stdin)
# try:
# return shlex.split(args or "")
# except ValueError as e:
# print(f"*** {e}")
# return None
#
# Path: ledgerbil/ledgershell/runner.py
# def get_ledger_command(args=None):
# files = []
# for f in get_setting("LEDGER_FILES"):
# files += ["-f", os.path.join(get_setting("LEDGER_DIR"), f)]
# return get_setting("LEDGER_COMMAND") + tuple(files) + (args or ())
#
# def get_ledger_output(args=None):
# cmd = get_ledger_command(args)
# process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
# output, _ = process.communicate()
# return output.decode("unicode_escape").rstrip()
#
# Path: ledgerbil/ledgershell/util.py
# AMOUNT = r"-?[\d,.]+"
# DOLLARS_REGEX = re.compile(rf"^\s*(?:(\$\s*{AMOUNT}|0(?= )))(.*)$")
# SHARES_REGEX = re.compile(rf"\s*({AMOUNT}) ([a-zA-Z]+)(.*)$")
# FIRST_DOLLAR_AMOUNT_REGEX = re.compile(rf"^.*?\$\s*({AMOUNT}).*$")
# PAYEE_SUBTOTAL_REGEX = re.compile(r"^.*?\$\s*(\S+)\s*\$.*$")
# DOLLARS = 0
# DOLLARS = 0
# def get_account_balance(line, shares=False, strip_account=True):
# def get_account_balance_generic(line):
# def get_payee_subtotal(line):
# def get_first_dollar_amount_float(line):
. Output only the next line. | return output.split("\n") |
Given the code snippet: <|code_start|>
def setup_function():
settings_getter.settings = MockSettings()
def teardown_function():
settings_getter.settings = settings.Settings()
BIG_CO = 0
BONDS = 1
BIG_NAME = 2
BONDS_2 = 3
CLOSED = 4
portfolio_json_data = """\
[
{
"account": "assets: 401k: big co 500 idx",
"labels": [
"large",
"401k",
"flurb"
],
"years": {
"2016": {
"symbol": "abcdx",
"price": 80.23,
"shares": 12200.78,
<|code_end|>
, generate the next line using the imports in this file:
import json
import pytest
from unittest import mock
from .. import portfolio, settings, settings_getter
from ..colorable import Colorable
from ..ledgerbilexceptions import LdgPortfolioError
from .helpers import OutputFileTester
and context (functions, classes, or occasionally code) from other files:
# Path: ledgerbil/colorable.py
# class Colorable:
#
# START_CODE = "\033"
# END_CODE = f"{START_CODE}[0m"
#
# BRIGHT_OFFSET = 60
#
# COLORS = {
# "black": 30,
# "gray": 30,
# "grey": 30,
# "red": 31,
# "green": 32,
# "yellow": 33,
# "blue": 34,
# "magenta": 35,
# "purple": 35,
# "cyan": 36,
# "white": 37,
# }
#
# ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
#
# def __init__(self, color, value, fmt="", bright=False):
#
# if color not in self.COLORS:
# raise UnsupportedColorError(
# f"I don't know what to do with this color: {color}"
# )
#
# self.my_color = color
# self.value = value
# self.bright = bright
# self.format_string = fmt
#
# def __repr__(self):
# return (
# f"Colorable('{self.my_color}', '{self.value}', "
# f"fmt='{self.format_string}', bright={self.bright})"
# )
#
# def __str__(self):
# start = self.ansi_sequence(self.COLORS[self.my_color], bright=self.bright)
# ansi_str = f"{start}{self.value:{self.format_string}}{self.END_CODE}"
# return ansi_str
#
# def __len__(self):
# return len(self.value)
#
# def __eq__(self, other):
# return str(self) == str(other)
#
# def ansi_sequence(self, code, bright=False):
# offset = 60 if bright else 0
# color = code + offset
# return f"{self.START_CODE}[0;{color}m"
#
# def plain(self):
# return self.value
#
# @staticmethod
# def get_plain_string(ansi_string):
# return Colorable.ansi_escape.sub("", ansi_string)
#
# Path: ledgerbil/ledgerbilexceptions.py
# class LdgPortfolioError(LdgException):
# pass
#
# Path: ledgerbil/tests/helpers.py
# class OutputFileTester(OutputFileTesterBase):
# def __init__(self, testfile):
# super().__init__()
# self.testfile = testfile
#
# def save_out_file(self, data):
# with open(self.get_out_filename(self.testfile), "w", encoding="utf-8") as afile:
# afile.write(self.remove_color(data))
#
# def assert_out_equals_expected(self):
# assert filecmp.cmp(
# self.get_out_filename(self.testfile),
# self.get_expected_filename(self.testfile),
# ), f"test filename out: {self.get_out_filename(self.testfile)}"
. Output only the next line. | "contributions": 1500.79, |
Here is a snippet: <|code_start|> "contributions": 750,
"transfers": 15000
}
}
},
{
"account": "assets: 401k: long account name that goes on...",
"labels": ["401k", "flurb", "intl", "active", "smactive"],
"years": {}
},
{
"account": "assets: 401k: bonds idx 2",
"labels": [],
"years": {}
},
{
"account": "assets: yog: mog",
"labels": ["closed"],
"years": {
"2014": {
"price": 10,
"shares": 1000,
"contributions": 0,
"transfers": 9950
},
"2015": {
"price": 0,
"shares": 0,
"contributions": 0,
"transfers": -10025
<|code_end|>
. Write the next line using the current file imports:
import json
import pytest
from unittest import mock
from .. import portfolio, settings, settings_getter
from ..colorable import Colorable
from ..ledgerbilexceptions import LdgPortfolioError
from .helpers import OutputFileTester
and context from other files:
# Path: ledgerbil/colorable.py
# class Colorable:
#
# START_CODE = "\033"
# END_CODE = f"{START_CODE}[0m"
#
# BRIGHT_OFFSET = 60
#
# COLORS = {
# "black": 30,
# "gray": 30,
# "grey": 30,
# "red": 31,
# "green": 32,
# "yellow": 33,
# "blue": 34,
# "magenta": 35,
# "purple": 35,
# "cyan": 36,
# "white": 37,
# }
#
# ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
#
# def __init__(self, color, value, fmt="", bright=False):
#
# if color not in self.COLORS:
# raise UnsupportedColorError(
# f"I don't know what to do with this color: {color}"
# )
#
# self.my_color = color
# self.value = value
# self.bright = bright
# self.format_string = fmt
#
# def __repr__(self):
# return (
# f"Colorable('{self.my_color}', '{self.value}', "
# f"fmt='{self.format_string}', bright={self.bright})"
# )
#
# def __str__(self):
# start = self.ansi_sequence(self.COLORS[self.my_color], bright=self.bright)
# ansi_str = f"{start}{self.value:{self.format_string}}{self.END_CODE}"
# return ansi_str
#
# def __len__(self):
# return len(self.value)
#
# def __eq__(self, other):
# return str(self) == str(other)
#
# def ansi_sequence(self, code, bright=False):
# offset = 60 if bright else 0
# color = code + offset
# return f"{self.START_CODE}[0;{color}m"
#
# def plain(self):
# return self.value
#
# @staticmethod
# def get_plain_string(ansi_string):
# return Colorable.ansi_escape.sub("", ansi_string)
#
# Path: ledgerbil/ledgerbilexceptions.py
# class LdgPortfolioError(LdgException):
# pass
#
# Path: ledgerbil/tests/helpers.py
# class OutputFileTester(OutputFileTesterBase):
# def __init__(self, testfile):
# super().__init__()
# self.testfile = testfile
#
# def save_out_file(self, data):
# with open(self.get_out_filename(self.testfile), "w", encoding="utf-8") as afile:
# afile.write(self.remove_color(data))
#
# def assert_out_equals_expected(self):
# assert filecmp.cmp(
# self.get_out_filename(self.testfile),
# self.get_expected_filename(self.testfile),
# ), f"test filename out: {self.get_out_filename(self.testfile)}"
, which may include functions, classes, or code. Output only the next line. | } |
Using the snippet: <|code_start|> "401k",
"flurb"
],
"years": {
"2016": {
"symbol": "abcdx",
"price": 80.23,
"shares": 12200.78,
"contributions": 1500.79,
"transfers": 900000,
"note": "optional..."
},
"2019": {
"symbol": "abcdx",
"price": 83.11,
"shares": 1700,
"contributions": 500,
"transfers": -100000
},
"2017": {
"symbol": "abcdx",
"price": 81.57,
"shares": 999,
"contributions": 11500
}
}
},
{
"account": "assets: 401k: bonds idx",
"labels": [
<|code_end|>
, determine the next line of code. You have imports:
import json
import pytest
from unittest import mock
from .. import portfolio, settings, settings_getter
from ..colorable import Colorable
from ..ledgerbilexceptions import LdgPortfolioError
from .helpers import OutputFileTester
and context (class names, function names, or code) available:
# Path: ledgerbil/colorable.py
# class Colorable:
#
# START_CODE = "\033"
# END_CODE = f"{START_CODE}[0m"
#
# BRIGHT_OFFSET = 60
#
# COLORS = {
# "black": 30,
# "gray": 30,
# "grey": 30,
# "red": 31,
# "green": 32,
# "yellow": 33,
# "blue": 34,
# "magenta": 35,
# "purple": 35,
# "cyan": 36,
# "white": 37,
# }
#
# ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
#
# def __init__(self, color, value, fmt="", bright=False):
#
# if color not in self.COLORS:
# raise UnsupportedColorError(
# f"I don't know what to do with this color: {color}"
# )
#
# self.my_color = color
# self.value = value
# self.bright = bright
# self.format_string = fmt
#
# def __repr__(self):
# return (
# f"Colorable('{self.my_color}', '{self.value}', "
# f"fmt='{self.format_string}', bright={self.bright})"
# )
#
# def __str__(self):
# start = self.ansi_sequence(self.COLORS[self.my_color], bright=self.bright)
# ansi_str = f"{start}{self.value:{self.format_string}}{self.END_CODE}"
# return ansi_str
#
# def __len__(self):
# return len(self.value)
#
# def __eq__(self, other):
# return str(self) == str(other)
#
# def ansi_sequence(self, code, bright=False):
# offset = 60 if bright else 0
# color = code + offset
# return f"{self.START_CODE}[0;{color}m"
#
# def plain(self):
# return self.value
#
# @staticmethod
# def get_plain_string(ansi_string):
# return Colorable.ansi_escape.sub("", ansi_string)
#
# Path: ledgerbil/ledgerbilexceptions.py
# class LdgPortfolioError(LdgException):
# pass
#
# Path: ledgerbil/tests/helpers.py
# class OutputFileTester(OutputFileTesterBase):
# def __init__(self, testfile):
# super().__init__()
# self.testfile = testfile
#
# def save_out_file(self, data):
# with open(self.get_out_filename(self.testfile), "w", encoding="utf-8") as afile:
# afile.write(self.remove_color(data))
#
# def assert_out_equals_expected(self):
# assert filecmp.cmp(
# self.get_out_filename(self.testfile),
# self.get_expected_filename(self.testfile),
# ), f"test filename out: {self.get_out_filename(self.testfile)}"
. Output only the next line. | "bonds", |
Given the following code snippet before the placeholder: <|code_start|>
NO_PREVIOUS_DATE = "-"
def run_reconciler(ledgerfiles):
try:
reconciler = Reconciler(ledgerfiles)
except LdgReconcilerError as e:
return util.handle_error(str(e))
reconciler.cmdloop()
class Reconciler(cmd.Cmd):
<|code_end|>
, predict the next line using imports from the current file:
import cmd
import json
import os
import re
import sys
from dataclasses import dataclass
from datetime import date
from . import util
from .colorable import Colorable
from .ledgerbilexceptions import LdgReconcilerError
from .ledgershell.runner import get_ledger_output
from .ledgershell.util import get_account_balance_generic
from .settings_getter import get_setting
and context including class names, function names, and sometimes code from other files:
# Path: ledgerbil/colorable.py
# class Colorable:
#
# START_CODE = "\033"
# END_CODE = f"{START_CODE}[0m"
#
# BRIGHT_OFFSET = 60
#
# COLORS = {
# "black": 30,
# "gray": 30,
# "grey": 30,
# "red": 31,
# "green": 32,
# "yellow": 33,
# "blue": 34,
# "magenta": 35,
# "purple": 35,
# "cyan": 36,
# "white": 37,
# }
#
# ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
#
# def __init__(self, color, value, fmt="", bright=False):
#
# if color not in self.COLORS:
# raise UnsupportedColorError(
# f"I don't know what to do with this color: {color}"
# )
#
# self.my_color = color
# self.value = value
# self.bright = bright
# self.format_string = fmt
#
# def __repr__(self):
# return (
# f"Colorable('{self.my_color}', '{self.value}', "
# f"fmt='{self.format_string}', bright={self.bright})"
# )
#
# def __str__(self):
# start = self.ansi_sequence(self.COLORS[self.my_color], bright=self.bright)
# ansi_str = f"{start}{self.value:{self.format_string}}{self.END_CODE}"
# return ansi_str
#
# def __len__(self):
# return len(self.value)
#
# def __eq__(self, other):
# return str(self) == str(other)
#
# def ansi_sequence(self, code, bright=False):
# offset = 60 if bright else 0
# color = code + offset
# return f"{self.START_CODE}[0;{color}m"
#
# def plain(self):
# return self.value
#
# @staticmethod
# def get_plain_string(ansi_string):
# return Colorable.ansi_escape.sub("", ansi_string)
#
# Path: ledgerbil/ledgerbilexceptions.py
# class LdgReconcilerError(LdgException):
# pass
#
# Path: ledgerbil/ledgershell/runner.py
# def get_ledger_output(args=None):
# cmd = get_ledger_command(args)
# process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
# output, _ = process.communicate()
# return output.decode("unicode_escape").rstrip()
#
# Path: ledgerbil/ledgershell/util.py
# def get_account_balance_generic(line):
# balance = get_account_balance(line, shares=False)
# if not balance:
# return get_account_balance(line, shares=True)
# return balance
#
# Path: ledgerbil/settings_getter.py
# def get_setting(setting, default=None):
# if settings and hasattr(settings, setting):
# return getattr(settings, setting)
#
# return defaults.get(setting, default)
. Output only the next line. | UNKNOWN_SYNTAX = "*** Unknown syntax: " |
Predict the next line for this snippet: <|code_start|>
NO_PREVIOUS_DATE = "-"
def run_reconciler(ledgerfiles):
try:
reconciler = Reconciler(ledgerfiles)
except LdgReconcilerError as e:
return util.handle_error(str(e))
reconciler.cmdloop()
<|code_end|>
with the help of current file imports:
import cmd
import json
import os
import re
import sys
from dataclasses import dataclass
from datetime import date
from . import util
from .colorable import Colorable
from .ledgerbilexceptions import LdgReconcilerError
from .ledgershell.runner import get_ledger_output
from .ledgershell.util import get_account_balance_generic
from .settings_getter import get_setting
and context from other files:
# Path: ledgerbil/colorable.py
# class Colorable:
#
# START_CODE = "\033"
# END_CODE = f"{START_CODE}[0m"
#
# BRIGHT_OFFSET = 60
#
# COLORS = {
# "black": 30,
# "gray": 30,
# "grey": 30,
# "red": 31,
# "green": 32,
# "yellow": 33,
# "blue": 34,
# "magenta": 35,
# "purple": 35,
# "cyan": 36,
# "white": 37,
# }
#
# ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
#
# def __init__(self, color, value, fmt="", bright=False):
#
# if color not in self.COLORS:
# raise UnsupportedColorError(
# f"I don't know what to do with this color: {color}"
# )
#
# self.my_color = color
# self.value = value
# self.bright = bright
# self.format_string = fmt
#
# def __repr__(self):
# return (
# f"Colorable('{self.my_color}', '{self.value}', "
# f"fmt='{self.format_string}', bright={self.bright})"
# )
#
# def __str__(self):
# start = self.ansi_sequence(self.COLORS[self.my_color], bright=self.bright)
# ansi_str = f"{start}{self.value:{self.format_string}}{self.END_CODE}"
# return ansi_str
#
# def __len__(self):
# return len(self.value)
#
# def __eq__(self, other):
# return str(self) == str(other)
#
# def ansi_sequence(self, code, bright=False):
# offset = 60 if bright else 0
# color = code + offset
# return f"{self.START_CODE}[0;{color}m"
#
# def plain(self):
# return self.value
#
# @staticmethod
# def get_plain_string(ansi_string):
# return Colorable.ansi_escape.sub("", ansi_string)
#
# Path: ledgerbil/ledgerbilexceptions.py
# class LdgReconcilerError(LdgException):
# pass
#
# Path: ledgerbil/ledgershell/runner.py
# def get_ledger_output(args=None):
# cmd = get_ledger_command(args)
# process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
# output, _ = process.communicate()
# return output.decode("unicode_escape").rstrip()
#
# Path: ledgerbil/ledgershell/util.py
# def get_account_balance_generic(line):
# balance = get_account_balance(line, shares=False)
# if not balance:
# return get_account_balance(line, shares=True)
# return balance
#
# Path: ledgerbil/settings_getter.py
# def get_setting(setting, default=None):
# if settings and hasattr(settings, setting):
# return getattr(settings, setting)
#
# return defaults.get(setting, default)
, which may contain function names, class names, or code. Output only the next line. | class Reconciler(cmd.Cmd): |
Using the snippet: <|code_start|>NO_PREVIOUS_DATE = "-"
def run_reconciler(ledgerfiles):
try:
reconciler = Reconciler(ledgerfiles)
except LdgReconcilerError as e:
return util.handle_error(str(e))
reconciler.cmdloop()
class Reconciler(cmd.Cmd):
UNKNOWN_SYNTAX = "*** Unknown syntax: "
NO_HELP = "*** No help on "
def __init__(self, ledgerfiles):
cmd.Cmd.__init__(self)
self.aliases = {
"end": self.do_finish,
"EOF": self.do_quit,
"l": self.do_list,
"ll": self.do_list,
"m": self.do_mark,
"u": self.do_unmark,
"un": self.do_unmark,
"q": self.do_quit,
"r": self.do_reload,
"s": self.do_show,
<|code_end|>
, determine the next line of code. You have imports:
import cmd
import json
import os
import re
import sys
from dataclasses import dataclass
from datetime import date
from . import util
from .colorable import Colorable
from .ledgerbilexceptions import LdgReconcilerError
from .ledgershell.runner import get_ledger_output
from .ledgershell.util import get_account_balance_generic
from .settings_getter import get_setting
and context (class names, function names, or code) available:
# Path: ledgerbil/colorable.py
# class Colorable:
#
# START_CODE = "\033"
# END_CODE = f"{START_CODE}[0m"
#
# BRIGHT_OFFSET = 60
#
# COLORS = {
# "black": 30,
# "gray": 30,
# "grey": 30,
# "red": 31,
# "green": 32,
# "yellow": 33,
# "blue": 34,
# "magenta": 35,
# "purple": 35,
# "cyan": 36,
# "white": 37,
# }
#
# ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
#
# def __init__(self, color, value, fmt="", bright=False):
#
# if color not in self.COLORS:
# raise UnsupportedColorError(
# f"I don't know what to do with this color: {color}"
# )
#
# self.my_color = color
# self.value = value
# self.bright = bright
# self.format_string = fmt
#
# def __repr__(self):
# return (
# f"Colorable('{self.my_color}', '{self.value}', "
# f"fmt='{self.format_string}', bright={self.bright})"
# )
#
# def __str__(self):
# start = self.ansi_sequence(self.COLORS[self.my_color], bright=self.bright)
# ansi_str = f"{start}{self.value:{self.format_string}}{self.END_CODE}"
# return ansi_str
#
# def __len__(self):
# return len(self.value)
#
# def __eq__(self, other):
# return str(self) == str(other)
#
# def ansi_sequence(self, code, bright=False):
# offset = 60 if bright else 0
# color = code + offset
# return f"{self.START_CODE}[0;{color}m"
#
# def plain(self):
# return self.value
#
# @staticmethod
# def get_plain_string(ansi_string):
# return Colorable.ansi_escape.sub("", ansi_string)
#
# Path: ledgerbil/ledgerbilexceptions.py
# class LdgReconcilerError(LdgException):
# pass
#
# Path: ledgerbil/ledgershell/runner.py
# def get_ledger_output(args=None):
# cmd = get_ledger_command(args)
# process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
# output, _ = process.communicate()
# return output.decode("unicode_escape").rstrip()
#
# Path: ledgerbil/ledgershell/util.py
# def get_account_balance_generic(line):
# balance = get_account_balance(line, shares=False)
# if not balance:
# return get_account_balance(line, shares=True)
# return balance
#
# Path: ledgerbil/settings_getter.py
# def get_setting(setting, default=None):
# if settings and hasattr(settings, setting):
# return getattr(settings, setting)
#
# return defaults.get(setting, default)
. Output only the next line. | "start": self.do_statement, |
Predict the next line after this snippet: <|code_start|> "m": self.do_mark,
"u": self.do_unmark,
"un": self.do_unmark,
"q": self.do_quit,
"r": self.do_reload,
"s": self.do_show,
"start": self.do_statement,
}
util.assert_only_one_matching_account(
[
ledgerfile.rec_account_matched
for ledgerfile in ledgerfiles
if ledgerfile.rec_account_matched is not None
]
)
self.ledgerfiles = ledgerfiles
self.ending_date = date.today()
self.ending_balance = None
self.previous_date = date.today()
self.previous_balance = None
self.cached_is_shares = None
self.get_statement_info_from_cache()
self.populate_open_transactions()
intro = ""
prompt = "> "
def emptyline(self):
<|code_end|>
using the current file's imports:
import cmd
import json
import os
import re
import sys
from dataclasses import dataclass
from datetime import date
from . import util
from .colorable import Colorable
from .ledgerbilexceptions import LdgReconcilerError
from .ledgershell.runner import get_ledger_output
from .ledgershell.util import get_account_balance_generic
from .settings_getter import get_setting
and any relevant context from other files:
# Path: ledgerbil/colorable.py
# class Colorable:
#
# START_CODE = "\033"
# END_CODE = f"{START_CODE}[0m"
#
# BRIGHT_OFFSET = 60
#
# COLORS = {
# "black": 30,
# "gray": 30,
# "grey": 30,
# "red": 31,
# "green": 32,
# "yellow": 33,
# "blue": 34,
# "magenta": 35,
# "purple": 35,
# "cyan": 36,
# "white": 37,
# }
#
# ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
#
# def __init__(self, color, value, fmt="", bright=False):
#
# if color not in self.COLORS:
# raise UnsupportedColorError(
# f"I don't know what to do with this color: {color}"
# )
#
# self.my_color = color
# self.value = value
# self.bright = bright
# self.format_string = fmt
#
# def __repr__(self):
# return (
# f"Colorable('{self.my_color}', '{self.value}', "
# f"fmt='{self.format_string}', bright={self.bright})"
# )
#
# def __str__(self):
# start = self.ansi_sequence(self.COLORS[self.my_color], bright=self.bright)
# ansi_str = f"{start}{self.value:{self.format_string}}{self.END_CODE}"
# return ansi_str
#
# def __len__(self):
# return len(self.value)
#
# def __eq__(self, other):
# return str(self) == str(other)
#
# def ansi_sequence(self, code, bright=False):
# offset = 60 if bright else 0
# color = code + offset
# return f"{self.START_CODE}[0;{color}m"
#
# def plain(self):
# return self.value
#
# @staticmethod
# def get_plain_string(ansi_string):
# return Colorable.ansi_escape.sub("", ansi_string)
#
# Path: ledgerbil/ledgerbilexceptions.py
# class LdgReconcilerError(LdgException):
# pass
#
# Path: ledgerbil/ledgershell/runner.py
# def get_ledger_output(args=None):
# cmd = get_ledger_command(args)
# process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
# output, _ = process.communicate()
# return output.decode("unicode_escape").rstrip()
#
# Path: ledgerbil/ledgershell/util.py
# def get_account_balance_generic(line):
# balance = get_account_balance(line, shares=False)
# if not balance:
# return get_account_balance(line, shares=True)
# return balance
#
# Path: ledgerbil/settings_getter.py
# def get_setting(setting, default=None):
# if settings and hasattr(settings, setting):
# return getattr(settings, setting)
#
# return defaults.get(setting, default)
. Output only the next line. | pass # pragma: no cover |
Next line prediction: <|code_start|> "s": self.do_show,
"start": self.do_statement,
}
util.assert_only_one_matching_account(
[
ledgerfile.rec_account_matched
for ledgerfile in ledgerfiles
if ledgerfile.rec_account_matched is not None
]
)
self.ledgerfiles = ledgerfiles
self.ending_date = date.today()
self.ending_balance = None
self.previous_date = date.today()
self.previous_balance = None
self.cached_is_shares = None
self.get_statement_info_from_cache()
self.populate_open_transactions()
intro = ""
prompt = "> "
def emptyline(self):
pass # pragma: no cover
def default(self, line):
command, arg, line = self.parseline(line)
<|code_end|>
. Use current file imports:
(import cmd
import json
import os
import re
import sys
from dataclasses import dataclass
from datetime import date
from . import util
from .colorable import Colorable
from .ledgerbilexceptions import LdgReconcilerError
from .ledgershell.runner import get_ledger_output
from .ledgershell.util import get_account_balance_generic
from .settings_getter import get_setting)
and context including class names, function names, or small code snippets from other files:
# Path: ledgerbil/colorable.py
# class Colorable:
#
# START_CODE = "\033"
# END_CODE = f"{START_CODE}[0m"
#
# BRIGHT_OFFSET = 60
#
# COLORS = {
# "black": 30,
# "gray": 30,
# "grey": 30,
# "red": 31,
# "green": 32,
# "yellow": 33,
# "blue": 34,
# "magenta": 35,
# "purple": 35,
# "cyan": 36,
# "white": 37,
# }
#
# ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
#
# def __init__(self, color, value, fmt="", bright=False):
#
# if color not in self.COLORS:
# raise UnsupportedColorError(
# f"I don't know what to do with this color: {color}"
# )
#
# self.my_color = color
# self.value = value
# self.bright = bright
# self.format_string = fmt
#
# def __repr__(self):
# return (
# f"Colorable('{self.my_color}', '{self.value}', "
# f"fmt='{self.format_string}', bright={self.bright})"
# )
#
# def __str__(self):
# start = self.ansi_sequence(self.COLORS[self.my_color], bright=self.bright)
# ansi_str = f"{start}{self.value:{self.format_string}}{self.END_CODE}"
# return ansi_str
#
# def __len__(self):
# return len(self.value)
#
# def __eq__(self, other):
# return str(self) == str(other)
#
# def ansi_sequence(self, code, bright=False):
# offset = 60 if bright else 0
# color = code + offset
# return f"{self.START_CODE}[0;{color}m"
#
# def plain(self):
# return self.value
#
# @staticmethod
# def get_plain_string(ansi_string):
# return Colorable.ansi_escape.sub("", ansi_string)
#
# Path: ledgerbil/ledgerbilexceptions.py
# class LdgReconcilerError(LdgException):
# pass
#
# Path: ledgerbil/ledgershell/runner.py
# def get_ledger_output(args=None):
# cmd = get_ledger_command(args)
# process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
# output, _ = process.communicate()
# return output.decode("unicode_escape").rstrip()
#
# Path: ledgerbil/ledgershell/util.py
# def get_account_balance_generic(line):
# balance = get_account_balance(line, shares=False)
# if not balance:
# return get_account_balance(line, shares=True)
# return balance
#
# Path: ledgerbil/settings_getter.py
# def get_setting(setting, default=None):
# if settings and hasattr(settings, setting):
# return getattr(settings, setting)
#
# return defaults.get(setting, default)
. Output only the next line. | if command == "EOF": |
Given the following code snippet before the placeholder: <|code_start|>
class MockSettings:
NETWORTH_ACCOUNTS = "(^fu ^bar)"
DATE_FORMAT_MONTH = settings_getter.defaults["DATE_FORMAT_MONTH"]
class MockSettingsAltDateFormat:
NETWORTH_ACCOUNTS = "(^bar ^fu)"
<|code_end|>
, predict the next line using imports from the current file:
import sys
import pytest
from datetime import date
from textwrap import dedent
from unittest import mock
from ... import settings, settings_getter
from ...colorable import Colorable
from ...tests.helpers import OutputFileTester
from .. import grid
and context including class names, function names, and sometimes code from other files:
# Path: ledgerbil/colorable.py
# class Colorable:
#
# START_CODE = "\033"
# END_CODE = f"{START_CODE}[0m"
#
# BRIGHT_OFFSET = 60
#
# COLORS = {
# "black": 30,
# "gray": 30,
# "grey": 30,
# "red": 31,
# "green": 32,
# "yellow": 33,
# "blue": 34,
# "magenta": 35,
# "purple": 35,
# "cyan": 36,
# "white": 37,
# }
#
# ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
#
# def __init__(self, color, value, fmt="", bright=False):
#
# if color not in self.COLORS:
# raise UnsupportedColorError(
# f"I don't know what to do with this color: {color}"
# )
#
# self.my_color = color
# self.value = value
# self.bright = bright
# self.format_string = fmt
#
# def __repr__(self):
# return (
# f"Colorable('{self.my_color}', '{self.value}', "
# f"fmt='{self.format_string}', bright={self.bright})"
# )
#
# def __str__(self):
# start = self.ansi_sequence(self.COLORS[self.my_color], bright=self.bright)
# ansi_str = f"{start}{self.value:{self.format_string}}{self.END_CODE}"
# return ansi_str
#
# def __len__(self):
# return len(self.value)
#
# def __eq__(self, other):
# return str(self) == str(other)
#
# def ansi_sequence(self, code, bright=False):
# offset = 60 if bright else 0
# color = code + offset
# return f"{self.START_CODE}[0;{color}m"
#
# def plain(self):
# return self.value
#
# @staticmethod
# def get_plain_string(ansi_string):
# return Colorable.ansi_escape.sub("", ansi_string)
#
# Path: ledgerbil/tests/helpers.py
# class OutputFileTester(OutputFileTesterBase):
# def __init__(self, testfile):
# super().__init__()
# self.testfile = testfile
#
# def save_out_file(self, data):
# with open(self.get_out_filename(self.testfile), "w", encoding="utf-8") as afile:
# afile.write(self.remove_color(data))
#
# def assert_out_equals_expected(self):
# assert filecmp.cmp(
# self.get_out_filename(self.testfile),
# self.get_expected_filename(self.testfile),
# ), f"test filename out: {self.get_out_filename(self.testfile)}"
. Output only the next line. | DATE_FORMAT_MONTH = "%Y-%m" |
Continue the code snippet: <|code_start|> period_names = ("lemon",)
actual = grid.get_rows(row_headers, columns, period_names)
expected = [["lemon", grid.EMPTY_VALUE], [100, "expenses: car: gas"]]
assert actual == expected
def test_get_csv_report():
"""csv report should turn whatever it's given into csv it tabs
not specified"""
rows = [
[1, 2, 3, 4, 5],
["a", "b", '"c"', "d e f", "g, h"],
["", 4, "", 6, "glurg"],
]
expected = dedent(
'''\
1,2,3,4,5
a,b,"""c""",d e f,"g, h"
,4,,6,glurg
'''
)
csv_report = grid.get_csv_report(rows)
assert csv_report == expected
def test_get_csv_report_with_tabs():
"""csv report should turn whatever it's given into tsv if tabs
are specified"""
rows = [
[1, 2, 3, 4, 5],
<|code_end|>
. Use current file imports:
import sys
import pytest
from datetime import date
from textwrap import dedent
from unittest import mock
from ... import settings, settings_getter
from ...colorable import Colorable
from ...tests.helpers import OutputFileTester
from .. import grid
and context (classes, functions, or code) from other files:
# Path: ledgerbil/colorable.py
# class Colorable:
#
# START_CODE = "\033"
# END_CODE = f"{START_CODE}[0m"
#
# BRIGHT_OFFSET = 60
#
# COLORS = {
# "black": 30,
# "gray": 30,
# "grey": 30,
# "red": 31,
# "green": 32,
# "yellow": 33,
# "blue": 34,
# "magenta": 35,
# "purple": 35,
# "cyan": 36,
# "white": 37,
# }
#
# ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
#
# def __init__(self, color, value, fmt="", bright=False):
#
# if color not in self.COLORS:
# raise UnsupportedColorError(
# f"I don't know what to do with this color: {color}"
# )
#
# self.my_color = color
# self.value = value
# self.bright = bright
# self.format_string = fmt
#
# def __repr__(self):
# return (
# f"Colorable('{self.my_color}', '{self.value}', "
# f"fmt='{self.format_string}', bright={self.bright})"
# )
#
# def __str__(self):
# start = self.ansi_sequence(self.COLORS[self.my_color], bright=self.bright)
# ansi_str = f"{start}{self.value:{self.format_string}}{self.END_CODE}"
# return ansi_str
#
# def __len__(self):
# return len(self.value)
#
# def __eq__(self, other):
# return str(self) == str(other)
#
# def ansi_sequence(self, code, bright=False):
# offset = 60 if bright else 0
# color = code + offset
# return f"{self.START_CODE}[0;{color}m"
#
# def plain(self):
# return self.value
#
# @staticmethod
# def get_plain_string(ansi_string):
# return Colorable.ansi_escape.sub("", ansi_string)
#
# Path: ledgerbil/tests/helpers.py
# class OutputFileTester(OutputFileTesterBase):
# def __init__(self, testfile):
# super().__init__()
# self.testfile = testfile
#
# def save_out_file(self, data):
# with open(self.get_out_filename(self.testfile), "w", encoding="utf-8") as afile:
# afile.write(self.remove_color(data))
#
# def assert_out_equals_expected(self):
# assert filecmp.cmp(
# self.get_out_filename(self.testfile),
# self.get_expected_filename(self.testfile),
# ), f"test filename out: {self.get_out_filename(self.testfile)}"
. Output only the next line. | ["a", "b", '"c"', "d e f", "g\th"], |
Given the following code snippet before the placeholder: <|code_start|>
@pytest.mark.parametrize("test_input", [FT.alpha_sortedfile, FT.alpha_unsortedfile])
def test_main_no_options(test_input):
"""main should parse and write sorted and unsorted files unchanged"""
expected = FT.read_file(test_input)
with FT.temp_file(expected) as templedgerfile:
ledgerbil.main(["--file", templedgerfile])
actual = FT.read_file(templedgerfile)
assert actual == expected
@pytest.mark.parametrize("test_input", [FT.alpha_sortedfile, FT.alpha_unsortedfile])
def test_main_sort(test_input):
"""main should write sorted file"""
testdata = FT.read_file(test_input)
with FT.temp_file(testdata) as templedgerfile:
ledgerbil.main(["--file", templedgerfile, "--sort"])
actual = FT.read_file(templedgerfile)
expected = FT.read_file(FT.alpha_sortedfile)
assert actual == expected
def test_main_sort_different_date_format():
"""main should fail to sort file if date format is different
than in ledger entries"""
class MockSettings:
<|code_end|>
, predict the next line using imports from the current file:
from datetime import date
from textwrap import dedent
from unittest import mock
from dateutil.relativedelta import relativedelta
from ..ledgerbilexceptions import ERROR_RETURN_VALUE
from . import filetester as FT
from .helpers import Redirector
from .test_schedulefile import schedule_testdata
from .. import ( # noqa: F401 (stuff used in patches) isort:skip
ledgerbil,
reconciler,
scheduler,
settings,
settings_getter,
util,
)
import pytest
and context including class names, function names, and sometimes code from other files:
# Path: ledgerbil/ledgerbilexceptions.py
# ERROR_RETURN_VALUE = 1
#
# Path: ledgerbil/tests/helpers.py
# class Redirector(TestCase):
# def setUp(self):
# self.savestdout = sys.stdout
# self.reset_redirect()
#
# self.savestderr = sys.stderr
# self.reset_err_redirect()
#
# def tearDown(self):
# self.redirect.close()
# sys.stdout = self.savestdout
#
# self.redirecterr.close()
# sys.stderr = self.savestderr
#
# def reset_redirect(self):
# self.redirect = StringIO()
# sys.stdout = self.redirect
#
# def reset_err_redirect(self):
# self.redirecterr = StringIO()
# sys.stderr = self.redirecterr
#
# Path: ledgerbil/tests/test_schedulefile.py
# def test_next_scheduled_transaction():
# def test_next_scheduled_transaction_no_next():
# def test_add_thing_with_no_lines():
. Output only the next line. | DATE_FORMAT = "%Y-%m-%d" |
Predict the next line after this snippet: <|code_start|> expected = "error: -f/--file is required"
mock_handle_error.assert_called_once_with(expected)
def test_main_investments_with_argv_none_retun_value():
with mock.patch("sys.argv", ["/script"]):
assert ledgerbil.main() == ERROR_RETURN_VALUE
@mock.patch(__name__ + ".scheduler.handle_error")
def test_next_scheduled_date_scheduler_exception(mock_handle_error):
schedulefile_data = ";; scheduler enter 567 days"
with FT.temp_file(schedulefile_data) as tempfilename:
ledgerbil.main(["--schedule", tempfilename, "-n"])
expected = dedent(
"""\
Invalid schedule file config:
;; scheduler enter 567 days
Expected:
;; scheduler ; enter N days"""
)
mock_handle_error.assert_called_once_with(expected)
def test_next_scheduled_date_scheduler_exception_return_value():
schedulefile_data = ";; scheduler enter 567 days"
with FT.temp_file(schedulefile_data) as tempfilename:
assert ledgerbil.main(["--schedule", tempfilename, "-n"]) == ERROR_RETURN_VALUE
<|code_end|>
using the current file's imports:
from datetime import date
from textwrap import dedent
from unittest import mock
from dateutil.relativedelta import relativedelta
from ..ledgerbilexceptions import ERROR_RETURN_VALUE
from . import filetester as FT
from .helpers import Redirector
from .test_schedulefile import schedule_testdata
from .. import ( # noqa: F401 (stuff used in patches) isort:skip
ledgerbil,
reconciler,
scheduler,
settings,
settings_getter,
util,
)
import pytest
and any relevant context from other files:
# Path: ledgerbil/ledgerbilexceptions.py
# ERROR_RETURN_VALUE = 1
#
# Path: ledgerbil/tests/helpers.py
# class Redirector(TestCase):
# def setUp(self):
# self.savestdout = sys.stdout
# self.reset_redirect()
#
# self.savestderr = sys.stderr
# self.reset_err_redirect()
#
# def tearDown(self):
# self.redirect.close()
# sys.stdout = self.savestdout
#
# self.redirecterr.close()
# sys.stderr = self.savestderr
#
# def reset_redirect(self):
# self.redirect = StringIO()
# sys.stdout = self.redirect
#
# def reset_err_redirect(self):
# self.redirecterr = StringIO()
# sys.stderr = self.redirecterr
#
# Path: ledgerbil/tests/test_schedulefile.py
# def test_next_scheduled_transaction():
# def test_next_scheduled_transaction_no_next():
# def test_add_thing_with_no_lines():
. Output only the next line. | @mock.patch(__name__ + ".scheduler.handle_error") |
Predict the next line for this snippet: <|code_start|> mock_handle_error.assert_called_once_with(expected)
def test_main_investments_with_argv_none_retun_value():
with mock.patch("sys.argv", ["/script"]):
assert ledgerbil.main() == ERROR_RETURN_VALUE
@mock.patch(__name__ + ".scheduler.handle_error")
def test_next_scheduled_date_scheduler_exception(mock_handle_error):
schedulefile_data = ";; scheduler enter 567 days"
with FT.temp_file(schedulefile_data) as tempfilename:
ledgerbil.main(["--schedule", tempfilename, "-n"])
expected = dedent(
"""\
Invalid schedule file config:
;; scheduler enter 567 days
Expected:
;; scheduler ; enter N days"""
)
mock_handle_error.assert_called_once_with(expected)
def test_next_scheduled_date_scheduler_exception_return_value():
schedulefile_data = ";; scheduler enter 567 days"
with FT.temp_file(schedulefile_data) as tempfilename:
assert ledgerbil.main(["--schedule", tempfilename, "-n"]) == ERROR_RETURN_VALUE
@mock.patch(__name__ + ".scheduler.handle_error")
<|code_end|>
with the help of current file imports:
from datetime import date
from textwrap import dedent
from unittest import mock
from dateutil.relativedelta import relativedelta
from ..ledgerbilexceptions import ERROR_RETURN_VALUE
from . import filetester as FT
from .helpers import Redirector
from .test_schedulefile import schedule_testdata
from .. import ( # noqa: F401 (stuff used in patches) isort:skip
ledgerbil,
reconciler,
scheduler,
settings,
settings_getter,
util,
)
import pytest
and context from other files:
# Path: ledgerbil/ledgerbilexceptions.py
# ERROR_RETURN_VALUE = 1
#
# Path: ledgerbil/tests/helpers.py
# class Redirector(TestCase):
# def setUp(self):
# self.savestdout = sys.stdout
# self.reset_redirect()
#
# self.savestderr = sys.stderr
# self.reset_err_redirect()
#
# def tearDown(self):
# self.redirect.close()
# sys.stdout = self.savestdout
#
# self.redirecterr.close()
# sys.stderr = self.savestderr
#
# def reset_redirect(self):
# self.redirect = StringIO()
# sys.stdout = self.redirect
#
# def reset_err_redirect(self):
# self.redirecterr = StringIO()
# sys.stderr = self.redirecterr
#
# Path: ledgerbil/tests/test_schedulefile.py
# def test_next_scheduled_transaction():
# def test_next_scheduled_transaction_no_next():
# def test_add_thing_with_no_lines():
, which may contain function names, class names, or code. Output only the next line. | def test_scheduler_exception(mock_handle_error): |
Given the following code snippet before the placeholder: <|code_start|> # Many queries with no results will come up empty on period names and
# return above, but some, for example queries with "and" in them, may not
if not row_headers:
return ""
rows = get_rows(
row_headers,
columns,
period_names,
args.sort,
args.limit_rows,
args.total_only,
no_total=args.networth,
)
# Move account/payee name to first column for csv and/or transpose
# - Makes more sense for csv/spreadsheet
# - Positions for move to top in transpose
# - But we'll move back to right side for transposed flat report to
# avoid a bunch of complications from handling differently there
if args.csv or args.transpose:
for row in rows:
row.insert(0, row.pop())
if args.transpose:
rows = list(map(list, zip(*rows)))
if args.csv:
return get_csv_report(rows, tabs=args.tab)
<|code_end|>
, predict the next line using imports from the current file:
import argparse
import csv
import re
import sys
from collections import defaultdict
from concurrent import futures
from datetime import date
from io import StringIO
from textwrap import dedent
from dateutil.relativedelta import relativedelta
from .. import util
from ..colorable import Colorable
from ..settings_getter import get_setting
from ..util import get_date, parse_args
from .runner import get_ledger_output
from .util import get_account_balance, get_first_dollar_amount_float, get_payee_subtotal
and context including class names, function names, and sometimes code from other files:
# Path: ledgerbil/colorable.py
# class Colorable:
#
# START_CODE = "\033"
# END_CODE = f"{START_CODE}[0m"
#
# BRIGHT_OFFSET = 60
#
# COLORS = {
# "black": 30,
# "gray": 30,
# "grey": 30,
# "red": 31,
# "green": 32,
# "yellow": 33,
# "blue": 34,
# "magenta": 35,
# "purple": 35,
# "cyan": 36,
# "white": 37,
# }
#
# ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
#
# def __init__(self, color, value, fmt="", bright=False):
#
# if color not in self.COLORS:
# raise UnsupportedColorError(
# f"I don't know what to do with this color: {color}"
# )
#
# self.my_color = color
# self.value = value
# self.bright = bright
# self.format_string = fmt
#
# def __repr__(self):
# return (
# f"Colorable('{self.my_color}', '{self.value}', "
# f"fmt='{self.format_string}', bright={self.bright})"
# )
#
# def __str__(self):
# start = self.ansi_sequence(self.COLORS[self.my_color], bright=self.bright)
# ansi_str = f"{start}{self.value:{self.format_string}}{self.END_CODE}"
# return ansi_str
#
# def __len__(self):
# return len(self.value)
#
# def __eq__(self, other):
# return str(self) == str(other)
#
# def ansi_sequence(self, code, bright=False):
# offset = 60 if bright else 0
# color = code + offset
# return f"{self.START_CODE}[0;{color}m"
#
# def plain(self):
# return self.value
#
# @staticmethod
# def get_plain_string(ansi_string):
# return Colorable.ansi_escape.sub("", ansi_string)
#
# Path: ledgerbil/settings_getter.py
# def get_setting(setting, default=None):
# if settings and hasattr(settings, setting):
# return getattr(settings, setting)
#
# return defaults.get(setting, default)
#
# Path: ledgerbil/util.py
# def get_date(date_string, the_format=None):
# if not the_format:
# the_format = get_setting("DATE_FORMAT")
# return datetime.strptime(date_string, the_format).date()
#
# def parse_args(args):
# # args should be a string, but we'll make sure it isn't None
# # (which would cause the string to be read from stdin)
# try:
# return shlex.split(args or "")
# except ValueError as e:
# print(f"*** {e}")
# return None
#
# Path: ledgerbil/ledgershell/runner.py
# def get_ledger_output(args=None):
# cmd = get_ledger_command(args)
# process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
# output, _ = process.communicate()
# return output.decode("unicode_escape").rstrip()
#
# Path: ledgerbil/ledgershell/util.py
# def get_account_balance(line, shares=False, strip_account=True):
# if shares:
# match = SHARES_REGEX.match(line)
# if match:
# amount, symbol, account = match.groups()
# else:
# match = DOLLARS_REGEX.match(line)
# if match:
# amount, account = match.groups()
# symbol = "$"
#
# if not match:
# return None
#
# return AccountBalance(
# account.strip() if strip_account else account, get_float(amount), symbol
# )
#
# def get_first_dollar_amount_float(line):
# DOLLARS = 0
# match = FIRST_DOLLAR_AMOUNT_REGEX.match(line)
# if match:
# return get_float(match.groups()[DOLLARS])
# return None
#
# def get_payee_subtotal(line):
# DOLLARS = 0
# match = PAYEE_SUBTOTAL_REGEX.match(line)
# if match:
# return get_float(match.groups()[DOLLARS])
# return None
. Output only the next line. | if args.transpose: |
Predict the next line for this snippet: <|code_start|> the_header.append(first_part)
for part in parts:
if len("".join(row_in_progress + [part.rstrip()])) <= padded_width:
row_in_progress.append(part)
else:
if row_in_progress:
the_header.append("".join(row_in_progress).strip())
if len(part.rstrip()) > padded_width:
part = f"{part[:padded_width - 1]}{TRUNC_CHAR}"
row_in_progress = [part]
the_header.append("".join(row_in_progress).strip())
header_lists.append(the_header)
# pad header row lists so they're all the same length
longest_list = max(len(hlist) for hlist in header_lists)
for header_list in header_lists:
for _ in range(longest_list - len(header_list)):
header_list.insert(0, "")
return header_lists
def get_period_names(args, ledger_args, unit="year"):
# --collapse behavior seems suspicous, but with --empty
# appears to work for our purposes here
# groups.google.com/forum/?fromgroups=#!topic/ledger-cli/HAKAMYiaL7w
begin = ("--begin", args.begin) if args.begin else ()
<|code_end|>
with the help of current file imports:
import argparse
import csv
import re
import sys
from collections import defaultdict
from concurrent import futures
from datetime import date
from io import StringIO
from textwrap import dedent
from dateutil.relativedelta import relativedelta
from .. import util
from ..colorable import Colorable
from ..settings_getter import get_setting
from ..util import get_date, parse_args
from .runner import get_ledger_output
from .util import get_account_balance, get_first_dollar_amount_float, get_payee_subtotal
and context from other files:
# Path: ledgerbil/colorable.py
# class Colorable:
#
# START_CODE = "\033"
# END_CODE = f"{START_CODE}[0m"
#
# BRIGHT_OFFSET = 60
#
# COLORS = {
# "black": 30,
# "gray": 30,
# "grey": 30,
# "red": 31,
# "green": 32,
# "yellow": 33,
# "blue": 34,
# "magenta": 35,
# "purple": 35,
# "cyan": 36,
# "white": 37,
# }
#
# ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
#
# def __init__(self, color, value, fmt="", bright=False):
#
# if color not in self.COLORS:
# raise UnsupportedColorError(
# f"I don't know what to do with this color: {color}"
# )
#
# self.my_color = color
# self.value = value
# self.bright = bright
# self.format_string = fmt
#
# def __repr__(self):
# return (
# f"Colorable('{self.my_color}', '{self.value}', "
# f"fmt='{self.format_string}', bright={self.bright})"
# )
#
# def __str__(self):
# start = self.ansi_sequence(self.COLORS[self.my_color], bright=self.bright)
# ansi_str = f"{start}{self.value:{self.format_string}}{self.END_CODE}"
# return ansi_str
#
# def __len__(self):
# return len(self.value)
#
# def __eq__(self, other):
# return str(self) == str(other)
#
# def ansi_sequence(self, code, bright=False):
# offset = 60 if bright else 0
# color = code + offset
# return f"{self.START_CODE}[0;{color}m"
#
# def plain(self):
# return self.value
#
# @staticmethod
# def get_plain_string(ansi_string):
# return Colorable.ansi_escape.sub("", ansi_string)
#
# Path: ledgerbil/settings_getter.py
# def get_setting(setting, default=None):
# if settings and hasattr(settings, setting):
# return getattr(settings, setting)
#
# return defaults.get(setting, default)
#
# Path: ledgerbil/util.py
# def get_date(date_string, the_format=None):
# if not the_format:
# the_format = get_setting("DATE_FORMAT")
# return datetime.strptime(date_string, the_format).date()
#
# def parse_args(args):
# # args should be a string, but we'll make sure it isn't None
# # (which would cause the string to be read from stdin)
# try:
# return shlex.split(args or "")
# except ValueError as e:
# print(f"*** {e}")
# return None
#
# Path: ledgerbil/ledgershell/runner.py
# def get_ledger_output(args=None):
# cmd = get_ledger_command(args)
# process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
# output, _ = process.communicate()
# return output.decode("unicode_escape").rstrip()
#
# Path: ledgerbil/ledgershell/util.py
# def get_account_balance(line, shares=False, strip_account=True):
# if shares:
# match = SHARES_REGEX.match(line)
# if match:
# amount, symbol, account = match.groups()
# else:
# match = DOLLARS_REGEX.match(line)
# if match:
# amount, account = match.groups()
# symbol = "$"
#
# if not match:
# return None
#
# return AccountBalance(
# account.strip() if strip_account else account, get_float(amount), symbol
# )
#
# def get_first_dollar_amount_float(line):
# DOLLARS = 0
# match = FIRST_DOLLAR_AMOUNT_REGEX.match(line)
# if match:
# return get_float(match.groups()[DOLLARS])
# return None
#
# def get_payee_subtotal(line):
# DOLLARS = 0
# match = PAYEE_SUBTOTAL_REGEX.match(line)
# if match:
# return get_float(match.groups()[DOLLARS])
# return None
, which may contain function names, class names, or code. Output only the next line. | end = ("--end", args.end) if args.end else () |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.