Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line after this snippet: <|code_start|>
HERE = os.path.dirname(os.path.abspath(__file__))
class TestSpore(TestCase):
def test_spore(self):
<|code_end|>
using the current file's imports:
from unittest import TestCase
from werkzeug.wrappers import BaseResponse
from werkzeug.test import Client
... | client = Client(WSGIDispatcher([ApiApp], name='ApiApp', version='1.0', |
Based on the snippet: <|code_start|>
HERE = os.path.dirname(os.path.abspath(__file__))
class TestSpore(TestCase):
def test_spore(self):
<|code_end|>
, predict the immediate next line with the help of imports:
from unittest import TestCase
from werkzeug.wrappers import BaseResponse
from werkzeug.test import Cl... | client = Client(WSGIDispatcher([ApiApp], name='ApiApp', version='1.0', |
Given the code snippet: <|code_start|>ViConstString = _ctypes.POINTER(ViChar)
# Part Two: Type Assignments for VISA only, see spec table 3.1.2. The
# difference to the above is of no significance in Python, so I use it here
# only for easier synchronisation with the spec.
ViAccessMode, ViPAccessMode = _type_pair(Vi... | ViHndlr = FUNCTYPE(ViStatus, ViSession, ViEventType, ViEvent, ViAddr) |
Given the following code snippet before the placeholder: <|code_start|> if member.type == tarfile.DIRTYPE:
git_dirs.add(name)
else:
git_files.add(name)
return git_files, git_dirs
def _git_ls_files_and_dirs(toplevel):
# use git archive instead of git l... | if not is_toplevel_acceptable(toplevel): |
Next line prediction: <|code_start|>
def _git_ls_files_and_dirs(toplevel):
# use git archive instead of git ls-file to honor
# export-ignore git attribute
cmd = ["git", "archive", "--prefix", toplevel + os.path.sep, "HEAD"]
proc = subprocess.Popen(
cmd, stdout=subprocess.PIPE, cwd=toplevel, std... | return scm_find_files(path, git_files, git_dirs) |
Here is a snippet: <|code_start|>
log = logging.getLogger(__name__)
def _git_toplevel(path):
try:
cwd = os.path.abspath(path or ".")
<|code_end|>
. Write the next line using the current file imports:
import logging
import os
import subprocess
import tarfile
from .file_finder import is_toplevel_acceptabl... | out, err, ret = do_ex(["git", "rev-parse", "HEAD"], cwd=cwd) |
Given the following code snippet before the placeholder: <|code_start|>log = logging.getLogger(__name__)
def _git_toplevel(path):
try:
cwd = os.path.abspath(path or ".")
out, err, ret = do_ex(["git", "rev-parse", "HEAD"], cwd=cwd)
if ret != 0:
# BAIL if there is no commit
... | trace("find files toplevel", out) |
Using the snippet: <|code_start|>
def parse_pkginfo(root, config=None):
pkginfo = os.path.join(root, "PKG-INFO")
trace("pkginfo", pkginfo)
<|code_end|>
, determine the next line of code. You have imports:
import os
from .utils import data_from_mime
from .utils import trace
from .version import meta
from .ve... | data = data_from_mime(pkginfo) |
Here is a snippet: <|code_start|>
def parse_pkginfo(root, config=None):
pkginfo = os.path.join(root, "PKG-INFO")
trace("pkginfo", pkginfo)
data = data_from_mime(pkginfo)
version = data.get("Version")
if version != "UNKNOWN":
<|code_end|>
. Write the next line using the current file imports:
impo... | return meta(version, preformatted=True, config=config) |
Here is a snippet: <|code_start|>
def parse_pkginfo(root, config=None):
pkginfo = os.path.join(root, "PKG-INFO")
trace("pkginfo", pkginfo)
data = data_from_mime(pkginfo)
version = data.get("Version")
if version != "UNKNOWN":
return meta(version, preformatted=True, config=config)
def par... | version = tag_to_version( |
Given the code snippet: <|code_start|>
class Workdir:
def __init__(self, path):
require_command(self.COMMAND)
self.path = path
def do_ex(self, cmd):
return do_ex(cmd, cwd=self.path)
<|code_end|>
, generate the next line using the imports in this file:
from .utils import do
from .util... | def do(self, cmd): |
Given snippet: <|code_start|>
class Workdir:
def __init__(self, path):
require_command(self.COMMAND)
self.path = path
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .utils import do
from .utils import do_ex
from .utils import require_command
and context:... | def do_ex(self, cmd): |
Predict the next line for this snippet: <|code_start|> ).startswith(os.pardir):
# a symlink to a directory not outside path:
# we keep it in the result and don't walk its content
res.append(os.path.join(path, os.path.relpath(dirpath, path)))
dirnames[:] = []
... | trace(toplevel, ignored) |
Next line prediction: <|code_start|> stderr=devnull,
)
return os.path.normcase(os.path.realpath(out.strip()))
except subprocess.CalledProcessError:
# hg returned error, we are not in a mercurial repo
return None
except OSError:
# hg command not found, p... | if not is_toplevel_acceptable(toplevel): |
Based on the snippet: <|code_start|> except subprocess.CalledProcessError:
# hg returned error, we are not in a mercurial repo
return None
except OSError:
# hg command not found, probably
return None
def _hg_ls_files_and_dirs(toplevel):
hg_files = set()
hg_dirs = {toplev... | return scm_find_files(path, hg_files, hg_dirs) |
Next line prediction: <|code_start|>
def _hg_toplevel(path):
try:
with open(os.devnull, "wb") as devnull:
out = subprocess.check_output(
["hg", "root"],
cwd=(path or "."),
universal_newlines=True,
stderr=devnull,
)
... | out, err, ret = do_ex(["hg", "files"], cwd=toplevel) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
"""Test code for envVocabulary for SmartContainers.
This module provides tests for the ComputationalEnvironment ontology.
"""
tstuuid = str(uuid.uuid4())
uuidurn = "urn:uuid:"+tstuuid
def test_create_graph():
<|code_end|>
, generate the next line using t... | vocab = envVocabulary.envVocabulary() |
Here is a snippet: <|code_start|>
@pytest.fixture(scope="session")
def createClient():
myclient = None
# Find docker-machine environment variables
docker_host = os.getenv("DOCKER_HOST")
docker_cert_path = os.getenv("DOCKER_CERT_PATH")
docker_machine_name = os.getenv("DOCKER_MACHINE_NAME")
# Lo... | myclient = client.scClient(base_url=docker_socket_file, version="auto") |
Using the snippet: <|code_start|>
@pytest.fixture
def runner():
return CliRunner()
def test_cli(runner):
<|code_end|>
, determine the next line of code. You have imports:
import pytest
from click.testing import CliRunner
from sc import cli
and context (class names, function names, or code) available:
# Path: ... | result = runner.invoke(cli.cli) |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
"""Tests for Smart Containers buildProcessor.
Tests for Smart Containers buildProcessor.
This module provides functions for processing Build commands.
"""
base_dir = os.path.dirname(os.path.abspath(__file__))
class BuildProcessorTestCase(unittest.TestCase):... | buildProcessor.buildProcessor(), |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
"""Test code for RDFlib Graph Factory for SmartContainers.
This module provides a common interface to all RDFlib graphs created by all
vocabularies. New vocabularies should subclass graphFactory.
"""
tstuuid = str(uuid.uuid4())
uuidurn = "urn:uuid:"+tstuuid
... | class Vocabulary1(baseVocabulary.baseVocabulary): |
Given snippet: <|code_start|> Version of get_events which returns immediately
"""
return self._events[:]
async def _input_callback(self, ev):
"""
Coroutine called by the evdev module when data is available
"""
self._expire()
if ev.keystate == ev.key_... | if self._logger.isEnabledFor(LOG_TRACE): |
Next line prediction: <|code_start|>
_KeyInputEvent = NamedTuple('KeyInputEvent', \
[('timestamp', float),
('expire_time', float),
('keycode', str),
('scancode', str),
('keystate', int),
('coords', list),
('data', dict)])
class KeyInputEvent(_KeyInputEvent, object):
"""
Conta... | return clamp(self.time_remaining / duration, 0.0, 1.0) |
Based on the snippet: <|code_start|> if not self._opened:
return
if event.type == evdev.ecodes.EV_KEY:
ev = evdev.categorize(event)
for callback in self._event_callbacks:
await callback(ev)
... | task = ensure_future(self._evdev_callback(event_device)) |
Predict the next line after this snippet: <|code_start|> 'sphinx.ext.viewcode',
'sphinx_autodoc_annotation'
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
#... | version = __version__ |
Continue the code snippet: <|code_start|>
def test_config_loaded():
assert Hardware.get_device(0x210).product_id == 0x0210
def test_recursive_attribute():
assert Hardware.get_device(0x210).vendor_id == 0x1532
def test_type_coercion():
hw = Hardware.get_device(0x210)
<|code_end|>
. Use current file impor... | assert isinstance(hw.key_mapping, KeyMapping) |
Here is a snippet: <|code_start|>
def test_config_loaded():
assert Hardware.get_device(0x210).product_id == 0x0210
def test_recursive_attribute():
assert Hardware.get_device(0x210).vendor_id == 0x1532
def test_type_coercion():
hw = Hardware.get_device(0x210)
assert isinstance(hw.key_mapping, KeyMapp... | assert isinstance(coord, Point) |
Next line prediction: <|code_start|>
def test_config_loaded():
assert Hardware.get_device(0x210).product_id == 0x0210
def test_recursive_attribute():
assert Hardware.get_device(0x210).vendor_id == 0x1532
def test_type_coercion():
hw = Hardware.get_device(0x210)
assert isinstance(hw.key_mapping, KeyM... | assert isinstance(space, PointList) |
Based on the snippet: <|code_start|> def get_fx(self, fx_name) -> BaseFX:
"""
Get the requested effects implementation.
Returns the last active object if appropriate.
:param fx_name: The string name of the effect object
"""
if self.current_fx[0] == fx_name:
... | argsdict = get_args_dict(fx) |
Given the following code snippet before the placeholder: <|code_start|>
class BaseFX(HasTraits):
# meta
hidden = Bool(default_value=False, read_only=True)
description = Unicode('_unimplemented_', read_only=True)
def __init__(self, fxmod, driver, *args, **kwargs):
super(BaseFX, self).__init__... | key = camel_to_snake(re.sub(r'FX$', '', k)) |
Continue the code snippet: <|code_start|>#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
# License for more details.
#
# pylint: disable=protecte... | value = to_color(value) |
Using the snippet: <|code_start|> raise TypeError("Object must be a dict (was: %s)" % obj)
traits = {}
values = {}
for k, v in obj.items():
if '__value__' in v:
values[k] = v.pop('__value__')
trait = dict_as_trait(v)
if trait is None:
continue
... | argsdict = ArgsDict() |
Given the code snippet: <|code_start|> self._logger = driver.logger
self._driver = driver
self._status = status
self._transaction_id = transaction_id
self._remaining_packets = remaining_packets
self._protocol_type = protocol_type
self._command_class = command_cl... | if self._logger.isEnabledFor(LOG_PROTOCOL_TRACE): |
Continue the code snippet: <|code_start|>
def run(self, delay: float = None, timeout_cb=None) -> bool:
"""
Run this report and retrieve the result from the hardware.
Sends the feature report and parses the result. A small delay
is required between calls to the hardware or a BUSY st... | self._driver.last_cmd_time = smart_delay(delay, self._driver.last_cmd_time, |
Predict the next line after this snippet: <|code_start|> REQ_HEADER = '=BHBBBB'
RSP_HEADER = '=BBHBBBB'
REQ_REPORT_ID = b'\x02'
RSP_REPORT_ID = b'\x00'
BUF_SIZE = 90
DATA_BUF_SIZE = 80
# Time to sleep between requests, needed to avoid BUSY replies
CMD_DELAY_TIME = 0.007
def __init... | self._data = ByteArgs(RazerReport.DATA_BUF_SIZE, data=data) |
Given the following code snippet before the placeholder: <|code_start|> if driver is None:
self._parser.error("Invalid device: %s" % self._args.device)
else:
dev_paths = self._client.get_device_paths()
if len(dev_paths) == 1:
driver = self._cli... | value = dbus_prepare(value)[0] |
Given snippet: <|code_start|>
@property
def version(self):
return 'uchroma-%s' % __version__
def _add_subparsers(self, sub):
pass
def get_driver(self):
if hasattr(self._args, 'device') and self._args.device is not None:
driver = self._client.get_device(self._arg... | name = snake_to_camel(name) |
Given the following code snippet before the placeholder: <|code_start|> autocomplete(self._parser)
self._args, self._unparsed = self._parser.parse_known_args(self._unparsed, self._args)
if not hasattr(self._args, 'func'):
self._parser.print_help()
self._parser.exit(1)
... | return 'uchroma-%s' % __version__ |
Based on the snippet: <|code_start|>"""
Various helper functions that are used across the library.
"""
class UChromaConsoleUtil(object):
"""
A base class for command-line utilities
"""
def __init__(self):
self._parser = ArgumentParser(description=self.description, add_help=False)
... | self._client = UChromaClient() |
Predict the next line after this snippet: <|code_start|> for field in self.__slots__:
if field not in ['parent', '_children']:
tmp[field] = self.get(field)
return self.__class__(**tmp)
return tuple(flat)
def _asdict(self) -> OrderedDict:
o... | odict = ArgsDict({x: getattr(self, x) for x in fields}) |
Predict the next line for this snippet: <|code_start|>
class EnumTest(Enum):
FIRST = 1
SECOND = 2
THIRD = 3
def test_primitives():
<|code_end|>
with the help of current file imports:
import sys
from enum import Enum
from gi.repository import GLib
from grapefruit import Color
from traitlets import Int
f... | assert dbus_prepare(23)[1] == 'n' |
Using the snippet: <|code_start|> if arg is None:
return (0, 0, 0)
if isinstance(arg, Color):
return arg.intTuple[:3]
if isinstance(arg, str):
return Color.NewFromHtml(arg).intTuple[:3]
if isinstance(arg, tuple) or isinstance(arg, list):
if arg[0] is None:
retu... | colorarg = autocast_decorator(ColorType, to_color) |
Based on the snippet: <|code_start|>
def rgb_from_tuple(arg: tuple) -> Color:
"""
Convert a 3-tuple of ints or floats to a Grapefruit color
:param arg: The RGB tuple to convert
:return: The Color object
"""
if len(arg) >= 3:
if arg[0] is None:
return Color.NewFromRgb(0, 0, ... | return tuple([clamp(round(x), 0, 255) for x in arg[:3]]) |
Continue the code snippet: <|code_start|> return [to_rgb(item) for item in arg]
return rgb_to_int_tuple(arg)
raise TypeError('Unable to parse color from \'%s\' (%s)' % (arg, type(arg)))
"""
Decorator to parse various color representations
Invokes to_color on any arguments listed in decls. Thi... | s = lerp(start[1], end[1], amount) |
Based on the snippet: <|code_start|> or isinstance(arg[0], str) or isinstance(arg[0], Color):
return [to_rgb(item) for item in arg]
return rgb_to_int_tuple(arg)
raise TypeError('Unable to parse color from \'%s\' (%s)' % (arg, type(arg)))
"""
Decorator to parse various color rep... | h = lerp_degrees(start[0], end[0], amount) |
Given the following code snippet before the placeholder: <|code_start|>GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
"""
test_gwf.py
~~~~~~~~~~~
Tests to ensure that gwf works so ... | out, err = gwf.perform_command_and_validate(proc, "Shouldn't happen") |
Given snippet: <|code_start|>MOCK_SERIAL_RESPONSE = "line"
vent_disc_iterator = iter([1, 1] + [0] * 10000)
def test_get_configuration_from_main():
with patch("raspi.scripts.get_serial.open") as mock_open:
with patch("raspi.scripts.get_serial.serial") as mock_serial:
with patch("raspi.scripts.g... | config_dict = get_configuration("foo/bar") |
Next line prediction: <|code_start|> "tty_file": "foo/bar",
"data_path": "pi/mock/data",
"refresh_rate": 0.01,
"vent_disconnect_tolerance": 0.01,
}
MOCK_CONFIG_FILE = """
[config]
baudrate=38400
tty_file=foo/bar
data_path=pi/mock/data
refresh_rate=1000
vent_disconnect_tolerance=1
"""
MOCK_SERIAL_RESPONSE... | get_serial("testing") |
Predict the next line for this snippet: <|code_start|>
register = template.Library()
@register.filter
def as_html(invoice):
template = loader.get_template('invoicing/formatters/html.html')
<|code_end|>
with the help of current file imports:
from django import template
from django.template import loader, Contex... | formatter = HTMLFormatter(invoice) |
Here is a snippet: <|code_start|>
SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))
def _test_load_store_instrument(source_lsdsng, lsdinst_path, original_index):
proj = load_lsdsng(source_lsdsng)
proj.song.instruments.import_from_file(0x2a, lsdinst_path)
target_instr = proj.song.instruments[0x2a]
... | with temporary_file() as tmpfile: |
Based on the snippet: <|code_start|> def command(self):
"""the effect's command"""
return self._params.fx[self._table_index][self._fx_index]
@command.setter
def command(self, value):
self._params.fx[self._table_index][self._fx_index] = value
@property
def value(self):
... | for i in range(STEPS_PER_TABLE)] |
Based on the snippet: <|code_start|> def name(self):
"""the instrument's name (5 characters, zero-padded)"""
instr_name = self.song.song_data.instrument_names[self.index]
if type(instr_name) == bytes:
instr_name = instr_name.decode('utf-8')
return instr_name
@name.s... | assert_index_sane(self.data.table, len(self.song.tables)) |
Predict the next line after this snippet: <|code_start|>
EMPTY_SAMPLE_NAME = '\0--'
# WAVs are 8 bits/sample PCM-encoded @ 11468 Hz
# These are parameters passed to Wave_write objects during writing
WAVE_NUM_CHANNELS = 1
WAVE_SAMPLE_WIDTH = 1
WAVE_FRAMERATE = 11468
WAVE_PARAMS = (WAVE_NUM_CHANNELS, WAVE_SAMPLE_WI... | self._data = b.parse(fp, lsdj_rom_kits) |
Given the following code snippet before the placeholder: <|code_start|> else:
sample_start, sample_end = self._get_sample_data_bounds(index)
return (sample_end - sample_start + 1)
def _get_sample_data(self, index):
if not self._sample_used(index):
return None
... | value, KIT_SAMPLE_NAME_LENGTH, '-') |
Continue the code snippet: <|code_start|> with open(rom_file, 'rb') as fp:
self._data = b.parse(fp, lsdj_rom_kits)
# Don't include the last four kits in the kit list, which are reserved
# for the speech synthesizer
self._kits = list(map(lambda k: Kit(k), self._data.kits[:-4])... | range(SAMPLES_PER_KIT))) |
Here is a snippet: <|code_start|>
def __str__(self):
return '\n'.join(map(str, self._kits))
def __iter__(self):
for kit in self._kits:
yield kit
class Kit(object):
"""An individual sample kit"""
def __init__(self, data):
self._data = data
if self._data.ma... | self._data.kit_name = fixed_width_string(value, KIT_NAME_LENGTH) |
Using the snippet: <|code_start|>
# Because of data layout, indices for bits are
#
# 7, 6, 5, ..., 0, unused, 14, 13, ..., 8
#
# so the indexing logic is a little funky.
if self.index < 8:
self.force_loop_index = 7 - self.index
else:
self.... | sample_start = sample_start - SAMPLE_START_ADDRESS |
Given the code snippet: <|code_start|>
@sample_data.setter
def sample_data(self, sample_data):
# For simplicity, we'll just pack samples into their new locations and
# overwrite the sample memory for the kit.
new_sample_ends = []
new_sample_data = []
for i in range(SAM... | if len(new_sample_data) < MAX_SAMPLE_LENGTH * 2: |
Given the code snippet: <|code_start|>
def __str__(self):
return '\n'.join(map(str, self._kits))
def __iter__(self):
for kit in self._kits:
yield kit
class Kit(object):
"""An individual sample kit"""
def __init__(self, data):
self._data = data
if self._da... | self._data.kit_name = fixed_width_string(value, KIT_NAME_LENGTH) |
Predict the next line for this snippet: <|code_start|> @phase_amount.setter
def phase_amount(self, value):
self._params.phase_amount = value
self._overwrite_lock.disable()
@property
def vertical_shift(self):
"""the amount to shift the waveform vertically"""
return self._p... | for wave_index in range(WAVES_PER_SYNTH)] |
Predict the next line for this snippet: <|code_start|>
SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))
def test_wave_synth_overwrite_locks():
test_project = os.path.join(SCRIPT_DIR, 'test_data', 'UNTOLDST.lsdsng')
<|code_end|>
with the help of current file imports:
import os
from nose.tools import asse... | project = load_lsdsng(test_project) |
Given snippet: <|code_start|>
class Chain(object):
"""A chain is a sequence of phrases for a single channel. Each phrase can be
transposed by a number of semitones.
"""
def __init__(self, song, index):
self.song = song
self.index = index
self.transposes = self.song.song_data.... | self.phrases = ObjectLookupDict( |
Given snippet: <|code_start|>
class EnvelopeMixin(object):
@property
def envelope(self):
"""the noise instrument's volume envelope (8-bit integer)"""
return self.data.envelope
@envelope.setter
def envelope(self, value):
self.data.envelope = value
@staticmethod
def imp... | return Vibrato(self.data.vibrato) |
Continue the code snippet: <|code_start|>
def test_kit_used():
test_rom = os.path.join(os.path.dirname(__file__), "test_data",
"lsdj_onlykits.gb")
<|code_end|>
. Use current file imports:
import os
import tempfile
from nose.tools import assert_equal, raises
from .kits import Kits
fro... | kits = Kits(test_rom) |
Continue the code snippet: <|code_start|> sigma_position : float
Parameter of the Generic String Kernel controlling the penalty incurred when two n-grams are not sharing the
same position.
max_n_gram_count : int
The number of n-grams in the training string of highest length.
feature_s... | self.feature_space = build_feature_space_with_positions(alphabet, self.n, Y) |
Given snippet: <|code_start|> def _get_n_gram_count_in_each_y(self, n, Y):
y_n_gram_counts = numpy.array([len(y) - n + 1 for y in Y])
return y_n_gram_counts
def compute_weights(self, y_weights, y_length):
"""Compute the inference graph weights
Parameters
----------
... | position_weights = compute_position_weights(i, self.max_n_gram_count, self.sigma_position).reshape(-1, 1) |
Predict the next line for this snippet: <|code_start|> """Create the output feature space for the Generic String kernel
Parameters
----------
alphabet : list
list of letters
n : int
n-gram length
Y : array, [n_samples, ]
The training st... | y_y_similarity = element_wise_kernel(Y, sigma_position, n, alphabet) |
Using the snippet: <|code_start|>__author__ = 'amelie'
class Alphabet:
latin = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
'v', 'w', 'x', 'y', 'z']
def get_n_gram_to_index(alphabet, n):
n_grams = get_n_grams(alphabet, n)
index... | raise InvalidNGramLengthError(n) |
Continue the code snippet: <|code_start|>__author__ = 'amelie'
class TestPolynomialKernel(unittest2.TestCase):
def setUp(self):
self.X_one = [[1, 2]]
self.X_two = [[1, 0], [1, 3]]
self.gram_matrix_degree_one_x_one_x_one = [[5.]]
self.gram_matrix_degree_two_x_one_x_one = [[25.]]
... | kernel = PolynomialKernel(degree=1, bias=0, is_normalized=False) |
Based on the snippet: <|code_start|>
def get_gs_node_creator(n, graph, graph_weights, y_length, n_gram_to_index, n_grams, sigma_position):
"""Create the bounds and the node creator for the branch and bound search of the generic string kernel.
Only takes in account the position penalties when comparing strings,... | position_weights = compute_position_weights(0, y_length, sigma_position) |
Using the snippet: <|code_start|> return node_creator
def get_gs_similarity_node_creator(alphabet, n, graph, graph_weights, y_length, gs_kernel):
"""Create the bounds and the node creator for the branch and bound search of the generic string kernel.
Takes in account the position and the n-gram penalties w... | n_gram_to_index = get_n_gram_to_index(alphabet, n) |
Continue the code snippet: <|code_start|>
def get_gs_similarity_node_creator(alphabet, n, graph, graph_weights, y_length, gs_kernel):
"""Create the bounds and the node creator for the branch and bound search of the generic string kernel.
Takes in account the position and the n-gram penalties when comparing str... | n_grams = get_n_grams(alphabet, n) |
Given the code snippet: <|code_start|>__author__ = 'amelie'
class TestStructuredKernelRidgeRegression(unittest2.TestCase):
def setUp(self):
self.setup_x_and_y()
self.setup_kernel()
self.setup_learners()
def setup_x_and_y(self):
self.X_train = [[1., 0], [0.5, 1]]
self... | self.structured_krr = StructuredKernelRidgeRegression(alpha=0, kernel=self.kernel_mock, |
Here is a snippet: <|code_start|> self.gram_matrix_plus_one_half_diagonal_inverse = [[0.75, -0.25], [-0.25, 0.75]]
self.gram_matrix_x_train_x_test = [[0, 1, 0], [0, 0, 1]]
self.Y_weights = [[0, 0], [1.33333333, -0.66666667], [-0.66666667, 1.33333333]]
self.kernel_mock = Mock(side_effect=[... | InferenceFitParameters.__init__ = inference_parameter_mock |
Predict the next line after this snippet: <|code_start|> self.setup_alphabet()
self.setup_feature_space()
self.setup_patch()
def setup_alphabet(self):
self.alphabet = ['a', 'b']
self.b = ['b']
self.abb = ['abb']
self.abaaa = ['abaaa']
self.abb_abaaa = ... | feature_space = build_feature_space_without_positions(alphabet=self.alphabet, n=1, Y=self.b) |
Given the code snippet: <|code_start|> def test_one_gram_three_letter_y_n_gram_feature_space_has_three_n_grams(self):
self.n_gram_to_index_patch.start().return_value = self.one_gram_to_index
feature_space = build_feature_space_without_positions(alphabet=self.alphabet, n=1, Y=self.abb)
numpy... | feature_space = build_feature_space_with_positions(n=1, alphabet=self.alphabet, Y=self.b) |
Using the snippet: <|code_start|> self.n_gram_to_index_patch.start().return_value = self.one_gram_to_index
feature_space = build_feature_space_without_positions(alphabet=self.alphabet, n=1, Y=self.b)
numpy.testing.assert_array_equal(feature_space.toarray(), self.feature_space_one_gram_b)
d... | with self.assertRaises(InvalidNGramError): |
Based on the snippet: <|code_start|> Training dataset.
"""
return __load_peptide_dataset('camps.pickle')
def load_bpps_dataset():
"""Load the BPPs dataset consisting of 31 bradykinin-potentiating pentapeptides.
Returns
-------
train_dataset: StandardDataset
Training dataset.
... | def load_amino_acids_and_descriptors(file_name=AminoAcidFile.blosum62_natural): |
Here is a snippet: <|code_start|> Creates a sparse matrix representation of the n-grams in each training string. The representation takes in account
the positions of the n-grams in the strings, This is used to compute the weights of the graph during the inference
phase.
Attributes
----------
n :... | self.feature_space = build_feature_space_with_positions(alphabet, self.n, Y) |
Next line prediction: <|code_start|> max_length : int
Maximum position.
Returns
-------
position_matrix : array, shape = [max_length, max_length]
Similarity of each position with all the other positions.
"""
position_matrix = compute_position_weigh... | amino_acids, descriptors = load_amino_acids_and_descriptors(self.amino_acid_file_name) |
Predict the next line for this snippet: <|code_start|> Computes the similarity between two strings by comparing each of their l-gram of length 1 to n. Each l-gram
comparison yields a score that depends on the similarity of their respective amino acids (letters) and a shifting
contribution term that decays ex... | def __init__(self, amino_acid_file_name=AminoAcidFile.blosum62_natural, sigma_position=1.0, sigma_amino_acid=1.0, |
Given snippet: <|code_start|>__author__ = 'amelie'
def element_wise_kernel(X, sigma_position, n, alphabet):
"""Compute the similarity of each string in X with itself in the Generic String kernel.
Takes only in account the position penalties and the n-gram of length n. No n-gram penalties (no sigma_c).
... | position_matrix = compute_position_weights_matrix(max_length, sigma_position) |
Here is a snippet: <|code_start|>__author__ = 'amelie'
def element_wise_kernel(X, sigma_position, n, alphabet):
"""Compute the similarity of each string in X with itself in the Generic String kernel.
Takes only in account the position penalties and the n-gram of length n. No n-gram penalties (no sigma_c).
... | X_int = transform_strings_to_integer_lists(X, alphabet) |
Given the following code snippet before the placeholder: <|code_start|>__author__ = 'amelie'
class GraphBuilder:
"""Graph builder for the pre-image of multiple string kernels.
Solves the pre-image problem of string kernels with constant norms (Hamming, Weighted Degree). For string kernel
where the norm... | self._index_to_n_gram = get_index_to_n_gram(alphabet, self.n) |
Given the code snippet: <|code_start|> partition_weights = graph_weights
else:
partition_weights = graph_weights[i, :]
return partition_weights
def _get_max_string_end_indexes_in_range(self, graph, min_partition, n_partitions, is_normalized):
norm = [n_gram_count for ... | raise InvalidShapeError('graph_weights', graph_weights.shape, valid_shapes) |
Next line prediction: <|code_start|>
def _get_weights(self, i, graph_weights):
if graph_weights.ndim == 1:
partition_weights = graph_weights
else:
partition_weights = graph_weights[i, :]
return partition_weights
def _get_max_string_end_indexes_in_range(self, grap... | raise InvalidYLengthError(self.n, n_partitions + self.n - 1) |
Given the code snippet: <|code_start|>
def _get_max_string_end_indexes_in_range(self, graph, min_partition, n_partitions, is_normalized):
norm = [n_gram_count for n_gram_count in range(min_partition + 1, n_partitions + 1)]
norm = numpy.array(norm).reshape(-1, 1)
if is_normalized:
... | raise InvalidMinLengthError(min_length, max_length) |
Next line prediction: <|code_start|>__author__ = 'amelie'
class TestWeightedDegreeModel(unittest2.TestCase):
def setUp(self):
self.setup_feature_space()
self.setup_fit_parameters()
self.setup_graph_builder()
self.alphabet = ['a', 'b', 'c']
<|code_end|>
. Use current file imports:... | self.model_with_length = WeightedDegreeModel(self.alphabet, n=2, is_using_length=True) |
Given the following code snippet before the placeholder: <|code_start|>__author__ = 'amelie'
class TestWeightedDegreeModel(unittest2.TestCase):
def setUp(self):
self.setup_feature_space()
self.setup_fit_parameters()
self.setup_graph_builder()
self.alphabet = ['a', 'b', 'c']
... | self.fit_parameters = InferenceFitParameters(self.weights, self.gram_matrix, Y=['a', 'ab'], |
Given snippet: <|code_start|> self.n_gram_weights = [0, 1, 0]
self.feature_space_mock = Mock()
self.feature_space_mock.compute_weights.return_value = self.n_gram_weights
self.feature_space_patch = patch('preimage.models.weighted_degree_model.WeightedDegreeFeatureSpace')
self.featu... | with self.assertRaises(NoYLengthsError): |
Predict the next line for this snippet: <|code_start|>
class Model(BaseEstimator):
__metaclass__ = abc.ABCMeta
def __init__(self, alphabet, n, is_using_length=True):
self._n = n
self._alphabet = alphabet
self._is_using_length = is_using_length
self._feature_space_ = None
... | raise NoYLengthsError() |
Next line prediction: <|code_start|>__author__ = 'amelie'
class TestPosition(unittest2.TestCase):
def setUp(self):
self.position_weights_one_sigma_p_index_zero = [1., 0.6065307, 0.1353353]
self.position_weights_one_sigma_p_index_one = [0.6065307, 1., 0.6065307]
self.position_weights_half... | position_weights = compute_position_weights(position_index=0, max_position=1, sigma_position=1) |
Here is a snippet: <|code_start|>class TestPosition(unittest2.TestCase):
def setUp(self):
self.position_weights_one_sigma_p_index_zero = [1., 0.6065307, 0.1353353]
self.position_weights_one_sigma_p_index_one = [0.6065307, 1., 0.6065307]
self.position_weights_half_sigma_p_index_zero = [1., 0.... | position_weights = compute_position_weights_matrix(max_position=1, sigma_position=1) |
Predict the next line after this snippet: <|code_start|>__author__ = 'amelie'
class TestEulerianPathModel(unittest2.TestCase):
def setUp(self):
self.setup_fit_parameters()
self.setup_predict_parameters()
self.setup_thresholds()
self.setup_eulerian_path_algorithm()
self.al... | self.model_with_length = EulerianPathModel(self.alphabet, n=2, is_using_length=True) |
Based on the snippet: <|code_start|>__author__ = 'amelie'
class TestAlphabet(unittest2.TestCase):
def setUp(self):
self.a_b_alphabet = ['a', 'b']
self.abc_alphabet = ['a', 'b', 'c']
self.two_grams = ['aa', 'ab', 'ba', 'bb']
self.one_gram_to_index = {'a': 0, 'b': 1}
self.t... | alphabet.get_n_grams(self.a_b_alphabet, n=0.5) |
Predict the next line for this snippet: <|code_start|> self.cab = ['cab']
self.cab_aa = ['cab', 'aa']
self.cab_int = [[2, 0, 1]]
self.cab_aa_int = [[2, 0, 1], [0, 0, -1]]
def test_integer_n_is_zero_get_n_grams_raises_value_error(self):
with self.assertRaises(ValueError):
... | with self.assertRaises(InvalidNGramLengthError): |
Given the following code snippet before the placeholder: <|code_start|>__author__ = 'amelie'
# Shouldn't label this as "feature-space" since we don't use a sparse matrix representation here.
class GenericStringSimilarityFeatureSpace:
"""Output space for the Generic String kernel with position and n-gram similari... | self._Y_int = transform_strings_to_integer_lists(Y, alphabet) |
Given the following code snippet before the placeholder: <|code_start|>__author__ = 'amelie'
# Shouldn't label this as "feature-space" since we don't use a sparse matrix representation here.
class GenericStringSimilarityFeatureSpace:
"""Output space for the Generic String kernel with position and n-gram similari... | self._n_grams_int = transform_strings_to_integer_lists(get_n_grams(alphabet, n), alphabet) |
Here is a snippet: <|code_start|>__author__ = 'amelie'
def branch_and_bound_side_effect(node_creator, y_length, alphabet, max_time):
solution_dict = {1: ('a', 1), 2: ('ba', 3)}
return solution_dict[y_length]
class TestNGramModel(unittest2.TestCase):
def setUp(self):
self.setup_feature_space()
... | self.model_with_length = NGramModel(self.alphabet, n=1, is_using_length=True) |
Predict the next line after this snippet: <|code_start|>__author__ = 'amelie'
def branch_and_bound_side_effect(node_creator, y_length, alphabet, max_time):
solution_dict = {1: ('a', 1), 2: ('ba', 3)}
return solution_dict[y_length]
class TestNGramModel(unittest2.TestCase):
def setUp(self):
self... | self.fit_parameters = InferenceFitParameters(self.weights, self.gram_matrix, Y=['a', 'ab'], |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.