Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
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 TestGenericStringModel(unittest2.TestCase):
def setUp(self):
... | self.model_with_length = GenericStringModel(self.alphabet, n=1, is_using_length=True, |
Next line prediction: <|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 TestGenericStringModel(unittest2.TestCase):
def setUp(self):
self.setup_featu... | self.fit_parameters = InferenceFitParameters(self.weights, self.gram_matrix, Y=['a', 'ab'], |
Predict the next line after this snippet: <|code_start|>
class NGramFeatureSpace:
"""Output feature space for the N-Gram Kernel
Creates a sparse matrix representation of the n-grams in each training string. This is used to compute the weights
of the graph during the inference phase.
Attributes
-... | self.feature_space = build_feature_space_without_positions(alphabet, n, Y) |
Using the snippet: <|code_start|>__author__ = 'amelie'
class TestStructuredOutputMetrics(unittest2.TestCase):
def setUp(self):
self.unicorn = ['unicorn']
self.unicarn = ['unicarn']
self.nicornu = ['nicornu']
self.unicor = ['unicor']
self.potato = ['potato']
self.t... | loss = zero_one_loss(self.unicorn, self.unicorn) |
Here is a snippet: <|code_start|> self.tomato = ['tomato']
self.a = ['a']
self.unicorn_potato = self.unicorn + self.potato
self.unicor_tomato = self.unicor + self.tomato
self.unicor_potato = self.unicor + self.potato
self.unicarn_tomato = self.unicarn + self.tomato
... | loss = hamming_loss(self.unicorn, self.unicorn) |
Given the code snippet: <|code_start|>
def test_same_word_hamming_loss_is_zero(self):
loss = hamming_loss(self.unicorn, self.unicorn)
self.assertEqual(loss, 0.)
def test_one_wrong_letter_on_seven_hamming_loss_is_one_on_seven(self):
loss = hamming_loss(self.unicorn, self.unicarn)
... | loss = levenshtein_loss(self.unicorn, self.unicorn) |
Using the snippet: <|code_start|> merge the paths together when the graph is not connected. We chose to find the longest path and merge the remaining
paths after, but this might differ from what Cortes et al. did in their work. The n-gram kernel also has a
non-unique pre-image. For instance if the string to ... | self._index_to_n_gram = get_index_to_n_gram(alphabet, self.n) |
Given snippet: <|code_start|>
References
----------
.. [1] Cortes, Corinna, Mehryar Mohri, and Jason Weston. "A general regression framework for learning
string-to-string mappings." Predicting Structured Data (2007): 143-168.
"""
def __init__(self, alphabet, n, min_length=1, is_merging_path=... | raise InvalidNGramLengthError(n, 1) |
Using the snippet: <|code_start|> together when is_merging_path is True, and predict the longest path otherwise.
Parameters
----------
n_gram_weights : array, shape=[len(alphabet)**n]
Weight of each n-gram.
y_length : int or None
Length of the string to pr... | raise InvalidYLengthError(self.n, y_length) |
Continue the code snippet: <|code_start|> n_gram_weights : array, shape=[len(alphabet)**n]
Weight of each n-gram.
y_length : int or None
Length of the string to predict. None if thresholds are used.
thresholds :array, shape=[len(alphabet)**n] or None
Threshold ... | raise NoThresholdsError() |
Predict the next line for this snippet: <|code_start|> Rounds the n_gram_weights to integer values, creates a graph with the predicted n-grams, and predicts the output
string by finding an eulerian path in this graph. If the graph is not connected, it will merge multiple paths
together when is_me... | raise InvalidShapeError('n_gram_weights', n_gram_weights.shape, [(self._n_gram_count,)]) |
Next line prediction: <|code_start|>__author__ = 'amelie'
class TestStringMaximizationModel(unittest2.TestCase):
def setUp(self):
self.setup_feature_space()
self.setup_graph_builder()
self.setup_branch_and_bound()
self.alphabet = ['a', 'b', 'c']
<|code_end|>
. Use current file im... | self.model_with_length = StringMaximizationModel(self.alphabet, n=1, gs_kernel=Mock(), max_time=30) |
Predict the next line after this snippet: <|code_start|> self.setup_gs_weights()
self.setup_gs_kernel_mock()
def setup_parameters(self):
self.alphabet = ['a', 'b']
self.abb = ['abb']
self.abaaa = ['abaaa']
self.abb_abaaa = self.abb + self.abaaa
def setup_gs_weigh... | feature_space = GenericStringSimilarityFeatureSpace(self.alphabet, n=1, Y=self.abb, is_normalized=False, |
Here is a snippet: <|code_start|>"""Builder of string feature space represented as sparse matrix"""
__author__ = 'amelie'
def build_feature_space_without_positions(alphabet, n, Y):
"""Create the feature space without considering the position of the n-gram in the strings
Parameters
----------
alph... | n_gram_to_index = get_n_gram_to_index(alphabet, n) |
Using the snippet: <|code_start|> return feature_space
def __initialize_pointers_indexes_data(n_examples):
index_pointers = numpy.empty(n_examples + 1, dtype=numpy.int)
index_pointers[0] = 0
indexes = []
data = []
return index_pointers, indexes, data
def __build_y_pointers_indexes_data(index_... | raise InvalidNGramError(n, key_error.args[0]) |
Continue the code snippet: <|code_start|>__author__ = 'amelie'
# This is just to ensure the pickle files were made correctly
# (not real unit testing since we use the real .pickle files)
class TestLoader(unittest2.TestCase):
def setUp(self):
self.ocr_n_examples_in_fold = [626, 704, 684, 698, 693, 651, 7... | train_dataset, test_dataset = loader.load_ocr_letters(fold_id) |
Given the following code snippet before the placeholder: <|code_start|> self.setup_patch()
def setup_alphabet(self):
self.alphabet = ['a', 'b']
self.abb = ['abb']
self.abaaa = ['abaaa']
self.abb_abaaa = self.abb + self.abaaa
def setup_feature_space(self):
self.fe... | feature_space = NGramFeatureSpace(self.alphabet, n=1, Y=self.abb, is_normalized=True) |
Based on the snippet: <|code_start|> info = ""
tag = tag.strip()
info = info.strip()
ret.append({
"severity": flag,
"component": component,
"tag": tag,
"info": info
})
return ret
def lint(path, pedantic=False, info=False, ... | logger.warning("Failed to execute lintian: %s" % (e)) |
Given the following code snippet before the placeholder: <|code_start|>
tag = tag.strip()
info = info.strip()
ret.append({
"severity": flag,
"component": component,
"tag": tag,
"info": info
})
return ret
def lint(path, pedantic=False,... | raise DputConfigurationError("lintian: %s" % (e)) |
Continue the code snippet: <|code_start|> "Please configure the lintian checker instead.")
if not profile['run_lintian']: # XXX: Broken. Fixme.
logger.info("skipping lintian checking, enable with "
"run_lintian = 1 in your dput.cf")
return
... | default=BUTTON_NO) |
Given the following code snippet before the placeholder: <|code_start|>
class HashValidationError(HookException):
"""
Subclass of the :class:`dput.exceptions.HookException`.
Thrown if the ``checksum`` checker encounters an issue.
"""
pass
def validate_checksums(changes, profile, interface):
"... | except ChangesFileException as e: |
Continue the code snippet: <|code_start|> for index in range(0, len(str_button) + 1):
buttons = [count for count in ALL_BUTTONS if
count.startswith(str_button[0:index])]
if len(buttons) == 0:
break
elif len(buttons) == 1:
... | logger.trace("translated user input '%s'" % (user_input)) |
Predict the next line for this snippet: <|code_start|># WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program... | for item in ALL_BUTTONS: |
Given the code snippet: <|code_start|> assert(False)
def str_to_button(self, str_button, default):
"""
Translate a string input to a button known to the interface. In case
of the CLI interface there is no straight notion of a button, so this
is abstracted by expected data inp... | def boolean(self, title, message, question_type=BUTTON_YES_NO, |
Next line prediction: <|code_start|> buttons = [count for count in ALL_BUTTONS if
count.startswith(str_button[0:index])]
if len(buttons) == 0:
break
elif len(buttons) == 1:
return buttons[0]
return None
def boolean(se... | if user_input in (BUTTON_OK, BUTTON_YES): |
Continue the code snippet: <|code_start|> buttons = [count for count in ALL_BUTTONS if
count.startswith(str_button[0:index])]
if len(buttons) == 0:
break
elif len(buttons) == 1:
return buttons[0]
return None
def boole... | if user_input in (BUTTON_OK, BUTTON_YES): |
Continue the code snippet: <|code_start|># Copyright (c) 2012 dput authors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later vers... | return generate_debianqueued_commands_name(profile) |
Predict the next line for this snippet: <|code_start|># This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program i... | class CancelCommand(AbstractCommand): |
Predict the next line after this snippet: <|code_start|># vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
# Copyright (c) 2012 dput authors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation;... | logger.trace("Commands file will be named %s" % (the_file)) |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
# Copyright (c) 2012 dput authors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; ei... | the_file = "%s-%s.commands" % (get_local_username(), int(time.time())) |
Based on the snippet: <|code_start|>
def check_debs_in_upload(changes, profile, interface):
"""
The ``check-debs`` checker is a stock dput checker that checks packages
intended for upload for .deb packages.
Profile key: ``foo``
Example profile::
{
"skip": false,
"... | logger.debug("Is BYHAND: %s" % (BYHAND)) |
Next line prediction: <|code_start|># the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR... | logger.debug("overriding upload directory to %s" % (incoming_directory)) |
Continue the code snippet: <|code_start|>
# Copyright (c) 2013 Luca Falavigna <dktrkranz@debian.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at y... | return generate_debianqueued_commands_name(profile) |
Next line prediction: <|code_start|> def register(self, parser, **kwargs):
parser.add_argument('-s', '--source', metavar="SOURCE", action='store',
default=None, help="source package to rebuild. ",
required=True)
parser.add_argument('-v', '--vers... | profile = load_profile(args.host) |
Here is a snippet: <|code_start|> if not isinstance(a, Sftp.STATUS):
raise SftpUnexpectedAnswerException(a, a.forr)
elif a.status != a.Status.OK:
raise SftpUploadException("Error writing to %s: %s: %s" % (
filename, a.forr, a))
class SFTPUploader(Abstrac... | logger.warning("SFTP does not support ~/path, continuing with" |
Next line prediction: <|code_start|> else:
raise SftpUploadException("Failed to create %s: %s" % (filename, a))
if not isinstance(a, Sftp.HANDLE):
raise SftpUnexpectedAnswerException(a, a.forr)
h = a.handle
a.forr.done()
ranges = list(range(0, size, 32600))
if ranges:
... | class SFTPUploader(AbstractUploader): |
Here is a snippet: <|code_start|> (e.value, str(l), type(self).__name__))
def __int__(self):
v = 0
for i in self:
v = v | int(i)
return v
def __str__(self):
return "|".join([str(i) for i in self])
@classmethod
def create(cls, ... | class SftpUploadException(UploadException): |
Predict the next line for this snippet: <|code_start|> Sections with a prefix, separated with a forward-slash also show the
component.
It returns a list of strings in the form [component, section].
For example, `non-free/python` has component `non-free` and section
`python`.
... | logger.info("Not checking signature") |
Based on the snippet: <|code_start|> return section.split('/')
else:
return ['main', section]
def set_directory(self, directory):
if directory:
self._directory = directory
else:
self._directory = ""
def validate(self, check_hash="sha1", ch... | (gpg_output, gpg_output_stderr, exit_status) = run_command([ |
Based on the snippet: <|code_start|> """
def __init__(self, filename=None, string=None):
"""
Object constructor. The object allows the user to specify **either**:
#. a path to a *changes* file to parse
#. a string with the *changes* file contents.
::
a = Change... | raise ChangesFileException('Changes file could not be parsed.') |
Here is a snippet: <|code_start|># 02110-1301, USA.
def test_parse_overrides():
test_cases = [
({'foo': [['bar']]},
['foo=bar']),
({'foo': [None]},
['-foo']),
({'+foo': [['bar']]},
['+foo=bar']),
({'foo': [None, ['1']]},
['-foo', 'foo... | print(parse_overrides(case)) |
Predict the next line for this snippet: <|code_start|> ({'foo': [None]},
['-foo']),
({'+foo': [['bar']]},
['+foo=bar']),
({'foo': [None, ['1']]},
['-foo', 'foo=1']),
({'foo': {'bar': {'baz': [['paultag.is.a.god']]}}},
['foo.bar.baz=paultag.i... | except DputConfigurationError: |
Given the following code snippet before the placeholder: <|code_start|># Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
"""
FTP Uploader implementation.
"""
class FtpUploadException(UploadException):
"""
Thrown in the event of a problem connecting, uploading to or
termi... | logger.debug("Logging into %s as %s" % ( |
Continue the code snippet: <|code_start|># This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed... | class FtpUploader(AbstractUploader): |
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
# General Public License for more details.
#
# You should have received a co... | class DmCommand(AbstractCommand): |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
# Copyright (c) 2012 dput authors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Fre... | class DmCommandError(DcutError): |
Here is a snippet: <|code_start|># This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the ... | logger.trace("Commands file will be named %s" % (the_file)) |
Given the code snippet: <|code_start|># Copyright (c) 2012 dput authors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version... | the_file = "%s-%s.dak-commands" % (get_local_username(), int(time.time())) |
Next line prediction: <|code_start|>
def validate(self, args):
if args.force:
return
if not all((os.path.exists(keyring) for keyring in KEYRINGS)):
raise DmCommandError(
"To manage DM permissions, the `debian-keyring' "
"keyring package must b... | (out, err, exit_status) = run_command(cmd) |
Next line prediction: <|code_start|>
dput.core.CONFIG_LOCATIONS = {
os.path.abspath("./tests/dputng"): 0
} # Isolate.
def test_config_load():
""" Make sure we can cleanly load a config """
obj = load_config('profiles', 'test_profile')
comp = {
"incoming": "/dev/null",
"method": "loca... | validate_object('config', obj, "profiles/test_profile") |
Continue the code snippet: <|code_start|>
dput.core.CONFIG_LOCATIONS = {
os.path.abspath("./tests/dputng"): 0
} # Isolate.
def test_config_load():
""" Make sure we can cleanly load a config """
<|code_end|>
. Use current file imports:
from dput.util import validate_object, load_config
from dput.exceptions ... | obj = load_config('profiles', 'test_profile') |
Continue the code snippet: <|code_start|>
dput.core.CONFIG_LOCATIONS = {
os.path.abspath("./tests/dputng"): 0
} # Isolate.
def test_config_load():
""" Make sure we can cleanly load a config """
obj = load_config('profiles', 'test_profile')
comp = {
"incoming": "/dev/null",
"method": "... | except InvalidConfigError as e: |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
# Copyright (c) 2013 dput authors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publi... | class UnknownDistribution(HookException): |
Predict the next line after this snippet: <|code_start|># This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program... | class HTTPUploader(AbstractUploader): |
Given snippet: <|code_start|> _incoming = self._config['incoming']
if not _incoming.startswith("/"):
_incoming = "/" + _incoming
if not _incoming.endswith("/"):
_incoming = _incoming + "/"
_path = self._baseurl.path
if not _path:
_path = _incom... | logger.debug("Upload to %s" % (upload_filename)) |
Given the following code snippet before the placeholder: <|code_start|># (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General P... | logger.trace("Loading object: %s" % (obj_path)) |
Based on the snippet: <|code_start|>def load_obj(obj_path):
"""
Dynamically load an object (class, method, etc) by name (such as
`dput.core.ClassName`), and return that object to work with. This is
useful for loading modules on the fly, without them being all loaded at
once, or even in the same pack... | raise NoSuchConfigError("No such config") |
Given the following code snippet before the placeholder: <|code_start|> op = operators[operator]
if kname in ret:
ret[kname] = op(ret[key], ret[kname])
else:
foo = op(ret[key], [])
if foo != []:
ret[kname] = foo
ret.pop(key)
return ... | raise DputConfigurationError("syntax error in %s: %s" % ( |
Predict the next line after this snippet: <|code_start|> logger.debug("Loading schema %s from %s" % (schema, root))
spath = "%s/%s.json" % (
root,
schema
)
try:
if os.path.exists(spath):
sobj = json.load(open(spath, 'r'))
els... | ex = InvalidConfigError(error) |
Predict the next line for this snippet: <|code_start|> if accept:
super(AskToAccept, self).missing_host_key(client, hostname, key)
else:
raise paramiko.SSHException('Unknown server %s' % hostname)
class SFTPUploader(AbstractUploader):
"""
Provides an interface to upload ... | logger.warning("SFTP does not support ~/path, continuing with" |
Using the snippet: <|code_start|> "No user to upload could be retrieved. "
"Please set 'login' explicitly in your profile"
)
return user
class AskToAccept(paramiko.AutoAddPolicy):
"""
Paramiko policy to automatically add the hostname, but only after asking.
"""
def ... | class SFTPUploader(AbstractUploader): |
Here is a snippet: <|code_start|>
Thrown if the ``suite-mismatch`` checker encounters an issue.
"""
pass
def check_allowed_distribution(changes, profile, interface):
"""
The ``allowed-distribution`` checker is a stock dput checker that checks
packages intended for upload for a valid upload dis... | logger.debug("Distribution does not %s match '%s'" % ( |
Based on the snippet: <|code_start|> allowed_block = profile.get('allowed-distribution', {})
suite = changes['Distribution']
if 'allowed_distributions' in profile:
srgx = profile['allowed_distributions']
if re.match(srgx, suite) is None:
logger.debug("Distribution does not %s matc... | codenames = load_config('codenames', profile['codenames']) |
Continue the code snippet: <|code_start|> testing-proposed-updates, stable-security, etc.) did really follow the
archive policies for that.
Profile key: none
"""
# XXX: This check does not contain code names yet. We need a global way
# to retrieve and share current code names.
suite = ... | if not interface.boolean('Protected Checker', msg, default=BUTTON_NO): |
Given snippet: <|code_start|>
Thrown if the ``gpg`` checker encounters an issue.
"""
pass
def check_gpg_signature(changes, profile, interface):
"""
The ``gpg`` checker is a stock dput checker that checks packages
intended for upload for a GPG signature.
Profile key: ``gpg``
Example p... | logger.info("Not checking GPG signature due to " |
Next line prediction: <|code_start|>
Profile key: ``gpg``
Example profile::
{
"allowed_keys": [
"8F049AD82C92066C7352D28A7B585B30807C2A87",
"B7982329"
]
}
``allowed_keys`` is an optional entry which contains all the keys that
may... | except ChangesFileException as e: |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
# Copyright (c) 2012 dput authors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Fre... | class DputCfConfig(AbstractConfig): |
Given the following code snippet before the placeholder: <|code_start|># You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
"""
Old dput config file implementat... | logger.debug("Skipping file %s: Not accessible" % ( |
Predict the next line after this snippet: <|code_start|>class DputCfConfig(AbstractConfig):
"""
dput-old config file implementation. Subclass of a
:class:`dput.config.AbstractConfig`.
"""
def preload(self, configs):
"""
See :meth:`dput.config.AbstractConfig.preload`
"""
... | raise DputConfigurationError("Error parsing file %s: %s" % ( |
Based on the snippet: <|code_start|># Copyright (c) 2012 dput authors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
... | return generate_dak_commands_name(profile) |
Given snippet: <|code_start|>
class BreakTheArchiveCommand(AbstractCommand):
def __init__(self, interface):
super(BreakTheArchiveCommand, self).__init__(interface)
self.cmd_name = "break-the-archive"
self.cmd_purpose = "break the archive (no, really)"
def generate_commands_name(self, p... | default=BUTTON_NO |
Given snippet: <|code_start|> """
def __init__(self, filename=None, string=None):
"""
Object constructor. The object allows the user to specify **either**:
#. a path to a *changes* file to parse
#. a string with the *changes* file contents.
::
a = Dsc(filename=... | raise DscFileException('Changes file could not be parsed.') |
Given the code snippet: <|code_start|> return getattr(self, name)
return self._raw.get(name, *args)
def set(self, name: str, value: str) -> None:
"""
Set the value of a metadata element
"""
self._raw[name.lower()] = value
def unset(self, name: str) -> None:
... | def parse(self, lines: Lines) -> None: |
Given snippet: <|code_start|> """
return name.lower() in self._raw
def get(self, name: str, *args) -> str:
"""
Get a metadata element by name, optionally with a default.
"""
name = name.lower()
if hasattr(self, name):
return getattr(self, name)
... | self.set("total", format_duration(durations[""])) |
Next line prediction: <|code_start|># coding: utf8
body_p = """Name: test
2016
15 march: 9:00-9:30
- wrote unit tests
Write more unit tests
"""
body_p1 = """Name: p1
tags: foo, bar
"""
body_p2 = """Name: p2
tags: blubb, foo
"""
<|code_end|>
. Use current file imports:
(import unittest
import os
import egtlib
... | class TestCommands(ProjectTestMixin, unittest.TestCase): |
Predict the next line for this snippet: <|code_start|>
basedir = os.path.dirname(__file__)
if not basedir:
basedir = os.getcwd()
basedir = os.path.abspath(os.path.join(basedir, ".."))
testdir = os.path.join(basedir, "test")
class TestScan(unittest.TestCase):
"""
Test scan results
"""
def test_sca... | res = sorted([x[len(testdir) + 10:] for x in scan(os.path.join(testdir, "testdata"))]) |
Predict the next line after this snippet: <|code_start|> while True:
line = cls.process.stdout.readline()
if line.strip():
print(line.strip())
if "Remote interface" in str(line):
success = True
break
if not success:
... | run_commands(load.commands_from_data([ENTRY_VALUES])) |
Next line prediction: <|code_start|>
EXPECTED_ENTRY_VALUES = {
"Author": ["fore_name last_name"],
"pubDate": {
"date": "2011-11-11",
"components": {
"Year": True,
"Month": True,
"Day": True
}
},
"reviseDate": {
"date": "2012-11-11",
... | parsexml.file_to_element_tree(stream) |
Next line prediction: <|code_start|> n_requested_samples,
ln_prior=None,
init_batch_size=None,
growth_factor=128,
n_linear_samples=1):
n_total_samples = len(prior_sam... | logger.log(1, f"iteration {i}, computing {n_process} likelihoods") |
Using the snippet: <|code_start|> "object's table datatype do not match. "
f"{existing_header['datatype']} vs. {this_header['datatype']}")
# If we got here, we can now try to append:
current_size = len(output_group[name])
output_group[name].resize((current_size + ... | data, *_ = validate_prepare_data(data, |
Using the snippet: <|code_start|>
if self.rv_err.ndim == 1:
self._has_cov = False
elif self.rv_err.ndim == 2:
self._has_cov = True
if (self.rv_err.shape != (self.rv.size, self.rv.size)
and self.rv_err.shape != (self.rv.size, )):
raise ValueErr... | logger.info(f"Filtering {n_filter} NaN/Inf data points") |
Using the snippet: <|code_start|> if time_kwargs is None:
time_kwargs = dict()
# First check for any of the valid astropy Time format names:
# FUTURETODO: right now we only support jd and mjd (and b-preceding)
for fmt in ['jd', 'mjd']:
if fmt in lwr_cols:
... | 'format', guess_time_format(tbl[lwr_to_col[name]])) |
Given the following code snippet before the placeholder: <|code_start|># Third-party
# Project
__all__ = ['RVData']
class RVData:
"""
Time-domain radial velocity measurements for a single target.
Parameters
----------
t : `~astropy.time.Time`, array_like
Array of measurement times. Eith... | warning_type=TheJokerDeprecationWarning) |
Based on the snippet: <|code_start|> err_msg = ("Unable to guess time format! Initialize with an "
"explicit astropy.time.Time() object instead.")
if jd_check and mjd_check:
raise ValueError(err_msg)
elif jd_check:
return 'jd'
elif mjd_check:
return 'mjd'
els... | trend_M = get_trend_design_matrix(data, None, poly_trend) |
Using the snippet: <|code_start|> The number of conversations created in this
interval.
"""
start_time = proto.Field(
proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp,
)
conversation_count = proto.Field(proto... | message=resources.IssueModelLabelStats.IssueStats, |
Predict the next line after this snippet: <|code_start|> probs = scores_to_probs(scores)
assert_less(abs(sum(probs) - 1), 1e-6)
for prob in probs:
assert_less_equal(0, prob)
assert_less_equal(prob, 1)
def test_multinomial_goodness_of_fit():
for dim in range(2, 20):
yield _test_m... | counts, bounds = bin_samples(samples, 2) |
Using the snippet: <|code_start|># INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR... | p_good = multinomial_goodness_of_fit(probs, counts, sample_count) |
Using the snippet: <|code_start|>#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT H... | seed_all(0) |
Given the code snippet: <|code_start|> score_empty = self.score_add_value(0, bogus, size)
if len(counts) == 0 or counts[-1] != 0:
counts.append(0)
scores.append(score_empty)
else:
scores[-1] = score_empty
assign = sample_dis... | score += count * log(count) |
Predict the next line after this snippet: <|code_start|>
#-------------------------------------------------------------------------
# Sampling
def sample_assignments(self, sample_size):
'''
Sample partial assignment vector
[X_0, ..., X_{n-1}]
where
n = sam... | assign = sample_discrete_log(scores) |
Here is a snippet: <|code_start|> self.count_times_variance = float(raw['count_times_variance'])
def dump(self):
return {
'count': self.count,
'mean': self.mean,
'count_times_variance': self.count_times_variance,
}
def protobuf_load(self, message):
... | self.sigma = sqrt(sigmasq_star) |
Using the snippet: <|code_start|># "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, ... | score -= .5 * log(nu * pi * sigmasq) |
Given the following code snippet before the placeholder: <|code_start|># "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FO... | score -= .5 * log(nu * pi * sigmasq) |
Using the snippet: <|code_start|># THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOL... | score = gammaln(.5 * (nu + 1.)) - gammaln(.5 * nu) |
Predict the next line for this snippet: <|code_start|> self.mean = float(raw['mean'])
self.count_times_variance = float(raw['count_times_variance'])
def dump(self):
return {
'count': self.count,
'mean': self.mean,
'count_times_variance': self.count_times_v... | sigmasq_star = post.nu * post.sigmasq / sample_chi2(post.nu) |
Next line prediction: <|code_start|>
def dump(self):
return {
'count': self.count,
'mean': self.mean,
'count_times_variance': self.count_times_variance,
}
def protobuf_load(self, message):
self.count = int(message.count)
self.mean = float(mess... | self.mu = sample_normal(post.mu, sqrt(sigmasq_star / post.kappa)) |
Here is a snippet: <|code_start|>
def test_log_stirling1_row():
require_cython()
MAX_N = 128
rows = [[1]]
for n in range(1, MAX_N + 1):
prev = rows[-1]
middle = [(n - 1) * prev[k] + prev[k - 1] for k in range(1, n)]
row = [0] + middle + [1]
rows.append(row)
for n i... | assert_close(dx_py, dx_cpp, tol=0.5) |
Next line prediction: <|code_start|> for alpha in self.alphas:
message.alphas.append(alpha)
class Group(GroupIoMixin):
def __init__(self):
self.counts = None
def init(self, shared):
self.counts = numpy.zeros(shared.dim, dtype=numpy.int)
def add_value(self, shared, valu... | return log(numer / denom) |
Here is a snippet: <|code_start|> def add_repeated_value(self, shared, value, count):
self.counts[value] += count
def remove_value(self, shared, value):
self.counts[value] -= 1
def merge(self, shared, source):
self.counts += source.counts
def score_value(self, shared, value):
... | score = sum(gammaln(a[k] + m[k]) - gammaln(a[k]) for k in xrange(dim)) |
Using the snippet: <|code_start|> return score
def sample_value(self, shared):
sampler = Sampler()
sampler.init(shared, self)
return sampler.eval(shared)
def load(self, raw):
self.counts = numpy.array(raw['counts'], dtype=numpy.int)
def dump(self):
return {'... | return sample_discrete(self.ps) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.