Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Next line prediction: <|code_start|> return args
def main():
parser = get_parser()
args = validate_args(parser)
seq_records = seqrecords.read_fasta(args.fasta)
patterns = []
for i in range(args.min_word_size, args.max_word_size + 1):
p = word_pattern.create(seq_records.seq_list, i)
... | matrix = distmatrix.create(seq_records.id_list, dist) |
Predict the next line for this snippet: <|code_start|>
if len(sys.argv[1:]) == 0:
# parser.print_help()
parser.print_usage()
parser.exit()
return parser
def validate_args(parser):
args = parser.parse_args()
if not args.min_word_size:
parser.error("min_word_size must be... | seq_records = seqrecords.read_fasta(args.fasta) |
Given the code snippet: <|code_start|> group = parser.add_argument_group('OPTIONAL ARGUMENTS')
group.add_argument('--min_word_size', '-l',
help='minimum word size [default: %(default)s]',
type=int, metavar="WORD_SIZE", default=1,
)
group.ad... | version='%(prog)s {}'.format(__version__)) |
Using the snippet: <|code_start|> default='phylip',
help='distances output format [default: %(default)s]')
group = parser.add_argument_group("OTHER OPTIONS")
group.add_argument("-h", "--help", action="help",
help="show this help message and ex... | vector = bbc.create_vectors(seq_records, args.k, alphabet=args.alphabet) |
Continue the code snippet: <|code_start|>
group = parser.add_argument_group("OTHER OPTIONS")
group.add_argument("-h", "--help", action="help",
help="show this help message and exit")
group.add_argument('--version', action='version',
version='%(prog)s {}'.format(... | matrix = distmatrix.create(seq_records.id_list, dist) |
Based on the snippet: <|code_start|> group.add_argument('--outfmt', choices=['phylip', 'pairwise'],
default='phylip',
help='distances output format [default: %(default)s]')
group = parser.add_argument_group("OTHER OPTIONS")
group.add_argument("-h", "--help", act... | seq_records = seqrecords.read_fasta(args.fasta) |
Given the code snippet: <|code_start|> type=argparse.FileType('r'), metavar="FILE")
group.add_argument('--molecule', '-m', choices=['dna', 'rna', 'protein'],
help='choose sequence alphabet', required=True)
group = parser.add_argument_group('OPTIONAL ARGUMENTS')
... | args.alphabet = get_alphabet(args.molecule) |
Given the code snippet: <|code_start|>
def get_parser():
parser = argparse.ArgumentParser(
description='''Calculatee distance between DNA/protein sequences
based on Base-Base Correlation (BBC).''',
add_help=False, prog='calc_bbc.py'
)
group = parser.add_argument_group('REQUIRED ARG... | version='%(prog)s {}'.format(__version__)) |
Given the following code snippet before the placeholder: <|code_start|>
class DistanceTest(unittest.TestCase, utils.ModulesCommonTest):
def __init__(self, *args, **kwargs):
super(DistanceTest, self).__init__(*args, **kwargs)
utils.ModulesCommonTest.set_test_data()
self.patterns = []
... | dist = word_d2.Distance(self.counts) |
Given the following code snippet before the placeholder: <|code_start|>
class DistanceTest(unittest.TestCase, utils.ModulesCommonTest):
def __init__(self, *args, **kwargs):
super(DistanceTest, self).__init__(*args, **kwargs)
utils.ModulesCommonTest.set_test_data()
self.patterns = []
... | p = word_pattern.create(self.pep_records.seq_list, i) |
Given the following code snippet before the placeholder: <|code_start|>
class DistanceTest(unittest.TestCase, utils.ModulesCommonTest):
def __init__(self, *args, **kwargs):
super(DistanceTest, self).__init__(*args, **kwargs)
utils.ModulesCommonTest.set_test_data()
self.patterns = []
... | c = word_vector.Counts(self.pep_records.length_list, p) |
Here is a snippet: <|code_start|>
class DistanceTest(unittest.TestCase, utils.ModulesCommonTest):
def __init__(self, *args, **kwargs):
super(DistanceTest, self).__init__(*args, **kwargs)
utils.ModulesCommonTest.set_test_data()
self.patterns = []
self.counts = []
self.freq... | matrix = distmatrix.create(self.pep_records.id_list, dist) |
Predict the next line for this snippet: <|code_start|> group.add_argument('--out', '-o', help="output filename",
metavar="FILE")
group.add_argument('--outfmt', choices=['phylip', 'pairwise'],
default='phylip',
help='distances output format [DEF... | dist = ncd.Distance(seq_records) |
Given snippet: <|code_start|> metavar="FILE")
group.add_argument('--outfmt', choices=['phylip', 'pairwise'],
default='phylip',
help='distances output format [DEFAULT: %(default)s]')
group = parser.add_argument_group("OTHER OPTIONS")
group.... | matrix = distmatrix.create(seq_records.id_list, dist) |
Continue the code snippet: <|code_start|> group = parser.add_argument_group('OUTPUT ARGUMENTS')
group.add_argument('--out', '-o', help="output filename",
metavar="FILE")
group.add_argument('--outfmt', choices=['phylip', 'pairwise'],
default='phylip',
... | seq_records = seqrecords.read_fasta(args.fasta) |
Continue the code snippet: <|code_start|>#! /usr/bin/env python
# Copyright (c) 2016 Zielezinski A, combio.pl
def get_parser():
parser = argparse.ArgumentParser(
description='''Calculate distances between DNA/protein sequences based
on Normalized Compression Distance (NCD).''',
add_help... | version='%(prog)s {}'.format(__version__)) |
Predict the next line for this snippet: <|code_start|> help='distances output format [default: %(default)s]')
group = parser.add_argument_group("OTHER OPTIONS")
group.add_argument("-h", "--help", action="help",
help="show this help message and exit")
group.add_a... | vector = graphdna.create_2DSGraphVectors(seq_records) |
Here is a snippet: <|code_start|> version='%(prog)s {}'.format(__version__))
if len(sys.argv[1:]) == 0:
# parser.print_help()
parser.print_usage()
parser.exit()
return parser
def validate_args(parser):
args = parser.parse_args()
if args.vector == '2DMV' a... | matrix = distmatrix.create(seq_records.id_list, dist) |
Predict the next line for this snippet: <|code_start|> group.add_argument('--outfmt', choices=['phylip', 'pairwise'],
default='phylip',
help='distances output format [default: %(default)s]')
group = parser.add_argument_group("OTHER OPTIONS")
group.add_argument("... | seq_records = seqrecords.read_fasta(args.fasta) |
Predict the next line for this snippet: <|code_start|>def get_parser():
parser = argparse.ArgumentParser(
description='''Calculate distance between DNA sequences based on
the two-dimensional (2D) graphical DNA curve''',
add_help=False, prog='calc_graphdna.py'
)
group = parser.add_arg... | version='%(prog)s {}'.format(__version__)) |
Based on the snippet: <|code_start|> group = parser.add_argument_group('OUTPUT ARGUMENTS')
group.add_argument('--out', '-o', help="output filename",
metavar="FILE")
group.add_argument('--outfmt', choices=['phylip', 'pairwise'],
default='phylip',
... | dist = lempelziv.Distance(seq_records, args.distance) |
Given the following code snippet before the placeholder: <|code_start|> group.add_argument('--out', '-o', help="output filename",
metavar="FILE")
group.add_argument('--outfmt', choices=['phylip', 'pairwise'],
default='phylip',
help='distances o... | matrix = distmatrix.create(seq_records.id_list, dist) |
Predict the next line after this snippet: <|code_start|>
group = parser.add_argument_group('OUTPUT ARGUMENTS')
group.add_argument('--out', '-o', help="output filename",
metavar="FILE")
group.add_argument('--outfmt', choices=['phylip', 'pairwise'],
default='phyli... | seq_records = seqrecords.read_fasta(args.fasta) |
Predict the next line after this snippet: <|code_start|>
def get_parser():
parser = argparse.ArgumentParser(
description='''Calculate distance between DNA/protein sequences based
on Lempel-Ziv complexity.''',
add_help=False, prog='calc_lempelziv.py'
)
group = parser.add_argument_grou... | version='%(prog)s {}'.format(__version__)) |
Next line prediction: <|code_start|> parser.print_usage() # for just the usage line
parser.exit()
return parser
def validate_args(parser):
args = parser.parse_args()
if args.teiresias:
if args.l is None:
parser.error("Teiresias requires --l")
if args.k is None:... | p = word_pattern.run_teiresias(args.fasta.name, |
Next line prediction: <|code_start|>def validate_args(parser):
args = parser.parse_args()
if args.teiresias:
if args.l is None:
parser.error("Teiresias requires --l")
if args.k is None:
parser.error("Teiresias requires --k")
if args.word_size < 2:
pars... | seq_records = seqrecords.read_fasta(args.fasta) |
Here is a snippet: <|code_start|> group = parser.add_argument_group('REQUIRED ARGUMENTS')
group.add_argument('--fasta', '-f',
help='input FASTA sequence filename', required=True,
type=argparse.FileType('r'), metavar="FILE")
group.add_argument('--word_size', '-w',... | version='%(prog)s {}'.format(__version__)) |
Next line prediction: <|code_start|>
class Test(unittest.TestCase, utils.ModulesCommonTest):
def __init__(self, *args, **kwargs):
super(Test, self).__init__(*args, **kwargs)
utils.ModulesCommonTest.set_test_data()
def test_complexity1(self):
seq = 'AACGTACCATTGAACGTACCGTAGG'
<|code_... | c = ncd.complexity(seq) |
Given snippet: <|code_start|>
class Test(unittest.TestCase, utils.ModulesCommonTest):
def __init__(self, *args, **kwargs):
super(Test, self).__init__(*args, **kwargs)
utils.ModulesCommonTest.set_test_data()
def test_complexity1(self):
seq = 'AACGTACCATTGAACGTACCGTAGG'
c = ncd.... | matrix = distmatrix.create(self.pep_records.id_list, dist) |
Given snippet: <|code_start|>
class VectorTest(unittest.TestCase):
def test_count_seq_chars(self):
seq = 'MKSTGWHFSG'
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
from alfpy import wmetric
from alfpy.utils import distmatrix
from alfpy.utils.data im... | l = wmetric.count_seq_chars(seq, utils.ALPHABET_PEP) |
Here is a snippet: <|code_start|> seq = 'MKSTGWHFSG'
l = wmetric.count_seq_chars(seq, utils.ALPHABET_PEP)
expl = [0, 0, 0, 0, 1, 2, 1, 0, 1, 0, 1, 0, 0, 0, 2, 1, 0, 1, 0, 0]
self.assertEqual(l, expl)
def test_count_seq_chars_pep_ambiguous(self):
seq = 'MKSTGWXXXXXXXOOOOOOOHFS... | matrix = distmatrix.create(self.pep_records.id_list, dist) |
Given the code snippet: <|code_start|>
def test_count_seq_chars(self):
seq = 'MKSTGWHFSG'
l = wmetric.count_seq_chars(seq, utils.ALPHABET_PEP)
expl = [0, 0, 0, 0, 1, 2, 1, 0, 1, 0, 1, 0, 0, 0, 2, 1, 0, 1, 0, 0]
self.assertEqual(l, expl)
def test_count_seq_chars_pep_ambiguous(sel... | matrix = subsmat.get('blosum62') |
Based on the snippet: <|code_start|>
class VectorTest(unittest.TestCase, utils.ModulesCommonTest):
def __init__(self, *args, **kwargs):
super(VectorTest, self).__init__(*args, **kwargs)
utils.ModulesCommonTest.set_test_data()
def test_fcgr_vector1(self):
<|code_end|>
, predict the immediate... | vec = fcgr.fcgr_vector('CTAGGGAACATACCA', 1) |
Continue the code snippet: <|code_start|> vec = fcgr.fcgr_vector('CTAGGGAACATACCA', 1)
self.assertEqual(vec, [3.0, 6.0, 3.0])
def test_fcgr_vector2(self):
vec = fcgr.fcgr_vector('CTAGGGAACATACCA', 2)
exp = [0.0, 0.0, 2.0, 2.0, 1.0, 1.0, 0.0, 2.0,
1.0, 2.0, 0.0, 1.0, 2.... | matrix = distmatrix.create(self.dna_records.id_list, dist) |
Using the snippet: <|code_start|>
class VectorTest(unittest.TestCase, utils.ModulesCommonTest):
"""Shared methods and tests for creating BBC vectors."""
def __init__(self, *args, **kwargs):
super(VectorTest, self).__init__(*args, **kwargs)
utils.ModulesCommonTest.set_test_data()
def tes... | vec = bbc.base_base_correlation(seq, 1, utils.ALPHABET_DNA) |
Here is a snippet: <|code_start|>
def test_create_vectors_on_dna_k1(self):
vec = bbc.create_vectors(self.dna_records, 1, utils.ALPHABET_DNA)
md5 = utils.calc_md5(vec)
self.assertEqual(vec.shape, (3, 16))
self.assertEqual(md5, 'e99bc40356b00e04fd858a665af597ec')
def test_create_v... | matrix = distmatrix.create(self.dna_records.id_list, dist) |
Predict the next line for this snippet: <|code_start|>
class SeqRecordsTest(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(SeqRecordsTest, self).__init__(*args, **kwargs)
self.ID_LIST = ['seq1', 'seq2', 'seq3', 'seq4']
self.DESC_LIST = ['seq1 desc', 'seq2 desc', 'seq3 des... | rec = seqrecords.SeqRecords( |
Given the following code snippet before the placeholder: <|code_start|>
class VectorTest(unittest.TestCase, utils.ModulesCommonTest):
def __init__(self, *args, **kwargs):
super(VectorTest, self).__init__(*args, **kwargs)
utils.ModulesCommonTest.set_test_data()
def test_2DSGraphVector(self):... | vec = graphdna._2DSGraphVector(seq) |
Given the code snippet: <|code_start|> vec = graphdna._2DNGraphVector(seq)
md5 = utils.calc_md5(vec)
self.assertEqual(len(vec), 48)
self.assertEqual(md5, '44829cc0277531646d656cdaacd3ae94')
def test_create_2DSGraphVectors(self):
data = graphdna.create_2DSGraphVectors(self.dna... | matrix = distmatrix.create(self.dna_records.id_list, dist) |
Given the following code snippet before the placeholder: <|code_start|> pos1 = word_positions[i - 1]
pos2 = word_positions[i]
pos = pos2 - pos1
l.append(pos)
return np.mean(l), np.std(l)
def create_vector(seqcount, pattern):
"""Compute a matrix of sequence-representing RTD vecto... | class Distance(distance.Distance): |
Using the snippet: <|code_start|> return (nft, ntf)
def _nbool_correspond_all(u, v):
"""Function used by some distance methods (in Distance class).
Based on: https://github.com/scipy/scipy
Args:
u (numpy.ndarray) : bool, shape: (N, )
v (numpy.ndarray) : as above
Returns:
t... | class Distance(distance.Distance): |
Using the snippet: <|code_start|> >>> for s in blob.sentences:
... print(s)
... print(s.classify())
...
The beer is good.
pos
But the hangover is horrible.
neg
.. versionadded:: 0.6.0 (``textblob``)
"""
from __future__ import absolute_import
### Basic feature extractors ###
... | return word_tokenize(words, include_punc=False) |
Based on the snippet: <|code_start|> >>> blob = TextBlob("The beer is good. But the hangover is horrible.", classifier=cl)
>>> for s in blob.sentences:
... print(s)
... print(s.classify())
...
The beer is good.
pos
But the hangover is horrible.
neg
.. versionadded:: 0.6.0 (``... | if isinstance(words, basestring): |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
#
# Code imported from the main `TextBlob`_ library.
#
# :repo: `https://github.com/sloria/TextBlob`_
# :source: textblob/en/parsers.py
# :version: 2013-10-21 (a88e86a76a)
#
# :modified: 2014-08-04 <m.killer@langui.ch>
#
"""D... | pattern_pprint = pattern_de.pprint |
Next line prediction: <|code_start|> '''Parser that uses the implementation in Tom de Smedt's pattern library.
http://www.clips.ua.ac.be/pages/pattern-de#parser
:param tokenizer: (optional) A tokenizer instance. If ``None``, defaults to
:class:`PatternTokenizer() <textblob_de.tokenizers.PatternToke... | self.tokenizer = tokenizer if tokenizer is not None else PatternTokenizer() |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
"""Prepare docs (usually called by Makefile)."""
from __future__ import unicode_literals, print_function
_HERE = os.path.dirname(__file__)
def read(fname):
<|code_end|>
with the help of current file imports:
import os
import re
import ... | with _open(fname, encoding='utf-8') as fp: |
Given the following code snippet before the placeholder: <|code_start|> elif line.strip().startswith("Using fallback version of '"):
print("skipped line: {}".format(line))
else:
# correctly indent tips in 'make help'
if line.strip().startswith("-->"... | _pandoc = get_external_executable("pandoc") |
Continue the code snippet: <|code_start|>Skip slow tests: ::
python run_tests.py fast
Code imported from ``textblob-fr`` sample extension.
:repo: `https://github.com/sloria/textblob-fr`_
:source: run_tests.py
:version: 2013-09-18 (1a8438b5ea)
"""
from __future__ import unicode_literals
def main():
args =... | if not PY2: |
Next line prediction: <|code_start|>
python run_tests.py
Skip slow tests: ::
python run_tests.py fast
Code imported from ``textblob-fr`` sample extension.
:repo: `https://github.com/sloria/textblob-fr`_
:source: run_tests.py
:version: 2013-09-18 (1a8438b5ea)
"""
from __future__ import unicode_literals
d... | if PY26: |
Using the snippet: <|code_start|>
with open(os.path.join(MODULE, 'ext', '_pattern', 'text', 'de', 'de-verbs.txt'), 'r') as _vl:
for line in _vl:
verb_lexicon[
line[0].lower()] = set(
list(
verb_lexicon[
line[0].lower()])... | self.tokenizer = tokenizer if tokenizer is not None else PatternTokenizer() |
Given the following code snippet before the placeholder: <|code_start|> for np in extracted_list:
_np = np.split()
if _np[0] in INSIGNIFICANT:
_np.pop(0)
try:
if _np[-1] in INSIGNIFICANT:
_np.pop(-1)
# e.g. 'w... | _sentences = sent_tokenize(text, tokenizer=self.tokenizer) |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
#
# Code adapted from the main `TextBlob`_ library.
#
# :repo: `https://github.com/sloria/TextBlob`_
# :source: textblob/tokenizers.py
# :version: 2013-12-27 (fbdcaf2709)
#
# :modified: 2014-10-02 <m.killer@langui.ch>
#
"""Various tokenizer implementations."""
from _... | ABBREVIATIONS_DE = pattern_de.ABBREVIATIONS |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
"""Various lemmatizer implementations.
:class:`PatternParserLemmatizer() <textblob_de.lemmatizers.PatternParserLemmatizer>`.
"""
from __future__ import absolute_import
pattern_parse = pattern_de.parse
try:
MODULE = os.path.dirname(os.path.realpath(__... | class PatternParserLemmatizer(BaseLemmatizer): |
Predict the next line after this snippet: <|code_start|>"""
from __future__ import absolute_import
pattern_parse = pattern_de.parse
try:
MODULE = os.path.dirname(os.path.realpath(__file__))
except:
MODULE = ""
class PatternParserLemmatizer(BaseLemmatizer):
"""Extract lemmas from PatternParser() outpu... | self.tokenizer = tokenizer if tokenizer is not None else PatternTokenizer() |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
#
# Code adapted from ``textblob-fr`` sample extension.
#
# :repo: `https://github.com/sloria/textblob-fr`_
# :source: textblob_fr/taggers.py
# :version: 2013-10-28 (5c6329d209)
#
# :modified: 2014-08-04 <m.killer@langui.ch>
#
"""Default taggers for German.
>... | pattern_tag = pattern_de.tag |
Next line prediction: <|code_start|> (space separated string).
"""
#: Do not process empty strings (Issue #3)
if sentence.strip() == "":
return []
#: Do not process strings consisting of a single punctuation mark (Issue #4)
elif sentence.strip() in PUNCTUA... | unicode(t))] |
Given snippet: <|code_start|>"""
from __future__ import absolute_import
pattern_tag = pattern_de.tag
PUNCTUATION = string.punctuation
class PatternTagger(BaseTagger):
'''Tagger that uses the implementation in
Tom de Smedt's pattern library
(http://www.clips.ua.ac.be/pattern).
:param tokenizer: ... | self.tokenizer = tokenizer if tokenizer is not None else PatternTokenizer() |
Continue the code snippet: <|code_start|>
__all__ = ['Message']
class Message(object):
"""A log message. All attributes are read-only."""
__slots__ = ['fields', 'suppress_newlines', 'traceback', 'text']
#: default option values. Don't change these!
_default_options = {'suppress_newlines': True,
... | format_spec = to_text(format_spec, errors='surrogate_or_replace') |
Predict the next line after this snippet: <|code_start|># coding: utf-8
if sys.version_info >= (2, 7):
else:
try:
except ImportError:
raise RuntimeError("unittest2 is required for Python < 2.7")
<|code_end|>
using the current file's imports:
import itertools
import re
import sys
import pytest
im... | @pytest.fixture(params=(logger.Logger, logger.InternalLogger)) |
Predict the next line after this snippet: <|code_start|># coding: utf-8
if sys.version_info >= (2, 7):
else:
try:
except ImportError:
raise RuntimeError("unittest2 is required for Python < 2.7")
@pytest.fixture(params=(logger.Logger, logger.InternalLogger))
def test_logger(request):
<|code_end|>
... | output = outputs.ListOutput(close_atexit=False) |
Predict the next line after this snippet: <|code_start|># coding: utf-8
if sys.version_info >= (2, 7):
else:
try:
except ImportError:
raise RuntimeError("unittest2 is required for Python < 2.7")
@pytest.fixture(params=(logger.Logger, logger.InternalLogger))
def test_logger(request):
output = o... | emitters['*'] = filters.Emitter(levels.DEBUG, None, output) |
Predict the next line after this snippet: <|code_start|># coding: utf-8
if sys.version_info >= (2, 7):
else:
try:
except ImportError:
raise RuntimeError("unittest2 is required for Python < 2.7")
@pytest.fixture(params=(logger.Logger, logger.InternalLogger))
def test_logger(request):
output = o... | emitters['*'] = filters.Emitter(levels.DEBUG, None, output) |
Continue the code snippet: <|code_start|>
def conv_val(x):
return x
def conv_item(x, y):
return x, y
class HelperTestCase(unittest.TestCase):
def test_drop(self):
assert drop(1, 2) is None
def test_same_value(self):
o = object()
assert same_value(o) is o
def test_same_... | c = Converter("pants", conv_val, conv_item) |
Continue the code snippet: <|code_start|>
class HelperTestCase(unittest.TestCase):
def test_drop(self):
assert drop(1, 2) is None
def test_same_value(self):
o = object()
assert same_value(o) is o
def test_same_item(self):
o1 = object()
o2 = object()
x1, x... | ct = ConversionTable() |
Next line prediction: <|code_start|>
if sys.version_info >= (2, 7):
else:
try:
except ImportError:
raise RuntimeError("unittest2 is required for Python < 2.7")
def conv_val(x):
return x
def conv_item(x, y):
return x, y
class HelperTestCase(unittest.TestCase):
def test_drop(self):
... | x1, x2 = same_item(o1, o2) |
Using the snippet: <|code_start|>
if sys.version_info >= (2, 7):
else:
try:
except ImportError:
raise RuntimeError("unittest2 is required for Python < 2.7")
def conv_val(x):
return x
def conv_item(x, y):
return x, y
class HelperTestCase(unittest.TestCase):
def test_drop(self):
... | assert same_value(o) is o |
Here is a snippet: <|code_start|>
if sys.version_info >= (2, 7):
else:
try:
except ImportError:
raise RuntimeError("unittest2 is required for Python < 2.7")
def conv_val(x):
return x
def conv_item(x, y):
return x, y
class HelperTestCase(unittest.TestCase):
def test_drop(self):
<|code... | assert drop(1, 2) is None |
Given the code snippet: <|code_start|>
INVALID_ATTRIBUTES = (
(5, "This value must be a string naming {0}, not 5 of type <(class|type) 'int'>"),
('nonexistent', 'Could not find {0} named nonexistent'),
('does.not.exist', 'Could not import a module with {0} named does.not.exist'),
('itertools.does.not... | os_via_import_module = _import_module('os') |
Given the code snippet: <|code_start|> (5, "This value must be a string naming {0}, not 5 of type <(class|type) 'int'>"),
('nonexistent', 'Could not find {0} named nonexistent'),
('does.not.exist', 'Could not import a module with {0} named does.not.exist'),
('itertools.does.not.exist', 'Could not find {0... | assert _string_to_attribute('dir', type_='function') == dir |
Here is a snippet: <|code_start|> def test_valid_function_post_import(self):
# A function from inside a module after the module has been imported
chain_via_validator = _string_to_attribute('itertools.chain', type_='function')
assert chain_via_validator == chain
def test_valid_method_pre_... | assert _parse_external('normal string') == 'normal string' |
Predict the next line for this snippet: <|code_start|> async def _make_request(self, base64_url, method='GET', body=None):
try:
url = b64decode(base64_url).decode()
if not (url.startswith('https://') and 'googleapis.com' in url):
raise ValueError('URL is not a valid Google API service')
exc... | user_agent = 'jupyterlab_gcpextension/{}'.format(VERSION) |
Given the following code snippet before the placeholder: <|code_start|>
def _configure_mock_client(self, mock_client):
mock_response = MagicMock()
mock_response.body = self.RESPONSE_BODY
mock_fetch = MagicMock(return_value=async_return(mock_response))
mock_client.return_value.fetch = mock_fetch
re... | self.assertEqual('jupyterlab_gcpextension/{}'.format(VERSION), |
Continue the code snippet: <|code_start|> def import_users(self, request, obj):
g = GlassFrogImporter(api_key=obj.glassfrog_api_key, organization=obj)
g.import_users()
self.message_user(request, 'Users imported.')
import_users.label = _('Import users for this organization')
def impor... | admin.site.register(Organization, OrganizationAdmin) |
Continue the code snippet: <|code_start|>
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'first_name', 'last_name', 'prefix', 'glassfrog_id', 'extra_info')
depth = 2
class ExtraUserInfoSerializer(serializers.ModelSerializer):
class Meta:
<... | model = ExtraUserInfo |
Continue the code snippet: <|code_start|>
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'first_name', 'last_name', 'prefix', 'glassfrog_id', 'extra_info')
depth = 2
class ExtraUserInfoSerializer(serializers.ModelSerializer):
class Meta:
... | model = ExtraUserInfoCategory |
Predict the next line for this snippet: <|code_start|> page = self.paginate_queryset(self.filter_queryset(sent_feedback))
if page is not None:
serializer = FeedbackSerializer(page, many=True)
return self.get_paginated_response(serializer.data)
sent_feedback = self.filter_... | queryset = ExtraUserInfo.objects.all() |
Continue the code snippet: <|code_start|>
@list_route(methods=['GET'], url_path='feedback-as-receiver')
def feedback_as_receiver(self, request, *args, **kwargs):
"""
This view returns all the feedback the user has received.
"""
received_feedback = Feedback.objects.filter(
... | queryset = ExtraUserInfoCategory.objects.all() |
Based on the snippet: <|code_start|> @list_route(methods=['GET'], url_path='feedback-as-receiver')
def feedback_as_receiver(self, request, *args, **kwargs):
"""
This view returns all the feedback the user has received.
"""
received_feedback = Feedback.objects.filter(
r... | serializer_class = ExtraUserInfoCategorySerializer |
Predict the next line for this snippet: <|code_start|> if page is not None:
serializer = FeedbackSerializer(page, many=True)
return self.get_paginated_response(serializer.data)
sent_feedback = self.filter_queryset(sent_feedback)
serializer = FeedbackSerializer(sent_feedba... | serializer_class = ExtraUserInfoSerializer |
Using the snippet: <|code_start|>
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all()
<|code_end|>
, determine the next line of code. You have imports:
from rest_framework import viewsets
from rest_framework.decorator... | serializer_class = UserSerializer |
Here is a snippet: <|code_start|>
class RoleTestCase(TestCase):
"""
Used to confirm the correct behaviour of Role methods.
"""
def setUp(self):
<|code_end|>
. Write the next line using the current file imports:
from django.test import TestCase
from .factories import RoleFactory
and context from oth... | self.anchor_circle = RoleFactory() |
Based on the snippet: <|code_start|>
class FeedbackTestCase(TestCase):
"""
Used to confirm the correct behaviour of Feedback methods.
"""
def setUp(self):
<|code_end|>
, predict the immediate next line with the help of imports:
from django.test import TestCase
from .factories import FeedbackFactory
... | self.feedback = FeedbackFactory() |
Given the code snippet: <|code_start|>
logger = logging.getLogger(__name__)
class GlassFrogImporter(object):
"""
GlassFrogImporter can be used to import users and roles from GlassFrog.
To import all users, use `import_users`.
To import all roles, user `import_circles` with the circle_id, for the
... | self.import_run = RoleImportRun.objects.create() |
Continue the code snippet: <|code_start|>
class UserCreationForm(forms.ModelForm):
"""
A form for creating new users. Includes all the required
fields, plus a repeated password.
"""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Pas... | model = User |
Given the code snippet: <|code_start|> # Human-readable title which will be displayed in the
# right admin sidebar just above the filter options.
title = _('Is Circle')
# Parameter for the filter that will be used in the URL query.
parameter_name = 'is_circle'
def lookups(self, request, model_a... | @admin.register(Role) |
Predict the next line after this snippet: <|code_start|> # Override the default domains serializer with SerializerMethodField to override the getter.
domains = serializers.SerializerMethodField()
def get_accountabilities(self, obj):
"""
Override the getter for accountabilities to try and con... | model = Role |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
"""Sample code."""
def main():
"""Sample main."""
here = os.path.dirname(os.path.abspath(__file__))
path = os.path.join(here, 'sample_data.json')
with open(path) as _file:
descrs = json.load(_file)
for descr in descrs:
<|cod... | sysdescr = sysdescrparser(descr['raw']) |
Continue the code snippet: <|code_start|>
!!! IMPORTANT !!!
Note that the locks used are not recursive/reentrant. Therefore, a synchronized
method (decorated by @reader or @writer) must *not* call other synchronized
methods, otherwise we get a deadlock!
"""
# TODO Note that self.file must never be (accidentally) mo... | @reader |
Given the code snippet: <|code_start|> Args:
node: instance of h5py.Group or h5py.Dataset
Returns:
Corresponding object as a h5pyswmr object
Raises:
TypeError if ``obj`` is of unknown type
"""
if isinstance(node, h5py.File):
return... | @writer |
Given the following code snippet before the placeholder: <|code_start|> """
result = []
with h5py.File(self.file, 'r') as f:
for name, obj in f[self.path].items():
result.append((name, self._wrap_class(obj)))
return result
@reader
def __contains__(sel... | app_log.debug("XXX {},{} ...".format(name, mode)) |
Predict the next line for this snippet: <|code_start|> 'd': 'days',
'w': 'weeks',
}
_FLOAT_PATTERN = r'[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?'
_TIMEDELTA_PATTERN = re.compile(
r'\s*(%s)\s*(\w*)\s*' % _FLOAT_PATTERN, re.IGNORECASE)
def _parse_timedelta(self, value):
... | return _unicode(value) |
Continue the code snippet: <|code_start|> option = self._options[name]
if not equals:
if option.type == bool:
value = "true"
else:
raise Error('Option %r requires a value' % name)
option.parse(value)
if f... | exec_in(native_str(f.read()), config, config) |
Predict the next line for this snippet: <|code_start|> See `OptionParser.parse_command_line`.
"""
return options.parse_command_line(args, final=final)
def parse_config_file(path, final=True):
"""Parses global options from a config file.
See `OptionParser.parse_config_file`.
"""
return opti... | define_logging_options(options) |
Given snippet: <|code_start|> for option in self._options.values():
by_group.setdefault(option.group_name, []).append(option)
for filename, o in sorted(by_group.items()):
if filename:
print("\n%s options:\n" % os.path.normpath(filename), file=file)
o.s... | self._parse_callbacks.append(stack_context.wrap(callback)) |
Next line prediction: <|code_start|>
As of ``mock`` version 1.0.1, when an object uses ``__getattr__``
hooks instead of ``__dict__``, ``patch.__exit__`` tries to delete
the attribute it set instead of setting a new one (assuming that
the object does not catpure ``__setattr__``, so the patch
created ... | def __init__(self, name, default=None, type=basestring_type, help=None, |
Continue the code snippet: <|code_start|> option = self._options[name]
if not equals:
if option.type == bool:
value = "true"
else:
raise Error('Option %r requires a value' % name)
option.parse(value)
if f... | exec_in(native_str(f.read()), config, config) |
Predict the next line after this snippet: <|code_start|>
class MsgPackTestCase(unittest.TestCase):
def test_ndarray(self):
data_in = np.random.randint(0, 255, size=(5, 10)).astype('uint8')
<|code_end|>
using the current file's imports:
import unittest
import msgpack
import numpy as np
from hurray.msgpa... | packed_nparray = msgpack.packb(data_in, default=encode, |
Continue the code snippet: <|code_start|>
class MsgPackTestCase(unittest.TestCase):
def test_ndarray(self):
data_in = np.random.randint(0, 255, size=(5, 10)).astype('uint8')
packed_nparray = msgpack.packb(data_in, default=encode,
use_bin_type=True)
u... | object_hook=decode, |
Given the code snippet: <|code_start|>#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | class Waker(interface.Waker): |
Continue the code snippet: <|code_start|>These streams may be configured independently using the standard library's
`logging` module. For example, you may wish to send ``hurray.access`` logs
to a separate file for analysis.
"""
from __future__ import absolute_import, division, print_function, with_statement
try:
ex... | _TO_UNICODE_TYPES = (unicode_type, type(None)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.