Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given snippet: <|code_start|>
# Tilde API demo
# calculates molecular weight for organic molecules
# Author: Evgeny Blokhin
# deps third-party code and common routines
# here are already available:
class Example_app():
'''# this determines how the data should be represented in a table cell
@staticmethod
def cell_wrapper(obj):
selfname = __name__.split('.')[-1]
if not selfname in obj['apps']:
return "—"
return "<i>%s</i>" % obj['apps'][selfname]'''
# this is a main class code
def __init__(self, tilde_calc):
self.weight = 0
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from ase.data import chemical_symbols, atomic_masses
from tilde.core.common import ModuleError
and context:
# Path: tilde/core/common.py
# class ModuleError(Exception):
# def __init__(self, value):
# self.value = value
which might include code, classes, or functions. Output only the next line. | for a in tilde_calc.structures[-1]: |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
logging.basicConfig(level=logging.INFO)
Tilde = API()
USER, PASS = 'test', 'test'
settings['debug_regime'] = False
class TildeGUIProvider:
@staticmethod
def login(req, client_id, db_session):
result, error = None, None
if not isinstance(req, dict): return result, 'Invalid request!'
user = req.get('user')
pwhash = req.get('pass', '')
pwhash = pwhash.encode('ascii')
<|code_end|>
using the current file's imports:
import time
import logging
import bcrypt
import set_path
import tilde.core.model as model
from tornado import web, ioloop
from sockjs.tornado import SockJSRouter
from tilde.core.settings import settings, GUI_URL_TPL
from tilde.core.api import API
from tilde.berlinium import Async_Connection, add_redirection
and any relevant context from other files:
# Path: tilde/core/settings.py
# DB_SCHEMA_VERSION = '5.20'
# SETTINGS_FILE = 'settings.json'
# DEFAULT_SQLITE_DB = 'default.db'
# BASE_DIR = os.path.dirname(os.path.realpath(os.path.abspath(__file__)))
# ROOT_DIR = os.path.normpath(BASE_DIR + '/../')
# DATA_DIR = os.path.join(ROOT_DIR, 'data')
# EXAMPLE_DIR = os.path.join(ROOT_DIR, '../tests/data')
# INIT_DATA = os.path.join(DATA_DIR, 'sql/init-data.sql')
# TEST_DBS_FILE = os.path.join(DATA_DIR, 'test_dbs.txt')
# TEST_DBS_REF_FILE = os.path.join(DATA_DIR, 'test_dbs_ref.txt')
# SETTINGS_PATH = DATA_DIR + os.sep + SETTINGS_FILE
# GUI_URL_TPL = 'http://tilde-lab.github.io/berlinium/?http://127.0.0.1:%s' # ?https://db.tilde.pro
# DEFAULT_SETUP = {
#
# # General part
# 'debug_regime': False, # TODO
# 'log_dir': os.path.join(DATA_DIR, "logs"), # TODO
# 'skip_unfinished': False,
# 'skip_notenergy': False,
# 'skip_if_path': [],
#
# # DB part
# 'db': {
# 'default_sqlite_db': DEFAULT_SQLITE_DB,
# 'engine': 'sqlite', # if sqlite is chosen: further info is not used
# 'host': 'localhost',
# 'port': 5432,
# 'user': 'postgres',
# 'password': '',
# 'dbname': 'tilde'
# },
#
# # Server part
# 'webport': 8070,
# 'title': "Tilde GUI"
# }
# def virtualize_path(item):
# def connect_url(settings, named=None):
# def connect_database(settings, named=None, no_pooling=False, default_actions=True, scoped=False):
# def write_settings(settings):
# def get_hierarchy(settings):
#
# Path: tilde/core/api.py
# API = TildeAPI
. Output only the next line. | pass_match = False |
Given the code snippet: <|code_start|>#!/usr/bin/env python
logging.basicConfig(level=logging.INFO)
Tilde = API()
USER, PASS = 'test', 'test'
settings['debug_regime'] = False
class TildeGUIProvider:
@staticmethod
def login(req, client_id, db_session):
result, error = None, None
if not isinstance(req, dict): return result, 'Invalid request!'
user = req.get('user')
pwhash = req.get('pass', '')
pwhash = pwhash.encode('ascii')
pass_match = False
try: pass_match = (pwhash == bcrypt.hashpw(PASS.encode('ascii'), pwhash))
except: pass
<|code_end|>
, generate the next line using the imports in this file:
import time
import logging
import bcrypt
import set_path
import tilde.core.model as model
from tornado import web, ioloop
from sockjs.tornado import SockJSRouter
from tilde.core.settings import settings, GUI_URL_TPL
from tilde.core.api import API
from tilde.berlinium import Async_Connection, add_redirection
and context (functions, classes, or occasionally code) from other files:
# Path: tilde/core/settings.py
# DB_SCHEMA_VERSION = '5.20'
# SETTINGS_FILE = 'settings.json'
# DEFAULT_SQLITE_DB = 'default.db'
# BASE_DIR = os.path.dirname(os.path.realpath(os.path.abspath(__file__)))
# ROOT_DIR = os.path.normpath(BASE_DIR + '/../')
# DATA_DIR = os.path.join(ROOT_DIR, 'data')
# EXAMPLE_DIR = os.path.join(ROOT_DIR, '../tests/data')
# INIT_DATA = os.path.join(DATA_DIR, 'sql/init-data.sql')
# TEST_DBS_FILE = os.path.join(DATA_DIR, 'test_dbs.txt')
# TEST_DBS_REF_FILE = os.path.join(DATA_DIR, 'test_dbs_ref.txt')
# SETTINGS_PATH = DATA_DIR + os.sep + SETTINGS_FILE
# GUI_URL_TPL = 'http://tilde-lab.github.io/berlinium/?http://127.0.0.1:%s' # ?https://db.tilde.pro
# DEFAULT_SETUP = {
#
# # General part
# 'debug_regime': False, # TODO
# 'log_dir': os.path.join(DATA_DIR, "logs"), # TODO
# 'skip_unfinished': False,
# 'skip_notenergy': False,
# 'skip_if_path': [],
#
# # DB part
# 'db': {
# 'default_sqlite_db': DEFAULT_SQLITE_DB,
# 'engine': 'sqlite', # if sqlite is chosen: further info is not used
# 'host': 'localhost',
# 'port': 5432,
# 'user': 'postgres',
# 'password': '',
# 'dbname': 'tilde'
# },
#
# # Server part
# 'webport': 8070,
# 'title': "Tilde GUI"
# }
# def virtualize_path(item):
# def connect_url(settings, named=None):
# def connect_database(settings, named=None, no_pooling=False, default_actions=True, scoped=False):
# def write_settings(settings):
# def get_hierarchy(settings):
#
# Path: tilde/core/api.py
# API = TildeAPI
. Output only the next line. | if user != USER or not pass_match: |
Continue the code snippet: <|code_start|>
# Calculation of atomic relaxations
# during atomic structure optimization
# Author: Evgeny Blokhin
class Atomic_relaxation():
def __init__(self, tilde_calc):
self.ardata = {}
if len(tilde_calc.structures[0]) != len(tilde_calc.structures[-1]):
raise ModuleError('Different number of atoms before and after optimization!')
for n in range(len(tilde_calc.structures[0])):
# atomic index is counted from zero!
# NB: in case of relaxation is more than a cell vector
# a proper centring must be accounted!
self.ardata[ n+1 ] = round(math.sqrt( \
<|code_end|>
. Use current file imports:
import math
from tilde.core.common import ModuleError
and context (classes, functions, or code) from other files:
# Path: tilde/core/common.py
# class ModuleError(Exception):
# def __init__(self, value):
# self.value = value
. Output only the next line. | (tilde_calc.structures[-1][n].x - tilde_calc.structures[0][n].x)**2 + \ |
Based on the snippet: <|code_start|> Type = 'asynchronous'
Clients = {}
GUIProvider = GUIProviderMockup
def on_open(self, info):
self.Clients[ getattr(self.session, 'session_id', self.session.__hash__()) ] = Client()
logging.info("Server connected %s-th client" % len(self.Clients))
def on_message(self, message):
logging.debug("Server got: %s" % message)
try:
message = json.loads(message)
message.get('act')
except: return self.send(json.dumps({'act':'login', 'error':'Not a valid JSON!'}))
frame = {
'client_id': getattr(self.session, 'session_id', self.session.__hash__()),
'act': message.get('act', 'unknown'),
'req': message.get('req', ''),
'error': '',
'result': ''
}
# security check: a client must be authorized
if not self.Clients[frame['client_id']].authorized and frame['act'] != 'login': return self.close()
if not hasattr(self.GUIProvider, frame['act']):
frame['error'] = 'No server handler for action: %s' % frame['act']
return self.respond(frame)
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
import multiprocessing
import ujson as json
from functools import partial
from concurrent.futures import ThreadPoolExecutor
from tornado import ioloop
from sockjs.tornado import SockJSConnection
from tilde.berlinium.impl import GUIProviderMockup, Client
from tilde.core.settings import settings, connect_database
and context (classes, functions, sometimes code) from other files:
# Path: tilde/berlinium/impl.py
# class GUIProviderMockup:
# pass
#
# class Client:
# def __init__(self):
# self.usettings = {}
# self.authorized = False
# self.db = None
#
# Path: tilde/core/settings.py
# DB_SCHEMA_VERSION = '5.20'
# SETTINGS_FILE = 'settings.json'
# DEFAULT_SQLITE_DB = 'default.db'
# BASE_DIR = os.path.dirname(os.path.realpath(os.path.abspath(__file__)))
# ROOT_DIR = os.path.normpath(BASE_DIR + '/../')
# DATA_DIR = os.path.join(ROOT_DIR, 'data')
# EXAMPLE_DIR = os.path.join(ROOT_DIR, '../tests/data')
# INIT_DATA = os.path.join(DATA_DIR, 'sql/init-data.sql')
# TEST_DBS_FILE = os.path.join(DATA_DIR, 'test_dbs.txt')
# TEST_DBS_REF_FILE = os.path.join(DATA_DIR, 'test_dbs_ref.txt')
# SETTINGS_PATH = DATA_DIR + os.sep + SETTINGS_FILE
# GUI_URL_TPL = 'http://tilde-lab.github.io/berlinium/?http://127.0.0.1:%s' # ?https://db.tilde.pro
# DEFAULT_SETUP = {
#
# # General part
# 'debug_regime': False, # TODO
# 'log_dir': os.path.join(DATA_DIR, "logs"), # TODO
# 'skip_unfinished': False,
# 'skip_notenergy': False,
# 'skip_if_path': [],
#
# # DB part
# 'db': {
# 'default_sqlite_db': DEFAULT_SQLITE_DB,
# 'engine': 'sqlite', # if sqlite is chosen: further info is not used
# 'host': 'localhost',
# 'port': 5432,
# 'user': 'postgres',
# 'password': '',
# 'dbname': 'tilde'
# },
#
# # Server part
# 'webport': 8070,
# 'title': "Tilde GUI"
# }
# def virtualize_path(item):
# def connect_url(settings, named=None):
# def connect_database(settings, named=None, no_pooling=False, default_actions=True, scoped=False):
# def write_settings(settings):
# def get_hierarchy(settings):
. Output only the next line. | def worker(frame): |
Next line prediction: <|code_start|>
# implementation of thread pool for asynchronous websocket connections
# with dynamically re-created DB sessions
thread_pool = ThreadPoolExecutor(max_workers=4*multiprocessing.cpu_count())
class Connection(SockJSConnection):
Type = 'asynchronous'
Clients = {}
GUIProvider = GUIProviderMockup
def on_open(self, info):
self.Clients[ getattr(self.session, 'session_id', self.session.__hash__()) ] = Client()
logging.info("Server connected %s-th client" % len(self.Clients))
def on_message(self, message):
logging.debug("Server got: %s" % message)
try:
<|code_end|>
. Use current file imports:
(import logging
import multiprocessing
import ujson as json
from functools import partial
from concurrent.futures import ThreadPoolExecutor
from tornado import ioloop
from sockjs.tornado import SockJSConnection
from tilde.berlinium.impl import GUIProviderMockup, Client
from tilde.core.settings import settings, connect_database)
and context including class names, function names, or small code snippets from other files:
# Path: tilde/berlinium/impl.py
# class GUIProviderMockup:
# pass
#
# class Client:
# def __init__(self):
# self.usettings = {}
# self.authorized = False
# self.db = None
#
# Path: tilde/core/settings.py
# DB_SCHEMA_VERSION = '5.20'
# SETTINGS_FILE = 'settings.json'
# DEFAULT_SQLITE_DB = 'default.db'
# BASE_DIR = os.path.dirname(os.path.realpath(os.path.abspath(__file__)))
# ROOT_DIR = os.path.normpath(BASE_DIR + '/../')
# DATA_DIR = os.path.join(ROOT_DIR, 'data')
# EXAMPLE_DIR = os.path.join(ROOT_DIR, '../tests/data')
# INIT_DATA = os.path.join(DATA_DIR, 'sql/init-data.sql')
# TEST_DBS_FILE = os.path.join(DATA_DIR, 'test_dbs.txt')
# TEST_DBS_REF_FILE = os.path.join(DATA_DIR, 'test_dbs_ref.txt')
# SETTINGS_PATH = DATA_DIR + os.sep + SETTINGS_FILE
# GUI_URL_TPL = 'http://tilde-lab.github.io/berlinium/?http://127.0.0.1:%s' # ?https://db.tilde.pro
# DEFAULT_SETUP = {
#
# # General part
# 'debug_regime': False, # TODO
# 'log_dir': os.path.join(DATA_DIR, "logs"), # TODO
# 'skip_unfinished': False,
# 'skip_notenergy': False,
# 'skip_if_path': [],
#
# # DB part
# 'db': {
# 'default_sqlite_db': DEFAULT_SQLITE_DB,
# 'engine': 'sqlite', # if sqlite is chosen: further info is not used
# 'host': 'localhost',
# 'port': 5432,
# 'user': 'postgres',
# 'password': '',
# 'dbname': 'tilde'
# },
#
# # Server part
# 'webport': 8070,
# 'title': "Tilde GUI"
# }
# def virtualize_path(item):
# def connect_url(settings, named=None):
# def connect_database(settings, named=None, no_pooling=False, default_actions=True, scoped=False):
# def write_settings(settings):
# def get_hierarchy(settings):
. Output only the next line. | message = json.loads(message) |
Continue the code snippet: <|code_start|> if not self.Clients[frame['client_id']].authorized and frame['act'] != 'login': return self.close()
if not hasattr(self.GUIProvider, frame['act']):
frame['error'] = 'No server handler for action: %s' % frame['act']
return self.respond(frame)
def worker(frame):
db_session = connect_database(settings, default_actions=False, no_pooling=True)
logging.debug("New DB connection to %s" % (
settings['db']['default_sqlite_db']
if settings['db']['engine'] == 'sqlite'
else settings['db']['dbname'] + '@' + settings['db']['engine']
))
frame['result'], frame['error'] = getattr(self.GUIProvider, frame['act'])( frame['req'], frame['client_id'], db_session )
# must explicitly close db connection inside a thread
db_session.close()
del db_session
logging.debug("DB connection closed")
return frame
def callback(res):
return self.respond(res.result())
thread_pool.submit( partial(worker, frame) ).add_done_callback(
lambda future: ioloop.IOLoop.instance().add_callback(
partial(callback, future)
)
<|code_end|>
. Use current file imports:
import logging
import multiprocessing
import ujson as json
from functools import partial
from concurrent.futures import ThreadPoolExecutor
from tornado import ioloop
from sockjs.tornado import SockJSConnection
from tilde.berlinium.impl import GUIProviderMockup, Client
from tilde.core.settings import settings, connect_database
and context (classes, functions, or code) from other files:
# Path: tilde/berlinium/impl.py
# class GUIProviderMockup:
# pass
#
# class Client:
# def __init__(self):
# self.usettings = {}
# self.authorized = False
# self.db = None
#
# Path: tilde/core/settings.py
# DB_SCHEMA_VERSION = '5.20'
# SETTINGS_FILE = 'settings.json'
# DEFAULT_SQLITE_DB = 'default.db'
# BASE_DIR = os.path.dirname(os.path.realpath(os.path.abspath(__file__)))
# ROOT_DIR = os.path.normpath(BASE_DIR + '/../')
# DATA_DIR = os.path.join(ROOT_DIR, 'data')
# EXAMPLE_DIR = os.path.join(ROOT_DIR, '../tests/data')
# INIT_DATA = os.path.join(DATA_DIR, 'sql/init-data.sql')
# TEST_DBS_FILE = os.path.join(DATA_DIR, 'test_dbs.txt')
# TEST_DBS_REF_FILE = os.path.join(DATA_DIR, 'test_dbs_ref.txt')
# SETTINGS_PATH = DATA_DIR + os.sep + SETTINGS_FILE
# GUI_URL_TPL = 'http://tilde-lab.github.io/berlinium/?http://127.0.0.1:%s' # ?https://db.tilde.pro
# DEFAULT_SETUP = {
#
# # General part
# 'debug_regime': False, # TODO
# 'log_dir': os.path.join(DATA_DIR, "logs"), # TODO
# 'skip_unfinished': False,
# 'skip_notenergy': False,
# 'skip_if_path': [],
#
# # DB part
# 'db': {
# 'default_sqlite_db': DEFAULT_SQLITE_DB,
# 'engine': 'sqlite', # if sqlite is chosen: further info is not used
# 'host': 'localhost',
# 'port': 5432,
# 'user': 'postgres',
# 'password': '',
# 'dbname': 'tilde'
# },
#
# # Server part
# 'webport': 8070,
# 'title': "Tilde GUI"
# }
# def virtualize_path(item):
# def connect_url(settings, named=None):
# def connect_database(settings, named=None, no_pooling=False, default_actions=True, scoped=False):
# def write_settings(settings):
# def get_hierarchy(settings):
. Output only the next line. | ) |
Continue the code snippet: <|code_start|> GUIProvider = GUIProviderMockup
def on_open(self, info):
self.Clients[ getattr(self.session, 'session_id', self.session.__hash__()) ] = Client()
logging.info("Server connected %s-th client" % len(self.Clients))
def on_message(self, message):
logging.debug("Server got: %s" % message)
try:
message = json.loads(message)
message.get('act')
except: return self.send(json.dumps({'act':'login', 'error':'Not a valid JSON!'}))
frame = {
'client_id': getattr(self.session, 'session_id', self.session.__hash__()),
'act': message.get('act', 'unknown'),
'req': message.get('req', ''),
'error': '',
'result': ''
}
# security check: a client must be authorized
if not self.Clients[frame['client_id']].authorized and frame['act'] != 'login': return self.close()
if not hasattr(self.GUIProvider, frame['act']):
frame['error'] = 'No server handler for action: %s' % frame['act']
return self.respond(frame)
def worker(frame):
db_session = connect_database(settings, default_actions=False, no_pooling=True)
<|code_end|>
. Use current file imports:
import logging
import multiprocessing
import ujson as json
from functools import partial
from concurrent.futures import ThreadPoolExecutor
from tornado import ioloop
from sockjs.tornado import SockJSConnection
from tilde.berlinium.impl import GUIProviderMockup, Client
from tilde.core.settings import settings, connect_database
and context (classes, functions, or code) from other files:
# Path: tilde/berlinium/impl.py
# class GUIProviderMockup:
# pass
#
# class Client:
# def __init__(self):
# self.usettings = {}
# self.authorized = False
# self.db = None
#
# Path: tilde/core/settings.py
# DB_SCHEMA_VERSION = '5.20'
# SETTINGS_FILE = 'settings.json'
# DEFAULT_SQLITE_DB = 'default.db'
# BASE_DIR = os.path.dirname(os.path.realpath(os.path.abspath(__file__)))
# ROOT_DIR = os.path.normpath(BASE_DIR + '/../')
# DATA_DIR = os.path.join(ROOT_DIR, 'data')
# EXAMPLE_DIR = os.path.join(ROOT_DIR, '../tests/data')
# INIT_DATA = os.path.join(DATA_DIR, 'sql/init-data.sql')
# TEST_DBS_FILE = os.path.join(DATA_DIR, 'test_dbs.txt')
# TEST_DBS_REF_FILE = os.path.join(DATA_DIR, 'test_dbs_ref.txt')
# SETTINGS_PATH = DATA_DIR + os.sep + SETTINGS_FILE
# GUI_URL_TPL = 'http://tilde-lab.github.io/berlinium/?http://127.0.0.1:%s' # ?https://db.tilde.pro
# DEFAULT_SETUP = {
#
# # General part
# 'debug_regime': False, # TODO
# 'log_dir': os.path.join(DATA_DIR, "logs"), # TODO
# 'skip_unfinished': False,
# 'skip_notenergy': False,
# 'skip_if_path': [],
#
# # DB part
# 'db': {
# 'default_sqlite_db': DEFAULT_SQLITE_DB,
# 'engine': 'sqlite', # if sqlite is chosen: further info is not used
# 'host': 'localhost',
# 'port': 5432,
# 'user': 'postgres',
# 'password': '',
# 'dbname': 'tilde'
# },
#
# # Server part
# 'webport': 8070,
# 'title': "Tilde GUI"
# }
# def virtualize_path(item):
# def connect_url(settings, named=None):
# def connect_database(settings, named=None, no_pooling=False, default_actions=True, scoped=False):
# def write_settings(settings):
# def get_hierarchy(settings):
. Output only the next line. | logging.debug("New DB connection to %s" % ( |
Predict the next line after this snippet: <|code_start|>
# Tilde project: plotting interfaces
# for flot.js browser-side plotting library
# Author: Evgeny Blokhin
def frac2float(num):
if '/' in str(num):
fract = map(float, num.split('/'))
return fract[0] / fract[1]
return float(num)
def jmol_to_hex(ase_jmol):
<|code_end|>
using the current file's imports:
import math
from numpy import dot, array, linalg, arange
from tilde.berlinium.cubicspline import NaturalCubicSpline
from tilde.berlinium.dos import TotalDos, PartialDos
from ase.data.colors import jmol_colors
from ase.data import chemical_symbols
and any relevant context from other files:
# Path: tilde/berlinium/dos.py
# class TotalDos(Dos):
# def __init__(self, eigenvalues, sigma=None):
# Dos.__init__(self, eigenvalues, sigma)
#
# def get_density_of_states_at_omega(self, omega):
# return np.sum( self.smearing_function.calc(self.eigenvalues - omega))
#
# def calculate(self):
# omega = self.omega_min
# dos = []
#
# if self.omega_pitch == 0: self.omega_pitch = 1 # beware of endless loop if omega_pitch=0
# while omega < self.omega_max + self.omega_pitch/10 :
# p = self.get_density_of_states_at_omega(omega)
# dos.append( [round(omega, 3), round(p, 3)] ) # round to reduce output
# omega += self.omega_pitch
# return dos
#
# class PartialDos(Dos):
# # eigenvalues and impacts must be unique and one-to-one correspondent
# def __init__(self, eigenvalues, impacts, sigma=None):
# Dos.__init__(self, eigenvalues, sigma)
# self.impacts = np.array(impacts)
#
# def get_partial_dos_impact_at_omega(self, omega):
# # function for obtaining scaled partial impacts in any omega point using a linear equation interpolation
# if omega in self.eigenvalues:
# return self.impacts[ np.where(self.eigenvalues == omega)[0][0] ]
# if omega < self.eigenvalues[0]:
# return np.zeros( len(self.impacts[0]) )
# elif omega > self.eigenvalues[-1]:
# return self.impacts[-1]
# else:
# for n in range(len(self.eigenvalues)):
# if n < len(self.eigenvalues) and self.eigenvalues[n] < omega < self.eigenvalues[n+1]:
# result = (omega - self.eigenvalues[n])*(self.impacts[n+1] - self.impacts[n])/(self.eigenvalues[n+1] - self.eigenvalues[n]) + self.impacts[n]
# return result
#
# def calculate(self, types, labels):
# omega = self.omega_min
# pdos = []
# omegas = []
#
# plots = []
#
# if self.omega_pitch == 0: self.omega_pitch = 1 # beware of endless loop if omega_pitch=0
# while omega < self.omega_max + self.omega_pitch/10:
# partial = self.get_partial_dos_impact_at_omega(omega) * np.sum( self.smearing_function.calc(self.eigenvalues - omega) )
# omegas.append( omega )
# pdos.append( partial )
# omega += self.omega_pitch
# partial_dos = np.array(pdos).transpose()
# omegas = np.array(omegas)
#
# for n, set_for_sum in enumerate(types):
# atom = [k for k, v in labels.iteritems() if v == n][0] # find k by v
#
# multdos = 1
# #if atom != 'Fe': continue
# #else: multdos = 3
#
# pdos_sum = np.zeros(omegas.shape, dtype=float)
# for i in set_for_sum:
# pdos_sum += multdos * partial_dos[(i-1):i].sum(axis=0)
# plots.append( {'label': atom, 'data': [ [ round(omegas[n], 3), round(i, 3) ] for n, i in enumerate(pdos_sum.tolist()) ]} ) # round to reduce output
# return plots
. Output only the next line. | r, g, b = map(lambda x: x*255, ase_jmol) |
Predict the next line for this snippet: <|code_start|> __tablename__ = 'electrons'
checksum = Column(String, ForeignKey('calculations.checksum'), primary_key=True)
gap = Column(Float, default=None)
is_direct = Column(Integer, default=0)
class Phonons(Base):
__tablename__ = 'phonons'
checksum = Column(String, ForeignKey('calculations.checksum'), primary_key=True)
class Spectra(Base):
__tablename__ = 'spectra'
checksum = Column(String, ForeignKey('calculations.checksum'), primary_key=True)
ELECTRON = 'ELECTRON'
PHONON = 'PHONON'
kind = Column(Enum(ELECTRON, PHONON, name='spectrum_kind_enum'), primary_key=True)
dos = Column(JSONString, default=None)
bands = Column(JSONString, default=None)
projected = Column(JSONString, default=None)
eigenvalues = Column(JSONString, default=None)
class Forces(Base):
__tablename__ = 'forces'
checksum = Column(String, ForeignKey('calculations.checksum'), primary_key=True)
content = Column(JSONString, nullable=False)
class Structure(Base):
__tablename__ = 'structures'
struct_id = Column(Integer, primary_key=True)
checksum = Column(String, ForeignKey('calculations.checksum'), nullable=False)
step = Column(Integer, nullable=False)
<|code_end|>
with the help of current file imports:
import logging
import datetime
import six
import ujson as json
from collections import namedtuple
from tilde.core.orm_tools import UniqueMixin, get_or_create, correct_topics
from sqlalchemy import and_, or_, Index, UniqueConstraint, MetaData, String, UnicodeText, Table, Column, Boolean, Float, Integer, BigInteger, Enum, Text, Date, DateTime, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.ext.declarative import DeclarativeMeta, declarative_base
from sqlalchemy.sql.expression import insert, delete
from sqlalchemy import UnicodeText as JSONString
from sqlalchemy import LargeBinary as JSONString
and context from other files:
# Path: tilde/core/orm_tools.py
# class UniqueMixin(object):
# @classmethod
# def unique_filter(cls, query, *arg, **kw):
# raise NotImplementedError()
#
# @classmethod
# def as_unique(cls, session, *arg, **kw):
# return _unique(session, cls, cls.unique_filter, cls, arg, kw)
#
# @classmethod
# def as_unique_todict(cls, session, *arg, **kw):
# return _unique_todict(session, cls, cls.unique_filter, arg, kw)
#
# def get_or_create(cls, session, defaults=None, **kwds):
# result = session.query(cls).filter_by(**kwds).first()
# if result:
# return result, False
# new_vals = defaults
# if defaults is None:
# new_vals = {}
# new_vals.update(kwds)
# result = cls(**new_vals)
# session.add(result)
# session.flush()
# return result, True
#
# def correct_topics(session, model, calc_id, cid, new_topics, mode, topics_hierarchy):
# assert model.Calculation.__tablename__
#
# found_entity = None
# for e in topics_hierarchy:
# if e['cid'] == cid:
# found_entity = e
# break
# assert found_entity, "Wrong topic identifier!"
#
# if isinstance(calc_id, str):
# calc_id = [calc_id]
# assert isinstance(calc_id, list)
# if isinstance(new_topics, str):
# new_topics = [new_topics]
# assert isinstance(new_topics, list)
#
# if mode == 'REPLACE':
# _replace_topics(session, model, calc_id, cid, new_topics)
# elif mode == 'APPEND':
# assert found_entity.get('multiple', False)
# _append_topics(session, model, calc_id, cid, new_topics)
, which may contain function names, class names, or code. Output only the next line. | final = Column(Boolean, nullable=False) |
Given snippet: <|code_start|>START_TIME = time.time()
USER, PASS = 'test', 'test'
class RespHandler(object):
@classmethod
def on_error(self, ws, error):
logging.error(error)
@classmethod
def on_close(self, ws):
logging.debug("Closed")
ws.close()
@classmethod
def on_open(self, ws):
logging.debug("Opened")
pwhash = bcrypt.hashpw(PASS.encode('ascii'), bcrypt.gensalt())
ws.send(json.dumps({'act': 'login', 'req': {'user': USER, 'pass': pwhash}}))
@classmethod
def on_message(self, ws, message):
logging.debug("Received: %s" % message[:100])
message = json.loads(message)
if message['act'] == 'login':
if message['result'] == 'OK':
ws.send(json.dumps({'act': 'sleep', 'req': 3}))
else:
logging.error("Auth failed!")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
import time
import logging
import bcrypt
import websocket
try: import ujson as json
except ImportError: import json
import set_path
from tilde.core.settings import settings
and context:
# Path: tilde/core/settings.py
# DB_SCHEMA_VERSION = '5.20'
# SETTINGS_FILE = 'settings.json'
# DEFAULT_SQLITE_DB = 'default.db'
# BASE_DIR = os.path.dirname(os.path.realpath(os.path.abspath(__file__)))
# ROOT_DIR = os.path.normpath(BASE_DIR + '/../')
# DATA_DIR = os.path.join(ROOT_DIR, 'data')
# EXAMPLE_DIR = os.path.join(ROOT_DIR, '../tests/data')
# INIT_DATA = os.path.join(DATA_DIR, 'sql/init-data.sql')
# TEST_DBS_FILE = os.path.join(DATA_DIR, 'test_dbs.txt')
# TEST_DBS_REF_FILE = os.path.join(DATA_DIR, 'test_dbs_ref.txt')
# SETTINGS_PATH = DATA_DIR + os.sep + SETTINGS_FILE
# GUI_URL_TPL = 'http://tilde-lab.github.io/berlinium/?http://127.0.0.1:%s' # ?https://db.tilde.pro
# DEFAULT_SETUP = {
#
# # General part
# 'debug_regime': False, # TODO
# 'log_dir': os.path.join(DATA_DIR, "logs"), # TODO
# 'skip_unfinished': False,
# 'skip_notenergy': False,
# 'skip_if_path': [],
#
# # DB part
# 'db': {
# 'default_sqlite_db': DEFAULT_SQLITE_DB,
# 'engine': 'sqlite', # if sqlite is chosen: further info is not used
# 'host': 'localhost',
# 'port': 5432,
# 'user': 'postgres',
# 'password': '',
# 'dbname': 'tilde'
# },
#
# # Server part
# 'webport': 8070,
# 'title': "Tilde GUI"
# }
# def virtualize_path(item):
# def connect_url(settings, named=None):
# def connect_database(settings, named=None, no_pooling=False, default_actions=True, scoped=False):
# def write_settings(settings):
# def get_hierarchy(settings):
which might include code, classes, or functions. Output only the next line. | sys.exit(1) |
Next line prediction: <|code_start|> #print 'corners:', [i+1 for i in octahedron[1]]
# Option 1. Extract only one tilting plane, the closest to perpendicular to Z-axis
'''tiltplane = self.get_tiltplane(octahedron[1])
if len(tiltplane) == 4:
t = self.get_tilting(tiltplane)
#print 'result:', [i+1 for i in tiltplane], t
self.prec_angles.update( { octahedron[0]: [ t ] } )'''
# Option 2. Extract all three possible tilting planes,
# try to spot the closest to perpendicular to Z-axis
# and consider the smallest tilting
plane_tilting = []
for oplane in self.get_tiltplanes(octahedron[1]):
t = self.get_tilting(oplane)
#print "result:", [i+1 for i in oplane], t
plane_tilting.append( t )
self.prec_angles.update( { octahedron[0]: plane_tilting } )
if not self.prec_angles: raise ModuleError("Cannot find any main tilting plane!")
# uniquify and round self.prec_angles to obtain self.angles
u, todel = [], []
for o in self.prec_angles:
self.prec_angles[o] = reduce(lambda x, y: x if sum(x) <= sum(y) else y, self.prec_angles[o]) # only minimal angles are taken if tilting planes vary!
self.prec_angles[o] = list(map(lambda x: list(map(lambda y: round(y, 2), x)), [self.prec_angles[o]])) # Py3
for i in self.prec_angles[o]:
u.append([o] + i)
<|code_end|>
. Use current file imports:
(import math
from functools import reduce
from numpy.linalg import norm
from ase import Atom
from tilde.core.common import ModuleError #, generate_xyz
from tilde.core.constants import Perovskite_Structure
from tilde.core.symmetry import SymmetryFinder)
and context including class names, function names, or small code snippets from other files:
# Path: tilde/core/common.py
# class ModuleError(Exception):
# def __init__(self, value):
# self.value = value
#
# Path: tilde/core/constants.py
# class Perovskite_Structure:
# A = 'Li, Na, K, Rb, Cs, Fr, Mg, Ca, Sr, Ba, Ra, Sc, Sc, Y, La, Ce, Pr, Nd, Pm, Sm, Eu, Gd, Tb, Dy, Ho, Er, Tm, Yb, Lu, Ag, Pb, Bi, Th, In, Mn, Zn'.split(', ')
# B = 'Ti, V, Cr, Mn, Fe, Co, Ni, Cu, Zn, Ga, Zr, Nb, Mo, Tc, Ru, Rh, Pd, Ag, Cd, In, Sn, Sb, Hf, Ta, W, Re, Se, La, Pr, Pb'.split(', ')
# C = 'H, O, F, Cl, Br, I'.split(', ')
#
# Path: tilde/core/symmetry.py
# class SymmetryFinder:
# accuracy = 1e-04
#
# def __init__(self, accuracy=None):
# self.error = None
# self.accuracy=accuracy if accuracy else SymmetryFinder.accuracy
# self.angle_tolerance = -1
#
# def get_spacegroup(self, tilde_obj):
# try:
# symmetry = spg.get_spacegroup(tilde_obj['structures'][-1], symprec=self.accuracy, angle_tolerance=self.angle_tolerance)
# except Exception as ex:
# self.error = 'Symmetry finder error: %s' % ex
# else:
# try:
# self.sg, self.ng = symmetry.split()
# self.ng = int(self.ng.strip("()"))
# except (ValueError, IndexError, AttributeError):
# self.ng = 0
# self.error = 'Symmetry finder error (probably, coinciding atoms)'
#
# def refine_cell(self, tilde_obj):
# '''
# NB only used for perovskite_tilting app
# '''
# try: lattice, positions, numbers = spg.refine_cell(tilde_obj['structures'][-1], symprec=self.accuracy, angle_tolerance=self.angle_tolerance)
# except Exception as ex:
# self.error = 'Symmetry finder error: %s' % ex
# else:
# self.refinedcell = Atoms(numbers=numbers, cell=lattice, scaled_positions=positions, pbc=tilde_obj['structures'][-1].get_pbc())
# self.refinedcell.periodicity = sum(self.refinedcell.get_pbc())
# self.refinedcell.dims = abs(det(tilde_obj['structures'][-1].cell))
. Output only the next line. | u = sorted(u, key=lambda x:x[0]) |
Predict the next line for this snippet: <|code_start|> (reference[num_of_atom].x + a_component * cell[0][0] + b_component * cell[1][0] + c_component * cell[2][0],
reference[num_of_atom].y + a_component * cell[0][1] + b_component * cell[1][1] + c_component * cell[2][1],
reference[num_of_atom].z + a_component * cell[0][2] + b_component * cell[1][2] + c_component * cell[2][2])
))
def get_bisector_point(self, num_of_A, num_of_O, num_of_B, reference):
xA = reference[num_of_A].x
yA = reference[num_of_A].y
zA = reference[num_of_A].z
xO = reference[num_of_O].x
yO = reference[num_of_O].y
zO = reference[num_of_O].z
xB = reference[num_of_B].x
yB = reference[num_of_B].y
zB = reference[num_of_B].z
m = self.virtual_atoms.get_distance(num_of_O, num_of_A)
n = self.virtual_atoms.get_distance(num_of_O, num_of_B)
# bisector length
l = 2 * m * n * math.cos(math.radians(self.virtual_atoms.get_angle(num_of_A, num_of_O, num_of_B) / 2)) / (m + n)
v = math.sqrt(n**2 - n * l**2 / m)
u = m * v / n
A = yA*(zO - zB) + yO*(zB - zA) + yB*(zA - zO)
B = zA*(xO - xB) + zO*(xB - xA) + zB*(xA - xO)
C = xA*(yO - yB) + xO*(yB - yA) + xB*(yA - yO)
if C == 0: C = 1E-10 # prevent zero division
D = xA*(yO*zB - yB*zO) + xO*(yB*zA - yA*zB) + xB*(yA*zO - yO*zA)
D *= -1
# from surface analytical equation
<|code_end|>
with the help of current file imports:
import math
from functools import reduce
from numpy.linalg import norm
from ase import Atom
from tilde.core.common import ModuleError #, generate_xyz
from tilde.core.constants import Perovskite_Structure
from tilde.core.symmetry import SymmetryFinder
and context from other files:
# Path: tilde/core/common.py
# class ModuleError(Exception):
# def __init__(self, value):
# self.value = value
#
# Path: tilde/core/constants.py
# class Perovskite_Structure:
# A = 'Li, Na, K, Rb, Cs, Fr, Mg, Ca, Sr, Ba, Ra, Sc, Sc, Y, La, Ce, Pr, Nd, Pm, Sm, Eu, Gd, Tb, Dy, Ho, Er, Tm, Yb, Lu, Ag, Pb, Bi, Th, In, Mn, Zn'.split(', ')
# B = 'Ti, V, Cr, Mn, Fe, Co, Ni, Cu, Zn, Ga, Zr, Nb, Mo, Tc, Ru, Rh, Pd, Ag, Cd, In, Sn, Sb, Hf, Ta, W, Re, Se, La, Pr, Pb'.split(', ')
# C = 'H, O, F, Cl, Br, I'.split(', ')
#
# Path: tilde/core/symmetry.py
# class SymmetryFinder:
# accuracy = 1e-04
#
# def __init__(self, accuracy=None):
# self.error = None
# self.accuracy=accuracy if accuracy else SymmetryFinder.accuracy
# self.angle_tolerance = -1
#
# def get_spacegroup(self, tilde_obj):
# try:
# symmetry = spg.get_spacegroup(tilde_obj['structures'][-1], symprec=self.accuracy, angle_tolerance=self.angle_tolerance)
# except Exception as ex:
# self.error = 'Symmetry finder error: %s' % ex
# else:
# try:
# self.sg, self.ng = symmetry.split()
# self.ng = int(self.ng.strip("()"))
# except (ValueError, IndexError, AttributeError):
# self.ng = 0
# self.error = 'Symmetry finder error (probably, coinciding atoms)'
#
# def refine_cell(self, tilde_obj):
# '''
# NB only used for perovskite_tilting app
# '''
# try: lattice, positions, numbers = spg.refine_cell(tilde_obj['structures'][-1], symprec=self.accuracy, angle_tolerance=self.angle_tolerance)
# except Exception as ex:
# self.error = 'Symmetry finder error: %s' % ex
# else:
# self.refinedcell = Atoms(numbers=numbers, cell=lattice, scaled_positions=positions, pbc=tilde_obj['structures'][-1].get_pbc())
# self.refinedcell.periodicity = sum(self.refinedcell.get_pbc())
# self.refinedcell.dims = abs(det(tilde_obj['structures'][-1].cell))
, which may contain function names, class names, or code. Output only the next line. | x = (xA + u*xB/v)/(1+u/v) |
Given the code snippet: <|code_start|> #with open('tilting.xyz', 'w') as f:
# f.write(generate_xyz(self.virtual_atoms))
# translate atoms around octahedra in all directions
shift_dirs = [(1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (1, 1, 0), (1, -1, 0), (-1, -1, 0), (-1, 1, 0), (0, 0, 1), (0, 0, -1)]
for k, i in enumerate(symm.refinedcell):
if i.symbol in Perovskite_Structure.C:
for sdir in shift_dirs:
self.translate(k, symm.refinedcell.cell, sdir, self.virtual_atoms)
# extract octahedra and their main tilting planes
for octahedron in self.get_octahedra(symm.refinedcell, symm.refinedcell.periodicity):
#print 'octahedron:', octahedron[0]+1 #, self.virtual_atoms[octahedron[0]].symbol, self.virtual_atoms[octahedron[0]].x, self.virtual_atoms[octahedron[0]].y, self.virtual_atoms[octahedron[0]].z
#print 'corners:', [i+1 for i in octahedron[1]]
# Option 1. Extract only one tilting plane, the closest to perpendicular to Z-axis
'''tiltplane = self.get_tiltplane(octahedron[1])
if len(tiltplane) == 4:
t = self.get_tilting(tiltplane)
#print 'result:', [i+1 for i in tiltplane], t
self.prec_angles.update( { octahedron[0]: [ t ] } )'''
# Option 2. Extract all three possible tilting planes,
# try to spot the closest to perpendicular to Z-axis
# and consider the smallest tilting
plane_tilting = []
for oplane in self.get_tiltplanes(octahedron[1]):
t = self.get_tilting(oplane)
#print "result:", [i+1 for i in oplane], t
<|code_end|>
, generate the next line using the imports in this file:
import math
from functools import reduce
from numpy.linalg import norm
from ase import Atom
from tilde.core.common import ModuleError #, generate_xyz
from tilde.core.constants import Perovskite_Structure
from tilde.core.symmetry import SymmetryFinder
and context (functions, classes, or occasionally code) from other files:
# Path: tilde/core/common.py
# class ModuleError(Exception):
# def __init__(self, value):
# self.value = value
#
# Path: tilde/core/constants.py
# class Perovskite_Structure:
# A = 'Li, Na, K, Rb, Cs, Fr, Mg, Ca, Sr, Ba, Ra, Sc, Sc, Y, La, Ce, Pr, Nd, Pm, Sm, Eu, Gd, Tb, Dy, Ho, Er, Tm, Yb, Lu, Ag, Pb, Bi, Th, In, Mn, Zn'.split(', ')
# B = 'Ti, V, Cr, Mn, Fe, Co, Ni, Cu, Zn, Ga, Zr, Nb, Mo, Tc, Ru, Rh, Pd, Ag, Cd, In, Sn, Sb, Hf, Ta, W, Re, Se, La, Pr, Pb'.split(', ')
# C = 'H, O, F, Cl, Br, I'.split(', ')
#
# Path: tilde/core/symmetry.py
# class SymmetryFinder:
# accuracy = 1e-04
#
# def __init__(self, accuracy=None):
# self.error = None
# self.accuracy=accuracy if accuracy else SymmetryFinder.accuracy
# self.angle_tolerance = -1
#
# def get_spacegroup(self, tilde_obj):
# try:
# symmetry = spg.get_spacegroup(tilde_obj['structures'][-1], symprec=self.accuracy, angle_tolerance=self.angle_tolerance)
# except Exception as ex:
# self.error = 'Symmetry finder error: %s' % ex
# else:
# try:
# self.sg, self.ng = symmetry.split()
# self.ng = int(self.ng.strip("()"))
# except (ValueError, IndexError, AttributeError):
# self.ng = 0
# self.error = 'Symmetry finder error (probably, coinciding atoms)'
#
# def refine_cell(self, tilde_obj):
# '''
# NB only used for perovskite_tilting app
# '''
# try: lattice, positions, numbers = spg.refine_cell(tilde_obj['structures'][-1], symprec=self.accuracy, angle_tolerance=self.angle_tolerance)
# except Exception as ex:
# self.error = 'Symmetry finder error: %s' % ex
# else:
# self.refinedcell = Atoms(numbers=numbers, cell=lattice, scaled_positions=positions, pbc=tilde_obj['structures'][-1].get_pbc())
# self.refinedcell.periodicity = sum(self.refinedcell.get_pbc())
# self.refinedcell.dims = abs(det(tilde_obj['structures'][-1].cell))
. Output only the next line. | plane_tilting.append( t ) |
Given the following code snippet before the placeholder: <|code_start|>
# implementation of blocking websocket connections
# with (customly) pooled DB sessions
class Connection(SockJSConnection):
Type = 'blocking'
Clients = {}
GUIProvider = GUIProviderMockup
def on_open(self, info):
self.Clients[ getattr(self.session, 'session_id', self.session.__hash__()) ] = Client()
logging.info("Server connected %s-th client" % len(self.Clients))
def on_message(self, message):
logging.debug("Server got: %s" % message)
<|code_end|>
, predict the next line using imports from the current file:
import logging
import ujson as json
from tornado import ioloop
from sockjs.tornado import SockJSConnection
from tilde.berlinium.impl import GUIProviderMockup, Client
from tilde.core.settings import settings, connect_database
and context including class names, function names, and sometimes code from other files:
# Path: tilde/berlinium/impl.py
# class GUIProviderMockup:
# pass
#
# class Client:
# def __init__(self):
# self.usettings = {}
# self.authorized = False
# self.db = None
#
# Path: tilde/core/settings.py
# DB_SCHEMA_VERSION = '5.20'
# SETTINGS_FILE = 'settings.json'
# DEFAULT_SQLITE_DB = 'default.db'
# BASE_DIR = os.path.dirname(os.path.realpath(os.path.abspath(__file__)))
# ROOT_DIR = os.path.normpath(BASE_DIR + '/../')
# DATA_DIR = os.path.join(ROOT_DIR, 'data')
# EXAMPLE_DIR = os.path.join(ROOT_DIR, '../tests/data')
# INIT_DATA = os.path.join(DATA_DIR, 'sql/init-data.sql')
# TEST_DBS_FILE = os.path.join(DATA_DIR, 'test_dbs.txt')
# TEST_DBS_REF_FILE = os.path.join(DATA_DIR, 'test_dbs_ref.txt')
# SETTINGS_PATH = DATA_DIR + os.sep + SETTINGS_FILE
# GUI_URL_TPL = 'http://tilde-lab.github.io/berlinium/?http://127.0.0.1:%s' # ?https://db.tilde.pro
# DEFAULT_SETUP = {
#
# # General part
# 'debug_regime': False, # TODO
# 'log_dir': os.path.join(DATA_DIR, "logs"), # TODO
# 'skip_unfinished': False,
# 'skip_notenergy': False,
# 'skip_if_path': [],
#
# # DB part
# 'db': {
# 'default_sqlite_db': DEFAULT_SQLITE_DB,
# 'engine': 'sqlite', # if sqlite is chosen: further info is not used
# 'host': 'localhost',
# 'port': 5432,
# 'user': 'postgres',
# 'password': '',
# 'dbname': 'tilde'
# },
#
# # Server part
# 'webport': 8070,
# 'title': "Tilde GUI"
# }
# def virtualize_path(item):
# def connect_url(settings, named=None):
# def connect_database(settings, named=None, no_pooling=False, default_actions=True, scoped=False):
# def write_settings(settings):
# def get_hierarchy(settings):
. Output only the next line. | try: |
Next line prediction: <|code_start|>
# implementation of blocking websocket connections
# with (customly) pooled DB sessions
class Connection(SockJSConnection):
Type = 'blocking'
Clients = {}
GUIProvider = GUIProviderMockup
def on_open(self, info):
self.Clients[ getattr(self.session, 'session_id', self.session.__hash__()) ] = Client()
logging.info("Server connected %s-th client" % len(self.Clients))
def on_message(self, message):
<|code_end|>
. Use current file imports:
(import logging
import ujson as json
from tornado import ioloop
from sockjs.tornado import SockJSConnection
from tilde.berlinium.impl import GUIProviderMockup, Client
from tilde.core.settings import settings, connect_database)
and context including class names, function names, or small code snippets from other files:
# Path: tilde/berlinium/impl.py
# class GUIProviderMockup:
# pass
#
# class Client:
# def __init__(self):
# self.usettings = {}
# self.authorized = False
# self.db = None
#
# Path: tilde/core/settings.py
# DB_SCHEMA_VERSION = '5.20'
# SETTINGS_FILE = 'settings.json'
# DEFAULT_SQLITE_DB = 'default.db'
# BASE_DIR = os.path.dirname(os.path.realpath(os.path.abspath(__file__)))
# ROOT_DIR = os.path.normpath(BASE_DIR + '/../')
# DATA_DIR = os.path.join(ROOT_DIR, 'data')
# EXAMPLE_DIR = os.path.join(ROOT_DIR, '../tests/data')
# INIT_DATA = os.path.join(DATA_DIR, 'sql/init-data.sql')
# TEST_DBS_FILE = os.path.join(DATA_DIR, 'test_dbs.txt')
# TEST_DBS_REF_FILE = os.path.join(DATA_DIR, 'test_dbs_ref.txt')
# SETTINGS_PATH = DATA_DIR + os.sep + SETTINGS_FILE
# GUI_URL_TPL = 'http://tilde-lab.github.io/berlinium/?http://127.0.0.1:%s' # ?https://db.tilde.pro
# DEFAULT_SETUP = {
#
# # General part
# 'debug_regime': False, # TODO
# 'log_dir': os.path.join(DATA_DIR, "logs"), # TODO
# 'skip_unfinished': False,
# 'skip_notenergy': False,
# 'skip_if_path': [],
#
# # DB part
# 'db': {
# 'default_sqlite_db': DEFAULT_SQLITE_DB,
# 'engine': 'sqlite', # if sqlite is chosen: further info is not used
# 'host': 'localhost',
# 'port': 5432,
# 'user': 'postgres',
# 'password': '',
# 'dbname': 'tilde'
# },
#
# # Server part
# 'webport': 8070,
# 'title': "Tilde GUI"
# }
# def virtualize_path(item):
# def connect_url(settings, named=None):
# def connect_database(settings, named=None, no_pooling=False, default_actions=True, scoped=False):
# def write_settings(settings):
# def get_hierarchy(settings):
. Output only the next line. | logging.debug("Server got: %s" % message) |
Predict the next line after this snippet: <|code_start|>
if not Connection.Clients[frame['client_id']].db:
Connection.Clients[frame['client_id']].db = connect_database(settings, default_actions=False, no_pooling=True)
logging.debug("New DB connection to %s" % (
settings['db']['default_sqlite_db']
if settings['db']['engine'] == 'sqlite'
else settings['db']['dbname'] + '@' + settings['db']['engine']
))
frame['result'], frame['error'] = getattr(self.GUIProvider, frame['act'])( frame['req'], frame['client_id'], Connection.Clients[frame['client_id']].db )
self.respond(frame)
def respond(self, output):
del output['client_id']
if not output['error'] and not output['result']:
output['error'] = "Handler %s has returned an empty result!" % output['act']
logging.debug("Server responds: %s" % output)
self.send(json.dumps(output))
def on_close(self):
logging.info("Server will close connection with %s-th client" % len(self.Clients))
client_id = getattr(self.session, 'session_id', self.session.__hash__())
# must explicitly close db connection
try:
self.Clients[client_id].db.close()
self.Clients[client_id].db = None
logging.debug("DB connection closed")
except: pass
<|code_end|>
using the current file's imports:
import logging
import ujson as json
from tornado import ioloop
from sockjs.tornado import SockJSConnection
from tilde.berlinium.impl import GUIProviderMockup, Client
from tilde.core.settings import settings, connect_database
and any relevant context from other files:
# Path: tilde/berlinium/impl.py
# class GUIProviderMockup:
# pass
#
# class Client:
# def __init__(self):
# self.usettings = {}
# self.authorized = False
# self.db = None
#
# Path: tilde/core/settings.py
# DB_SCHEMA_VERSION = '5.20'
# SETTINGS_FILE = 'settings.json'
# DEFAULT_SQLITE_DB = 'default.db'
# BASE_DIR = os.path.dirname(os.path.realpath(os.path.abspath(__file__)))
# ROOT_DIR = os.path.normpath(BASE_DIR + '/../')
# DATA_DIR = os.path.join(ROOT_DIR, 'data')
# EXAMPLE_DIR = os.path.join(ROOT_DIR, '../tests/data')
# INIT_DATA = os.path.join(DATA_DIR, 'sql/init-data.sql')
# TEST_DBS_FILE = os.path.join(DATA_DIR, 'test_dbs.txt')
# TEST_DBS_REF_FILE = os.path.join(DATA_DIR, 'test_dbs_ref.txt')
# SETTINGS_PATH = DATA_DIR + os.sep + SETTINGS_FILE
# GUI_URL_TPL = 'http://tilde-lab.github.io/berlinium/?http://127.0.0.1:%s' # ?https://db.tilde.pro
# DEFAULT_SETUP = {
#
# # General part
# 'debug_regime': False, # TODO
# 'log_dir': os.path.join(DATA_DIR, "logs"), # TODO
# 'skip_unfinished': False,
# 'skip_notenergy': False,
# 'skip_if_path': [],
#
# # DB part
# 'db': {
# 'default_sqlite_db': DEFAULT_SQLITE_DB,
# 'engine': 'sqlite', # if sqlite is chosen: further info is not used
# 'host': 'localhost',
# 'port': 5432,
# 'user': 'postgres',
# 'password': '',
# 'dbname': 'tilde'
# },
#
# # Server part
# 'webport': 8070,
# 'title': "Tilde GUI"
# }
# def virtualize_path(item):
# def connect_url(settings, named=None):
# def connect_database(settings, named=None, no_pooling=False, default_actions=True, scoped=False):
# def write_settings(settings):
# def get_hierarchy(settings):
. Output only the next line. | del self.Clients[client_id] |
Given the code snippet: <|code_start|>
if not Connection.Clients[frame['client_id']].db:
Connection.Clients[frame['client_id']].db = connect_database(settings, default_actions=False, no_pooling=True)
logging.debug("New DB connection to %s" % (
settings['db']['default_sqlite_db']
if settings['db']['engine'] == 'sqlite'
else settings['db']['dbname'] + '@' + settings['db']['engine']
))
frame['result'], frame['error'] = getattr(self.GUIProvider, frame['act'])( frame['req'], frame['client_id'], Connection.Clients[frame['client_id']].db )
self.respond(frame)
def respond(self, output):
del output['client_id']
if not output['error'] and not output['result']:
output['error'] = "Handler %s has returned an empty result!" % output['act']
logging.debug("Server responds: %s" % output)
self.send(json.dumps(output))
def on_close(self):
logging.info("Server will close connection with %s-th client" % len(self.Clients))
client_id = getattr(self.session, 'session_id', self.session.__hash__())
# must explicitly close db connection
try:
self.Clients[client_id].db.close()
self.Clients[client_id].db = None
logging.debug("DB connection closed")
except: pass
<|code_end|>
, generate the next line using the imports in this file:
import logging
import ujson as json
from tornado import ioloop
from sockjs.tornado import SockJSConnection
from tilde.berlinium.impl import GUIProviderMockup, Client
from tilde.core.settings import settings, connect_database
and context (functions, classes, or occasionally code) from other files:
# Path: tilde/berlinium/impl.py
# class GUIProviderMockup:
# pass
#
# class Client:
# def __init__(self):
# self.usettings = {}
# self.authorized = False
# self.db = None
#
# Path: tilde/core/settings.py
# DB_SCHEMA_VERSION = '5.20'
# SETTINGS_FILE = 'settings.json'
# DEFAULT_SQLITE_DB = 'default.db'
# BASE_DIR = os.path.dirname(os.path.realpath(os.path.abspath(__file__)))
# ROOT_DIR = os.path.normpath(BASE_DIR + '/../')
# DATA_DIR = os.path.join(ROOT_DIR, 'data')
# EXAMPLE_DIR = os.path.join(ROOT_DIR, '../tests/data')
# INIT_DATA = os.path.join(DATA_DIR, 'sql/init-data.sql')
# TEST_DBS_FILE = os.path.join(DATA_DIR, 'test_dbs.txt')
# TEST_DBS_REF_FILE = os.path.join(DATA_DIR, 'test_dbs_ref.txt')
# SETTINGS_PATH = DATA_DIR + os.sep + SETTINGS_FILE
# GUI_URL_TPL = 'http://tilde-lab.github.io/berlinium/?http://127.0.0.1:%s' # ?https://db.tilde.pro
# DEFAULT_SETUP = {
#
# # General part
# 'debug_regime': False, # TODO
# 'log_dir': os.path.join(DATA_DIR, "logs"), # TODO
# 'skip_unfinished': False,
# 'skip_notenergy': False,
# 'skip_if_path': [],
#
# # DB part
# 'db': {
# 'default_sqlite_db': DEFAULT_SQLITE_DB,
# 'engine': 'sqlite', # if sqlite is chosen: further info is not used
# 'host': 'localhost',
# 'port': 5432,
# 'user': 'postgres',
# 'password': '',
# 'dbname': 'tilde'
# },
#
# # Server part
# 'webport': 8070,
# 'title': "Tilde GUI"
# }
# def virtualize_path(item):
# def connect_url(settings, named=None):
# def connect_database(settings, named=None, no_pooling=False, default_actions=True, scoped=False):
# def write_settings(settings):
# def get_hierarchy(settings):
. Output only the next line. | del self.Clients[client_id] |
Based on the snippet: <|code_start|> echo $PEARL_PKGVARDIR >> {home_dir}/result2
echo $PEARL_PKGNAME >> {home_dir}/result2
echo $PEARL_PKGREPONAME >> {home_dir}/result2
return 0
}}
"""
builder = PackageTestBuilder(home_dir)
builder.add_local_package(tmp_path, hooks_sh_script, is_installed=True)
packages = builder.build()
package = packages['repo-test']['pkg-test']
pearl_env = create_pearl_env(home_dir, packages)
update_package(pearl_env, package, PackageArgs(verbose=2))
assert (home_dir / 'packages/repo-test/pkg-test/pearl-config/hooks.sh').is_file()
expected_result = f"""{package.dir}\n{home_dir}\n{package.dir}\n{package.vardir}\n{package.name}\n{package.repo_name}\n"""
assert (home_dir / 'result').read_text() == expected_result
expected_result = f"""{package.dir}\n{home_dir}\n{package.dir}\n{package.vardir}\n{package.name}\n{package.repo_name}\n"""
assert (home_dir / 'result2').read_text() == expected_result
def test_update_local_package_forced(tmp_path):
home_dir = create_pearl_home(tmp_path)
hooks_sh_script = """
pre_update() {{
return 11
<|code_end|>
, predict the immediate next line with the help of imports:
from unittest import mock
from pearllib.exceptions import PackageAlreadyInstalledError, \
HookFunctionError, PackageNotInstalledError, PackageRequiredByOtherError
from pearllib.package import install_package, remove_package, list_packages, update_package, emerge_package, \
create_package, info_package, install_packages, update_packages, emerge_packages, \
remove_packages, info_packages, closure_dependency_tree
from pearllib.pearlenv import Package, PearlEnvironment, PackageBuilder
from .utils import create_pearl_env, create_pearl_home, PackageTestBuilder, PackageArgs
import pytest
and context (classes, functions, sometimes code) from other files:
# Path: tests/test_pearllib/utils.py
# def create_pearl_env(home_dir, packages):
# pearl_env = mock.Mock(spec=PearlEnvironment)
# pearl_env.home = home_dir
# pearl_env.packages = packages
# return pearl_env
#
# def create_pearl_home(tmp_path):
# home_dir = tmp_path / 'home'
# home_dir.mkdir(parents=True)
# pearl_conf = home_dir / 'pearl.conf'
# pearl_conf.touch()
# return home_dir
#
# class PackageTestBuilder:
# def __init__(self, home_dir):
# self.packages = {}
# self.home_dir = home_dir
#
# def add_local_package(
# self,
# tmp_path, hooks_sh_script,
# repo_name='repo-test',
# package_name='pkg-test',
# is_installed=False,
# depends=(),
# ):
# """Install a package somewhere locally"""
# pkg_dir = tmp_path / f'{repo_name}/{package_name}'
# (pkg_dir / 'pearl-config').mkdir(parents=True)
# hooks_sh = pkg_dir / 'pearl-config/hooks.sh'
# hooks_sh.touch()
# hooks_sh.write_text(hooks_sh_script)
#
# if is_installed:
# self._install_package(
# hooks_sh_script,
# repo_name=repo_name,
# package_name=package_name,
# )
#
# package = Package(
# self.home_dir, repo_name, package_name, str(pkg_dir), '',
# depends=depends
# )
# self._update_packages(package)
#
# def add_git_package(
# self,
# hooks_sh_script,
# repo_name='repo-test',
# package_name='pkg-test',
# url='https://github.com/pkg',
# git_url=None,
# is_installed=False,
# depends=(),
# ):
#
# if is_installed:
# if git_url is None:
# git_url = url
# self._install_package(
# hooks_sh_script,
# repo_name='repo-test',
# package_name='pkg-test',
# git_url=git_url
# )
# package = Package(
# self.home_dir, repo_name, package_name, url, '',
# depends=depends
# )
# self._update_packages(package)
#
# def build(self):
# return self.packages
#
# def _update_packages(self, package: Package):
# if package.repo_name not in self.packages:
# self.packages[package.repo_name] = {}
# self.packages[package.repo_name][package.name] = package
#
# def _install_package(
# self,
# hooks_sh_script,
# repo_name='repo-test',
# package_name='pkg-test',
# git_url=None
# ):
# pkg_dir = self.home_dir / f'packages/{repo_name}/{package_name}'
# (pkg_dir / 'pearl-config').mkdir(parents=True)
#
# hooks_sh = pkg_dir / 'pearl-config/hooks.sh'
# hooks_sh.write_text(hooks_sh_script)
#
# if git_url is not None:
# subprocess.run(
# ['git', '-C', str(pkg_dir), 'init'],
# )
# subprocess.run(
# ['git', '-C', str(pkg_dir), 'remote', 'add', 'origin', git_url],
# )
#
# class PackageArgs(Namespace):
# def __init__(
# self, no_confirm=False, verbose=0, force=False,
# pattern=".*", package_only=False, installed_only=False,
# dependency_tree=False,
# name="", dest_dir=None,
# packages=()
# ):
# super().__init__()
# self.no_confirm = no_confirm
# self.verbose = verbose
# self.force = force
# self.pattern = pattern
# self.package_only = package_only
# self.installed_only = installed_only
# self.dependency_tree = dependency_tree
# self.name = name
# self.dest_dir = dest_dir
# self.packages = packages
. Output only the next line. | }} |
Based on the snippet: <|code_start|> packages = builder.build()
package = packages['repo-test']['pkg-test']
pearl_env = create_pearl_env(home_dir, packages)
update_package(pearl_env, package, args=PackageArgs(False, 0, force=True))
with pytest.raises(HookFunctionError):
update_package(pearl_env, package, args=PackageArgs(False, 0, force=False))
assert (home_dir / 'packages/repo-test/pkg-test/pearl-config/hooks.sh').is_file()
def test_update_local_package_no_confirm(tmp_path):
home_dir = create_pearl_home(tmp_path)
hooks_sh_script = f"""
pre_update() {{
if ask "Are you sure?" "Y"
then
echo "YES" > {home_dir}/result
else
echo "NO" > {home_dir}/result
fi
local choice=$(choose "What?" "banana" "apple" "banana" "orange")
echo "$choice" >> {home_dir}/result
return 0
}}
post_update() {{
if ask "Are you sure?" "N"
<|code_end|>
, predict the immediate next line with the help of imports:
from unittest import mock
from pearllib.exceptions import PackageAlreadyInstalledError, \
HookFunctionError, PackageNotInstalledError, PackageRequiredByOtherError
from pearllib.package import install_package, remove_package, list_packages, update_package, emerge_package, \
create_package, info_package, install_packages, update_packages, emerge_packages, \
remove_packages, info_packages, closure_dependency_tree
from pearllib.pearlenv import Package, PearlEnvironment, PackageBuilder
from .utils import create_pearl_env, create_pearl_home, PackageTestBuilder, PackageArgs
import pytest
and context (classes, functions, sometimes code) from other files:
# Path: tests/test_pearllib/utils.py
# def create_pearl_env(home_dir, packages):
# pearl_env = mock.Mock(spec=PearlEnvironment)
# pearl_env.home = home_dir
# pearl_env.packages = packages
# return pearl_env
#
# def create_pearl_home(tmp_path):
# home_dir = tmp_path / 'home'
# home_dir.mkdir(parents=True)
# pearl_conf = home_dir / 'pearl.conf'
# pearl_conf.touch()
# return home_dir
#
# class PackageTestBuilder:
# def __init__(self, home_dir):
# self.packages = {}
# self.home_dir = home_dir
#
# def add_local_package(
# self,
# tmp_path, hooks_sh_script,
# repo_name='repo-test',
# package_name='pkg-test',
# is_installed=False,
# depends=(),
# ):
# """Install a package somewhere locally"""
# pkg_dir = tmp_path / f'{repo_name}/{package_name}'
# (pkg_dir / 'pearl-config').mkdir(parents=True)
# hooks_sh = pkg_dir / 'pearl-config/hooks.sh'
# hooks_sh.touch()
# hooks_sh.write_text(hooks_sh_script)
#
# if is_installed:
# self._install_package(
# hooks_sh_script,
# repo_name=repo_name,
# package_name=package_name,
# )
#
# package = Package(
# self.home_dir, repo_name, package_name, str(pkg_dir), '',
# depends=depends
# )
# self._update_packages(package)
#
# def add_git_package(
# self,
# hooks_sh_script,
# repo_name='repo-test',
# package_name='pkg-test',
# url='https://github.com/pkg',
# git_url=None,
# is_installed=False,
# depends=(),
# ):
#
# if is_installed:
# if git_url is None:
# git_url = url
# self._install_package(
# hooks_sh_script,
# repo_name='repo-test',
# package_name='pkg-test',
# git_url=git_url
# )
# package = Package(
# self.home_dir, repo_name, package_name, url, '',
# depends=depends
# )
# self._update_packages(package)
#
# def build(self):
# return self.packages
#
# def _update_packages(self, package: Package):
# if package.repo_name not in self.packages:
# self.packages[package.repo_name] = {}
# self.packages[package.repo_name][package.name] = package
#
# def _install_package(
# self,
# hooks_sh_script,
# repo_name='repo-test',
# package_name='pkg-test',
# git_url=None
# ):
# pkg_dir = self.home_dir / f'packages/{repo_name}/{package_name}'
# (pkg_dir / 'pearl-config').mkdir(parents=True)
#
# hooks_sh = pkg_dir / 'pearl-config/hooks.sh'
# hooks_sh.write_text(hooks_sh_script)
#
# if git_url is not None:
# subprocess.run(
# ['git', '-C', str(pkg_dir), 'init'],
# )
# subprocess.run(
# ['git', '-C', str(pkg_dir), 'remote', 'add', 'origin', git_url],
# )
#
# class PackageArgs(Namespace):
# def __init__(
# self, no_confirm=False, verbose=0, force=False,
# pattern=".*", package_only=False, installed_only=False,
# dependency_tree=False,
# name="", dest_dir=None,
# packages=()
# ):
# super().__init__()
# self.no_confirm = no_confirm
# self.verbose = verbose
# self.force = force
# self.pattern = pattern
# self.package_only = package_only
# self.installed_only = installed_only
# self.dependency_tree = dependency_tree
# self.name = name
# self.dest_dir = dest_dir
# self.packages = packages
. Output only the next line. | then |
Predict the next line after this snippet: <|code_start|> "",
is_installed=True,
url='https://github.com/new-pkg',
git_url='https://github.com/pkg',
)
packages = builder.build()
package = packages['repo-test']['pkg-test']
pearl_env = create_pearl_env(home_dir, packages)
with mock.patch(_MODULE_UNDER_TEST + ".run_pearl_bash") as run_mock, \
mock.patch(_MODULE_UNDER_TEST + ".remove_package") as remove_mock, \
mock.patch(_MODULE_UNDER_TEST + ".install_package") as install_mock:
update_package(pearl_env, package, PackageArgs())
expected_calls = [
mock.call(mock.ANY, pearl_env, enable_errexit=True, enable_xtrace=False, input=None),
mock.call(f'\nupdate_git_repo {tmp_path}/home/packages/repo-test/pkg-test "" true\n', pearl_env, input=None),
mock.call(mock.ANY, pearl_env, enable_errexit=True, enable_xtrace=False, input=None)
]
run_mock.assert_has_calls(expected_calls)
assert remove_mock.call_count == 1
assert install_mock.call_count == 1
def test_update_package_raise_hook(tmp_path):
home_dir = create_pearl_home(tmp_path)
hooks_sh_script = """
pre_update() {{
command-notfound
return 0
<|code_end|>
using the current file's imports:
from unittest import mock
from pearllib.exceptions import PackageAlreadyInstalledError, \
HookFunctionError, PackageNotInstalledError, PackageRequiredByOtherError
from pearllib.package import install_package, remove_package, list_packages, update_package, emerge_package, \
create_package, info_package, install_packages, update_packages, emerge_packages, \
remove_packages, info_packages, closure_dependency_tree
from pearllib.pearlenv import Package, PearlEnvironment, PackageBuilder
from .utils import create_pearl_env, create_pearl_home, PackageTestBuilder, PackageArgs
import pytest
and any relevant context from other files:
# Path: tests/test_pearllib/utils.py
# def create_pearl_env(home_dir, packages):
# pearl_env = mock.Mock(spec=PearlEnvironment)
# pearl_env.home = home_dir
# pearl_env.packages = packages
# return pearl_env
#
# def create_pearl_home(tmp_path):
# home_dir = tmp_path / 'home'
# home_dir.mkdir(parents=True)
# pearl_conf = home_dir / 'pearl.conf'
# pearl_conf.touch()
# return home_dir
#
# class PackageTestBuilder:
# def __init__(self, home_dir):
# self.packages = {}
# self.home_dir = home_dir
#
# def add_local_package(
# self,
# tmp_path, hooks_sh_script,
# repo_name='repo-test',
# package_name='pkg-test',
# is_installed=False,
# depends=(),
# ):
# """Install a package somewhere locally"""
# pkg_dir = tmp_path / f'{repo_name}/{package_name}'
# (pkg_dir / 'pearl-config').mkdir(parents=True)
# hooks_sh = pkg_dir / 'pearl-config/hooks.sh'
# hooks_sh.touch()
# hooks_sh.write_text(hooks_sh_script)
#
# if is_installed:
# self._install_package(
# hooks_sh_script,
# repo_name=repo_name,
# package_name=package_name,
# )
#
# package = Package(
# self.home_dir, repo_name, package_name, str(pkg_dir), '',
# depends=depends
# )
# self._update_packages(package)
#
# def add_git_package(
# self,
# hooks_sh_script,
# repo_name='repo-test',
# package_name='pkg-test',
# url='https://github.com/pkg',
# git_url=None,
# is_installed=False,
# depends=(),
# ):
#
# if is_installed:
# if git_url is None:
# git_url = url
# self._install_package(
# hooks_sh_script,
# repo_name='repo-test',
# package_name='pkg-test',
# git_url=git_url
# )
# package = Package(
# self.home_dir, repo_name, package_name, url, '',
# depends=depends
# )
# self._update_packages(package)
#
# def build(self):
# return self.packages
#
# def _update_packages(self, package: Package):
# if package.repo_name not in self.packages:
# self.packages[package.repo_name] = {}
# self.packages[package.repo_name][package.name] = package
#
# def _install_package(
# self,
# hooks_sh_script,
# repo_name='repo-test',
# package_name='pkg-test',
# git_url=None
# ):
# pkg_dir = self.home_dir / f'packages/{repo_name}/{package_name}'
# (pkg_dir / 'pearl-config').mkdir(parents=True)
#
# hooks_sh = pkg_dir / 'pearl-config/hooks.sh'
# hooks_sh.write_text(hooks_sh_script)
#
# if git_url is not None:
# subprocess.run(
# ['git', '-C', str(pkg_dir), 'init'],
# )
# subprocess.run(
# ['git', '-C', str(pkg_dir), 'remote', 'add', 'origin', git_url],
# )
#
# class PackageArgs(Namespace):
# def __init__(
# self, no_confirm=False, verbose=0, force=False,
# pattern=".*", package_only=False, installed_only=False,
# dependency_tree=False,
# name="", dest_dir=None,
# packages=()
# ):
# super().__init__()
# self.no_confirm = no_confirm
# self.verbose = verbose
# self.force = force
# self.pattern = pattern
# self.package_only = package_only
# self.installed_only = installed_only
# self.dependency_tree = dependency_tree
# self.name = name
# self.dest_dir = dest_dir
# self.packages = packages
. Output only the next line. | }} |
Predict the next line for this snippet: <|code_start|>
_MODULE_UNDER_TEST = 'pearllib.package'
def test_install_local_package(tmp_path):
home_dir = create_pearl_home(tmp_path)
hooks_sh_script = f"""
post_install() {{
echo $PWD > {home_dir}/result
echo $PEARL_HOME >> {home_dir}/result
echo $PEARL_PKGDIR >> {home_dir}/result
<|code_end|>
with the help of current file imports:
from unittest import mock
from pearllib.exceptions import PackageAlreadyInstalledError, \
HookFunctionError, PackageNotInstalledError, PackageRequiredByOtherError
from pearllib.package import install_package, remove_package, list_packages, update_package, emerge_package, \
create_package, info_package, install_packages, update_packages, emerge_packages, \
remove_packages, info_packages, closure_dependency_tree
from pearllib.pearlenv import Package, PearlEnvironment, PackageBuilder
from .utils import create_pearl_env, create_pearl_home, PackageTestBuilder, PackageArgs
import pytest
and context from other files:
# Path: tests/test_pearllib/utils.py
# def create_pearl_env(home_dir, packages):
# pearl_env = mock.Mock(spec=PearlEnvironment)
# pearl_env.home = home_dir
# pearl_env.packages = packages
# return pearl_env
#
# def create_pearl_home(tmp_path):
# home_dir = tmp_path / 'home'
# home_dir.mkdir(parents=True)
# pearl_conf = home_dir / 'pearl.conf'
# pearl_conf.touch()
# return home_dir
#
# class PackageTestBuilder:
# def __init__(self, home_dir):
# self.packages = {}
# self.home_dir = home_dir
#
# def add_local_package(
# self,
# tmp_path, hooks_sh_script,
# repo_name='repo-test',
# package_name='pkg-test',
# is_installed=False,
# depends=(),
# ):
# """Install a package somewhere locally"""
# pkg_dir = tmp_path / f'{repo_name}/{package_name}'
# (pkg_dir / 'pearl-config').mkdir(parents=True)
# hooks_sh = pkg_dir / 'pearl-config/hooks.sh'
# hooks_sh.touch()
# hooks_sh.write_text(hooks_sh_script)
#
# if is_installed:
# self._install_package(
# hooks_sh_script,
# repo_name=repo_name,
# package_name=package_name,
# )
#
# package = Package(
# self.home_dir, repo_name, package_name, str(pkg_dir), '',
# depends=depends
# )
# self._update_packages(package)
#
# def add_git_package(
# self,
# hooks_sh_script,
# repo_name='repo-test',
# package_name='pkg-test',
# url='https://github.com/pkg',
# git_url=None,
# is_installed=False,
# depends=(),
# ):
#
# if is_installed:
# if git_url is None:
# git_url = url
# self._install_package(
# hooks_sh_script,
# repo_name='repo-test',
# package_name='pkg-test',
# git_url=git_url
# )
# package = Package(
# self.home_dir, repo_name, package_name, url, '',
# depends=depends
# )
# self._update_packages(package)
#
# def build(self):
# return self.packages
#
# def _update_packages(self, package: Package):
# if package.repo_name not in self.packages:
# self.packages[package.repo_name] = {}
# self.packages[package.repo_name][package.name] = package
#
# def _install_package(
# self,
# hooks_sh_script,
# repo_name='repo-test',
# package_name='pkg-test',
# git_url=None
# ):
# pkg_dir = self.home_dir / f'packages/{repo_name}/{package_name}'
# (pkg_dir / 'pearl-config').mkdir(parents=True)
#
# hooks_sh = pkg_dir / 'pearl-config/hooks.sh'
# hooks_sh.write_text(hooks_sh_script)
#
# if git_url is not None:
# subprocess.run(
# ['git', '-C', str(pkg_dir), 'init'],
# )
# subprocess.run(
# ['git', '-C', str(pkg_dir), 'remote', 'add', 'origin', git_url],
# )
#
# class PackageArgs(Namespace):
# def __init__(
# self, no_confirm=False, verbose=0, force=False,
# pattern=".*", package_only=False, installed_only=False,
# dependency_tree=False,
# name="", dest_dir=None,
# packages=()
# ):
# super().__init__()
# self.no_confirm = no_confirm
# self.verbose = verbose
# self.force = force
# self.pattern = pattern
# self.package_only = package_only
# self.installed_only = installed_only
# self.dependency_tree = dependency_tree
# self.name = name
# self.dest_dir = dest_dir
# self.packages = packages
, which may contain function names, class names, or code. Output only the next line. | echo $PEARL_PKGVARDIR >> {home_dir}/result |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
#
# Driver for FPGA based PROFIBUS PHY.
#
# Copyright (c) 2019 Michael Buesch <m@bues.ch>
#
# Licensed under the terms of the GNU General Public License version 2,
# or (at your option) any later version.
#
from __future__ import division, absolute_import, print_function, unicode_literals
__all__ = [
"FpgaPhyDriver",
<|code_end|>
. Use current file imports:
from pyprofibus.compat import *
from pyprofibus.phy_fpga_driver.exceptions import *
from pyprofibus.phy_fpga_driver.messages import *
from pyprofibus.phy_fpga_driver.io import *
from pyprofibus.util import monotonic_time, FaultDebouncer
import time
and context (classes, functions, or code) from other files:
# Path: pyprofibus/util.py
# def monotonic_time():
# return time.ticks_ms() / 1e3
#
# class FaultDebouncer(object):
# """Fault counter/debouncer.
# """
#
# __slots__ = (
# "__countMax",
# "__count",
# )
#
# def __init__(self, countMax = 0xFFFF):
# self.__countMax = countMax
# self.reset()
#
# def reset(self):
# self.__count = 0
#
# def inc(self):
# if self.__count < self.__countMax - 2:
# self.__count += 2
# return (self.__count + 1) // 2
#
# def dec(self):
# if self.__count > 0:
# self.__count -= 1
# return (self.__count + 1) // 2
#
# fault = inc
# ok = dec
#
# def get(self):
# return (self.__count + 1) // 2
. Output only the next line. | ] |
Continue the code snippet: <|code_start|>ext_modules = setup_cython.ext_modules
warnings.filterwarnings("ignore", r".*'long_description_content_type'.*")
with open(os.path.join(basedir, "README.rst"), "rb") as fd:
readmeText = fd.read().decode("UTF-8")
setup( name = "pyprofibus",
version = VERSION_STRING,
description = "Python PROFIBUS module",
license = "GNU General Public License v2 or later",
author = "Michael Buesch",
author_email = "m@bues.ch",
url = "https://bues.ch/a/profibus",
scripts = [ "gsdparser",
"profisniff",
"pyprofibus-linuxcnc-hal", ],
packages = [ "pyprofibus", "pyprofibus.gsd", "pyprofibus.phy_fpga_driver" ],
cmdclass = cmdclass,
ext_modules = ext_modules,
keywords = [ "PROFIBUS", "PROFIBUS-DP", "SPS", "PLC",
"Step 7", "Siemens",
"GSD", "GSD parser", "General Station Description", ],
classifiers = [
"Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: Developers",
"Intended Audience :: Education",
"Intended Audience :: Information Technology",
<|code_end|>
. Use current file imports:
import sys, os
import setup_cython
import warnings
import re
from pyprofibus.version import VERSION_STRING
from distutils.core import setup
and context (classes, functions, or code) from other files:
# Path: pyprofibus/version.py
# VERSION_STRING = "%d.%d%s" % (VERSION_MAJOR, VERSION_MINOR, VERSION_EXTRA)
. Output only the next line. | "Intended Audience :: Manufacturing", |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
#
# PROFIBUS - GSD file parser
#
# Copyright (c) 2016-2021 Michael Buesch <m@bues.ch>
#
# Licensed under the terms of the GNU General Public License version 2,
# or (at your option) any later version.
#
from __future__ import division, absolute_import, print_function, unicode_literals
__all__ = [
"GsdError",
"GsdParser",
<|code_end|>
. Use current file imports:
(from pyprofibus.compat import *
from pyprofibus.util import ProfibusError
from pyprofibus.gsd.fields import *
import gc
import re
import copy)
and context including class names, function names, or small code snippets from other files:
# Path: pyprofibus/util.py
# class ProfibusError(Exception):
# __slots__ = (
# )
. Output only the next line. | ] |
Continue the code snippet: <|code_start|> """
print a welcome message
"""
clist = sysConf.commands.keys()
clist.sort()
commands = "\n".join(textwrap.wrap(
", ".join(clist),
subsequent_indent=' ',
initial_indent=' ',
)).lstrip()
moa.ui.fprint("""{{bold}}{{blue}}Welcome to MOA!{{reset}} (v %(version)s)
{{bold}}Available commands{{reset}}: %(commands)s
Try:
* `{{bold}}moa --help{{reset}}` for information on running the `{{green}}moa{{reset}}` command.
* `{{bold}}moa help{{reset}}` inside a moa job directory for information on the operation
of that template
* reading the manual at: {{green}}http://mfiers.github.com/Moa/{{reset}}
""" % {'commands' : commands,
'version' : sysConf.getVersion()
}, f='jinja')
TESTHELP = '''
moa simple -t test -- echo
x=`moa help`
[[ -n "$x" ]]
<|code_end|>
. Use current file imports:
import os
import sys
import pydoc
import textwrap
import subprocess as sp
import jinja2
import moa.job
import moa.utils
import moa.template
import moa.plugin
import moa.args
from moa.sysConf import sysConf
and context (classes, functions, or code) from other files:
# Path: moa/sysConf.py
# USERCONFIGFILE = os.path.join(os.path.expanduser('~'),
# '.config', 'moa', 'config')
# SYSCONFIGFILE = os.path.join('etc', 'moa', 'config')
# def _interpret_var(v):
# def __init__(self):
# def getUser(self):
# def saveUser(self, conf):
# def getVersion(self):
# class SysConf(Yaco.Yaco):
. Output only the next line. | echo $x | grep -q "moa simple" |
Given the following code snippet before the placeholder: <|code_start|>
def ruffusExecutor(input, output, script, jobData):
if not sysConf.actor.has_key('files_processed'):
sysConf.actor.files_processed = []
sysConf.actor.files_processed.append((input, output))
wd = jobData['wd']
tmpdir = os.path.abspath(
os.path.join(wd, '.moa', 'tmp'))
if not os.path.exists(tmpdir):
os.makedirs(tmpdir)
tf = tempfile.NamedTemporaryFile( delete = False,
dir=tmpdir,
prefix='moa',
mode='w')
tf.write(script)
tf.close()
os.chmod(tf.name, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
for k in jobData:
v = jobData[k]
<|code_end|>
, predict the next line using imports from the current file:
import os
import stat
import tempfile
import ruffus
import moa.actor
from moa.sysConf import sysConf
and context including class names, function names, and sometimes code from other files:
# Path: moa/sysConf.py
# USERCONFIGFILE = os.path.join(os.path.expanduser('~'),
# '.config', 'moa', 'config')
# SYSCONFIGFILE = os.path.join('etc', 'moa', 'config')
# def _interpret_var(v):
# def __init__(self):
# def getUser(self):
# def saveUser(self, conf):
# def getVersion(self):
# class SysConf(Yaco.Yaco):
. Output only the next line. | if isinstance(v, list): |
Using the snippet: <|code_start|> print " ".join(job.conf.keys())
TESTRAWCOMMANDS = '''
out=`moa raw_commands`
[[ "$out" =~ "help" ]]
[[ "$out" =~ "list" ]]
[[ "$out" =~ "new" ]]
'''
TESTSCRIPT = """
moa new adhoc -t 'something'
moa set mode=simple
moa set process='echo "ERR" >&2; echo "OUT"'
moa run
moa out | grep OUT
moa err | grep ERR
moa version
"""
TESTOUT = '''
moa simple -t "test" -- echo "something"
moa run >/dev/null 2>/dev/null
out=`moa out`
[[ "$out" =~ "something" ]] || (echo "Moa out failed" ; false)
'''
TESTERR = '''
moa simple -t "test" --np
moa set process='echo "something" >&2'
moa run >/dev/null 2>/dev/null
<|code_end|>
, determine the next line of code. You have imports:
import os
import re
import fnmatch
import moa.ui
import moa.utils
import moa.actor
import moa.template
import moa.args
from moa.sysConf import sysConf
and context (class names, function names, or code) available:
# Path: moa/sysConf.py
# USERCONFIGFILE = os.path.join(os.path.expanduser('~'),
# '.config', 'moa', 'config')
# SYSCONFIGFILE = os.path.join('etc', 'moa', 'config')
# def _interpret_var(v):
# def __init__(self):
# def getUser(self):
# def saveUser(self, conf):
# def getVersion(self):
# class SysConf(Yaco.Yaco):
. Output only the next line. | err=`moa err` |
Given the code snippet: <|code_start|># Copyright 2009-2011 Mark Fiers
# The New Zealand Institute for Plant & Food Research
#
# This file is part of Moa - http://github.com/mfiers/Moa
#
# Licensed under the GPL license (see 'COPYING')
#
"""
**remoteLogger** - Remotely log Moa activity
--------------------------------------------
requires the standard moa logger to be active
"""
SQL = """
INSERT INTO log (status, start, stop, level, command, full_command, wd, server, template, user, title)
VALUES (%(status)s, %(start)s, %(stop)s, %(level)s,
%(command)s, %(full_command)s, %(wd)s, %(server)s,
%(template)s, %(user)s, %(title)s
<|code_end|>
, generate the next line using the imports in this file:
import os
import sys
import MySQLdb
import socket
import getpass
import moa.job
import moa.utils
import moa.logger as l
from datetime import datetime
from moa.sysConf import sysConf
and context (functions, classes, or occasionally code) from other files:
# Path: moa/sysConf.py
# USERCONFIGFILE = os.path.join(os.path.expanduser('~'),
# '.config', 'moa', 'config')
# SYSCONFIGFILE = os.path.join('etc', 'moa', 'config')
# def _interpret_var(v):
# def __init__(self):
# def getUser(self):
# def saveUser(self, conf):
# def getVersion(self):
# class SysConf(Yaco.Yaco):
. Output only the next line. | ) |
Continue the code snippet: <|code_start|>
## Initialize the logger
l = moa.logger.getLogger(__name__)
sysConf.pluginHandler = moa.plugin.PluginHandler(sysConf.plugins.system)
def load_tests(loader, tests, ignore):
tests.addTests(templateTestSuite())
return tests
def templateTestSuite():
suite = unittest.TestSuite()
for provider, template in moa.template.templateList():
job = moa.job.newTestJob(template, provider=provider)
if job.template.backend == 'ruff':
<|code_end|>
. Use current file imports:
import random
import unittest
import doctest
import moa.job
import moa.plugin
import moa.template
import moa.logger
import moa.backend.ruff.test
from moa.sysConf import sysConf
and context (classes, functions, or code) from other files:
# Path: moa/sysConf.py
# USERCONFIGFILE = os.path.join(os.path.expanduser('~'),
# '.config', 'moa', 'config')
# SYSCONFIGFILE = os.path.join('etc', 'moa', 'config')
# def _interpret_var(v):
# def __init__(self):
# def getUser(self):
# def saveUser(self, conf):
# def getVersion(self):
# class SysConf(Yaco.Yaco):
. Output only the next line. | test = moa.backend.ruff.test.templateTest(job) |
Given the code snippet: <|code_start|>
@moa.args.private
@moa.args.command
def dumpTemplate(job, args):
"""
**moa template_dump** - Show raw template information
Usage::
moa template_dump [TEMPLATE_NAME]
Show the raw template sysConf.
"""
template = _getTemplateFromData(job)
print template.pretty()
LISTTEST = '''
moa list | grep -q "map"
'''
TEMPLATETEST = '''
moa simple -t test -- echo
moa template | grep -q "simple"
'''
TEMPLATEDUMPTEST = '''
moa simple -t test -- echo
out=`moa template_dump`
[[ "$out" =~ "author" ]]
<|code_end|>
, generate the next line using the imports in this file:
import textwrap
import moa.ui
import moa.utils
import moa.args
import moa.template
from moa.sysConf import sysConf
and context (functions, classes, or occasionally code) from other files:
# Path: moa/sysConf.py
# USERCONFIGFILE = os.path.join(os.path.expanduser('~'),
# '.config', 'moa', 'config')
# SYSCONFIGFILE = os.path.join('etc', 'moa', 'config')
# def _interpret_var(v):
# def __init__(self):
# def getUser(self):
# def saveUser(self, conf):
# def getVersion(self):
# class SysConf(Yaco.Yaco):
. Output only the next line. | [[ "$out" =~ "backend" ]] |
Here is a snippet: <|code_start|> moa.ui.warn("Pausing job %d" % pid)
os.kill(pid, 19)
_setStatus(job, 'paused')
@moa.args.needsJob
@moa.args.command
def resume(job, args):
"""
Resume a running job
"""
status = _getStatus(job)
if LLOG: print 'resuming job with status', status
if status != 'paused':
moa.ui.exitError("Not paused")
pid = _getPid(job)
moa.ui.warn("Resuming job %d" % pid)
os.kill(pid, 18)
_setStatus(job, 'running')
KILLTEST = '''
'''
STATUSTEST = '''
moa status | grep -qi "not a Moa job"
moa simple --np -t test
moa status | grep -qi "template: simple"
moa status | grep -qi "Status: waiting"
moa run 2>/dev/null || true
echo a
<|code_end|>
. Write the next line using the current file imports:
import os
import signal
import moa.ui
import moa.utils
import moa.args
import moa.logger as l
from moa.sysConf import sysConf
and context from other files:
# Path: moa/sysConf.py
# USERCONFIGFILE = os.path.join(os.path.expanduser('~'),
# '.config', 'moa', 'config')
# SYSCONFIGFILE = os.path.join('etc', 'moa', 'config')
# def _interpret_var(v):
# def __init__(self):
# def getUser(self):
# def saveUser(self, conf):
# def getVersion(self):
# class SysConf(Yaco.Yaco):
, which may include functions, classes, or code. Output only the next line. | moa show |
Given the following code snippet before the placeholder: <|code_start|>@moa.args.command
def lock(job, args):
"""
Lock a job - prevent execution
"""
lockfile = os.path.join(job.confDir, 'lock')
if not os.path.exists(lockfile):
l.debug("locking job in %s" % job.wd)
with open(lockfile, 'w') as F:
F.write(" ")
moa.ui.message("Locked job")
LOCKTEST = '''
moa simple --np -t test -- echo "poiuy"
out=`moa run` 2>/dev/null
[[ ! -f ".moa/lock" ]]
[[ ! "$out" =~ "querty" ]]
[[ "$out" =~ "poiuy" ]]
moa lock
[[ -f ".moa/lock" ]]
out=`moa run 2>&1 || true`
[[ "$out" =~ "This Moa job is locked" ]]
'''
UNLOCKTEST = '''
moa simple --np -t test -- echo "poiuy"
moa lock
[[ -f ".moa/lock" ]]
out=`moa run 2>&1 || true`
<|code_end|>
, predict the next line using imports from the current file:
import os
import sys
import moa.ui
import moa.job
import moa.logger as l
import moa.args
import moa.plugin
from moa.sysConf import sysConf
and context including class names, function names, and sometimes code from other files:
# Path: moa/sysConf.py
# USERCONFIGFILE = os.path.join(os.path.expanduser('~'),
# '.config', 'moa', 'config')
# SYSCONFIGFILE = os.path.join('etc', 'moa', 'config')
# def _interpret_var(v):
# def __init__(self):
# def getUser(self):
# def saveUser(self, conf):
# def getVersion(self):
# class SysConf(Yaco.Yaco):
. Output only the next line. | [[ "$out" =~ "This Moa job is locked" ]] |
Given snippet: <|code_start|># sysConf.git.commitDir(sysConf.moautil.mv.fr, 'Preparing for git mv')
# #seems that we need to call git directly gitpython does not work
# os.system('git mv %s %s' % (sysConf.moautil.mv.fr, sysConf.moautil.mv.to))
# os.system('git commit %s %s -m "moa mv %s %s"' % (
# sysConf.moautil.mv.fr, sysConf.moautil.mv.to,
# sysConf.moautil.mv.fr, sysConf.moautil.mv.to))
# #repo.index.add(map(os.path.abspath, files))
# #repo.index.commit("moa cp %s" % " ".join(sysConf.newargs))
#Unittest scripts
RENTEST = '''
mkdir 10.test
moa ren 10.test 20.test
[[ ! -d 10.test ]]
[[ -d 20.test ]]
moa ren 20.test 30
[[ ! -d 20.test ]]
[[ -d 30.test ]]
moa ren 30 40
[[ ! -d 30.test ]]
[[ -d 40.test ]]
'''
COPYTEST = '''
mkdir 10.test
cd 10.test
moa simple -t "test" -- echo "hello"
cd ..
moa cp 10.test 20 2>/dev/null
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import glob
import os
import re
import shutil
import sys
import tarfile
import moa.args
import moa.logger
import moa.ui
from moa.sysConf import sysConf
and context:
# Path: moa/sysConf.py
# USERCONFIGFILE = os.path.join(os.path.expanduser('~'),
# '.config', 'moa', 'config')
# SYSCONFIGFILE = os.path.join('etc', 'moa', 'config')
# def _interpret_var(v):
# def __init__(self):
# def getUser(self):
# def saveUser(self, conf):
# def getVersion(self):
# class SysConf(Yaco.Yaco):
which might include code, classes, or functions. Output only the next line. | cd 20.test |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
#Copyright (C) Fiz Vazquez vud1@sindominio.net
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
class WindowCalendar(object):
def __init__(self, data_path = None, parent = None, date = None):
warnings.warn("Deprecated WindowCalendar class called", DeprecationWarning, stacklevel=2)
<|code_end|>
, determine the next line of code. You have imports:
import warnings
from pytrainer.gui.dialogs import calendar_dialog
and context (class names, function names, or code) available:
# Path: pytrainer/gui/dialogs.py
# def calendar_dialog(title="Calendar", date=None):
# dialog = Gtk.Dialog(title=title, flags=Gtk.DialogFlags.MODAL)
# dialog.add_buttons(Gtk.STOCK_OK, Gtk.ResponseType.OK,
# Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL)
# calendar = Gtk.Calendar()
# if date:
# try:
# year, month, day = date.split("-")
# calendar.select_month(int(month)-1, int(year))
# calendar.select_day(int(day))
# except:
# pass
# dialog.vbox.pack_start(calendar, True, True, 0)
# calendar.show()
# result = dialog.run()
# dialog.destroy()
# if result == Gtk.ResponseType.OK:
# date = calendar.get_date()
# return "%0.4d-%0.2d-%0.2d" % (date[0], date[1] + 1, date[2])
# elif result == Gtk.ResponseType.CANCEL:
# return None
. Output only the next line. | self.parent = parent |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
#Copyright (C) Fiz Vazquez vud1@sindominio.net
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
class WeekGraph(TimeGraph):
value_params = [
(None, _("Distance (km)"),_("Daily Distance"), None),
(None, _("Time (hours)"), _("Daily Time"), None),
(None, _("Average Heart Rate (bpm)"), _("Daily Average Heart Rate"), None),
(None, _("Average Speed (km/h)"), _("Daily Average Speed"), None),
(None, _("Calories"), _("Daily Calories"), None),
<|code_end|>
. Write the next line using the current file imports:
import datetime
from pytrainer.timegraph import TimeGraph
from pytrainer.lib.localization import locale_str
and context from other files:
# Path: pytrainer/timegraph.py
# class TimeGraph(object):
# def __init__(self, sports, vbox = None, window = None, combovalue = None, combovalue2 = None, main = None):
# self.drawarea = DrawArea(vbox, window)
# self.SPORT_FIELD = 9
# self.sport_colors = dict([(sport.name, sport.color.to_hex_string()) for sport in sports])
#
# def getFloatValue(self, value):
# try:
# return float(value)
# except:
# return float(0)
#
# def getValue(self,record,value_selected):
# #hacemos una relacion entre el value_selected y los values / we make a relation between value_selected and the values
# conv = {
# 0: 'distance', #value 0 es kilometros (1)
# 1: 'duration', #value 1 es tiempo (2)
# 2: 'beats', #value 2 es pulsaciones(3)
# 3: 'average', #value 3 es media(5)
# 4: 'calories' #value 4 es calorias(6)
# }
# value_sel = conv[value_selected]
# #si la opcion es tiempo lo pasamos a horas / if the option is time we passed it to hours
# if (value_sel == 'duration'):
# return self.getFloatValue(getattr(record, value_sel))/3600
# else:
# return self.getFloatValue(getattr(record, value_sel))
#
# def get_values(self, values, value_selected, key_format, sportfield=9):
# valueDict = {} #Stores the totals
# valueCount = {} #Counts the totals to allow for averaging if needed
# sportColors = {}
#
# for record in values:
# if record.date:
# day = locale_str(record.date.strftime(key_format)) # Gives year for this record
# sport = record.sport.name
# value = self.getValue(record, value_selected)
# if sport in valueDict: #Already got this sport
# if day in valueDict[sport]: #Already got this sport on this day
# valueDict[sport][day] += value
# valueCount[sport][day] += 1
# else: #New day for this sport
# valueDict[sport][day] = value
# valueCount[sport][day] = 1
# else: #New sport
# valueDict[sport] = {day: value}
# valueCount[sport] = {day: 1}
# else:
# logging.debug("No date string found, skipping entry: %s", record)
#
# if value_selected in (2, 3):
# total = {}
# count = {}
# for sport in valueDict.keys():
# for day in valueDict[sport].keys():
# if valueCount[sport][day] > 1: #Only average if 2 or more entries on this day
# valueDict[sport][day] /= valueCount[sport][day]
#
# if value_selected == 1: #Values are of time type
# valuesAreTime=True
# else:
# valuesAreTime=False
#
# return valueDict, valuesAreTime
#
# def drawgraph(self,values, extra=None, x_func=None):
# xval = []
# yval = []
# xlab = []
# ylab = []
# tit = []
#
# valsAreTime = []
# value_selected = self.combovalue.get_active()
# value_selected2 = self.combovalue2.get_active()
# if value_selected < 0:
# self.combovalue.set_active(0)
# value_selected = 0
#
# y1,ylabel,title,y2 = self.get_value_params(value_selected)
# ylab.append(ylabel)
# tit.append(title)
#
# yvalues, valuesAreTime = self.get_values(values,value_selected, self.KEY_FORMAT, sportfield=self.SPORT_FIELD)
# xvalues = x_func(yvalues)
#
# yval.append(yvalues)
# xlab.append(xvalues)
# valsAreTime.append(valuesAreTime)
#
# #Second combobox used
# if value_selected2 > 0:
# value_selected2 = value_selected2-1
# y1, ylabel,title,y2 = self.get_value_params(value_selected2)
# ylab.append(ylabel)
# tit.append(title)
# yvalues, valuesAreTime = self.get_values(values,value_selected2, self.KEY_FORMAT, sportfield=self.SPORT_FIELD)
# yval.append(yvalues)
# xlab.append(xvalues)
# valsAreTime.append(valuesAreTime)
# #Draw chart
# self.drawarea.drawStackedBars(xlab,yval,ylab,tit,valsAreTime, colors = self.sport_colors)
#
# def get_value_params(self,value):
# return self.value_params[value]
#
# Path: pytrainer/lib/localization.py
# def locale_str(string):
# if sys.version_info[0] == 2:
# lcname, encoding=locale.getlocale()
# return string.decode(encoding)
# else:
# return string
, which may include functions, classes, or code. Output only the next line. | ] |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
#Copyright (C) Fiz Vazquez vud1@sindominio.net
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
class WeekGraph(TimeGraph):
value_params = [
(None, _("Distance (km)"),_("Daily Distance"), None),
(None, _("Time (hours)"), _("Daily Time"), None),
(None, _("Average Heart Rate (bpm)"), _("Daily Average Heart Rate"), None),
(None, _("Average Speed (km/h)"), _("Daily Average Speed"), None),
(None, _("Calories"), _("Daily Calories"), None),
]
<|code_end|>
, generate the next line using the imports in this file:
import datetime
from pytrainer.timegraph import TimeGraph
from pytrainer.lib.localization import locale_str
and context (functions, classes, or occasionally code) from other files:
# Path: pytrainer/timegraph.py
# class TimeGraph(object):
# def __init__(self, sports, vbox = None, window = None, combovalue = None, combovalue2 = None, main = None):
# self.drawarea = DrawArea(vbox, window)
# self.SPORT_FIELD = 9
# self.sport_colors = dict([(sport.name, sport.color.to_hex_string()) for sport in sports])
#
# def getFloatValue(self, value):
# try:
# return float(value)
# except:
# return float(0)
#
# def getValue(self,record,value_selected):
# #hacemos una relacion entre el value_selected y los values / we make a relation between value_selected and the values
# conv = {
# 0: 'distance', #value 0 es kilometros (1)
# 1: 'duration', #value 1 es tiempo (2)
# 2: 'beats', #value 2 es pulsaciones(3)
# 3: 'average', #value 3 es media(5)
# 4: 'calories' #value 4 es calorias(6)
# }
# value_sel = conv[value_selected]
# #si la opcion es tiempo lo pasamos a horas / if the option is time we passed it to hours
# if (value_sel == 'duration'):
# return self.getFloatValue(getattr(record, value_sel))/3600
# else:
# return self.getFloatValue(getattr(record, value_sel))
#
# def get_values(self, values, value_selected, key_format, sportfield=9):
# valueDict = {} #Stores the totals
# valueCount = {} #Counts the totals to allow for averaging if needed
# sportColors = {}
#
# for record in values:
# if record.date:
# day = locale_str(record.date.strftime(key_format)) # Gives year for this record
# sport = record.sport.name
# value = self.getValue(record, value_selected)
# if sport in valueDict: #Already got this sport
# if day in valueDict[sport]: #Already got this sport on this day
# valueDict[sport][day] += value
# valueCount[sport][day] += 1
# else: #New day for this sport
# valueDict[sport][day] = value
# valueCount[sport][day] = 1
# else: #New sport
# valueDict[sport] = {day: value}
# valueCount[sport] = {day: 1}
# else:
# logging.debug("No date string found, skipping entry: %s", record)
#
# if value_selected in (2, 3):
# total = {}
# count = {}
# for sport in valueDict.keys():
# for day in valueDict[sport].keys():
# if valueCount[sport][day] > 1: #Only average if 2 or more entries on this day
# valueDict[sport][day] /= valueCount[sport][day]
#
# if value_selected == 1: #Values are of time type
# valuesAreTime=True
# else:
# valuesAreTime=False
#
# return valueDict, valuesAreTime
#
# def drawgraph(self,values, extra=None, x_func=None):
# xval = []
# yval = []
# xlab = []
# ylab = []
# tit = []
#
# valsAreTime = []
# value_selected = self.combovalue.get_active()
# value_selected2 = self.combovalue2.get_active()
# if value_selected < 0:
# self.combovalue.set_active(0)
# value_selected = 0
#
# y1,ylabel,title,y2 = self.get_value_params(value_selected)
# ylab.append(ylabel)
# tit.append(title)
#
# yvalues, valuesAreTime = self.get_values(values,value_selected, self.KEY_FORMAT, sportfield=self.SPORT_FIELD)
# xvalues = x_func(yvalues)
#
# yval.append(yvalues)
# xlab.append(xvalues)
# valsAreTime.append(valuesAreTime)
#
# #Second combobox used
# if value_selected2 > 0:
# value_selected2 = value_selected2-1
# y1, ylabel,title,y2 = self.get_value_params(value_selected2)
# ylab.append(ylabel)
# tit.append(title)
# yvalues, valuesAreTime = self.get_values(values,value_selected2, self.KEY_FORMAT, sportfield=self.SPORT_FIELD)
# yval.append(yvalues)
# xlab.append(xvalues)
# valsAreTime.append(valuesAreTime)
# #Draw chart
# self.drawarea.drawStackedBars(xlab,yval,ylab,tit,valsAreTime, colors = self.sport_colors)
#
# def get_value_params(self,value):
# return self.value_params[value]
#
# Path: pytrainer/lib/localization.py
# def locale_str(string):
# if sys.version_info[0] == 2:
# lcname, encoding=locale.getlocale()
# return string.decode(encoding)
# else:
# return string
. Output only the next line. | def __init__(self, sports, vbox = None, window = None, combovalue = None, combovalue2 = None, main = None): |
Given the code snippet: <|code_start|>
# lap info added in version 1.9.0
def upgrade(migrate_engine=None):
if migrate_engine is None:
# sqlalchemy-migrate 0.5.4 does not provide migrate engine to upgrade scripts
migrate_engine = sqlalchemy.create_engine(UPGRADE_CONTEXT.db_url)
logging.info("Populating laps details columns")
resultset = migrate_engine.execute(text("select distinct record from laps where intensity is null"))
record_ids = []
for row in resultset:
record_ids.append(row["record"])
resultset.close()
for record_id in record_ids:
gpx_file = UPGRADE_CONTEXT.conf_dir + "/gpx/{0}.gpx".format(record_id)
if os.path.isfile(gpx_file):
gpx_record = gpx.Gpx(filename=gpx_file)
populate_laps_from_gpx(migrate_engine, record_id, gpx_record)
def populate_laps_from_gpx(migrate_engine, record_id, gpx_record):
resultset = migrate_engine.execute(text("select id_lap from laps where record=:record_id" ), record_id=record_id)
lap_ids = []
for row in resultset:
lap_ids.append(row["id_lap"])
resultset.close()
if(len(lap_ids) > 0):
logging.info("Populating laps from GPX for record %s" , record_id)
for lap_id, gpx_lap in zip(lap_ids, gpx_record.getLaps()):
populate_lap_from_gpx(migrate_engine, lap_id, gpx_lap)
def populate_lap_from_gpx(migrate_engine, lap_id, gpx_lap):
<|code_end|>
, generate the next line using the imports in this file:
from pytrainer.lib import gpx
from pytrainer.upgrade.context import UPGRADE_CONTEXT
from sqlalchemy.sql.expression import text
import logging
import os.path
import sqlalchemy
import migrate.versioning.exceptions as ex1
import migrate.changeset.exceptions as ex2
and context (functions, classes, or occasionally code) from other files:
# Path: pytrainer/lib/gpx.py
# class Gpx:
# def __init__(self, data_path = None, filename = None, trkname = None):
# def getMaxValues(self):
# def getDate(self):
# def getTrackRoutes(self):
# def getUnevenness(self):
# def getTrackList(self):
# def getHeartRateAverage(self):
# def getCalories(self):
# def getStart_time(self):
# def getLaps(self):
# def _getValues(self):
# def _distance_between_points(self, lat1, lon1, lat2, lon2):
# def _calculate_speed(self, dist_elapsed, time_elapsed, smoothing_factor=3):
# def getStartTimeFromGPX(self, gpxFile):
# JITTER_VALUE = 0 #Elevation changes less than this value are not counted in +-
# RADIANS_PER_DEGREE = 0.01745329252
# DEGREES_PER_RADIAN = 57.29577951
#
# Path: pytrainer/upgrade/context.py
# UPGRADE_CONTEXT = None
. Output only the next line. | logging.info("Populating lap details from GPX for lap %s" , lap_id) |
Given snippet: <|code_start|> record_ids.append(row["record"])
resultset.close()
for record_id in record_ids:
gpx_file = UPGRADE_CONTEXT.conf_dir + "/gpx/{0}.gpx".format(record_id)
if os.path.isfile(gpx_file):
gpx_record = gpx.Gpx(filename=gpx_file)
populate_laps_from_gpx(migrate_engine, record_id, gpx_record)
def populate_laps_from_gpx(migrate_engine, record_id, gpx_record):
resultset = migrate_engine.execute(text("select id_lap from laps where record=:record_id" ), record_id=record_id)
lap_ids = []
for row in resultset:
lap_ids.append(row["id_lap"])
resultset.close()
if(len(lap_ids) > 0):
logging.info("Populating laps from GPX for record %s" , record_id)
for lap_id, gpx_lap in zip(lap_ids, gpx_record.getLaps()):
populate_lap_from_gpx(migrate_engine, lap_id, gpx_lap)
def populate_lap_from_gpx(migrate_engine, lap_id, gpx_lap):
logging.info("Populating lap details from GPX for lap %s" , lap_id)
migrate_engine.execute(text("""update laps set
intensity=:intensity,
avg_hr=:avg_heart_rate,
max_hr=:max_heart_rate,
max_speed=:max_speed,
laptrigger=:lap_trigger
where id_lap=:lap_id"""),
intensity=gpx_lap[7],
avg_heart_rate=gpx_lap[8],
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pytrainer.lib import gpx
from pytrainer.upgrade.context import UPGRADE_CONTEXT
from sqlalchemy.sql.expression import text
import logging
import os.path
import sqlalchemy
import migrate.versioning.exceptions as ex1
import migrate.changeset.exceptions as ex2
and context:
# Path: pytrainer/lib/gpx.py
# class Gpx:
# def __init__(self, data_path = None, filename = None, trkname = None):
# def getMaxValues(self):
# def getDate(self):
# def getTrackRoutes(self):
# def getUnevenness(self):
# def getTrackList(self):
# def getHeartRateAverage(self):
# def getCalories(self):
# def getStart_time(self):
# def getLaps(self):
# def _getValues(self):
# def _distance_between_points(self, lat1, lon1, lat2, lon2):
# def _calculate_speed(self, dist_elapsed, time_elapsed, smoothing_factor=3):
# def getStartTimeFromGPX(self, gpxFile):
# JITTER_VALUE = 0 #Elevation changes less than this value are not counted in +-
# RADIANS_PER_DEGREE = 0.01745329252
# DEGREES_PER_RADIAN = 57.29577951
#
# Path: pytrainer/upgrade/context.py
# UPGRADE_CONTEXT = None
which might include code, classes, or functions. Output only the next line. | max_heart_rate=gpx_lap[9], |
Given the following code snippet before the placeholder: <|code_start|> self.okmethod(self.gpx,trackname)
self.closewindow()
logging.debug("<<")
def on_cancel_clicked(self,widget):
logging.debug("--")
self.closewindow()
def closewindow(self):
logging.debug("--")
self.selecttrackdialog.hide()
#self.selecttrackdialog = None
self.quit()
def create_treeview(self,treeview,column_names):
logging.debug(">>")
i=0
for column_index, column_name in enumerate(column_names):
column = Gtk.TreeViewColumn(column_name, Gtk.CellRendererText(), text=column_index)
column.set_resizable(True)
column.set_sort_column_id(i)
treeview.append_column(column)
i+=1
logging.debug("<<")
def actualize_treeview(self, treeview, record_list):
logging.debug(">>")
iterOne = False
store = Gtk.ListStore(
GObject.TYPE_STRING,
<|code_end|>
, predict the next line using imports from the current file:
from .SimpleGladeApp import SimpleBuilderApp
from gi.repository import Gtk
from gi.repository import GObject
import logging
and context including class names, function names, and sometimes code from other files:
# Path: pytrainer/gui/SimpleGladeApp.py
# class SimpleBuilderApp(dict):
# def __init__(self, ui_filename):
# self._builder = Gtk.Builder()
# env = Environment()
# file_path = os.path.join(env.glade_dir, ui_filename)
# self._builder.add_from_file(file_path)
# self.signal_autoconnect()
# self._builder.connect_signals(self)
# self.new()
#
# def signal_autoconnect(self):
# signals = {}
# for attr_name in dir(self):
# attr = getattr(self, attr_name)
# if callable(attr):
# signals[attr_name] = attr
# self._builder.connect_signals(signals)
#
# def __getattr__(self, data_name):
# if data_name in self:
# data = self[data_name]
# return data
# else:
# widget = self._builder.get_object(data_name)
# if widget != None:
# self[data_name] = widget
# return widget
# else:
# raise AttributeError(data_name)
#
# def __setattr__(self, name, value):
# self[name] = value
#
# def new(self):
# pass
#
# def on_keyboard_interrupt(self):
# pass
#
# def gtk_widget_show(self, widget, *args):
# widget.show()
#
# def gtk_widget_hide(self, widget, *args):
# widget.hide()
#
# def gtk_widget_grab_focus(self, widget, *args):
# widget.grab_focus()
#
# def gtk_widget_destroy(self, widget, *args):
# widget.destroy()
#
# def gtk_window_activate_default(self, widget, *args):
# widget.activate_default()
#
# def gtk_true(self, *args):
# return True
#
# def gtk_false(self, *args):
# return False
#
# def gtk_main_quit(self, *args):
# Gtk.main_quit()
#
# def main(self):
# Gtk.main()
#
# def quit(self, widget=None):
# Gtk.main_quit()
#
# def run(self):
# try:
# self.main()
# except KeyboardInterrupt:
# self.on_keyboard_interrupt()
#
# def create_treeview(self,treeview,column_names):
# i=0
# for column_index, column_name in enumerate(column_names):
# column = Gtk.TreeViewColumn(column_name, Gtk.CellRendererText(), text=column_index)
# column.set_resizable(True)
# if i==0:
# column.set_visible(False)
# column.set_sort_column_id(i)
# treeview.append_column(column)
. Output only the next line. | GObject.TYPE_STRING, |
Predict the next line after this snippet: <|code_start|>
If the data version cannot be determined then None is returned."""
if self.is_versioned():
return self._migratable_db.get_version()
else:
# Calculate data version in older version that does not use the
# current data versioning scheme.
legacy_version = self._legacy_version_provider.get_legacy_version()
if legacy_version is not None:
legacy_version = int(legacy_version)
if legacy_version == 1: # 1.7.1
return 1
elif legacy_version == 2: # 1.7.2-dev
return 2
elif legacy_version == 3: # 1.7.2
return 3
elif legacy_version == 4: # 1.8.0-dev
return 4
elif legacy_version == 5: # 1.8.0-dev
return 5
elif legacy_version == 6: # 1.8.0
return 9
elif legacy_version == 7: # 1.9.0-dev
return 10
elif legacy_version == 8: # 1.9.0-dev
return 12
elif legacy_version == 9: # 1.9.0-dev
return 12
return None
<|code_end|>
using the current file's imports:
import logging
import os
import pytrainer
from lxml import etree
from pytrainer.upgrade.context import UpgradeContext
from pytrainer.upgrade.migratedb import MigratableDb
and any relevant context from other files:
# Path: pytrainer/upgrade/context.py
# class UpgradeContext(object):
#
# """Context used by upgrade scripts.
#
# Provides access to the application base dir."""
#
# def __init__(self, conf_dir, db_url):
# self.conf_dir = conf_dir
# self.db_url = db_url
#
# Path: pytrainer/upgrade/migratedb.py
# class MigratableDb(object):
# """Object bridge for sqlalchemy-migrate API functions."""
#
# def __init__(self, repository_path, db_url):
# """Create a migratable DB.
#
# Arguments:
# repository_path -- The path to the migrate repository, relative to the
# pypath.
# db_url -- the connection URL string for the DB.
# """
# self._repository_path = repository_path
# self._db_url = db_url
#
# def is_empty(self):
# """Check if the DB schema is empty.
#
# An empty schema indicates a new uninitialised database."""
# metadata = MetaData()
# metadata.bind = sqlalchemy.create_engine(self._db_url)
# metadata.reflect()
# tables = metadata.tables
# return not tables
#
# def is_versioned(self):
# """ Check if the DB has been initiaized with version metadata."""
# try:
# self.get_version()
# except DatabaseNotControlledError:
# return False
# except NoSuchTableError:
# # prior to 0.6.0, sqlalchemy-migrate did not handle querying
# # against unversioned databases.
# return False
# return True
#
# def get_version(self):
# """Get the current version of the versioned DB.
#
# Raises DatabaseNotControlledError if the DB is not initialized."""
# return db_version(self._db_url, self._repository_path)
#
# def get_upgrade_version(self):
# """Get the latest version available in upgrade repository."""
# return version(self._repository_path)
#
# def version(self, initial_version):
# """Initialize the database with migrate metadata.
#
# Raises DatabaseAlreadyControlledError if the DB is already initialized."""
# version_control(self._db_url, self._repository_path, initial_version)
#
# def upgrade(self):
# """Run all available upgrade scripts for the repository."""
# upgrade(self._db_url, self._repository_path)
. Output only the next line. | def get_available_version(self): |
Here is a snippet: <|code_start|>
#Copyright (C) Nathan Jones ncjones@users.sourceforge.net
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
def initialize_data(ddbb, conf_dir):
"""Initializes the installation's data."""
db_url = ddbb.get_connection_url()
migratable_db = MigratableDb(os.path.dirname(__file__), db_url)
InstalledData(migratable_db, ddbb, LegacyVersionProvider(conf_dir), UpgradeContext(conf_dir, db_url)).update_to_current()
class InstalledData(object):
"""Encapsulates an installation's existing data and provides means to
check version state and upgrade."""
def __init__(self, migratable_db, ddbb, legacy_version_provider, upgrade_context):
<|code_end|>
. Write the next line using the current file imports:
import logging
import os
import pytrainer
from lxml import etree
from pytrainer.upgrade.context import UpgradeContext
from pytrainer.upgrade.migratedb import MigratableDb
and context from other files:
# Path: pytrainer/upgrade/context.py
# class UpgradeContext(object):
#
# """Context used by upgrade scripts.
#
# Provides access to the application base dir."""
#
# def __init__(self, conf_dir, db_url):
# self.conf_dir = conf_dir
# self.db_url = db_url
#
# Path: pytrainer/upgrade/migratedb.py
# class MigratableDb(object):
# """Object bridge for sqlalchemy-migrate API functions."""
#
# def __init__(self, repository_path, db_url):
# """Create a migratable DB.
#
# Arguments:
# repository_path -- The path to the migrate repository, relative to the
# pypath.
# db_url -- the connection URL string for the DB.
# """
# self._repository_path = repository_path
# self._db_url = db_url
#
# def is_empty(self):
# """Check if the DB schema is empty.
#
# An empty schema indicates a new uninitialised database."""
# metadata = MetaData()
# metadata.bind = sqlalchemy.create_engine(self._db_url)
# metadata.reflect()
# tables = metadata.tables
# return not tables
#
# def is_versioned(self):
# """ Check if the DB has been initiaized with version metadata."""
# try:
# self.get_version()
# except DatabaseNotControlledError:
# return False
# except NoSuchTableError:
# # prior to 0.6.0, sqlalchemy-migrate did not handle querying
# # against unversioned databases.
# return False
# return True
#
# def get_version(self):
# """Get the current version of the versioned DB.
#
# Raises DatabaseNotControlledError if the DB is not initialized."""
# return db_version(self._db_url, self._repository_path)
#
# def get_upgrade_version(self):
# """Get the latest version available in upgrade repository."""
# return version(self._repository_path)
#
# def version(self, initial_version):
# """Initialize the database with migrate metadata.
#
# Raises DatabaseAlreadyControlledError if the DB is already initialized."""
# version_control(self._db_url, self._repository_path, initial_version)
#
# def upgrade(self):
# """Run all available upgrade scripts for the repository."""
# upgrade(self._db_url, self._repository_path)
, which may include functions, classes, or code. Output only the next line. | self._migratable_db = migratable_db |
Given the code snippet: <|code_start|> ylab.append(ylabel)
tit.append(title)
col.append(color)
if value_selected2 < 0:
self.combovalue2.set_active(0)
value_selected2 = 0
if value_selected2 > 0:
value_selected2 = value_selected2-1
daysmonth,xlabel,ylabel,title,color = self.get_value_params(value_selected2)
xvalues,yvalues = self.get_values(values,value_selected2,daysmonth)
xval.append(xvalues)
yval.append(yvalues)
xlab.append(xlabel)
ylab.append(ylabel)
tit.append(title)
col.append(color)
self.drawarea.stadistics("bars",xval,yval,xlab,ylab,tit,col)
def get_values2(self,values,value_selected,monthsnumber):
#hacemos una relacion entre el value_selected y los values
conv = {
0: 1, #value 0 es kilometros (1)
1: 2, #value 1 es tiempo (2)
2: 3, #value 2 es pulsaciones(3)
3: 5, #value 3 es media(5)
4: 6 #value 4 es calorias(6)
}
list_values = {}
list_average = {}
<|code_end|>
, generate the next line using the imports in this file:
import calendar
import datetime
from pytrainer.timegraph import TimeGraph
from pytrainer.lib.localization import locale_str
and context (functions, classes, or occasionally code) from other files:
# Path: pytrainer/timegraph.py
# class TimeGraph(object):
# def __init__(self, sports, vbox = None, window = None, combovalue = None, combovalue2 = None, main = None):
# self.drawarea = DrawArea(vbox, window)
# self.SPORT_FIELD = 9
# self.sport_colors = dict([(sport.name, sport.color.to_hex_string()) for sport in sports])
#
# def getFloatValue(self, value):
# try:
# return float(value)
# except:
# return float(0)
#
# def getValue(self,record,value_selected):
# #hacemos una relacion entre el value_selected y los values / we make a relation between value_selected and the values
# conv = {
# 0: 'distance', #value 0 es kilometros (1)
# 1: 'duration', #value 1 es tiempo (2)
# 2: 'beats', #value 2 es pulsaciones(3)
# 3: 'average', #value 3 es media(5)
# 4: 'calories' #value 4 es calorias(6)
# }
# value_sel = conv[value_selected]
# #si la opcion es tiempo lo pasamos a horas / if the option is time we passed it to hours
# if (value_sel == 'duration'):
# return self.getFloatValue(getattr(record, value_sel))/3600
# else:
# return self.getFloatValue(getattr(record, value_sel))
#
# def get_values(self, values, value_selected, key_format, sportfield=9):
# valueDict = {} #Stores the totals
# valueCount = {} #Counts the totals to allow for averaging if needed
# sportColors = {}
#
# for record in values:
# if record.date:
# day = locale_str(record.date.strftime(key_format)) # Gives year for this record
# sport = record.sport.name
# value = self.getValue(record, value_selected)
# if sport in valueDict: #Already got this sport
# if day in valueDict[sport]: #Already got this sport on this day
# valueDict[sport][day] += value
# valueCount[sport][day] += 1
# else: #New day for this sport
# valueDict[sport][day] = value
# valueCount[sport][day] = 1
# else: #New sport
# valueDict[sport] = {day: value}
# valueCount[sport] = {day: 1}
# else:
# logging.debug("No date string found, skipping entry: %s", record)
#
# if value_selected in (2, 3):
# total = {}
# count = {}
# for sport in valueDict.keys():
# for day in valueDict[sport].keys():
# if valueCount[sport][day] > 1: #Only average if 2 or more entries on this day
# valueDict[sport][day] /= valueCount[sport][day]
#
# if value_selected == 1: #Values are of time type
# valuesAreTime=True
# else:
# valuesAreTime=False
#
# return valueDict, valuesAreTime
#
# def drawgraph(self,values, extra=None, x_func=None):
# xval = []
# yval = []
# xlab = []
# ylab = []
# tit = []
#
# valsAreTime = []
# value_selected = self.combovalue.get_active()
# value_selected2 = self.combovalue2.get_active()
# if value_selected < 0:
# self.combovalue.set_active(0)
# value_selected = 0
#
# y1,ylabel,title,y2 = self.get_value_params(value_selected)
# ylab.append(ylabel)
# tit.append(title)
#
# yvalues, valuesAreTime = self.get_values(values,value_selected, self.KEY_FORMAT, sportfield=self.SPORT_FIELD)
# xvalues = x_func(yvalues)
#
# yval.append(yvalues)
# xlab.append(xvalues)
# valsAreTime.append(valuesAreTime)
#
# #Second combobox used
# if value_selected2 > 0:
# value_selected2 = value_selected2-1
# y1, ylabel,title,y2 = self.get_value_params(value_selected2)
# ylab.append(ylabel)
# tit.append(title)
# yvalues, valuesAreTime = self.get_values(values,value_selected2, self.KEY_FORMAT, sportfield=self.SPORT_FIELD)
# yval.append(yvalues)
# xlab.append(xvalues)
# valsAreTime.append(valuesAreTime)
# #Draw chart
# self.drawarea.drawStackedBars(xlab,yval,ylab,tit,valsAreTime, colors = self.sport_colors)
#
# def get_value_params(self,value):
# return self.value_params[value]
#
# Path: pytrainer/lib/localization.py
# def locale_str(string):
# if sys.version_info[0] == 2:
# lcname, encoding=locale.getlocale()
# return string.decode(encoding)
# else:
# return string
. Output only the next line. | tm_total = {} |
Given snippet: <|code_start|>
if value_selected2 < 0:
self.combovalue2.set_active(0)
value_selected2 = 0
if value_selected2 > 0:
value_selected2 = value_selected2-1
daysmonth,xlabel,ylabel,title,color = self.get_value_params(value_selected2)
xvalues,yvalues = self.get_values(values,value_selected2,daysmonth)
xval.append(xvalues)
yval.append(yvalues)
xlab.append(xlabel)
ylab.append(ylabel)
tit.append(title)
col.append(color)
self.drawarea.stadistics("bars",xval,yval,xlab,ylab,tit,col)
def get_values2(self,values,value_selected,monthsnumber):
#hacemos una relacion entre el value_selected y los values
conv = {
0: 1, #value 0 es kilometros (1)
1: 2, #value 1 es tiempo (2)
2: 3, #value 2 es pulsaciones(3)
3: 5, #value 3 es media(5)
4: 6 #value 4 es calorias(6)
}
list_values = {}
list_average = {}
tm_total = {}
for i in range(1,monthsnumber+1):
list_values[i]=0
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import calendar
import datetime
from pytrainer.timegraph import TimeGraph
from pytrainer.lib.localization import locale_str
and context:
# Path: pytrainer/timegraph.py
# class TimeGraph(object):
# def __init__(self, sports, vbox = None, window = None, combovalue = None, combovalue2 = None, main = None):
# self.drawarea = DrawArea(vbox, window)
# self.SPORT_FIELD = 9
# self.sport_colors = dict([(sport.name, sport.color.to_hex_string()) for sport in sports])
#
# def getFloatValue(self, value):
# try:
# return float(value)
# except:
# return float(0)
#
# def getValue(self,record,value_selected):
# #hacemos una relacion entre el value_selected y los values / we make a relation between value_selected and the values
# conv = {
# 0: 'distance', #value 0 es kilometros (1)
# 1: 'duration', #value 1 es tiempo (2)
# 2: 'beats', #value 2 es pulsaciones(3)
# 3: 'average', #value 3 es media(5)
# 4: 'calories' #value 4 es calorias(6)
# }
# value_sel = conv[value_selected]
# #si la opcion es tiempo lo pasamos a horas / if the option is time we passed it to hours
# if (value_sel == 'duration'):
# return self.getFloatValue(getattr(record, value_sel))/3600
# else:
# return self.getFloatValue(getattr(record, value_sel))
#
# def get_values(self, values, value_selected, key_format, sportfield=9):
# valueDict = {} #Stores the totals
# valueCount = {} #Counts the totals to allow for averaging if needed
# sportColors = {}
#
# for record in values:
# if record.date:
# day = locale_str(record.date.strftime(key_format)) # Gives year for this record
# sport = record.sport.name
# value = self.getValue(record, value_selected)
# if sport in valueDict: #Already got this sport
# if day in valueDict[sport]: #Already got this sport on this day
# valueDict[sport][day] += value
# valueCount[sport][day] += 1
# else: #New day for this sport
# valueDict[sport][day] = value
# valueCount[sport][day] = 1
# else: #New sport
# valueDict[sport] = {day: value}
# valueCount[sport] = {day: 1}
# else:
# logging.debug("No date string found, skipping entry: %s", record)
#
# if value_selected in (2, 3):
# total = {}
# count = {}
# for sport in valueDict.keys():
# for day in valueDict[sport].keys():
# if valueCount[sport][day] > 1: #Only average if 2 or more entries on this day
# valueDict[sport][day] /= valueCount[sport][day]
#
# if value_selected == 1: #Values are of time type
# valuesAreTime=True
# else:
# valuesAreTime=False
#
# return valueDict, valuesAreTime
#
# def drawgraph(self,values, extra=None, x_func=None):
# xval = []
# yval = []
# xlab = []
# ylab = []
# tit = []
#
# valsAreTime = []
# value_selected = self.combovalue.get_active()
# value_selected2 = self.combovalue2.get_active()
# if value_selected < 0:
# self.combovalue.set_active(0)
# value_selected = 0
#
# y1,ylabel,title,y2 = self.get_value_params(value_selected)
# ylab.append(ylabel)
# tit.append(title)
#
# yvalues, valuesAreTime = self.get_values(values,value_selected, self.KEY_FORMAT, sportfield=self.SPORT_FIELD)
# xvalues = x_func(yvalues)
#
# yval.append(yvalues)
# xlab.append(xvalues)
# valsAreTime.append(valuesAreTime)
#
# #Second combobox used
# if value_selected2 > 0:
# value_selected2 = value_selected2-1
# y1, ylabel,title,y2 = self.get_value_params(value_selected2)
# ylab.append(ylabel)
# tit.append(title)
# yvalues, valuesAreTime = self.get_values(values,value_selected2, self.KEY_FORMAT, sportfield=self.SPORT_FIELD)
# yval.append(yvalues)
# xlab.append(xvalues)
# valsAreTime.append(valuesAreTime)
# #Draw chart
# self.drawarea.drawStackedBars(xlab,yval,ylab,tit,valsAreTime, colors = self.sport_colors)
#
# def get_value_params(self,value):
# return self.value_params[value]
#
# Path: pytrainer/lib/localization.py
# def locale_str(string):
# if sys.version_info[0] == 2:
# lcname, encoding=locale.getlocale()
# return string.decode(encoding)
# else:
# return string
which might include code, classes, or functions. Output only the next line. | list_average[i]=0 |
Next line prediction: <|code_start|> def __str__(self):
return repr(self.value)
class SportService(object):
"""Provides access to stored sports."""
def __init__(self, ddbb):
self._ddbb = ddbb
def get_sport(self, sport_id):
"""Get the sport with the specified id.
If no sport with the given id exists then None is returned."""
if sport_id is None:
raise ValueError("Sport id cannot be None")
try:
return self._ddbb.session.query(Sport).filter(Sport.id == sport_id).one()
except NoResultFound:
return None
def get_sport_by_name(self, name):
"""Get the sport with the specified name.
If no sport with the given name exists then None is returned."""
if name is None:
raise ValueError("Sport name cannot be None")
try:
return self._ddbb.session.query(Sport).filter(Sport.name == name).one()
except NoResultFound:
<|code_end|>
. Use current file imports:
(from pytrainer.util.color import Color, color_from_hex_string
from pytrainer.lib.ddbb import DeclarativeBase, ForcedInteger
from sqlalchemy import Column, Integer, Float, Unicode, CheckConstraint
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import InvalidRequestError, IntegrityError
import sqlalchemy.types as types
import logging)
and context including class names, function names, or small code snippets from other files:
# Path: pytrainer/util/color.py
# class Color(object):
#
# """A color represented as a 24-bit RGB value."""
#
# def __init__(self, rgb_val=0):
# rgb_val_int = int(rgb_val)
# if rgb_val_int < 0:
# raise ValueError("RGB value must not be negative.")
# if rgb_val_int > 0xffffff:
# raise ValueError("RGB value must not be greater than 0xffffff.")
# self._rgb_val = rgb_val_int
#
# def _get_rgb_val(self):
# return self._rgb_val
#
# rgb_val = property(_get_rgb_val)
#
# def _get_rgba_val(self):
# return self._rgb_val << 8
#
# rgba_val = property(_get_rgba_val)
#
# def to_hex_string(self):
# return "{0:06x}".format(self._rgb_val)
#
# def color_from_hex_string(hex_string):
# return Color(int(hex_string, 16))
#
# Path: pytrainer/lib/ddbb.py
# class DDBB(Singleton):
# class ForcedInteger(TypeDecorator):
# def __init__(self, url=None):
# def get_connection_url(self):
# def connect(self):
# def disconnect(self):
# def select(self,table,cells,condition=None, mod=None):
# def create_tables(self, add_default=True):
# def drop_tables(self):
# def create_backup(self):
# def process_bind_param(self, value, dialect):
. Output only the next line. | return None |
Based on the snippet: <|code_start|> name = Column(Unicode(length=100), nullable=False, unique=True, index=True)
weight = Column(Float, CheckConstraint('weight>=0'), nullable=False)
def __init__(self, **kwargs):
self.name = u""
self.weight = 0.0
self.met = None
self.max_pace = None
self.color = Color(0x0000ff)
super(Sport, self).__init__(**kwargs)
class SportServiceException(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class SportService(object):
"""Provides access to stored sports."""
def __init__(self, ddbb):
self._ddbb = ddbb
def get_sport(self, sport_id):
"""Get the sport with the specified id.
If no sport with the given id exists then None is returned."""
<|code_end|>
, predict the immediate next line with the help of imports:
from pytrainer.util.color import Color, color_from_hex_string
from pytrainer.lib.ddbb import DeclarativeBase, ForcedInteger
from sqlalchemy import Column, Integer, Float, Unicode, CheckConstraint
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import InvalidRequestError, IntegrityError
import sqlalchemy.types as types
import logging
and context (classes, functions, sometimes code) from other files:
# Path: pytrainer/util/color.py
# class Color(object):
#
# """A color represented as a 24-bit RGB value."""
#
# def __init__(self, rgb_val=0):
# rgb_val_int = int(rgb_val)
# if rgb_val_int < 0:
# raise ValueError("RGB value must not be negative.")
# if rgb_val_int > 0xffffff:
# raise ValueError("RGB value must not be greater than 0xffffff.")
# self._rgb_val = rgb_val_int
#
# def _get_rgb_val(self):
# return self._rgb_val
#
# rgb_val = property(_get_rgb_val)
#
# def _get_rgba_val(self):
# return self._rgb_val << 8
#
# rgba_val = property(_get_rgba_val)
#
# def to_hex_string(self):
# return "{0:06x}".format(self._rgb_val)
#
# def color_from_hex_string(hex_string):
# return Color(int(hex_string, 16))
#
# Path: pytrainer/lib/ddbb.py
# class DDBB(Singleton):
# class ForcedInteger(TypeDecorator):
# def __init__(self, url=None):
# def get_connection_url(self):
# def connect(self):
# def disconnect(self):
# def select(self,table,cells,condition=None, mod=None):
# def create_tables(self, add_default=True):
# def drop_tables(self):
# def create_backup(self):
# def process_bind_param(self, value, dialect):
. Output only the next line. | if sport_id is None: |
Given the following code snippet before the placeholder: <|code_start|> def get_sport(self, sport_id):
"""Get the sport with the specified id.
If no sport with the given id exists then None is returned."""
if sport_id is None:
raise ValueError("Sport id cannot be None")
try:
return self._ddbb.session.query(Sport).filter(Sport.id == sport_id).one()
except NoResultFound:
return None
def get_sport_by_name(self, name):
"""Get the sport with the specified name.
If no sport with the given name exists then None is returned."""
if name is None:
raise ValueError("Sport name cannot be None")
try:
return self._ddbb.session.query(Sport).filter(Sport.name == name).one()
except NoResultFound:
return None
def get_all_sports(self):
"""Get all stored sports."""
return self._ddbb.session.query(Sport).all()
def store_sport(self, sport):
"""Store a new or update an existing sport.
The stored object is returned."""
<|code_end|>
, predict the next line using imports from the current file:
from pytrainer.util.color import Color, color_from_hex_string
from pytrainer.lib.ddbb import DeclarativeBase, ForcedInteger
from sqlalchemy import Column, Integer, Float, Unicode, CheckConstraint
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import InvalidRequestError, IntegrityError
import sqlalchemy.types as types
import logging
and context including class names, function names, and sometimes code from other files:
# Path: pytrainer/util/color.py
# class Color(object):
#
# """A color represented as a 24-bit RGB value."""
#
# def __init__(self, rgb_val=0):
# rgb_val_int = int(rgb_val)
# if rgb_val_int < 0:
# raise ValueError("RGB value must not be negative.")
# if rgb_val_int > 0xffffff:
# raise ValueError("RGB value must not be greater than 0xffffff.")
# self._rgb_val = rgb_val_int
#
# def _get_rgb_val(self):
# return self._rgb_val
#
# rgb_val = property(_get_rgb_val)
#
# def _get_rgba_val(self):
# return self._rgb_val << 8
#
# rgba_val = property(_get_rgba_val)
#
# def to_hex_string(self):
# return "{0:06x}".format(self._rgb_val)
#
# def color_from_hex_string(hex_string):
# return Color(int(hex_string, 16))
#
# Path: pytrainer/lib/ddbb.py
# class DDBB(Singleton):
# class ForcedInteger(TypeDecorator):
# def __init__(self, url=None):
# def get_connection_url(self):
# def connect(self):
# def disconnect(self):
# def select(self,table,cells,condition=None, mod=None):
# def create_tables(self, add_default=True):
# def drop_tables(self):
# def create_backup(self):
# def process_bind_param(self, value, dialect):
. Output only the next line. | try: |
Predict the next line after this snippet: <|code_start|> def get_sport_by_name(self, name):
"""Get the sport with the specified name.
If no sport with the given name exists then None is returned."""
if name is None:
raise ValueError("Sport name cannot be None")
try:
return self._ddbb.session.query(Sport).filter(Sport.name == name).one()
except NoResultFound:
return None
def get_all_sports(self):
"""Get all stored sports."""
return self._ddbb.session.query(Sport).all()
def store_sport(self, sport):
"""Store a new or update an existing sport.
The stored object is returned."""
try:
self._ddbb.session.add(sport)
self._ddbb.session.commit()
except IntegrityError:
raise SportServiceException("")
return sport
def remove_sport(self, sport):
"""Delete a stored sport.
All records associated with the sport will also be deleted."""
<|code_end|>
using the current file's imports:
from pytrainer.util.color import Color, color_from_hex_string
from pytrainer.lib.ddbb import DeclarativeBase, ForcedInteger
from sqlalchemy import Column, Integer, Float, Unicode, CheckConstraint
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import InvalidRequestError, IntegrityError
import sqlalchemy.types as types
import logging
and any relevant context from other files:
# Path: pytrainer/util/color.py
# class Color(object):
#
# """A color represented as a 24-bit RGB value."""
#
# def __init__(self, rgb_val=0):
# rgb_val_int = int(rgb_val)
# if rgb_val_int < 0:
# raise ValueError("RGB value must not be negative.")
# if rgb_val_int > 0xffffff:
# raise ValueError("RGB value must not be greater than 0xffffff.")
# self._rgb_val = rgb_val_int
#
# def _get_rgb_val(self):
# return self._rgb_val
#
# rgb_val = property(_get_rgb_val)
#
# def _get_rgba_val(self):
# return self._rgb_val << 8
#
# rgba_val = property(_get_rgba_val)
#
# def to_hex_string(self):
# return "{0:06x}".format(self._rgb_val)
#
# def color_from_hex_string(hex_string):
# return Color(int(hex_string, 16))
#
# Path: pytrainer/lib/ddbb.py
# class DDBB(Singleton):
# class ForcedInteger(TypeDecorator):
# def __init__(self, url=None):
# def get_connection_url(self):
# def connect(self):
# def disconnect(self):
# def select(self,table,cells,condition=None, mod=None):
# def create_tables(self, add_default=True):
# def drop_tables(self):
# def create_backup(self):
# def process_bind_param(self, value, dialect):
. Output only the next line. | if not sport.id: |
Here is a snippet: <|code_start|> mainNS = string.Template(".//{http://www.topografix.com/GPX/1/0}$tag")
timeTag = mainNS.substitute(tag="time")
trackTag = mainNS.substitute(tag="trk")
trackPointTag = mainNS.substitute(tag="trkpt")
trackPointTagLast = mainNS.substitute(tag="trkpt[last()]")
trackSegTag = mainNS.substitute(tag="trkseg")
elevationTag = mainNS.substitute(tag="ele")
nameTag = mainNS.substitute(tag="name")
else:
logging.debug("Importing version %s gpx file" % self.tree.get("version"))
mainNS = string.Template(".//{http://www.topografix.com/GPX/1/1}$tag")
timeTag = mainNS.substitute(tag="time")
trackTag = mainNS.substitute(tag="trk")
trackPointTag = mainNS.substitute(tag="trkpt")
trackPointTagLast = mainNS.substitute(tag="trkpt[last()]")
trackSegTag = mainNS.substitute(tag="trkseg")
elevationTag = mainNS.substitute(tag="ele")
nameTag = mainNS.substitute(tag="name")
intensityTag = mainNS.substitute(tag="intensity")
logging.debug("getting values...")
self.Values = self._getValues()
logging.debug("<<")
def getMaxValues(self):
return self.total_dist, self.total_time, self.maxvel, self.maxhr
def getDate(self):
return self.date
<|code_end|>
. Write the next line using the current file imports:
import sys
import string
import math
import re
import os
import time
import logging
from datetime import datetime
from lxml import etree
from pytrainer.lib.date import getDateTime
and context from other files:
# Path: pytrainer/lib/date.py
# def getDateTime(time_):
# # Time can be in multiple formats
# # - zulu 2009-12-15T09:00Z
# # - local ISO8601 2009-12-15T10:00+01:00
# try:
# dateTime = dateutil.parser.parse(time_)
# except ValueError as e:
# logging.debug("Unable to parse %s as a date time" % time_)
# logging.debug(str(e))
# return (None, None)
# timezone = dateTime.tzinfo
# if timezone is None: #got a naive time, so assume is local time
# local_dateTime = dateTime.replace(tzinfo=tzlocal())
# elif timezone == tzutc(): #got a zulu time
# local_dateTime = dateTime.astimezone(tzlocal()) #datetime with localtime offset (from OS)
# else:
# local_dateTime = dateTime #use datetime as supplied
# utc_dateTime = local_dateTime.astimezone(tzutc()) #datetime with 00:00 offset
# return (utc_dateTime,local_dateTime)
, which may include functions, classes, or code. Output only the next line. | def getTrackRoutes(self): |
Next line prediction: <|code_start|> else:
strElapsedTime = "%0.0fs" % (elapsedTimeSecs)
#process lat and lon for this lap
try:
lapLat = float(lap['end_lat'])
lapLon = float(lap['end_lon'])
content += "var lap%dmarker = new google.maps.Marker({position: new google.maps.LatLng(%f, %f), icon: lapimage, map: map, title:\"Lap%d\"}); \n " % (lapNumber, lapLat, lapLon, lapNumber)
content += "var lap%d = new google.maps.InfoWindow({content: \"<div class='info_content'>End of lap:%s<br>Elapsed time:%s<br>Distance:%0.2f km<br>Calories:%s</div>\" });\n" % (lapNumber, lapNumber, strElapsedTime, float(lap['distance'])/1000, lap['calories'])
content += "google.maps.event.addListener(lap%dmarker, 'click', function() { lap%d.open(map,lap%dmarker); });\n" % (lapNumber,lapNumber,lapNumber)
except Exception as e:
#Error processing lap lat or lon
#dont show this lap
logging.debug( "Error processing lap "+ str(lap) )
logging.debug(str(e))
content += '''
var boundsBox = new google.maps.LatLngBounds(swlatlng, nelatlng );\n
map.fitBounds(boundsBox);\n'''
pre = 0
for point in polyline:
if pre:
content += '''var polylineCoordinates = [\n'''
content += " %s,\n" % (pre[0])
content += " %s,\n" % (point[0])
content += ''' ];\n
// Add a polyline.\n
var polyline = new google.maps.Polyline({\n
path: polylineCoordinates,\n
<|code_end|>
. Use current file imports:
(import os
import re
import logging
import colorsys
import math
import traceback
import html
import cgi as html
import pytrainer.lib.points as Points
from pytrainer.lib.fileUtils import fileUtils
from pytrainer.lib.uc import UC)
and context including class names, function names, or small code snippets from other files:
# Path: pytrainer/lib/fileUtils.py
# class fileUtils:
# def __init__(self, filename, data):
# self.filename = filename
# self.data = data
#
# def run(self):
# logging.debug('>>')
# if self.data is not None:
# logging.debug("Writing in %s " % self.filename)
# out = open(self.filename, 'w')
# out.write(self.data)
# out.close()
# else:
# logging.error("Nothing to write in %s" % self.filename)
# logging.debug('<<')
#
# Path: pytrainer/lib/uc.py
# class UC(Singleton):
# """
# When instantiated first time us is assigned to False.
# us = False; user system is metric
# us = True ; user system is imperial
# """
#
# """ Units of physical quantities [metric, imperial] """
# uc_units = {'distance' : [_('km'),_('mi')] , 'speed' : [_('km/h'), _('mph')],
# 'pace' : [_('min/km'),_('min/mi')], 'height' : [_('m'), _('ft')],
# 'weight': [_('kg'), _('lb')]}
#
# """ Conversion factors from metric to imperial, units as in uc_units """
# uc_factors = {'distance' : 0.621371192, 'speed': 0.621371192, 'pace':1.609344,
# 'height': 3.2808399, 'weight': 2.204624, 'none': 1}
#
# def __init__(self):
# if not hasattr(self, 'us'):
# self.us = False
#
# def __str__(self):
# if self.us:
# return 'imperial'
# else:
# return 'metric'
#
# def set_us(self, us):
# if type(us) == bool:
# self.us = us
#
# def get_unit(self, quantity):
# if self.us:
# return self.uc_units[quantity][1]
# else:
# return self.uc_units[quantity][0]
#
# unit_distance = property(lambda self: self.get_unit('distance') )
# unit_speed = property( lambda self: self.get_unit('speed') )
# unit_pace = property( lambda self: self.get_unit('pace') )
# unit_height = property( lambda self: self.get_unit('height') )
# unit_weight = property( lambda self: self.get_unit('weight') )
#
# def sys2usr(self, quantity, value):
# """ Gives value of physical quantity (metric) in users system"""
# try:
# _val = float(value)
# except (ValueError, TypeError):
# return None
# if self.us:
# return _val * self.uc_factors[quantity]
# else:
# return _val
#
# def usr2sys(self, quantity, value):
# """ Takes value (users system) and convert to metric (sys)"""
# try:
# _val = float(value)
# except (ValueError, TypeError):
# return None
# if self.us:
# return _val / self.uc_factors[quantity]
# else:
# return _val
#
# def usr2sys_str(self, quantity, val_str):
# """ Similar to usr2sys but I/O is string representing a float.
# Necessary until we have proper input validation in windowrecord.
# Escpecially pace fix here should be eliminated asap.
# """
# if not self.us:
# return val_str
#
# if quantity == 'pace':
# _pace_dec = pace2float(val_str)
# _pace_uc = self.usr2sys('pace', _pace_dec)
# return float2pace(_pace_uc)
# else:
# try:
# _val = float(val_str)
# except (ValueError, TypeError):
# return ""
# return str( self.usr2sys(quantity, _val))
#
# """ Aliases for sys2usr """
# def distance(self, value):
# return self.sys2usr('distance', value)
# def speed(self, value):
# return self.sys2usr('speed', value)
# def pace(self, value):
# return self.sys2usr('pace', value)
# def height(self, value):
# return self.sys2usr('height', value)
# def weight(self, value):
# return self.sys2usr('weight', value)
. Output only the next line. | strokeColor: \"%s\",\n |
Continue the code snippet: <|code_start|>
try:
except ImportError:
class Googlemaps:
def __init__(self, data_path = None, waypoint = None, pytrainer_main=None):
logging.debug(">>")
self.data_path = data_path
self.waypoint=waypoint
self.pytrainer_main = pytrainer_main
self.htmlfile = "%s/googlemaps.html" % (self.pytrainer_main.profile.tmpdir)
self.uc = UC()
logging.debug("<<")
def colorLine(self, polyline, average, variance):
stdev = math.sqrt(variance)
for i in polyline:
speed = i[1]
speed = (speed - (average - 2*stdev))/(4*stdev)
speed = min(max(speed,0), 1)
rgb_tuple = colorsys.hsv_to_rgb(0.66-(speed*0.66), 1, 0.8)
rgb_tuple = (int(rgb_tuple[0] * 255),int(rgb_tuple[1] * 255),int(rgb_tuple[2] * 255))
i[2] = '#%02x%02x%02x' % rgb_tuple
def colorLineAbs(self, polyline):
for i in polyline:
speed = i[1]
if 0 <= speed < 7.5: #walk
rgb_tuple = colorsys.hsv_to_rgb(0.66, 1, (speed/7.5)*0.6)
<|code_end|>
. Use current file imports:
import os
import re
import logging
import colorsys
import math
import traceback
import html
import cgi as html
import pytrainer.lib.points as Points
from pytrainer.lib.fileUtils import fileUtils
from pytrainer.lib.uc import UC
and context (classes, functions, or code) from other files:
# Path: pytrainer/lib/fileUtils.py
# class fileUtils:
# def __init__(self, filename, data):
# self.filename = filename
# self.data = data
#
# def run(self):
# logging.debug('>>')
# if self.data is not None:
# logging.debug("Writing in %s " % self.filename)
# out = open(self.filename, 'w')
# out.write(self.data)
# out.close()
# else:
# logging.error("Nothing to write in %s" % self.filename)
# logging.debug('<<')
#
# Path: pytrainer/lib/uc.py
# class UC(Singleton):
# """
# When instantiated first time us is assigned to False.
# us = False; user system is metric
# us = True ; user system is imperial
# """
#
# """ Units of physical quantities [metric, imperial] """
# uc_units = {'distance' : [_('km'),_('mi')] , 'speed' : [_('km/h'), _('mph')],
# 'pace' : [_('min/km'),_('min/mi')], 'height' : [_('m'), _('ft')],
# 'weight': [_('kg'), _('lb')]}
#
# """ Conversion factors from metric to imperial, units as in uc_units """
# uc_factors = {'distance' : 0.621371192, 'speed': 0.621371192, 'pace':1.609344,
# 'height': 3.2808399, 'weight': 2.204624, 'none': 1}
#
# def __init__(self):
# if not hasattr(self, 'us'):
# self.us = False
#
# def __str__(self):
# if self.us:
# return 'imperial'
# else:
# return 'metric'
#
# def set_us(self, us):
# if type(us) == bool:
# self.us = us
#
# def get_unit(self, quantity):
# if self.us:
# return self.uc_units[quantity][1]
# else:
# return self.uc_units[quantity][0]
#
# unit_distance = property(lambda self: self.get_unit('distance') )
# unit_speed = property( lambda self: self.get_unit('speed') )
# unit_pace = property( lambda self: self.get_unit('pace') )
# unit_height = property( lambda self: self.get_unit('height') )
# unit_weight = property( lambda self: self.get_unit('weight') )
#
# def sys2usr(self, quantity, value):
# """ Gives value of physical quantity (metric) in users system"""
# try:
# _val = float(value)
# except (ValueError, TypeError):
# return None
# if self.us:
# return _val * self.uc_factors[quantity]
# else:
# return _val
#
# def usr2sys(self, quantity, value):
# """ Takes value (users system) and convert to metric (sys)"""
# try:
# _val = float(value)
# except (ValueError, TypeError):
# return None
# if self.us:
# return _val / self.uc_factors[quantity]
# else:
# return _val
#
# def usr2sys_str(self, quantity, val_str):
# """ Similar to usr2sys but I/O is string representing a float.
# Necessary until we have proper input validation in windowrecord.
# Escpecially pace fix here should be eliminated asap.
# """
# if not self.us:
# return val_str
#
# if quantity == 'pace':
# _pace_dec = pace2float(val_str)
# _pace_uc = self.usr2sys('pace', _pace_dec)
# return float2pace(_pace_uc)
# else:
# try:
# _val = float(val_str)
# except (ValueError, TypeError):
# return ""
# return str( self.usr2sys(quantity, _val))
#
# """ Aliases for sys2usr """
# def distance(self, value):
# return self.sys2usr('distance', value)
# def speed(self, value):
# return self.sys2usr('speed', value)
# def pace(self, value):
# return self.sys2usr('pace', value)
# def height(self, value):
# return self.sys2usr('height', value)
# def weight(self, value):
# return self.sys2usr('weight', value)
. Output only the next line. | elif 7.5 <= speed < 15: #jog-run |
Here is a snippet: <|code_start|> equipment.life_expectancy = "3"
self.ddbb.session.add(equipment)
self.ddbb.session.commit()
self.assertEqual(3, equipment.life_expectancy)
def test_life_expectancy_set_to_non_numeric_string(self):
equipment = Equipment()
equipment.life_expectancy = "test"
try:
self.ddbb.session.add(equipment)
self.ddbb.session.flush()
except StatementError:
pass
else:
self.fail("Should not be able to set life expectancy to non numeric value.")
def test_prior_usage_defaults_to_zero(self):
equipment = Equipment()
self.assertEqual(0, equipment.prior_usage)
def test_prior_usage_set_to_integer(self):
equipment = Equipment()
equipment.prior_usage = 2
self.assertEqual(2, equipment.prior_usage)
def test_prior_usage_set_to_numeric_string(self):
equipment = Equipment()
equipment.prior_usage = "3"
self.ddbb.session.add(equipment)
self.ddbb.session.commit()
<|code_end|>
. Write the next line using the current file imports:
import unittest
import sys
from pytrainer.core.equipment import Equipment, EquipmentService,\
EquipmentServiceException
from pytrainer.lib.ddbb import DDBB, DeclarativeBase
from sqlalchemy.exc import StatementError, IntegrityError, ProgrammingError, OperationalError, DataError
and context from other files:
# Path: pytrainer/core/equipment.py
# class Equipment(DeclarativeBase):
# """An equipment item that can be used during an activity, such as a pair of running shoes."""
#
# __tablename__ = 'equipment'
# active = Column(Boolean)
# description = Column(Unicode(length=100), unique=True, index=True)
# id = Column(Integer, primary_key=True)
# life_expectancy = Column(ForcedInteger)
# notes = Column(UnicodeText)
# prior_usage = Column(ForcedInteger)
#
# def __init__(self, **kwargs):
# self.description = u""
# self.active = True
# self.life_expectancy = 0
# self.prior_usage = 0
# self.notes = u""
# super(Equipment, self).__init__(**kwargs)
#
# def __eq__(self, o):
# if isinstance(o, Equipment):
# if self.id is not None and o.id is not None:
# return self.id == o.id
# return False
#
# def __hash__(self):
# if self.id is not None:
# return self.id
# else:
# return object.__hash__(self)
#
# class EquipmentService(object):
#
# """Provides access to stored equipment items."""
#
# def __init__(self, ddbb):
# self._ddbb = ddbb
#
# def get_all_equipment(self):
# """Get all equipment items."""
# return self._ddbb.session.query(Equipment).all()
#
# def get_active_equipment(self):
# """Get all the active equipment items."""
# return self._ddbb.session.query(Equipment).filter(Equipment.active == True).all()
#
# def get_equipment_item(self, item_id):
# """Get an individual equipment item by id.
#
# If no item with the given id exists then None is returned.
# """
# try:
# return self._ddbb.session.query(Equipment).filter(Equipment.id == item_id).one()
# except exc.NoResultFound:
# return None
#
# def store_equipment(self, equipment):
# """Store a new or update an existing equipment item.
#
# The stored object is returned."""
# logging.debug("Storing equipment item.")
# try:
# self._ddbb.session.add(equipment)
# self._ddbb.session.commit()
# except IntegrityError:
# raise EquipmentServiceException("An equipment item already exists with description '{0}'".format(equipment.description))
# return equipment
#
# def remove_equipment(self, equipment):
# """Remove an existing equipment item."""
# logging.debug("Deleting equipment item with id: '{0}'".format(equipment.id))
# self._ddbb.session.delete(equipment)
# self._ddbb.session.commit()
#
# def get_equipment_usage(self, equipment):
# """Get the total use of the given equipment."""
# result = self._ddbb.session.query(func.sum(Activity.distance).label('sum')).filter(Activity.equipment.contains(equipment))
# usage = result.scalar()
# return (0 if usage == None else float(usage)) + equipment.prior_usage
#
# class EquipmentServiceException(Exception):
#
# def __init__(self, value):
# self.value = value
#
# def __str__(self):
# return repr(self.value)
#
# Path: pytrainer/lib/ddbb.py
# class DDBB(Singleton):
# class ForcedInteger(TypeDecorator):
# def __init__(self, url=None):
# def get_connection_url(self):
# def connect(self):
# def disconnect(self):
# def select(self,table,cells,condition=None, mod=None):
# def create_tables(self, add_default=True):
# def drop_tables(self):
# def create_backup(self):
# def process_bind_param(self, value, dialect):
, which may include functions, classes, or code. Output only the next line. | self.assertEqual(3, equipment.prior_usage) |
Predict the next line for this snippet: <|code_start|> pass
else:
self.fail("Should not be able to set equipment id to non numeric value.")
def test_description_defaults_to_empty_string(self):
equipment = Equipment()
self.assertEqual(u"", equipment.description)
@unittest.skipIf(sys.version_info > (3, 0), "All strings are unicode in Python 3")
def test_description_set_to_non_unicode_string(self):
equipment = Equipment()
equipment.description = "100$ Shoes" + chr(255)
try:
self.ddbb.session.add(equipment)
self.ddbb.session.flush()
except (ProgrammingError, DataError, OperationalError):
pass
else:
self.fail("Should not be able to set description to non unicode string value.")
def test_description_set_to_unicode_string(self):
equipment = Equipment()
equipment.description = u"Zapatos de €100"
self.assertEqual(u"Zapatos de €100", equipment.description)
def test_description_set_to_non_string(self):
equipment = Equipment()
equipment.description = 42
self.ddbb.session.add(equipment)
self.ddbb.session.commit()
<|code_end|>
with the help of current file imports:
import unittest
import sys
from pytrainer.core.equipment import Equipment, EquipmentService,\
EquipmentServiceException
from pytrainer.lib.ddbb import DDBB, DeclarativeBase
from sqlalchemy.exc import StatementError, IntegrityError, ProgrammingError, OperationalError, DataError
and context from other files:
# Path: pytrainer/core/equipment.py
# class Equipment(DeclarativeBase):
# """An equipment item that can be used during an activity, such as a pair of running shoes."""
#
# __tablename__ = 'equipment'
# active = Column(Boolean)
# description = Column(Unicode(length=100), unique=True, index=True)
# id = Column(Integer, primary_key=True)
# life_expectancy = Column(ForcedInteger)
# notes = Column(UnicodeText)
# prior_usage = Column(ForcedInteger)
#
# def __init__(self, **kwargs):
# self.description = u""
# self.active = True
# self.life_expectancy = 0
# self.prior_usage = 0
# self.notes = u""
# super(Equipment, self).__init__(**kwargs)
#
# def __eq__(self, o):
# if isinstance(o, Equipment):
# if self.id is not None and o.id is not None:
# return self.id == o.id
# return False
#
# def __hash__(self):
# if self.id is not None:
# return self.id
# else:
# return object.__hash__(self)
#
# class EquipmentService(object):
#
# """Provides access to stored equipment items."""
#
# def __init__(self, ddbb):
# self._ddbb = ddbb
#
# def get_all_equipment(self):
# """Get all equipment items."""
# return self._ddbb.session.query(Equipment).all()
#
# def get_active_equipment(self):
# """Get all the active equipment items."""
# return self._ddbb.session.query(Equipment).filter(Equipment.active == True).all()
#
# def get_equipment_item(self, item_id):
# """Get an individual equipment item by id.
#
# If no item with the given id exists then None is returned.
# """
# try:
# return self._ddbb.session.query(Equipment).filter(Equipment.id == item_id).one()
# except exc.NoResultFound:
# return None
#
# def store_equipment(self, equipment):
# """Store a new or update an existing equipment item.
#
# The stored object is returned."""
# logging.debug("Storing equipment item.")
# try:
# self._ddbb.session.add(equipment)
# self._ddbb.session.commit()
# except IntegrityError:
# raise EquipmentServiceException("An equipment item already exists with description '{0}'".format(equipment.description))
# return equipment
#
# def remove_equipment(self, equipment):
# """Remove an existing equipment item."""
# logging.debug("Deleting equipment item with id: '{0}'".format(equipment.id))
# self._ddbb.session.delete(equipment)
# self._ddbb.session.commit()
#
# def get_equipment_usage(self, equipment):
# """Get the total use of the given equipment."""
# result = self._ddbb.session.query(func.sum(Activity.distance).label('sum')).filter(Activity.equipment.contains(equipment))
# usage = result.scalar()
# return (0 if usage == None else float(usage)) + equipment.prior_usage
#
# class EquipmentServiceException(Exception):
#
# def __init__(self, value):
# self.value = value
#
# def __str__(self):
# return repr(self.value)
#
# Path: pytrainer/lib/ddbb.py
# class DDBB(Singleton):
# class ForcedInteger(TypeDecorator):
# def __init__(self, url=None):
# def get_connection_url(self):
# def connect(self):
# def disconnect(self):
# def select(self,table,cells,condition=None, mod=None):
# def create_tables(self, add_default=True):
# def drop_tables(self):
# def create_backup(self):
# def process_bind_param(self, value, dialect):
, which may contain function names, class names, or code. Output only the next line. | self.assertEqual(u"42", equipment.description) |
Next line prediction: <|code_start|> "prior_usage": 300, "active": True})
items = self.equipment_service.get_active_equipment()
item = items[0]
self.assertEqual(1, item.id)
self.assertEqual("Test item 1", item.description)
self.assertTrue(item.active)
self.assertEqual(500, item.life_expectancy)
self.assertEqual(200, item.prior_usage)
self.assertEqual("Test notes 1.", item.notes)
item = items[1]
self.assertEqual(2, item.id)
self.assertEqual("Test item 2", item.description)
self.assertTrue(item.active)
self.assertEqual(600, item.life_expectancy)
self.assertEqual(300, item.prior_usage)
self.assertEqual("Test notes 2.", item.notes)
def test_get_active_equipment_non_existant(self):
items = self.equipment_service.get_active_equipment()
self.assertEqual([], items)
def test_store_equipment(self):
equipment = Equipment()
equipment.description = u"test description"
stored_equipment = self.equipment_service.store_equipment(equipment)
self.assertEqual(1, stored_equipment.id)
def test_store_equipment_duplicate_description(self):
self.mock_ddbb.session.execute(self.equipment_table.insert(),
{"life_expectancy": 500,
<|code_end|>
. Use current file imports:
(import unittest
import sys
from pytrainer.core.equipment import Equipment, EquipmentService,\
EquipmentServiceException
from pytrainer.lib.ddbb import DDBB, DeclarativeBase
from sqlalchemy.exc import StatementError, IntegrityError, ProgrammingError, OperationalError, DataError)
and context including class names, function names, or small code snippets from other files:
# Path: pytrainer/core/equipment.py
# class Equipment(DeclarativeBase):
# """An equipment item that can be used during an activity, such as a pair of running shoes."""
#
# __tablename__ = 'equipment'
# active = Column(Boolean)
# description = Column(Unicode(length=100), unique=True, index=True)
# id = Column(Integer, primary_key=True)
# life_expectancy = Column(ForcedInteger)
# notes = Column(UnicodeText)
# prior_usage = Column(ForcedInteger)
#
# def __init__(self, **kwargs):
# self.description = u""
# self.active = True
# self.life_expectancy = 0
# self.prior_usage = 0
# self.notes = u""
# super(Equipment, self).__init__(**kwargs)
#
# def __eq__(self, o):
# if isinstance(o, Equipment):
# if self.id is not None and o.id is not None:
# return self.id == o.id
# return False
#
# def __hash__(self):
# if self.id is not None:
# return self.id
# else:
# return object.__hash__(self)
#
# class EquipmentService(object):
#
# """Provides access to stored equipment items."""
#
# def __init__(self, ddbb):
# self._ddbb = ddbb
#
# def get_all_equipment(self):
# """Get all equipment items."""
# return self._ddbb.session.query(Equipment).all()
#
# def get_active_equipment(self):
# """Get all the active equipment items."""
# return self._ddbb.session.query(Equipment).filter(Equipment.active == True).all()
#
# def get_equipment_item(self, item_id):
# """Get an individual equipment item by id.
#
# If no item with the given id exists then None is returned.
# """
# try:
# return self._ddbb.session.query(Equipment).filter(Equipment.id == item_id).one()
# except exc.NoResultFound:
# return None
#
# def store_equipment(self, equipment):
# """Store a new or update an existing equipment item.
#
# The stored object is returned."""
# logging.debug("Storing equipment item.")
# try:
# self._ddbb.session.add(equipment)
# self._ddbb.session.commit()
# except IntegrityError:
# raise EquipmentServiceException("An equipment item already exists with description '{0}'".format(equipment.description))
# return equipment
#
# def remove_equipment(self, equipment):
# """Remove an existing equipment item."""
# logging.debug("Deleting equipment item with id: '{0}'".format(equipment.id))
# self._ddbb.session.delete(equipment)
# self._ddbb.session.commit()
#
# def get_equipment_usage(self, equipment):
# """Get the total use of the given equipment."""
# result = self._ddbb.session.query(func.sum(Activity.distance).label('sum')).filter(Activity.equipment.contains(equipment))
# usage = result.scalar()
# return (0 if usage == None else float(usage)) + equipment.prior_usage
#
# class EquipmentServiceException(Exception):
#
# def __init__(self, value):
# self.value = value
#
# def __str__(self):
# return repr(self.value)
#
# Path: pytrainer/lib/ddbb.py
# class DDBB(Singleton):
# class ForcedInteger(TypeDecorator):
# def __init__(self, url=None):
# def get_connection_url(self):
# def connect(self):
# def disconnect(self):
# def select(self,table,cells,condition=None, mod=None):
# def create_tables(self, add_default=True):
# def drop_tables(self):
# def create_backup(self):
# def process_bind_param(self, value, dialect):
. Output only the next line. | "notes": u"Test notes.", |
Next line prediction: <|code_start|> self.assertEqual("Test Description", item.description)
self.assertTrue(item.active)
self.assertEqual(500, item.life_expectancy)
self.assertEqual(200, item.prior_usage)
self.assertEqual("Test notes.", item.notes)
def test_get_equipment_item_non_unicode(self):
self.mock_ddbb.session.execute(self.equipment_table.insert(),
{"life_expectancy": 500,
"notes": u"Test notes.",
"description": u"Test Description",
"prior_usage": 200, "active": True})
item = self.equipment_service.get_equipment_item(1)
self.assertEqual("Test Description", item.description)
self.assertEqual("Test notes.", item.notes)
def test_get_equipment_item_non_existant(self):
item = self.equipment_service.get_equipment_item(1)
self.assertEqual(None, item)
def test_get_all_equipment(self):
self.mock_ddbb.session.execute(self.equipment_table.insert(),
{"life_expectancy": 500,
"notes": u"Test notes 1.",
"description": u"Test item 1",
"prior_usage": 200, "active": True})
self.mock_ddbb.session.execute(self.equipment_table.insert(),
{"life_expectancy": 600,
"notes": u"Test notes 2.",
"description": u"Test item 2",
<|code_end|>
. Use current file imports:
(import unittest
import sys
from pytrainer.core.equipment import Equipment, EquipmentService,\
EquipmentServiceException
from pytrainer.lib.ddbb import DDBB, DeclarativeBase
from sqlalchemy.exc import StatementError, IntegrityError, ProgrammingError, OperationalError, DataError)
and context including class names, function names, or small code snippets from other files:
# Path: pytrainer/core/equipment.py
# class Equipment(DeclarativeBase):
# """An equipment item that can be used during an activity, such as a pair of running shoes."""
#
# __tablename__ = 'equipment'
# active = Column(Boolean)
# description = Column(Unicode(length=100), unique=True, index=True)
# id = Column(Integer, primary_key=True)
# life_expectancy = Column(ForcedInteger)
# notes = Column(UnicodeText)
# prior_usage = Column(ForcedInteger)
#
# def __init__(self, **kwargs):
# self.description = u""
# self.active = True
# self.life_expectancy = 0
# self.prior_usage = 0
# self.notes = u""
# super(Equipment, self).__init__(**kwargs)
#
# def __eq__(self, o):
# if isinstance(o, Equipment):
# if self.id is not None and o.id is not None:
# return self.id == o.id
# return False
#
# def __hash__(self):
# if self.id is not None:
# return self.id
# else:
# return object.__hash__(self)
#
# class EquipmentService(object):
#
# """Provides access to stored equipment items."""
#
# def __init__(self, ddbb):
# self._ddbb = ddbb
#
# def get_all_equipment(self):
# """Get all equipment items."""
# return self._ddbb.session.query(Equipment).all()
#
# def get_active_equipment(self):
# """Get all the active equipment items."""
# return self._ddbb.session.query(Equipment).filter(Equipment.active == True).all()
#
# def get_equipment_item(self, item_id):
# """Get an individual equipment item by id.
#
# If no item with the given id exists then None is returned.
# """
# try:
# return self._ddbb.session.query(Equipment).filter(Equipment.id == item_id).one()
# except exc.NoResultFound:
# return None
#
# def store_equipment(self, equipment):
# """Store a new or update an existing equipment item.
#
# The stored object is returned."""
# logging.debug("Storing equipment item.")
# try:
# self._ddbb.session.add(equipment)
# self._ddbb.session.commit()
# except IntegrityError:
# raise EquipmentServiceException("An equipment item already exists with description '{0}'".format(equipment.description))
# return equipment
#
# def remove_equipment(self, equipment):
# """Remove an existing equipment item."""
# logging.debug("Deleting equipment item with id: '{0}'".format(equipment.id))
# self._ddbb.session.delete(equipment)
# self._ddbb.session.commit()
#
# def get_equipment_usage(self, equipment):
# """Get the total use of the given equipment."""
# result = self._ddbb.session.query(func.sum(Activity.distance).label('sum')).filter(Activity.equipment.contains(equipment))
# usage = result.scalar()
# return (0 if usage == None else float(usage)) + equipment.prior_usage
#
# class EquipmentServiceException(Exception):
#
# def __init__(self, value):
# self.value = value
#
# def __str__(self):
# return repr(self.value)
#
# Path: pytrainer/lib/ddbb.py
# class DDBB(Singleton):
# class ForcedInteger(TypeDecorator):
# def __init__(self, url=None):
# def get_connection_url(self):
# def connect(self):
# def disconnect(self):
# def select(self,table,cells,condition=None, mod=None):
# def create_tables(self, add_default=True):
# def drop_tables(self):
# def create_backup(self):
# def process_bind_param(self, value, dialect):
. Output only the next line. | "prior_usage": 300, "active": False}) |
Given the code snippet: <|code_start|> self.ddbb.session.add(equipment)
self.ddbb.session.commit()
self.assertEqual(u"42", equipment.description)
def test_active_defaults_to_true(self):
equipment = Equipment()
self.assertTrue(equipment.active)
def test_active_set_to_boolean(self):
equipment = Equipment()
equipment.active = False
self.assertFalse(equipment.active)
def test_active_set_to_non_boolean(self):
equipment = Equipment()
equipment.active = "test"
self.ddbb.session.add(equipment)
try:
self.ddbb.session.commit()
self.assertTrue(equipment.active)
except StatementError:
pass
def test_life_expectancy_defaults_to_zero(self):
equipment = Equipment()
self.assertEqual(0, equipment.life_expectancy)
def test_life_expectancy_set_to_integer(self):
equipment = Equipment()
equipment.life_expectancy = 2
<|code_end|>
, generate the next line using the imports in this file:
import unittest
import sys
from pytrainer.core.equipment import Equipment, EquipmentService,\
EquipmentServiceException
from pytrainer.lib.ddbb import DDBB, DeclarativeBase
from sqlalchemy.exc import StatementError, IntegrityError, ProgrammingError, OperationalError, DataError
and context (functions, classes, or occasionally code) from other files:
# Path: pytrainer/core/equipment.py
# class Equipment(DeclarativeBase):
# """An equipment item that can be used during an activity, such as a pair of running shoes."""
#
# __tablename__ = 'equipment'
# active = Column(Boolean)
# description = Column(Unicode(length=100), unique=True, index=True)
# id = Column(Integer, primary_key=True)
# life_expectancy = Column(ForcedInteger)
# notes = Column(UnicodeText)
# prior_usage = Column(ForcedInteger)
#
# def __init__(self, **kwargs):
# self.description = u""
# self.active = True
# self.life_expectancy = 0
# self.prior_usage = 0
# self.notes = u""
# super(Equipment, self).__init__(**kwargs)
#
# def __eq__(self, o):
# if isinstance(o, Equipment):
# if self.id is not None and o.id is not None:
# return self.id == o.id
# return False
#
# def __hash__(self):
# if self.id is not None:
# return self.id
# else:
# return object.__hash__(self)
#
# class EquipmentService(object):
#
# """Provides access to stored equipment items."""
#
# def __init__(self, ddbb):
# self._ddbb = ddbb
#
# def get_all_equipment(self):
# """Get all equipment items."""
# return self._ddbb.session.query(Equipment).all()
#
# def get_active_equipment(self):
# """Get all the active equipment items."""
# return self._ddbb.session.query(Equipment).filter(Equipment.active == True).all()
#
# def get_equipment_item(self, item_id):
# """Get an individual equipment item by id.
#
# If no item with the given id exists then None is returned.
# """
# try:
# return self._ddbb.session.query(Equipment).filter(Equipment.id == item_id).one()
# except exc.NoResultFound:
# return None
#
# def store_equipment(self, equipment):
# """Store a new or update an existing equipment item.
#
# The stored object is returned."""
# logging.debug("Storing equipment item.")
# try:
# self._ddbb.session.add(equipment)
# self._ddbb.session.commit()
# except IntegrityError:
# raise EquipmentServiceException("An equipment item already exists with description '{0}'".format(equipment.description))
# return equipment
#
# def remove_equipment(self, equipment):
# """Remove an existing equipment item."""
# logging.debug("Deleting equipment item with id: '{0}'".format(equipment.id))
# self._ddbb.session.delete(equipment)
# self._ddbb.session.commit()
#
# def get_equipment_usage(self, equipment):
# """Get the total use of the given equipment."""
# result = self._ddbb.session.query(func.sum(Activity.distance).label('sum')).filter(Activity.equipment.contains(equipment))
# usage = result.scalar()
# return (0 if usage == None else float(usage)) + equipment.prior_usage
#
# class EquipmentServiceException(Exception):
#
# def __init__(self, value):
# self.value = value
#
# def __str__(self):
# return repr(self.value)
#
# Path: pytrainer/lib/ddbb.py
# class DDBB(Singleton):
# class ForcedInteger(TypeDecorator):
# def __init__(self, url=None):
# def get_connection_url(self):
# def connect(self):
# def disconnect(self):
# def select(self,table,cells,condition=None, mod=None):
# def create_tables(self, add_default=True):
# def drop_tables(self):
# def create_backup(self):
# def process_bind_param(self, value, dialect):
. Output only the next line. | self.assertEqual(2, equipment.life_expectancy) |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
#Copyright (C) Fiz Vazquez vud1@sindominio.net
# vud1@grupoikusnet.com
# Jakinbidea & Grupo Ikusnet Developer
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
def second2time(seconds):
if not seconds:
return 0,0,0
<|code_end|>
, predict the immediate next line with the help of imports:
import time
import datetime
import calendar
import dateutil.parser
import logging
from dateutil.tz import tzutc, tzlocal
from pytrainer.platform import get_platform
from pytrainer.lib.localization import locale_str
and context (classes, functions, sometimes code) from other files:
# Path: pytrainer/platform.py
# def get_platform():
# if os.name == "posix":
# return _Linux() #although not true, not changing original return name to avoid side effects
# elif os.name == "nt":
# return _Windows()
# else:
# logging.critical("Unsupported os.name: %s.", os.name)
# sys.exit(1)
#
# Path: pytrainer/lib/localization.py
# def locale_str(string):
# if sys.version_info[0] == 2:
# lcname, encoding=locale.getlocale()
# return string.decode(encoding)
# else:
# return string
. Output only the next line. | hours = seconds // (60*60) |
Given the code snippet: <|code_start|> return 0
else:
return self.get_value(y, 2)*100-self.get_value(x, 2)*100
def _append_row(self, equipment):
self.append(self._create_tuple(equipment))
def _create_tuple(self, equipment):
usage = self._equipment_service.get_equipment_usage(equipment) + equipment.prior_usage
return (equipment.id,
equipment.description,
self._calculate_usage_percent(usage, equipment.life_expectancy),
str(int(round(usage))) + " / " + str(equipment.life_expectancy),
equipment.active)
def _calculate_usage_percent(self, usage, life_expectancy):
if life_expectancy == 0:
return 0
else:
return min(100, 100.0 * usage / life_expectancy)
def add_equipment(self, equipment):
added_equipment = self._equipment_service.store_equipment(equipment)
self._append_row(added_equipment)
def get_equipment_item(self, item_path):
item = None
if item_path is not None:
item_id = self.get_value(self.get_iter(item_path), 0)
item = self._equipment_service.get_equipment_item(item_id)
<|code_end|>
, generate the next line using the imports in this file:
from gi.repository import Gtk
from pytrainer.core.equipment import Equipment
from pytrainer.lib.localization import gtk_str
and context (functions, classes, or occasionally code) from other files:
# Path: pytrainer/core/equipment.py
# class Equipment(DeclarativeBase):
# """An equipment item that can be used during an activity, such as a pair of running shoes."""
#
# __tablename__ = 'equipment'
# active = Column(Boolean)
# description = Column(Unicode(length=100), unique=True, index=True)
# id = Column(Integer, primary_key=True)
# life_expectancy = Column(ForcedInteger)
# notes = Column(UnicodeText)
# prior_usage = Column(ForcedInteger)
#
# def __init__(self, **kwargs):
# self.description = u""
# self.active = True
# self.life_expectancy = 0
# self.prior_usage = 0
# self.notes = u""
# super(Equipment, self).__init__(**kwargs)
#
# def __eq__(self, o):
# if isinstance(o, Equipment):
# if self.id is not None and o.id is not None:
# return self.id == o.id
# return False
#
# def __hash__(self):
# if self.id is not None:
# return self.id
# else:
# return object.__hash__(self)
#
# Path: pytrainer/lib/localization.py
# def gtk_str(string):
# """On Python 2 GTK returns all strings as UTF-8 encoded str. See
# https://python-gtk-3-tutorial.readthedocs.io/en/latest/unicode.html for
# more details."""
# if sys.version_info[0] == 2:
# if string is None:
# return None
# else:
# return string.decode('utf-8')
# else:
# return string
. Output only the next line. | return item |
Predict the next line after this snippet: <|code_start|> def show_page_equipment_add(self):
self._get_notebook().set_current_page(1)
self._builder.get_object("entryEquipmentAddDescription").grab_focus()
def show_page_equipment_edit(self):
self._get_notebook().set_current_page(2)
def show_page_equipment_delete(self):
self._get_notebook().set_current_page(3)
def _add_equipment_clicked(self, widget):
self.clear_add_equipment_fields()
self.show_page_equipment_add()
def _cancel_add_equipment_clicked(self, widget):
self.show_page_equipment_list()
def _confirm_add_equipment_clicked(self, widget):
#FIXME input validation for numeric fields
description = gtk_str(self._builder.get_object("entryEquipmentAddDescription").get_text())
life_expectancy = gtk_str(self._builder.get_object("entryEquipmentAddLifeExpectancy").get_text())
prior_usage = gtk_str(self._builder.get_object("entryEquipmentAddPriorUsage").get_text())
active = self._builder.get_object("checkbuttonEquipmentAddActive").get_active()
notes_buffer = self._builder.get_object("textviewEquipmentAddNotes").get_buffer()
notes = gtk_str(notes_buffer.get_text(notes_buffer.get_start_iter(),
notes_buffer.get_end_iter(), True))
new_equipment = Equipment()
new_equipment.description = description
new_equipment.active = bool(active)
new_equipment.life_expectancy = int(life_expectancy)
<|code_end|>
using the current file's imports:
from gi.repository import Gtk
from pytrainer.core.equipment import Equipment
from pytrainer.lib.localization import gtk_str
and any relevant context from other files:
# Path: pytrainer/core/equipment.py
# class Equipment(DeclarativeBase):
# """An equipment item that can be used during an activity, such as a pair of running shoes."""
#
# __tablename__ = 'equipment'
# active = Column(Boolean)
# description = Column(Unicode(length=100), unique=True, index=True)
# id = Column(Integer, primary_key=True)
# life_expectancy = Column(ForcedInteger)
# notes = Column(UnicodeText)
# prior_usage = Column(ForcedInteger)
#
# def __init__(self, **kwargs):
# self.description = u""
# self.active = True
# self.life_expectancy = 0
# self.prior_usage = 0
# self.notes = u""
# super(Equipment, self).__init__(**kwargs)
#
# def __eq__(self, o):
# if isinstance(o, Equipment):
# if self.id is not None and o.id is not None:
# return self.id == o.id
# return False
#
# def __hash__(self):
# if self.id is not None:
# return self.id
# else:
# return object.__hash__(self)
#
# Path: pytrainer/lib/localization.py
# def gtk_str(string):
# """On Python 2 GTK returns all strings as UTF-8 encoded str. See
# https://python-gtk-3-tutorial.readthedocs.io/en/latest/unicode.html for
# more details."""
# if sys.version_info[0] == 2:
# if string is None:
# return None
# else:
# return string.decode('utf-8')
# else:
# return string
. Output only the next line. | new_equipment.prior_usage = int(prior_usage) |
Next line prediction: <|code_start|> return retorno
def getAllWaypoints(self):
logging.debug(">>")
retorno = self.pytrainer_main.ddbb.select("waypoints","id_waypoint,lat,lon,ele,comment,time,name,sym","1=1 order by name")
logging.debug("<<")
return retorno
def actualize_fromgpx(self,gpxfile):
logging.debug(">>")
gpx = Gpx(self.data_path,gpxfile)
tracks = gpx.getTrackRoutes()
if len(tracks) > 1:
time = unixtime2date(tracks[0][1])
self.recordwindow.rcd_date.set_text(time)
self._actualize_fromgpx(gpx)
else:
msg = _("The gpx file seems to be a several days records. Perhaps you will need to edit your gpx file")
warning = Warning(self.data_path,self._actualize_fromgpx,[gpx])
warning.set_text(msg)
warning.run()
logging.debug("<<")
def _actualize_fromgpx(self, gpx):
logging.debug(">>")
distance, time = gpx.getMaxValues()
upositive,unegative = gpx.getUnevenness()
self.recordwindow.rcd_upositive.set_text(str(upositive))
self.recordwindow.rcd_unegative.set_text(str(unegative))
<|code_end|>
. Use current file imports:
(import logging
from pytrainer.lib.date import unixtime2date
from sqlalchemy import Column, Unicode, Float, Integer, Date
from pytrainer.lib.ddbb import DeclarativeBase
from .lib.gpx import Gpx
from .gui.warning import Warning)
and context including class names, function names, or small code snippets from other files:
# Path: pytrainer/lib/date.py
# def unixtime2date(unixtime):
# tm = time.gmtime(unixtime)
# year = tm[0]
# month = tm[1]
# day = tm[2]
# return "%0.4d-%0.2d-%0.2d" %(year,month,day)
#
# Path: pytrainer/lib/ddbb.py
# class DDBB(Singleton):
# class ForcedInteger(TypeDecorator):
# def __init__(self, url=None):
# def get_connection_url(self):
# def connect(self):
# def disconnect(self):
# def select(self,table,cells,condition=None, mod=None):
# def create_tables(self, add_default=True):
# def drop_tables(self):
# def create_backup(self):
# def process_bind_param(self, value, dialect):
. Output only the next line. | self.recordwindow.set_distance(distance) |
Using the snippet: <|code_start|> self.pytrainer_main.ddbb.session.add(waypoint)
self.pytrainer_main.ddbb.session.commit()
logging.debug("<<")
return waypoint.id
def getwaypointInfo(self,id_waypoint):
logging.debug(">>")
retorno = self.pytrainer_main.ddbb.select("waypoints",
"lat,lon,ele,comment,time,name,sym",
"id_waypoint=%s" %id_waypoint)
logging.debug("<<")
return retorno
def getAllWaypoints(self):
logging.debug(">>")
retorno = self.pytrainer_main.ddbb.select("waypoints","id_waypoint,lat,lon,ele,comment,time,name,sym","1=1 order by name")
logging.debug("<<")
return retorno
def actualize_fromgpx(self,gpxfile):
logging.debug(">>")
gpx = Gpx(self.data_path,gpxfile)
tracks = gpx.getTrackRoutes()
if len(tracks) > 1:
time = unixtime2date(tracks[0][1])
self.recordwindow.rcd_date.set_text(time)
self._actualize_fromgpx(gpx)
else:
msg = _("The gpx file seems to be a several days records. Perhaps you will need to edit your gpx file")
<|code_end|>
, determine the next line of code. You have imports:
import logging
from pytrainer.lib.date import unixtime2date
from sqlalchemy import Column, Unicode, Float, Integer, Date
from pytrainer.lib.ddbb import DeclarativeBase
from .lib.gpx import Gpx
from .gui.warning import Warning
and context (class names, function names, or code) available:
# Path: pytrainer/lib/date.py
# def unixtime2date(unixtime):
# tm = time.gmtime(unixtime)
# year = tm[0]
# month = tm[1]
# day = tm[2]
# return "%0.4d-%0.2d-%0.2d" %(year,month,day)
#
# Path: pytrainer/lib/ddbb.py
# class DDBB(Singleton):
# class ForcedInteger(TypeDecorator):
# def __init__(self, url=None):
# def get_connection_url(self):
# def connect(self):
# def disconnect(self):
# def select(self,table,cells,condition=None, mod=None):
# def create_tables(self, add_default=True):
# def drop_tables(self):
# def create_backup(self):
# def process_bind_param(self, value, dialect):
. Output only the next line. | warning = Warning(self.data_path,self._actualize_fromgpx,[gpx]) |
Continue the code snippet: <|code_start|> self.prefwindow.add(table)
self.prefwindow.show_all()
def on_help_clicked(self,widget):
selected,iter = self.extensionsTree.get_selection().get_selected()
name,description,status,helpfile,type = self.parent.getExtensionInfo(selected.get_value(iter,0))
with io.open(helpfile, encoding='utf-8') as input_file:
text = input_file.read(2000)
helpwindow = Gtk.Window()
button = Gtk.Button(_("OK"))
button.connect("clicked", self.on_accepthelp_clicked, helpwindow)
vbox = Gtk.VBox()
buffer = Gtk.TextBuffer()
buffer.set_text(text)
textview = Gtk.TextView()
textview.set_buffer(buffer)
scrolledwindow = Gtk.ScrolledWindow()
scrolledwindow.add(textview)
vbox.pack_start(scrolledwindow, True, True, 0)
vbox.pack_start(button, False, False, 0)
helpwindow.add(vbox)
helpwindow.resize(550,300)
helpwindow.show_all()
def on_accepthelp_clicked(self,widget,window):
window.hide()
window = None
def on_acceptSettings_clicked(self, widget, widget2):
selected,iter = self.extensionsTree.get_selection().get_selected()
<|code_end|>
. Use current file imports:
from .SimpleGladeApp import SimpleBuilderApp
from gi.repository import Gtk
from gi.repository import GObject
from pytrainer.lib.localization import gtk_str
import io
and context (classes, functions, or code) from other files:
# Path: pytrainer/gui/SimpleGladeApp.py
# class SimpleBuilderApp(dict):
# def __init__(self, ui_filename):
# self._builder = Gtk.Builder()
# env = Environment()
# file_path = os.path.join(env.glade_dir, ui_filename)
# self._builder.add_from_file(file_path)
# self.signal_autoconnect()
# self._builder.connect_signals(self)
# self.new()
#
# def signal_autoconnect(self):
# signals = {}
# for attr_name in dir(self):
# attr = getattr(self, attr_name)
# if callable(attr):
# signals[attr_name] = attr
# self._builder.connect_signals(signals)
#
# def __getattr__(self, data_name):
# if data_name in self:
# data = self[data_name]
# return data
# else:
# widget = self._builder.get_object(data_name)
# if widget != None:
# self[data_name] = widget
# return widget
# else:
# raise AttributeError(data_name)
#
# def __setattr__(self, name, value):
# self[name] = value
#
# def new(self):
# pass
#
# def on_keyboard_interrupt(self):
# pass
#
# def gtk_widget_show(self, widget, *args):
# widget.show()
#
# def gtk_widget_hide(self, widget, *args):
# widget.hide()
#
# def gtk_widget_grab_focus(self, widget, *args):
# widget.grab_focus()
#
# def gtk_widget_destroy(self, widget, *args):
# widget.destroy()
#
# def gtk_window_activate_default(self, widget, *args):
# widget.activate_default()
#
# def gtk_true(self, *args):
# return True
#
# def gtk_false(self, *args):
# return False
#
# def gtk_main_quit(self, *args):
# Gtk.main_quit()
#
# def main(self):
# Gtk.main()
#
# def quit(self, widget=None):
# Gtk.main_quit()
#
# def run(self):
# try:
# self.main()
# except KeyboardInterrupt:
# self.on_keyboard_interrupt()
#
# def create_treeview(self,treeview,column_names):
# i=0
# for column_index, column_name in enumerate(column_names):
# column = Gtk.TreeViewColumn(column_name, Gtk.CellRendererText(), text=column_index)
# column.set_resizable(True)
# if i==0:
# column.set_visible(False)
# column.set_sort_column_id(i)
# treeview.append_column(column)
#
# Path: pytrainer/lib/localization.py
# def gtk_str(string):
# """On Python 2 GTK returns all strings as UTF-8 encoded str. See
# https://python-gtk-3-tutorial.readthedocs.io/en/latest/unicode.html for
# more details."""
# if sys.version_info[0] == 2:
# if string is None:
# return None
# else:
# return string.decode('utf-8')
# else:
# return string
. Output only the next line. | prefs = self.parent.getExtensionConfParams(selected.get_value(iter,0)) |
Predict the next line after this snippet: <|code_start|> button.connect("clicked", self.on_acceptSettings_clicked, None)
table.attach(button,0,2,i,i+1)
self.prefwindow.add(table)
self.prefwindow.show_all()
def on_help_clicked(self,widget):
selected,iter = self.extensionsTree.get_selection().get_selected()
name,description,status,helpfile,type = self.parent.getExtensionInfo(selected.get_value(iter,0))
with io.open(helpfile, encoding='utf-8') as input_file:
text = input_file.read(2000)
helpwindow = Gtk.Window()
button = Gtk.Button(_("OK"))
button.connect("clicked", self.on_accepthelp_clicked, helpwindow)
vbox = Gtk.VBox()
buffer = Gtk.TextBuffer()
buffer.set_text(text)
textview = Gtk.TextView()
textview.set_buffer(buffer)
scrolledwindow = Gtk.ScrolledWindow()
scrolledwindow.add(textview)
vbox.pack_start(scrolledwindow, True, True, 0)
vbox.pack_start(button, False, False, 0)
helpwindow.add(vbox)
helpwindow.resize(550,300)
helpwindow.show_all()
def on_accepthelp_clicked(self,widget,window):
window.hide()
window = None
<|code_end|>
using the current file's imports:
from .SimpleGladeApp import SimpleBuilderApp
from gi.repository import Gtk
from gi.repository import GObject
from pytrainer.lib.localization import gtk_str
import io
and any relevant context from other files:
# Path: pytrainer/gui/SimpleGladeApp.py
# class SimpleBuilderApp(dict):
# def __init__(self, ui_filename):
# self._builder = Gtk.Builder()
# env = Environment()
# file_path = os.path.join(env.glade_dir, ui_filename)
# self._builder.add_from_file(file_path)
# self.signal_autoconnect()
# self._builder.connect_signals(self)
# self.new()
#
# def signal_autoconnect(self):
# signals = {}
# for attr_name in dir(self):
# attr = getattr(self, attr_name)
# if callable(attr):
# signals[attr_name] = attr
# self._builder.connect_signals(signals)
#
# def __getattr__(self, data_name):
# if data_name in self:
# data = self[data_name]
# return data
# else:
# widget = self._builder.get_object(data_name)
# if widget != None:
# self[data_name] = widget
# return widget
# else:
# raise AttributeError(data_name)
#
# def __setattr__(self, name, value):
# self[name] = value
#
# def new(self):
# pass
#
# def on_keyboard_interrupt(self):
# pass
#
# def gtk_widget_show(self, widget, *args):
# widget.show()
#
# def gtk_widget_hide(self, widget, *args):
# widget.hide()
#
# def gtk_widget_grab_focus(self, widget, *args):
# widget.grab_focus()
#
# def gtk_widget_destroy(self, widget, *args):
# widget.destroy()
#
# def gtk_window_activate_default(self, widget, *args):
# widget.activate_default()
#
# def gtk_true(self, *args):
# return True
#
# def gtk_false(self, *args):
# return False
#
# def gtk_main_quit(self, *args):
# Gtk.main_quit()
#
# def main(self):
# Gtk.main()
#
# def quit(self, widget=None):
# Gtk.main_quit()
#
# def run(self):
# try:
# self.main()
# except KeyboardInterrupt:
# self.on_keyboard_interrupt()
#
# def create_treeview(self,treeview,column_names):
# i=0
# for column_index, column_name in enumerate(column_names):
# column = Gtk.TreeViewColumn(column_name, Gtk.CellRendererText(), text=column_index)
# column.set_resizable(True)
# if i==0:
# column.set_visible(False)
# column.set_sort_column_id(i)
# treeview.append_column(column)
#
# Path: pytrainer/lib/localization.py
# def gtk_str(string):
# """On Python 2 GTK returns all strings as UTF-8 encoded str. See
# https://python-gtk-3-tutorial.readthedocs.io/en/latest/unicode.html for
# more details."""
# if sys.version_info[0] == 2:
# if string is None:
# return None
# else:
# return string.decode('utf-8')
# else:
# return string
. Output only the next line. | def on_acceptSettings_clicked(self, widget, widget2): |
Using the snippet: <|code_start|> self.validate = validate
self.data_path = os.path.dirname(__file__)
self.tmpdir = self.pytrainer_main.profile.tmpdir
def run(self):
logging.debug(">>")
selectedFiles = fileChooserDialog(title="Choose a Google Earth file (.kml) to import", multiple=True).getFiles()
guiFlush()
importfiles = []
if not selectedFiles:
return importfiles
for filename in selectedFiles:
if self.valid_input_file(filename):
if not self.inDatabase(filename):
sport = self.getSport(filename) #TODO Fix sport determination
gpxfile = "%s/googleearth-%d.gpx" % (self.tmpdir, len(importfiles))
outgps = subprocess.call(
["gpsbabel",
"-t",
"-i", "kml",
"-f", filename,
"-o", "gpx",
"-F", gpxfile])
#self.createGPXfile(gpxfile, filename) #TODO Fix processing so not dependant on the broken gpsbabel
importfiles.append((gpxfile, sport))
else:
logging.debug("%s already in database. Skipping import." % (filename) )
else:
logging.info("File %s failed validation" % (filename))
logging.debug("<<")
<|code_end|>
, determine the next line of code. You have imports:
import os
import subprocess
import logging
from lxml import etree
from pytrainer.gui.dialogs import fileChooserDialog, guiFlush
and context (class names, function names, or code) available:
# Path: pytrainer/gui/dialogs.py
# class fileChooserDialog():
# def __init__(self, title = "Choose a file", multiple = False):
# warnings.warn("Deprecated fileChooserDialog class called", DeprecationWarning, stacklevel=2)
# self.inputfiles = open_file_chooser_dialog(title=title, multiple=multiple)
#
# def getFiles(self):
# return self.inputfiles
#
# class guiFlush():
# def __init__(self):
# dialog = Gtk.Dialog(title=None, parent=None, flags=0, buttons=None)
# dialog.show()
# dialog.destroy()
. Output only the next line. | return importfiles |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
#Copyright (C) Fiz Vazquez vud1@sindominio.net
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
class googleearth():
def __init__(self, parent = None, validate=False):
self.parent = parent
self.pytrainer_main = parent.pytrainer_main
self.validate = validate
self.data_path = os.path.dirname(__file__)
self.tmpdir = self.pytrainer_main.profile.tmpdir
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import subprocess
import logging
from lxml import etree
from pytrainer.gui.dialogs import fileChooserDialog, guiFlush
and context:
# Path: pytrainer/gui/dialogs.py
# class fileChooserDialog():
# def __init__(self, title = "Choose a file", multiple = False):
# warnings.warn("Deprecated fileChooserDialog class called", DeprecationWarning, stacklevel=2)
# self.inputfiles = open_file_chooser_dialog(title=title, multiple=multiple)
#
# def getFiles(self):
# return self.inputfiles
#
# class guiFlush():
# def __init__(self):
# dialog = Gtk.Dialog(title=None, parent=None, flags=0, buttons=None)
# dialog.show()
# dialog.destroy()
which might include code, classes, or functions. Output only the next line. | def run(self): |
Using the snippet: <|code_start|>#Copyright (C) Nathan Jones ncjones@users.sourceforge.net
#Copyright (C) Arto Jantunen <viiru@iki.fi>
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
class PlatformTest(unittest.TestCase):
def test_first_day_of_week_should_be_non_negative_integer(self):
first_day = get_platform().get_first_day_of_week()
<|code_end|>
, determine the next line of code. You have imports:
import unittest
from pytrainer.platform import get_platform
and context (class names, function names, or code) available:
# Path: pytrainer/platform.py
# def get_platform():
# if os.name == "posix":
# return _Linux() #although not true, not changing original return name to avoid side effects
# elif os.name == "nt":
# return _Windows()
# else:
# logging.critical("Unsupported os.name: %s.", os.name)
# sys.exit(1)
. Output only the next line. | self.assertTrue(first_day >= 0) |
Using the snippet: <|code_start|>
self.category = [{'isPrimary': True, "categoryId" : self.category_nbr}]
self.error = ""
self.log =""
self.idrecord = options.idrecord
self.webserviceserver = SOAPpy.SOAPProxy("http://localhost:8081/")
#we try the connection to the xml/rpc server
try :
self.connect = xmlrpclib.Server(self.xmlrpcserver)
self.error = False
except :
print("can't connect the server")
def loadRecordInfo(self):
record = self.webserviceserver.getRecordInfo(self.idrecord)
self.sport = record["sport"]
self.date = record["date"]
self.distance = record["distance"]
self.time = second2time(float(record["time"]))
self.heure = self.time[0]
self.minute = self.time[1]
self.seconde = self.time[2]
self.beats = record["beats"]
self.comments = record["comments"]
self.average = record["average"]
self.calories = record["calories"]
self.title = record["title"]
self.upositive = record["upositive"]
<|code_end|>
, determine the next line of code. You have imports:
import xmlrpclib
import SOAPpy
import os
from pytrainer.lib.date import second2time
from pytrainer.lib.soapUtils import *
from optparse import OptionParser
and context (class names, function names, or code) available:
# Path: pytrainer/lib/date.py
# def second2time(seconds):
# if not seconds:
# return 0,0,0
# hours = seconds // (60*60)
# seconds %= (60*60)
# minutes = seconds // 60
# seconds %= 60
# return hours,minutes,seconds
. Output only the next line. | self.unegative = record["unegative"] |
Next line prediction: <|code_start|> def __init__(self, data_path = None, pytrainer_main=None, box=None):
logging.debug(">>")
self.data_path = data_path
self.pytrainer_main = pytrainer_main
if box is None:
logging.debug("Display box (%s) is None" % ( str(box)))
return
self.box = box
self.wkview = WebKit2.WebView()
self.pack_box()
logging.debug("<<")
def pack_box(self):
logging.debug(">>")
scrolled_window = Gtk.ScrolledWindow()
scrolled_window.add(self.wkview)
self.box.pack_start(scrolled_window, True, True, 0)
self.box.show_all()
logging.debug("<<")
def display_map(self, htmlfile=None):
logging.debug(">>")
if htmlfile is None:
htmlfile = self.createErrorHtml()
self.wkview.load_uri("file://%s" % (htmlfile))
#self.box.show_all()
logging.debug("<<")
def createErrorHtml(self):
logging.debug(">>")
<|code_end|>
. Use current file imports:
(from pytrainer.lib.fileUtils import fileUtils
from gi.repository import Gtk
from gi.repository import WebKit2
import gi
import logging)
and context including class names, function names, or small code snippets from other files:
# Path: pytrainer/lib/fileUtils.py
# class fileUtils:
# def __init__(self, filename, data):
# self.filename = filename
# self.data = data
#
# def run(self):
# logging.debug('>>')
# if self.data is not None:
# logging.debug("Writing in %s " % self.filename)
# out = open(self.filename, 'w')
# out.write(self.data)
# out.close()
# else:
# logging.error("Nothing to write in %s" % self.filename)
# logging.debug('<<')
. Output only the next line. | htmlfile = "%s/error.html" % (self.pytrainer_main.profile.tmpdir) |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
#Copyright (C) Nathan Jones ncjones@users.sourceforge.net
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
try:
except ImportError:
class InstalledDataTest(unittest.TestCase):
def setUp(self):
self._mock_migratable_db = Mock()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
import pytrainer.upgrade.context
from unittest.mock import Mock
from mock import Mock
from pytrainer.upgrade.data import InstalledData, DataState, DataInitializationException
and context:
# Path: pytrainer/upgrade/data.py
# class InstalledData(object):
#
# """Encapsulates an installation's existing data and provides means to
# check version state and upgrade."""
#
# def __init__(self, migratable_db, ddbb, legacy_version_provider, upgrade_context):
# self._migratable_db = migratable_db
# self._ddbb = ddbb
# self._legacy_version_provider = legacy_version_provider
# self._upgrade_context = upgrade_context
#
# def update_to_current(self):
# """Check the current state of the installation's data and update them
# if necessary so they are compatible with the latest version.
#
# The update steps depend on the state of the installation's data. The
# possible states and the update steps from those states are:
#
# 1. Current (data is up to date):
# - do nothing
# 2. Fresh (new installation):
# - initialise empty db
# - initialise db version metadata
# 3. Stale: (data requires upgrading):
# - run upgrade scripts
# 4. Legacy (data requires upgrading but is missing version metadata):
# - initialise db version metadata
# - run upgrade scripts
#
# """
# data_state = self.get_state()
# logging.info("Initializing data. Data state is: '%s'.", data_state)
# data_state.update_to_current(self)
#
# def get_state(self):
# """Get the current state of the installation's data.
#
# raises DataInitializationException if the existing data is not
# compatible and cannot be upgraded.
# """
# version = self.get_version()
# available_version= self.get_available_version()
# if self.is_versioned():
# if version == available_version:
# return DataState.CURRENT
# elif version > available_version:
# raise DataInitializationException("Existing data version ({0}) is greater than available version ({1}).".format(version, available_version))
# else:
# return DataState.STALE
# else:
# if version == None:
# if self.is_fresh():
# return DataState.FRESH
# else:
# raise DataInitializationException("Existing data version cannot be determined.")
# else:
# return DataState.LEGACY
#
# def is_fresh(self):
# """Check if this is a fresh installation."""
# return self._migratable_db.is_empty()
#
# def get_version(self):
# """Get the version number of an installation's data.
#
# If the data version cannot be determined then None is returned."""
# if self.is_versioned():
# return self._migratable_db.get_version()
# else:
# # Calculate data version in older version that does not use the
# # current data versioning scheme.
# legacy_version = self._legacy_version_provider.get_legacy_version()
# if legacy_version is not None:
# legacy_version = int(legacy_version)
# if legacy_version == 1: # 1.7.1
# return 1
# elif legacy_version == 2: # 1.7.2-dev
# return 2
# elif legacy_version == 3: # 1.7.2
# return 3
# elif legacy_version == 4: # 1.8.0-dev
# return 4
# elif legacy_version == 5: # 1.8.0-dev
# return 5
# elif legacy_version == 6: # 1.8.0
# return 9
# elif legacy_version == 7: # 1.9.0-dev
# return 10
# elif legacy_version == 8: # 1.9.0-dev
# return 12
# elif legacy_version == 9: # 1.9.0-dev
# return 12
# return None
#
# def get_available_version(self):
# return self._migratable_db.get_upgrade_version()
#
# def is_versioned(self):
# """ Check if the version metadata has been initiaized."""
# return self._migratable_db.is_versioned()
#
# def initialize_version(self, initial_version):
# """Initialize the version metadata."""
# logging.info("Initializing version metadata to version: '%s'.", initial_version)
# self._migratable_db.version(initial_version)
#
# def initialize(self):
# logging.info("Initializing new database.")
# self._ddbb.create_tables()
#
# def upgrade(self):
# logging.info("Upgrading data from version '%s' to version '%s'.", self.get_version(), self.get_available_version())
# self._ddbb.create_backup()
# pytrainer.upgrade.context.UPGRADE_CONTEXT = self._upgrade_context
# self._migratable_db.upgrade()
#
# class DataState(object):
#
# """The state of an installation's data.
#
# The state knows how to update the data to the "current" state."""
#
# def __init__(self, name, update_function):
# self.name = name
# self._update_function = update_function
#
# def __str__(self):
# return self.name
#
# def update_to_current(self, installed_data):
# """Update the installed data so it is compatible with the current
# version."""
# self._update_function(installed_data)
#
# class DataInitializationException(Exception):
#
# def __init__(self, value):
# self.value = value
which might include code, classes, or functions. Output only the next line. | self._mock_ddbb = Mock() |
Using the snippet: <|code_start|>#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
class MonthGraph(TimeGraph):
value_params = [
(_("day"),_("Distance (km)"),_("Daily Distance"),"y"),
(_("day"),_("Time (hours)"), _("Daily Time"),"b"),
(_("day"),_("Average Heart Rate (bpm)"), _("Daily Average Heart Rate"),"r"),
(_("day"),_("Average Speed (km/h)"), _("Daily Average Speed"),"g"),
(_("day"),_("Calories"), _("Daily Calories"),"b"),
]
def __init__(self, sports, vbox = None, window = None, combovalue = None, combovalue2 = None, main = None):
TimeGraph.__init__(self, sports, vbox=vbox, window=window, main=main)
self.combovalue = combovalue
self.combovalue2 = combovalue2
self.KEY_FORMAT = "%d"
<|code_end|>
, determine the next line of code. You have imports:
import dateutil
import datetime
from .timegraph import TimeGraph
and context (class names, function names, or code) available:
# Path: pytrainer/timegraph.py
# class TimeGraph(object):
# def __init__(self, sports, vbox = None, window = None, combovalue = None, combovalue2 = None, main = None):
# self.drawarea = DrawArea(vbox, window)
# self.SPORT_FIELD = 9
# self.sport_colors = dict([(sport.name, sport.color.to_hex_string()) for sport in sports])
#
# def getFloatValue(self, value):
# try:
# return float(value)
# except:
# return float(0)
#
# def getValue(self,record,value_selected):
# #hacemos una relacion entre el value_selected y los values / we make a relation between value_selected and the values
# conv = {
# 0: 'distance', #value 0 es kilometros (1)
# 1: 'duration', #value 1 es tiempo (2)
# 2: 'beats', #value 2 es pulsaciones(3)
# 3: 'average', #value 3 es media(5)
# 4: 'calories' #value 4 es calorias(6)
# }
# value_sel = conv[value_selected]
# #si la opcion es tiempo lo pasamos a horas / if the option is time we passed it to hours
# if (value_sel == 'duration'):
# return self.getFloatValue(getattr(record, value_sel))/3600
# else:
# return self.getFloatValue(getattr(record, value_sel))
#
# def get_values(self, values, value_selected, key_format, sportfield=9):
# valueDict = {} #Stores the totals
# valueCount = {} #Counts the totals to allow for averaging if needed
# sportColors = {}
#
# for record in values:
# if record.date:
# day = locale_str(record.date.strftime(key_format)) # Gives year for this record
# sport = record.sport.name
# value = self.getValue(record, value_selected)
# if sport in valueDict: #Already got this sport
# if day in valueDict[sport]: #Already got this sport on this day
# valueDict[sport][day] += value
# valueCount[sport][day] += 1
# else: #New day for this sport
# valueDict[sport][day] = value
# valueCount[sport][day] = 1
# else: #New sport
# valueDict[sport] = {day: value}
# valueCount[sport] = {day: 1}
# else:
# logging.debug("No date string found, skipping entry: %s", record)
#
# if value_selected in (2, 3):
# total = {}
# count = {}
# for sport in valueDict.keys():
# for day in valueDict[sport].keys():
# if valueCount[sport][day] > 1: #Only average if 2 or more entries on this day
# valueDict[sport][day] /= valueCount[sport][day]
#
# if value_selected == 1: #Values are of time type
# valuesAreTime=True
# else:
# valuesAreTime=False
#
# return valueDict, valuesAreTime
#
# def drawgraph(self,values, extra=None, x_func=None):
# xval = []
# yval = []
# xlab = []
# ylab = []
# tit = []
#
# valsAreTime = []
# value_selected = self.combovalue.get_active()
# value_selected2 = self.combovalue2.get_active()
# if value_selected < 0:
# self.combovalue.set_active(0)
# value_selected = 0
#
# y1,ylabel,title,y2 = self.get_value_params(value_selected)
# ylab.append(ylabel)
# tit.append(title)
#
# yvalues, valuesAreTime = self.get_values(values,value_selected, self.KEY_FORMAT, sportfield=self.SPORT_FIELD)
# xvalues = x_func(yvalues)
#
# yval.append(yvalues)
# xlab.append(xvalues)
# valsAreTime.append(valuesAreTime)
#
# #Second combobox used
# if value_selected2 > 0:
# value_selected2 = value_selected2-1
# y1, ylabel,title,y2 = self.get_value_params(value_selected2)
# ylab.append(ylabel)
# tit.append(title)
# yvalues, valuesAreTime = self.get_values(values,value_selected2, self.KEY_FORMAT, sportfield=self.SPORT_FIELD)
# yval.append(yvalues)
# xlab.append(xvalues)
# valsAreTime.append(valuesAreTime)
# #Draw chart
# self.drawarea.drawStackedBars(xlab,yval,ylab,tit,valsAreTime, colors = self.sport_colors)
#
# def get_value_params(self,value):
# return self.value_params[value]
. Output only the next line. | def drawgraph(self,values, daysInMonth): |
Given the code snippet: <|code_start|>#Copyright (C) Nathan Jones ncjones@users.sourceforge.net
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
class ColorConverterTest(unittest.TestCase):
def setUp(self):
self._converter = ColorConverter()
def test_convert_to_gdk_color_should_create_gdk_color_with_equivalent_rgb_values(self):
color = Color(0xaaff33)
gdk_color = self._converter.convert_to_gdk_color(color)
self.assertEqual(0x3333, gdk_color.blue)
self.assertEqual(0xffff, gdk_color.green)
self.assertEqual(0xaaaa, gdk_color.red)
def test_convert_to_color_should_create_color_with_equivalent_rgb_values(self):
<|code_end|>
, generate the next line using the imports in this file:
from pytrainer.gui.color import ColorConverter
from pytrainer.util.color import Color
from gi.repository import Gdk
import unittest
and context (functions, classes, or occasionally code) from other files:
# Path: pytrainer/gui/color.py
# class ColorConverter(object):
#
# """Converts between Pytrainer and GDK color instances."""
#
# def convert_to_gdk_color(self, color):
# """Convert a Pytrainer color to a GDK color."""
# color_format = "#{0:06x}".format(color.rgb_val)
# return Gdk.color_parse(color_format)
#
# def convert_to_color(self, gdk_col):
# """Convert a GDK color to a Pytrainer color."""
# red = gdk_col.red >> 8
# green = gdk_col.green >> 8
# blue = gdk_col.blue >> 8
# rgb_val = (red << 16) + (green << 8) + blue
# return Color(rgb_val)
#
# Path: pytrainer/util/color.py
# class Color(object):
#
# """A color represented as a 24-bit RGB value."""
#
# def __init__(self, rgb_val=0):
# rgb_val_int = int(rgb_val)
# if rgb_val_int < 0:
# raise ValueError("RGB value must not be negative.")
# if rgb_val_int > 0xffffff:
# raise ValueError("RGB value must not be greater than 0xffffff.")
# self._rgb_val = rgb_val_int
#
# def _get_rgb_val(self):
# return self._rgb_val
#
# rgb_val = property(_get_rgb_val)
#
# def _get_rgba_val(self):
# return self._rgb_val << 8
#
# rgba_val = property(_get_rgba_val)
#
# def to_hex_string(self):
# return "{0:06x}".format(self._rgb_val)
. Output only the next line. | gdk_col = Gdk.color_parse("#aaff33") |
Using the snippet: <|code_start|>#Copyright (C) Nathan Jones ncjones@users.sourceforge.net
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
class ColorConverterTest(unittest.TestCase):
def setUp(self):
self._converter = ColorConverter()
def test_convert_to_gdk_color_should_create_gdk_color_with_equivalent_rgb_values(self):
color = Color(0xaaff33)
gdk_color = self._converter.convert_to_gdk_color(color)
self.assertEqual(0x3333, gdk_color.blue)
self.assertEqual(0xffff, gdk_color.green)
self.assertEqual(0xaaaa, gdk_color.red)
def test_convert_to_color_should_create_color_with_equivalent_rgb_values(self):
<|code_end|>
, determine the next line of code. You have imports:
from pytrainer.gui.color import ColorConverter
from pytrainer.util.color import Color
from gi.repository import Gdk
import unittest
and context (class names, function names, or code) available:
# Path: pytrainer/gui/color.py
# class ColorConverter(object):
#
# """Converts between Pytrainer and GDK color instances."""
#
# def convert_to_gdk_color(self, color):
# """Convert a Pytrainer color to a GDK color."""
# color_format = "#{0:06x}".format(color.rgb_val)
# return Gdk.color_parse(color_format)
#
# def convert_to_color(self, gdk_col):
# """Convert a GDK color to a Pytrainer color."""
# red = gdk_col.red >> 8
# green = gdk_col.green >> 8
# blue = gdk_col.blue >> 8
# rgb_val = (red << 16) + (green << 8) + blue
# return Color(rgb_val)
#
# Path: pytrainer/util/color.py
# class Color(object):
#
# """A color represented as a 24-bit RGB value."""
#
# def __init__(self, rgb_val=0):
# rgb_val_int = int(rgb_val)
# if rgb_val_int < 0:
# raise ValueError("RGB value must not be negative.")
# if rgb_val_int > 0xffffff:
# raise ValueError("RGB value must not be greater than 0xffffff.")
# self._rgb_val = rgb_val_int
#
# def _get_rgb_val(self):
# return self._rgb_val
#
# rgb_val = property(_get_rgb_val)
#
# def _get_rgba_val(self):
# return self._rgb_val << 8
#
# rgba_val = property(_get_rgba_val)
#
# def to_hex_string(self):
# return "{0:06x}".format(self._rgb_val)
. Output only the next line. | gdk_col = Gdk.color_parse("#aaff33") |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
#Copyright (C) Fiz Vazquez vud1@sindominio.net
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
class WindowPlugins(SimpleBuilderApp):
def __init__(self, data_path = None, parent=None):
self.parent = parent
SimpleBuilderApp.__init__(self, "plugins.ui")
<|code_end|>
. Use current file imports:
(from .SimpleGladeApp import SimpleBuilderApp
from gi.repository import Gtk
from gi.repository import GObject
from pytrainer.lib.localization import gtk_str
import os)
and context including class names, function names, or small code snippets from other files:
# Path: pytrainer/gui/SimpleGladeApp.py
# class SimpleBuilderApp(dict):
# def __init__(self, ui_filename):
# self._builder = Gtk.Builder()
# env = Environment()
# file_path = os.path.join(env.glade_dir, ui_filename)
# self._builder.add_from_file(file_path)
# self.signal_autoconnect()
# self._builder.connect_signals(self)
# self.new()
#
# def signal_autoconnect(self):
# signals = {}
# for attr_name in dir(self):
# attr = getattr(self, attr_name)
# if callable(attr):
# signals[attr_name] = attr
# self._builder.connect_signals(signals)
#
# def __getattr__(self, data_name):
# if data_name in self:
# data = self[data_name]
# return data
# else:
# widget = self._builder.get_object(data_name)
# if widget != None:
# self[data_name] = widget
# return widget
# else:
# raise AttributeError(data_name)
#
# def __setattr__(self, name, value):
# self[name] = value
#
# def new(self):
# pass
#
# def on_keyboard_interrupt(self):
# pass
#
# def gtk_widget_show(self, widget, *args):
# widget.show()
#
# def gtk_widget_hide(self, widget, *args):
# widget.hide()
#
# def gtk_widget_grab_focus(self, widget, *args):
# widget.grab_focus()
#
# def gtk_widget_destroy(self, widget, *args):
# widget.destroy()
#
# def gtk_window_activate_default(self, widget, *args):
# widget.activate_default()
#
# def gtk_true(self, *args):
# return True
#
# def gtk_false(self, *args):
# return False
#
# def gtk_main_quit(self, *args):
# Gtk.main_quit()
#
# def main(self):
# Gtk.main()
#
# def quit(self, widget=None):
# Gtk.main_quit()
#
# def run(self):
# try:
# self.main()
# except KeyboardInterrupt:
# self.on_keyboard_interrupt()
#
# def create_treeview(self,treeview,column_names):
# i=0
# for column_index, column_name in enumerate(column_names):
# column = Gtk.TreeViewColumn(column_name, Gtk.CellRendererText(), text=column_index)
# column.set_resizable(True)
# if i==0:
# column.set_visible(False)
# column.set_sort_column_id(i)
# treeview.append_column(column)
#
# Path: pytrainer/lib/localization.py
# def gtk_str(string):
# """On Python 2 GTK returns all strings as UTF-8 encoded str. See
# https://python-gtk-3-tutorial.readthedocs.io/en/latest/unicode.html for
# more details."""
# if sys.version_info[0] == 2:
# if string is None:
# return None
# else:
# return string.decode('utf-8')
# else:
# return string
. Output only the next line. | def new(self): |
Using the snippet: <|code_start|> if iterOne:
self.pluginsTreeview.get_selection().select_iter(iterOne)
self.on_pluginsTree_clicked(None,None)
def create_treeview(self,treeview,column_names):
i=0
for column_index, column_name in enumerate(column_names):
column = Gtk.TreeViewColumn(column_name, Gtk.CellRendererText(), text=column_index)
if i==0:
column.set_visible(False)
treeview.append_column(column)
i+=1
def on_pluginsTree_clicked(self,widget,widget2):
selected,iter = self.pluginsTreeview.get_selection().get_selected()
name,description,status = self.parent.getPluginInfo(selected.get_value(iter,0))
self.nameEntry.set_text(name)
self.descriptionEntry.set_text(description)
if int(status) > 0:
self.statusEntry.set_text(_("Enable"))
else:
self.statusEntry.set_text(_("Disable"))
def on_preferences_clicked(self,widget):
selected,iter = self.pluginsTreeview.get_selection().get_selected()
name,description,status = self.parent.getPluginInfo(selected.get_value(iter,0))
prefs = self.parent.getPluginConfParams(selected.get_value(iter,0))
self.prefwindow = Gtk.Window()
self.prefwindow.set_border_width(20)
<|code_end|>
, determine the next line of code. You have imports:
from .SimpleGladeApp import SimpleBuilderApp
from gi.repository import Gtk
from gi.repository import GObject
from pytrainer.lib.localization import gtk_str
import os
and context (class names, function names, or code) available:
# Path: pytrainer/gui/SimpleGladeApp.py
# class SimpleBuilderApp(dict):
# def __init__(self, ui_filename):
# self._builder = Gtk.Builder()
# env = Environment()
# file_path = os.path.join(env.glade_dir, ui_filename)
# self._builder.add_from_file(file_path)
# self.signal_autoconnect()
# self._builder.connect_signals(self)
# self.new()
#
# def signal_autoconnect(self):
# signals = {}
# for attr_name in dir(self):
# attr = getattr(self, attr_name)
# if callable(attr):
# signals[attr_name] = attr
# self._builder.connect_signals(signals)
#
# def __getattr__(self, data_name):
# if data_name in self:
# data = self[data_name]
# return data
# else:
# widget = self._builder.get_object(data_name)
# if widget != None:
# self[data_name] = widget
# return widget
# else:
# raise AttributeError(data_name)
#
# def __setattr__(self, name, value):
# self[name] = value
#
# def new(self):
# pass
#
# def on_keyboard_interrupt(self):
# pass
#
# def gtk_widget_show(self, widget, *args):
# widget.show()
#
# def gtk_widget_hide(self, widget, *args):
# widget.hide()
#
# def gtk_widget_grab_focus(self, widget, *args):
# widget.grab_focus()
#
# def gtk_widget_destroy(self, widget, *args):
# widget.destroy()
#
# def gtk_window_activate_default(self, widget, *args):
# widget.activate_default()
#
# def gtk_true(self, *args):
# return True
#
# def gtk_false(self, *args):
# return False
#
# def gtk_main_quit(self, *args):
# Gtk.main_quit()
#
# def main(self):
# Gtk.main()
#
# def quit(self, widget=None):
# Gtk.main_quit()
#
# def run(self):
# try:
# self.main()
# except KeyboardInterrupt:
# self.on_keyboard_interrupt()
#
# def create_treeview(self,treeview,column_names):
# i=0
# for column_index, column_name in enumerate(column_names):
# column = Gtk.TreeViewColumn(column_name, Gtk.CellRendererText(), text=column_index)
# column.set_resizable(True)
# if i==0:
# column.set_visible(False)
# column.set_sort_column_id(i)
# treeview.append_column(column)
#
# Path: pytrainer/lib/localization.py
# def gtk_str(string):
# """On Python 2 GTK returns all strings as UTF-8 encoded str. See
# https://python-gtk-3-tutorial.readthedocs.io/en/latest/unicode.html for
# more details."""
# if sys.version_info[0] == 2:
# if string is None:
# return None
# else:
# return string.decode('utf-8')
# else:
# return string
. Output only the next line. | self.prefwindow.set_title(_("%s settings" %name)) |
Continue the code snippet: <|code_start|> del(DDBB.self)
def tearDown(self):
del(DDBB.self)
@mock.patch.dict('os.environ', {}, clear=True)
def test_none_url(self):
self.ddbb = DDBB()
self.assertEqual(self.ddbb.url, 'sqlite://')
def test_basic_url(self):
self.ddbb = DDBB(url='sqlite:///test_url')
self.assertEqual(self.ddbb.url, 'sqlite:///test_url')
def test_mysql_url(self):
self.ddbb = DDBB(url='mysql://pytrainer@localhost/pytrainer')
self.assertEqual(self.ddbb.url, 'mysql://pytrainer@localhost/pytrainer?charset=utf8')
@mock.patch.dict('os.environ', {'PYTRAINER_ALCHEMYURL': 'sqlite:///envtest'})
def test_env_url(self):
self.ddbb = DDBB()
self.assertEqual(self.ddbb.url, 'sqlite:///envtest')
@mock.patch.dict('os.environ', {'PYTRAINER_ALCHEMYURL': 'mysql://pytrainer@localhost/pytrainer'})
def test_env_mysql_url(self):
self.ddbb = DDBB()
self.assertEqual(self.ddbb.url, 'mysql://pytrainer@localhost/pytrainer?charset=utf8')
def test_singleton(self):
self.ddbb = DDBB(url='sqlite:///test_url')
<|code_end|>
. Use current file imports:
import unittest
import mock
from unittest import mock
from pytrainer.lib.ddbb import DDBB
and context (classes, functions, or code) from other files:
# Path: pytrainer/lib/ddbb.py
# class DDBB(Singleton):
# url = None
# engine = None
# sessionmaker = sessionmaker()
# session = None
#
# def __init__(self, url=None):
# """Initialize database connection, defaulting to SQLite in-memory
# if no url is provided"""
# if not self.url and not url:
# # Starting from scratch without specifying a url
# if 'PYTRAINER_ALCHEMYURL' in os.environ:
# url = os.environ['PYTRAINER_ALCHEMYURL']
# else:
# url = "sqlite://"
#
# # Mysql special case
# if not self.url and url.startswith('mysql'):
# self.url = '%s%s' % (url, '?charset=utf8')
#
# if url and self.url and not self.url != url:
# # The url has changed, destroy the engine
# self.engine.dispose()
# self.engine = None
# self.session = None
# self.url = url
#
# if not self.url:
# self.url = url
#
# if not self.engine:
# self.engine = create_engine(self.url, logging_name='db')
# self.sessionmaker.configure(bind=self.engine)
# logging.info("DDBB created with url %s", self.url)
#
# def get_connection_url(self):
# return self.url
#
# def connect(self):
# self.session = self.sessionmaker()
#
# def disconnect(self):
# self.session.close()
#
# def select(self,table,cells,condition=None, mod=None):
# warnings.warn("Deprecated call to ddbb.select", DeprecationWarning, stacklevel=2)
# sql = "select %s from %s" %(cells,table)
# if condition is not None:
# sql = "%s where %s" % (sql, condition)
# if mod is not None:
# sql = "%s %s" % (sql, mod)
# return list(self.session.execute(sql))
#
# def create_tables(self, add_default=True):
# """Initialise the database schema from an empty database."""
# logging.info("Creating database tables")
# from pytrainer.core.sport import Sport
# from pytrainer.core.equipment import Equipment
# from pytrainer.waypoint import Waypoint
# from pytrainer.core.activity import Lap
# from pytrainer.athlete import Athletestat
# DeclarativeBase.metadata.create_all(self.engine)
# if add_default:
# for item in [Sport(name=u"Mountain Bike", weight=0.0, color=color_from_hex_string("0000ff")),
# Sport(name=u"Bike", weight=0.0, color=color_from_hex_string("00ff00")),
# Sport(name=u"Run", weight=0.0, color=color_from_hex_string("ffff00"))]:
# self.session.add(item)
# self.session.commit()
#
# def drop_tables(self):
# """Drop the database schema"""
# DeclarativeBase.metadata.drop_all(self.engine)
#
# def create_backup(self):
# """Create a backup of the current database."""
# try:
# import urlparse
# from urllib import url2pathname
# except ImportError:
# import urllib.parse as urlparse
# from urllib.request import url2pathname
# scheme, netloc, path, params, query, fragment = urlparse.urlparse(self.url)
# if scheme == 'sqlite':
# import datetime
# import gzip
# logging.info("Creating compressed copy of current DB")
# logging.debug('Database path: %s', self.url)
# path = url2pathname(path)
# backup_path = '%s_%s.gz' % (path, datetime.datetime.now().strftime('%Y%m%d_%H%M'))
# with open(path, 'rb') as orig_file:
# with gzip.open(backup_path, 'wb') as backup_file:
# backup_file.write(orig_file.read())
# logging.info('Database backup successfully created')
. Output only the next line. | self.assertEqual(self.ddbb.url, 'sqlite:///test_url') |
Given the code snippet: <|code_start|> self.data_path = data_path
def run(self):
logging.debug('>>')
filename = save_file_chooser_dialog(title="savecsvfile", pattern="*.csv")
records = self.record.getAllrecord()
# CSV Header
content = "date_time_local,title,sports.name,distance,duration,average,maxspeed,pace,maxpace,beats,maxbeats,calories,upositive,unegative,comments\n"
try:
for record in records:
line = ""
for i, data in enumerate(record):
if i in [3, 5, 6, 7, 8, 12, 13]:
try:
data = round(data, 2)
except:
pass
data = "%s" %data
data = data.replace(",", " ")
data = data.replace("\n", " ")
data = data.replace("\r", " ")
if i>0:
line += ",%s" %data
else:
line += "%s" %data
content += "%s\n" %line
logging.info("Record data successfully retrieved. Choosing file to save it")
file = fileUtils(filename,content)
file.run()
except:
<|code_end|>
, generate the next line using the imports in this file:
from .lib.fileUtils import fileUtils
from pytrainer.gui.dialogs import save_file_chooser_dialog
import logging
import traceback
and context (functions, classes, or occasionally code) from other files:
# Path: pytrainer/lib/fileUtils.py
# class fileUtils:
# def __init__(self, filename, data):
# self.filename = filename
# self.data = data
#
# def run(self):
# logging.debug('>>')
# if self.data is not None:
# logging.debug("Writing in %s " % self.filename)
# out = open(self.filename, 'w')
# out.write(self.data)
# out.close()
# else:
# logging.error("Nothing to write in %s" % self.filename)
# logging.debug('<<')
#
# Path: pytrainer/gui/dialogs.py
# def save_file_chooser_dialog(title="Choose a file", pattern="*.csv"):
# dialog = Gtk.FileChooserDialog(title, None, Gtk.FileChooserAction.SAVE,
# (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
# Gtk.STOCK_SAVE, Gtk.ResponseType.OK))
# dialog.set_default_response(Gtk.ResponseType.OK)
# dialog.set_current_name(pattern)
# response = dialog.run()
# result = None
# if response == Gtk.ResponseType.OK:
# result = dialog.get_filename()
# dialog.destroy()
# return result
. Output only the next line. | logging.debug("Traceback: %s" % traceback.format_exc()) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
#Copyright (C) Fiz Vazquez vud1@sindominio.net
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
class Save:
def __init__(self, data_path = None, record = None):
self.record = record
self.data_path = data_path
def run(self):
logging.debug('>>')
filename = save_file_chooser_dialog(title="savecsvfile", pattern="*.csv")
<|code_end|>
, generate the next line using the imports in this file:
from .lib.fileUtils import fileUtils
from pytrainer.gui.dialogs import save_file_chooser_dialog
import logging
import traceback
and context (functions, classes, or occasionally code) from other files:
# Path: pytrainer/lib/fileUtils.py
# class fileUtils:
# def __init__(self, filename, data):
# self.filename = filename
# self.data = data
#
# def run(self):
# logging.debug('>>')
# if self.data is not None:
# logging.debug("Writing in %s " % self.filename)
# out = open(self.filename, 'w')
# out.write(self.data)
# out.close()
# else:
# logging.error("Nothing to write in %s" % self.filename)
# logging.debug('<<')
#
# Path: pytrainer/gui/dialogs.py
# def save_file_chooser_dialog(title="Choose a file", pattern="*.csv"):
# dialog = Gtk.FileChooserDialog(title, None, Gtk.FileChooserAction.SAVE,
# (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
# Gtk.STOCK_SAVE, Gtk.ResponseType.OK))
# dialog.set_default_response(Gtk.ResponseType.OK)
# dialog.set_current_name(pattern)
# response = dialog.run()
# result = None
# if response == Gtk.ResponseType.OK:
# result = dialog.get_filename()
# dialog.destroy()
# return result
. Output only the next line. | records = self.record.getAllrecord() |
Given snippet: <|code_start|>#Copyright (C) Nathan Jones ncjones@users.sourceforge.net
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
class ColorTest(unittest.TestCase):
def test_constructor_should_accept_integer(self):
color = Color(12345)
self.assertEqual(12345, color.rgb_val)
def test_constructor_should_accept_integer_string(self):
color = Color("12345")
self.assertEqual(12345, color.rgb_val)
def test_constructor_should_not_accept_non_integer_string(self):
try:
Color("ff00ff")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pytrainer.util.color import Color, color_from_hex_string
import unittest
and context:
# Path: pytrainer/util/color.py
# class Color(object):
#
# """A color represented as a 24-bit RGB value."""
#
# def __init__(self, rgb_val=0):
# rgb_val_int = int(rgb_val)
# if rgb_val_int < 0:
# raise ValueError("RGB value must not be negative.")
# if rgb_val_int > 0xffffff:
# raise ValueError("RGB value must not be greater than 0xffffff.")
# self._rgb_val = rgb_val_int
#
# def _get_rgb_val(self):
# return self._rgb_val
#
# rgb_val = property(_get_rgb_val)
#
# def _get_rgba_val(self):
# return self._rgb_val << 8
#
# rgba_val = property(_get_rgba_val)
#
# def to_hex_string(self):
# return "{0:06x}".format(self._rgb_val)
#
# def color_from_hex_string(hex_string):
# return Color(int(hex_string, 16))
which might include code, classes, or functions. Output only the next line. | except(ValueError): |
Based on the snippet: <|code_start|> try:
Color(2 ** 24)
except(ValueError):
pass
else:
self.fail()
def test_rgb_value_should_default_to_0(self):
color = Color()
self.assertEqual(0, color.rgb_val)
def test_rgb_value_should_be_read_only(self):
color = Color()
try:
color.rgb_val = 1
except(AttributeError):
pass
else:
self.fail()
def test_rgba_value_should_be_rgb_value_with_two_trailing_zero_hex_digits(self):
color = Color(0x1177ff)
self.assertEqual(0x1177ff00, color.rgba_val)
def test_to_hex_string_should_create_six_digit_hex_value(self):
color = Color(0xfab)
self.assertEqual("000fab", color.to_hex_string())
def test_color_from_hex_string_should_correctly_decode_hex_value(self):
color = color_from_hex_string("fab")
<|code_end|>
, predict the immediate next line with the help of imports:
from pytrainer.util.color import Color, color_from_hex_string
import unittest
and context (classes, functions, sometimes code) from other files:
# Path: pytrainer/util/color.py
# class Color(object):
#
# """A color represented as a 24-bit RGB value."""
#
# def __init__(self, rgb_val=0):
# rgb_val_int = int(rgb_val)
# if rgb_val_int < 0:
# raise ValueError("RGB value must not be negative.")
# if rgb_val_int > 0xffffff:
# raise ValueError("RGB value must not be greater than 0xffffff.")
# self._rgb_val = rgb_val_int
#
# def _get_rgb_val(self):
# return self._rgb_val
#
# rgb_val = property(_get_rgb_val)
#
# def _get_rgba_val(self):
# return self._rgb_val << 8
#
# rgba_val = property(_get_rgba_val)
#
# def to_hex_string(self):
# return "{0:06x}".format(self._rgb_val)
#
# def color_from_hex_string(hex_string):
# return Color(int(hex_string, 16))
. Output only the next line. | self.assertEqual(0xfab, color.rgb_val) |
Continue the code snippet: <|code_start|>
def set_text(self, msg):
self.text = msg
def on_accept_clicked(self):
if self.okparams != None:
num = len(self.okparams)
if num==0:
self.okmethod()
if num==1:
self.okmethod(self.okparams[0])
if num==2:
self.okmethod(self.okparams[0],self.okparams[1])
def on_cancel_clicked(self):
if self.cancelparams != None:
num = len(self.cancelparams)
if num==0:
self.cancelmethod()
if num==1:
self.cancelmethod(self.cancelparams[0])
if num==2:
self.cancelmethod(self.cancelparams[0], self.cancelparams[1])
def run(self):
if self.okmethod:
response = warning_dialog(text=self.text, title=self.title, cancel=True)
else:
response = warning_dialog(text=self.text, title=self.title, cancel=False)
if response == Gtk.ResponseType.OK:
<|code_end|>
. Use current file imports:
from pytrainer.gui.dialogs import warning_dialog
from gi.repository import Gtk
import warnings
and context (classes, functions, or code) from other files:
# Path: pytrainer/gui/dialogs.py
# def warning_dialog(text="", title="Warning", cancel=False):
# if cancel:
# dialog = Gtk.MessageDialog(type=Gtk.MessageType.QUESTION,
# buttons=Gtk.ButtonsType.OK_CANCEL,
# message_format=text,
# flags=Gtk.DialogFlags.MODAL)
# else:
# dialog = Gtk.MessageDialog(type=Gtk.MessageType.WARNING,
# buttons=Gtk.ButtonsType.OK,
# message_format=text,
# flags=Gtk.DialogFlags.MODAL)
# dialog.set_title(title)
# result = dialog.run()
# dialog.destroy()
# return result
. Output only the next line. | self.on_accept_clicked() |
Predict the next line for this snippet: <|code_start|> # Environment is a singleton, make sure to destroy it between tests
del(Environment.self)
self.environment = Environment(TEST_DIR_NAME, DATA_DIR_NAME)
def tearDown(self):
del(Environment.self)
def test_get_conf_dir(self):
self.assertEqual(TEST_DIR_NAME, self.environment.conf_dir)
def test_get_data_path(self):
self.assertEqual(DATA_DIR_NAME, self.environment.data_path)
def test_environment_singleton(self):
self.environment = Environment()
self.assertEqual(TEST_DIR_NAME, self.environment.conf_dir)
self.assertEqual(DATA_DIR_NAME, self.environment.data_path)
def test_get_conf_file(self):
self.assertEqual(TEST_DIR_NAME + "/conf.xml", self.environment.conf_file)
def test_get_log_file(self):
self.assertEqual(TEST_DIR_NAME + "/log.out", self.environment.log_file)
def test_get_temp_dir(self):
self.assertEqual(TEST_DIR_NAME + "/tmp", self.environment.temp_dir)
def test_get_gpx_dir(self):
self.assertEqual(TEST_DIR_NAME + "/gpx", self.environment.gpx_dir)
<|code_end|>
with the help of current file imports:
import unittest
from unittest.mock import Mock
from mock import Mock
from pytrainer.environment import Environment
and context from other files:
# Path: pytrainer/environment.py
# class Environment(Singleton):
#
# """Describes the location of the program's configuration directories and files."""
#
# def __init__(self, conf_dir=None, data_path=None):
# """Initialise an environment.
#
# Arguments:
# conf_dir -- the directory where program configuration should be stored. If None, then the default for the platform is used.
#
# """
# if not hasattr(self, 'conf_dir'):
# if conf_dir:
# self.conf_dir = conf_dir
# else:
# self.conf_dir = get_platform().get_default_conf_dir()
#
# if not hasattr(self, 'data_path'):
# if data_path:
# self.data_path = data_path
# else:
# self.data_path = get_platform().get_default_data_path()
#
# @property
# def conf_file(self):
# return os.path.join(self.conf_dir, "conf.xml")
#
# @property
# def log_file(self):
# return os.path.join(self.conf_dir, "log.out")
#
# @property
# def temp_dir(self):
# return os.path.join(self.conf_dir, "tmp")
#
# @property
# def gpx_dir(self):
# return os.path.join(self.conf_dir, "gpx")
#
# @property
# def extension_dir(self):
# return os.path.join(self.conf_dir, "extensions")
#
# @property
# def plugin_dir(self):
# return os.path.join(self.conf_dir, "plugins")
#
# @property
# def glade_dir(self):
# return os.path.join(self.data_path, "glade")
#
# def clear_temp_dir(self):
# """Remove all files from the tmp directory."""
# if not os.path.isdir(self.temp_dir):
# return
# else:
# files = os.listdir(self.temp_dir)
# for name in files:
# fullname = (os.path.join(self.temp_dir, name))
# if os.path.isfile(fullname):
# os.remove(os.path.join(self.temp_dir, name))
#
# def create_directories(self):
# """Create all required directories if they do not already exist."""
# self._create_dir(self.conf_dir)
# self._create_dir(self.temp_dir)
# self._create_dir(self.extension_dir)
# self._create_dir(self.plugin_dir)
# self._create_dir(self.gpx_dir)
#
# def _create_dir(self, dir_name):
# if not os.path.isdir(dir_name):
# os.mkdir(dir_name)
, which may contain function names, class names, or code. Output only the next line. | def test_get_extension_dir(self): |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
#Copyright (C) Fiz Vazquez vud1@sindominio.net
# vud1@grupoikusnet.com
# Jakinbidea & Grupo Ikusnet Developer
# Modified by dgranda
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
DeclarativeBase = declarative_base()
record_to_equipment = Table('record_equipment', DeclarativeBase.metadata,
Column('id', Integer, primary_key=True),
Column('equipment_id', Integer,
<|code_end|>
. Use current file imports:
import logging
import os
import warnings
import urlparse
import urllib.parse as urlparse
import datetime
import gzip
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.types import TypeDecorator
from sqlalchemy import Integer, Table, Column, ForeignKey
from pytrainer.util.color import color_from_hex_string
from pytrainer.lib.singleton import Singleton
from pytrainer.core.sport import Sport
from pytrainer.core.equipment import Equipment
from pytrainer.waypoint import Waypoint
from pytrainer.core.activity import Lap
from pytrainer.athlete import Athletestat
from urllib import url2pathname
from urllib.request import url2pathname
and context (classes, functions, or code) from other files:
# Path: pytrainer/util/color.py
# def color_from_hex_string(hex_string):
# return Color(int(hex_string, 16))
#
# Path: pytrainer/lib/singleton.py
# class Singleton (object):
# def __new__(cls, *args, **kwargs):
# if not hasattr(cls, 'self'):
# cls.self = object.__new__(cls)
# return cls.self
. Output only the next line. | ForeignKey('equipment.id'), |
Given the code snippet: <|code_start|> index=True, nullable=False))
class DDBB(Singleton):
url = None
engine = None
sessionmaker = sessionmaker()
session = None
def __init__(self, url=None):
"""Initialize database connection, defaulting to SQLite in-memory
if no url is provided"""
if not self.url and not url:
# Starting from scratch without specifying a url
if 'PYTRAINER_ALCHEMYURL' in os.environ:
url = os.environ['PYTRAINER_ALCHEMYURL']
else:
url = "sqlite://"
# Mysql special case
if not self.url and url.startswith('mysql'):
self.url = '%s%s' % (url, '?charset=utf8')
if url and self.url and not self.url != url:
# The url has changed, destroy the engine
self.engine.dispose()
self.engine = None
self.session = None
self.url = url
if not self.url:
<|code_end|>
, generate the next line using the imports in this file:
import logging
import os
import warnings
import urlparse
import urllib.parse as urlparse
import datetime
import gzip
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.types import TypeDecorator
from sqlalchemy import Integer, Table, Column, ForeignKey
from pytrainer.util.color import color_from_hex_string
from pytrainer.lib.singleton import Singleton
from pytrainer.core.sport import Sport
from pytrainer.core.equipment import Equipment
from pytrainer.waypoint import Waypoint
from pytrainer.core.activity import Lap
from pytrainer.athlete import Athletestat
from urllib import url2pathname
from urllib.request import url2pathname
and context (functions, classes, or occasionally code) from other files:
# Path: pytrainer/util/color.py
# def color_from_hex_string(hex_string):
# return Color(int(hex_string, 16))
#
# Path: pytrainer/lib/singleton.py
# class Singleton (object):
# def __new__(cls, *args, **kwargs):
# if not hasattr(cls, 'self'):
# cls.self = object.__new__(cls)
# return cls.self
. Output only the next line. | self.url = url |
Next line prediction: <|code_start|>#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
def pace2float(pace_str):
if pace_str.count(':') != 1:
return 0.0
else:
_prts = pace_str.split(':')
try:
_p_min = int(_prts[0])
_p_sec = int(_prts[1])
return float( _p_min + (_p_sec/60.0))
except:
return 0.0
def float2pace(pace_flt):
try:
_pace = float(pace_flt)
<|code_end|>
. Use current file imports:
(from pytrainer.lib.singleton import Singleton
from gettext import gettext as _)
and context including class names, function names, or small code snippets from other files:
# Path: pytrainer/lib/singleton.py
# class Singleton (object):
# def __new__(cls, *args, **kwargs):
# if not hasattr(cls, 'self'):
# cls.self = object.__new__(cls)
# return cls.self
. Output only the next line. | except: |
Continue the code snippet: <|code_start|> attr = getattr(self, attr_name)
if callable(attr):
signals[attr_name] = attr
self._builder.connect_signals(signals)
def __getattr__(self, data_name):
if data_name in self:
data = self[data_name]
return data
else:
widget = self._builder.get_object(data_name)
if widget != None:
self[data_name] = widget
return widget
else:
raise AttributeError(data_name)
def __setattr__(self, name, value):
self[name] = value
def new(self):
pass
def on_keyboard_interrupt(self):
pass
def gtk_widget_show(self, widget, *args):
widget.show()
def gtk_widget_hide(self, widget, *args):
<|code_end|>
. Use current file imports:
import os
import sys
from gi.repository import Gtk
from pytrainer.environment import Environment
and context (classes, functions, or code) from other files:
# Path: pytrainer/environment.py
# class Environment(Singleton):
#
# """Describes the location of the program's configuration directories and files."""
#
# def __init__(self, conf_dir=None, data_path=None):
# """Initialise an environment.
#
# Arguments:
# conf_dir -- the directory where program configuration should be stored. If None, then the default for the platform is used.
#
# """
# if not hasattr(self, 'conf_dir'):
# if conf_dir:
# self.conf_dir = conf_dir
# else:
# self.conf_dir = get_platform().get_default_conf_dir()
#
# if not hasattr(self, 'data_path'):
# if data_path:
# self.data_path = data_path
# else:
# self.data_path = get_platform().get_default_data_path()
#
# @property
# def conf_file(self):
# return os.path.join(self.conf_dir, "conf.xml")
#
# @property
# def log_file(self):
# return os.path.join(self.conf_dir, "log.out")
#
# @property
# def temp_dir(self):
# return os.path.join(self.conf_dir, "tmp")
#
# @property
# def gpx_dir(self):
# return os.path.join(self.conf_dir, "gpx")
#
# @property
# def extension_dir(self):
# return os.path.join(self.conf_dir, "extensions")
#
# @property
# def plugin_dir(self):
# return os.path.join(self.conf_dir, "plugins")
#
# @property
# def glade_dir(self):
# return os.path.join(self.data_path, "glade")
#
# def clear_temp_dir(self):
# """Remove all files from the tmp directory."""
# if not os.path.isdir(self.temp_dir):
# return
# else:
# files = os.listdir(self.temp_dir)
# for name in files:
# fullname = (os.path.join(self.temp_dir, name))
# if os.path.isfile(fullname):
# os.remove(os.path.join(self.temp_dir, name))
#
# def create_directories(self):
# """Create all required directories if they do not already exist."""
# self._create_dir(self.conf_dir)
# self._create_dir(self.temp_dir)
# self._create_dir(self.extension_dir)
# self._create_dir(self.plugin_dir)
# self._create_dir(self.gpx_dir)
#
# def _create_dir(self, dir_name):
# if not os.path.isdir(dir_name):
# os.mkdir(dir_name)
. Output only the next line. | widget.hide() |
Here is a snippet: <|code_start|>
client = docker.from_env()
def verify_container(container: Container, response_text: str) -> None:
response = requests.get("http://127.0.0.1:8000")
assert response.text == response_text
nginx_config = get_nginx_config(container)
assert "client_max_body_size 0;" in nginx_config
assert "worker_processes 1;" in nginx_config
assert "listen 80;" in nginx_config
assert "worker_connections 1024;" in nginx_config
assert "worker_rlimit_nofile;" not in nginx_config
<|code_end|>
. Write the next line using the current file imports:
import os
import time
import docker
import requests
from pathlib import Path
from docker.models.containers import Container
from ..utils import (
CONTAINER_NAME,
generate_dockerfile_content_simple_app,
get_logs,
get_nginx_config,
get_response_text2,
remove_previous_container,
)
and context from other files:
# Path: tests/utils.py
# CONTAINER_NAME = "uwsgi-nginx-test"
#
# def generate_dockerfile_content_simple_app(name: str) -> str:
# content = f"FROM tiangolo/uwsgi-nginx:{name}\n"
# content += "COPY ./app/main.py /app/main.py\n"
# return content
#
# def get_logs(container: Container) -> str:
# logs = container.logs()
# return logs.decode("utf-8")
#
# def get_nginx_config(container: Container) -> str:
# result = container.exec_run(f"/usr/sbin/nginx -T")
# return result.output.decode()
#
# def get_response_text2() -> str:
# python_version = os.getenv("PYTHON_VERSION")
# return f"Hello World from Nginx uWSGI Python {python_version} app in a Docker container"
#
# def remove_previous_container(client: DockerClient) -> None:
# try:
# previous = client.containers.get(CONTAINER_NAME)
# previous.stop()
# previous.remove()
# except NotFound:
# return None
, which may include functions, classes, or code. Output only the next line. | assert "daemon off;" in nginx_config |
Given the following code snippet before the placeholder: <|code_start|>
client = docker.from_env()
def verify_container(container: Container, response_text: str) -> None:
response = requests.get("http://127.0.0.1:8000")
assert response.text == response_text
nginx_config = get_nginx_config(container)
assert "client_max_body_size 0;" in nginx_config
assert "worker_processes 1;" in nginx_config
assert "listen 80;" in nginx_config
assert "worker_connections 1024;" in nginx_config
assert "worker_rlimit_nofile;" not in nginx_config
assert "daemon off;" in nginx_config
assert "include uwsgi_params;" in nginx_config
assert "uwsgi_pass unix:///tmp/uwsgi.sock;" in nginx_config
logs = get_logs(container)
assert "getting INI configuration from /app/uwsgi.ini" in logs
assert "getting INI configuration from /etc/uwsgi/uwsgi.ini" in logs
assert "ini = /app/uwsgi.ini" in logs
assert "ini = /etc/uwsgi/uwsgi.ini" in logs
assert "socket = /tmp/uwsgi.sock" in logs
assert "chown-socket = nginx:nginx" in logs
assert "chmod-socket = 664" in logs
assert "hook-master-start = unix_signal:15 gracefully_kill_them_all" in logs
assert "need-app = true" in logs
assert "die-on-term = true" in logs
assert "show-config = true" in logs
assert "wsgi-file = /app/main.py" in logs
assert "processes = 16" in logs
<|code_end|>
, predict the next line using imports from the current file:
import os
import time
import docker
import requests
from pathlib import Path
from docker.models.containers import Container
from ..utils import (
CONTAINER_NAME,
generate_dockerfile_content_simple_app,
get_logs,
get_nginx_config,
get_response_text2,
remove_previous_container,
)
and context including class names, function names, and sometimes code from other files:
# Path: tests/utils.py
# CONTAINER_NAME = "uwsgi-nginx-test"
#
# def generate_dockerfile_content_simple_app(name: str) -> str:
# content = f"FROM tiangolo/uwsgi-nginx:{name}\n"
# content += "COPY ./app/main.py /app/main.py\n"
# return content
#
# def get_logs(container: Container) -> str:
# logs = container.logs()
# return logs.decode("utf-8")
#
# def get_nginx_config(container: Container) -> str:
# result = container.exec_run(f"/usr/sbin/nginx -T")
# return result.output.decode()
#
# def get_response_text2() -> str:
# python_version = os.getenv("PYTHON_VERSION")
# return f"Hello World from Nginx uWSGI Python {python_version} app in a Docker container"
#
# def remove_previous_container(client: DockerClient) -> None:
# try:
# previous = client.containers.get(CONTAINER_NAME)
# previous.stop()
# previous.remove()
# except NotFound:
# return None
. Output only the next line. | assert "cheaper = 2" in logs |
Predict the next line after this snippet: <|code_start|> assert "hook-master-start = unix_signal:15 gracefully_kill_them_all" in logs
assert "need-app = true" in logs
assert "die-on-term = true" in logs
assert "show-config = true" in logs
assert "wsgi-file = /app/main.py" in logs
assert "processes = 16" in logs
assert "cheaper = 2" in logs
assert "Checking for script in /app/prestart.sh" in logs
assert "Running script /app/prestart.sh" in logs
assert (
"Running inside /app/prestart.sh, you could add migrations to this file" in logs
)
assert "spawned uWSGI master process" in logs
assert "spawned uWSGI worker 1" in logs
assert "spawned uWSGI worker 2" in logs
assert "spawned uWSGI worker 3" not in logs
assert 'running "unix_signal:15 gracefully_kill_them_all" (master-start)' in logs
assert "success: nginx entered RUNNING state, process has stayed up for" in logs
assert "success: uwsgi entered RUNNING state, process has stayed up for" in logs
def test_env_vars_1() -> None:
name = os.getenv("NAME", "")
dockerfile_content = generate_dockerfile_content_simple_app(name)
dockerfile = "Dockerfile"
response_text = get_response_text2()
sleep_time = int(os.getenv("SLEEP_TIME", 3))
remove_previous_container(client)
tag = "uwsgi-nginx-testimage"
test_path = Path(__file__)
<|code_end|>
using the current file's imports:
import os
import time
import docker
import requests
from pathlib import Path
from docker.models.containers import Container
from ..utils import (
CONTAINER_NAME,
generate_dockerfile_content_simple_app,
get_logs,
get_nginx_config,
get_response_text2,
remove_previous_container,
)
and any relevant context from other files:
# Path: tests/utils.py
# CONTAINER_NAME = "uwsgi-nginx-test"
#
# def generate_dockerfile_content_simple_app(name: str) -> str:
# content = f"FROM tiangolo/uwsgi-nginx:{name}\n"
# content += "COPY ./app/main.py /app/main.py\n"
# return content
#
# def get_logs(container: Container) -> str:
# logs = container.logs()
# return logs.decode("utf-8")
#
# def get_nginx_config(container: Container) -> str:
# result = container.exec_run(f"/usr/sbin/nginx -T")
# return result.output.decode()
#
# def get_response_text2() -> str:
# python_version = os.getenv("PYTHON_VERSION")
# return f"Hello World from Nginx uWSGI Python {python_version} app in a Docker container"
#
# def remove_previous_container(client: DockerClient) -> None:
# try:
# previous = client.containers.get(CONTAINER_NAME)
# previous.stop()
# previous.remove()
# except NotFound:
# return None
. Output only the next line. | path = test_path.parent / "simple_app" |
Continue the code snippet: <|code_start|> logs = get_logs(container)
assert "getting INI configuration from /app/uwsgi.ini" in logs
assert "getting INI configuration from /etc/uwsgi/uwsgi.ini" in logs
assert "ini = /app/uwsgi.ini" in logs
assert "ini = /etc/uwsgi/uwsgi.ini" in logs
assert "socket = /tmp/uwsgi.sock" in logs
assert "chown-socket = nginx:nginx" in logs
assert "chmod-socket = 664" in logs
assert "hook-master-start = unix_signal:15 gracefully_kill_them_all" in logs
assert "need-app = true" in logs
assert "die-on-term = true" in logs
assert "show-config = true" in logs
assert "wsgi-file = /app/main.py" in logs
assert "processes = 16" in logs
assert "cheaper = 2" in logs
assert "Checking for script in /app/prestart.sh" in logs
assert "Running script /app/prestart.sh" in logs
assert (
"Running inside /app/prestart.sh, you could add migrations to this file" in logs
)
assert "spawned uWSGI master process" in logs
assert "spawned uWSGI worker 1" in logs
assert "spawned uWSGI worker 2" in logs
assert "spawned uWSGI worker 3" not in logs
assert 'running "unix_signal:15 gracefully_kill_them_all" (master-start)' in logs
assert "success: nginx entered RUNNING state, process has stayed up for" in logs
assert "success: uwsgi entered RUNNING state, process has stayed up for" in logs
def test_env_vars_1() -> None:
<|code_end|>
. Use current file imports:
import os
import time
import docker
import requests
from pathlib import Path
from docker.models.containers import Container
from ..utils import (
CONTAINER_NAME,
generate_dockerfile_content_simple_app,
get_logs,
get_nginx_config,
get_response_text2,
remove_previous_container,
)
and context (classes, functions, or code) from other files:
# Path: tests/utils.py
# CONTAINER_NAME = "uwsgi-nginx-test"
#
# def generate_dockerfile_content_simple_app(name: str) -> str:
# content = f"FROM tiangolo/uwsgi-nginx:{name}\n"
# content += "COPY ./app/main.py /app/main.py\n"
# return content
#
# def get_logs(container: Container) -> str:
# logs = container.logs()
# return logs.decode("utf-8")
#
# def get_nginx_config(container: Container) -> str:
# result = container.exec_run(f"/usr/sbin/nginx -T")
# return result.output.decode()
#
# def get_response_text2() -> str:
# python_version = os.getenv("PYTHON_VERSION")
# return f"Hello World from Nginx uWSGI Python {python_version} app in a Docker container"
#
# def remove_previous_container(client: DockerClient) -> None:
# try:
# previous = client.containers.get(CONTAINER_NAME)
# previous.stop()
# previous.remove()
# except NotFound:
# return None
. Output only the next line. | name = os.getenv("NAME", "") |
Given snippet: <|code_start|> assert "wsgi-file = /app/main.py" in logs
assert "processes = 16" in logs
assert "cheaper = 2" in logs
assert "Checking for script in /app/prestart.sh" in logs
assert "Running script /app/prestart.sh" in logs
assert (
"Running inside /app/prestart.sh, you could add migrations to this file" in logs
)
assert "spawned uWSGI master process" in logs
assert "spawned uWSGI worker 1" in logs
assert "spawned uWSGI worker 2" in logs
assert "spawned uWSGI worker 3" not in logs
assert 'running "unix_signal:15 gracefully_kill_them_all" (master-start)' in logs
assert "success: nginx entered RUNNING state, process has stayed up for" in logs
assert "success: uwsgi entered RUNNING state, process has stayed up for" in logs
def test_env_vars_1() -> None:
name = os.getenv("NAME", "")
dockerfile_content = generate_dockerfile_content_simple_app(name)
dockerfile = "Dockerfile"
response_text = get_response_text2()
sleep_time = int(os.getenv("SLEEP_TIME", 3))
remove_previous_container(client)
tag = "uwsgi-nginx-testimage"
test_path = Path(__file__)
path = test_path.parent / "simple_app"
dockerfile_path = path / dockerfile
dockerfile_path.write_text(dockerfile_content)
client.images.build(path=str(path), dockerfile=dockerfile, tag=tag)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import time
import docker
import requests
from pathlib import Path
from docker.models.containers import Container
from ..utils import (
CONTAINER_NAME,
generate_dockerfile_content_simple_app,
get_logs,
get_nginx_config,
get_response_text2,
remove_previous_container,
)
and context:
# Path: tests/utils.py
# CONTAINER_NAME = "uwsgi-nginx-test"
#
# def generate_dockerfile_content_simple_app(name: str) -> str:
# content = f"FROM tiangolo/uwsgi-nginx:{name}\n"
# content += "COPY ./app/main.py /app/main.py\n"
# return content
#
# def get_logs(container: Container) -> str:
# logs = container.logs()
# return logs.decode("utf-8")
#
# def get_nginx_config(container: Container) -> str:
# result = container.exec_run(f"/usr/sbin/nginx -T")
# return result.output.decode()
#
# def get_response_text2() -> str:
# python_version = os.getenv("PYTHON_VERSION")
# return f"Hello World from Nginx uWSGI Python {python_version} app in a Docker container"
#
# def remove_previous_container(client: DockerClient) -> None:
# try:
# previous = client.containers.get(CONTAINER_NAME)
# previous.stop()
# previous.remove()
# except NotFound:
# return None
which might include code, classes, or functions. Output only the next line. | container = client.containers.run( |
Given the code snippet: <|code_start|>
client = docker.from_env()
def verify_container(container: Container, response_text: str) -> None:
response = requests.get("http://127.0.0.1:8000")
assert response.text == response_text
nginx_config = get_nginx_config(container)
assert "client_max_body_size 0;" in nginx_config
assert "worker_processes 1;" in nginx_config
assert "listen 80;" in nginx_config
assert "worker_connections 1024;" in nginx_config
assert "worker_rlimit_nofile;" not in nginx_config
assert "daemon off;" in nginx_config
assert "include uwsgi_params;" in nginx_config
assert "uwsgi_pass unix:///tmp/uwsgi.sock;" in nginx_config
logs = get_logs(container)
assert "getting INI configuration from /app/uwsgi.ini" in logs
assert "getting INI configuration from /etc/uwsgi/uwsgi.ini" in logs
assert "ini = /app/uwsgi.ini" in logs
assert "ini = /etc/uwsgi/uwsgi.ini" in logs
assert "socket = /tmp/uwsgi.sock" in logs
assert "chown-socket = nginx:nginx" in logs
<|code_end|>
, generate the next line using the imports in this file:
import os
import time
import docker
import requests
from pathlib import Path
from docker.models.containers import Container
from ..utils import (
CONTAINER_NAME,
generate_dockerfile_content_simple_app,
get_logs,
get_nginx_config,
get_response_text2,
remove_previous_container,
)
and context (functions, classes, or occasionally code) from other files:
# Path: tests/utils.py
# CONTAINER_NAME = "uwsgi-nginx-test"
#
# def generate_dockerfile_content_simple_app(name: str) -> str:
# content = f"FROM tiangolo/uwsgi-nginx:{name}\n"
# content += "COPY ./app/main.py /app/main.py\n"
# return content
#
# def get_logs(container: Container) -> str:
# logs = container.logs()
# return logs.decode("utf-8")
#
# def get_nginx_config(container: Container) -> str:
# result = container.exec_run(f"/usr/sbin/nginx -T")
# return result.output.decode()
#
# def get_response_text2() -> str:
# python_version = os.getenv("PYTHON_VERSION")
# return f"Hello World from Nginx uWSGI Python {python_version} app in a Docker container"
#
# def remove_previous_container(client: DockerClient) -> None:
# try:
# previous = client.containers.get(CONTAINER_NAME)
# previous.stop()
# previous.remove()
# except NotFound:
# return None
. Output only the next line. | assert "chmod-socket = 664" in logs |
Given the code snippet: <|code_start|> assert "client_max_body_size 1m;" in nginx_config
assert "worker_processes 2;" in nginx_config
assert "listen 80;" in nginx_config
assert "worker_connections 2048;" in nginx_config
assert "worker_rlimit_nofile 2048;" in nginx_config
assert "daemon off;" in nginx_config
assert "listen 80;" in nginx_config
assert "include uwsgi_params;" in nginx_config
assert "uwsgi_pass unix:///tmp/uwsgi.sock;" in nginx_config
logs = get_logs(container)
assert "getting INI configuration from /app/uwsgi.ini" in logs
assert "getting INI configuration from /etc/uwsgi/uwsgi.ini" in logs
assert "ini = /app/uwsgi.ini" in logs
assert "ini = /etc/uwsgi/uwsgi.ini" in logs
assert "socket = /tmp/uwsgi.sock" in logs
assert "chown-socket = nginx:nginx" in logs
assert "chmod-socket = 664" in logs
assert "hook-master-start = unix_signal:15 gracefully_kill_them_all" in logs
assert "need-app = true" in logs
assert "die-on-term = true" in logs
assert "show-config = true" in logs
assert "wsgi-file = /app/main.py" in logs
assert "processes = 8" in logs
assert "cheaper = 3" in logs
assert "Checking for script in /app/prestart.sh" in logs
assert "Running script /app/prestart.sh" in logs
assert (
"Running inside /app/prestart.sh, you could add migrations to this file" in logs
)
assert "spawned uWSGI master process" in logs
<|code_end|>
, generate the next line using the imports in this file:
import os
import time
import docker
import requests
from docker.models.containers import Container
from ..utils import (
CONTAINER_NAME,
get_logs,
get_nginx_config,
get_response_text1,
remove_previous_container,
)
and context (functions, classes, or occasionally code) from other files:
# Path: tests/utils.py
# CONTAINER_NAME = "uwsgi-nginx-test"
#
# def get_logs(container: Container) -> str:
# logs = container.logs()
# return logs.decode("utf-8")
#
# def get_nginx_config(container: Container) -> str:
# result = container.exec_run(f"/usr/sbin/nginx -T")
# return result.output.decode()
#
# def get_response_text1() -> str:
# python_version = os.getenv("PYTHON_VERSION")
# return f"Hello World from a default Nginx uWSGI Python {python_version} app in a Docker container (default)"
#
# def remove_previous_container(client: DockerClient) -> None:
# try:
# previous = client.containers.get(CONTAINER_NAME)
# previous.stop()
# previous.remove()
# except NotFound:
# return None
. Output only the next line. | assert "spawned uWSGI worker 1" in logs |
Using the snippet: <|code_start|>
client = docker.from_env()
def verify_container(container: Container, response_text: str) -> None:
response = requests.get("http://127.0.0.1:8000")
assert response.text == response_text
nginx_config = get_nginx_config(container)
assert "client_max_body_size 1m;" in nginx_config
assert "worker_processes 2;" in nginx_config
assert "listen 80;" in nginx_config
assert "worker_connections 2048;" in nginx_config
assert "worker_rlimit_nofile 2048;" in nginx_config
assert "daemon off;" in nginx_config
assert "listen 80;" in nginx_config
assert "include uwsgi_params;" in nginx_config
assert "uwsgi_pass unix:///tmp/uwsgi.sock;" in nginx_config
logs = get_logs(container)
assert "getting INI configuration from /app/uwsgi.ini" in logs
assert "getting INI configuration from /etc/uwsgi/uwsgi.ini" in logs
assert "ini = /app/uwsgi.ini" in logs
<|code_end|>
, determine the next line of code. You have imports:
import os
import time
import docker
import requests
from docker.models.containers import Container
from ..utils import (
CONTAINER_NAME,
get_logs,
get_nginx_config,
get_response_text1,
remove_previous_container,
)
and context (class names, function names, or code) available:
# Path: tests/utils.py
# CONTAINER_NAME = "uwsgi-nginx-test"
#
# def get_logs(container: Container) -> str:
# logs = container.logs()
# return logs.decode("utf-8")
#
# def get_nginx_config(container: Container) -> str:
# result = container.exec_run(f"/usr/sbin/nginx -T")
# return result.output.decode()
#
# def get_response_text1() -> str:
# python_version = os.getenv("PYTHON_VERSION")
# return f"Hello World from a default Nginx uWSGI Python {python_version} app in a Docker container (default)"
#
# def remove_previous_container(client: DockerClient) -> None:
# try:
# previous = client.containers.get(CONTAINER_NAME)
# previous.stop()
# previous.remove()
# except NotFound:
# return None
. Output only the next line. | assert "ini = /etc/uwsgi/uwsgi.ini" in logs |
Next line prediction: <|code_start|>
client = docker.from_env()
def verify_container(container: Container, response_text: str) -> None:
response = requests.get("http://127.0.0.1:8000")
assert response.text == response_text
nginx_config = get_nginx_config(container)
assert "client_max_body_size 1m;" in nginx_config
<|code_end|>
. Use current file imports:
(import os
import time
import docker
import requests
from docker.models.containers import Container
from ..utils import (
CONTAINER_NAME,
get_logs,
get_nginx_config,
get_response_text1,
remove_previous_container,
))
and context including class names, function names, or small code snippets from other files:
# Path: tests/utils.py
# CONTAINER_NAME = "uwsgi-nginx-test"
#
# def get_logs(container: Container) -> str:
# logs = container.logs()
# return logs.decode("utf-8")
#
# def get_nginx_config(container: Container) -> str:
# result = container.exec_run(f"/usr/sbin/nginx -T")
# return result.output.decode()
#
# def get_response_text1() -> str:
# python_version = os.getenv("PYTHON_VERSION")
# return f"Hello World from a default Nginx uWSGI Python {python_version} app in a Docker container (default)"
#
# def remove_previous_container(client: DockerClient) -> None:
# try:
# previous = client.containers.get(CONTAINER_NAME)
# previous.stop()
# previous.remove()
# except NotFound:
# return None
. Output only the next line. | assert "worker_processes 2;" in nginx_config |
Using the snippet: <|code_start|>
client = docker.from_env()
def verify_container(container: Container, response_text: str) -> None:
response = requests.get("http://127.0.0.1:8000")
assert response.text == response_text
nginx_config = get_nginx_config(container)
assert "client_max_body_size 1m;" in nginx_config
assert "worker_processes 2;" in nginx_config
assert "listen 80;" in nginx_config
assert "worker_connections 2048;" in nginx_config
assert "worker_rlimit_nofile 2048;" in nginx_config
assert "daemon off;" in nginx_config
assert "listen 80;" in nginx_config
assert "include uwsgi_params;" in nginx_config
assert "uwsgi_pass unix:///tmp/uwsgi.sock;" in nginx_config
logs = get_logs(container)
assert "getting INI configuration from /app/uwsgi.ini" in logs
assert "getting INI configuration from /etc/uwsgi/uwsgi.ini" in logs
<|code_end|>
, determine the next line of code. You have imports:
import os
import time
import docker
import requests
from docker.models.containers import Container
from ..utils import (
CONTAINER_NAME,
get_logs,
get_nginx_config,
get_response_text1,
remove_previous_container,
)
and context (class names, function names, or code) available:
# Path: tests/utils.py
# CONTAINER_NAME = "uwsgi-nginx-test"
#
# def get_logs(container: Container) -> str:
# logs = container.logs()
# return logs.decode("utf-8")
#
# def get_nginx_config(container: Container) -> str:
# result = container.exec_run(f"/usr/sbin/nginx -T")
# return result.output.decode()
#
# def get_response_text1() -> str:
# python_version = os.getenv("PYTHON_VERSION")
# return f"Hello World from a default Nginx uWSGI Python {python_version} app in a Docker container (default)"
#
# def remove_previous_container(client: DockerClient) -> None:
# try:
# previous = client.containers.get(CONTAINER_NAME)
# previous.stop()
# previous.remove()
# except NotFound:
# return None
. Output only the next line. | assert "ini = /app/uwsgi.ini" in logs |
Predict the next line after this snippet: <|code_start|> assert "spawned uWSGI worker 2" in logs
assert "spawned uWSGI worker 3" in logs
assert "spawned uWSGI worker 4" not in logs
assert 'running "unix_signal:15 gracefully_kill_them_all" (master-start)' in logs
assert "success: nginx entered RUNNING state, process has stayed up for" in logs
assert "success: uwsgi entered RUNNING state, process has stayed up for" in logs
def test_env_vars_1() -> None:
name = os.getenv("NAME")
image = f"tiangolo/uwsgi-nginx:{name}"
response_text = get_response_text1()
sleep_time = int(os.getenv("SLEEP_TIME", 3))
remove_previous_container(client)
container = client.containers.run(
image,
name=CONTAINER_NAME,
environment={
"UWSGI_CHEAPER": 3,
"UWSGI_PROCESSES": 8,
"NGINX_MAX_UPLOAD": "1m",
"NGINX_WORKER_PROCESSES": 2,
"NGINX_WORKER_CONNECTIONS": 2048,
"NGINX_WORKER_OPEN_FILES": 2048,
},
ports={"80": "8000"},
detach=True,
)
time.sleep(sleep_time)
verify_container(container, response_text)
<|code_end|>
using the current file's imports:
import os
import time
import docker
import requests
from docker.models.containers import Container
from ..utils import (
CONTAINER_NAME,
get_logs,
get_nginx_config,
get_response_text1,
remove_previous_container,
)
and any relevant context from other files:
# Path: tests/utils.py
# CONTAINER_NAME = "uwsgi-nginx-test"
#
# def get_logs(container: Container) -> str:
# logs = container.logs()
# return logs.decode("utf-8")
#
# def get_nginx_config(container: Container) -> str:
# result = container.exec_run(f"/usr/sbin/nginx -T")
# return result.output.decode()
#
# def get_response_text1() -> str:
# python_version = os.getenv("PYTHON_VERSION")
# return f"Hello World from a default Nginx uWSGI Python {python_version} app in a Docker container (default)"
#
# def remove_previous_container(client: DockerClient) -> None:
# try:
# previous = client.containers.get(CONTAINER_NAME)
# previous.stop()
# previous.remove()
# except NotFound:
# return None
. Output only the next line. | container.stop() |
Using the snippet: <|code_start|>
client = docker.from_env()
def verify_container(container: Container, response_text: str) -> None:
response = requests.get("http://127.0.0.1:8080")
assert response.text == response_text
nginx_config = get_nginx_config(container)
assert "client_max_body_size 0;" not in nginx_config
assert "worker_processes 2;" in nginx_config
assert "listen 8080;" in nginx_config
assert "worker_connections 2048;" in nginx_config
assert "worker_rlimit_nofile;" not in nginx_config
assert "daemon off;" in nginx_config
assert "include uwsgi_params;" in nginx_config
assert "uwsgi_pass unix:///tmp/uwsgi.sock;" in nginx_config
assert "keepalive_timeout 300;" in nginx_config
logs = get_logs(container)
assert "getting INI configuration from /app/uwsgi.ini" in logs
assert "getting INI configuration from /etc/uwsgi/uwsgi.ini" in logs
assert "ini = /app/uwsgi.ini" in logs
assert "ini = /etc/uwsgi/uwsgi.ini" in logs
assert "socket = /tmp/uwsgi.sock" in logs
assert "chown-socket = nginx:nginx" in logs
assert "chmod-socket = 664" in logs
<|code_end|>
, determine the next line of code. You have imports:
import os
import time
import docker
import requests
from pathlib import Path
from docker.models.containers import Container
from ..utils import (
CONTAINER_NAME,
generate_dockerfile_content_custom_nginx_app,
get_logs,
get_nginx_config,
get_response_text2,
remove_previous_container,
)
and context (class names, function names, or code) available:
# Path: tests/utils.py
# CONTAINER_NAME = "uwsgi-nginx-test"
#
# def generate_dockerfile_content_custom_nginx_app(name: str) -> str:
# content = f"FROM tiangolo/uwsgi-nginx:{name}\n"
# content += "COPY app /app\n"
# return content
#
# def get_logs(container: Container) -> str:
# logs = container.logs()
# return logs.decode("utf-8")
#
# def get_nginx_config(container: Container) -> str:
# result = container.exec_run(f"/usr/sbin/nginx -T")
# return result.output.decode()
#
# def get_response_text2() -> str:
# python_version = os.getenv("PYTHON_VERSION")
# return f"Hello World from Nginx uWSGI Python {python_version} app in a Docker container"
#
# def remove_previous_container(client: DockerClient) -> None:
# try:
# previous = client.containers.get(CONTAINER_NAME)
# previous.stop()
# previous.remove()
# except NotFound:
# return None
. Output only the next line. | assert "hook-master-start = unix_signal:15 gracefully_kill_them_all" in logs |
Here is a snippet: <|code_start|>
client = docker.from_env()
def verify_container(container: Container, response_text: str) -> None:
response = requests.get("http://127.0.0.1:8080")
assert response.text == response_text
nginx_config = get_nginx_config(container)
assert "client_max_body_size 0;" not in nginx_config
assert "worker_processes 2;" in nginx_config
assert "listen 8080;" in nginx_config
assert "worker_connections 2048;" in nginx_config
assert "worker_rlimit_nofile;" not in nginx_config
assert "daemon off;" in nginx_config
assert "include uwsgi_params;" in nginx_config
assert "uwsgi_pass unix:///tmp/uwsgi.sock;" in nginx_config
assert "keepalive_timeout 300;" in nginx_config
logs = get_logs(container)
assert "getting INI configuration from /app/uwsgi.ini" in logs
assert "getting INI configuration from /etc/uwsgi/uwsgi.ini" in logs
assert "ini = /app/uwsgi.ini" in logs
assert "ini = /etc/uwsgi/uwsgi.ini" in logs
assert "socket = /tmp/uwsgi.sock" in logs
assert "chown-socket = nginx:nginx" in logs
assert "chmod-socket = 664" in logs
assert "hook-master-start = unix_signal:15 gracefully_kill_them_all" in logs
assert "need-app = true" in logs
assert "die-on-term = true" in logs
assert "show-config = true" in logs
<|code_end|>
. Write the next line using the current file imports:
import os
import time
import docker
import requests
from pathlib import Path
from docker.models.containers import Container
from ..utils import (
CONTAINER_NAME,
generate_dockerfile_content_custom_nginx_app,
get_logs,
get_nginx_config,
get_response_text2,
remove_previous_container,
)
and context from other files:
# Path: tests/utils.py
# CONTAINER_NAME = "uwsgi-nginx-test"
#
# def generate_dockerfile_content_custom_nginx_app(name: str) -> str:
# content = f"FROM tiangolo/uwsgi-nginx:{name}\n"
# content += "COPY app /app\n"
# return content
#
# def get_logs(container: Container) -> str:
# logs = container.logs()
# return logs.decode("utf-8")
#
# def get_nginx_config(container: Container) -> str:
# result = container.exec_run(f"/usr/sbin/nginx -T")
# return result.output.decode()
#
# def get_response_text2() -> str:
# python_version = os.getenv("PYTHON_VERSION")
# return f"Hello World from Nginx uWSGI Python {python_version} app in a Docker container"
#
# def remove_previous_container(client: DockerClient) -> None:
# try:
# previous = client.containers.get(CONTAINER_NAME)
# previous.stop()
# previous.remove()
# except NotFound:
# return None
, which may include functions, classes, or code. Output only the next line. | assert "wsgi-file = /app/main.py" in logs |
Given the code snippet: <|code_start|>
client = docker.from_env()
def verify_container(container: Container, response_text: str) -> None:
response = requests.get("http://127.0.0.1:8080")
assert response.text == response_text
nginx_config = get_nginx_config(container)
assert "client_max_body_size 0;" not in nginx_config
assert "worker_processes 2;" in nginx_config
assert "listen 8080;" in nginx_config
assert "worker_connections 2048;" in nginx_config
assert "worker_rlimit_nofile;" not in nginx_config
assert "daemon off;" in nginx_config
assert "include uwsgi_params;" in nginx_config
assert "uwsgi_pass unix:///tmp/uwsgi.sock;" in nginx_config
<|code_end|>
, generate the next line using the imports in this file:
import os
import time
import docker
import requests
from pathlib import Path
from docker.models.containers import Container
from ..utils import (
CONTAINER_NAME,
generate_dockerfile_content_custom_nginx_app,
get_logs,
get_nginx_config,
get_response_text2,
remove_previous_container,
)
and context (functions, classes, or occasionally code) from other files:
# Path: tests/utils.py
# CONTAINER_NAME = "uwsgi-nginx-test"
#
# def generate_dockerfile_content_custom_nginx_app(name: str) -> str:
# content = f"FROM tiangolo/uwsgi-nginx:{name}\n"
# content += "COPY app /app\n"
# return content
#
# def get_logs(container: Container) -> str:
# logs = container.logs()
# return logs.decode("utf-8")
#
# def get_nginx_config(container: Container) -> str:
# result = container.exec_run(f"/usr/sbin/nginx -T")
# return result.output.decode()
#
# def get_response_text2() -> str:
# python_version = os.getenv("PYTHON_VERSION")
# return f"Hello World from Nginx uWSGI Python {python_version} app in a Docker container"
#
# def remove_previous_container(client: DockerClient) -> None:
# try:
# previous = client.containers.get(CONTAINER_NAME)
# previous.stop()
# previous.remove()
# except NotFound:
# return None
. Output only the next line. | assert "keepalive_timeout 300;" in nginx_config |
Predict the next line after this snippet: <|code_start|> assert "spawned uWSGI master process" in logs
assert "spawned uWSGI worker 1" in logs
assert "spawned uWSGI worker 2" in logs
assert "spawned uWSGI worker 3" not in logs
assert 'running "unix_signal:15 gracefully_kill_them_all" (master-start)' in logs
assert "success: nginx entered RUNNING state, process has stayed up for" in logs
assert "success: uwsgi entered RUNNING state, process has stayed up for" in logs
def test_env_vars_1() -> None:
name = os.getenv("NAME", "")
dockerfile_content = generate_dockerfile_content_custom_nginx_app(name)
dockerfile = "Dockerfile"
response_text = get_response_text2()
sleep_time = int(os.getenv("SLEEP_TIME", 3))
remove_previous_container(client)
tag = "uwsgi-nginx-testimage"
test_path = Path(__file__)
path = test_path.parent / "custom_nginx_app"
dockerfile_path = path / dockerfile
dockerfile_path.write_text(dockerfile_content)
client.images.build(path=str(path), dockerfile=dockerfile, tag=tag)
container = client.containers.run(
tag, name=CONTAINER_NAME, ports={"8080": "8080"}, detach=True
)
time.sleep(sleep_time)
verify_container(container, response_text)
container.stop()
# Test that everything works after restarting too
container.start()
<|code_end|>
using the current file's imports:
import os
import time
import docker
import requests
from pathlib import Path
from docker.models.containers import Container
from ..utils import (
CONTAINER_NAME,
generate_dockerfile_content_custom_nginx_app,
get_logs,
get_nginx_config,
get_response_text2,
remove_previous_container,
)
and any relevant context from other files:
# Path: tests/utils.py
# CONTAINER_NAME = "uwsgi-nginx-test"
#
# def generate_dockerfile_content_custom_nginx_app(name: str) -> str:
# content = f"FROM tiangolo/uwsgi-nginx:{name}\n"
# content += "COPY app /app\n"
# return content
#
# def get_logs(container: Container) -> str:
# logs = container.logs()
# return logs.decode("utf-8")
#
# def get_nginx_config(container: Container) -> str:
# result = container.exec_run(f"/usr/sbin/nginx -T")
# return result.output.decode()
#
# def get_response_text2() -> str:
# python_version = os.getenv("PYTHON_VERSION")
# return f"Hello World from Nginx uWSGI Python {python_version} app in a Docker container"
#
# def remove_previous_container(client: DockerClient) -> None:
# try:
# previous = client.containers.get(CONTAINER_NAME)
# previous.stop()
# previous.remove()
# except NotFound:
# return None
. Output only the next line. | time.sleep(sleep_time) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.