Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
# (c) 2015 Andreas Motl <andreas.motl@getkotori.org>
# https://pypi.python.org/pypi/twisted-mqtt
# https://github.com/astrorafael/twisted-mqtt/
from __future__ import absolute_import
log = Logger()
class TwistedMqttAdapter(BaseMqttAdapter, Service):
def connect(self):
log.info('Connecting')
factory = MQTTFactory(profile=MQTTFactory.PUBLISHER | MQTTFactory.SUBSCRIBER)
point = TCP4ClientEndpoint(reactor, self.broker_host, self.broker_port)
d = point.connect(factory).addCallback(self.gotProtocol)
d.addErrback(self.on_error)
def gotProtocol(self, p):
<|code_end|>
. Use current file imports:
from twisted.logger import Logger
from twisted.internet import reactor
from twisted.application.service import Service
from twisted.internet.endpoints import TCP4ClientEndpoint
from kotori.daq.intercom.mqtt.base import BaseMqttAdapter
from mqtt.client.factory import MQTTFactory
and context (classes, functions, or code) from other files:
# Path: kotori/daq/intercom/mqtt/base.py
# class BaseMqttAdapter(object):
#
# def __init__(self, name,
# broker_host=u'localhost', broker_port=1883, broker_username=None, broker_password=None,
# debug=False, callback=None, subscriptions=None):
# self.name = name
# self.broker_host = broker_host
# self.broker_port = broker_port
# self.broker_username = broker_username
# self.broker_password = broker_password
# self.callback = callback or self.on_message
# self.subscriptions = subscriptions or []
#
# def startService(self):
# self.log(log.info, u'Starting')
# self.running = 1
# self.connect()
# #reactor.callInThread(self.connect)
#
# def connect(self):
# raise NotImplementedError('Please implement the "connect" method in derived class')
#
# def subscribe(self, *args):
# raise NotImplementedError('Please implement the "subscribe" method in derived class')
#
# def on_message(self, topic=None, payload=None, **kwargs):
# # former def on_message(self, topic, payload, qos, dup, retain, msgId):
# # kwargs: qos, dup, retain, msgId
# raise NotImplementedError('Please implement the "on_message" method in derived class or pass a callable using the "callback" constructor argument')
#
# def on_error(self, *args):
# log.error("ERROR: args={args!s}", args=args)
#
# def log(self, callable, prefix):
# callable(u'{prefix} {class_name}. name={name}, broker={broker_host}:{broker_port}, object={repr}',
# prefix=prefix, class_name=self.__class__.__name__,
# name=self.name, repr=repr(self),
# broker_host=self.broker_host, broker_port=self.broker_port)
#
# """
# def _todo_publish(self):
# d = self.protocol.publish(topic="foo/bar/baz", message="hello friends")
# d.addErrback(self.on_error)
#
# def _todo_prepareToPublish(self, *args):
# self.task = task.LoopingCall(self.publish)
# self.task.start(5.0)
# """
. Output only the next line. | log.info('gotProtocol, connecting {name}', name=self.name) |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
# (c) 2016-2021 Andreas Motl <andreas@getkotori.org>
log = Logger()
class QueryTransformer(object):
@classmethod
<|code_end|>
with the help of current file imports:
import arrow
from arrow.parser import DateTimeParser
from datetime import datetime, timedelta
from twisted.logger import Logger
from kotori.io.protocol.util import is_number
from kotori.util.common import tdelta
from pyinfluxql import Query
from pyinfluxql.functions import Mean
and context from other files:
# Path: kotori/io/protocol/util.py
# def is_number(s):
# """
# Check string for being a numeric value.
# http://pythoncentral.io/how-to-check-if-a-string-is-a-number-in-python-including-unicode/
# """
# try:
# float(s)
# return True
# except ValueError:
# pass
#
# try:
# import unicodedata
# unicodedata.numeric(s)
# return True
# except (TypeError, ValueError):
# pass
#
# return False
#
# Path: kotori/util/common.py
# def tdelta(input):
# # https://blog.posativ.org/2011/parsing-human-readable-timedeltas-in-python/
# keys = ["weeks", "days", "hours", "minutes", "seconds"]
# regex = "".join(["((?P<%s>\d+)%s ?)?" % (k, k[0]) for k in keys])
# kwargs = {}
# for k,v in re.match(regex, input).groupdict(default="0").items():
# kwargs[k] = int(v)
# return timedelta(**kwargs)
, which may contain function names, class names, or code. Output only the next line. | def transform(cls, data): |
Predict the next line after this snippet: <|code_start|> # Check response.
response = deferred.result
assert response.status_code == 200
assert response.content == json.dumps([
{"type": "info", "message": "Received header fields ['temperature', 'humidity']"},
{"type": "info", "message": "Received #1 readings"},
], indent=4).encode("utf-8")
# Wait for some time to process the message.
yield sleep(PROCESS_DELAY_HTTP)
# Proof that data arrived in InfluxDB.
record = influx_sensors.get_first_record()
del record['time']
assert record == {u'temperature': 25.26, u'humidity': 51.8}
yield record
@pytest_twisted.inlineCallbacks
@pytest.mark.http
@pytest.mark.mongodb
def test_http_csv_semicolon_valid(machinery, create_influxdb, reset_influxdb):
"""
Submit two readings in Variometer CSV format to HTTP API
and proof they are stored in the InfluxDB database.
"""
# Submit a single measurement, with timestamp.
def submit():
data = """
<|code_end|>
using the current file's imports:
import json
import logging
import pytest
import pytest_twisted
import requests
from twisted.internet import threads
from test.settings.mqttkit import settings, influx_sensors, PROCESS_DELAY_HTTP
from test.util import http_json_sensor, http_form_sensor, http_csv_sensor, sleep, http_raw
and any relevant context from other files:
# Path: test/settings/mqttkit.py
# PROCESS_DELAY_MQTT = 0.3
# PROCESS_DELAY_HTTP = 0.3
# class TestSettings:
#
# Path: test/util.py
# def http_json_sensor(topic, data):
# uri = 'http://localhost:24642/api{}'.format(topic)
# logger.info('HTTP: Submitting reading to {} using JSON'.format(uri))
# return requests.post(uri, json=data)
#
# def http_form_sensor(topic, data):
# uri = 'http://localhost:24642/api{}'.format(topic)
# logger.info('HTTP: Submitting reading to {} using x-www-form-urlencoded'.format(uri))
# return requests.post(uri, data=data)
#
# def http_csv_sensor(topic, data):
# uri = 'http://localhost:24642/api{}'.format(topic)
# logger.info('HTTP: Submitting reading to {} using CSV'.format(uri))
# body = ''
# body += '## {}\n'.format(','.join(map(str, list(data.keys()))))
# body += '{}\n'.format(','.join(map(str, list(data.values()))))
# return requests.post(uri, data=body, headers={'Content-Type': 'text/csv'})
#
# def sleep(secs):
# # https://gist.github.com/jhorman/891717
# return deferLater(reactor, secs, lambda: None)
#
# def http_raw(topic, headers=None, json=None, data=None):
# uri = 'http://localhost:24642/api{}'.format(topic)
# logger.info('HTTP: Submitting raw request to {}'.format(uri))
# return requests.post(uri, headers=headers, json=json, data=data)
. Output only the next line. | Runtime;BatVolt;batPercent;Date;Time;Startflag;alt[ft];Pressure[hpa];SensorTemp[Deg];QNH[hpa];VAR[m/s];Envelope Temp[Deg];HDG[deg];GS[kt];GPS_Alt[m];Lat[deg];Lon[deg]; |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
# (c) 2020-2021 Andreas Motl <andreas@getkotori.org>
logger = logging.getLogger(__name__)
@pytest_twisted.inlineCallbacks
@pytest.mark.http
<|code_end|>
. Write the next line using the current file imports:
import json
import logging
import pytest
import pytest_twisted
import requests
from twisted.internet import threads
from test.settings.mqttkit import settings, influx_sensors, PROCESS_DELAY_HTTP
from test.util import http_json_sensor, http_form_sensor, http_csv_sensor, sleep, http_raw
and context from other files:
# Path: test/settings/mqttkit.py
# PROCESS_DELAY_MQTT = 0.3
# PROCESS_DELAY_HTTP = 0.3
# class TestSettings:
#
# Path: test/util.py
# def http_json_sensor(topic, data):
# uri = 'http://localhost:24642/api{}'.format(topic)
# logger.info('HTTP: Submitting reading to {} using JSON'.format(uri))
# return requests.post(uri, json=data)
#
# def http_form_sensor(topic, data):
# uri = 'http://localhost:24642/api{}'.format(topic)
# logger.info('HTTP: Submitting reading to {} using x-www-form-urlencoded'.format(uri))
# return requests.post(uri, data=data)
#
# def http_csv_sensor(topic, data):
# uri = 'http://localhost:24642/api{}'.format(topic)
# logger.info('HTTP: Submitting reading to {} using CSV'.format(uri))
# body = ''
# body += '## {}\n'.format(','.join(map(str, list(data.keys()))))
# body += '{}\n'.format(','.join(map(str, list(data.values()))))
# return requests.post(uri, data=body, headers={'Content-Type': 'text/csv'})
#
# def sleep(secs):
# # https://gist.github.com/jhorman/891717
# return deferLater(reactor, secs, lambda: None)
#
# def http_raw(topic, headers=None, json=None, data=None):
# uri = 'http://localhost:24642/api{}'.format(topic)
# logger.info('HTTP: Submitting raw request to {}'.format(uri))
# return requests.post(uri, headers=headers, json=json, data=data)
, which may include functions, classes, or code. Output only the next line. | def test_http_json_valid(machinery, create_influxdb, reset_influxdb): |
Predict the next line after this snippet: <|code_start|> response = deferred.result
assert response.status_code == 200
assert response.content == json.dumps([
{"type": "info", "message": "Received header fields ['temperature', 'humidity']"},
{"type": "info", "message": "Received #1 readings"},
], indent=4).encode("utf-8")
# Wait for some time to process the message.
yield sleep(PROCESS_DELAY_HTTP)
# Proof that data arrived in InfluxDB.
record = influx_sensors.get_first_record()
del record['time']
assert record == {u'temperature': 25.26, u'humidity': 51.8}
yield record
@pytest_twisted.inlineCallbacks
@pytest.mark.http
@pytest.mark.mongodb
def test_http_csv_semicolon_valid(machinery, create_influxdb, reset_influxdb):
"""
Submit two readings in Variometer CSV format to HTTP API
and proof they are stored in the InfluxDB database.
"""
# Submit a single measurement, with timestamp.
def submit():
data = """
Runtime;BatVolt;batPercent;Date;Time;Startflag;alt[ft];Pressure[hpa];SensorTemp[Deg];QNH[hpa];VAR[m/s];Envelope Temp[Deg];HDG[deg];GS[kt];GPS_Alt[m];Lat[deg];Lon[deg];
<|code_end|>
using the current file's imports:
import json
import logging
import pytest
import pytest_twisted
import requests
from twisted.internet import threads
from test.settings.mqttkit import settings, influx_sensors, PROCESS_DELAY_HTTP
from test.util import http_json_sensor, http_form_sensor, http_csv_sensor, sleep, http_raw
and any relevant context from other files:
# Path: test/settings/mqttkit.py
# PROCESS_DELAY_MQTT = 0.3
# PROCESS_DELAY_HTTP = 0.3
# class TestSettings:
#
# Path: test/util.py
# def http_json_sensor(topic, data):
# uri = 'http://localhost:24642/api{}'.format(topic)
# logger.info('HTTP: Submitting reading to {} using JSON'.format(uri))
# return requests.post(uri, json=data)
#
# def http_form_sensor(topic, data):
# uri = 'http://localhost:24642/api{}'.format(topic)
# logger.info('HTTP: Submitting reading to {} using x-www-form-urlencoded'.format(uri))
# return requests.post(uri, data=data)
#
# def http_csv_sensor(topic, data):
# uri = 'http://localhost:24642/api{}'.format(topic)
# logger.info('HTTP: Submitting reading to {} using CSV'.format(uri))
# body = ''
# body += '## {}\n'.format(','.join(map(str, list(data.keys()))))
# body += '{}\n'.format(','.join(map(str, list(data.values()))))
# return requests.post(uri, data=body, headers={'Content-Type': 'text/csv'})
#
# def sleep(secs):
# # https://gist.github.com/jhorman/891717
# return deferLater(reactor, secs, lambda: None)
#
# def http_raw(topic, headers=None, json=None, data=None):
# uri = 'http://localhost:24642/api{}'.format(topic)
# logger.info('HTTP: Submitting raw request to {}'.format(uri))
# return requests.post(uri, headers=headers, json=json, data=data)
. Output only the next line. | 05;4.0;75.67;21/09/21;07:21:55;0;2213.7;934.79;17.03;1013.25; +0.0;0.00; 0;0.0; 0;0.000000;0.000000; |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
# (c) 2020-2021 Andreas Motl <andreas@getkotori.org>
logger = logging.getLogger(__name__)
@pytest_twisted.inlineCallbacks
@pytest.mark.http
<|code_end|>
with the help of current file imports:
import json
import logging
import pytest
import pytest_twisted
import requests
from twisted.internet import threads
from test.settings.mqttkit import settings, influx_sensors, PROCESS_DELAY_HTTP
from test.util import http_json_sensor, http_form_sensor, http_csv_sensor, sleep, http_raw
and context from other files:
# Path: test/settings/mqttkit.py
# PROCESS_DELAY_MQTT = 0.3
# PROCESS_DELAY_HTTP = 0.3
# class TestSettings:
#
# Path: test/util.py
# def http_json_sensor(topic, data):
# uri = 'http://localhost:24642/api{}'.format(topic)
# logger.info('HTTP: Submitting reading to {} using JSON'.format(uri))
# return requests.post(uri, json=data)
#
# def http_form_sensor(topic, data):
# uri = 'http://localhost:24642/api{}'.format(topic)
# logger.info('HTTP: Submitting reading to {} using x-www-form-urlencoded'.format(uri))
# return requests.post(uri, data=data)
#
# def http_csv_sensor(topic, data):
# uri = 'http://localhost:24642/api{}'.format(topic)
# logger.info('HTTP: Submitting reading to {} using CSV'.format(uri))
# body = ''
# body += '## {}\n'.format(','.join(map(str, list(data.keys()))))
# body += '{}\n'.format(','.join(map(str, list(data.values()))))
# return requests.post(uri, data=body, headers={'Content-Type': 'text/csv'})
#
# def sleep(secs):
# # https://gist.github.com/jhorman/891717
# return deferLater(reactor, secs, lambda: None)
#
# def http_raw(topic, headers=None, json=None, data=None):
# uri = 'http://localhost:24642/api{}'.format(topic)
# logger.info('HTTP: Submitting raw request to {}'.format(uri))
# return requests.post(uri, headers=headers, json=json, data=data)
, which may contain function names, class names, or code. Output only the next line. | def test_http_json_valid(machinery, create_influxdb, reset_influxdb): |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
# (c) 2014 Andreas Motl, Elmyra UG <andreas.motl@elmyra.de>
class BinaryInputPort(object):
def __init__(self, portname, signal=None):
self.portname = portname
self.signal = signal
# detect edge on port
self.gpio = GpioInput(self.portname, self.sensor_on)
def sensor_on(self, port):
print("DEBUG: Port {0} EVENT".format(self.portname))
# signal sensor-on
<|code_end|>
using the current file's imports:
from twisted.internet import reactor
from twisted.internet.task import LoopingCall
from kotori.vendor.ilaundry.node.gpio import GpioInput, GpioOutput
and any relevant context from other files:
# Path: kotori/vendor/ilaundry/node/gpio.py
# class GpioInput(object):
#
# def __init__(self, port, callback):
# self.port = port
# self.callback = callback
#
# GPIO.setup(self.port, GPIO.IN)
#
# print("DETECT EVENTS:", self.port)
#
# # GPIO.RISING, GPIO.FALLING, GPIO.BOTH
# GPIO.remove_event_detect(self.port)
# GPIO.add_event_detect(self.port, GPIO.RISING, callback=self.check_rising, bouncetime=300)
# #GPIO.add_event_detect(self.port, GPIO.BOTH, callback=self.check_rising)
# #GPIO.add_event_detect(self.port, GPIO.FALLING, callback=self.check_falling)
# #GPIO.add_event_detect(self.port, GPIO.FALLING, self.check_falling)
#
# def check_rising(self, port):
# #print "check_rising:", port, self.port
# if port == self.port:
# reactor.callFromThread(self.callback, port)
#
# # doesn't work with Adafruit GPIO
# """
# def check_falling(self, port):
# if port == self.port:
# #self.callback(port)
# print "================= FALLING"
# """
#
# class GpioOutput(object):
#
# def __init__(self, port):
# self.port = port
# GPIO.setup(self.port, GPIO.OUT)
#
# def on(self):
# self.high()
#
# def off(self):
# self.low()
#
# def low(self):
# GPIO.output(self.port, GPIO.LOW)
#
# def high(self):
# GPIO.output(self.port, GPIO.HIGH)
. Output only the next line. | if self.signal: |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
# (c) 2014 Andreas Motl, Elmyra UG <andreas.motl@elmyra.de>
class BinaryInputPort(object):
def __init__(self, portname, signal=None):
self.portname = portname
self.signal = signal
# detect edge on port
self.gpio = GpioInput(self.portname, self.sensor_on)
def sensor_on(self, port):
<|code_end|>
, generate the next line using the imports in this file:
from twisted.internet import reactor
from twisted.internet.task import LoopingCall
from kotori.vendor.ilaundry.node.gpio import GpioInput, GpioOutput
and context (functions, classes, or occasionally code) from other files:
# Path: kotori/vendor/ilaundry/node/gpio.py
# class GpioInput(object):
#
# def __init__(self, port, callback):
# self.port = port
# self.callback = callback
#
# GPIO.setup(self.port, GPIO.IN)
#
# print("DETECT EVENTS:", self.port)
#
# # GPIO.RISING, GPIO.FALLING, GPIO.BOTH
# GPIO.remove_event_detect(self.port)
# GPIO.add_event_detect(self.port, GPIO.RISING, callback=self.check_rising, bouncetime=300)
# #GPIO.add_event_detect(self.port, GPIO.BOTH, callback=self.check_rising)
# #GPIO.add_event_detect(self.port, GPIO.FALLING, callback=self.check_falling)
# #GPIO.add_event_detect(self.port, GPIO.FALLING, self.check_falling)
#
# def check_rising(self, port):
# #print "check_rising:", port, self.port
# if port == self.port:
# reactor.callFromThread(self.callback, port)
#
# # doesn't work with Adafruit GPIO
# """
# def check_falling(self, port):
# if port == self.port:
# #self.callback(port)
# print "================= FALLING"
# """
#
# class GpioOutput(object):
#
# def __init__(self, port):
# self.port = port
# GPIO.setup(self.port, GPIO.OUT)
#
# def on(self):
# self.high()
#
# def off(self):
# self.low()
#
# def low(self):
# GPIO.output(self.port, GPIO.LOW)
#
# def high(self):
# GPIO.output(self.port, GPIO.HIGH)
. Output only the next line. | print("DEBUG: Port {0} EVENT".format(self.portname)) |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
# (c) 2020-2021 Andreas Motl <andreas@getkotori.org>
logger = logging.getLogger(__name__)
@pytest_twisted.inlineCallbacks
@pytest.mark.http
@pytest.mark.export
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import json
import logging
import io
import pandas as pd
import pytest
import pytest_twisted
import h5py
from twisted.internet import threads
from test.settings.mqttkit import settings, PROCESS_DELAY_MQTT
from test.util import sleep, http_json_sensor, http_get_data
from pandas.testing import assert_frame_equal
from datadiff.tools import assert_equal
from io import BytesIO
from pandas import array
and context:
# Path: test/settings/mqttkit.py
# PROCESS_DELAY_MQTT = 0.3
# PROCESS_DELAY_HTTP = 0.3
# class TestSettings:
#
# Path: test/util.py
# def sleep(secs):
# # https://gist.github.com/jhorman/891717
# return deferLater(reactor, secs, lambda: None)
#
# def http_json_sensor(topic, data):
# uri = 'http://localhost:24642/api{}'.format(topic)
# logger.info('HTTP: Submitting reading to {} using JSON'.format(uri))
# return requests.post(uri, json=data)
#
# def http_get_data(topic=None, format='csv', ts_from=None, ts_to=None):
# uri = 'http://localhost:24642/api{topic}.{format}?from={ts_from}&to={ts_to}'.format(
# topic=topic, format=format, ts_from=ts_from, ts_to=ts_to)
# logger.info('HTTP: Exporting data from {} using format "{}"'.format(uri, format))
# payload = requests.get(uri).content
# if format in ["csv", "txt", "json", "html"]:
# payload = payload.decode()
# return payload
which might include code, classes, or functions. Output only the next line. | def test_export(machinery, create_influxdb, reset_influxdb): |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
# (c) 2020-2021 Andreas Motl <andreas@getkotori.org>
logger = logging.getLogger(__name__)
@pytest_twisted.inlineCallbacks
@pytest.mark.http
<|code_end|>
. Use current file imports:
(import json
import logging
import io
import pandas as pd
import pytest
import pytest_twisted
import h5py
from twisted.internet import threads
from test.settings.mqttkit import settings, PROCESS_DELAY_MQTT
from test.util import sleep, http_json_sensor, http_get_data
from pandas.testing import assert_frame_equal
from datadiff.tools import assert_equal
from io import BytesIO
from pandas import array)
and context including class names, function names, or small code snippets from other files:
# Path: test/settings/mqttkit.py
# PROCESS_DELAY_MQTT = 0.3
# PROCESS_DELAY_HTTP = 0.3
# class TestSettings:
#
# Path: test/util.py
# def sleep(secs):
# # https://gist.github.com/jhorman/891717
# return deferLater(reactor, secs, lambda: None)
#
# def http_json_sensor(topic, data):
# uri = 'http://localhost:24642/api{}'.format(topic)
# logger.info('HTTP: Submitting reading to {} using JSON'.format(uri))
# return requests.post(uri, json=data)
#
# def http_get_data(topic=None, format='csv', ts_from=None, ts_to=None):
# uri = 'http://localhost:24642/api{topic}.{format}?from={ts_from}&to={ts_to}'.format(
# topic=topic, format=format, ts_from=ts_from, ts_to=ts_to)
# logger.info('HTTP: Exporting data from {} using format "{}"'.format(uri, format))
# payload = requests.get(uri).content
# if format in ["csv", "txt", "json", "html"]:
# payload = payload.decode()
# return payload
. Output only the next line. | @pytest.mark.export |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
# (c) 2020-2021 Andreas Motl <andreas@getkotori.org>
logger = logging.getLogger(__name__)
@pytest_twisted.inlineCallbacks
@pytest.mark.http
<|code_end|>
using the current file's imports:
import json
import logging
import io
import pandas as pd
import pytest
import pytest_twisted
import h5py
from twisted.internet import threads
from test.settings.mqttkit import settings, PROCESS_DELAY_MQTT
from test.util import sleep, http_json_sensor, http_get_data
from pandas.testing import assert_frame_equal
from datadiff.tools import assert_equal
from io import BytesIO
from pandas import array
and any relevant context from other files:
# Path: test/settings/mqttkit.py
# PROCESS_DELAY_MQTT = 0.3
# PROCESS_DELAY_HTTP = 0.3
# class TestSettings:
#
# Path: test/util.py
# def sleep(secs):
# # https://gist.github.com/jhorman/891717
# return deferLater(reactor, secs, lambda: None)
#
# def http_json_sensor(topic, data):
# uri = 'http://localhost:24642/api{}'.format(topic)
# logger.info('HTTP: Submitting reading to {} using JSON'.format(uri))
# return requests.post(uri, json=data)
#
# def http_get_data(topic=None, format='csv', ts_from=None, ts_to=None):
# uri = 'http://localhost:24642/api{topic}.{format}?from={ts_from}&to={ts_to}'.format(
# topic=topic, format=format, ts_from=ts_from, ts_to=ts_to)
# logger.info('HTTP: Exporting data from {} using format "{}"'.format(uri, format))
# payload = requests.get(uri).content
# if format in ["csv", "txt", "json", "html"]:
# payload = payload.decode()
# return payload
. Output only the next line. | @pytest.mark.export |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
# (c) 2020-2021 Andreas Motl <andreas@getkotori.org>
logger = logging.getLogger(__name__)
@pytest_twisted.inlineCallbacks
@pytest.mark.http
<|code_end|>
, generate the next line using the imports in this file:
import json
import logging
import io
import pandas as pd
import pytest
import pytest_twisted
import h5py
from twisted.internet import threads
from test.settings.mqttkit import settings, PROCESS_DELAY_MQTT
from test.util import sleep, http_json_sensor, http_get_data
from pandas.testing import assert_frame_equal
from datadiff.tools import assert_equal
from io import BytesIO
from pandas import array
and context (functions, classes, or occasionally code) from other files:
# Path: test/settings/mqttkit.py
# PROCESS_DELAY_MQTT = 0.3
# PROCESS_DELAY_HTTP = 0.3
# class TestSettings:
#
# Path: test/util.py
# def sleep(secs):
# # https://gist.github.com/jhorman/891717
# return deferLater(reactor, secs, lambda: None)
#
# def http_json_sensor(topic, data):
# uri = 'http://localhost:24642/api{}'.format(topic)
# logger.info('HTTP: Submitting reading to {} using JSON'.format(uri))
# return requests.post(uri, json=data)
#
# def http_get_data(topic=None, format='csv', ts_from=None, ts_to=None):
# uri = 'http://localhost:24642/api{topic}.{format}?from={ts_from}&to={ts_to}'.format(
# topic=topic, format=format, ts_from=ts_from, ts_to=ts_to)
# logger.info('HTTP: Exporting data from {} using format "{}"'.format(uri, format))
# payload = requests.get(uri).content
# if format in ["csv", "txt", "json", "html"]:
# payload = payload.decode()
# return payload
. Output only the next line. | @pytest.mark.export |
Based on the snippet: <|code_start|>
class PlainRouter(BaseRouter):
def get_hosts(self, **kwargs):
return self.hosts
class ShuffleRouter(BaseRouter):
def __init__(self, solr, hosts):
super().__init__(solr, hosts)
# only shuffle the hosts once, so they're in a different order in all your processes
# not all proesses contact the same host, but distribute requests
self.shuffle_hosts()
class RandomRouter(BaseRouter):
<|code_end|>
, predict the immediate next line with the help of imports:
from .base import BaseRouter
and context (classes, functions, sometimes code) from other files:
# Path: SolrClient/routers/base.py
# class BaseRouter(object):
# def __init__(self, solr, hosts, **kwargs):
# self.solr = solr
# self.hosts = self._proc_host(hosts)
# self.logger = logging.getLogger(str(__package__))
#
# def get_hosts(self, **kwargs):
# raise NotImplementedError
#
# def _proc_host(self, host):
# if type(host) is str:
# if not host.endswith('/'):
# host += '/'
# return [host]
# elif type(host) is list:
# for index, h in enumerate(host):
# if not h.endswith('/'):
# host[index] = h + '/'
# return host
# raise Exception("host:%s type: %s is not string or list of strings" % (host, type(host)))
#
# def shuffle_hosts(self):
# """
# Shuffle hosts so we don't always query the first one.
# Example: using in a webapp with X processes in Y servers, the hosts contacted will be more random.
# The user can also call this function to reshuffle every 'x' seconds or before every request.
# :return:
# """
# if len(self.hosts) > 1:
# random.shuffle(self.hosts)
# return self.hosts
. Output only the next line. | def get_hosts(self, **kwargs): |
Given the code snippet: <|code_start|># from sklearn.utils import class_weight as cw
def create_gridsearch_model(logger, rparams, gparams, options, exp_settings, scoring, select_model, input_shape, output_shape):
sklearn_params = {
'param_distributions': gparams,
'n_iter': options.n_iter,
'n_jobs': options.n_jobs,
'cv': options.n_cv,
'verbose': exp_settings["verbose"],
'scoring': scoring,
'return_train_score': True,
'refit': True,
'random_state': exp_settings["random_state"]}
keras_params = {
'param_distributions': gparams,
'n_iter': options.n_iter,
'n_jobs': options.n_jobs,
'cv': options.n_cv,
'verbose': exp_settings["verbose"],
'scoring': scoring,
'return_train_score': True,
'refit': True,
'pre_dispatch': options.n_cv,
<|code_end|>
, generate the next line using the imports in this file:
import sys
import xgboost as xgb
from sklearn.svm import SVC, SVR
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LogisticRegression, LinearRegression
from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor
from sklearn.ensemble import RandomForestClassifier, IsolationForest, RandomForestRegressor
from sklearn.ensemble import AdaBoostClassifier, AdaBoostRegressor, BaggingClassifier, BaggingRegressor
from sklearn.ensemble import GradientBoostingClassifier, GradientBoostingRegressor, ExtraTreesClassifier, ExtraTreesRegressor
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor, ExtraTreeClassifier, ExtraTreeRegressor
from sklearn.neural_network import BernoulliRBM, MLPClassifier, MLPRegressor
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV # , PredefinedSplit
from keras.wrappers.scikit_learn import KerasClassifier
from moloi.models.keras_models import FCNN, LSTM, MLP, Logreg
from sklearn.isotonic import IsotonicRegression
from lightgbm import LGBMClassifier, LGBMRegressor
from keras.wrappers.scikit_learn import KerasClassifier
and context (functions, classes, or occasionally code) from other files:
# Path: moloi/models/keras_models.py
# def FCNN(input_shape, output_shape, inference=False, input_dropout=0.0, l2=0.0, hidden_dim_1=100,
# hidden_dim_2=100, activation="relu", bn=True, dropout_1=0.3, dropout_2=0.3,
# loss='binary_crossentropy', metrics=['accuracy'], optimizer='Adam'):
# dropouts = [dropout_1, dropout_2]
# hidden_dims = [hidden_dim_1, hidden_dim_2]
# input = Input(shape=(input_shape,))
# x = Dense(input_dropout)(input)
# for h_id, (hd, drop) in enumerate(zip(hidden_dims, dropouts)):
# x = Dense(hd, name="dense_" + str(h_id), kernel_regularizer=l2_reg(l2))(x)
# if bn:
# x = BatchNormalization(name="bn_" + str(h_id))(x)
# x = Dropout(drop, name="drop_" + str(h_id))(x) # , training=not inference)
# x = Activation(activation, name="act_" + str(h_id))(x)
# # TODO: Refactor
# if output_shape == 1:
# output = Dense(input_shape=(input_shape,), activation="sigmoid", units=1, name="final_softmax",
# kernel_regularizer=l2_reg(l2))(x)
# else:
# output = Dense(input_shape=(input_shape,), activation="softmax", units=output_shape, name="final_softmax",
# kernel_regularizer=l2_reg(l2))(x)
# model = Model(inputs=[input], outputs=[output])
# model.compile(loss=loss, metrics=metrics, optimizer=optimizer)
# # model.summary()
# setattr(model, "steerable_variables", {})
# return model
#
# def LSTM(input_shape, output_shape, input_length, embedding_length=64, neurons=256,
# activation='softmax', loss='binary_crossentropy', metrics=['accuracy'], optimizer='Adam'):
# model = Sequential()
# model.add(Embedding(input_shape, embedding_length, input_length=input_length))
# model.add(LSTM_layer(neurons))
# model.add(Dropout(0.2))
# model.add(Dense(output_shape, activation=activation))
# model.compile(loss=loss, optimizer=optimizer, metrics=metrics)
# return model
#
# def MLP(input_shape, output_shape, activation_1='relu', activation_2='sigmoid',
# loss='binary_crossentropy', metrics=['accuracy'], optimizer='Adam', learning_rate=0.01,
# momentum=0, init_mode='uniform', layers=3, neurons_1=10, neurons_2=10):
# """
# Multilayer perceptron model definition
# """
# model = Sequential()
# model.add(Dense(input_shape=(input_shape, ), kernel_initializer=init_mode,
# activation=activation_1, units=neurons_1))
#
# for _ in range(layers):
# model.add(Dense(kernel_initializer=init_mode, activation=activation_1, units=neurons_2))
#
# model.add(Dense(kernel_initializer=init_mode, activation=activation_2, units=output_shape))
# optimizer = compile_optimizer(optimizer, learning_rate, momentum)
# model.compile(loss=loss, metrics=metrics, optimizer=optimizer)
# return model
#
# def Logreg(input_shape, output_shape, l2=0.0, lr=0.1, momentum=0.9, metrics=['binary_crossentropy', 'accuracy'],
# loss='binary_crossentropy', activation='sigmoid'):
# """
# Logistic regression model definition
# """
# model = Sequential()
# model.add(Dense(input_shape=(input_shape, ), activation=activation,
# kernel_regularizer=l2_reg(l2), units=output_shape))
# model.compile(loss=loss, optimizer=SGD(lr=lr, momentum=momentum), metrics=metrics)
# return model
. Output only the next line. | 'random_state': exp_settings["random_state"]} |
Next line prediction: <|code_start|>
def create_cv(smiles, split_type, n_cv, random_state, y=False):
if split_type == "scaffold":
count = n_cv
<|code_end|>
. Use current file imports:
(import sys
import numpy as np
from moloi.splits.scaffold_split import scaffold_split
from moloi.splits.cluster_split import cluster_split
from moloi.config_processing import cv_splits_save, cv_splits_load
from sklearn.model_selection import train_test_split)
and context including class names, function names, or small code snippets from other files:
# Path: moloi/splits/scaffold_split.py
# def scaffold_split(smiles, frac_train=.8, seed=777):
# """
# Splits compounds into train/validation/test by scaffold.
#
# Warning: if there is one very popular scaffold can produce unbalanced split
#
# Params
# ------
# smiles: list
# List of smiles
# frac_train: float, default: 0.8
# Float in [0, 1] range indicating size of the training set
# seed: int
# Used to shuffle smiles before splitting
#
# Notes
# -----
# Copied from https://github.com/deepchem/deepchem/blob/master/deepchem/splits/splitters.py
# """
# smiles = list(smiles)
#
# scaffolds = {}
#
# for ind, smi in tqdm(enumerate(smiles), total=len(smiles)):
# scaffold = generate_scaffold(smi)
# if scaffold not in scaffolds:
# scaffolds[scaffold] = [ind]
# else:
# scaffolds[scaffold].append(ind)
#
# scaffolds_keys = list(scaffolds)
# rng = np.random.RandomState(seed)
# rng.shuffle(scaffolds_keys)
#
# train_cutoff = frac_train * len(smiles)
# train_inds, test_inds = [], []
# for scaffold_key in scaffolds_keys:
# if len(train_inds) > train_cutoff:
# test_inds += scaffolds[scaffold_key]
# else:
# train_inds += scaffolds[scaffold_key]
# return train_inds, test_inds
#
# Path: moloi/splits/cluster_split.py
# def cluster_split(smi, test_cluster_id, n_splits):
# X_molprint, _ = molprint2d_count_fingerprinter(np.array(smi))
# X_molprint = X_molprint.astype(np.float32)
# K_molprint_tanimoto = tanimoto_similarity(X_molprint, X_molprint)
#
# clustering = BalancedAgglomerativeClustering(n_clusters=n_splits)
# logger.info("Clustering")
# labels = clustering.fit_predict(K_molprint_tanimoto)
#
# train_ids = np.where(np.array(labels) != test_cluster_id)[0]
# test_ids = np.where(np.array(labels) == test_cluster_id)[0]
#
# return train_ids, test_ids
#
# Path: moloi/config_processing.py
# def cv_splits_save(split_type, split_size, n_cv, data_config, targets):
# sv_config = ConfigParser.ConfigParser()
#
# sv_config.read(data_config)
# try:
# sv_config[split_type + " " + str(split_size)]['cv_' + str(targets)] = str(n_cv)
# except:
# with open(data_config, "a") as ini:
# ini.write('[' + split_type + " " + str(split_size) + ']')
# sv_config.read(data_config)
# sv_config[split_type + " " + str(split_size)]['cv_' + str(targets)] = str(n_cv)
# with open(data_config, 'w') as configfile:
# sv_config.write(configfile)
#
# def cv_splits_load(split_type, split_size, data_config, targets):
# loaded_cv = False
# cv_config = ConfigParser.ConfigParser()
# cv_config.read(data_config)
# if split_type is False:
# section = 'init'
# else:
# section = split_type + " " + str(split_size)
#
# if split_type + " " + str(split_size) not in cv_config.sections():
# section = 'init'
# else:
# section = split_type + " " + str(split_size)
#
# if cv_config.has_option(section, 'cv_' + str(targets)):
# loaded_cv = cv_config.get(section, 'cv_' + str(targets))
# return loaded_cv
. Output only the next line. | n_cv = [([], []) for _ in range(count)] |
Predict the next line for this snippet: <|code_start|> # print(len(test))
# print(len(train))
# n_cv[i][0].append(train)
# n_cv[i][1].append(test)
elif split_type == "random" or split_type == "cluster":
count = n_cv
n_cv = [([], []) for _ in range(count)]
for i in range(count):
shuffle = True
stratify = None
idx = [i for i in range(len(smiles))]
train, test = train_test_split(idx, test_size=1 - ((len(smiles)/count)/(len(smiles)/100))/100,
stratify=stratify, shuffle=shuffle)
n_cv[i][0].append(train)
n_cv[i][1].append(test)
elif split_type == "stratified":
count = n_cv
n_cv = [([], []) for _ in range(count)]
for i in range(count):
shuffle = True
stratify = y
idx = [i for i in range(len(smiles))]
train, test = train_test_split(idx, test_size=1 - ((len(smiles)/count)/(len(smiles)/100))/100,
stratify=stratify, shuffle=shuffle)
n_cv[i][0].append(train)
n_cv[i][1].append(test)
elif split_type == "generator":
<|code_end|>
with the help of current file imports:
import sys
import numpy as np
from moloi.splits.scaffold_split import scaffold_split
from moloi.splits.cluster_split import cluster_split
from moloi.config_processing import cv_splits_save, cv_splits_load
from sklearn.model_selection import train_test_split
and context from other files:
# Path: moloi/splits/scaffold_split.py
# def scaffold_split(smiles, frac_train=.8, seed=777):
# """
# Splits compounds into train/validation/test by scaffold.
#
# Warning: if there is one very popular scaffold can produce unbalanced split
#
# Params
# ------
# smiles: list
# List of smiles
# frac_train: float, default: 0.8
# Float in [0, 1] range indicating size of the training set
# seed: int
# Used to shuffle smiles before splitting
#
# Notes
# -----
# Copied from https://github.com/deepchem/deepchem/blob/master/deepchem/splits/splitters.py
# """
# smiles = list(smiles)
#
# scaffolds = {}
#
# for ind, smi in tqdm(enumerate(smiles), total=len(smiles)):
# scaffold = generate_scaffold(smi)
# if scaffold not in scaffolds:
# scaffolds[scaffold] = [ind]
# else:
# scaffolds[scaffold].append(ind)
#
# scaffolds_keys = list(scaffolds)
# rng = np.random.RandomState(seed)
# rng.shuffle(scaffolds_keys)
#
# train_cutoff = frac_train * len(smiles)
# train_inds, test_inds = [], []
# for scaffold_key in scaffolds_keys:
# if len(train_inds) > train_cutoff:
# test_inds += scaffolds[scaffold_key]
# else:
# train_inds += scaffolds[scaffold_key]
# return train_inds, test_inds
#
# Path: moloi/splits/cluster_split.py
# def cluster_split(smi, test_cluster_id, n_splits):
# X_molprint, _ = molprint2d_count_fingerprinter(np.array(smi))
# X_molprint = X_molprint.astype(np.float32)
# K_molprint_tanimoto = tanimoto_similarity(X_molprint, X_molprint)
#
# clustering = BalancedAgglomerativeClustering(n_clusters=n_splits)
# logger.info("Clustering")
# labels = clustering.fit_predict(K_molprint_tanimoto)
#
# train_ids = np.where(np.array(labels) != test_cluster_id)[0]
# test_ids = np.where(np.array(labels) == test_cluster_id)[0]
#
# return train_ids, test_ids
#
# Path: moloi/config_processing.py
# def cv_splits_save(split_type, split_size, n_cv, data_config, targets):
# sv_config = ConfigParser.ConfigParser()
#
# sv_config.read(data_config)
# try:
# sv_config[split_type + " " + str(split_size)]['cv_' + str(targets)] = str(n_cv)
# except:
# with open(data_config, "a") as ini:
# ini.write('[' + split_type + " " + str(split_size) + ']')
# sv_config.read(data_config)
# sv_config[split_type + " " + str(split_size)]['cv_' + str(targets)] = str(n_cv)
# with open(data_config, 'w') as configfile:
# sv_config.write(configfile)
#
# def cv_splits_load(split_type, split_size, data_config, targets):
# loaded_cv = False
# cv_config = ConfigParser.ConfigParser()
# cv_config.read(data_config)
# if split_type is False:
# section = 'init'
# else:
# section = split_type + " " + str(split_size)
#
# if split_type + " " + str(split_size) not in cv_config.sections():
# section = 'init'
# else:
# section = split_type + " " + str(split_size)
#
# if cv_config.has_option(section, 'cv_' + str(targets)):
# loaded_cv = cv_config.get(section, 'cv_' + str(targets))
# return loaded_cv
, which may contain function names, class names, or code. Output only the next line. | count = n_cv |
Next line prediction: <|code_start|> train, test = scaffold_split(smiles, frac_train=1 - ((len(smiles)/count)/(len(smiles)/100))/100,
seed=random_state)
n_cv[i][0].append(train)
n_cv[i][1].append(test)
# The cluster size can not be specified.
# elif split_type == "cluster":
# count = n_cv
# n_cv = [([], []) for _ in range(count)]
# for i in range(count):
# train, test = cluster_split(smiles, test_cluster_id=1, n_splits=2)
# print(test)
# print(train)
# print(len(test))
# print(len(train))
# n_cv[i][0].append(train)
# n_cv[i][1].append(test)
elif split_type == "random" or split_type == "cluster":
count = n_cv
n_cv = [([], []) for _ in range(count)]
for i in range(count):
shuffle = True
stratify = None
idx = [i for i in range(len(smiles))]
train, test = train_test_split(idx, test_size=1 - ((len(smiles)/count)/(len(smiles)/100))/100,
stratify=stratify, shuffle=shuffle)
n_cv[i][0].append(train)
n_cv[i][1].append(test)
<|code_end|>
. Use current file imports:
(import sys
import numpy as np
from moloi.splits.scaffold_split import scaffold_split
from moloi.splits.cluster_split import cluster_split
from moloi.config_processing import cv_splits_save, cv_splits_load
from sklearn.model_selection import train_test_split)
and context including class names, function names, or small code snippets from other files:
# Path: moloi/splits/scaffold_split.py
# def scaffold_split(smiles, frac_train=.8, seed=777):
# """
# Splits compounds into train/validation/test by scaffold.
#
# Warning: if there is one very popular scaffold can produce unbalanced split
#
# Params
# ------
# smiles: list
# List of smiles
# frac_train: float, default: 0.8
# Float in [0, 1] range indicating size of the training set
# seed: int
# Used to shuffle smiles before splitting
#
# Notes
# -----
# Copied from https://github.com/deepchem/deepchem/blob/master/deepchem/splits/splitters.py
# """
# smiles = list(smiles)
#
# scaffolds = {}
#
# for ind, smi in tqdm(enumerate(smiles), total=len(smiles)):
# scaffold = generate_scaffold(smi)
# if scaffold not in scaffolds:
# scaffolds[scaffold] = [ind]
# else:
# scaffolds[scaffold].append(ind)
#
# scaffolds_keys = list(scaffolds)
# rng = np.random.RandomState(seed)
# rng.shuffle(scaffolds_keys)
#
# train_cutoff = frac_train * len(smiles)
# train_inds, test_inds = [], []
# for scaffold_key in scaffolds_keys:
# if len(train_inds) > train_cutoff:
# test_inds += scaffolds[scaffold_key]
# else:
# train_inds += scaffolds[scaffold_key]
# return train_inds, test_inds
#
# Path: moloi/splits/cluster_split.py
# def cluster_split(smi, test_cluster_id, n_splits):
# X_molprint, _ = molprint2d_count_fingerprinter(np.array(smi))
# X_molprint = X_molprint.astype(np.float32)
# K_molprint_tanimoto = tanimoto_similarity(X_molprint, X_molprint)
#
# clustering = BalancedAgglomerativeClustering(n_clusters=n_splits)
# logger.info("Clustering")
# labels = clustering.fit_predict(K_molprint_tanimoto)
#
# train_ids = np.where(np.array(labels) != test_cluster_id)[0]
# test_ids = np.where(np.array(labels) == test_cluster_id)[0]
#
# return train_ids, test_ids
#
# Path: moloi/config_processing.py
# def cv_splits_save(split_type, split_size, n_cv, data_config, targets):
# sv_config = ConfigParser.ConfigParser()
#
# sv_config.read(data_config)
# try:
# sv_config[split_type + " " + str(split_size)]['cv_' + str(targets)] = str(n_cv)
# except:
# with open(data_config, "a") as ini:
# ini.write('[' + split_type + " " + str(split_size) + ']')
# sv_config.read(data_config)
# sv_config[split_type + " " + str(split_size)]['cv_' + str(targets)] = str(n_cv)
# with open(data_config, 'w') as configfile:
# sv_config.write(configfile)
#
# def cv_splits_load(split_type, split_size, data_config, targets):
# loaded_cv = False
# cv_config = ConfigParser.ConfigParser()
# cv_config.read(data_config)
# if split_type is False:
# section = 'init'
# else:
# section = split_type + " " + str(split_size)
#
# if split_type + " " + str(split_size) not in cv_config.sections():
# section = 'init'
# else:
# section = split_type + " " + str(split_size)
#
# if cv_config.has_option(section, 'cv_' + str(targets)):
# loaded_cv = cv_config.get(section, 'cv_' + str(targets))
# return loaded_cv
. Output only the next line. | elif split_type == "stratified": |
Given the following code snippet before the placeholder: <|code_start|>
if sys.version_info[0] == 2:
else:
def read_model_config(config_path, section):
model_config = ConfigParser.ConfigParser()
model_config.read(config_path)
epochs = eval(model_config.get('DEFAULT', 'epochs'))
rparams = eval(model_config.get(section, 'rparams'))
gparams = eval(model_config.get(section, 'gparams'))
<|code_end|>
, predict the next line using imports from the current file:
import os
import sys
import ConfigParser
import configparser as ConfigParser
from moloi.dictionaries import addresses_dict
and context including class names, function names, and sometimes code from other files:
# Path: moloi/dictionaries.py
# def addresses_dict():
# addresses = {
# 'dataset_train': False,
# 'dataset_test': False,
# 'dataset_val': False,
# 'labels_train': False,
# 'labels_test': False,
# 'labels_val': False,
# 'maccs_train': False,
# 'maccs_test': False,
# 'maccs_val': False,
# 'morgan_train': False,
# 'morgan_test': False,
# 'morgan_val': False,
# 'spectrophore_train': False,
# 'spectrophore_test': False,
# 'spectrophore_val': False,
# 'mordred_train': False,
# 'mordred_test': False,
# 'mordred_val': False,
# 'rdkit_train': False,
# 'rdkit_test': False,
# 'rdkit_val': False,
# 'external_train': False,
# 'external_test': False,
# 'external_val': False
# }
# return addresses
. Output only the next line. | return epochs, rparams, gparams |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
BACKEND = 'loki'
if BACKEND not in BACKENDS.keys():
BACKEND = 'multiprocessing'
# mlp.use('Agg')
params = {
'axes.labelsize': 8,
'font.size': 8,
'legend.fontsize': 10,
'xtick.labelsize': 10,
'ytick.labelsize': 10,
'figure.figsize': [8, 4]
}
<|code_end|>
, predict the next line using imports from the current file:
import os
import pylab
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib as mlp
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from mpl_toolkits.mplot3d import Axes3D # keep it
from sklearn.metrics import roc_auc_score, roc_curve, r2_score, mean_absolute_error
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from joblib import Parallel, delayed
from joblib.parallel import BACKENDS
from moloi.descriptors.rdkit_descriptor import rdkit_fetures_names
from moloi.descriptors.mordred_descriptor import mordred_fetures_names
from moloi.data_processing import m_mean
and context including class names, function names, and sometimes code from other files:
# Path: moloi/descriptors/rdkit_descriptor.py
# def rdkit_fetures_names():
# DESCRIPTORS = {_camel_to_snail(s): f for (s, f) in Descriptors.descList}
# return DESCRIPTORS.keys()
#
# Path: moloi/descriptors/mordred_descriptor.py
# def mordred_fetures_names():
# calc = Calculator(descriptors)
# cols = []
# for i in calc.descriptors:
# i = str(i)
# i = i.split(".")[-1]
# cols.append(str(i))
# return cols
#
# Path: moloi/data_processing.py
# def m_mean(a, column):
# """
# for feature importance
# """
# mean = np.mean(a.T[column])
# for i in range(len(a)):
# a[i][column] = mean
# return a
. Output only the next line. | pylab.rcParams.update(params) |
Next line prediction: <|code_start|>
def correlation(logger, X, path):
logger.info("Creating correlation plot")
try:
X = pd.DataFrame(X)
corr = X.corr()
sns.heatmap(corr, cmap='RdYlGn_r', square=True)
plt.title('Features correlation')
plt.savefig(path, dpi=150)
plt.clf()
plt.cla()
plt.close()
except Exception as e:
logger.info("Can not create correlation plot for this experiment: " + str(e))
def distributions(logger, X, path):
logger.info("Creating distributions plot")
try:
X = pd.DataFrame(X)
X.hist(sharex=True)
plt.title('Attribute distributions', fontsize=10)
plt.savefig(path, dpi=150)
plt.clf()
plt.cla()
plt.close()
except Exception as e:
logger.info("Can not create distributions plot for this experiment: " + str(e))
def plot_history(logger, path):
<|code_end|>
. Use current file imports:
(import os
import pylab
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib as mlp
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from mpl_toolkits.mplot3d import Axes3D # keep it
from sklearn.metrics import roc_auc_score, roc_curve, r2_score, mean_absolute_error
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from joblib import Parallel, delayed
from joblib.parallel import BACKENDS
from moloi.descriptors.rdkit_descriptor import rdkit_fetures_names
from moloi.descriptors.mordred_descriptor import mordred_fetures_names
from moloi.data_processing import m_mean)
and context including class names, function names, or small code snippets from other files:
# Path: moloi/descriptors/rdkit_descriptor.py
# def rdkit_fetures_names():
# DESCRIPTORS = {_camel_to_snail(s): f for (s, f) in Descriptors.descList}
# return DESCRIPTORS.keys()
#
# Path: moloi/descriptors/mordred_descriptor.py
# def mordred_fetures_names():
# calc = Calculator(descriptors)
# cols = []
# for i in calc.descriptors:
# i = str(i)
# i = i.split(".")[-1]
# cols.append(str(i))
# return cols
#
# Path: moloi/data_processing.py
# def m_mean(a, column):
# """
# for feature importance
# """
# mean = np.mean(a.T[column])
# for i in range(len(a)):
# a[i][column] = mean
# return a
. Output only the next line. | logger.info("Creating history plot") |
Using the snippet: <|code_start|> 'font.size': 8,
'legend.fontsize': 10,
'xtick.labelsize': 10,
'ytick.labelsize': 10,
'figure.figsize': [8, 4]
}
pylab.rcParams.update(params)
def correlation(logger, X, path):
logger.info("Creating correlation plot")
try:
X = pd.DataFrame(X)
corr = X.corr()
sns.heatmap(corr, cmap='RdYlGn_r', square=True)
plt.title('Features correlation')
plt.savefig(path, dpi=150)
plt.clf()
plt.cla()
plt.close()
except Exception as e:
logger.info("Can not create correlation plot for this experiment: " + str(e))
def distributions(logger, X, path):
logger.info("Creating distributions plot")
try:
X = pd.DataFrame(X)
X.hist(sharex=True)
plt.title('Attribute distributions', fontsize=10)
plt.savefig(path, dpi=150)
<|code_end|>
, determine the next line of code. You have imports:
import os
import pylab
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib as mlp
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from mpl_toolkits.mplot3d import Axes3D # keep it
from sklearn.metrics import roc_auc_score, roc_curve, r2_score, mean_absolute_error
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from joblib import Parallel, delayed
from joblib.parallel import BACKENDS
from moloi.descriptors.rdkit_descriptor import rdkit_fetures_names
from moloi.descriptors.mordred_descriptor import mordred_fetures_names
from moloi.data_processing import m_mean
and context (class names, function names, or code) available:
# Path: moloi/descriptors/rdkit_descriptor.py
# def rdkit_fetures_names():
# DESCRIPTORS = {_camel_to_snail(s): f for (s, f) in Descriptors.descList}
# return DESCRIPTORS.keys()
#
# Path: moloi/descriptors/mordred_descriptor.py
# def mordred_fetures_names():
# calc = Calculator(descriptors)
# cols = []
# for i in calc.descriptors:
# i = str(i)
# i = i.split(".")[-1]
# cols.append(str(i))
# return cols
#
# Path: moloi/data_processing.py
# def m_mean(a, column):
# """
# for feature importance
# """
# mean = np.mean(a.T[column])
# for i in range(len(a)):
# a[i][column] = mean
# return a
. Output only the next line. | plt.clf() |
Continue the code snippet: <|code_start|>from __future__ import division, print_function, absolute_import
class SilenceableStreamHandler(logging.StreamHandler):
def __init__(self, *args, **kwargs):
super(SilenceableStreamHandler, self).__init__(*args, **kwargs)
self.silenced = False
def emit(self, record):
if not self.silenced:
super(SilenceableStreamHandler, self).emit(record)
class SilenceableFileHandler(logging.FileHandler):
def __init__(self, *args, **kwargs):
super(SilenceableFileHandler, self).__init__(*args, **kwargs)
self.silenced = False
def emit(self, record):
if not self.silenced:
super(SilenceableFileHandler, self).emit(record)
<|code_end|>
. Use current file imports:
import os
import logging
from datetime import datetime
from ..modules.patterns import Singleton
and context (classes, functions, or code) from other files:
# Path: mlpy/modules/patterns.py
# class Singleton(type):
# """
# Metaclass ensuring only one instance of the class exists.
#
# The singleton pattern ensures that a class has only one instance
# and provides a global point of access to that instance.
#
# Methods
# -------
# __call__
#
# Notes
# -----
# To define a class as a singleton include the :data:`__metaclass__`
# directive.
#
# See Also
# --------
# :class:`Borg`
#
# Examples
# --------
# Define a singleton class:
#
# >>> from mlpy.modules.patterns import Singleton
# >>> class MyClass(object):
# >>> __metaclass__ = Singleton
#
# .. note::
# | Project: Code from `StackOverflow <http://stackoverflow.com/q/6760685>`_.
# | Code author: `theheadofabroom <http://stackoverflow.com/users/655372/theheadofabroom>`_
# | License: `CC-Wiki <http://creativecommons.org/licenses/by-sa/3.0/>`_
#
# """
# _instance = {}
#
# def __call__(cls, *args, **kwargs):
# """Returns instance to object."""
# if cls not in cls._instance:
# # noinspection PyArgumentList
# cls._instance[cls] = super(Singleton, cls).__call__(*args, **kwargs)
# return cls._instance[cls]
. Output only the next line. | class LoggingMgr(object): |
Given the following code snippet before the placeholder: <|code_start|>from __future__ import division, print_function, absolute_import
# noinspection PyUnresolvedReferences
# noinspection PyPackageRequirements
__all__ = ['is_posdef', 'randpd', 'stacked_randpd', 'normalize_logspace', 'sq_distance',
'partitioned_mean', 'partitioned_cov', 'partitioned_sum', 'shrink_cov',
<|code_end|>
, predict the next line using imports from the current file:
from six.moves import range
from sklearn.utils.extmath import logsumexp
from ..auxiliary.array import nunique
import numpy as np
and context including class names, function names, and sometimes code from other files:
# Path: mlpy/auxiliary/array.py
# def nunique(x, axis=None):
# """Efficiently count the unique elements of `x` along the given axis.
#
# Parameters
# ----------
# x : array_like
# The array for which to count the unique elements.
# axis : int
# Dimension along which to count the unique elements.
#
# Returns
# -------
# int or array_like :
# The number of unique elements along the given axis.
#
# Examples
# --------
# >>>
#
# .. note::
# Ported from Matlab:
#
# | Project: `Probabilistic Modeling Toolkit for Matlab/Octave <https://github.com/probml/pmtk3>`_.
# | Copyright (2010) Kevin Murphy and Matt Dunham
# | License: `MIT <https://github.com/probml/pmtk3/blob/5fefd068a2e84ae508684d3e4750bd72a4164ba0/license.txt>`_
#
# """
# axis = 0 if axis is None else axis
# n = np.sum(np.diff(np.sort(x, axis=axis), axis=axis) > 0, axis=axis) + 1
# return n
. Output only the next line. | 'canonize_labels'] |
Given the following code snippet before the placeholder: <|code_start|> picture = Column(GUID, ForeignKey('user_pictures.id'))
karma = Column(Integer, default=0)
notify_by_mail = Column(Boolean, default=True)
twitter_origination = Column(Boolean, default=False)
twitter_oauth_key = Column(UnicodeText)
twitter_oauth_secret = Column(UnicodeText)
facebook_origination = Column(Boolean, default=False)
facebook_user_id = Column(UnicodeText)
is_admin = Column(Boolean, default=False)
lost_password_token = Column(GUID)
password_token_claim_date = Column(DateTime(timezone=True))
added_on = Column(DateTime(timezone=True), default=sqlalchemy.sql.func.now())
added_by = Column(GUID)
followed = relationship("User", secondary=follows, primaryjoin=id==follows.c.followed, secondaryjoin=id==follows.c.follower, backref="follows")
saved = relationship("Submission", secondary=users_saves)
picture_ref = relationship("UserPicture")
def update_karma(self):
#@TODO: find out if we want to allow negative general karma scores
tally = 0
try:
for s in self.submissions:
tally += s.points
except:
pass
try:
for c in self.comments:
tally += c.points
except:
<|code_end|>
, predict the next line using imports from the current file:
from raggregate.models import *
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import Unicode
from sqlalchemy import UnicodeText
from sqlalchemy import DateTime
from sqlalchemy import text
from sqlalchemy import Boolean
from sqlalchemy import ForeignKey
from sqlalchemy.schema import Table
from sqlalchemy.orm import relationship
from raggregate.guid_recipe import GUID
from raggregate.queries import notify
import sqlalchemy
and context including class names, function names, and sometimes code from other files:
# Path: raggregate/guid_recipe.py
# class GUID(TypeDecorator):
# """Platform-independent GUID type.
#
# Uses Postgresql's UUID type, otherwise uses
# CHAR(32), storing as stringified hex values.
#
# """
# impl = CHAR
#
# def load_dialect_impl(self, dialect):
# if dialect.name == 'postgresql':
# return dialect.type_descriptor(UUID())
# else:
# return dialect.type_descriptor(CHAR(32))
#
# def process_bind_param(self, value, dialect):
# if value is None:
# return value
# elif dialect.name == 'postgresql':
# return str(value)
# else:
# if not isinstance(value, uuid.UUID):
# return "{0}".format(uuid.UUID(value))
# else:
# # hexstring
# return "{0}".format(value)
#
# def process_result_value(self, value, dialect):
# if value is None:
# return value
# else:
# return uuid.UUID(value)
. Output only the next line. | pass |
Given snippet: <|code_start|>
class Submission(Base):
__tablename__ = 'submissions'
id = Column(GUID, primary_key=True)
title = Column(UnicodeText, nullable=False)
description = Column(UnicodeText)
points = Column(Integer)
comment_tally = Column(Integer)
category = Column(GUID)
url = Column(UnicodeText)
self_post = Column(Boolean)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from raggregate.models import *
from raggregate.models.vote import Vote
from raggregate.models.comment import Comment
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import Unicode
from sqlalchemy import UnicodeText
from sqlalchemy import DateTime
from sqlalchemy import text
from sqlalchemy import Boolean
from sqlalchemy import ForeignKey
from raggregate.guid_recipe import GUID
import sqlalchemy
import urlparse
and context:
# Path: raggregate/models/vote.py
# class Vote(Base):
# __tablename__ = 'votes'
# id = Column(GUID, primary_key=True)
# # we do not coalesce these into a generic item column
# # because things are easier/safer with the FK support.
# # the tradeoff here is size on various db structures.
# submission_id = Column(GUID, ForeignKey('submissions.id'))
# comment_id = Column(GUID, ForeignKey('comments.id'))
# motd_id = Column(GUID, ForeignKey('motds.id'))
# user_id = Column(GUID, ForeignKey('users.id'), nullable=False)
# # points: -1 for down, 0 for neutral, 1 for up
# # this also allows easier manipulation of vote tallying if needed
# # considered using a boolean and deleting the row if a user unvotes
# # i guess but have no evidence that's slower than putting this back
# # to zero, and as above, makes it more difficult to "modify" the
# # voting system if needed.
# points = Column(Integer, nullable=False, default=0)
# # 0 for none, 1 for up, -1 for down
# direction = Column(Integer, nullable=False, default=0)
# added_on = Column(DateTime(timezone=True), default=sqlalchemy.sql.func.now())
#
# voter = relationship("User", backref="votes")
#
# def __init__(self, item_id, user_id, points, target_type, comment_id = None):
# if target_type == 'comment':
# self.comment_id = comment_id
# self.submission_id = item_id
# elif target_type == 'submission':
# self.submission_id = item_id
# elif target_type == 'motd':
# self.motd_id = item_id
# else:
# raise Exception("Need to know target type for this vote.")
# self.user_id = user_id
# self.points = points
#
# Path: raggregate/models/comment.py
# class Comment(Base):
# __tablename__ = 'comments'
#
# id = Column(GUID, primary_key=True)
# submission_id = Column(GUID, ForeignKey('submissions.id'), nullable=False)
# user_id = Column(GUID, ForeignKey('users.id'), nullable=False)
# parent_id = Column(GUID, nullable=False)
# in_reply_to = Column(GUID, ForeignKey('users.id'), nullable=True)
# body = Column(UnicodeText, nullable=False)
# points = Column(Integer, default=0)
# # unread field for epistle/mailbox display.
# unread = Column(Boolean, default=True)
# deleted = Column(Boolean, default=False)
# added_on = Column(DateTime(timezone=True), default=sqlalchemy.sql.func.now())
#
# submitter = relationship("User", backref="comments", primaryjoin="User.id == Comment.user_id")
# recipient_u = relationship("User", primaryjoin="User.id == Comment.in_reply_to")
# votes = relationship("Vote", cascade="all, delete, delete-orphan")
# submission = relationship("Submission", backref="comments")
#
# def __init__(self, submission_id, user_id, parent_id, body, in_reply_to = None):
# self.submission_id = submission_id
# self.user_id = user_id
# self.parent_id = parent_id
# if body is None:
# raise Exception("Please include a message.")
# else:
# self.body = body
# self.in_reply_to = in_reply_to
#
# def tally_votes(self):
# votes = DBSession.query(Vote).filter(Vote.comment_id == self.id).all()
# tally = 0
# for v in votes:
# tally += v.points
# if self.points != tally:
# self.points = tally
# return votes
#
# def load_parent(self):
# # raggregate.queries depends on the models defined in this file
# # so it shouldn't be imported until it's ready to be used in a function
# # as it's being imported here. Otherwise, we die with dependency problems.
# # it is probably not advisable to do things this way, but it is much nicer
# from raggregate.queries import general
# if self.parent_id == None:
# print("No parent id on comment {0}, this is a problem...".format(self.id))
# return None
# p = general.find_by_id(self.parent_id)
# return p
#
# def load_submission(self):
# from raggregate.queries import submission
# return submission.get_story_by_id(self.submission_id)
#
# Path: raggregate/guid_recipe.py
# class GUID(TypeDecorator):
# """Platform-independent GUID type.
#
# Uses Postgresql's UUID type, otherwise uses
# CHAR(32), storing as stringified hex values.
#
# """
# impl = CHAR
#
# def load_dialect_impl(self, dialect):
# if dialect.name == 'postgresql':
# return dialect.type_descriptor(UUID())
# else:
# return dialect.type_descriptor(CHAR(32))
#
# def process_bind_param(self, value, dialect):
# if value is None:
# return value
# elif dialect.name == 'postgresql':
# return str(value)
# else:
# if not isinstance(value, uuid.UUID):
# return "{0}".format(uuid.UUID(value))
# else:
# # hexstring
# return "{0}".format(value)
#
# def process_result_value(self, value, dialect):
# if value is None:
# return value
# else:
# return uuid.UUID(value)
which might include code, classes, or functions. Output only the next line. | slug = Column(UnicodeText, unique=True) |
Based on the snippet: <|code_start|>
class Submission(Base):
__tablename__ = 'submissions'
id = Column(GUID, primary_key=True)
title = Column(UnicodeText, nullable=False)
description = Column(UnicodeText)
points = Column(Integer)
comment_tally = Column(Integer)
category = Column(GUID)
<|code_end|>
, predict the immediate next line with the help of imports:
from raggregate.models import *
from raggregate.models.vote import Vote
from raggregate.models.comment import Comment
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import Unicode
from sqlalchemy import UnicodeText
from sqlalchemy import DateTime
from sqlalchemy import text
from sqlalchemy import Boolean
from sqlalchemy import ForeignKey
from raggregate.guid_recipe import GUID
import sqlalchemy
import urlparse
and context (classes, functions, sometimes code) from other files:
# Path: raggregate/models/vote.py
# class Vote(Base):
# __tablename__ = 'votes'
# id = Column(GUID, primary_key=True)
# # we do not coalesce these into a generic item column
# # because things are easier/safer with the FK support.
# # the tradeoff here is size on various db structures.
# submission_id = Column(GUID, ForeignKey('submissions.id'))
# comment_id = Column(GUID, ForeignKey('comments.id'))
# motd_id = Column(GUID, ForeignKey('motds.id'))
# user_id = Column(GUID, ForeignKey('users.id'), nullable=False)
# # points: -1 for down, 0 for neutral, 1 for up
# # this also allows easier manipulation of vote tallying if needed
# # considered using a boolean and deleting the row if a user unvotes
# # i guess but have no evidence that's slower than putting this back
# # to zero, and as above, makes it more difficult to "modify" the
# # voting system if needed.
# points = Column(Integer, nullable=False, default=0)
# # 0 for none, 1 for up, -1 for down
# direction = Column(Integer, nullable=False, default=0)
# added_on = Column(DateTime(timezone=True), default=sqlalchemy.sql.func.now())
#
# voter = relationship("User", backref="votes")
#
# def __init__(self, item_id, user_id, points, target_type, comment_id = None):
# if target_type == 'comment':
# self.comment_id = comment_id
# self.submission_id = item_id
# elif target_type == 'submission':
# self.submission_id = item_id
# elif target_type == 'motd':
# self.motd_id = item_id
# else:
# raise Exception("Need to know target type for this vote.")
# self.user_id = user_id
# self.points = points
#
# Path: raggregate/models/comment.py
# class Comment(Base):
# __tablename__ = 'comments'
#
# id = Column(GUID, primary_key=True)
# submission_id = Column(GUID, ForeignKey('submissions.id'), nullable=False)
# user_id = Column(GUID, ForeignKey('users.id'), nullable=False)
# parent_id = Column(GUID, nullable=False)
# in_reply_to = Column(GUID, ForeignKey('users.id'), nullable=True)
# body = Column(UnicodeText, nullable=False)
# points = Column(Integer, default=0)
# # unread field for epistle/mailbox display.
# unread = Column(Boolean, default=True)
# deleted = Column(Boolean, default=False)
# added_on = Column(DateTime(timezone=True), default=sqlalchemy.sql.func.now())
#
# submitter = relationship("User", backref="comments", primaryjoin="User.id == Comment.user_id")
# recipient_u = relationship("User", primaryjoin="User.id == Comment.in_reply_to")
# votes = relationship("Vote", cascade="all, delete, delete-orphan")
# submission = relationship("Submission", backref="comments")
#
# def __init__(self, submission_id, user_id, parent_id, body, in_reply_to = None):
# self.submission_id = submission_id
# self.user_id = user_id
# self.parent_id = parent_id
# if body is None:
# raise Exception("Please include a message.")
# else:
# self.body = body
# self.in_reply_to = in_reply_to
#
# def tally_votes(self):
# votes = DBSession.query(Vote).filter(Vote.comment_id == self.id).all()
# tally = 0
# for v in votes:
# tally += v.points
# if self.points != tally:
# self.points = tally
# return votes
#
# def load_parent(self):
# # raggregate.queries depends on the models defined in this file
# # so it shouldn't be imported until it's ready to be used in a function
# # as it's being imported here. Otherwise, we die with dependency problems.
# # it is probably not advisable to do things this way, but it is much nicer
# from raggregate.queries import general
# if self.parent_id == None:
# print("No parent id on comment {0}, this is a problem...".format(self.id))
# return None
# p = general.find_by_id(self.parent_id)
# return p
#
# def load_submission(self):
# from raggregate.queries import submission
# return submission.get_story_by_id(self.submission_id)
#
# Path: raggregate/guid_recipe.py
# class GUID(TypeDecorator):
# """Platform-independent GUID type.
#
# Uses Postgresql's UUID type, otherwise uses
# CHAR(32), storing as stringified hex values.
#
# """
# impl = CHAR
#
# def load_dialect_impl(self, dialect):
# if dialect.name == 'postgresql':
# return dialect.type_descriptor(UUID())
# else:
# return dialect.type_descriptor(CHAR(32))
#
# def process_bind_param(self, value, dialect):
# if value is None:
# return value
# elif dialect.name == 'postgresql':
# return str(value)
# else:
# if not isinstance(value, uuid.UUID):
# return "{0}".format(uuid.UUID(value))
# else:
# # hexstring
# return "{0}".format(value)
#
# def process_result_value(self, value, dialect):
# if value is None:
# return value
# else:
# return uuid.UUID(value)
. Output only the next line. | url = Column(UnicodeText) |
Here is a snippet: <|code_start|>
class AuthPolicy(object):
def authenticated_userid(self, request):
if not request.session['users.id']:
return None
return users.get_user_by_id(request.session['users.id'])
def unauthenticated_userid(self, request):
if not request.session['users.id']:
return None
return request.session['users.id']
<|code_end|>
. Write the next line using the current file imports:
from raggregate.queries import users
from pyramid.security import Everyone
from pyramid.security import Authenticated
and context from other files:
# Path: raggregate/queries/users.py
# def get_user_by_id(id):
# def get_user_by_name(name):
# def get_user_by_email(email):
# def get_user_by_token(token):
# def is_user_allowed_admin_action(user_id, target_id, request = None, target_class = 'user_post',):
# def get_followed_users(id):
# def get_user_votes(user_id, vote_type, submission_id=None):
# def create_temp_user(initial_pw = None):
# def fuzzify_date(d):
# def create_user(**kwargs):
# def login_user(request, u, password, bypass_password = False):
# def add_user_picture(orig_filename, new_prefix, up_dir, image_file):
# def send_email_to_user(request, to_email, title, body):
# def send_lost_password_verify_email(request, user):
# def generate_new_password(request, user):
, which may include functions, classes, or code. Output only the next line. | def effective_principals(self, request): |
Next line prediction: <|code_start|>
class Section(Base):
__tablename__ = 'sections'
id = Column(GUID, primary_key=True)
name = Column(UnicodeText)
description = Column(UnicodeText)
subscribe_by_default = Column(Boolean, default=False)
parent = Column(GUID, ForeignKey('sections.id'), nullable=True)
added_by = Column(GUID, ForeignKey('users.id'), nullable=False)
enabled = Column(Boolean, default=True)
added_on = Column(DateTime(timezone=True), default=sqlalchemy.sql.func.now())
modified_on = Column(DateTime(timezone=True), default=sqlalchemy.sql.func.now())
picture = Column(GUID, ForeignKey('section_pictures.id'))
stories = relationship("Submission", backref="sections")
picture_ref = relationship("SectionPicture")
def __init__(self, name = None, description = None, parent = None, added_by = None, modified_on = None, subscribe_by_default = False, enabled = True):
self.name = name
self.description = description
self.parent = parent
self.added_by = added_by
self.modified_on = modified_on
<|code_end|>
. Use current file imports:
(from raggregate.models import *
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import Unicode
from sqlalchemy import UnicodeText
from sqlalchemy import DateTime
from sqlalchemy import text
from sqlalchemy import Boolean
from sqlalchemy import ForeignKey
from raggregate.guid_recipe import GUID
import sqlalchemy)
and context including class names, function names, or small code snippets from other files:
# Path: raggregate/guid_recipe.py
# class GUID(TypeDecorator):
# """Platform-independent GUID type.
#
# Uses Postgresql's UUID type, otherwise uses
# CHAR(32), storing as stringified hex values.
#
# """
# impl = CHAR
#
# def load_dialect_impl(self, dialect):
# if dialect.name == 'postgresql':
# return dialect.type_descriptor(UUID())
# else:
# return dialect.type_descriptor(CHAR(32))
#
# def process_bind_param(self, value, dialect):
# if value is None:
# return value
# elif dialect.name == 'postgresql':
# return str(value)
# else:
# if not isinstance(value, uuid.UUID):
# return "{0}".format(uuid.UUID(value))
# else:
# # hexstring
# return "{0}".format(value)
#
# def process_result_value(self, value, dialect):
# if value is None:
# return value
# else:
# return uuid.UUID(value)
. Output only the next line. | self.subscribe_by_default = subscribe_by_default |
Predict the next line after this snippet: <|code_start|>
dbsession = sqlahelper.get_session()
def get_sublists():
return dbsession.query(Sublist).all()
def get_sublist_by_title(title):
return dbsession.query(Sublist).filter(Sublist.title == title).all()
def get_sublist_members(sublist_id):
members = dbsession.query(SublistMember).filter(SublistMember.sublist_id == sublist_id).all()
member_list = []
for m in members:
member_list.append(submission_queries.get_story_by_id(m.member_id))
return member_list
def find_member_in_sublist(member_id, sublist_id):
q = dbsession.query(SublistMember).filter(SublistMember.sublist_id == sublist_id)
q = q.filter(SublistMember.member_id == member_id)
return q.all()[0]
def remove_sublist_member(member_id, sublist_id):
s = find_member_in_sublist(member_id, sublist_id)
dbsession.delete(s)
dbsession.flush()
<|code_end|>
using the current file's imports:
import sqlalchemy
import sqlahelper
from raggregate.queries import users
from raggregate.queries import submission as submission_queries
from raggregate.models.sublist import Sublist
from raggregate.models.sublist_member import SublistMember
and any relevant context from other files:
# Path: raggregate/queries/users.py
# def get_user_by_id(id):
# def get_user_by_name(name):
# def get_user_by_email(email):
# def get_user_by_token(token):
# def is_user_allowed_admin_action(user_id, target_id, request = None, target_class = 'user_post',):
# def get_followed_users(id):
# def get_user_votes(user_id, vote_type, submission_id=None):
# def create_temp_user(initial_pw = None):
# def fuzzify_date(d):
# def create_user(**kwargs):
# def login_user(request, u, password, bypass_password = False):
# def add_user_picture(orig_filename, new_prefix, up_dir, image_file):
# def send_email_to_user(request, to_email, title, body):
# def send_lost_password_verify_email(request, user):
# def generate_new_password(request, user):
#
# Path: raggregate/queries/submission.py
# def get_story_list(page_num = 1, per_page = 30, sort = 'new', request = None, self_only = False, section = None):
# def get_story_by_id(id):
# def get_story_by_url_oldest(url):
# def update_story_vote_tally(story_id):
# def get_endpoints_from_page_num(page_num, per_page):
# def get_comments(id, organize_parentage = False, page_num = 1, per_page = 30, sort = 'new', target = 'story', target_id = None):
# def _build_comment_trees(all_comments, allowed_roots):
# def count_comment_children(comment_id):
# def get_comment_parent_story(id):
# def get_comment_by_id(id):
# def get_recent_comments(num):
# def get_story_id_from_slug(slug):
#
# Path: raggregate/models/sublist.py
# class Sublist(Base):
# __tablename__ = 'sublists'
# id = Column(GUID, primary_key=True)
# title = Column(UnicodeText)
# description = Column(UnicodeText)
# visibility = Column(UnicodeText)
# added_by = Column(GUID, ForeignKey('users.id'))
# added_on = Column(DateTime)
#
# def __init__(self, title = None, description = None, visibility = None,
# added_by = None, added_on = None):
# self.title = title
# self.description = description
# self.visibility = visibility
# self.added_by = added_by
# self.added_on = added_on
#
# Path: raggregate/models/sublist_member.py
# class SublistMember(Base):
# __tablename__ = 'sublists_members'
# id = Column(GUID, primary_key=True)
# sublist_id = Column(GUID, ForeignKey('sublists.id'))
# member_id = Column(GUID, ForeignKey('submissions.id'))
# added_by = Column(GUID, ForeignKey('users.id'))
# added_on = Column(DateTime)
#
# def __init__(self, sublist_id = None, member_id = None, added_by = None,
# added_on = None):
# self.sublist_id = sublist_id
# self.member_id = member_id
# self.added_by = added_by
# self.added_on = added_on
. Output only the next line. | return True |
Here is a snippet: <|code_start|>
dbsession = sqlahelper.get_session()
def get_sublists():
return dbsession.query(Sublist).all()
def get_sublist_by_title(title):
return dbsession.query(Sublist).filter(Sublist.title == title).all()
<|code_end|>
. Write the next line using the current file imports:
import sqlalchemy
import sqlahelper
from raggregate.queries import users
from raggregate.queries import submission as submission_queries
from raggregate.models.sublist import Sublist
from raggregate.models.sublist_member import SublistMember
and context from other files:
# Path: raggregate/queries/users.py
# def get_user_by_id(id):
# def get_user_by_name(name):
# def get_user_by_email(email):
# def get_user_by_token(token):
# def is_user_allowed_admin_action(user_id, target_id, request = None, target_class = 'user_post',):
# def get_followed_users(id):
# def get_user_votes(user_id, vote_type, submission_id=None):
# def create_temp_user(initial_pw = None):
# def fuzzify_date(d):
# def create_user(**kwargs):
# def login_user(request, u, password, bypass_password = False):
# def add_user_picture(orig_filename, new_prefix, up_dir, image_file):
# def send_email_to_user(request, to_email, title, body):
# def send_lost_password_verify_email(request, user):
# def generate_new_password(request, user):
#
# Path: raggregate/queries/submission.py
# def get_story_list(page_num = 1, per_page = 30, sort = 'new', request = None, self_only = False, section = None):
# def get_story_by_id(id):
# def get_story_by_url_oldest(url):
# def update_story_vote_tally(story_id):
# def get_endpoints_from_page_num(page_num, per_page):
# def get_comments(id, organize_parentage = False, page_num = 1, per_page = 30, sort = 'new', target = 'story', target_id = None):
# def _build_comment_trees(all_comments, allowed_roots):
# def count_comment_children(comment_id):
# def get_comment_parent_story(id):
# def get_comment_by_id(id):
# def get_recent_comments(num):
# def get_story_id_from_slug(slug):
#
# Path: raggregate/models/sublist.py
# class Sublist(Base):
# __tablename__ = 'sublists'
# id = Column(GUID, primary_key=True)
# title = Column(UnicodeText)
# description = Column(UnicodeText)
# visibility = Column(UnicodeText)
# added_by = Column(GUID, ForeignKey('users.id'))
# added_on = Column(DateTime)
#
# def __init__(self, title = None, description = None, visibility = None,
# added_by = None, added_on = None):
# self.title = title
# self.description = description
# self.visibility = visibility
# self.added_by = added_by
# self.added_on = added_on
#
# Path: raggregate/models/sublist_member.py
# class SublistMember(Base):
# __tablename__ = 'sublists_members'
# id = Column(GUID, primary_key=True)
# sublist_id = Column(GUID, ForeignKey('sublists.id'))
# member_id = Column(GUID, ForeignKey('submissions.id'))
# added_by = Column(GUID, ForeignKey('users.id'))
# added_on = Column(DateTime)
#
# def __init__(self, sublist_id = None, member_id = None, added_by = None,
# added_on = None):
# self.sublist_id = sublist_id
# self.member_id = member_id
# self.added_by = added_by
# self.added_on = added_on
, which may include functions, classes, or code. Output only the next line. | def get_sublist_members(sublist_id): |
Next line prediction: <|code_start|>
dbsession = sqlahelper.get_session()
def get_sublists():
return dbsession.query(Sublist).all()
def get_sublist_by_title(title):
return dbsession.query(Sublist).filter(Sublist.title == title).all()
def get_sublist_members(sublist_id):
members = dbsession.query(SublistMember).filter(SublistMember.sublist_id == sublist_id).all()
member_list = []
for m in members:
member_list.append(submission_queries.get_story_by_id(m.member_id))
return member_list
def find_member_in_sublist(member_id, sublist_id):
q = dbsession.query(SublistMember).filter(SublistMember.sublist_id == sublist_id)
q = q.filter(SublistMember.member_id == member_id)
return q.all()[0]
def remove_sublist_member(member_id, sublist_id):
s = find_member_in_sublist(member_id, sublist_id)
dbsession.delete(s)
dbsession.flush()
<|code_end|>
. Use current file imports:
(import sqlalchemy
import sqlahelper
from raggregate.queries import users
from raggregate.queries import submission as submission_queries
from raggregate.models.sublist import Sublist
from raggregate.models.sublist_member import SublistMember)
and context including class names, function names, or small code snippets from other files:
# Path: raggregate/queries/users.py
# def get_user_by_id(id):
# def get_user_by_name(name):
# def get_user_by_email(email):
# def get_user_by_token(token):
# def is_user_allowed_admin_action(user_id, target_id, request = None, target_class = 'user_post',):
# def get_followed_users(id):
# def get_user_votes(user_id, vote_type, submission_id=None):
# def create_temp_user(initial_pw = None):
# def fuzzify_date(d):
# def create_user(**kwargs):
# def login_user(request, u, password, bypass_password = False):
# def add_user_picture(orig_filename, new_prefix, up_dir, image_file):
# def send_email_to_user(request, to_email, title, body):
# def send_lost_password_verify_email(request, user):
# def generate_new_password(request, user):
#
# Path: raggregate/queries/submission.py
# def get_story_list(page_num = 1, per_page = 30, sort = 'new', request = None, self_only = False, section = None):
# def get_story_by_id(id):
# def get_story_by_url_oldest(url):
# def update_story_vote_tally(story_id):
# def get_endpoints_from_page_num(page_num, per_page):
# def get_comments(id, organize_parentage = False, page_num = 1, per_page = 30, sort = 'new', target = 'story', target_id = None):
# def _build_comment_trees(all_comments, allowed_roots):
# def count_comment_children(comment_id):
# def get_comment_parent_story(id):
# def get_comment_by_id(id):
# def get_recent_comments(num):
# def get_story_id_from_slug(slug):
#
# Path: raggregate/models/sublist.py
# class Sublist(Base):
# __tablename__ = 'sublists'
# id = Column(GUID, primary_key=True)
# title = Column(UnicodeText)
# description = Column(UnicodeText)
# visibility = Column(UnicodeText)
# added_by = Column(GUID, ForeignKey('users.id'))
# added_on = Column(DateTime)
#
# def __init__(self, title = None, description = None, visibility = None,
# added_by = None, added_on = None):
# self.title = title
# self.description = description
# self.visibility = visibility
# self.added_by = added_by
# self.added_on = added_on
#
# Path: raggregate/models/sublist_member.py
# class SublistMember(Base):
# __tablename__ = 'sublists_members'
# id = Column(GUID, primary_key=True)
# sublist_id = Column(GUID, ForeignKey('sublists.id'))
# member_id = Column(GUID, ForeignKey('submissions.id'))
# added_by = Column(GUID, ForeignKey('users.id'))
# added_on = Column(DateTime)
#
# def __init__(self, sublist_id = None, member_id = None, added_by = None,
# added_on = None):
# self.sublist_id = sublist_id
# self.member_id = member_id
# self.added_by = added_by
# self.added_on = added_on
. Output only the next line. | return True |
Using the snippet: <|code_start|>
class Sublist(Base):
__tablename__ = 'sublists'
id = Column(GUID, primary_key=True)
title = Column(UnicodeText)
<|code_end|>
, determine the next line of code. You have imports:
from raggregate.models import *
from sqlalchemy import Column
from sqlalchemy import UnicodeText
from raggregate.guid_recipe import GUID
from sqlalchemy import ForeignKey
from sqlalchemy import DateTime
import sqlalchemy
and context (class names, function names, or code) available:
# Path: raggregate/guid_recipe.py
# class GUID(TypeDecorator):
# """Platform-independent GUID type.
#
# Uses Postgresql's UUID type, otherwise uses
# CHAR(32), storing as stringified hex values.
#
# """
# impl = CHAR
#
# def load_dialect_impl(self, dialect):
# if dialect.name == 'postgresql':
# return dialect.type_descriptor(UUID())
# else:
# return dialect.type_descriptor(CHAR(32))
#
# def process_bind_param(self, value, dialect):
# if value is None:
# return value
# elif dialect.name == 'postgresql':
# return str(value)
# else:
# if not isinstance(value, uuid.UUID):
# return "{0}".format(uuid.UUID(value))
# else:
# # hexstring
# return "{0}".format(value)
#
# def process_result_value(self, value, dialect):
# if value is None:
# return value
# else:
# return uuid.UUID(value)
. Output only the next line. | description = Column(UnicodeText) |
Predict the next line for this snippet: <|code_start|>
class Notify(Base):
__tablename__ = 'notifications'
id = Column(GUID, primary_key=True)
user_id = Column(GUID, ForeignKey('users.id'))
target_id = Column(GUID)
target_type = Column(UnicodeText)
added_on = Column(DateTime)
added_by = Column(GUID, ForeignKey('users.id'))
def __init__(self, user_id = None, target_id = None, target_type = None,
added_on = None, added_by = None):
self.user_id = user_id
self.target_id = target_id
self.target_type = target_type
self.added_by = added_by
if added_on:
self.added_on = added_on
<|code_end|>
with the help of current file imports:
from raggregate.models import *
from sqlalchemy import Column
from sqlalchemy import UnicodeText
from sqlalchemy import DateTime
from sqlalchemy import ForeignKey
from raggregate.guid_recipe import GUID
import sqlalchemy
import datetime
and context from other files:
# Path: raggregate/guid_recipe.py
# class GUID(TypeDecorator):
# """Platform-independent GUID type.
#
# Uses Postgresql's UUID type, otherwise uses
# CHAR(32), storing as stringified hex values.
#
# """
# impl = CHAR
#
# def load_dialect_impl(self, dialect):
# if dialect.name == 'postgresql':
# return dialect.type_descriptor(UUID())
# else:
# return dialect.type_descriptor(CHAR(32))
#
# def process_bind_param(self, value, dialect):
# if value is None:
# return value
# elif dialect.name == 'postgresql':
# return str(value)
# else:
# if not isinstance(value, uuid.UUID):
# return "{0}".format(uuid.UUID(value))
# else:
# # hexstring
# return "{0}".format(value)
#
# def process_result_value(self, value, dialect):
# if value is None:
# return value
# else:
# return uuid.UUID(value)
, which may contain function names, class names, or code. Output only the next line. | else: |
Next line prediction: <|code_start|>
class UserPreference(Base):
__tablename__ = 'user_preferences'
id = Column(GUID, primary_key=True)
user_id = Column(GUID, ForeignKey('users.id'))
preference_list = Column(UnicodeText)
user = relationship('User', backref='preferences')
<|code_end|>
. Use current file imports:
(from raggregate.models import *
from sqlalchemy import Column
from sqlalchemy import UnicodeText
from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship
from raggregate.models.user import User
from raggregate.guid_recipe import GUID)
and context including class names, function names, or small code snippets from other files:
# Path: raggregate/models/user.py
# class User(Base):
# __tablename__ = 'users'
# id = Column(GUID, primary_key=True)
# name = Column(Unicode(255), unique=True)
# password = Column(UnicodeText)
# email = Column(UnicodeText)
# real_name = Column(UnicodeText)
# temporary = Column(Boolean, default=False)
# about_me = Column(UnicodeText)
# picture = Column(GUID, ForeignKey('user_pictures.id'))
# karma = Column(Integer, default=0)
# notify_by_mail = Column(Boolean, default=True)
# twitter_origination = Column(Boolean, default=False)
# twitter_oauth_key = Column(UnicodeText)
# twitter_oauth_secret = Column(UnicodeText)
# facebook_origination = Column(Boolean, default=False)
# facebook_user_id = Column(UnicodeText)
# is_admin = Column(Boolean, default=False)
# lost_password_token = Column(GUID)
# password_token_claim_date = Column(DateTime(timezone=True))
# added_on = Column(DateTime(timezone=True), default=sqlalchemy.sql.func.now())
# added_by = Column(GUID)
#
# followed = relationship("User", secondary=follows, primaryjoin=id==follows.c.followed, secondaryjoin=id==follows.c.follower, backref="follows")
# saved = relationship("Submission", secondary=users_saves)
# picture_ref = relationship("UserPicture")
#
# def update_karma(self):
# #@TODO: find out if we want to allow negative general karma scores
# tally = 0
# try:
# for s in self.submissions:
# tally += s.points
# except:
# pass
# try:
# for c in self.comments:
# tally += c.points
# except:
# pass
# if self.karma != tally:
# self.karma = tally
# return tally
#
# def display_name(self):
# if self.real_name:
# return self.real_name
# else:
# return self.name
#
# # need an adaptable default picture getter method
# #def display_picture_filename(self):
# # if self.picture_ref:
# # return self.picture_ref.filename
# # else:
# # from raggregate import queries
# # return queries.get_default_picture_filename()
#
# def hash_pw(self, pw):
# return crypt.encode(pw)
#
# def verify_pw(self, pw):
# return crypt.check(self.password, pw)
#
# def is_user_admin(self):
# # this is simplistic for now, but one day should use a real roles / permissions system
# return self.is_admin
#
# def is_user_notified(self, target_id):
# from raggregate.queries import notify
# return notify.is_user_notified(self.id, target_id)
#
# def __init__(self, name, password, email = None, real_name = None,
# temporary = False, notify_by_mail = True):
# self.name = name
# self.password = self.hash_pw(password)
# self.email = email
# if real_name:
# self.real_name = real_name
# if temporary:
# self.temporary = True
# self.notify_by_mail = notify_by_mail
#
# Path: raggregate/guid_recipe.py
# class GUID(TypeDecorator):
# """Platform-independent GUID type.
#
# Uses Postgresql's UUID type, otherwise uses
# CHAR(32), storing as stringified hex values.
#
# """
# impl = CHAR
#
# def load_dialect_impl(self, dialect):
# if dialect.name == 'postgresql':
# return dialect.type_descriptor(UUID())
# else:
# return dialect.type_descriptor(CHAR(32))
#
# def process_bind_param(self, value, dialect):
# if value is None:
# return value
# elif dialect.name == 'postgresql':
# return str(value)
# else:
# if not isinstance(value, uuid.UUID):
# return "{0}".format(uuid.UUID(value))
# else:
# # hexstring
# return "{0}".format(value)
#
# def process_result_value(self, value, dialect):
# if value is None:
# return value
# else:
# return uuid.UUID(value)
. Output only the next line. | def __init__(self, user_id, preference_list): |
Predict the next line for this snippet: <|code_start|>
def upgrade(migrate_engine):
meta = MetaData(bind=migrate_engine)
comments = Table('comments', meta, autoload=True)
unreadc = Column('unread', Boolean, default=True)
in_reply_toc = Column('in_reply_to', GUID, nullable=True)
unreadc.create(comments)
in_reply_toc.create(comments)
def downgrade(migrate_engine):
# Operations to reverse the above upgrade go here.
<|code_end|>
with the help of current file imports:
from sqlalchemy import *
from migrate import *
from raggregate.guid_recipe import GUID
and context from other files:
# Path: raggregate/guid_recipe.py
# class GUID(TypeDecorator):
# """Platform-independent GUID type.
#
# Uses Postgresql's UUID type, otherwise uses
# CHAR(32), storing as stringified hex values.
#
# """
# impl = CHAR
#
# def load_dialect_impl(self, dialect):
# if dialect.name == 'postgresql':
# return dialect.type_descriptor(UUID())
# else:
# return dialect.type_descriptor(CHAR(32))
#
# def process_bind_param(self, value, dialect):
# if value is None:
# return value
# elif dialect.name == 'postgresql':
# return str(value)
# else:
# if not isinstance(value, uuid.UUID):
# return "{0}".format(uuid.UUID(value))
# else:
# # hexstring
# return "{0}".format(value)
#
# def process_result_value(self, value, dialect):
# if value is None:
# return value
# else:
# return uuid.UUID(value)
, which may contain function names, class names, or code. Output only the next line. | meta = MetaData(bind=migrate_engine) |
Given the code snippet: <|code_start|>
md = markdown.Markdown( safe_mode='escape', )
def render_md(s):
if s:
return md.convert(s)
else:
<|code_end|>
, generate the next line using the imports in this file:
import markdown
import queries
from raggregate.queries import submission
from raggregate.models.submission import Submission
and context (functions, classes, or occasionally code) from other files:
# Path: raggregate/queries/submission.py
# def get_story_list(page_num = 1, per_page = 30, sort = 'new', request = None, self_only = False, section = None):
# def get_story_by_id(id):
# def get_story_by_url_oldest(url):
# def update_story_vote_tally(story_id):
# def get_endpoints_from_page_num(page_num, per_page):
# def get_comments(id, organize_parentage = False, page_num = 1, per_page = 30, sort = 'new', target = 'story', target_id = None):
# def _build_comment_trees(all_comments, allowed_roots):
# def count_comment_children(comment_id):
# def get_comment_parent_story(id):
# def get_comment_by_id(id):
# def get_recent_comments(num):
# def get_story_id_from_slug(slug):
#
# Path: raggregate/models/submission.py
# class Submission(Base):
# __tablename__ = 'submissions'
# id = Column(GUID, primary_key=True)
# title = Column(UnicodeText, nullable=False)
# description = Column(UnicodeText)
# points = Column(Integer)
# comment_tally = Column(Integer)
# category = Column(GUID)
# url = Column(UnicodeText)
# self_post = Column(Boolean)
# slug = Column(UnicodeText, unique=True)
# added_on = Column(DateTime(timezone=True), default=sqlalchemy.sql.func.now())
# added_by = Column(GUID, ForeignKey('users.id'), nullable=False)
# deleted = Column(Boolean, default=False)
# invisible = Column(Boolean, default=False)
# hot_window_score = Column(Integer, default=None)
# hot_window_score_timestamp = Column(DateTime(timezone=True), default=None)
# downvote_tally = Column(Integer, default=None)
# downvote_tally_timestamp = Column(DateTime(timezone=True), default=None)
# upvote_tally = Column(Integer, default=None)
# upvote_tally_timestamp = Column(DateTime(timezone=True), default=None)
# total_vote_tally = Column(Integer)
# total_vote_timestamp = Column(DateTime(timezone=True), default=None)
# section = Column(GUID, ForeignKey('sections.id'), nullable=True)
# render_type = Column(UnicodeText, default='story_md')
#
# submitter = relationship("User", backref="submissions")
# votes = relationship("Vote", cascade="all, delete, delete-orphan")
#
# def __init__(self, title, description, url, user_id, slug = None, section = None,
# render_type = None):
# self.title = title
# self.description = description
# self.url = url
# self.added_by = user_id
# self.slug = slug
# self.section = section
# self.render_type = render_type
#
# if url is None:
# self.self_post = True
# else:
# self.self_post = False
#
# def tally_votes(self):
# votes = DBSession.query(Vote).filter(Vote.submission_id == self.id).filter(Vote.comment_id == None).all()
# tally = 0
# for v in votes:
# tally += v.points
# if self.points != tally:
# self.points = tally
# return votes
#
# def tally_comments(self):
# comments = DBSession.query(Comment).filter(Comment.submission_id == self.id).filter(Comment.body != '[deleted]').count()
# self.comment_tally = comments
# return comments
#
# def get_domain_name(self):
# if self.url:
# dn = urlparse.urlparse(self.url).netloc
#
# # replace preceding www. if it appears
# if 'www.' in dn[0:4]:
# dn = dn.replace('www.', '', 1)
#
# return dn
# else:
# return ''
. Output only the next line. | return "" |
Predict the next line after this snippet: <|code_start|>
class Comment(Base):
__tablename__ = 'comments'
id = Column(GUID, primary_key=True)
submission_id = Column(GUID, ForeignKey('submissions.id'), nullable=False)
user_id = Column(GUID, ForeignKey('users.id'), nullable=False)
parent_id = Column(GUID, nullable=False)
in_reply_to = Column(GUID, ForeignKey('users.id'), nullable=True)
body = Column(UnicodeText, nullable=False)
points = Column(Integer, default=0)
# unread field for epistle/mailbox display.
unread = Column(Boolean, default=True)
deleted = Column(Boolean, default=False)
<|code_end|>
using the current file's imports:
from raggregate.models import *
from raggregate.models.vote import Vote
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import Unicode
from sqlalchemy import UnicodeText
from sqlalchemy import DateTime
from sqlalchemy import text
from sqlalchemy import Boolean
from sqlalchemy import ForeignKey
from raggregate.guid_recipe import GUID
from raggregate.queries import general
from raggregate.queries import submission
import sqlalchemy
and any relevant context from other files:
# Path: raggregate/models/vote.py
# class Vote(Base):
# __tablename__ = 'votes'
# id = Column(GUID, primary_key=True)
# # we do not coalesce these into a generic item column
# # because things are easier/safer with the FK support.
# # the tradeoff here is size on various db structures.
# submission_id = Column(GUID, ForeignKey('submissions.id'))
# comment_id = Column(GUID, ForeignKey('comments.id'))
# motd_id = Column(GUID, ForeignKey('motds.id'))
# user_id = Column(GUID, ForeignKey('users.id'), nullable=False)
# # points: -1 for down, 0 for neutral, 1 for up
# # this also allows easier manipulation of vote tallying if needed
# # considered using a boolean and deleting the row if a user unvotes
# # i guess but have no evidence that's slower than putting this back
# # to zero, and as above, makes it more difficult to "modify" the
# # voting system if needed.
# points = Column(Integer, nullable=False, default=0)
# # 0 for none, 1 for up, -1 for down
# direction = Column(Integer, nullable=False, default=0)
# added_on = Column(DateTime(timezone=True), default=sqlalchemy.sql.func.now())
#
# voter = relationship("User", backref="votes")
#
# def __init__(self, item_id, user_id, points, target_type, comment_id = None):
# if target_type == 'comment':
# self.comment_id = comment_id
# self.submission_id = item_id
# elif target_type == 'submission':
# self.submission_id = item_id
# elif target_type == 'motd':
# self.motd_id = item_id
# else:
# raise Exception("Need to know target type for this vote.")
# self.user_id = user_id
# self.points = points
#
# Path: raggregate/guid_recipe.py
# class GUID(TypeDecorator):
# """Platform-independent GUID type.
#
# Uses Postgresql's UUID type, otherwise uses
# CHAR(32), storing as stringified hex values.
#
# """
# impl = CHAR
#
# def load_dialect_impl(self, dialect):
# if dialect.name == 'postgresql':
# return dialect.type_descriptor(UUID())
# else:
# return dialect.type_descriptor(CHAR(32))
#
# def process_bind_param(self, value, dialect):
# if value is None:
# return value
# elif dialect.name == 'postgresql':
# return str(value)
# else:
# if not isinstance(value, uuid.UUID):
# return "{0}".format(uuid.UUID(value))
# else:
# # hexstring
# return "{0}".format(value)
#
# def process_result_value(self, value, dialect):
# if value is None:
# return value
# else:
# return uuid.UUID(value)
. Output only the next line. | added_on = Column(DateTime(timezone=True), default=sqlalchemy.sql.func.now()) |
Given snippet: <|code_start|>
class MOTD(Base):
__tablename__ = 'motds'
id = Column(GUID, primary_key=True)
message = Column(UnicodeText, nullable=False)
author = Column(UnicodeText)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from raggregate.models import *
from sqlalchemy import Column
from sqlalchemy import UnicodeText
from raggregate.guid_recipe import GUID
import sqlalchemy
and context:
# Path: raggregate/guid_recipe.py
# class GUID(TypeDecorator):
# """Platform-independent GUID type.
#
# Uses Postgresql's UUID type, otherwise uses
# CHAR(32), storing as stringified hex values.
#
# """
# impl = CHAR
#
# def load_dialect_impl(self, dialect):
# if dialect.name == 'postgresql':
# return dialect.type_descriptor(UUID())
# else:
# return dialect.type_descriptor(CHAR(32))
#
# def process_bind_param(self, value, dialect):
# if value is None:
# return value
# elif dialect.name == 'postgresql':
# return str(value)
# else:
# if not isinstance(value, uuid.UUID):
# return "{0}".format(uuid.UUID(value))
# else:
# # hexstring
# return "{0}".format(value)
#
# def process_result_value(self, value, dialect):
# if value is None:
# return value
# else:
# return uuid.UUID(value)
which might include code, classes, or functions. Output only the next line. | source = Column(UnicodeText) |
Given the code snippet: <|code_start|>
@view_config(renderer='search.mak', route_name='search')
def search(request):
r = request
ses = r.session
try:
sc = request.registry.solr_conn
except AttributeError:
r.session['message'] = 'I could not find the search engine.'
return {'code': 'ENOSOLR', 'success': False}
search_term = r.params['term']
q = sc.query()
for term in search_term.split():
q = q.query(term)
res = q.execute()
<|code_end|>
, generate the next line using the imports in this file:
from pyramid.view import view_config
from raggregate.queries import users
from raggregate.queries import submission
and context (functions, classes, or occasionally code) from other files:
# Path: raggregate/queries/users.py
# def get_user_by_id(id):
# def get_user_by_name(name):
# def get_user_by_email(email):
# def get_user_by_token(token):
# def is_user_allowed_admin_action(user_id, target_id, request = None, target_class = 'user_post',):
# def get_followed_users(id):
# def get_user_votes(user_id, vote_type, submission_id=None):
# def create_temp_user(initial_pw = None):
# def fuzzify_date(d):
# def create_user(**kwargs):
# def login_user(request, u, password, bypass_password = False):
# def add_user_picture(orig_filename, new_prefix, up_dir, image_file):
# def send_email_to_user(request, to_email, title, body):
# def send_lost_password_verify_email(request, user):
# def generate_new_password(request, user):
#
# Path: raggregate/queries/submission.py
# def get_story_list(page_num = 1, per_page = 30, sort = 'new', request = None, self_only = False, section = None):
# def get_story_by_id(id):
# def get_story_by_url_oldest(url):
# def update_story_vote_tally(story_id):
# def get_endpoints_from_page_num(page_num, per_page):
# def get_comments(id, organize_parentage = False, page_num = 1, per_page = 30, sort = 'new', target = 'story', target_id = None):
# def _build_comment_trees(all_comments, allowed_roots):
# def count_comment_children(comment_id):
# def get_comment_parent_story(id):
# def get_comment_by_id(id):
# def get_recent_comments(num):
# def get_story_id_from_slug(slug):
. Output only the next line. | stories = [] |
Given snippet: <|code_start|>
@view_config(renderer='search.mak', route_name='search')
def search(request):
r = request
ses = r.session
try:
sc = request.registry.solr_conn
except AttributeError:
r.session['message'] = 'I could not find the search engine.'
return {'code': 'ENOSOLR', 'success': False}
search_term = r.params['term']
q = sc.query()
for term in search_term.split():
q = q.query(term)
res = q.execute()
stories = []
vds = []
vote_dict = {}
for r in res:
stories.append(submission.get_story_by_id(r['id']))
if 'users.id' in ses:
vds.append(users.get_user_votes(ses['users.id'], "on_submission", r['id']))
for vd in vds:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pyramid.view import view_config
from raggregate.queries import users
from raggregate.queries import submission
and context:
# Path: raggregate/queries/users.py
# def get_user_by_id(id):
# def get_user_by_name(name):
# def get_user_by_email(email):
# def get_user_by_token(token):
# def is_user_allowed_admin_action(user_id, target_id, request = None, target_class = 'user_post',):
# def get_followed_users(id):
# def get_user_votes(user_id, vote_type, submission_id=None):
# def create_temp_user(initial_pw = None):
# def fuzzify_date(d):
# def create_user(**kwargs):
# def login_user(request, u, password, bypass_password = False):
# def add_user_picture(orig_filename, new_prefix, up_dir, image_file):
# def send_email_to_user(request, to_email, title, body):
# def send_lost_password_verify_email(request, user):
# def generate_new_password(request, user):
#
# Path: raggregate/queries/submission.py
# def get_story_list(page_num = 1, per_page = 30, sort = 'new', request = None, self_only = False, section = None):
# def get_story_by_id(id):
# def get_story_by_url_oldest(url):
# def update_story_vote_tally(story_id):
# def get_endpoints_from_page_num(page_num, per_page):
# def get_comments(id, organize_parentage = False, page_num = 1, per_page = 30, sort = 'new', target = 'story', target_id = None):
# def _build_comment_trees(all_comments, allowed_roots):
# def count_comment_children(comment_id):
# def get_comment_parent_story(id):
# def get_comment_by_id(id):
# def get_recent_comments(num):
# def get_story_id_from_slug(slug):
which might include code, classes, or functions. Output only the next line. | if type(vd) == dict: |
Predict the next line after this snippet: <|code_start|>
class SublistMember(Base):
__tablename__ = 'sublists_members'
id = Column(GUID, primary_key=True)
sublist_id = Column(GUID, ForeignKey('sublists.id'))
member_id = Column(GUID, ForeignKey('submissions.id'))
added_by = Column(GUID, ForeignKey('users.id'))
added_on = Column(DateTime)
def __init__(self, sublist_id = None, member_id = None, added_by = None,
added_on = None):
self.sublist_id = sublist_id
self.member_id = member_id
<|code_end|>
using the current file's imports:
from raggregate.models import *
from sqlalchemy import Column
from sqlalchemy import UnicodeText
from sqlalchemy import DateTime
from sqlalchemy import ForeignKey
from raggregate.guid_recipe import GUID
import sqlalchemy
and any relevant context from other files:
# Path: raggregate/guid_recipe.py
# class GUID(TypeDecorator):
# """Platform-independent GUID type.
#
# Uses Postgresql's UUID type, otherwise uses
# CHAR(32), storing as stringified hex values.
#
# """
# impl = CHAR
#
# def load_dialect_impl(self, dialect):
# if dialect.name == 'postgresql':
# return dialect.type_descriptor(UUID())
# else:
# return dialect.type_descriptor(CHAR(32))
#
# def process_bind_param(self, value, dialect):
# if value is None:
# return value
# elif dialect.name == 'postgresql':
# return str(value)
# else:
# if not isinstance(value, uuid.UUID):
# return "{0}".format(uuid.UUID(value))
# else:
# # hexstring
# return "{0}".format(value)
#
# def process_result_value(self, value, dialect):
# if value is None:
# return value
# else:
# return uuid.UUID(value)
. Output only the next line. | self.added_by = added_by |
Based on the snippet: <|code_start|>
meta = MetaData()
def make_subscriptions_table(meta):
users = Table('users', meta, autoload=True)
sections = Table('sections', meta, autoload=True)
users_subscriptions = Table(
'users_subscriptions', meta,
Column('id', GUID, primary_key=True),
Column('user_id', GUID, ForeignKey('users.id')),
Column('section_id', GUID, ForeignKey('sections.id')),
Column('subscription_status', Boolean),
)
return users_subscriptions
def upgrade(migrate_engine):
meta.bind = migrate_engine
subscriptions = make_subscriptions_table(meta)
subscriptions.create()
<|code_end|>
, predict the immediate next line with the help of imports:
from sqlalchemy import *
from migrate import *
from raggregate.guid_recipe import GUID
and context (classes, functions, sometimes code) from other files:
# Path: raggregate/guid_recipe.py
# class GUID(TypeDecorator):
# """Platform-independent GUID type.
#
# Uses Postgresql's UUID type, otherwise uses
# CHAR(32), storing as stringified hex values.
#
# """
# impl = CHAR
#
# def load_dialect_impl(self, dialect):
# if dialect.name == 'postgresql':
# return dialect.type_descriptor(UUID())
# else:
# return dialect.type_descriptor(CHAR(32))
#
# def process_bind_param(self, value, dialect):
# if value is None:
# return value
# elif dialect.name == 'postgresql':
# return str(value)
# else:
# if not isinstance(value, uuid.UUID):
# return "{0}".format(uuid.UUID(value))
# else:
# # hexstring
# return "{0}".format(value)
#
# def process_result_value(self, value, dialect):
# if value is None:
# return value
# else:
# return uuid.UUID(value)
. Output only the next line. | def downgrade(migrate_engine): |
Predict the next line for this snippet: <|code_start|> __tablename__ = 'epistles'
id = Column(GUID, primary_key=True)
recipient = Column(GUID, ForeignKey('users.id'))
sender = Column(GUID, ForeignKey('users.id'))
body = Column(UnicodeText)
subject = Column(UnicodeText)
unread = Column(Boolean, default = True)
#for threading
parent = Column(GUID)
# valid parent_types are 'epistle', 'story', 'comment'
parent_type = Column(UnicodeText, default=u'epistle')
added_on = Column(DateTime(timezone=True), default=sqlalchemy.sql.func.now())
recipient_u = relationship("User", primaryjoin=("Epistle.recipient == User.id"))
sender_u = relationship("User", primaryjoin=("Epistle.sender == User.id"))
def __init__(self, recipient, sender, body, parent_type = None, parent = None, subject = None):
self.recipient = recipient
self.sender = sender
self.body = body
if parent_type is not None:
self.parent_type = parent_type
if parent is not None:
self.parent = parent
if subject is not None:
self.subject = subject
def display_subject(self):
<|code_end|>
with the help of current file imports:
from raggregate.models import *
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import Unicode
from sqlalchemy import UnicodeText
from sqlalchemy import DateTime
from sqlalchemy import text
from sqlalchemy import Boolean
from sqlalchemy import ForeignKey
from raggregate.guid_recipe import GUID
import sqlalchemy
and context from other files:
# Path: raggregate/guid_recipe.py
# class GUID(TypeDecorator):
# """Platform-independent GUID type.
#
# Uses Postgresql's UUID type, otherwise uses
# CHAR(32), storing as stringified hex values.
#
# """
# impl = CHAR
#
# def load_dialect_impl(self, dialect):
# if dialect.name == 'postgresql':
# return dialect.type_descriptor(UUID())
# else:
# return dialect.type_descriptor(CHAR(32))
#
# def process_bind_param(self, value, dialect):
# if value is None:
# return value
# elif dialect.name == 'postgresql':
# return str(value)
# else:
# if not isinstance(value, uuid.UUID):
# return "{0}".format(uuid.UUID(value))
# else:
# # hexstring
# return "{0}".format(value)
#
# def process_result_value(self, value, dialect):
# if value is None:
# return value
# else:
# return uuid.UUID(value)
, which may contain function names, class names, or code. Output only the next line. | if self.subject is not None: |
Using the snippet: <|code_start|>
class UserPicture(Base):
__tablename__ = 'user_pictures'
id = Column(GUID, primary_key=True)
orig_filename = Column(UnicodeText)
filename = Column(UnicodeText)
file_hash = Column(UnicodeText)
# 0 for user's computer
# 1 for twitter
# 2 for facebook
source = Column(Integer, default=0)
# @TODO: we should implement storage_schemes, etc., here.
def __init__(self, orig_filename, filename, file_hash, source):
<|code_end|>
, determine the next line of code. You have imports:
from raggregate.models import *
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import Unicode
from sqlalchemy import UnicodeText
from sqlalchemy import DateTime
from sqlalchemy import text
from sqlalchemy import Boolean
from sqlalchemy import ForeignKey
from raggregate.guid_recipe import GUID
import sqlalchemy
and context (class names, function names, or code) available:
# Path: raggregate/guid_recipe.py
# class GUID(TypeDecorator):
# """Platform-independent GUID type.
#
# Uses Postgresql's UUID type, otherwise uses
# CHAR(32), storing as stringified hex values.
#
# """
# impl = CHAR
#
# def load_dialect_impl(self, dialect):
# if dialect.name == 'postgresql':
# return dialect.type_descriptor(UUID())
# else:
# return dialect.type_descriptor(CHAR(32))
#
# def process_bind_param(self, value, dialect):
# if value is None:
# return value
# elif dialect.name == 'postgresql':
# return str(value)
# else:
# if not isinstance(value, uuid.UUID):
# return "{0}".format(uuid.UUID(value))
# else:
# # hexstring
# return "{0}".format(value)
#
# def process_result_value(self, value, dialect):
# if value is None:
# return value
# else:
# return uuid.UUID(value)
. Output only the next line. | self.orig_filename = orig_filename |
Continue the code snippet: <|code_start|> if key in post and post[key] != '':
return post[key]
else:
return None
def realize_timedelta_constructor(con_str):
""" Converts a timedelta constructor parameter list into a real timedelta.
@param con_str: the constructor parameters to convert"""
return eval("timedelta({0})".format(con_str))
def now_in_utc():
return datetime.utcnow().replace(tzinfo=pytz.utc)
def get_key_from_stat(key, type = None):
sa = dbsession.query(Stat).filter(Stat.key == key).one()
val = json.loads(sa.value)
if type == 'datetime':
val = datetime.fromtimestamp(val).replace(tzinfo=pytz.utc)
return {'key': key, 'value': val, 'sa': sa}
def set_key_in_stat(key, value, type = None):
if type == 'datetime':
value = calendar.timegm(time.gmtime(time.mktime(value.timetuple())))
try:
sa = dbsession.query(Stat).filter(Stat.key == key).one()
sa.key = key
<|code_end|>
. Use current file imports:
from raggregate.models.stat import Stat
from datetime import datetime
from datetime import timedelta
from raggregate.queries import submission
from raggregate.queries import users
from raggregate.queries import epistle as epistle_queries
from raggregate.models.anonallowance import AnonAllowance
from lxml.html import fromstring, tostring
from raggregate.models.ban import Ban
from raggregate.queries import user_preference as up
import calendar
import pytz
import time
import sqlahelper
import sqlalchemy
import json
import uuid
import os
and context (classes, functions, or code) from other files:
# Path: raggregate/models/stat.py
# class Stat(Base):
# __tablename__ = 'stats'
#
# # this table is a k-v store for statistical information.
# key = Column(UnicodeText, primary_key=True)
# value = Column(UnicodeText)
# last_update = Column(DateTime(timezone=True), default=sqlalchemy.sql.func.now())
#
# def __init__(self, key, value):
# self.key = key
# self.value = value
. Output only the next line. | sa.value = value |
Predict the next line for this snippet: <|code_start|>
dbsession = sqlahelper.get_session()
def start_auth(request):
app_twit = request.registry.app_twit
auth_toks = app_twit.get_authentication_tokens()
return auth_toks
<|code_end|>
with the help of current file imports:
import sqlalchemy
import sqlahelper
import urllib2
from raggregate.models.user import User
from raggregate.queries import users
from twython import Twython
and context from other files:
# Path: raggregate/models/user.py
# class User(Base):
# __tablename__ = 'users'
# id = Column(GUID, primary_key=True)
# name = Column(Unicode(255), unique=True)
# password = Column(UnicodeText)
# email = Column(UnicodeText)
# real_name = Column(UnicodeText)
# temporary = Column(Boolean, default=False)
# about_me = Column(UnicodeText)
# picture = Column(GUID, ForeignKey('user_pictures.id'))
# karma = Column(Integer, default=0)
# notify_by_mail = Column(Boolean, default=True)
# twitter_origination = Column(Boolean, default=False)
# twitter_oauth_key = Column(UnicodeText)
# twitter_oauth_secret = Column(UnicodeText)
# facebook_origination = Column(Boolean, default=False)
# facebook_user_id = Column(UnicodeText)
# is_admin = Column(Boolean, default=False)
# lost_password_token = Column(GUID)
# password_token_claim_date = Column(DateTime(timezone=True))
# added_on = Column(DateTime(timezone=True), default=sqlalchemy.sql.func.now())
# added_by = Column(GUID)
#
# followed = relationship("User", secondary=follows, primaryjoin=id==follows.c.followed, secondaryjoin=id==follows.c.follower, backref="follows")
# saved = relationship("Submission", secondary=users_saves)
# picture_ref = relationship("UserPicture")
#
# def update_karma(self):
# #@TODO: find out if we want to allow negative general karma scores
# tally = 0
# try:
# for s in self.submissions:
# tally += s.points
# except:
# pass
# try:
# for c in self.comments:
# tally += c.points
# except:
# pass
# if self.karma != tally:
# self.karma = tally
# return tally
#
# def display_name(self):
# if self.real_name:
# return self.real_name
# else:
# return self.name
#
# # need an adaptable default picture getter method
# #def display_picture_filename(self):
# # if self.picture_ref:
# # return self.picture_ref.filename
# # else:
# # from raggregate import queries
# # return queries.get_default_picture_filename()
#
# def hash_pw(self, pw):
# return crypt.encode(pw)
#
# def verify_pw(self, pw):
# return crypt.check(self.password, pw)
#
# def is_user_admin(self):
# # this is simplistic for now, but one day should use a real roles / permissions system
# return self.is_admin
#
# def is_user_notified(self, target_id):
# from raggregate.queries import notify
# return notify.is_user_notified(self.id, target_id)
#
# def __init__(self, name, password, email = None, real_name = None,
# temporary = False, notify_by_mail = True):
# self.name = name
# self.password = self.hash_pw(password)
# self.email = email
# if real_name:
# self.real_name = real_name
# if temporary:
# self.temporary = True
# self.notify_by_mail = notify_by_mail
#
# Path: raggregate/queries/users.py
# def get_user_by_id(id):
# def get_user_by_name(name):
# def get_user_by_email(email):
# def get_user_by_token(token):
# def is_user_allowed_admin_action(user_id, target_id, request = None, target_class = 'user_post',):
# def get_followed_users(id):
# def get_user_votes(user_id, vote_type, submission_id=None):
# def create_temp_user(initial_pw = None):
# def fuzzify_date(d):
# def create_user(**kwargs):
# def login_user(request, u, password, bypass_password = False):
# def add_user_picture(orig_filename, new_prefix, up_dir, image_file):
# def send_email_to_user(request, to_email, title, body):
# def send_lost_password_verify_email(request, user):
# def generate_new_password(request, user):
, which may contain function names, class names, or code. Output only the next line. | def complete_auth(request, auth_toks): |
Based on the snippet: <|code_start|>
class Ban(Base):
__tablename__ = 'bans'
id = Column(GUID, primary_key=True)
# 0 for IP, 1 for username, 2 for ip/username pair
# left as integer for possible expansion
ban_type = Column(Integer, default = 0)
expires = Column(DateTime(timezone=True), default=None)
# @FIXME: we should use INET from the PgSQL dialect after learning
# how to fall back on other backends (hopefully smoother than GUID).
# but in a hurry so just using UnicodeText for simplicity for now
ip = Column(UnicodeText)
duration = Column(UnicodeText)
username = Column(UnicodeText)
user_id = Column(GUID, ForeignKey('users.id'), default = None)
added_by = Column(GUID, ForeignKey('users.id'), nullable=False)
added_on = Column(DateTime(timezone=True), default=sqlalchemy.sql.func.now())
def __init__(self, ban_type = 0, ip = None, username = None, user_id = None, duration = None, added_by = None):
self.ban_type = ban_type
<|code_end|>
, predict the immediate next line with the help of imports:
from raggregate.models import *
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import Unicode
from sqlalchemy import UnicodeText
from sqlalchemy import DateTime
from sqlalchemy import text
from sqlalchemy import Boolean
from sqlalchemy import ForeignKey
from raggregate.guid_recipe import GUID
from datetime import datetime
import sqlalchemy
and context (classes, functions, sometimes code) from other files:
# Path: raggregate/guid_recipe.py
# class GUID(TypeDecorator):
# """Platform-independent GUID type.
#
# Uses Postgresql's UUID type, otherwise uses
# CHAR(32), storing as stringified hex values.
#
# """
# impl = CHAR
#
# def load_dialect_impl(self, dialect):
# if dialect.name == 'postgresql':
# return dialect.type_descriptor(UUID())
# else:
# return dialect.type_descriptor(CHAR(32))
#
# def process_bind_param(self, value, dialect):
# if value is None:
# return value
# elif dialect.name == 'postgresql':
# return str(value)
# else:
# if not isinstance(value, uuid.UUID):
# return "{0}".format(uuid.UUID(value))
# else:
# # hexstring
# return "{0}".format(value)
#
# def process_result_value(self, value, dialect):
# if value is None:
# return value
# else:
# return uuid.UUID(value)
. Output only the next line. | self.ip = ip |
Using the snippet: <|code_start|>
class Vote(Base):
__tablename__ = 'votes'
id = Column(GUID, primary_key=True)
# we do not coalesce these into a generic item column
# because things are easier/safer with the FK support.
# the tradeoff here is size on various db structures.
submission_id = Column(GUID, ForeignKey('submissions.id'))
comment_id = Column(GUID, ForeignKey('comments.id'))
motd_id = Column(GUID, ForeignKey('motds.id'))
user_id = Column(GUID, ForeignKey('users.id'), nullable=False)
# points: -1 for down, 0 for neutral, 1 for up
# this also allows easier manipulation of vote tallying if needed
# considered using a boolean and deleting the row if a user unvotes
# i guess but have no evidence that's slower than putting this back
# to zero, and as above, makes it more difficult to "modify" the
# voting system if needed.
points = Column(Integer, nullable=False, default=0)
# 0 for none, 1 for up, -1 for down
direction = Column(Integer, nullable=False, default=0)
added_on = Column(DateTime(timezone=True), default=sqlalchemy.sql.func.now())
voter = relationship("User", backref="votes")
def __init__(self, item_id, user_id, points, target_type, comment_id = None):
if target_type == 'comment':
self.comment_id = comment_id
self.submission_id = item_id
<|code_end|>
, determine the next line of code. You have imports:
from raggregate.models import *
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import Unicode
from sqlalchemy import UnicodeText
from sqlalchemy import DateTime
from sqlalchemy import text
from sqlalchemy import Boolean
from sqlalchemy import ForeignKey
from raggregate.guid_recipe import GUID
import sqlalchemy
and context (class names, function names, or code) available:
# Path: raggregate/guid_recipe.py
# class GUID(TypeDecorator):
# """Platform-independent GUID type.
#
# Uses Postgresql's UUID type, otherwise uses
# CHAR(32), storing as stringified hex values.
#
# """
# impl = CHAR
#
# def load_dialect_impl(self, dialect):
# if dialect.name == 'postgresql':
# return dialect.type_descriptor(UUID())
# else:
# return dialect.type_descriptor(CHAR(32))
#
# def process_bind_param(self, value, dialect):
# if value is None:
# return value
# elif dialect.name == 'postgresql':
# return str(value)
# else:
# if not isinstance(value, uuid.UUID):
# return "{0}".format(uuid.UUID(value))
# else:
# # hexstring
# return "{0}".format(value)
#
# def process_result_value(self, value, dialect):
# if value is None:
# return value
# else:
# return uuid.UUID(value)
. Output only the next line. | elif target_type == 'submission': |
Predict the next line after this snippet: <|code_start|> 'granite_armour' : 'granite_armour',
'faint' : 'faint',
'quicksand' : 'quicksand',
'blizzard' : 'blizzard',
'frost_storm' : 'frost_storm',
'glacier' : 'glacier',
'ice_cage' : 'ice_cage',
'frostbite' : 'frost_bite',
'chill_strike' : 'chill_strike',
'ice_breaker' : 'ice_breaker',
'ice_wall' : 'ice_wall',
'drop_mixtape' : 'drop_mixtape',
'blazing_salvo' : 'blazing_salvo',
'fireball' : 'fireball',
'lava_storm' : 'lava_storm',
'flame_wave' : 'flame_wave',
'backdraft' : 'backdraft',
'solar_blaze' : 'solar_blaze',
'unmake' : 'unmake',
'power_swirl' : 'power_swirl',
'sting_of_neptune': 'sting_of_neptune',
'water_jet' : 'water_jet',
'riptide' : 'riptide',
'tidal_wave' : 'tidal_wave',
'monsoon' : 'monsoon',
'healing_wave' : 'healing_wave',
'absorb' : 'absorb',
'nope' : 'nope',
}
<|code_end|>
using the current file's imports:
import pygame
import os
from app.resources.directories import SOUND_DIR
and any relevant context from other files:
# Path: app/resources/directories.py
# SOUND_DIR = os.path.join(DATA_DIR, "sounds")
. Output only the next line. | def play_sound(self, sound_name): |
Predict the next line after this snippet: <|code_start|>
pygame.font.init()
title_font = pygame.font.Font(FONT_ALEX_BRUSH, 84)
cursive_small = pygame.font.Font(FONT_ALEX_BRUSH, 48)
menu_item_font = pygame.font.SysFont('serif', 32)
huge_font = pygame.font.SysFont('serif', 64)
large_font = pygame.font.SysFont('serif', 48)
regular_font = pygame.font.SysFont('serif', 24)
small_font = pygame.font.SysFont('serif', 18)
def render_title(text, colour = colours.COLOUR_AMLSERVINYOUR):
return title_font.render(text, 1, colour)
def render_menu_item(text, colour = colours.COLOUR_AMLSERVINYOUR):
<|code_end|>
using the current file's imports:
import pygame
import os
from app.resources.directories import FONT_ALEX_BRUSH
from app.resources import colours
and any relevant context from other files:
# Path: app/resources/directories.py
# FONT_ALEX_BRUSH = os.path.join(FONT_DIR, ALEX_BRUSH_FILE)
#
# Path: app/resources/colours.py
# COLOUR_BLUE = ( 0, 0, 255)
# COLOUR_RED = ( 255, 0, 0)
# COLOUR_GREEN = ( 0, 255, 0)
# COLOUR_WHITE = ( 255, 255, 255)
# COLOUR_GREY = ( 128, 128, 128)
# COLOUR_BLACK = ( 0, 0, 0)
# COLOUR_YELLOW = (255,223,0)
# COLOUR_LEAVES_OF_AUTUMN = ( 101, 91, 19 )
# COLOUR_628450 = ( 98, 132, 80 )
# COLOUR_FUTURE = ( 96, 150, 107 )
# COLOUR_AMLSERVINYOUR = ( 132, 172, 149 )
# COLOUR_ASTERIX = ( 248, 239, 214 )
# COLOUR_IRISH_GREEN = ( 0, 154, 73 )
# COLOUR_IRISH_ORANGE = ( 255, 121, 0 )
. Output only the next line. | return menu_item_font.render(text, 1, colour) |
Based on the snippet: <|code_start|>
def render_title(text, colour = colours.COLOUR_AMLSERVINYOUR):
return title_font.render(text, 1, colour)
def render_menu_item(text, colour = colours.COLOUR_AMLSERVINYOUR):
return menu_item_font.render(text, 1, colour)
def render_huge_text(text, colour = colours.COLOUR_AMLSERVINYOUR):
return huge_font.render(text, 1, colour)
def render_large_text(text, colour = colours.COLOUR_AMLSERVINYOUR):
return large_font.render(text, 1, colour)
def render_text(text, colour = colours.COLOUR_AMLSERVINYOUR ):
return regular_font.render(text, 1, colour)
def render_small_text(text, colour = colours.COLOUR_AMLSERVINYOUR ):
return small_font.render(text, 1, colour)
def render_cursive_small(text, colour = colours.COLOUR_AMLSERVINYOUR ):
return cursive_small.render(text, 1, colour)
def render_text_wrapped(surface, text, rect, color = colours.COLOUR_AMLSERVINYOUR, aa=True):
rect = pygame.Rect(rect)
y = rect.top
lineSpacing = -2
# get the height of the font
fontHeight = regular_font.size("Tg")[1]
<|code_end|>
, predict the immediate next line with the help of imports:
import pygame
import os
from app.resources.directories import FONT_ALEX_BRUSH
from app.resources import colours
and context (classes, functions, sometimes code) from other files:
# Path: app/resources/directories.py
# FONT_ALEX_BRUSH = os.path.join(FONT_DIR, ALEX_BRUSH_FILE)
#
# Path: app/resources/colours.py
# COLOUR_BLUE = ( 0, 0, 255)
# COLOUR_RED = ( 255, 0, 0)
# COLOUR_GREEN = ( 0, 255, 0)
# COLOUR_WHITE = ( 255, 255, 255)
# COLOUR_GREY = ( 128, 128, 128)
# COLOUR_BLACK = ( 0, 0, 0)
# COLOUR_YELLOW = (255,223,0)
# COLOUR_LEAVES_OF_AUTUMN = ( 101, 91, 19 )
# COLOUR_628450 = ( 98, 132, 80 )
# COLOUR_FUTURE = ( 96, 150, 107 )
# COLOUR_AMLSERVINYOUR = ( 132, 172, 149 )
# COLOUR_ASTERIX = ( 248, 239, 214 )
# COLOUR_IRISH_GREEN = ( 0, 154, 73 )
# COLOUR_IRISH_ORANGE = ( 255, 121, 0 )
. Output only the next line. | while text: |
Here is a snippet: <|code_start|> else:
# Invalid target! Don't do anything
print("Invalid target")
print("")
return {"success" : False, "caster" :self, "reason" : "invalid target"}
try:
# Cast the spell!
summary = self.cast_spell(decision[0], target)
except Exception as e:
print(e)
return {"success" : False, "caster" :self, "reason" : "does nothing"}
return summary
def cast_spell(self, spell, target):
return self.spellbook.cast_spell(spell, self, target)
def restore_health(self, amount):
if not self.is_conscious():
print("{} has fainted and cannot have health restored".format(self.name))
return
delta = min(amount, self.max_hp - self.cur_hp)
self.cur_hp += delta
print("{} regained {} HP".format(self.name, delta))
def get_remaining_health_percentage(self):
return float(self.cur_hp)/max(self.max_hp,1)
<|code_end|>
. Write the next line using the current file imports:
from app.models import magic
import time
and context from other files:
# Path: app/models/magic.py
# class Element(object):
# class Effect(object):
# class AttackEffect(Effect):
# class ReboundAttackEffect(AttackEffect):
# class LeechAttackEffect(AttackEffect):
# class BoostStatEffect(Effect):
# class ReduceStatEffect(Effect):
# class HealingEffect(Effect):
# class Spell(object):
# class GroupSpell(Spell):
# class SpellCommand:
# class CastSpell(SpellCommand):
# class Magic:
# class SpellBook:
# def __init__(self, name, strong, weak, compatible):
# def is_compatible_with(self, element):
# def is_strong_against(self, element):
# def is_weak_against(self, element):
# def __init__(self, element, power, accuracy=100):
# def target_evades(self, caster, target):
# def apply_effect(self, caster, target):
# def __init__(self, element, power, accuracy, critical_hit_prob):
# def compute_damage(self, caster, target, critical_hit=False):
# def is_critical_hit(self):
# def apply_effect(self, caster, target):
# def __init__(self, element, power, accuracy, critical_hit_prob, rebound):
# def apply_effect(self, caster, target):
# def __init__(self, element, power, accuracy, critical_hit_prob, leech):
# def apply_effect(self, caster, target):
# def __init__(self, element, power, stat):
# def apply_effect(self, caster, target):
# def __init__(self, element, power, accuracy, stat):
# def apply_effect(self, caster, target):
# def apply_effect(self, caster, target):
# def __init__(self, name, effects, element):
# def is_castable_by(self, caster):
# def cast(self, caster, target):
# def cast(self, caster, targets):
# def __init__(self, spell, caster, target):
# def execute(self):
# def execute(self):
# def __init__(self):
# def execute(self, command):
# def __init__(self):
# def cast_spell(self, spell, caster, target):
# def __load_elements(xml_tree):
# def __load_spells(xml_tree):
# def load_spell_book(spell_book):
# def get_element_object(identifier):
# def get_spell_object(identifier):
, which may include functions, classes, or code. Output only the next line. | def take_damage(self, damage): |
Next line prediction: <|code_start|>class ImageManager:
class __ImageManager:
def __init__(self):
self.images = {}
image_files = os.listdir(IMAGE_DIR)
for image_name in image_files:
self.images[os.path.splitext(image_name)[0]] = pygame.image.load(os.path.join(IMAGE_DIR, image_name))
self.tile_size = 100
def get_image(self, image_name):
if image_name not in self.images:
s = pygame.Surface((self.tile_size,self.tile_size))
s.fill((0,0,0))
return s
return self.images[image_name]
def get_tile(self, image_name, clip_x, clip_y):
if image_name not in self.images:
s = pygame.Surface((self.tile_size,self.tile_size))
s.fill((0,0,0))
return s
surface = self.images[image_name]
rect = pygame.Rect(
(
<|code_end|>
. Use current file imports:
(import pygame
import os
from app.resources.directories import IMAGE_DIR)
and context including class names, function names, or small code snippets from other files:
# Path: app/resources/directories.py
# IMAGE_DIR = os.path.join(DATA_DIR, "images")
. Output only the next line. | clip_x*self.tile_size, |
Predict the next line for this snippet: <|code_start|>
class MusicManager:
class __MusicManager:
def __init__(self, settings):
self.music = {}
self.now_playing = ""
if settings == None:
self.settings = {
"sound" :
{
"sound_volume":0.3,
"sound_enabled" : True
}
<|code_end|>
with the help of current file imports:
import pygame
import os
from app.resources.directories import MUSIC_DIR
and context from other files:
# Path: app/resources/directories.py
# MUSIC_DIR = os.path.join(DATA_DIR, "music")
, which may contain function names, class names, or code. Output only the next line. | } |
Predict the next line after this snippet: <|code_start|> self.scores[team.get_short_name()] = 0
def get_matches_list(self):
return self.matches
def get_current_match(self):
return self.current_match
def get_scores(self):
return self.scores
def record_result(self, battle):
self.scores[battle.get_winner()] += 1
def winners_chosen(self):
ranks = defaultdict(list)
team_scores = []
for team in self.teams:
score = self.scores[team.get_short_name()]
ranks[score].append(team)
team_scores.append(score)
team_scores = sorted(set(team_scores), key=lambda x: -x)
for score in team_scores:
if len(self.winners) >= self.n_winners:
break
if len(ranks[score]) + len(self.winners) <= self.n_winners:
self.winners += ranks[score]
else:
self.initialize_matches(ranks[score])
<|code_end|>
using the current file's imports:
from app.models.battle import Battle
from collections import defaultdict
and any relevant context from other files:
# Path: app/models/battle.py
# class Battle:
# def __init__(self, team1, team2):
# self.team1 = team1
# self.team2 = team2
#
# self.team1.reinitialize()
# self.team2.reinitialize()
#
# self.cur_round = None
# self.round_counter = 0
# self.max_round = 10
#
# self.start_new_round()
#
# def set_state(self, state):
# if state not in self.states:
# return
#
# self.cur_state = state
# self.state = self.states[self.cur_state](self)
#
# def play_next_move(self):
# if not self.is_battle_over():
# result = self.cur_round.next_move()
# if self.cur_round.round_over():
# self.start_new_round()
# result["finished"] = False
# return result
# return { "finished" : True }
#
# def start_new_round(self):
# self.cur_round = BattleRound(self.team1, self.team2)
# self.round_counter += 1
#
# def get_round_number(self):
# return self.round_counter
#
# def is_battle_over(self):
# return self.team2.is_defeated() or self.team1.is_defeated() or self.round_counter > self.max_round
#
# def award_victory(self, team_no):
# if team_no == 2:
# for mage in self.team1:
# mage.cur_hp = 0
# elif team_no == 1:
# for mage in self.team2:
# mage.cur_hp = 0
#
# def get_winner(self):
# if self.team2.is_defeated():
# return self.team1.get_short_name()
#
# if self.team1.is_defeated():
# return self.team2.get_short_name()
#
# if self.round_counter > self.max_round:
# dt1 = [tm.get_remaining_health_percentage() for tm in self.team1]
# dt2 = [tm.get_remaining_health_percentage() for tm in self.team2]
# dt1 = sum(dt1)
# dt2 = sum(dt2)
#
# return self.team1.get_short_name() if dt1 > dt2 else self.team2.get_short_name()
#
# return None
#
# def __str__(self):
# text = "Round {}\n".format(self.round_counter) if not self.is_battle_over() else "{} won\n".format(self.get_winner())
# text += str(self.team1)
# text += '\n'
# text += str(self.team2)
#
# return text
. Output only the next line. | return False |
Here is a snippet: <|code_start|> try:
self.write_message(dumps({'action': action, 'data': data}, json_options=RELAXED_JSON_OPTIONS))
except Exception as e:
logger.error('Exception in send_message: %s %s', action, data, exc_info=e)
self.on_close()
self.close()
class BaseUIHandler(RequestHandler):
def initialize(self, wui):
self._wui = wui
@property
def _db(self):
return self._wui.controller.db
@property
def _config(self):
return self._wui.controller.config
def render(self, *args, **kwargs):
super().render(*args, version=__version__, **kwargs)
def write_error(self, status_code, **kwargs):
if 'exc_info' in kwargs:
icon = 'sentiment_very_dissatisfied'
if self.application.settings.get('serve_traceback'):
exc_info = markdown('```\n%s\n```' % ''.join(traceback.format_exception(*kwargs['exc_info'])), extensions=['extra', 'fenced_code', 'codehilite'])
else:
<|code_end|>
. Write the next line using the current file imports:
import logging
import mimetypes
import pkgutil
import threading
import traceback
from urllib.parse import urljoin, urlparse, urlunparse
from bson.json_util import dumps, RELAXED_JSON_OPTIONS
from markdown import markdown
from tornado.template import BaseLoader, Template
from tornado.web import HTTPError, RequestHandler
from tornado.websocket import WebSocketHandler
from ...config import config_get_object
from ...formatter import JsonFormatter
from ...pkgdata import __version__
from ...tracker import TrackerError
and context from other files:
# Path: fuzzinator/pkgdata.py
, which may include functions, classes, or code. Output only the next line. | exc_info = '' |
Given the following code snippet before the placeholder: <|code_start|>
class EditIssueDialog(Dialog):
exit_keys = ['esc', 'f4']
def __init__(self, issue, db):
self.issue = issue
self.db = db
self.edit_boxes = {}
self.type_dict = {}
rows = []
for prop in issue:
if prop == '_id':
continue
self.edit_boxes[prop] = BugEditor('', self._to_str(prop, issue[prop]), multiline=True)
rows.append(Columns([('weight', 1, Text(('dialog_secondary', prop + ': '))),
('weight', 10, self.edit_boxes[prop])], dividechars=1))
super().__init__(title=issue['id'],
body=rows,
footer_btns=[FormattedButton('Save', self.save_modifications),
FormattedButton('Close', lambda button: self._emit('close'))])
def _to_str(self, prop, value):
t = type(value)
self.type_dict[prop] = t
if t == str:
<|code_end|>
, predict the next line using imports from the current file:
from ast import literal_eval
from datetime import datetime
from urwid import *
from ...config import config_get_object
from ...formatter import JsonFormatter
from ...pkgdata import __author__, __author_email__, __pkg_name__, __url__, __version__
from .button import FormattedButton
from .decor_widgets import PatternBox
from .graphics import fz_box_pattern
and context including class names, function names, and sometimes code from other files:
# Path: fuzzinator/pkgdata.py
#
# Path: fuzzinator/ui/tui/button.py
# class FormattedButton(WidgetWrap):
# signals = ['click']
# _selectable = True
#
# def __init__(self, label, on_press=None, user_data=None, style='button'):
# self.text_len = len(label)
# self.btn = ShortButton(label, on_press, user_data)
# super().__init__(AttrMap(self.btn, style))
# connect_signal(self.btn, 'click', lambda btn: self._emit('click'))
#
# def sizing(self):
# return frozenset(['fixed'])
#
# def pack(self, size=None, focus=None):
# return self.text_len + 6, 1
. Output only the next line. | return value |
Predict the next line for this snippet: <|code_start|> def _to_str(self, prop, value):
t = type(value)
self.type_dict[prop] = t
if t == str:
return value
if t == bytes:
return value.decode('utf-8', errors='ignore')
if t == datetime:
return value.strftime('%Y-%m-%d %H:%M:%S')
if value is None:
self.type_dict[prop] = None
return ''
return str(value)
def _from_str(self, prop, value):
t = self.type_dict[prop]
if t == str:
return value
if t == int:
return int(value)
if t == bytes:
return value.encode('utf-8', errors='ignore')
if t == datetime:
return datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
if t is None:
return value or None
return literal_eval(value)
<|code_end|>
with the help of current file imports:
from ast import literal_eval
from datetime import datetime
from urwid import *
from ...config import config_get_object
from ...formatter import JsonFormatter
from ...pkgdata import __author__, __author_email__, __pkg_name__, __url__, __version__
from .button import FormattedButton
from .decor_widgets import PatternBox
from .graphics import fz_box_pattern
and context from other files:
# Path: fuzzinator/pkgdata.py
#
# Path: fuzzinator/ui/tui/button.py
# class FormattedButton(WidgetWrap):
# signals = ['click']
# _selectable = True
#
# def __init__(self, label, on_press=None, user_data=None, style='button'):
# self.text_len = len(label)
# self.btn = ShortButton(label, on_press, user_data)
# super().__init__(AttrMap(self.btn, style))
# connect_signal(self.btn, 'click', lambda btn: self._emit('click'))
#
# def sizing(self):
# return frozenset(['fixed'])
#
# def pack(self, size=None, focus=None):
# return self.text_len + 6, 1
, which may contain function names, class names, or code. Output only the next line. | def save_modifications(self, btn): |
Predict the next line for this snippet: <|code_start|># Copyright (c) 2016-2022 Renata Hodovan, Akos Kiss.
#
# Licensed under the BSD 3-Clause License
# <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>.
# This file may not be copied, modified, or distributed except
# according to those terms.
class Dialog(PopUpTarget):
signals = ['close']
exit_keys = ['esc']
def __init__(self, title, body, footer_btns, warning=False):
if not warning:
style = dict(body='dialog', title='dialog_title', border='dialog_border')
else:
<|code_end|>
with the help of current file imports:
from ast import literal_eval
from datetime import datetime
from urwid import *
from ...config import config_get_object
from ...formatter import JsonFormatter
from ...pkgdata import __author__, __author_email__, __pkg_name__, __url__, __version__
from .button import FormattedButton
from .decor_widgets import PatternBox
from .graphics import fz_box_pattern
and context from other files:
# Path: fuzzinator/pkgdata.py
#
# Path: fuzzinator/ui/tui/button.py
# class FormattedButton(WidgetWrap):
# signals = ['click']
# _selectable = True
#
# def __init__(self, label, on_press=None, user_data=None, style='button'):
# self.text_len = len(label)
# self.btn = ShortButton(label, on_press, user_data)
# super().__init__(AttrMap(self.btn, style))
# connect_signal(self.btn, 'click', lambda btn: self._emit('click'))
#
# def sizing(self):
# return frozenset(['fixed'])
#
# def pack(self, size=None, focus=None):
# return self.text_len + 6, 1
, which may contain function names, class names, or code. Output only the next line. | style = dict(body='warning', title='warning_title', border='warning_border') |
Here is a snippet: <|code_start|># Copyright (c) 2016-2022 Renata Hodovan, Akos Kiss.
#
# Licensed under the BSD 3-Clause License
# <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>.
# This file may not be copied, modified, or distributed except
# according to those terms.
class Dialog(PopUpTarget):
signals = ['close']
exit_keys = ['esc']
def __init__(self, title, body, footer_btns, warning=False):
if not warning:
style = dict(body='dialog', title='dialog_title', border='dialog_border')
<|code_end|>
. Write the next line using the current file imports:
from ast import literal_eval
from datetime import datetime
from urwid import *
from ...config import config_get_object
from ...formatter import JsonFormatter
from ...pkgdata import __author__, __author_email__, __pkg_name__, __url__, __version__
from .button import FormattedButton
from .decor_widgets import PatternBox
from .graphics import fz_box_pattern
and context from other files:
# Path: fuzzinator/pkgdata.py
#
# Path: fuzzinator/ui/tui/button.py
# class FormattedButton(WidgetWrap):
# signals = ['click']
# _selectable = True
#
# def __init__(self, label, on_press=None, user_data=None, style='button'):
# self.text_len = len(label)
# self.btn = ShortButton(label, on_press, user_data)
# super().__init__(AttrMap(self.btn, style))
# connect_signal(self.btn, 'click', lambda btn: self._emit('click'))
#
# def sizing(self):
# return frozenset(['fixed'])
#
# def pack(self, size=None, focus=None):
# return self.text_len + 6, 1
, which may include functions, classes, or code. Output only the next line. | else: |
Here is a snippet: <|code_start|> else:
style = dict(body='warning', title='warning_title', border='warning_border')
self.walker = SimpleListWalker(body)
self.listbox = ListBox(self.walker)
self.frame = Frame(body=AttrMap(self.listbox, style['body']),
footer=Columns([('pack', btn) for btn in footer_btns], dividechars=1),
focus_part='body')
super().__init__(AttrMap(PatternBox(self.frame, title=(style['title'], title), **fz_box_pattern()),
attr_map=style['border']))
def keypress(self, size, key):
if key in self.exit_keys:
self._emit('close')
return None
if key in ['tab']:
if self.frame.focus_part == 'body':
try:
next_pos = self.walker.next_position(self.listbox.focus_position)
self.listbox.focus_position = next_pos
except IndexError:
self.frame.focus_part = 'footer'
self.frame.footer.focus_col = 0
elif self.frame.footer and self.frame.footer.contents:
if self.frame.footer.focus_col < len(self.frame.footer.contents) - 1:
self.frame.footer.focus_col += 1
else:
self.frame.focus_part = 'body'
self.listbox.focus_position = 0
return None
<|code_end|>
. Write the next line using the current file imports:
from ast import literal_eval
from datetime import datetime
from urwid import *
from ...config import config_get_object
from ...formatter import JsonFormatter
from ...pkgdata import __author__, __author_email__, __pkg_name__, __url__, __version__
from .button import FormattedButton
from .decor_widgets import PatternBox
from .graphics import fz_box_pattern
and context from other files:
# Path: fuzzinator/pkgdata.py
#
# Path: fuzzinator/ui/tui/button.py
# class FormattedButton(WidgetWrap):
# signals = ['click']
# _selectable = True
#
# def __init__(self, label, on_press=None, user_data=None, style='button'):
# self.text_len = len(label)
# self.btn = ShortButton(label, on_press, user_data)
# super().__init__(AttrMap(self.btn, style))
# connect_signal(self.btn, 'click', lambda btn: self._emit('click'))
#
# def sizing(self):
# return frozenset(['fixed'])
#
# def pack(self, size=None, focus=None):
# return self.text_len + 6, 1
, which may include functions, classes, or code. Output only the next line. | return super().keypress(size, key) |
Next line prediction: <|code_start|> def _to_str(self, prop, value):
t = type(value)
self.type_dict[prop] = t
if t == str:
return value
if t == bytes:
return value.decode('utf-8', errors='ignore')
if t == datetime:
return value.strftime('%Y-%m-%d %H:%M:%S')
if value is None:
self.type_dict[prop] = None
return ''
return str(value)
def _from_str(self, prop, value):
t = self.type_dict[prop]
if t == str:
return value
if t == int:
return int(value)
if t == bytes:
return value.encode('utf-8', errors='ignore')
if t == datetime:
return datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
if t is None:
return value or None
return literal_eval(value)
<|code_end|>
. Use current file imports:
(from ast import literal_eval
from datetime import datetime
from urwid import *
from ...config import config_get_object
from ...formatter import JsonFormatter
from ...pkgdata import __author__, __author_email__, __pkg_name__, __url__, __version__
from .button import FormattedButton
from .decor_widgets import PatternBox
from .graphics import fz_box_pattern)
and context including class names, function names, or small code snippets from other files:
# Path: fuzzinator/pkgdata.py
#
# Path: fuzzinator/ui/tui/button.py
# class FormattedButton(WidgetWrap):
# signals = ['click']
# _selectable = True
#
# def __init__(self, label, on_press=None, user_data=None, style='button'):
# self.text_len = len(label)
# self.btn = ShortButton(label, on_press, user_data)
# super().__init__(AttrMap(self.btn, style))
# connect_signal(self.btn, 'click', lambda btn: self._emit('click'))
#
# def sizing(self):
# return frozenset(['fixed'])
#
# def pack(self, size=None, focus=None):
# return self.text_len + 6, 1
. Output only the next line. | def save_modifications(self, btn): |
Given the following code snippet before the placeholder: <|code_start|> colorscheme "mint-examples2"
"""
config2 = r"""
[layout]
style layout
[node]
style poly
fontName $FONTNAME
fontSize $FONTSIZE
textBaselineCorrection $BASELINE_CORR
numSides 6
strokeWidth 3
textPadX 15
textPadY 15
[connection]
style curve
[color]
style cycle
colorscheme "mint-examples"
"""
config3 = r"""
[layout]
style layout
[node]
<|code_end|>
, predict the next line using imports from the current file:
import os, sys
from fig import *
from twyg.cairowrapper import context as ctx
and context including class names, function names, and sometimes code from other files:
# Path: twyg/cairowrapper.py
# class Color(object):
# class Context(object):
# def __init__(self, c1, c2, c3, a, mode='rgb'):
# def __repr__(self):
# def copy(self):
# def rgba(self):
# def darken(self, step=0.1):
# def lighten(self, step=0.1):
# def blend(self, clr, factor=0.5):
# def _update_hsv(self):
# def _update_rgb(self):
# def color(*args):
# def __init__(self):
# def init():
# def rect(self, x, y, width, height, roundness=0.0, draw=True):
# def oval(self, x, y, width, height, draw=True):
# def line(self, x1, y1, x2, y2, draw=True):
# def arrow(x, y, width, type, draw=True):
# def star(x, y, points=20, outer=100, inner=50, draw=True):
# def beginpath(self, x, y):
# def moveto(self, x, y):
# def lineto(self, x, y):
# def curveto(self, x1, y1, x2, y2, x3, y3):
# def findpath(list, curvature=1.0):
# def endpath(self, draw=True):
# def drawpath(self, path):
# def beginclip(self, path):
# def endclip(self):
# def autoclosepath(self, close=True):
# def transform(mode):
# def translate(self, x, y):
# def rotate(self, degrees=0.0, radians=0.0):
# def scale(self, x, y=None):
# def skew(x, y=None):
# def push(self):
# def pop(self):
# def reset(self):
# def outputmode(self, mode):
# def colormode(self, mode):
# def color(self, *args):
# def fill(self, *args):
# def nofill(self):
# def stroke(self, *args):
# def nostroke(self):
# def strokewidth(self, width):
# def background(self, *args):
# def font(self, fontname, fontsize=None):
# def fontsize(self, fontsize):
# def text(self, txt, x, y):
# def textpath(txt, x, y, width=None, height=1000000):
# def textwidth(self, txt):
# def textheight(self, txt):
# def textmetrics(self, txt):
# def lineheight(self, height=None):
# def align(self, align):
# def image(path, x, y, width=None, height=None, alpha=1.0, data=None):
# def imagesize(path):
# def size(w, h):
# def var(name, type, default, min, max):
# def random(v1=None, v2=None):
# def choice(list):
# def grid(cols, rows, colsize=1, rowsize=1):
# def files(path):
# def autotext(xml):
# def rgba_color(self, c):
# def gradientfill(self, path, clr1, clr2, dx=0.0, dy=0.0,
# type='linear',spread=1.0):
# def shadow(self, dx=0.0, dy=0.0, blur=3.0, clr=color(0, 0, 0, 1)):
# def noshadow(self):
# def initsurface(self, w, h, fmt, fname=None, scale=1.0):
# def writesurface(self):
# def _make_color_obj(self, *args):
# def _draw_stroke(self):
# def _draw(self):
# def _draw_shadow(self):
# def _render_bitmap_shadow(self):
. Output only the next line. | style poly |
Based on the snippet: <|code_start|>
class Direction(object):
Top, Right, Bottom, Left = range(4)
def opposite_dir(d):
if d == Direction.Bottom:
return Direction.Top
if d == Direction.Right:
return Direction.Left
if d == Direction.Top:
return Direction.Bottom
if d == Direction.Left:
return Direction.Right
else:
<|code_end|>
, predict the immediate next line with the help of imports:
import sys
from twyg.geom import Vector2, Rectangle
and context (classes, functions, sometimes code) from other files:
# Path: twyg/geom.py
# class Vector2(object):
# """ Class representing two-dimensional vectors.
#
# The coordinate system used has the following properties:
# - the origo (0,0) is located in the top left corner
# - the positive x direction is from left to right
# - the positive y direction is from top to bottom
# - positive rotation is counter-clockwise
# """
# def __init__(self, *args, **kwargs):
# if args:
# if isinstance(args[0], Vector2):
# self.x = float(args[0].x)
# self.y = float(args[0].y)
# return
# elif len(args) < 2:
# raise ValueError, "Must specify 'x' and 'y' of new vector"
# self.x = float(args[0])
# self.y = float(args[1])
# else:
# if not ('m' in kwargs and 'angle' in kwargs):
# raise ValueError, "Must specify 'm' and 'angle' of new vector"
# m = kwargs['m']
# a = -kwargs['angle']
# self.x = m * math.cos(a)
# self.y = m * math.sin(a)
#
# def __repr__(self):
# return '(%s, %s)' % (self.x, self.y)
#
# def magnitude(self):
# return math.sqrt(self.x * self.x + self.y * self.y)
#
# m = property(magnitude)
#
# def angle(self):
# a = -math.atan2(self.y, self.x)
# if a < 0:
# a += math.pi * 2
# return a
#
# a = property(angle)
#
# def normalize(self):
# m = self.magnitude()
# if m != 0:
# self.x /= m
# self.y /= m
# return self
#
# def rotate(self, angle):
# angle = -angle
# cos = math.cos(angle)
# sin = math.sin(angle)
# x = self.x * cos - self.y * sin
# y = self.x * sin + self.y * cos
# self.x = x
# self.y = y
# return self
#
# def __add__(self, s):
# return Vector2(self.x + s.x, self.y + s.y)
#
# def __iadd__(self, s):
# self.x += s.x
# self.y += s.y
# return self
#
# def __sub__(self, s):
# return Vector2(self.x - s.x, self.y - s.y)
#
# def __isub__(self, s):
# self.x -= s.x
# self.y -= s.y
# return self
#
# def __mul__(self, s):
# return Vector2(self.x * s, self.y * s)
#
# def __rmul__(self, s):
# return Vector2(self.x * s, self.y * s)
#
# def __imul__(self, s):
# self.x *= s
# self.y *= s
# return self
#
# def __div__(self, s):
# return Vector2(self.x / s, self.y / s)
#
# def __idiv__(self, s):
# self.x /= s
# self.y /= s
# return self
#
# class Rectangle(object):
# def __init__(self, x, y, w, h):
# self.x = x
# self.y = y
# self.w = w
# self.h = h
#
# def __repr__(self):
# return '(x=%s, y=%s, w=%s, h=%s)' % (self.x, self.y, self.w, self.h)
#
# def params(self):
# return self.x, self.y, self.w, self.h
#
# def points(self):
# return [Point2D(self.x, self.y),
# Point2D(self.x + self.w, self.y),
# Point2D(self.x + self.w, self.y + self.h),
# Point2D(self.x, self.y + self.h)]
#
# def expand(self, rect):
# r1x1 = self.x
# r1y1 = self.y
# r1x2 = r1x1 + self.w
# r1y2 = r1y1 + self.h
#
# r2x1 = rect.x
# r2y1 = rect.y
# r2x2 = r2x1 + rect.w
# r2y2 = r2y1 + rect.h
#
# x1 = min(r1x1, r2x1)
# y1 = min(r1y1, r2y1)
# x2 = max(r1x2, r2x2)
# y2 = max(r1y2, r2y2)
#
# self.x = x1
# self.y = y1
# self.w = x2 - x1
# self.h = y2 - y1
. Output only the next line. | raise ValueError, 'Invalid direction: %s' % d
|
Predict the next line after this snippet: <|code_start|>
sys.path.append(os.path.join('..'))
class TestCSS3Colors(unittest.TestCase):
def test_valid(self):
r, g, b, a = color_to_rgba('aquamarine')
c = rgba_to_color(r, g, b, a, format='rgb')
self.assertEquals('rgb(127, 255, 212)', c)
r, g, b, a = color_to_rgba('000')
c = rgba_to_color(r, g, b, a, format='hex')
self.assertEquals('#000000', c)
r, g, b, a = color_to_rgba(' 000')
c = rgba_to_color(r, g, b, a, format='hex')
self.assertEquals('#000000', c)
r, g, b, a = color_to_rgba('#123')
c = rgba_to_color(r, g, b, a, format='hex')
self.assertEquals('#112233', c)
r, g, b, a = color_to_rgba(' #123')
c = rgba_to_color(r, g, b, a, format='hex')
<|code_end|>
using the current file's imports:
import os, sys, unittest
from twyg.css3colors import color_to_rgba, rgba_to_color
and any relevant context from other files:
# Path: twyg/css3colors.py
# def color_to_rgba(col):
# # Convert to string to handle hex colors consisting of decimal
# # digits only correctly
# col = str(col).strip()
# a = 1.0
#
# if col in colornames:
# r, g, b = colornames[col]
# return r / 255., g / 255., b / 255., a
#
# try:
# r, g, b = _parse_hex(col)
# return r, g, b, a
# except ValueError:
# pass
#
# # rgb(r, g, b)
# m = _re_rgb.match(col)
# if m:
# r, g, b = m.groups()
# r = _conv_rgb(r)
# g = _conv_rgb(g)
# b = _conv_rgb(b)
# return r, g, b, a
#
# # rgb(r%, g%, b%)
# m = _re_rgb_p.match(col)
# if m:
# r, g, b = m.groups()
# r = _conv_percent(r)
# g = _conv_percent(g)
# b = _conv_percent(b)
# return r, g, b, a
#
# # rgba(r, g, b, a)
# m = _re_rgba.match(col)
# if m:
# r, g, b, a = m.groups()
# r = _conv_rgb(r)
# g = _conv_rgb(g)
# b = _conv_rgb(b)
# a = _conv_alpha(a)
# return r, g, b, a
#
# # rgba(r%, g%, b%, a)
# m = _re_rgba_p.match(col)
# if m:
# r, g, b, a = m.groups()
# r = _conv_percent(r)
# g = _conv_percent(g)
# b = _conv_percent(b)
# a = _conv_alpha(a)
# return r, g, b, a
#
# # hsl(h, s, l)
# m = _re_hsl.match(col)
# if m:
# h, s, l = m.groups()
# h = _conv_hue(h)
# s = _conv_percent(s)
# l = _conv_percent(l)
# r, g, b = colorsys.hls_to_rgb(h, l, s)
# return r, g, b, a
#
# # hsla(h, s, l, a)
# m = _re_hsla.match(col)
# if m:
# h, s, l, a = m.groups()
# h = _conv_hue(h)
# s = _conv_percent(s)
# l = _conv_percent(l)
# a = _conv_alpha(a)
# r, g, b = colorsys.hls_to_rgb(h, l, s)
# return r, g, b, a
#
# raise ValueError, ('Invalid color: %s' % col)
#
# def rgba_to_color(r, g, b, a, format='rgba'):
# r = min(max(r, 0), 1)
# g = min(max(g, 0), 1)
# b = min(max(b, 0), 1)
# a = min(max(a, 0), 1)
#
# if format == 'hex':
# return '#%02x%02x%02x' % (r * 255 + .5, g * 255 + .5, b * 255 + .5)
#
# if format == 'rgb':
# return 'rgb(%.0f, %.0f, %.0f)' % (r * 255, g * 255, b * 255)
#
# if format == 'rgba':
# return 'rgba(%.0f, %.0f, %.0f, %.3f)' % (r * 255, g * 255, b * 255, a)
#
# if format == 'rgb_p':
# return 'rgb(%.0f%%, %.0f%%, %.0f%%)' % (r * 100, g * 100, b * 100)
#
# if format == 'rgba_p':
# return ('rgba(%.0f%%, %.0f%%, %.0f%%, %.3f)'
# % (r * 100, g * 100, b * 100, a))
#
# if format == 'hsl':
# h, l, s = colorsys.rgb_to_hls(r, g, b)
# return 'hsl(%.0f, %.0f%%, %.0f%%)' % (h * 360, s * 100, l * 100)
#
# if format == 'hsla':
# h, l, s = colorsys.rgb_to_hls(r, g, b)
# return ('hsla(%.0f, %.0f%%, %.0f%%, %.3f)'
# % (h * 360, s * 100, l * 100, a))
#
# raise ValueError, 'Invalid color format: %s' % format
. Output only the next line. | self.assertEquals('#112233', c)
|
Given the code snippet: <|code_start|> numSides 6
strokeWidth 3
textPadX 15
textPadY 15
[connection]
style curve
[color]
style cycle
colorscheme "mint-examples"
"""
config3 = r"""
[layout]
style layout
[node]
style poly
fontName $FONTNAME
fontSize $FONTSIZE
textBaselineCorrection $BASELINE_CORR
numSides 8
strokeWidth 6
textPadX 15
textPadY 15
[connection]
style curve
<|code_end|>
, generate the next line using the imports in this file:
import os, sys
from fig import *
from twyg.cairowrapper import context as ctx
and context (functions, classes, or occasionally code) from other files:
# Path: twyg/cairowrapper.py
# class Color(object):
# class Context(object):
# def __init__(self, c1, c2, c3, a, mode='rgb'):
# def __repr__(self):
# def copy(self):
# def rgba(self):
# def darken(self, step=0.1):
# def lighten(self, step=0.1):
# def blend(self, clr, factor=0.5):
# def _update_hsv(self):
# def _update_rgb(self):
# def color(*args):
# def __init__(self):
# def init():
# def rect(self, x, y, width, height, roundness=0.0, draw=True):
# def oval(self, x, y, width, height, draw=True):
# def line(self, x1, y1, x2, y2, draw=True):
# def arrow(x, y, width, type, draw=True):
# def star(x, y, points=20, outer=100, inner=50, draw=True):
# def beginpath(self, x, y):
# def moveto(self, x, y):
# def lineto(self, x, y):
# def curveto(self, x1, y1, x2, y2, x3, y3):
# def findpath(list, curvature=1.0):
# def endpath(self, draw=True):
# def drawpath(self, path):
# def beginclip(self, path):
# def endclip(self):
# def autoclosepath(self, close=True):
# def transform(mode):
# def translate(self, x, y):
# def rotate(self, degrees=0.0, radians=0.0):
# def scale(self, x, y=None):
# def skew(x, y=None):
# def push(self):
# def pop(self):
# def reset(self):
# def outputmode(self, mode):
# def colormode(self, mode):
# def color(self, *args):
# def fill(self, *args):
# def nofill(self):
# def stroke(self, *args):
# def nostroke(self):
# def strokewidth(self, width):
# def background(self, *args):
# def font(self, fontname, fontsize=None):
# def fontsize(self, fontsize):
# def text(self, txt, x, y):
# def textpath(txt, x, y, width=None, height=1000000):
# def textwidth(self, txt):
# def textheight(self, txt):
# def textmetrics(self, txt):
# def lineheight(self, height=None):
# def align(self, align):
# def image(path, x, y, width=None, height=None, alpha=1.0, data=None):
# def imagesize(path):
# def size(w, h):
# def var(name, type, default, min, max):
# def random(v1=None, v2=None):
# def choice(list):
# def grid(cols, rows, colsize=1, rowsize=1):
# def files(path):
# def autotext(xml):
# def rgba_color(self, c):
# def gradientfill(self, path, clr1, clr2, dx=0.0, dy=0.0,
# type='linear',spread=1.0):
# def shadow(self, dx=0.0, dy=0.0, blur=3.0, clr=color(0, 0, 0, 1)):
# def noshadow(self):
# def initsurface(self, w, h, fmt, fname=None, scale=1.0):
# def writesurface(self):
# def _make_color_obj(self, *args):
# def _draw_stroke(self):
# def _draw(self):
# def _draw_shadow(self):
# def _render_bitmap_shadow(self):
. Output only the next line. | [color] |
Next line prediction: <|code_start|>
class Layout(object):
def __init__(self, config):
properties = {
'horizontalBalance': (NumberProperty, {}),
'verticalAlignFactor': (NumberProperty, {'min': 0.0,
<|code_end|>
. Use current file imports:
(import math, os, sys
from twyg.config import Properties, NumberProperty, BooleanProperty
from twyg.tree import Direction, opposite_dir
from twyg.geomutils import halfcircle
)
and context including class names, function names, or small code snippets from other files:
# Path: twyg/config.py
# class Properties(object):
# """ Class for managing configuration properties. """
#
# def __init__(self, properties, defaults, config, extra_prop_warning=True):
# """
# Load and parse the default config file ``default`` and merge it
# with the configuration ``config`` (defaults will be
# overwritten).
#
# The ``properties`` dict contains the list of allowed properties
# where the key is the name of the property and the value a
# two-element tuple of which the first element is the class of the
# property and the second element the property's extra parameters
# (note that some property types have mandatory extra parameters,
# e.g. ArrayProperty). For example:
#
# {
# 'fontName': (StringProperty, {}),
# 'fontSizes': (ArrayProperty, {'type': NumberProperty})
# }
#
# Warn on property names that are not listed in the ``properties``
# dict if ``extra_prop_warning`` is True.
# """
#
# c = loaddefaults(defaults)
# c.update(config)
# config = c
#
# # Build properties dictionary
# self._properties = {}
# for name, prop_params in properties.iteritems():
# # The first parameter is the property class, the second the
# # optional constructor parameters
# prop_class, opts = prop_params
# self._properties[name] = prop_class(name, **opts)
#
# for name, prop in self._properties.iteritems():
# if name not in config:
# raise ConfigError("Missing property: '%s'" % name)
# e = parse_expr(config[name])
# # print '>>>', name, ':', e
# prop.expr = e
# prop.name = name
#
# if extra_prop_warning:
# self._warn_extra_props(config)
#
# def _warn_extra_props(self, config):
# extra_props = set(config.keys()) - set(self._properties.keys())
# for p in extra_props:
# token = config[p][0]
# #TODO make displaying warnings optional? print to stdout?
# print >>sys.stderr, (
# "Warning: Unknown property '%s' in configuration "
# "file '%s' on line %s" % (p, token.file, token.line))
#
# def eval(self, name, scope=None, vars={}):
# """ Evaluate the value of a property.
#
# ``name`` is the name of the property, ``scope`` the object in
# whose context the property is to be evaluated and ``vars``
# contains a dict of variable name and value pairs that will be
# injected into the evaluation scope.
# """
#
# if name not in self._properties:
# # TODO more detailed error message
# raise AttributeError("Property '%s' does not exist" % name)
#
# p = self._properties[name]
# if scope:
# for propname, varname in scope.property_mappings.iteritems():
# if hasattr(scope, propname):
# vars[varname] = getattr(scope, propname)
# # TODO triggered by 'basecolor' -- why?
# # else:
# # raise ConfigError("Variable '%s' is not evaluated "
# # "at this point" % (varname))
#
# return p.eval(vars)
#
# class NumberProperty(Property):
# def __init__(self, name, min=None, max=None):
# super(NumberProperty, self).__init__(name)
# self.min = min
# self.max = max
#
# def _validate(self):
# if type(self.value) not in (int, float):
# raise ConfigError("Property '%s' must evaluate to a number"
# % self.name, self.expr)
#
# if self.min and self.value < self.min:
# raise ConfigError(
# "Number property '%s' must have a value greater "
# "than %s" % (self.name, self.min), self.expr)
#
# if self.max and self.value > self.max:
# raise ConfigError("Number property '%s' must have a value less "
# "than %s" % (self.name, self.max), self.expr)
#
# class BooleanProperty(Property):
# def eval(self, vars):
# vars = {'no': 0, 'off': 0, 'false': 0, 'yes': 1, 'on': 1, 'true': 1}
# n = eval_expr(self.expr, vars)
#
# if type(n) not in (int, float):
# raise ConfigError(
# ("Boolean property '%s' must evaluate to a numeric value"
# % self.name), self.expr)
#
# self.value = True if n > 0.0 else False
# return self.value
#
# Path: twyg/tree.py
# class Direction(object):
# Top, Right, Bottom, Left = range(4)
#
# def opposite_dir(d):
# if d == Direction.Bottom:
# return Direction.Top
# if d == Direction.Right:
# return Direction.Left
# if d == Direction.Top:
# return Direction.Bottom
# if d == Direction.Left:
# return Direction.Right
# else:
# raise ValueError, 'Invalid direction: %s' % d
#
# Path: twyg/geomutils.py
# def halfcircle(cx, y1, y2, rfactor, dir, y):
# dir = -dir
# dy = float(y2 - y1)
# r = dy / 2
# cy = (y1 + y2) / 2.
# r *= rfactor
# xcorr = dir * math.sqrt(r * r - pow(y1 - cy, 2))
# return cx - dir * math.sqrt(r * r - pow(y - cy, 2)) + xcorr
. Output only the next line. | 'max': 1.0}),
|
Predict the next line for this snippet: <|code_start|>
sys.path.append(os.path.join('..'))
deg = math.degrees
rad = math.radians
class TestEvalExpr(unittest.TestCase):
def assert_equals(self, a, b):
self.assertTrue(abs(a - b) < 1e-12)
def test_constructor_cartesian1(self):
v = Vector2(3, -4)
self.assert_equals(5, v.m)
self.assert_equals(53.13010235415598, deg(v.a))
def test_constructor_cartesian2(self):
v = Vector2(4, -4)
self.assert_equals(5.6568542494923806, v.m)
self.assert_equals(45.0, deg(v.a))
<|code_end|>
with the help of current file imports:
import math, os, sys, unittest
from twyg.geom import Vector2
and context from other files:
# Path: twyg/geom.py
# class Vector2(object):
# """ Class representing two-dimensional vectors.
#
# The coordinate system used has the following properties:
# - the origo (0,0) is located in the top left corner
# - the positive x direction is from left to right
# - the positive y direction is from top to bottom
# - positive rotation is counter-clockwise
# """
# def __init__(self, *args, **kwargs):
# if args:
# if isinstance(args[0], Vector2):
# self.x = float(args[0].x)
# self.y = float(args[0].y)
# return
# elif len(args) < 2:
# raise ValueError, "Must specify 'x' and 'y' of new vector"
# self.x = float(args[0])
# self.y = float(args[1])
# else:
# if not ('m' in kwargs and 'angle' in kwargs):
# raise ValueError, "Must specify 'm' and 'angle' of new vector"
# m = kwargs['m']
# a = -kwargs['angle']
# self.x = m * math.cos(a)
# self.y = m * math.sin(a)
#
# def __repr__(self):
# return '(%s, %s)' % (self.x, self.y)
#
# def magnitude(self):
# return math.sqrt(self.x * self.x + self.y * self.y)
#
# m = property(magnitude)
#
# def angle(self):
# a = -math.atan2(self.y, self.x)
# if a < 0:
# a += math.pi * 2
# return a
#
# a = property(angle)
#
# def normalize(self):
# m = self.magnitude()
# if m != 0:
# self.x /= m
# self.y /= m
# return self
#
# def rotate(self, angle):
# angle = -angle
# cos = math.cos(angle)
# sin = math.sin(angle)
# x = self.x * cos - self.y * sin
# y = self.x * sin + self.y * cos
# self.x = x
# self.y = y
# return self
#
# def __add__(self, s):
# return Vector2(self.x + s.x, self.y + s.y)
#
# def __iadd__(self, s):
# self.x += s.x
# self.y += s.y
# return self
#
# def __sub__(self, s):
# return Vector2(self.x - s.x, self.y - s.y)
#
# def __isub__(self, s):
# self.x -= s.x
# self.y -= s.y
# return self
#
# def __mul__(self, s):
# return Vector2(self.x * s, self.y * s)
#
# def __rmul__(self, s):
# return Vector2(self.x * s, self.y * s)
#
# def __imul__(self, s):
# self.x *= s
# self.y *= s
# return self
#
# def __div__(self, s):
# return Vector2(self.x / s, self.y / s)
#
# def __idiv__(self, s):
# self.x /= s
# self.y /= s
# return self
, which may contain function names, class names, or code. Output only the next line. | def test_normalize(self):
|
Here is a snippet: <|code_start|>ctx.fill(c)
ctx.rect(x, y, w, h)
x += w + padx
c = c.blend(white, f)
ctx.fill(c)
ctx.rect(x, y, w, h)
y += h + pady
x = xo
ctx.fill(textcol)
ctx.text('darken', 84, y + 36)
c = col2
ctx.fill(c)
ctx.rect(x, y, w, h)
x += w + padx
c = c.darken(f)
ctx.fill(c)
ctx.rect(x, y, w, h)
x += w + padx
c = c.darken(f)
ctx.fill(c)
ctx.rect(x, y, w, h)
<|code_end|>
. Write the next line using the current file imports:
import os, sys
from fig import *
from twyg.cairowrapper import context as ctx
and context from other files:
# Path: twyg/cairowrapper.py
# class Color(object):
# class Context(object):
# def __init__(self, c1, c2, c3, a, mode='rgb'):
# def __repr__(self):
# def copy(self):
# def rgba(self):
# def darken(self, step=0.1):
# def lighten(self, step=0.1):
# def blend(self, clr, factor=0.5):
# def _update_hsv(self):
# def _update_rgb(self):
# def color(*args):
# def __init__(self):
# def init():
# def rect(self, x, y, width, height, roundness=0.0, draw=True):
# def oval(self, x, y, width, height, draw=True):
# def line(self, x1, y1, x2, y2, draw=True):
# def arrow(x, y, width, type, draw=True):
# def star(x, y, points=20, outer=100, inner=50, draw=True):
# def beginpath(self, x, y):
# def moveto(self, x, y):
# def lineto(self, x, y):
# def curveto(self, x1, y1, x2, y2, x3, y3):
# def findpath(list, curvature=1.0):
# def endpath(self, draw=True):
# def drawpath(self, path):
# def beginclip(self, path):
# def endclip(self):
# def autoclosepath(self, close=True):
# def transform(mode):
# def translate(self, x, y):
# def rotate(self, degrees=0.0, radians=0.0):
# def scale(self, x, y=None):
# def skew(x, y=None):
# def push(self):
# def pop(self):
# def reset(self):
# def outputmode(self, mode):
# def colormode(self, mode):
# def color(self, *args):
# def fill(self, *args):
# def nofill(self):
# def stroke(self, *args):
# def nostroke(self):
# def strokewidth(self, width):
# def background(self, *args):
# def font(self, fontname, fontsize=None):
# def fontsize(self, fontsize):
# def text(self, txt, x, y):
# def textpath(txt, x, y, width=None, height=1000000):
# def textwidth(self, txt):
# def textheight(self, txt):
# def textmetrics(self, txt):
# def lineheight(self, height=None):
# def align(self, align):
# def image(path, x, y, width=None, height=None, alpha=1.0, data=None):
# def imagesize(path):
# def size(w, h):
# def var(name, type, default, min, max):
# def random(v1=None, v2=None):
# def choice(list):
# def grid(cols, rows, colsize=1, rowsize=1):
# def files(path):
# def autotext(xml):
# def rgba_color(self, c):
# def gradientfill(self, path, clr1, clr2, dx=0.0, dy=0.0,
# type='linear',spread=1.0):
# def shadow(self, dx=0.0, dy=0.0, blur=3.0, clr=color(0, 0, 0, 1)):
# def noshadow(self):
# def initsurface(self, w, h, fmt, fname=None, scale=1.0):
# def writesurface(self):
# def _make_color_obj(self, *args):
# def _draw_stroke(self):
# def _draw(self):
# def _draw_shadow(self):
# def _render_bitmap_shadow(self):
, which may include functions, classes, or code. Output only the next line. | x += w + padx |
Given the code snippet: <|code_start|>COLOR_CONFIG = 'color'
##############################################################################
# Properties
##############################################################################
class Property(object):
def __init__(self, name):
self.name = name
def eval(self, vars):
self.value = eval_expr(self.expr, vars)
self._validate()
return self.value
class StringProperty(Property):
def _validate(self):
if type(self.value) not in (str, unicode):
raise ConfigError("Property '%s' must evaluate to a string"
% self.name, self.expr[0])
class NumberProperty(Property):
def __init__(self, name, min=None, max=None):
super(NumberProperty, self).__init__(name)
self.min = min
self.max = max
<|code_end|>
, generate the next line using the imports in this file:
import math, os, re, sys
import operator as _operator
import twyg.common
from pkg_resources import resource_filename
from collections import OrderedDict
from twyg.ordereddict import OrderedDict
from twyg.css3colors import color_to_rgba, colornames
from twyg.tree import Direction
and context (functions, classes, or occasionally code) from other files:
# Path: twyg/css3colors.py
# def _parse_hex(col):
# def _conv_rgb(c):
# def _conv_percent(p):
# def _conv_alpha(a):
# def _conv_hue(h):
# def color_to_rgba(col):
# def rgba_to_color(r, g, b, a, format='rgba'):
#
# Path: twyg/tree.py
# class Direction(object):
# Top, Right, Bottom, Left = range(4)
. Output only the next line. | def _validate(self): |
Predict the next line after this snippet: <|code_start|>
class ColorProperty(Property):
def _validate(self):
if type(self.value).__name__ != 'Color':
raise ConfigError("Property '%s' must evaluate to a color"
% self.name, self.expr)
class EnumProperty(Property):
def __init__(self, name, values):
super(EnumProperty, self).__init__(name)
self.values = values
def eval(self, vars):
enumvars = {}
for value, name in enumerate(self.values):
enumvars[name] = value
vars.update(enumvars)
n = eval_expr(self.expr, vars)
if type(n) not in (int, float):
raise ConfigError(
("Enum property '%s' must evaluate to a numeric value"
% self.name), self.expr)
n = int(round(n))
if n < 0 or n >= len(self.values):
raise ConfigError(
("Enum property '%s' evaluated to an invalid "
<|code_end|>
using the current file's imports:
import math, os, re, sys
import operator as _operator
import twyg.common
from pkg_resources import resource_filename
from collections import OrderedDict
from twyg.ordereddict import OrderedDict
from twyg.css3colors import color_to_rgba, colornames
from twyg.tree import Direction
and any relevant context from other files:
# Path: twyg/css3colors.py
# def _parse_hex(col):
# def _conv_rgb(c):
# def _conv_percent(p):
# def _conv_alpha(a):
# def _conv_hue(h):
# def color_to_rgba(col):
# def rgba_to_color(r, g, b, a, format='rgba'):
#
# Path: twyg/tree.py
# class Direction(object):
# Top, Right, Bottom, Left = range(4)
. Output only the next line. | "numeric value: %s" % (self.name, n)), self.expr) |
Predict the next line for this snippet: <|code_start|> textPadX 14
textPadY 14
[connection]
style curve
[color]
style cycle
colorscheme "mint-examples"
"""
config2 = r"""
[layout]
style layout
[node]
style oval
fontName $FONTNAME
fontSize $FONTSIZE
textBaselineCorrection $BASELINE_CORR
strokeWidth 3
aspectRatio .7
textPadX 8
textPadY 8
[connection]
style curve
[color]
style cycle
<|code_end|>
with the help of current file imports:
import os, sys
from fig import *
from twyg.cairowrapper import context as ctx
and context from other files:
# Path: twyg/cairowrapper.py
# class Color(object):
# class Context(object):
# def __init__(self, c1, c2, c3, a, mode='rgb'):
# def __repr__(self):
# def copy(self):
# def rgba(self):
# def darken(self, step=0.1):
# def lighten(self, step=0.1):
# def blend(self, clr, factor=0.5):
# def _update_hsv(self):
# def _update_rgb(self):
# def color(*args):
# def __init__(self):
# def init():
# def rect(self, x, y, width, height, roundness=0.0, draw=True):
# def oval(self, x, y, width, height, draw=True):
# def line(self, x1, y1, x2, y2, draw=True):
# def arrow(x, y, width, type, draw=True):
# def star(x, y, points=20, outer=100, inner=50, draw=True):
# def beginpath(self, x, y):
# def moveto(self, x, y):
# def lineto(self, x, y):
# def curveto(self, x1, y1, x2, y2, x3, y3):
# def findpath(list, curvature=1.0):
# def endpath(self, draw=True):
# def drawpath(self, path):
# def beginclip(self, path):
# def endclip(self):
# def autoclosepath(self, close=True):
# def transform(mode):
# def translate(self, x, y):
# def rotate(self, degrees=0.0, radians=0.0):
# def scale(self, x, y=None):
# def skew(x, y=None):
# def push(self):
# def pop(self):
# def reset(self):
# def outputmode(self, mode):
# def colormode(self, mode):
# def color(self, *args):
# def fill(self, *args):
# def nofill(self):
# def stroke(self, *args):
# def nostroke(self):
# def strokewidth(self, width):
# def background(self, *args):
# def font(self, fontname, fontsize=None):
# def fontsize(self, fontsize):
# def text(self, txt, x, y):
# def textpath(txt, x, y, width=None, height=1000000):
# def textwidth(self, txt):
# def textheight(self, txt):
# def textmetrics(self, txt):
# def lineheight(self, height=None):
# def align(self, align):
# def image(path, x, y, width=None, height=None, alpha=1.0, data=None):
# def imagesize(path):
# def size(w, h):
# def var(name, type, default, min, max):
# def random(v1=None, v2=None):
# def choice(list):
# def grid(cols, rows, colsize=1, rowsize=1):
# def files(path):
# def autotext(xml):
# def rgba_color(self, c):
# def gradientfill(self, path, clr1, clr2, dx=0.0, dy=0.0,
# type='linear',spread=1.0):
# def shadow(self, dx=0.0, dy=0.0, blur=3.0, clr=color(0, 0, 0, 1)):
# def noshadow(self):
# def initsurface(self, w, h, fmt, fname=None, scale=1.0):
# def writesurface(self):
# def _make_color_obj(self, *args):
# def _draw_stroke(self):
# def _draw(self):
# def _draw_shadow(self):
# def _render_bitmap_shadow(self):
, which may contain function names, class names, or code. Output only the next line. | colorscheme "mint-examples3" |
Given snippet: <|code_start|>
def drawconn(ctx, linewidth_start, linewidth_end, x1, y1, x2, y2,
cx1, cx2, cy1, cy2):
ctx.strokewidth(linewidth_end)
x2 -= linewidth_end / 2
cx1 = (x2 - x1) * cx1
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os, sys
from fig import *
from twyg.cairowrapper import context as ctx
and context:
# Path: twyg/cairowrapper.py
# class Color(object):
# class Context(object):
# def __init__(self, c1, c2, c3, a, mode='rgb'):
# def __repr__(self):
# def copy(self):
# def rgba(self):
# def darken(self, step=0.1):
# def lighten(self, step=0.1):
# def blend(self, clr, factor=0.5):
# def _update_hsv(self):
# def _update_rgb(self):
# def color(*args):
# def __init__(self):
# def init():
# def rect(self, x, y, width, height, roundness=0.0, draw=True):
# def oval(self, x, y, width, height, draw=True):
# def line(self, x1, y1, x2, y2, draw=True):
# def arrow(x, y, width, type, draw=True):
# def star(x, y, points=20, outer=100, inner=50, draw=True):
# def beginpath(self, x, y):
# def moveto(self, x, y):
# def lineto(self, x, y):
# def curveto(self, x1, y1, x2, y2, x3, y3):
# def findpath(list, curvature=1.0):
# def endpath(self, draw=True):
# def drawpath(self, path):
# def beginclip(self, path):
# def endclip(self):
# def autoclosepath(self, close=True):
# def transform(mode):
# def translate(self, x, y):
# def rotate(self, degrees=0.0, radians=0.0):
# def scale(self, x, y=None):
# def skew(x, y=None):
# def push(self):
# def pop(self):
# def reset(self):
# def outputmode(self, mode):
# def colormode(self, mode):
# def color(self, *args):
# def fill(self, *args):
# def nofill(self):
# def stroke(self, *args):
# def nostroke(self):
# def strokewidth(self, width):
# def background(self, *args):
# def font(self, fontname, fontsize=None):
# def fontsize(self, fontsize):
# def text(self, txt, x, y):
# def textpath(txt, x, y, width=None, height=1000000):
# def textwidth(self, txt):
# def textheight(self, txt):
# def textmetrics(self, txt):
# def lineheight(self, height=None):
# def align(self, align):
# def image(path, x, y, width=None, height=None, alpha=1.0, data=None):
# def imagesize(path):
# def size(w, h):
# def var(name, type, default, min, max):
# def random(v1=None, v2=None):
# def choice(list):
# def grid(cols, rows, colsize=1, rowsize=1):
# def files(path):
# def autotext(xml):
# def rgba_color(self, c):
# def gradientfill(self, path, clr1, clr2, dx=0.0, dy=0.0,
# type='linear',spread=1.0):
# def shadow(self, dx=0.0, dy=0.0, blur=3.0, clr=color(0, 0, 0, 1)):
# def noshadow(self):
# def initsurface(self, w, h, fmt, fname=None, scale=1.0):
# def writesurface(self):
# def _make_color_obj(self, *args):
# def _draw_stroke(self):
# def _draw(self):
# def _draw_shadow(self):
# def _render_bitmap_shadow(self):
which might include code, classes, or functions. Output only the next line. | cx2 = (x2 - x1) * cx2 |
Given the following code snippet before the placeholder: <|code_start|>
config1 = r"""
[layout]
style layout
horizontalBalance 0
rootPadX 110
nodePadY 10
radialMinNodes 1000
sameWidthSiblings no
snapParentToChildren yes
[node]
style rect
fontName $FONTNAME
fontSize $FONTSIZE
textBaselineCorrection $BASELINE_CORR
strokeWidth 3
roundness 1.0
roundingStyle arc
cornerRadius 7
textPadX 15
textPadY 5
<|code_end|>
, predict the next line using imports from the current file:
import os, sys
from fig import *
from twyg.cairowrapper import context as ctx
and context including class names, function names, and sometimes code from other files:
# Path: twyg/cairowrapper.py
# class Color(object):
# class Context(object):
# def __init__(self, c1, c2, c3, a, mode='rgb'):
# def __repr__(self):
# def copy(self):
# def rgba(self):
# def darken(self, step=0.1):
# def lighten(self, step=0.1):
# def blend(self, clr, factor=0.5):
# def _update_hsv(self):
# def _update_rgb(self):
# def color(*args):
# def __init__(self):
# def init():
# def rect(self, x, y, width, height, roundness=0.0, draw=True):
# def oval(self, x, y, width, height, draw=True):
# def line(self, x1, y1, x2, y2, draw=True):
# def arrow(x, y, width, type, draw=True):
# def star(x, y, points=20, outer=100, inner=50, draw=True):
# def beginpath(self, x, y):
# def moveto(self, x, y):
# def lineto(self, x, y):
# def curveto(self, x1, y1, x2, y2, x3, y3):
# def findpath(list, curvature=1.0):
# def endpath(self, draw=True):
# def drawpath(self, path):
# def beginclip(self, path):
# def endclip(self):
# def autoclosepath(self, close=True):
# def transform(mode):
# def translate(self, x, y):
# def rotate(self, degrees=0.0, radians=0.0):
# def scale(self, x, y=None):
# def skew(x, y=None):
# def push(self):
# def pop(self):
# def reset(self):
# def outputmode(self, mode):
# def colormode(self, mode):
# def color(self, *args):
# def fill(self, *args):
# def nofill(self):
# def stroke(self, *args):
# def nostroke(self):
# def strokewidth(self, width):
# def background(self, *args):
# def font(self, fontname, fontsize=None):
# def fontsize(self, fontsize):
# def text(self, txt, x, y):
# def textpath(txt, x, y, width=None, height=1000000):
# def textwidth(self, txt):
# def textheight(self, txt):
# def textmetrics(self, txt):
# def lineheight(self, height=None):
# def align(self, align):
# def image(path, x, y, width=None, height=None, alpha=1.0, data=None):
# def imagesize(path):
# def size(w, h):
# def var(name, type, default, min, max):
# def random(v1=None, v2=None):
# def choice(list):
# def grid(cols, rows, colsize=1, rowsize=1):
# def files(path):
# def autotext(xml):
# def rgba_color(self, c):
# def gradientfill(self, path, clr1, clr2, dx=0.0, dy=0.0,
# type='linear',spread=1.0):
# def shadow(self, dx=0.0, dy=0.0, blur=3.0, clr=color(0, 0, 0, 1)):
# def noshadow(self):
# def initsurface(self, w, h, fmt, fname=None, scale=1.0):
# def writesurface(self):
# def _make_color_obj(self, *args):
# def _draw_stroke(self):
# def _draw(self):
# def _draw_shadow(self):
# def _render_bitmap_shadow(self):
. Output only the next line. | [connection] |
Predict the next line after this snippet: <|code_start|>
config1 = r"""
[layout]
style layout
[node]
style rect
fontName $FONTNAME
fontSize $FONTSIZE
textBaselineCorrection $BASELINE_CORR
strokeWidth 3
roundness 0
[connection]
style curve
[color]
style cycle
colorscheme "mint-examples"
fontColorAuto no
fontColor #fff
"""
config2 = r"""
[layout]
<|code_end|>
using the current file's imports:
import os, sys
from fig import *
from twyg.cairowrapper import context as ctx
and any relevant context from other files:
# Path: twyg/cairowrapper.py
# class Color(object):
# class Context(object):
# def __init__(self, c1, c2, c3, a, mode='rgb'):
# def __repr__(self):
# def copy(self):
# def rgba(self):
# def darken(self, step=0.1):
# def lighten(self, step=0.1):
# def blend(self, clr, factor=0.5):
# def _update_hsv(self):
# def _update_rgb(self):
# def color(*args):
# def __init__(self):
# def init():
# def rect(self, x, y, width, height, roundness=0.0, draw=True):
# def oval(self, x, y, width, height, draw=True):
# def line(self, x1, y1, x2, y2, draw=True):
# def arrow(x, y, width, type, draw=True):
# def star(x, y, points=20, outer=100, inner=50, draw=True):
# def beginpath(self, x, y):
# def moveto(self, x, y):
# def lineto(self, x, y):
# def curveto(self, x1, y1, x2, y2, x3, y3):
# def findpath(list, curvature=1.0):
# def endpath(self, draw=True):
# def drawpath(self, path):
# def beginclip(self, path):
# def endclip(self):
# def autoclosepath(self, close=True):
# def transform(mode):
# def translate(self, x, y):
# def rotate(self, degrees=0.0, radians=0.0):
# def scale(self, x, y=None):
# def skew(x, y=None):
# def push(self):
# def pop(self):
# def reset(self):
# def outputmode(self, mode):
# def colormode(self, mode):
# def color(self, *args):
# def fill(self, *args):
# def nofill(self):
# def stroke(self, *args):
# def nostroke(self):
# def strokewidth(self, width):
# def background(self, *args):
# def font(self, fontname, fontsize=None):
# def fontsize(self, fontsize):
# def text(self, txt, x, y):
# def textpath(txt, x, y, width=None, height=1000000):
# def textwidth(self, txt):
# def textheight(self, txt):
# def textmetrics(self, txt):
# def lineheight(self, height=None):
# def align(self, align):
# def image(path, x, y, width=None, height=None, alpha=1.0, data=None):
# def imagesize(path):
# def size(w, h):
# def var(name, type, default, min, max):
# def random(v1=None, v2=None):
# def choice(list):
# def grid(cols, rows, colsize=1, rowsize=1):
# def files(path):
# def autotext(xml):
# def rgba_color(self, c):
# def gradientfill(self, path, clr1, clr2, dx=0.0, dy=0.0,
# type='linear',spread=1.0):
# def shadow(self, dx=0.0, dy=0.0, blur=3.0, clr=color(0, 0, 0, 1)):
# def noshadow(self):
# def initsurface(self, w, h, fmt, fname=None, scale=1.0):
# def writesurface(self):
# def _make_color_obj(self, *args):
# def _draw_stroke(self):
# def _draw(self):
# def _draw_shadow(self):
# def _render_bitmap_shadow(self):
. Output only the next line. | style layout |
Given the following code snippet before the placeholder: <|code_start|>
config1 = r"""
[layout]
style layout
[node]
style line
fontName $FONTNAME
fontSize $FONTSIZE
textBaselineCorrection $BASELINE_CORR
strokeWidth 4
[connection]
style curve
<|code_end|>
, predict the next line using imports from the current file:
import os, sys
from fig import *
from twyg.cairowrapper import context as ctx
and context including class names, function names, and sometimes code from other files:
# Path: twyg/cairowrapper.py
# class Color(object):
# class Context(object):
# def __init__(self, c1, c2, c3, a, mode='rgb'):
# def __repr__(self):
# def copy(self):
# def rgba(self):
# def darken(self, step=0.1):
# def lighten(self, step=0.1):
# def blend(self, clr, factor=0.5):
# def _update_hsv(self):
# def _update_rgb(self):
# def color(*args):
# def __init__(self):
# def init():
# def rect(self, x, y, width, height, roundness=0.0, draw=True):
# def oval(self, x, y, width, height, draw=True):
# def line(self, x1, y1, x2, y2, draw=True):
# def arrow(x, y, width, type, draw=True):
# def star(x, y, points=20, outer=100, inner=50, draw=True):
# def beginpath(self, x, y):
# def moveto(self, x, y):
# def lineto(self, x, y):
# def curveto(self, x1, y1, x2, y2, x3, y3):
# def findpath(list, curvature=1.0):
# def endpath(self, draw=True):
# def drawpath(self, path):
# def beginclip(self, path):
# def endclip(self):
# def autoclosepath(self, close=True):
# def transform(mode):
# def translate(self, x, y):
# def rotate(self, degrees=0.0, radians=0.0):
# def scale(self, x, y=None):
# def skew(x, y=None):
# def push(self):
# def pop(self):
# def reset(self):
# def outputmode(self, mode):
# def colormode(self, mode):
# def color(self, *args):
# def fill(self, *args):
# def nofill(self):
# def stroke(self, *args):
# def nostroke(self):
# def strokewidth(self, width):
# def background(self, *args):
# def font(self, fontname, fontsize=None):
# def fontsize(self, fontsize):
# def text(self, txt, x, y):
# def textpath(txt, x, y, width=None, height=1000000):
# def textwidth(self, txt):
# def textheight(self, txt):
# def textmetrics(self, txt):
# def lineheight(self, height=None):
# def align(self, align):
# def image(path, x, y, width=None, height=None, alpha=1.0, data=None):
# def imagesize(path):
# def size(w, h):
# def var(name, type, default, min, max):
# def random(v1=None, v2=None):
# def choice(list):
# def grid(cols, rows, colsize=1, rowsize=1):
# def files(path):
# def autotext(xml):
# def rgba_color(self, c):
# def gradientfill(self, path, clr1, clr2, dx=0.0, dy=0.0,
# type='linear',spread=1.0):
# def shadow(self, dx=0.0, dy=0.0, blur=3.0, clr=color(0, 0, 0, 1)):
# def noshadow(self):
# def initsurface(self, w, h, fmt, fname=None, scale=1.0):
# def writesurface(self):
# def _make_color_obj(self, *args):
# def _draw_stroke(self):
# def _draw(self):
# def _draw_shadow(self):
# def _render_bitmap_shadow(self):
. Output only the next line. | [color] |
Predict the next line for this snippet: <|code_start|># Copyright (C) 2007 Giampaolo Rodola' <g.rodola@gmail.com>.
# Use of this source code is governed by MIT license that can be
# found in the LICENSE file.
try:
except ImportError:
try:
except ImportError:
pwd = grp = None
try:
except ImportError:
try:
except ImportError:
scandir = None
__all__ = ['FilesystemError', 'AbstractedFS']
_months_map = {1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr', 5: 'May', 6: 'Jun',
7: 'Jul', 8: 'Aug', 9: 'Sep', 10: 'Oct', 11: 'Nov', 12: 'Dec'}
<|code_end|>
with the help of current file imports:
import os
import stat
import tempfile
import time
import grp
import pwd
from stat import filemode as _filemode # PY 3.3
from tarfile import filemode as _filemode
from os import scandir # py 3.5
from scandir import scandir # requires "pip install scandir"
from ._compat import PY3
from ._compat import u
from ._compat import unicode
and context from other files:
# Path: pyftpdlib/_compat.py
# PY3 = sys.version_info[0] == 3
#
# Path: pyftpdlib/_compat.py
# def u(s):
# return s
#
# Path: pyftpdlib/_compat.py
# PY3 = sys.version_info[0] == 3
# _SENTINEL = object()
# def u(s):
# def b(s):
# def u(s):
# def b(s):
# def callable(obj):
# def _instance_checking_exception(base_exception=Exception):
# def wrapped(instance_checker):
# def __init__(self, *args, **kwargs):
# def __instancecheck__(cls, inst):
# def __subclasscheck__(cls, classinfo):
# def FileNotFoundError(inst):
# def FileExistsError(inst):
# def super(type_=_SENTINEL, type_or_obj=_SENTINEL, framedepth=1):
# class TemporaryClass(base_exception):
# class __metaclass__(type):
, which may contain function names, class names, or code. Output only the next line. | def _memoize(fun): |
Predict the next line after this snippet: <|code_start|># Copyright (C) 2007 Giampaolo Rodola' <g.rodola@gmail.com>.
# Use of this source code is governed by MIT license that can be
# found in the LICENSE file.
try:
except ImportError:
try:
except ImportError:
pwd = grp = None
<|code_end|>
using the current file's imports:
import os
import stat
import tempfile
import time
import grp
import pwd
from stat import filemode as _filemode # PY 3.3
from tarfile import filemode as _filemode
from os import scandir # py 3.5
from scandir import scandir # requires "pip install scandir"
from ._compat import PY3
from ._compat import u
from ._compat import unicode
and any relevant context from other files:
# Path: pyftpdlib/_compat.py
# PY3 = sys.version_info[0] == 3
#
# Path: pyftpdlib/_compat.py
# def u(s):
# return s
#
# Path: pyftpdlib/_compat.py
# PY3 = sys.version_info[0] == 3
# _SENTINEL = object()
# def u(s):
# def b(s):
# def u(s):
# def b(s):
# def callable(obj):
# def _instance_checking_exception(base_exception=Exception):
# def wrapped(instance_checker):
# def __init__(self, *args, **kwargs):
# def __instancecheck__(cls, inst):
# def __subclasscheck__(cls, classinfo):
# def FileNotFoundError(inst):
# def FileExistsError(inst):
# def super(type_=_SENTINEL, type_or_obj=_SENTINEL, framedepth=1):
# class TemporaryClass(base_exception):
# class __metaclass__(type):
. Output only the next line. | try: |
Using the snippet: <|code_start|>
context = super(KioskView, self).get_context_data(**kwargs)
context['kiosk'] = kiosk.name
return context
@csrf_exempt
def kiosk_data(request, **kwargs):
slug = kwargs['name']
kiosk = get_object_or_404(Kiosk, name=slug)
currentPresentation = kiosk.presentation
# construct the JSON representation of the kiosk
for scheduledPresentation in kiosk.kioskpresentationcalendar_set.all():
if scheduledPresentation.endTime > timezone.now() >= scheduledPresentation.startTime:
currentPresentation = scheduledPresentation.scheduledPresentation
# Clean up past KioskPresentationCalendar (the presentation itself is not deleted)
elif timezone.now() > scheduledPresentation.endTime:
scheduledPresentation.delete()
sections = []
for section in kiosk.sections.all():
sections.append(section.to_json())
slides = []
for slide in currentPresentation.slides.all():
if (slide.type == Slide.EVENT and
(timezone.now().date() > slide.event.date or
(
timezone.now().date() == slide.event.date and
timezone.now().time() > slide.event.endTime
<|code_end|>
, determine the next line of code. You have imports:
from django.views.generic.base import TemplateView
from django.shortcuts import get_object_or_404, render
from .models import Kiosk
from event_kiosk.presentations.models import Slide
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
import django.utils.timezone as timezone
import os
import datetime
and context (class names, function names, or code) available:
# Path: backend/event_kiosk/event_kiosk/kiosks/models.py
# class Kiosk(models.Model):
# name = models.SlugField(_('name'))
# presentation = models.ForeignKey(to=Presentation, related_name='+', null=True, blank=True)
# presentation_calendar = models.ManyToManyField(to=Presentation, through='KioskPresentationCalendar', through_fields=('kiosk', 'scheduledPresentation'))
#
# def __str__(self):
# return self.name
. Output only the next line. | ) |
Using the snippet: <|code_start|>Table = NewTag('Table', 'table', Table, class_='table')
H1 = NewTag('H1', 'h1', H1, class_='title is-1')
H2 = NewTag('H2', 'h2', H2, class_='title is-2')
H3 = NewTag('H3', 'h3', H3, class_='title is-3')
H4 = NewTag('H4', 'h4', H4, class_='title is-4')
H5 = NewTag('H5', 'h5', H5, class_='title is-5')
H6 = NewTag('H6', 'h6', H6, class_='title is-6')
Container = NewTag('Container', 'div', Container, class_='content')
Wrapper = NewTag('Wrapper', 'div', Wrapper, class_='content')
Row = NewTag('Row', 'div', Row, class_='columns')
Col = NewTag('Col', 'div', Col, class_='column')
Col1 = NewTag('Col1', 'div', Col, class_='is-1', is_='col1')
Col2 = NewTag('Col2', 'div', Col, class_='is-2', is_='col2')
Col3 = NewTag('Col3', 'div', Col, class_='is-3', is_='col3')
Col4 = NewTag('Col4', 'div', Col, class_='is-4', is_='col4')
Col5 = NewTag('Col5', 'div', Col, class_='is-5', is_='col5')
Col6 = NewTag('Col6', 'div', Col, class_='is-6', is_='col6')
Col7 = NewTag('Col7', 'div', Col, class_='is-7', is_='col7')
Col8 = NewTag('Col8', 'div', Col, class_='is-8', is_='col8')
Col9 = NewTag('Col9', 'div', Col, class_='is-9', is_='col9')
Col10 = NewTag('Col10', 'div', Col, class_='is-10', is_='col10')
Col11 = NewTag('Col11', 'div', Col, class_='is-11', is_='col11')
Col12 = NewTag('Col12', 'div', Col, class_='is-12', is_='col12')
extended_classes = [
Button,
DefaultButton,
<|code_end|>
, determine the next line of code. You have imports:
from wdom.tag import NewTagClass as NewTag
from wdom.themes import *
and context (class names, function names, or code) available:
# Path: wdom/tag.py
# def NewTagClass(class_name: str, tag: str = None,
# bases: Union[type, Iterable] = (Tag, ),
# **kwargs: Any) -> type:
# """Generate and return new ``Tag`` class.
#
# If ``tag`` is empty, lower case of ``class_name`` is used for a tag name of
# the new class. ``bases`` should be a tuple of base classes. If it is empty,
# use ``Tag`` class for a base class. Other keyword arguments are used for
# class variables of the new class.
#
# Example::
#
# MyButton = NewTagClass('MyButton', 'button', (Button,),
# class_='btn', is_='my-button')
# my_button = MyButton('Click!')
# print(my_button.html)
#
# >>> <button class="btn" id="111111111" is="my-button">Click!</button>
# """
# if tag is None:
# tag = class_name.lower()
# if not isinstance(type, tuple):
# if isinstance(bases, Iterable):
# bases = tuple(bases)
# elif isinstance(bases, type):
# bases = (bases, )
# else:
# TypeError('Invalid base class: {}'.format(str(bases)))
# kwargs['tag'] = tag
# # Here not use type() function, since it does not support
# # metaclasss (__prepare__) properly.
# cls = new_class( # type: ignore
# class_name, bases, {}, lambda ns: ns.update(kwargs))
# return cls
. Output only the next line. | PrimaryButton, |
Given the code snippet: <|code_start|>Row = NewTag('Row', 'div', Row, class_='row')
Col = NewTag('Col', 'div', Col, class_='span')
Col1 = NewTag('Col1', 'div', (Col1, Col), class_='one')
Col2 = NewTag('Col2', 'div', (Col2, Col), class_='two')
Col3 = NewTag('Col3', 'div', (Col3, Col), class_='three')
Col4 = NewTag('Col4', 'div', (Col4, Col), class_='four')
Col5 = NewTag('Col5', 'div', (Col5, Col), class_='five')
Col6 = NewTag('Col6', 'div', (Col6, Col), class_='six')
Col7 = NewTag('Col7', 'div', (Col7, Col), class_='seven')
Col8 = NewTag('Col8', 'div', (Col8, Col), class_='eight')
Col9 = NewTag('Col9', 'div', (Col9, Col), class_='nine')
Col10 = NewTag('Col10', 'div', (Col10, Col), class_='ten')
Col11 = NewTag('Col11', 'div', (Col11, Col), class_='eleven')
extended_classes = [
Button,
DefaultButton,
PrimaryButton,
SuccessButton,
InfoButton,
WarningButton,
DangerButton,
ErrorButton,
LinkButton,
Table,
Row,
Col1,
Col2,
Col3,
Col4,
<|code_end|>
, generate the next line using the imports in this file:
from wdom.tag import NewTagClass as NewTag
from wdom.themes import *
and context (functions, classes, or occasionally code) from other files:
# Path: wdom/tag.py
# def NewTagClass(class_name: str, tag: str = None,
# bases: Union[type, Iterable] = (Tag, ),
# **kwargs: Any) -> type:
# """Generate and return new ``Tag`` class.
#
# If ``tag`` is empty, lower case of ``class_name`` is used for a tag name of
# the new class. ``bases`` should be a tuple of base classes. If it is empty,
# use ``Tag`` class for a base class. Other keyword arguments are used for
# class variables of the new class.
#
# Example::
#
# MyButton = NewTagClass('MyButton', 'button', (Button,),
# class_='btn', is_='my-button')
# my_button = MyButton('Click!')
# print(my_button.html)
#
# >>> <button class="btn" id="111111111" is="my-button">Click!</button>
# """
# if tag is None:
# tag = class_name.lower()
# if not isinstance(type, tuple):
# if isinstance(bases, Iterable):
# bases = tuple(bases)
# elif isinstance(bases, type):
# bases = (bases, )
# else:
# TypeError('Invalid base class: {}'.format(str(bases)))
# kwargs['tag'] = tag
# # Here not use type() function, since it does not support
# # metaclasss (__prepare__) properly.
# cls = new_class( # type: ignore
# class_name, bases, {}, lambda ns: ns.update(kwargs))
# return cls
. Output only the next line. | Col5, |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# fake connection
_tornado.connections.append(1) # type: ignore
root = Path(__file__).absolute().parent.parent
html_file = root / 'docs/_build/html/node.html'
with open(html_file) as f:
real_html = f.read()
src = '<div>' + '''
<div a="1">
<span b="2">text</span>
<|code_end|>
using the current file's imports:
from cProfile import Profile
from pstats import Stats
from pathlib import Path
from wdom.parser import parse_html
from wdom.server import _tornado
and any relevant context from other files:
# Path: wdom/parser.py
# def parse_html(html: str, parser: FragmentParser = None) -> Node:
# """Parse HTML fragment and return DocumentFragment object.
#
# DocumentFragment object has parsed Node objects as its child nodes.
# """
# parser = parser or FragmentParser()
# parser.feed(html)
# return parser.root
#
# Path: wdom/server/_tornado.py
# def is_connected() -> bool:
# def get(self) -> None:
# def open(self) -> None:
# def on_message(self, message: str) -> None:
# async def terminate(self) -> None:
# def on_close(self) -> None:
# def set_extra_headers(self, path: str) -> None:
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# def log_request(self, handler: web.RequestHandler) -> None:
# def add_static_path(self, prefix: str, path: str) -> None:
# def add_favicon_path(self, path: str) -> None:
# def get_app(*args: Any, **kwargs: Any) -> Application:
# def set_application(app: Application) -> None:
# def start_server(app: web.Application = None, port: int = None,
# address: str = None, **kwargs: Any) -> HTTPServer:
# def stop_server(server: HTTPServer) -> None:
# class MainHandler(web.RequestHandler):
# class WSHandler(websocket.WebSocketHandler):
# class StaticFileHandlerNoCache(web.StaticFileHandler):
# class Application(web.Application):
. Output only the next line. | <span b="2">text</span> |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# fake connection
_tornado.connections.append(1) # type: ignore
root = Path(__file__).absolute().parent.parent
html_file = root / 'docs/_build/html/node.html'
with open(html_file) as f:
real_html = f.read()
src = '<div>' + '''
<|code_end|>
with the help of current file imports:
from cProfile import Profile
from pstats import Stats
from pathlib import Path
from wdom.parser import parse_html
from wdom.server import _tornado
and context from other files:
# Path: wdom/parser.py
# def parse_html(html: str, parser: FragmentParser = None) -> Node:
# """Parse HTML fragment and return DocumentFragment object.
#
# DocumentFragment object has parsed Node objects as its child nodes.
# """
# parser = parser or FragmentParser()
# parser.feed(html)
# return parser.root
#
# Path: wdom/server/_tornado.py
# def is_connected() -> bool:
# def get(self) -> None:
# def open(self) -> None:
# def on_message(self, message: str) -> None:
# async def terminate(self) -> None:
# def on_close(self) -> None:
# def set_extra_headers(self, path: str) -> None:
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# def log_request(self, handler: web.RequestHandler) -> None:
# def add_static_path(self, prefix: str, path: str) -> None:
# def add_favicon_path(self, path: str) -> None:
# def get_app(*args: Any, **kwargs: Any) -> Application:
# def set_application(app: Application) -> None:
# def start_server(app: web.Application = None, port: int = None,
# address: str = None, **kwargs: Any) -> HTTPServer:
# def stop_server(server: HTTPServer) -> None:
# class MainHandler(web.RequestHandler):
# class WSHandler(websocket.WebSocketHandler):
# class StaticFileHandlerNoCache(web.StaticFileHandler):
# class Application(web.Application):
, which may contain function names, class names, or code. Output only the next line. | <div a="1"> |
Given snippet: <|code_start|>LinkButton = NewTag('LinkButton', 'a', class_='button-alt', is_='link-button')
Col1 = NewTag('Col1', 'div', Col, class_='col-1', is_='col1')
Col2 = NewTag('Col2', 'div', Col, class_='col-2', is_='col2')
Col3 = NewTag('Col3', 'div', Col, class_='col-3', is_='col3')
Col4 = NewTag('Col4', 'div', Col, class_='col-4', is_='col4')
Col5 = NewTag('Col5', 'div', Col, class_='col-5', is_='col5')
Col6 = NewTag('Col6', 'div', Col, class_='col-6', is_='col6')
Col7 = NewTag('Col7', 'div', Col, class_='col-7', is_='col7')
Col8 = NewTag('Col8', 'div', Col, class_='col-8', is_='col8')
Col9 = NewTag('Col9', 'div', Col, class_='col-9', is_='col9')
Col10 = NewTag('Col10', 'div', Col, class_='col-10', is_='col10')
Col11 = NewTag('Col11', 'div', Col, class_='col-11', is_='col11')
Col12 = NewTag('Col12', 'div', Col, class_='col-12', is_='col12')
extended_classes = [
Button,
DefaultButton,
PrimaryButton,
SecondaryButton,
SuccessButton,
InfoButton,
WarningButton,
DangerButton,
ErrorButton,
LinkButton,
Col1,
Col2,
Col3,
Col4,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from wdom.tag import NewTagClass as NewTag
from wdom.themes import *
and context:
# Path: wdom/tag.py
# def NewTagClass(class_name: str, tag: str = None,
# bases: Union[type, Iterable] = (Tag, ),
# **kwargs: Any) -> type:
# """Generate and return new ``Tag`` class.
#
# If ``tag`` is empty, lower case of ``class_name`` is used for a tag name of
# the new class. ``bases`` should be a tuple of base classes. If it is empty,
# use ``Tag`` class for a base class. Other keyword arguments are used for
# class variables of the new class.
#
# Example::
#
# MyButton = NewTagClass('MyButton', 'button', (Button,),
# class_='btn', is_='my-button')
# my_button = MyButton('Click!')
# print(my_button.html)
#
# >>> <button class="btn" id="111111111" is="my-button">Click!</button>
# """
# if tag is None:
# tag = class_name.lower()
# if not isinstance(type, tuple):
# if isinstance(bases, Iterable):
# bases = tuple(bases)
# elif isinstance(bases, type):
# bases = (bases, )
# else:
# TypeError('Invalid base class: {}'.format(str(bases)))
# kwargs['tag'] = tag
# # Here not use type() function, since it does not support
# # metaclasss (__prepare__) properly.
# cls = new_class( # type: ignore
# class_name, bases, {}, lambda ns: ns.update(kwargs))
# return cls
which might include code, classes, or functions. Output only the next line. | Col5, |
Based on the snippet: <|code_start|>
input = Input(type='checkbox')
print(input.html_noid) # <input type="checkbox">
# this is equivalent to:
input = Input()
<|code_end|>
, predict the immediate next line with the help of imports:
from wdom.tag import Input
and context (classes, functions, sometimes code) from other files:
# Path: wdom/tag.py
# class Input(Tag, HTMLInputElement):
# """Base class for ``<input>`` element."""
#
# tag = 'input'
# #: type attribute; text, button, checkbox, or radio... and so on.
# type_ = ''
#
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# if self.type_ and 'type' not in kwargs:
# kwargs['type'] = self.type_
# super().__init__(*args, **kwargs)
. Output only the next line. | input.setAttribute('type', 'checkbox') |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Item(Tag):
tag = 'span'
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
def sample_page(**kwargs) -> Document:
app = Container()
title = H1(parent=app)
title.textContent = 'Todo example'
form = FormGroup(parent=app)
text_input = TextInput()
form.append(text_input)
add_button = Button(parent=form)
add_button.textContent = 'ADD'
todo_list = Div(parent=app)
todo_heading = Div(parent=todo_list)
todo_heading.append('Todo list')
# add_button.addEventListener('click')
def new_item(event=None) -> Tag:
<|code_end|>
, predict the next line using imports from the current file:
from wdom.themes.bootstrap3 import Tag, H1, Button, Div
from wdom.themes.bootstrap3 import Container, FormGroup, TextInput
from wdom.themes.bootstrap3 import css_files, js_files
from wdom.document import get_document, Document
and context including class names, function names, and sometimes code from other files:
# Path: wdom/themes/bootstrap3.py
#
# Path: wdom/themes/bootstrap3.py
#
# Path: wdom/themes/bootstrap3.py
#
# Path: wdom/document.py
# def get_document() -> Document:
# """Get current root document object.
#
# :rtype: Document
# """
# return rootDocument
#
# class Document(Node, ParentNode, EventTarget):
# """Base class for Document node."""
#
# nodeType = Node.DOCUMENT_NODE
# nodeName = '#document'
#
# def __init__(self, *,
# doctype: str = 'html',
# default_class: type = HTMLElement,
# **kwargs: Any) -> None:
# """Create new Document node.
#
# :arg str doctype: Document type of this document.
# :arg type default_class: Default class created by
# :py:meth:`createElement` method.
# """
# super().__init__()
# self.__window = Window(self)
# self._default_class = default_class
#
# self.__doctype = DocumentType(doctype, parent=self)
# self.__html = Html(parent=self)
# self.__head = Head(parent=self.documentElement)
# self.__body = Body(parent=self.documentElement)
#
# @property
# def defaultView(self) -> Window:
# """Return :class:`Window` class of this document."""
# return self.__window
#
# @property
# def doctype(self) -> DocumentType:
# """Return DocumentType element of this document."""
# return self.__doctype
#
# @property
# def documentElement(self) -> Element:
# """Return <html> element of this document."""
# return self.__html
#
# @property
# def head(self) -> Element:
# """Return <head> element of this document."""
# return self.__head
#
# def _find_charset_node(self) -> Optional[Element]:
# for child in self.head:
# if child.localName == 'meta' and child.hasAttribute('charset'):
# return child
# return None
#
# @property
# def characterSet(self) -> str:
# """Get/Set charset of this document."""
# charset = self._find_charset_node()
# if charset:
# return charset.getAttribute('charset') # type: ignore
# return ''
#
# @characterSet.setter
# def characterSet(self, charset: str) -> None:
# """Set character set of this document."""
# charset_node = self._find_charset_node() or Meta(parent=self.head)
# charset_node.setAttribute('charset', charset)
#
# @property
# def body(self) -> Element:
# """Return <body> element of this document."""
# return self.__body
#
# @property
# def title(self) -> str:
# """Get/Set title string of this document."""
# title_element = _find_tag(self.head, 'title')
# if title_element:
# return title_element.textContent
# return ''
#
# @title.setter
# def title(self, new_title: str) -> None:
# _title = _find_tag(self.head, 'title')
# title_element = _title or Title(parent=self.head)
# title_element.textContent = new_title
#
# def getElementsBy(self, cond: Callable[[Element], bool]) -> NodeList:
# """Get elements in this document which matches condition."""
# return getElementsBy(self, cond)
#
# def getElementsByTagName(self, tag: str) -> NodeList:
# """Get elements with tag name in this document."""
# return getElementsByTagName(self, tag)
#
# def getElementsByClassName(self, class_name: str) -> NodeList:
# """Get elements with class name in this document."""
# return getElementsByClassName(self, class_name)
#
# def getElementById(self, id: str) -> Optional[Node]:
# """Get element by ``id``.
#
# If this document does not have the element with the id, return None.
# """
# elm = getElementById(id)
# if elm and elm.ownerDocument is self:
# return elm
# return None
#
# def createDocumentFragment(self) -> DocumentFragment:
# """Create empty document fragment."""
# return DocumentFragment()
#
# def createTextNode(self, text: str) -> Text:
# """Create text node with ``text``."""
# return Text(text)
#
# def createComment(self, comment: str) -> Comment:
# """Create comment node with ``comment``."""
# return Comment(comment)
#
# def createElement(self, tag: str) -> Node:
# """Create new element whose tag name is ``tag``."""
# return create_element(tag, base=self._default_class)
#
# def createEvent(self, event: str) -> Event:
# """Create Event object with ``event`` type."""
# return Event(event)
#
# def createAttribute(self, name: str) -> Attr:
# """Create Attribute object with ``name``."""
# return Attr(name)
#
# def querySelector(self, selectors: str) -> Node:
# """Not Implemented."""
# return querySelector(self, selectors)
#
# def querySelectorAll(self, selectors: str) -> NodeList:
# """Not Implemented."""
# return querySelectorAll(self, selectors)
. Output only the next line. | item = Item() |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Item(Tag):
tag = 'span'
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
def sample_page(**kwargs) -> Document:
app = Container()
title = H1(parent=app)
title.textContent = 'Todo example'
form = FormGroup(parent=app)
text_input = TextInput()
form.append(text_input)
add_button = Button(parent=form)
add_button.textContent = 'ADD'
todo_list = Div(parent=app)
todo_heading = Div(parent=todo_list)
todo_heading.append('Todo list')
# add_button.addEventListener('click')
def new_item(event=None) -> Tag:
<|code_end|>
using the current file's imports:
from wdom.themes.bootstrap3 import Tag, H1, Button, Div
from wdom.themes.bootstrap3 import Container, FormGroup, TextInput
from wdom.themes.bootstrap3 import css_files, js_files
from wdom.document import get_document, Document
and any relevant context from other files:
# Path: wdom/themes/bootstrap3.py
#
# Path: wdom/themes/bootstrap3.py
#
# Path: wdom/themes/bootstrap3.py
#
# Path: wdom/document.py
# def get_document() -> Document:
# """Get current root document object.
#
# :rtype: Document
# """
# return rootDocument
#
# class Document(Node, ParentNode, EventTarget):
# """Base class for Document node."""
#
# nodeType = Node.DOCUMENT_NODE
# nodeName = '#document'
#
# def __init__(self, *,
# doctype: str = 'html',
# default_class: type = HTMLElement,
# **kwargs: Any) -> None:
# """Create new Document node.
#
# :arg str doctype: Document type of this document.
# :arg type default_class: Default class created by
# :py:meth:`createElement` method.
# """
# super().__init__()
# self.__window = Window(self)
# self._default_class = default_class
#
# self.__doctype = DocumentType(doctype, parent=self)
# self.__html = Html(parent=self)
# self.__head = Head(parent=self.documentElement)
# self.__body = Body(parent=self.documentElement)
#
# @property
# def defaultView(self) -> Window:
# """Return :class:`Window` class of this document."""
# return self.__window
#
# @property
# def doctype(self) -> DocumentType:
# """Return DocumentType element of this document."""
# return self.__doctype
#
# @property
# def documentElement(self) -> Element:
# """Return <html> element of this document."""
# return self.__html
#
# @property
# def head(self) -> Element:
# """Return <head> element of this document."""
# return self.__head
#
# def _find_charset_node(self) -> Optional[Element]:
# for child in self.head:
# if child.localName == 'meta' and child.hasAttribute('charset'):
# return child
# return None
#
# @property
# def characterSet(self) -> str:
# """Get/Set charset of this document."""
# charset = self._find_charset_node()
# if charset:
# return charset.getAttribute('charset') # type: ignore
# return ''
#
# @characterSet.setter
# def characterSet(self, charset: str) -> None:
# """Set character set of this document."""
# charset_node = self._find_charset_node() or Meta(parent=self.head)
# charset_node.setAttribute('charset', charset)
#
# @property
# def body(self) -> Element:
# """Return <body> element of this document."""
# return self.__body
#
# @property
# def title(self) -> str:
# """Get/Set title string of this document."""
# title_element = _find_tag(self.head, 'title')
# if title_element:
# return title_element.textContent
# return ''
#
# @title.setter
# def title(self, new_title: str) -> None:
# _title = _find_tag(self.head, 'title')
# title_element = _title or Title(parent=self.head)
# title_element.textContent = new_title
#
# def getElementsBy(self, cond: Callable[[Element], bool]) -> NodeList:
# """Get elements in this document which matches condition."""
# return getElementsBy(self, cond)
#
# def getElementsByTagName(self, tag: str) -> NodeList:
# """Get elements with tag name in this document."""
# return getElementsByTagName(self, tag)
#
# def getElementsByClassName(self, class_name: str) -> NodeList:
# """Get elements with class name in this document."""
# return getElementsByClassName(self, class_name)
#
# def getElementById(self, id: str) -> Optional[Node]:
# """Get element by ``id``.
#
# If this document does not have the element with the id, return None.
# """
# elm = getElementById(id)
# if elm and elm.ownerDocument is self:
# return elm
# return None
#
# def createDocumentFragment(self) -> DocumentFragment:
# """Create empty document fragment."""
# return DocumentFragment()
#
# def createTextNode(self, text: str) -> Text:
# """Create text node with ``text``."""
# return Text(text)
#
# def createComment(self, comment: str) -> Comment:
# """Create comment node with ``comment``."""
# return Comment(comment)
#
# def createElement(self, tag: str) -> Node:
# """Create new element whose tag name is ``tag``."""
# return create_element(tag, base=self._default_class)
#
# def createEvent(self, event: str) -> Event:
# """Create Event object with ``event`` type."""
# return Event(event)
#
# def createAttribute(self, name: str) -> Attr:
# """Create Attribute object with ``name``."""
# return Attr(name)
#
# def querySelector(self, selectors: str) -> Node:
# """Not Implemented."""
# return querySelector(self, selectors)
#
# def querySelectorAll(self, selectors: str) -> NodeList:
# """Not Implemented."""
# return querySelectorAll(self, selectors)
. Output only the next line. | item = Item() |
Continue the code snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Item(Tag):
tag = 'span'
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
def sample_page(**kwargs) -> Document:
app = Container()
title = H1(parent=app)
title.textContent = 'Todo example'
form = FormGroup(parent=app)
text_input = TextInput()
form.append(text_input)
add_button = Button(parent=form)
add_button.textContent = 'ADD'
todo_list = Div(parent=app)
todo_heading = Div(parent=todo_list)
todo_heading.append('Todo list')
# add_button.addEventListener('click')
def new_item(event=None) -> Tag:
item = Item()
<|code_end|>
. Use current file imports:
from wdom.themes.bootstrap3 import Tag, H1, Button, Div
from wdom.themes.bootstrap3 import Container, FormGroup, TextInput
from wdom.themes.bootstrap3 import css_files, js_files
from wdom.document import get_document, Document
and context (classes, functions, or code) from other files:
# Path: wdom/themes/bootstrap3.py
#
# Path: wdom/themes/bootstrap3.py
#
# Path: wdom/themes/bootstrap3.py
#
# Path: wdom/document.py
# def get_document() -> Document:
# """Get current root document object.
#
# :rtype: Document
# """
# return rootDocument
#
# class Document(Node, ParentNode, EventTarget):
# """Base class for Document node."""
#
# nodeType = Node.DOCUMENT_NODE
# nodeName = '#document'
#
# def __init__(self, *,
# doctype: str = 'html',
# default_class: type = HTMLElement,
# **kwargs: Any) -> None:
# """Create new Document node.
#
# :arg str doctype: Document type of this document.
# :arg type default_class: Default class created by
# :py:meth:`createElement` method.
# """
# super().__init__()
# self.__window = Window(self)
# self._default_class = default_class
#
# self.__doctype = DocumentType(doctype, parent=self)
# self.__html = Html(parent=self)
# self.__head = Head(parent=self.documentElement)
# self.__body = Body(parent=self.documentElement)
#
# @property
# def defaultView(self) -> Window:
# """Return :class:`Window` class of this document."""
# return self.__window
#
# @property
# def doctype(self) -> DocumentType:
# """Return DocumentType element of this document."""
# return self.__doctype
#
# @property
# def documentElement(self) -> Element:
# """Return <html> element of this document."""
# return self.__html
#
# @property
# def head(self) -> Element:
# """Return <head> element of this document."""
# return self.__head
#
# def _find_charset_node(self) -> Optional[Element]:
# for child in self.head:
# if child.localName == 'meta' and child.hasAttribute('charset'):
# return child
# return None
#
# @property
# def characterSet(self) -> str:
# """Get/Set charset of this document."""
# charset = self._find_charset_node()
# if charset:
# return charset.getAttribute('charset') # type: ignore
# return ''
#
# @characterSet.setter
# def characterSet(self, charset: str) -> None:
# """Set character set of this document."""
# charset_node = self._find_charset_node() or Meta(parent=self.head)
# charset_node.setAttribute('charset', charset)
#
# @property
# def body(self) -> Element:
# """Return <body> element of this document."""
# return self.__body
#
# @property
# def title(self) -> str:
# """Get/Set title string of this document."""
# title_element = _find_tag(self.head, 'title')
# if title_element:
# return title_element.textContent
# return ''
#
# @title.setter
# def title(self, new_title: str) -> None:
# _title = _find_tag(self.head, 'title')
# title_element = _title or Title(parent=self.head)
# title_element.textContent = new_title
#
# def getElementsBy(self, cond: Callable[[Element], bool]) -> NodeList:
# """Get elements in this document which matches condition."""
# return getElementsBy(self, cond)
#
# def getElementsByTagName(self, tag: str) -> NodeList:
# """Get elements with tag name in this document."""
# return getElementsByTagName(self, tag)
#
# def getElementsByClassName(self, class_name: str) -> NodeList:
# """Get elements with class name in this document."""
# return getElementsByClassName(self, class_name)
#
# def getElementById(self, id: str) -> Optional[Node]:
# """Get element by ``id``.
#
# If this document does not have the element with the id, return None.
# """
# elm = getElementById(id)
# if elm and elm.ownerDocument is self:
# return elm
# return None
#
# def createDocumentFragment(self) -> DocumentFragment:
# """Create empty document fragment."""
# return DocumentFragment()
#
# def createTextNode(self, text: str) -> Text:
# """Create text node with ``text``."""
# return Text(text)
#
# def createComment(self, comment: str) -> Comment:
# """Create comment node with ``comment``."""
# return Comment(comment)
#
# def createElement(self, tag: str) -> Node:
# """Create new element whose tag name is ``tag``."""
# return create_element(tag, base=self._default_class)
#
# def createEvent(self, event: str) -> Event:
# """Create Event object with ``event`` type."""
# return Event(event)
#
# def createAttribute(self, name: str) -> Attr:
# """Create Attribute object with ``name``."""
# return Attr(name)
#
# def querySelector(self, selectors: str) -> Node:
# """Not Implemented."""
# return querySelector(self, selectors)
#
# def querySelectorAll(self, selectors: str) -> NodeList:
# """Not Implemented."""
# return querySelectorAll(self, selectors)
. Output only the next line. | item.append('New Item') |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Item(Tag):
tag = 'span'
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
def sample_page(**kwargs) -> Document:
app = Container()
title = H1(parent=app)
title.textContent = 'Todo example'
form = FormGroup(parent=app)
text_input = TextInput()
form.append(text_input)
add_button = Button(parent=form)
add_button.textContent = 'ADD'
todo_list = Div(parent=app)
todo_heading = Div(parent=todo_list)
todo_heading.append('Todo list')
# add_button.addEventListener('click')
def new_item(event=None) -> Tag:
<|code_end|>
with the help of current file imports:
from wdom.themes.bootstrap3 import Tag, H1, Button, Div
from wdom.themes.bootstrap3 import Container, FormGroup, TextInput
from wdom.themes.bootstrap3 import css_files, js_files
from wdom.document import get_document, Document
and context from other files:
# Path: wdom/themes/bootstrap3.py
#
# Path: wdom/themes/bootstrap3.py
#
# Path: wdom/themes/bootstrap3.py
#
# Path: wdom/document.py
# def get_document() -> Document:
# """Get current root document object.
#
# :rtype: Document
# """
# return rootDocument
#
# class Document(Node, ParentNode, EventTarget):
# """Base class for Document node."""
#
# nodeType = Node.DOCUMENT_NODE
# nodeName = '#document'
#
# def __init__(self, *,
# doctype: str = 'html',
# default_class: type = HTMLElement,
# **kwargs: Any) -> None:
# """Create new Document node.
#
# :arg str doctype: Document type of this document.
# :arg type default_class: Default class created by
# :py:meth:`createElement` method.
# """
# super().__init__()
# self.__window = Window(self)
# self._default_class = default_class
#
# self.__doctype = DocumentType(doctype, parent=self)
# self.__html = Html(parent=self)
# self.__head = Head(parent=self.documentElement)
# self.__body = Body(parent=self.documentElement)
#
# @property
# def defaultView(self) -> Window:
# """Return :class:`Window` class of this document."""
# return self.__window
#
# @property
# def doctype(self) -> DocumentType:
# """Return DocumentType element of this document."""
# return self.__doctype
#
# @property
# def documentElement(self) -> Element:
# """Return <html> element of this document."""
# return self.__html
#
# @property
# def head(self) -> Element:
# """Return <head> element of this document."""
# return self.__head
#
# def _find_charset_node(self) -> Optional[Element]:
# for child in self.head:
# if child.localName == 'meta' and child.hasAttribute('charset'):
# return child
# return None
#
# @property
# def characterSet(self) -> str:
# """Get/Set charset of this document."""
# charset = self._find_charset_node()
# if charset:
# return charset.getAttribute('charset') # type: ignore
# return ''
#
# @characterSet.setter
# def characterSet(self, charset: str) -> None:
# """Set character set of this document."""
# charset_node = self._find_charset_node() or Meta(parent=self.head)
# charset_node.setAttribute('charset', charset)
#
# @property
# def body(self) -> Element:
# """Return <body> element of this document."""
# return self.__body
#
# @property
# def title(self) -> str:
# """Get/Set title string of this document."""
# title_element = _find_tag(self.head, 'title')
# if title_element:
# return title_element.textContent
# return ''
#
# @title.setter
# def title(self, new_title: str) -> None:
# _title = _find_tag(self.head, 'title')
# title_element = _title or Title(parent=self.head)
# title_element.textContent = new_title
#
# def getElementsBy(self, cond: Callable[[Element], bool]) -> NodeList:
# """Get elements in this document which matches condition."""
# return getElementsBy(self, cond)
#
# def getElementsByTagName(self, tag: str) -> NodeList:
# """Get elements with tag name in this document."""
# return getElementsByTagName(self, tag)
#
# def getElementsByClassName(self, class_name: str) -> NodeList:
# """Get elements with class name in this document."""
# return getElementsByClassName(self, class_name)
#
# def getElementById(self, id: str) -> Optional[Node]:
# """Get element by ``id``.
#
# If this document does not have the element with the id, return None.
# """
# elm = getElementById(id)
# if elm and elm.ownerDocument is self:
# return elm
# return None
#
# def createDocumentFragment(self) -> DocumentFragment:
# """Create empty document fragment."""
# return DocumentFragment()
#
# def createTextNode(self, text: str) -> Text:
# """Create text node with ``text``."""
# return Text(text)
#
# def createComment(self, comment: str) -> Comment:
# """Create comment node with ``comment``."""
# return Comment(comment)
#
# def createElement(self, tag: str) -> Node:
# """Create new element whose tag name is ``tag``."""
# return create_element(tag, base=self._default_class)
#
# def createEvent(self, event: str) -> Event:
# """Create Event object with ``event`` type."""
# return Event(event)
#
# def createAttribute(self, name: str) -> Attr:
# """Create Attribute object with ``name``."""
# return Attr(name)
#
# def querySelector(self, selectors: str) -> Node:
# """Not Implemented."""
# return querySelector(self, selectors)
#
# def querySelectorAll(self, selectors: str) -> NodeList:
# """Not Implemented."""
# return querySelectorAll(self, selectors)
, which may contain function names, class names, or code. Output only the next line. | item = Item() |
Predict the next line after this snippet: <|code_start|>
class Item(Tag):
tag = 'span'
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
def sample_page(**kwargs) -> Document:
app = Container()
title = H1(parent=app)
title.textContent = 'Todo example'
form = FormGroup(parent=app)
text_input = TextInput()
form.append(text_input)
add_button = Button(parent=form)
add_button.textContent = 'ADD'
todo_list = Div(parent=app)
todo_heading = Div(parent=todo_list)
todo_heading.append('Todo list')
# add_button.addEventListener('click')
def new_item(event=None) -> Tag:
item = Item()
item.append('New Item')
todo_list.append(item)
return item
<|code_end|>
using the current file's imports:
from wdom.themes.bootstrap3 import Tag, H1, Button, Div
from wdom.themes.bootstrap3 import Container, FormGroup, TextInput
from wdom.themes.bootstrap3 import css_files, js_files
from wdom.document import get_document, Document
and any relevant context from other files:
# Path: wdom/themes/bootstrap3.py
#
# Path: wdom/themes/bootstrap3.py
#
# Path: wdom/themes/bootstrap3.py
#
# Path: wdom/document.py
# def get_document() -> Document:
# """Get current root document object.
#
# :rtype: Document
# """
# return rootDocument
#
# class Document(Node, ParentNode, EventTarget):
# """Base class for Document node."""
#
# nodeType = Node.DOCUMENT_NODE
# nodeName = '#document'
#
# def __init__(self, *,
# doctype: str = 'html',
# default_class: type = HTMLElement,
# **kwargs: Any) -> None:
# """Create new Document node.
#
# :arg str doctype: Document type of this document.
# :arg type default_class: Default class created by
# :py:meth:`createElement` method.
# """
# super().__init__()
# self.__window = Window(self)
# self._default_class = default_class
#
# self.__doctype = DocumentType(doctype, parent=self)
# self.__html = Html(parent=self)
# self.__head = Head(parent=self.documentElement)
# self.__body = Body(parent=self.documentElement)
#
# @property
# def defaultView(self) -> Window:
# """Return :class:`Window` class of this document."""
# return self.__window
#
# @property
# def doctype(self) -> DocumentType:
# """Return DocumentType element of this document."""
# return self.__doctype
#
# @property
# def documentElement(self) -> Element:
# """Return <html> element of this document."""
# return self.__html
#
# @property
# def head(self) -> Element:
# """Return <head> element of this document."""
# return self.__head
#
# def _find_charset_node(self) -> Optional[Element]:
# for child in self.head:
# if child.localName == 'meta' and child.hasAttribute('charset'):
# return child
# return None
#
# @property
# def characterSet(self) -> str:
# """Get/Set charset of this document."""
# charset = self._find_charset_node()
# if charset:
# return charset.getAttribute('charset') # type: ignore
# return ''
#
# @characterSet.setter
# def characterSet(self, charset: str) -> None:
# """Set character set of this document."""
# charset_node = self._find_charset_node() or Meta(parent=self.head)
# charset_node.setAttribute('charset', charset)
#
# @property
# def body(self) -> Element:
# """Return <body> element of this document."""
# return self.__body
#
# @property
# def title(self) -> str:
# """Get/Set title string of this document."""
# title_element = _find_tag(self.head, 'title')
# if title_element:
# return title_element.textContent
# return ''
#
# @title.setter
# def title(self, new_title: str) -> None:
# _title = _find_tag(self.head, 'title')
# title_element = _title or Title(parent=self.head)
# title_element.textContent = new_title
#
# def getElementsBy(self, cond: Callable[[Element], bool]) -> NodeList:
# """Get elements in this document which matches condition."""
# return getElementsBy(self, cond)
#
# def getElementsByTagName(self, tag: str) -> NodeList:
# """Get elements with tag name in this document."""
# return getElementsByTagName(self, tag)
#
# def getElementsByClassName(self, class_name: str) -> NodeList:
# """Get elements with class name in this document."""
# return getElementsByClassName(self, class_name)
#
# def getElementById(self, id: str) -> Optional[Node]:
# """Get element by ``id``.
#
# If this document does not have the element with the id, return None.
# """
# elm = getElementById(id)
# if elm and elm.ownerDocument is self:
# return elm
# return None
#
# def createDocumentFragment(self) -> DocumentFragment:
# """Create empty document fragment."""
# return DocumentFragment()
#
# def createTextNode(self, text: str) -> Text:
# """Create text node with ``text``."""
# return Text(text)
#
# def createComment(self, comment: str) -> Comment:
# """Create comment node with ``comment``."""
# return Comment(comment)
#
# def createElement(self, tag: str) -> Node:
# """Create new element whose tag name is ``tag``."""
# return create_element(tag, base=self._default_class)
#
# def createEvent(self, event: str) -> Event:
# """Create Event object with ``event`` type."""
# return Event(event)
#
# def createAttribute(self, name: str) -> Attr:
# """Create Attribute object with ``name``."""
# return Attr(name)
#
# def querySelector(self, selectors: str) -> Node:
# """Not Implemented."""
# return querySelector(self, selectors)
#
# def querySelectorAll(self, selectors: str) -> NodeList:
# """Not Implemented."""
# return querySelectorAll(self, selectors)
. Output only the next line. | add_button.addEventListener('click', new_item) |
Given snippet: <|code_start|>
class Item(Tag):
tag = 'span'
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
def sample_page(**kwargs) -> Document:
app = Container()
title = H1(parent=app)
title.textContent = 'Todo example'
form = FormGroup(parent=app)
text_input = TextInput()
form.append(text_input)
add_button = Button(parent=form)
add_button.textContent = 'ADD'
todo_list = Div(parent=app)
todo_heading = Div(parent=todo_list)
todo_heading.append('Todo list')
# add_button.addEventListener('click')
def new_item(event=None) -> Tag:
item = Item()
item.append('New Item')
todo_list.append(item)
return item
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from wdom.themes.bootstrap3 import Tag, H1, Button, Div
from wdom.themes.bootstrap3 import Container, FormGroup, TextInput
from wdom.themes.bootstrap3 import css_files, js_files
from wdom.document import get_document, Document
and context:
# Path: wdom/themes/bootstrap3.py
#
# Path: wdom/themes/bootstrap3.py
#
# Path: wdom/themes/bootstrap3.py
#
# Path: wdom/document.py
# def get_document() -> Document:
# """Get current root document object.
#
# :rtype: Document
# """
# return rootDocument
#
# class Document(Node, ParentNode, EventTarget):
# """Base class for Document node."""
#
# nodeType = Node.DOCUMENT_NODE
# nodeName = '#document'
#
# def __init__(self, *,
# doctype: str = 'html',
# default_class: type = HTMLElement,
# **kwargs: Any) -> None:
# """Create new Document node.
#
# :arg str doctype: Document type of this document.
# :arg type default_class: Default class created by
# :py:meth:`createElement` method.
# """
# super().__init__()
# self.__window = Window(self)
# self._default_class = default_class
#
# self.__doctype = DocumentType(doctype, parent=self)
# self.__html = Html(parent=self)
# self.__head = Head(parent=self.documentElement)
# self.__body = Body(parent=self.documentElement)
#
# @property
# def defaultView(self) -> Window:
# """Return :class:`Window` class of this document."""
# return self.__window
#
# @property
# def doctype(self) -> DocumentType:
# """Return DocumentType element of this document."""
# return self.__doctype
#
# @property
# def documentElement(self) -> Element:
# """Return <html> element of this document."""
# return self.__html
#
# @property
# def head(self) -> Element:
# """Return <head> element of this document."""
# return self.__head
#
# def _find_charset_node(self) -> Optional[Element]:
# for child in self.head:
# if child.localName == 'meta' and child.hasAttribute('charset'):
# return child
# return None
#
# @property
# def characterSet(self) -> str:
# """Get/Set charset of this document."""
# charset = self._find_charset_node()
# if charset:
# return charset.getAttribute('charset') # type: ignore
# return ''
#
# @characterSet.setter
# def characterSet(self, charset: str) -> None:
# """Set character set of this document."""
# charset_node = self._find_charset_node() or Meta(parent=self.head)
# charset_node.setAttribute('charset', charset)
#
# @property
# def body(self) -> Element:
# """Return <body> element of this document."""
# return self.__body
#
# @property
# def title(self) -> str:
# """Get/Set title string of this document."""
# title_element = _find_tag(self.head, 'title')
# if title_element:
# return title_element.textContent
# return ''
#
# @title.setter
# def title(self, new_title: str) -> None:
# _title = _find_tag(self.head, 'title')
# title_element = _title or Title(parent=self.head)
# title_element.textContent = new_title
#
# def getElementsBy(self, cond: Callable[[Element], bool]) -> NodeList:
# """Get elements in this document which matches condition."""
# return getElementsBy(self, cond)
#
# def getElementsByTagName(self, tag: str) -> NodeList:
# """Get elements with tag name in this document."""
# return getElementsByTagName(self, tag)
#
# def getElementsByClassName(self, class_name: str) -> NodeList:
# """Get elements with class name in this document."""
# return getElementsByClassName(self, class_name)
#
# def getElementById(self, id: str) -> Optional[Node]:
# """Get element by ``id``.
#
# If this document does not have the element with the id, return None.
# """
# elm = getElementById(id)
# if elm and elm.ownerDocument is self:
# return elm
# return None
#
# def createDocumentFragment(self) -> DocumentFragment:
# """Create empty document fragment."""
# return DocumentFragment()
#
# def createTextNode(self, text: str) -> Text:
# """Create text node with ``text``."""
# return Text(text)
#
# def createComment(self, comment: str) -> Comment:
# """Create comment node with ``comment``."""
# return Comment(comment)
#
# def createElement(self, tag: str) -> Node:
# """Create new element whose tag name is ``tag``."""
# return create_element(tag, base=self._default_class)
#
# def createEvent(self, event: str) -> Event:
# """Create Event object with ``event`` type."""
# return Event(event)
#
# def createAttribute(self, name: str) -> Attr:
# """Create Attribute object with ``name``."""
# return Attr(name)
#
# def querySelector(self, selectors: str) -> Node:
# """Not Implemented."""
# return querySelector(self, selectors)
#
# def querySelectorAll(self, selectors: str) -> NodeList:
# """Not Implemented."""
# return querySelectorAll(self, selectors)
which might include code, classes, or functions. Output only the next line. | add_button.addEventListener('click', new_item) |
Predict the next line for this snippet: <|code_start|>
class Col(Div):
column = None
is_ = 'col'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.column:
self.setAttribute('column', str(self.column))
Col1 = NewTag('Col1', 'div', Col, column=1, is_='col1')
Col2 = NewTag('Col2', 'div', Col, column=2, is_='col2')
Col3 = NewTag('Col3', 'div', Col, column=3, is_='col3')
Col4 = NewTag('Col4', 'div', Col, column=4, is_='col4')
Col5 = NewTag('Col5', 'div', Col, column=5, is_='col5')
Col6 = NewTag('Col6', 'div', Col, column=6, is_='col6')
Col7 = NewTag('Col7', 'div', Col, column=7, is_='col7')
Col8 = NewTag('Col8', 'div', Col, column=8, is_='col8')
Col9 = NewTag('Col9', 'div', Col, column=9, is_='col9')
Col10 = NewTag('Col10', 'div', Col, column=10, is_='col10')
Col11 = NewTag('Col11', 'div', Col, column=11, is_='col11')
Col12 = NewTag('Col12', 'div', Col, column=12, is_='col12')
extended_classes = [
Button,
DefaultButton,
PrimaryButton,
SecondaryButton,
SuccessButton,
InfoButton,
WarningButton,
<|code_end|>
with the help of current file imports:
from wdom.tag import NewTagClass as NewTag
from wdom.themes import *
and context from other files:
# Path: wdom/tag.py
# def NewTagClass(class_name: str, tag: str = None,
# bases: Union[type, Iterable] = (Tag, ),
# **kwargs: Any) -> type:
# """Generate and return new ``Tag`` class.
#
# If ``tag`` is empty, lower case of ``class_name`` is used for a tag name of
# the new class. ``bases`` should be a tuple of base classes. If it is empty,
# use ``Tag`` class for a base class. Other keyword arguments are used for
# class variables of the new class.
#
# Example::
#
# MyButton = NewTagClass('MyButton', 'button', (Button,),
# class_='btn', is_='my-button')
# my_button = MyButton('Click!')
# print(my_button.html)
#
# >>> <button class="btn" id="111111111" is="my-button">Click!</button>
# """
# if tag is None:
# tag = class_name.lower()
# if not isinstance(type, tuple):
# if isinstance(bases, Iterable):
# bases = tuple(bases)
# elif isinstance(bases, type):
# bases = (bases, )
# else:
# TypeError('Invalid base class: {}'.format(str(bases)))
# kwargs['tag'] = tag
# # Here not use type() function, since it does not support
# # metaclasss (__prepare__) properly.
# cls = new_class( # type: ignore
# class_name, bases, {}, lambda ns: ns.update(kwargs))
# return cls
, which may contain function names, class names, or code. Output only the next line. | DangerButton, |
Given the following code snippet before the placeholder: <|code_start|>Container = NewTag('Container', 'div', Container, class_='container')
Wrapper = NewTag('Wrapper', 'div', Wrapper, class_='container')
Row = NewTag('Row', 'div', Row, class_='row')
Col = NewTag('Col', 'div', Col, class_='columns')
Col1 = NewTag('Col1', 'div', Col1, class_='one column')
Col2 = NewTag('Col2', 'div', Col2, class_='two columns')
Col3 = NewTag('Col3', 'div', Col3, class_='three columns')
Col4 = NewTag('Col4', 'div', Col4, class_='four columns')
Col5 = NewTag('Col5', 'div', Col5, class_='five columns')
Col6 = NewTag('Col6', 'div', Col6, class_='six columns')
Col7 = NewTag('Col7', 'div', Col7, class_='seven columns')
Col8 = NewTag('Col8', 'div', Col8, class_='eight columns')
Col9 = NewTag('Col9', 'div', Col9, class_='nine columns')
Col10 = NewTag('Col10', 'div', Col10, class_='ten columns')
Col11 = NewTag('Col11', 'div', Col11, class_='eleven columns')
Col12 = NewTag('Col12', 'div', Col12, class_='twelve columns')
extended_classes = [
PrimaryButton,
Container,
Wrapper,
Row,
Col,
Col1,
Col2,
Col3,
Col4,
Col5,
Col6,
Col7,
<|code_end|>
, predict the next line using imports from the current file:
from wdom.tag import NewTagClass as NewTag
from wdom.themes import *
and context including class names, function names, and sometimes code from other files:
# Path: wdom/tag.py
# def NewTagClass(class_name: str, tag: str = None,
# bases: Union[type, Iterable] = (Tag, ),
# **kwargs: Any) -> type:
# """Generate and return new ``Tag`` class.
#
# If ``tag`` is empty, lower case of ``class_name`` is used for a tag name of
# the new class. ``bases`` should be a tuple of base classes. If it is empty,
# use ``Tag`` class for a base class. Other keyword arguments are used for
# class variables of the new class.
#
# Example::
#
# MyButton = NewTagClass('MyButton', 'button', (Button,),
# class_='btn', is_='my-button')
# my_button = MyButton('Click!')
# print(my_button.html)
#
# >>> <button class="btn" id="111111111" is="my-button">Click!</button>
# """
# if tag is None:
# tag = class_name.lower()
# if not isinstance(type, tuple):
# if isinstance(bases, Iterable):
# bases = tuple(bases)
# elif isinstance(bases, type):
# bases = (bases, )
# else:
# TypeError('Invalid base class: {}'.format(str(bases)))
# kwargs['tag'] = tag
# # Here not use type() function, since it does not support
# # metaclasss (__prepare__) properly.
# cls = new_class( # type: ignore
# class_name, bases, {}, lambda ns: ns.update(kwargs))
# return cls
. Output only the next line. | Col8, |
Given the following code snippet before the placeholder: <|code_start|>Row = NewTag('Row', 'div', Row, class_='row')
Col1 = NewTag('Col1', 'div', Col1, class_='one twelfth')
Col2 = NewTag('Col2', 'div', Col2, class_='one sixth')
Col3 = NewTag('Col3', 'div', Col3, class_='one fourth')
Col4 = NewTag('Col4', 'div', Col4, class_='one third')
Col5 = NewTag('Col5', 'div', Col5, class_='five twelfths')
Col6 = NewTag('Col6', 'div', Col6, class_='one half')
Col7 = NewTag('Col7', 'div', Col7, class_='seven twelfths')
Col8 = NewTag('Col8', 'div', Col8, class_='two thirds')
Col9 = NewTag('Col9', 'div', Col9, class_='three fourths')
Col10 = NewTag('Col10', 'div', Col10, class_='five sixths')
Col11 = NewTag('Col11', 'div', Col11, class_='eleven twelfths')
extended_classes = [
Button,
DefaultButton,
PrimaryButton,
SecondaryButton,
SuccessButton,
InfoButton,
WarningButton,
DangerButton,
ErrorButton,
LinkButton,
Row,
Col1,
Col2,
Col3,
Col4,
Col5,
<|code_end|>
, predict the next line using imports from the current file:
from wdom.tag import NewTagClass as NewTag
from wdom.themes import *
and context including class names, function names, and sometimes code from other files:
# Path: wdom/tag.py
# def NewTagClass(class_name: str, tag: str = None,
# bases: Union[type, Iterable] = (Tag, ),
# **kwargs: Any) -> type:
# """Generate and return new ``Tag`` class.
#
# If ``tag`` is empty, lower case of ``class_name`` is used for a tag name of
# the new class. ``bases`` should be a tuple of base classes. If it is empty,
# use ``Tag`` class for a base class. Other keyword arguments are used for
# class variables of the new class.
#
# Example::
#
# MyButton = NewTagClass('MyButton', 'button', (Button,),
# class_='btn', is_='my-button')
# my_button = MyButton('Click!')
# print(my_button.html)
#
# >>> <button class="btn" id="111111111" is="my-button">Click!</button>
# """
# if tag is None:
# tag = class_name.lower()
# if not isinstance(type, tuple):
# if isinstance(bases, Iterable):
# bases = tuple(bases)
# elif isinstance(bases, type):
# bases = (bases, )
# else:
# TypeError('Invalid base class: {}'.format(str(bases)))
# kwargs['tag'] = tag
# # Here not use type() function, since it does not support
# # metaclasss (__prepare__) properly.
# cls = new_class( # type: ignore
# class_name, bases, {}, lambda ns: ns.update(kwargs))
# return cls
. Output only the next line. | Col6, |
Continue the code snippet: <|code_start|>
def test_default_loglevel(self):
parse_command_line()
set_loglevel()
logger = logging.getLogger('wdom')
self.assertEqual(logger.getEffectiveLevel(), logging.INFO)
@parameterized.expand([
('debug', logging.DEBUG),
('info', logging.INFO),
('warn', logging.WARN),
('error', logging.ERROR),
])
def test_loglevel(self, level_name, level):
sys.argv.extend(['--logging', level_name])
parse_command_line()
logger = logging.getLogger('wdom')
self.assertEqual(logger.getEffectiveLevel(), level)
reset_options()
def test_debug_without_logging(self):
sys.argv.extend(['--debug'])
parse_command_line()
logger = logging.getLogger('wdom')
self.assertEqual(logger.getEffectiveLevel(), logging.DEBUG)
def test_debug_with_logging(self):
sys.argv.extend(['--debug', '--logging', 'warn'])
parse_command_line()
logger = logging.getLogger('wdom')
<|code_end|>
. Use current file imports:
import sys
import logging
import unittest
from copy import copy
from importlib import reload
from parameterized import parameterized
from wdom.options import parse_command_line, config, set_loglevel
from wdom import tag
from .base import TestCase
from wdom.themes import default
from wdom.themes import bootstrap3
and context (classes, functions, or code) from other files:
# Path: wdom/options.py
# def level_to_int(level: Union[str, int]) -> int:
# def set_loglevel(level: Union[int, str, None] = None) -> None:
# def parse_command_line() -> Namespace:
#
# Path: wdom/tag.py
# class Tag(WdomElement):
# class NestedTag(Tag):
# class Input(Tag, HTMLInputElement):
# class Textarea(Tag, HTMLTextAreaElement): # noqa: D204
# class Script(Tag, HTMLScriptElement): # noqa: D204
# class RawHtmlNode(Tag):
# def __init__(self, *args: Any, attrs: Dict[str, _AttrValueType] = None,
# **kwargs: Any) -> None:
# def _clone_node(self) -> 'Tag':
# def type(self) -> _AttrValueType: # noqa: D102
# def type(self, val: str) -> None: # noqa: D102
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# def appendChild(self, child: Node) -> Node: # noqa: D102
# def insertBefore(self, child: Node, ref_node: Node) -> Node: # noqa: D102
# def removeChild(self, child: Node) -> Node: # noqa: D102
# def replaceChild(self, new_child: Node, old_child: Node
# ) -> Node: # noqa: D102
# def childNodes(self) -> NodeList: # noqa: D102
# def empty(self) -> None: # noqa: D102
# def textContent(self, text: str) -> None: # type: ignore
# def html(self) -> str:
# def innerHTML(self) -> str:
# def innerHTML(self, html: str) -> None:
# def NewTagClass(class_name: str, tag: str = None,
# bases: Union[type, Iterable] = (Tag, ),
# **kwargs: Any) -> type:
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# def value(self) -> str:
# def value(self, value: str) -> None:
# def __init__(self, *args: Any, type: str = 'text/javascript',
# **kwargs: Any) -> None:
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# H1 = NewTagClass('H1')
# H2 = NewTagClass('H2')
# H3 = NewTagClass('H3')
# H4 = NewTagClass('H4')
# H5 = NewTagClass('H5')
# H6 = NewTagClass('H6')
# P = NewTagClass('P')
# A = NewTagClass('A', 'a', (Tag, HTMLAnchorElement))
# U = NewTagClass('U')
#
# Path: tests/base.py
# class TestCase(unittest.TestCase):
# """Base class for testing wdom modules.
#
# This class is a sub class of the ``unittest.TestCase``. After all test
# methods, reset wdom's global objects like document, application, and
# elements. If you use ``tearDown`` method, do not forget to call
# ``super().tearDown()``.
# """
#
# def setUp(self) -> None:
# """Reset WDOM states."""
# super().setUp()
# reset()
#
# def tearDown(self) -> None:
# """Reset WDOM states."""
# reset()
# super().tearDown()
#
# def assertIsTrue(self, bl: bool) -> None:
# """Check arg is exactly True, not truthy."""
# self.assertIs(bl, True)
#
# def assertIsFalse(self, bl: bool) -> None:
# """Check arg is exactly False, not falsy."""
# self.assertIs(bl, False)
. Output only the next line. | assert logger.getEffectiveLevel() == logging.WARN |
Predict the next line for this snippet: <|code_start|> logger = logging.getLogger('wdom')
self.assertEqual(logger.getEffectiveLevel(), level)
reset_options()
def test_debug_without_logging(self):
sys.argv.extend(['--debug'])
parse_command_line()
logger = logging.getLogger('wdom')
self.assertEqual(logger.getEffectiveLevel(), logging.DEBUG)
def test_debug_with_logging(self):
sys.argv.extend(['--debug', '--logging', 'warn'])
parse_command_line()
logger = logging.getLogger('wdom')
assert logger.getEffectiveLevel() == logging.WARN
def test_unknown_args(self):
sys.argv.extend(['--test-args', 'a'])
# no error/log when get unknown args
with self.assertRaises(AssertionError):
with self.assertLogs('wdom'):
parse_command_line()
class TestThemeOption(unittest.TestCase):
def setUp(self):
super().setUp()
self.theme_mod = default
def tearDown(self):
<|code_end|>
with the help of current file imports:
import sys
import logging
import unittest
from copy import copy
from importlib import reload
from parameterized import parameterized
from wdom.options import parse_command_line, config, set_loglevel
from wdom import tag
from .base import TestCase
from wdom.themes import default
from wdom.themes import bootstrap3
and context from other files:
# Path: wdom/options.py
# def level_to_int(level: Union[str, int]) -> int:
# def set_loglevel(level: Union[int, str, None] = None) -> None:
# def parse_command_line() -> Namespace:
#
# Path: wdom/tag.py
# class Tag(WdomElement):
# class NestedTag(Tag):
# class Input(Tag, HTMLInputElement):
# class Textarea(Tag, HTMLTextAreaElement): # noqa: D204
# class Script(Tag, HTMLScriptElement): # noqa: D204
# class RawHtmlNode(Tag):
# def __init__(self, *args: Any, attrs: Dict[str, _AttrValueType] = None,
# **kwargs: Any) -> None:
# def _clone_node(self) -> 'Tag':
# def type(self) -> _AttrValueType: # noqa: D102
# def type(self, val: str) -> None: # noqa: D102
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# def appendChild(self, child: Node) -> Node: # noqa: D102
# def insertBefore(self, child: Node, ref_node: Node) -> Node: # noqa: D102
# def removeChild(self, child: Node) -> Node: # noqa: D102
# def replaceChild(self, new_child: Node, old_child: Node
# ) -> Node: # noqa: D102
# def childNodes(self) -> NodeList: # noqa: D102
# def empty(self) -> None: # noqa: D102
# def textContent(self, text: str) -> None: # type: ignore
# def html(self) -> str:
# def innerHTML(self) -> str:
# def innerHTML(self, html: str) -> None:
# def NewTagClass(class_name: str, tag: str = None,
# bases: Union[type, Iterable] = (Tag, ),
# **kwargs: Any) -> type:
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# def value(self) -> str:
# def value(self, value: str) -> None:
# def __init__(self, *args: Any, type: str = 'text/javascript',
# **kwargs: Any) -> None:
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# H1 = NewTagClass('H1')
# H2 = NewTagClass('H2')
# H3 = NewTagClass('H3')
# H4 = NewTagClass('H4')
# H5 = NewTagClass('H5')
# H6 = NewTagClass('H6')
# P = NewTagClass('P')
# A = NewTagClass('A', 'a', (Tag, HTMLAnchorElement))
# U = NewTagClass('U')
#
# Path: tests/base.py
# class TestCase(unittest.TestCase):
# """Base class for testing wdom modules.
#
# This class is a sub class of the ``unittest.TestCase``. After all test
# methods, reset wdom's global objects like document, application, and
# elements. If you use ``tearDown`` method, do not forget to call
# ``super().tearDown()``.
# """
#
# def setUp(self) -> None:
# """Reset WDOM states."""
# super().setUp()
# reset()
#
# def tearDown(self) -> None:
# """Reset WDOM states."""
# reset()
# super().tearDown()
#
# def assertIsTrue(self, bl: bool) -> None:
# """Check arg is exactly True, not truthy."""
# self.assertIs(bl, True)
#
# def assertIsFalse(self, bl: bool) -> None:
# """Check arg is exactly False, not falsy."""
# self.assertIs(bl, False)
, which may contain function names, class names, or code. Output only the next line. | reset_options() |
Predict the next line for this snippet: <|code_start|> super().tearDown()
def test_default_loglevel(self):
parse_command_line()
set_loglevel()
logger = logging.getLogger('wdom')
self.assertEqual(logger.getEffectiveLevel(), logging.INFO)
@parameterized.expand([
('debug', logging.DEBUG),
('info', logging.INFO),
('warn', logging.WARN),
('error', logging.ERROR),
])
def test_loglevel(self, level_name, level):
sys.argv.extend(['--logging', level_name])
parse_command_line()
logger = logging.getLogger('wdom')
self.assertEqual(logger.getEffectiveLevel(), level)
reset_options()
def test_debug_without_logging(self):
sys.argv.extend(['--debug'])
parse_command_line()
logger = logging.getLogger('wdom')
self.assertEqual(logger.getEffectiveLevel(), logging.DEBUG)
def test_debug_with_logging(self):
sys.argv.extend(['--debug', '--logging', 'warn'])
parse_command_line()
<|code_end|>
with the help of current file imports:
import sys
import logging
import unittest
from copy import copy
from importlib import reload
from parameterized import parameterized
from wdom.options import parse_command_line, config, set_loglevel
from wdom import tag
from .base import TestCase
from wdom.themes import default
from wdom.themes import bootstrap3
and context from other files:
# Path: wdom/options.py
# def level_to_int(level: Union[str, int]) -> int:
# def set_loglevel(level: Union[int, str, None] = None) -> None:
# def parse_command_line() -> Namespace:
#
# Path: wdom/tag.py
# class Tag(WdomElement):
# class NestedTag(Tag):
# class Input(Tag, HTMLInputElement):
# class Textarea(Tag, HTMLTextAreaElement): # noqa: D204
# class Script(Tag, HTMLScriptElement): # noqa: D204
# class RawHtmlNode(Tag):
# def __init__(self, *args: Any, attrs: Dict[str, _AttrValueType] = None,
# **kwargs: Any) -> None:
# def _clone_node(self) -> 'Tag':
# def type(self) -> _AttrValueType: # noqa: D102
# def type(self, val: str) -> None: # noqa: D102
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# def appendChild(self, child: Node) -> Node: # noqa: D102
# def insertBefore(self, child: Node, ref_node: Node) -> Node: # noqa: D102
# def removeChild(self, child: Node) -> Node: # noqa: D102
# def replaceChild(self, new_child: Node, old_child: Node
# ) -> Node: # noqa: D102
# def childNodes(self) -> NodeList: # noqa: D102
# def empty(self) -> None: # noqa: D102
# def textContent(self, text: str) -> None: # type: ignore
# def html(self) -> str:
# def innerHTML(self) -> str:
# def innerHTML(self, html: str) -> None:
# def NewTagClass(class_name: str, tag: str = None,
# bases: Union[type, Iterable] = (Tag, ),
# **kwargs: Any) -> type:
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# def value(self) -> str:
# def value(self, value: str) -> None:
# def __init__(self, *args: Any, type: str = 'text/javascript',
# **kwargs: Any) -> None:
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# H1 = NewTagClass('H1')
# H2 = NewTagClass('H2')
# H3 = NewTagClass('H3')
# H4 = NewTagClass('H4')
# H5 = NewTagClass('H5')
# H6 = NewTagClass('H6')
# P = NewTagClass('P')
# A = NewTagClass('A', 'a', (Tag, HTMLAnchorElement))
# U = NewTagClass('U')
#
# Path: tests/base.py
# class TestCase(unittest.TestCase):
# """Base class for testing wdom modules.
#
# This class is a sub class of the ``unittest.TestCase``. After all test
# methods, reset wdom's global objects like document, application, and
# elements. If you use ``tearDown`` method, do not forget to call
# ``super().tearDown()``.
# """
#
# def setUp(self) -> None:
# """Reset WDOM states."""
# super().setUp()
# reset()
#
# def tearDown(self) -> None:
# """Reset WDOM states."""
# reset()
# super().tearDown()
#
# def assertIsTrue(self, bl: bool) -> None:
# """Check arg is exactly True, not truthy."""
# self.assertIs(bl, True)
#
# def assertIsFalse(self, bl: bool) -> None:
# """Check arg is exactly False, not falsy."""
# self.assertIs(bl, False)
, which may contain function names, class names, or code. Output only the next line. | logger = logging.getLogger('wdom') |
Based on the snippet: <|code_start|>
_argv = copy(sys.argv)
_config = copy(vars(config))
def reset_options():
sys.argv = copy(_argv)
for k, v in _config.items():
setattr(config, k, v)
class TestOptions(TestCase):
def tearDown(self):
reset_options()
super().tearDown()
def test_default_loglevel(self):
parse_command_line()
set_loglevel()
logger = logging.getLogger('wdom')
self.assertEqual(logger.getEffectiveLevel(), logging.INFO)
@parameterized.expand([
('debug', logging.DEBUG),
('info', logging.INFO),
('warn', logging.WARN),
('error', logging.ERROR),
<|code_end|>
, predict the immediate next line with the help of imports:
import sys
import logging
import unittest
from copy import copy
from importlib import reload
from parameterized import parameterized
from wdom.options import parse_command_line, config, set_loglevel
from wdom import tag
from .base import TestCase
from wdom.themes import default
from wdom.themes import bootstrap3
and context (classes, functions, sometimes code) from other files:
# Path: wdom/options.py
# def level_to_int(level: Union[str, int]) -> int:
# def set_loglevel(level: Union[int, str, None] = None) -> None:
# def parse_command_line() -> Namespace:
#
# Path: wdom/tag.py
# class Tag(WdomElement):
# class NestedTag(Tag):
# class Input(Tag, HTMLInputElement):
# class Textarea(Tag, HTMLTextAreaElement): # noqa: D204
# class Script(Tag, HTMLScriptElement): # noqa: D204
# class RawHtmlNode(Tag):
# def __init__(self, *args: Any, attrs: Dict[str, _AttrValueType] = None,
# **kwargs: Any) -> None:
# def _clone_node(self) -> 'Tag':
# def type(self) -> _AttrValueType: # noqa: D102
# def type(self, val: str) -> None: # noqa: D102
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# def appendChild(self, child: Node) -> Node: # noqa: D102
# def insertBefore(self, child: Node, ref_node: Node) -> Node: # noqa: D102
# def removeChild(self, child: Node) -> Node: # noqa: D102
# def replaceChild(self, new_child: Node, old_child: Node
# ) -> Node: # noqa: D102
# def childNodes(self) -> NodeList: # noqa: D102
# def empty(self) -> None: # noqa: D102
# def textContent(self, text: str) -> None: # type: ignore
# def html(self) -> str:
# def innerHTML(self) -> str:
# def innerHTML(self, html: str) -> None:
# def NewTagClass(class_name: str, tag: str = None,
# bases: Union[type, Iterable] = (Tag, ),
# **kwargs: Any) -> type:
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# def value(self) -> str:
# def value(self, value: str) -> None:
# def __init__(self, *args: Any, type: str = 'text/javascript',
# **kwargs: Any) -> None:
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# H1 = NewTagClass('H1')
# H2 = NewTagClass('H2')
# H3 = NewTagClass('H3')
# H4 = NewTagClass('H4')
# H5 = NewTagClass('H5')
# H6 = NewTagClass('H6')
# P = NewTagClass('P')
# A = NewTagClass('A', 'a', (Tag, HTMLAnchorElement))
# U = NewTagClass('U')
#
# Path: tests/base.py
# class TestCase(unittest.TestCase):
# """Base class for testing wdom modules.
#
# This class is a sub class of the ``unittest.TestCase``. After all test
# methods, reset wdom's global objects like document, application, and
# elements. If you use ``tearDown`` method, do not forget to call
# ``super().tearDown()``.
# """
#
# def setUp(self) -> None:
# """Reset WDOM states."""
# super().setUp()
# reset()
#
# def tearDown(self) -> None:
# """Reset WDOM states."""
# reset()
# super().tearDown()
#
# def assertIsTrue(self, bl: bool) -> None:
# """Check arg is exactly True, not truthy."""
# self.assertIs(bl, True)
#
# def assertIsFalse(self, bl: bool) -> None:
# """Check arg is exactly False, not falsy."""
# self.assertIs(bl, False)
. Output only the next line. | ]) |
Continue the code snippet: <|code_start|>
ul = Ul()
ul.innerHTML = '''\
<li>item1</li>
<li>item2</li>
<|code_end|>
. Use current file imports:
from wdom.tag import Ul
and context (classes, functions, or code) from other files:
# Path: wdom/tag.py
# class Tag(WdomElement):
# class NestedTag(Tag):
# class Input(Tag, HTMLInputElement):
# class Textarea(Tag, HTMLTextAreaElement): # noqa: D204
# class Script(Tag, HTMLScriptElement): # noqa: D204
# class RawHtmlNode(Tag):
# def __init__(self, *args: Any, attrs: Dict[str, _AttrValueType] = None,
# **kwargs: Any) -> None:
# def _clone_node(self) -> 'Tag':
# def type(self) -> _AttrValueType: # noqa: D102
# def type(self, val: str) -> None: # noqa: D102
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# def appendChild(self, child: Node) -> Node: # noqa: D102
# def insertBefore(self, child: Node, ref_node: Node) -> Node: # noqa: D102
# def removeChild(self, child: Node) -> Node: # noqa: D102
# def replaceChild(self, new_child: Node, old_child: Node
# ) -> Node: # noqa: D102
# def childNodes(self) -> NodeList: # noqa: D102
# def empty(self) -> None: # noqa: D102
# def textContent(self, text: str) -> None: # type: ignore
# def html(self) -> str:
# def innerHTML(self) -> str:
# def innerHTML(self, html: str) -> None:
# def NewTagClass(class_name: str, tag: str = None,
# bases: Union[type, Iterable] = (Tag, ),
# **kwargs: Any) -> type:
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# def value(self) -> str:
# def value(self, value: str) -> None:
# def __init__(self, *args: Any, type: str = 'text/javascript',
# **kwargs: Any) -> None:
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# H1 = NewTagClass('H1')
# H2 = NewTagClass('H2')
# H3 = NewTagClass('H3')
# H4 = NewTagClass('H4')
# H5 = NewTagClass('H5')
# H6 = NewTagClass('H6')
# P = NewTagClass('P')
# A = NewTagClass('A', 'a', (Tag, HTMLAnchorElement))
# U = NewTagClass('U')
. Output only the next line. | <li>item3</li> |
Given snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def tearDownModule():
close_webdriver()
CURDIR = path.dirname(path.abspath(__file__))
ROOTDIR = path.dirname(path.dirname(CURDIR))
ENV = os.environ.copy()
ENV['PYTHONPATH'] = ROOTDIR
src_base = '''
import sys # noqa: F401
import asyncio
from wdom.tag import H1
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
import os
import asyncio
import subprocess
import unittest
from os import path
from tempfile import NamedTemporaryFile
from selenium.common.exceptions import NoSuchElementException
from syncer import sync
from ..base import TestCase
from .base import free_port, browser_implict_wait
from .base import get_webdriver, close_webdriver
and context:
# Path: tests/base.py
# class TestCase(unittest.TestCase):
# """Base class for testing wdom modules.
#
# This class is a sub class of the ``unittest.TestCase``. After all test
# methods, reset wdom's global objects like document, application, and
# elements. If you use ``tearDown`` method, do not forget to call
# ``super().tearDown()``.
# """
#
# def setUp(self) -> None:
# """Reset WDOM states."""
# super().setUp()
# reset()
#
# def tearDown(self) -> None:
# """Reset WDOM states."""
# reset()
# super().tearDown()
#
# def assertIsTrue(self, bl: bool) -> None:
# """Check arg is exactly True, not truthy."""
# self.assertIs(bl, True)
#
# def assertIsFalse(self, bl: bool) -> None:
# """Check arg is exactly False, not falsy."""
# self.assertIs(bl, False)
#
# Path: tests/test_selenium/base.py
# def _get_chromedriver_path() -> str:
# def get_chrome_options() -> webdriver.ChromeOptions:
# def start_webdriver() -> None:
# def close_webdriver() -> None:
# def get_webdriver() -> WebDriver:
# def _clear() -> None:
# def start_remote_browser() -> None:
# def start_browser() -> None:
# def close_remote_browser() -> None:
# def get_remote_browser() -> WebDriver:
# def __init__(self, conn: Connection) -> None:
# def set_element_by_id(self, id: int) -> Union[bool, str]:
# def quit(self) -> str:
# def close(self) -> str:
# def _execute_method(self, method: str, args: Iterable[str]) -> None:
# def run(self) -> None: # noqa: C901
# def wait_for() -> str:
# async def wait_coro() -> str:
# def _get_properties(cls: type) -> Set[str]:
# def __getattr__(self, attr: str) -> Connection:
# def wrapper(*args: str) -> str:
# def start(self) -> None:
# def tearDown(self) -> None:
# def port(self) -> Optional[str]:
# def wait(self, timeout: float = None, times: int = 1) -> None:
# def wait_until(self, func: Callable[[], Any],
# timeout: float = None) -> None:
# def _set_element(self, node: Element) -> Union[bool, str]:
# def set_element(self, node: Element, timeout: float = None) -> bool:
# def setUpClass(cls) -> None: # noqa: D102
# def tearDownClass(cls) -> None: # noqa: D102
# def start(self) -> None:
# def start_server(port: int) -> None:
# def tearDown(self) -> None:
# def wait(self, timeout: float = None, times: int = 1) -> None:
# def wait_until(self, func: Callable[[], Any],
# timeout: float = None) -> None:
# def send_keys(self, element: Element, keys: str) -> None:
# class BrowserController:
# class Controller:
# class ProcessController(Controller):
# class RemoteBrowserController(Controller):
# class RemoteElementController(Controller):
# class TimeoutError(Exception):
# class RemoteBrowserTestCase:
# class WebDriverTestCase:
#
# Path: tests/test_selenium/base.py
# def get_webdriver() -> WebDriver:
# """Return WebDriver of current process.
#
# If it is not started yet, start and return it.
# """
# if globals().get('local_webdriver') is None:
# start_webdriver()
# return local_webdriver
#
# def close_webdriver() -> None:
# """Close WebDriver."""
# global local_webdriver
# if local_webdriver is not None:
# local_webdriver.close()
# local_webdriver = None
which might include code, classes, or functions. Output only the next line. | from wdom.document import get_document |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.